content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
sequence
answers_scores
sequence
non_answers
sequence
non_answers_scores
sequence
tags
sequence
name
stringlengths
35
137
Q: python introspection not showing functions for Lock When I try to use introspection to look at what methods are available on threading.Lock I don't see what I would expect. Specifically I don't see acquire, release or locked. Why is this? Here's what I do see: >>> dir (threading.Lock) ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__str__'] A: You're doing it wrong. threading.Lock is not an object. >>> import threading >>> threading.Lock <built-in function allocate_lock> >>> type(threading.Lock) <type 'builtin_function_or_method'> >>> x=threading.Lock() >>> type(x) <type 'thread.lock'> >>> dir(x) ['__enter__', '__exit__', 'acquire', 'acquire_lock', 'locked', 'locked_lock', 'release', 'release_lock'] >>>
python introspection not showing functions for Lock
When I try to use introspection to look at what methods are available on threading.Lock I don't see what I would expect. Specifically I don't see acquire, release or locked. Why is this? Here's what I do see: >>> dir (threading.Lock) ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__str__']
[ "You're doing it wrong. threading.Lock is not an object.\n>>> import threading\n>>> threading.Lock\n<built-in function allocate_lock>\n>>> type(threading.Lock)\n<type 'builtin_function_or_method'>\n>>> x=threading.Lock()\n>>> type(x)\n<type 'thread.lock'>\n>>> dir(x)\n['__enter__', '__exit__', 'acquire', 'acquire_lock', 'locked', 'locked_lock', 'release', 'release_lock']\n>>>\n\n" ]
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0000394300_python.txt
Q: Finding when the ActiveApplication changes in OSX through Python Is there a way to find when the activeApplication changes in OSX through Python and AppKit? I know how to find out launchedApplication and activeApplication ( please refer to my other question here: Finding the Current Active Window in Mac OS X using Python ) A: I've got an OS X app that does this by polling with an NSTimer. I tried searching for distributed notifications to see if I could find a better way to do it, but I couldn't see anything terribly useful. I did get notifications when application were launched or quit. which is at least a little helpful. You can see the registration of these where my controller wakes up. This application has been immensely helpful to me and even polling once a second uses nearly no CPU. If I could make it more event driven, I would, though. :) A: I'm not aware of an 'official'/good way to do this, but one hackish way to go about this is to listen for any distributed notifications and see which ones are always fired when the frontmost app changes, so you can listen for that one: You can set something like this up: def awakeFromNib(self): NSDistributedNotificationCenter.defaultCenter().addObserver_selector_name_object_( self, 'someNotification:', None, None) def someNotification_(self, notification): NSLog(notification.name()) After you've found a notification that always fires when apps are switched, you can replace the first 'None' in the addObserver_etc_ call with the name of that notification and check for the frontmost app in your 'someNotification_' method. In my case I noticed that the 'AppleSelectedInputSourcesChangedNotification' fired everytime I switched apps, so I would listen to that.. Keep in mind that this can break any moment and you'll prolly be checking for a change in the frontmost app more often than needed. There must be a better way though.. hopefully :)
Finding when the ActiveApplication changes in OSX through Python
Is there a way to find when the activeApplication changes in OSX through Python and AppKit? I know how to find out launchedApplication and activeApplication ( please refer to my other question here: Finding the Current Active Window in Mac OS X using Python )
[ "I've got an OS X app that does this by polling with an NSTimer. I tried searching for distributed notifications to see if I could find a better way to do it, but I couldn't see anything terribly useful.\nI did get notifications when application were launched or quit. which is at least a little helpful. You can see the registration of these where my controller wakes up.\nThis application has been immensely helpful to me and even polling once a second uses nearly no CPU. If I could make it more event driven, I would, though. :)\n", "I'm not aware of an 'official'/good way to do this, but one hackish way to go about this is to listen for any distributed notifications and see which ones are always fired when the frontmost app changes, so you can listen for that one:\nYou can set something like this up:\ndef awakeFromNib(self):\n NSDistributedNotificationCenter.defaultCenter().addObserver_selector_name_object_(\n self, 'someNotification:', None, None)\n\ndef someNotification_(self, notification):\n NSLog(notification.name())\n\nAfter you've found a notification that always fires when apps are switched, you can replace the first 'None' in the addObserver_etc_ call with the name of that notification and check for the frontmost app in your 'someNotification_' method.\nIn my case I noticed that the 'AppleSelectedInputSourcesChangedNotification' fired everytime I switched apps, so I would listen to that..\nKeep in mind that this can break any moment and you'll prolly be checking for a change in the frontmost app more often than needed.\nThere must be a better way though.. hopefully :)\n" ]
[ 1, 0 ]
[]
[]
[ "cocoa_touch", "macos", "python" ]
stackoverflow_0000394372_cocoa_touch_macos_python.txt
Q: Is there a simple way in Python to create a file which can be written to in one thread and read in a different one? In the python program I'm writing, I've got a thread which iterates over a large structure in memory and writes it incrementally into a file-like object. I've got another thread which takes a file-like object and writes it to disk. Is there an easy way to connect the two, such that any data input from the first thread will be buffered for the second? Specifically, I'm trying to pass data to subprocess.Popen(). The process will read from stdin, but you cannot pass a "file-like" object to Popen because it calls stdin.fileno() and blows up unless you have a real file. Instead, you need to pass the PIPE argument to Popen, which allows you to use proc.stdin as a file-like object. But if you've already got a file-like object, there doesn't seem to be a great way to yolk the two of them together. A: You should use the Queue module for sharing sequential data across threads. You would have to make a file-like Queue subclass, where .read and .write mutually block each other, with a buffer in-between. OTOH, I wonder why the first thread can't write to the real file in the first place. A: Use shutil's copyfileobj() function: import shutil import subprocess proc = subprocess.Popen([...], stdin=subprocess.PIPE) my_input = get_filelike_object('from a place not given in the question') shutil.copyfileobj(my_input, proc.stdin) No need to use threads. A: I think there is something wrong in the design if you already have a file-like object if you want your data to end up in the subprocess. You should then arrange that they get written into the subprocess in the first place, rather than having them written into something else file-like first. Whoever is writing the data should allow the flexibility to specify the output stream, and that should be the subprocess pipe. Alternatively, if the writer insists on creating its own stream object, you should let it complete writing, and only then start the subprocess, feeding it from the result of first write. E.g. if it is a StringIO object, take its value after writing, and write it into the pipe; no need for thread synchronization here. A: I'm not clear what you're trying to do ehre. This sounds like a job for a regular old pipe, which is a file-like object. I'm guessing, however, that you mean you're got a stream of some other sort. It also sounds a lot like what you want is a python Queue, or maybe a tempfile.
Is there a simple way in Python to create a file which can be written to in one thread and read in a different one?
In the python program I'm writing, I've got a thread which iterates over a large structure in memory and writes it incrementally into a file-like object. I've got another thread which takes a file-like object and writes it to disk. Is there an easy way to connect the two, such that any data input from the first thread will be buffered for the second? Specifically, I'm trying to pass data to subprocess.Popen(). The process will read from stdin, but you cannot pass a "file-like" object to Popen because it calls stdin.fileno() and blows up unless you have a real file. Instead, you need to pass the PIPE argument to Popen, which allows you to use proc.stdin as a file-like object. But if you've already got a file-like object, there doesn't seem to be a great way to yolk the two of them together.
[ "You should use the Queue module for sharing sequential data across threads. You would have to make a file-like Queue subclass, where .read and .write mutually block each other, with a buffer in-between.\nOTOH, I wonder why the first thread can't write to the real file in the first place.\n", "Use shutil's copyfileobj() function:\nimport shutil\nimport subprocess\n\nproc = subprocess.Popen([...], stdin=subprocess.PIPE)\n\nmy_input = get_filelike_object('from a place not given in the question')\n\nshutil.copyfileobj(my_input, proc.stdin)\n\nNo need to use threads.\n", "I think there is something wrong in the design if you already have a file-like object if you want your data to end up in the subprocess. You should then arrange that they get written into the subprocess in the first place, rather than having them written into something else file-like first. Whoever is writing the data should allow the flexibility to specify the output stream, and that should be the subprocess pipe.\nAlternatively, if the writer insists on creating its own stream object, you should let it complete writing, and only then start the subprocess, feeding it from the result of first write. E.g. if it is a StringIO object, take its value after writing, and write it into the pipe; no need for thread synchronization here.\n", "I'm not clear what you're trying to do ehre. This sounds like a job for a regular old pipe, which is a file-like object. I'm guessing, however, that you mean you're got a stream of some other sort.\nIt also sounds a lot like what you want is a python Queue, or maybe a tempfile.\n" ]
[ 5, 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000394500_python.txt
Q: Python threads stack_size and segfaults A web crawler script that spawns at most 500 threads and each thread basically requests for certain data served from the remote server, which each server's reply is different in content and size from others. i'm setting stack_size as 756K's for threads threading.stack_size(756*1024) which enables me to have the sufficient number of threads required and complete most of the jobs and requests. But as some servers' responses are bigger than others, and when a thread gets that kind of response, script dies with SIGSEGV. stack_sizes more than 756K makes it impossible to have the required number of threads at the same time. any suggestions on how can i continue with given stack_size without crashes? and how can i get the current used stack_size of any given thread? A: Why on earth are you spawning 500 threads? That seems like a terrible idea! Remove threading completely, use an event loop to do the crawling. Your program will be faster, simpler, and easier to maintain. Lots of threads waiting for network won't make your program wait faster. Instead, collect all open sockets in a list and run a loop where you check if any of them has data available. I recommend using Twisted - It is an event-driven networking engine. It is very flexile, secure, scalable and very stable (no segfaults). You could also take a look at Scrapy - It is a web crawling and screen scraping framework written in Python/Twisted. It is still under heavy development, but maybe you can take some ideas.
Python threads stack_size and segfaults
A web crawler script that spawns at most 500 threads and each thread basically requests for certain data served from the remote server, which each server's reply is different in content and size from others. i'm setting stack_size as 756K's for threads threading.stack_size(756*1024) which enables me to have the sufficient number of threads required and complete most of the jobs and requests. But as some servers' responses are bigger than others, and when a thread gets that kind of response, script dies with SIGSEGV. stack_sizes more than 756K makes it impossible to have the required number of threads at the same time. any suggestions on how can i continue with given stack_size without crashes? and how can i get the current used stack_size of any given thread?
[ "Why on earth are you spawning 500 threads? That seems like a terrible idea! \nRemove threading completely, use an event loop to do the crawling. Your program will be faster, simpler, and easier to maintain.\nLots of threads waiting for network won't make your program wait faster. Instead, collect all open sockets in a list and run a loop where you check if any of them has data available.\nI recommend using Twisted - It is an event-driven networking engine. It is very flexile, secure, scalable and very stable (no segfaults).\nYou could also take a look at Scrapy - It is a web crawling and screen scraping framework written in Python/Twisted. It is still under heavy development, but maybe you can take some ideas.\n" ]
[ 10 ]
[]
[]
[ "multithreading", "python", "segmentation_fault", "stack_size" ]
stackoverflow_0000394895_multithreading_python_segmentation_fault_stack_size.txt
Q: Python: Lock directory access under windows I'd like to be able to lock directory access under windows. The following code work greatly with file or directory under POSIX system: def flock(fd, blocking=False, exclusive=False): if exclusive: flags = fcntl.LOCK_EX else: flags = fcntl.LOCK_SH if not blocking: flags |= fcntl.LOCK_NB fcntl.flock(fd, flags) But I only find a way to perform lock access for file, not directory with the following code: def flock(fd, blocking=False, exclusive=False): if blocking: flags = msvcrt.LK_NBLCK else: flags = msvcrt.LK_LOCK msvcrt.locking(fd.fileno(), flags, os.path.getsize(fd.name)) Have you got any idea how to improve this code and be able to lock directory access ? Bertrand A: I don't believe it's possible to use flock() on directories in windows. PHPs docs on flock() indicate that it won't even work on FAT32 filesystems. On the other hand, Windows already tends to not allow you to delete files/directories if any files are still open. This, plus maybe using ACLs intelligently, might get you a 95% equivalent solution. A: You probably can do something like this to indirectly lock a directory with the latter flock function. for file in os.listdir(dir): f = open(file) flock(f) This is a limited version, since the user will be able to create new files in the directory. A: Yep you are right, at least I can try to lock every file of the directory but it can be painful because I need to walk into all the subdirectories of my directory. In POSIX system it's easy because directories are seen like files so, no problem with that. But in Windows when I try to open a directory, it doesn't really like that. open(dirname) raises exception: OSError: [Errno 13] Permission denied: dirname I am not really sure my solution is actually the good way to do it.
Python: Lock directory access under windows
I'd like to be able to lock directory access under windows. The following code work greatly with file or directory under POSIX system: def flock(fd, blocking=False, exclusive=False): if exclusive: flags = fcntl.LOCK_EX else: flags = fcntl.LOCK_SH if not blocking: flags |= fcntl.LOCK_NB fcntl.flock(fd, flags) But I only find a way to perform lock access for file, not directory with the following code: def flock(fd, blocking=False, exclusive=False): if blocking: flags = msvcrt.LK_NBLCK else: flags = msvcrt.LK_LOCK msvcrt.locking(fd.fileno(), flags, os.path.getsize(fd.name)) Have you got any idea how to improve this code and be able to lock directory access ? Bertrand
[ "I don't believe it's possible to use flock() on directories in windows. PHPs docs on flock() indicate that it won't even work on FAT32 filesystems.\nOn the other hand, Windows already tends to not allow you to delete files/directories if any files are still open. This, plus maybe using ACLs intelligently, might get you a 95% equivalent solution.\n", "You probably can do something like this to indirectly lock a directory with the latter flock function.\nfor file in os.listdir(dir):\n f = open(file)\n flock(f)\n\nThis is a limited version, since the user will be able to create new files in the directory.\n", "Yep you are right, at least I can try to lock every file of the directory but it can be painful because I need to walk into all the subdirectories of my directory.\nIn POSIX system it's easy because directories are seen like files so, no problem with that. But in Windows when I try to open a directory, it doesn't really like that.\nopen(dirname)\n\nraises exception: \nOSError: [Errno 13] Permission denied: dirname\n\nI am not really sure my solution is actually the good way to do it.\n" ]
[ 1, 0, 0 ]
[]
[]
[ "directory", "locking", "python", "windows" ]
stackoverflow_0000394439_directory_locking_python_windows.txt
Q: Calling Application Methods from a wx Frame Class I'm starting out with wxPython and have been working my way through every tutorial and example I can get my hands on. I've run into a slight problem, however, and it has to do with the wx.App versus the wx.Frame and which should contain specific methods. Just about every example I've seen don't go much beyond layouts/sizers and event handling, none really tackle project organization of a wxPython project. For example, I have a method that gets a list of folders. The way most examples would deal with this would be to stick the method right in the frame class. This method has the potential to be used in several other parts of the application, so it would make more sense to store it at the application class level. How should I organize and call "universal" methods like these so that I don't clutter up my frame classes. UPDATE: To clarify, the "list of folders" was just an example, my actual method does a lot more work. What I'm saying is I have code that isn't Frame-specific. If I had this in the application class, what is the best way to call it from and event method in my frame. I'm looking for actual project organization techniques, not programming fundamentals. A: As Mark stated you should make a new class that handles things like this. The ideal layout of code when using something like wxWidgets is the model view controller where the wxFrame class only has the code needed to display items and all the logic and business rules are handled by other class that interact with the wxFrame. This way you can change logic and business rules with out having to change your interface and change (or swap) your interface with out having to change your logic and business rules. A: Your classes that inherit from wxWidgets/wxPython data types should not implement any business logic. wxWidgets is a GUI library, so any subclasses of wxApp or wxFrame should remain focused on GUI, that is on displaying the interface and being responsive to user actions. The code that does something useful should be separated from wx, as you can decide later to use it in some web or console application and you don't want to create wxApp object in such case. You can also decide later on to move some computations to separate 'worker threads', while your GUI will be the 'main thread' - responsive, and repainted properly during long lasting computations. Last but not least - the classes that encapsulate your logic might tend to grow during projects lifetime. If they're mixed with your GUI classes they will grow faster, and finally they become so complex that you're almost unable to debug them... While having them separated leads to clean code when you don't mix bugs in logic with bugs in GUI (refreshing/layout/progress bar etc.). Such approach has another nice feature - ability to split work among GUI-people and logic-people, which can do their work without constant conflicts. A: I probably should have been a lot clearer from the start, but I found what I was looking for: http://wiki.wxpython.org/ModelViewController/ Burried within the wxpython wiki, I found several simple, concrete examples of MVC projects. A: In a proper OOP design, this would be independent or part of a filesystem class - it wouldn't be part of the app or the frame.
Calling Application Methods from a wx Frame Class
I'm starting out with wxPython and have been working my way through every tutorial and example I can get my hands on. I've run into a slight problem, however, and it has to do with the wx.App versus the wx.Frame and which should contain specific methods. Just about every example I've seen don't go much beyond layouts/sizers and event handling, none really tackle project organization of a wxPython project. For example, I have a method that gets a list of folders. The way most examples would deal with this would be to stick the method right in the frame class. This method has the potential to be used in several other parts of the application, so it would make more sense to store it at the application class level. How should I organize and call "universal" methods like these so that I don't clutter up my frame classes. UPDATE: To clarify, the "list of folders" was just an example, my actual method does a lot more work. What I'm saying is I have code that isn't Frame-specific. If I had this in the application class, what is the best way to call it from and event method in my frame. I'm looking for actual project organization techniques, not programming fundamentals.
[ "As Mark stated you should make a new class that handles things like this. \nThe ideal layout of code when using something like wxWidgets is the model view controller where the wxFrame class only has the code needed to display items and all the logic and business rules are handled by other class that interact with the wxFrame. This way you can change logic and business rules with out having to change your interface and change (or swap) your interface with out having to change your logic and business rules.\n", "Your classes that inherit from wxWidgets/wxPython data types should not implement any business logic. wxWidgets is a GUI library, so any subclasses of wxApp or wxFrame should remain focused on GUI, that is on displaying the interface and being responsive to user actions. \nThe code that does something useful should be separated from wx, as you can decide later to use it in some web or console application and you don't want to create wxApp object in such case. You can also decide later on to move some computations to separate 'worker threads', while your GUI will be the 'main thread' - responsive, and repainted properly during long lasting computations. \nLast but not least - the classes that encapsulate your logic might tend to grow during projects lifetime. If they're mixed with your GUI classes they will grow faster, and finally they become so complex that you're almost unable to debug them... \nWhile having them separated leads to clean code when you don't mix bugs in logic with bugs in GUI (refreshing/layout/progress bar etc.). Such approach has another nice feature - ability to split work among GUI-people and logic-people, which can do their work without constant conflicts.\n", "I probably should have been a lot clearer from the start, but I found what I was looking for:\nhttp://wiki.wxpython.org/ModelViewController/\nBurried within the wxpython wiki, I found several simple, concrete examples of MVC projects.\n", "In a proper OOP design, this would be independent or part of a filesystem class - it wouldn't be part of the app or the frame.\n" ]
[ 2, 2, 2, 0 ]
[]
[]
[ "model_view_controller", "project_organization", "python", "wxpython", "wxwidgets" ]
stackoverflow_0000390867_model_view_controller_project_organization_python_wxpython_wxwidgets.txt
Q: Threads in Python General tutorial or good resource on how to use threads in Python? When to use threads, how they are effective, and some general background on threads [specific to Python]? A: Threads should be used when you want two things to run at once, or want something to run in the background without slowing down the main process. My recommendation is to only use threads if you have to. They generally add complexity to a program. The main documentation for threading is here: http://docs.python.org/library/threading.html Some examples are here: http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/1/ http://linuxgazette.net/107/pai.html http://www.wellho.net/solutions/python-python-threads-a-first-example.html A: One thing to remember before spending time and effort in writing a multi-threaded Python application is that there is a Global Interpreter Lock (GIL), so you won't actually be running more than one thread at a time. This makes threading unsuitable for trying to take advantage of multiple cores or CPUs. You may get some speedup from multiplexing other resources (network, disk, ...), but it's never been particularly noticeable in my experience. In general, I only use threads when there are several logically separate tasks happening at once, and yet I want them all in the same VM. A thread pulling data from the web and putting it on a Queue, while another thread pops from the Queue and writes to a database, something like that. With Python 2.6, there is the new multiprocessing module which is pretty cool - it's got a very similar interface to the threading module, but actually spawns new OS processes, sidestepping the GIL. A: There is a fantastic pdf, Tutorial on Threads Programming with Python by Norman Matloff and Francis Hsu, of University of California, Davis. Threads should be avoided whenever possible. They add much in complexity, synchronization issues and hard to debug issues. However some problems require them (i.e. GUI programming), but I would encourage you to look for a single-threaded solution if you can. A: There are several tutorials here.
Threads in Python
General tutorial or good resource on how to use threads in Python? When to use threads, how they are effective, and some general background on threads [specific to Python]?
[ "Threads should be used when you want two things to run at once, or want something to run in the background without slowing down the main process.\nMy recommendation is to only use threads if you have to. They generally add complexity to a program.\nThe main documentation for threading is here: http://docs.python.org/library/threading.html\nSome examples are here:\nhttp://www.devshed.com/c/a/Python/Basic-Threading-in-Python/1/\nhttp://linuxgazette.net/107/pai.html\nhttp://www.wellho.net/solutions/python-python-threads-a-first-example.html\n", "One thing to remember before spending time and effort in writing a multi-threaded Python application is that there is a Global Interpreter Lock (GIL), so you won't actually be running more than one thread at a time.\nThis makes threading unsuitable for trying to take advantage of multiple cores or CPUs. You may get some speedup from multiplexing other resources (network, disk, ...), but it's never been particularly noticeable in my experience.\nIn general, I only use threads when there are several logically separate tasks happening at once, and yet I want them all in the same VM. A thread pulling data from the web and putting it on a Queue, while another thread pops from the Queue and writes to a database, something like that.\nWith Python 2.6, there is the new multiprocessing module which is pretty cool - it's got a very similar interface to the threading module, but actually spawns new OS processes, sidestepping the GIL.\n", "There is a fantastic pdf, Tutorial on Threads Programming with Python by \nNorman Matloff and Francis Hsu, of University of California, Davis.\nThreads should be avoided whenever possible. They add much in complexity, synchronization issues and hard to debug issues. However some problems require them (i.e. GUI programming), but I would encourage you to look for a single-threaded solution if you can.\n", "There are several tutorials here. \n" ]
[ 13, 8, 3, 1 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0000395704_multithreading_python.txt
Q: Caching compiled regex objects in Python? Each time a python file is imported that contains a large quantity of static regular expressions, cpu cycles are spent compiling the strings into their representative state machines in memory. a = re.compile("a.*b") b = re.compile("c.*d") ... Question: Is it possible to store these regular expressions in a cache on disk in a pre-compiled manner to avoid having to execute the regex compilations on each import? Pickling the object simply does the following, causing compilation to happen anyway: >>> import pickle >>> import re >>> x = re.compile(".*") >>> pickle.dumps(x) "cre\n_compile\np0\n(S'.*'\np1\nI0\ntp2\nRp3\n." And re objects are unmarshallable: >>> import marshal >>> import re >>> x = re.compile(".*") >>> marshal.dumps(x) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: unmarshallable object A: Is it possible to store these regular expressions in a cache on disk in a pre-compiled manner to avoid having to execute the regex compilations on each import? Not easily. You'd have to write a custom serializer that hooks into the C sre implementation of the Python regex engine. Any performance benefits would be vastly outweighed by the time and effort required. First, have you actually profiled the code? I doubt that compiling regexes is a significant part of the application's run-time. Remember that they are only compiled the first time the module is imported in the current execution -- thereafter, the module and its attributes are cached in memory. If you have a program that basically spawns once, compiles a bunch of regexes, and then exits, you could try re-engineering it to perform multiple tests in one invocation. Then you could re-use the regexes, as above. Finally, you could compile the regexes into C-based state machines and then link them in with an extension module. While this would likely be more difficult to maintain, it would eliminate regex compilation entirely from your application. A: Note that each module initializes itself only once during the life of an app, no matter how many times you import it. So if you compile your expressions at the module's global scope (ie. not in a function) you should be fine. A: First of all, this is a clear limitation in the python re module. It causes a limit how much and how big regular expressions are reasonable. The limit is bigger with long running processes and smaller with short lived processes like command line applications. Some years ago I did look at it and it is possible to dig out the compilation result, pickle it and then unpickle it and reuse it. The problem is that it requires using the sre.py internals and so won't probably work in different python versions. I would like to have this kind of feature in my toolbox. I would also like to know, if there are any separate modules that could be used instead.
Caching compiled regex objects in Python?
Each time a python file is imported that contains a large quantity of static regular expressions, cpu cycles are spent compiling the strings into their representative state machines in memory. a = re.compile("a.*b") b = re.compile("c.*d") ... Question: Is it possible to store these regular expressions in a cache on disk in a pre-compiled manner to avoid having to execute the regex compilations on each import? Pickling the object simply does the following, causing compilation to happen anyway: >>> import pickle >>> import re >>> x = re.compile(".*") >>> pickle.dumps(x) "cre\n_compile\np0\n(S'.*'\np1\nI0\ntp2\nRp3\n." And re objects are unmarshallable: >>> import marshal >>> import re >>> x = re.compile(".*") >>> marshal.dumps(x) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: unmarshallable object
[ "\nIs it possible to store these regular expressions in a cache on disk in a pre-compiled manner to avoid having to execute the regex compilations on each import?\n\nNot easily. You'd have to write a custom serializer that hooks into the C sre implementation of the Python regex engine. Any performance benefits would be vastly outweighed by the time and effort required.\nFirst, have you actually profiled the code? I doubt that compiling regexes is a significant part of the application's run-time. Remember that they are only compiled the first time the module is imported in the current execution -- thereafter, the module and its attributes are cached in memory.\nIf you have a program that basically spawns once, compiles a bunch of regexes, and then exits, you could try re-engineering it to perform multiple tests in one invocation. Then you could re-use the regexes, as above.\nFinally, you could compile the regexes into C-based state machines and then link them in with an extension module. While this would likely be more difficult to maintain, it would eliminate regex compilation entirely from your application.\n", "Note that each module initializes itself only once during the life of an app, no matter how many times you import it. So if you compile your expressions at the module's global scope (ie. not in a function) you should be fine.\n", "First of all, this is a clear limitation in the python re module. It causes a limit how much and how big regular expressions are reasonable. The limit is bigger with long running processes and smaller with short lived processes like command line applications.\nSome years ago I did look at it and it is possible to dig out the compilation result, pickle it and then unpickle it and reuse it. The problem is that it requires using the sre.py internals and so won't probably work in different python versions.\nI would like to have this kind of feature in my toolbox. I would also like to know, if there are any separate modules that could be used instead.\n" ]
[ 13, 4, 2 ]
[ "The shelve module appears to work just fine:\n\nimport re\nimport shelve\na_pattern = \"a.*b\"\nb_pattern = \"c.*d\"\na = re.compile(a_pattern)\nb = re.compile(b_pattern)\n\nx = shelve.open('re_cache')\nx[a_pattern] = a\nx[b_pattern] = b\nx.close()\n\n# ...\nx = shelve.open('re_cache')\na = x[a_pattern]\nb = x[b_pattern]\nx.close()\n\n\nYou can then make a nice wrapper class that automatically handles the caching for you so that it becomes transparent to the user... an exercise left to the reader.\n", "Hum,\nDoesn't shelve use pickle ?\nAnyway, I agree with the previous anwsers. Since a module is processed only once, I doubt compiling regexps will be your app bottle neck. And Python re module is wicked fast since it's coded in C :-)\nBut the good news is that Python got a nice community, so I am sure you can find somebody currently hacking just what you need.\nI googled 5 sec and found : http://home.gna.org/oomadness/en/cerealizer/index.html.\nDon't know if it will do it but if not, good luck in you research :-)\n", "Open /usr/lib/python2.5/re.py and look for \"def _compile\". You'll find re.py's internal cache mechanism. \n" ]
[ -1, -1, -1 ]
[ "caching", "python", "regex" ]
stackoverflow_0000065266_caching_python_regex.txt
Q: "MetaClass", "__new__", "cls" and "super" - what is the mechanism exactly? I have read posts like these: What is a metaclass in Python? What are your (concrete) use-cases for metaclasses in Python? Python's Super is nifty, but you can't use it But somehow I got confused. Many confusions like: When and why would I have to do something like the following? # Refer link1 return super(MyType, cls).__new__(cls, name, bases, newattrs) or # Refer link2 return super(MetaSingleton, cls).__call__(*args, **kw) or # Refer link2 return type(self.__name__ + other.__name__, (self, other), {}) How does super work exactly? What is class registry and unregistry in link1 and how exactly does it work? (I thought it has something to do with singleton. I may be wrong, being from C background. My coding style is still a mix of functional and OO). What is the flow of class instantiation (subclass, metaclass, super, type) and method invocation ( metaclass->__new__, metaclass->__init__, super->__new__, subclass->__init__ inherited from metaclass ) with well-commented working code (though the first link is quite close, but it does not talk about cls keyword and super(..) and registry). Preferably an example with multiple inheritance. P.S.: I made the last part as code because Stack Overflow formatting was converting the text metaclass->__new__ to metaclass->new A: OK, you've thrown quite a few concepts into the mix here! I'm going to pull out a few of the specific questions you have. In general, understanding super, the MRO and metclasses is made much more complicated because there have been lots of changes in this tricky area over the last few versions of Python. Python's own documentation is a very good reference, and completely up to date. There is an IBM developerWorks article which is fine as an introduction and takes a more tutorial-based approach, but note that it's five years old, and spends a lot of time talking about the older-style approaches to meta-classes. super is how you access an object's super-classes. It's more complex than (for example) Java's super keyword, mainly because of multiple inheritance in Python. As Super Considered Harmful explains, using super() can result in you implicitly using a chain of super-classes, the order of which is defined by the Method Resolution Order (MRO). You can see the MRO for a class easily by invoking mro() on the class (not on an instance). Note that meta-classes are not in an object's super-class hierarchy. Thomas' description of meta-classes here is excellent: A metaclass is the class of a class. Like a class defines how an instance of the class behaves, a metaclass defines how a class behaves. A class is an instance of a metaclass. In the examples you give, here's what's going on: The call to __new__ is being bubbled up to the next thing in the MRO. In this case, super(MyType, cls) would resolve to type; calling type.__new__ lets Python complete it's normal instance creation steps. This example is using meta-classes to enforce a singleton. He's overriding __call__ in the metaclass so that whenever a class instance is created, he intercepts that, and can bypass instance creation if there already is one (stored in cls.instance). Note that overriding __new__ in the metaclass won't be good enough, because that's only called when creating the class. Overriding __new__ on the class would work, however. This shows a way to dynamically create a class. Here's he's appending the supplied class's name to the created class name, and adding it to the class hierarchy too. I'm not exactly sure what sort of code example you're looking for, but here's a brief one showing meta-classes, inheritance and method resolution: print('>>> # Defining classes:') class MyMeta(type): def __new__(cls, name, bases, dct): print("meta: creating %s %s" % (name, bases)) return type.__new__(cls, name, bases, dct) def meta_meth(cls): print("MyMeta.meta_meth") __repr__ = lambda c: c.__name__ class A(metaclass=MyMeta): def __init__(self): super(A, self).__init__() print("A init") def meth(self): print("A.meth") class B(metaclass=MyMeta): def __init__(self): super(B, self).__init__() print("B init") def meth(self): print("B.meth") class C(A, B, metaclass=MyMeta): def __init__(self): super(C, self).__init__() print("C init") print('>>> c_obj = C()') c_obj = C() print('>>> c_obj.meth()') c_obj.meth() print('>>> C.meta_meth()') C.meta_meth() print('>>> c_obj.meta_meth()') c_obj.meta_meth() Example output (using Python >= 3.6): >>> # Defining classes: meta: creating A () meta: creating B () meta: creating C (A, B) >>> c_obj = C() B init A init C init >>> c_obj.meth() A.meth >>> C.meta_meth() MyMeta.meta_meth >>> c_obj.meta_meth() Traceback (most recent call last): File "metatest.py", line 41, in <module> c_obj.meta_meth() AttributeError: 'C' object has no attribute 'meta_meth' A: Here's the more pragmatic answer. It rarely matters "What is a metaclass in Python". Bottom line, type is the metaclass of all classes. You have almost no practical use for this. class X(object): pass type(X) == type "What are your (concrete) use cases for metaclasses in Python?". Bottom line. None. "Python's Super is nifty, but you can't use it". Interesting note, but little practical value. You'll never have a need for resolving complex multiple inheritance networks. It's easy to prevent this problem from arising by using an explicity Strategy design instead of multiple inheritance. Here's my experience over the last 7 years of Python programming. A class has 1 or more superclasses forming a simple chain from my class to object. The concept of "class" is defined by a metaclass named type. I might want to extend the concept of "class", but so far, it's never come up in practice. Not once. type always does the right thing. Using super works out really well in practice. It allows a subclass to defer to it's superclass. It happens to show up in these metaclass examples because they're extending the built-in metaclass, type. However, in all subclass situations, you'll make use of super to extend a superclass. Metaclasses The metaclass issue is this: Every object has a reference to it's type definition, or "class". A class is, itself, also an object. Therefore a object of type class has a reference to it's type or "class". The "class" of a "class" is a metaclass. Since a "class" isn't a C++ run-time object, this doesn't happen in C++. It does happen in Java, Smalltalk and Python. A metaclass defines the behavior of a class object. 90% of your interaction with a class is to ask the class to create a new object. 10% of the time, you'll be using class methods or class variables ("static" in C++ or Java parlance.) I have found a few use cases for class-level methods. I have almost no use cases for class variables. I've never had a situation to change the way object construction works.
"MetaClass", "__new__", "cls" and "super" - what is the mechanism exactly?
I have read posts like these: What is a metaclass in Python? What are your (concrete) use-cases for metaclasses in Python? Python's Super is nifty, but you can't use it But somehow I got confused. Many confusions like: When and why would I have to do something like the following? # Refer link1 return super(MyType, cls).__new__(cls, name, bases, newattrs) or # Refer link2 return super(MetaSingleton, cls).__call__(*args, **kw) or # Refer link2 return type(self.__name__ + other.__name__, (self, other), {}) How does super work exactly? What is class registry and unregistry in link1 and how exactly does it work? (I thought it has something to do with singleton. I may be wrong, being from C background. My coding style is still a mix of functional and OO). What is the flow of class instantiation (subclass, metaclass, super, type) and method invocation ( metaclass->__new__, metaclass->__init__, super->__new__, subclass->__init__ inherited from metaclass ) with well-commented working code (though the first link is quite close, but it does not talk about cls keyword and super(..) and registry). Preferably an example with multiple inheritance. P.S.: I made the last part as code because Stack Overflow formatting was converting the text metaclass->__new__ to metaclass->new
[ "OK, you've thrown quite a few concepts into the mix here! I'm going to pull out a few of the specific questions you have.\nIn general, understanding super, the MRO and metclasses is made much more complicated because there have been lots of changes in this tricky area over the last few versions of Python.\nPython's own documentation is a very good reference, and completely up to date. There is an IBM developerWorks article which is fine as an introduction and takes a more tutorial-based approach, but note that it's five years old, and spends a lot of time talking about the older-style approaches to meta-classes.\nsuper is how you access an object's super-classes. It's more complex than (for example) Java's super keyword, mainly because of multiple inheritance in Python. As Super Considered Harmful explains, using super() can result in you implicitly using a chain of super-classes, the order of which is defined by the Method Resolution Order (MRO).\nYou can see the MRO for a class easily by invoking mro() on the class (not on an instance). Note that meta-classes are not in an object's super-class hierarchy.\nThomas' description of meta-classes here is excellent:\n\nA metaclass is the class of a class.\nLike a class defines how an instance\nof the class behaves, a metaclass\ndefines how a class behaves. A class\nis an instance of a metaclass.\n\nIn the examples you give, here's what's going on:\n\nThe call to __new__ is being\nbubbled up to the next thing in the\nMRO. In this case, super(MyType, cls) would resolve to type;\ncalling type.__new__ lets Python\ncomplete it's normal instance\ncreation steps.\n\nThis example is using meta-classes\nto enforce a singleton. He's\noverriding __call__ in the\nmetaclass so that whenever a class\ninstance is created, he intercepts\nthat, and can bypass instance\ncreation if there already is one\n(stored in cls.instance). Note\nthat overriding __new__ in the\nmetaclass won't be good enough,\nbecause that's only called when\ncreating the class. Overriding\n__new__ on the class would work,\nhowever.\n\nThis shows a way to dynamically\ncreate a class. Here's he's\nappending the supplied class's name\nto the created class name, and\nadding it to the class hierarchy\ntoo.\n\n\nI'm not exactly sure what sort of code example you're looking for, but here's a brief one showing meta-classes, inheritance and method resolution:\nprint('>>> # Defining classes:')\n\nclass MyMeta(type):\n def __new__(cls, name, bases, dct):\n print(\"meta: creating %s %s\" % (name, bases))\n return type.__new__(cls, name, bases, dct)\n\n def meta_meth(cls):\n print(\"MyMeta.meta_meth\")\n\n __repr__ = lambda c: c.__name__\n\nclass A(metaclass=MyMeta):\n def __init__(self):\n super(A, self).__init__()\n print(\"A init\")\n\n def meth(self):\n print(\"A.meth\")\n\nclass B(metaclass=MyMeta):\n def __init__(self):\n super(B, self).__init__()\n print(\"B init\")\n\n def meth(self):\n print(\"B.meth\")\n\nclass C(A, B, metaclass=MyMeta):\n def __init__(self):\n super(C, self).__init__()\n print(\"C init\")\n\nprint('>>> c_obj = C()')\nc_obj = C()\nprint('>>> c_obj.meth()')\nc_obj.meth()\nprint('>>> C.meta_meth()')\nC.meta_meth()\nprint('>>> c_obj.meta_meth()')\nc_obj.meta_meth()\n\nExample output (using Python >= 3.6):\n>>> # Defining classes:\nmeta: creating A ()\nmeta: creating B ()\nmeta: creating C (A, B)\n>>> c_obj = C()\nB init\nA init\nC init\n>>> c_obj.meth()\nA.meth\n>>> C.meta_meth()\nMyMeta.meta_meth\n>>> c_obj.meta_meth()\nTraceback (most recent call last):\nFile \"metatest.py\", line 41, in <module>\n c_obj.meta_meth()\nAttributeError: 'C' object has no attribute 'meta_meth'\n\n", "Here's the more pragmatic answer.\nIt rarely matters\n\n\"What is a metaclass in Python\". Bottom line, type is the metaclass of all classes. You have almost no practical use for this. \nclass X(object):\n pass\ntype(X) == type\n\n\"What are your (concrete) use cases for metaclasses in Python?\". Bottom line. None.\n\"Python's Super is nifty, but you can't use it\". Interesting note, but little practical value. You'll never have a need for resolving complex multiple inheritance networks. It's easy to prevent this problem from arising by using an explicity Strategy design instead of multiple inheritance. \n\nHere's my experience over the last 7 years of Python programming.\n\nA class has 1 or more superclasses forming a simple chain from my class to object.\nThe concept of \"class\" is defined by a metaclass named type. I might want to extend the concept of \"class\", but so far, it's never come up in practice. Not once. type always does the right thing.\nUsing super works out really well in practice. It allows a subclass to defer to it's superclass. It happens to show up in these metaclass examples because they're extending the built-in metaclass, type. \nHowever, in all subclass situations, you'll make use of super to extend a superclass.\n\nMetaclasses\nThe metaclass issue is this: \n\nEvery object has a reference to it's type definition, or \"class\".\nA class is, itself, also an object.\nTherefore a object of type class has a reference to it's type or \"class\". The \"class\" of a \"class\" is a metaclass.\n\nSince a \"class\" isn't a C++ run-time object, this doesn't happen in C++. It does happen in Java, Smalltalk and Python.\nA metaclass defines the behavior of a class object.\n\n90% of your interaction with a class is to ask the class to create a new object.\n10% of the time, you'll be using class methods or class variables (\"static\" in C++ or Java parlance.)\n\nI have found a few use cases for class-level methods. I have almost no use cases for class variables. I've never had a situation to change the way object construction works.\n" ]
[ 25, 9 ]
[]
[]
[ "metaclass", "python", "super", "types" ]
stackoverflow_0000395982_metaclass_python_super_types.txt
Q: How do I install MySQL and the Python MySQL package on OS X Leopard? Or how do I learn about being a web developer using OS X? I'm new to the Mac OS X, and I'm just about ready to throw my brand new MacBook Pro out the window. Every tutorial on setting up a Django development environment on Mac OS X Leopard is insidiously wrong. They are all skipping over one step, or assuming you have setup something one way, or are just assuming that I know one thing that I must not. I'm very familiar with how to setup the environment on Ubuntu/Linux, and the only part I'm getting stuck on with OS X is how to install MySQL, autostart it, and install the Python MySQL bindings. I think my mistake was using a hodgepodge of tools I don't fully understand; I used fink to install MySQL and its development libraries and then tried to build the Python-MySQL bindings from source (but they won't build.) UPDATE: I installed the binary MySQL package from http://dev.mysql.com/downloads/mysql/5.1.html#macosx-dmg, and I got MySQL server running (can access with admin.) The MySQL version I got from port was rubbish, I could not get it to run at all. I modified the source for the Python-MySQL package as per the answer I chose, but I still got compilation errors that I listed in the comments. I was able to fix these by adding /usr/local/mysql/bin/ to my path in my "~/.profile" file. " PATH=/usr/local/mysql/bin:$PATH " Thanks for the help, I was very wary about editing the source code since this operation had been so easy on Ubuntu, but I'll be more willing to try that in the future. I'm really missing Ubuntu's "apt-get" command; it makes life very easy and simple sometimes. I already have an Ubuntu VMware image running on my Mac, so I can always use that as a fallback (plus it more closely matches my production machines so should be a good test environment for debugging production problems.) A: Did the MySQL and MySQL-dev installations go smoothly? Can you run MySQL, connect to it and so on? Does /usr/local/mysql/include contain lots of header files? (I've got 46 header files there, for reference). If so, MySQL should be good to go. There are still a few manual steps required to compile MySQL-python, however. This is a decent guide: I've included the salient steps below. Download the MySQL-python source (v1.2.2 at time of writing: all subsequent instructions are for this version) $ tar xzf MySQL-python-1.2.2.tar.gz && cd MySQL-python-1.2.2 Edit _mysql.c: remove lines 37-39 and change lines 481-482. Here's the diff: 37,39d36 < #ifndef uint < #define uint unsigned int < #endif 484,485c481,482 < uint port = MYSQL_PORT; < uint client_flag = 0; --- > unsigned int port = MYSQL_PORT; > unsigned int client_flag = 0; Symlink the libs to where MySQL-python expects them: $ sudo ln -s /usr/local/mysql/lib /usr/local/mysql/lib/mysql In your MySQL-python-1.2.2 directory, rebuild your package: $ sudo python setup.py build Note: You will receive a warning, ignore it. Install the package: $ sudo python setup.py install As for starting MySQL, there are instructions here on starting it as a service. Personally, I just run sudo mysqld_safe manually, backgrounding it with ^Z and bg once I've put in my password. A: You can use the BSD-alike(?) http://macports.org, which provides gentoo-like build-it-yourself installations of a wide swath of software you'd expect to find in a Linux distro. Alternatively you could just run Ubuntu in a virtual machine as your test stage. It's honestly a simple # port install <pkgname> A: Assuming this is just a development environment, you could try using SQLite 3 as your database. Mileage may vary depending on how low-level you need to get with the database for your specific application. A: The Python mysqldb packge is in fink, but it's in the unstable tree. Just enable the unstable tree, and you will be able to install it. Or, if you're up for having two alternate package managers, it's also in MacPorts. I also had problems last time I had to do this and ended up going with the fink version and saving a lot of headache. A: I put a step-by-step guide in a blog post that might help: Installing Django with MySQL on Mac OS X. A: If you are a Mac user, install MacPorts. Almost any Linux/Unix application is available through "port". It is simple and easy to manage. A: Install MacPorts. Run port install mysql. It worked for me!
How do I install MySQL and the Python MySQL package on OS X Leopard? Or how do I learn about being a web developer using OS X?
I'm new to the Mac OS X, and I'm just about ready to throw my brand new MacBook Pro out the window. Every tutorial on setting up a Django development environment on Mac OS X Leopard is insidiously wrong. They are all skipping over one step, or assuming you have setup something one way, or are just assuming that I know one thing that I must not. I'm very familiar with how to setup the environment on Ubuntu/Linux, and the only part I'm getting stuck on with OS X is how to install MySQL, autostart it, and install the Python MySQL bindings. I think my mistake was using a hodgepodge of tools I don't fully understand; I used fink to install MySQL and its development libraries and then tried to build the Python-MySQL bindings from source (but they won't build.) UPDATE: I installed the binary MySQL package from http://dev.mysql.com/downloads/mysql/5.1.html#macosx-dmg, and I got MySQL server running (can access with admin.) The MySQL version I got from port was rubbish, I could not get it to run at all. I modified the source for the Python-MySQL package as per the answer I chose, but I still got compilation errors that I listed in the comments. I was able to fix these by adding /usr/local/mysql/bin/ to my path in my "~/.profile" file. " PATH=/usr/local/mysql/bin:$PATH " Thanks for the help, I was very wary about editing the source code since this operation had been so easy on Ubuntu, but I'll be more willing to try that in the future. I'm really missing Ubuntu's "apt-get" command; it makes life very easy and simple sometimes. I already have an Ubuntu VMware image running on my Mac, so I can always use that as a fallback (plus it more closely matches my production machines so should be a good test environment for debugging production problems.)
[ "Did the MySQL and MySQL-dev installations go smoothly? Can you run MySQL, connect to it and so on? Does /usr/local/mysql/include contain lots of header files? (I've got 46 header files there, for reference).\nIf so, MySQL should be good to go. There are still a few manual steps required to compile MySQL-python, however.\nThis is a decent guide: I've included the salient steps below.\n\n\nDownload the MySQL-python source (v1.2.2 at time of writing: all subsequent instructions are for this version)\n$ tar xzf MySQL-python-1.2.2.tar.gz && cd MySQL-python-1.2.2\n\nEdit _mysql.c: remove lines 37-39 and change lines 481-482. Here's the diff:\n37,39d36\n< #ifndef uint\n< #define uint unsigned int\n< #endif\n484,485c481,482\n< uint port = MYSQL_PORT;\n< uint client_flag = 0;\n---\n> unsigned int port = MYSQL_PORT;\n> unsigned int client_flag = 0;\n\nSymlink the libs to where MySQL-python expects them:\n$ sudo ln -s /usr/local/mysql/lib /usr/local/mysql/lib/mysql\n\nIn your MySQL-python-1.2.2 directory, rebuild your package:\n$ sudo python setup.py build\n\nNote: You will receive a warning, ignore it.\nInstall the package:\n$ sudo python setup.py install\n\n\n\nAs for starting MySQL, there are instructions here on starting it as a service. Personally, I just run\nsudo mysqld_safe \n\nmanually, backgrounding it with ^Z and bg once I've put in my password.\n", "You can use the BSD-alike(?) http://macports.org, which provides gentoo-like build-it-yourself installations of a wide swath of software you'd expect to find in a Linux distro.\nAlternatively you could just run Ubuntu in a virtual machine as your test stage.\nIt's honestly a simple \n# port install <pkgname>\n", "Assuming this is just a development environment, you could try using SQLite 3 as your database. Mileage may vary depending on how low-level you need to get with the database for your specific application.\n", "The Python mysqldb packge is in fink, but it's in the unstable tree. Just enable the unstable tree, and you will be able to install it.\nOr, if you're up for having two alternate package managers, it's also in MacPorts.\nI also had problems last time I had to do this and ended up going with the fink version and saving a lot of headache.\n", "I put a step-by-step guide in a blog post that might help: Installing Django with MySQL on Mac OS X.\n", "If you are a Mac user, install MacPorts. Almost any Linux/Unix application is available through \"port\". It is simple and easy to manage.\n", "Install MacPorts. Run port install mysql. It worked for me!\n" ]
[ 12, 2, 2, 0, 0, 0, 0 ]
[]
[]
[ "django", "macos", "mysql", "python", "sysadmin" ]
stackoverflow_0000395509_django_macos_mysql_python_sysadmin.txt
Q: Desktop graphics - or "skinned" windows I'm looking for a way to draw animations right on the desktop. No window frames and with transparent background. I'm using Python in windows XP for it, but it doesn't have to be cross platform, although it'd be a nice bonus. Does anyone know about a python library that can do this? A: If you want a frameless window, there are several options. For example, pygame can be initialized with the following flag: pygame.init() screen = pygame.display.set_mode(size=(640,480), pygame.NOFRAME) Your question doesn't make it clear if you're looking for a transparent surface, though.
Desktop graphics - or "skinned" windows
I'm looking for a way to draw animations right on the desktop. No window frames and with transparent background. I'm using Python in windows XP for it, but it doesn't have to be cross platform, although it'd be a nice bonus. Does anyone know about a python library that can do this?
[ "If you want a frameless window, there are several options. For example, pygame can be initialized with the following flag:\npygame.init()\nscreen = pygame.display.set_mode(size=(640,480), pygame.NOFRAME)\n\nYour question doesn't make it clear if you're looking for a transparent surface, though.\n" ]
[ 2 ]
[]
[]
[ "desktop", "graphics", "python", "shaped_window", "skinning" ]
stackoverflow_0000396791_desktop_graphics_python_shaped_window_skinning.txt
Q: commands to send messages in Python via the Poplib module? I've found a number of tutorials online involving downloading messages via Poplib, but haven't been able to find anything explaining how to create new messages. Does this exist? A: As S.Lott rightly says, you will want some smtp, but to create the actual email, use the email package from the standard library, then use an message's as_string method to send it. An example with multipart MIME (how cool is that!) A: Send yourself an email to create a message. SMTP is the protocol the email uses to send. In Python, you'd find this in smtplib. There are numerous email RFC's. Here are a few. SMTP - RFC 821 POP - RFC 1939 IMAP - RFC 1730
commands to send messages in Python via the Poplib module?
I've found a number of tutorials online involving downloading messages via Poplib, but haven't been able to find anything explaining how to create new messages. Does this exist?
[ "As S.Lott rightly says, you will want some smtp, but to create the actual email, use the email package from the standard library, then use an message's as_string method to send it.\nAn example with multipart MIME (how cool is that!)\n", "Send yourself an email to create a message.\nSMTP is the protocol the email uses to send. In Python, you'd find this in smtplib.\nThere are numerous email RFC's. Here are a few.\nSMTP - RFC 821 \nPOP - RFC 1939\nIMAP - RFC 1730\n" ]
[ 3, 2 ]
[]
[]
[ "email", "poplib", "python" ]
stackoverflow_0000396991_email_poplib_python.txt
Q: Trouble with encoding in emails I have a little python script that pulls emails from a POP mail address and dumps them into a file (one file one email) Then a PHP script runs through the files and displays them. I am having an issue with ISO-8859-1 (Latin-1) encoded email Here's an example of the text i get: =?iso-8859-1?Q?G=EDsli_Karlsson?= and Sj=E1um hva=F0 =F3li er kl=E1r J The way i pull emails is this code. pop = poplib.POP3(server) mail_list = pop.list()[1] for m in mail_list: mno, size = m.split() lines = pop.retr(mno)[1] file = StringIO.StringIO("\r\n".join(lines)) msg = rfc822.Message(file) body = file.readlines() f = open(str(random.randint(1,100)) + ".email", "w") f.write(msg["From"] + "\n") f.write(msg["Subject"] + "\n") f.write(msg["Date"] + "\n") for b in body: f.write(b) I have tried probably all combinations of encode / decode within python and php. A: You can use the python email library (python 2.5+) to avoid these problems: import email import poplib import random from cStringIO import StringIO from email.generator import Generator pop = poplib.POP3(server) mail_count = len(pop.list()[1]) for message_num in xrange(mail_count): message = "\r\n".join(pop.retr(message_num)[1]) message = email.message_from_string(message) out_file = StringIO() message_gen = Generator(out_file, mangle_from_=False, maxheaderlen=60) message_gen.flatten(message) message_text = out_file.getvalue() filename = "%s.email" % random.randint(1,100) email_file = open(filename, "w") email_file.write(message_text) email_file.close() This code will get all the messages from your server and turn them into Python message objects then flatten them out into strings again for writing to the file. By using the email package from the Python standard library MIME encoding and decoding issues should be handled for you. DISCLAIMER: I have not tested that code, but it should work just fine. A: That's the MIME encoding of headers, RFC 2047. Here is how to decode it in Python: import email.Header import sys header_and_encoding = email.Header.decode_header(sys.stdin.readline()) for part in header_and_encoding: if part[1] is None: print part[0], else: upart = (part[0]).decode(part[1]) print upart.encode('latin-1'), print More detailed explanations (in French) in http://www.bortzmeyer.org/decoder-en-tetes-courrier.html A: There is a better way to do this, but this is what i ended up with. Thanks for your help guys. import poplib, quopri import random, md5 import sys, rfc822, StringIO import email from email.Generator import Generator user = "email@example.com" password = "password" server = "mail.example.com" # connects try: pop = poplib.POP3(server) except: print "Error connecting to server" sys.exit(-1) # user auth try: print pop.user(user) print pop.pass_(password) except: print "Authentication error" sys.exit(-2) # gets the mail list mail_list = pop.list()[1] for m in mail_list: mno, size = m.split() message = "\r\n".join(pop.retr(mno)[1]) message = email.message_from_string(message) # uses the email flatten out_file = StringIO.StringIO() message_gen = Generator(out_file, mangle_from_=False, maxheaderlen=60) message_gen.flatten(message) message_text = out_file.getvalue() # fixes mime encoding issues (for display within html) clean_text = quopri.decodestring(message_text) msg = email.message_from_string(clean_text) # finds the last body (when in mime multipart, html is the last one) for part in msg.walk(): if part.get_content_type(): body = part.get_payload(decode=True) filename = "%s.email" % random.randint(1,100) email_file = open(filename, "w") email_file.write(msg["From"] + "\n") email_file.write(msg["Return-Path"] + "\n") email_file.write(msg["Subject"] + "\n") email_file.write(msg["Date"] + "\n") email_file.write(body) email_file.close() pop.quit() sys.exit() A: Until very recently, plain Latin-N or utf-N were no allowed in headers which means that they would get to be encoded by a method described at first in RFC-1522 but it has been superseded later. Accents are encoded either in quoted-printable or in Base64 and it is indicated by the ?Q? (or ?B? for Base64). You'll have to decode them. Oh and space is encoded as "_". See Wikipedia. A: That's MIME content, and that's how the email actually looks like, not a bug somewhere. You have to use a MIME decoding library (or decode it yourself manually) on the PHP side of things (which, if I understood correctly, is the one acting as email renderer). In Python you'd use mimetools. In PHP, I'm not sure. It seems the Zend framework has a MIME parser somewhere, and there are probably zillions of snippets floating around. http://en.wikipedia.org/wiki/MIME#Encoded-Word
Trouble with encoding in emails
I have a little python script that pulls emails from a POP mail address and dumps them into a file (one file one email) Then a PHP script runs through the files and displays them. I am having an issue with ISO-8859-1 (Latin-1) encoded email Here's an example of the text i get: =?iso-8859-1?Q?G=EDsli_Karlsson?= and Sj=E1um hva=F0 =F3li er kl=E1r J The way i pull emails is this code. pop = poplib.POP3(server) mail_list = pop.list()[1] for m in mail_list: mno, size = m.split() lines = pop.retr(mno)[1] file = StringIO.StringIO("\r\n".join(lines)) msg = rfc822.Message(file) body = file.readlines() f = open(str(random.randint(1,100)) + ".email", "w") f.write(msg["From"] + "\n") f.write(msg["Subject"] + "\n") f.write(msg["Date"] + "\n") for b in body: f.write(b) I have tried probably all combinations of encode / decode within python and php.
[ "You can use the python email library (python 2.5+) to avoid these problems:\nimport email\nimport poplib\nimport random\nfrom cStringIO import StringIO\nfrom email.generator import Generator\n\npop = poplib.POP3(server)\n\nmail_count = len(pop.list()[1])\n\nfor message_num in xrange(mail_count):\n message = \"\\r\\n\".join(pop.retr(message_num)[1])\n message = email.message_from_string(message)\n\n out_file = StringIO()\n message_gen = Generator(out_file, mangle_from_=False, maxheaderlen=60)\n message_gen.flatten(message)\n message_text = out_file.getvalue()\n\n filename = \"%s.email\" % random.randint(1,100)\n email_file = open(filename, \"w\")\n email_file.write(message_text)\n email_file.close()\n\nThis code will get all the messages from your server and turn them into Python message objects then flatten them out into strings again for writing to the file. By using the email package from the Python standard library MIME encoding and decoding issues should be handled for you.\nDISCLAIMER: I have not tested that code, but it should work just fine.\n", "That's the MIME encoding of headers, RFC 2047. Here is how to decode it in Python:\nimport email.Header\nimport sys\n\nheader_and_encoding = email.Header.decode_header(sys.stdin.readline())\nfor part in header_and_encoding:\n if part[1] is None:\n print part[0],\n else:\n upart = (part[0]).decode(part[1])\n print upart.encode('latin-1'),\nprint\n\nMore detailed explanations (in French) in http://www.bortzmeyer.org/decoder-en-tetes-courrier.html\n", "There is a better way to do this, but this is what i ended up with. Thanks for your help guys.\nimport poplib, quopri\nimport random, md5\nimport sys, rfc822, StringIO\nimport email\nfrom email.Generator import Generator\n\nuser = \"email@example.com\"\npassword = \"password\"\nserver = \"mail.example.com\"\n\n# connects\ntry:\n pop = poplib.POP3(server)\nexcept:\n print \"Error connecting to server\"\n sys.exit(-1)\n\n# user auth\ntry:\n print pop.user(user)\n print pop.pass_(password)\nexcept:\n print \"Authentication error\"\n sys.exit(-2)\n\n# gets the mail list\nmail_list = pop.list()[1]\n\nfor m in mail_list:\n mno, size = m.split()\n message = \"\\r\\n\".join(pop.retr(mno)[1])\n message = email.message_from_string(message)\n\n # uses the email flatten\n out_file = StringIO.StringIO()\n message_gen = Generator(out_file, mangle_from_=False, maxheaderlen=60)\n message_gen.flatten(message)\n message_text = out_file.getvalue()\n\n # fixes mime encoding issues (for display within html)\n clean_text = quopri.decodestring(message_text)\n\n msg = email.message_from_string(clean_text)\n\n # finds the last body (when in mime multipart, html is the last one)\n for part in msg.walk():\n if part.get_content_type():\n body = part.get_payload(decode=True)\n\n filename = \"%s.email\" % random.randint(1,100)\n\n email_file = open(filename, \"w\")\n\n email_file.write(msg[\"From\"] + \"\\n\")\n email_file.write(msg[\"Return-Path\"] + \"\\n\")\n email_file.write(msg[\"Subject\"] + \"\\n\")\n email_file.write(msg[\"Date\"] + \"\\n\")\n email_file.write(body)\n\n email_file.close()\n\npop.quit()\nsys.exit()\n\n", "Until very recently, plain Latin-N or utf-N were no allowed in headers which means that they would get to be encoded by a method described at first in RFC-1522 but it has been superseded later. Accents are encoded either in quoted-printable or in Base64 and it is indicated by the ?Q? (or ?B? for Base64). You'll have to decode them. Oh and space is encoded as \"_\". See Wikipedia.\n", "That's MIME content, and that's how the email actually looks like, not a bug somewhere. You have to use a MIME decoding library (or decode it yourself manually) on the PHP side of things (which, if I understood correctly, is the one acting as email renderer).\nIn Python you'd use mimetools. In PHP, I'm not sure. It seems the Zend framework has a MIME parser somewhere, and there are probably zillions of snippets floating around.\nhttp://en.wikipedia.org/wiki/MIME#Encoded-Word\n" ]
[ 3, 2, 2, 1, 0 ]
[]
[]
[ "email", "encoding", "python" ]
stackoverflow_0000389398_email_encoding_python.txt
Q: PHP vs. application server? For those of you who have had the opportunity of writing web applications in PHP and then as an application server (eg. Python-based solutions like CherryPy or Pylons), in what context are application servers a better alternative to PHP? I tend to favor PHP simply because it's available on just about any web server (especially shared host), but I'm looking for other good reasons to make an informed choice. Thank you. A: I have a feeling that some of the responses didn't address the initial question directly, so I decided to post my own. I understand that the question was about the difference between the mod_php deployment model and the application server deployment model. In simple words, PHP executes a given script on every request, and the application has no knowledge of what has happened before (unless it is emulated somehow). Moreover even the source code is being parsed on every request (unless you use a bytecode cache like APC). This process can be slow, especially if you have a framework with complex initialization. In contrast to this, the application server has to be started once, and then it waits for a request to be processed. The application server should clean up resources after every requests (allocated memory, open descriptors, etc.), it can also pool certain resources (like database connections) that can be reused between requests for extra performance. This later model (application server) is more efficient in most cases, but on the other hand more difficult to setup and maintain. It is also more demanding, as you have to pay more attention to the resources you utilize, in order to avoid resource leaks. A: The advantage of deployment for PHP is a huge one. You will also have a large developer base, and sound like you already have considerable expertise. In general if you know how to use a programming language well, you are safer to stick with it. The advantages of using a Python web framework like Pylons are that your code will be neater, and more maintainable. Of course this is possible with PHP, but seems much harder to achieve. Python is simply a nicer language than PHP, so that might affect your decision. Personally, I would not describe either Pylons or CherryPy as an "application server", if you want a Python application server, try Zope. (They both do serve WSGI Applications, but that is a topic for another question.) There seem to be plenty of equivalent frameworks for PHP, and they have been listed in other answers. A: There are several products in PHP which fill the same space as CherryPy or Pylons. (except, of course, they don't run Python ;) Have a look at - CakePHP - http://www.cakephp.org/ Symfony - http://www.symfony-project.org/ Code Igniter - http://codeigniter.com/ Zend Framework - http://framework.zend.com/ Personally, I prefer Drupal, which works as a great framework and comes with a lot of CMS and community site features out of the box. The ones above are quite different in many ways, but any of these should offer you the best of both worlds if you want an app framework / appserver that runs on PHP. Drupal - http://drupal.org/ Which one is the right choice is largely a matter of taste, although each has its various advantages and disadvantages. There are many more - these are just the ones I've heard good things about from colleagues and collaborators. It's not a complete list. A: Python web-apps tend to require more initial setup and development than the equivalent PHP site (particularly so for small sites). There also tend to be more reusable pieces for PHP (ie Wordpress as a blog). Configuring a server to run Python web-apps can be a difficult process, and not always well documented. PHP tends to be very easy to get running with Apache. Also, as PHP is very widely used and is heavily used by beginners, there tends to be very good documentation for it. However, Python is much more fun, and much more maintainable. It scales well (in development complexity terms, rather than traffic). Personally, I would also say that using Python tends to train you to solve problems in a better way. I am definitely a better developer for having learned the Pythonic way of doing things. A: Using application servers like Pylons, Django, etc. require much more work to setup and deploy then PHP applications which are generally supported out of the box. I run a few Django apps and had to learn a bit of configuring apache with mod_python in order to get things to work. I put forth the effort because coding in python is much more enjoyable to me than PHP and after you get the Apache config right once you never really have to mess with it again. On another note, if you decide to go with a framework like Django, Rails, Pylons, .... they tend to solve a lot of small repetitive tasks that you would otherwise do on your own. But frameworks are their own huge topic of discussion.
PHP vs. application server?
For those of you who have had the opportunity of writing web applications in PHP and then as an application server (eg. Python-based solutions like CherryPy or Pylons), in what context are application servers a better alternative to PHP? I tend to favor PHP simply because it's available on just about any web server (especially shared host), but I'm looking for other good reasons to make an informed choice. Thank you.
[ "I have a feeling that some of the responses didn't address the initial question directly, so I decided to post my own. I understand that the question was about the difference between the mod_php deployment model and the application server deployment model.\nIn simple words, PHP executes a given script on every request, and the application has no knowledge of what has happened before (unless it is emulated somehow). Moreover even the source code is being parsed on every request (unless you use a bytecode cache like APC). This process can be slow, especially if you have a framework with complex initialization.\nIn contrast to this, the application server has to be started once, and then it waits for a request to be processed. The application server should clean up resources after every requests (allocated memory, open descriptors, etc.), it can also pool certain resources (like database connections) that can be reused between requests for extra performance.\nThis later model (application server) is more efficient in most cases, but on the other hand more difficult to setup and maintain. It is also more demanding, as you have to pay more attention to the resources you utilize, in order to avoid resource leaks.\n", "The advantage of deployment for PHP is a huge one. You will also have a large developer base, and sound like you already have considerable expertise. In general if you know how to use a programming language well, you are safer to stick with it.\nThe advantages of using a Python web framework like Pylons are that your code will be neater, and more maintainable. Of course this is possible with PHP, but seems much harder to achieve. Python is simply a nicer language than PHP, so that might affect your decision.\nPersonally, I would not describe either Pylons or CherryPy as an \"application server\", if you want a Python application server, try Zope. (They both do serve WSGI Applications, but that is a topic for another question.) There seem to be plenty of equivalent frameworks for PHP, and they have been listed in other answers.\n", "There are several products in PHP which fill the same space as CherryPy or Pylons.\n(except, of course, they don't run Python ;)\nHave a look at -\n\nCakePHP - http://www.cakephp.org/\nSymfony - http://www.symfony-project.org/\nCode Igniter - http://codeigniter.com/\nZend Framework - http://framework.zend.com/\n\nPersonally, I prefer Drupal, which works as a great framework and comes with a lot of CMS and community site features out of the box. The ones above are quite different in many ways, but any of these should offer you the best of both worlds if you want an app framework / appserver that runs on PHP. \n\nDrupal - http://drupal.org/\n\nWhich one is the right choice is largely a matter of taste, although each has its various advantages and disadvantages.\nThere are many more - these are just the ones I've heard good things about from colleagues and collaborators. It's not a complete list.\n", "Python web-apps tend to require more initial setup and development than the equivalent PHP site (particularly so for small sites). There also tend to be more reusable pieces for PHP (ie Wordpress as a blog). Configuring a server to run Python web-apps can be a difficult process, and not always well documented. PHP tends to be very easy to get running with Apache.\nAlso, as PHP is very widely used and is heavily used by beginners, there tends to be very good documentation for it.\nHowever, Python is much more fun, and much more maintainable. It scales well (in development complexity terms, rather than traffic).\nPersonally, I would also say that using Python tends to train you to solve problems in a better way. I am definitely a better developer for having learned the Pythonic way of doing things.\n", "Using application servers like Pylons, Django, etc. require much more work to setup and deploy then PHP applications which are generally supported out of the box. I run a few Django apps and had to learn a bit of configuring apache with mod_python in order to get things to work. I put forth the effort because coding in python is much more enjoyable to me than PHP and after you get the Apache config right once you never really have to mess with it again.\nOn another note, if you decide to go with a framework like Django, Rails, Pylons, .... they tend to solve a lot of small repetitive tasks that you would otherwise do on your own. But frameworks are their own huge topic of discussion.\n" ]
[ 5, 4, 1, 1, 0 ]
[]
[]
[ "php", "python" ]
stackoverflow_0000395960_php_python.txt
Q: django,fastcgi: how to manage a long running process? I have inherited a django+fastcgi application which needs to be modified to perform a lengthy computation (up to half an hour or more). What I want to do is run the computation in the background and return a "your job has been started" -type response. While the process is running, further hits to the url should return "your job is still running" until the job finishes at which point the results of the job should be returned. Any subsequent hit on the url should return the cached result. I'm an utter novice at django and haven't done any significant web work in a decade so I don't know if there's a built-in way to do what I want. I've tried starting the process via subprocess.Popen(), and that works fine except for the fact it leaves a defunct entry in the process table. I need a clean solution that can remove temporary files and any traces of the process once it has finished. I've also experimented with fork() and threads and have yet to come up with a viable solution. Is there a canonical solution to what seems to me to be a pretty common use case? FWIW this will only be used on an internal server with very low traffic. A: I have to solve a similar problem now. It is not going to be a public site, but similarly, an internal server with low traffic. Technical constraints: all input data to the long running process can be supplied on its start long running process does not require user interaction (except for the initial input to start a process) the time of the computation is long enough so that the results cannot be served to the client in an immediate HTTP response some sort of feedback (sort of progress bar) from the long running process is required. Hence, we need at least two web “views”: one to initiate the long running process, and the other, to monitor its status/collect the results. We also need some sort of interprocess communication: send user data from the initiator (the web server on http request) to the long running process, and then send its results to the reciever (again web server, driven by http requests). The former is easy, the latter is less obvious. Unlike in normal unix programming, the receiver is not known initially. The receiver may be a different process from the initiator, and it may start when the long running job is still in progress or is already finished. So the pipes do not work and we need some permamence of the results of the long running process. I see two possible solutions: dispatch launches of the long running processes to the long running job manager (this is probably what the above-mentioned django-queue-service is); save the results permanently, either in a file or in DB. I preferred to use temporary files and to remember their locaiton in the session data. I don't think it can be made more simple. A job script (this is the long running process), myjob.py: import sys from time import sleep i = 0 while i < 1000: print 'myjob:', i i=i+1 sleep(0.1) sys.stdout.flush() django urls.py mapping: urlpatterns = patterns('', (r'^startjob/$', 'mysite.myapp.views.startjob'), (r'^showjob/$', 'mysite.myapp.views.showjob'), (r'^rmjob/$', 'mysite.myapp.views.rmjob'), ) django views: from tempfile import mkstemp from os import fdopen,unlink,kill from subprocess import Popen import signal def startjob(request): """Start a new long running process unless already started.""" if not request.session.has_key('job'): # create a temporary file to save the resuls outfd,outname=mkstemp() request.session['jobfile']=outname outfile=fdopen(outfd,'a+') proc=Popen("python myjob.py",shell=True,stdout=outfile) # remember pid to terminate the job later request.session['job']=proc.pid return HttpResponse('A <a href="/showjob/">new job</a> has started.') def showjob(request): """Show the last result of the running job.""" if not request.session.has_key('job'): return HttpResponse('Not running a job.'+\ '<a href="/startjob/">Start a new one?</a>') else: filename=request.session['jobfile'] results=open(filename) lines=results.readlines() try: return HttpResponse(lines[-1]+\ '<p><a href="/rmjob/">Terminate?</a>') except: return HttpResponse('No results yet.'+\ '<p><a href="/rmjob/">Terminate?</a>') return response def rmjob(request): """Terminate the runining job.""" if request.session.has_key('job'): job=request.session['job'] filename=request.session['jobfile'] try: kill(job,signal.SIGKILL) # unix only unlink(filename) except OSError, e: pass # probably the job has finished already del request.session['job'] del request.session['jobfile'] return HttpResponseRedirect('/startjob/') # start a new one A: Maybe you could look at the problem the other way around. Maybe you could try DjangoQueueService, and have a "daemon" listening to the queue, seeing if there's something new and process it.
django,fastcgi: how to manage a long running process?
I have inherited a django+fastcgi application which needs to be modified to perform a lengthy computation (up to half an hour or more). What I want to do is run the computation in the background and return a "your job has been started" -type response. While the process is running, further hits to the url should return "your job is still running" until the job finishes at which point the results of the job should be returned. Any subsequent hit on the url should return the cached result. I'm an utter novice at django and haven't done any significant web work in a decade so I don't know if there's a built-in way to do what I want. I've tried starting the process via subprocess.Popen(), and that works fine except for the fact it leaves a defunct entry in the process table. I need a clean solution that can remove temporary files and any traces of the process once it has finished. I've also experimented with fork() and threads and have yet to come up with a viable solution. Is there a canonical solution to what seems to me to be a pretty common use case? FWIW this will only be used on an internal server with very low traffic.
[ "I have to solve a similar problem now. It is not going to be a public site, but similarly, an internal server with low traffic.\nTechnical constraints:\n\nall input data to the long running process can be supplied on its start\nlong running process does not require user interaction (except for the initial input to start a process)\nthe time of the computation is long enough so that the results cannot be served to the client in an immediate HTTP response\nsome sort of feedback (sort of progress bar) from the long running process is required.\n\nHence, we need at least two web “views”: one to initiate the long running process, and the other, to monitor its status/collect the results.\nWe also need some sort of interprocess communication: send user data from the initiator (the web server on http request) to the long running process, and then send its results to the reciever (again web server, driven by http requests). The former is easy, the latter is less obvious. Unlike in normal unix programming, the receiver is not known initially. The receiver may be a different process from the initiator, and it may start when the long running job is still in progress or is already finished. So the pipes do not work and we need some permamence of the results of the long running process.\nI see two possible solutions:\n\ndispatch launches of the long running processes to the long running job manager (this is probably what the above-mentioned django-queue-service is);\nsave the results permanently, either in a file or in DB.\n\nI preferred to use temporary files and to remember their locaiton in the session data. I don't think it can be made more simple.\nA job script (this is the long running process), myjob.py:\nimport sys\nfrom time import sleep\n\ni = 0\nwhile i < 1000:\n print 'myjob:', i \n i=i+1\n sleep(0.1)\n sys.stdout.flush()\n\ndjango urls.py mapping:\nurlpatterns = patterns('',\n(r'^startjob/$', 'mysite.myapp.views.startjob'),\n(r'^showjob/$', 'mysite.myapp.views.showjob'),\n(r'^rmjob/$', 'mysite.myapp.views.rmjob'),\n)\n\ndjango views:\nfrom tempfile import mkstemp\nfrom os import fdopen,unlink,kill\nfrom subprocess import Popen\nimport signal\n\ndef startjob(request):\n \"\"\"Start a new long running process unless already started.\"\"\"\n if not request.session.has_key('job'):\n # create a temporary file to save the resuls\n outfd,outname=mkstemp()\n request.session['jobfile']=outname\n outfile=fdopen(outfd,'a+')\n proc=Popen(\"python myjob.py\",shell=True,stdout=outfile)\n # remember pid to terminate the job later\n request.session['job']=proc.pid\n return HttpResponse('A <a href=\"/showjob/\">new job</a> has started.')\n\ndef showjob(request):\n \"\"\"Show the last result of the running job.\"\"\"\n if not request.session.has_key('job'):\n return HttpResponse('Not running a job.'+\\\n '<a href=\"/startjob/\">Start a new one?</a>')\n else:\n filename=request.session['jobfile']\n results=open(filename)\n lines=results.readlines()\n try:\n return HttpResponse(lines[-1]+\\\n '<p><a href=\"/rmjob/\">Terminate?</a>')\n except:\n return HttpResponse('No results yet.'+\\\n '<p><a href=\"/rmjob/\">Terminate?</a>')\n return response\n\ndef rmjob(request):\n \"\"\"Terminate the runining job.\"\"\"\n if request.session.has_key('job'):\n job=request.session['job']\n filename=request.session['jobfile']\n try:\n kill(job,signal.SIGKILL) # unix only\n unlink(filename)\n except OSError, e:\n pass # probably the job has finished already\n del request.session['job']\n del request.session['jobfile']\n return HttpResponseRedirect('/startjob/') # start a new one\n\n", "Maybe you could look at the problem the other way around.\nMaybe you could try DjangoQueueService, and have a \"daemon\" listening to the queue, seeing if there's something new and process it.\n" ]
[ 4, 3 ]
[]
[]
[ "django", "fastcgi", "python" ]
stackoverflow_0000219329_django_fastcgi_python.txt
Q: Can I call and set the Python gettext module in a library and a module using it at the same time? Im a coding a library including textual feedback that I need to translate. I put the following lines in a _config.py module that I import everywhere in my app : import gettext, os, sys pathname = os.path.dirname(sys.argv[0]) localdir = os.path.abspath(pathname) + "/locale" gettext.install("messages", localdir) I have the *.mo files in ./locale/lang_LANG/LC_MESSAGES and I apply the _() function to all the strings that need to be translated. Now I just added a feature for the user, supposedly a programmer, to be able to create his own messages. I don't want him to care about the underlying implementation, so I want him to be able to make it something straightforward like : lib_object.message = "My message" I used properties to make it clean, but what if my user whats to translate his own code (that uses mine) and does something like : import gettext, os, sys pathname = os.path.dirname(sys.argv[0]) localdir = os.path.abspath(pathname) + "/locale" gettext.install("user_app", localdir) lib_object.message = _("My message") Is it a problem ? What can I do to avoid troubles without bothering my user ? A: You can use the class based gettext api to isolate message catalogs. This is also what is recommended in the python gettext documentation. The drawback is that you, or the other dev, will have to use the gettext method or define the _() method in the local scope, bound to the specific gettext class. An example of a class with its own string catalog: import gettext class MyClass(object): def __init__(self, locale_for_instance): self.lang = gettext.translation("appname", localedir, \ locale=locale_for_instance) def some_method(self, arg): return self.lang.gettext("You called some method") def other_method(self, arg): # does the same thing _ = self.lang.gettext return _("You called some method") You could stick the code for adding the _() in a decorator, so all the methods that need it is prefixed with something like @with_local_gettext (Note, I've not tested the above could but It Should Work Just Fine(tm) ) If the goal is to not bother your user (and he's not very good) I guess you could use the class based approach in your code and let the user use the global one. A: You can only gettext.install() once. In general it's useless for library work -- gettext.install() will only do the right thing if the module calling it is in charge of the whole program, since it will only provide you with one catalog to load from. Library code should do something akin to what Mailman does: have their own wrapper for gettext() that passes the right arguments for this module, then imports that as '_' in each module that wants to use it.
Can I call and set the Python gettext module in a library and a module using it at the same time?
Im a coding a library including textual feedback that I need to translate. I put the following lines in a _config.py module that I import everywhere in my app : import gettext, os, sys pathname = os.path.dirname(sys.argv[0]) localdir = os.path.abspath(pathname) + "/locale" gettext.install("messages", localdir) I have the *.mo files in ./locale/lang_LANG/LC_MESSAGES and I apply the _() function to all the strings that need to be translated. Now I just added a feature for the user, supposedly a programmer, to be able to create his own messages. I don't want him to care about the underlying implementation, so I want him to be able to make it something straightforward like : lib_object.message = "My message" I used properties to make it clean, but what if my user whats to translate his own code (that uses mine) and does something like : import gettext, os, sys pathname = os.path.dirname(sys.argv[0]) localdir = os.path.abspath(pathname) + "/locale" gettext.install("user_app", localdir) lib_object.message = _("My message") Is it a problem ? What can I do to avoid troubles without bothering my user ?
[ "You can use the class based gettext api to isolate message catalogs. This is also what is recommended in the python gettext documentation.\nThe drawback is that you, or the other dev, will have to use the gettext method or define the _() method in the local scope, bound to the specific gettext class. An example of a class with its own string catalog:\nimport gettext\n\nclass MyClass(object):\n def __init__(self, locale_for_instance):\n self.lang = gettext.translation(\"appname\", localedir, \\\n locale=locale_for_instance)\n\n def some_method(self, arg):\n return self.lang.gettext(\"You called some method\")\n\n def other_method(self, arg): # does the same thing\n _ = self.lang.gettext\n return _(\"You called some method\")\n\nYou could stick the code for adding the _() in a decorator, so all the methods that need it is prefixed with something like @with_local_gettext\n(Note, I've not tested the above could but It Should Work Just Fine(tm) )\nIf the goal is to not bother your user (and he's not very good) I guess you could use the class based approach in your code and let the user use the global one.\n", "You can only gettext.install() once. In general it's useless for library work -- gettext.install() will only do the right thing if the module calling it is in charge of the whole program, since it will only provide you with one catalog to load from. Library code should do something akin to what Mailman does: have their own wrapper for gettext() that passes the right arguments for this module, then imports that as '_' in each module that wants to use it.\n" ]
[ 4, 2 ]
[]
[]
[ "gettext", "internationalization", "python" ]
stackoverflow_0000246137_gettext_internationalization_python.txt
Q: Python Proxy Script I'm writing a simple python script so I can test my websites from a different ip address. The url of a page is given in the querystring, the script fetches the page and displays it to the user. The code below is used to rewrite the tags that contain urls but I don't think it's complete/totally correct. def rel2abs(rel_url, base=loc): return urlparse.urljoin(base, rel_url) def is_proxy_else_abs(tag, attr): if tag in ('a',): return True if tag in ('form', 'img', 'link') and attr in ('href', 'src', 'action', 'background'): return False def repl(matchobj): if is_proxy_else_abs(matchobj.group(1).lower(), matchobj.group(3).lower()): return r'<%s %s %s="http://%s?%s" ' %(proxy_script_url, matchobj.group(1), matchobj.group(2), matchobj.group(3), urllib.urlencode({'loc':rel2abs(matchobj.group(5))})) else: return r'<%s %s %s="%s" ' %(matchobj.group(1), matchobj.group(2), matchobj.group(3), rel2abs(matchobj.group(5))) def fix_urls(page): get_link_re = re.compile(r"""<(a|form|img|link) ([^>]*?)(href|src|action|background)\s*=\s*("|'?)([^>]*?)\4""", re.I|re.DOTALL) page = get_link_re.sub(repl, page) return page The idea is that 'a' tag's href attributes should be routed through the proxy script, but css, javascript, images, forms etc should not be, so these have to be made absolute if they are relative in the original page. The problem is the code doesn't always work, css can be written in a number of ways etc. Is there a more comprehensive regex I can use? A: Please read other postings here about parsing HTML. For example Python regular expression for HTML parsing (BeautifulSoup) and HTML parser in Python. Use Beautiful Soup, not regular expressions.
Python Proxy Script
I'm writing a simple python script so I can test my websites from a different ip address. The url of a page is given in the querystring, the script fetches the page and displays it to the user. The code below is used to rewrite the tags that contain urls but I don't think it's complete/totally correct. def rel2abs(rel_url, base=loc): return urlparse.urljoin(base, rel_url) def is_proxy_else_abs(tag, attr): if tag in ('a',): return True if tag in ('form', 'img', 'link') and attr in ('href', 'src', 'action', 'background'): return False def repl(matchobj): if is_proxy_else_abs(matchobj.group(1).lower(), matchobj.group(3).lower()): return r'<%s %s %s="http://%s?%s" ' %(proxy_script_url, matchobj.group(1), matchobj.group(2), matchobj.group(3), urllib.urlencode({'loc':rel2abs(matchobj.group(5))})) else: return r'<%s %s %s="%s" ' %(matchobj.group(1), matchobj.group(2), matchobj.group(3), rel2abs(matchobj.group(5))) def fix_urls(page): get_link_re = re.compile(r"""<(a|form|img|link) ([^>]*?)(href|src|action|background)\s*=\s*("|'?)([^>]*?)\4""", re.I|re.DOTALL) page = get_link_re.sub(repl, page) return page The idea is that 'a' tag's href attributes should be routed through the proxy script, but css, javascript, images, forms etc should not be, so these have to be made absolute if they are relative in the original page. The problem is the code doesn't always work, css can be written in a number of ways etc. Is there a more comprehensive regex I can use?
[ "Please read other postings here about parsing HTML. For example Python regular expression for HTML parsing (BeautifulSoup) and HTML parser in Python.\nUse Beautiful Soup, not regular expressions.\n" ]
[ 3 ]
[]
[]
[ "proxy", "python" ]
stackoverflow_0000398385_proxy_python.txt
Q: Split by \b when your regex engine doesn't support it How can I split by word boundary in a regex engine that doesn't support it? python's re can match on \b but doesn't seem to support splitting on it. I seem to recall dealing with other regex engines that had the same limitation. example input: "hello, foo" expected output: ['hello', ', ', 'foo'] actual python output: >>> re.compile(r'\b').split('hello, foo') ['hello, foo'] A: (\W+) can give you the expected output: >>> re.compile(r'(\W+)').split('hello, foo') ['hello', ', ', 'foo'] A: One can also use re.findall() for this: >>> re.findall(r'.+?\b', 'hello, foo') ['hello', ', ', 'foo'] A: Ok I figured it out: Put the split pattern in capturing parens and will be included in the output. You can use either \w+ or \W+: >>> re.compile(r'(\w+)').split('hello, foo') ['', 'hello', ', ', 'foo', ''] To get rid of the empty results, pass it through filter() with None as the filter function, which will filter anything that doesn't evaluate to true: >>> filter(None, re.compile(r'(\w+)').split('hello, foo')) ['hello', ', ', 'foo'] Edit: CMS points out that if you use \W+ you don't need to use filter() A: Try >>> re.compile(r'\W\b').split('hello, foo') ['hello,', 'foo'] This splits at the non-word characted before a boundry. Your example has nothing to split on. A: Interesting. So far most RE engines I tried do this split. I played a bit and found that re.compile(r'(\W+)').split('hello, foo') is giving the output you expected... Not sure if that's reliable, though.
Split by \b when your regex engine doesn't support it
How can I split by word boundary in a regex engine that doesn't support it? python's re can match on \b but doesn't seem to support splitting on it. I seem to recall dealing with other regex engines that had the same limitation. example input: "hello, foo" expected output: ['hello', ', ', 'foo'] actual python output: >>> re.compile(r'\b').split('hello, foo') ['hello, foo']
[ "(\\W+) can give you the expected output:\n>>> re.compile(r'(\\W+)').split('hello, foo')\n['hello', ', ', 'foo']\n\n", "One can also use re.findall() for this:\n>>> re.findall(r'.+?\\b', 'hello, foo')\n['hello', ', ', 'foo']\n\n", "Ok I figured it out:\nPut the split pattern in capturing parens and will be included in the output. You can use either \\w+ or \\W+:\n>>> re.compile(r'(\\w+)').split('hello, foo')\n['', 'hello', ', ', 'foo', '']\n\nTo get rid of the empty results, pass it through filter() with None as the filter function, which will filter anything that doesn't evaluate to true:\n>>> filter(None, re.compile(r'(\\w+)').split('hello, foo'))\n['hello', ', ', 'foo']\n\nEdit: CMS points out that if you use \\W+ you don't need to use filter()\n", "Try \n>>> re.compile(r'\\W\\b').split('hello, foo')\n['hello,', 'foo']\n\nThis splits at the non-word characted before a boundry.\nYour example has nothing to split on.\n", "Interesting. So far most RE engines I tried do this split.\nI played a bit and found that re.compile(r'(\\W+)').split('hello, foo') is giving the output you expected... Not sure if that's reliable, though.\n" ]
[ 11, 2, 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000398560_python_regex.txt
Q: Need help on selecting items in simple database in python I'm trying to write a circuit schematic drawing tool in Python. I'm creating a simple database based on dictionaries which holds all the components and their properties. I'm also trying to create a simple query language where you can select, for example, all resistors with value>100ohms or footprint='0402' So far, I can select things using some primitive predicate search and then union and intersection for more complex things. However, I'm having trouble defining what the semantics ought to be for a purely negative search. For instance, something like footprint != '0402' should select all items with footprint not equal to 0402. But doing this with only intersection gives me a blank result. For this to work I need to select all components, then intersect with "not 0402" to remove the ones I don't want. But this seems kind of brute force and seems like a fishy solution. I'm not interested in using a "real" database and query language, so please don't suggest that. I'm looking for the proper engineering rationale here, not necessarily a workaround to the problem. This problem was covered to some degree in SICP book, but I got very confused, since I think they were also using continuations and stuff, which I don't get yet. Can someone please explain what the 'proper' usage ought to be for negatively selecting stuff. I tried this in a commercial cad tool and it worked as expected, but then I've seen some SQL query examples (I think), which selected things first, then removed the unwanted ones. thanks michael A: You'll be a lot happier with a proper database. You have SQLite with your Python distribution. Simply define tables instead of dictionaries and use SQL. If you need more power and sophistication, you can add SQLAlchemy (or SQLObject) and you won't struggle with these problems. A: It really depends on how you've implemented this "simple database based on dictionaries" as to why straight negation isn't working - you'll have to give us some more clues. There's no reason why a straightforward negation match shouldn't work in Python, e.g.: components = [ { 'name': 'resistor', 'footprint': '0402', }, { 'name': 'LED', 'footprint': '0100', }, { 'name': 'speaker', 'footprint': '2000', }, ] [comp for comp in components if comp['footprint'] != '0402'] # [{'footprint': '0100', 'name': 'LED'}, {'footprint': '2000', 'name': 'speaker'}] At a stretch, this is a simple database based on dictionaries - the specific capabilities are really going to depend on your actual implementation. I'm resisting the temptation to suggest use of a real database and query language as I assume this is a learning exercise. It is a learning exercise, right? :) A: I agree with S.Lott that you would be happier with a real DB. SQLite is really light and fast, almost no drawbacks on using it. if you really need to expose a simpler, yet complete, query language to the user, check JSONPath or JSONQuery (the second is a superset of the first). The exact syntax is (obviously) thought for JavaScript; but it should give you some ideas. also, try to check similarities and differences with XPath and XQuery. it helps to see what is useful and what's culture-specific.
Need help on selecting items in simple database in python
I'm trying to write a circuit schematic drawing tool in Python. I'm creating a simple database based on dictionaries which holds all the components and their properties. I'm also trying to create a simple query language where you can select, for example, all resistors with value>100ohms or footprint='0402' So far, I can select things using some primitive predicate search and then union and intersection for more complex things. However, I'm having trouble defining what the semantics ought to be for a purely negative search. For instance, something like footprint != '0402' should select all items with footprint not equal to 0402. But doing this with only intersection gives me a blank result. For this to work I need to select all components, then intersect with "not 0402" to remove the ones I don't want. But this seems kind of brute force and seems like a fishy solution. I'm not interested in using a "real" database and query language, so please don't suggest that. I'm looking for the proper engineering rationale here, not necessarily a workaround to the problem. This problem was covered to some degree in SICP book, but I got very confused, since I think they were also using continuations and stuff, which I don't get yet. Can someone please explain what the 'proper' usage ought to be for negatively selecting stuff. I tried this in a commercial cad tool and it worked as expected, but then I've seen some SQL query examples (I think), which selected things first, then removed the unwanted ones. thanks michael
[ "You'll be a lot happier with a proper database.\nYou have SQLite with your Python distribution. Simply define tables instead of dictionaries and use SQL. \nIf you need more power and sophistication, you can add SQLAlchemy (or SQLObject) and you won't struggle with these problems.\n", "It really depends on how you've implemented this \"simple database based on dictionaries\" as to why straight negation isn't working - you'll have to give us some more clues.\nThere's no reason why a straightforward negation match shouldn't work in Python, e.g.:\ncomponents = [\n { 'name': 'resistor', 'footprint': '0402', },\n { 'name': 'LED', 'footprint': '0100', },\n { 'name': 'speaker', 'footprint': '2000', },\n]\n\n[comp for comp in components if comp['footprint'] != '0402']\n# [{'footprint': '0100', 'name': 'LED'}, {'footprint': '2000', 'name': 'speaker'}]\n\nAt a stretch, this is a simple database based on dictionaries - the specific capabilities are really going to depend on your actual implementation.\nI'm resisting the temptation to suggest use of a real database and query language as I assume this is a learning exercise. It is a learning exercise, right? :)\n", "I agree with S.Lott that you would be happier with a real DB. SQLite is really light and fast, almost no drawbacks on using it.\nif you really need to expose a simpler, yet complete, query language to the user, check JSONPath or JSONQuery (the second is a superset of the first). The exact syntax is (obviously) thought for JavaScript; but it should give you some ideas.\nalso, try to check similarities and differences with XPath and XQuery. it helps to see what is useful and what's culture-specific.\n" ]
[ 5, 3, 1 ]
[]
[]
[ "circuit", "eda", "python", "sql" ]
stackoverflow_0000399957_circuit_eda_python_sql.txt
Q: How do you get Python to write down the code of a function it has in memory? When I pass the options in the program (a computational biology experiment) I usually pass them through a .py file. So I have this .py file that reads like: starting_length=9 starting_cell_size=1000 LengthofExperiments=5000000 Then I execute the file and get the data. Since the program is all on my machine and no one else has access to it, it is secure in a trivial way. I can also write a similar file very easily: def writeoptions(directory): options="" options+="starting_length=%s%s"%(starting_length,os.linesep) options+="starting_cell_size=%s%s"%(starting_cell_size,os.linesep) options+="LengthofExperiments=%s%s"%(LengthofExperiments,os.linesep) ... open("%s%soptions.py"%(directory,os.sep),'w').write(options) I want to pass a function as one of the parameters: starting_length=9 starting_cell_size=1000 LengthofExperiments=5000000 def pippo(a,b): return a+b functionoperator=pippo And of course in the real experiment the function pippo will be much more complex. And different from experiment to experiment. But what I am unable to do is to write the function automatically. In short I don't know how to generalise the writeoptions function to keep on writing the options, if one of the options is a function. I could of course copy the original file, but this is inelegant, inefficient (because it contains a lot of extra options that are not being used), and generally does not solve the question. How do you get python to write down the code of a function, as it writes down the value of a variable? A: vinko@mithril$ more a.py def foo(a): print a vinko@mithril$ more b.py import a import inspect a.foo(89) print inspect.getsource(a.foo) vinko@mithril$ python b.py 89 def foo(a): print a A: You might also consider some other means of data persistence. In my own (astronomy) research, I've been experimenting with two different means of storing scripts for reproducibility. The first is to have them exclusively inside a subversion repository, and then have the job submission script automatically commit them. For instance, if you just wanted to do this in bash: alias run_py='svn ci -m "Commit before running"; python2.5 $*' and inside the script, have the output prefixed by the current subversion revision number for that file, you'd have a record of each script that was run and what the input was. You could pull this back out of subversion as need be. Another, substantially less full-featured, means of tracking the input to a function could be via something like LodgeIt, a pastebin that accepts XML-RPC input and comes with Python bindings. (It can be installed locally, and has support for replying to and updating existing pastes.) But, if you are looking for a relatively small amount of code to be included, Vinko's solution using inspect should work quite well. Doug Hellman covered the inspect module in his Python Module of the Week series. You could create a decorator that examines each option and argument and then prints it out as appropriate (I'll use inspect.getargspec to get the names of the arguments.) import inspect from functools import wraps def option_printer(func): @wraps(func) def run_func(*args, **kwargs): for name, arg in zip(inspect.getargspec(func)[0], args) \ + sorted(kwargs.items()): if isinstance(arg, types.FunctionType): print "Function argument '%s' named '%s':\n" % (name, func.func_name) print inspect.getsource(func) else: print "%s: %s" % (name, arg) return func(*args, **kwargs) return run_func This could probably be made a bit more elegant, but in my tests it works for simple sets of arguments and variables. Additionally, it might have some trouble with lambdas. A: Are you asking about this? def writeoptions(directory): options="" options+="starting_length=%s%s"%(starting_length,os.linesep) options+="starting_cell_size=%s%s"%(starting_cell_size,os.linesep) options+="LengthofExperiments=%s%s"%(LengthofExperiments,os.linesep) options+="def pippo(a,b):%s" % ( os.linesep, ) options+=" '''Some version of pippo'''%s" % ( os.linesep, ) options+=" return 2*a+b%s" % ( os.linesep, ) open("%s%soptions.py"%(directory,os.sep),'w').write(options) Or something else? A: While it is possible to do what you ask (as Vinko has shown), I'd say it is cleaner to share code. Put pippo and his buddies in a submodule that both programs can access. A: Instead of diving into the subject of disassemblers and bytecodes (e.g inspect), why don't you just save the generated Python source in a module (file.py), and later, import it? I would suggest looking into a more standard way of handling what you call options. For example, you can use the JSON module and save or restore your data. Or look into the marshal and pickle modules.
How do you get Python to write down the code of a function it has in memory?
When I pass the options in the program (a computational biology experiment) I usually pass them through a .py file. So I have this .py file that reads like: starting_length=9 starting_cell_size=1000 LengthofExperiments=5000000 Then I execute the file and get the data. Since the program is all on my machine and no one else has access to it, it is secure in a trivial way. I can also write a similar file very easily: def writeoptions(directory): options="" options+="starting_length=%s%s"%(starting_length,os.linesep) options+="starting_cell_size=%s%s"%(starting_cell_size,os.linesep) options+="LengthofExperiments=%s%s"%(LengthofExperiments,os.linesep) ... open("%s%soptions.py"%(directory,os.sep),'w').write(options) I want to pass a function as one of the parameters: starting_length=9 starting_cell_size=1000 LengthofExperiments=5000000 def pippo(a,b): return a+b functionoperator=pippo And of course in the real experiment the function pippo will be much more complex. And different from experiment to experiment. But what I am unable to do is to write the function automatically. In short I don't know how to generalise the writeoptions function to keep on writing the options, if one of the options is a function. I could of course copy the original file, but this is inelegant, inefficient (because it contains a lot of extra options that are not being used), and generally does not solve the question. How do you get python to write down the code of a function, as it writes down the value of a variable?
[ "\nvinko@mithril$ more a.py\n\ndef foo(a):\n print a\n\nvinko@mithril$ more b.py\n\nimport a\nimport inspect\n\na.foo(89)\nprint inspect.getsource(a.foo)\n\nvinko@mithril$ python b.py\n89\ndef foo(a):\n print a\n\n\n", "You might also consider some other means of data persistence. In my own (astronomy) research, I've been experimenting with two different means of storing scripts for reproducibility. The first is to have them exclusively inside a subversion repository, and then have the job submission script automatically commit them. For instance, if you just wanted to do this in bash:\nalias run_py='svn ci -m \"Commit before running\"; python2.5 $*'\n\nand inside the script, have the output prefixed by the current subversion revision number for that file, you'd have a record of each script that was run and what the input was. You could pull this back out of subversion as need be.\nAnother, substantially less full-featured, means of tracking the input to a function could be via something like LodgeIt, a pastebin that accepts XML-RPC input and comes with Python bindings. (It can be installed locally, and has support for replying to and updating existing pastes.)\nBut, if you are looking for a relatively small amount of code to be included, Vinko's solution using inspect should work quite well. Doug Hellman covered the inspect module in his Python Module of the Week series. You could create a decorator that examines each option and argument and then prints it out as appropriate (I'll use inspect.getargspec to get the names of the arguments.)\nimport inspect\nfrom functools import wraps\n\ndef option_printer(func):\n @wraps(func)\n def run_func(*args, **kwargs):\n for name, arg in zip(inspect.getargspec(func)[0], args) \\\n + sorted(kwargs.items()):\n if isinstance(arg, types.FunctionType): \n print \"Function argument '%s' named '%s':\\n\" % (name, func.func_name)\n print inspect.getsource(func)\n else:\n print \"%s: %s\" % (name, arg)\n return func(*args, **kwargs)\n return run_func\n\nThis could probably be made a bit more elegant, but in my tests it works for simple sets of arguments and variables. Additionally, it might have some trouble with lambdas.\n", "Are you asking about this?\ndef writeoptions(directory):\n options=\"\"\n options+=\"starting_length=%s%s\"%(starting_length,os.linesep)\n options+=\"starting_cell_size=%s%s\"%(starting_cell_size,os.linesep)\n options+=\"LengthofExperiments=%s%s\"%(LengthofExperiments,os.linesep)\n options+=\"def pippo(a,b):%s\" % ( os.linesep, )\n options+=\" '''Some version of pippo'''%s\" % ( os.linesep, )\n options+=\" return 2*a+b%s\" % ( os.linesep, )\n open(\"%s%soptions.py\"%(directory,os.sep),'w').write(options)\n\nOr something else?\n", "While it is possible to do what you ask (as Vinko has shown), I'd say it is cleaner to share code. Put pippo and his buddies in a submodule that both programs can access.\n", "Instead of diving into the subject of disassemblers and bytecodes (e.g inspect), why don't you just save the generated Python source in a module (file.py), and later, import it?\nI would suggest looking into a more standard way of handling what you call options. For example, you can use the JSON module and save or restore your data. Or look into the marshal and pickle modules.\n" ]
[ 15, 2, 0, 0, 0 ]
[]
[]
[ "artificial_intelligence", "python" ]
stackoverflow_0000399991_artificial_intelligence_python.txt
Q: Ignoring XML errors in Python I am using XML minidom (xml.dom.minidom) in Python, but any error in the XML will kill the parser. Is it possible to ignore them, like a browser for example? I am trying to write a browser in Python, but it just throws an exception if the tags aren't fully compatible. A: There is a library called BeautifulSoup, I think it's what you're looking for. As you're trying to parse a invalid XML, the normal XML parser won't work. BeautifulSoup is more fail-tolerant, it can still extract information from invalid XML. Beautiful Soup is a Python HTML/XML parser designed for quick turnaround projects like screen-scraping. Three features make it powerful: Beautiful Soup won't choke if you give it bad markup. It yields a parse tree that makes approximately as much sense as your original document. This is usually good enough to collect the data you need and run away. Beautiful Soup provides a few simple methods and Pythonic idioms for navigating, searching, and modifying a parse tree: a toolkit for dissecting a document and extracting what you need. You don't have to create a custom parser for each application. Beautiful Soup automatically converts incoming documents to Unicode and outgoing documents to UTF-8. You don't have to think about encodings, unless the document doesn't specify an encoding and Beautiful Soup can't autodetect one. Then you just have to specify the original encoding. Beautiful Soup parses anything you give it, and does the tree traversal stuff for you. You can tell it "Find all the links", or "Find all the links of class externalLink", or "Find all the links whose urls match "foo.com", or "Find the table heading that's got bold text, then give me that text." A: It should be noted that while HTML looks like XML it is not XML. XHTML is an XML form of HTML. A: See, for example, extracting-text-from-html-file-using-python for suggestions regarding ways for parsing HTML in Python.
Ignoring XML errors in Python
I am using XML minidom (xml.dom.minidom) in Python, but any error in the XML will kill the parser. Is it possible to ignore them, like a browser for example? I am trying to write a browser in Python, but it just throws an exception if the tags aren't fully compatible.
[ "There is a library called BeautifulSoup, I think it's what you're looking for.\nAs you're trying to parse a invalid XML, the normal XML parser won't work. BeautifulSoup is more fail-tolerant, it can still extract information from invalid XML.\n\nBeautiful Soup is a Python HTML/XML\n parser designed for quick turnaround\n projects like screen-scraping. Three\n features make it powerful:\n\nBeautiful Soup won't choke if you give it bad markup. It yields a\n parse tree that makes approximately as\n much sense as your original document.\n This is usually good enough to collect\n the data you need and run away.\nBeautiful Soup provides a few simple methods and Pythonic idioms for\n navigating, searching, and modifying a\n parse tree: a toolkit for dissecting a\n document and extracting what you need.\n You don't have to create a custom\n parser for each application.\nBeautiful Soup automatically converts incoming documents to Unicode\n and outgoing documents to UTF-8. You\n don't have to think about encodings,\n unless the document doesn't specify an\n encoding and Beautiful Soup can't\n autodetect one. Then you just have to\n specify the original encoding. \n\nBeautiful Soup parses anything you\n give it, and does the tree traversal\n stuff for you. You can tell it \"Find\n all the links\", or \"Find all the links\n of class externalLink\", or \"Find all\n the links whose urls match \"foo.com\",\n or \"Find the table heading that's got\n bold text, then give me that text.\"\n\n", "It should be noted that while HTML looks like XML it is not XML. XHTML is an XML form of HTML.\n", "See, for example, extracting-text-from-html-file-using-python for suggestions regarding ways for parsing HTML in Python.\n" ]
[ 12, 3, 0 ]
[]
[]
[ "minidom", "python", "xml" ]
stackoverflow_0000399980_minidom_python_xml.txt
Q: Regex that only matches text that's not part of HTML markup? (python) How can I make a pattern match so long as it's not inside of an HTML tag? Here's my attempt below. Anyone have a better/different approach? import re inputstr = 'mary had a <b class="foo"> little loomb</b>' rx = re.compile('[aob]') repl = 'x' outputstr = '' i = 0 for astr in re.compile(r'(<[^>]*>)').split(inputstr): i = 1 - i if i: astr = re.sub(rx, repl, astr) outputstr += astr print outputstr output: mxry hxd x <b class="foo"> little lxxmx</b> Notes: The <[^>]*> pattern to match HTML tags is obviously flawed -- I wrote this quickly and didn't account for the possibility of angle brackets within quoted attributes (e.g. '<img alt="next >" />'). It doesn't account for <script> or <style> tags or comments, either. A: Since you are using Python anyway, if I were you, I would have a look at Beautiful Soup, which is a Python HTML/XML parser. Really, there are so many special cases and headaches with writing your own parser, it just doesn't worth the effort. Your regular expression will get unmanageably large and will still not yield the correct results in all of the cases. Just use Beautiful Soup.
Regex that only matches text that's not part of HTML markup? (python)
How can I make a pattern match so long as it's not inside of an HTML tag? Here's my attempt below. Anyone have a better/different approach? import re inputstr = 'mary had a <b class="foo"> little loomb</b>' rx = re.compile('[aob]') repl = 'x' outputstr = '' i = 0 for astr in re.compile(r'(<[^>]*>)').split(inputstr): i = 1 - i if i: astr = re.sub(rx, repl, astr) outputstr += astr print outputstr output: mxry hxd x <b class="foo"> little lxxmx</b> Notes: The <[^>]*> pattern to match HTML tags is obviously flawed -- I wrote this quickly and didn't account for the possibility of angle brackets within quoted attributes (e.g. '<img alt="next >" />'). It doesn't account for <script> or <style> tags or comments, either.
[ "Since you are using Python anyway, if I were you, I would have a look at Beautiful Soup, which is a Python HTML/XML parser. Really, there are so many special cases and headaches with writing your own parser, it just doesn't worth the effort. Your regular expression will get unmanageably large and will still not yield the correct results in all of the cases.\nJust use Beautiful Soup.\n" ]
[ 12 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000401726_python_regex.txt
Q: Why can't I subclass datetime.date? Why doesn't the following work (Python 2.5.2)? >>> import datetime >>> class D(datetime.date): def __init__(self, year): datetime.date.__init__(self, year, 1, 1) >>> D(2008) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: function takes exactly 3 arguments (1 given) I wanted to create a class that was just like datetime.date, but with a different __init__ function. Apparently my function never gets called. Instead the original datetime.date.__init__ is called and fails because that expects 3 arguments and I am passing in one. What's going on here? And is this a clue? >>> datetime.date.__init__ <slot wrapper '__init__' of 'object' objects> Thanks! A: Regarding several other answers, this doesn't have anything to do with dates being implemented in C per se. The __init__ method does nothing because they are immutable objects, therefore the constructor (__new__) should do all the work. You would see the same behavior subclassing int, str, etc. >>> import datetime >>> class D(datetime.date): def __new__(cls, year): return datetime.date.__new__(cls, year, 1, 1) >>> D(2008) D(2008, 1, 1) A: Please read the Python reference on Data model, especially about the __new__ special method. Excerpt from that page (my italics): __new__() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation. datetime.datetime is also an immutable type. PS If you think that: an object implemented in C cannot be subclassed, or __init__ doesn't get called for C implemented objects, only __new__ then please try it: >>> import array >>> array <module 'array' (built-in)> >>> class A(array.array): def __init__(self, *args): super(array.array, self).__init__(*args) print "init is fine for objects implemented in C" >>> a=A('c') init is fine for objects implemented in C >>> A: Here's the answer, and a possible solution (use a function or strptime instead of subclassing) http://www.mail-archive.com/python-list@python.org/msg192783.html A: You're function isn't being bypassed; Python just never gets to the point where it would call it. Since datetime is implemented in C, it does its initialization in datetime.__new__ not datetime.__init__. This is because datetime is immutable. You could presumably get around this by overriding __new__ instead of __init__. But as other people have suggested, the best way is probably not subclassing datetime at all. A: You can wrap it and add extended functionality to your wrapper. Here is an example: class D2(object): def __init__(self, *args, **kwargs): self.date_object = datetime.date(*args, **kwargs) def __getattr__(self, name): return getattr(self.date_object, name) And here is how it works: >>> d = D2(2005, 10, 20) >>> d.weekday() 3 >>> dir(d) ['__class__', '__delattr__', '__dict__', '__doc__', '__getattr__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'date_object'] >>> d.strftime('%d.%m.%Y') '20.10.2005' >>> Note that dir() doesn't list datetime.dates attributes. A: You should probably use a factory function instead of creating a subclass: def first_day_of_the_year(year): return datetime.date(year, 1, 1)
Why can't I subclass datetime.date?
Why doesn't the following work (Python 2.5.2)? >>> import datetime >>> class D(datetime.date): def __init__(self, year): datetime.date.__init__(self, year, 1, 1) >>> D(2008) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: function takes exactly 3 arguments (1 given) I wanted to create a class that was just like datetime.date, but with a different __init__ function. Apparently my function never gets called. Instead the original datetime.date.__init__ is called and fails because that expects 3 arguments and I am passing in one. What's going on here? And is this a clue? >>> datetime.date.__init__ <slot wrapper '__init__' of 'object' objects> Thanks!
[ "Regarding several other answers, this doesn't have anything to do with dates being implemented in C per se. The __init__ method does nothing because they are immutable objects, therefore the constructor (__new__) should do all the work. You would see the same behavior subclassing int, str, etc.\n>>> import datetime\n>>> class D(datetime.date):\n def __new__(cls, year):\n return datetime.date.__new__(cls, year, 1, 1)\n\n\n>>> D(2008)\nD(2008, 1, 1)\n\n", "Please read the Python reference on Data model, especially about the __new__ special method.\nExcerpt from that page (my italics):\n\n__new__() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation.\n\ndatetime.datetime is also an immutable type.\nPS If you think that:\n\nan object implemented in C cannot be subclassed, or\n__init__ doesn't get called for C implemented objects, only __new__\n\nthen please try it:\n>>> import array\n>>> array\n<module 'array' (built-in)>\n>>> class A(array.array):\n def __init__(self, *args):\n super(array.array, self).__init__(*args)\n print \"init is fine for objects implemented in C\"\n\n>>> a=A('c')\ninit is fine for objects implemented in C\n>>> \n\n", "Here's the answer, and a possible solution (use a function or strptime instead of subclassing)\nhttp://www.mail-archive.com/python-list@python.org/msg192783.html\n", "You're function isn't being bypassed; Python just never gets to the point where it would call it. Since datetime is implemented in C, it does its initialization in datetime.__new__ not datetime.__init__. This is because datetime is immutable. You could presumably get around this by overriding __new__ instead of __init__. But as other people have suggested, the best way is probably not subclassing datetime at all.\n", "You can wrap it and add extended functionality to your wrapper.\nHere is an example:\nclass D2(object):\n def __init__(self, *args, **kwargs):\n self.date_object = datetime.date(*args, **kwargs)\n\n def __getattr__(self, name):\n return getattr(self.date_object, name)\n\nAnd here is how it works:\n>>> d = D2(2005, 10, 20)\n>>> d.weekday()\n3\n>>> dir(d)\n['__class__', '__delattr__', '__dict__', '__doc__', '__getattr__',\n '__getattribute__', '__hash__', '__init__', '__module__', '__new__',\n '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__',\n '__weakref__', 'date_object']\n>>> d.strftime('%d.%m.%Y')\n'20.10.2005'\n>>>\n\nNote that dir() doesn't list datetime.dates attributes.\n", "You should probably use a factory function instead of creating a subclass:\ndef first_day_of_the_year(year):\n return datetime.date(year, 1, 1)\n\n" ]
[ 40, 12, 4, 2, 1, 0 ]
[]
[]
[ "datetime", "oop", "python", "subclass" ]
stackoverflow_0000399022_datetime_oop_python_subclass.txt
Q: Help--Function Pointers in Python My idea of program: I have a dictionary: options = { 'string' : select_fun(function pointer), 'float' : select_fun(function pointer), 'double' : select_fun(function pointer) } whatever type comes single function select_fun(function pointer) gets called. Inside select_fun(function pointer),I will have diff functions for float, double and so on. Depending on function pointers, specified function will get called. I don't know whether my programming knowledge is good or bad, still I need help. A: Could you be more specific on what you're trying to do? You don't have to do anything special to get function pointers in Python -- you can pass around functions like regular objects: def plus_1(x): return x + 1 def minus_1(x): return x - 1 func_map = {'+' : plus_1, '-' : minus_1} func_map['+'](3) # returns plus_1(3) ==> 4 func_map['-'](3) # returns minus_1(3) ==> 2 A: You can use the type() built-in function to detect the type of the function. Say, if you want to check if a certain name hold a string data, you could do this: if type(this_is_string) == type('some random string'): # this_is_string is indeed a string So in your case, you could do it like this: options = { 'some string' : string_function, (float)(123.456) : float_function, (int)(123) : int_function } def call_option(arg): # loop through the dictionary for (k, v) in options.iteritems(): # if found matching type... if type(k) == type(arg): # call the matching function func = option[k] func(arg) Then you can use it like this: call_option('123') # string_function gets called call_option(123.456) # float_function gets called call_option(123) # int_function gets called I don't have a python interpreter nearby and I don't program in Python much so there may be some errors, but you should get the idea. EDIT: As per @Adam's suggestion, there are built-in type constants that you can check against directly, so a better approach would be: from types import * options = { types.StringType : string_function, types.FloatType : float_function, types.IntType : int_function, types.LongType : long_function } def call_option(arg): for (k, v) in options.iteritems(): # check if arg is of type k if type(arg) == k: # call the matching function func = options[k] func(arg) And since the key itself is comparable to the value of the type() function, you can just do this: def call_option(arg): func = options[type(arg)] func(arg) Which is more elegant :-) save for some error-checking. EDIT: And for ctypes support, after some fiddling around, I've found that ctypes.[type_name_here] is actually implented as classes. So this method still works, you just need to use the ctypes.c_xxx type classes. options = { ctypes.c_long : c_long_processor, ctypes.c_ulong : c_unsigned_long_processor, types.StringType : python_string_procssor } call_option = lambda x: options[type(x)](x) A: Functions are the first-class objects in Python therefore you can pass them as arguments to other functions as you would with any other object such as string or an integer. There is no single-precision floating point type in Python. Python's float corresponds to C's double. def process(anobject): if isinstance(anobject, basestring): # anobject is a string fun = process_string elif isinstance(anobject, (float, int, long, complex)): # anobject is a number fun = process_number else: raise TypeError("expected string or number but received: '%s'" % ( type(anobject),)) return fun(anobject) There is functools.singledispatch that allows to create a generic function: from functools import singledispatch from numbers import Number @singledispatch def process(anobject): # default implementation raise TypeError("'%s' type is not supported" % type(anobject)) @process.register(str) def _(anobject): # handle strings here return process_string(anobject) process.register(Number)(process_number) # use existing function for numbers On Python 2, similar functionality is available as pkgutil.simplegeneric(). Here's a couple of code example of using generic functions: Remove whitespaces and newlines from JSON file Make my_average(a, b) work with any a and b for which f_add and d_div are defined. As well as builtins A: Looking at your example, it seems to me some C procedure, directly translated to Python. For this reason, I think there could be some design issue, because usually, in Python, you do not care about type of an object, but only about the messages you can send to it. Of course, there are plenty of exceptions to this approach, but still in this case I would try encapsulating in some polymorphism; eg. class StringSomething(object): data = None def data_function(self): string_function_pointer(self.data) class FloatSomething(object): data = None def data_function(self): float_function_pointer(self.data) etc. Again, all of this under the assumption you are translating from a procedural language to python; if it is not the case, then discard my answer :-) A: Maybe you want to call the same select_fun() every time, with a different argument. If that is what you mean, you need a different dictionary: >>> options = {'string' : str, 'float' : float, 'double' : float } >>> options {'double': <type 'float'>, 'float': <type 'float'>, 'string': <type 'str'>} >>> def call_option(val, func): ... return func(val) ... >>> call_option('555',options['float']) 555.0 >>>
Help--Function Pointers in Python
My idea of program: I have a dictionary: options = { 'string' : select_fun(function pointer), 'float' : select_fun(function pointer), 'double' : select_fun(function pointer) } whatever type comes single function select_fun(function pointer) gets called. Inside select_fun(function pointer),I will have diff functions for float, double and so on. Depending on function pointers, specified function will get called. I don't know whether my programming knowledge is good or bad, still I need help.
[ "Could you be more specific on what you're trying to do? You don't have to do anything special to get function pointers in Python -- you can pass around functions like regular objects:\ndef plus_1(x):\n return x + 1\n\ndef minus_1(x):\n return x - 1\n\nfunc_map = {'+' : plus_1, '-' : minus_1}\n\nfunc_map['+'](3) # returns plus_1(3) ==> 4\nfunc_map['-'](3) # returns minus_1(3) ==> 2\n\n", "You can use the type() built-in function to detect the type of the function.\nSay, if you want to check if a certain name hold a string data, you could do this:\nif type(this_is_string) == type('some random string'):\n # this_is_string is indeed a string\n\nSo in your case, you could do it like this:\noptions = { 'some string' : string_function,\n (float)(123.456) : float_function,\n (int)(123) : int_function\n }\n\ndef call_option(arg):\n\n # loop through the dictionary\n for (k, v) in options.iteritems():\n\n # if found matching type...\n if type(k) == type(arg):\n\n # call the matching function\n func = option[k]\n func(arg)\n\nThen you can use it like this:\ncall_option('123') # string_function gets called\ncall_option(123.456) # float_function gets called\ncall_option(123) # int_function gets called\n\nI don't have a python interpreter nearby and I don't program in Python much so there may be some errors, but you should get the idea.\n\nEDIT: As per @Adam's suggestion, there are built-in type constants that you can check against directly, so a better approach would be:\nfrom types import *\n\noptions = { types.StringType : string_function,\n types.FloatType : float_function,\n types.IntType : int_function,\n types.LongType : long_function\n }\n\ndef call_option(arg):\n for (k, v) in options.iteritems():\n\n # check if arg is of type k\n if type(arg) == k:\n\n # call the matching function\n func = options[k]\n func(arg)\n\nAnd since the key itself is comparable to the value of the type() function, you can just do this:\ndef call_option(arg):\n func = options[type(arg)]\n func(arg)\n\nWhich is more elegant :-) save for some error-checking.\n\nEDIT: And for ctypes support, after some fiddling around, I've found that ctypes.[type_name_here] is actually implented as classes. So this method still works, you just need to use the ctypes.c_xxx type classes.\noptions = { ctypes.c_long : c_long_processor,\n ctypes.c_ulong : c_unsigned_long_processor,\n types.StringType : python_string_procssor\n }\n\ncall_option = lambda x: options[type(x)](x)\n\n", "Functions are the first-class objects in Python therefore you can pass them as arguments to other functions as you would with any other object such as string or an integer.\nThere is no single-precision floating point type in Python. Python's float corresponds to C's double.\ndef process(anobject):\n if isinstance(anobject, basestring):\n # anobject is a string\n fun = process_string\n elif isinstance(anobject, (float, int, long, complex)):\n # anobject is a number\n fun = process_number\n else:\n raise TypeError(\"expected string or number but received: '%s'\" % (\n type(anobject),))\n return fun(anobject)\n\nThere is functools.singledispatch that allows to create a generic function:\nfrom functools import singledispatch\nfrom numbers import Number\n\n@singledispatch\ndef process(anobject): # default implementation\n raise TypeError(\"'%s' type is not supported\" % type(anobject))\n\n@process.register(str)\ndef _(anobject):\n # handle strings here\n return process_string(anobject)\n\nprocess.register(Number)(process_number) # use existing function for numbers\n\nOn Python 2, similar functionality is available as pkgutil.simplegeneric().\nHere's a couple of code example of using generic functions:\n\nRemove whitespaces and newlines from JSON file\nMake my_average(a, b) work with any a and b for which f_add and d_div are defined. As well as builtins\n\n", "Looking at your example, it seems to me some C procedure, directly translated to Python.\nFor this reason, I think there could be some design issue, because usually, in Python, you do not care about type of an object, but only about the messages you can send to it.\nOf course, there are plenty of exceptions to this approach, but still in this case I would try encapsulating in some polymorphism; eg.\nclass StringSomething(object):\n data = None\n def data_function(self):\n string_function_pointer(self.data)\n\nclass FloatSomething(object):\n data = None\n def data_function(self):\n float_function_pointer(self.data)\n\netc.\nAgain, all of this under the assumption you are translating from a procedural language to python; if it is not the case, then discard my answer :-)\n", "Maybe you want to call the same select_fun() every time, with a different argument. If that is what you mean, you need a different dictionary:\n>>> options = {'string' : str, 'float' : float, 'double' : float }\n>>> options\n{'double': <type 'float'>, 'float': <type 'float'>, 'string': <type 'str'>}\n>>> def call_option(val, func):\n... return func(val)\n... \n>>> call_option('555',options['float'])\n555.0\n>>> \n\n" ]
[ 20, 6, 4, 4, 3 ]
[]
[]
[ "function", "pointers", "python" ]
stackoverflow_0000402364_function_pointers_python.txt
Q: Best way to organize the folders containing the SQLAlchemy models I use SQLAlchemy at work and it does the job really fine. Now I am thinking about best practices. For now, I create a module holding all the SQLA stuff : my_model |__ __init__.py |__ _config.py <<<<< contains LOGIN, HOST, and a MetaData instance |__ table1.py <<<<< contains the class, the model and the mapper for table1 |__ table2.py <<<<< contains the class, the model and the mapper for table2 [...] Now, I really don't know if it's the best way to do it. I would like to load the classes with a fine granularity and be sure to create one connection only with the db, etc. Here, all the classes are separated, but all import _config and I am wondering if it's a good thing. What's more, I would like to be able to create subclasses of the model classes that could be stored independently without messing up with the mapper every time. How can I do that ? For now I just put them in the same file and I have to create another mapper, but the first mapper is still called every time. The same would go if I'd have to import the parent class because the mapper is triggered at import. If I don't use the class to access data, isn't it overheat to map it each time ? I'd like to avoid using Elixir too, please. A: Personally I like to keep the database / ORM logic out of the model classes. It makes them easier to test. I typically have something like a types.py which defines the types used in my application, but independent of the database. Then typically there is a db.py or something similar which has the Session class and the rest of the code required to set up the database, including all the mappers etc. None of the other modules except those which perform database operations need to import the db module and the existence of the database is totally hidden from most of the application classes. As far as I know, you can't easily make subclasses without changing the mapper. SQLAlchemy will have no way to know which subclass to retrieve from the database when you perform a query and you need to be able to indicate the subclass when you are storing the data anyway. I haven't really seen any problems arise from calling all the mappers at once from the main db module, so I don't think initializing them all the time is really a concern unless you actually identify it as a bottleneck. In my experience, other processing is a far larger factor than the minor mapper overhead.
Best way to organize the folders containing the SQLAlchemy models
I use SQLAlchemy at work and it does the job really fine. Now I am thinking about best practices. For now, I create a module holding all the SQLA stuff : my_model |__ __init__.py |__ _config.py <<<<< contains LOGIN, HOST, and a MetaData instance |__ table1.py <<<<< contains the class, the model and the mapper for table1 |__ table2.py <<<<< contains the class, the model and the mapper for table2 [...] Now, I really don't know if it's the best way to do it. I would like to load the classes with a fine granularity and be sure to create one connection only with the db, etc. Here, all the classes are separated, but all import _config and I am wondering if it's a good thing. What's more, I would like to be able to create subclasses of the model classes that could be stored independently without messing up with the mapper every time. How can I do that ? For now I just put them in the same file and I have to create another mapper, but the first mapper is still called every time. The same would go if I'd have to import the parent class because the mapper is triggered at import. If I don't use the class to access data, isn't it overheat to map it each time ? I'd like to avoid using Elixir too, please.
[ "Personally I like to keep the database / ORM logic out of the model classes. It makes them easier to test. I typically have something like a types.py which defines the types used in my application, but independent of the database.\nThen typically there is a db.py or something similar which has the Session class and the rest of the code required to set up the database, including all the mappers etc.\nNone of the other modules except those which perform database operations need to import the db module and the existence of the database is totally hidden from most of the application classes.\nAs far as I know, you can't easily make subclasses without changing the mapper. SQLAlchemy will have no way to know which subclass to retrieve from the database when you perform a query and you need to be able to indicate the subclass when you are storing the data anyway.\nI haven't really seen any problems arise from calling all the mappers at once from the main db module, so I don't think initializing them all the time is really a concern unless you actually identify it as a bottleneck. In my experience, other processing is a far larger factor than the minor mapper overhead.\n" ]
[ 3 ]
[]
[]
[ "orm", "python", "sqlalchemy" ]
stackoverflow_0000362998_orm_python_sqlalchemy.txt
Q: Making the value of a table equal to another value in a different table I have a small problem with a program that im writing. I have a table - stocks which contains information(products, barcodes etc.) about items stored in a fridge. I then have another table - shop which acts like a shop,containing loads of products and their barcodes.some of the products in the shop table are in the stock table at the moment, and there is a boolenan field called stock which tells us if that product is in the stock table or not, if its equal to 1, it is in the fridge, if it is equal to 0, it is not in the fridge. Two fields in the stocks table are amount and quantity. The amount is what is in the fridge at the moment, the quantity is what has to be in the fridge at all times. When something is taken out of the fridge, that product's amount amount drops by 1. Each barcode in the stocks table has a matching one in the shop table. I need to make a query to the database from a python program which will order products from the shops table when the amount (whats in the fridge) is less than the quantity (whats meant to be in the fridge at all times). So you need to take the barcode of a row in the stocks table where the amount is less than the quantity and match that up to the barcode in the shops table. Then in the row of that matching barcode you need to set stock = 1. I would be really happy if somebody could help me with this as I really am finding it difficult to write this function. Below is the checkin and checkout functions if that will help. checkin def check_in(): db = MySQLdb.connect(host='localhost', user='root', passwd='$$', db='fillmyfridge') cursor=db.cursor(MySQLdb.cursors.DictCursor) user_input=raw_input('please enter the product barcode that you wish to checkin to the fridge: \n') cursor.execute("""update shop set stock = 1 where barcode = %s""", (user_input)) db.commit() numrows = int(cursor.rowcount) if numrows >= 1: row = cursor.fetchone() print row["product"] cursor.execute('update stock set amount = amount + 1 where product = %s', row["product"]) db.commit() cursor.execute('udpate shop set stock = 1 where barcode = user_input') db.commit() else: new_prodname = raw_input('what is the name of the product and press enter: \n') cursor.execute('insert into shop (product, barcode, category) values (%s, %s, %s)', (new_prodname, user_input, new_prodname)) cursor = db.cursor() query = ('select * from shop where product = %s', (new_prodname)) cursor.execute(query): db.commit() numrows = int(cursor.rowcount) if numrows<1: cursor.execute('insert into atock (barcode, quantity, amount, product) values (%s, 1, 1, %s)', (user_input, new_prodname)) db.commit() cursor.execute('insert into shop (product, barcode, category, stock) values (%s, %s, %s, 1)', (new_prodname, user_input, new_prodname)) print new_prodname print 'has been added to the fridge stock' else: cursor.execute('update atock set amount = amount + 1 where product = %s', (new_prodname)) db.commit() cursor.execute('insert into shop (product, barcode, category, stock) values (%s, %s, %s, 1)', (new_prodname, user_input, new_prodname)) print new_prodname print 'has been added to the fridge stock' checkout import MySQLdb def check_out(): db = MySQLdb.connect(host='localhost', user='root', passwd='$$', db='fillmyfridge') cursor=db.cursor() user_input=raw_input('please enter the product barcode you wish to remove from the fridge: \n') query = cursor.execute('update stock set instock=0, howmanytoorder=howmanytoorder + 1, amount = amount - 1 where barcode = %s', (user_input)) if cursor.execute(query): db.commit() print 'the following product has been removed from the fridge nd needs to be ordered' cursor.execute('update shop set stock = 0 where barcode = %s' (user_input) db.commit() else: return 0 A: So, if I got that right you have the following tables: Stock with at least a barcode, amount and quantity column Shop with at least a barcode and a stock column I don't understand why you need that stock column in the shop table, because you could easily get the products which are in stock by using a join like this: SELECT barcode, ... FROM Stock ST JOIN Shop SH ON ST.barcode = SH.barcode; Obviously you should also select some other columns from the Shop table or otherwise you could just select everything from the Stock table. You can get a list of products which need to be ordered (where the amount is less than the quantity): SELECT barcode FROM Stock ST WHERE ST.amount < ST.quantity; A: Try to make the question shorter. That will generate more responses, I guess.
Making the value of a table equal to another value in a different table
I have a small problem with a program that im writing. I have a table - stocks which contains information(products, barcodes etc.) about items stored in a fridge. I then have another table - shop which acts like a shop,containing loads of products and their barcodes.some of the products in the shop table are in the stock table at the moment, and there is a boolenan field called stock which tells us if that product is in the stock table or not, if its equal to 1, it is in the fridge, if it is equal to 0, it is not in the fridge. Two fields in the stocks table are amount and quantity. The amount is what is in the fridge at the moment, the quantity is what has to be in the fridge at all times. When something is taken out of the fridge, that product's amount amount drops by 1. Each barcode in the stocks table has a matching one in the shop table. I need to make a query to the database from a python program which will order products from the shops table when the amount (whats in the fridge) is less than the quantity (whats meant to be in the fridge at all times). So you need to take the barcode of a row in the stocks table where the amount is less than the quantity and match that up to the barcode in the shops table. Then in the row of that matching barcode you need to set stock = 1. I would be really happy if somebody could help me with this as I really am finding it difficult to write this function. Below is the checkin and checkout functions if that will help. checkin def check_in(): db = MySQLdb.connect(host='localhost', user='root', passwd='$$', db='fillmyfridge') cursor=db.cursor(MySQLdb.cursors.DictCursor) user_input=raw_input('please enter the product barcode that you wish to checkin to the fridge: \n') cursor.execute("""update shop set stock = 1 where barcode = %s""", (user_input)) db.commit() numrows = int(cursor.rowcount) if numrows >= 1: row = cursor.fetchone() print row["product"] cursor.execute('update stock set amount = amount + 1 where product = %s', row["product"]) db.commit() cursor.execute('udpate shop set stock = 1 where barcode = user_input') db.commit() else: new_prodname = raw_input('what is the name of the product and press enter: \n') cursor.execute('insert into shop (product, barcode, category) values (%s, %s, %s)', (new_prodname, user_input, new_prodname)) cursor = db.cursor() query = ('select * from shop where product = %s', (new_prodname)) cursor.execute(query): db.commit() numrows = int(cursor.rowcount) if numrows<1: cursor.execute('insert into atock (barcode, quantity, amount, product) values (%s, 1, 1, %s)', (user_input, new_prodname)) db.commit() cursor.execute('insert into shop (product, barcode, category, stock) values (%s, %s, %s, 1)', (new_prodname, user_input, new_prodname)) print new_prodname print 'has been added to the fridge stock' else: cursor.execute('update atock set amount = amount + 1 where product = %s', (new_prodname)) db.commit() cursor.execute('insert into shop (product, barcode, category, stock) values (%s, %s, %s, 1)', (new_prodname, user_input, new_prodname)) print new_prodname print 'has been added to the fridge stock' checkout import MySQLdb def check_out(): db = MySQLdb.connect(host='localhost', user='root', passwd='$$', db='fillmyfridge') cursor=db.cursor() user_input=raw_input('please enter the product barcode you wish to remove from the fridge: \n') query = cursor.execute('update stock set instock=0, howmanytoorder=howmanytoorder + 1, amount = amount - 1 where barcode = %s', (user_input)) if cursor.execute(query): db.commit() print 'the following product has been removed from the fridge nd needs to be ordered' cursor.execute('update shop set stock = 0 where barcode = %s' (user_input) db.commit() else: return 0
[ "So, if I got that right you have the following tables:\nStock with at least a barcode, amount and quantity column\nShop with at least a barcode and a stock column\nI don't understand why you need that stock column in the shop table, because you could easily get the products which are in stock by using a join like this:\nSELECT barcode, ... FROM Stock ST JOIN Shop SH ON ST.barcode = SH.barcode;\n\nObviously you should also select some other columns from the Shop table or otherwise you could just select everything from the Stock table.\nYou can get a list of products which need to be ordered (where the amount is less than the quantity):\nSELECT barcode FROM Stock ST WHERE ST.amount < ST.quantity;\n\n", "Try to make the question shorter. That will generate more responses, I guess.\n" ]
[ 1, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0000403433_mysql_python.txt
Q: Calling from a parent file in python I have a file called main.py and a file called classes.py main.py contains the application and what's happening while class.py contains some classes. main.py has the following code main.py import classes def addItem(text): print text myClass = classes.ExampleClass() And then we have classes.py classes.py class ExampleClass (object): def __init__(self): addItem('bob') Surprisingly enough that's not the actual code I am using because I've stripped out anything that'd get in the way of you seeing what I want to do. I want to be able to call a method that's defined in main.py from a class within classes.py. How do I do this? Thanks in advance A: I couldn't answer this any better than this post by Alex Martelli. Basically any way you try to do this will lead to trouble and you are much better off refactoring the code to avoid mutual dependencies between two modules... If you have two modules A and B which depend on each other, the easiest way is to isolate a part of the code that they both depend on into a third module C, and have both of them import C. A: The suggestions to refactor are good ones. If you have to leave the files as they are, then you can edit main.py to make sure that nothing is executed simply by importing the file, then import main in the function that needs it: class ExampleClass (object): def __init__(self): import main main.addItem('bob') This avoids the circular imports, but isn't as nice as refactoring in the first place... A: I would suggest putting common functions either in classes.py, or probably even better in a third module, perhaps utils.py. A: All your executable code should be inside a if __name__ == "__main__" . This will prevent it from being execucted when imported as a module. In main.py if __name__=="__main__": myClass = classes.ExampleClass() However, as dF states, it is probably better to refactor at this stage than to try to resolve cyclic dependencies.
Calling from a parent file in python
I have a file called main.py and a file called classes.py main.py contains the application and what's happening while class.py contains some classes. main.py has the following code main.py import classes def addItem(text): print text myClass = classes.ExampleClass() And then we have classes.py classes.py class ExampleClass (object): def __init__(self): addItem('bob') Surprisingly enough that's not the actual code I am using because I've stripped out anything that'd get in the way of you seeing what I want to do. I want to be able to call a method that's defined in main.py from a class within classes.py. How do I do this? Thanks in advance
[ "I couldn't answer this any better than this post by Alex Martelli. Basically any way you try to do this will lead to trouble and you are much better off refactoring the code to avoid mutual dependencies between two modules... \nIf you have two modules A and B which depend on each other, the easiest way is to isolate a part of the code that they both depend on into a third module C, and have both of them import C.\n", "The suggestions to refactor are good ones. If you have to leave the files as they are, then you can edit main.py to make sure that nothing is executed simply by importing the file, then import main in the function that needs it:\nclass ExampleClass (object):\n def __init__(self):\n import main\n main.addItem('bob')\n\nThis avoids the circular imports, but isn't as nice as refactoring in the first place...\n", "I would suggest putting common functions either in classes.py, or probably even better in a third module, perhaps utils.py.\n", "All your executable code should be inside a if __name__ == \"__main__\" . This will prevent it from being execucted when imported as a module. In main.py\nif __name__==\"__main__\":\n myClass = classes.ExampleClass()\n\nHowever, as dF states, it is probably better to refactor at this stage than to try to resolve cyclic dependencies.\n" ]
[ 9, 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000403822_python.txt
Q: Making a SQL Query in two tables I'm wondering, is it possible to make an sql query that does the same function as 'select products where barcode in table1 = barcode in table2'. I am writing this function in a python program. Once that function is called will the table be joined permanently or just while that function is running? thanks. A: SELECT t1.products FROM [Table1] t1 INNER JOIN [Table2] t2 ON t2.barcode = t1.barcode A: I think you want to join two tables: http://www.w3schools.com/Sql/sql_join.asp A: Something like: SELECT * FROM table1 WHERE barcode IN (SELECT barcode FROM table2) Is that what you're looking for? A: SELECT table1.*, table2.* FROM table1 left join table2 on table1.barcode = table2.barcode A: Here is an example of inner joining two tables based on a common field in both tables. SELECT table1.Products FROM table1 INNER JOIN table2 on table1.barcode = table2.barcode WHERE table1.Products is not null A: Here's a way to talk yourself through table design in these cases, based on Object Role Modeling. (Yes, I realize this is only indirectly related to the question.) You have products and barcodes. Products are uniquely identified by Product Code (e.g. 'A2111'; barcodes are uniquely identified by Value (e.g. 1002155061). A Product has a Barcode. Questions: Can a product have no barcode? Can the same product have multiple barcodes? Can multiple products have the same barcode? (If you have any experience with UPC labels, you know the answer to all these is TRUE.) So you can make some assertions: A Product (code) has zero or more Barcode (value). A Barcode (value) has one or more Product (code). -- assumption: we barcodes don't have independent existence if they aren't/haven't been/won't be related to products). Which leads directly (via your ORM model) to a schema with two tables: Product ProductCode(PK) Description etc ProductBarcode ProductCode(FK) BarcodeValue -- with a two-part natural primary key, ProductCode + BarcodeValue and you tie them together as described in the other answers. Similar assertions can be used to determine which fields go into various tables in your design.
Making a SQL Query in two tables
I'm wondering, is it possible to make an sql query that does the same function as 'select products where barcode in table1 = barcode in table2'. I am writing this function in a python program. Once that function is called will the table be joined permanently or just while that function is running? thanks.
[ "SELECT t1.products\nFROM [Table1] t1\nINNER JOIN [Table2] t2 ON t2.barcode = t1.barcode\n\n", "I think you want to join two tables:\nhttp://www.w3schools.com/Sql/sql_join.asp\n", "Something like:\nSELECT * FROM table1 WHERE barcode IN (SELECT barcode FROM table2)\n\nIs that what you're looking for?\n", "SELECT table1.*, table2.* FROM table1 left join table2 on table1.barcode = table2.barcode\n\n", "Here is an example of inner joining two tables based on a common field in both tables.\nSELECT table1.Products\nFROM table1 \nINNER JOIN table2 on table1.barcode = table2.barcode\nWHERE table1.Products is not null\n", "Here's a way to talk yourself through table design in these cases, based on Object Role Modeling. (Yes, I realize this is only indirectly related to the question.)\nYou have products and barcodes. Products are uniquely identified by Product Code (e.g. 'A2111'; barcodes are uniquely identified by Value (e.g. 1002155061).\nA Product has a Barcode. Questions: Can a product have no barcode? Can the same product have multiple barcodes? Can multiple products have the same barcode? (If you have any experience with UPC labels, you know the answer to all these is TRUE.)\nSo you can make some assertions: \nA Product (code) has zero or more Barcode (value).\nA Barcode (value) has one or more Product (code). -- assumption: we barcodes don't have independent existence if they aren't/haven't been/won't be related to products).\nWhich leads directly (via your ORM model) to a schema with two tables: \nProduct\nProductCode(PK) Description etc\nProductBarcode\nProductCode(FK) BarcodeValue\n-- with a two-part natural primary key, ProductCode + BarcodeValue \nand you tie them together as described in the other answers.\nSimilar assertions can be used to determine which fields go into various tables in your design.\n" ]
[ 10, 7, 1, 0, 0, 0 ]
[]
[]
[ "python", "sql" ]
stackoverflow_0000403527_python_sql.txt
Q: using results from a sql query in a python program in another sql query sorry for my previous question which was very ambiguous, but i think if i get the answer to this question I can work it out. In the program below i have selected the barcodes of products where the amount is less than the quantity. I want to say, that if the barcodes(in the fridge table) match barcodes in another table(products), set the stock field equal to 0. The problem Im getting is that the program is trying to match all the barcodes that it found in the query against single barcodes in the products table(thats what I think). does anyone know what to do. thanks a million. lincoln. import MySQLdb def order(): db = MySQLdb.connect(host='localhost', user='root', passwd='$$', db='fillmyfridge') cursor = db.cursor() cursor.execute('select barcode from fridge where amount < quantity') db.commit() row = cursor.fetchall() cursor.execute('update products set stock = 0 where barcode = %s', row) A: UPDATE products SET stock = 0 WHERE barcode IN ( SELECT fridge.barcode FROM fridge WHERE fridge.amount < fridge.quantity ); I know this doesn't answer the question exactly but two SQL statements are not required. To do it in python: import MySQLdb def order(): db = MySQLdb.connect(host='localhost', user='root', passwd='$$', db='fillmyfridge') cursor = db.cursor() cursor.execute('select barcode from fridge where amount < quantity') db.commit() rows = cursor.fetchall() for row in rows cursor.execute('update products set stock = 0 where barcode = %s', row[0]) A: This is more of SQL query than Python, but still I will try to answer that: (I haven't worked with MySQL but PostgreSQL, so there might slight variation in interpretation of things here). when you did cursor.execute('select barcode from fridge where amount < quantity') db.commit() row = cursor.fetchall() the variable 'row' now is a resultset (to understand: a list of rows from the database) something like [(barcode1), (barcode2), (barcode3)..] when you do the update statement cursor.execute('update products set stock = 0 where barcode = %s', row) this turns into something like: update products set stock = 0 where barcode = [(barcode1), (barcode2), (barcode3)..] which is not a correct SQL statement. you should do something like this: cursor.execute('update products set stock = 0 where barcode in (%s)', ','.join([each[0] for each in row])) or better, the optimized thing: import MySQLdb def order(): db = MySQLdb.connect(host='localhost', user='root', passwd='$$', db='fillmyfridge') cursor = db.cursor() cursor.execute('update products set stock = 0 where barcode in (select barcode from fridge where amount < quantity)') db.commit() Well, to add more you have a db.commit() after a select query and not after an update query, thats a basic fault. Select is idempotent, doesn't need commit, whereas Update does. I will strongly recommend you to go through some SQL before continuing.
using results from a sql query in a python program in another sql query
sorry for my previous question which was very ambiguous, but i think if i get the answer to this question I can work it out. In the program below i have selected the barcodes of products where the amount is less than the quantity. I want to say, that if the barcodes(in the fridge table) match barcodes in another table(products), set the stock field equal to 0. The problem Im getting is that the program is trying to match all the barcodes that it found in the query against single barcodes in the products table(thats what I think). does anyone know what to do. thanks a million. lincoln. import MySQLdb def order(): db = MySQLdb.connect(host='localhost', user='root', passwd='$$', db='fillmyfridge') cursor = db.cursor() cursor.execute('select barcode from fridge where amount < quantity') db.commit() row = cursor.fetchall() cursor.execute('update products set stock = 0 where barcode = %s', row)
[ "UPDATE products SET stock = 0 WHERE barcode IN ( \n SELECT fridge.barcode FROM fridge WHERE fridge.amount < fridge.quantity );\n\nI know this doesn't answer the question exactly but two SQL statements are not required.\nTo do it in python:\nimport MySQLdb\n\ndef order():\n db = MySQLdb.connect(host='localhost', user='root', passwd='$$', db='fillmyfridge')\n cursor = db.cursor()\n cursor.execute('select barcode from fridge where amount < quantity')\n db.commit()\n rows = cursor.fetchall()\n for row in rows\n cursor.execute('update products set stock = 0 where barcode = %s', row[0])\n\n", "This is more of SQL query than Python, but still I will try to answer that:\n(I haven't worked with MySQL but PostgreSQL, so there might slight variation in interpretation of things here).\nwhen you did\ncursor.execute('select barcode from fridge where amount < quantity')\ndb.commit()\nrow = cursor.fetchall()\n\nthe variable 'row' now is a resultset (to understand: a list of rows from the database)\nsomething like [(barcode1), (barcode2), (barcode3)..]\nwhen you do the update statement\ncursor.execute('update products set stock = 0 where barcode = %s', row)\n\nthis turns into something like:\nupdate products set stock = 0 where barcode = [(barcode1), (barcode2), (barcode3)..]\n\nwhich is not a correct SQL statement.\nyou should do something like this:\ncursor.execute('update products set stock = 0 where barcode in (%s)', ','.join([each[0] for each in row]))\n\nor better, the optimized thing:\nimport MySQLdb\n\ndef order():\n db = MySQLdb.connect(host='localhost', user='root', passwd='$$', db='fillmyfridge')\n cursor = db.cursor()\n cursor.execute('update products set stock = 0 where barcode in (select barcode from fridge where amount < quantity)')\n db.commit()\n\nWell, to add more you have a db.commit() after a select query and not after an update query, thats a basic fault. Select is idempotent, doesn't need commit, whereas Update does. I will strongly recommend you to go through some SQL before continuing.\n" ]
[ 5, 4 ]
[]
[]
[ "python", "sql" ]
stackoverflow_0000403897_python_sql.txt
Q: All code in one file After asking organising my Python project and then calling from a parent file in Python it's occurring to me that it'll be so much easier to put all my code in one file (data will be read in externally). I've always thought that this was bad project organisation but it seems to be the easiest way to deal with the problems I'm thinking I will face. Have I simply gotten the wrong end of the stick with file count or have I not seen some great guide on large (for me) projects? A: If you are planning to use any kind of SCM then you are going to be screwed. Having one file is a guaranteed way to have lots of collisions and merges that will be painstaking to deal with over time. Stick to conventions and break apart your files. If nothing more than to save the guy who will one day have to maintain your code... A: If your code is going to work together all the time anyway, and isn't useful separately, there's nothing wrong with keeping everything in one file. I can think of at least popular package (BeautifulSoup) that does this. Sure makes installation easier. Of course, if it seems, down the road, that you could use part of your code with another project, or if maintainance starts to be an issue, then worry about organizing your project differently. It seems to me from the questions you've been asking lately that you're worrying about all of this a bit prematurely. Often, for me, these sorts of issues are better tackled a little later on in the solution. Especially for smaller projects, my goal is to get a solution that is correct, and then optimal. A: It's always a now verses then argument. If you're under the gun to get it done, do it. Source control will be a problem later, as with many things there's no black and white answer. You need to be responsible to both your deadline and the long term maintenance of the code. A: If that's the best way to organise it, you're probably doing something wrong. If it's more than just a toy program or a simple script, then you should break it up into separate files, etc. It's the only sane way of doing it. When your project gets big enough that you need someone else helping on it, then it will make the SCM a whole bunch easier. Additionally, sooner or later you are going to need to add a separate utility to your project, that is going to need some common code/structures. It's far easier to do this if you have separate source files than if you have just one big one. A: Since Calling from a parent file in Python indicates serious design problems, I'd say that you have two choices. Don't have a library module try to call back to main. You'll have to rewrite things to fix this. [An imported component calling the main program is an improper dependency. And Python doesn't support it because it's a poor design.] Put it all in one file until you figure out a better design with proper one-way dependencies. Then you'll have to rewrite it to fix the dependency problems. A module (a single file) should be a logical piece of related code. Not everything. Not a single class definition. There's a middle ground of modularity. Additionally, there should be a proper one-way dependency graph from main program to components (which do NOT depend on the main program) to utility libraries and what-not (that do not know about the components OR the main program. Circular (or mutual) dependencies often indicate a design problem. Callbacks are one way out of the problem. Another way is to decompose the circular elements to get a proper one-way graph. A: Looking at your earlier questions I would say all code in one file would be a good intermediate state on the way to a complete refactoring of your project. To do this you'll need a regression test suite to make sure you don't break the project while refactoring it. Once all your code is in one file, I suggest iterating on the following: Identify a small group of interdependent classes. Pull those classes into a separate file. Add unit tests for the new separate file. Retest the entire project. Depending on the size of your project, it shouldn't take too many iterations for you to reach something reasonable.
All code in one file
After asking organising my Python project and then calling from a parent file in Python it's occurring to me that it'll be so much easier to put all my code in one file (data will be read in externally). I've always thought that this was bad project organisation but it seems to be the easiest way to deal with the problems I'm thinking I will face. Have I simply gotten the wrong end of the stick with file count or have I not seen some great guide on large (for me) projects?
[ "If you are planning to use any kind of SCM then you are going to be screwed. Having one file is a guaranteed way to have lots of collisions and merges that will be painstaking to deal with over time.\nStick to conventions and break apart your files. If nothing more than to save the guy who will one day have to maintain your code...\n", "If your code is going to work together all the time anyway, and isn't useful separately, there's nothing wrong with keeping everything in one file. I can think of at least popular package (BeautifulSoup) that does this. Sure makes installation easier.\nOf course, if it seems, down the road, that you could use part of your code with another project, or if maintainance starts to be an issue, then worry about organizing your project differently. \nIt seems to me from the questions you've been asking lately that you're worrying about all of this a bit prematurely. Often, for me, these sorts of issues are better tackled a little later on in the solution. Especially for smaller projects, my goal is to get a solution that is correct, and then optimal.\n", "It's always a now verses then argument. If you're under the gun to get it done, do it. Source control will be a problem later, as with many things there's no black and white answer. You need to be responsible to both your deadline and the long term maintenance of the code.\n", "If that's the best way to organise it, you're probably doing something wrong.\nIf it's more than just a toy program or a simple script, then you should break it up into separate files, etc. It's the only sane way of doing it. When your project gets big enough that you need someone else helping on it, then it will make the SCM a whole bunch easier.\nAdditionally, sooner or later you are going to need to add a separate utility to your project, that is going to need some common code/structures. It's far easier to do this if you have separate source files than if you have just one big one.\n", "Since Calling from a parent file in Python indicates serious design problems, I'd say that you have two choices.\n\nDon't have a library module try to call back to main. You'll have to rewrite things to fix this. \n[An imported component calling the main program is an improper dependency. And Python doesn't support it because it's a poor design.]\nPut it all in one file until you figure out a better design with proper one-way dependencies. Then you'll have to rewrite it to fix the dependency problems.\n\nA module (a single file) should be a logical piece of related code. Not everything. Not a single class definition. There's a middle ground of modularity. \nAdditionally, there should be a proper one-way dependency graph from main program to components (which do NOT depend on the main program) to utility libraries and what-not (that do not know about the components OR the main program. \nCircular (or mutual) dependencies often indicate a design problem. Callbacks are one way out of the problem. Another way is to decompose the circular elements to get a proper one-way graph.\n", "Looking at your earlier questions I would say all code in one file would be a good intermediate state on the way to a complete refactoring of your project. To do this you'll need a regression test suite to make sure you don't break the project while refactoring it.\nOnce all your code is in one file, I suggest iterating on the following:\n\nIdentify a small group of interdependent classes.\nPull those classes into a separate file.\nAdd unit tests for the new separate file.\nRetest the entire project.\n\nDepending on the size of your project, it shouldn't take too many iterations for you to reach something reasonable.\n" ]
[ 14, 4, 2, 2, 2, 2 ]
[]
[]
[ "project_management", "python", "version_control" ]
stackoverflow_0000403934_project_management_python_version_control.txt
Q: I need help--lists and Python How to return a list in Python??? When I tried returning a list,I got an empty list.What's the reason??? A: As Andrew commented, you will receive better answers if you show us the code you are currently using. Also if you could state what version of Python you are using that would be great. There are a few ways you can return a list. Say for example we have a function called retlist. def retlist(): return [] will return the empty list def retlist(): a = list() a.append(5) return a will return [5]. You can also use list comprehension to return a list def retlist(): return [x*x for x in range(10)] There are plenty of ways to return a list. But basically it involves return . If you are after a more detailed response, comment for what you need. Good Luck A: to wit: In [1]: def pants(): ...: return [1, 2, 'steve'] ...: In [2]: pants() Out[2]: [1, 2, 'steve']
I need help--lists and Python
How to return a list in Python??? When I tried returning a list,I got an empty list.What's the reason???
[ "As Andrew commented, you will receive better answers if you show us the code you are currently using. Also if you could state what version of Python you are using that would be great.\nThere are a few ways you can return a list. Say for example we have a function called retlist.\ndef retlist():\n return []\n\nwill return the empty list\ndef retlist():\n a = list()\n a.append(5)\n return a\n\nwill return [5].\nYou can also use list comprehension to return a list\ndef retlist():\n return [x*x for x in range(10)]\n\nThere are plenty of ways to return a list. But basically it involves return .\nIf you are after a more detailed response, comment for what you need.\nGood Luck\n", "to wit:\nIn [1]: def pants():\n ...: return [1, 2, 'steve']\n ...: \nIn [2]: pants()\nOut[2]: [1, 2, 'steve']\n\n" ]
[ 2, 0 ]
[]
[]
[ "list", "python", "return" ]
stackoverflow_0000404825_list_python_return.txt
Q: Scaling the y-axis with Matplotlib in Python How to scale the y-axis with Matplotlib? I don't want to change the y-limit, I just want to extend the physical space. ^ ^ | | | | +----> | Before +----> After A: Just use a larger height value when you instantiate the figure: from pylab import * x = linspace(0, 10*pi, 2**10) y = sin(x) figure(figsize=(5, 10)) plot(x, y) show() Where figsize=(width, height) and defaults to (8, 6). Values are in inches (the dpi keyword arg can be used to define the DPI for the figure, and there's a default value in your matplotlibrc file) For a figure already created, I believe there is a set_size_inches(width, height) method. A: Use the subplots_adjust function to control the abount of whitespace: fig.subplots_adust(bottom=0.05, top=0.95) There is an icon on the toolbar to do this interactively with a widget
Scaling the y-axis with Matplotlib in Python
How to scale the y-axis with Matplotlib? I don't want to change the y-limit, I just want to extend the physical space. ^ ^ | | | | +----> | Before +----> After
[ "Just use a larger height value when you instantiate the figure:\nfrom pylab import *\nx = linspace(0, 10*pi, 2**10)\ny = sin(x)\nfigure(figsize=(5, 10))\nplot(x, y)\nshow()\n\nWhere figsize=(width, height) and defaults to (8, 6). Values are in inches (the dpi keyword arg can be used to define the DPI for the figure, and there's a default value in your matplotlibrc file)\nFor a figure already created, I believe there is a set_size_inches(width, height) method.\n", "Use the subplots_adjust function to control the abount of whitespace:\nfig.subplots_adust(bottom=0.05, top=0.95)\n\nThere is an icon on the toolbar to do this interactively with a widget\n" ]
[ 8, 2 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0000401787_matplotlib_python.txt
Q: Line reading chokes on 0x1A I have the following file: abcde kwakwa <0x1A> line3 linllll Where <0x1A> represents a byte with the hex value of 0x1A. When attempting to read this file in Python as: for line in open('t.txt'): print line, It only reads the first two lines, and exits the loop. The solution seems to be to open the file in binary (or universal newline mode) - 'rb' or 'rU'. Can you explain this behavior ? A: 0x1A is Ctrl-Z, and DOS historically used that as an end-of-file marker. For example, try using a command prompt, and "type"ing your file. It will only display the content up the Ctrl-Z. Python uses the Windows CRT function _wfopen, which implements the "Ctrl-Z is EOF" semantics. A: Ned is of course correct. If your curiosity runs a little deeper, the root cause is backwards compatibility taken to an extreme. Windows is compatible with DOS, which used Ctrl-Z as an optional end of file marker for text files. What you might not know is that DOS was compatible with CP/M, which was popular on small computers before the PC. CP/M's file system didn't keep track of file sizes down to the byte level, it only kept track by the number of floppy disk sectors. If your file wasn't an exact multiple of 128 bytes, you needed a way to mark the end of the text. This Wikipedia article implies that the selection of Ctrl-Z was based on an even older convention used by DEC.
Line reading chokes on 0x1A
I have the following file: abcde kwakwa <0x1A> line3 linllll Where <0x1A> represents a byte with the hex value of 0x1A. When attempting to read this file in Python as: for line in open('t.txt'): print line, It only reads the first two lines, and exits the loop. The solution seems to be to open the file in binary (or universal newline mode) - 'rb' or 'rU'. Can you explain this behavior ?
[ "0x1A is Ctrl-Z, and DOS historically used that as an end-of-file marker. For example, try using a command prompt, and \"type\"ing your file. It will only display the content up the Ctrl-Z. \nPython uses the Windows CRT function _wfopen, which implements the \"Ctrl-Z is EOF\" semantics.\n", "Ned is of course correct.\nIf your curiosity runs a little deeper, the root cause is backwards compatibility taken to an extreme. Windows is compatible with DOS, which used Ctrl-Z as an optional end of file marker for text files. What you might not know is that DOS was compatible with CP/M, which was popular on small computers before the PC. CP/M's file system didn't keep track of file sizes down to the byte level, it only kept track by the number of floppy disk sectors. If your file wasn't an exact multiple of 128 bytes, you needed a way to mark the end of the text. This Wikipedia article implies that the selection of Ctrl-Z was based on an even older convention used by DEC.\n" ]
[ 28, 9 ]
[]
[]
[ "binary_data", "python", "windows" ]
stackoverflow_0000405058_binary_data_python_windows.txt
Q: I can't but help get the idea I'm doing it all wrong (Python, again) All of the questions that I've asked recently about Python have been for this project. I have realised that the reason I'm asking so many questions may not be because I'm so new to Python (but I know a good bit of PHP) and is probably not because Python has some inherent flaw. Thus I will now say what the project is and what my current idea is and you can either tell me I'm doing it all wrong, that there's a few things I need to learn or that Python is simply not suited to dealing with this type of project and language XYZ would be better in this instance or even that there's some open source project I might want to get involved in. The project I run a free turn based strategy game (think the campaign mode from the total war series but with even more complexity and depth) and am creating a combat simulator for it (again, think total war as an idea of how it'd work). I'm in no way deluded enough to think that I'll ever make anything as good as the Total war games alone but I do think that I can automate a process that I currently do by hand. What will it do It will have to take into account a large range of variables for the units, equipment, training, weather, terrain and so on and so forth. I'm aware it's a big task and I plan to do it a piece at a time in my free time. I've zero budget but it's a hobby that I'm prepared to put time into (and have already). My current stumbling block In PHP everything can access everything else, "wrong" though some might consider this it's really really handy for this. If I have an array of equipment for use by the units, I can get hold of that array from anywhere. With Python I have to remake that array each time I import the relevant data file and this seems quite a silly solution for a language that from my experience is well thought out. I've put in a system of logging function calls and class creation (because I know from a very basic version of this that I did in PHP once that it'll help a lot down the line) and the way that I've kept the data in one place is to pass each of my classes an instance to my logging list, smells like a hack to me but it's the only way I've gotten it to work. Thus I conclude I'm missing something and would very much appreciate the insight of anybody willing to give it. Thank you. Code samples This creates a list of formations, so far there's only one value (besides the name) but I anticipate adding more on which is why they're a list of classes rather than just a standard list. This is found within data.py formations = [] formationsHash = [] def createFormations(logger): """This creates all the formations that will be used""" # Standard close quarter formation, maximum number of people per square metre formationsHash.append('Tight') formations.append(Formation(logger, 'Tight', tightness = 1)) # Standard ranged combat formation, good people per square metre but not too cramped formationsHash.append('Loose') formations.append(Formation(logger, 'Loose', tightness = 0.5)) # Standard skirmishing formation, very good for moving around terrain and avoiding missile fire formationsHash.append('Skirmish') formations.append(Formation(logger, 'Skirmish', tightness = 0.1)) # Very unflexible but good for charges formationsHash.append('Arrowhead') formations.append(Formation(logger, 'Arrowhead', tightness = 1)) def getFormation(searchFor): """Returns the fomation object with this name""" indexValue = formationsHash.index(searchFor) return formations[indexValue] I don't have a code sample of when I'd need to access it because I've not gotten as far as making it but I anticipate the code looking something like the following: Python tempFormation = data.getFormation(unit.formationType) tempTerrain = data.getTerrain(unit.currentTerrain) unit.attackDamage = unit.attackDamage * tempTerrain.tighnessBonus(tempFormation.tightness) The unit contains an integer that links to the index/key of the relevant terrain, formation and whatnot in the master list. Temporary variables are used to make the 3rd line shorter but in the long run will possibly cause issues if I forget to get one and it's use a value from earlier which is then incorrect (that's where the logging comes in handy). PHP $unit->attackDamage *= $terrain[$unit->currentTerrain]->tighnessBonus($unit->currentTerrain) The unit class contains the index (probably a string) of the relevant terrain it's on and the formation it's in. Maybe this will show some massive flaw in my understanding of Python (6 months vs the 3 years of PHP). A: With Python I have to remake that array each time I import the relevant data file You're missing a subtle point of Python semantics here. When you import a module for a second time, you aren't re-executing the code in that module. The name is found in a list of all modules imported, and the same module is returned to you. So the second time you import your module, you'll get a reference to the same list (in Python, don't say array, say list). You'll probably need to post specific code samples to get more help, it seems like there are a few Python misconceptions mixed into this, and once those are cleared up you'll have a simpler time. A: I have narrowed your issue down to: With Python I have to remake that array each time I import the relevant data file Well you have two choices really, the first and easiest is to keep the structure in memory. That way (just like PHP) you can in theory access it from "anywhere", you are slightly limited by namespacing, but that is for your own good. It would translate as "anywhere you would like to". The second choice is to have some data abstraction (like a database, or data file as you have) which stores and you retrieve data from this. This may be better than the first choice, as you might have far too much data to fit in memory at once. Again the way of getting this data will be available "anywhere" just like PHP. You can either pass these things directly to instances in an explicit way, or you can use module-level globals and import them into places where you need them, as you go on to say: and the way that I've kept the data in one place is to pass each of my classes an instance to my logging list I can assure you that this is not a hack. It's quite reasonable, depending on the use, eg a config object can be used in the same way, as you may want to test your application with simultaneous different configs. Logging might be better suited as a module-level global that is just imported and called, as you probably only ever want one way of logging, but again, it depends on your requirements. I guess to sum up, you really are on the right track. Try not to give in to that "hackish" smell especially when using languages you are not altogether familiar with. A hack in one language might be the gold-standard in another. And of course, best of luck with your project - it sounds fun. A: Please don't reinvent the wheel. Your formationsHash as a list of key values isn't helpful and it duplicates the features of a dictionary. def createFormations(logger): """This creates all the formations that will be used""" formations = {} formations['Tight']= Formation(logger, 'Tight', tightness = 1) formations['Loose']= Formation(logger, 'Loose', tightness = 0.5) formations['Skirmish']= Formation(logger, 'Skirmish', tightness = 0.1) formations['Arrowhead']= Formation(logger, 'Arrowhead', tightness = 1) return formations Note, you don't actually need getFormation, since it does you no good. You can simply use something like this. formations = createFormations( whatever ) f= formations[name] A: "data.py creates an array (well, list), to use this list from another file I need to import data.py and remake said list." I can't figure out what you're talking about. Seriously. Here's a main program, which imports the data, and another module. SomeMainProgram.py import data import someOtherModule print data.formations['Arrowhead'] someOtherModule.function() someOtherModule.py import data def function(): print data.formations['Tight'] data.py import theLoggerThing class Formation( object ): pass # details omitted. def createFormations( logger ): pass # details omitted formations= createFormations( theLoggerThing.logger ) So the main program works like this. import data. The data module is imported. a. import theLoggerThing. Whatever this is. b. class Formation( object ):. Create a class Formations. c. def createFormations( logger ):. Create a function createFormations. d. formations =. Create an object, formations. import someOtherModule. The someOtherModule is imported. a. import data. Nothing happens. data is already available globally. This is a reference to what is -- effectively -- a Singleton. All Python modules are Singletons. b. def function. Create a function function. print data.formations['Arrowhead']. Evaluate data.formations, which is a dictionary object. Do a get('Arrowhead') on the dictionary which does some magical lookup and returns the object found there (an instance of Formation). someOtherModule.function(). What happens during this function evaluation. a. print data.formations['Tight']. Evaluate data.formations, which is a dictionary object. Do a get('Tight') on the dictionary which does some magical lookup and returns the object found there (an instance of Formation).
I can't but help get the idea I'm doing it all wrong (Python, again)
All of the questions that I've asked recently about Python have been for this project. I have realised that the reason I'm asking so many questions may not be because I'm so new to Python (but I know a good bit of PHP) and is probably not because Python has some inherent flaw. Thus I will now say what the project is and what my current idea is and you can either tell me I'm doing it all wrong, that there's a few things I need to learn or that Python is simply not suited to dealing with this type of project and language XYZ would be better in this instance or even that there's some open source project I might want to get involved in. The project I run a free turn based strategy game (think the campaign mode from the total war series but with even more complexity and depth) and am creating a combat simulator for it (again, think total war as an idea of how it'd work). I'm in no way deluded enough to think that I'll ever make anything as good as the Total war games alone but I do think that I can automate a process that I currently do by hand. What will it do It will have to take into account a large range of variables for the units, equipment, training, weather, terrain and so on and so forth. I'm aware it's a big task and I plan to do it a piece at a time in my free time. I've zero budget but it's a hobby that I'm prepared to put time into (and have already). My current stumbling block In PHP everything can access everything else, "wrong" though some might consider this it's really really handy for this. If I have an array of equipment for use by the units, I can get hold of that array from anywhere. With Python I have to remake that array each time I import the relevant data file and this seems quite a silly solution for a language that from my experience is well thought out. I've put in a system of logging function calls and class creation (because I know from a very basic version of this that I did in PHP once that it'll help a lot down the line) and the way that I've kept the data in one place is to pass each of my classes an instance to my logging list, smells like a hack to me but it's the only way I've gotten it to work. Thus I conclude I'm missing something and would very much appreciate the insight of anybody willing to give it. Thank you. Code samples This creates a list of formations, so far there's only one value (besides the name) but I anticipate adding more on which is why they're a list of classes rather than just a standard list. This is found within data.py formations = [] formationsHash = [] def createFormations(logger): """This creates all the formations that will be used""" # Standard close quarter formation, maximum number of people per square metre formationsHash.append('Tight') formations.append(Formation(logger, 'Tight', tightness = 1)) # Standard ranged combat formation, good people per square metre but not too cramped formationsHash.append('Loose') formations.append(Formation(logger, 'Loose', tightness = 0.5)) # Standard skirmishing formation, very good for moving around terrain and avoiding missile fire formationsHash.append('Skirmish') formations.append(Formation(logger, 'Skirmish', tightness = 0.1)) # Very unflexible but good for charges formationsHash.append('Arrowhead') formations.append(Formation(logger, 'Arrowhead', tightness = 1)) def getFormation(searchFor): """Returns the fomation object with this name""" indexValue = formationsHash.index(searchFor) return formations[indexValue] I don't have a code sample of when I'd need to access it because I've not gotten as far as making it but I anticipate the code looking something like the following: Python tempFormation = data.getFormation(unit.formationType) tempTerrain = data.getTerrain(unit.currentTerrain) unit.attackDamage = unit.attackDamage * tempTerrain.tighnessBonus(tempFormation.tightness) The unit contains an integer that links to the index/key of the relevant terrain, formation and whatnot in the master list. Temporary variables are used to make the 3rd line shorter but in the long run will possibly cause issues if I forget to get one and it's use a value from earlier which is then incorrect (that's where the logging comes in handy). PHP $unit->attackDamage *= $terrain[$unit->currentTerrain]->tighnessBonus($unit->currentTerrain) The unit class contains the index (probably a string) of the relevant terrain it's on and the formation it's in. Maybe this will show some massive flaw in my understanding of Python (6 months vs the 3 years of PHP).
[ "\nWith Python I have to remake that\n array each time I import the relevant\n data file\n\nYou're missing a subtle point of Python semantics here. When you import a module for a second time, you aren't re-executing the code in that module. The name is found in a list of all modules imported, and the same module is returned to you. So the second time you import your module, you'll get a reference to the same list (in Python, don't say array, say list).\nYou'll probably need to post specific code samples to get more help, it seems like there are a few Python misconceptions mixed into this, and once those are cleared up you'll have a simpler time.\n", "I have narrowed your issue down to:\n\nWith Python I have to remake that\n array each time I import the relevant\n data file\n\nWell you have two choices really, the first and easiest is to keep the structure in memory. That way (just like PHP) you can in theory access it from \"anywhere\", you are slightly limited by namespacing, but that is for your own good. It would translate as \"anywhere you would like to\".\nThe second choice is to have some data abstraction (like a database, or data file as you have) which stores and you retrieve data from this. This may be better than the first choice, as you might have far too much data to fit in memory at once. Again the way of getting this data will be available \"anywhere\" just like PHP.\nYou can either pass these things directly to instances in an explicit way, or you can use module-level globals and import them into places where you need them, as you go on to say:\n\nand the way that I've kept the data in\n one place is to pass each of my\n classes an instance to my logging list\n\nI can assure you that this is not a hack. It's quite reasonable, depending on the use, eg a config object can be used in the same way, as you may want to test your application with simultaneous different configs. Logging might be better suited as a module-level global that is just imported and called, as you probably only ever want one way of logging, but again, it depends on your requirements.\nI guess to sum up, you really are on the right track. Try not to give in to that \"hackish\" smell especially when using languages you are not altogether familiar with. A hack in one language might be the gold-standard in another. And of course, best of luck with your project - it sounds fun.\n", "Please don't reinvent the wheel. Your formationsHash as a list of key values isn't helpful and it duplicates the features of a dictionary.\ndef createFormations(logger):\n \"\"\"This creates all the formations that will be used\"\"\"\n formations = {}\n formations['Tight']= Formation(logger, 'Tight', tightness = 1)\n formations['Loose']= Formation(logger, 'Loose', tightness = 0.5)\n formations['Skirmish']= Formation(logger, 'Skirmish', tightness = 0.1)\n formations['Arrowhead']= Formation(logger, 'Arrowhead', tightness = 1)\n return formations\n\nNote, you don't actually need getFormation, since it does you no good. You can simply use something like this.\nformations = createFormations( whatever )\nf= formations[name]\n\n", "\"data.py creates an array (well, list), to use this list from another file I need to import data.py and remake said list.\"\nI can't figure out what you're talking about. Seriously.\nHere's a main program, which imports the data, and another module.\nSomeMainProgram.py\nimport data\nimport someOtherModule\n\nprint data.formations['Arrowhead']\nsomeOtherModule.function()\n\nsomeOtherModule.py\nimport data\ndef function():\n print data.formations['Tight']\n\ndata.py\nimport theLoggerThing\nclass Formation( object ):\n pass # details omitted.\ndef createFormations( logger ):\n pass # details omitted\nformations= createFormations( theLoggerThing.logger )\n\nSo the main program works like this.\n\nimport data. The data module is imported.\na. import theLoggerThing. Whatever this is.\nb. class Formation( object ):. Create a class Formations.\nc. def createFormations( logger ):. Create a function createFormations.\nd. formations =. Create an object, formations.\nimport someOtherModule. The someOtherModule is imported.\na. import data. Nothing happens. data is already available globally. This is a reference to what is -- effectively -- a Singleton. All Python modules are Singletons.\nb. def function. Create a function function.\nprint data.formations['Arrowhead']. Evaluate data.formations, which is a dictionary object. Do a get('Arrowhead') on the dictionary which does some magical lookup and returns the object found there (an instance of Formation).\nsomeOtherModule.function().\nWhat happens during this function evaluation.\na. print data.formations['Tight']. Evaluate data.formations, which is a dictionary object. Do a get('Tight') on the dictionary which does some magical lookup and returns the object found there (an instance of Formation).\n\n" ]
[ 5, 3, 3, 1 ]
[]
[]
[ "php", "project", "project_planning", "python" ]
stackoverflow_0000405106_php_project_project_planning_python.txt
Q: Accepting File Argument in Python (from Send To context menu) I'm going to start of by noting that I have next to no python experience. alt text http://www.aquate.us/u/9986423875612301299.jpg As you may know, by simply dropping a shortcut in the Send To folder on your Windows PC, you can allow a program to take a file as an argument. How would I write a python program that takes this file as an argument? And, as a bonus if anyone gets a chance -- How would I integrate that with a urllib2 to POST the file to a PHP script on my server? Thanks in advance. Edit-- also, how do I make something show up in the Sendto menu? I was under the impression that you just drop a shortcut into the SendTo folder and it automatically adds an option in the menu... Never mind. I figured out what I was doing wrong :) A: Find out what the dragged file was: http://docs.python.org/library/sys.html#sys.argv Open it: http://docs.python.org/library/functions.html#open Read it in: http://docs.python.org/library/stdtypes.html#file.read Post it: http://docs.python.org/library/urllib2.html#urllib2.urlopen A: import sys for arg in sys.argv: print arg
Accepting File Argument in Python (from Send To context menu)
I'm going to start of by noting that I have next to no python experience. alt text http://www.aquate.us/u/9986423875612301299.jpg As you may know, by simply dropping a shortcut in the Send To folder on your Windows PC, you can allow a program to take a file as an argument. How would I write a python program that takes this file as an argument? And, as a bonus if anyone gets a chance -- How would I integrate that with a urllib2 to POST the file to a PHP script on my server? Thanks in advance. Edit-- also, how do I make something show up in the Sendto menu? I was under the impression that you just drop a shortcut into the SendTo folder and it automatically adds an option in the menu... Never mind. I figured out what I was doing wrong :)
[ "\nFind out what the dragged file was: http://docs.python.org/library/sys.html#sys.argv\nOpen it: http://docs.python.org/library/functions.html#open\nRead it in: http://docs.python.org/library/stdtypes.html#file.read\nPost it: http://docs.python.org/library/urllib2.html#urllib2.urlopen\n\n", "import sys\n\nfor arg in sys.argv:\n print arg\n\n" ]
[ 7, 2 ]
[]
[]
[ "contextmenu", "python", "sendto", "urllib2" ]
stackoverflow_0000405612_contextmenu_python_sendto_urllib2.txt
Q: insert two values from an mysql table into another table using a python program I'm having a small problem with a Python program (below) that I'm writing. I want to insert two values from a MySQL table into another table from a Python program. The two fields are priority and product and I have selected them from the shop table and I want to insert them into the products table. Can anyone help? Thanks a lot. Marc. import MySQLdb def checkOut(): db = MySQLdb.connect(host='localhost', user = 'root', passwd = '$$', db = 'fillmyfridge') cursor = db.cursor(MySQLdb.cursors.DictCursor) user_input = raw_input('please enter the product barcode that you are taking out of the fridge: \n') cursor.execute('update shops set instock=0, howmanytoorder = howmanytoorder + 1 where barcode = %s', (user_input)) db.commit() cursor.execute('select product, priority from shop where barcode = %s', (user_input)) rows = cursor.fetchall() cursor.execute('insert into products(product, barcode, priority) values (%s, %s)', (rows["product"], user_input, rows["priority"])) db.commit() print 'the following product has been removed from the fridge and needs to be ordered' A: Well, the same thing again: import MySQLdb def checkOut(): db = MySQLdb.connect(host='localhost', user = 'root', passwd = '$$', db = 'fillmyfridge') cursor = db.cursor(MySQLdb.cursors.DictCursor) user_input = raw_input('please enter the product barcode that you are taking out of the fridge: \n') cursor.execute('update shops set instock=0, howmanytoorder = howmanytoorder + 1 where barcode = %s', (user_input)) db.commit() cursor.execute('select product, priority from shop where barcode = %s', (user_input)) rows = cursor.fetchall() Do you need fetchall()?? Barcode's are unique I guess and one barcode is to one product I guess. So, fetchone() is enough....isn't it?? In any case if you do a fetchall() its a result set not a single result. So rows["product"] is not valid. It has to be for row in rows: cursor.execute('insert into products(product, barcode, priority) values (%s, %s, %s)', (row["product"], user_input, row["priority"])) db.commit() print 'the following product has been removed from the fridge and needs to be ordered' or better import MySQLdb def checkOut(): db = MySQLdb.connect(host='localhost', user = 'root', passwd = '$$', db = 'fillmyfridge') cursor = db.cursor(MySQLdb.cursors.DictCursor) user_input = raw_input('please enter the product barcode that you are taking out of the fridge: \n') cursor.execute('update shops set instock=0, howmanytoorder = howmanytoorder + 1 where barcode = %s', (user_input)) cursor.execute('insert into products(product, barcode, priority) select product, barcode, priority from shop where barcode = %s', (user_input)) db.commit() Edit: Also, you use db.commit() almost like print - anywhere, you need to read and understand the atomicity principle for databases A: You don't mention what the problem is, but in the code you show this: cursor.execute('insert into products(product, barcode, priority) values (%s, %s)', (rows["product"], user_input, rows["priority"])) where your values clause only has two %s's in it, where it should have three: cursor.execute('insert into products(product, barcode, priority) values (%s, %s, %s)', (rows["product"], user_input, rows["priority"]))
insert two values from an mysql table into another table using a python program
I'm having a small problem with a Python program (below) that I'm writing. I want to insert two values from a MySQL table into another table from a Python program. The two fields are priority and product and I have selected them from the shop table and I want to insert them into the products table. Can anyone help? Thanks a lot. Marc. import MySQLdb def checkOut(): db = MySQLdb.connect(host='localhost', user = 'root', passwd = '$$', db = 'fillmyfridge') cursor = db.cursor(MySQLdb.cursors.DictCursor) user_input = raw_input('please enter the product barcode that you are taking out of the fridge: \n') cursor.execute('update shops set instock=0, howmanytoorder = howmanytoorder + 1 where barcode = %s', (user_input)) db.commit() cursor.execute('select product, priority from shop where barcode = %s', (user_input)) rows = cursor.fetchall() cursor.execute('insert into products(product, barcode, priority) values (%s, %s)', (rows["product"], user_input, rows["priority"])) db.commit() print 'the following product has been removed from the fridge and needs to be ordered'
[ "Well, the same thing again:\nimport MySQLdb\n\ndef checkOut():\n db = MySQLdb.connect(host='localhost', user = 'root', passwd = '$$', db = 'fillmyfridge')\n cursor = db.cursor(MySQLdb.cursors.DictCursor)\n user_input = raw_input('please enter the product barcode that you are taking out of the fridge: \\n')\n cursor.execute('update shops set instock=0, howmanytoorder = howmanytoorder + 1 where barcode = %s', (user_input))\n db.commit()\n cursor.execute('select product, priority from shop where barcode = %s', (user_input))\n rows = cursor.fetchall()\n\n\nDo you need fetchall()?? Barcode's are unique I guess and one barcode is to one product I guess. So, fetchone() is enough....isn't it??\nIn any case if you do a fetchall() its a result set not a single result.\nSo rows[\"product\"] is not valid.\nIt has to be\nfor row in rows:\n cursor.execute('insert into products(product, barcode, priority) values (%s, %s, %s)', (row[\"product\"], user_input, row[\"priority\"]))\ndb.commit()\nprint 'the following product has been removed from the fridge and needs to be ordered'\n\n\nor better\nimport MySQLdb\n\ndef checkOut():\n db = MySQLdb.connect(host='localhost', user = 'root', passwd = '$$', db = 'fillmyfridge')\n cursor = db.cursor(MySQLdb.cursors.DictCursor)\n user_input = raw_input('please enter the product barcode that you are taking out of the fridge: \\n')\n cursor.execute('update shops set instock=0, howmanytoorder = howmanytoorder + 1 where barcode = %s', (user_input))\n cursor.execute('insert into products(product, barcode, priority) select product, barcode, priority from shop where barcode = %s', (user_input))\n db.commit()\n\nEdit: Also, you use db.commit() almost like print - anywhere, you need to read and understand the atomicity principle for databases\n", "You don't mention what the problem is, but in the code you show this:\ncursor.execute('insert into products(product, barcode, priority) values (%s, %s)', (rows[\"product\"], user_input, rows[\"priority\"]))\n\nwhere your values clause only has two %s's in it, where it should have three:\ncursor.execute('insert into products(product, barcode, priority) values (%s, %s, %s)', (rows[\"product\"], user_input, rows[\"priority\"]))\n\n" ]
[ 1, 1 ]
[]
[]
[ "database", "mysql", "python" ]
stackoverflow_0000405617_database_mysql_python.txt
Q: Modifying Microsoft Outlook contacts from Python I have written a few Python tools in the past to extract data from my Outlook contacts. Now, I am trying to modify my Outlook Contacts. I am finding that my changes are being noted by Outlook, but they aren't sticking. I seem to be updating some cache, but not the real record. The code is straightforward. import win32com.client import pywintypes o = win32com.client.Dispatch("Outlook.Application") ns = o.GetNamespace("MAPI") profile = ns.Folders.Item("My Profile Name") contacts = profile.Folders.Item("Contacts") contact = contacts.Items[43] # Grab a random contact, for this example. print "About to overwrite ",contact.FirstName, contact.LastName contact.categories = 'Supplier' # Override the categories # Edit: I don't always do these last steps. ns = None o = None At this point, I change over to Outlook, which is opened to the Detailed Address Cards view. I look at the contact summary (without opening it) and the category is unchanged (not refreshed?). I open the contact and its category HAS changed, sometimes. (Not sure of when, but it feels like it is cache related.) If it has changed, it prompts me to Save Changes when I close it which is odd, because I haven't changed anything in the Outlook UI. If I quit and restart Outlook, the changes are gone. I suspect I am failing to call SaveChanges, but I can't see which object supports it. So my question is: Should I be calling SaveChanges? If so, where is it? Am I making some other silly mistake, which is causing my data to be discarded? A: I believe there is a .Save() method on the contact, so you need to add: contact.Save()
Modifying Microsoft Outlook contacts from Python
I have written a few Python tools in the past to extract data from my Outlook contacts. Now, I am trying to modify my Outlook Contacts. I am finding that my changes are being noted by Outlook, but they aren't sticking. I seem to be updating some cache, but not the real record. The code is straightforward. import win32com.client import pywintypes o = win32com.client.Dispatch("Outlook.Application") ns = o.GetNamespace("MAPI") profile = ns.Folders.Item("My Profile Name") contacts = profile.Folders.Item("Contacts") contact = contacts.Items[43] # Grab a random contact, for this example. print "About to overwrite ",contact.FirstName, contact.LastName contact.categories = 'Supplier' # Override the categories # Edit: I don't always do these last steps. ns = None o = None At this point, I change over to Outlook, which is opened to the Detailed Address Cards view. I look at the contact summary (without opening it) and the category is unchanged (not refreshed?). I open the contact and its category HAS changed, sometimes. (Not sure of when, but it feels like it is cache related.) If it has changed, it prompts me to Save Changes when I close it which is odd, because I haven't changed anything in the Outlook UI. If I quit and restart Outlook, the changes are gone. I suspect I am failing to call SaveChanges, but I can't see which object supports it. So my question is: Should I be calling SaveChanges? If so, where is it? Am I making some other silly mistake, which is causing my data to be discarded?
[ "I believe there is a .Save() method on the contact, so you need to add:\ncontact.Save()\n" ]
[ 6 ]
[]
[]
[ "mapi", "outlook", "python", "winapi" ]
stackoverflow_0000405724_mapi_outlook_python_winapi.txt
Q: Many instances of a class I am trying to write a life simulation in python with a variety of animals. It is impossible to name each instance of the classes I am going to use because I have no way of knowing how many there will be. So, my question: How can I automatically give a name to an object? I was thinking of creating a "Herd" class which could be all the animals of that type alive at the same time... A: Hm, well you normally just stuff all those instances in a list and then iterate over that list if you want to do something with them. If you want to automatically keep track of each instance created you can also make the adding to the list implicit in the class' constructor or create a factory method that keeps track of the created instances. A: Like this? class Animal( object ): pass # lots of details omitted herd= [ Animal() for i in range(10000) ] At this point, herd will have 10,000 distinct instances of the Animal class. A: If you need a way to refer to them individually, it's relatively common to have the class give each instance a unique identifier on initialization: >>> import itertools >>> class Animal(object): ... id_iter = itertools.count(1) ... def __init__(self): ... self.id = self.id_iter.next() ... >>> print(Animal().id) 1 >>> print(Animal().id) 2 >>> print(Animal().id) 3 A: you could make an 'animal' class with a name attribute. Or you could programmically define the class like so: from new import classobj my_class=classobj('Foo',(object,),{}) Found this: http://www.gamedev.net/community/forums/topic.asp?topic_id=445037 A: Any instance could have a name attribute. So it sounds like you may be asking how to dynamically name a class, not an instance. If that's the case, you can explicitly set the __name__ attribute of a class, or better yet just create the class with the builtin type (with 3 args). class Ungulate(Mammal): hoofed = True would be equivalent to cls = type('Ungulate', (Mammal,), {'hoofed': True})
Many instances of a class
I am trying to write a life simulation in python with a variety of animals. It is impossible to name each instance of the classes I am going to use because I have no way of knowing how many there will be. So, my question: How can I automatically give a name to an object? I was thinking of creating a "Herd" class which could be all the animals of that type alive at the same time...
[ "Hm, well you normally just stuff all those instances in a list and then iterate over that list if you want to do something with them. If you want to automatically keep track of each instance created you can also make the adding to the list implicit in the class' constructor or create a factory method that keeps track of the created instances.\n", "Like this?\nclass Animal( object ):\n pass # lots of details omitted\n\n\nherd= [ Animal() for i in range(10000) ]\n\nAt this point, herd will have 10,000 distinct instances of the Animal class.\n", "If you need a way to refer to them individually, it's relatively common to have the class give each instance a unique identifier on initialization:\n>>> import itertools\n>>> class Animal(object):\n... id_iter = itertools.count(1)\n... def __init__(self):\n... self.id = self.id_iter.next()\n... \n>>> print(Animal().id)\n1\n>>> print(Animal().id)\n2\n>>> print(Animal().id)\n3\n\n", "you could make an 'animal' class with a name attribute.\nOr\nyou could programmically define the class like so:\n\nfrom new import classobj\nmy_class=classobj('Foo',(object,),{})\n\n\nFound this:\nhttp://www.gamedev.net/community/forums/topic.asp?topic_id=445037\n", "Any instance could have a name attribute. So it sounds like you may be asking how to dynamically name a class, not an instance. If that's the case, you can explicitly set the __name__ attribute of a class, or better yet just create the class with the builtin type (with 3 args).\nclass Ungulate(Mammal):\n hoofed = True\n\nwould be equivalent to\ncls = type('Ungulate', (Mammal,), {'hoofed': True})\n\n" ]
[ 8, 5, 4, 2, 1 ]
[]
[]
[ "class", "multiple_instances", "object", "python" ]
stackoverflow_0000405282_class_multiple_instances_object_python.txt
Q: Assigning a 'for loop' to a variable in a python program Im writing a program at the moment that interacts with a MySQL database and im having a problem. As you can see I've written a query that will look for products in the products table that corresponds to the barcode that the user has inputted. If the barcode that is input by the user is found in the products table, I want to increase the 'amount' field by 1 in the stocks table where the product that corresponds to the barcode input, is the same as the product in the stocks table. As you can see I've tried to assign a variable to the for loop to try and get it to work that way but its not working. does anyone have any idea of how to do it? import MySQLdb def look_up_product(): db = MySQLdb.connect(host='localhost', user = 'root', passwd='$$', db='fillmyfridge') cursor = db.cursor (MySQLdb.cursors.DictCursor) user_input=raw_input('please enter the product barcode that you wish to checkin to the fridge: \n') if cursor.execute("""select * from products where product = %s""", (user_input)): db.commit() result_set = cursor.fetchall () #i want here to assign a variable to this for loop and the line below = for product in result_set: print "%s" % (row["product"]) cursor.execute('update stocks set amount = amount + 1 where product = %s', (#here i want the result of the for loop)) db.commit() else: print 'no not in products table' thanks a million. A: The answer depends on what you mean by "assign a variable to a for loop." This wording is confusing because a for loop is a tool for controlling the flow of execution -- it's not normally thought of as having a value. But I think I know what you mean. Every time the loop runs, it will execute print "%s" % (row["product"]). I'm guessing that you want to store all of the strings that this makes as the loop runs. I'm also going to guess you meant row[product] and not row["product"], because the latter will be the same for the whole loop. Then you can do this: mylist = [] for product in result_set: mylist.append("%s" % (row[product],)) Notice that the % operation works even though you're not printing the string anymore -- this is a surprise for people coming from C. You can also use python list comprehensions to make this event more succinct: mylist = ["%s" % (row[product],) for product in result_set] A: Are you expecting a single row as a result? If so, try this: row = cursor.fetchone() print row["product"] cursor.execute('update stocks set amount = amount + 1 where product = %s', row["product"]) A: I'm not sure how you get a row id from value fetched from products table. I'd recommend explicitely specifying needed columns and not using the select * from idiom. I introduced the helper function for the id retrieval to make code more readable: def getAnIdFromValue(someValueTuple): '''This function retrieves some table row identifier from a row tuple''' returns someValueTuple[0] I'd try the following function body if multiple rows are expected: db = MySQLdb.connect(...) cursor = db.cursor() ids = [] cursor.execute("""select * from products where product = %s""", (user_input)) for value in cursor.fetchall(): #value is a tuple. len(value) == number of columns in products table ids.append(getAnIdFromValue(value)) if len(ids): cursor.executemany("update stocks set amount = amount + 1 where product =%s", tuple(ids)) db.commit() else: print 'no not in products table' A: I think you need to indent the "update stocks..." line so that it's inside the for loop. A: There there. I also fixed a comma you were missing on the first cursor.execute line. import MySQLdb def look_up_product(): db = MySQLdb.connect(host='localhost', user = 'root', passwd='$$', db='fillmyfridge') cursor = db.cursor (MySQLdb.cursors.DictCursor) user_input=raw_input('please enter the product barcode ' 'that you wish to checkin to the fridge: \n') cursor.execute("""select * from products where product = %s""", (user_input,)) for row in iter(cursor.fetchone, None): print row["product"] cursor.execute('update stocks set amount = amount + 1' ' where product = %s', (row["product"],)) db.commit() Of course, you could always use sqlalchemy instead: import sqlalchemy as sa import sqlalchemy.orm # Prepare high-level objects: class Product(object): pass engine = sa.create_engine('mysql://root:$$@localhost/fillmyfridge') session = sa.orm.create_session(bind=engine) product_table = sa.Table('products', sa.MetaData(), autoload=True) sqlalchemy.orm.mapper(Product, product_table) def look_up_product(): user_input=raw_input('please enter the product barcode ' 'that you wish to checkin to the fridge: \n') for prod in session.query(Product).filter(Product.product == user_input): print prod.product # Here's the nicety: to update just change the object directly: prod.ammount = prod.ammount + 1 session.flush() session.commit()
Assigning a 'for loop' to a variable in a python program
Im writing a program at the moment that interacts with a MySQL database and im having a problem. As you can see I've written a query that will look for products in the products table that corresponds to the barcode that the user has inputted. If the barcode that is input by the user is found in the products table, I want to increase the 'amount' field by 1 in the stocks table where the product that corresponds to the barcode input, is the same as the product in the stocks table. As you can see I've tried to assign a variable to the for loop to try and get it to work that way but its not working. does anyone have any idea of how to do it? import MySQLdb def look_up_product(): db = MySQLdb.connect(host='localhost', user = 'root', passwd='$$', db='fillmyfridge') cursor = db.cursor (MySQLdb.cursors.DictCursor) user_input=raw_input('please enter the product barcode that you wish to checkin to the fridge: \n') if cursor.execute("""select * from products where product = %s""", (user_input)): db.commit() result_set = cursor.fetchall () #i want here to assign a variable to this for loop and the line below = for product in result_set: print "%s" % (row["product"]) cursor.execute('update stocks set amount = amount + 1 where product = %s', (#here i want the result of the for loop)) db.commit() else: print 'no not in products table' thanks a million.
[ "The answer depends on what you mean by \"assign a variable to a for loop.\" This wording is confusing because a for loop is a tool for controlling the flow of execution -- it's not normally thought of as having a value. But I think I know what you mean. Every time the loop runs, it will execute print \"%s\" % (row[\"product\"]). I'm guessing that you want to store all of the strings that this makes as the loop runs. I'm also going to guess you meant row[product] and not row[\"product\"], because the latter will be the same for the whole loop. Then you can do this:\nmylist = []\nfor product in result_set: \n mylist.append(\"%s\" % (row[product],))\n\nNotice that the % operation works even though you're not printing the string anymore -- this is a surprise for people coming from C. You can also use python list comprehensions to make this event more succinct:\nmylist = [\"%s\" % (row[product],) for product in result_set]\n\n", "Are you expecting a single row as a result? If so, try this:\nrow = cursor.fetchone()\nprint row[\"product\"]\ncursor.execute('update stocks set amount = amount + 1 where product = %s', row[\"product\"])\n\n", "I'm not sure how you get a row id from value fetched from products table. I'd recommend explicitely specifying needed columns and not using the select * from idiom.\nI introduced the helper function for the id retrieval to make code more readable:\ndef getAnIdFromValue(someValueTuple):\n '''This function retrieves some table row identifier from a row tuple'''\n returns someValueTuple[0]\n\nI'd try the following function body if multiple rows are expected: \ndb = MySQLdb.connect(...)\ncursor = db.cursor()\nids = []\ncursor.execute(\"\"\"select * from products where product = %s\"\"\", (user_input))\nfor value in cursor.fetchall():\n #value is a tuple. len(value) == number of columns in products table\n ids.append(getAnIdFromValue(value))\nif len(ids):\n cursor.executemany(\"update stocks set amount = amount + 1 where product =%s\", tuple(ids))\n db.commit()\nelse:\n print 'no not in products table'\n\n", "I think you need to indent the \"update stocks...\" line so that it's inside the for loop.\n", "There there. I also fixed a comma you were missing on the first cursor.execute line.\nimport MySQLdb\n\ndef look_up_product():\n db = MySQLdb.connect(host='localhost', user = 'root',\n passwd='$$', db='fillmyfridge')\n cursor = db.cursor (MySQLdb.cursors.DictCursor)\n user_input=raw_input('please enter the product barcode '\n 'that you wish to checkin to the fridge: \\n')\n cursor.execute(\"\"\"select * from products where product = %s\"\"\",\n (user_input,))\n for row in iter(cursor.fetchone, None):\n print row[\"product\"]\n cursor.execute('update stocks set amount = amount + 1' \n ' where product = %s', (row[\"product\"],))\n db.commit()\n\nOf course, you could always use sqlalchemy instead:\nimport sqlalchemy as sa\nimport sqlalchemy.orm\n\n# Prepare high-level objects:\nclass Product(object): pass\nengine = sa.create_engine('mysql://root:$$@localhost/fillmyfridge')\nsession = sa.orm.create_session(bind=engine)\nproduct_table = sa.Table('products', sa.MetaData(), autoload=True)\nsqlalchemy.orm.mapper(Product, product_table)\n\ndef look_up_product():\n user_input=raw_input('please enter the product barcode '\n 'that you wish to checkin to the fridge: \\n')\n for prod in session.query(Product).filter(Product.product == user_input):\n print prod.product\n # Here's the nicety: to update just change the object directly:\n prod.ammount = prod.ammount + 1\n session.flush()\n session.commit()\n\n" ]
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "database", "input", "mysql", "python" ]
stackoverflow_0000399032_database_input_mysql_python.txt
Q: opengl set texture color with vertex color Because I need to display a huge number of labels that move independently, I need to render a label in pyglet to a texture (otherwise updating the vertex list for each glyph is too slow). I have a solution to do this, but my problem is that the texture that contains the glyphs is black, but I'd like it to be red. See the example below: from pyglet.gl import * def label2texture(label): vertex_list = label._vertex_lists[0].vertices[:] xpos = map(int, vertex_list[::8]) ypos = map(int, vertex_list[1::8]) glyphs = label._get_glyphs() xstart = xpos[0] xend = xpos[-1] + glyphs[-1].width width = xend - xstart ystart = min(ypos) yend = max(ystart+glyph.height for glyph in glyphs) height = yend - ystart texture = pyglet.image.Texture.create(width, height, pyglet.gl.GL_RGBA) for glyph, x, y in zip(glyphs, xpos, ypos): data = glyph.get_image_data() x = x - xstart y = height - glyph.height - y + ystart texture.blit_into(data, x, y, 0) return texture.get_transform(flip_y=True) window = pyglet.window.Window() label = pyglet.text.Label('Hello World!', font_size = 36) texture = label2texture(label) @window.event def on_draw(): hoff = (window.width / 2) - (texture.width / 2) voff = (window.height / 2) - (texture.height / 2) glClear(GL_COLOR_BUFFER_BIT) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glClearColor(0.0, 1.0, 0.0, 1.0) window.clear() glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texture.id) glColor4f(1.0, 0.0, 0.0, 1.0) #I'd like the font to be red glBegin(GL_QUADS); glTexCoord2d(0.0,1.0); glVertex2d(hoff,voff); glTexCoord2d(1.0,1.0); glVertex2d(hoff+texture.width,voff); glTexCoord2d(1.0,0.0); glVertex2d(hoff+texture.width,voff+texture.height); glTexCoord2d(0.0,0.0); glVertex2d(hoff, voff+texture.height); glEnd(); pyglet.app.run() Any idea how I could color this? A: You want to set glEnable(GL_COLOR_MATERIAL). This makes the texture color mix with the current OpenGL color. You can also use the glColorMaterial function to specify whether the front/back/both of each polygon should be affected. Docs here. A: Isn't that when you use decaling, through glTexEnv()?
opengl set texture color with vertex color
Because I need to display a huge number of labels that move independently, I need to render a label in pyglet to a texture (otherwise updating the vertex list for each glyph is too slow). I have a solution to do this, but my problem is that the texture that contains the glyphs is black, but I'd like it to be red. See the example below: from pyglet.gl import * def label2texture(label): vertex_list = label._vertex_lists[0].vertices[:] xpos = map(int, vertex_list[::8]) ypos = map(int, vertex_list[1::8]) glyphs = label._get_glyphs() xstart = xpos[0] xend = xpos[-1] + glyphs[-1].width width = xend - xstart ystart = min(ypos) yend = max(ystart+glyph.height for glyph in glyphs) height = yend - ystart texture = pyglet.image.Texture.create(width, height, pyglet.gl.GL_RGBA) for glyph, x, y in zip(glyphs, xpos, ypos): data = glyph.get_image_data() x = x - xstart y = height - glyph.height - y + ystart texture.blit_into(data, x, y, 0) return texture.get_transform(flip_y=True) window = pyglet.window.Window() label = pyglet.text.Label('Hello World!', font_size = 36) texture = label2texture(label) @window.event def on_draw(): hoff = (window.width / 2) - (texture.width / 2) voff = (window.height / 2) - (texture.height / 2) glClear(GL_COLOR_BUFFER_BIT) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glClearColor(0.0, 1.0, 0.0, 1.0) window.clear() glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texture.id) glColor4f(1.0, 0.0, 0.0, 1.0) #I'd like the font to be red glBegin(GL_QUADS); glTexCoord2d(0.0,1.0); glVertex2d(hoff,voff); glTexCoord2d(1.0,1.0); glVertex2d(hoff+texture.width,voff); glTexCoord2d(1.0,0.0); glVertex2d(hoff+texture.width,voff+texture.height); glTexCoord2d(0.0,0.0); glVertex2d(hoff, voff+texture.height); glEnd(); pyglet.app.run() Any idea how I could color this?
[ "You want to set glEnable(GL_COLOR_MATERIAL). This makes the texture color mix with the current OpenGL color. You can also use the glColorMaterial function to specify whether the front/back/both of each polygon should be affected. Docs here.\n", "Isn't that when you use decaling, through glTexEnv()?\n" ]
[ 2, 0 ]
[]
[]
[ "opengl", "pyglet", "python" ]
stackoverflow_0000244720_opengl_pyglet_python.txt
Q: How do you fix a Trac installation that begins giving errors relating to PYTHON_EGG_CACHE? We've been using Trac for task/defect tracking and things were going well enough, but this morning it started serving up a 500 error. Looking in the Apache error_log, I get a stack trace that culminates in: PythonHandler trac.web.modpython_frontend: ExtractionError: Can't extract file(s) to egg cache The following error occurred while trying to extract file(s) to the Python egg cache: [Errno 13] Permission denied: '/.python-eggs' The Python egg cache directory is currently set to: /.python-eggs Perhaps your account does not have write access to this directory? You can change the cache directory by setting the PYTHON_EGG_CACHE environment variable to point to an accessible directory So I explicitly set PYTHON_EGG_CACHE to /srv/trac/plugin-cache. I restarted Apache. Yet I get the same error (it still says "egg cache directory current set to: \n\n /.python_eggs.") How should I proceed? Is the simplest thing to do to reinstall Trac? If I go that route, what steps do I need to take to ensure that I don't lose existing data? A: That should be fixed in 0.11 according to their bug tracking system. If that's not the case you should try to pass the environment var to apache, since doing a SetEnv in the configuration file doesn't work. Adding something like export PYTHON_EGG_CACHE=/tmp/python_eggs to the script you use to start apache should work. A: I ran into the same problem when upgrading from Trac 10.4 to 0.11 earlier this year. Something must have changed for this problem to have just suddenly appeared -- an updated Python or Apache installation? I don't remember all of the permutations I tried to solve this, but I ended up having to use SetEnv PYTHON_EGG_CACHE /.python-eggs and create /.python-eggs with 777 permissions. This might not be the best solution, but it fixed the problem. I never investigated what the root cause was. As agnul says, this may have been fixed in a subsequent Trac release. A: I have wrestled many a battle with PYTHON_EGG_CACHE and I never figured out the correct way of setting it - apache's envvars, httpd.conf (SetEnv and PythonOption), nothing worked. In the end I just unpacked all python eggs manually, there were only two or three anyway - problem gone. I never understood why on earth people zip up files weighting no more than a few kilobytes in the first place... A: I had the same problem. In my case the directory wasn't there so I created and chown'ed it over to the apache user (apache on my centos 4.3 box). Then made sure it had read-write permissions on the directory. You could get by with giving rw rights to the directory if the group that owns the directory contains the apache user. A simple ps aux|grep httpd should show you what account your server is running under if you don't know it. If you have trouble finding the directory remember the -a on the ls command since it is a "hidden" directory. A: I found that using the PythonOption directive in the site config did not work, but SetEnv did. The environment variable route will also work though.
How do you fix a Trac installation that begins giving errors relating to PYTHON_EGG_CACHE?
We've been using Trac for task/defect tracking and things were going well enough, but this morning it started serving up a 500 error. Looking in the Apache error_log, I get a stack trace that culminates in: PythonHandler trac.web.modpython_frontend: ExtractionError: Can't extract file(s) to egg cache The following error occurred while trying to extract file(s) to the Python egg cache: [Errno 13] Permission denied: '/.python-eggs' The Python egg cache directory is currently set to: /.python-eggs Perhaps your account does not have write access to this directory? You can change the cache directory by setting the PYTHON_EGG_CACHE environment variable to point to an accessible directory So I explicitly set PYTHON_EGG_CACHE to /srv/trac/plugin-cache. I restarted Apache. Yet I get the same error (it still says "egg cache directory current set to: \n\n /.python_eggs.") How should I proceed? Is the simplest thing to do to reinstall Trac? If I go that route, what steps do I need to take to ensure that I don't lose existing data?
[ "That should be fixed in 0.11 according to their bug tracking system. \nIf that's not the case you should try to pass the environment var to apache, since doing a SetEnv in the configuration file doesn't work. Adding something like \nexport PYTHON_EGG_CACHE=/tmp/python_eggs\n\nto the script you use to start apache should work.\n", "I ran into the same problem when upgrading from Trac 10.4 to 0.11 earlier this year. Something must have changed for this problem to have just suddenly appeared -- an updated Python or Apache installation?\nI don't remember all of the permutations I tried to solve this, but I ended up having to use SetEnv PYTHON_EGG_CACHE /.python-eggs and create /.python-eggs with 777 permissions. This might not be the best solution, but it fixed the problem. \nI never investigated what the root cause was. As agnul says, this may have been fixed in a subsequent Trac release.\n", "I have wrestled many a battle with PYTHON_EGG_CACHE and I never figured out the correct way of setting it - apache's envvars, httpd.conf (SetEnv and PythonOption), nothing worked. In the end I just unpacked all python eggs manually, there were only two or three anyway - problem gone. I never understood why on earth people zip up files weighting no more than a few kilobytes in the first place...\n", "I had the same problem. In my case the directory wasn't there so I created and chown'ed it over to the apache user (apache on my centos 4.3 box). Then made sure it had read-write permissions on the directory. You could get by with giving rw rights to the directory if the group that owns the directory contains the apache user. A simple ps aux|grep httpd should show you what account your server is running under if you don't know it. If you have trouble finding the directory remember the -a on the ls command since it is a \"hidden\" directory.\n", "I found that using the PythonOption directive in the site config did not work, but SetEnv did. The environment variable route will also work though.\n" ]
[ 5, 1, 1, 0, 0 ]
[]
[]
[ "configuration", "python", "python_egg_cache", "trac" ]
stackoverflow_0000215267_configuration_python_python_egg_cache_trac.txt
Q: What does asterisk * mean in Python? Does * have a special meaning in Python as it does in C? I saw a function like this in the Python Cookbook: def get(self, *a, **kw) Would you please explain it to me or point out where I can find an answer (Google interprets the * as wild card character and thus I cannot find a satisfactory answer). A: See Function Definitions in the Language Reference. If the form *identifier is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form **identifier is present, it is initialized to a new dictionary receiving any excess keyword arguments, defaulting to a new empty dictionary. Also, see Function Calls. Assuming that one knows what positional and keyword arguments are, here are some examples: Example 1: # Excess keyword argument (python 2) example: def foo(a, b, c, **args): print "a = %s" % (a,) print "b = %s" % (b,) print "c = %s" % (c,) print args foo(a="testa", d="excess", c="testc", b="testb", k="another_excess") As you can see in the above example, we only have parameters a, b, c in the signature of the foo function. Since d and k are not present, they are put into the args dictionary. The output of the program is: a = testa b = testb c = testc {'k': 'another_excess', 'd': 'excess'} Example 2: # Excess positional argument (python 2) example: def foo(a, b, c, *args): print "a = %s" % (a,) print "b = %s" % (b,) print "c = %s" % (c,) print args foo("testa", "testb", "testc", "excess", "another_excess") Here, since we're testing positional arguments, the excess ones have to be on the end, and *args packs them into a tuple, so the output of this program is: a = testa b = testb c = testc ('excess', 'another_excess') You can also unpack a dictionary or a tuple into arguments of a function: def foo(a,b,c,**args): print "a=%s" % (a,) print "b=%s" % (b,) print "c=%s" % (c,) print "args=%s" % (args,) argdict = dict(a="testa", b="testb", c="testc", excessarg="string") foo(**argdict) Prints: a=testa b=testb c=testc args={'excessarg': 'string'} And def foo(a,b,c,*args): print "a=%s" % (a,) print "b=%s" % (b,) print "c=%s" % (c,) print "args=%s" % (args,) argtuple = ("testa","testb","testc","excess") foo(*argtuple) Prints: a=testa b=testb c=testc args=('excess',) A: I only have one thing to add that wasn't clear from the other answers (for completeness's sake). You may also use the stars when calling the function. For example, say you have code like this: >>> def foo(*args): ... print(args) ... >>> l = [1,2,3,4,5] You can pass the list l into foo like so... >>> foo(*l) (1, 2, 3, 4, 5) You can do the same for dictionaries... >>> def foo(**argd): ... print(argd) ... >>> d = {'a' : 'b', 'c' : 'd'} >>> foo(**d) {'a': 'b', 'c': 'd'} A: All of the above answers were perfectly clear and complete, but just for the record I'd like to confirm that the meaning of * and ** in python has absolutely no similarity with the meaning of similar-looking operators in C. They are called the argument-unpacking and keyword-argument-unpacking operators. A: A single star means that the variable 'a' will be a tuple of extra parameters that were supplied to the function. The double star means the variable 'kw' will be a variable-size dictionary of extra parameters that were supplied with keywords. Although the actual behavior is spec'd out, it still sometimes can be very non-intuitive. Writing some sample functions and calling them with various parameter styles may help you understand what is allowed and what the results are. def f0(a) def f1(*a) def f2(**a) def f3(*a, **b) etc... A: I find * useful when writing a function that takes another callback function as a parameter: def some_function(parm1, parm2, callback, *callback_args): a = 1 b = 2 ... callback(a, b, *callback_args) ... That way, callers can pass in arbitrary extra parameters that will be passed through to their callback function. The nice thing is that the callback function can use normal function parameters. That is, it doesn't need to use the * syntax at all. Here's an example: def my_callback_function(a, b, x, y, z): ... x = 5 y = 6 z = 7 some_function('parm1', 'parm2', my_callback_function, x, y, z) Of course, closures provide another way of doing the same thing without requiring you to pass x, y, and z through some_function() and into my_callback_function().
What does asterisk * mean in Python?
Does * have a special meaning in Python as it does in C? I saw a function like this in the Python Cookbook: def get(self, *a, **kw) Would you please explain it to me or point out where I can find an answer (Google interprets the * as wild card character and thus I cannot find a satisfactory answer).
[ "See Function Definitions in the Language Reference.\n\nIf the form *identifier is\n present, it is initialized to a tuple\n receiving any excess positional\n parameters, defaulting to the empty\n tuple. If the form **identifier is\n present, it is initialized to a new\n dictionary receiving any excess\n keyword arguments, defaulting to a new\n empty dictionary.\n\nAlso, see Function Calls.\nAssuming that one knows what positional and keyword arguments are, here are some examples:\nExample 1:\n# Excess keyword argument (python 2) example:\ndef foo(a, b, c, **args):\n print \"a = %s\" % (a,)\n print \"b = %s\" % (b,)\n print \"c = %s\" % (c,)\n print args\n\nfoo(a=\"testa\", d=\"excess\", c=\"testc\", b=\"testb\", k=\"another_excess\")\n\nAs you can see in the above example, we only have parameters a, b, c in the signature of the foo function. Since d and k are not present, they are put into the args dictionary. The output of the program is:\na = testa\nb = testb\nc = testc\n{'k': 'another_excess', 'd': 'excess'}\n\nExample 2:\n# Excess positional argument (python 2) example:\ndef foo(a, b, c, *args):\n print \"a = %s\" % (a,)\n print \"b = %s\" % (b,)\n print \"c = %s\" % (c,)\n print args\n\nfoo(\"testa\", \"testb\", \"testc\", \"excess\", \"another_excess\")\n\nHere, since we're testing positional arguments, the excess ones have to be on the end, and *args packs them into a tuple, so the output of this program is:\na = testa\nb = testb\nc = testc\n('excess', 'another_excess')\n\nYou can also unpack a dictionary or a tuple into arguments of a function:\ndef foo(a,b,c,**args):\n print \"a=%s\" % (a,)\n print \"b=%s\" % (b,)\n print \"c=%s\" % (c,)\n print \"args=%s\" % (args,)\n\nargdict = dict(a=\"testa\", b=\"testb\", c=\"testc\", excessarg=\"string\")\nfoo(**argdict)\n\nPrints:\na=testa\nb=testb\nc=testc\nargs={'excessarg': 'string'}\n\nAnd\ndef foo(a,b,c,*args):\n print \"a=%s\" % (a,)\n print \"b=%s\" % (b,)\n print \"c=%s\" % (c,)\n print \"args=%s\" % (args,)\n\nargtuple = (\"testa\",\"testb\",\"testc\",\"excess\")\nfoo(*argtuple)\n\nPrints:\na=testa\nb=testb\nc=testc\nargs=('excess',)\n\n", "I only have one thing to add that wasn't clear from the other answers (for completeness's sake).\nYou may also use the stars when calling the function. For example, say you have code like this:\n>>> def foo(*args):\n... print(args)\n...\n>>> l = [1,2,3,4,5]\n\nYou can pass the list l into foo like so...\n>>> foo(*l)\n(1, 2, 3, 4, 5)\n\nYou can do the same for dictionaries...\n>>> def foo(**argd):\n... print(argd)\n...\n>>> d = {'a' : 'b', 'c' : 'd'}\n>>> foo(**d)\n{'a': 'b', 'c': 'd'}\n\n", "All of the above answers were perfectly clear and complete, but just for the record I'd like to confirm that the meaning of * and ** in python has absolutely no similarity with the meaning of similar-looking operators in C. \nThey are called the argument-unpacking and keyword-argument-unpacking operators.\n", "A single star means that the variable 'a' will be a tuple of extra parameters that were supplied to the function. The double star means the variable 'kw' will be a variable-size dictionary of extra parameters that were supplied with keywords.\nAlthough the actual behavior is spec'd out, it still sometimes can be very non-intuitive. Writing some sample functions and calling them with various parameter styles may help you understand what is allowed and what the results are.\ndef f0(a)\ndef f1(*a)\ndef f2(**a)\ndef f3(*a, **b)\netc...\n\n", "I find * useful when writing a function that takes another callback function as a parameter:\ndef some_function(parm1, parm2, callback, *callback_args):\n a = 1\n b = 2\n ...\n callback(a, b, *callback_args)\n ...\n\nThat way, callers can pass in arbitrary extra parameters that will be passed through to their callback function. The nice thing is that the callback function can use normal function parameters. That is, it doesn't need to use the * syntax at all. Here's an example:\ndef my_callback_function(a, b, x, y, z):\n ...\n\nx = 5\ny = 6\nz = 7\n\nsome_function('parm1', 'parm2', my_callback_function, x, y, z)\n\nOf course, closures provide another way of doing the same thing without requiring you to pass x, y, and z through some_function() and into my_callback_function().\n" ]
[ 345, 201, 93, 41, 30 ]
[]
[]
[ "python" ]
stackoverflow_0000400739_python.txt
Q: ForeignKey form restrictions in Django I'm using Django to write a blog app, and I'm trying to implement a hierarchical category structure. Each category has a "parent" ForeignKey pointing back to the same Category model. I want to allow admins to add categories, and I want the interface to allow them to select a category's parent category. However, I want to avoid I'm-my-own-grandpa situations, so I want to limit the available choices of categories to those which do not have category in question as an ancestor. Right now, I'm controlling this from the view: parent_candidates = list(Category.objects.all()) pruned_parent_list = [cat for cat in parent_candidates if instance.id not in cat.getHierarchy()] where instance is the category being edited and getHierarchy() is a method to get a list of ancestor ids. There are a number of problems with this approach. In particular, it uses an extra database hit to get the list of all categories and it makes me write the selection mechanism into my template by looping through pruned_parent_list to get the options, when I'd really rather just specify a widget. Is there any better way to do this? I know I can add custom validation on the back-end to prevent this, but why give users the option? A: I have had to deal with arbitrary-depth categories on SQL and it seems not well suited for storing data of this type in a normal form, as nested queries and/or multiple JOINs tend to get ugly extremely quickly. This is almost the only case where I would go with a sort of improper solution, namely to store categories in string form, subcategories separated by a delimiter. It makes both database queries and other operations much more trivial. Categories table would look something like this: id name 1 Internet 2 Internet/Google 3 Internet/Yahoo 4 Offline 5 Offline/MS Office/MS Excel 6 Offline/Openoffice Another solution is, that depending on your expected usage, you can maybe implement binary tree in the category list. That allows to select category trees and parent/child relationships elegantly. It has the limitation, however, that upon inserting new categories the whole tree may have to be recalculated, and that knowing the approximate size of tree in advance is useful. At any rate, hierarchical data in SQL is not trivial by itself, so, whatever you do, you will probably have to do quite some custom coding. A: Take a look at the django-treebeard app. A: "Is there any better way to do this?" Not really. Hierarchies are hard in the relational model. Nothing makes the easier except giving up on SQL entirely. "write the selection mechanism into my template by looping through pruned_parent_list to get the options" -- probably not optimal. This should happen in your view. A: If I understand your predicament correctly, the problem itself lies with the way you're dealing with which categories can be parents and which ones can't. One option to avoid these problems is to actually limit the level of categories which can become parents. For example, let's say you have the following categories: Internet Google Yahoo Offline MS Office OpenOffice The way I usually handle this is I obviously have a parent_id FK on the categories table. For the root elements (Internet, Offline), the parent_id would be 0. So, when in your view you're trying to retrieve the "parent categories" for the dropdown, you need to decide how far down can they keep nesting. I mostly limit this to the first level, so to choose which categories to show in your dropdown, you'd do something like: parents = Category.objects.filter(parent_id=0) Now obviously, this limits the approach somewhat, but you can increase the level you'd like to include and work out some kind of visual identification system in your template for the dropdown (including extra spaces or dashes for each level in the hierarchy or something). Anyway, sorry about the long response, and hopefully this addressed your issue somewhat. A: I am not sure if this is better (interaction-wise or otherwise) but... You can check hierarchical integrity on save and raise an error if necessary. Ideally for such a data type I would like to see a tree of instances on the side. Or at least the full ancestory on the object detail view. In both cases you'd already have done the extra trip mentioned to the database.
ForeignKey form restrictions in Django
I'm using Django to write a blog app, and I'm trying to implement a hierarchical category structure. Each category has a "parent" ForeignKey pointing back to the same Category model. I want to allow admins to add categories, and I want the interface to allow them to select a category's parent category. However, I want to avoid I'm-my-own-grandpa situations, so I want to limit the available choices of categories to those which do not have category in question as an ancestor. Right now, I'm controlling this from the view: parent_candidates = list(Category.objects.all()) pruned_parent_list = [cat for cat in parent_candidates if instance.id not in cat.getHierarchy()] where instance is the category being edited and getHierarchy() is a method to get a list of ancestor ids. There are a number of problems with this approach. In particular, it uses an extra database hit to get the list of all categories and it makes me write the selection mechanism into my template by looping through pruned_parent_list to get the options, when I'd really rather just specify a widget. Is there any better way to do this? I know I can add custom validation on the back-end to prevent this, but why give users the option?
[ "I have had to deal with arbitrary-depth categories on SQL and it seems not well suited for storing data of this type in a normal form, as nested queries and/or multiple JOINs tend to get ugly extremely quickly.\nThis is almost the only case where I would go with a sort of improper solution, namely to store categories in string form, subcategories separated by a delimiter. It makes both database queries and other operations much more trivial.\nCategories table would look something like this:\nid name\n1 Internet\n2 Internet/Google\n3 Internet/Yahoo\n4 Offline\n5 Offline/MS Office/MS Excel\n6 Offline/Openoffice\n\nAnother solution is, that depending on your expected usage, you can maybe implement binary tree in the category list. That allows to select category trees and parent/child relationships elegantly. It has the limitation, however, that upon inserting new categories the whole tree may have to be recalculated, and that knowing the approximate size of tree in advance is useful.\nAt any rate, hierarchical data in SQL is not trivial by itself, so, whatever you do, you will probably have to do quite some custom coding.\n", "Take a look at the django-treebeard app.\n", "\"Is there any better way to do this?\" Not really. Hierarchies are hard in the relational model. Nothing makes the easier except giving up on SQL entirely.\n\"write the selection mechanism into my template by looping through pruned_parent_list to get the options\" -- probably not optimal. This should happen in your view.\n", "If I understand your predicament correctly, the problem itself lies with the way you're dealing with which categories can be parents and which ones can't. One option to avoid these problems is to actually limit the level of categories which can become parents. For example, let's say you have the following categories:\n\nInternet\n\n\nGoogle\nYahoo\n\nOffline\n\n\nMS Office\nOpenOffice\n\n\nThe way I usually handle this is I obviously have a parent_id FK on the categories table. For the root elements (Internet, Offline), the parent_id would be 0. So, when in your view you're trying to retrieve the \"parent categories\" for the dropdown, you need to decide how far down can they keep nesting. I mostly limit this to the first level, so to choose which categories to show in your dropdown, you'd do something like:\nparents = Category.objects.filter(parent_id=0)\n\nNow obviously, this limits the approach somewhat, but you can increase the level you'd like to include and work out some kind of visual identification system in your template for the dropdown (including extra spaces or dashes for each level in the hierarchy or something).\nAnyway, sorry about the long response, and hopefully this addressed your issue somewhat.\n", "I am not sure if this is better (interaction-wise or otherwise) but...\nYou can check hierarchical integrity on save and raise an error if necessary.\nIdeally for such a data type I would like to see a tree of instances on the side. Or at least the full ancestory on the object detail view. In both cases you'd already have done the extra trip mentioned to the database.\n" ]
[ 1, 1, 0, 0, 0 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0000401118_django_django_forms_python.txt
Q: Hiding implementation details on an email templating system written in Python I am writing an application where one of the features is to allow the user to write an email template using Markdown syntax. Besides formatting, the user must be able to use placeholders for a couple of variables that would get replaced at runtime. The way this is currently working is very simple: the templates have the Pythonic %(var)s placeholders and I replace those with a dictionary before applying Markdown2 formatting. Turns out that the end user of this system will be a tech-savvy user and I wouldn't like to make it obvious to everyone that it's written in Python. It's not that I don't like Python... I actually think Python is the perfect tool for the job, I just don't want to expose that to the user (would like the same even if it were written in Java, Perl, Ruby or anything else). So I'd like to ask for insights on what would be, in your opinion, the best way to expose placeholders for the users: What do you think is the best placeholder format (thinks like ${var}, $(var) or #{var})? What would be the best way to replace those placeholders? I though of using a Regular Expression to change - for instance - ${var} into %(var)s and then applying the regular Python templating substitution, but I am not sure that's the best approach. If you go that way, it would be very nice if you could indicate me what is a draft of that regular expression as well. Thanks! Update: An user pointed out using full-blown templating systems, but I think that may not be worth it, since all I need is placeholders substitution: I won't have loops or anything like that. Final Update: I have chosen not to use any template engines at this time. I chose to go with the simpler string.Template approach (as pointed out on a comment by hyperboreean). Truth is that I don't like to pick a solution because sometime in the future there may be a need. I will keep all those suggestions on my sleeve, and if on the lifespan of the application there is a clear need for one or more features offered by them, I'll revisit the idea. Right now, I really think it's an overkill. Having full blown templates that the end user can edit as he wants is, at least on my point of view, more trouble than benefit. Nevertheless, it feels much nicer being aware of the reasons I did not went down that path, than just not researching anything and choosing it. Thanks a lot for all the input. A: Use a real template tool: mako or jinja. Don't roll your own. Not worth it. A: Have a light templating system ... I am not sure if you can use some of the ones TurboGears provides (Kid or Genshi) A: I would recommend jinja2. It shouldn't create runtime performance issue since it compiles templates to python. It would offer much greater flexibility. As for maintainability; it depends much on the coder, but theoretically (and admittedly superficially) I can't see why it should be harder to maintain. With a little more work you can give your tech-savvy user the ability to define the substitution style herself. Or choose one from defaults you supply. A: You could try Python 2.6/3.0's new str.format() method: http://docs.python.org/library/string.html#formatstrings This looks a bit different to %-formatting and might not be as instantly recognisable as Python: 'fish{chips}'.format(chips= 'x')
Hiding implementation details on an email templating system written in Python
I am writing an application where one of the features is to allow the user to write an email template using Markdown syntax. Besides formatting, the user must be able to use placeholders for a couple of variables that would get replaced at runtime. The way this is currently working is very simple: the templates have the Pythonic %(var)s placeholders and I replace those with a dictionary before applying Markdown2 formatting. Turns out that the end user of this system will be a tech-savvy user and I wouldn't like to make it obvious to everyone that it's written in Python. It's not that I don't like Python... I actually think Python is the perfect tool for the job, I just don't want to expose that to the user (would like the same even if it were written in Java, Perl, Ruby or anything else). So I'd like to ask for insights on what would be, in your opinion, the best way to expose placeholders for the users: What do you think is the best placeholder format (thinks like ${var}, $(var) or #{var})? What would be the best way to replace those placeholders? I though of using a Regular Expression to change - for instance - ${var} into %(var)s and then applying the regular Python templating substitution, but I am not sure that's the best approach. If you go that way, it would be very nice if you could indicate me what is a draft of that regular expression as well. Thanks! Update: An user pointed out using full-blown templating systems, but I think that may not be worth it, since all I need is placeholders substitution: I won't have loops or anything like that. Final Update: I have chosen not to use any template engines at this time. I chose to go with the simpler string.Template approach (as pointed out on a comment by hyperboreean). Truth is that I don't like to pick a solution because sometime in the future there may be a need. I will keep all those suggestions on my sleeve, and if on the lifespan of the application there is a clear need for one or more features offered by them, I'll revisit the idea. Right now, I really think it's an overkill. Having full blown templates that the end user can edit as he wants is, at least on my point of view, more trouble than benefit. Nevertheless, it feels much nicer being aware of the reasons I did not went down that path, than just not researching anything and choosing it. Thanks a lot for all the input.
[ "Use a real template tool: mako or jinja. Don't roll your own. Not worth it.\n", "Have a light templating system ... I am not sure if you can use some of the ones TurboGears provides (Kid or Genshi)\n", "I would recommend jinja2.\nIt shouldn't create runtime performance issue since it compiles templates to python. It would offer much greater flexibility. As for maintainability; it depends much on the coder, but theoretically (and admittedly superficially) I can't see why it should be harder to maintain.\nWith a little more work you can give your tech-savvy user the ability to define the substitution style herself. Or choose one from defaults you supply.\n", "You could try Python 2.6/3.0's new str.format() method: http://docs.python.org/library/string.html#formatstrings\nThis looks a bit different to %-formatting and might not be as instantly recognisable as Python:\n'fish{chips}'.format(chips= 'x')\n\n" ]
[ 6, 2, 1, 0 ]
[]
[]
[ "email", "formatting", "python", "templates" ]
stackoverflow_0000405509_email_formatting_python_templates.txt
Q: Most pythonic form for mapping a series of statements? This is something that has bugged me for some time. I learnt Haskell before I learnt Python, so I've always been fond of thinking of many computations as a mapping onto a list. This is beautifully expressed by a list comprehension (I'm giving the pythonic version here): result = [ f(x) for x in list ] In many cases though, we want to execute more than a single statement on x, say: result = [ f(g(h(x))) for x in list ] This very quickly gets clunky, and difficult to read. My normal solution to this is to expand this back into a for loop: result = [] for x in list: x0 = h(x) x1 = g(x0) x2 = f(x1) result.append(x2) One thing about this that bothers me no end is having to initialize the empty list 'result'. It's a triviality, but it makes me unhappy. I was wondering if there were any alternative equivalent forms. One way may be to use a local function(is that what they're called in Python?) def operation(x): x0 = h(x) x1 = g(x0) x2 = f(x1) return x2 result = [ operation(x) for x in list ] Are there any particular advantages/disadvantages to either of the two forms above? Or is there perhaps a more elegant way? A: You can easily do function composition in Python. Here's a demonstrates of a way to create a new function which is a composition of existing functions. >>> def comp( a, b ): def compose( args ): return a( b( args ) ) return compose >>> def times2(x): return x*2 >>> def plus1(x): return x+1 >>> comp( times2, plus1 )(32) 66 Here's a more complete recipe for function composition. This should make it look less clunky. A: Follow the style that most matches your tastes. I would not worry about performance; only in case you really see some issue you can try to move to a different style. Here some other possible suggestions, in addition to your proposals: result = [f( g( h(x) ) ) for x in list] Use progressive list comprehensions: result = [h(x) for x in list] result = [g(x) for x in result] result = [f(x) for x in result] Again, that's only a matter of style and taste. Pick the one you prefer most, and stick with it :-) A: If this is something you're doing often and with several different statements you could write something like def seriesoffncs(fncs,x): for f in fncs[::-1]: x=f(x) return x where fncs is a list of functions. so seriesoffncs((f,g,h),x) would return f(g(h(x))). This way if you later in your code need to workout h(q(g(f(x)))) you would simply do seriesoffncs((h,q,g,f),x) rather than make a new operations function for each combination of functions. A: If your only concerned with the last result, your last answer is the best. It's clear for anyone looking at it what your doing. I often take any code that starts to get complex and move it to a function. This basically serves as a comment for that block of code. (any complex code probably needs a re-write anyway, and putting it in a function I can go back and work on it later) def operation(x): x0 = h(x) x1 = g(x0) x2 = f(x1) return x2 result = [ operation(x) for x in list] A: A variation of dagw.myopenid.com's function: def chained_apply(*args): val = args[-1] for f in fncs[:-1:-1]: val=f(val) return val Instead of seriesoffncs((h,q,g,f),x) now you can call: result = chained_apply(foo, bar, baz, x) A: As far as I know there's no built-in/native syntax for composition in Python, but you can write your own function to compose stuff without too much trouble. def compose(*f): return f[0] if len(f) == 1 else lambda *args: f[0](compose(*f[1:])(*args)) def f(x): return 'o ' + str(x) def g(x): return 'hai ' + str(x) def h(x, y): return 'there ' + str(x) + str(y) + '\n' action = compose(f, g, h) print [action("Test ", item) for item in [1, 2, 3]] Composing outside the comprehension isn't required, of course. print [compose(f, g, h)("Test ", item) for item in [1, 2, 3]] This way of composing will work for any number of functions (well, up to the recursion limit) with any number of parameters for the inner function. A: There are cases where it's best to go back to the for-loop, yes, but more often I prefer one of these approaches: Use appropriate line breaks and indentation to keep it readable: result = [blah(blah(blah(x))) for x in list] Or extract (enough of) the logic into another function, as you mention. But not necessarily local; Python programmers prefer flat to nested structure, if you can see a reasonable way of factoring the functionality out. I came to Python from the functional-programming world, too, and share your prejudice.
Most pythonic form for mapping a series of statements?
This is something that has bugged me for some time. I learnt Haskell before I learnt Python, so I've always been fond of thinking of many computations as a mapping onto a list. This is beautifully expressed by a list comprehension (I'm giving the pythonic version here): result = [ f(x) for x in list ] In many cases though, we want to execute more than a single statement on x, say: result = [ f(g(h(x))) for x in list ] This very quickly gets clunky, and difficult to read. My normal solution to this is to expand this back into a for loop: result = [] for x in list: x0 = h(x) x1 = g(x0) x2 = f(x1) result.append(x2) One thing about this that bothers me no end is having to initialize the empty list 'result'. It's a triviality, but it makes me unhappy. I was wondering if there were any alternative equivalent forms. One way may be to use a local function(is that what they're called in Python?) def operation(x): x0 = h(x) x1 = g(x0) x2 = f(x1) return x2 result = [ operation(x) for x in list ] Are there any particular advantages/disadvantages to either of the two forms above? Or is there perhaps a more elegant way?
[ "You can easily do function composition in Python. \nHere's a demonstrates of a way to create a new function which is a composition of existing functions.\n>>> def comp( a, b ):\n def compose( args ):\n return a( b( args ) )\n return compose\n\n>>> def times2(x): return x*2\n\n>>> def plus1(x): return x+1\n\n>>> comp( times2, plus1 )(32)\n66\n\nHere's a more complete recipe for function composition. This should make it look less clunky.\n", "Follow the style that most matches your tastes.\nI would not worry about performance; only in case you really see some issue you can try to move to a different style.\nHere some other possible suggestions, in addition to your proposals:\nresult = [f(\n g(\n h(x)\n )\n )\n for x in list]\n\nUse progressive list comprehensions:\nresult = [h(x) for x in list]\nresult = [g(x) for x in result]\nresult = [f(x) for x in result]\n\nAgain, that's only a matter of style and taste. Pick the one you prefer most, and stick with it :-)\n", "If this is something you're doing often and with several different statements you could write something like\ndef seriesoffncs(fncs,x):\n for f in fncs[::-1]:\n x=f(x)\n return x\n\nwhere fncs is a list of functions. so seriesoffncs((f,g,h),x) would return \nf(g(h(x))).\nThis way if you later in your code need to workout h(q(g(f(x)))) you would simply do seriesoffncs((h,q,g,f),x) rather than make a new operations function for each combination of functions.\n", "If your only concerned with the last result, your last answer is the best. It's clear for anyone looking at it what your doing. \nI often take any code that starts to get complex and move it to a function. This basically serves as a comment for that block of code. (any complex code probably needs a re-write anyway, and putting it in a function I can go back and work on it later)\ndef operation(x):\n x0 = h(x)\n x1 = g(x0)\n x2 = f(x1)\n return x2\nresult = [ operation(x) for x in list]\n\n", "A variation of dagw.myopenid.com's function:\ndef chained_apply(*args):\n val = args[-1]\n for f in fncs[:-1:-1]:\n val=f(val)\n return val\n\nInstead of seriesoffncs((h,q,g,f),x) now you can call:\nresult = chained_apply(foo, bar, baz, x)\n\n", "As far as I know there's no built-in/native syntax for composition in Python, but you can write your own function to compose stuff without too much trouble.\ndef compose(*f):\n return f[0] if len(f) == 1 else lambda *args: f[0](compose(*f[1:])(*args))\n\ndef f(x): \n return 'o ' + str(x)\n\ndef g(x): \n return 'hai ' + str(x)\n\ndef h(x, y): \n return 'there ' + str(x) + str(y) + '\\n'\n\naction = compose(f, g, h)\nprint [action(\"Test \", item) for item in [1, 2, 3]]\n\nComposing outside the comprehension isn't required, of course.\nprint [compose(f, g, h)(\"Test \", item) for item in [1, 2, 3]]\n\nThis way of composing will work for any number of functions (well, up to the recursion limit) with any number of parameters for the inner function.\n", "There are cases where it's best to go back to the for-loop, yes, but more often I prefer one of these approaches:\nUse appropriate line breaks and indentation to keep it readable:\nresult = [blah(blah(blah(x)))\n for x in list]\n\nOr extract (enough of) the logic into another function, as you mention. But not necessarily local; Python programmers prefer flat to nested structure, if you can see a reasonable way of factoring the functionality out.\nI came to Python from the functional-programming world, too, and share your prejudice.\n" ]
[ 5, 3, 2, 1, 1, 1, 0 ]
[]
[]
[ "coding_style", "idioms", "python" ]
stackoverflow_0000352076_coding_style_idioms_python.txt
Q: How to intercept special (alt / ctrl) key press? How can I catch key combinations like ALT+K or CTRL+ALT+H in python curses? A: A terminal converts the control key in combination with a letter key to a normal ASCII code. This can be read from the getch() function like any other key press. CTRL-A: getch() returns 1 CTRL-B: getch() returns 2 ... CTRL-Z: getch() returns 26 Also, the keypad() function must be called to enable other special function keys (e.g. left arrow, F1, home, etc). I don't believe there is a portable way to receive meta-keys (e.g. ALT-H) through a terminal. Some send an escape (0x1B) followed by the modified key while others set the high-bit and only send one byte.
How to intercept special (alt / ctrl) key press?
How can I catch key combinations like ALT+K or CTRL+ALT+H in python curses?
[ "A terminal converts the control key in combination with a letter key to a normal ASCII code. This can be read from the getch() function like any other key press.\nCTRL-A: getch() returns 1\nCTRL-B: getch() returns 2\n...\nCTRL-Z: getch() returns 26\n\nAlso, the keypad() function must be called to enable other special function keys (e.g. left arrow, F1, home, etc).\nI don't believe there is a portable way to receive meta-keys (e.g. ALT-H) through a terminal. Some send an escape (0x1B) followed by the modified key while others set the high-bit and only send one byte.\n" ]
[ 12 ]
[]
[]
[ "curses", "python" ]
stackoverflow_0000406933_curses_python.txt
Q: Floating Point Limitations My code: a = '2.3' I wanted to display a as a floating point value. Since a is a string, I tried: float(a) The result I got was : 2.2999999999999998 I want a solution for this problem. Please, kindly help me. I was following this tutorial. A: I think it reflects more on your understanding of floating point types than on Python. See my article about floating point numbers (.NET-based, but still relevant) for the reasons behind this "inaccuracy". If you need to keep the exact decimal representation, you should use the decimal module. A: This is not a drawback of python, rather, it is a drawback of the way floating point numbers are stored on a computer. Regardless of implementation language, you will find similar problems. You say that you want to 'display' A as a floating point, why not just display the string? Visually it will be identical to what you expect. As Jon mentioned, if your needs are more than just 'displaying' the floating point number, you should use the decimal module to store the exact representation. A: Excellent answers explaining reasons. I just wish to add a possible practical solution from the standard library: >>> from decimal import Decimal >>> a = Decimal('2.3') >>> print a 2.3 This is actually a (very) F.A.Q. for Python and you can read the answer here. Edit: I just noticed that John Skeet already mentioned this. Oh well...
Floating Point Limitations
My code: a = '2.3' I wanted to display a as a floating point value. Since a is a string, I tried: float(a) The result I got was : 2.2999999999999998 I want a solution for this problem. Please, kindly help me. I was following this tutorial.
[ "I think it reflects more on your understanding of floating point types than on Python. See my article about floating point numbers (.NET-based, but still relevant) for the reasons behind this \"inaccuracy\". If you need to keep the exact decimal representation, you should use the decimal module.\n", "This is not a drawback of python, rather, it is a drawback of the way floating point numbers are stored on a computer. Regardless of implementation language, you will find similar problems.\nYou say that you want to 'display' A as a floating point, why not just display the string? Visually it will be identical to what you expect.\nAs Jon mentioned, if your needs are more than just 'displaying' the floating point number, you should use the decimal module to store the exact representation.\n", "Excellent answers explaining reasons. I just wish to add a possible practical solution from the standard library:\n>>> from decimal import Decimal\n>>> a = Decimal('2.3')\n>>> print a\n2.3\n\nThis is actually a (very) F.A.Q. for Python and you can read the answer here.\n\nEdit: I just noticed that John Skeet already mentioned this. Oh well...\n" ]
[ 19, 6, 5 ]
[]
[]
[ "floating_accuracy", "floating_point", "precision", "python" ]
stackoverflow_0000406361_floating_accuracy_floating_point_precision_python.txt
Q: How to synchronize the same object on client and server side in client-server application? Is small messages framework good for this job? I'm making a game engine in c++ and python. I'm using OGRE for 3D rendering, OpenAL for sound, ODE for physics, OIS for input, HawkNL for networking and boost.python for embedded python interpreter. Every subsystem (library) is wrapped by a class - manager and every manager is singleton. Now, I have a class - Object - this could be every visible object in game world. This is some kind of mix, object has graphics representation (entity) and representation in physics simulator (solid). These two are most important here. Class Object is just pure abstract base class - interface. I've decided to implement Object on client side as ObjectClientSide - this implementation has the entity, and on server side as ObjectServerSide - this implementation has the solid. Physics simulator runs only on server, and rendering is done only on client of course. The object can exist only when both implementations are working together. Every object has unique id and both instances of the same object on client and server side have the same id. So, after this short background, my first question is: is this design good? How can I make it better? And the main question: how should I synchronize these objects? Next, both implementations have the same interface, but part of it is implemented on server side and part on client side. So, for example, if player wants to move forward his character he should send a request to object on server. The server then makes changes to simulation and sends updated position to client. For that reason, I've created small messages framework. There is a Message class, Router, Rule and rules inherited from Rule. When message arrives, Router checks it against the rules and sends it to destination. So, when I call myObjectInstanceOnClientSide->setPosition(x,y,z) this object creates Message, its content is function and parameters and destination is object with the same id on server. When object with the same id on server side gets this message it calls this function with given arguments. So, when a function can't be implemented on one side it creates a message and sends it to object on the other side. I think this can be very useful in scripts. Scripts can be very clean, if script needs for example turn on animation on clients, I only need to call this function on server's local object - the rest is in background. So, is this ok? Am I wrong about this? It this common solution? A: It sounds like you would be sending a lot of tiny messages. The UDP and IP headers will add 28 bytes of overhead (20 bytes for the IPv4 header or 40 for IPv6 plus 8 bytes for the UDP header). So, I would suggest combining multiple messages to be dispatched together at a perioidic rate. You may also want to read these other questions and answers: Dealing with Latency in Networked Games Real-time multiplayer game (concept question) I added a bunch of useful links to the DevMaster.net Wiki years ago that are still relavent: Networking for Games 101 FAQ Multiplayer and Network Programming Introduction to Multiplayer Game Programming The Quake3 Networking Model Unreal Networking Architecture Networked Physics Beej's Network Guide I'd suggest starting to read Glenn Fiedler's blog. He's done some incredibly work with networked physics including the recent Mercenaries 2 release. He started a series of articles called Networking for Game Programmers.
How to synchronize the same object on client and server side in client-server application? Is small messages framework good for this job?
I'm making a game engine in c++ and python. I'm using OGRE for 3D rendering, OpenAL for sound, ODE for physics, OIS for input, HawkNL for networking and boost.python for embedded python interpreter. Every subsystem (library) is wrapped by a class - manager and every manager is singleton. Now, I have a class - Object - this could be every visible object in game world. This is some kind of mix, object has graphics representation (entity) and representation in physics simulator (solid). These two are most important here. Class Object is just pure abstract base class - interface. I've decided to implement Object on client side as ObjectClientSide - this implementation has the entity, and on server side as ObjectServerSide - this implementation has the solid. Physics simulator runs only on server, and rendering is done only on client of course. The object can exist only when both implementations are working together. Every object has unique id and both instances of the same object on client and server side have the same id. So, after this short background, my first question is: is this design good? How can I make it better? And the main question: how should I synchronize these objects? Next, both implementations have the same interface, but part of it is implemented on server side and part on client side. So, for example, if player wants to move forward his character he should send a request to object on server. The server then makes changes to simulation and sends updated position to client. For that reason, I've created small messages framework. There is a Message class, Router, Rule and rules inherited from Rule. When message arrives, Router checks it against the rules and sends it to destination. So, when I call myObjectInstanceOnClientSide->setPosition(x,y,z) this object creates Message, its content is function and parameters and destination is object with the same id on server. When object with the same id on server side gets this message it calls this function with given arguments. So, when a function can't be implemented on one side it creates a message and sends it to object on the other side. I think this can be very useful in scripts. Scripts can be very clean, if script needs for example turn on animation on clients, I only need to call this function on server's local object - the rest is in background. So, is this ok? Am I wrong about this? It this common solution?
[ "It sounds like you would be sending a lot of tiny messages. The UDP and IP headers will add 28 bytes of overhead (20 bytes for the IPv4 header or 40 for IPv6 plus 8 bytes for the UDP header). So, I would suggest combining multiple messages to be dispatched together at a perioidic rate.\nYou may also want to read these other questions and answers:\n\nDealing with Latency in Networked Games\nReal-time multiplayer game (concept question)\n\nI added a bunch of useful links to the DevMaster.net Wiki years ago that are still relavent:\n\nNetworking for Games 101 FAQ\nMultiplayer and Network Programming\nIntroduction to Multiplayer Game\nProgramming The Quake3 Networking Model\nUnreal Networking Architecture\nNetworked Physics\nBeej's Network Guide\n\nI'd suggest starting to read Glenn Fiedler's blog. He's done some incredibly work with networked physics including the recent Mercenaries 2 release. He started a series of articles called Networking for Game Programmers.\n" ]
[ 7 ]
[]
[]
[ "c++", "oop", "python" ]
stackoverflow_0000407464_c++_oop_python.txt
Q: Prevent Python subprocess from passing fds on Windows? Python's subprocess module by default passes all open file descriptors to any child processes it spawns. This means that if the parent process is listening on a port, and is killed, it cannot restart and begin listening again (even using SO_REUSEADDR) because the child is still in possession of that descriptor. I have no control over the child process. The subprocess POpen constructor does accept a close_fds argument, which would close descriptors on the child, just as I want. However, there is a restriction, only on Windows, that prevents it from being used if stdin/stdout are also overridden, which I need to do. Does anyone know of a work-around for this on Windows? A: What seems to be the most relevant information that I can find: SetHandleInformation, referenced in this article, should give you pointers. You'll probably need to use pywin32 and/or ctypes to accomplish what you want.
Prevent Python subprocess from passing fds on Windows?
Python's subprocess module by default passes all open file descriptors to any child processes it spawns. This means that if the parent process is listening on a port, and is killed, it cannot restart and begin listening again (even using SO_REUSEADDR) because the child is still in possession of that descriptor. I have no control over the child process. The subprocess POpen constructor does accept a close_fds argument, which would close descriptors on the child, just as I want. However, there is a restriction, only on Windows, that prevents it from being used if stdin/stdout are also overridden, which I need to do. Does anyone know of a work-around for this on Windows?
[ "What seems to be the most relevant information that I can find: SetHandleInformation, referenced in this article, should give you pointers.\nYou'll probably need to use pywin32 and/or ctypes to accomplish what you want.\n" ]
[ 2 ]
[ "I don't have a windows box around, so this is untested, but I'd be tempted to try the os.dup and os.dup2 methods; duplicate the file descriptors and use those instead of the parent ones.\n" ]
[ -2 ]
[ "popen", "python", "subprocess", "windows" ]
stackoverflow_0000408039_popen_python_subprocess_windows.txt
Q: Iterate over subclasses of a given class in a given module In Python, given a module X and a class Y, how can I iterate or generate a list of all subclasses of Y that exist in module X? A: Although Quamrana's suggestion works fine, there are a couple of possible improvements I'd like to suggest to make it more pythonic. They rely on using the inspect module from the standard library. You can avoid the getattr call by using inspect.getmembers() The try/catch can be avoided by using inspect.isclass() With those, you can reduce the whole thing to a single list comprehension if you like: def find_subclasses(module, clazz): return [ cls for name, cls in inspect.getmembers(module) if inspect.isclass(cls) and issubclass(cls, clazz) ] A: Here's one way to do it: import inspect def get_subclasses(mod, cls): """Yield the classes in module ``mod`` that inherit from ``cls``""" for name, obj in inspect.getmembers(mod): if hasattr(obj, "__bases__") and cls in obj.__bases__: yield obj A: Can I suggest that neither of the answers from Chris AtLee and zacherates fulfill the requirements? I think this modification to zacerates answer is better: def find_subclasses(module, clazz): for name in dir(module): o = getattr(module, name) try: if (o != clazz) and issubclass(o, clazz): yield name, o except TypeError: pass The reason I disagree with the given answers is that the first does not produce classes that are a distant subclass of the given class, and the second includes the given class. A: Given the module foo.py class foo(object): pass class bar(foo): pass class baz(foo): pass class grar(Exception): pass def find_subclasses(module, clazz): for name in dir(module): o = getattr(module, name) try: if issubclass(o, clazz): yield name, o except TypeError: pass >>> import foo >>> list(foo.find_subclasses(foo, foo.foo)) [('bar', <class 'foo.bar'>), ('baz', <class 'foo.baz'>), ('foo', <class 'foo.foo'>)] >>> list(foo.find_subclasses(foo, object)) [('bar', <class 'foo.bar'>), ('baz', <class 'foo.baz'>), ('foo', <class 'foo.foo'>), ('grar', <class 'foo.grar'>)] >>> list(foo.find_subclasses(foo, Exception)) [('grar', <class 'foo.grar'>)]
Iterate over subclasses of a given class in a given module
In Python, given a module X and a class Y, how can I iterate or generate a list of all subclasses of Y that exist in module X?
[ "Although Quamrana's suggestion works fine, there are a couple of possible improvements I'd like to suggest to make it more pythonic. They rely on using the inspect module from the standard library.\n\nYou can avoid the getattr call by using inspect.getmembers()\nThe try/catch can be avoided by using inspect.isclass()\n\nWith those, you can reduce the whole thing to a single list comprehension if you like:\ndef find_subclasses(module, clazz):\n return [\n cls\n for name, cls in inspect.getmembers(module)\n if inspect.isclass(cls) and issubclass(cls, clazz)\n ]\n\n", "Here's one way to do it:\nimport inspect\n\ndef get_subclasses(mod, cls):\n \"\"\"Yield the classes in module ``mod`` that inherit from ``cls``\"\"\"\n for name, obj in inspect.getmembers(mod):\n if hasattr(obj, \"__bases__\") and cls in obj.__bases__:\n yield obj\n\n", "Can I suggest that neither of the answers from Chris AtLee and zacherates fulfill the requirements?\nI think this modification to zacerates answer is better:\ndef find_subclasses(module, clazz):\n for name in dir(module):\n o = getattr(module, name)\n try:\n if (o != clazz) and issubclass(o, clazz):\n yield name, o\n except TypeError: pass\n\nThe reason I disagree with the given answers is that the first does not produce classes that are a distant subclass of the given class, and the second includes the given class.\n", "Given the module foo.py\nclass foo(object): pass\nclass bar(foo): pass\nclass baz(foo): pass\n\nclass grar(Exception): pass\n\ndef find_subclasses(module, clazz):\n for name in dir(module):\n o = getattr(module, name)\n\n try: \n if issubclass(o, clazz):\n yield name, o\n except TypeError: pass\n\n>>> import foo\n>>> list(foo.find_subclasses(foo, foo.foo))\n[('bar', <class 'foo.bar'>), ('baz', <class 'foo.baz'>), ('foo', <class 'foo.foo'>)]\n>>> list(foo.find_subclasses(foo, object))\n[('bar', <class 'foo.bar'>), ('baz', <class 'foo.baz'>), ('foo', <class 'foo.foo'>), ('grar', <class 'foo.grar'>)]\n>>> list(foo.find_subclasses(foo, Exception))\n[('grar', <class 'foo.grar'>)]\n\n" ]
[ 21, 14, 4, 1 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0000044352_oop_python.txt
Q: How to produce a 303 Http Response in Django? Last couple of days we were discussing at another question the best to manage randomness in a RESTful way; today I went to play a little bit with some ideas in Django only to find that there is no easy standard way of returning a 303 response (nor a 300 one, btw), that is, there doesn't seem to exist an HttpResponseSeeOther inside django.HTTP or in another place. Do you know any means for achieving this? A: You could just override HttpResponse, like the other Responses do: class HttpResponseSeeOther(HttpResponseRedirect): status_code = 303 return HttpResponseSeeOther('/other-url/') A: The generic HttpResponse object lets you specify any status code you want: response = HttpResponse(content="", status=303) response["Location"] = "http://example.com/redirect/here/" If you need something re-usable then Gerald's answer is definitely valid; simply create your own HttpResponseSeeOther class. Django only provides these specific classes for a few of the most common status codes.
How to produce a 303 Http Response in Django?
Last couple of days we were discussing at another question the best to manage randomness in a RESTful way; today I went to play a little bit with some ideas in Django only to find that there is no easy standard way of returning a 303 response (nor a 300 one, btw), that is, there doesn't seem to exist an HttpResponseSeeOther inside django.HTTP or in another place. Do you know any means for achieving this?
[ "You could just override HttpResponse, like the other Responses do:\nclass HttpResponseSeeOther(HttpResponseRedirect):\n status_code = 303\n\nreturn HttpResponseSeeOther('/other-url/')\n\n", "The generic HttpResponse object lets you specify any status code you want:\nresponse = HttpResponse(content=\"\", status=303)\nresponse[\"Location\"] = \"http://example.com/redirect/here/\"\n\nIf you need something re-usable then Gerald's answer is definitely valid; simply create your own HttpResponseSeeOther class. Django only provides these specific classes for a few of the most common status codes.\n" ]
[ 31, 21 ]
[]
[]
[ "django", "http", "python", "rest" ]
stackoverflow_0000408541_django_http_python_rest.txt
Q: In Windows, how can I enumerate and get text from another window's controls? More particularly - I have a window handle of another running application. This application contains a TListControl.UnicodeClass control somewhere (I know this from Winspector). How can I, using the Windows API and that window handle, go through all the items in that list control and get the text from all of the items? You can assume the language is C/C++, though I'll actually be using win32all for python. References to the appropriate API calls would be great. A: You want EnumWindows and EnumChildWindows for the enumeration. See here for examples and usage info/warnings. For window text, once you have the appropriate HWND, you want GetWindowText in general, and control-specific API's if the text is stored in a different place (eg: list controls). For the specific control, you will need to know the specific API, and it may not be available though just Windows API calls (for example, controls with owner-draw items can store their text in the app, not accessible to Windows). A: Above answers are completely wrong and don't even know what is a PAS. This has been answered hundreds of times for 20 years on Usenet. You must use IPC of course (RPM) ask on news://comp.os.ms-windows.programmer.win32 for code.
In Windows, how can I enumerate and get text from another window's controls?
More particularly - I have a window handle of another running application. This application contains a TListControl.UnicodeClass control somewhere (I know this from Winspector). How can I, using the Windows API and that window handle, go through all the items in that list control and get the text from all of the items? You can assume the language is C/C++, though I'll actually be using win32all for python. References to the appropriate API calls would be great.
[ "You want EnumWindows and EnumChildWindows for the enumeration. See here for examples and usage info/warnings.\nFor window text, once you have the appropriate HWND, you want GetWindowText in general, and control-specific API's if the text is stored in a different place (eg: list controls). For the specific control, you will need to know the specific API, and it may not be available though just Windows API calls (for example, controls with owner-draw items can store their text in the app, not accessible to Windows).\n", "Above answers are completely wrong and don't even know what is a PAS.\nThis has been answered hundreds of times for 20 years on Usenet.\nYou must use IPC of course (RPM)\nask on news://comp.os.ms-windows.programmer.win32 for code.\n" ]
[ 5, 2 ]
[]
[]
[ "controls", "python", "winapi", "windows" ]
stackoverflow_0000408334_controls_python_winapi_windows.txt
Q: Python mailbox encoding errors First, let me say that I'm a complete beginner at Python. I've never learned the language, I just thought "how hard can it be" when Google turned up nothing but Python snippets to solve my problem. :) I have a bunch of mailboxes in Maildir format (a backup from the mail server on my old web host), and I need to extract the emails from these. So far, the simplest way I've found has been to convert them to the mbox format, which Thunderbird supports, and it seems Python has a few classes for reading/writing both formats. Seems perfect. The Python docs even have this little code snippet doing exactly what I need: src = mailbox.Maildir('maildir', factory=None) dest = mailbox.mbox('/tmp/mbox') for msg in src: #1 dest.add(msg) #2 Except it doesn't work. And here's where my complete lack of knowledge about Python sets in. On a few messages, I get a UnicodeDecodeError during the iteration (that is, when it's trying to read msg from src, on line #1). On others, I get a UnicodeEncodeError when trying to add msg to dest (line #2). Clearly it makes some wrong assumptions about the encoding used. But I have no clue how to specify an encoding on the mailbox (For that matter, I don't know what the encoding should be either, but I can probably figure that out once I find a way to actually specify an encoding). I get stack traces similar to the following: File "E:\Python30\lib\mailbox.py", line 102, in itervalues value = self[key] File "E:\Python30\lib\mailbox.py", line 74, in __getitem__ return self.get_message(key) File "E:\Python30\lib\mailbox.py", line 317, in get_message msg = MaildirMessage(f) File "E:\Python30\lib\mailbox.py", line 1373, in __init__ Message.__init__(self, message) File "E:\Python30\lib\mailbox.py", line 1345, in __init__ self._become_message(email.message_from_file(message)) File "E:\Python30\lib\email\__init__.py", line 46, in message_from_file return Parser(*args, **kws).parse(fp) File "E:\Python30\lib\email\parser.py", line 68, in parse data = fp.read(8192) File "E:\Python30\lib\io.py", line 1733, in read eof = not self._read_chunk() File "E:\Python30\lib\io.py", line 1562, in _read_chunk self._set_decoded_chars(self._decoder.decode(input_chunk, eof)) File "E:\Python30\lib\io.py", line 1295, in decode output = self.decoder.decode(input, final=final) File "E:\Python30\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 37: character maps to <undefined> And on the UnicodeEncodeErrors: File "E:\Python30\lib\email\message.py", line 121, in __str__ return self.as_string() File "E:\Python30\lib\email\message.py", line 136, in as_string g.flatten(self, unixfrom=unixfrom) File "E:\Python30\lib\email\generator.py", line 76, in flatten self._write(msg) File "E:\Python30\lib\email\generator.py", line 108, in _write self._write_headers(msg) File "E:\Python30\lib\email\generator.py", line 141, in _write_headers header_name=h, continuation_ws='\t') File "E:\Python30\lib\email\header.py", line 189, in __init__ self.append(s, charset, errors) File "E:\Python30\lib\email\header.py", line 262, in append input_bytes = s.encode(input_charset, errors) UnicodeEncodeError: 'ascii' codec can't encode character '\xe5' in position 16: ordinal not in range(128) Anyone able to help me out here? (Suggestions for completely different solutions not involving Python are obviously welcome too. I just need a way to access get import the mails from these Maildir files. Updates: sys.getdefaultencoding returns 'utf-8' I uploaded sample messages which cause both errors. This one throws UnicodeEncodeError, and this throws UnicodeDecodeError I tried running the same script in Python2.6, and got TypeErrors instead: File "c:\python26\lib\mailbox.py", line 529, in add self._toc[self._next_key] = self._append_message(message) File "c:\python26\lib\mailbox.py", line 665, in _append_message offsets = self._install_message(message) File "c:\python26\lib\mailbox.py", line 724, in _install_message self._dump_message(message, self._file, self._mangle_from_) File "c:\python26\lib\mailbox.py", line 220, in _dump_message raise TypeError('Invalid message type: %s' % type(message)) TypeError: Invalid message type: <type 'instance'> A: Try it in Python 2.5 or 2.6 instead of 3.0. 3.0 has completely different Unicode handling and this module may not have been updated for 3.0. A: Note @Jimmy2Times could be very True in saying that this module may not be updated for 3.0. This is not an answer particularly rather a probable explanation of what is going on, why, how to reproduce it, other people can benefit from this. I am trying further to complete this answer. I have put up whatever I could find as Edit below ===== I think this is what is happening Among many other characters in your data, you have the two chars - \x9d and \xe5 and these are encoded in some encoding format say iso-8859-1. when Python 3.0 finds the encoded string it first tries to guess the encoding of the string and then decode it into unicode using the guessed encoding (the way it keeps encoded unicode strings - Link). I think its the guessing part is where it is going wrong. To show what's most likely going on - Let's say the encoding was iso-8859-1 and the wrong guess was cp1252 (as from the first traceback). The decode for \x9d fails. In [290]: unicode(u'\x9d'.encode('iso-8859-1'), 'cp1252') --------------------------------------------------------------------------- <type 'exceptions.UnicodeDecodeError'> Traceback (most recent call last) /home/jv/<ipython console> in <module>() /usr/lib/python2.5/encodings/cp1252.py in decode(self, input, errors) 13 14 def decode(self,input,errors='strict'): ---> 15 return codecs.charmap_decode(input,errors,decoding_table) 16 17 class IncrementalEncoder(codecs.IncrementalEncoder): <type 'exceptions.UnicodeDecodeError'>: 'charmap' codec can't decode byte 0x9d in position 0: character maps to <undefined> The decode for \xe5 passes but then, when the message is retrieved from Python somewhere it is trying to encode it in ascii which fails In [291]: unicode(u'\xe5'.encode('iso-8859-1'), 'cp1252').encode('ascii') --------------------------------------------------------------------------- <type 'exceptions.UnicodeEncodeError'> Traceback (most recent call last) /home/jv/<ipython console> in <module>() <type 'exceptions.UnicodeEncodeError'>: 'ascii' codec can't encode character u'\xe5' in position 0: ordinal not in range(128) ============ EDIT: Both your problems are in line #2. Where it first decodes into unicode and then encodes into ascii First do easy_install chardet The decode error: In [75]: decd=open('jalf_decode_err','r').read() In [76]: chardet.detect(decd) Out[76]: {'confidence': 0.98999999999999999, 'encoding': 'utf-8'} ##this is what is tried at the back - my guess :) In [77]: unicode(decd, 'cp1252') --------------------------------------------------------------------------- <type 'exceptions.UnicodeDecodeError'> Traceback (most recent call last) /home/jv/<ipython console> in <module>() /usr/lib/python2.5/encodings/cp1252.py in decode(self, input, errors) 13 14 def decode(self,input,errors='strict'): ---> 15 return codecs.charmap_decode(input,errors,decoding_table) 16 17 class IncrementalEncoder(codecs.IncrementalEncoder): <type 'exceptions.UnicodeDecodeError'>: 'charmap' codec can't decode byte 0x9d in position 2812: character maps to <undefined>' ##this is a FIX- this way all your messages r accepted In [78]: unicode(decd, chardet.detect(decd)['encoding']) Out[78]: u'Return-path: <root@apps2.servage.net>\nEnvelope-to: public@jalf.dk\nDelivery-date: Fri, 22 Aug 2008 16:49:53 -0400\nReceived: from [77.232.66.102] (helo=apps2.servage.net)\n\tby c1p.hostingzoom.com with esmtp (Exim 4.69)\n\t(envelope-from <root@apps2.servage.net>)\n\tid 1KWdZu-0003VX-HP\n\tfor public@jalf.dk; Fri, 22 Aug 2008 16:49:52 -0400\nReceived: from apps2.servage.net (apps2.servage.net [127.0.0.1])\n\tby apps2.servage.net (Postfix) with ESMTP id 4A87F980026\n\tfor <public@jalf.dk>; Fri, 22 Aug 2008 21:49:46 +0100 (BST)\nReceived: (from root@localhost)\n\tby apps2.servage.net (8.13.8/8.13.8/Submit) id m7MKnkrB006225;\n\tFri, 22 Aug 2008 21:49:46 +0100\nDate: Fri, 22 Aug 2008 21:49:46 +0100\nMessage-Id: <200808222049.m7MKnkrB006225@apps2.servage.net>\nTo: public@jalf.dk\nSubject: =?UTF-8?B?WW5ncmVzYWdlbnMgTnloZWRzYnJldiAyMi44LjA4?=\nFrom: Nyhedsbrev fra Yngresagen <info@yngresagen.dk>\nReply-To: info@yngresagen.dk\nContent-type: text/plain; charset=UTF-8\nX-Abuse: Servage.net Listid 16329\nMime-Version: 1.0\nX-mailer: Servage Maillist System\nX-Spam-Status: No, score=0.1\nX-Spam-Score: 1\nX-Spam-Bar: /\nX-Spam-Flag: NO\nX-ClamAntiVirus-Scanner: This mail is clean\n\n\nK\xe6re medlem\n\nH\xe5ber du har en god sommer og er klar p\xe5 at l\xe6se seneste nyt i Yngresagen. God forn\xf8jelse!\n\n\n::. KOM TIL YS-CAF\xc8 .::\nFlere og billigere ungdomsboliger, afskaf 24-\xe5rs-reglen eller hvad synes du? Yngresagen indbyder dig til en \xe5ben debat over kaffe og snacks. Yngresagens Kristian Lauta, Mette Marb\xe6k, og formand Steffen M\xf8ller fort\xe6ller om tidligere projekter og vil gerne diskutere, hvad Yngresagen skal bruge sin tid p\xe5 fremover. \nVil du diskutere et emne, du br\xe6nder for, eller vil du bare v\xe6re med p\xe5 en lytter?\nS\xe5 kom torsdag d. 28/8 kl. 17-19, Kulturhuset 44, 2200 KBH N \n \n::. VIND GAVEKORT & BLIV H\xd8RT .:: \nYngresagen har lavet et sp\xf8rgeskema, s\xe5 du har direkte mulighed for at sige din mening, og v\xe6re med til at forme Yngresagens arbejde. Brug 5 min. p\xe5 at dele dine holdninger om f.eks. uddannelse, arbejde og unges vilk\xe5r - og vind et gavekort til en musikbutik. Vi tr\xe6kker lod blandt alle svarene og finder tre heldige vindere. Sp\xf8rgeskemaet er her: www.yngresagen.dk\n\n::. YS SPARKER NORDJYLLAND I GANG .::\nNordjylland bliver Yngresagens sunde region. Her er regionsansvarlig Andreas M\xf8ller Stehr ved at starte tre projekter op: 1) L\xf8beklub, 2) F\xf8rstehj\xe6lpskursus, 3) Mad til unge-program.\nVi har brug for flere frivillige til at sparke projekterne i gang. Vi tilbyder gratis fede aktiviteter, gratis t-shirts og ture til K\xf8benhavn, hvor du kan m\xf8de andre unge i YS. Har det fanget din interesse, s\xe5 t\xf8v ikke med at kontakte os: nordjylland@yngresagen.dk tlf. 21935185. \n\n::. YNGRESAGEN I PRESSEN .::\nL\xe6s her et udsnit af sidste nyt om Yngresagen i medierne. L\xe6s og lyt mere p\xe5 hjemmesiden under \u201dYS i pressen\u201d.\n\n:: Radionyhederne: Unge skal informeres bedre om l\xe5n \nUnge ved for lidt om at l\xe5ne penge. Det udnytter banker og rejseselskaber til at give dem l\xe5n med t\xe5rnh\xf8je renter. S\xe5dan lyder det fra formand Steffen M\xf8ller fra landsforeningen Yngresagen. \n\n:: Danmarks Radio P1: Dansk Folkeparti - de \xe6ldres parti? \nHvorfor er det kun fattige \xe6ldre og ikke alle fattige, der kan s\xf8ge om at f\xe5 nedsat medielicens?\nDansk Folkepartis ungeordf\xf8rer, Karin N\xf8dgaard, og Yngresagens formand Steffen M\xf8ller debatterer medielicens, \xe6ldrecheck og indflydelse til unge \n\n:: Frederiksborg Amts Avis: Turen til Roskilde koster en holdning!\nFor at skabe et m\xf8de mellem politikere og unge fragter Yngresagen unge gratis til \xe5rets Roskilde Festival. Det sker med den s\xe5kaldte Yngrebussen, der kan l\xe6ses mere om p\xe5 www.yngrebussen.dk\n\n \n \nMed venlig hilsen \nYngresagen\n\nLandsforeningen Yngresagen\nKulturhuset Kapelvej 44\n2200 K\xf8benhavn N\n\ntlf. 29644960\ninfo@yngresagen.dk\nwww.yngresagen.dk\n\n\n-------------------------------------------------------\nUnsubscribe Link: \nhttp://apps.corecluster.net/apps/ml/r.php?l=16329&e=public%40jalf.dk%0D%0A&id=40830383\n-------------------------------------------------------\n\n' Now its in unicode so it shouldn't give you any problem. Now the encode problem: It is a problem In [129]: encd=open('jalf_encode_err','r').read() In [130]: chardet.detect(encd) Out[130]: {'confidence': 0.78187650822865284, 'encoding': 'ISO-8859-2'} #even after the unicode conversion the encoding to ascii fails - because the criteris is strict by default In [131]: unicode(encd, chardet.detect(encd)['encoding']).encode('ascii') --------------------------------------------------------------------------- <type 'exceptions.UnicodeEncodeError'> Traceback (most recent call last) /home/jv/<ipython console> in <module>() <type 'exceptions.UnicodeEncodeError'>: 'ascii' codec can't encode character u'\u0159' in position 557: ordinal not in range(128)' ##changing the criteria to ignore In [132]: unicode(encd, chardet.detect(encd)['encoding']).encode('ascii', 'ignore') Out[132]: 'Return-path: <info@kollegierneskontor.dk>\nEnvelope-to: alf@5elements.net\nDelivery-date: Tue, 21 Aug 2007 06:10:08 -0400\nReceived: from pfepc.post.tele.dk ([195.41.46.237]:52065)\n\tby c1p.hostingzoom.com with esmtp (Exim 4.66)\n\t(envelope-from <info@kollegierneskontor.dk>)\n\tid 1INQgX-0003fI-Un\n\tfor alf@5elements.net; Tue, 21 Aug 2007 06:10:08 -0400\nReceived: from local.com (ns2.datadan.dk [195.41.7.21])\n\tby pfepc.post.tele.dk (Postfix) with SMTP id ADF4C8A0086\n\tfor <alf@5elements.net>; Tue, 21 Aug 2007 12:10:04 +0200 (CEST)\nFrom: "Kollegiernes Kontor I Kbenhavn" <info@kollegierneskontor.dk>\nTo: "Jesper Alf Dam" <alf@5elements.net>\nSubject: Fornyelse af profil\nDate: Tue, 21 Aug 2007 12:10:03 +0200\nX-Mailer: Dundas Mailer Control 1.0\nMIME-Version: 1.0\nContent-Type: Multipart/Alternative;\n\tboundary="Gark=_20078211010346yhSD0hUCo"\nMessage-Id: <20070821101004.ADF4C8A0086@pfepc.post.tele.dk>\nX-Spam-Status: No, score=0.0\nX-Spam-Score: 0\nX-Spam-Bar: /\nX-Spam-Flag: NO\nX-ClamAntiVirus-Scanner: This mail is clean\n\n\n\n--Gark=_20078211010346yhSD0hUCo\nContent-Type: text/plain; charset=ISO-8859-1\nContent-Transfer-Encoding: Quoted-Printable\n\nHej Jesper Alf Dam=0D=0A=0D=0AHusk at forny din profil hos KKIK inden 28.=\n august 2007=0D=0ALog ind p=E5 din profil og benyt ikonet "forny".=0D=0A=0D=\n=0AVenlig hilsen=0D=0AKollegiernes Kontor i K=F8benhavn=0D=0A=0D=0Ahttp:/=\n/www.kollegierneskontor.dk/=0D=0A=0D=0A\n\n--Gark=_20078211010346yhSD0hUCo\nContent-Type: text/html; charset=ISO-8859-1\nContent-Transfer-Encoding: Quoted-Printable\n\n<html>=0D=0A<head>=0D=0A=0D=0A<style>=0D=0ABODY, TD {=0D=0Afont-family: v=\nerdana, arial, helvetica; font-size: 12px; color: #666666;=0D=0A}=0D=0A</=\nstyle>=0D=0A=0D=0A<title></title>=0D=0A=0D=0A</head>=0D=0A<body bgcolor=3D=\n#FFFFFF>=0D=0A<hr size=3D1 noshade>=0D=0A<table cellpadding=3D0 cellspaci=\nng=3D0 border=3D0 width=3D100%>=0D=0A<tr><td >=0D=0AHej Jesper Alf Dam<br=\n><br>Husk at forny din profil inden 28. august 2007<br>=0D=0ALog ind p=E5=\n din profil og benyt ikonet "forny".=0D=0A<br><br>=0D=0A<a href=3D"http:/=\n/www.kollegierneskontor.dk/">Klik her</a> for at logge ind.<br><br>Venlig=\n hilsen<br>Kollegiernes Kontor i K=F8benhavn=0D=0A</td></tr>=0D=0A</table=\n>=0D=0A<hr size=3D1 noshade>=0D=0A</body>=0D=0A</html>=0D=0A\n\n--Gark=_20078211010346yhSD0hUCo--\n\n' In [133]: len(encd) Out[133]: 2303 In [134]: len(unicode(encd, chardet.detect(encd)['encoding']).encode('ascii', 'ignore')) Out[134]: 2302 CAUTION: as you can see there could be minor to moderate loss of data in this procedure. So its upto the user to use it or not. so the code should look like import chardet for msg in src: msg=unicode(msg, chardet.detect(msg)['encoding']).encode('ascii', 'ignore') dest.add(msg)
Python mailbox encoding errors
First, let me say that I'm a complete beginner at Python. I've never learned the language, I just thought "how hard can it be" when Google turned up nothing but Python snippets to solve my problem. :) I have a bunch of mailboxes in Maildir format (a backup from the mail server on my old web host), and I need to extract the emails from these. So far, the simplest way I've found has been to convert them to the mbox format, which Thunderbird supports, and it seems Python has a few classes for reading/writing both formats. Seems perfect. The Python docs even have this little code snippet doing exactly what I need: src = mailbox.Maildir('maildir', factory=None) dest = mailbox.mbox('/tmp/mbox') for msg in src: #1 dest.add(msg) #2 Except it doesn't work. And here's where my complete lack of knowledge about Python sets in. On a few messages, I get a UnicodeDecodeError during the iteration (that is, when it's trying to read msg from src, on line #1). On others, I get a UnicodeEncodeError when trying to add msg to dest (line #2). Clearly it makes some wrong assumptions about the encoding used. But I have no clue how to specify an encoding on the mailbox (For that matter, I don't know what the encoding should be either, but I can probably figure that out once I find a way to actually specify an encoding). I get stack traces similar to the following: File "E:\Python30\lib\mailbox.py", line 102, in itervalues value = self[key] File "E:\Python30\lib\mailbox.py", line 74, in __getitem__ return self.get_message(key) File "E:\Python30\lib\mailbox.py", line 317, in get_message msg = MaildirMessage(f) File "E:\Python30\lib\mailbox.py", line 1373, in __init__ Message.__init__(self, message) File "E:\Python30\lib\mailbox.py", line 1345, in __init__ self._become_message(email.message_from_file(message)) File "E:\Python30\lib\email\__init__.py", line 46, in message_from_file return Parser(*args, **kws).parse(fp) File "E:\Python30\lib\email\parser.py", line 68, in parse data = fp.read(8192) File "E:\Python30\lib\io.py", line 1733, in read eof = not self._read_chunk() File "E:\Python30\lib\io.py", line 1562, in _read_chunk self._set_decoded_chars(self._decoder.decode(input_chunk, eof)) File "E:\Python30\lib\io.py", line 1295, in decode output = self.decoder.decode(input, final=final) File "E:\Python30\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 37: character maps to <undefined> And on the UnicodeEncodeErrors: File "E:\Python30\lib\email\message.py", line 121, in __str__ return self.as_string() File "E:\Python30\lib\email\message.py", line 136, in as_string g.flatten(self, unixfrom=unixfrom) File "E:\Python30\lib\email\generator.py", line 76, in flatten self._write(msg) File "E:\Python30\lib\email\generator.py", line 108, in _write self._write_headers(msg) File "E:\Python30\lib\email\generator.py", line 141, in _write_headers header_name=h, continuation_ws='\t') File "E:\Python30\lib\email\header.py", line 189, in __init__ self.append(s, charset, errors) File "E:\Python30\lib\email\header.py", line 262, in append input_bytes = s.encode(input_charset, errors) UnicodeEncodeError: 'ascii' codec can't encode character '\xe5' in position 16: ordinal not in range(128) Anyone able to help me out here? (Suggestions for completely different solutions not involving Python are obviously welcome too. I just need a way to access get import the mails from these Maildir files. Updates: sys.getdefaultencoding returns 'utf-8' I uploaded sample messages which cause both errors. This one throws UnicodeEncodeError, and this throws UnicodeDecodeError I tried running the same script in Python2.6, and got TypeErrors instead: File "c:\python26\lib\mailbox.py", line 529, in add self._toc[self._next_key] = self._append_message(message) File "c:\python26\lib\mailbox.py", line 665, in _append_message offsets = self._install_message(message) File "c:\python26\lib\mailbox.py", line 724, in _install_message self._dump_message(message, self._file, self._mangle_from_) File "c:\python26\lib\mailbox.py", line 220, in _dump_message raise TypeError('Invalid message type: %s' % type(message)) TypeError: Invalid message type: <type 'instance'>
[ "Try it in Python 2.5 or 2.6 instead of 3.0. 3.0 has completely different Unicode handling and this module may not have been updated for 3.0. \n", "Note \n\n@Jimmy2Times could be very True in saying that this module may not be updated for 3.0.\nThis is not an answer particularly rather a probable explanation of what is going on, why, how to reproduce it, other people can benefit from this. I am trying further to complete this answer.\n\nI have put up whatever I could find as Edit below\n=====\nI think this is what is happening\nAmong many other characters in your data, you have the two chars - \\x9d and \\xe5 and these are encoded in some encoding format say iso-8859-1.\nwhen Python 3.0 finds the encoded string it first tries to guess the encoding of the string and then decode it into unicode using the guessed encoding (the way it keeps encoded unicode strings - Link). \nI think its the guessing part is where it is going wrong. \nTo show what's most likely going on - \nLet's say the encoding was iso-8859-1 and the wrong guess was cp1252 (as from the first traceback).\nThe decode for \\x9d fails.\nIn [290]: unicode(u'\\x9d'.encode('iso-8859-1'), 'cp1252')\n---------------------------------------------------------------------------\n<type 'exceptions.UnicodeDecodeError'> Traceback (most recent call last)\n\n/home/jv/<ipython console> in <module>()\n\n/usr/lib/python2.5/encodings/cp1252.py in decode(self, input, errors)\n 13 \n 14 def decode(self,input,errors='strict'):\n---> 15 return codecs.charmap_decode(input,errors,decoding_table)\n 16 \n 17 class IncrementalEncoder(codecs.IncrementalEncoder):\n\n<type 'exceptions.UnicodeDecodeError'>: 'charmap' codec can't decode byte 0x9d in position 0: character maps to <undefined>\n\nThe decode for \\xe5 passes but then, when the message is retrieved from Python somewhere it is trying to encode it in ascii which fails\nIn [291]: unicode(u'\\xe5'.encode('iso-8859-1'), 'cp1252').encode('ascii')\n---------------------------------------------------------------------------\n<type 'exceptions.UnicodeEncodeError'> Traceback (most recent call last)\n\n/home/jv/<ipython console> in <module>()\n\n<type 'exceptions.UnicodeEncodeError'>: 'ascii' codec can't encode character u'\\xe5' in position 0: ordinal not in range(128)\n\n============\nEDIT:\nBoth your problems are in line #2. Where it first decodes into unicode and then encodes into ascii\nFirst do easy_install chardet\nThe decode error:\nIn [75]: decd=open('jalf_decode_err','r').read()\n\nIn [76]: chardet.detect(decd)\nOut[76]: {'confidence': 0.98999999999999999, 'encoding': 'utf-8'}\n##this is what is tried at the back - my guess :)\nIn [77]: unicode(decd, 'cp1252') \n---------------------------------------------------------------------------\n<type 'exceptions.UnicodeDecodeError'> Traceback (most recent call last)\n\n/home/jv/<ipython console> in <module>()\n\n/usr/lib/python2.5/encodings/cp1252.py in decode(self, input, errors)\n 13 \n 14 def decode(self,input,errors='strict'):\n---> 15 return codecs.charmap_decode(input,errors,decoding_table)\n 16 \n 17 class IncrementalEncoder(codecs.IncrementalEncoder):\n\n<type 'exceptions.UnicodeDecodeError'>: 'charmap' codec can't decode byte 0x9d in position 2812: character maps to <undefined>'\n\n##this is a FIX- this way all your messages r accepted\nIn [78]: unicode(decd, chardet.detect(decd)['encoding']) \nOut[78]: u'Return-path: <root@apps2.servage.net>\\nEnvelope-to: public@jalf.dk\\nDelivery-date: Fri, 22 Aug 2008 16:49:53 -0400\\nReceived: from [77.232.66.102] (helo=apps2.servage.net)\\n\\tby c1p.hostingzoom.com with esmtp (Exim 4.69)\\n\\t(envelope-from <root@apps2.servage.net>)\\n\\tid 1KWdZu-0003VX-HP\\n\\tfor public@jalf.dk; Fri, 22 Aug 2008 16:49:52 -0400\\nReceived: from apps2.servage.net (apps2.servage.net [127.0.0.1])\\n\\tby apps2.servage.net (Postfix) with ESMTP id 4A87F980026\\n\\tfor <public@jalf.dk>; Fri, 22 Aug 2008 21:49:46 +0100 (BST)\\nReceived: (from root@localhost)\\n\\tby apps2.servage.net (8.13.8/8.13.8/Submit) id m7MKnkrB006225;\\n\\tFri, 22 Aug 2008 21:49:46 +0100\\nDate: Fri, 22 Aug 2008 21:49:46 +0100\\nMessage-Id: <200808222049.m7MKnkrB006225@apps2.servage.net>\\nTo: public@jalf.dk\\nSubject: =?UTF-8?B?WW5ncmVzYWdlbnMgTnloZWRzYnJldiAyMi44LjA4?=\\nFrom: Nyhedsbrev fra Yngresagen <info@yngresagen.dk>\\nReply-To: info@yngresagen.dk\\nContent-type: text/plain; charset=UTF-8\\nX-Abuse: Servage.net Listid 16329\\nMime-Version: 1.0\\nX-mailer: Servage Maillist System\\nX-Spam-Status: No, score=0.1\\nX-Spam-Score: 1\\nX-Spam-Bar: /\\nX-Spam-Flag: NO\\nX-ClamAntiVirus-Scanner: This mail is clean\\n\\n\\nK\\xe6re medlem\\n\\nH\\xe5ber du har en god sommer og er klar p\\xe5 at l\\xe6se seneste nyt i Yngresagen. God forn\\xf8jelse!\\n\\n\\n::. KOM TIL YS-CAF\\xc8 .::\\nFlere og billigere ungdomsboliger, afskaf 24-\\xe5rs-reglen eller hvad synes du? Yngresagen indbyder dig til en \\xe5ben debat over kaffe og snacks. Yngresagens Kristian Lauta, Mette Marb\\xe6k, og formand Steffen M\\xf8ller fort\\xe6ller om tidligere projekter og vil gerne diskutere, hvad Yngresagen skal bruge sin tid p\\xe5 fremover. \\nVil du diskutere et emne, du br\\xe6nder for, eller vil du bare v\\xe6re med p\\xe5 en lytter?\\nS\\xe5 kom torsdag d. 28/8 kl. 17-19, Kulturhuset 44, 2200 KBH N \\n \\n::. VIND GAVEKORT & BLIV H\\xd8RT .:: \\nYngresagen har lavet et sp\\xf8rgeskema, s\\xe5 du har direkte mulighed for at sige din mening, og v\\xe6re med til at forme Yngresagens arbejde. Brug 5 min. p\\xe5 at dele dine holdninger om f.eks. uddannelse, arbejde og unges vilk\\xe5r - og vind et gavekort til en musikbutik. Vi tr\\xe6kker lod blandt alle svarene og finder tre heldige vindere. Sp\\xf8rgeskemaet er her: www.yngresagen.dk\\n\\n::. YS SPARKER NORDJYLLAND I GANG .::\\nNordjylland bliver Yngresagens sunde region. Her er regionsansvarlig Andreas M\\xf8ller Stehr ved at starte tre projekter op: 1) L\\xf8beklub, 2) F\\xf8rstehj\\xe6lpskursus, 3) Mad til unge-program.\\nVi har brug for flere frivillige til at sparke projekterne i gang. Vi tilbyder gratis fede aktiviteter, gratis t-shirts og ture til K\\xf8benhavn, hvor du kan m\\xf8de andre unge i YS. Har det fanget din interesse, s\\xe5 t\\xf8v ikke med at kontakte os: nordjylland@yngresagen.dk tlf. 21935185. \\n\\n::. YNGRESAGEN I PRESSEN .::\\nL\\xe6s her et udsnit af sidste nyt om Yngresagen i medierne. L\\xe6s og lyt mere p\\xe5 hjemmesiden under \\u201dYS i pressen\\u201d.\\n\\n:: Radionyhederne: Unge skal informeres bedre om l\\xe5n \\nUnge ved for lidt om at l\\xe5ne penge. Det udnytter banker og rejseselskaber til at give dem l\\xe5n med t\\xe5rnh\\xf8je renter. S\\xe5dan lyder det fra formand Steffen M\\xf8ller fra landsforeningen Yngresagen. \\n\\n:: Danmarks Radio P1: Dansk Folkeparti - de \\xe6ldres parti? \\nHvorfor er det kun fattige \\xe6ldre og ikke alle fattige, der kan s\\xf8ge om at f\\xe5 nedsat medielicens?\\nDansk Folkepartis ungeordf\\xf8rer, Karin N\\xf8dgaard, og Yngresagens formand Steffen M\\xf8ller debatterer medielicens, \\xe6ldrecheck og indflydelse til unge \\n\\n:: Frederiksborg Amts Avis: Turen til Roskilde koster en holdning!\\nFor at skabe et m\\xf8de mellem politikere og unge fragter Yngresagen unge gratis til \\xe5rets Roskilde Festival. Det sker med den s\\xe5kaldte Yngrebussen, der kan l\\xe6ses mere om p\\xe5 www.yngrebussen.dk\\n\\n \\n \\nMed venlig hilsen \\nYngresagen\\n\\nLandsforeningen Yngresagen\\nKulturhuset Kapelvej 44\\n2200 K\\xf8benhavn N\\n\\ntlf. 29644960\\ninfo@yngresagen.dk\\nwww.yngresagen.dk\\n\\n\\n-------------------------------------------------------\\nUnsubscribe Link: \\nhttp://apps.corecluster.net/apps/ml/r.php?l=16329&e=public%40jalf.dk%0D%0A&id=40830383\\n-------------------------------------------------------\\n\\n'\n\nNow its in unicode so it shouldn't give you any problem.\nNow the encode problem: It is a problem\nIn [129]: encd=open('jalf_encode_err','r').read()\n\nIn [130]: chardet.detect(encd)\nOut[130]: {'confidence': 0.78187650822865284, 'encoding': 'ISO-8859-2'}\n\n#even after the unicode conversion the encoding to ascii fails - because the criteris is strict by default\nIn [131]: unicode(encd, chardet.detect(encd)['encoding']).encode('ascii')\n---------------------------------------------------------------------------\n<type 'exceptions.UnicodeEncodeError'> Traceback (most recent call last)\n\n/home/jv/<ipython console> in <module>()\n\n<type 'exceptions.UnicodeEncodeError'>: 'ascii' codec can't encode character u'\\u0159' in position 557: ordinal not in range(128)'\n\n##changing the criteria to ignore\nIn [132]: unicode(encd, chardet.detect(encd)['encoding']).encode('ascii', 'ignore')\nOut[132]: 'Return-path: <info@kollegierneskontor.dk>\\nEnvelope-to: alf@5elements.net\\nDelivery-date: Tue, 21 Aug 2007 06:10:08 -0400\\nReceived: from pfepc.post.tele.dk ([195.41.46.237]:52065)\\n\\tby c1p.hostingzoom.com with esmtp (Exim 4.66)\\n\\t(envelope-from <info@kollegierneskontor.dk>)\\n\\tid 1INQgX-0003fI-Un\\n\\tfor alf@5elements.net; Tue, 21 Aug 2007 06:10:08 -0400\\nReceived: from local.com (ns2.datadan.dk [195.41.7.21])\\n\\tby pfepc.post.tele.dk (Postfix) with SMTP id ADF4C8A0086\\n\\tfor <alf@5elements.net>; Tue, 21 Aug 2007 12:10:04 +0200 (CEST)\\nFrom: \"Kollegiernes Kontor I Kbenhavn\" <info@kollegierneskontor.dk>\\nTo: \"Jesper Alf Dam\" <alf@5elements.net>\\nSubject: Fornyelse af profil\\nDate: Tue, 21 Aug 2007 12:10:03 +0200\\nX-Mailer: Dundas Mailer Control 1.0\\nMIME-Version: 1.0\\nContent-Type: Multipart/Alternative;\\n\\tboundary=\"Gark=_20078211010346yhSD0hUCo\"\\nMessage-Id: <20070821101004.ADF4C8A0086@pfepc.post.tele.dk>\\nX-Spam-Status: No, score=0.0\\nX-Spam-Score: 0\\nX-Spam-Bar: /\\nX-Spam-Flag: NO\\nX-ClamAntiVirus-Scanner: This mail is clean\\n\\n\\n\\n--Gark=_20078211010346yhSD0hUCo\\nContent-Type: text/plain; charset=ISO-8859-1\\nContent-Transfer-Encoding: Quoted-Printable\\n\\nHej Jesper Alf Dam=0D=0A=0D=0AHusk at forny din profil hos KKIK inden 28.=\\n august 2007=0D=0ALog ind p=E5 din profil og benyt ikonet \"forny\".=0D=0A=0D=\\n=0AVenlig hilsen=0D=0AKollegiernes Kontor i K=F8benhavn=0D=0A=0D=0Ahttp:/=\\n/www.kollegierneskontor.dk/=0D=0A=0D=0A\\n\\n--Gark=_20078211010346yhSD0hUCo\\nContent-Type: text/html; charset=ISO-8859-1\\nContent-Transfer-Encoding: Quoted-Printable\\n\\n<html>=0D=0A<head>=0D=0A=0D=0A<style>=0D=0ABODY, TD {=0D=0Afont-family: v=\\nerdana, arial, helvetica; font-size: 12px; color: #666666;=0D=0A}=0D=0A</=\\nstyle>=0D=0A=0D=0A<title></title>=0D=0A=0D=0A</head>=0D=0A<body bgcolor=3D=\\n#FFFFFF>=0D=0A<hr size=3D1 noshade>=0D=0A<table cellpadding=3D0 cellspaci=\\nng=3D0 border=3D0 width=3D100%>=0D=0A<tr><td >=0D=0AHej Jesper Alf Dam<br=\\n><br>Husk at forny din profil inden 28. august 2007<br>=0D=0ALog ind p=E5=\\n din profil og benyt ikonet \"forny\".=0D=0A<br><br>=0D=0A<a href=3D\"http:/=\\n/www.kollegierneskontor.dk/\">Klik her</a> for at logge ind.<br><br>Venlig=\\n hilsen<br>Kollegiernes Kontor i K=F8benhavn=0D=0A</td></tr>=0D=0A</table=\\n>=0D=0A<hr size=3D1 noshade>=0D=0A</body>=0D=0A</html>=0D=0A\\n\\n--Gark=_20078211010346yhSD0hUCo--\\n\\n'\n\nIn [133]: len(encd)\nOut[133]: 2303\n\nIn [134]: len(unicode(encd, chardet.detect(encd)['encoding']).encode('ascii', 'ignore'))\nOut[134]: 2302\n\nCAUTION: as you can see there could be minor to moderate loss of data in this procedure. So its upto the user to use it or not.\nso the code should look like \nimport chardet\n\nfor msg in src:\n msg=unicode(msg, chardet.detect(msg)['encoding']).encode('ascii', 'ignore')\n dest.add(msg)\n\n" ]
[ 4, 4 ]
[]
[]
[ "email_formats", "encoding", "python" ]
stackoverflow_0000409217_email_formats_encoding_python.txt
Q: Loop function parameters for sanity check I have a Python function in which I am doing some sanitisation of the input parameters: def func(param1, param2, param3): param1 = param1 or '' param2 = param2 or '' param3 = param3 or '' This caters for the arguments being passed as None rather than empty strings. Is there an easier/more concise way to loop round the function parameters to apply such an expression to all of them. My actual function has nine parameters. A: This looks like a good job for a decorator. How about this: def sanitized(func): def sfunc(*args, **kwds): return func(*[arg or '' for arg in args], **dict((k, v or '') for k,v in kwds.iteritems())) sfunc.func_name = func.func_name sfunc.func_doc = func.func_doc return sfunc You would use this on your function like so: @sanitized def func(param1, param2, param3): print param1, param2, param3 Then the parameters will be replaced by the empty string if they are false: >>> func('foo', None, 'spam') foo spam (Note that this will still mess up the function signature as Ned Batchelder points out in his answer. To fix that you could use Michele Simionato's decorator module-- I think you'd just need to add a @decorator before the definition of sanitized) A: You could do some list manipulation: def func(param1, param2, param3): param1, param2, param3 = map(lambda x: x or '', (param1, param2, param3)) but I'm not sure that's better than just writing out the nine lines, since once you get to nine parameters, that's a heinously long line. You could change the declaration of the function: def func(*args): param1, param2, param3 = map(lambda x: x or '', args) but then you lose the documentation that comes from having real parameter names, as well as the possibility of changing the defaults, etc. And you still have a pretty fugly line there to unpack them. I say write out the nine lines, or change the function to have fewer parameters: nine is kind of a lot anyway!
Loop function parameters for sanity check
I have a Python function in which I am doing some sanitisation of the input parameters: def func(param1, param2, param3): param1 = param1 or '' param2 = param2 or '' param3 = param3 or '' This caters for the arguments being passed as None rather than empty strings. Is there an easier/more concise way to loop round the function parameters to apply such an expression to all of them. My actual function has nine parameters.
[ "This looks like a good job for a decorator. How about this:\ndef sanitized(func):\n def sfunc(*args, **kwds):\n return func(*[arg or '' for arg in args],\n **dict((k, v or '') for k,v in kwds.iteritems()))\n sfunc.func_name = func.func_name\n sfunc.func_doc = func.func_doc\n return sfunc\n\nYou would use this on your function like so:\n@sanitized\ndef func(param1, param2, param3):\n print param1, param2, param3\n\nThen the parameters will be replaced by the empty string if they are false:\n>>> func('foo', None, 'spam')\nfoo spam\n\n(Note that this will still mess up the function signature as Ned Batchelder points out in his answer. To fix that you could use Michele Simionato's decorator module-- I think you'd just need to add a @decorator before the definition of sanitized)\n", "You could do some list manipulation:\ndef func(param1, param2, param3):\n param1, param2, param3 = map(lambda x: x or '', (param1, param2, param3))\n\nbut I'm not sure that's better than just writing out the nine lines, since once you get to nine parameters, that's a heinously long line.\nYou could change the declaration of the function:\ndef func(*args):\n param1, param2, param3 = map(lambda x: x or '', args)\n\nbut then you lose the documentation that comes from having real parameter names, as well as the possibility of changing the defaults, etc. And you still have a pretty fugly line there to unpack them.\nI say write out the nine lines, or change the function to have fewer parameters: nine is kind of a lot anyway!\n" ]
[ 7, 2 ]
[ "def func(x='', y='', z='hooray!'):\n print x, y, z\n\nIn [2]: f('test')\ntest hooray!\n\nIn [3]: f('test', 'and')\ntest and hooray!\n\nIn [4]: f('test', 'and', 'done!')\ntest and done!\n\n" ]
[ -2 ]
[ "arguments", "function", "parameters", "python", "sanitization" ]
stackoverflow_0000409449_arguments_function_parameters_python_sanitization.txt
Q: What versions of Python and wxPython correspond to each version of OSX? I'd like to know what versions of Python and wxPython correspond to each version of OSX. I'm interested to know exactly how far back some of my apps will remain compatible on a mac before having to install newer versions of Python and wxPython. A: Tiger shipped with Python 2.3.5 and wxPython 2.5.3, Leopard ships with python 2.5.1 and wxPython 2.8.4. wxPython was not shipped with previous versions. OSX Lion has 2.7.1
What versions of Python and wxPython correspond to each version of OSX?
I'd like to know what versions of Python and wxPython correspond to each version of OSX. I'm interested to know exactly how far back some of my apps will remain compatible on a mac before having to install newer versions of Python and wxPython.
[ "Tiger shipped with Python 2.3.5 and wxPython 2.5.3, Leopard ships with python 2.5.1 and wxPython 2.8.4.\nwxPython was not shipped with previous versions.\n\nOSX Lion has 2.7.1\n" ]
[ 3 ]
[]
[]
[ "compatibility", "macos", "python", "wxpython" ]
stackoverflow_0000409677_compatibility_macos_python_wxpython.txt
Q: Alter elements of a list I have a list of booleans where occasionally I reset them all to false. After first writing the reset as: for b in bool_list: b = False I found it doesn't work. I spent a moment scratching my head, then remembered that of course it won't work since I'm only changing a reference to the bool, not its value. So I rewrote as: for i in xrange(len(bool_list)): bool_list[i] = False and everything works fine. But I found myself asking, "Is that really the most pythonic way to alter all elements of a list?" Are there other ways that manage to be either more efficient or clearer? A: If you only have one reference to the list, the following may be easier: bool_list = [False] * len(bool_list) This creates a new list populated with False elements. See my answer to Python dictionary clear for a similar example. A: Here's another version: bool_list = [False for item in bool_list] A: Summary Performance-wise, numpy or a list multiplication are clear winners, as they are 10-20x faster than other approaches. I did some performance testing on the various options proposed. I used Python 2.5.2, on Linux (Ubuntu 8.10), with a 1.5 Ghz Pentium M. Original: python timeit.py -s 'bool_list = [True] * 1000' 'for x in xrange(len(bool_list)): bool_list[x] = False' 1000 loops, best of 3: 280 usec per loop Slice-based replacement with a list comprehension: python timeit.py -s 'bool_list = [True] * 1000' 'bool_list[:] = [False for element in bool_list]' 1000 loops, best of 3: 215 usec per loop Slice-based replacement with a generator comprehension: python timeit.py -s 'bool_list = [True] * 1000' 'bool_list[:] = (False for element in bool_list)' 1000 loops, best of 3: 265 usec per loop Enumerate: python timeit.py -s 'bool_list = [True] * 1000' 'for i, v in enumerate(bool_list): bool_list[i] = False' 1000 loops, best of 3: 385 usec per loop Numpy: python timeit.py -s 'import numpy' -s 'bool_list = numpy.zeros((1000,), dtype=numpy.bool)' 'bool_list[:] = False' 10000 loops, best of 3: 15.9 usec per loop Slice-based replacement with list multiplication: python timeit.py -s 'bool_list = [True] * 1000' 'bool_list[:] = [False] * len(bool_list)' 10000 loops, best of 3: 23.3 usec per loop Reference replacement with list multiplication python timeit.py -s 'bool_list = [True] * 1000' 'bool_list = [False] * len(bool_list)' 10000 loops, best of 3: 11.3 usec per loop A: bool_list[:] = [False] * len(bool_list) or bool_list[:] = [False for item in bool_list] A: If you're willing to use numpy arrays, it's actually really easy to do things like this using array slices. import numpy bool_list = numpy.zeros((100,), dtype=numpy.bool) # do something interesting with bool_list as if it were a normal list bool_list[:] = False # all elements have been reset to False now A: I wouldn't use the range and len. It's a lot cleaner to use enumerate() for i, v in enumerate(bool_list): #i, v = index and value bool_list[i] = False It's left with an unused variable in this case, but it still looks cleaner in my opinion. There's no noticeable change in performance either. A: For value types such as int, bool and string, your 2nd example is about as pretty as its going to get. Your first example will work on any reference types like classes, dicts, or other lists. A: I think bool_list = [False for element in bool_list] is as pythonic as it gets. Using lists like this should generaly be faster then a for loop in python too.
Alter elements of a list
I have a list of booleans where occasionally I reset them all to false. After first writing the reset as: for b in bool_list: b = False I found it doesn't work. I spent a moment scratching my head, then remembered that of course it won't work since I'm only changing a reference to the bool, not its value. So I rewrote as: for i in xrange(len(bool_list)): bool_list[i] = False and everything works fine. But I found myself asking, "Is that really the most pythonic way to alter all elements of a list?" Are there other ways that manage to be either more efficient or clearer?
[ "If you only have one reference to the list, the following may be easier:\nbool_list = [False] * len(bool_list)\n\nThis creates a new list populated with False elements.\nSee my answer to Python dictionary clear for a similar example.\n", "Here's another version:\nbool_list = [False for item in bool_list]\n\n", "Summary\nPerformance-wise, numpy or a list multiplication are clear winners, as they are 10-20x faster than other approaches.\nI did some performance testing on the various options proposed. I used Python 2.5.2, on Linux (Ubuntu 8.10), with a 1.5 Ghz Pentium M.\nOriginal:\npython timeit.py -s 'bool_list = [True] * 1000' 'for x in xrange(len(bool_list)): bool_list[x] = False'\n\n1000 loops, best of 3: 280 usec per loop\nSlice-based replacement with a list comprehension:\npython timeit.py -s 'bool_list = [True] * 1000' 'bool_list[:] = [False for element in bool_list]'\n\n1000 loops, best of 3: 215 usec per loop\nSlice-based replacement with a generator comprehension:\npython timeit.py -s 'bool_list = [True] * 1000' 'bool_list[:] = (False for element in bool_list)'\n\n1000 loops, best of 3: 265 usec per loop\nEnumerate:\npython timeit.py -s 'bool_list = [True] * 1000' 'for i, v in enumerate(bool_list): bool_list[i] = False'\n\n1000 loops, best of 3: 385 usec per loop\nNumpy:\npython timeit.py -s 'import numpy' -s 'bool_list = numpy.zeros((1000,), dtype=numpy.bool)' 'bool_list[:] = False'\n\n10000 loops, best of 3: 15.9 usec per loop\nSlice-based replacement with list multiplication:\npython timeit.py -s 'bool_list = [True] * 1000' 'bool_list[:] = [False] * len(bool_list)'\n\n10000 loops, best of 3: 23.3 usec per loop\nReference replacement with list multiplication\n python timeit.py -s 'bool_list = [True] * 1000' 'bool_list = [False] * len(bool_list)'\n\n10000 loops, best of 3: 11.3 usec per loop\n", "bool_list[:] = [False] * len(bool_list)\n\nor\nbool_list[:] = [False for item in bool_list]\n\n", "If you're willing to use numpy arrays, it's actually really easy to do things like this using array slices.\nimport numpy\n\nbool_list = numpy.zeros((100,), dtype=numpy.bool)\n\n# do something interesting with bool_list as if it were a normal list\n\nbool_list[:] = False\n# all elements have been reset to False now\n\n", "I wouldn't use the range and len. It's a lot cleaner to use enumerate()\nfor i, v in enumerate(bool_list): #i, v = index and value\n bool_list[i] = False\n\nIt's left with an unused variable in this case, but it still looks cleaner in my opinion. There's no noticeable change in performance either.\n", "For value types such as int, bool and string, your 2nd example is about as pretty as its going to get. Your first example will work on any reference types like classes, dicts, or other lists.\n", "I think \nbool_list = [False for element in bool_list]\n\nis as pythonic as it gets. Using lists like this should generaly be faster then a for loop in python too.\n" ]
[ 13, 13, 12, 11, 4, 3, 0, 0 ]
[]
[]
[ "coding_style", "python" ]
stackoverflow_0000409732_coding_style_python.txt
Q: How to compare and search list of integers efficiently? I have a database populated with 1 million objects. Each object has a 'tags' field - set of integers. For example: object1: tags(1,3,4) object2: tags(2) object3: tags(3,4) object4: tags(5) and so on. Query parameter is a set on integers, lets try q(3,4,5) object1 does not match ('1' not in '3,4,5') object2 does not match ('2' not in '3,4,5') object3 matches ('3 and 4' in '3,4,5' ) object4 matches ('5' in '3,4,5' ) How to select matched objects efficiently? A: Given that you are using PostgreSQL, you could use its array datatype and its contains/overlaps operators. Of course this would tie your app to PostgreSQL tightly, which may not be desired. On the other hand, it may save you coding for when it's really needed (ie, when you finally have to port it to another database) Although, given that in Python you have the set datatype for that exact group of operations, using PostgreSQL might be overkill (depending on the performance requirements) >>> a = set([1,2,3]) >>> a set([1, 2, 3]) >>> 1 in a True >>> set([1,2]) in a False >>> set([2,3]) & a set([2, 3]) >>> set([8,9]) & a set([]) >>> set([1,3]) & a set([1, 3]) >>> A: You're making a common mistake in database design, by storing a comma-separated list of tag id's. It's not a surprise that performing efficient queries against this is a blocker for you. What you need is to model the mapping between objects and tags in a separate table. CREATE TABLE Tagged ( object_id INT NOT NULL, tag_id INT NOT NULL, PRIMARY KEY (object_id, tag_id), FOREIGN KEY (object_id) REFERENCES Objects(object_id), FOREIGN KEY (tag_id) REFERENCES Tags(tag_id) ); Insert one row for each object/tag pairing. Of course, this means you have several rows for each object_id, but that's okay. You can query for all objects that have tags 3,4,5: SELECT DISTINCT object_id FROM Tagged WHERE tag_id IN (3, 4, 5); But this matches object1, which you don't want. You want to exclude objects that have other tags not in 3,4,5. SELECT DISTINCT t1.object_id FROM Tagged t1 LEFT OUTER JOIN Tagged t2 ON (t1.object_id = t2.object_id AND t2.tag_id NOT IN (3, 4, 5)) WHERE t1.tag_id IN (3, 4, 5) AND t2.object_id IS NULL; A: If I understood it right, its something like a: Post-> posttags <-tags kindof schema. I wonder why are you doing it this way? Is it a problem you have reached because you are using an ORM which retrieves data in objects and other lazy loaded associated objects. Like a Post and Tag class in SQLAlchemy, with Post mapper having a property called 'tags' which can load set of Tag objects for given Post object. If that's so, those kind of operations are usually very costly in ORM's and should be done with the SQL Statement support of ORM's or using the direct dbapi's like psycopg2. Again, if the number of objects loaded from a query is huge (keeping in mind your 1Million) you need machine with lot of resources (or maybe None at all - pure ORM not recommended). If its not an ORM and still your tags are stored like (sets) then I think there is something wrong with the schema. posttags is a many-to-many relationship as i see it and its a different table by itself (which is easily queriable), not a 'set' in posts table. A: You haven't stated weather you'd like to use SQL or if your reading the data into an application before doing so. From sounds of things your looking for a code based solution? In .NET you would make a class implement the ICompare interface and write your own method to to compare two values that would either return a 0 or 1. A: This is basic set theory. Intersect the two sets and if the result is the same as the original then the result is "match". Otherwise its not. You can apply this principle using many languages. Most have libraries for doing things with sets. You can even do this using SQL. A: Looks to me like the issubset() method of sets is what you are looking for: tags(1, 2, 3).issubset(q(1, 2, 3, 4)) If both tags and q are subclasses of the set class. But I agree with the other answers that solving this in the database would be a better solution. A: I'm sorry. Looks like it was hard to me to explain the problem well :) The 'postgresql' tag here os lot more meaningful than 'python'. Self joined TAG table with IS NULL condition is what I really need. SQLalchemy is also good advise. Thank you all.
How to compare and search list of integers efficiently?
I have a database populated with 1 million objects. Each object has a 'tags' field - set of integers. For example: object1: tags(1,3,4) object2: tags(2) object3: tags(3,4) object4: tags(5) and so on. Query parameter is a set on integers, lets try q(3,4,5) object1 does not match ('1' not in '3,4,5') object2 does not match ('2' not in '3,4,5') object3 matches ('3 and 4' in '3,4,5' ) object4 matches ('5' in '3,4,5' ) How to select matched objects efficiently?
[ "Given that you are using PostgreSQL, you could use its array datatype and its contains/overlaps operators.\nOf course this would tie your app to PostgreSQL tightly, which may not be desired. On the other hand, it may save you coding for when it's really needed (ie, when you finally have to port it to another database)\nAlthough, given that in Python you have the set datatype for that exact group of operations, using PostgreSQL might be overkill (depending on the performance requirements)\n>>> a = set([1,2,3])\n>>> a\nset([1, 2, 3])\n>>> 1 in a\nTrue\n>>> set([1,2]) in a\nFalse\n>>> set([2,3]) & a\nset([2, 3])\n>>> set([8,9]) & a\nset([])\n>>> set([1,3]) & a\nset([1, 3])\n>>>\n\n", "You're making a common mistake in database design, by storing a comma-separated list of tag id's. It's not a surprise that performing efficient queries against this is a blocker for you.\nWhat you need is to model the mapping between objects and tags in a separate table.\nCREATE TABLE Tagged (\n object_id INT NOT NULL,\n tag_id INT NOT NULL,\n PRIMARY KEY (object_id, tag_id),\n FOREIGN KEY (object_id) REFERENCES Objects(object_id),\n FOREIGN KEY (tag_id) REFERENCES Tags(tag_id)\n);\n\nInsert one row for each object/tag pairing. Of course, this means you have several rows for each object_id, but that's okay.\nYou can query for all objects that have tags 3,4,5:\nSELECT DISTINCT object_id\nFROM Tagged\nWHERE tag_id IN (3, 4, 5);\n\nBut this matches object1, which you don't want. You want to exclude objects that have other tags not in 3,4,5.\nSELECT DISTINCT t1.object_id\nFROM Tagged t1 \n LEFT OUTER JOIN Tagged t2\n ON (t1.object_id = t2.object_id AND t2.tag_id NOT IN (3, 4, 5))\nWHERE t1.tag_id IN (3, 4, 5)\n AND t2.object_id IS NULL;\n\n", "If I understood it right, its something like a:\nPost-> posttags <-tags\nkindof schema.\nI wonder why are you doing it this way? \nIs it a problem you have reached because you are using an ORM which retrieves data in objects and other lazy loaded associated objects.\nLike a Post and Tag class in SQLAlchemy, with Post mapper having a property called 'tags' which can load set of Tag objects for given Post object.\nIf that's so, those kind of operations are usually very costly in ORM's and should be done with the SQL Statement support of ORM's or using the direct dbapi's like psycopg2.\nAgain, if the number of objects loaded from a query is huge (keeping in mind your 1Million) you need machine with lot of resources (or maybe None at all - pure ORM not recommended).\nIf its not an ORM and still your tags are stored like (sets) then I think there is something wrong with the schema.\nposttags is a many-to-many relationship as i see it and its a different table by itself (which is easily queriable), not a 'set' in posts table.\n", "You haven't stated weather you'd like to use SQL or if your reading the data into an application before doing so. From sounds of things your looking for a code based solution?\nIn .NET you would make a class implement the ICompare interface and write your own method to to compare two values that would either return a 0 or 1.\n", "This is basic set theory. Intersect the two sets and if the result is the same as the original then the result is \"match\". Otherwise its not.\nYou can apply this principle using many languages. Most have libraries for doing things with sets. You can even do this using SQL.\n", "Looks to me like the issubset() method of sets is what you are looking for:\ntags(1, 2, 3).issubset(q(1, 2, 3, 4))\n\nIf both tags and q are subclasses of the set class.\nBut I agree with the other answers that solving this in the database would be a better solution.\n", "I'm sorry. Looks like it was hard to me to explain the problem well :)\nThe 'postgresql' tag here os lot more meaningful than 'python'.\nSelf joined TAG table with IS NULL condition is what I really need.\nSQLalchemy is also good advise.\nThank you all.\n" ]
[ 3, 3, 1, 0, 0, 0, 0 ]
[]
[]
[ "postgresql", "python" ]
stackoverflow_0000408855_postgresql_python.txt
Q: What's the best way to upgrade from Django 0.96 to 1.0? Should I try to actually upgrade my existing app, or just rewrite it mostly from scratch, saving what pieces (templates, etc) I can? A: Although this depends on what you're doing, most applications should be able to just upgrade and then fix everything that breaks. In my experience, the main things that I've had to fix after an upgrade are Changes to some of the funky stuff with models, such as the syntax for following foreign keys. A small set of template changes, most notably auto-escaping. Anything that depends on the specific structure of Django's internals. This shouldn't be an issue unless you're doing stuff like dynamically modifying Django internals to change their behavior in a way that's necessary/convenient for your project. To summarize, unless you're doing a lot of really weird and/or complex stuff, a simple upgrade should be relatively painless and only require a few changes. A: Upgrade. For me it was very simple: change __str__() to __unicode__(), write basic admin.py, and done. Just start running your app on 1.0, test it, and when you encounter an error use the documentation on backwards-incompatible changes to see how to fix the issue. A: Just upgrade your app. The switch from 0.96 to 1.0 was huge, but in terms of Backwards Incompatible changes I doubt your app even has 10% of them. I was on trunk before Django 1.0 so I the transition for me was over time but even then the only major things I had to change were newforms, newforms-admin, str() to unicode() and maxlength to max_length Most of the other changes were new features or backend rewrites or stuff that as someone who was building basic websites did not even get near. A: Only simplest sites are easy to upgrade. Expect real pain if your site happen to be for non-ASCII part of the world (read: anywhere outside USA and UK). The most painful change in Django was switching from bytestrings to unicode objects internally - now you have to find all places where you use bytestrings and change this to unicode. Worst case is the template rendering, you'll never know you forgot to change one variable until you get UnicodeError. Other notable thing: manipulators (oldforms) have gone and you have no other way than to rewrite all parts with forms (newforms). If this is your case and your project is larger than 2-3 apps, I'd be rather reluctant to upgrade until really necessary. A: We upgraded in a multi step process and I'm quite happy with that. The application in Question was about 100.000 LoC and running several core business functions with lot's of interfacing to legacy systems. We worked like that: Update to django 0.97-post unicode merge. Fix all the unicode issues refactor the application into reusable apps, add tests. That left us with 40.000 LoC in the main application/Project Upgrade to django 0.97-post autoexcape merge. Fix auto escaping in the reusable apps created in 3. Then fix the remaining auto-escaping issues in the mian application. Upgrade to 1.0. What was left was mostly fixing the admin stuff. The whole thing took about 6 months where we where running a legacy production branch on our servers while porting an other branch to 1.0. While doing so we also where adding features to the production branch. The final merge was much less messy than expected and took about a week for 4 coders merging, reviewing, testing and fixing. We then rolled out, and for about a week got bitten by previously unexpected bugs. All in all I'm quite satisfied with the outcome. We have a much better codebase now for further development.
What's the best way to upgrade from Django 0.96 to 1.0?
Should I try to actually upgrade my existing app, or just rewrite it mostly from scratch, saving what pieces (templates, etc) I can?
[ "Although this depends on what you're doing, most applications should be able to just upgrade and then fix everything that breaks. In my experience, the main things that I've had to fix after an upgrade are\n\nChanges to some of the funky stuff with models, such as the syntax for following foreign keys.\nA small set of template changes, most notably auto-escaping.\nAnything that depends on the specific structure of Django's internals. This shouldn't be an issue unless you're doing stuff like dynamically modifying Django internals to change their behavior in a way that's necessary/convenient for your project.\n\nTo summarize, unless you're doing a lot of really weird and/or complex stuff, a simple upgrade should be relatively painless and only require a few changes.\n", "Upgrade. For me it was very simple: change __str__() to __unicode__(), write basic admin.py, and done. Just start running your app on 1.0, test it, and when you encounter an error use the documentation on backwards-incompatible changes to see how to fix the issue.\n", "Just upgrade your app. The switch from 0.96 to 1.0 was huge, but in terms of Backwards Incompatible changes I doubt your app even has 10% of them.\nI was on trunk before Django 1.0 so I the transition for me was over time but even then the only major things I had to change were newforms, newforms-admin, str() to unicode() and maxlength to max_length\nMost of the other changes were new features or backend rewrites or stuff that as someone who was building basic websites did not even get near.\n", "Only simplest sites are easy to upgrade.\nExpect real pain if your site happen to be for non-ASCII part of the world (read: anywhere outside USA and UK). The most painful change in Django was switching from bytestrings to unicode objects internally - now you have to find all places where you use bytestrings and change this to unicode. Worst case is the template rendering, you'll never know you forgot to change one variable until you get UnicodeError.\nOther notable thing: manipulators (oldforms) have gone and you have no other way than to rewrite all parts with forms (newforms).\nIf this is your case and your project is larger than 2-3 apps, I'd be rather reluctant to upgrade until really necessary.\n", "We upgraded in a multi step process and I'm quite happy with that. The application in Question was about 100.000 LoC and running several core business functions with lot's of interfacing to legacy systems. We worked like that:\n\nUpdate to django 0.97-post unicode\nmerge. Fix all the unicode issues\nrefactor the application into\nreusable apps, add tests. That left us with\n40.000 LoC in the main application/Project\nUpgrade to django 0.97-post autoexcape merge. Fix auto escaping in the reusable apps created in 3. Then fix the remaining auto-escaping issues in the mian application. \nUpgrade to 1.0. What was left was mostly fixing the admin stuff.\n\nThe whole thing took about 6 months where we where running a legacy production branch on our servers while porting an other branch to 1.0. While doing so we also where adding features to the production branch.\nThe final merge was much less messy than expected and took about a week for 4 coders merging, reviewing, testing and fixing. We then rolled out, and for about a week got bitten by previously unexpected bugs.\nAll in all I'm quite satisfied with the outcome. We have a much better codebase now for further development. \n" ]
[ 7, 3, 2, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000128466_django_python.txt
Q: Avoid exceptions? This particular example relates to Django in Python, but should apply to any language supporting exceptions: try: object = ModelClass.objects.get(search=value) except DoesNotExist: pass if object: # do stuff The Django model class provides a simple method get which allows me to search for one and only one object from the database, if it finds more or less it raises an exception. If can find zero or more with an alternative filter method, which returns a list: objects = ModelClass.objects.filter(search=value) if len(objects) == 1: object = objects[0] # do stuff Am I overly averse to exceptions? To me the exception seems a little wasteful, at a guess, a quarter-to-a-half of the time will be 'exceptional'. I'd much prefer a function that returns None on failure. Would I be better to use Django's filter method and process the list myself? A: Believe it or not, this actually is an issue that is a bit different in each language. In Python, exceptions are regularly thrown for events that aren't exceptional by the language itself. Thus I think that the "you should only throw exceptions under exceptional circumstances" rule doesn't quite apply. I think the results you'll get on this forum will be slanted towards that point of view though, considering the high number of .Net programmers (see this question) for more info on that). At a very minimum, I'd better not catch anyone who sticks to that rule ever using a generator or a for loop in Python (both of which involve throwing exceptions for non-exceptional circumstances). A: There's a big schism in programming languages around the use of exceptions. The majority view is that exceptions should be exceptional. In most languages with exceptions, transfer of control by exception is considerably more expensive than by procedure return, for example. There is a strong minority view that exceptions are just another control-flow construct, and they should be cheap. The Standard ML of New Jersey and Objective Caml compilers subscribe to that view. If you have cheap exceptions you can code some fancy backtracking algorithms in ways that are more difficult to code cleanly using other mechanisms. I've seen this debate repeated many times for new language designs, and almost always, the winner decides that exceptions should be expensive and rare. When you care about performanced, you'd be wise to program with this in mind. A: The clue is in the name - exceptions should be exceptional. If you always expect the item will exist then use get, but if you expect it not to exist a reasonable proportion of the time (i.e. it not existing is an expected result rather than an exceptional result) then I'd suggest using filter. So, seeing as you indicated that between 1 in 2 and 1 in 4 are expected not to exist, I'd definitely write a wrapper around filter, as that's definitely not an exceptional case. A: I agree with the other answer but I wanted to add that exception passing like this is going to give you a very noticeable performance hit. Highly recommended that you check to see if the result exists (if that's what filter does) instead of passing on exceptions. Edit: In response to request for numbers on this, I ran this simple test... import time def timethis(func, list, num): st=time.time() for i in xrange(0,1000000): try: func(list,num) except: pass et = time.time() print "Took %gs" % (et-st) def check(list, num): if num < len(list): return list[num] else: return None a=[1] timethis(check, a, 1) timethis(lambda x,y:x[y], a, 1) And the output was.. Took 0.772558s Took 3.4512s HTH. A: The answer will depend on the intent of the code. (I'm not sure what your code sample was meant to do, the pass in the exceptional case is confusing, what will the rest of the code do with object variable to work with?) Whether to use exceptions or to use a method which treat the case as non-exceptional is a matter of taste in many cases. Certainly if the real code in the except clause is as complicated as the filter method you'd have to use to avoid the exception, then use the filter method. Simpler code is better code. A: Aversion to excpetions is a matter of opinion - however, if there's reason to believe that a function or method is going to be called many times or called rapidly, exceptions will cause a significant slowdown. I learned this from my previous question, where I was previously relying on a thrown exception to return a default value rather than doing parameter checking to return that default. Of course, exceptions can still exist for any reason, and you shouldn't be afraid to use or throw one if necessary - especially ones that could potentially break the normal flow of the calling function. A: I disagree with the above comments that an exception is inefficient in this instance, especially since it's being used in an I/O bound operation. Here's a more realistic example using Django with an in-memory sqlite database. Each of a 100 different queries was run, then averaged for each of a 100 runs. Although I doubt if it would matter, I also changed the order of execution. With ObjectDoesNotExist... 0.102783939838 Without exception ........ 0.105322141647 With ObjectDoesNotExist... 0.102762134075 Without exception ........ 0.101523952484 With ObjectDoesNotExist... 0.100004930496 Without exception ........ 0.107946784496 You can instrument this in your own Django environment, but I doubt if your time is well spent avoiding this exception.
Avoid exceptions?
This particular example relates to Django in Python, but should apply to any language supporting exceptions: try: object = ModelClass.objects.get(search=value) except DoesNotExist: pass if object: # do stuff The Django model class provides a simple method get which allows me to search for one and only one object from the database, if it finds more or less it raises an exception. If can find zero or more with an alternative filter method, which returns a list: objects = ModelClass.objects.filter(search=value) if len(objects) == 1: object = objects[0] # do stuff Am I overly averse to exceptions? To me the exception seems a little wasteful, at a guess, a quarter-to-a-half of the time will be 'exceptional'. I'd much prefer a function that returns None on failure. Would I be better to use Django's filter method and process the list myself?
[ "Believe it or not, this actually is an issue that is a bit different in each language. In Python, exceptions are regularly thrown for events that aren't exceptional by the language itself. Thus I think that the \"you should only throw exceptions under exceptional circumstances\" rule doesn't quite apply. I think the results you'll get on this forum will be slanted towards that point of view though, considering the high number of .Net programmers (see this question) for more info on that).\nAt a very minimum, I'd better not catch anyone who sticks to that rule ever using a generator or a for loop in Python (both of which involve throwing exceptions for non-exceptional circumstances).\n", "There's a big schism in programming languages around the use of exceptions.\n\nThe majority view is that exceptions should be exceptional. In most languages with exceptions, transfer of control by exception is considerably more expensive than by procedure return, for example.\nThere is a strong minority view that exceptions are just another control-flow construct, and they should be cheap. The Standard ML of New Jersey and Objective Caml compilers subscribe to that view. If you have cheap exceptions you can code some fancy backtracking algorithms in ways that are more difficult to code cleanly using other mechanisms.\n\nI've seen this debate repeated many times for new language designs, and almost always, the winner decides that exceptions should be expensive and rare. When you care about performanced, you'd be wise to program with this in mind.\n", "The clue is in the name - exceptions should be exceptional.\nIf you always expect the item will exist then use get, but if you expect it not to exist a reasonable proportion of the time (i.e. it not existing is an expected result rather than an exceptional result) then I'd suggest using filter.\nSo, seeing as you indicated that between 1 in 2 and 1 in 4 are expected not to exist, I'd definitely write a wrapper around filter, as that's definitely not an exceptional case.\n", "I agree with the other answer but I wanted to add that exception passing like this is going to give you a very noticeable performance hit. Highly recommended that you check to see if the result exists (if that's what filter does) instead of passing on exceptions.\n\nEdit:\nIn response to request for numbers on this, I ran this simple test...\nimport time\n\ndef timethis(func, list, num):\n st=time.time()\n for i in xrange(0,1000000):\n try:\n func(list,num)\n except:\n pass\n et = time.time()\n print \"Took %gs\" % (et-st)\n\ndef check(list, num):\n if num < len(list):\n return list[num]\n else:\n return None\n\na=[1]\ntimethis(check, a, 1)\ntimethis(lambda x,y:x[y], a, 1)\n\nAnd the output was..\nTook 0.772558s\nTook 3.4512s\n\nHTH.\n", "The answer will depend on the intent of the code. (I'm not sure what your code sample was meant to do, the pass in the exceptional case is confusing, what will the rest of the code do with object variable to work with?)\nWhether to use exceptions or to use a method which treat the case as non-exceptional is a matter of taste in many cases. Certainly if the real code in the except clause is as complicated as the filter method you'd have to use to avoid the exception, then use the filter method. Simpler code is better code.\n", "Aversion to excpetions is a matter of opinion - however, if there's reason to believe that a function or method is going to be called many times or called rapidly, exceptions will cause a significant slowdown. I learned this from my previous question, where I was previously relying on a thrown exception to return a default value rather than doing parameter checking to return that default.\nOf course, exceptions can still exist for any reason, and you shouldn't be afraid to use or throw one if necessary - especially ones that could potentially break the normal flow of the calling function.\n", "I disagree with the above comments that an exception is inefficient in this instance, especially since it's being used in an I/O bound operation.\nHere's a more realistic example using Django with an in-memory sqlite database. Each of a 100 different queries was run, then averaged for each of a 100 runs. Although I doubt if it would matter, I also changed the order of execution.\nWith ObjectDoesNotExist... 0.102783939838\nWithout exception ........ 0.105322141647\n\nWith ObjectDoesNotExist... 0.102762134075\nWithout exception ........ 0.101523952484\n\nWith ObjectDoesNotExist... 0.100004930496\nWithout exception ........ 0.107946784496\n\nYou can instrument this in your own Django environment, but I doubt if your time is well spent avoiding this exception.\n" ]
[ 11, 8, 5, 3, 2, 2, 2 ]
[]
[]
[ "django", "exception", "python" ]
stackoverflow_0000409529_django_exception_python.txt
Q: Best modules to develop a simple windowed 3D modeling application? I want to create a very basic 3D modeling tool. The application is supposed to be windowed and will need to respond to mouse click and drag events in the 3D viewport. I've decided on wxPython for the actual window since I'm fairly familiar with it already. However, I need to produce an OpenGL viewport that can respond to the various mouse events. It wouldn't hurt to have some convenience math in place for converting the 2D mouse positions in "camera space" into world space coordinates to make selection tasks easier. I'm looking for recommendations on which modules I should be looking at. A: Any reason you wouldn't use wx's GLCanvas? Here's an example that draws a sphere. A: As a very basic 3D modelling tool I'd recommend VPython. A: I'm not aware of any boxed up modules which provide that functionality, but you can take some inspiration from Blender 3D, which has all of the features you described: its a 3D modeling tool, its written in Python, has an OpenGL viewport which responds to mouse events, and its open source. You can probably take inspiration from Blender and apply it your own projects.
Best modules to develop a simple windowed 3D modeling application?
I want to create a very basic 3D modeling tool. The application is supposed to be windowed and will need to respond to mouse click and drag events in the 3D viewport. I've decided on wxPython for the actual window since I'm fairly familiar with it already. However, I need to produce an OpenGL viewport that can respond to the various mouse events. It wouldn't hurt to have some convenience math in place for converting the 2D mouse positions in "camera space" into world space coordinates to make selection tasks easier. I'm looking for recommendations on which modules I should be looking at.
[ "Any reason you wouldn't use wx's GLCanvas? Here's an example that draws a sphere.\n", "As a very basic 3D modelling tool I'd recommend VPython.\n", "I'm not aware of any boxed up modules which provide that functionality, but you can take some inspiration from Blender 3D, which has all of the features you described: its a 3D modeling tool, its written in Python, has an OpenGL viewport which responds to mouse events, and its open source.\nYou can probably take inspiration from Blender and apply it your own projects.\n" ]
[ 3, 2, 1 ]
[]
[]
[ "3d", "opengl", "python", "wxpython" ]
stackoverflow_0000410941_3d_opengl_python_wxpython.txt
Q: gtk.Builder, container subclass and binding child widgets I'm trying to use custom container widgets in gtk.Builder definition files. As far as instantiating those widgets, it works great: #!/usr/bin/env python import sys import gtk class MyDialog(gtk.Dialog): __gtype_name__ = "MyDialog" if __name__ == "__main__": builder = gtk.Builder() builder.add_from_file("mydialog.glade") dialog = builder.get_object("mydialog-instance") dialog.run() Now the question is that say I have a gtk.TreeView widget inside that dialog. I'm trying to figure out how to bind that widget to an MyDialog instance variable. One cheap alternative I can think of is to call additional method after getting the dialog widget like so: dialog = builder.get_object("mydialog-instance") dialog.bind_widgets(builder) But that seems fairly awkward. Has anyone solved this already or has a better idea on how to go about doing it? Thanks, A: Alright, I guess I answered my own question. One way to do the above is to override gtk.Buildable's parser_finished(), which gives access to the builder object that created the class instance itself. The method is called after entire .xml file has been loaded, so all of the additional widgets we may want to get hold of are already present and intialized: class MyDialog(gtk.Dialog, gtk.Buildable): __gtype_name__ = "MyDialog" def do_parser_finished(self, builder): self.treeview = builder.get_object("treeview1") # Do any other associated post-initialization One thing to note is that for some reason (at least for me, in pygtk 2.12), if I don't explicitly inherit from gtk.Buildable, the override method doesn't get called, even thought gtk.Dialog already implements the buildable interface.
gtk.Builder, container subclass and binding child widgets
I'm trying to use custom container widgets in gtk.Builder definition files. As far as instantiating those widgets, it works great: #!/usr/bin/env python import sys import gtk class MyDialog(gtk.Dialog): __gtype_name__ = "MyDialog" if __name__ == "__main__": builder = gtk.Builder() builder.add_from_file("mydialog.glade") dialog = builder.get_object("mydialog-instance") dialog.run() Now the question is that say I have a gtk.TreeView widget inside that dialog. I'm trying to figure out how to bind that widget to an MyDialog instance variable. One cheap alternative I can think of is to call additional method after getting the dialog widget like so: dialog = builder.get_object("mydialog-instance") dialog.bind_widgets(builder) But that seems fairly awkward. Has anyone solved this already or has a better idea on how to go about doing it? Thanks,
[ "Alright, I guess I answered my own question.\nOne way to do the above is to override gtk.Buildable's parser_finished(), which gives access to the builder object that created the class instance itself. The method is called after entire .xml file has been loaded, so all of the additional widgets we may want to get hold of are already present and intialized:\nclass MyDialog(gtk.Dialog, gtk.Buildable):\n __gtype_name__ = \"MyDialog\"\n\n def do_parser_finished(self, builder):\n self.treeview = builder.get_object(\"treeview1\")\n # Do any other associated post-initialization\n\nOne thing to note is that for some reason (at least for me, in pygtk 2.12), if I don't explicitly inherit from gtk.Buildable, the override method doesn't get called, even thought gtk.Dialog already implements the buildable interface.\n" ]
[ 5 ]
[]
[]
[ "bind", "gtk", "gtkbuilder", "python", "subclass" ]
stackoverflow_0000411708_bind_gtk_gtkbuilder_python_subclass.txt
Q: Variable number of inputs with Django forms possible? Is it possible to have a variable number of fields using django forms? The specific application is this: A user can upload as many pictures as they want on the image upload form. Once the pictures are uploaded they are taken to a page where they can give the pictures a name and description. The number of pictures will depend on how many the user has chosen to upload. So how do I get django to generate a form using a variable number of input fields (which could be passed as an argument if necessary)? edit: a few things have changed since the article mentioned in jeff bauer's answer was written. Namely this line of code which doesn't seem to work: # BAD CODE DO NOT USE!!! return type('ContactForm', [forms.BaseForm], { 'base_fields': fields }) So here is what I came up with... The Answer I used: from tagging.forms import TagField from django import forms def make_tagPhotos_form(photoIdList): "Expects a LIST of photo objects (ie. photo_sharing.models.photo)" fields = {} for id in photoIdList: id = str(id) fields[id+'_name'] = forms.CharField() fields[id+'_tags'] = TagField() fields[id+'_description'] = forms.CharField(widget=forms.Textarea) return type('tagPhotos', (forms.BaseForm,), { 'base_fields': fields }) note tagging is not part of django, but it is free and very useful. check it out: django-tagging A: Yes, it's possible to create forms dynamically in Django. You can even mix and match dynamic fields with normal fields. class EligibilityForm(forms.Form): def __init__(self, *args, **kwargs): super(EligibilityForm, self).__init__(*args, **kwargs) # dynamic fields here ... self.fields['plan_id'] = CharField() # normal fields here ... date_requested = DateField() For a better elaboration of this technique, see James Bennett's article: So you want a dynamic form? http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/ A: If you run python manage.py shell and type: from app.forms import PictureForm p = PictureForm() p.fields type(p.fields) you'll see that p.fields is a SortedDict. you just have to insert a new field. Something like p.fields.insert(len(p.fields)-2, 'fieldname', Field()) In this case it would insert before the last field, a new field. You should now adapt to your code. Other alternative is to make a for/while loop in your template and do the form in HTML, but django forms rock for some reason, right? A: Use either multiple forms (django.forms.Form not the tag) class Foo(forms.Form): field = forms.Charfield() forms = [Foo(prefix=i) for i in xrange(x)] or add multiple fields to the form dynamically using self.fields. class Bar(forms.Form): def __init__(self, fields, *args, **kwargs): super(Bar, self).__init__(*args, **kwargs) for i in xrange(fields): self.fields['my_field_%i' % i] = forms.Charfield()
Variable number of inputs with Django forms possible?
Is it possible to have a variable number of fields using django forms? The specific application is this: A user can upload as many pictures as they want on the image upload form. Once the pictures are uploaded they are taken to a page where they can give the pictures a name and description. The number of pictures will depend on how many the user has chosen to upload. So how do I get django to generate a form using a variable number of input fields (which could be passed as an argument if necessary)? edit: a few things have changed since the article mentioned in jeff bauer's answer was written. Namely this line of code which doesn't seem to work: # BAD CODE DO NOT USE!!! return type('ContactForm', [forms.BaseForm], { 'base_fields': fields }) So here is what I came up with... The Answer I used: from tagging.forms import TagField from django import forms def make_tagPhotos_form(photoIdList): "Expects a LIST of photo objects (ie. photo_sharing.models.photo)" fields = {} for id in photoIdList: id = str(id) fields[id+'_name'] = forms.CharField() fields[id+'_tags'] = TagField() fields[id+'_description'] = forms.CharField(widget=forms.Textarea) return type('tagPhotos', (forms.BaseForm,), { 'base_fields': fields }) note tagging is not part of django, but it is free and very useful. check it out: django-tagging
[ "Yes, it's possible to create forms dynamically in Django. You can even mix and match dynamic fields with normal fields.\nclass EligibilityForm(forms.Form):\n def __init__(self, *args, **kwargs):\n super(EligibilityForm, self).__init__(*args, **kwargs)\n # dynamic fields here ...\n self.fields['plan_id'] = CharField()\n # normal fields here ...\n date_requested = DateField()\n\nFor a better elaboration of this technique, see James Bennett's article: So you want a dynamic form?\nhttp://www.b-list.org/weblog/2008/nov/09/dynamic-forms/\n", "If you run\npython manage.py shell\n\nand type:\nfrom app.forms import PictureForm\np = PictureForm()\np.fields\ntype(p.fields)\n\nyou'll see that p.fields is a SortedDict. you just have to insert a new field. Something like\np.fields.insert(len(p.fields)-2, 'fieldname', Field())\n\nIn this case it would insert before the last field, a new field. You should now adapt to your code.\nOther alternative is to make a for/while loop in your template and do the form in HTML, but django forms rock for some reason, right?\n", "Use either multiple forms (django.forms.Form not the tag)\nclass Foo(forms.Form):\n field = forms.Charfield()\n\nforms = [Foo(prefix=i) for i in xrange(x)]\n\nor add multiple fields to the form dynamically using self.fields.\nclass Bar(forms.Form):\n def __init__(self, fields, *args, **kwargs):\n super(Bar, self).__init__(*args, **kwargs)\n for i in xrange(fields):\n self.fields['my_field_%i' % i] = forms.Charfield()\n\n" ]
[ 20, 7, 7 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0000411761_django_django_forms_python.txt
Q: How to access to the root path in a mod_python directory? In my Apache webserver I put this: <Directory /var/www/MYDOMAIN.com/htdocs> SetHandler mod_python PythonHandler mod_python.publisher PythonDebug On </Directory> Then I have a handler.py file with an index function. When I go to MYDOMAIN.com/handler.py, I see a web page produced by the index function (just a plain vanilla HTML page). Every other page is of this type: MYDOMAIN.com/handler.py/somename where somename corresponds to a funcion in handler.py file. But when I go to MYDOMAIN.com, I get this: Not Found The requested URL / was not found on this server. Is theres a way with mod_python and publisher to just use the root and not a name.py as a starting point? I already tried with this in the apache conf file: DirectoryIndex handler.py To no avail :( A: Yes, but you need to create your own handler. You currently use publisher, it just checks the URI and loads given python module. To create your own handler you need to create a module like this (just a minimalistic example): from mod_python import apache def requesthandler(req): req.content_type = "text/plain" req.write("Hello World!") return apache.OK Then you just point to it in Apache configuration. You can still use publisher handler inside your own handler, although you can't have pretty URLs with it AFAIK. A: Try creating an empty file called index (or whatever) in the directory and then use DirectoryIndex index Seems like DirectoryIndex checking is done watching the filesystem.
How to access to the root path in a mod_python directory?
In my Apache webserver I put this: <Directory /var/www/MYDOMAIN.com/htdocs> SetHandler mod_python PythonHandler mod_python.publisher PythonDebug On </Directory> Then I have a handler.py file with an index function. When I go to MYDOMAIN.com/handler.py, I see a web page produced by the index function (just a plain vanilla HTML page). Every other page is of this type: MYDOMAIN.com/handler.py/somename where somename corresponds to a funcion in handler.py file. But when I go to MYDOMAIN.com, I get this: Not Found The requested URL / was not found on this server. Is theres a way with mod_python and publisher to just use the root and not a name.py as a starting point? I already tried with this in the apache conf file: DirectoryIndex handler.py To no avail :(
[ "Yes, but you need to create your own handler. You currently use publisher, it just checks the URI and loads given python module.\nTo create your own handler you need to create a module like this (just a minimalistic example):\nfrom mod_python import apache\n\ndef requesthandler(req):\n req.content_type = \"text/plain\"\n req.write(\"Hello World!\")\n return apache.OK\n\nThen you just point to it in Apache configuration.\nYou can still use publisher handler inside your own handler, although you can't have pretty URLs with it AFAIK.\n", "Try creating an empty file called index (or whatever) in the directory and then use\nDirectoryIndex index\n\nSeems like DirectoryIndex checking is done watching the filesystem.\n" ]
[ 2, 0 ]
[]
[]
[ "mod_python", "publisher", "python" ]
stackoverflow_0000412498_mod_python_publisher_python.txt
Q: Algorithm to keep a list of percentages to add up to 100% (code examples are python) Lets assume we have a list of percentages that add up to 100: mylist = [2.0, 7.0, 12.0, 35.0, 21.0, 23.0] Some values of mylist may be changed, others must stay fixed. Lets assume the first 3 (2.0, 7.0, 12.0) must stay fixed and the last three (35.0, 21.0, 23.0) may be changed. fix = mylist[:3] vari = mylist[3:] The goal is to add a new item to mylist, while sum(mylist) stays 100.0 and vari items keep their relations to each other. For that we need to substract a CERTAIN PERCENTAGE from each vari item. Example: lets assume we want to add 4.0 to mylist. Using an ugly aproximation loop I found out that i need to substract ca. 5.0634% of each vari item (CERTAIN PERCENTAGE = 5.0634): adjusted =[] for number in vari: adjusted.append(number-(number*(5.0634/100.0))) adjusted.extend(fix) adjusted.append(4.0) adjusted now contains my desired result. My question is how to calculate CERTAIN PERCENTAGE ;.) A: How's this? def adjustAppend( v, n ): weight= -n/sum(v) return [ i+i*weight for i in v ] + [n] Given a list of numbers v, append a new number, n. Weight the existing number to keep the sum the same. sum(v) == sum( v + [n] ) Each element of v, i, must be reduced by some function of i, r(i) such that sum(r(i)) == -n or sum( map( r, v ) ) == -n Therefore, the weighting function is -(n*i)/sum(v) A: you're being silly. let's say you want to add 4.0 to the list. You don't need to subtract a certain amount from each one. What you need to do is multiply each item. 100 - 4 = 96. therefore, multiply each item by 0.96 you want to add 20.0 as an item. so then you multiply each item by 0.8, which is (100-20)*0.01 update: Hrmn I didn't read carefuly enough. think of it like this. (fixed)+(vari)= 100; (fixed)+(vari * x) + newitem = 100; so basically like what we did before except with just the vari portion. if vari totals to 50, and the new item you're adding is 3.0, then multiply each item in vari by (47/50) A: new_item = 4.0 CERTAIN_PERCENTAGE = 100 * (float(new_item) / sum(vari)) A: NEW_NUMBER = 4.0 mylist = [2.0, 7.0, 12.0, 35.0, 21.0, 23.0] fix = mylist[:3] vari = mylist[3:] weight = (100 - sum(fix) - NEW_NUMBER)/sum(vari) adjusted = [] adjusted.extend( (weight*v for v in vari) ) adjusted.extend(fix) adjusted.append(NEW_NUMBER) print sum(adjusted) # 100.0 Edit: Triptych is right, if you are actually interested in the certain percentage, the following code goes for it: certain_percentage = 100 * NEW_NUMBER / sum(vari) print certain_percentage # 5.06329113924 I think that your constant 5.0634 should actually be 5.0633.
Algorithm to keep a list of percentages to add up to 100%
(code examples are python) Lets assume we have a list of percentages that add up to 100: mylist = [2.0, 7.0, 12.0, 35.0, 21.0, 23.0] Some values of mylist may be changed, others must stay fixed. Lets assume the first 3 (2.0, 7.0, 12.0) must stay fixed and the last three (35.0, 21.0, 23.0) may be changed. fix = mylist[:3] vari = mylist[3:] The goal is to add a new item to mylist, while sum(mylist) stays 100.0 and vari items keep their relations to each other. For that we need to substract a CERTAIN PERCENTAGE from each vari item. Example: lets assume we want to add 4.0 to mylist. Using an ugly aproximation loop I found out that i need to substract ca. 5.0634% of each vari item (CERTAIN PERCENTAGE = 5.0634): adjusted =[] for number in vari: adjusted.append(number-(number*(5.0634/100.0))) adjusted.extend(fix) adjusted.append(4.0) adjusted now contains my desired result. My question is how to calculate CERTAIN PERCENTAGE ;.)
[ "How's this?\ndef adjustAppend( v, n ):\n weight= -n/sum(v)\n return [ i+i*weight for i in v ] + [n]\n\nGiven a list of numbers v, append a new number, n.\nWeight the existing number to keep the sum the same.\n sum(v) == sum( v + [n] )\n\nEach element of v, i, must be reduced by some function of i, r(i) such that\nsum(r(i)) == -n\n\nor\nsum( map( r, v ) ) == -n\n\nTherefore, the weighting function is -(n*i)/sum(v)\n", "you're being silly.\nlet's say you want to add 4.0 to the list. You don't need to subtract a certain amount from each one. What you need to do is multiply each item.\n100 - 4 = 96.\ntherefore, multiply each item by\n0.96\nyou want to add 20.0 as an item. so then you multiply each item by 0.8, which is (100-20)*0.01\nupdate: Hrmn I didn't read carefuly enough.\nthink of it like this.\n(fixed)+(vari)= 100;\n(fixed)+(vari * x) + newitem = 100;\nso basically like what we did before except with just the vari portion. if vari totals to 50, and the new item you're adding is 3.0, then multiply each item in vari by (47/50)\n", "new_item = 4.0\nCERTAIN_PERCENTAGE = 100 * (float(new_item) / sum(vari)) \n\n", "NEW_NUMBER = 4.0\n\nmylist = [2.0, 7.0, 12.0, 35.0, 21.0, 23.0]\nfix = mylist[:3]\nvari = mylist[3:]\n\nweight = (100 - sum(fix) - NEW_NUMBER)/sum(vari)\n\nadjusted = []\nadjusted.extend( (weight*v for v in vari) )\nadjusted.extend(fix)\nadjusted.append(NEW_NUMBER)\n\nprint sum(adjusted) # 100.0\n\nEdit: Triptych is right, \nif you are actually interested in the certain percentage, the following code goes for it:\ncertain_percentage = 100 * NEW_NUMBER / sum(vari)\nprint certain_percentage # 5.06329113924\n\nI think that your constant 5.0634 should actually be 5.0633.\n" ]
[ 9, 3, 3, 1 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0000412943_algorithm_python.txt
Q: Apps Similar to Nodebox? I'm looking for apps/environments similar to Nodebox. Nodebox is so cool and I want to know if there were other similar apps out there. They don't have to be graphics-related; I'm interested in software that uses programming languages in a new way. A: http://processing.org/ is a language for creating graphics and animations similar to Nodebox. A: it was referenced on @Jonas processing.org, but alice.org is interesting.
Apps Similar to Nodebox?
I'm looking for apps/environments similar to Nodebox. Nodebox is so cool and I want to know if there were other similar apps out there. They don't have to be graphics-related; I'm interested in software that uses programming languages in a new way.
[ "http://processing.org/ is a language for creating graphics and animations similar to Nodebox.\n", "it was referenced on @Jonas processing.org, but alice.org is interesting.\n" ]
[ 5, 0 ]
[]
[]
[ "nodebox", "python" ]
stackoverflow_0000412775_nodebox_python.txt
Q: Django and units conversion I need to store some values in the database, distance, weight etc. In my model, I have field that contains quantity of something and IntegerField with choices option, that determines what this quantity means (length, time duration etc). Should I create a model for units and physical quantity or should I use IntegerField that contains the type of unit? A: By field(enum)" do you mean you are using the choices option on a field? A simple set of choices works out reasonably well for small lists of conversions. It allows you to make simplifying assumptions that helps your users (and you) get something that works. Creating a formal model for units should only be done if you have (a) a LOT of units involved, (b) your need to extend it, AND (c) there's some rational expectation that the DB lookups will be of some value. Units don't change all that often. There seems little reason to use the database for this. It seems a lot simpler to hard-code the list of choices. Choices You can, for example, use something like this to keep track of conversions. UNIT_CHOICES = ( ('m', 'meters'), ('f', 'feet' ), ('i', 'inches'), ('pt', 'points') ) unit_conversions = { ('m','f'): 3.xyz, ('m','i'): 39.xyz, ('m','pt'): 29.xyz*72, ('f','m'): 1/3.xyz, ('f','i'): 12.0, ('f','pt'): 12.0*72, etc. } Given this mapping, you can get a conversion factor in your conversion method function, do the math, and return the converted unit. class WithUnit( Model ): ... def toUnit( self, someUnit ): if someUnit == self.unit: return self.value elif (someUnit,self.unit) in unit_conversions: return self.value * unit_conversions[(someUnit,self.unit)] else: raise Exception( "Can't convert" ) Model. If you want to create a formal model for units, you have to carry around the kind of dimension (length, volume, mass, weight/force, pressure, temperature, etc.) and the various unit conversion factors. This works for everything but temperature, where you have a constant term in addition to a factor. You have to pick a "baseline" set of units (e.g., MKS) and carry all the multipliers among the various units. You also have to choose how many of the Imperial units to load into your table (fluid ounces, teaspoons, tablespoons, cups, pints, quarts, etc.) A: It depends on how you want to use it. Let's say you have length value and two possible units, cm and mm. If you want only to print the value later, you can always print it as [value]&nbsp;[unit]. However, if you want to do some calculations with the value, for instance, calculate the area, you need to convert the values to the same units. So you have to define unit conversion table anyway. I would convert the units to the same internal unit before I store them in the database, rather than converting them every time I use them. I would add a model for units and physical quantities only if there are too many of them and the conversion is really tricky. Such a model could work as a converter. But for simple cases, like mm⇒cm or inch⇒cm, a static conversion table would suffice. A: Use a field that indicates the type of measure (weight, length, etc.), and store the value in another field. That should be sufficient. The unit of measure should be implicit. I'm assuming you are using the same unit of measure for each measure type, for example always meters for length. A concrete example: let's say you have two entities, "Car" and "CarMeasures". I'd write the model this way: class Car(models.Model): type=models.CharField(max_length=256); class CarMeasures(models.Model): carId=models.ForeignKey(Car); measureValue=models.DecimalField(..., max_digits=10, decimal_places=2); measureType=models.CharField(max_length=32);
Django and units conversion
I need to store some values in the database, distance, weight etc. In my model, I have field that contains quantity of something and IntegerField with choices option, that determines what this quantity means (length, time duration etc). Should I create a model for units and physical quantity or should I use IntegerField that contains the type of unit?
[ "By field(enum)\" do you mean you are using the choices option on a field? \nA simple set of choices works out reasonably well for small lists of conversions. It allows you to make simplifying assumptions that helps your users (and you) get something that works.\nCreating a formal model for units should only be done if you have (a) a LOT of units involved, (b) your need to extend it, AND (c) there's some rational expectation that the DB lookups will be of some value. \nUnits don't change all that often. There seems little reason to use the database for this. It seems a lot simpler to hard-code the list of choices.\nChoices\nYou can, for example, use something like this to keep track of conversions.\nUNIT_CHOICES = ( ('m', 'meters'), ('f', 'feet' ), ('i', 'inches'), ('pt', 'points') )\n\nunit_conversions = {\n ('m','f'): 3.xyz,\n ('m','i'): 39.xyz,\n ('m','pt'): 29.xyz*72,\n ('f','m'): 1/3.xyz,\n ('f','i'): 12.0,\n ('f','pt'): 12.0*72,\n etc.\n}\n\nGiven this mapping, you can get a conversion factor in your conversion method\nfunction, do the math, and return the converted unit.\nclass WithUnit( Model ):\n ...\n def toUnit( self, someUnit ):\n if someUnit == self.unit: return self.value\n elif (someUnit,self.unit) in unit_conversions:\n return self.value * unit_conversions[(someUnit,self.unit)]\n else:\n raise Exception( \"Can't convert\" )\n\nModel.\nIf you want to create a formal model for units, you have to carry around the kind of dimension (length, volume, mass, weight/force, pressure, temperature, etc.) and the various unit conversion factors. This works for everything but temperature, where you have a constant term in addition to a factor. \nYou have to pick a \"baseline\" set of units (e.g., MKS) and carry all the multipliers among the various units.\nYou also have to choose how many of the Imperial units to load into your table (fluid ounces, teaspoons, tablespoons, cups, pints, quarts, etc.)\n", "It depends on how you want to use it. Let's say you have length value and two possible units, cm and mm. If you want only to print the value later, you can always print it as [value]&nbsp;[unit].\nHowever, if you want to do some calculations with the value, for instance, calculate the area, you need to convert the values to the same units. So you have to define unit conversion table anyway.\nI would convert the units to the same internal unit before I store them in the database, rather than converting them every time I use them.\nI would add a model for units and physical quantities only if there are too many of them and the conversion is really tricky. Such a model could work as a converter. But for simple cases, like mm⇒cm or inch⇒cm, a static conversion table would suffice.\n", "Use a field that indicates the type of measure (weight, length, etc.), and store the value in another field. That should be sufficient. The unit of measure should be implicit.\nI'm assuming you are using the same unit of measure for each measure type, for example always meters for length.\nA concrete example: let's say you have two entities, \"Car\" and \"CarMeasures\". I'd write the model this way:\nclass Car(models.Model):\n type=models.CharField(max_length=256);\n\nclass CarMeasures(models.Model):\n carId=models.ForeignKey(Car);\n measureValue=models.DecimalField(..., max_digits=10, decimal_places=2);\n measureType=models.CharField(max_length=32);\n\n" ]
[ 4, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000413446_django_python.txt
Q: Is there a Python library than can simulate network traffic from different addresses Is there a python library out there than can allow me to send UDP packets to a machine (sending to localhost is ok) from different source addresses and ports? I remember that one existed, but can't find it anymore. A: You can spoof an IP address using Scapy library. Here's an example from Packet Wizardry: Ruling the Network with Python: #!/usr/bin/env python import sys from scapy import * conf.verb=0 if len(sys.argv) != 4: print "Usage: ./spoof.py <target> <spoofed_ip> <port>" sys.exit(1) target = sys.argv[1] spoofed_ip = sys.argv[2] port = int(sys.argv[3]) p1=IP(dst=target,src=spoofed_ip)/TCP(dport=port,sport=5000,flags='S') send(p1) print "Okay, SYN sent. Enter the sniffed sequence number now: " seq=sys.stdin.readline() print "Okay, using sequence number " + seq seq=int(seq[:-1]) p2=IP(dst=target,src=spoofed_ip)/TCP(dport=port,sport=5000,flags='A', ack=seq+1,seq=1) send(p2) print "Okay, final ACK sent. Check netstat on your target :-)"
Is there a Python library than can simulate network traffic from different addresses
Is there a python library out there than can allow me to send UDP packets to a machine (sending to localhost is ok) from different source addresses and ports? I remember that one existed, but can't find it anymore.
[ "You can spoof an IP address using Scapy library.\nHere's an example from Packet Wizardry: Ruling the Network with Python:\n#!/usr/bin/env python\nimport sys\nfrom scapy import *\nconf.verb=0\n\nif len(sys.argv) != 4:\n print \"Usage: ./spoof.py <target> <spoofed_ip> <port>\"\n sys.exit(1)\n\ntarget = sys.argv[1]\nspoofed_ip = sys.argv[2]\nport = int(sys.argv[3])\n\np1=IP(dst=target,src=spoofed_ip)/TCP(dport=port,sport=5000,flags='S')\nsend(p1)\nprint \"Okay, SYN sent. Enter the sniffed sequence number now: \"\n\nseq=sys.stdin.readline()\nprint \"Okay, using sequence number \" + seq\n\nseq=int(seq[:-1])\np2=IP(dst=target,src=spoofed_ip)/TCP(dport=port,sport=5000,flags='A',\n ack=seq+1,seq=1)\nsend(p2)\n\nprint \"Okay, final ACK sent. Check netstat on your target :-)\"\n\n" ]
[ 20 ]
[]
[]
[ "networking", "python" ]
stackoverflow_0000414025_networking_python.txt
Q: python "'NoneType' object has no attribute 'encode'" I wrote this tiny Python snippet that scrapes a feed and prints it out. When I run the code, something in the feed triggers the error message you see here as my question. Here's the complete console output on error: > Traceback (most recent call last): > File "/home/vijay/ffour/ffour5.py", > line 20, in <module> > myfeed() File "/home/vijay/ffour/ffour5.py", line > 15, in myfeed > sys.stdout.write(entry["title"]).encode('utf-8') > AttributeError: 'NoneType' object has > no attribute 'encode' A: > sys.stdout.write(entry["title"]).encode('utf-8') This is the culprit. You probably mean: sys.stdout.write(entry["title"].encode('utf-8')) (Notice the position of the last closing bracket.) A: Lets try to clear up some of the confusion in the exception message. The function call sys.stdout.write(entry["title"]) Returns None. The ".encode('utf-8')" is a call to the encode function on what is returned by the above function. The problem is that None doesn't have an encode function (or an encode attribute) and so you get an attribute error that names the type you were trying to get an attribute of and the attribute you were trying to get.
python "'NoneType' object has no attribute 'encode'"
I wrote this tiny Python snippet that scrapes a feed and prints it out. When I run the code, something in the feed triggers the error message you see here as my question. Here's the complete console output on error: > Traceback (most recent call last): > File "/home/vijay/ffour/ffour5.py", > line 20, in <module> > myfeed() File "/home/vijay/ffour/ffour5.py", line > 15, in myfeed > sys.stdout.write(entry["title"]).encode('utf-8') > AttributeError: 'NoneType' object has > no attribute 'encode'
[ "\n> sys.stdout.write(entry[\"title\"]).encode('utf-8')\n\n\nThis is the culprit. You probably mean:\nsys.stdout.write(entry[\"title\"].encode('utf-8'))\n\n(Notice the position of the last closing bracket.)\n", "Lets try to clear up some of the confusion in the exception message.\nThe function call\nsys.stdout.write(entry[\"title\"])\n\nReturns None. The \".encode('utf-8')\" is a call to the encode function on what is returned by the above function.\nThe problem is that None doesn't have an encode function (or an encode attribute) and so you get an attribute error that names the type you were trying to get an attribute of and the attribute you were trying to get.\n" ]
[ 12, 5 ]
[]
[]
[ "python", "urlencode" ]
stackoverflow_0000414230_python_urlencode.txt
Q: How to bring program to front using python I would like to force my python app to the front if a condition occurs. I'm using Kubuntu & QT3.1 I've tried setActiveWindow(), but it only flashes the task bar in KDE. I think Windows has a function bringwindowtofront() for VB. Is there something similar for KDE? A: Check if KWin is configured to prevent focus stealing. There might be nothing wrong with your code -- but we linux people don't like applications bugging us when we work, so stealing focus is kinda frowned upon, and difficult under some window managers. A: Have you tried using those 3 (in this order) on your window instead of only setActiveWindow? show() raise() # this might be raiseW() in Python setActiveWindow() A: It works! show() raiseW() setActiveWindow() #in that sequence plus KWin config change to force focus steal prevention. Thanks for the help.
How to bring program to front using python
I would like to force my python app to the front if a condition occurs. I'm using Kubuntu & QT3.1 I've tried setActiveWindow(), but it only flashes the task bar in KDE. I think Windows has a function bringwindowtofront() for VB. Is there something similar for KDE?
[ "Check if KWin is configured to prevent focus stealing.\nThere might be nothing wrong with your code -- but we linux people don't like applications bugging us when we work, so stealing focus is kinda frowned upon, and difficult under some window managers.\n", "Have you tried using those 3 (in this order) on your window instead of only setActiveWindow?\nshow()\nraise() # this might be raiseW() in Python\nsetActiveWindow()\n\n", "It works!\nshow()\nraiseW()\nsetActiveWindow() #in that sequence\n\nplus KWin config change to force focus steal prevention.\nThanks for the help.\n" ]
[ 4, 1, 1 ]
[]
[]
[ "python", "qt" ]
stackoverflow_0000412214_python_qt.txt
Q: How to (simply) connect Python to my web site? I've been playing with Python for a while and wrote a little program to make a database to keep track of some info (its really basic, and hand written). I want to add the ability to create a website from the data that I will then pass to my special little place on the internet. What should I use to build up the website? After dabbling with Django, I've found it overkill and over my head, but if that's the only option I'll learn to use it. Does anyone know an easy way to output a database of arbitrary format to one or more HTML (or different format) files? A: I would generate a page or two of HTML using a template engine (Jinja is my personal choice) and just stick them in your public_html directory or wherever the webserver's root is. A: Generating static HTML is great, if that works for you go for it. If you want a dynamic website and the ability to update, web.py might work for you. Simpler than Django and stand-alone (although just about everything I start in web.py eventually gets rewritten as a Django app...)
How to (simply) connect Python to my web site?
I've been playing with Python for a while and wrote a little program to make a database to keep track of some info (its really basic, and hand written). I want to add the ability to create a website from the data that I will then pass to my special little place on the internet. What should I use to build up the website? After dabbling with Django, I've found it overkill and over my head, but if that's the only option I'll learn to use it. Does anyone know an easy way to output a database of arbitrary format to one or more HTML (or different format) files?
[ "I would generate a page or two of HTML using a template engine (Jinja is my personal choice) and just stick them in your public_html directory or wherever the webserver's root is.\n", "Generating static HTML is great, if that works for you go for it. \nIf you want a dynamic website and the ability to update, web.py might work for you. Simpler than Django and stand-alone (although just about everything I start in web.py eventually gets rewritten as a Django app...)\n" ]
[ 12, 0 ]
[]
[]
[ "python", "web" ]
stackoverflow_0000412368_python_web.txt
Q: URLs: Binary Blob, Unicode or Encoded Unicode String? I wish to store URLs in a database (MySQL in this case) and process it in Python. Though the database and programming language are probably not this relevant to my question. In my setup I receive unicode strings when querying a text field in the database. But is a URL actually text? Is encoding from and decoding to unicode an operation that should be done to a URL? Or is it better to make the column in the database a binary blob? So, how do you handle this problem? Clarification: This question is not about urlencoding non-ASCII characters with the percent notation. It's about the distiction that unicode represents text and byte strings represent a way to encode this text into a sequence of bytes. In Python (prior to 3.0) this distinction is between the unicode and the str types. In MySQL it is TEXT to BLOBS. So the concepts seem to correspond between programming language and database. But what is the best way to handle URLs in this scheme? A: The relevant answer is found in RFC 2396, section 2.1 URI and non-ASCII characters The relationship between URI and characters has been a source of confusion for characters that are not part of US-ASCII. To describe the relationship, it is useful to distinguish between a "character" (as a distinguishable semantic entity) and an "octet" (an 8-bit byte). There are two mappings, one from URI characters to octets, and a second from octets to original characters: URI character sequence->octet sequence->original character sequence A URI is represented as a sequence of characters, not as a sequence of octets. That is because URI might be "transported" by means that are not through a computer network, e.g., printed on paper, read over the radio, etc. A: On the question: "But is a URL actually text?" It depends on the context, in some languages or libraries (for example java, I'm not sure about python), a URL may be represented internally as an object. However, a URL always has a well defined text representation. So storing the text-representation is much more portable than storing the internal representation used by whatever is the current language of choice. URL syntax and semantics are covered by quite a few standards, recommendations and implementations, but I think the most authoritative source for parsing and constructing correct URL-s would be RFC 2396. On the question about unicode, section 2.1 deals with non-ascii characters. (Edit: changed rfc-reference to the newest edition, thank you S.Lott) A: Do note there is also a standard for Unicode Web addresses, IRI (Internationalized Resource Identifiers). RFC 3987
URLs: Binary Blob, Unicode or Encoded Unicode String?
I wish to store URLs in a database (MySQL in this case) and process it in Python. Though the database and programming language are probably not this relevant to my question. In my setup I receive unicode strings when querying a text field in the database. But is a URL actually text? Is encoding from and decoding to unicode an operation that should be done to a URL? Or is it better to make the column in the database a binary blob? So, how do you handle this problem? Clarification: This question is not about urlencoding non-ASCII characters with the percent notation. It's about the distiction that unicode represents text and byte strings represent a way to encode this text into a sequence of bytes. In Python (prior to 3.0) this distinction is between the unicode and the str types. In MySQL it is TEXT to BLOBS. So the concepts seem to correspond between programming language and database. But what is the best way to handle URLs in this scheme?
[ "The relevant answer is found in RFC 2396, section \n2.1 URI and non-ASCII characters\n\nThe relationship between URI and characters has been a source of\nconfusion for characters that are not part of US-ASCII. To describe\nthe relationship, it is useful to distinguish between a \"character\"\n(as a distinguishable semantic entity) and an \"octet\" (an 8-bit\nbyte). There are two mappings, one from URI characters to octets, and\na second from octets to original characters:\nURI character sequence->octet sequence->original character sequence\nA URI is represented as a sequence of characters, not as a sequence\nof octets. That is because URI might be \"transported\" by means that\nare not through a computer network, e.g., printed on paper, read over\nthe radio, etc.\n\n", "On the question: \"But is a URL actually text?\"\nIt depends on the context, in some languages or libraries (for example java, I'm not sure about python), a URL may be represented internally as an object. However, a URL always has a well defined text representation. So storing the text-representation is much more portable than storing the internal representation used by whatever is the current language of choice.\nURL syntax and semantics are covered by quite a few standards, recommendations and implementations, but I think the most authoritative source for parsing and constructing correct URL-s would be RFC 2396.\nOn the question about unicode, section 2.1 deals with non-ascii characters.\n(Edit: changed rfc-reference to the newest edition, thank you S.Lott)\n", "Do note there is also a standard for Unicode Web addresses, IRI (Internationalized Resource Identifiers). RFC 3987\n" ]
[ 3, 1, 1 ]
[]
[]
[ "database", "mysql", "python", "url" ]
stackoverflow_0000416315_database_mysql_python_url.txt
Q: Filtering away nearby points from a list I half-answered a question about finding clusters of mass in a bitmap. I say half-answered because I left it in a condition where I had all the points in the bitmap sorted by mass and left it to the reader to filter the list removing points from the same cluster. Then when thinking about that step I found that the solution didn't jump out at me like I thought it would. So now I'm asking you guys for help. We have a list of points with masses like so (a Python list of tuples, but you can represent it as you see fit in any language): [ (6, 2, 6.1580555555555554), (2, 1, 5.4861111111111107), (1, 1, 4.6736111111111107), (1, 4, 4.5938888888888885), (2, 0, 4.54), (1, 5, 4.4480555555555554), (4, 7, 4.4480555555555554), (5, 7, 4.4059637188208614), (4, 8, 4.3659637188208613), (1, 0, 4.3611111111111107), (5, 8, 4.3342191043083904), (5, 2, 4.119574829931973), ... (8, 8, 0.27611111111111108), (0, 8, 0.24138888888888888) ] Each tuple is of the form: (x, y, mass) Note that the list is sorted here. If your solution prefers to not have them sorted it's perfectly OK. The challenge, if you recall, is to find the main clusters of mass. The number of clusters is not known. But you know the dimensions of the bitmap. Sometimes several points within a cluster has more mass than the center of the next (in size) cluster. So what I want to do is go from the higher-mass points and remove points in the same cluster (points nearby). When I tried this I ended up having to walk through parts of the list over and over again. I have a feeling I'm just stupid about it. How would you do it? Pseudo code or real code. Of course, if you can just take off where I left in that answer with Python code it's easier for me to experiment with it. Next step is to figure out how many clusters there really are in the bitmap. I'm still struggling with defining that problem so I might return with a question about it. EDIT: I should clarify that I know that there's no "correct" answer to this question. And the name of the question is key. Phase one of the my clustering is done. Im in search of a fast, accurate-"enough" method of filtering away nearby points. Let me know if you see how I can make the question clearer. A: Just so you know, you are asking for a solution to an ill-posed problem: no definitive solution exists. That's fine...it just makes it more fun. Your problem is ill-posed mostly because you don't know how many clusters you want. Clustering is one of the key areas of machine learning and there a quite a few approaches that have been developed over the years. As Arachnid pointed out, the k-means algorithm tends to be a good one and it's pretty easy to implement. The results depend critically on the initial guess made and on the number of desired clusters. To overcome the initial guess problem, it's common to run the algorithm many times with random initializations and pick the best result. You'll need to define what "best" means. One measure would be the mean squared distance of each point to its cluster center. If you want to automatically guess how many clusters there are, you should run the algorithm with a whole range of numbers of clusters. For any good "best" measure, more clusters will always look better than fewer, so you'll need a way to penalize having too many clusters. The MDL discussion on wikipedia is a good starting point. K-means clustering is basically the simplest mixture model. Sometimes it's helpful to upgrade to a mixture of Gaussians learned by expectation maximization (described in the link just given). This can be more robust than k-means. It takes a little more effort to understand it, but when you do, it's not much harder than k-means to implement. There are plenty of other clustering techniques such as agglomerative clustering and spectral clustering. Agglomerative clustering is pretty easy to implement, but choosing when to stop building the clusters can be tricky. If you do agglomerative clustering, you'll probably want to look at kd trees for faster nearest neighbor searches. smacl's answer describes one slightly different way of doing agglomerative clustering using a Voronoi diagram. There are models that can automatically choose the number of clusters for you such as ones based on Latent Dirichlet Allocation, but they are a lot harder to understand an implement correctly. You might also want to look at the mean-shift algorithm to see if it's closer to what you really want. A: It sounds to me like you're looking for the K-means algorithm. A: As I mentioned in the comment to your question, the answer is based on whether or not mass can be considered scalar in this context. If so, color based solutions are probably not going to work as color is often not taken as being scalar. For example, if I have a given area with 1 point of high mass, is that the same as having the same area with 10 points of 1/10 the mass? If this is true, mass is not scalar in this context, and I would tend to look at an algorithm used for spatially gouping similar non-scalable values, e.g. voronoi diagrams. In this case, where two adjacent voronoi areas have a close enough mass match and distance, they can be clustered together. You could repeat this to find all clusters. If on the other hand, your mass is scalable, or that the mass at an unknown position can be interpolated from surrounding points, I would tend to triangulate and contour the input data and use areas between contours to find clusters of similar mass. A: This sounds like color quantization, where you reduce the number of colors in an image. One way would be to plot the colors in space, and combine clusters into the center (or a weighted average) of a cluster. The exact name of the algorithm that triggered this memory fails me, but I'll edit the answer if it pops up, but in the meantime, you should look at color quantization and see if some of the algorithms are useful. A: Start with the "Convex Hull" problem. You're also looking for some "convex hull"-like clusters. Note that "clusters" is vague. You have an average mass across your field. Some points have above average mass, and some below average. How far above average means you've found a cluster? How far apart do nodes have to be to be part of a cluster or a separate cluster? What's the difference between two mountain peaks and a ridge? You have to compute a "topography" - joining all points with equal density into regions. This requires that you pick a spot and work your want out from a point radially, locating positions where the densities are equal. You can connect those points into regions. If you picked your initial point wisely, the regions should nest. Picking your starting point is easy because you start at local highs. A: Since you are already talking about mass, why not a gravity based solution. A simple particle system would not need to be super accurate, and you would not have to run it for too long before you could make a much better guess at the number of clusters. If you have a better idea about cluster numbers, k-means nearest neighbour becomes feasible.
Filtering away nearby points from a list
I half-answered a question about finding clusters of mass in a bitmap. I say half-answered because I left it in a condition where I had all the points in the bitmap sorted by mass and left it to the reader to filter the list removing points from the same cluster. Then when thinking about that step I found that the solution didn't jump out at me like I thought it would. So now I'm asking you guys for help. We have a list of points with masses like so (a Python list of tuples, but you can represent it as you see fit in any language): [ (6, 2, 6.1580555555555554), (2, 1, 5.4861111111111107), (1, 1, 4.6736111111111107), (1, 4, 4.5938888888888885), (2, 0, 4.54), (1, 5, 4.4480555555555554), (4, 7, 4.4480555555555554), (5, 7, 4.4059637188208614), (4, 8, 4.3659637188208613), (1, 0, 4.3611111111111107), (5, 8, 4.3342191043083904), (5, 2, 4.119574829931973), ... (8, 8, 0.27611111111111108), (0, 8, 0.24138888888888888) ] Each tuple is of the form: (x, y, mass) Note that the list is sorted here. If your solution prefers to not have them sorted it's perfectly OK. The challenge, if you recall, is to find the main clusters of mass. The number of clusters is not known. But you know the dimensions of the bitmap. Sometimes several points within a cluster has more mass than the center of the next (in size) cluster. So what I want to do is go from the higher-mass points and remove points in the same cluster (points nearby). When I tried this I ended up having to walk through parts of the list over and over again. I have a feeling I'm just stupid about it. How would you do it? Pseudo code or real code. Of course, if you can just take off where I left in that answer with Python code it's easier for me to experiment with it. Next step is to figure out how many clusters there really are in the bitmap. I'm still struggling with defining that problem so I might return with a question about it. EDIT: I should clarify that I know that there's no "correct" answer to this question. And the name of the question is key. Phase one of the my clustering is done. Im in search of a fast, accurate-"enough" method of filtering away nearby points. Let me know if you see how I can make the question clearer.
[ "Just so you know, you are asking for a solution to an ill-posed problem: no definitive solution exists. That's fine...it just makes it more fun. Your problem is ill-posed mostly because you don't know how many clusters you want. Clustering is one of the key areas of machine learning and there a quite a few approaches that have been developed over the years.\nAs Arachnid pointed out, the k-means algorithm tends to be a good one and it's pretty easy to implement. The results depend critically on the initial guess made and on the number of desired clusters. To overcome the initial guess problem, it's common to run the algorithm many times with random initializations and pick the best result. You'll need to define what \"best\" means. One measure would be the mean squared distance of each point to its cluster center. If you want to automatically guess how many clusters there are, you should run the algorithm with a whole range of numbers of clusters. For any good \"best\" measure, more clusters will always look better than fewer, so you'll need a way to penalize having too many clusters. The MDL discussion on wikipedia is a good starting point. \nK-means clustering is basically the simplest mixture model. Sometimes it's helpful to upgrade to a mixture of Gaussians learned by expectation maximization (described in the link just given). This can be more robust than k-means. It takes a little more effort to understand it, but when you do, it's not much harder than k-means to implement. \nThere are plenty of other clustering techniques such as agglomerative clustering and spectral clustering. Agglomerative clustering is pretty easy to implement, but choosing when to stop building the clusters can be tricky. If you do agglomerative clustering, you'll probably want to look at kd trees for faster nearest neighbor searches. smacl's answer describes one slightly different way of doing agglomerative clustering using a Voronoi diagram.\nThere are models that can automatically choose the number of clusters for you such as ones based on Latent Dirichlet Allocation, but they are a lot harder to understand an implement correctly. \nYou might also want to look at the mean-shift algorithm to see if it's closer to what you really want.\n", "It sounds to me like you're looking for the K-means algorithm.\n", "As I mentioned in the comment to your question, the answer is based on whether or not mass can be considered scalar in this context. If so, color based solutions are probably not going to work as color is often not taken as being scalar.\nFor example, if I have a given area with 1 point of high mass, is that the same as having the same area with 10 points of 1/10 the mass? If this is true, mass is not scalar in this context, and I would tend to look at an algorithm used for spatially gouping similar non-scalable values, e.g. voronoi diagrams.\n\nIn this case, where two adjacent voronoi areas have a close enough mass match and distance, they can be clustered together. You could repeat this to find all clusters.\nIf on the other hand, your mass is scalable, or that the mass at an unknown position can be interpolated from surrounding points, I would tend to triangulate and contour the input data and use areas between contours to find clusters of similar mass.\n", "This sounds like color quantization, where you reduce the number of colors in an image. One way would be to plot the colors in space, and combine clusters into the center (or a weighted average) of a cluster.\nThe exact name of the algorithm that triggered this memory fails me, but I'll edit the answer if it pops up, but in the meantime, you should look at color quantization and see if some of the algorithms are useful.\n", "Start with the \"Convex Hull\" problem. You're also looking for some \"convex hull\"-like clusters.\nNote that \"clusters\" is vague. You have an average mass across your field. Some points have above average mass, and some below average. How far above average means you've found a cluster? How far apart do nodes have to be to be part of a cluster or a separate cluster?\nWhat's the difference between two mountain peaks and a ridge? \nYou have to compute a \"topography\" - joining all points with equal density into regions. This requires that you pick a spot and work your want out from a point radially, locating positions where the densities are equal. You can connect those points into regions.\nIf you picked your initial point wisely, the regions should nest. Picking your starting point is easy because you start at local highs.\n", "Since you are already talking about mass, why not a gravity based solution. A simple particle system would not need to be super accurate, and you would not have to run it for too long before you could make a much better guess at the number of clusters.\nIf you have a better idea about cluster numbers, k-means nearest neighbour becomes feasible.\n" ]
[ 5, 4, 3, 1, 1, 1 ]
[]
[]
[ "algorithm", "bitmap", "filtering", "language_agnostic", "python" ]
stackoverflow_0000416406_algorithm_bitmap_filtering_language_agnostic_python.txt
Q: Implementing a buffer-like structure in Python I'm trying to write a small wsgi application which will put some objects to an external queue after each request. I want to make this in batch, ie. make the webserver put the object to a buffer-like structure in memory, and another thread and/or process for sending these objects to the queue in batch, when buffer is big enough or after certain timeout, and clearing the buffer. I don't want to be in NIH syndrome and not want to bother with threading stuff, however I could not find a suitable code for this job. Any suggestions? A: Examine https://docs.python.org/library/queue.html to see if it meets your needs. A: Since you write "thread and/or process", see also multiprocessing.Queue and multiprocessing.JoinableQueue from 2.6. Those are interprocess variants of Queue. A: Use a buffered stream if you are using python 3.0.
Implementing a buffer-like structure in Python
I'm trying to write a small wsgi application which will put some objects to an external queue after each request. I want to make this in batch, ie. make the webserver put the object to a buffer-like structure in memory, and another thread and/or process for sending these objects to the queue in batch, when buffer is big enough or after certain timeout, and clearing the buffer. I don't want to be in NIH syndrome and not want to bother with threading stuff, however I could not find a suitable code for this job. Any suggestions?
[ "Examine https://docs.python.org/library/queue.html to see if it meets your needs.\n", "Since you write \"thread and/or process\", see also multiprocessing.Queue and multiprocessing.JoinableQueue from 2.6. Those are interprocess variants of Queue.\n", "Use a buffered stream if you are using python 3.0.\n" ]
[ 8, 3, 1 ]
[]
[]
[ "data_structures", "message_queue", "multithreading", "python" ]
stackoverflow_0000410273_data_structures_message_queue_multithreading_python.txt
Q: What does "|" sign mean in a Django template? I often see something like that: something.property|escape something is an object, property is it's string property. escape - i don't know :) What does this mean? And what min python version it is used in? EDIT: The question was asked wrongly, it said "What does | mean in Python", so the bitwise or answers are correct, but irrelevant, please do not downvote them A: The pipe character indicates that you want to send the results of the left hand side to the filter defined on the right side. The filter will modify the value in some way. The 'escape' filter is just one of many. The list of built in filters can be found here: Django Documentation - Built-in filters reference In a django template the | character definitely does not mean the 'bitwise OR' operator. A: obj.property|escape is the way to apply the escape filter in a template, which will HTML escape the string representation of that property.
What does "|" sign mean in a Django template?
I often see something like that: something.property|escape something is an object, property is it's string property. escape - i don't know :) What does this mean? And what min python version it is used in? EDIT: The question was asked wrongly, it said "What does | mean in Python", so the bitwise or answers are correct, but irrelevant, please do not downvote them
[ "The pipe character indicates that you want to send the results of the left hand side to the filter defined on the right side. The filter will modify the value in some way. \nThe 'escape' filter is just one of many.\nThe list of built in filters can be found here: \nDjango Documentation - Built-in filters reference\nIn a django template the | character definitely does not mean the 'bitwise OR' operator.\n", "obj.property|escape is the way to apply the escape filter in a template, which will HTML escape the string representation of that property.\n" ]
[ 14, 10 ]
[ "It's a bitwise \"or\". It means escape if the property doesn't exist/is null.\n" ]
[ -3 ]
[ "django", "django_templates", "python" ]
stackoverflow_0000417265_django_django_templates_python.txt
Q: What are "first-class" objects? When are objects or something else said to be "first-class" in a given programming language, and why? In what way do they differ from languages where they are not? When one says "everything is an object" (like in Python), do they indeed mean that "everything is first-class"? A: In short, it means there are no restrictions on the object's use. It's the same as any other object. A first class object is an entity that can be dynamically created, destroyed, passed to a function, returned as a value, and have all the rights as other variables in the programming language have. Depending on the language, this can imply: being expressible as an anonymous literal value being storable in variables being storable in data structures having an intrinsic identity (independent of any given name) being comparable for equality with other entities being passable as a parameter to a procedure/function being returnable as the result of a procedure/function being constructible at runtime being printable being readable being transmissible among distributed processes being storable outside running processes Source. In C++ functions themselves are not first class objects, however: You can override the '()' operator making it possible to have an object function, which is first class. Function pointers are first class. boost bind, lambda and function do offer first class functions In C++, classes are not first class objects but instances of those classes are. In Python both the classes and the objects are first class objects. (See this answer for more details about classes as objects). Here is an example of Javascript first class functions: // f: function that takes a number and returns a number // deltaX: small positive number // returns a function that is an approximate derivative of f function makeDerivative( f, deltaX ) { var deriv = function(x) { return ( f(x + deltaX) - f(x) )/ deltaX; } return deriv; } var cos = makeDerivative( Math.sin, 0.000001); // cos(0) ~> 1 // cos(pi/2) ~> 0 Source. Entities that are not first class objects are referred to as second-class objects. Functions in C++ are second class because they can't be dynamically created. Regarding the edit: EDIT. When one says "everything is an object" (like in Python), does he indeed mean that "everything is first-class"? The term object can be used loosely and doesn't imply being first class. And it would probably make more sense to call the whole concept 'first class entities'. But in Python they do aim to make everything first class. I believe the intent of the person who made your statement meant first class. A: "When one says "everything is an object" (like in Python), does he indeed mean that "everything is first-class"?" Yes. Everything in Python is a proper object. Even things that are "primitive types" in other languages. You find that an object like 2 actually has a fairly rich and sophisticated interface. >>> dir(2) ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__', '__xor__'] Because everything's a first-class object in Python, there are relatively few obscure special cases. In Java, for example, there are primitive types (int, bool, double, char) that aren't proper objects. That's why Java has to introduce Integer, Boolean, Double, and Character as first-class types. This can be hard to teach to beginners -- it isn't obvious why both a primitive type and a class have to exist side-by-side. It also means that an object's class is -- itself -- an object. This is different from C++, where the classes don't always have a distinct existence at run-time. The type of 2 is the type 'int' object, which has methods, attributes, and a type. >>> type(2) <class 'int'> The type of a built-in type like int is the type 'type' object. This has methods and attributes, also. >>> type(type(2)) <class 'type'> A: “First class” means you can operate on them in the usual manner. Most of the times, this just means you can pass these first-class citizens as arguments to functions, or return them from functions. This is self-evident for objects but not always so evident for functions, or even classes: void f(int n) { return n * 2; } void g(Action<int> a, int n) { return a(n); } // Now call g and pass f: g(f, 10); // = 20 This is an example in C# where functions actually aren't first-class objects. The above code therefore uses a small workaround (namely a generic delegate called Action<>) to pass a function as an argument. Other languages, such as Ruby or Python, allow treating even classes and code blocks as normal variables (or in the case of Ruby, constants). A: From a slide in Structure and Interpretation of Computer Programs, lecture 2A (1986), which in turns quotes Christopher Stracey: The rights and privileges of first-class citizens: To be named by variables. To be passed as arguments to procedures. To be returned as values of procedures. To be incorporated into data structures A: IMO this is one of those metaphors used to describe things in a natural language. The term is essentially used in context of describing functions as first class objects. If you consider a object oriented language, we can impart various features to objects for eg: inheritance, class definition, ability to pass to other sections of code(method arguments), ability to store in a data structure etc. If we can do the same with an entity which is not normally considered as a object, like functions in the case of java script, such entities are considered to be first class objects. First class essentially here means, not handled as second class (with degraded behaviour). Essentially the mocking is perfect or indistinguishable.
What are "first-class" objects?
When are objects or something else said to be "first-class" in a given programming language, and why? In what way do they differ from languages where they are not? When one says "everything is an object" (like in Python), do they indeed mean that "everything is first-class"?
[ "In short, it means there are no restrictions on the object's use. It's the same as\nany other object.\nA first class object is an entity that can be dynamically created, destroyed, passed to a function, returned as a value, and have all the rights as other variables in the programming language have. \n\nDepending on the language, this can\n imply:\n\nbeing expressible as an anonymous literal value\nbeing storable in variables\nbeing storable in data structures\nhaving an intrinsic identity (independent of any given name)\nbeing comparable for equality with other entities\nbeing passable as a parameter to a procedure/function\nbeing returnable as the result of a procedure/function\nbeing constructible at runtime\nbeing printable\nbeing readable\nbeing transmissible among distributed processes\nbeing storable outside running processes\n\n\nSource.\nIn C++ functions themselves are not first class objects, however:\n\nYou can override the '()' operator making it possible to have an object function, which is first class.\nFunction pointers are first class. \nboost bind, lambda and function do offer first class functions\n\nIn C++, classes are not first class objects but instances of those classes are. In Python both the classes and the objects are first class objects. (See this answer for more details about classes as objects).\nHere is an example of Javascript first class functions:\n// f: function that takes a number and returns a number\n// deltaX: small positive number\n// returns a function that is an approximate derivative of f\nfunction makeDerivative( f, deltaX )\n{\n var deriv = function(x)\n { \n return ( f(x + deltaX) - f(x) )/ deltaX;\n }\n return deriv;\n}\nvar cos = makeDerivative( Math.sin, 0.000001);\n// cos(0) ~> 1\n// cos(pi/2) ~> 0\n\nSource.\nEntities that are not first class objects are referred to as second-class objects. Functions in C++ are second class because they can't be dynamically created. \nRegarding the edit:\n\nEDIT. When one says \"everything is\n an object\" (like in Python), does he\n indeed mean that \"everything is\n first-class\"?\n\nThe term object can be used loosely and doesn't imply being first class. And it would probably make more sense to call the whole concept 'first class entities'. But in Python they do aim to make everything first class. I believe the intent of the person who made your statement meant first class. \n", "\"When one says \"everything is an object\" (like in Python), does he indeed mean that \"everything is first-class\"?\"\nYes.\nEverything in Python is a proper object. Even things that are \"primitive types\" in other languages.\nYou find that an object like 2 actually has a fairly rich and sophisticated interface.\n>>> dir(2)\n['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__', '__xor__']\n\nBecause everything's a first-class object in Python, there are relatively few obscure special cases. \nIn Java, for example, there are primitive types (int, bool, double, char) that aren't proper objects. That's why Java has to introduce Integer, Boolean, Double, and Character as first-class types. This can be hard to teach to beginners -- it isn't obvious why both a primitive type and a class have to exist side-by-side.\nIt also means that an object's class is -- itself -- an object. This is different from C++, where the classes don't always have a distinct existence at run-time.\nThe type of 2 is the type 'int' object, which has methods, attributes, and a type.\n>>> type(2)\n<class 'int'>\n\nThe type of a built-in type like int is the type 'type' object. This has methods and attributes, also.\n>>> type(type(2))\n<class 'type'>\n\n", "“First class” means you can operate on them in the usual manner. Most of the times, this just means you can pass these first-class citizens as arguments to functions, or return them from functions.\nThis is self-evident for objects but not always so evident for functions, or even classes:\nvoid f(int n) { return n * 2; }\n\nvoid g(Action<int> a, int n) { return a(n); }\n\n// Now call g and pass f:\n\ng(f, 10); // = 20\n\nThis is an example in C# where functions actually aren't first-class objects. The above code therefore uses a small workaround (namely a generic delegate called Action<>) to pass a function as an argument. Other languages, such as Ruby or Python, allow treating even classes and code blocks as normal variables (or in the case of Ruby, constants).\n", "From a slide in Structure and Interpretation of Computer Programs, lecture 2A (1986), which in turns quotes Christopher Stracey:\nThe rights and privileges of first-class citizens:\n\nTo be named by variables.\nTo be passed as arguments to procedures.\nTo be returned as values of procedures.\nTo be incorporated into data structures\n\n", "IMO this is one of those metaphors used to describe things in a natural language. The term is essentially used in context of describing functions as first class objects. \nIf you consider a object oriented language, we can impart various features to objects for eg: inheritance, class definition, ability to pass to other sections of code(method arguments), ability to store in a data structure etc. If we can do the same with an entity which is not normally considered as a object, like functions in the case of java script, such entities are considered to be first class objects.\nFirst class essentially here means, not handled as second class (with degraded behaviour). Essentially the mocking is perfect or indistinguishable.\n" ]
[ 227, 28, 20, 18, 3 ]
[]
[]
[ "language_agnostic", "python" ]
stackoverflow_0000245192_language_agnostic_python.txt
Q: Best way to create a simple python web service I've been using python for years, but I have little experience with python web programming. I'd like to create a very simple web service that exposes some functionality from an existing python script for use within my company. It will likely return the results in csv. What's the quickest way to get something up? If it affects your suggestion, I will likely be adding more functionality to this, down the road. A: Have a look at werkzeug. Werkzeug started as a simple collection of various utilities for WSGI applications and has become one of the most advanced WSGI utility modules. It includes a powerful debugger, full featured request and response objects, HTTP utilities to handle entity tags, cache control headers, HTTP dates, cookie handling, file uploads, a powerful URL routing system and a bunch of community contributed addon modules. It includes lots of cool tools to work with http and has the advantage that you can use it with wsgi in different environments (cgi, fcgi, apache/mod_wsgi or with a plain simple python server for debugging). A: web.py is probably the simplest web framework out there. "Bare" CGI is simpler, but you're completely on your own when it comes to making a service that actually does something. "Hello, World!" according to web.py isn't much longer than an bare CGI version, but it adds URL mapping, HTTP command distinction, and query parameter parsing for free: import web urls = ( '/(.*)', 'hello' ) app = web.application(urls, globals()) class hello: def GET(self, name): if not name: name = 'world' return 'Hello, ' + name + '!' if __name__ == "__main__": app.run() A: The simplest way to get a Python script online is to use CGI: #!/usr/bin/python print "Content-type: text/html" print print "<p>Hello world.</p>" Put that code in a script that lives in your web server CGI directory, make it executable, and run it. The cgi module has a number of useful utilities when you need to accept parameters from the user. A: Raw CGI is kind of a pain, Django is kind of heavyweight. There are a number of simpler, lighter frameworks about, e.g. CherryPy. It's worth looking around a bit. A: Look at the WSGI reference implementation. You already have it in your Python libraries. It's quite simple. A: If you mean with "Web Service" something accessed by other Programms SimpleXMLRPCServer might be right for you. It is included with every Python install since Version 2.2. For Simple human accessible things I usually use Pythons SimpleHTTPServer which also comes with every install. Obviously you also could access SimpleHTTPServer by client programs. A: Life is simple if you get a good web framework. Web services in Django are easy. Define your model, write view functions that return your CSV documents. Skip the templates. A: If you mean "web service" in SOAP/WSDL sense, you might want to look at Generating a WSDL using Python and SOAPpy A: maybe Twisted http://twistedmatrix.com/trac/
Best way to create a simple python web service
I've been using python for years, but I have little experience with python web programming. I'd like to create a very simple web service that exposes some functionality from an existing python script for use within my company. It will likely return the results in csv. What's the quickest way to get something up? If it affects your suggestion, I will likely be adding more functionality to this, down the road.
[ "Have a look at werkzeug. Werkzeug started as a simple collection of various utilities for WSGI applications and has become one of the most advanced WSGI utility modules. It includes a powerful debugger, full featured request and response objects, HTTP utilities to handle entity tags, cache control headers, HTTP dates, cookie handling, file uploads, a powerful URL routing system and a bunch of community contributed addon modules.\nIt includes lots of cool tools to work with http and has the advantage that you can use it with wsgi in different environments (cgi, fcgi, apache/mod_wsgi or with a plain simple python server for debugging). \n", "web.py is probably the simplest web framework out there. \"Bare\" CGI is simpler, but you're completely on your own when it comes to making a service that actually does something.\n\"Hello, World!\" according to web.py isn't much longer than an bare CGI version, but it adds URL mapping, HTTP command distinction, and query parameter parsing for free:\nimport web\n\nurls = (\n '/(.*)', 'hello'\n)\napp = web.application(urls, globals())\n\nclass hello: \n def GET(self, name):\n if not name: \n name = 'world'\n return 'Hello, ' + name + '!'\n\nif __name__ == \"__main__\":\n app.run()\n\n", "The simplest way to get a Python script online is to use CGI:\n#!/usr/bin/python\n\nprint \"Content-type: text/html\"\nprint\n\nprint \"<p>Hello world.</p>\"\n\nPut that code in a script that lives in your web server CGI directory, make it executable, and run it. The cgi module has a number of useful utilities when you need to accept parameters from the user.\n", "Raw CGI is kind of a pain, Django is kind of heavyweight. There are a number of simpler, lighter frameworks about, e.g. CherryPy. It's worth looking around a bit.\n", "Look at the WSGI reference implementation. You already have it in your Python libraries. It's quite simple.\n", "If you mean with \"Web Service\" something accessed by other Programms SimpleXMLRPCServer might be right for you. It is included with every Python install since Version 2.2.\nFor Simple human accessible things I usually use Pythons SimpleHTTPServer which also comes with every install. Obviously you also could access SimpleHTTPServer by client programs.\n", "Life is simple if you get a good web framework. Web services in Django are easy. Define your model, write view functions that return your CSV documents. Skip the templates.\n", "If you mean \"web service\" in SOAP/WSDL sense, you might want to look at Generating a WSDL using Python and SOAPpy\n", "maybe Twisted\nhttp://twistedmatrix.com/trac/\n" ]
[ 55, 26, 17, 12, 9, 4, 2, 2, 1 ]
[]
[]
[ "python", "web_services" ]
stackoverflow_0000415192_python_web_services.txt
Q: How to check that a path has a sticky bit in python? How to check with python if a path has the sticky bit set? A: import os def is_sticky(path): return os.stat(path).st_mode & 01000 == 01000 A: os.stat() will return a tupple of information about the file. The first item will be the mode. You would then be able to use some bit arithmetic to get for the sticky bit. The sticky bit has an octal value of 1000.
How to check that a path has a sticky bit in python?
How to check with python if a path has the sticky bit set?
[ "import os\ndef is_sticky(path):\n return os.stat(path).st_mode & 01000 == 01000\n\n", "os.stat() will return a tupple of information about the file. The first item will be the mode. You would then be able to use some bit arithmetic to get for the sticky bit. The sticky bit has an octal value of 1000.\n" ]
[ 8, 2 ]
[]
[]
[ "python" ]
stackoverflow_0000418204_python.txt
Q: Python: C++-like stream input Is there a pythonic way of reading - say - mixed integer and char input without reading the whole input at once and without worrying about linebreaks? For example I have a file with whitespace-separated data of which I only know that there are x integers, then y chars and then z more integers. I don't want to assume anything about linebreaks. I mean something as mindless as the following in C++: ... int i, buf; char cbuf; vector<int> X, Z; vector<int> Y; for (i = 0; i < x; i++) { cin >> buf; X.push_back(buf); } for (i = 0; i < y; i++) { cin >> cbuf; Y.push_back(cbuf); } for (i = 0; i < z; i++) { cin >> buf; Z.push_back(buf); } EDIT: i forgot to say that I'd like it to behave well under live input from console as well - i.e. there should be no need to press ctrl+d before getting tokens and the function should be able to return them as soon as a line has been entered. :) A: How about a small generator function that returns a stream of tokens and behaves like cin: def read_tokens(f): for line in f: for token in line.split(): yield token x = y = z = 5 # for simplicity: 5 ints, 5 char tokens, 5 ints f = open('data.txt', 'r') tokens = read_tokens(f) X = [] for i in xrange(x): X.append(int(tokens.next())) Y = [] for i in xrange(y): Y.append(tokens.next()) Z = [] for i in xrange(z): Z.append(int(tokens.next())) A: if you don't want to read in a whole line at a time, you might want to try something like this: def read_tokens(file): while True: token = [] while True: c = file.read(1) if c not in ['', ' ', '\t', '\n']: token.append(c) elif c in [' ', '\t', '\n']: yield ''.join(token) break elif c == '': yield ''.join(token) raise StopIteration that should generate each whitespace-delimited token in the file reading one character at a time. from there you should be able to convert them to whatever type they should be. the whitespace can probably be taken care of better, too. A: Like this? >>> data = "1 2 3 4 5 6 abcdefg 9 8 7 6 5 4 3" For example, we might get this with data= someFile.read() >>> fields= data.split() >>> x= map(int,fields[:6]) >>> y= fields[6] >>> z= map(int,fields[7:]) Results >>> x [1, 2, 3, 4, 5, 6] >>> y 'abcdefg' >>> z [9, 8, 7, 6, 5, 4, 3] A: How's this? Building on heikogerlach's excellent read_tokens. def read_tokens(f): for line in f: for token in line.split(): yield token We can do things like the following to pick up 6 numbers, 7 characters and 6 numbers. fi = read_tokens(data) x= [ int(fi.next()) for i in xrange(6) ] y= [ fi.next() for i in xrange(7) ] z= [ int(fi.next()) for i in xrange(6) ]
Python: C++-like stream input
Is there a pythonic way of reading - say - mixed integer and char input without reading the whole input at once and without worrying about linebreaks? For example I have a file with whitespace-separated data of which I only know that there are x integers, then y chars and then z more integers. I don't want to assume anything about linebreaks. I mean something as mindless as the following in C++: ... int i, buf; char cbuf; vector<int> X, Z; vector<int> Y; for (i = 0; i < x; i++) { cin >> buf; X.push_back(buf); } for (i = 0; i < y; i++) { cin >> cbuf; Y.push_back(cbuf); } for (i = 0; i < z; i++) { cin >> buf; Z.push_back(buf); } EDIT: i forgot to say that I'd like it to behave well under live input from console as well - i.e. there should be no need to press ctrl+d before getting tokens and the function should be able to return them as soon as a line has been entered. :)
[ "How about a small generator function that returns a stream of tokens and behaves like cin:\ndef read_tokens(f):\n for line in f:\n for token in line.split():\n yield token\n\nx = y = z = 5 # for simplicity: 5 ints, 5 char tokens, 5 ints\nf = open('data.txt', 'r')\ntokens = read_tokens(f)\nX = []\nfor i in xrange(x):\n X.append(int(tokens.next()))\nY = []\nfor i in xrange(y):\n Y.append(tokens.next())\nZ = []\nfor i in xrange(z):\n Z.append(int(tokens.next()))\n\n", "if you don't want to read in a whole line at a time, you might want to try something like this:\ndef read_tokens(file):\n while True:\n token = []\n while True:\n c = file.read(1)\n if c not in ['', ' ', '\\t', '\\n']:\n token.append(c)\n elif c in [' ', '\\t', '\\n']:\n yield ''.join(token)\n break\n elif c == '':\n yield ''.join(token)\n raise StopIteration\n\nthat should generate each whitespace-delimited token in the file reading one character at a time. from there you should be able to convert them to whatever type they should be. the whitespace can probably be taken care of better, too.\n", "Like this?\n>>> data = \"1 2 3 4 5 6 abcdefg 9 8 7 6 5 4 3\"\n\nFor example, we might get this with data= someFile.read()\n>>> fields= data.split()\n>>> x= map(int,fields[:6])\n>>> y= fields[6]\n>>> z= map(int,fields[7:])\n\nResults\n>>> x\n[1, 2, 3, 4, 5, 6]\n>>> y\n'abcdefg'\n>>> z\n[9, 8, 7, 6, 5, 4, 3]\n\n", "How's this? Building on heikogerlach's excellent read_tokens.\ndef read_tokens(f):\n for line in f:\n for token in line.split():\n yield token\n\nWe can do things like the following to pick up 6 numbers, 7 characters and 6 numbers.\nfi = read_tokens(data)\nx= [ int(fi.next()) for i in xrange(6) ]\ny= [ fi.next() for i in xrange(7) ]\nz= [ int(fi.next()) for i in xrange(6) ]\n\n" ]
[ 7, 3, 2, 0 ]
[]
[]
[ "c++", "input", "python", "stream" ]
stackoverflow_0000417703_c++_input_python_stream.txt
Q: Why does Python's string.printable contains unprintable characters? I have two String.printable mysteries in the one question. First, in Python 2.6: >>> string.printable '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' Look at the end of the string, and you'll find '\x0b\x0c' sticking out like a sore-thumb. Why are they there? I am using a machine set to Australian settings, so there shouldn't be any accented characters or the like. Next, try running this code: for x in string.printable: print x, print for x in string.printable: print x The first line successfully prints all the characters separated by a space. The two odd characters turn out as the Male and Female symbols. The second line successfully prints all the characters EXCEPT THE LAST separated by a line feed. The Male symbol prints; the female symbol is replaced with a missing character (a box). I'm sure Python wasn't intended to be gender-biased, so what gives with the difference? A: There is a difference in "printable" for "can be displayed on your screen". Your terminal displays the low ascii printer control codes 0x0B and 0x0C as the male and female symbols because that is what those indices in your font contain. Those characters are more accurately described as the Vertical Tabulator and Form Feed characters. These two characters, along with \t \r and \n, are all printable, and do well defined things on a printer. A: From within cmd.exe: >>> print '\x0b' ♂ >>> print '\x0c' ♀ >>> print '\f' # form feed ♀ >>> print '\v' # vertical tab ♂ >>> Inside Emacs: >>> print '\f\v' ^L^K Here's an excerpt from formats(5)' man page: | Sequence | Character | Terminal Action | |----------+--------------+---------------------------------------------| | \f | form-feed | Moves the printing position to the initial | | | | printing position of the next logical page. | | \v | vertical-tab | Moves the printing position to the start of | | | | the next vertical tab position. If there | | | | are no more vertical tab positions left on | | | | the page, the behavior is undefined. |
Why does Python's string.printable contains unprintable characters?
I have two String.printable mysteries in the one question. First, in Python 2.6: >>> string.printable '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' Look at the end of the string, and you'll find '\x0b\x0c' sticking out like a sore-thumb. Why are they there? I am using a machine set to Australian settings, so there shouldn't be any accented characters or the like. Next, try running this code: for x in string.printable: print x, print for x in string.printable: print x The first line successfully prints all the characters separated by a space. The two odd characters turn out as the Male and Female symbols. The second line successfully prints all the characters EXCEPT THE LAST separated by a line feed. The Male symbol prints; the female symbol is replaced with a missing character (a box). I'm sure Python wasn't intended to be gender-biased, so what gives with the difference?
[ "There is a difference in \"printable\" for \"can be displayed on your screen\". Your terminal displays the low ascii printer control codes 0x0B and 0x0C as the male and female symbols because that is what those indices in your font contain. Those characters are more accurately described as the Vertical Tabulator and Form Feed characters. These two characters, along with \\t \\r and \\n, are all printable, and do well defined things on a printer.\n", "From within cmd.exe:\n>>> print '\\x0b'\n♂\n>>> print '\\x0c'\n♀\n>>> print '\\f' # form feed\n♀\n>>> print '\\v' # vertical tab\n♂\n>>>\n\nInside Emacs:\n>>> print '\\f\\v'\n^L^K\n\nHere's an excerpt from formats(5)' man page:\n\n| Sequence | Character | Terminal Action |\n|----------+--------------+---------------------------------------------|\n| \\f | form-feed | Moves the printing position to the initial |\n| | | printing position of the next logical page. |\n| \\v | vertical-tab | Moves the printing position to the start of |\n| | | the next vertical tab position. If there |\n| | | are no more vertical tab positions left on |\n| | | the page, the behavior is undefined. |\n\n" ]
[ 27, 6 ]
[]
[]
[ "character_encoding", "python" ]
stackoverflow_0000418176_character_encoding_python.txt
Q: py2exe setup.py with icons How do I make icons for my exe file when compiling my Python program? A: I was searching for this a while ago, and found this: http://www.mail-archive.com/pygame-users@seul.org/msg05619.html Quote from above link: The setup.py File: PY_PROG = 'trek10.py' APP_NAME = 'Trek_Game' cfg = { 'name':APP_NAME, 'version':'1.0', 'description':'', 'author':'', 'author_email':'', 'url':'', 'py2exe.target':'', 'py2exe.icon':'icon.ico', #64x64 'py2exe.binary':APP_NAME, #leave off the .exe, it will be added 'py2app.target':'', 'py2app.icon':'icon.icns', #128x128 'cx_freeze.cmd':'~/src/cx_Freeze-3.0.3/FreezePython', 'cx_freeze.target':'', 'cx_freeze.binary':APP_NAME, } --snip-- A: Linking the icons is answered in other answers. Creating the thing is as easy as using png2ico. It creates an ico file from 1 or more png's and handles multiple sizes etc, like: png2ico myicon.ico logo16x16.png logo32x32.png Will create myicon.ico with sizes 16x16 and 32x32. Sizes must be multiples of 8 squares, and no larger than 256x256. A: py2exe is a little dated, and has been continued with pyinstaller (which itself is a little dated; the svn release is the most up to date) http://pyinstaller.python-hosting.com/ After running through the initial scripts for pyinstaller and generating the spec file from Makespec.py, edit the spec file and look for the EXE section. At the tail end of that just add in your ico definition; so console=True) would become console=True, icon='mine.ico' ) That is, if the mine.ico file were in the same folder as the Makespec.py file. There's also a command line option for feeding the icon into it. I think it was python Makespec.py -i 'mine.ico' /path/to/file.py
py2exe setup.py with icons
How do I make icons for my exe file when compiling my Python program?
[ "I was searching for this a while ago, and found this: http://www.mail-archive.com/pygame-users@seul.org/msg05619.html\nQuote from above link:\n\nThe setup.py File: PY_PROG =\n'trek10.py' APP_NAME = 'Trek_Game'\ncfg = {\n'name':APP_NAME,\n'version':'1.0',\n'description':'',\n'author':'',\n'author_email':'',\n'url':'',\n\n'py2exe.target':'',\n'py2exe.icon':'icon.ico', #64x64\n'py2exe.binary':APP_NAME, #leave off the .exe, it will be added\n\n'py2app.target':'',\n'py2app.icon':'icon.icns', #128x128\n\n'cx_freeze.cmd':'~/src/cx_Freeze-3.0.3/FreezePython',\n'cx_freeze.target':'',\n'cx_freeze.binary':APP_NAME,\n}\n\n--snip--\n\n", "Linking the icons is answered in other answers. Creating the thing is as easy as using png2ico. It creates an ico file from 1 or more png's and handles multiple sizes etc, like:\npng2ico myicon.ico logo16x16.png logo32x32.png\n\nWill create myicon.ico with sizes 16x16 and 32x32. Sizes must be multiples of 8 squares, and no larger than 256x256.\n", "py2exe is a little dated, and has been continued with pyinstaller (which itself is a little dated; the svn release is the most up to date)\nhttp://pyinstaller.python-hosting.com/\nAfter running through the initial scripts for pyinstaller and generating the spec file from Makespec.py, edit the spec file and look for the EXE section. At the tail end of that just add in your ico definition; so\n\nconsole=True)\n\nwould become\n\nconsole=True, icon='mine.ico' )\n\nThat is, if the mine.ico file were in the same folder as the Makespec.py file. There's also a command line option for feeding the icon into it. I think it was \npython Makespec.py -i 'mine.ico' /path/to/file.py\n\n" ]
[ 2, 2, 2 ]
[ "I have no experience with py2exe but a quick google search found this, if embedding icons in exe files was what you asked for. \nIf you want to create .ico files, I'd really suggest you search for a icon designer or finished icons. Sure you can create a Win 3.x style icon fairly easy by creating a 16x16, 32x32, or 64x64 px image in paint, and rename it to .ico. But to create modern multi resolution icons for windows is a lot more complicated.\n(I was about to ask what OS you was compiling for, when I realized \"exe\" sounds very windows, and sure enough...)\n" ]
[ -1 ]
[ "icons", "py2exe", "python" ]
stackoverflow_0000289518_icons_py2exe_python.txt
Q: Python Threads - Critical Section What is the "critical section" of a thread (in Python)? A thread enters the critical section by calling the acquire() method, which can either be blocking or non-blocking. A thread exits the critical section, by calling the release() method. - Understanding Threading in Python, Linux Gazette Also, what is the purpose of a lock? A: Other people have given very nice definitions. Here's the classic example: import threading account_balance = 0 # The "resource" that zenazn mentions. account_balance_lock = threading.Lock() def change_account_balance(delta): global account_balance with account_balance_lock: # Critical section is within this block. account_balance += delta Let's say that the += operator consists of three subcomponents: Read the current value Add the RHS to that value Write the accumulated value back to the LHS (technically bind it in Python terms) If you don't have the with account_balance_lock statement and you execute two change_account_balance calls in parallel you can end up interleaving the three subcomponent operations in a hazardous manner. Let's say you simultaneously call change_account_balance(100) (AKA pos) and change_account_balance(-100) (AKA neg). This could happen: pos = threading.Thread(target=change_account_balance, args=[100]) neg = threading.Thread(target=change_account_balance, args=[-100]) pos.start(), neg.start() pos: read current value -> 0 neg: read current value -> 0 pos: add current value to read value -> 100 neg: add current value to read value -> -100 pos: write current value -> account_balance = 100 neg: write current value -> account_balance = -100 Because you didn't force the operations to happen in discrete chunks you can have three possible outcomes (-100, 0, 100). The with [lock] statement is a single, indivisible operation that says, "Let me be the only thread executing this block of code. If something else is executing, it's cool -- I'll wait." This ensures that the updates to the account_balance are "thread-safe" (parallelism-safe). Note: There is a caveat to this schema: you have to remember to acquire the account_balance_lock (via with) every time you want to manipulate the account_balance for the code to remain thread-safe. There are ways to make this less fragile, but that's the answer to a whole other question. Edit: In retrospect, it's probably important to mention that the with statement implicitly calls a blocking acquire on the lock -- this is the "I'll wait" part of the above thread dialog. In contrast, a non-blocking acquire says, "If I can't acquire the lock right away, let me know," and then relies on you to check whether you got the lock or not. import logging # This module is thread safe. import threading LOCK = threading.Lock() def run(): if LOCK.acquire(False): # Non-blocking -- return whether we got it logging.info('Got the lock!') LOCK.release() else: logging.info("Couldn't get the lock. Maybe next time") logging.basicConfig(level=logging.INFO) threads = [threading.Thread(target=run) for i in range(100)] for thread in threads: thread.start() I also want to add that the lock's primary purpose is to guarantee the atomicity of acquisition (the indivisibility of the acquire across threads), which a simple boolean flag will not guarantee. The semantics of atomic operations are probably also the content of another question. A: A critical section of code is one that can only be executed by one thread at a time. Take a chat server for instance. If you have a thread for each connection (i.e., each end user), one "critical section" is the spooling code (sending an incoming message to all the clients). If more than one thread tries to spool a message at once, you'll get BfrIToS mANtwD PIoEmesCEsaSges intertwined, which is obviously no good at all. A lock is something that can be used to synchronize access to a critical section (or resources in general). In our chat server example, the lock is like a locked room with a typewriter in it. If one thread is in there (to type a message out), no other thread can get into the room. Once the first thread is done, he unlocks the room and leaves. Then another thread can go in the room (locking it). "Aquiring" the lock just means "I get the room." A: A "critical section" is a chunk of code in which, for correctness, it is necessary to ensure that only one thread of control can be in that section at a time. In general, you need a critical section to contain references that write values into memory that can be shared among more than one concurrent process.
Python Threads - Critical Section
What is the "critical section" of a thread (in Python)? A thread enters the critical section by calling the acquire() method, which can either be blocking or non-blocking. A thread exits the critical section, by calling the release() method. - Understanding Threading in Python, Linux Gazette Also, what is the purpose of a lock?
[ "Other people have given very nice definitions. Here's the classic example:\nimport threading\naccount_balance = 0 # The \"resource\" that zenazn mentions.\naccount_balance_lock = threading.Lock()\n\ndef change_account_balance(delta):\n global account_balance\n with account_balance_lock:\n # Critical section is within this block.\n account_balance += delta\n\nLet's say that the += operator consists of three subcomponents:\n\nRead the current value\nAdd the RHS to that value\nWrite the accumulated value back to the LHS (technically bind it in Python terms)\n\nIf you don't have the with account_balance_lock statement and you execute two change_account_balance calls in parallel you can end up interleaving the three subcomponent operations in a hazardous manner. Let's say you simultaneously call change_account_balance(100) (AKA pos) and change_account_balance(-100) (AKA neg). This could happen:\npos = threading.Thread(target=change_account_balance, args=[100])\nneg = threading.Thread(target=change_account_balance, args=[-100])\npos.start(), neg.start()\n\n\npos: read current value -> 0\nneg: read current value -> 0\npos: add current value to read value -> 100\nneg: add current value to read value -> -100\npos: write current value -> account_balance = 100\nneg: write current value -> account_balance = -100\n\nBecause you didn't force the operations to happen in discrete chunks you can have three possible outcomes (-100, 0, 100).\nThe with [lock] statement is a single, indivisible operation that says, \"Let me be the only thread executing this block of code. If something else is executing, it's cool -- I'll wait.\" This ensures that the updates to the account_balance are \"thread-safe\" (parallelism-safe).\nNote: There is a caveat to this schema: you have to remember to acquire the account_balance_lock (via with) every time you want to manipulate the account_balance for the code to remain thread-safe. There are ways to make this less fragile, but that's the answer to a whole other question.\nEdit: In retrospect, it's probably important to mention that the with statement implicitly calls a blocking acquire on the lock -- this is the \"I'll wait\" part of the above thread dialog. In contrast, a non-blocking acquire says, \"If I can't acquire the lock right away, let me know,\" and then relies on you to check whether you got the lock or not.\nimport logging # This module is thread safe.\nimport threading\n\nLOCK = threading.Lock()\n\ndef run():\n if LOCK.acquire(False): # Non-blocking -- return whether we got it\n logging.info('Got the lock!')\n LOCK.release()\n else:\n logging.info(\"Couldn't get the lock. Maybe next time\")\n\nlogging.basicConfig(level=logging.INFO)\nthreads = [threading.Thread(target=run) for i in range(100)]\nfor thread in threads:\n thread.start()\n\nI also want to add that the lock's primary purpose is to guarantee the atomicity of acquisition (the indivisibility of the acquire across threads), which a simple boolean flag will not guarantee. The semantics of atomic operations are probably also the content of another question.\n", "A critical section of code is one that can only be executed by one thread at a time. Take a chat server for instance. If you have a thread for each connection (i.e., each end user), one \"critical section\" is the spooling code (sending an incoming message to all the clients). If more than one thread tries to spool a message at once, you'll get BfrIToS mANtwD PIoEmesCEsaSges intertwined, which is obviously no good at all.\nA lock is something that can be used to synchronize access to a critical section (or resources in general). In our chat server example, the lock is like a locked room with a typewriter in it. If one thread is in there (to type a message out), no other thread can get into the room. Once the first thread is done, he unlocks the room and leaves. Then another thread can go in the room (locking it). \"Aquiring\" the lock just means \"I get the room.\"\n", "A \"critical section\" is a chunk of code in which, for correctness, it is necessary to ensure that only one thread of control can be in that section at a time. In general, you need a critical section to contain references that write values into memory that can be shared among more than one concurrent process.\n" ]
[ 24, 18, 0 ]
[]
[]
[ "language_agnostic", "multithreading", "python" ]
stackoverflow_0000419145_language_agnostic_multithreading_python.txt
Q: How can I convert XML into a Python object? I need to load an XML file and convert the contents into an object-oriented Python structure. I want to take this: <main> <object1 attr="name">content</object> </main> And turn it into something like this: main main.object1 = "content" main.object1.attr = "name" The XML data will have a more complicated structure than that and I can't hard code the element names. The attribute names need to be collected when parsing and used as the object properties. How can I convert XML data into a Python object? A: It's worth looking at lxml.objectify. xml = """<main> <object1 attr="name">content</object1> <object1 attr="foo">contenbar</object1> <test>me</test> </main>""" from lxml import objectify main = objectify.fromstring(xml) main.object1[0] # content main.object1[1] # contenbar main.object1[0].get("attr") # name main.test # me Or the other way around to build xml structures: item = objectify.Element("item") item.title = "Best of python" item.price = 17.98 item.price.set("currency", "EUR") order = objectify.Element("order") order.append(item) order.item.quantity = 3 order.price = sum(item.price * item.quantity for item in order.item) import lxml.etree print(lxml.etree.tostring(order, pretty_print=True)) Output: <order> <item> <title>Best of python</title> <price currency="EUR">17.98</price> <quantity>3</quantity> </item> <price>53.94</price> </order> A: I've been recommending this more than once today, but try Beautiful Soup (easy_install BeautifulSoup). from BeautifulSoup import BeautifulSoup xml = """ <main> <object attr="name">content</object> </main> """ soup = BeautifulSoup(xml) # look in the main node for object's with attr=name, optionally look up attrs with regex my_objects = soup.main.findAll("object", attrs={'attr':'name'}) for my_object in my_objects: # this will print a list of the contents of the tag print my_object.contents # if only text is inside the tag you can use this # print tag.string A: David Mertz's gnosis.xml.objectify would seem to do this for you. Documentation's a bit hard to come by, but there are a few IBM articles on it, including this one (text only version). from gnosis.xml import objectify xml = "<root><nodes><node>node 1</node><node>node 2</node></nodes></root>" root = objectify.make_instance(xml) print root.nodes.node[0].PCDATA # node 1 print root.nodes.node[1].PCDATA # node 2 Creating xml from objects in this way is a different matter, though. A: How about this http://evanjones.ca/software/simplexmlparse.html A: #@Stephen: #"can't hardcode the element names, so I need to collect them #at parse and use them somehow as the object names." #I don't think thats possible. Instead you can do this. #this will help you getting any object with a required name. import BeautifulSoup class Coll(object): """A class which can hold your Foo clas objects and retrieve them easily when you want abstracting the storage and retrieval logic """ def __init__(self): self.foos={} def add(self, fooobj): self.foos[fooobj.name]=fooobj def get(self, name): return self.foos[name] class Foo(object): """The required class """ def __init__(self, name, attr1=None, attr2=None): self.name=name self.attr1=attr1 self.attr2=attr2 s="""<main> <object name="somename"> <attr name="attr1">value1</attr> <attr name="attr2">value2</attr> </object> <object name="someothername"> <attr name="attr1">value3</attr> <attr name="attr2">value4</attr> </object> </main> """ # soup=BeautifulSoup.BeautifulSoup(s) bars=Coll() for each in soup.findAll('object'): bar=Foo(each['name']) attrs=each.findAll('attr') for attr in attrs: setattr(bar, attr['name'], attr.renderContents()) bars.add(bar) #retrieve objects by name print bars.get('somename').__dict__ print '\n\n', bars.get('someothername').__dict__ output {'attr2': 'value2', 'name': u'somename', 'attr1': 'value1'} {'attr2': 'value4', 'name': u'someothername', 'attr1': 'value3'} A: There are three common XML parsers for python: xml.dom.minidom, elementree, and BeautifulSoup. IMO, BeautifulSoup is by far the best. http://www.crummy.com/software/BeautifulSoup/
How can I convert XML into a Python object?
I need to load an XML file and convert the contents into an object-oriented Python structure. I want to take this: <main> <object1 attr="name">content</object> </main> And turn it into something like this: main main.object1 = "content" main.object1.attr = "name" The XML data will have a more complicated structure than that and I can't hard code the element names. The attribute names need to be collected when parsing and used as the object properties. How can I convert XML data into a Python object?
[ "It's worth looking at lxml.objectify.\nxml = \"\"\"<main>\n<object1 attr=\"name\">content</object1>\n<object1 attr=\"foo\">contenbar</object1>\n<test>me</test>\n</main>\"\"\"\n\nfrom lxml import objectify\n\nmain = objectify.fromstring(xml)\nmain.object1[0] # content\nmain.object1[1] # contenbar\nmain.object1[0].get(\"attr\") # name\nmain.test # me\n\nOr the other way around to build xml structures:\nitem = objectify.Element(\"item\")\nitem.title = \"Best of python\"\nitem.price = 17.98\nitem.price.set(\"currency\", \"EUR\")\n\norder = objectify.Element(\"order\")\norder.append(item)\norder.item.quantity = 3\norder.price = sum(item.price * item.quantity for item in order.item)\n\nimport lxml.etree\nprint(lxml.etree.tostring(order, pretty_print=True))\n\nOutput:\n<order>\n <item>\n <title>Best of python</title>\n <price currency=\"EUR\">17.98</price>\n <quantity>3</quantity>\n </item>\n <price>53.94</price>\n</order>\n\n", "I've been recommending this more than once today, but try Beautiful Soup (easy_install BeautifulSoup).\nfrom BeautifulSoup import BeautifulSoup\n\nxml = \"\"\"\n<main>\n <object attr=\"name\">content</object>\n</main>\n\"\"\"\n\nsoup = BeautifulSoup(xml)\n# look in the main node for object's with attr=name, optionally look up attrs with regex\nmy_objects = soup.main.findAll(\"object\", attrs={'attr':'name'})\nfor my_object in my_objects:\n # this will print a list of the contents of the tag\n print my_object.contents\n # if only text is inside the tag you can use this\n # print tag.string\n\n", "David Mertz's gnosis.xml.objectify would seem to do this for you. Documentation's a bit hard to come by, but there are a few IBM articles on it, including this one (text only version).\nfrom gnosis.xml import objectify\n\nxml = \"<root><nodes><node>node 1</node><node>node 2</node></nodes></root>\"\nroot = objectify.make_instance(xml)\n\nprint root.nodes.node[0].PCDATA # node 1\nprint root.nodes.node[1].PCDATA # node 2\n\nCreating xml from objects in this way is a different matter, though.\n", "How about this\nhttp://evanjones.ca/software/simplexmlparse.html\n", "#@Stephen: \n#\"can't hardcode the element names, so I need to collect them \n#at parse and use them somehow as the object names.\"\n\n#I don't think thats possible. Instead you can do this. \n#this will help you getting any object with a required name.\n\nimport BeautifulSoup\n\n\nclass Coll(object):\n \"\"\"A class which can hold your Foo clas objects \n and retrieve them easily when you want\n abstracting the storage and retrieval logic\n \"\"\"\n def __init__(self):\n self.foos={} \n\n def add(self, fooobj):\n self.foos[fooobj.name]=fooobj\n\n def get(self, name):\n return self.foos[name]\n\nclass Foo(object):\n \"\"\"The required class\n \"\"\"\n def __init__(self, name, attr1=None, attr2=None):\n self.name=name\n self.attr1=attr1\n self.attr2=attr2\n\ns=\"\"\"<main>\n <object name=\"somename\">\n <attr name=\"attr1\">value1</attr>\n <attr name=\"attr2\">value2</attr>\n </object>\n <object name=\"someothername\">\n <attr name=\"attr1\">value3</attr>\n <attr name=\"attr2\">value4</attr>\n </object>\n </main>\n\"\"\"\n\n#\nsoup=BeautifulSoup.BeautifulSoup(s)\n\n\nbars=Coll()\nfor each in soup.findAll('object'):\n bar=Foo(each['name'])\n attrs=each.findAll('attr')\n for attr in attrs:\n setattr(bar, attr['name'], attr.renderContents())\n bars.add(bar)\n\n\n#retrieve objects by name\nprint bars.get('somename').__dict__\n\nprint '\\n\\n', bars.get('someothername').__dict__\n\noutput\n{'attr2': 'value2', 'name': u'somename', 'attr1': 'value1'}\n\n\n{'attr2': 'value4', 'name': u'someothername', 'attr1': 'value3'}\n\n", "There are three common XML parsers for python: xml.dom.minidom, elementree, and BeautifulSoup.\nIMO, BeautifulSoup is by far the best. \nhttp://www.crummy.com/software/BeautifulSoup/\n" ]
[ 59, 9, 4, 1, 1, 0 ]
[ "If googling around for a code-generator doesn't work, you could write your own that uses XML as input and outputs objects in your language of choice.\nIt's not terribly difficult, however the three step process of Parse XML, Generate Code, Compile/Execute Script does making debugging a bit harder.\n" ]
[ -1 ]
[ "python", "xml" ]
stackoverflow_0000418497_python_xml.txt
Q: Grabbing text from a webpage I would like to write a program that will find bus stop times and update my personal webpage accordingly. If I were to do this manually I would Visit www.calgarytransit.com Enter a stop number. ie) 9510 Click the button "next bus" The results may look like the following: 10:16p Route 154 10:46p Route 154 11:32p Route 154 Once I've grabbed the time and routes then I will update my webpage accordingly. I have no idea where to start. I know diddly squat about web programming but can write some C and Python. What are some topics/libraries I could look into? A: Beautiful Soup is a Python library designed for parsing web pages. Between it and urllib2 (urllib.request in Python 3) you should be able to figure out what you need. A: What you're asking about is called "web scraping." I'm sure if you google around you'll find some stuff, but the core notion is that you want to open a connection to the website, slurp in the HTML, parse it and identify the chunks you want. The Python Wiki has a good lot of stuff on this. A: Since you write in C, you may want to check out cURL; in particular, take a look at libcurl. It's great. A: You can use Perl to help you complete your task. use strict; use LWP; my $browser = LWP::UserAgent->new; my $responce = $browser->get("http://google.com"); print $responce->content; Your responce object can tell you if it suceeded as well as returning the content of the page.You can also use this same library to post to a page. Here is some documentation. http://metacpan.org/pod/LWP::UserAgent A: You can use the mechanize library that is available for Python http://wwwsearch.sourceforge.net/mechanize/ A: That site doesnt offer an API for you to be able to get the appropriate data that you need. In that case you'll need to parse the actual HTML page returned by, for example, a CURL request . A: This is called Web scraping, and it even has its own Wikipedia article where you can find more information. Also, you might find more details in this SO discussion. A: As long as the layout of the web page your trying to 'scrape' doesnt regularly change, you should be able to parse the html with any modern day programming language.
Grabbing text from a webpage
I would like to write a program that will find bus stop times and update my personal webpage accordingly. If I were to do this manually I would Visit www.calgarytransit.com Enter a stop number. ie) 9510 Click the button "next bus" The results may look like the following: 10:16p Route 154 10:46p Route 154 11:32p Route 154 Once I've grabbed the time and routes then I will update my webpage accordingly. I have no idea where to start. I know diddly squat about web programming but can write some C and Python. What are some topics/libraries I could look into?
[ "Beautiful Soup is a Python library designed for parsing web pages. Between it and urllib2 (urllib.request in Python 3) you should be able to figure out what you need.\n", "What you're asking about is called \"web scraping.\" I'm sure if you google around you'll find some stuff, but the core notion is that you want to open a connection to the website, slurp in the HTML, parse it and identify the chunks you want.\nThe Python Wiki has a good lot of stuff on this.\n", "Since you write in C, you may want to check out cURL; in particular, take a look at libcurl. It's great.\n", "You can use Perl to help you complete your task.\nuse strict;\nuse LWP;\n\nmy $browser = LWP::UserAgent->new;\n\nmy $responce = $browser->get(\"http://google.com\");\nprint $responce->content;\n\nYour responce object can tell you if it suceeded as well as returning the content of the page.You can also use this same library to post to a page.\nHere is some documentation. http://metacpan.org/pod/LWP::UserAgent\n", "You can use the mechanize library that is available for Python http://wwwsearch.sourceforge.net/mechanize/\n", "That site doesnt offer an API for you to be able to get the appropriate data that you need. In that case you'll need to parse the actual HTML page returned by, for example, a CURL request .\n", "This is called Web scraping, and it even has its own Wikipedia article where you can find more information.\nAlso, you might find more details in this SO discussion.\n", "As long as the layout of the web page your trying to 'scrape' doesnt regularly change, you should be able to parse the html with any modern day programming language.\n" ]
[ 13, 5, 3, 2, 2, 1, 1, 0 ]
[]
[]
[ "c", "python", "text", "webpage" ]
stackoverflow_0000419260_c_python_text_webpage.txt
Q: How would a system tray application be accomplished on other platforms? Windows has the "system tray" that houses the clock and alway-running services like MSN, Steam, etc. I'd like to develop a wxPython tray application but I'm wondering how well this will port to other platforms. What is the tray equivalent on each platform, and how much manual work would be required to support Windows, OSX and Linux (which shells in particular would be friendliest). A: wx is a cross-platform GUI and tools library that supports Win32, Mac OS X, GTK+, X11, Motif, WinCE, and more. And if you use it's classes then your application should work on all these platforms. For system tray look at wxTaskBarIcon (http://docs.wxwidgets.org/stable/wx_wxtaskbaricon.html#wxtaskbaricon). A: Under OS X you have the Status Menu bar - the right-most items are often status-related things (like battery status, WiFi connections, etc). Try searching for NSStatusBar and NSMenuExtra. It's almost trivial to turn an application into one that has an NSStatusBar menu and doesn't appear in the Dock. There are tutorials around on how to do it. A: For many Linux desktop systems (Gnome, KDE, etc.) a Freedesktop's SysTray Protocol is implemented. You can try that if any other solution fails. A: On Linux it really depends - you got diffrent programming environments there, and some window managers don't even have a tray area. Altho, if you use Gtk (and wx is Gtk really), the gtk.StatusIcon is your friend. Here are some examples of that (haven't checked if they actually work, but should show you the path). For wx I found some example code here. A: Use Qt: Qt Systray Example That'll show a systray icon on all platforms that Qt runs on and that support such icons. You'll need to come up with a strategy when systray functionality isn't supported, though.
How would a system tray application be accomplished on other platforms?
Windows has the "system tray" that houses the clock and alway-running services like MSN, Steam, etc. I'd like to develop a wxPython tray application but I'm wondering how well this will port to other platforms. What is the tray equivalent on each platform, and how much manual work would be required to support Windows, OSX and Linux (which shells in particular would be friendliest).
[ "wx is a cross-platform GUI and tools library that supports Win32, Mac OS X, GTK+, X11, Motif, WinCE, and more. And if you use it's classes then your application should work on all these platforms.\nFor system tray look at wxTaskBarIcon (http://docs.wxwidgets.org/stable/wx_wxtaskbaricon.html#wxtaskbaricon).\n", "Under OS X you have the Status Menu bar - the right-most items are often status-related things (like battery status, WiFi connections, etc).\nTry searching for NSStatusBar and NSMenuExtra. It's almost trivial to turn an application into one that has an NSStatusBar menu and doesn't appear in the Dock. There are tutorials around on how to do it.\n", "For many Linux desktop systems (Gnome, KDE, etc.) a Freedesktop's SysTray Protocol is implemented. You can try that if any other solution fails.\n", "On Linux it really depends - you got diffrent programming environments there, and some window managers don't even have a tray area. Altho, if you use Gtk (and wx is Gtk really), the gtk.StatusIcon is your friend. \nHere are some examples of that (haven't checked if they actually work, but should show you the path).\nFor wx I found some example code here. \n", "Use Qt: Qt Systray Example\nThat'll show a systray icon on all platforms that Qt runs on and that support such icons. You'll need to come up with a strategy when systray functionality isn't supported, though.\n" ]
[ 6, 3, 2, 1, 1 ]
[]
[]
[ "cross_platform", "operating_system", "python", "system_tray", "wxpython" ]
stackoverflow_0000419334_cross_platform_operating_system_python_system_tray_wxpython.txt
Q: How to raise an exception on the version number of a module How can you raise an exception when you import a module that is less or greater than a given value for its __version__? There are a lot of different ways you could do it, but I feel like there must be some really simple way that eludes me at the moment. In this case the version number is of the format x.x.x A: Python comes with this inbuilt as part of distutils. The module is called distutils.version and is able to compare several different version number formats. from distutils.version import StrictVersion print StrictVersion('1.2.2') > StrictVersion('1.2.1') For way more information than you need, see the documentation: >>> import distutils.version >>> help(distutils.version) A: If you are talking about modules installed with easy_install, this is what you need import pkg_resources pkg_resources.require("TurboGears>=1.0.5") this will raise an error if the installed module is of a lower version Traceback (most recent call last): File "tempplg.py", line 2, in <module> pkg_resources.require("TurboGears>=1.0.5") File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 626, in require needed = self.resolve(parse_requirements(requirements)) File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 528, in resolve raise VersionConflict(dist,req) # XXX put more info here pkg_resources.VersionConflict: (TurboGears 1.0.4.4 (/usr/lib/python2.5/site-packages/TurboGears-1.0.4.4-py2.5.egg), Requirement.parse('TurboGears>=1.0.5')) A: Like this? assert tuple(map(int,module.__version__.split("."))) >= (1,2), "Module not version 1.2.x" This is wordy, but works pretty well. Also, look into pip, which provides more advanced functionality. A: You should be using setuptools: It allows you to lock the dependancies of an application, so even if multiple versions of an egg or package exist on a system only the right one will ever be used. This is a better way of working: Rather than fail if the wrong version of a dependancy is present it is better to ensure that the right version is present. Setuptools provides an installer which guarantees that everything required to run the application is present at install-time. It also gives you the means to select which of the many versions of a package which may be present on your PC is the one that gets loaded when you issue an import statement.
How to raise an exception on the version number of a module
How can you raise an exception when you import a module that is less or greater than a given value for its __version__? There are a lot of different ways you could do it, but I feel like there must be some really simple way that eludes me at the moment. In this case the version number is of the format x.x.x
[ "Python comes with this inbuilt as part of distutils. The module is called distutils.version and is able to compare several different version number formats.\nfrom distutils.version import StrictVersion\n\nprint StrictVersion('1.2.2') > StrictVersion('1.2.1')\n\nFor way more information than you need, see the documentation:\n>>> import distutils.version\n>>> help(distutils.version)\n\n", "If you are talking about modules installed with easy_install, this is what you need\nimport pkg_resources\npkg_resources.require(\"TurboGears>=1.0.5\")\n\nthis will raise an error if the installed module is of a lower version\nTraceback (most recent call last):\n File \"tempplg.py\", line 2, in <module>\n pkg_resources.require(\"TurboGears>=1.0.5\")\n File \"/usr/lib/python2.5/site-packages/pkg_resources.py\", line 626, in require\n needed = self.resolve(parse_requirements(requirements))\n File \"/usr/lib/python2.5/site-packages/pkg_resources.py\", line 528, in resolve\n raise VersionConflict(dist,req) # XXX put more info here\npkg_resources.VersionConflict: (TurboGears 1.0.4.4 (/usr/lib/python2.5/site-packages/TurboGears-1.0.4.4-py2.5.egg), Requirement.parse('TurboGears>=1.0.5'))\n\n", "Like this?\nassert tuple(map(int,module.__version__.split(\".\"))) >= (1,2), \"Module not version 1.2.x\"\n\nThis is wordy, but works pretty well.\nAlso, look into pip, which provides more advanced functionality.\n", "You should be using setuptools: \nIt allows you to lock the dependancies of an application, so even if multiple versions of an egg or package exist on a system only the right one will ever be used. \nThis is a better way of working: Rather than fail if the wrong version of a dependancy is present it is better to ensure that the right version is present. \nSetuptools provides an installer which guarantees that everything required to run the application is present at install-time. It also gives you the means to select which of the many versions of a package which may be present on your PC is the one that gets loaded when you issue an import statement.\n" ]
[ 6, 2, 1, 0 ]
[ "If you know the exact formatting of the version string a plain comparison will work:\n>>> \"1.2.2\" > \"1.2.1\"\nTrue\n\nThis will only work if each part of the version is in the single digits, though:\n>>> \"1.2.2\" > \"1.2.10\" # Bug!\nTrue\n\n" ]
[ -2 ]
[ "python", "versioning" ]
stackoverflow_0000419010_python_versioning.txt
Q: Automated Class timetable optimize crawler? Overall Plan Get my class information to automatically optimize and select my uni class timetable Overall Algorithm Logon to the website using its Enterprise Sign On Engine login Find my current semester and its related subjects (pre setup) Navigate to the right page and get the data from each related subject (lecture, practical and workshop times) Strip the data of useless information Rank the classes which are closer to each other higher, the ones on random days lower Solve a best time table solution Output me a detailed list of the BEST CASE information Output me a detailed list of the possible class information (some might be full for example) Get the program to select the best classes automatically Keep checking to see if we can achieve 7. 6 in detail Get all the classes, using the lectures as a focus point, would be highest ranked (only one per subject), and try to arrange the classes around that. Questions Can anyone supply me with links to something that might be similar to this hopefully written in python? In regards to 6.: what data structure would you recommend to store this information in? A linked list where each object of uniclass? Should i write all information to a text file? I am thinking uniclass to be setup like the following attributes: Subject Rank Time Type Teacher I am hardly experienced in Python and thought this would be a good learning project to try to accomplish. Thanks for any help and links provided to help get me started, open to edits to tag appropriately or what ever is necessary (not sure what this falls under other than programming and python?) EDIT: can't really get the proper formatting i want for this SO post >< A: Depending on how far you plan on taking #6, and how big the dataset is, it may be non-trivial; it certainly smacks of NP-hard global optimisation to me... Still, if you're talking about tens (rather than hundreds) of nodes, a fairly dumb algorithm should give good enough performance. So, you have two constraints: A total ordering on the classes by score; this is flexible. Class clashes; this is not flexible. What I mean by flexible is that you can go to more spaced out classes (with lower scores), but you cannot be in two classes at once. Interestingly, there's likely to be a positive correlation between score and clashes; higher scoring classes are more likely to clash. My first pass at an algorithm: selected_classes = [] classes = sorted(classes, key=lambda c: c.score) for clas in classes: if not clas.clashes_with(selected_classes): selected_classes.append(clas) Working out clashes might be awkward if classes are of uneven lengths, start at strange times and so on. Mapping start and end times into a simplified representation of "blocks" of time (every 15 minutes / 30 minutes or whatever you need) would make it easier to look for overlaps between the start and end of different classes. A: BeautifulSoup was mentioned here a few times, e.g get-list-of-xml-attribute-values-in-python. Beautiful Soup is a Python HTML/XML parser designed for quick turnaround projects like screen-scraping. Three features make it powerful: Beautiful Soup won't choke if you give it bad markup. It yields a parse tree that makes approximately as much sense as your original document. This is usually good enough to collect the data you need and run away. Beautiful Soup provides a few simple methods and Pythonic idioms for navigating, searching, and modifying a parse tree: a toolkit for dissecting a document and extracting what you need. You don't have to create a custom parser for each application. Beautiful Soup automatically converts incoming documents to Unicode and outgoing documents to UTF-8. You don't have to think about encodings, unless the document doesn't specify an encoding and Beautiful Soup can't autodetect one. Then you just have to specify the original encoding. Beautiful Soup parses anything you give it, and does the tree traversal stuff for you. You can tell it "Find all the links", or "Find all the links of class externalLink", or "Find all the links whose urls match "foo.com", or "Find the table heading that's got bold text, then give me that text." Valuable data that was once locked up in poorly-designed websites is now within your reach. Projects that would have taken hours take only minutes with Beautiful Soup. A: There are waaay too many questions here. Please break this down into subject areas and ask specific questions on each subject. Please focus on one of these with specific questions. Please define your terms: "best" doesn't mean anything without some specific measurement to optimize. Here's what I think I see in your list of topics. Scraping HTML 1 Logon to the website using its Enterprise Sign On Engine login 2 Find my current semester and its related subjects (pre setup) 3 Navigate to the right page and get the data from each related subject (lecture, practical and workshop times) 4 Strip the data of useless information Some algorithm to "rank" based on "closer to each other" looking for a "best time". Since these terms are undefined, it's nearly impossible to provide any help on this. 5 Rank the classes which are closer to each other higher, the ones on random days lower 6 Solve a best time table solution Output something. 7 Output me a detailed list of the BEST CASE information 8 Output me a detailed list of the possible class information (some might be full for example) Optimize something, looking for "best". Another undefinable term. 9 Get the program to select the best classes automatically 10 Keep checking to see if we can achieve 7. BTW, Python has "lists". Whether or not they're "linked" doesn't really enter into it.
Automated Class timetable optimize crawler?
Overall Plan Get my class information to automatically optimize and select my uni class timetable Overall Algorithm Logon to the website using its Enterprise Sign On Engine login Find my current semester and its related subjects (pre setup) Navigate to the right page and get the data from each related subject (lecture, practical and workshop times) Strip the data of useless information Rank the classes which are closer to each other higher, the ones on random days lower Solve a best time table solution Output me a detailed list of the BEST CASE information Output me a detailed list of the possible class information (some might be full for example) Get the program to select the best classes automatically Keep checking to see if we can achieve 7. 6 in detail Get all the classes, using the lectures as a focus point, would be highest ranked (only one per subject), and try to arrange the classes around that. Questions Can anyone supply me with links to something that might be similar to this hopefully written in python? In regards to 6.: what data structure would you recommend to store this information in? A linked list where each object of uniclass? Should i write all information to a text file? I am thinking uniclass to be setup like the following attributes: Subject Rank Time Type Teacher I am hardly experienced in Python and thought this would be a good learning project to try to accomplish. Thanks for any help and links provided to help get me started, open to edits to tag appropriately or what ever is necessary (not sure what this falls under other than programming and python?) EDIT: can't really get the proper formatting i want for this SO post ><
[ "Depending on how far you plan on taking #6, and how big the dataset is, it may be non-trivial; it certainly smacks of NP-hard global optimisation to me...\nStill, if you're talking about tens (rather than hundreds) of nodes, a fairly dumb algorithm should give good enough performance.\nSo, you have two constraints:\n\nA total ordering on the classes by score;\nthis is flexible. \nClass clashes; this is not flexible.\n\nWhat I mean by flexible is that you can go to more spaced out classes (with lower scores), but you cannot be in two classes at once. Interestingly, there's likely to be a positive correlation between score and clashes; higher scoring classes are more likely to clash.\nMy first pass at an algorithm:\nselected_classes = []\nclasses = sorted(classes, key=lambda c: c.score)\nfor clas in classes:\n if not clas.clashes_with(selected_classes):\n selected_classes.append(clas)\n\nWorking out clashes might be awkward if classes are of uneven lengths, start at strange times and so on. Mapping start and end times into a simplified representation of \"blocks\" of time (every 15 minutes / 30 minutes or whatever you need) would make it easier to look for overlaps between the start and end of different classes.\n", "BeautifulSoup was mentioned here a few times, e.g get-list-of-xml-attribute-values-in-python.\n\nBeautiful Soup is a Python HTML/XML parser designed for quick turnaround projects like screen-scraping. Three features make it powerful:\n\nBeautiful Soup won't choke if you give it bad markup. It yields a parse tree that makes approximately as much sense as your original document. This is usually good enough to collect the data you need and run away.\nBeautiful Soup provides a few simple methods and Pythonic idioms for navigating, searching, and modifying a parse tree: a toolkit for dissecting a document and extracting what you need. You don't have to create a custom parser for each application.\nBeautiful Soup automatically converts incoming documents to Unicode and outgoing documents to UTF-8. You don't have to think about encodings, unless the document doesn't specify an encoding and Beautiful Soup can't autodetect one. Then you just have to specify the original encoding.\n\nBeautiful Soup parses anything you give it, and does the tree traversal stuff for you. You can tell it \"Find all the links\", or \"Find all the links of class externalLink\", or \"Find all the links whose urls match \"foo.com\", or \"Find the table heading that's got bold text, then give me that text.\"\nValuable data that was once locked up in poorly-designed websites is now within your reach. Projects that would have taken hours take only minutes with Beautiful Soup.\n\n", "There are waaay too many questions here.\nPlease break this down into subject areas and ask specific questions on each subject. Please focus on one of these with specific questions. Please define your terms: \"best\" doesn't mean anything without some specific measurement to optimize.\nHere's what I think I see in your list of topics.\n\nScraping HTML\n1 Logon to the website using its Enterprise Sign On Engine login\n2 Find my current semester and its related subjects (pre setup)\n3 Navigate to the right page and get the data from each related subject (lecture, practical and workshop times)\n4 Strip the data of useless information\nSome algorithm to \"rank\" based on \"closer to each other\" looking for a \"best time\". Since these terms are undefined, it's nearly impossible to provide any help on this.\n5 Rank the classes which are closer to each other higher, the ones on random days lower\n6 Solve a best time table solution\nOutput something.\n7 Output me a detailed list of the BEST CASE information\n8 Output me a detailed list of the possible class information (some might be full for example)\nOptimize something, looking for \"best\". Another undefinable term.\n9 Get the program to select the best classes automatically\n10 Keep checking to see if we can achieve 7.\n\nBTW, Python has \"lists\". Whether or not they're \"linked\" doesn't really enter into it. \n" ]
[ 2, 0, 0 ]
[]
[]
[ "python", "scheduling", "screen_scraping" ]
stackoverflow_0000419698_python_scheduling_screen_scraping.txt
Q: python install on leopard I'll admit I'm completely dumbed by python install. Can someone help me on how to install module I want to play with PyGame, PyOpenGL etc. So I install them, but I everytime I type "import pygame" error message shows up. here's my environment so far. In .bash_profile PATH=${PATH}:/System/Library/Frameworks/Python.framework/Versions/Current/bin Using easy_install PyOpenGL placed this /Library/Python/2.5/site-packages/PyOpenGL-3.0.0b8-py2.5.egg Locating pygame module dchong:~ danielchong$ locate pygame /System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/py2app/recipes/pygame.py /System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/py2app/recipes/pygame.pyc dchong:~ danielchong$ locate pyopengl /System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/py2app/recipes/pyopengl.py /System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/py2app/recipes/pyopengl.pyc when I run python Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import pygame Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named pygame A: I'm not a huge fan of the default python install on OS X in the first place, mostly because it's usually a pretty old version. I find everything works better if I use the macports package. easy_install seems to work better with the macports package, but maybe that's just because I'm too lazy to figure out all the nuances of the default install. From what I can see there, it looks like the path to the packages isn't set correctly. Are you sure you're using the right site-packages directory? A: See http://farmdev.com/thoughts/66/python-3-0-on-mac-os-x-alongside-2-6-2-5-etc-/
python install on leopard
I'll admit I'm completely dumbed by python install. Can someone help me on how to install module I want to play with PyGame, PyOpenGL etc. So I install them, but I everytime I type "import pygame" error message shows up. here's my environment so far. In .bash_profile PATH=${PATH}:/System/Library/Frameworks/Python.framework/Versions/Current/bin Using easy_install PyOpenGL placed this /Library/Python/2.5/site-packages/PyOpenGL-3.0.0b8-py2.5.egg Locating pygame module dchong:~ danielchong$ locate pygame /System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/py2app/recipes/pygame.py /System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/py2app/recipes/pygame.pyc dchong:~ danielchong$ locate pyopengl /System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/py2app/recipes/pyopengl.py /System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/py2app/recipes/pyopengl.pyc when I run python Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import pygame Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named pygame
[ "I'm not a huge fan of the default python install on OS X in the first place, mostly because it's usually a pretty old version. I find everything works better if I use the macports package.\neasy_install seems to work better with the macports package, but maybe that's just because I'm too lazy to figure out all the nuances of the default install.\nFrom what I can see there, it looks like the path to the packages isn't set correctly. Are you sure you're using the right site-packages directory?\n", "See http://farmdev.com/thoughts/66/python-3-0-on-mac-os-x-alongside-2-6-2-5-etc-/\n" ]
[ 1, 0 ]
[]
[]
[ "easy_install", "macos", "osx_leopard", "python" ]
stackoverflow_0000420515_easy_install_macos_osx_leopard_python.txt
Q: What are the best prebuilt libraries for doing Web Crawling in Python I need to crawl and store locally for future analysis the contents of a finite list of websites. I basically want to slurp in all pages and follow all internal links to get the entire publicly available site. Are there existing free libraries to get me there? I've seen Chilkat, but it's for pay. I'm just looking for baseline functionality here. Thoughts? Suggestions? Exact Duplicate: Anyone know of a good python based web crawler that I could use? A: Use Scrapy. It is a twisted-based web crawler framework. Still under heavy development but it works already. Has many goodies: Built-in support for parsing HTML, XML, CSV, and Javascript A media pipeline for scraping items with images (or any other media) and download the image files as well Support for extending Scrapy by plugging your own functionality using middlewares, extensions, and pipelines Wide range of built-in middlewares and extensions for handling of compression, cache, cookies, authentication, user-agent spoofing, robots.txt handling, statistics, crawl depth restriction, etc Interactive scraping shell console, very useful for developing and debugging Web management console for monitoring and controlling your bot Telnet console for low-level access to the Scrapy process Example code to extract information about all torrent files added today in the mininova torrent site, by using a XPath selector on the HTML returned: class Torrent(ScrapedItem): pass class MininovaSpider(CrawlSpider): domain_name = 'mininova.org' start_urls = ['http://www.mininova.org/today'] rules = [Rule(RegexLinkExtractor(allow=['/tor/\d+']), 'parse_torrent')] def parse_torrent(self, response): x = HtmlXPathSelector(response) torrent = Torrent() torrent.url = response.url torrent.name = x.x("//h1/text()").extract() torrent.description = x.x("//div[@id='description']").extract() torrent.size = x.x("//div[@id='info-left']/p[2]/text()[2]").extract() return [torrent] A: Do you really need a library? I strongly recommend Heritrix as a great general purpose crawler that will preserve the whole webpage (as opposed to the more common crawlers that store only part of the text). It's a bit rough around the edges, but works great. That said, you could try the HarvestMan http://www.harvestmanontheweb.com/
What are the best prebuilt libraries for doing Web Crawling in Python
I need to crawl and store locally for future analysis the contents of a finite list of websites. I basically want to slurp in all pages and follow all internal links to get the entire publicly available site. Are there existing free libraries to get me there? I've seen Chilkat, but it's for pay. I'm just looking for baseline functionality here. Thoughts? Suggestions? Exact Duplicate: Anyone know of a good python based web crawler that I could use?
[ "Use Scrapy.\nIt is a twisted-based web crawler framework. Still under heavy development but it works already. Has many goodies:\n\nBuilt-in support for parsing HTML, XML, CSV, and Javascript\nA media pipeline for scraping items with images (or any other media) and download the image files as well\nSupport for extending Scrapy by plugging your own functionality using middlewares, extensions, and pipelines\nWide range of built-in middlewares and extensions for handling of compression, cache, cookies, authentication, user-agent spoofing, robots.txt handling, statistics, crawl depth restriction, etc\nInteractive scraping shell console, very useful for developing and debugging\nWeb management console for monitoring and controlling your bot\nTelnet console for low-level access to the Scrapy process\n\nExample code to extract information about all torrent files added today in the mininova torrent site, by using a XPath selector on the HTML returned:\nclass Torrent(ScrapedItem):\n pass\n\nclass MininovaSpider(CrawlSpider):\n domain_name = 'mininova.org'\n start_urls = ['http://www.mininova.org/today']\n rules = [Rule(RegexLinkExtractor(allow=['/tor/\\d+']), 'parse_torrent')]\n\n def parse_torrent(self, response):\n x = HtmlXPathSelector(response)\n torrent = Torrent()\n\n torrent.url = response.url\n torrent.name = x.x(\"//h1/text()\").extract()\n torrent.description = x.x(\"//div[@id='description']\").extract()\n torrent.size = x.x(\"//div[@id='info-left']/p[2]/text()[2]\").extract()\n return [torrent]\n\n", "Do you really need a library? I strongly recommend Heritrix as a great general purpose crawler that will preserve the whole webpage (as opposed to the more common crawlers that store only part of the text). It's a bit rough around the edges, but works great. \nThat said, you could try the HarvestMan http://www.harvestmanontheweb.com/\n" ]
[ 7, 0 ]
[]
[]
[ "python", "web_crawler" ]
stackoverflow_0000421283_python_web_crawler.txt
Q: In Python, how I do use subprocess instead of os.system? I have a Python script that calls an executable program with various arguments (in this example, it is 'sqlpubwiz.exe' which is the "Microsoft SQL Server Database Publishing Wizard"): import os sqlpubwiz = r'"C:\Program Files\Microsoft SQL Server\90\Tools\Publishing\sqlpubwiz.exe"' server = 'myLocalServer' database = 'myLocalDatabase' connection_values = ['server=' + server, 'database=' + database, 'trusted_connection=true'] connection_string = ';'.join(connection_values) dbms_version = '2000' sqlscript_filename = 'CreateSchema.sql' args = [ sqlpubwiz, 'script', '-C ' + connection_string, sqlscript_filename, '-schemaonly', '-targetserver ' + dbms_version, '-f', ] cmd = ' '.join(args) os.system(cmd) This code runs properly but I have would like to get into the habit of using subprocess since it is intended to replace os.system. However, after a few failed attempts, I can not seem to get it work properly. How would the above code look like if it was converted to use subprocess in place of os.system? A: import subprocess p=subprocess.Popen(args, stdout=subprocess.PIPE) print p.communicate()[0] It would look pretty much the same. But the path should not be r'"whatever the path is"'. Because that gives me an error. You want "the path with escaped backslashes" or r'the path without escaping'. Also args should be of the form ['-arg', 'args'] instead of ['arg argsval']. A: Remove quotes from the name of the executable. On the first line of your example, instead of sqlpubwiz = r'"C:\Program Files\Microsoft SQL Server\90\Tools\Publishing\sqlpubwiz.exe"' use: sqlpubwiz = r'C:\Program Files\Microsoft SQL Server\90\Tools\Publishing\sqlpubwiz.exe' That's because you don't have to escape anything since a shell won't be involved. Then just use subprocess.call(args) (don't join the args, pass them as a list) If you want to capture the output (os.system can't do it) just follow subprocess documentation: result = subprocess.Popen(args, stdout=subprocess.PIPE).communicate()[0] print result A: Below is my revised code based on Carlos Rendon (and nosklo) help and suggestions: # import os import subprocess sqlpubwiz = r'C:\Program Files\Microsoft SQL Server\90\Tools\Publishing\sqlpubwiz.exe' server = 'myLocalServer' database = 'myLocalDatabase' connection_values = ['server=' + server, 'database=' + database, 'trusted_connection=true'] connection_string = ';'.join(connection_values) dbms_version = '2000' sqlscript_filename = 'CreateSchema.sql' args = [ sqlpubwiz, 'script', '-C', connection_string, sqlscript_filename, '-schemaonly', '-targetserver', dbms_version, '-f', ] # cmd = ' '.join(args) # os.system(cmd) subprocess.call(args) (Note: The original argument values that contained spaces needed to be converted into separate list items.) A: FYI, subprocess has a list2cmdline() function that will let you see the string that Popen will be using. Your version gives: '"C:\\Program Files\\Microsoft SQL Server\\90\\Tools\\Publishing\\sqlpubwiz.exe" script "-C server=myLocalServer;database=myLocalDatabase;trusted_connection=true" CreateSchema.sql -schemaonly "-targetserver 2000" -f' with extra quotes around "-C server=myLocalServer;database=myLocalDatabase;trusted_connection=true" and "-targetserver 2000". Properly formatted: args = [ sqlpubwiz, 'script', '-C', connection_string, sqlscript_filename, '-schemaonly', '-targetserver', dbms_version, '-f', ] gives: '"C:\\Program Files\\Microsoft SQL Server\\90\\Tools\\Publishing\\sqlpubwiz.exe" script -C server=myLocalServer;database=myLocalDatabase;trusted_connection=true CreateSchema.sql -schemaonly -targetserver 2000 -f' Also, minor point, but it's a good habit to make sequences such as args that don't need to be mutable into tuples instead of lists. A: Please remember that os.system uses the shell, and so you must really pass shell=True to the Popen constructor/call to emulate it properly. You may not actually need a shell, of course, but there it is. A: This isnt an answer directly to your question but I thought it might be helpful. In case you ever want more granular control over what is returned for exception handling etc, you can also check out pexpect. I have used it in situations where the process I was calling didn't necessarily exit with normal status signals, or I wanted to interact with it more. It's a pretty handy function. A: Windows commands will accept forward slashes '/' in place of backslashes in pathnames, so you can use the former to avoid escaping backslashes in your command strings. Not exactly an answer to your question, but perhaps useful to know.
In Python, how I do use subprocess instead of os.system?
I have a Python script that calls an executable program with various arguments (in this example, it is 'sqlpubwiz.exe' which is the "Microsoft SQL Server Database Publishing Wizard"): import os sqlpubwiz = r'"C:\Program Files\Microsoft SQL Server\90\Tools\Publishing\sqlpubwiz.exe"' server = 'myLocalServer' database = 'myLocalDatabase' connection_values = ['server=' + server, 'database=' + database, 'trusted_connection=true'] connection_string = ';'.join(connection_values) dbms_version = '2000' sqlscript_filename = 'CreateSchema.sql' args = [ sqlpubwiz, 'script', '-C ' + connection_string, sqlscript_filename, '-schemaonly', '-targetserver ' + dbms_version, '-f', ] cmd = ' '.join(args) os.system(cmd) This code runs properly but I have would like to get into the habit of using subprocess since it is intended to replace os.system. However, after a few failed attempts, I can not seem to get it work properly. How would the above code look like if it was converted to use subprocess in place of os.system?
[ "import subprocess\np=subprocess.Popen(args, stdout=subprocess.PIPE)\nprint p.communicate()[0]\n\nIt would look pretty much the same. But the path should not be r'\"whatever the path is\"'. Because that gives me an error. You want \"the path with escaped backslashes\" or r'the path without escaping'.\nAlso args should be of the form ['-arg', 'args'] instead of ['arg argsval'].\n", "Remove quotes from the name of the executable. On the first line of your example, instead of\nsqlpubwiz = r'\"C:\\Program Files\\Microsoft SQL Server\\90\\Tools\\Publishing\\sqlpubwiz.exe\"'\n\nuse:\nsqlpubwiz = r'C:\\Program Files\\Microsoft SQL Server\\90\\Tools\\Publishing\\sqlpubwiz.exe'\n\nThat's because you don't have to escape anything since a shell won't be involved.\nThen just use subprocess.call(args) (don't join the args, pass them as a list)\nIf you want to capture the output (os.system can't do it) just follow subprocess documentation:\nresult = subprocess.Popen(args, stdout=subprocess.PIPE).communicate()[0]\nprint result\n\n", "Below is my revised code based on Carlos Rendon (and nosklo) help and suggestions: \n# import os\nimport subprocess \n\nsqlpubwiz = r'C:\\Program Files\\Microsoft SQL Server\\90\\Tools\\Publishing\\sqlpubwiz.exe'\nserver = 'myLocalServer'\ndatabase = 'myLocalDatabase'\nconnection_values = ['server=' + server, 'database=' + database, 'trusted_connection=true']\nconnection_string = ';'.join(connection_values)\ndbms_version = '2000'\nsqlscript_filename = 'CreateSchema.sql' \n\nargs = [\n sqlpubwiz,\n 'script',\n '-C',\n connection_string,\n sqlscript_filename,\n '-schemaonly',\n '-targetserver',\n dbms_version,\n '-f',\n ] \n\n# cmd = ' '.join(args)\n# os.system(cmd)\n\nsubprocess.call(args)\n\n(Note: The original argument values that contained spaces needed to be converted into separate list items.)\n", "FYI, subprocess has a list2cmdline() function that will let you see the string that Popen will be using.\nYour version gives:\n'\"C:\\\\Program Files\\\\Microsoft SQL Server\\\\90\\\\Tools\\\\Publishing\\\\sqlpubwiz.exe\" script \"-C server=myLocalServer;database=myLocalDatabase;trusted_connection=true\" CreateSchema.sql -schemaonly \"-targetserver 2000\" -f'\n\nwith extra quotes around \"-C server=myLocalServer;database=myLocalDatabase;trusted_connection=true\" and \"-targetserver 2000\".\nProperly formatted:\nargs = [\n sqlpubwiz,\n 'script',\n '-C', connection_string,\n sqlscript_filename,\n '-schemaonly',\n '-targetserver', dbms_version,\n '-f',\n]\n\ngives:\n'\"C:\\\\Program Files\\\\Microsoft SQL Server\\\\90\\\\Tools\\\\Publishing\\\\sqlpubwiz.exe\" script -C server=myLocalServer;database=myLocalDatabase;trusted_connection=true CreateSchema.sql -schemaonly -targetserver 2000 -f'\n\nAlso, minor point, but it's a good habit to make sequences such as args that don't need to be mutable into tuples instead of lists.\n", "Please remember that os.system uses the shell, and so you must really pass\nshell=True\n\nto the Popen constructor/call to emulate it properly. You may not actually need a shell, of course, but there it is.\n", "This isnt an answer directly to your question but I thought it might be helpful.\nIn case you ever want more granular control over what is returned for exception handling etc, you can also check out pexpect. I have used it in situations where the process I was calling didn't necessarily exit with normal status signals, or I wanted to interact with it more. It's a pretty handy function.\n", "Windows commands will accept forward slashes '/' in place of backslashes in pathnames, so you can use the former to avoid escaping backslashes in your command strings. Not exactly an answer to your question, but perhaps useful to know.\n" ]
[ 5, 4, 4, 4, 0, 0, 0 ]
[]
[]
[ "process", "python", "scripting", "syntax" ]
stackoverflow_0000421206_process_python_scripting_syntax.txt
Q: Drawing with Webdings in PIL I've got a Python program using PIL to render text, and it works great with all kinds of fonts. But it only draws "missing glyph" rectangles with wingdings or webdings. Here's a sample that tries to draw every unicode character: # Run this with .ttf file path as an argument, and also an encoding if you like. # It will make 16 PNGs with all the characters drawn. import sys import Image, ImageDraw, ImageFont size = 20 per = 64 chars = 0x10000 perpage = per*per fontfile = sys.argv[1] encoding = sys.argv[2] if len(sys.argv) > 2 else '' font = ImageFont.truetype(sys.argv[1], size, encoding=encoding) for page in range(0, chars//perpage): im = Image.new("RGB", (size*per+30, size*per+30), '#ffffc0') draw = ImageDraw.Draw(im) for line in range(0, per): for col in range(0, per): c = page*perpage + line*per + col draw.text((col*size, line*size), unichr(c), font=font, fill='black') im.save('allchars_%03d.png' % page) With Arial.ttf (or even better, ArialUni.ttf), I get 16 interesting PNGs. Searching for issues with PIL, some symbol fonts need to have their encoding specified. If I use Symbol.ttf, I get all missing glyphs until I specify "symb" as the encoding. How do I get wingdings to work? A: I must have done something wrong before. "symb" as the encoding works for wingdings too! Sorry for the noise... A: Not all of wingdings is mapped to unicode: see http://www.alanwood.net/demos/wingdings.html Also you're only covering the Basic Multilingual Plane (wikipedia)
Drawing with Webdings in PIL
I've got a Python program using PIL to render text, and it works great with all kinds of fonts. But it only draws "missing glyph" rectangles with wingdings or webdings. Here's a sample that tries to draw every unicode character: # Run this with .ttf file path as an argument, and also an encoding if you like. # It will make 16 PNGs with all the characters drawn. import sys import Image, ImageDraw, ImageFont size = 20 per = 64 chars = 0x10000 perpage = per*per fontfile = sys.argv[1] encoding = sys.argv[2] if len(sys.argv) > 2 else '' font = ImageFont.truetype(sys.argv[1], size, encoding=encoding) for page in range(0, chars//perpage): im = Image.new("RGB", (size*per+30, size*per+30), '#ffffc0') draw = ImageDraw.Draw(im) for line in range(0, per): for col in range(0, per): c = page*perpage + line*per + col draw.text((col*size, line*size), unichr(c), font=font, fill='black') im.save('allchars_%03d.png' % page) With Arial.ttf (or even better, ArialUni.ttf), I get 16 interesting PNGs. Searching for issues with PIL, some symbol fonts need to have their encoding specified. If I use Symbol.ttf, I get all missing glyphs until I specify "symb" as the encoding. How do I get wingdings to work?
[ "I must have done something wrong before. \"symb\" as the encoding works for wingdings too! Sorry for the noise...\n", "Not all of wingdings is mapped to unicode: see http://www.alanwood.net/demos/wingdings.html\nAlso you're only covering the Basic Multilingual Plane (wikipedia)\n" ]
[ 2, 1 ]
[]
[]
[ "fonts", "python", "python_imaging_library" ]
stackoverflow_0000422555_fonts_python_python_imaging_library.txt
Q: How can the user communicate with my python script using the shell? How can I implement the following in python? #include <iostream> int main() { std::string a; std::cout << "What is your name? "; std::cin >> a; std::cout << std::endl << "You said: " << a << std::endl; } Output: What is your name? Nick You said: Nick A: Call name = raw_input('What is your name?') and print 'You said', name A: Look at the print statement and the raw_input() function. Or look at sys.stdin.read() and sys.stdout.write(). When using sys.stdout, don't forget to flush. A: print "You said:", raw_input("What is your name? ") EDIT: as Swaroop mentioned, this doesn't work (I'm guessing raw_input flushes stdout) A: The simplest way for python 2.x is var = raw_input() print var Another way is using the input() function; n.b. input(), unlike raw_input() expects the input to be a valid python expression. In most cases you should raw_input() and validate it first. You can also use import sys var = sys.stdin.read() lines = sys.stdin.readlines() more_lines = [line.strip() for line sys.stdin] sys.stdout.write(var) sys.stdout.writelines(lines+more_lines) # important sys.stdout.flush() As of python 3.0, however, input() replaces raw_input() and print becomes a function, so var = input() print(var)
How can the user communicate with my python script using the shell?
How can I implement the following in python? #include <iostream> int main() { std::string a; std::cout << "What is your name? "; std::cin >> a; std::cout << std::endl << "You said: " << a << std::endl; } Output: What is your name? Nick You said: Nick
[ "Call \nname = raw_input('What is your name?')\n\nand \nprint 'You said', name\n\n", "Look at the print statement and the raw_input() function.\nOr look at sys.stdin.read() and sys.stdout.write(). \nWhen using sys.stdout, don't forget to flush.\n", "print \"You said:\", raw_input(\"What is your name? \")\n\nEDIT: as Swaroop mentioned, this doesn't work (I'm guessing raw_input flushes stdout)\n", "The simplest way for python 2.x is\nvar = raw_input()\nprint var\n\nAnother way is using the input() function; n.b. input(), unlike raw_input() expects the input to be a valid python expression. In most cases you should raw_input() and validate it first. You can also use\nimport sys\nvar = sys.stdin.read()\nlines = sys.stdin.readlines()\nmore_lines = [line.strip() for line sys.stdin]\n\nsys.stdout.write(var)\nsys.stdout.writelines(lines+more_lines)\n# important\nsys.stdout.flush()\n\nAs of python 3.0, however, input() replaces raw_input() and print becomes a function, so\nvar = input()\nprint(var)\n\n" ]
[ 7, 3, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000422091_python.txt
Q: How to maintain lists and dictionaries between function calls in Python? I have a function. Inside that I'm maintainfing a dictionary of values. I want that dictionary to be maintained between different function calls Suppose the dic is : a = {'a':1,'b':2,'c':3} At first call,say,I changed a[a] to 100 Dict becomes a = {'a':100,'b':2,'c':3} At another call,i changed a[b] to 200 I want that dic to be a = {'a':100,'b':200,'c':3} But in my code a[a] doesn't remain 100.It changes to initial value 1. I need an answer ASAP....I m already late...Please help me friends... A: You might be talking about a callable object. class MyFunction( object ): def __init__( self ): self.rememberThis= dict() def __call__( self, arg1, arg2 ): # do something rememberThis['a'] = arg1 return someValue myFunction= MyFunction() From then on, use myFunction as a simple function. You can access the rememberThis dictionary using myFunction.rememberThis. A: You could use a static variable: def foo(k, v): foo.a[k] = v foo.a = {'a': 1, 'b': 2, 'c': 3} foo('a', 100) foo('b', 200) print foo.a A: Rather than forcing globals on the code base (that can be the decision of the caller) I prefer the idea of keeping the state related to an instance of the function. A class is good for this but doesn't communicate well what you are trying to accomplish and can be a bit verbose. Taking advantage of closures is, in my opinion, a lot cleaner. def function_the_world_sees(): a = {'a':1,'b':2,'c':3} def actual_function(arg0, arg1): a[arg0] = arg1 return a return actual_function stateful_function = function_the_world_sees() stateful_function("b", 100) stateful_function("b", 200) The main caution to keep in mind is that when you make assignments in "actual_function", they occur within "actual_function". This means you can't reassign a to a different variable. The work arounds I use are to put all of my variables I plan to reassign into either into a single element list per variable or a dictionary. A: If 'a' is being created inside the function. It is going out of scope. Simply create it outside the function(and before the function is called). By doing this the list/hash will not be deleted after the program leaves the function. a = {'a':1,'b':2,'c':3} # call you funciton here A: This question doesn't have an elegant answer, in my opinion. The options are callable objects, default values, and attribute hacks. Callable objects are the right answer, but they bring in a lot of structure for what would be a single "static" declaration in another language. Default values are a minor change to the code, but it's kludgy and can be confusing to a new python programmer looking at your code. I don't like them because their existence isn't hidden from anyone who might be looking at your API. I generally go with an attribute hack. My preferred method is: def myfunct(): if not hasattr(myfunct, 'state'): myfunct.state = list() # access myfunct.state in the body however you want This keeps the declaration of the state in the first line of the function where it belongs, as well as keeping myfunct as a function. The downside is you do the attribute check every time you call the function. This is almost certainly not going to be a bottleneck in most code. A: You can 'cheat' using Python's behavior for default arguments. Default arguments are only evaluated once; they get reused for every call of the function. >>> def testFunction(persistent_dict={'a': 0}): ... persistent_dict['a'] += 1 ... print persistent_dict['a'] ... >>> testFunction() 1 >>> testFunction() 2 This isn't the most elegant solution; if someone calls the function and passes in a parameter it will override the default, which probably isn't what you want. If you just want a quick and dirty way to get the results, that will work. If you're doing something more complicated it might be better to factor it out into a class like S. Lott mentioned. EDIT: Renamed the dictionary so it wouldn't hide the builtin dict as per the comment below. A: Personally, I like the idea of the global statement. It doesn't introduce a global variable but states that a local identifier actually refers to one in the global namespace. d = dict() l = list() def foo(bar, baz): global d global l l.append(bar, baz) d[bar] = baz In python 3.0 there is also a "nonlocal" statement.
How to maintain lists and dictionaries between function calls in Python?
I have a function. Inside that I'm maintainfing a dictionary of values. I want that dictionary to be maintained between different function calls Suppose the dic is : a = {'a':1,'b':2,'c':3} At first call,say,I changed a[a] to 100 Dict becomes a = {'a':100,'b':2,'c':3} At another call,i changed a[b] to 200 I want that dic to be a = {'a':100,'b':200,'c':3} But in my code a[a] doesn't remain 100.It changes to initial value 1. I need an answer ASAP....I m already late...Please help me friends...
[ "You might be talking about a callable object.\nclass MyFunction( object ):\n def __init__( self ):\n self.rememberThis= dict()\n def __call__( self, arg1, arg2 ):\n # do something\n rememberThis['a'] = arg1\n return someValue\n\nmyFunction= MyFunction()\n\nFrom then on, use myFunction as a simple function. You can access the rememberThis dictionary using myFunction.rememberThis.\n", "You could use a static variable:\ndef foo(k, v):\n foo.a[k] = v\nfoo.a = {'a': 1, 'b': 2, 'c': 3}\n\nfoo('a', 100)\nfoo('b', 200)\n\nprint foo.a\n\n", "Rather than forcing globals on the code base (that can be the decision of the caller) I prefer the idea of keeping the state related to an instance of the function. A class is good for this but doesn't communicate well what you are trying to accomplish and can be a bit verbose. Taking advantage of closures is, in my opinion, a lot cleaner.\ndef function_the_world_sees():\n a = {'a':1,'b':2,'c':3}\n\n def actual_function(arg0, arg1):\n a[arg0] = arg1\n return a\n\n return actual_function\nstateful_function = function_the_world_sees()\n\nstateful_function(\"b\", 100) \nstateful_function(\"b\", 200)\n\nThe main caution to keep in mind is that when you make assignments in \"actual_function\", they occur within \"actual_function\". This means you can't reassign a to a different variable. The work arounds I use are to put all of my variables I plan to reassign into either into a single element list per variable or a dictionary.\n", "If 'a' is being created inside the function. It is going out of scope. Simply create it outside the function(and before the function is called). By doing this the list/hash will not be deleted after the program leaves the function.\na = {'a':1,'b':2,'c':3}\n\n# call you funciton here\n\n", "This question doesn't have an elegant answer, in my opinion. The options are callable objects, default values, and attribute hacks. Callable objects are the right answer, but they bring in a lot of structure for what would be a single \"static\" declaration in another language. Default values are a minor change to the code, but it's kludgy and can be confusing to a new python programmer looking at your code. I don't like them because their existence isn't hidden from anyone who might be looking at your API.\nI generally go with an attribute hack. My preferred method is:\ndef myfunct():\n if not hasattr(myfunct, 'state'): myfunct.state = list()\n # access myfunct.state in the body however you want\n\nThis keeps the declaration of the state in the first line of the function where it belongs, as well as keeping myfunct as a function. The downside is you do the attribute check every time you call the function. This is almost certainly not going to be a bottleneck in most code.\n", "You can 'cheat' using Python's behavior for default arguments. Default arguments are only evaluated once; they get reused for every call of the function.\n>>> def testFunction(persistent_dict={'a': 0}):\n... persistent_dict['a'] += 1\n... print persistent_dict['a']\n...\n>>> testFunction()\n1\n>>> testFunction()\n2\n\nThis isn't the most elegant solution; if someone calls the function and passes in a parameter it will override the default, which probably isn't what you want.\nIf you just want a quick and dirty way to get the results, that will work. If you're doing something more complicated it might be better to factor it out into a class like S. Lott mentioned.\nEDIT: Renamed the dictionary so it wouldn't hide the builtin dict as per the comment below.\n", "Personally, I like the idea of the global statement. It doesn't introduce a global variable but states that a local identifier actually refers to one in the global namespace.\nd = dict()\nl = list()\ndef foo(bar, baz):\n global d\n global l\n l.append(bar, baz)\n d[bar] = baz\n\nIn python 3.0 there is also a \"nonlocal\" statement.\n" ]
[ 18, 15, 8, 6, 4, 3, 3 ]
[]
[]
[ "function_calls", "python", "variables" ]
stackoverflow_0000419379_function_calls_python_variables.txt
Q: can cherrypy receive multipart/mixed POSTs out of the box? We're receiving some POST data of xml + arbitrary binary files (like images and audio) from a device that only gives us multipart/mixed encoding. I've setup a cherrypy upload/POST handler for our receiver end. I've managed to allow it to do arbitrary number of parameters using multipart/form-data. However when we try to send the multipart-mixed data, we're not getting any processing. @cherrypy.expose def upload(self, *args,**kwargs): """upload adapted from cherrypy tutorials We use our variation of cgi.FieldStorage to parse the MIME encoded HTML form data containing the file.""" print args print kwargs cherrypy.response.timeout = 1300 lcHDRS = {} for key, val in cherrypy.request.headers.iteritems(): lcHDRS[key.lower()] = val incomingBytes = int(lcHDRS['content-length']) print cherrypy.request.rfile #etc..etc... So, when submitting multipart/form-data, args and kwargs are well defined. args are the form fields, kwargs=hash of vars and values. When I submit multipart/mixed, args and kwargs are empty, and I just have cherrypy.request.rfile as the raw POST information. My question is, does cherrypy have a built in handler to handle multipart/mixed and chunked encoding for POST? Or will I need to override the cherrypy.tools.process_request_body and roll my own decoder? It seems like the builtin wsgi server with cherrypy handles this as part of the HTTP/1.1 spec, but I could not seem to find documentation in cherrypy in accessing this functionality. ...to clarify I'm using latest version 3.1.1 or so of Cherrypy. Making a default form just involves making parameters in the upload function. For the multipart/form-data, I've been calling curl -F param1=@file1.jpg -F param2=sometext -F param3=@file3.wav http://destination:port/upload In that example, I get: args = ['param1','param2','param3] kwargs = {'param1':CString<>, 'param2': 'sometext', 'param3':CString<>} When trying to submit the multipart/mixed, I tried looking at the request.body, but kept on getting None for that, regardless of setting the body processing. The input we're getting is coming in as this: user-agent:UNTRUSTED/1.0 Profile/MIDP-2.0 Configuration/CLDC-1.1 content-language:en-US content-length:565719 mime-version:1.0 content-type:multipart/mixed; boundary='newdivider' host:192.168.1.1:8180 transfer-encoding:chunked --newdivider Content-type: text/xml <?xml version='1.0' ?><data><Stuff>.... etc...etc... --newdivider Content-type: image/jpeg Content-ID: file://localhost/root1/photos/Garden.jpg Content-transfer-encoding: binary <binary data> I've got a sneaking suspicion that the multipart/mixed is the problem that cherrypy is just giving me just the rfile. Our goal is to have cherrypy process the body into its parts with minimal processing on the receive side (ie, let cherrypy do its magic). If that requires us being tougher on the sending format to be a content-type that cherrypy likes, then so be it. What are the accepted formats? Is it only multipart/form-data? A: My bad. Whenever the Content-Type is of type "multipart/*", then CP tries to stick the contents into request.params (if any other Content-Type, it goes into request.body). Unfortunately, CP has assumed that any multipart message is form-data, and made no provision for other subtypes. I've just fixed this in trunk, and it should be released in 3.1.2. Sorry for the inconvenience. In the short term, you can try applying the changeset locally; see http://www.cherrypy.org/ticket/890.
can cherrypy receive multipart/mixed POSTs out of the box?
We're receiving some POST data of xml + arbitrary binary files (like images and audio) from a device that only gives us multipart/mixed encoding. I've setup a cherrypy upload/POST handler for our receiver end. I've managed to allow it to do arbitrary number of parameters using multipart/form-data. However when we try to send the multipart-mixed data, we're not getting any processing. @cherrypy.expose def upload(self, *args,**kwargs): """upload adapted from cherrypy tutorials We use our variation of cgi.FieldStorage to parse the MIME encoded HTML form data containing the file.""" print args print kwargs cherrypy.response.timeout = 1300 lcHDRS = {} for key, val in cherrypy.request.headers.iteritems(): lcHDRS[key.lower()] = val incomingBytes = int(lcHDRS['content-length']) print cherrypy.request.rfile #etc..etc... So, when submitting multipart/form-data, args and kwargs are well defined. args are the form fields, kwargs=hash of vars and values. When I submit multipart/mixed, args and kwargs are empty, and I just have cherrypy.request.rfile as the raw POST information. My question is, does cherrypy have a built in handler to handle multipart/mixed and chunked encoding for POST? Or will I need to override the cherrypy.tools.process_request_body and roll my own decoder? It seems like the builtin wsgi server with cherrypy handles this as part of the HTTP/1.1 spec, but I could not seem to find documentation in cherrypy in accessing this functionality. ...to clarify I'm using latest version 3.1.1 or so of Cherrypy. Making a default form just involves making parameters in the upload function. For the multipart/form-data, I've been calling curl -F param1=@file1.jpg -F param2=sometext -F param3=@file3.wav http://destination:port/upload In that example, I get: args = ['param1','param2','param3] kwargs = {'param1':CString<>, 'param2': 'sometext', 'param3':CString<>} When trying to submit the multipart/mixed, I tried looking at the request.body, but kept on getting None for that, regardless of setting the body processing. The input we're getting is coming in as this: user-agent:UNTRUSTED/1.0 Profile/MIDP-2.0 Configuration/CLDC-1.1 content-language:en-US content-length:565719 mime-version:1.0 content-type:multipart/mixed; boundary='newdivider' host:192.168.1.1:8180 transfer-encoding:chunked --newdivider Content-type: text/xml <?xml version='1.0' ?><data><Stuff>.... etc...etc... --newdivider Content-type: image/jpeg Content-ID: file://localhost/root1/photos/Garden.jpg Content-transfer-encoding: binary <binary data> I've got a sneaking suspicion that the multipart/mixed is the problem that cherrypy is just giving me just the rfile. Our goal is to have cherrypy process the body into its parts with minimal processing on the receive side (ie, let cherrypy do its magic). If that requires us being tougher on the sending format to be a content-type that cherrypy likes, then so be it. What are the accepted formats? Is it only multipart/form-data?
[ "My bad. Whenever the Content-Type is of type \"multipart/*\", then CP tries to stick the contents into request.params (if any other Content-Type, it goes into request.body).\nUnfortunately, CP has assumed that any multipart message is form-data, and made no provision for other subtypes. I've just fixed this in trunk, and it should be released in 3.1.2. Sorry for the inconvenience. In the short term, you can try applying the changeset locally; see http://www.cherrypy.org/ticket/890.\n" ]
[ 4 ]
[]
[]
[ "cherrypy", "python" ]
stackoverflow_0000415019_cherrypy_python.txt
Q: How to return more than one value from a function in Python? How to return more than one variable from a function in Python? A: You separate the values you want to return by commas: def get_name(): # you code return first_name, last_name The commas indicate it's a tuple, so you could wrap your values by parentheses: return (first_name, last_name) Then when you call the function you a) save all values to one variable as a tuple, or b) separate your variable names by commas name = get_name() # this is a tuple first_name, last_name = get_name() (first_name, last_name) = get_name() # You can put parentheses, but I find it ugly A: Here is also the code to handle the result: def foo (a): x=a y=a*2 return (x,y) (x,y) = foo(50) A: Return as a tuple, e.g. def foo (a): x=a y=a*2 return (x,y)
How to return more than one value from a function in Python?
How to return more than one variable from a function in Python?
[ "You separate the values you want to return by commas:\ndef get_name():\n # you code\n return first_name, last_name\n\nThe commas indicate it's a tuple, so you could wrap your values by parentheses:\nreturn (first_name, last_name)\n\nThen when you call the function you a) save all values to one variable as a tuple, or b) separate your variable names by commas\nname = get_name() # this is a tuple\nfirst_name, last_name = get_name()\n(first_name, last_name) = get_name() # You can put parentheses, but I find it ugly\n\n", "Here is also the code to handle the result:\ndef foo (a):\n x=a\n y=a*2\n return (x,y)\n\n(x,y) = foo(50)\n\n", "Return as a tuple, e.g.\ndef foo (a):\n x=a\n y=a*2\n return (x,y)\n\n" ]
[ 156, 14, 6 ]
[]
[]
[ "function", "multiple_variable_return", "python" ]
stackoverflow_0000423710_function_multiple_variable_return_python.txt
Q: How to save inline formset models in Django? Formsets have a .save() method, and the documentation says to save in views like this: if request.method == "POST": formset = BookInlineFormSet(request.POST, request.FILES, instance=author) if formset.is_valid(): formset.save() # Do something. else: formset = BookInlineFormSet(instance=author) I am following this, and it works when the parent is created, but I'm getting an exception in Django when it is saving existing models. The parent actually is saved to the database and the exception occurs when saving related models. KeyError at /bcdetails/NewProds/1/ None Request Method: POST Request URL: http://rdif.local/bcdetails/NewProds/1/ Exception Type: KeyError Exception Value: None Exception Location: /usr/lib/python2.5/site-packages/django/forms/models.py in save_existing_objects, line 403 Python Executable: /usr/bin/python Python Version: 2.5.2 Python Path: ['/usr/lib/python2.5/site-packages/paramiko-1.7.4-py2.5.egg', '/usr/lib/python2.5/site-packages/Fabric-0.0.9-py2.5.egg', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/local/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/Numeric', '/usr/lib/python2.5/site-packages/PIL', '/usr/lib/python2.5/site-packages/gst-0.10', '/var/lib/python-support/python2.5', '/usr/lib/python2.5/site-packages/gtk-2.0', '/var/lib/python-support/python2.5/gtk-2.0', '/usr/lib/site-python', '/home/www/rdif.com/test/'] Server time: Wed, 7 Jan 2009 23:18:19 -0700 I spent some time in Django source but can't find anything there. Do I need to iterate through each formset and only save models that have changed? A: I discovered my problem, and it's embarrassing. In the parent model form I had exclude = ('...',) in the Meta class, and one of the excluded fields was critical for the relations in the inline_formsets. So, I've removed the excludes and ignoring those fields in the template.
How to save inline formset models in Django?
Formsets have a .save() method, and the documentation says to save in views like this: if request.method == "POST": formset = BookInlineFormSet(request.POST, request.FILES, instance=author) if formset.is_valid(): formset.save() # Do something. else: formset = BookInlineFormSet(instance=author) I am following this, and it works when the parent is created, but I'm getting an exception in Django when it is saving existing models. The parent actually is saved to the database and the exception occurs when saving related models. KeyError at /bcdetails/NewProds/1/ None Request Method: POST Request URL: http://rdif.local/bcdetails/NewProds/1/ Exception Type: KeyError Exception Value: None Exception Location: /usr/lib/python2.5/site-packages/django/forms/models.py in save_existing_objects, line 403 Python Executable: /usr/bin/python Python Version: 2.5.2 Python Path: ['/usr/lib/python2.5/site-packages/paramiko-1.7.4-py2.5.egg', '/usr/lib/python2.5/site-packages/Fabric-0.0.9-py2.5.egg', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/local/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/Numeric', '/usr/lib/python2.5/site-packages/PIL', '/usr/lib/python2.5/site-packages/gst-0.10', '/var/lib/python-support/python2.5', '/usr/lib/python2.5/site-packages/gtk-2.0', '/var/lib/python-support/python2.5/gtk-2.0', '/usr/lib/site-python', '/home/www/rdif.com/test/'] Server time: Wed, 7 Jan 2009 23:18:19 -0700 I spent some time in Django source but can't find anything there. Do I need to iterate through each formset and only save models that have changed?
[ "I discovered my problem, and it's embarrassing.\nIn the parent model form I had exclude = ('...',) in the Meta class, and one of the excluded fields was critical for the relations in the inline_formsets. So, I've removed the excludes and ignoring those fields in the template.\n" ]
[ 4 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0000423437_django_django_forms_python.txt
Q: Python and different Operating Systems I am about to start a personal project using python and I will be using it on both Linux(Fedora) and Windows(Vista), Although I might as well make it work on a mac while im at it. I have found an API for the GUI that will work on all 3. The reason I am asking is because I have always heard of small differences that are easily avoided if you know about them before starting. Does anyone have any tips or suggestions that fall along these lines? A: In general: Be careful with paths. Use os.path wherever possible. Don't assume that HOME points to the user's home/profile directory. Avoid using things like unix-domain sockets, fifos, and other POSIX-specific stuff. More specific stuff: If you're using wxPython, note that there may be differences in things like which thread certain events are generated in. Don't assume that events are generated in a specific thread. If you're calling a method which triggers a GUI-event, don't assume that event-handlers have completed by the time your method returns. (And vice versa, of course.) There are always differences in how a GUI will appear. Layouts are not always implemented in the exact same way. A: Some things I've noticed in my cross platform development in Python: OSX doesn't have a tray, so application notifications usually happen right in the dock. So if you're building a background notification service you may need a small amount of platform-specific code. os.startfile() apparently only works on Windows. Either that or Python 2.5.1 on Leopard doesn't support it. os.normpath() is something you might want to consider using too, just to keep your paths and volumes using the correct slash notation and volume names. icons are dealt with in fundamentally different ways in Windows and OSX, be sure you provide icons at all the right sizes for both (16x16, 24x24, 32x32, 48x48, 64x64, 128x128 and 256x256) and be sure to read up on setting up icons with wx widgets. A: You should take care of the Python version you are developing against. Especially, on a Mac, the default version of Python installed with the OS, is rather old (of course, newer versions can be installed) Don't use the OS specific libraries Take special care of 'special' UI elements, like taskbar icons (windows), ... Use forward slashes when using paths, avoid C:/, /home/..., ... Use os.path to work with paths. A: Some filename problems: This.File and this.file are different files on Linux, but point to the same file on Windows. Troublesome if you manage some file repository and access it from both platforms. Less frequent related problem is that of names like NUL or LPT being files on Windows. Binary distribution code (if any) would likely use py2exe on Win, py2app on Mac and wouldn't be present on Linux.
Python and different Operating Systems
I am about to start a personal project using python and I will be using it on both Linux(Fedora) and Windows(Vista), Although I might as well make it work on a mac while im at it. I have found an API for the GUI that will work on all 3. The reason I am asking is because I have always heard of small differences that are easily avoided if you know about them before starting. Does anyone have any tips or suggestions that fall along these lines?
[ "In general:\n\nBe careful with paths. Use os.path wherever possible.\nDon't assume that HOME points to the user's home/profile directory.\nAvoid using things like unix-domain sockets, fifos, and other POSIX-specific stuff.\n\nMore specific stuff:\n\nIf you're using wxPython, note that there may be differences in things like which thread certain events are generated in. Don't assume that events are generated in a specific thread. If you're calling a method which triggers a GUI-event, don't assume that event-handlers have completed by the time your method returns. (And vice versa, of course.)\nThere are always differences in how a GUI will appear. Layouts are not always implemented in the exact same way.\n\n", "Some things I've noticed in my cross platform development in Python:\n\nOSX doesn't have a tray, so application notifications usually happen right in the dock. So if you're building a background notification service you may need a small amount of platform-specific code.\nos.startfile() apparently only works on Windows. Either that or Python 2.5.1 on Leopard doesn't support it.\nos.normpath() is something you might want to consider using too, just to keep your paths and volumes using the correct slash notation and volume names.\nicons are dealt with in fundamentally different ways in Windows and OSX, be sure you provide icons at all the right sizes for both (16x16, 24x24, 32x32, 48x48, 64x64, 128x128 and 256x256) and be sure to read up on setting up icons with wx widgets.\n\n", "\nYou should take care of the Python version you are developing against. Especially, on a Mac, the default version of Python installed with the OS, is rather old (of course, newer versions can be installed)\nDon't use the OS specific libraries\nTake special care of 'special' UI elements, like taskbar icons (windows), ...\nUse forward slashes when using paths, avoid C:/, /home/..., ... Use os.path to work with paths.\n\n", "Some filename problems: This.File and this.file are different files on Linux, but point to the same file on Windows. Troublesome if you manage some file repository and access it from both platforms. Less frequent related problem is that of names like NUL or LPT being files on Windows.\nBinary distribution code (if any) would likely use py2exe on Win, py2app on Mac and wouldn't be present on Linux.\n" ]
[ 4, 3, 1, 0 ]
[]
[]
[ "cross_platform", "python" ]
stackoverflow_0000425343_cross_platform_python.txt
Q: Correct way to detect sequence parameter? I want to write a function that accepts a parameter which can be either a sequence or a single value. The type of value is str, int, etc., but I don't want it to be restricted to a hardcoded list. In other words, I want to know if the parameter X is a sequence or something I have to convert to a sequence to avoid special-casing later. I could do type(X) in (list, tuple) but there may be other sequence types I'm not aware of, and no common base class. -N. Edit: See my "answer" below for why most of these answers don't help me. Maybe you have something better to suggest. A: As of 2.6, use abstract base classes. >>> import collections >>> isinstance([], collections.Sequence) True >>> isinstance(0, collections.Sequence) False Furthermore ABC's can be customized to account for exceptions, such as not considering strings to be sequences. Here an example: import abc import collections class Atomic(object): __metaclass__ = abc.ABCMeta @classmethod def __subclasshook__(cls, other): return not issubclass(other, collections.Sequence) or NotImplemented Atomic.register(basestring) After registration the Atomic class can be used with isinstance and issubclass: assert isinstance("hello", Atomic) == True This is still much better than a hard-coded list, because you only need to register the exceptions to the rule, and external users of the code can register their own. Note that in Python 3 the syntax for specifying metaclasses changed and the basestring abstract superclass was removed, which requires something like the following to be used instead: class Atomic(metaclass=abc.ABCMeta): @classmethod def __subclasshook__(cls, other): return not issubclass(other, collections.Sequence) or NotImplemented Atomic.register(str) If desired, it's possible to write code which is compatible both both Python 2.6+ and 3.x, but doing so requires using a slightly more complicated technique which dynamically creates the needed abstract base class, thereby avoiding syntax errors due to the metaclass syntax difference. This is essentially the same as what Benjamin Peterson's six module'swith_metaclass()function does. class _AtomicBase(object): @classmethod def __subclasshook__(cls, other): return not issubclass(other, collections.Sequence) or NotImplemented class Atomic(abc.ABCMeta("NewMeta", (_AtomicBase,), {})): pass try: unicode = unicode except NameError: # 'unicode' is undefined, assume Python >= 3 Atomic.register(str) # str includes unicode in Py3, make both Atomic Atomic.register(bytes) # bytes will also be considered Atomic (optional) else: # basestring is the abstract superclass of both str and unicode types Atomic.register(basestring) # make both types of strings Atomic In versions before 2.6, there are type checkers in theoperatormodule. >>> import operator >>> operator.isSequenceType([]) True >>> operator.isSequenceType(0) False A: The problem with all of the above mentioned ways is that str is considered a sequence (it's iterable, has getitem, etc.) yet it's usually treated as a single item. For example, a function may accept an argument that can either be a filename or a list of filenames. What's the most Pythonic way for the function to detect the first from the latter? Based on the revised question, it sounds like what you want is something more like: def to_sequence(arg): ''' determine whether an arg should be treated as a "unit" or a "sequence" if it's a unit, return a 1-tuple with the arg ''' def _multiple(x): return hasattr(x,"__iter__") if _multiple(arg): return arg else: return (arg,) >>> to_sequence("a string") ('a string',) >>> to_sequence( (1,2,3) ) (1, 2, 3) >>> to_sequence( xrange(5) ) xrange(5) This isn't guaranteed to handle all types, but it handles the cases you mention quite well, and should do the right thing for most of the built-in types. When using it, make sure whatever receives the output of this can handle iterables. A: Sequences are described here: https://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange So sequences are not the same as iterable objects. I think sequence must implement __getitem__, whereas iterable objects must implement __iter__. So for example string are sequences and don't implement __iter__, xrange objects are sequences and don't implement __getslice__. But from what you seen to want to do, I'm not sure you want sequences, but rather iterable objects. So go for hasattr("__getitem__", X) you want sequences, but go rather hasattr("__iter__", X) if you don't want strings for example. A: IMHO, the python way is to pass the list as *list. As in: myfunc(item) myfunc(*items) A: In cases like this, I prefer to just always take the sequence type or always take the scalar. Strings won't be the only types that would behave poorly in this setup; rather, any type that has an aggregate use and allows iteration over its parts might misbehave. A: The simplest method would be to check if you can turn it into an iterator. ie try: it = iter(X) # Iterable except TypeError: # Not iterable If you need to ensure that it's a restartable or random access sequence (ie not a generator etc), this approach won't be sufficient however. As others have noted, strings are also iterable, so if you need so exclude them (particularly important if recursing through items, as list(iter('a')) gives ['a'] again, then you may need to specifically exclude them with: if not isinstance(X, basestring) A: I'm new here so I don't know what's the correct way to do it. I want to answer my answers: The problem with all of the above mentioned ways is that str is considered a sequence (it's iterable, has __getitem__, etc.) yet it's usually treated as a single item. For example, a function may accept an argument that can either be a filename or a list of filenames. What's the most Pythonic way for the function to detect the first from the latter? Should I post this as a new question? Edit the original one? A: I think what I would do is check whether the object has certain methods that indicate it is a sequence. I'm not sure if there is an official definition of what makes a sequence. The best I can think of is, it must support slicing. So you could say: is_sequence = '__getslice__' in dir(X) You might also check for the particular functionality you're going to be using. As pi pointed out in the comment, one issue is that a string is a sequence, but you probably don't want to treat it as one. You could add an explicit test that the type is not str. A: If strings are the problem, detect a sequence and filter out the special case of strings: def is_iterable(x): if type(x) == str: return False try: iter(x) return True except TypeError: return False A: Revised answer: I don't know if your idea of "sequence" matches what the Python manuals call a "Sequence Type", but in case it does, you should look for the __Contains__ method. That is the method Python uses to implement the check "if something in object:" if hasattr(X, '__contains__'): print "X is a sequence" My original answer: I would check if the object that you received implements an iterator interface: if hasattr(X, '__iter__'): print "X is a sequence" For me, that's the closest match to your definition of sequence since that would allow you to do something like: for each in X: print each A: You're asking the wrong question. You don't try to detect types in Python; you detect behavior. Write another function that handles a single value. (let's call it _use_single_val). Write one function that handles a sequence parameter. (let's call it _use_sequence). Write a third parent function that calls the two above. (call it use_seq_or_val). Surround each call with an exception handler to catch an invalid parameter (i.e. not single value or sequence). Write unit tests to pass correct & incorrect parameters to the parent function to make sure it catches the exceptions properly. def _use_single_val(v): print v + 1 # this will fail if v is not a value type def _use_sequence(s): print s[0] # this will fail if s is not indexable def use_seq_or_val(item): try: _use_single_val(item) except TypeError: pass try: _use_sequence(item) except TypeError: pass raise TypeError, "item not a single value or sequence" EDIT: Revised to handle the "sequence or single value" asked about in the question.
Correct way to detect sequence parameter?
I want to write a function that accepts a parameter which can be either a sequence or a single value. The type of value is str, int, etc., but I don't want it to be restricted to a hardcoded list. In other words, I want to know if the parameter X is a sequence or something I have to convert to a sequence to avoid special-casing later. I could do type(X) in (list, tuple) but there may be other sequence types I'm not aware of, and no common base class. -N. Edit: See my "answer" below for why most of these answers don't help me. Maybe you have something better to suggest.
[ "As of 2.6, use abstract base classes.\n>>> import collections\n>>> isinstance([], collections.Sequence)\nTrue\n>>> isinstance(0, collections.Sequence)\nFalse\n\nFurthermore ABC's can be customized to account for exceptions, such as not considering strings to be sequences. Here an example:\nimport abc\nimport collections\n\nclass Atomic(object):\n __metaclass__ = abc.ABCMeta\n @classmethod\n def __subclasshook__(cls, other):\n return not issubclass(other, collections.Sequence) or NotImplemented\n\nAtomic.register(basestring)\n\nAfter registration the Atomic class can be used with isinstance and issubclass:\nassert isinstance(\"hello\", Atomic) == True\n\nThis is still much better than a hard-coded list, because you only need to register the exceptions to the rule, and external users of the code can register their own.\nNote that in Python 3 the syntax for specifying metaclasses changed and the basestring abstract superclass was removed, which requires something like the following to be used instead:\nclass Atomic(metaclass=abc.ABCMeta):\n @classmethod\n def __subclasshook__(cls, other):\n return not issubclass(other, collections.Sequence) or NotImplemented\n\nAtomic.register(str)\n\nIf desired, it's possible to write code which is compatible both both Python 2.6+ and 3.x, but doing so requires using a slightly more complicated technique which dynamically creates the needed abstract base class, thereby avoiding syntax errors due to the metaclass syntax difference. This is essentially the same as what Benjamin Peterson's six module'swith_metaclass()function does.\nclass _AtomicBase(object):\n @classmethod\n def __subclasshook__(cls, other):\n return not issubclass(other, collections.Sequence) or NotImplemented\n\nclass Atomic(abc.ABCMeta(\"NewMeta\", (_AtomicBase,), {})):\n pass\n\ntry:\n unicode = unicode\nexcept NameError: # 'unicode' is undefined, assume Python >= 3\n Atomic.register(str) # str includes unicode in Py3, make both Atomic\n Atomic.register(bytes) # bytes will also be considered Atomic (optional)\nelse:\n # basestring is the abstract superclass of both str and unicode types\n Atomic.register(basestring) # make both types of strings Atomic\n\nIn versions before 2.6, there are type checkers in theoperatormodule.\n>>> import operator\n>>> operator.isSequenceType([])\nTrue\n>>> operator.isSequenceType(0)\nFalse\n\n", "\nThe problem with all of the above\n mentioned ways is that str is\n considered a sequence (it's iterable,\n has getitem, etc.) yet it's\n usually treated as a single item.\nFor example, a function may accept an\n argument that can either be a filename\n or a list of filenames. What's the\n most Pythonic way for the function to\n detect the first from the latter?\n\nBased on the revised question, it sounds like what you want is something more like:\ndef to_sequence(arg):\n ''' \n determine whether an arg should be treated as a \"unit\" or a \"sequence\"\n if it's a unit, return a 1-tuple with the arg\n '''\n def _multiple(x): \n return hasattr(x,\"__iter__\")\n if _multiple(arg): \n return arg\n else:\n return (arg,)\n\n>>> to_sequence(\"a string\")\n('a string',)\n>>> to_sequence( (1,2,3) )\n(1, 2, 3)\n>>> to_sequence( xrange(5) )\nxrange(5)\n\nThis isn't guaranteed to handle all types, but it handles the cases you mention quite well, and should do the right thing for most of the built-in types.\nWhen using it, make sure whatever receives the output of this can handle iterables.\n", "Sequences are described here:\nhttps://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange\nSo sequences are not the same as iterable objects. I think sequence must implement\n__getitem__, whereas iterable objects must implement __iter__.\nSo for example string are sequences and don't implement __iter__, xrange objects are sequences and don't implement __getslice__.\nBut from what you seen to want to do, I'm not sure you want sequences, but rather iterable objects.\nSo go for hasattr(\"__getitem__\", X) you want sequences, but go rather hasattr(\"__iter__\", X) if you don't want strings for example.\n", "IMHO, the python way is to pass the list as *list. As in:\nmyfunc(item)\nmyfunc(*items)\n\n", "In cases like this, I prefer to just always take the sequence type or always take the scalar. Strings won't be the only types that would behave poorly in this setup; rather, any type that has an aggregate use and allows iteration over its parts might misbehave.\n", "The simplest method would be to check if you can turn it into an iterator. ie\ntry:\n it = iter(X)\n # Iterable\nexcept TypeError:\n # Not iterable\n\nIf you need to ensure that it's a restartable or random access sequence (ie not a generator etc), this approach won't be sufficient however.\nAs others have noted, strings are also iterable, so if you need so exclude them (particularly important if recursing through items, as list(iter('a')) gives ['a'] again, then you may need to specifically exclude them with:\n if not isinstance(X, basestring)\n\n", "I'm new here so I don't know what's the correct way to do it. I want to answer my answers:\nThe problem with all of the above mentioned ways is that str is considered a sequence (it's iterable, has __getitem__, etc.) yet it's usually treated as a single item.\nFor example, a function may accept an argument that can either be a filename or a list of filenames. What's the most Pythonic way for the function to detect the first from the latter?\nShould I post this as a new question? Edit the original one?\n", "I think what I would do is check whether the object has certain methods that indicate it is a sequence. I'm not sure if there is an official definition of what makes a sequence. The best I can think of is, it must support slicing. So you could say:\nis_sequence = '__getslice__' in dir(X)\n\nYou might also check for the particular functionality you're going to be using.\nAs pi pointed out in the comment, one issue is that a string is a sequence, but you probably don't want to treat it as one. You could add an explicit test that the type is not str.\n", "If strings are the problem, detect a sequence and filter out the special case of strings:\ndef is_iterable(x):\n if type(x) == str:\n return False\n try:\n iter(x)\n return True\n except TypeError:\n return False\n\n", "Revised answer: \nI don't know if your idea of \"sequence\" matches what the Python manuals call a \"Sequence Type\", but in case it does, you should look for the __Contains__ method. That is the method Python uses to implement the check \"if something in object:\"\nif hasattr(X, '__contains__'):\n print \"X is a sequence\"\n\nMy original answer:\nI would check if the object that you received implements an iterator interface:\nif hasattr(X, '__iter__'):\n print \"X is a sequence\"\n\nFor me, that's the closest match to your definition of sequence since that would allow you to do something like:\nfor each in X:\n print each\n\n", "You're asking the wrong question. You don't try to detect types in Python; you detect behavior.\n\nWrite another function that handles a single value. (let's call it _use_single_val).\nWrite one function that handles a sequence parameter. (let's call it _use_sequence).\nWrite a third parent function that calls the two above. (call it use_seq_or_val). Surround each call with an exception handler to catch an invalid parameter (i.e. not single value or sequence).\nWrite unit tests to pass correct & incorrect parameters to the parent function to make sure it catches the exceptions properly.\n\n\n def _use_single_val(v):\n print v + 1 # this will fail if v is not a value type\n\n def _use_sequence(s):\n print s[0] # this will fail if s is not indexable\n\n def use_seq_or_val(item): \n try:\n _use_single_val(item)\n except TypeError:\n pass\n\n try:\n _use_sequence(item)\n except TypeError:\n pass\n\n raise TypeError, \"item not a single value or sequence\"\n\nEDIT: Revised to handle the \"sequence or single value\" asked about in the question. \n" ]
[ 19, 5, 4, 4, 3, 3, 2, 1, 1, 0, 0 ]
[ "You could pass your parameter in the built-in len() function and check whether this causes an error. As others said, the string type requires special handling.\nAccording to the documentation the len function can accept a sequence (string, list, tuple) or a dictionary.\nYou could check that an object is a string with the following code:\nx.__class__ == \"\".__class__\n\n" ]
[ -1 ]
[ "python", "sequences", "types" ]
stackoverflow_0000305359_python_sequences_types.txt
Q: Drag button between panels in wxPython Does anyone know of an example where it is shown how to drag a button from one panel to another in wxPython? I have created a bitmap button in a panel, and I would like to be able to drag it to a different panel and drop I there. I haven't found any examples using buttons, just text and files. I am using the latest version of Python and wxPython. A: If you want to graphically represent the drag, one good way to do this is to create a borderless Frame that follows the mouse during a drag. You remove the button from your source Frame, temporarily put it in this "drag Frame", and then, when the user drops, add it to your destination Frame.
Drag button between panels in wxPython
Does anyone know of an example where it is shown how to drag a button from one panel to another in wxPython? I have created a bitmap button in a panel, and I would like to be able to drag it to a different panel and drop I there. I haven't found any examples using buttons, just text and files. I am using the latest version of Python and wxPython.
[ "If you want to graphically represent the drag, one good way to do this is to create a borderless Frame that follows the mouse during a drag. You remove the button from your source Frame, temporarily put it in this \"drag Frame\", and then, when the user drops, add it to your destination Frame.\n" ]
[ 4 ]
[]
[]
[ "drag_and_drop", "python", "wxpython" ]
stackoverflow_0000425722_drag_and_drop_python_wxpython.txt
Q: Most Pythonic way equivalent for: while ((x = next()) != END) What's the best Python idiom for this C construct? while ((x = next()) != END) { .... } I don't have the ability to recode next(). update: and the answer from seems to be: for x in iter(next, END): .... A: @Mark Harrison's answer: for x in iter(next_, END): .... Here's an excerpt from Python's documentation: iter(o[, sentinel]) Return an iterator object. ...(snip)... If the second argument, sentinel, is given, then o must be a callable object. The iterator created in this case will call o with no arguments for each call to its next() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned. A: It depends a bit what you want to do. To match your example as far as possible, I would make next a generator and iterate over it: def next(): for num in range(10): yield num for x in next(): print x A: Short answer: there's no way to do inline variable assignment in a while loop in Python. Meaning that I cannot say: while x=next(): // do something here! Since that's not possible, there are a number of "idiomatically correct" ways of doing this: while 1: x = next() if x != END: // Blah else: break Obviously, this is kind of ugly. You can also use one of the "iterator" approaches listed above, but, again, that may not be ideal. Finally, you can use the "pita pocket" approach that I actually just found while googling: class Pita( object ): __slots__ = ('pocket',) marker = object() def __init__(self, v=marker): if v is not self.marker: self.pocket = v def __call__(self, v=marker): if v is not self.marker: self.pocket = v return self.pocket Now you can do: p = Pita() while p( next() ) != END: // do stuff with p.pocket! Thanks for this question; learning about the __call__ idiom was really cool! :) EDIT: I'd like to give credit where credit is due. The 'pita pocket' idiom was found here A: Maybe it's not terribly idiomatic, but I'd be inclined to go with x = next() while x != END: do_something_with_x x = next() ... but that's because I find that sort of thing easy to read A: What are you trying to do here? If you're iterating over a list, you can use for e in L where e is the element and L is the list. If you're filtering a list, you can use list comprehensions (i.e. [ e for e in L if e % 2 == 0 ] to get all the even numbers in a list). A: If you need to do this more than once, the pythonic way would use an iterator for x in iternext(): do_something_with_x where iternext would be defined using something like (explicit is better than implicit!): def iternext(): x = next() while x != END: yield x x = next() A: Can you provide more information about what you're trying to accomplish? It's not clear to me why you can't just say for x in everything(): ... and have the everything function return everything, instead of writing a next function to just return one thing at a time. Generators can even do this quite efficiently.
Most Pythonic way equivalent for: while ((x = next()) != END)
What's the best Python idiom for this C construct? while ((x = next()) != END) { .... } I don't have the ability to recode next(). update: and the answer from seems to be: for x in iter(next, END): ....
[ "@Mark Harrison's answer:\nfor x in iter(next_, END):\n ....\n\nHere's an excerpt from Python's documentation:\niter(o[, sentinel])\n\n\nReturn an iterator object.\n ...(snip)... If the second argument, sentinel, is given, then o must be\n a callable object. The iterator\n created in this case will call o\n with no arguments for each call to its\n next() method; if the value returned\n is equal to sentinel,\n StopIteration will be raised,\n otherwise the value will be returned.\n\n", "It depends a bit what you want to do. To match your example as far as possible, I would make next a generator and iterate over it:\ndef next():\n for num in range(10):\n yield num\n\nfor x in next():\n print x\n\n", "Short answer: there's no way to do inline variable assignment in a while loop in Python. Meaning that I cannot say:\nwhile x=next():\n // do something here!\n\nSince that's not possible, there are a number of \"idiomatically correct\" ways of doing this:\nwhile 1:\n x = next()\n if x != END:\n // Blah\n else:\n break\n\nObviously, this is kind of ugly. You can also use one of the \"iterator\" approaches listed above, but, again, that may not be ideal. Finally, you can use the \"pita pocket\" approach that I actually just found while googling:\nclass Pita( object ):\n __slots__ = ('pocket',)\n marker = object()\n def __init__(self, v=marker):\n if v is not self.marker:\n self.pocket = v\n def __call__(self, v=marker):\n if v is not self.marker:\n self.pocket = v\n return self.pocket\n\nNow you can do:\np = Pita()\nwhile p( next() ) != END:\n // do stuff with p.pocket!\n\nThanks for this question; learning about the __call__ idiom was really cool! :)\nEDIT: I'd like to give credit where credit is due. The 'pita pocket' idiom was found here\n", "Maybe it's not terribly idiomatic, but I'd be inclined to go with\nx = next()\nwhile x != END:\n do_something_with_x\n x = next()\n\n... but that's because I find that sort of thing easy to read\n", "What are you trying to do here?\nIf you're iterating over a list, you can use for e in L where e is the element and L is the list. If you're filtering a list, you can use list comprehensions (i.e. [ e for e in L if e % 2 == 0 ] to get all the even numbers in a list).\n", "If you need to do this more than once, the pythonic way would use an iterator\nfor x in iternext():\n do_something_with_x\n\nwhere iternext would be defined using something like\n(explicit is better than implicit!):\ndef iternext():\n x = next()\n while x != END:\n yield x\n x = next() \n\n", "Can you provide more information about what you're trying to accomplish? It's not clear to me why you can't just say\nfor x in everything():\n ...\n\nand have the everything function return everything, instead of writing a next function to just return one thing at a time. Generators can even do this quite efficiently.\n" ]
[ 14, 5, 4, 2, 1, 1, 1 ]
[]
[]
[ "c", "python" ]
stackoverflow_0000028559_c_python.txt
Q: Cross Platform SWF Playback with Python? I'm looking for different solutions to playing back SWF files on Windows, OSX and Linux using Python. Ideally I'd like to embed the player inside a wxPython frame/window. One possibility I'm investigating is the Mozilla XPCOM framework since its used by FireFox to load the Flash plugin within the browser. A: Have you considered Adobe AIR? Bruce Eckel said: Try combining the power of Python with the polish of Adobe Flash to create a desktop application. A: Though I don't know how to embed a browser within a wxPython window, the following code might serve in a pinch (and will work cross-platform, assuming you're working in Python 2.5 or above): import webbrowser webbrowser.open(your_swf_url) It might be best to delegate this task to the browser anyway.
Cross Platform SWF Playback with Python?
I'm looking for different solutions to playing back SWF files on Windows, OSX and Linux using Python. Ideally I'd like to embed the player inside a wxPython frame/window. One possibility I'm investigating is the Mozilla XPCOM framework since its used by FireFox to load the Flash plugin within the browser.
[ "Have you considered Adobe AIR? \nBruce Eckel said: Try combining the power of Python with the polish of Adobe Flash to create a desktop application.\n", "Though I don't know how to embed a browser within a wxPython window, the following code might serve in a pinch (and will work cross-platform, assuming you're working in Python 2.5 or above):\nimport webbrowser\nwebbrowser.open(your_swf_url)\n\nIt might be best to delegate this task to the browser anyway.\n" ]
[ 3, 2 ]
[]
[]
[ "cross_platform", "flash", "python", "wxpython" ]
stackoverflow_0000417159_cross_platform_flash_python_wxpython.txt