content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Is there any python web app framework that provides database abstraction layer for SQL and NoSQL? Is it even possible to create an abstraction layer that can accommodate relational and non-relational databases? The purpose of this layer is to minimize repetition and allows a web application to use any kind of database by just changing/modifying the code in one place (ie, the abstraction layer). The part that sits on top of the abstraction layer must not need to worry whether the underlying database is relational (SQL) or non-relational (NoSQL) or whatever new kind of database that may come out later in the future. A: There's a Summer of Code project going on right now to add non-relational support to Django's ORM. It seems to be going well and chances are good that it will be merged into core in time for Django 1.3. A: You could use stock Django and Django-nonrel ( http://www.allbuttonspressed.com/projects/django-nonrel ) together to get a quite unified experience. Some limits apply, read docs carefully though, remembering Spolsky's "All abstractions are leaky". A: Yo may also check web2py, they support relational databases and GAE on the core. A: Regarding App Engine, all existing attempts limit you in some way (web2py doesn't support transactions or namespaces and probably many other stuff, for example). If you plan to work with GAE, use what GAE provides and forget looking for a SQL-NoSQL holy grail. Existing solutions are inevitably limited and affect performance negatively. A: Thank you for all the answers. To summarize the answers, currently only web2py and Django supports this kind of abstraction. It is not about a SQL-NoSQL holy grail, using abstraction can make the apps more flexible. Lets assume that you started a project using NoSQL, and then later on you need to switch over to SQL. It is desirable that you only make changes to the codes in a few spots instead of all over the place. For some cases, it does not really matter whether you store the data in a relational or non-relational db. For example, storing user profiles, text content for dynamic page, or blog entries. I know there must be a trade off by using the abstraction, but my question is more about the existing solution or technical insight, instead of the consequences.
Is there any python web app framework that provides database abstraction layer for SQL and NoSQL?
Is it even possible to create an abstraction layer that can accommodate relational and non-relational databases? The purpose of this layer is to minimize repetition and allows a web application to use any kind of database by just changing/modifying the code in one place (ie, the abstraction layer). The part that sits on top of the abstraction layer must not need to worry whether the underlying database is relational (SQL) or non-relational (NoSQL) or whatever new kind of database that may come out later in the future.
[ "There's a Summer of Code project going on right now to add non-relational support to Django's ORM. It seems to be going well and chances are good that it will be merged into core in time for Django 1.3.\n", "You could use stock Django and Django-nonrel ( http://www.allbuttonspressed.com/projects/django-nonrel ) ...
[ 2, 2, 1, 1, 0 ]
[]
[]
[ "database", "google_app_engine", "nosql", "python", "sql" ]
stackoverflow_0003606215_database_google_app_engine_nosql_python_sql.txt
Q: how to go to the next page using django paginator? I have something like this: myobj = paginator_method(request, myresult) return render_to_response(' ', myobj, context) And when I am going to page 2 and onward its giving MultiValueDictKeyError: Key 'name' not found in <QueryDict: {u'page': [u'2']} A: return render_to_response(' ', dict(pagination=myobj, data=myresult), context) . {{ pagination.somevar }} {{ data.somevar }}
how to go to the next page using django paginator?
I have something like this: myobj = paginator_method(request, myresult) return render_to_response(' ', myobj, context) And when I am going to page 2 and onward its giving MultiValueDictKeyError: Key 'name' not found in <QueryDict: {u'page': [u'2']}
[ "return render_to_response(' ', dict(pagination=myobj, data=myresult), context)\n\n.\n{{ pagination.somevar }}\n{{ data.somevar }}\n\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003649765_django_python.txt
Q: What are differences between List, Dictionary and Tuple in Python? What is the difference between list, dictionary and tuple in Python exactly? A: A list can store a sequence of objects in a certain order such that you can index into the list, or iterate over the list. List is a mutable type meaning that lists can be modified after they have been created. A tuple is similar to a list except it is immutable. There is also a semantic difference between a list and a tuple. To quote Nikow's answer: Tuples have structure, lists have order. A dictionary is a key-value store. It is not ordered and it requires that the keys are hashable. It is fast for lookups by key.
What are differences between List, Dictionary and Tuple in Python?
What is the difference between list, dictionary and tuple in Python exactly?
[ "A list can store a sequence of objects in a certain order such that you can index into the list, or iterate over the list. List is a mutable type meaning that lists can be modified after they have been created.\nA tuple is similar to a list except it is immutable. There is also a semantic difference between a list...
[ 53 ]
[]
[]
[ "python" ]
stackoverflow_0003649841_python.txt
Q: Using the ttk (tk 8.5) Notebook widget effectively (scrolling of tabs) I'm working on a project using Tkinter and Python. In order to have native theming and to take advantage of the new widgets I'm using ttk in Python 2.6. My problem is how to allow the user to scroll through the tabs in the notebook widget (a la firefox). Plus, I need a part in the right edge of the tabs for a close button. The frame for the active tab would need to fill the available horizontal space (including under the scroll arrows). I thought I could do this using the Place geometry manager, but I was wondering if there was a better way? The ttk python docs don't have any methods to deal with this that I could see. Edit: looks like there are difficulties for even trying to implement this using place. For one, I'd still need the tabs to scroll and the active panel to stay in the one place. A: The notebook widget doesn't do scrolling of tabs (or multiple layers of them either) because the developer doesn't believe that they make for a good GUI. I can see his point; such GUIs tend to suck. The best workaround I've seen is to have a panel on the side that allows the selection of which pane to display. You can then apply tricks to that panel to manage the amount of information there (e.g., by making it a treeview widget and holding the info hierarchically, much like most email clients handle mail folders; treeview widgets are scrollable). A: I've never used these widgets so I have no idea how possible this is, but what I would try is something akin to the grid_remove() method. If you can move the tabs to an invisible widget, or just make them invisible without losing content, that's what I'd look for/try.
Using the ttk (tk 8.5) Notebook widget effectively (scrolling of tabs)
I'm working on a project using Tkinter and Python. In order to have native theming and to take advantage of the new widgets I'm using ttk in Python 2.6. My problem is how to allow the user to scroll through the tabs in the notebook widget (a la firefox). Plus, I need a part in the right edge of the tabs for a close button. The frame for the active tab would need to fill the available horizontal space (including under the scroll arrows). I thought I could do this using the Place geometry manager, but I was wondering if there was a better way? The ttk python docs don't have any methods to deal with this that I could see. Edit: looks like there are difficulties for even trying to implement this using place. For one, I'd still need the tabs to scroll and the active panel to stay in the one place.
[ "The notebook widget doesn't do scrolling of tabs (or multiple layers of them either) because the developer doesn't believe that they make for a good GUI. I can see his point; such GUIs tend to suck. The best workaround I've seen is to have a panel on the side that allows the selection of which pane to display. You...
[ 3, 0 ]
[]
[]
[ "python", "tkinter", "ttk", "user_interface" ]
stackoverflow_0003386098_python_tkinter_ttk_user_interface.txt
Q: Why isn't web2py more readily adopted? I have been playing with python and different web frameworks. I started with Django, but am not in so deep that I am entrenched. I really quite like python but have not found that "perfect" web solution. My qualifications of perfect would be: simple to learn/code simple to host (my webhost, Site5, isn't exactly python-friendly) widely supported/used Web2Py seems like it might fit. Their case against simplicity is solid and it seems pretty simple to fire up an webserver (though the quest for a python-friendly web host continues). And Web2Py does not seem to be widely used. But why not? Tangents: Which framework do you use and why? Who do you use for your python web hosting? A: Django is more widely used, because Django is (already) more widely used.
Why isn't web2py more readily adopted?
I have been playing with python and different web frameworks. I started with Django, but am not in so deep that I am entrenched. I really quite like python but have not found that "perfect" web solution. My qualifications of perfect would be: simple to learn/code simple to host (my webhost, Site5, isn't exactly python-friendly) widely supported/used Web2Py seems like it might fit. Their case against simplicity is solid and it seems pretty simple to fire up an webserver (though the quest for a python-friendly web host continues). And Web2Py does not seem to be widely used. But why not? Tangents: Which framework do you use and why? Who do you use for your python web hosting?
[ "Django is more widely used, because Django is (already) more widely used. \n" ]
[ 1 ]
[]
[]
[ "django", "python", "web2py" ]
stackoverflow_0003649079_django_python_web2py.txt
Q: How to understand makefiles and python I'm trying to understand how a makefile works for compiling some .ui files to .py (PyQt -> Python). This is the makefile that I am using that was autogenerated: # Makefile for a PyQGIS plugin UI_FILES = Ui_UrbanAnalysis.py RESOURCE_FILES = resources.py default: compile compile: $(UI_FILES) $(RESOURCE_FILES) %.py : %.qrc pyrcc4 -o $@ $< %.py : %.ui pyuic4 -o $@ $< When I type: $ make I get the following message: make: *** No rule to make target `compile', needed by `default'. Stop. What am I doing incorrectly? Thanks. A: Not that I know the build steps you are trying to achieve, but both of these lines: default: compile compile: $(UI_FILES) $(RESOURCE_FILES) look like target lines, so they should probably be: default: compile compile: $(UI_FILES) $(RESOURCE_FILES) As it was make is probably trying to interpret the compile:... line as an action which won't do anything and means that there is no compile target. One more thing, you might want to use PHONY: default compile to tell make that these are abstract targets and do not represent files. Just as a matter of good practice.
How to understand makefiles and python
I'm trying to understand how a makefile works for compiling some .ui files to .py (PyQt -> Python). This is the makefile that I am using that was autogenerated: # Makefile for a PyQGIS plugin UI_FILES = Ui_UrbanAnalysis.py RESOURCE_FILES = resources.py default: compile compile: $(UI_FILES) $(RESOURCE_FILES) %.py : %.qrc pyrcc4 -o $@ $< %.py : %.ui pyuic4 -o $@ $< When I type: $ make I get the following message: make: *** No rule to make target `compile', needed by `default'. Stop. What am I doing incorrectly? Thanks.
[ "Not that I know the build steps you are trying to achieve, but both of these lines:\ndefault: compile\n compile: $(UI_FILES) $(RESOURCE_FILES)\n\nlook like target lines, so they should probably be:\ndefault: compile\n\ncompile: $(UI_FILES) $(RESOURCE_FILES)\n\nAs it was make is probably trying to interpret the ...
[ 2 ]
[]
[]
[ "makefile", "python" ]
stackoverflow_0003650625_makefile_python.txt
Q: Jump into a Python Interactive Session mid-program? Hey I was wondering... I am using the pydev with eclipse and I'm really enjoying the powerful debugging features, but I was wondering: Is it possible to set a breakpoint in eclipse and jump into the interactive python interpreter during execution? I think that would be pretty handy ;) edit: I want to emphasize that my goal is not to jump into a debugger. pydev/eclipse have a great debugger, and I can just look at the traceback and set break points. What I want is to execute a script and jump into an interactive python interpreter during execution so I can do things like... poke around check the values of things manipulate variables figure out some code before I add it to the app I know you can do this all with a debugger, but I can do it faster in the interactive interpreter because I can try something, see that it didn't work, and try something else without having get the app back to the point of executing that code again. A: So roughly a year on from the OP's question, PyDev has this capability built in. I am not sure when this feature was introduced, but all I know is I've spent the last ~2hrs Googling... configuring iPython and whatever (which was looking like it would have done the job), but only to realise Eclipse/PyDev has what I want ootb. As soon as you hit a breakpoint in debug mode, the console is right there ready and waiting! I only didn't notice this as there is no prompt or blinking cursor; I had wrongly assumed it was a standard, output-only, console... but it's not. It even has code-completion. Great stuff, see http://pydev.org/manual_adv_debug_console.html for more details. A: This is from an old project, and I didn't write it, but it does something similar to what you want using ipython. '''Start an IPython shell (for debugging) with current environment. Runs Call db() to start a shell, e.g. def foo(bar): for x in bar: if baz(x): import ipydb; ipydb.db() # <-- start IPython here, with current value of x (ipydb is the name of this module). . ''' import inspect,IPython def db(): '''Start IPython shell with callers environment.''' # find callers __up_frame = inspect.currentframe().f_back eval('IPython.Shell.IPShellEmbed([])()', # Empty list arg is # ipythons argv later args to dict take precedence, so # f_globals() shadows globals(). Need globals() for IPython # module. dict(globals().items() + __up_frame.f_globals.items()), __up_frame.f_locals) edit by Jim Robert (question owner): If you place the above code into a file called my_debug.py for the sake of this example. Then place that file in your python path, and you can insert the following lines anywhere in your code to jump into a debugger (as long as you execute from a shell): import my_debug my_debug.db() A: I've long been using this code in my sitecustomize.py to start a debugger on an exception. This can also be triggered by Ctrl+C. It works beautifully in the shell, don't know about eclipse. import sys def info(exception_type, value, tb): if hasattr(sys, 'ps1') or not sys.stderr.isatty() or not sys.stdin.isatty() or not sys.stdout.isatty() or type==SyntaxError: # we are in interactive mode or we don't have a tty-like # device, so we call the default hook sys.__excepthook__(exception_type, value, tb) else: import traceback import pdb if exception_type != KeyboardInterrupt: try: import growlnotify growlnotify.growlNotify("Script crashed", sticky = False) except ImportError: pass # we are NOT in interactive mode, print the exception... traceback.print_exception(exception_type, value, tb) print # ...then start the debugger in post-mortem mode. pdb.pm() sys.excepthook = info Here's the source and more discussion on StackOverflow. A: You can jump into an interactive session using code.InteractiveConsole as described here; however I don't know how to trigger this from Eclipse. A solution might be to intercept Ctrl+C to jump into this interactive console (using the signal module: signal.signal(signal.SIGINT, my_handler)), but it would probably change the execution context and you probably don't want this.
Jump into a Python Interactive Session mid-program?
Hey I was wondering... I am using the pydev with eclipse and I'm really enjoying the powerful debugging features, but I was wondering: Is it possible to set a breakpoint in eclipse and jump into the interactive python interpreter during execution? I think that would be pretty handy ;) edit: I want to emphasize that my goal is not to jump into a debugger. pydev/eclipse have a great debugger, and I can just look at the traceback and set break points. What I want is to execute a script and jump into an interactive python interpreter during execution so I can do things like... poke around check the values of things manipulate variables figure out some code before I add it to the app I know you can do this all with a debugger, but I can do it faster in the interactive interpreter because I can try something, see that it didn't work, and try something else without having get the app back to the point of executing that code again.
[ "So roughly a year on from the OP's question, PyDev has this capability built in. I am not sure when this feature was introduced, but all I know is I've spent the last ~2hrs Googling... configuring iPython and whatever (which was looking like it would have done the job), but only to realise Eclipse/PyDev has what I...
[ 9, 6, 3, 2 ]
[ "If you are already running in debug mode you can set an additional breakpoint if the program execution is currently paused (e.g. because you are already at a breakpoint). I just tried it out now with the latest Pydev - it works just fine. \nIf you are running normally (i.e. not in debug mode) all breakpoints will ...
[ -2 ]
[ "breakpoints", "debugging", "eclipse", "pydev", "python" ]
stackoverflow_0000925832_breakpoints_debugging_eclipse_pydev_python.txt
Q: Django - Ajax HttpResponse delay I have a django view function that calls another function if a condition is true, the function is called as a separate process, the view returns a status variable which shows if the function was called or not, the status is returned to a ajax click event assigned to a button. The problem is that when the function 'do_work' is executed ajax success function isn't run until 'do_work' terminates. view function /update/ if condition: p = Process(target=do_work, args(pack,)) p.daemon = True p.start() success = "True" else: success = "False" print success return HttpResponse(success) Ajax call $('button.update').click(function() { id = $(this).attr('id'); $.post("/update/", { pack : id, }, function(result){ alert(result); }); return false; }); the 'print success' gets executed right away in both cases, but the alert wont pop up until the function do_woks terminates A: Although you see the printed message before you return HttpResponse(success), that return statement in itself can't asynchronously finish the response. Presumably after that function returns, your web server is still waiting for something else to happen (such as for all child processes to terminate) before it finishes the response. For asynchronous tasks in Django I highly recommend Celery.
Django - Ajax HttpResponse delay
I have a django view function that calls another function if a condition is true, the function is called as a separate process, the view returns a status variable which shows if the function was called or not, the status is returned to a ajax click event assigned to a button. The problem is that when the function 'do_work' is executed ajax success function isn't run until 'do_work' terminates. view function /update/ if condition: p = Process(target=do_work, args(pack,)) p.daemon = True p.start() success = "True" else: success = "False" print success return HttpResponse(success) Ajax call $('button.update').click(function() { id = $(this).attr('id'); $.post("/update/", { pack : id, }, function(result){ alert(result); }); return false; }); the 'print success' gets executed right away in both cases, but the alert wont pop up until the function do_woks terminates
[ "Although you see the printed message before you return HttpResponse(success), that return statement in itself can't asynchronously finish the response.\nPresumably after that function returns, your web server is still waiting for something else to happen (such as for all child processes to terminate) before it fin...
[ 1 ]
[]
[]
[ "ajax", "django", "jquery", "process", "python" ]
stackoverflow_0003650465_ajax_django_jquery_process_python.txt
Q: Nicest, efficient way to get result tuple of sequence items fulfilling and not fulfilling condition (This is professional best practise/ pattern interest, not home work request) INPUT: any unordered sequence or generator items, function myfilter(item) returns True if filter condition is fulfilled OUTPUT: (filter_true, filter_false) tuple of sequences of original type which contain the elements partitioned according to filter in original sequence order. How would you express this without doing double filtering, or should I use double filtering? Maybe filter and loop/generator/list comprehencion with next could be answer? Should I take out the requirement of keeping the type or just change requirement giving tuple of tuple/generator result, I can not return easily generator for generator input, or can I? (The requirements are self-made) Here test of best candidate at the moment, offering two streams instead of tuple import itertools as it from sympy.ntheory import isprime as myfilter mylist = xrange(1000001,1010000,2) left,right = it.tee((myfilter(x), x) for x in mylist) filter_true = (x for p,x in left if p) filter_false = (x for p,x in right if not p) print 'Hundred primes and non-primes odd numbers' print '\n'.join( " Prime %i, not prime %i" % (next(filter_true),next(filter_false)) for i in range(100)) A: Here is a way to do it which only calls myfilter once for each item and will also work if mylist is a generator import itertools as it left,right = it.tee((myfilter(x), x) for x in mylist) filter_true = (x for p,x in left if p) filter_false = (x for p,x in right if not p) A: Let's suppose that your probleme is not memory but cpu, myfilter is heavy and you don't want to iterate and filter the original dataset twice. Here are some single pass ideas : The simple and versatile version (memoryvorous) : filter_true=[] filter_false=[] for item in items: if myfilter(item): filter_true.append(item) else: filter_false.append(item) The memory friendly version : (doesn't work with generators (unless used with list(items))) while items: item=items.pop() if myfilter(item): filter_true.append(item) else: filter_false.append(item) The generator friendly version : while True: try: item=next(items) if myfilter(item): filter_true.append(item) else: filter_false.append(item) except StopIteration: break A: The easy way (but less efficient) is to tee the iterable and filter both of them: import itertools left, right = itertools.tee( mylist ) filter_true = (x for x in left if myfilter(x)) filter_false = (x for x in right if myfilter(x)) This is less efficient than the optimal solution, because myfilter will be called repeatedly for each element. That is, if you have tested an element in left, you shouldn't have to re-test it in right because you already know the answer. If you require this optimisation, it shouldn't be hard to implement: have a look at the implementation of tee for clues. You'll need a deque for each returned iterable which you stock with the elements of the original sequence that should go in it but haven't been asked for yet.
Nicest, efficient way to get result tuple of sequence items fulfilling and not fulfilling condition
(This is professional best practise/ pattern interest, not home work request) INPUT: any unordered sequence or generator items, function myfilter(item) returns True if filter condition is fulfilled OUTPUT: (filter_true, filter_false) tuple of sequences of original type which contain the elements partitioned according to filter in original sequence order. How would you express this without doing double filtering, or should I use double filtering? Maybe filter and loop/generator/list comprehencion with next could be answer? Should I take out the requirement of keeping the type or just change requirement giving tuple of tuple/generator result, I can not return easily generator for generator input, or can I? (The requirements are self-made) Here test of best candidate at the moment, offering two streams instead of tuple import itertools as it from sympy.ntheory import isprime as myfilter mylist = xrange(1000001,1010000,2) left,right = it.tee((myfilter(x), x) for x in mylist) filter_true = (x for p,x in left if p) filter_false = (x for p,x in right if not p) print 'Hundred primes and non-primes odd numbers' print '\n'.join( " Prime %i, not prime %i" % (next(filter_true),next(filter_false)) for i in range(100))
[ "Here is a way to do it which only calls myfilter once for each item and will also work if mylist is a generator\nimport itertools as it\nleft,right = it.tee((myfilter(x), x) for x in mylist)\nfilter_true = (x for p,x in left if p)\nfilter_false = (x for p,x in right if not p)\n\n", "Let's suppose that your probl...
[ 5, 2, 0 ]
[ "I think your best bet will be constructing two separate generators:\nfilter_true = (x for x in mylist if myfilter(x))\nfilter_false = (x for x in mylist if not myfilter(x))\n\n" ]
[ -1 ]
[ "data_partitioning", "filter", "generator", "python" ]
stackoverflow_0003650305_data_partitioning_filter_generator_python.txt
Q: General network MVC framework for Python I have been using Django for web-development, and have become quite fond of that framework. However, I would like to use a similar framework but for more general network applications. Is there such a framework? Or is it possible to modify Django to be able to have a more general network/protocol backend? A: Twisted should be able to help you. Take a look at Twisted projects and decide on the protocol which you are going to use.
General network MVC framework for Python
I have been using Django for web-development, and have become quite fond of that framework. However, I would like to use a similar framework but for more general network applications. Is there such a framework? Or is it possible to modify Django to be able to have a more general network/protocol backend?
[ "Twisted should be able to help you. Take a look at Twisted projects and decide on the protocol which you are going to use.\n" ]
[ 3 ]
[]
[]
[ "django", "network_programming", "python" ]
stackoverflow_0003650818_django_network_programming_python.txt
Q: python threadpool problem (wait for something) I wrote simple web site crowler with threadpool. The problem is: then crawler is get all over site it must finish, but in real it wait for something in the end,and script dont finished, why this happend? from Queue import Queue from threading import Thread import sys from urllib import urlopen from BeautifulSoup import BeautifulSoup, SoupStrainer import re from Queue import Queue, Empty from threading import Thread visited = set() queue = Queue() class Worker(Thread): """Thread executing tasks from a given tasks queue""" def __init__(self, tasks): Thread.__init__(self) self.tasks = tasks self.daemon = True self.start() def run(self): while True: func, args, kargs = self.tasks.get() print "startcall in thread",self print args try: func(*args, **kargs) except Exception, e: print e print "stopcall in thread",self self.tasks.task_done() class ThreadPool: """Pool of threads consuming tasks from a queue""" def __init__(self, num_threads): self.tasks = Queue(num_threads) for _ in range(num_threads): Worker(self.tasks) def add_task(self, func, *args, **kargs): """Add a task to the queue""" self.tasks.put((func, args, kargs)) def wait_completion(self): """Wait for completion of all the tasks in the queue""" self.tasks.join() def process(pool,host,url): try: print "get url",url #content = urlopen(url).read().decode(charset) content = urlopen(url).read() except UnicodeDecodeError: return for link in BeautifulSoup(content, parseOnlyThese=SoupStrainer('a')): #print "link",link try: href = link['href'] except KeyError: continue if not href.startswith('http://'): href = 'http://%s%s' % (host, href) if not href.startswith('http://%s%s' % (host, '/')): continue if href not in visited: visited.add(href) pool.add_task(process,pool,host,href) print href def start(host,charset): pool = ThreadPool(7) pool.add_task(process,pool,host,'http://%s/' % (host)) pool.wait_completion() start('simplesite.com','utf8') A: The problem I see is that you never quit the while in run. So, it will block forever. You need to break that loop when the jobs are done. You could try to : 1) insert if not func: break after task.get(...) in run. 2) append pool.add_task(None, None, None) at the end of process. This is a way for process to notify the pool that he has no more task to process.
python threadpool problem (wait for something)
I wrote simple web site crowler with threadpool. The problem is: then crawler is get all over site it must finish, but in real it wait for something in the end,and script dont finished, why this happend? from Queue import Queue from threading import Thread import sys from urllib import urlopen from BeautifulSoup import BeautifulSoup, SoupStrainer import re from Queue import Queue, Empty from threading import Thread visited = set() queue = Queue() class Worker(Thread): """Thread executing tasks from a given tasks queue""" def __init__(self, tasks): Thread.__init__(self) self.tasks = tasks self.daemon = True self.start() def run(self): while True: func, args, kargs = self.tasks.get() print "startcall in thread",self print args try: func(*args, **kargs) except Exception, e: print e print "stopcall in thread",self self.tasks.task_done() class ThreadPool: """Pool of threads consuming tasks from a queue""" def __init__(self, num_threads): self.tasks = Queue(num_threads) for _ in range(num_threads): Worker(self.tasks) def add_task(self, func, *args, **kargs): """Add a task to the queue""" self.tasks.put((func, args, kargs)) def wait_completion(self): """Wait for completion of all the tasks in the queue""" self.tasks.join() def process(pool,host,url): try: print "get url",url #content = urlopen(url).read().decode(charset) content = urlopen(url).read() except UnicodeDecodeError: return for link in BeautifulSoup(content, parseOnlyThese=SoupStrainer('a')): #print "link",link try: href = link['href'] except KeyError: continue if not href.startswith('http://'): href = 'http://%s%s' % (host, href) if not href.startswith('http://%s%s' % (host, '/')): continue if href not in visited: visited.add(href) pool.add_task(process,pool,host,href) print href def start(host,charset): pool = ThreadPool(7) pool.add_task(process,pool,host,'http://%s/' % (host)) pool.wait_completion() start('simplesite.com','utf8')
[ "The problem I see is that you never quit the while in run. So, it will block forever. You need to break that loop when the jobs are done.\nYou could try to :\n1) insert \nif not func: break \n\nafter task.get(...) in run. \n2) append \npool.add_task(None, None, None) \n\nat the end of process. \nThis is a wa...
[ 1 ]
[]
[]
[ "multithreading", "pool", "python" ]
stackoverflow_0003648781_multithreading_pool_python.txt
Q: adding python packages to uClinux I have distribution of uClinux, throught "menu config" I check python and compile("make"). I have python on my chip now. There is a binary executable file /bin/python. But what about python packages? There are only some basic packages as sys, time etc. I want to add for example package pyserial for serial port. Before compilation I can in directory /python/modules in file "setup" select some packages. But all of them are in C, how can I add generally python package to my distribution? Thanks a lot for any idea. A: Did you take a look at this page : http://bytes.com/topic/python/answers/782203-python-board-os-uclinux ? I'm not sure it will fulfill your needs, but it could :)
adding python packages to uClinux
I have distribution of uClinux, throught "menu config" I check python and compile("make"). I have python on my chip now. There is a binary executable file /bin/python. But what about python packages? There are only some basic packages as sys, time etc. I want to add for example package pyserial for serial port. Before compilation I can in directory /python/modules in file "setup" select some packages. But all of them are in C, how can I add generally python package to my distribution? Thanks a lot for any idea.
[ "Did you take a look at this page : http://bytes.com/topic/python/answers/782203-python-board-os-uclinux ?\nI'm not sure it will fulfill your needs, but it could :)\n" ]
[ 0 ]
[]
[]
[ "linux", "package", "python", "uclinux" ]
stackoverflow_0003650780_linux_package_python_uclinux.txt
Q: going to next page using django paginator sends request again. My google search application making a request each time while i am using paginator. Suppose i have a 100 records. Each page have to show 10 records so ten pages. When i click 2nd page it again sending a request. Ideally it should not send the request. A: When i click 2nd page it again sending a request. Ideally it should not send the request. What do you mean by request? Is it a request to Google? Your application apparently does not cache the results. If your request to Google returns 100 pages then you should cache those hundred. When you request the second page the view should retrieve this cache and return the second page to you. If you mean request to your app, then @Daniel's comment has it right. You can get around this by sending all the results to the browser and then do the pagination using JavaScript to avoid this. A more detailed answer is difficult without seeing some code.
going to next page using django paginator sends request again.
My google search application making a request each time while i am using paginator. Suppose i have a 100 records. Each page have to show 10 records so ten pages. When i click 2nd page it again sending a request. Ideally it should not send the request.
[ "\nWhen i click 2nd page it again sending a request. Ideally it should not send the request.\n\nWhat do you mean by request? Is it a request to Google? \nYour application apparently does not cache the results. If your request to Google returns 100 pages then you should cache those hundred. When you request the seco...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003651125_django_python.txt
Q: Sending large file to PIPE input in python I have the following code: sourcefile = open(filein, "r") targetfile = open(pathout, "w") content= sourcefile.read(): p = Popen([SCRIPT], stdout=targetfile, stdin=PIPE) p.communicate(content) sourcefile.close() targetfile.close() The data in sourcefile is quite large, so it takes a lot of memory/swap to store it in 'content'. I tried to send the file directly to stdin with stdin=sourcefile, which works except the external script 'hangs', ie: keeps waiting for an EOF. This might be a bug in the external script, but that is out of my control for now.. Any advice on how to send the large file to my external script? A: Replace the p.communicate(content) with a loop which reads from the sourcefile, and writes to p.stdin in blocks. When sourcefile is EOF, make sure to close p.stdin. sourcefile = open(filein, "r") targetfile = open(pathout, "w") p = Popen([SCRIPT], stdout=targetfile, stdin=PIPE) while True: data = sourcefile.read(1024) if len(data) == 0: break p.stdin.write(data) sourcefile.close() p.stdin.close() p.wait() targetfile.close()
Sending large file to PIPE input in python
I have the following code: sourcefile = open(filein, "r") targetfile = open(pathout, "w") content= sourcefile.read(): p = Popen([SCRIPT], stdout=targetfile, stdin=PIPE) p.communicate(content) sourcefile.close() targetfile.close() The data in sourcefile is quite large, so it takes a lot of memory/swap to store it in 'content'. I tried to send the file directly to stdin with stdin=sourcefile, which works except the external script 'hangs', ie: keeps waiting for an EOF. This might be a bug in the external script, but that is out of my control for now.. Any advice on how to send the large file to my external script?
[ "Replace the p.communicate(content) with a loop which reads from the sourcefile, and writes to p.stdin in blocks. When sourcefile is EOF, make sure to close p.stdin.\nsourcefile = open(filein, \"r\")\ntargetfile = open(pathout, \"w\")\n\np = Popen([SCRIPT], stdout=targetfile, stdin=PIPE)\nwhile True:\n data = so...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0003651275_python.txt
Q: regexp python with parsing html page Good day. Little problem with regexp. I have a regexp that look like rexp2 = re.findall(r'<p>(.*?)</p>', data) And i need to grab all in <div id="header"> <h1></h1> <p> localhost OpenWrt Backfire<br /> Load: 0.00 0.00 0.00<br /> Hostname: localhost </p> </div> But my code doesnt work :( What im doing wrong? A: Statutory Warning: It is a Bad Idea to parse (X)HTML using regular expression. Fortunately there is a better way. To get going, first install the BeautifulSoup module. Next, read up on the documentation. Third, code! Here is one way to do what you are trying to do: from BeautifulSoup import BeautifulSoup html = """<div id="header"> <h1></h1> <p> localhost OpenWrt Backfire<br /> Load: 0.00 0.00 0.00<br /> Hostname: localhost </p> </div>""" soup = BeautifulSoup(html) for each in soup.findAll(name = 'p'): print each A: I wouldn't recommend using regular expressions this way. Try parsing HTML with Beautiful Soup instead and walk the DOM tree. A: dot is not mathching enter, use re.DOTALL re.findall(r'<p>(.*?)</p>', data, re.DOTALL) A: You need to specify re.M (multiline) flag to match multiline strings. But parsing HTML with regexps isn't a particularly good idea. It looks like you want some stats from an OpenWrt-powered router. Why don't you write simple CGI script that outputs required information in machine-readable format?
regexp python with parsing html page
Good day. Little problem with regexp. I have a regexp that look like rexp2 = re.findall(r'<p>(.*?)</p>', data) And i need to grab all in <div id="header"> <h1></h1> <p> localhost OpenWrt Backfire<br /> Load: 0.00 0.00 0.00<br /> Hostname: localhost </p> </div> But my code doesnt work :( What im doing wrong?
[ "Statutory Warning: It is a Bad Idea to parse (X)HTML using regular expression. \nFortunately there is a better way. To get going, first install the BeautifulSoup module. Next, read up on the documentation. Third, code!\nHere is one way to do what you are trying to do:\nfrom BeautifulSoup import BeautifulSoup\nhtml...
[ 4, 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003651589_python_regex.txt
Q: Python: Do relative imports mean you can't execute a subpackage by itself? I've recently ported my Python project to run on Python 3.1. For that I had to adopt the policy of relative imports within the submodules and subpackages of my project. I've don’t that and now the project itself works, but I noticed I can't execute any of the subpackages or submodules in it. If I try, I get "builtins.ValueError: Attempted relative import in non-package". I can only import the whole project. Is this normal? A: Yes, it's normal. If you want to execute a module that is also a part of a package (in itself a strange thing to do) you need to have absolute imports. When you execute the module it is not, from the interpreters point of view, a part of a package, but the __main__ module. So it wouldn't know where the relative packages are. The standard way to do it is to have functions in the packages, and separate executable scripts that call the functions, as this enables you to put the executable scripts outside the module, for example in /usr/bin A: You can use -m flag of the python interpreter to run modules in sub-packages (or even packages in 3.1.).
Python: Do relative imports mean you can't execute a subpackage by itself?
I've recently ported my Python project to run on Python 3.1. For that I had to adopt the policy of relative imports within the submodules and subpackages of my project. I've don’t that and now the project itself works, but I noticed I can't execute any of the subpackages or submodules in it. If I try, I get "builtins.ValueError: Attempted relative import in non-package". I can only import the whole project. Is this normal?
[ "Yes, it's normal. If you want to execute a module that is also a part of a package (in itself a strange thing to do) you need to have absolute imports. When you execute the module it is not, from the interpreters point of view, a part of a package, but the __main__ module. So it wouldn't know where the relative pa...
[ 4, 3 ]
[ "I had the same problem and I considered the -m switch too hard. \nInstead I use this:\ntry:\n from . import bar\nexcept ValueError:\n import bar\n\nif __name__ == \"__main__\":\n pass\n\n" ]
[ -1 ]
[ "import", "python", "python_3.x" ]
stackoverflow_0001585756_import_python_python_3.x.txt
Q: How can I call a particular base class method in Python? Let's say, I have the following two classes: class A(object): def __init__(self, i): self.i = i class B(object): def __init__(self, j): self.j = j class C(A, B): def __init__(self): super(C, self).__init__(self, 4) c = C() c will only have the i attribute set, not the j. What should I write to set both of attributes/only the j attribute? A: If you want to set only the j attribute, then only call B.__init__: class C(A, B): def __init__(self): B.__init__(self,4) If you want to manually call both A and B's __init__ methods, then of course you could do this: class C(A, B): def __init__(self): A.__init__(self,4) B.__init__(self,4) Using super is a bit tricky (in particular, see the section entitled "Argument passing, argh!"). If you still want to use super, here is one way you could do it: class D(object): def __init__(self, i): pass class A(D): def __init__(self, i): super(A,self).__init__(i) self.i = i class B(D): def __init__(self, j): super(B,self).__init__(j) self.j = j class C(A, B): def __init__(self): super(C, self).__init__(4) c = C() print(c.i,c.j) # (4, 4)
How can I call a particular base class method in Python?
Let's say, I have the following two classes: class A(object): def __init__(self, i): self.i = i class B(object): def __init__(self, j): self.j = j class C(A, B): def __init__(self): super(C, self).__init__(self, 4) c = C() c will only have the i attribute set, not the j. What should I write to set both of attributes/only the j attribute?
[ "If you want to set only the j attribute, then only call B.__init__:\nclass C(A, B):\n def __init__(self):\n B.__init__(self,4)\n\nIf you want to manually call both A and B's __init__ methods, then\nof course you could do this:\nclass C(A, B):\n def __init__(self):\n A.__init__(self,4)\n ...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0003651902_python.txt
Q: python - strange behavior question >>> class S(object): ... def __init__(self): ... self.x = 1 ... def x(self): ... return self.x ... >>> s = S() >>> s.x 1 >>> s.x() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not callable Why, in this example, is s.x a method, but also an integer? It seems to me that self.x = 1 should replace the def x(self): declaration of the attribute x during instantiation. Why is it that I can get and call, resulting in an integer and a method, respectively, the same attribute? My guess is that the variable look-up pattern in new-style classes is duck typed, so as to return the most relevant result to the caller. I would love to hear the whole story. A: Python doesn't use separate spaces for callable and non-callable objects: a name is a name is a name. s.x, by Python rules, must refer to exactly the same object, whether you're going to call it or not. Another way of putting it: assuming that _aux is a name not otherwise used, _aux = self.x _aux() and self.x() must have absolutely identical semantics in Python, the fact that in the former the intermediate value self.x is being bound to a name and called later notwithstanding. Having single, "unified" namespaces for callables and non-callables has a huge number of advantages -- it makes name-lookup rules (for each of bare and qualified names) enormously simpler, for example, by decoupling them totally from the purpose to which the name being looked up is going to be put (be it immediately after the lookup's result, or later still), and also from the type (callable or non-callable) of whatever object turns up to be first referenced according to the lookup rules. Especially considering how many different callable types Python has (functions, classes, instances of classes which define __call__, special types such as staticmethod and classmethod, ...!-), any other rule could only lead to total chaos. (Note also, for example, that even C++, a language which definitely is not afraid by complexity but which also lets class-instances be callable [[if the class overloads operator()]], uses a similar unified-namespace rule -- again, discriminating between callables and non-callables would be a totally unwarranted nightmare, were the rules any different in this regard!-). A: It looks like you're having a misunderstanding of the error you're seeing. When your s object is instantiated, its constructor replaces the method x by an integer, so in the s object, x is an integer, not a function. Trying to call it as a method results in an exception being thrown. Python is duck-typed in the sense that method calls are resolved at runtime - the compiler has no problem with s.x() because x might have been created as a method dynamically. However, when the interpreter actually calls x as a method, it notices x is an integer and can't be called, hence the TypeError. A: I'm not sure what you think is going on, but there's nothing that tricky happening. When you assign self.x = 1, the method x is no longer accessible. From that point forward, s.x is only an integer -- attempts to call it as a method result in an exception, as you saw. A: It seems that the x property is defined as a method in the class definition. However, actually instantiating an object overwrites that name with an integer - hence, the behavior observed. It's never actually two at once. So, this is basically some faulty code. A: This is what your code is doing: Create a class named S with 2 methods, __init__ and x Create an instance of S and name it s Call S.__init__ with s as parameter Set s.x with the value 1 Print s.x Print the result of calling s.x Now, if you look in 2.1.1 you will see that you have overrided the method x with an integer, which means that you cannot call that again withing s (but it stills in S class) If you have done that, and yet, need call x function, try it: >>> class S(object): ... def __init__(self): ... self.x = 1 ... def x(self): ... return self.x ... >>> s = S() >>> s.x 1 >>> S.x(s) 1 >>> I just did it so you understand why you are losing the x as method, do it in the right way and avoid to have instances variables with the same name as class methods
python - strange behavior question
>>> class S(object): ... def __init__(self): ... self.x = 1 ... def x(self): ... return self.x ... >>> s = S() >>> s.x 1 >>> s.x() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not callable Why, in this example, is s.x a method, but also an integer? It seems to me that self.x = 1 should replace the def x(self): declaration of the attribute x during instantiation. Why is it that I can get and call, resulting in an integer and a method, respectively, the same attribute? My guess is that the variable look-up pattern in new-style classes is duck typed, so as to return the most relevant result to the caller. I would love to hear the whole story.
[ "Python doesn't use separate spaces for callable and non-callable objects: a name is a name is a name. s.x, by Python rules, must refer to exactly the same object, whether you're going to call it or not. Another way of putting it: assuming that _aux is a name not otherwise used,\n_aux = self.x\n_aux()\n\nand\nsel...
[ 3, 2, 1, 0, 0 ]
[]
[]
[ "instantiation", "python", "scope" ]
stackoverflow_0003648890_instantiation_python_scope.txt
Q: How do I use an anonymous function within a class method in Python (closure)? class Test: def somemethod(self): def write(): print 'hello' write() x = Test() x.somemethod() write() is a function that will be used several times through somemethod(). somemethod() is the only function within the class that will require it's use so it seems silly to define it outside of somemethod(). Closure seems like the way to go. When I run that code, I get the following error: TypeError: somemethod() takes exactly 2 arguments (1 given) What am I doing wrong? Is self getting passed to write()? :/ A: I find it impossible to reproduce the problem you report: >>> class Test(object): ... def somemethod(self): ... def write(): ... print 'hello' ... write() ... >>> x = Test() >>> x.somemethod() hello >>> so I believe you must have done some transcription error, or something. What do you see when you run exactly the code I'm showing here? (Works identically in Python 2.4, 2.5, 2.6, 2.7, on all platforms). A: It also works for me: >>> class Test: ... def somemethod(self): ... def write(): ... print 'hello' ... write() ... >>> >>> x = Test() >>> x.somemethod() hello >>> I think you might be using tabs and spaces, or your identation is wrong
How do I use an anonymous function within a class method in Python (closure)?
class Test: def somemethod(self): def write(): print 'hello' write() x = Test() x.somemethod() write() is a function that will be used several times through somemethod(). somemethod() is the only function within the class that will require it's use so it seems silly to define it outside of somemethod(). Closure seems like the way to go. When I run that code, I get the following error: TypeError: somemethod() takes exactly 2 arguments (1 given) What am I doing wrong? Is self getting passed to write()? :/
[ "I find it impossible to reproduce the problem you report:\n>>> class Test(object):\n... def somemethod(self):\n... def write():\n... print 'hello'\n... write()\n... \n>>> x = Test()\n>>> x.somemethod()\nhello\n>>> \n\nso I believe you must have done some transcription error, or something. What do ...
[ 3, 0 ]
[]
[]
[ "anonymous_function", "closures", "python" ]
stackoverflow_0003649250_anonymous_function_closures_python.txt
Q: ping a server thru a specific port (fsockopen) in php function checkServer($domain, $port=80) { global $checkTimeout, $testServer; $status = 0; $starttime = microtime(true); $file = @fsockopen ($domain, $port, $errno, $errstr, $checkTimeout); $stoptime = microtime(true); if($file) { fclose($file); $status = ($stoptime - $starttime) * 1000; $status = floor($status); } else { $testfile = @fsockopen ($testServer, 80, $errno, $errstr, $checkTimeout); if($testfile) { fclose($testfile); $status = -1; } else { $status = -2; } } return $status; } the testserver is google.sk, and checkTimeout is 10 seconds. This actually works, but when i try to run it in a loop for about 50 times, and do other stuff (mysql queries and things like that), it's not slow, but it causes 100% load of my CPU until the script ends. It's a single apache proccess that drives my cpu crazy ... So i wanted to ask you if you have any ideas about it. maybe some tip how to do the same in python or bash or so will be appreciated. Thank you for the responses :) A: Use CURL this is an example how to conversion fsockopen to CURL PHP fsockopen to curl conversion Good luck
ping a server thru a specific port (fsockopen) in php
function checkServer($domain, $port=80) { global $checkTimeout, $testServer; $status = 0; $starttime = microtime(true); $file = @fsockopen ($domain, $port, $errno, $errstr, $checkTimeout); $stoptime = microtime(true); if($file) { fclose($file); $status = ($stoptime - $starttime) * 1000; $status = floor($status); } else { $testfile = @fsockopen ($testServer, 80, $errno, $errstr, $checkTimeout); if($testfile) { fclose($testfile); $status = -1; } else { $status = -2; } } return $status; } the testserver is google.sk, and checkTimeout is 10 seconds. This actually works, but when i try to run it in a loop for about 50 times, and do other stuff (mysql queries and things like that), it's not slow, but it causes 100% load of my CPU until the script ends. It's a single apache proccess that drives my cpu crazy ... So i wanted to ask you if you have any ideas about it. maybe some tip how to do the same in python or bash or so will be appreciated. Thank you for the responses :)
[ "Use CURL\nthis is an example how to conversion fsockopen to CURL \nPHP fsockopen to curl conversion\nGood luck\n" ]
[ 0 ]
[]
[]
[ "bash", "fsockopen", "php", "python", "sockets" ]
stackoverflow_0003652111_bash_fsockopen_php_python_sockets.txt
Q: Sortable tables in Django I read some of the other posts about this and some recommendations involved javascript and using other libraries. I did something quick by hand, but I'm new to Django and Python for that matter so I'm curious if this isn't a good way to do it. HTML <table> <tr> <td><a href="?sort=to">To</a></td> <td><a href="?sort=date">Date</a></td> <td><a href="?sort=type">Type</a></td> </tr> {% for record in records %} <tr><td>{{record.to}}</td><td>{{record.date}}</td><td>{{record.type}}</td></tr> {% endfor %} </table> View headers = {'to':'asc', 'date':'asc', 'type':'asc',} def table_view(request): sort = request.GET.get('sort') if sort is not None: if headers[sort] == "des": records = Record.objects.all().order_by(sort).reverse() headers[sort] = "asc" else: records = Record.objects.all().order_by(sort) headers[sort] = "des" else: records = Record.objects.all() return render_to_response("table.html",{'user':request.user,'profile':request.user.get_profile(),'records':records}) A: Looks good to me. I'd suggest one minor refactoring in the view code: headers = {'to':'asc', 'date':'asc', 'type':'asc',} def table_view(request): sort = request.GET.get('sort') records = Record.objects.all() if sort is not None: records = records.order_by(sort) if headers[sort] == "des": records = records.reverse() headers[sort] = "asc" else: headers[sort] = "des" return render_to_response(...) A: My first port of call for sortable tables is usually sorttable.js ( http://www.kryogenix.org/code/browser/sorttable/ ) or sortable-table ( http://yoast.com/articles/sortable-table/ )
Sortable tables in Django
I read some of the other posts about this and some recommendations involved javascript and using other libraries. I did something quick by hand, but I'm new to Django and Python for that matter so I'm curious if this isn't a good way to do it. HTML <table> <tr> <td><a href="?sort=to">To</a></td> <td><a href="?sort=date">Date</a></td> <td><a href="?sort=type">Type</a></td> </tr> {% for record in records %} <tr><td>{{record.to}}</td><td>{{record.date}}</td><td>{{record.type}}</td></tr> {% endfor %} </table> View headers = {'to':'asc', 'date':'asc', 'type':'asc',} def table_view(request): sort = request.GET.get('sort') if sort is not None: if headers[sort] == "des": records = Record.objects.all().order_by(sort).reverse() headers[sort] = "asc" else: records = Record.objects.all().order_by(sort) headers[sort] = "des" else: records = Record.objects.all() return render_to_response("table.html",{'user':request.user,'profile':request.user.get_profile(),'records':records})
[ "Looks good to me. I'd suggest one minor refactoring in the view code:\nheaders = {'to':'asc',\n 'date':'asc',\n 'type':'asc',}\n\ndef table_view(request):\n sort = request.GET.get('sort')\n records = Record.objects.all()\n\n if sort is not None:\n records = records.order_by(sort)\n\...
[ 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003648512_django_python.txt
Q: Open Source Queue that works with Java, PHP and Python I'm currently in the market for a new queue system for jobs we have in our system. I've tried beanstalk but it's been unable to keep up with the load. I'm looking for a simple system to get up and running that I can put pieces of data in from producers and have consumers in Java, PHP and Python pull data off and process it. Ideally I'd like to see features such as: Job verification -> jobs are removed from the queue only when I've marked them as finished (in case of failures I don't have to put the jobs back in) Priorities -> ability to prioritize jobs Multiple channels -> ability to have one queue that can service several apps with separate data streams(or databases) Disk Persistence -> ability to have jobs written to disk in case of failures anyone have any good suggestions? Currently looking at RabbitMQ A: How about Apache ActiveMQ. Accessible from Java, PHP, Python. Supports all the features you requested. A: RabbitMQ is good messaging system and there are bindings for Java, PHP, Python and many other languages. A: The Berkeley database can be used to build a priority queue with bindings to most relevant languages. The HA (High Availability) configuration can make it distributed as well. I believe the Sun Grid Engine, for instance, uses just that to synchronize jobs.
Open Source Queue that works with Java, PHP and Python
I'm currently in the market for a new queue system for jobs we have in our system. I've tried beanstalk but it's been unable to keep up with the load. I'm looking for a simple system to get up and running that I can put pieces of data in from producers and have consumers in Java, PHP and Python pull data off and process it. Ideally I'd like to see features such as: Job verification -> jobs are removed from the queue only when I've marked them as finished (in case of failures I don't have to put the jobs back in) Priorities -> ability to prioritize jobs Multiple channels -> ability to have one queue that can service several apps with separate data streams(or databases) Disk Persistence -> ability to have jobs written to disk in case of failures anyone have any good suggestions? Currently looking at RabbitMQ
[ "How about Apache ActiveMQ.\nAccessible from Java, PHP, Python.\nSupports all the features you requested.\n", "RabbitMQ is good messaging system and there are bindings for Java, PHP, Python and many other languages.\n", "The Berkeley database can be used to build a priority queue with bindings to most relevant ...
[ 3, 3, 0 ]
[]
[]
[ "java", "message_queue", "php", "python", "queue" ]
stackoverflow_0003652765_java_message_queue_php_python_queue.txt
Q: Why to copy a dictonairy from WSGI environment? In the following example from wsgi.org is cur_named copied: def __call__(self, environ, start_response): script_name = environ.get('SCRIPT_NAME', '') path_info = environ.get('PATH_INFO', '') for regex, application in self.patterns: match = regex.match(path_info) if not match: continue extra_path_info = path_info[match.end():] if extra_path_info and not extra_path_info.startswith('/'): # Not a very good match continue pos_args = match.groups() named_args = match.groupdict() cur_pos, cur_named = environ.get('wsgiorg.routing_args', ((), {})) new_pos = list(cur_pos) + list(pos_args) new_named = cur_named.copy() # Why copy()? new_named.update(named_args) environ['wsgiorg.routing_args'] = (new_pos, new_named) environ['SCRIPT_NAME'] = script_name + path_info[:match.end()] environ['PATH_INFO'] = extra_path_info return application(environ, start_response) return self.not_found(environ, start_response) Why not to call ur_named.update(named_args) directly? A: Do you know where cur_named dict came from? Just imaging something like the following: SOME_CONFIG = { 'some_key': ((..., ...), {...}), ... } environ['wsgiorg.routing_args'] = SOME_CONFIG['some_key'] Now when you update new_named in-place you are actually updating inner dictionary inside SOME_CONFIG which will bring your data to other requests. The safe way is to copy dictionary unless you are sure it's not needed.
Why to copy a dictonairy from WSGI environment?
In the following example from wsgi.org is cur_named copied: def __call__(self, environ, start_response): script_name = environ.get('SCRIPT_NAME', '') path_info = environ.get('PATH_INFO', '') for regex, application in self.patterns: match = regex.match(path_info) if not match: continue extra_path_info = path_info[match.end():] if extra_path_info and not extra_path_info.startswith('/'): # Not a very good match continue pos_args = match.groups() named_args = match.groupdict() cur_pos, cur_named = environ.get('wsgiorg.routing_args', ((), {})) new_pos = list(cur_pos) + list(pos_args) new_named = cur_named.copy() # Why copy()? new_named.update(named_args) environ['wsgiorg.routing_args'] = (new_pos, new_named) environ['SCRIPT_NAME'] = script_name + path_info[:match.end()] environ['PATH_INFO'] = extra_path_info return application(environ, start_response) return self.not_found(environ, start_response) Why not to call ur_named.update(named_args) directly?
[ "Do you know where cur_named dict came from? Just imaging something like the following:\nSOME_CONFIG = {\n 'some_key': ((..., ...), {...}),\n ...\n}\n\nenviron['wsgiorg.routing_args'] = SOME_CONFIG['some_key']\n\nNow when you update new_named in-place you are actually updating inner dictionary inside SOME_CON...
[ 1 ]
[]
[]
[ "dictionary", "python", "wsgi" ]
stackoverflow_0003651339_dictionary_python_wsgi.txt
Q: difficulty in installing SciPy and Numpy in Ubuntu(9.04)? HI folks. I have difficulty in installing these items in Ubuntu.......plz help me as soon as possible.iam experiencing errors such as no module name found......sometimes certain libraries are not found.......plz folks can all of u state the basic libraries required for installing these items and where to find them A: Let's start at the beginning - do you have Python installed and running on Ubuntu? If not, you won't have NumPy or SciPy, either. Did you download NumPy and SciPy and unpack them to your hard drive? Do you see directories that contain setup.py somewhere? Usually it's python setup.py install in a command shell to install modules like NumPy and SciPy. See if that works for you. A: There are Numpy and SciPy packages already in the Ubuntu repositories (SciPy is in the universe repo, you will have to enable this). No need to compile anything. You didn't state your Ubuntu version, so the links show the versions for Ubuntu Lucid (10.04LTS). ps: Sorry, only one link allowed. But you see the pattern. ;-) A: If you are looking for a simple and convenient way to install numpy, scipy, and many other tools for scientific programming, you should give a look at Python(x,y).
difficulty in installing SciPy and Numpy in Ubuntu(9.04)?
HI folks. I have difficulty in installing these items in Ubuntu.......plz help me as soon as possible.iam experiencing errors such as no module name found......sometimes certain libraries are not found.......plz folks can all of u state the basic libraries required for installing these items and where to find them
[ "Let's start at the beginning - do you have Python installed and running on Ubuntu? If not, you won't have NumPy or SciPy, either.\nDid you download NumPy and SciPy and unpack them to your hard drive? Do you see directories that contain setup.py somewhere?\nUsually it's python setup.py install in a command shell ...
[ 2, 1, 0 ]
[]
[]
[ "numpy", "python", "scipy", "ubuntu" ]
stackoverflow_0003652866_numpy_python_scipy_ubuntu.txt
Q: Simple Django form / model save question I want to set the BooleanField inuse to True when I save the ModelForm (I'm using a form outside of the admin area) and I'm unsure how to do it. Models: class Location(models.Model): place = models.CharField(max_length=100) inuse = models.BooleanField() class Booking(models.Model): name = models.CharField(max_length=100, verbose_name="Your name*:") place = models.ManyToManyField(Location, blank=True, null=True) Forms: class BookingForm(ModelForm): class Meta: model = Booking def save(self, commit=True): booking = super(BookingForm, self).save(commit=False) if commit: booking.save() self.save_m2m() for location in booking.place.all(): location.inuse = True print location #nothing prints location.save() View: def booking(request): form = BookingForm() if request.method == 'POST': form = BookingForm(request.POST) if form.is_valid(): form.save() else: form = form return render_to_response('bookingform.html', { 'form': form, }) Updated to latest (see Manoj Govindan's answer). It is still not updating inuse to True on submit / save. A: class BookingForm(ModelForm): class Meta: model = Booking def save(self, commit=True): booking = super(BookingForm, self).save(commit=False) booking.inuse = True if commit: booking.save() A: Here is my stab at it: class BookingForm(ModelForm): class Meta: model = Booking def save(self, commit=True): booking = super(BookingForm, self).save(commit=False) if commit: booking.save() self.save_m2m() for location in booking.place.all(): location.inuse = True location.save() Update Entire code I've used: # models.py class Location(models.Model): place = models.CharField(max_length=100) inuse = models.BooleanField() class Booking(models.Model): name = models.CharField(max_length=100, verbose_name="Your name*:") place = models.ManyToManyField(Location, blank=True, null=True) # forms.py class BookingForm(ModelForm): class Meta: model = Booking def save(self, commit=True): booking = super(BookingForm, self).save(commit=False) if commit: booking.save() self.save_m2m() for location in booking.place.all(): location.inuse = True location.save() In [1]: from test_app.forms import BookingForm In [2]: from test_app.models import Location # I had already saved some `Location` instances. In [3]: data = dict(name = 'MyCity', place = [p.id for p in Location.objects.all()]) In [4]: f = BookingForm(data) In [5]: f.save() In [6]: for each in Location.objects.all(): ...: print each.place, each.inuse ...: PlaceA True PlaceB True PlaceC True
Simple Django form / model save question
I want to set the BooleanField inuse to True when I save the ModelForm (I'm using a form outside of the admin area) and I'm unsure how to do it. Models: class Location(models.Model): place = models.CharField(max_length=100) inuse = models.BooleanField() class Booking(models.Model): name = models.CharField(max_length=100, verbose_name="Your name*:") place = models.ManyToManyField(Location, blank=True, null=True) Forms: class BookingForm(ModelForm): class Meta: model = Booking def save(self, commit=True): booking = super(BookingForm, self).save(commit=False) if commit: booking.save() self.save_m2m() for location in booking.place.all(): location.inuse = True print location #nothing prints location.save() View: def booking(request): form = BookingForm() if request.method == 'POST': form = BookingForm(request.POST) if form.is_valid(): form.save() else: form = form return render_to_response('bookingform.html', { 'form': form, }) Updated to latest (see Manoj Govindan's answer). It is still not updating inuse to True on submit / save.
[ "class BookingForm(ModelForm):\n\n class Meta:\n model = Booking\n\n def save(self, commit=True):\n booking = super(BookingForm, self).save(commit=False)\n booking.inuse = True\n if commit:\n booking.save()\n\n", "Here is my stab at it:\nclass BookingForm(ModelForm):\n...
[ 3, 2 ]
[]
[]
[ "django", "django_forms", "django_models", "python" ]
stackoverflow_0003652585_django_django_forms_django_models_python.txt
Q: Is code interpreted at every call in Web2Py? If so, What is the advantage ? (sure it will avoid restarting webserver). But isn't it a perfomance bottleneck? For production, is it possible to make web2py run directly from bytecode skipping interpreting stage (Caching) (except for the first request) ? A: In web2py, by default, all code in models, views and controllers (not web2py code, not code in modules imported by your models, views, controllers) is interpreted at every request. This allows to use a third party web server (for example apache) and still be able to see changes in your code reflected immediately without restart. PHP works in the same way. The performance penalty is negligible because the time to parse your code is less than the time to execute your code. Anyway, in the admin interface there is a "compile" button that will bytecode compile your code and collapse the view hierarchy (extended and included views) into a single file per action and remove the performance penalty. It also allows you to distribute your code bytecode compiled without giving away the source. The license allows it. A: I don't know web2py particularly, but it runs via WSGI like most other Python frameworks. This means that code is only interpreted when the process starts, and is otherwise kept in memory. Processes are dynamically started and killed by the web server itself, but usually last for multiple requests. In any case, the Python interpreter usually creates a byte-code file, .pyc, when code is first read. This works in a webserver environment just as it does anywhere else. Finally, however, it is generally considered that code parsing is not particularly a bottleneck - the conversion to bytecode is pretty quick. In a web application, your bottleneck is almost certainly elsewhere (probably in the connection to the database).
Is code interpreted at every call in Web2Py?
If so, What is the advantage ? (sure it will avoid restarting webserver). But isn't it a perfomance bottleneck? For production, is it possible to make web2py run directly from bytecode skipping interpreting stage (Caching) (except for the first request) ?
[ "In web2py, by default, all code in models, views and controllers (not web2py code, not code in modules imported by your models, views, controllers) is interpreted at every request. This allows to use a third party web server (for example apache) and still be able to see changes in your code reflected immediately w...
[ 6, 2 ]
[]
[]
[ "bytecode", "caching", "performance", "python", "web2py" ]
stackoverflow_0003649607_bytecode_caching_performance_python_web2py.txt
Q: What's the difference between "browser posting" and "program posting"? I've asked one question about this a month ago, it's here: "post" method to communicate directly with a server. And I still didn't get the reason why sometimes I get 404 error and sometimes everything works fine, I mean I've tried those codes with several different wordpress blogs. Using firefox or IE, you can post the comment without any problem whatever wordpress blog it is, but using python and "post" method directly communicating with a server I got 404 with several blogs. And I've tried to spoof the headers, adding cookies in the code, but the result remains the same. It's bugging me for quite a while... Anybody knows the reason? Or what code should I add to make the program works just like a browser such as firefox or IE etc ? Hopefully you guys would help me out! A: You should use somthing like mechanize. A: The blog may have some spam protection against this kind of posting. ( Using programmatic post without accessing/reading the page can be easily detected using javascript protection ). But if it's the case, I'm surprised you receive a 404... Anyway, if you wanna simulate a real browser, the best way is to use a real browser remote controlled by python. Check out WebDriver (http://seleniumhq.org/docs/09_webdriver.html) It has a python implementation and can run HtmlUnit, chrome, IE and Firefox browsers.
What's the difference between "browser posting" and "program posting"?
I've asked one question about this a month ago, it's here: "post" method to communicate directly with a server. And I still didn't get the reason why sometimes I get 404 error and sometimes everything works fine, I mean I've tried those codes with several different wordpress blogs. Using firefox or IE, you can post the comment without any problem whatever wordpress blog it is, but using python and "post" method directly communicating with a server I got 404 with several blogs. And I've tried to spoof the headers, adding cookies in the code, but the result remains the same. It's bugging me for quite a while... Anybody knows the reason? Or what code should I add to make the program works just like a browser such as firefox or IE etc ? Hopefully you guys would help me out!
[ "You should use somthing like mechanize.\n", "The blog may have some spam protection against this kind of posting. ( Using programmatic post without accessing/reading the page can be easily detected using javascript protection ).\nBut if it's the case, I'm surprised you receive a 404...\nAnyway, if you wanna simu...
[ 0, 0 ]
[]
[]
[ "comments", "post", "python", "wordpress" ]
stackoverflow_0003653086_comments_post_python_wordpress.txt
Q: Subdomains vs folders/directories I'm currently building a web application and I would like my users to have their own URLs to identify them. I could either do this using subdomains or using folders and am wondering what are the advantages and disadvantages of either one. I really like the folder solution because my URL mapping would be fairly easy. I have read about auto-generating subdomains and one solution was to create virtual hosts and then restart my nginx. It's a solution but I would prefer not to have to restart my web server everytime a new account is created. If there are any other ways on how to do automated subdomain creation, that would be great as well! Thanks! A: I think directories are the way to go. I believe it would be easier to adapt Django to the directories way much easier than to subdomains. And as one user commented you can avoid restarting your server each time. I prefer to keep subdomains reserved for system use. Users should get their own directories instead. This is not a rule, just my preference. A: Use something like mod_wsgi instead of cgi scripts, they allow you to use arbitrary URL configs (example: Django, web.py, Zope ...)
Subdomains vs folders/directories
I'm currently building a web application and I would like my users to have their own URLs to identify them. I could either do this using subdomains or using folders and am wondering what are the advantages and disadvantages of either one. I really like the folder solution because my URL mapping would be fairly easy. I have read about auto-generating subdomains and one solution was to create virtual hosts and then restart my nginx. It's a solution but I would prefer not to have to restart my web server everytime a new account is created. If there are any other ways on how to do automated subdomain creation, that would be great as well! Thanks!
[ "I think directories are the way to go. I believe it would be easier to adapt Django to the directories way much easier than to subdomains. And as one user commented you can avoid restarting your server each time.\nI prefer to keep subdomains reserved for system use. Users should get their own directories instead. ...
[ 1, 0 ]
[]
[]
[ "django", "nginx", "python", "subdomain" ]
stackoverflow_0003653239_django_nginx_python_subdomain.txt
Q: python failed to call flash loaded html page I tried to render html page which contains flash content. But it not responding. Loads endless. Text and image contents are OK. Here is my code. self.response.out.write(template.render('ieerror.html', dict())) html file contains: <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>flash content</title> <script src="scripts/AC_RunActiveContent.js" type="text/javascript"></script> </head> <body style=" text-align:center"> <script type="text/javascript"> AC_FL_RunContent( 'codebase','http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0','width','740','height','473','title','image navigation','src','image_navigation','quality','high','pluginspage','http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash','movie','image_navigation' ); //end AC code </script><noscript><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0" width="740" height="473" title="image navigation"> <param name="movie" value="image_navigation.swf" /> <param name="quality" value="high" /> <embed src="image_navigation.swf" quality="high" pluginspage="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="740" height="473"></embed> </object></noscript> </body> A: Use http://code.google.com/p/swfobject/ instead like from: <script type="text/javascript"> var flashvars = false; var params = { menu: "false", flashvars: "name1=hello&name2=world&name3=foobar" }; var attributes = { id: "myDynamicContent", name: "myDynamicContent" }; swfobject.embedSWF("myContent.swf", "myContent", "300", "120", "9.0.0","expressInstall.swf", flashvars, params, attributes); </script> and yes, except this code self.response.out.write(template.render('ieerror.html', dict())) we NEED all other runnable sample from your Python code. Thanks!
python failed to call flash loaded html page
I tried to render html page which contains flash content. But it not responding. Loads endless. Text and image contents are OK. Here is my code. self.response.out.write(template.render('ieerror.html', dict())) html file contains: <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>flash content</title> <script src="scripts/AC_RunActiveContent.js" type="text/javascript"></script> </head> <body style=" text-align:center"> <script type="text/javascript"> AC_FL_RunContent( 'codebase','http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0','width','740','height','473','title','image navigation','src','image_navigation','quality','high','pluginspage','http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash','movie','image_navigation' ); //end AC code </script><noscript><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0" width="740" height="473" title="image navigation"> <param name="movie" value="image_navigation.swf" /> <param name="quality" value="high" /> <embed src="image_navigation.swf" quality="high" pluginspage="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="740" height="473"></embed> </object></noscript> </body>
[ "Use http://code.google.com/p/swfobject/ instead\nlike from:\n<script type=\"text/javascript\">\n\nvar flashvars = false;\nvar params = {\n menu: \"false\",\n flashvars: \"name1=hello&name2=world&name3=foobar\"\n};\nvar attributes = {\n id: \"myDynamicContent\",\n name: \"myDynamicContent\"\n};\n\nswfobject.emb...
[ 0 ]
[]
[]
[ "flash", "html", "javascript", "python" ]
stackoverflow_0003651979_flash_html_javascript_python.txt
Q: Cleaning data which is of type URLField I have a simple URLField in my model link = models.URLField(verify_exists = False, max_length = 225) I would like to strip the leading and trailing spaces from the field. I don't think I can do this in "clean_fieldname" or in the "clean" method. Do I need to sub-class the "URLField" and remove the spaces in to_python method? Is there a better way to do this without any sub-classing? Edited This is my form class StoryForm(forms.ModelForm): title = forms.CharField(max_length=225, error_messages={'required' : 'Enter a title for the story'}) link = forms.URLField(max_length=225, error_messages={'required' : 'Enter a link to the story', 'invalid' : 'Enter a valid link like www.ted.com'}) class Meta: model = models.Story fields = ('title', 'link') def clean_link(self): link = self.cleaned_data['link'] return link.strip() and my model class Story(models.Model): title = models.CharField(max_length = 225) link = models.URLField(verify_exists = False, max_length = 225) A: I did a quick experiment and found out that you can indeed use a clean_ method to remove leading/trailing spaces. Something like this: # models.py class UrlModel(models.Model): link = models.URLField(verify_exists = False, max_length = 225) def __unicode__(self): return self.link # forms.py class UrlForm(ModelForm): class Meta: model = UrlModel def clean_link(self): link = self.cleaned_data['link'] return link.strip() # shell In [1]: from test_app.forms import UrlForm In [2]: f = UrlForm(data = dict(link = ' http://google.com ')) In [3]: f.is_valid() Out[3]: True In [4]: f.save() Out[4]: <UrlModel: http://google.com> Update I get an error saying "Enter a valid link like www.ted.com". I edited my question and included the model and form in question. I verified that your form class does give the error. After making a small change I was able to make it work. All I did was remove the custom title and link fields. We are working with a model form here and the underlying model already has these fields. I believe the redefinition led to a validation error being raised before the custom clean method was invoked. class StoryForm(forms.ModelForm): class Meta: model = Story fields = ('title', 'link') def clean_link(self): link = self.cleaned_data['link'] return link.strip() Here is some sample output from the shell: In [1]: from test_app.forms import StoryForm In [2]: data = dict(title="Google story", link = " http://google.com ") In [3]: f = StoryForm(data) In [4]: f.is_valid() Out[4]: True In [5]: f.save() Out[5]: <Story: Google story http://google.com>
Cleaning data which is of type URLField
I have a simple URLField in my model link = models.URLField(verify_exists = False, max_length = 225) I would like to strip the leading and trailing spaces from the field. I don't think I can do this in "clean_fieldname" or in the "clean" method. Do I need to sub-class the "URLField" and remove the spaces in to_python method? Is there a better way to do this without any sub-classing? Edited This is my form class StoryForm(forms.ModelForm): title = forms.CharField(max_length=225, error_messages={'required' : 'Enter a title for the story'}) link = forms.URLField(max_length=225, error_messages={'required' : 'Enter a link to the story', 'invalid' : 'Enter a valid link like www.ted.com'}) class Meta: model = models.Story fields = ('title', 'link') def clean_link(self): link = self.cleaned_data['link'] return link.strip() and my model class Story(models.Model): title = models.CharField(max_length = 225) link = models.URLField(verify_exists = False, max_length = 225)
[ "I did a quick experiment and found out that you can indeed use a clean_ method to remove leading/trailing spaces. Something like this:\n# models.py\nclass UrlModel(models.Model):\n link = models.URLField(verify_exists = False, max_length = 225)\n\n def __unicode__(self):\n return self.link\n\n# forms....
[ 0 ]
[]
[]
[ "django", "django_forms", "django_models", "python" ]
stackoverflow_0003653423_django_django_forms_django_models_python.txt
Q: Python: int to binary stream element? If you have a int and you wish to convert it to a single char string you can use the function chr() Is there a way to convert an int to a single char binary stream? e.g: >>> something(97) b'a' What is the something? A: You can do: bytes(chr(97)) A: In Python 3.x: >>> bytes([97]) b'a'
Python: int to binary stream element?
If you have a int and you wish to convert it to a single char string you can use the function chr() Is there a way to convert an int to a single char binary stream? e.g: >>> something(97) b'a' What is the something?
[ "You can do:\nbytes(chr(97))\n\n", "In Python 3.x:\n>>> bytes([97])\nb'a'\n\n" ]
[ 0, 0 ]
[]
[]
[ "binary", "python" ]
stackoverflow_0003653664_binary_python.txt
Q: criticism this python code (crawler with threadpool) how good this python code ? need criticism) there is a error in this code, some times script do print "ALL WAIT - CAN FINISH!" and freeze (no more actions are happend..) but i can't find reason why this happend? site crawler with threadpool: import sys from urllib import urlopen from BeautifulSoup import BeautifulSoup, SoupStrainer import re from Queue import Queue, Empty from threading import Thread W_WAIT = 1 W_WORK = 0 class Worker(Thread): """Thread executing tasks from a given tasks queue""" def __init__(self, pool, tasks): Thread.__init__(self) self.tasks = tasks self.daemon = True self.start() self.pool = pool self.state = None def is_wait(self): return self.state == W_WAIT def run(self): while True: #if all workers wait - time to exsit print "CHECK WAIT: !!! ",self.pool.is_all_wait() if self.pool.is_all_wait(): print "ALL WAIT - CAN FINISH!" return try: func, args, kargs = self.tasks.get(timeout=3) except Empty: print "task wait timeout" continue self.state = W_WORK print "START !!! in thread %s" % str(self) #print args try: func(*args, **kargs) except Exception, e: print e print "!!! STOP in thread %s", str(self) self.tasks.task_done() self.state = W_WAIT #threads can fast empty it! #if self.tasks.qsize() == 0: # print "QUIT!!!!!!" # break class ThreadPool: """Pool of threads consuming tasks from a queue""" def __init__(self, num_threads): #self.tasks = Queue(num_threads) self.tasks = Queue() self.workers = [] for _ in range(num_threads): self.workers.append(Worker(self,self.tasks)) def add_task(self, func, *args, **kargs): """Add a task to the queue""" self.tasks.put((func, args, kargs)) def wait_completion(self): """Wait for completion of all the tasks in the queue""" self.tasks.join() def is_all_wait(self): for w in self.workers: if not w.is_wait(): return False return True visited = set() queue = Queue() external_links_set = set() internal_links_set = set() external_links = 0 def process(pool,host,url): try: content = urlopen(url).read() except UnicodeDecodeError: return for link in BeautifulSoup(content, parseOnlyThese=SoupStrainer('a')): try: href = link['href'] except KeyError: continue if not href.startswith('http://'): href = 'http://%s%s' % (host, href) if not href.startswith('http://%s%s' % (host, '/')): continue internal_links_set.add(href) if href not in visited: visited.add(href) pool.add_task(process,pool,host,href) else: pass def start(host,charset): pool = ThreadPool(20) pool.add_task(process,pool,host,'http://%s/' % (host)) pool.wait_completion() start('evgenm.com','utf8') Thanx for help! i make new implementation: What you can say about this code#2 ? ==================================TRY #2======================================= import sys from urllib import urlopen from BeautifulSoup import BeautifulSoup, SoupStrainer import re from Queue import Queue, Empty from threading import Thread W_STOP = 1 class Worker(Thread): """Thread executing tasks from a given tasks queue""" def __init__(self, pool, tasks): Thread.__init__(self) self.tasks = tasks self.daemon = True self.pool = pool self.state = None self.start() def stop(self): self.state = W_STOP def run(self): while True: if self.state == W_STOP: print "\ncalled stop" break try: func, args, kargs = self.tasks.get(timeout=3) except Empty: continue print "\n***START*** %s" % str(self) try: func(*args, **kargs) except Exception, e: print e print "\n***STOP*** %s", str(self) self.tasks.task_done() class ThreadPool: """Pool of threads consuming tasks from a queue""" def __init__(self, num_threads): #self.tasks = Queue(num_threads) self.tasks = Queue() self.workers = [] for _ in range(num_threads): self.workers.append(Worker(self,self.tasks)) def add_task(self, func, *args, **kargs): """Add a task to the queue""" self.tasks.put((func, args, kargs)) def wait_completion(self): """Wait for completion of all the tasks in the queue""" self.tasks.join() def stop_threads(self): for w in self.workers: w.stop() def wait_stop(self): self.wait_completion() self.stop_threads() visited = set() queue = Queue() external_links_set = set() internal_links_set = set() external_links = 0 def process(pool,host,url): try: content = urlopen(url).read() except UnicodeDecodeError: return for link in BeautifulSoup(content, parseOnlyThese=SoupStrainer('a')): try: href = link['href'] except KeyError: continue if not href.startswith('http://'): href = 'http://%s%s' % (host, href) if not href.startswith('http://%s%s' % (host, '/')): continue internal_links_set.add(href) if href not in visited: visited.add(href) pool.add_task(process,pool,host,href) else: pass def start(host,charset): pool = ThreadPool(20) pool.add_task(process,pool,host,'http://%s/' % (host)) pool.wait_stop() start('evgenm.com','utf8') A: You are sharing state between threads (i.e., in is_all_wait) without synchronization. Plus, the fact that all threads are "waiting" is not a reliable indicator that the queue is empty (for instance, they could all be in the process of getting a task). I suspect that, occasionally, threads are exiting before the queue is truly empty. If this happens often enough, you will be left with tasks in the queue but no threads to run them. So queue.join() will wait forever. My recomendation is: Get rid of is_all_wait -- it's not a reliable indicator Get rid of the task state -- it's not really necessary Rely on queue.join to let you know when everything is processed If you need to kill the threads (for example, this is part of a larger, long-running program), then do so after the queue.join(). A: I have basic python knowledge but threading in python isn't useless? I've seen tons of articles criticizing the global lock interpreter for this.
criticism this python code (crawler with threadpool)
how good this python code ? need criticism) there is a error in this code, some times script do print "ALL WAIT - CAN FINISH!" and freeze (no more actions are happend..) but i can't find reason why this happend? site crawler with threadpool: import sys from urllib import urlopen from BeautifulSoup import BeautifulSoup, SoupStrainer import re from Queue import Queue, Empty from threading import Thread W_WAIT = 1 W_WORK = 0 class Worker(Thread): """Thread executing tasks from a given tasks queue""" def __init__(self, pool, tasks): Thread.__init__(self) self.tasks = tasks self.daemon = True self.start() self.pool = pool self.state = None def is_wait(self): return self.state == W_WAIT def run(self): while True: #if all workers wait - time to exsit print "CHECK WAIT: !!! ",self.pool.is_all_wait() if self.pool.is_all_wait(): print "ALL WAIT - CAN FINISH!" return try: func, args, kargs = self.tasks.get(timeout=3) except Empty: print "task wait timeout" continue self.state = W_WORK print "START !!! in thread %s" % str(self) #print args try: func(*args, **kargs) except Exception, e: print e print "!!! STOP in thread %s", str(self) self.tasks.task_done() self.state = W_WAIT #threads can fast empty it! #if self.tasks.qsize() == 0: # print "QUIT!!!!!!" # break class ThreadPool: """Pool of threads consuming tasks from a queue""" def __init__(self, num_threads): #self.tasks = Queue(num_threads) self.tasks = Queue() self.workers = [] for _ in range(num_threads): self.workers.append(Worker(self,self.tasks)) def add_task(self, func, *args, **kargs): """Add a task to the queue""" self.tasks.put((func, args, kargs)) def wait_completion(self): """Wait for completion of all the tasks in the queue""" self.tasks.join() def is_all_wait(self): for w in self.workers: if not w.is_wait(): return False return True visited = set() queue = Queue() external_links_set = set() internal_links_set = set() external_links = 0 def process(pool,host,url): try: content = urlopen(url).read() except UnicodeDecodeError: return for link in BeautifulSoup(content, parseOnlyThese=SoupStrainer('a')): try: href = link['href'] except KeyError: continue if not href.startswith('http://'): href = 'http://%s%s' % (host, href) if not href.startswith('http://%s%s' % (host, '/')): continue internal_links_set.add(href) if href not in visited: visited.add(href) pool.add_task(process,pool,host,href) else: pass def start(host,charset): pool = ThreadPool(20) pool.add_task(process,pool,host,'http://%s/' % (host)) pool.wait_completion() start('evgenm.com','utf8') Thanx for help! i make new implementation: What you can say about this code#2 ? ==================================TRY #2======================================= import sys from urllib import urlopen from BeautifulSoup import BeautifulSoup, SoupStrainer import re from Queue import Queue, Empty from threading import Thread W_STOP = 1 class Worker(Thread): """Thread executing tasks from a given tasks queue""" def __init__(self, pool, tasks): Thread.__init__(self) self.tasks = tasks self.daemon = True self.pool = pool self.state = None self.start() def stop(self): self.state = W_STOP def run(self): while True: if self.state == W_STOP: print "\ncalled stop" break try: func, args, kargs = self.tasks.get(timeout=3) except Empty: continue print "\n***START*** %s" % str(self) try: func(*args, **kargs) except Exception, e: print e print "\n***STOP*** %s", str(self) self.tasks.task_done() class ThreadPool: """Pool of threads consuming tasks from a queue""" def __init__(self, num_threads): #self.tasks = Queue(num_threads) self.tasks = Queue() self.workers = [] for _ in range(num_threads): self.workers.append(Worker(self,self.tasks)) def add_task(self, func, *args, **kargs): """Add a task to the queue""" self.tasks.put((func, args, kargs)) def wait_completion(self): """Wait for completion of all the tasks in the queue""" self.tasks.join() def stop_threads(self): for w in self.workers: w.stop() def wait_stop(self): self.wait_completion() self.stop_threads() visited = set() queue = Queue() external_links_set = set() internal_links_set = set() external_links = 0 def process(pool,host,url): try: content = urlopen(url).read() except UnicodeDecodeError: return for link in BeautifulSoup(content, parseOnlyThese=SoupStrainer('a')): try: href = link['href'] except KeyError: continue if not href.startswith('http://'): href = 'http://%s%s' % (host, href) if not href.startswith('http://%s%s' % (host, '/')): continue internal_links_set.add(href) if href not in visited: visited.add(href) pool.add_task(process,pool,host,href) else: pass def start(host,charset): pool = ThreadPool(20) pool.add_task(process,pool,host,'http://%s/' % (host)) pool.wait_stop() start('evgenm.com','utf8')
[ "You are sharing state between threads (i.e., in is_all_wait) without synchronization. Plus, the fact that all threads are \"waiting\" is not a reliable indicator that the queue is empty (for instance, they could all be in the process of getting a task). I suspect that, occasionally, threads are exiting before th...
[ 1, 0 ]
[]
[]
[ "multithreading", "pool", "python", "web_crawler" ]
stackoverflow_0003653675_multithreading_pool_python_web_crawler.txt
Q: Simple python Tkinter questions about buttons Can someone provide me with some example code. I am fairly fluent with python but can't figure this out. So i will be generating a list with say "x" elements from other code. I need Tkinter to display a "x" buttons that can be checked on or off. Then once the user has selected whichever ones they want, they will press GO and more code will execute on only the items in the list that are selected. So basically i just need to make something True or False (or 1 or 0) by using the checkbuttons in Tkinter. If someone can show me how to do this using Classes id love to see it. Thanks!! A: import Tkinter as tk def printVar(): print 'var is', var.get() root = tk.Tk() var = tk.IntVar() c = tk.Checkbutton(root, text='Check me', variable=var, command=printVar) c.pack() root.mainloop() Take a look at Tkinter page at the python wiki. Edit import Tkinter as tk def printOpts(): for opt, val in zip(options, checkboxes): print opt + ': ' + str(bool(val.get())) options = ['eggs', 'apples', 'pears'] checkboxes = [] root = tk.Tk() for opt in options: v = tk.IntVar() checkboxes.append(v) c = tk.Checkbutton(root, text=opt, variable=v) c.pack() btn = tk.Button(root, text='Print options', command=printOpts) btn.pack() root.mainloop() A: Makes a nice toggle button import Tkinter class TkToggle(Tkinter.Tk): def __init__(self, parent): Tkinter.Tk.__init__(self, parent) self.parent = parent self.initialize() def initialize(self): global toggle toggle = 0 self.Button = Tkinter.Label(self, text='X', relief='ridge') self.Button.pack(ipadx=15,ipady=15) self.Button.bind('<ButtonRelease-1>', self.Toggle) def Toggle (self, event): global toggle if toggle == 0: toggle = 1 self.Button.configure(text = '') print 'A' else: toggle = 0 self.Button.configure(text = 'X') print 'B' if __name__ == "__main__": app = TkToggle(None) app.mainloop()
Simple python Tkinter questions about buttons
Can someone provide me with some example code. I am fairly fluent with python but can't figure this out. So i will be generating a list with say "x" elements from other code. I need Tkinter to display a "x" buttons that can be checked on or off. Then once the user has selected whichever ones they want, they will press GO and more code will execute on only the items in the list that are selected. So basically i just need to make something True or False (or 1 or 0) by using the checkbuttons in Tkinter. If someone can show me how to do this using Classes id love to see it. Thanks!!
[ "import Tkinter as tk\n\ndef printVar():\n print 'var is', var.get()\n\nroot = tk.Tk()\nvar = tk.IntVar()\nc = tk.Checkbutton(root, text='Check me', variable=var, command=printVar)\nc.pack()\nroot.mainloop()\n\nTake a look at Tkinter page at the python wiki.\nEdit\nimport Tkinter as tk\n\ndef printOpts():\n f...
[ 2, 0 ]
[]
[]
[ "function", "python", "tkinter" ]
stackoverflow_0003614781_function_python_tkinter.txt
Q: "python manage.py runserver" = cannot execute binary file error (django) new one to me commend I'm running ubuntu 10.04 relatively fresh install on my laptop manually installed django 1.2.1 when I try to run inside of a virtualenv python manage.py **any command** I get the error "bash: /home/alvin/workspace/storm-guard/virtual_damage_restoration/bin/python: cannot execute binary file " I have done the following so far: removed and re-installed django removed and re-installed project directory removed first line from manage.py that defines the python shell to use verified file has permission to execute re-installed virtualenv at this point I'm scratching my head any advice is greatly apreciated A: the virtualenv I was attempting to use was copied from another computer for whatever reason when I created a new virtualenv and copied the bin directory over the existing everything started working
"python manage.py runserver" = cannot execute binary file error (django)
new one to me commend I'm running ubuntu 10.04 relatively fresh install on my laptop manually installed django 1.2.1 when I try to run inside of a virtualenv python manage.py **any command** I get the error "bash: /home/alvin/workspace/storm-guard/virtual_damage_restoration/bin/python: cannot execute binary file " I have done the following so far: removed and re-installed django removed and re-installed project directory removed first line from manage.py that defines the python shell to use verified file has permission to execute re-installed virtualenv at this point I'm scratching my head any advice is greatly apreciated
[ "the virtualenv I was attempting to use was copied from another computer\nfor whatever reason when I created a new virtualenv and copied the bin directory over the existing everything started working\n" ]
[ 0 ]
[]
[]
[ "django", "python", "virtualenv" ]
stackoverflow_0003654036_django_python_virtualenv.txt
Q: How do you get the last arrow key pressed using curses? I'm writing a Python snake game using curses, but am having some trouble controlling the snake, my current code for controlling the snake is placed inside the main loop and looks like this: while True: char = screen.getch() if char == 113: exit() # q elif char == curses.KEY_RIGHT: snake.update(RIGHT) elif char == curses.KEY_LEFT: snake.update(LEFT) elif char == curses.KEY_UP: snake.update(UP) elif char == curses.KEY_DOWN: snake.update(DOWN) else snake.update() time.sleep(0.1) However the code seems to treat the keys pressed as a que (so the snake will stop when it runs out of arrow-presses), whereas I actually want it to retrieve the last arrow key that was pressed. How can I retrieve the last arrow key that was pressed? A: Set screen.nodelay(1): screen.nodelay(1) while True: char = screen.getch() if char == 113: break # q elif char == curses.KEY_RIGHT: snake.update(RIGHT) elif char == curses.KEY_LEFT: snake.update(LEFT) elif char == curses.KEY_UP: snake.update(UP) elif char == curses.KEY_DOWN: snake.update(DOWN) else: snake.update() time.sleep(0.1)
How do you get the last arrow key pressed using curses?
I'm writing a Python snake game using curses, but am having some trouble controlling the snake, my current code for controlling the snake is placed inside the main loop and looks like this: while True: char = screen.getch() if char == 113: exit() # q elif char == curses.KEY_RIGHT: snake.update(RIGHT) elif char == curses.KEY_LEFT: snake.update(LEFT) elif char == curses.KEY_UP: snake.update(UP) elif char == curses.KEY_DOWN: snake.update(DOWN) else snake.update() time.sleep(0.1) However the code seems to treat the keys pressed as a que (so the snake will stop when it runs out of arrow-presses), whereas I actually want it to retrieve the last arrow key that was pressed. How can I retrieve the last arrow key that was pressed?
[ "Set screen.nodelay(1):\nscreen.nodelay(1)\nwhile True:\n char = screen.getch()\n if char == 113: break # q\n elif char == curses.KEY_RIGHT: snake.update(RIGHT)\n elif char == curses.KEY_LEFT: snake.update(LEFT)\n elif char == curses.KEY_UP: snake.update(UP)\n elif char == curses.KEY_DOWN: snake....
[ 4 ]
[]
[]
[ "curses", "keypress", "python" ]
stackoverflow_0003651709_curses_keypress_python.txt
Q: python mysql configuration problem I'm trying to make django work on snow leopard. So far I've installed mysql 64 bit installed python 2.7 64 bit and installed django 1.2.1. Now I'm trying to install mysql-python-1.2.3; at the beginning I had problems because I hadn't installed the setup tool, having done that when try to install it by executing these command python setup.py build python setup.py install here's what I got running build running build_py creating build/lib.macosx-10.5-fat3-2.7 error: could not create 'build/lib.macosx-10.5-fat3-2.7': Permission denied Any idea? Am I doing something wrong? Thanks Mauro A: You need to use sudo sudo setup.py build sudo setup.py install You might just want to use sqlite. A: At the risk of pointing out the obvious, you do not have permission to write to the build directory. Check and change the directory permissions (with the chmod command) or do the setup as an admin user.
python mysql configuration problem
I'm trying to make django work on snow leopard. So far I've installed mysql 64 bit installed python 2.7 64 bit and installed django 1.2.1. Now I'm trying to install mysql-python-1.2.3; at the beginning I had problems because I hadn't installed the setup tool, having done that when try to install it by executing these command python setup.py build python setup.py install here's what I got running build running build_py creating build/lib.macosx-10.5-fat3-2.7 error: could not create 'build/lib.macosx-10.5-fat3-2.7': Permission denied Any idea? Am I doing something wrong? Thanks Mauro
[ "You need to use sudo\nsudo setup.py build\nsudo setup.py install\n\nYou might just want to use sqlite.\n", "At the risk of pointing out the obvious, you do not have permission to write to the build directory. Check and change the directory permissions (with the chmod command) or do the setup as an admin user.\n...
[ 2, 0 ]
[]
[]
[ "django", "macos", "mysql", "python" ]
stackoverflow_0003654479_django_macos_mysql_python.txt
Q: Matplotlib: multiple y axes, grid lines applied to both? I've got a Matplotlib graph with two y axes, created like: ax1 = fig.add_subplot(111) ax1.grid(True, color='gray') ax1.plot(xdata, ydata1, 'b', linewidth=0.5) ax2 = ax1.twinx() ax2.plot(xdata, ydata2, 'g', linewidth=0.5) I need grid lines but I want them to apply to both y axes not just the left one. The scales of each axes will differ. What I get is grid lines that only match the values on the left hand axes. Can Matplotlib figure this out for me or do I have to do it myself? Edit: Don't think I was completely clear, I want the major ticks on both y axes to be aligned but the scales and ranges are potentially quite different making it tricky to setup the mins and maxes manually to achieve this. I am hoping that matplotlib will be able to do this "tricky" bit for me. Thanks A: EDIT Consider this simple example: from pylab import * # some random values xdata = arange(0.0, 2.0, 0.01) ydata1 = sin(2*pi*xdata) ydata2 = 5*cos(2*pi*xdata) + randn(len(xdata)) # number of ticks on the y-axis numSteps = 9; # plot figure() subplot(121) plot(xdata, ydata1, 'b') yticks( linspace(ylim()[0],ylim()[1],numSteps) ) grid() subplot(122) plot(xdata, ydata2, 'g') yticks( linspace(ylim()[0],ylim()[1],numSteps) ) grid() show()
Matplotlib: multiple y axes, grid lines applied to both?
I've got a Matplotlib graph with two y axes, created like: ax1 = fig.add_subplot(111) ax1.grid(True, color='gray') ax1.plot(xdata, ydata1, 'b', linewidth=0.5) ax2 = ax1.twinx() ax2.plot(xdata, ydata2, 'g', linewidth=0.5) I need grid lines but I want them to apply to both y axes not just the left one. The scales of each axes will differ. What I get is grid lines that only match the values on the left hand axes. Can Matplotlib figure this out for me or do I have to do it myself? Edit: Don't think I was completely clear, I want the major ticks on both y axes to be aligned but the scales and ranges are potentially quite different making it tricky to setup the mins and maxes manually to achieve this. I am hoping that matplotlib will be able to do this "tricky" bit for me. Thanks
[ "EDIT\nConsider this simple example:\nfrom pylab import *\n\n# some random values\nxdata = arange(0.0, 2.0, 0.01)\nydata1 = sin(2*pi*xdata)\nydata2 = 5*cos(2*pi*xdata) + randn(len(xdata))\n\n# number of ticks on the y-axis\nnumSteps = 9;\n\n# plot\nfigure()\n\nsubplot(121)\nplot(xdata, ydata1, 'b')\nyticks( linspac...
[ 3 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0003654619_matplotlib_python.txt
Q: Why can't I assign to undeclared attributes of an object() instance but I can with custom classes? Basically I want to know why this works: class MyClass: pass myObj = MyClass() myObj.foo = 'a' But this returns an AttributeError: myObj = object() myObj.foo = 'a' How can I tell which classes I can use undefined attributes with and which I can't? Thanks. A: You can set attributes on any class with a __dict__, because that is where they are stored. object instances (which are weird) and any class that defines __slots__ do not have one: >>> class Foo(object): pass ... >>> foo = Foo() >>> hasattr(foo, "__dict__") True >>> foo.bar = "baz" >>> >>> class Spam(object): ... __slots__ = tuple() ... >>> spam = Spam() >>> hasattr(spam, "__dict__") False >>> spam.ham = "eggs" Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Spam' object has no attribute 'ham' >>>
Why can't I assign to undeclared attributes of an object() instance but I can with custom classes?
Basically I want to know why this works: class MyClass: pass myObj = MyClass() myObj.foo = 'a' But this returns an AttributeError: myObj = object() myObj.foo = 'a' How can I tell which classes I can use undefined attributes with and which I can't? Thanks.
[ "You can set attributes on any class with a __dict__, because that is where they are stored. object instances (which are weird) and any class that defines __slots__ do not have one:\n>>> class Foo(object): pass\n...\n>>> foo = Foo()\n>>> hasattr(foo, \"__dict__\")\nTrue\n>>> foo.bar = \"baz\"\n>>>\n>>> class Spam(o...
[ 2 ]
[]
[]
[ "class_structure", "python" ]
stackoverflow_0003654669_class_structure_python.txt
Q: SVN/python library I need to manipulate a subversion client from python. I need to: check the most recent revision to change something under a given path. update a client to a given (head or non head) revision get logs for a given path (revisions that changed it and when). A quick search didn't turn up what I'm looking for and I'd rather not have to write my own wrapper around the svn command line tool. (BTW: running under Linux and python 2.6) A: Check out the pysvn library. Or skim the pysvn Programmer's Guide to see if it meets most of your use cases.
SVN/python library
I need to manipulate a subversion client from python. I need to: check the most recent revision to change something under a given path. update a client to a given (head or non head) revision get logs for a given path (revisions that changed it and when). A quick search didn't turn up what I'm looking for and I'd rather not have to write my own wrapper around the svn command line tool. (BTW: running under Linux and python 2.6)
[ "Check out the pysvn library. Or skim the pysvn Programmer's Guide to see if it meets most of your use cases.\n" ]
[ 6 ]
[]
[]
[ "python", "svn" ]
stackoverflow_0003654812_python_svn.txt
Q: Rounding up with pennies in Python? I am making a change program in python. The user must input a dollar amount and then the program will calculate the change in twenties, tens, fives, ones, quarters, dimes, nickels, and pennies. I was instructed to use the round function for the pennies because If I input an amount of $58.79, the program tells me to give 3 pennies back when it should be 4. Is there a way to round up these pennies? I know the value of a penny is .01, but python reads this as .100000000001 which I believe is the problem. Any help is appreciated, here is the section I need rounded: # get the amount to change from the user change = input("Please enter the amount to change: $") print "To make change for $",change,"give the customer back:" # calculate number of twenties twenties = int(change/ 20) print twenties, "twenties" change = change - twenties *20 # calculate tens tens = int(change / 10) print tens, "tens" change = change - tens *10 #calculate fives fives = int(change / 5) print fives, "fives" change = change - fives *5 #calculate ones ones = int(change / 1) print ones, "ones" change = change - ones * 1 #calculate quarters quarters = int(change / .25) print quarters, "quarters" change = change - quarters * .25 #calculate dimes dimes = int(change / .10) print dimes, "dimes" change = change - dimes * .10 #calculate nickels nickels = int(change / .05) print nickels, "nickels" change = change - nickels * .05 #calculate pennies pennies = int(change / .01) print pennies, "pennies" A: Multiply the user's inputed dollar value by 100, convert to int, and work in units of pennies. Integer arithmetic is dead simple (and exact). Floating point arithmetic is tricky and forces you to use more brain cells :) . Save brain cells and work entirely in ints. A: The problem is that 0.01 cannot be accurately represented as a binary floating point value (which is how normal floats are stored – this is true for any language, not just Python). So if you need exact values for dollars and cents, you can use the decimal module. That way you can be sure that your values will be rounded exactly. Or (since Decimals might be overkill here), first multiply every dollar value by 100 (this is not the same as dividing by 0.01 for the above reasons!), convert to int, do your calculations, and divide by 100. A: use the decimal package http://docs.python.org/library/decimal.html it is meant exactly for this kind of use case A: The problems you are having are a result of imprecise floating-point arithmetic. There is no way to precisely represent 0.01 in IEEE floating point. That is one reason not to use floats when working with currency. You should use decimals or even integers, because you know there are at most 2 digits after the decimal point. In that case, just work with the amount in pennies. On the problem itself, I think the easiest way to do it is convert your amount in dollars to the amount in pennies, then iterate through a predefined list of values containing listing the equivalent amount of pennies (in descending order) for each denomination: def change(amount): # this can be removed if you pass the amount in pennies # rather than dollars amount = int(round(amount*100)) values = [2000, 1000, 500, 100, 25, 10, 5, 1] denom = ['twenties', 'tens', 'fives', 'ones', 'quarters', 'dimes', 'nickels', 'pennies'] for i in range(len(values)): num = amount / values[i] amount -= num * values[i] print str(num) + " " + denom[i] Now calling change(58.79) will print 2 twenties 1 tens 1 fives 3 ones 3 quarters 0 dimes 0 nickels 4 pennies As seen on codepad.org A: >>> from math import ceil >>> a = 58.79 >>> ceil(a % 0.05 * 100) 4.0 >>> [edit] Now that I think of it, might aswell just go with >>> a = 58.79 >>> a*100 % 5 4.0
Rounding up with pennies in Python?
I am making a change program in python. The user must input a dollar amount and then the program will calculate the change in twenties, tens, fives, ones, quarters, dimes, nickels, and pennies. I was instructed to use the round function for the pennies because If I input an amount of $58.79, the program tells me to give 3 pennies back when it should be 4. Is there a way to round up these pennies? I know the value of a penny is .01, but python reads this as .100000000001 which I believe is the problem. Any help is appreciated, here is the section I need rounded: # get the amount to change from the user change = input("Please enter the amount to change: $") print "To make change for $",change,"give the customer back:" # calculate number of twenties twenties = int(change/ 20) print twenties, "twenties" change = change - twenties *20 # calculate tens tens = int(change / 10) print tens, "tens" change = change - tens *10 #calculate fives fives = int(change / 5) print fives, "fives" change = change - fives *5 #calculate ones ones = int(change / 1) print ones, "ones" change = change - ones * 1 #calculate quarters quarters = int(change / .25) print quarters, "quarters" change = change - quarters * .25 #calculate dimes dimes = int(change / .10) print dimes, "dimes" change = change - dimes * .10 #calculate nickels nickels = int(change / .05) print nickels, "nickels" change = change - nickels * .05 #calculate pennies pennies = int(change / .01) print pennies, "pennies"
[ "Multiply the user's inputed dollar value by 100, convert to int, and work in units of pennies.\nInteger arithmetic is dead simple (and exact). Floating point arithmetic is tricky and forces you to use more brain cells :) . Save brain cells and work entirely in ints. \n", "The problem is that 0.01 cannot be accur...
[ 4, 2, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003654331_python.txt
Q: How could you swap out a particular database implementation in python? If I have a seperate class for my db calls, and I create another implementation of the db layer but say with a different data store. Is there a way for me to completly swap out the implementation without having to change allot of code? i.e. I am starting a project, so I can design things properly to achieve this from the get-go. Note: I will use this pattern for other parts of the site also, not just the db layer so its not really specific to db layer only. A: As long as two modules implement exactly the same interface (classes with the same names, methods, and other attributes, functions with the same names and signatures, ...) you can pick one or the other at the time your application is starting up, for example on the basis of some configuration file, and import the chosen one under a fixed name. All the rest of your application can then use that fixed name and, net of the startup code, be blissfully unaware of any shenanigans that may have been done at the start. For example, consider a simplified case: # english.py def greet(): return 'Hello!' # italian.py def greet(): return 'Ciao!' # french.py def greet(): return 'Salut!' # config.py langname = 'italian' # startit.py import config import sys lang = __import__(config.langname) sys.modules['lang'] = lang Now, all the rest of the application can just import lang, and it will be getting under that name the italian module, so, when calling lang.greet(), it will get the string 'Ciao!'. Of course, in real life you'll have multiple modules, each with multiple functions, classes, and whatnot, but the general principles stay very similar. Just take special care about modules with qualified names (such as foo.bar), i.e., modules which must reside in a package (in this case, foo). For those, you can't just use __import__'s return value, but must use a slightly more roundabout approach, such as: import sys def importanyasname(actualname, fakename): __import__(actualname) sys.modules[fakename] = sys.modules[actualname] that is, ignore __import__'s return value, and reach right for the value that's left (with the actual name as the key) in the sys.modules dictionary -- that is the module object you seek, and that you can set back into sys.modules with the "fake name" by which all the rest of the application will be able to blissfully import it any time.
How could you swap out a particular database implementation in python?
If I have a seperate class for my db calls, and I create another implementation of the db layer but say with a different data store. Is there a way for me to completly swap out the implementation without having to change allot of code? i.e. I am starting a project, so I can design things properly to achieve this from the get-go. Note: I will use this pattern for other parts of the site also, not just the db layer so its not really specific to db layer only.
[ "As long as two modules implement exactly the same interface (classes with the same names, methods, and other attributes, functions with the same names and signatures, ...) you can pick one or the other at the time your application is starting up, for example on the basis of some configuration file, and import the ...
[ 2 ]
[]
[]
[ "ioc_container", "python" ]
stackoverflow_0003654873_ioc_container_python.txt
Q: Django, save data from form without having to manually set each field to save? I can't seem to figure out a good way to do this, I have a bunch of form input fields and rather than having to do like below where I have to type out each fieldname = "" and such, is there a way to code this so it would automatically save each field from within the form? b = Modelname(fieldname=request.POST['fieldname']) b.save() I realize security issues of this but could be negated by running it through a list that checks for a valid form value. A: Sure, request.POST.items() and request.POST.iteritems() work just like the methods of the same name in a dict, returning resp. a list and an iterator of all (name, value) pairs (2-items tuple) in that dict-like object. If there are multiple values for a name, that only gives you the last one; if you want all of them, use request.POST.iterlists(), which in the value slot of each pair has a list of all the values for fields with that name. So, assuming for example that you don't care about duplicates or know there are none, even a snippet as short as: for name, value in request.POST.iteritems(): ModelName(**dict( [ (name, value) ] )).save() might suffice, though it might definitely be better to add some validation checking of the name/value pair before saving it this way;-).
Django, save data from form without having to manually set each field to save?
I can't seem to figure out a good way to do this, I have a bunch of form input fields and rather than having to do like below where I have to type out each fieldname = "" and such, is there a way to code this so it would automatically save each field from within the form? b = Modelname(fieldname=request.POST['fieldname']) b.save() I realize security issues of this but could be negated by running it through a list that checks for a valid form value.
[ "Sure, request.POST.items() and request.POST.iteritems() work just like the methods of the same name in a dict, returning resp. a list and an iterator of all (name, value) pairs (2-items tuple) in that dict-like object. If there are multiple values for a name, that only gives you the last one; if you want all of t...
[ 3 ]
[]
[]
[ "django", "forms", "python" ]
stackoverflow_0003655018_django_forms_python.txt
Q: Python routes - I'm trying to set the format extension but it's failing I'm trying to setup my Routes and enable an optional 'format' extension to specify whether the page should load as a standard HTML page or within a lightbox. Following this http://routes.groovie.org/setting_up.html#format-extensions, I've come up with: map.connect('/info/test{.format:lightbox}', controller='front', action='test') class FrontController(BaseController): def test(self, format='html'): print format This fails. My route gets screwed up and the URL appears as /front/test rather than /info/test. It's falling back to the /{controller}/{action}. How do I allow for the format extension? :/ A: Generally: http://pylonsbook.com/en/1.1/urls-routing-and-dispatch.html#pylons-routing-in-detail Routes then searches each of the routes in the route map from top to bottom until it finds a route that matches the URL. Because matching is done from top to bottom, you are always advised to put your custom routes below the ones that Pylons provides to ensure you don’t accidentally interfere with the default behavior of Pylons. More generally speaking, you should always put your most general routes at the bottom of the route map so that they don’t accidentally get matched before a more specific route lower down in the route map. A: The first thing I'd check is that you're using routes 1.12. Several distros are still on 1.11, which doesn't support format extensions. Second, check the order in which your routes are defined. It matters.
Python routes - I'm trying to set the format extension but it's failing
I'm trying to setup my Routes and enable an optional 'format' extension to specify whether the page should load as a standard HTML page or within a lightbox. Following this http://routes.groovie.org/setting_up.html#format-extensions, I've come up with: map.connect('/info/test{.format:lightbox}', controller='front', action='test') class FrontController(BaseController): def test(self, format='html'): print format This fails. My route gets screwed up and the URL appears as /front/test rather than /info/test. It's falling back to the /{controller}/{action}. How do I allow for the format extension? :/
[ "Generally:\nhttp://pylonsbook.com/en/1.1/urls-routing-and-dispatch.html#pylons-routing-in-detail\n\nRoutes then searches each of the routes in the route map from top to bottom until it finds a route that matches the URL. Because matching is done from top to bottom, you are always advised to put your custom routes ...
[ 1, 0 ]
[]
[]
[ "pylons", "python", "routes" ]
stackoverflow_0003655142_pylons_python_routes.txt
Q: Python: Shorten ugly code? I have a ridiculous code segment in one of my programs right now: str(len(str(len(var_text)**255))) Is there an easy way to shorten that? 'Cause, frankly, that's ridiculous. A option to convert a number >500 digits to scientific notation would also be helpful (that's what I'm trying to do) Full code: print("Useless code rating:" , str(len(var_text)**255)[1] + "e" + str(len(str(len(var_text)**255)))) A: TL;DR: y = 2.408 * len(var_text) Lets assume that your passkey is a string of characters with 256 characters available (0-255). Then just as a 16bit number holds 65536 numbers (2**16) the permutations of a string of equal length would be n_perms = 256**len(passkey) If you want the number of (decimal) digits in n_perms, consider the logarithm: >>> from math import log10 >>> log10(1000) 3.0 >>> log10(9999) 3.9999565683801923 >>> So we have length = floor(log10(n_perms)) + 1. In python, int rounds down anyway, so I'd say you want n_perms = 256**len(var_text) length = int(log10(n_perms)) + 1 I'd argue that 'shortening' ugly code isn't always the best way - you want it to be clear what you're doing. Edit: On further consideration I realised that choosing base-10 to find the length of your permutations is really arbitrary anyway - so why not choose base-256! length = log256(256**len(var_text) length = len(var_text) # the log and exp cancel! You are effectively just finding the length of your passkey in a different base... Edit 2: Stand back, I'm going to attempt Mathematics! if x = len(var_text), we want y such that y = log10(256**x) 10**y = 256**x 10**y = (10**log10(256))**x 10**y = (10**(log10(256)x)) y = log10(256) * x So, how's this for short: length = log10(256) * len(var_text) # or about (2.408 * x) A: This looks like it's producing a string version of the number of digits in the 255th power of the length of a string. Is that right? I'd be curious what that's used for. You could compute the number differently, but it's not shorter and I'm not sure it's prettier: str(int(math.ceil(math.log10(len(var_text))*255))) or: "%d" % math.ceil(math.log10(len(v))*255) A: Are you trying to determine the number of possible strings having the same length as var_text? If so, you have your base and exponent reversed. You want to use 255**len(var_text) instead of len(var_text)**255. But, I have to ask ... how long do these passkeys get to be, and what are you using them for? And, why not just use the length of the passkey as an indicator of its length? A: Firstly, if your main problem is manipulating huge floating point expressions, use the bigfloat package: >>> import bigfloat >>> bigfloat.BigFloat('1e1000') BigFloat.exact('1.0000000000000001e+1000', precision=53) As for the details in your question: len(str(num)) is approximately equal to log(num, 10) + 1. This is not significantly shorter, but it's certainly a better way of expressing it in code (for the benefit of anyone who doesn't know that off the top of their head). You can then simplify it with log laws: len(str(x**y)) = log(x**y, 10) + 1 = y * log(x, 10) + 1 So maybe you'll find: "%i" % (log(len(var_text),10)*255 + 1) ... is better? It's not significantly shorter, but it's a much clearer mathematical relationship between input and output.
Python: Shorten ugly code?
I have a ridiculous code segment in one of my programs right now: str(len(str(len(var_text)**255))) Is there an easy way to shorten that? 'Cause, frankly, that's ridiculous. A option to convert a number >500 digits to scientific notation would also be helpful (that's what I'm trying to do) Full code: print("Useless code rating:" , str(len(var_text)**255)[1] + "e" + str(len(str(len(var_text)**255))))
[ "TL;DR: y = 2.408 * len(var_text)\nLets assume that your passkey is a string of characters with 256 characters available (0-255). Then just as a 16bit number holds 65536 numbers (2**16) the permutations of a string of equal length would be\nn_perms = 256**len(passkey)\n\nIf you want the number of (decimal) digits i...
[ 6, 0, 0, 0 ]
[]
[]
[ "coding_style", "python" ]
stackoverflow_0003654706_coding_style_python.txt
Q: Python: Listen on two ports import socket backlog = 1 #Number of queues sk_1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sk_2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) local = {"port":1433} internet = {"port":9999} sk_1.bind (('', internet["port"])) sk_1.listen(backlog) sk_2.bind (('', local["port"])) sk_2.listen(backlog) Basically, I have this code. I am trying to listen on two ports: 1433 and 9999. But, this doesn't seems to work. How can I listen on two ports, within the same python script?? A: The fancy-pants way to do this if you want to use Python std-lib would be to use SocketServer with the ThreadingMixin -- although the 'select' suggestion is probably the more efficient. Even though we only define one ThreadedTCPRequestHandler you can easily repurpose it such that each listener has it's own unique handler and it should be fairly trivial to wrap the server/thread creation into a single method if thats the kind of thing you like. #!/usr/bin/python import threading import time import SocketServer class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler): def handle(self): self.data = self.request.recv(1024).strip() print "%s wrote: " % self.client_address[0] print self.data self.request.send(self.data.upper()) class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass if __name__ == "__main__": HOST = '' PORT_A = 9999 PORT_B = 9876 server_A = ThreadedTCPServer((HOST, PORT_A), ThreadedTCPRequestHandler) server_B = ThreadedTCPServer((HOST, PORT_B), ThreadedTCPRequestHandler) server_A_thread = threading.Thread(target=server_A.serve_forever) server_B_thread = threading.Thread(target=server_B.serve_forever) server_A_thread.setDaemon(True) server_B_thread.setDaemon(True) server_A_thread.start() server_B_thread.start() while 1: time.sleep(1) A: The code so far is fine, as far as it goes (except that a backlog of 1 seems unduly strict), the problem of course comes when you try to accept a connection on either listening socket, since accept is normally a blocking call (and "polling" by trying to accept with short timeouts on either socket alternately will burn machine cycles to no good purpose). select to the rescue!-) select.select (or on the better OSs select.poll or even select.epoll or select.kqueue... but, good old select.select works everywhere!-) will let you know which socket is ready and when, so you can accept appropriately. Along these lines, asyncore and asynchat provide a bit more organization (and third-party framework twisted, of course, adds a lot of such "asynchronous" functionality). Alternatively, you can devote separate threads to servicing the two listening sockets, but in this case, if the different sockets' functionality needs to affect the same shared data structures, coordination (locking &c) may become ticklish. I would certainly recommend trying the async approach first -- it's actually simpler, as well as offering potential for substantially better performance!-)
Python: Listen on two ports
import socket backlog = 1 #Number of queues sk_1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sk_2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) local = {"port":1433} internet = {"port":9999} sk_1.bind (('', internet["port"])) sk_1.listen(backlog) sk_2.bind (('', local["port"])) sk_2.listen(backlog) Basically, I have this code. I am trying to listen on two ports: 1433 and 9999. But, this doesn't seems to work. How can I listen on two ports, within the same python script??
[ "The fancy-pants way to do this if you want to use Python std-lib would be to use SocketServer with the ThreadingMixin -- although the 'select' suggestion is probably the more efficient. \nEven though we only define one ThreadedTCPRequestHandler you can easily repurpose it such that each listener has it's own uniqu...
[ 11, 4 ]
[]
[]
[ "listen", "python", "sockets" ]
stackoverflow_0003655053_listen_python_sockets.txt
Q: object factory that generates an object or list of objects I have the following code: def f(cls, value): # cls is a class # value is a string value if cls == str: pass # value is already the right type elif cls == int: value = int(value) elif cls == C1: value = C1(value) elif cls == C2: value = C2(value) elif cls == C3 # in this case, we convert the string into a list of objects of class C3 value = C3.parse(value) else raise UnknownClass(repr(cls)) return value Obviously, I'm trying to replace it with something like: def f(cls, value) return cls(value) Unfortunately, in some cases (if cls == C3), the parsing of the input results in a list of objects of that class, rather than just one object. What's a neat way to handle this? I have access to all the classes. A: If most cases are best handled by calling cls, and a few are best handled otherwise, simplest is to single out the latter: themap = {C3: C3.parse} for C in (str, C1, C2): themap[C] = C def f(cls, value): wot = themap.get(cls) if wot is None: raise UnknownClass(repr(cls)) return wot(value) Note that calling str on a string is a pretty fast noop, so it's generally worth avoiding the "singling out" of that specific case in favor of code simplicity. A: That depends on what you'd do with the list. This is the simplest way: obj = cls(value) if type(obj) == list: handle_list(obj) return obj
object factory that generates an object or list of objects
I have the following code: def f(cls, value): # cls is a class # value is a string value if cls == str: pass # value is already the right type elif cls == int: value = int(value) elif cls == C1: value = C1(value) elif cls == C2: value = C2(value) elif cls == C3 # in this case, we convert the string into a list of objects of class C3 value = C3.parse(value) else raise UnknownClass(repr(cls)) return value Obviously, I'm trying to replace it with something like: def f(cls, value) return cls(value) Unfortunately, in some cases (if cls == C3), the parsing of the input results in a list of objects of that class, rather than just one object. What's a neat way to handle this? I have access to all the classes.
[ "If most cases are best handled by calling cls, and a few are best handled otherwise, simplest is to single out the latter:\nthemap = {C3: C3.parse}\nfor C in (str, C1, C2):\n themap[C] = C\n\ndef f(cls, value):\n wot = themap.get(cls)\n if wot is None:\n raise UnknownClass(repr(cls))\n return wo...
[ 2, 0 ]
[]
[]
[ "factory", "object", "python" ]
stackoverflow_0003655544_factory_object_python.txt
Q: How do I print a list of strings, when I can't know the char encoding in advance? I am retrieving a list of names from a webservice using a client I've written in Python. Upon retrieving the list, I encode each name to unicode and then print each of them to stdout. When I get to the name "Ólafur Jóhann Ólafsson", I get the following error: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128) Since I cannot know what the encoding will be, how do I convert all of these strings to unicode? Or can you suggest a better way to handle this problem? A: The UnicodeDammit module from BeautifulSoup can automagically detect the encoding. from BeautifulSoup import UnicodeDammit u = UnicodeDammit("Ólafur Jóhann Ólafsson") print u.unicode print u.originalEncoding A: This page may help you http://wiki.python.org/moin/PrintFails The problem, I guess, is that you need to print those names to console. Do you really need it? or it's just a test environment? if you use console just for testing, you may switch to other tools like unit testing to check what values you exactly get. A: First of all, you decode data to Unicode (the absence of encoding) when reading from a file, pipe, socket, terminal, etc.; and encode Unicode to an appropriate byte encoding when sending/persisting data. I suspect this is the root of your problem. The web service should declare the encoding in the headers or data received. print normally automatically encodes Unicode to the terminal's encoding (discovered through sys.stdout.encoding) or in absence of that just ascii. If the characters in your data are not supported by the target encoding, you'll get a UnicodeEncodeError. Since that is not the error you received, you should post some code so we can see what your are doing. Most likely, you are encoding a byte string instead of decoding. Here's an example of this: >>> data = '\xc2\xbd' # UTF-8 encoded 1/2 symbol. >>> data.encode('cp437') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\dev\python\lib\encodings\cp437.py", line 12, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128) What I did here is call encode on a byte string. Since encode requires a Unicode string, Python used the default ascii encoding to decode the byte string to Unicode first, before encoding to cp437. Fix this by decoding instead of encoding the data, then print will encode to stdout automatically. As long as your terminal supports the characters in the data, it will display properly: >>> import sys >>> sys.stdout.encoding 'cp437' >>> print data.decode('utf8') # implicit encode to sys.stdout.encoding ½ >>> print data.decode('utf8').encode('cp437') # explicit encode. ½
How do I print a list of strings, when I can't know the char encoding in advance?
I am retrieving a list of names from a webservice using a client I've written in Python. Upon retrieving the list, I encode each name to unicode and then print each of them to stdout. When I get to the name "Ólafur Jóhann Ólafsson", I get the following error: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128) Since I cannot know what the encoding will be, how do I convert all of these strings to unicode? Or can you suggest a better way to handle this problem?
[ "The UnicodeDammit module from BeautifulSoup can automagically detect the encoding.\nfrom BeautifulSoup import UnicodeDammit\n\nu = UnicodeDammit(\"Ólafur Jóhann Ólafsson\")\n\nprint u.unicode\nprint u.originalEncoding\n\n", "This page may help you http://wiki.python.org/moin/PrintFails \nThe problem, I guess, is...
[ 1, 1, 1 ]
[]
[]
[ "encoding", "python" ]
stackoverflow_0003652774_encoding_python.txt
Q: SWIG - running python code upon import I have a C++ module that I'm wrapping with SWIG that uses dynamic linking. Because of the way that python deals with scope of imported functions I've had to run the command dl.open(library, dl.RLTD_NOW, dl.RTLD_GLOBAL) directly after import. This is to make sure that the C++ libraries functions are available to the other libraries that it imports. Of course what this means is that in order to import the module three lines are needed instead of one. However the other lines are constant and depend on nothing. That is I want to convert the lines: import dl import module dl.open(library, dl.RTLD_NOW, dl.RTLD_GLOBAL) into simply: import module I have tried looking through the SWIG documentation as to how to make it run code upon the import of the module, but I can't find anything. Is this possible to do? Thanks. A: Try wrapping your module. Build your C++ code into a "private" module, and call it module_ or something, to make it clear that you shouldn't import it. Then, in module.py (the wrapper module): import dl from module_ import * dl.open(library, dl.RTLD_NOW, dl.RTLD_GLOBAL)
SWIG - running python code upon import
I have a C++ module that I'm wrapping with SWIG that uses dynamic linking. Because of the way that python deals with scope of imported functions I've had to run the command dl.open(library, dl.RLTD_NOW, dl.RTLD_GLOBAL) directly after import. This is to make sure that the C++ libraries functions are available to the other libraries that it imports. Of course what this means is that in order to import the module three lines are needed instead of one. However the other lines are constant and depend on nothing. That is I want to convert the lines: import dl import module dl.open(library, dl.RTLD_NOW, dl.RTLD_GLOBAL) into simply: import module I have tried looking through the SWIG documentation as to how to make it run code upon the import of the module, but I can't find anything. Is this possible to do? Thanks.
[ "Try wrapping your module. Build your C++ code into a \"private\" module, and call it module_ or something, to make it clear that you shouldn't import it. Then, in module.py (the wrapper module):\nimport dl\nfrom module_ import *\ndl.open(library, dl.RTLD_NOW, dl.RTLD_GLOBAL)\n\n" ]
[ 2 ]
[]
[]
[ "python", "swig" ]
stackoverflow_0003650059_python_swig.txt
Q: Write a script to do content filtering with postfix How can i write in python or ruby a script to do content filtering in postfix via smtp or uucp (not pipe)? There is some examples? A: If you don't need the whole mail body to process it, you could simply write a policy server for Postfix, see Access policy delegation. If you need to process the whole mail, you have several possibilities, see Postfix Content Inspection. You could either implement a content filter (see FILTER_README) which gets the mail via SMTP or LMTP and, after processing it, sends it back to Postfix through SMTP, or you could implement a milter, for which appropriate libraries for Python exist.
Write a script to do content filtering with postfix
How can i write in python or ruby a script to do content filtering in postfix via smtp or uucp (not pipe)? There is some examples?
[ "If you don't need the whole mail body to process it, you could simply write a policy server for Postfix, see Access policy delegation.\nIf you need to process the whole mail, you have several possibilities, see Postfix Content Inspection.\nYou could either implement a content filter (see FILTER_README) which gets ...
[ 4 ]
[]
[]
[ "postfix_mta", "python", "ruby" ]
stackoverflow_0003652161_postfix_mta_python_ruby.txt
Q: Binary Search Trees This is some code found on wikipedia regarding BST : # 'node' refers to the parent-node in this case def search_binary_tree(node, key): if node is None: return None # key not found if key < node.key: return search_binary_tree(node.leftChild, key) elif key > node.key: return search_binary_tree(node.rightChild, key) else: # key is equal to node key return node.value # found key Now here's a Binary Tree : 10 5 12 3 8 9 14 4 11 If I am searching for 11, and I follow the algorithm up there, I start with 10, I go right to 12, and then left to 9. And I reach the end of the tree without finding 11. But 11 exists in my tree, it's just on the other side. Can you please explain what are the restrictions in a Binary Tree for this algorithm to work on my tree ? Thanks. A: It's just because your tree is not a binary search tree: it is not ordered correctly. The BST is build as described in the algorithm actually. For instance in your tree: the node '9' is not at the right position because as 9 < 10 it should be under the left branch of your root node '10'. Same for '14' and '11' which should be on the right branch. for instance a BST could sth like this: 10 5 11 3 8 12 14 A: Do not confuse between Binary Tree and Binary Search Tree. The binary search tree (in short called as BST) is a special type of binary tree where all the nodes on the left are lesser than or equal to the parent node and all the nodes right are greater than the parent node. Whereas the example you've given is just a Binary Tree and not a Binary Search Tree. You can see that the value 11 and 14 are left to the parent node 10 which violates the BST property. Take a look here for Binary search trees. A: The tree you presented in not a BST. 11 and 14 would have never been inserted to the left of 10, and that's why the algorithm doesn't search there. 9 is also out of place. Insertion according to Wikipedia: Insertion begins as a search would begin; if the root is not equal to the value, we search the left or right subtrees as before. Eventually, we will reach an external node and add the value as its right or left child, depending on the node's value. In other words, we examine the root and recursively insert the new node to the left subtree if the new value is less than the root, or the right subtree if the new value is greater than or equal to the root. You can tell that a Binary Tree is a BST if it has these properties (also from Wikipedia): The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. A: You have placed the nodes 14 and 11 in the wrong place. From the Wikipedia article on BSTs: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. As you can see, both 14 and 11 are greater than 8. A: your tree is not a binary search tree
Binary Search Trees
This is some code found on wikipedia regarding BST : # 'node' refers to the parent-node in this case def search_binary_tree(node, key): if node is None: return None # key not found if key < node.key: return search_binary_tree(node.leftChild, key) elif key > node.key: return search_binary_tree(node.rightChild, key) else: # key is equal to node key return node.value # found key Now here's a Binary Tree : 10 5 12 3 8 9 14 4 11 If I am searching for 11, and I follow the algorithm up there, I start with 10, I go right to 12, and then left to 9. And I reach the end of the tree without finding 11. But 11 exists in my tree, it's just on the other side. Can you please explain what are the restrictions in a Binary Tree for this algorithm to work on my tree ? Thanks.
[ "It's just because your tree is not a binary search tree: it is not ordered correctly. The BST is build as described in the algorithm actually. For instance in your tree: the node '9' is not at the right position because as 9 < 10 it should be under the left branch of your root node '10'. Same for '14' and '11' whi...
[ 10, 3, 3, 1, 1 ]
[]
[]
[ "algorithm", "binary_search_tree", "binary_tree", "python" ]
stackoverflow_0003656008_algorithm_binary_search_tree_binary_tree_python.txt
Q: manage.py syncdb error while Django model using non-ascii verbose_name I am pretty new to Django. I want the name of my models to be displayed in Chinese, so i used verbose_name in my meta class of my model, codes below: #this models.py file is encoded in unicode class TS_zone(models.Model): index = models.IntegerField() zone_name = models.CharField(max_length=50); zone_icon = models.ImageField(upload_to='zone_icon', null=True) is_active = models.NullBooleanField(blank=True, null=True) status = models.CharField(max_length=7,choices=SETTING_STATUS_CHOICES) class Meta: ordering = ('index',) verbose_name = u'你好嗎?' verbose_name_plural = u'你們都好嗎?' def __unicode__(self): return self.zone_name However when i run manage.py syncdb, the following errors throws: File "E:\pythonroot\myproject\..\myproject\myapp\models.py", line 19 SyntaxError: Non-ASCII character '\xe4' in file E:\pythonroot\myproject\..\myproject\myapp\models.py on line 19, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details It seems that manage.py cannot process non-ascii character in my verbose_name. Anything i have done wrong? Thank you. A: You have to specify an encoding. Add the following line as the first line of your models.py file. # encoding: utf-8 Update The OP has edited his question to say that the "models.py is encoded in Unicode". Then the error is strange. It works for me using Django 1.2.1, Python 2.6.2 on Ubuntu Jaunty. Update 2 Can you post the encoding string you have used for your models.py?
manage.py syncdb error while Django model using non-ascii verbose_name
I am pretty new to Django. I want the name of my models to be displayed in Chinese, so i used verbose_name in my meta class of my model, codes below: #this models.py file is encoded in unicode class TS_zone(models.Model): index = models.IntegerField() zone_name = models.CharField(max_length=50); zone_icon = models.ImageField(upload_to='zone_icon', null=True) is_active = models.NullBooleanField(blank=True, null=True) status = models.CharField(max_length=7,choices=SETTING_STATUS_CHOICES) class Meta: ordering = ('index',) verbose_name = u'你好嗎?' verbose_name_plural = u'你們都好嗎?' def __unicode__(self): return self.zone_name However when i run manage.py syncdb, the following errors throws: File "E:\pythonroot\myproject\..\myproject\myapp\models.py", line 19 SyntaxError: Non-ASCII character '\xe4' in file E:\pythonroot\myproject\..\myproject\myapp\models.py on line 19, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details It seems that manage.py cannot process non-ascii character in my verbose_name. Anything i have done wrong? Thank you.
[ "You have to specify an encoding. Add the following line as the first line of your models.py file.\n# encoding: utf-8\n\nUpdate\nThe OP has edited his question to say that the \"models.py is encoded in Unicode\". Then the error is strange. It works for me using Django 1.2.1, Python 2.6.2 on Ubuntu Jaunty. \nUpdate ...
[ 5 ]
[]
[]
[ "django", "manage.py", "python", "syncdb" ]
stackoverflow_0003656119_django_manage.py_python_syncdb.txt
Q: Mac OS X: Trouble with Local Django + PyDev install working with remote MySQL I've got PyDev installed in Eclipse. I'm trying to play with Django. I'm got a remote MySQL database set up. I would really like to not install MySQL on my MacBook. Trying to set up the MySQL plugin for python, I get (djangotest)jeebus:MySQL-python-1.2.3 blah$ python setup.py clean sh: mysql_config: command not found Traceback (most recent call last): File "setup.py", line 15, in <module> metadata, options = get_config() File "/Users/nali/djangotest/temp/MySQL-python-1.2.3/setup_posix.py", line 43, in get_config libs = mysql_config("libs_r") File "/Users/nali/djangotest/temp/MySQL-python-1.2.3/setup_posix.py", line 24, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) EnvironmentError: mysql_config not found The error makes sense since I don't have any of MySQL or related tools set up. Are there an Snow Leopard MySQL libraries I can use to satisfy the need for mysql_config without actually installing MySQL? A: In a word, no. You need the client side libraries of MySQL but you don't need the server components. Most package managers provide each as separate packages. MySQL-python, AKA MySQLdb, is not a client module per se. It is a wrapper or interface between Python programs and the standard MySQL client libraries. MySQLdb conforms to the Python standard DB API. There are other conforming adapters implemented for other database managers. Using the common API makes it much easier to write database-independent code in Python; the adapters handle (much of) the messy differences among the various database client libraries. Thus, you do need to install MySQL client libraries; there are several ways to do this: the easiest options are probably downloading prebuilt libraries from mysql.com or you can use a package manager, like MacPorts, to install them and other dependencies. For OS X 10.6, because of the potential gotchas in getting all of the needed pieces installed in a compatible manner, I highly recommend using a total solution from MacPorts to get Python MySQL support. See the answer here for more details. MacPorts even provides a Django port. A: Why not use macports instead. It also has a gui called porticus. A: pip install mysql-python ... or use easy_install if you don't have pip.
Mac OS X: Trouble with Local Django + PyDev install working with remote MySQL
I've got PyDev installed in Eclipse. I'm trying to play with Django. I'm got a remote MySQL database set up. I would really like to not install MySQL on my MacBook. Trying to set up the MySQL plugin for python, I get (djangotest)jeebus:MySQL-python-1.2.3 blah$ python setup.py clean sh: mysql_config: command not found Traceback (most recent call last): File "setup.py", line 15, in <module> metadata, options = get_config() File "/Users/nali/djangotest/temp/MySQL-python-1.2.3/setup_posix.py", line 43, in get_config libs = mysql_config("libs_r") File "/Users/nali/djangotest/temp/MySQL-python-1.2.3/setup_posix.py", line 24, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) EnvironmentError: mysql_config not found The error makes sense since I don't have any of MySQL or related tools set up. Are there an Snow Leopard MySQL libraries I can use to satisfy the need for mysql_config without actually installing MySQL?
[ "In a word, no. You need the client side libraries of MySQL but you don't need the server components. Most package managers provide each as separate packages.\nMySQL-python, AKA MySQLdb, is not a client module per se. It is a wrapper or interface between Python programs and the standard MySQL client libraries. M...
[ 1, 0, 0 ]
[]
[]
[ "django", "mysql", "pydev", "python" ]
stackoverflow_0003654350_django_mysql_pydev_python.txt
Q: Django / Python, using iteritems() to update database gives strange error: "dictionary update sequence element #0 has length 4; 2 is required" I'm trying to do a Django database save from a form where I don't have to manually specify the fieldnames (as I do in the 2nd code block), the way I am trying to do this is as below (1st code block) as I got the tip from another S.O. post. However, when I try this I get the error "dictionary update sequence element #0 has length 4; 2 is required", I even tried it, as below, with just a testdict dictionary, instead of the request.POST, but am still getting the error.. obviously the field value is fine since it works in the 2nd code block, so I am stumped as to why this is happening, would appreciate if anyone can shed any light on this for me... thanks trying it this way gives the error: testdict = {'name':'account_username','value':'vvvvvv'} for name, value in testdict.iteritems(): if name != '' and name != 'top_select': b = Twitter(**dict((name, value))) b.save() >>> dictionary update sequence element #0 has length 4; 2 is required but this works fine: b = Twitter(account_username='vvvvvv') b.save() A: Not sure what you are trying to do, but maybe you want something like this b = Twitter(**{name: value}) But to get the equivalent to Twitter(account_username='vvvvvv') you would need something like this Twitter(**{testdict['name'], testdict['value']}) where testdict would only contain a single entity to send to Twitter() Then the code would look more like this test_twits = [{'name':'account_username','value':'vvvvvv'}, {'name':'account_username','value':'wwwwww'}, ] for twit in test_twits: name = twit['name'] value = twit['value'] if name != '' and name != 'top_select': b = Twitter(**{name: value}) b.save() A: Correct me if I am wrong. From your second code snippet I take it that the Twitter class needs account_username as a keyword argument. When you are iterating through the dictionary using iteritems you are passing the name - i.e. the key of the dictionary as the keyword argument to the class. Isn't this wrong? The dictionary's keys are name and value, _not _ account_username. I believe you need the one of values from the dictionary to be passed as keyword argument, not one of the keys. A: just do this: dict(((name, value),)) 'dict' takes a sequence of key, value tuples whereas you are giving it one key, value tuple. The reason it says '... sequence element #0 has length 4' is because the key 'name' from testdict has a length of 4.
Django / Python, using iteritems() to update database gives strange error: "dictionary update sequence element #0 has length 4; 2 is required"
I'm trying to do a Django database save from a form where I don't have to manually specify the fieldnames (as I do in the 2nd code block), the way I am trying to do this is as below (1st code block) as I got the tip from another S.O. post. However, when I try this I get the error "dictionary update sequence element #0 has length 4; 2 is required", I even tried it, as below, with just a testdict dictionary, instead of the request.POST, but am still getting the error.. obviously the field value is fine since it works in the 2nd code block, so I am stumped as to why this is happening, would appreciate if anyone can shed any light on this for me... thanks trying it this way gives the error: testdict = {'name':'account_username','value':'vvvvvv'} for name, value in testdict.iteritems(): if name != '' and name != 'top_select': b = Twitter(**dict((name, value))) b.save() >>> dictionary update sequence element #0 has length 4; 2 is required but this works fine: b = Twitter(account_username='vvvvvv') b.save()
[ "Not sure what you are trying to do, but maybe you want something like this\nb = Twitter(**{name: value})\n\nBut to get the equivalent to Twitter(account_username='vvvvvv') you would need something like this\nTwitter(**{testdict['name'], testdict['value']})\n\nwhere testdict would only contain a single entity to se...
[ 1, 0, 0 ]
[]
[]
[ "dictionary", "django", "loops", "python" ]
stackoverflow_0003655700_dictionary_django_loops_python.txt
Q: Django + IIS +? I need to run a django app on windows under either IIS6 or IIS7 (yes, I don't know the exact requirements right now). What I did: I've tried to set up a working environment on my windows 7 (so its IIS7 for now) machine. I've followed the instructions at django trac using PyISAPIe. What came out of it: Apparently, either I am doing something completely wrong, or the pyisapie.py handler, that I am supposed to put into django's core/handlers is very much incompatible with stable django (1.2). There are at least two things that it "does wrong": it attempts to invoke request_started and request_finished signals using the outdated signatures, - I've fixed those. its http.HttpRequest subclass (PyISAPIeRequest) doesn't conform to the HttpRequest interface, - path_info is left out. I suppose, it comes out of the environment, analogous to how the WSGIRequest does it. So I've hacked this in too. I really have no idea what else will fail on me (apparently, it also has a problem with multipart forms) and, quite frankly, I am not prepared to accept a solution that might die on me at any moment in production (although, on a side note, I'd love to make the whole IIS+Django thing actually work). Are there any other ways to run django on windows? Perhaps I can use a standalone server, like flup and use IIS as a reverse proxy (though, I don't know if it is possible at all)? I need the windows+basic authentication, - the application is supposed to use the remote user authentication backend, though authentication is not the sole reason why IIS has to be used. I can't use another machine and I am against installing a full-blown web server (I could technically use apache+mod_wsgi). Performance/high availability will not be an issue, but one thing is certain, - large file uploads should be handled correctly (see above about multipart forms). A: This is a cut and paste from my response on the mailing list. I suppose either here or there would be fine for further questions. http://groups.google.com/group/pyisapie/browse_thread/thread/af7dac9398336e67?hl=en_US The module isn't supported at all and the Django folks didn't get around to including it in the core, so it shouldn't be considered when trying to get PyISAPIe+Django working. If you look in the Examples folder, you'll see some info on how to get it all set up with WSGI only, which is a better long-term solution.
Django + IIS +?
I need to run a django app on windows under either IIS6 or IIS7 (yes, I don't know the exact requirements right now). What I did: I've tried to set up a working environment on my windows 7 (so its IIS7 for now) machine. I've followed the instructions at django trac using PyISAPIe. What came out of it: Apparently, either I am doing something completely wrong, or the pyisapie.py handler, that I am supposed to put into django's core/handlers is very much incompatible with stable django (1.2). There are at least two things that it "does wrong": it attempts to invoke request_started and request_finished signals using the outdated signatures, - I've fixed those. its http.HttpRequest subclass (PyISAPIeRequest) doesn't conform to the HttpRequest interface, - path_info is left out. I suppose, it comes out of the environment, analogous to how the WSGIRequest does it. So I've hacked this in too. I really have no idea what else will fail on me (apparently, it also has a problem with multipart forms) and, quite frankly, I am not prepared to accept a solution that might die on me at any moment in production (although, on a side note, I'd love to make the whole IIS+Django thing actually work). Are there any other ways to run django on windows? Perhaps I can use a standalone server, like flup and use IIS as a reverse proxy (though, I don't know if it is possible at all)? I need the windows+basic authentication, - the application is supposed to use the remote user authentication backend, though authentication is not the sole reason why IIS has to be used. I can't use another machine and I am against installing a full-blown web server (I could technically use apache+mod_wsgi). Performance/high availability will not be an issue, but one thing is certain, - large file uploads should be handled correctly (see above about multipart forms).
[ "This is a cut and paste from my response on the mailing list. I suppose either here or there would be fine for further questions.\nhttp://groups.google.com/group/pyisapie/browse_thread/thread/af7dac9398336e67?hl=en_US\n\nThe module isn't supported at all and the Django folks didn't get around to including it in th...
[ 2 ]
[]
[]
[ "django", "iis_6", "iis_7", "python", "windows" ]
stackoverflow_0003651648_django_iis_6_iis_7_python_windows.txt
Q: reading .bash_history file through python script I want to write a python script which reads the '.bash_history' file and prints the statistics. Also, I would like to print the command which was used the most. I was able to read the bash history through the terminal but I'm not able to do it through python programming. Can someone please help me with how to start with it? A: http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files A: Something beginning with... #!/usr/bin/env python import os homedir = os.path.expanduser('~') bash_history = open(homedir+"/.bash_history", 'r') Now we have the file open... what operations do you want to do now? Print the contents of the file. bash_history_text = bash_history.read() print bash_history_text Turn the string into an array of lines... import re splitter = re.compile(r'\n') bash_history_array = splitter.split(bash_history_text) Now you can do array sorting, filtering etc. to your hearts content. A: Just some basic ideas, with important python functions for that: read the file; open go through all lines and sum up the number of occurences of a line; for, dict in case you only want to check parts of a command (for example treat cd XY and cd .. the same), normalize the lines by removing the command arguments after the space; split sort the sums and print out the command with the highest sum.
reading .bash_history file through python script
I want to write a python script which reads the '.bash_history' file and prints the statistics. Also, I would like to print the command which was used the most. I was able to read the bash history through the terminal but I'm not able to do it through python programming. Can someone please help me with how to start with it?
[ "http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files\n", "Something beginning with...\n#!/usr/bin/env python\n\nimport os\n\nhomedir = os.path.expanduser('~')\nbash_history = open(homedir+\"/.bash_history\", 'r')\n\nNow we have the file open... what operations do you want to do now?\nPrint ...
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003656500_python.txt
Q: How to reset global variable in python? SOME_VARIABLE = [] def some_fun: append in SOME_VARIABLE s = [] s = SOME_VARIABLE SOME_VARIABLE = [] // Not setting to empty list. return s How to reset SOME_VARIABLE to empty. A: If you read a variable, Python looks for it in the entire scope chain. This mean that: GLOB_VAR = "Some string" def some_fun(): print GLOB_VAR will print Some string Now, if you write to a variable, Python looks for it in the local scope, and if it cannot find a variable with the name you gave at the local level, then it creates one. This means that in your example, you have created a variable named SOME_VARIABLE local to your some_fun function, instead of updating the global SOME_VARIABLE. This is a classic python gotcha. If you want to write to your global, you have to explicitly tell Python that you are talking about a global variable that already exists. To do so, you need to use the global keyword. So, the following: GLOB_VAR = "Some string" def some_fun(): global GLOB_VAR GLOB_VAR = "Some other string" some_fun() print GLOB_VAR will print Some other string. Note: I see it as a way of encouraging people to keep global variables read-only, or at least to think about what they're doing. The behaviour is the same (just a bit more surprising) when you try to read first and then write to a global. The following: GLOB_VAR = False def some_fun(): if GLOB_VAR: GLOB_VAR = False some_fun() will raise: Traceback (most recent call last): File "t.py", line 7, in <module> some_fun() File "t.py", line 4, in some_fun if GLOB_VAR: UnboundLocalError: local variable 'GLOB_VAR' referenced before assignment because since we will modify GLOB_VAR, it is considered a local variable. Update: Ely Bendersky has a related in-depth post about this that is worth a read for more formal details. A: You need to tell the interpreter that you are talking about a global variable: def some_fun: global SOME_VARIABLE ... SOME_VARIABLE = [] A: if you don't need the SOME_VARIABLE anymore you could use: del SOME_VARIABLE if you want a empty list: del SOME_VARIABLE[:] A: SOME_VARIABLE is global, so rebinding it won't take effect unless you use global. But since it's a mutable object, just mutate it appropriately. del SOME_VARIABLE[:]
How to reset global variable in python?
SOME_VARIABLE = [] def some_fun: append in SOME_VARIABLE s = [] s = SOME_VARIABLE SOME_VARIABLE = [] // Not setting to empty list. return s How to reset SOME_VARIABLE to empty.
[ "If you read a variable, Python looks for it in the entire scope chain. This mean that:\nGLOB_VAR = \"Some string\"\n\ndef some_fun():\n print GLOB_VAR\n\nwill print Some string\nNow, if you write to a variable, Python looks for it in the local scope, and if it cannot find a variable with the name you gave at th...
[ 11, 8, 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003657163_django_python.txt
Q: python - edit a text file I am using python and i want to delete some characters from the end of a text file. The file is big a and i dont want to read all of it and duplicate the interesting part. My best guess is that i need to change the file size.... can anyone help me please thanks A: I guess that you need to open the file, seek to the end, delete characters and save it. seek ( http://docs.python.org/library/stdtypes.html#file.seek ) accepts negative values (e.g. f.seek(-3, os.SEEK_END) sets the position to the third to last), so that you can easily go to the end of your file. http://docs.python.org/library/stdtypes.html#file-objects - this link may be a good starting point.
python - edit a text file
I am using python and i want to delete some characters from the end of a text file. The file is big a and i dont want to read all of it and duplicate the interesting part. My best guess is that i need to change the file size.... can anyone help me please thanks
[ "I guess that you need to open the file, seek to the end, delete characters and save it.\nseek ( http://docs.python.org/library/stdtypes.html#file.seek ) accepts negative values (e.g. f.seek(-3, os.SEEK_END) sets the position to the third to last), so that you can easily go to the end of your file.\nhttp://docs.pyt...
[ 2 ]
[]
[]
[ "python", "text", "text_files" ]
stackoverflow_0003657109_python_text_text_files.txt
Q: Python: Reading Excel 2007 files under Linux environment I want to read excel 2007 files via python on my Ubuntu server. I have already checked http://www.python-excel.org/ xlwt and xlrd but it seems like none of them can read excel 2007 files. What would be your recommendation? Regards A: Try pyXLSX. There is also openpyxl which can also read / write .xlsx files.
Python: Reading Excel 2007 files under Linux environment
I want to read excel 2007 files via python on my Ubuntu server. I have already checked http://www.python-excel.org/ xlwt and xlrd but it seems like none of them can read excel 2007 files. What would be your recommendation? Regards
[ "Try pyXLSX. There is also openpyxl which can also read / write .xlsx files.\n" ]
[ 3 ]
[]
[]
[ "excel", "excel_2007", "openpyxl", "python" ]
stackoverflow_0003656911_excel_excel_2007_openpyxl_python.txt
Q: Best way to know that my Python Code base is using PyXML or not? I have a python code base and want to know whether pyxml is really used in the code any where. The python version i have is 2.6. pyxml's last binary distribution ended with 2.4 python version. Any clues or ideas to judge the code whether it is free of pyxml 0.8.4 on python 2.6 ? Thanks in Advance. A: When you run python -v script.py Python prints all the modules imported to stderr. You can then inspect that output for the string "import pyxml": python -v script.py 2>&1 | grep "import pyxml" This works even if script.py imported pyxml in an unconventional way, such as __import__('pyxml'). It even works if the import were buried inside of a function: def foo(): import pyxml ... provided that function eventually gets called. A: grep your codebase for from xml import or import xml. A: Search pyxml.py (or .pyc or similar). Rename it to something else say pyxmltest.py. See if it something crashes or if you want to be more sure and more gentle. Put in the same place file pyxml.py: print('pyxml imported') import pyxmltest.py After test remove the test file and rename back the original. Alternatively you could put the same print in the beginning of the actual module if it is written in python (plain .py) Also some editors like IDLE has search in files function where you can search for pyxml. It works recursively in subdirectories.
Best way to know that my Python Code base is using PyXML or not?
I have a python code base and want to know whether pyxml is really used in the code any where. The python version i have is 2.6. pyxml's last binary distribution ended with 2.4 python version. Any clues or ideas to judge the code whether it is free of pyxml 0.8.4 on python 2.6 ? Thanks in Advance.
[ "When you run \npython -v script.py\n\nPython prints all the modules imported to stderr. You can then inspect that output for the string \"import pyxml\":\npython -v script.py 2>&1 | grep \"import pyxml\"\n\nThis works even if script.py imported pyxml in an unconventional way, such as __import__('pyxml').\nIt even ...
[ 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003657165_python.txt
Q: Django / Python, Make database save function re-usable (so that it takes modelname and appname from strings), using contenttypes or some other method? I want to make some functions that are re-usable by any model so that I can specify the appname and model in string format and then use this to import that model and make calls to it such as creating database fields, updating, deleting, etc... I had thought I could do this using contenttypes in Django but am trying this, as below and am getting the error message "'ContentType' object is not callable": from django.contrib.contenttypes.models import ContentType instancemodelname = ContentType.objects.get(app_label="myappname", model="mymodelname") b = instancemodelname(account_username='testtestest') b.save() >>>>'ContentType' object is not callable I would appreciate any advice on the proper way to do this, thanks A: The following code will work: instancemodelname = ContentType.objects.get(app_label="myappname", model="mymodelname") b = instancemodelname.model_class()(account_username='testtestest') b.save() That said I am not entirely convinced that contenttypes is the best way to achieve what you want. A: Don't use the ContentType model. There's a function for exactly this use case that doesn't genereate a database hit: from django.db.models import get_model mymodel = get_model("myappname", "mymodelname") b = mymodel(account_username='testtestest') b.save()
Django / Python, Make database save function re-usable (so that it takes modelname and appname from strings), using contenttypes or some other method?
I want to make some functions that are re-usable by any model so that I can specify the appname and model in string format and then use this to import that model and make calls to it such as creating database fields, updating, deleting, etc... I had thought I could do this using contenttypes in Django but am trying this, as below and am getting the error message "'ContentType' object is not callable": from django.contrib.contenttypes.models import ContentType instancemodelname = ContentType.objects.get(app_label="myappname", model="mymodelname") b = instancemodelname(account_username='testtestest') b.save() >>>>'ContentType' object is not callable I would appreciate any advice on the proper way to do this, thanks
[ "The following code will work:\ninstancemodelname = ContentType.objects.get(app_label=\"myappname\", model=\"mymodelname\")\nb = instancemodelname.model_class()(account_username='testtestest')\nb.save()\n\nThat said I am not entirely convinced that contenttypes is the best way to achieve what you want. \n", "Don'...
[ 2, 1 ]
[]
[]
[ "code_reuse", "content_type", "django", "python" ]
stackoverflow_0003657076_code_reuse_content_type_django_python.txt
Q: inverted comma and string in python I'm kinda' new to python, but I have already written many programs including some like download-managers, games and text-editors which require a lot of string manipulation. For representing a string literal I use either single or double inverted commas.. whichever comes to my mind first at that time. Although I haven't yet faced any trouble. My question: is there any purpose for which python allows both or is it just for compatibility, usability etc? A: There is no difference between "string" and 'string' in Python, so, as you suggest, it's just for usability. >>> 'string' == "string" True You can also use triple quotes for multiline strings: >>> mystring = """Hello ... World!""" >>> mystring 'Hello\nWorld!' Another trick is that adjacent string literals are automatically concatenated: >>> mystring = "Hello" 'World!' >>> mystring 'HelloWorld!' There are also string prefixes which you can read about in the documentation. A: It means you can easily have a string with either single or double quotes in it without needing any escape characters. So you can do: a = 'The knights who say "ni!"' b = "We're knights of the Round Table, we dance whene'er we're able." A: Just for compatibility and usability. It is sometimes useful when you have one of them embedded in the string, so I would use "Who's there?" compared to 'He says: "Hello"'. The other option is of course triple quoted strings, like """This is a long string that can contain single quotations like ' or ". It can also span multiple lines""" which is equal to '''This is a long string that can contain single quotations like ' or ". It can also span multiple lines'''
inverted comma and string in python
I'm kinda' new to python, but I have already written many programs including some like download-managers, games and text-editors which require a lot of string manipulation. For representing a string literal I use either single or double inverted commas.. whichever comes to my mind first at that time. Although I haven't yet faced any trouble. My question: is there any purpose for which python allows both or is it just for compatibility, usability etc?
[ "There is no difference between \"string\" and 'string' in Python, so, as you suggest, it's just for usability.\n>>> 'string' == \"string\"\nTrue\n\nYou can also use triple quotes for multiline strings:\n>>> mystring = \"\"\"Hello\n... World!\"\"\"\n>>> mystring\n'Hello\\nWorld!'\n\nAnother trick is that adjacent s...
[ 5, 4, 1 ]
[]
[]
[ "literals", "python", "string" ]
stackoverflow_0003657792_literals_python_string.txt
Q: Does "Find-Replace whole word only" exist in python? Does "Find-Replace whole word only" exist in python? e.g. "old string oldstring boldstring bold" if i want to replace 'old' with 'new', new string should look like, "new string oldstring boldstring bold" can somebody help me? A: >>> import re >>> s = "old string oldstring boldstring bold" >>> re.sub(r'\bold\b', 'new', s) 'new string oldstring boldstring bold' This is done by using word boundaries. Needless to say, this regex is not Python-specific and is implemented in most regex engines. A: you need the following regex: \bold\b
Does "Find-Replace whole word only" exist in python?
Does "Find-Replace whole word only" exist in python? e.g. "old string oldstring boldstring bold" if i want to replace 'old' with 'new', new string should look like, "new string oldstring boldstring bold" can somebody help me?
[ ">>> import re\n>>> s = \"old string oldstring boldstring bold\"\n>>> re.sub(r'\\bold\\b', 'new', s)\n'new string oldstring boldstring bold'\n\nThis is done by using word boundaries. Needless to say, this regex is not Python-specific and is implemented in most regex engines.\n", "you need the following regex:\n\\...
[ 44, 5 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003658215_python_regex.txt
Q: Automation of Open Zoom How would I automate the process of deploying a gigantic jpeg on a web server and then generate the necessary files to load the image up on the frontend site in OpenZoom? I'm working in php but any shell/bash/python scripts are welcome A: http://github.com/stinie/deepzoom.php/blob/master/php5.2/tests/index.php Using this library one can generate and display Deep Zoom Images using purely php on the fly =]
Automation of Open Zoom
How would I automate the process of deploying a gigantic jpeg on a web server and then generate the necessary files to load the image up on the frontend site in OpenZoom? I'm working in php but any shell/bash/python scripts are welcome
[ "http://github.com/stinie/deepzoom.php/blob/master/php5.2/tests/index.php\nUsing this library one can generate and display Deep Zoom Images using purely php on the fly =]\n" ]
[ 0 ]
[]
[]
[ "bash", "deepzoom", "python" ]
stackoverflow_0003658023_bash_deepzoom_python.txt
Q: How Do You Predict A Non-Linear Script's Run Time? I wrote this simple code in python to calculate a given number of primes. The question I want to ask is whether or not it's possible for me to write a script that calculates how long it will take, in terms of processor cycles, to execute this? If yes then how? primes = [2] pstep = 3 count = 1 def ifprime (a): """ Checking if the passed number is prime or not""" global primes for check in primes: if (a%check) == 0: return False return True while 1000000000>= count: if ifprime(pstep): primes.append (pstep) print pstep count += 1 pstep += 1 The interesting thing about this problem is that whether or not I find primes after x cycles of incrementation is something nearly impossible to predict. Moreover, there's recursion happening in this scenario since the larger 'prime' list grow the longer it will take to execute this function. Any tips? A: I think you would have to use an approximation of the distribution of primes, a la PNT which (I think) states that between 1 and x you'll have approximately x/ln(x) primes (ln being natural log). So given rough estimates of the time taken for a single iteration, you should be able to create an estimate. You have approximately x/ln(x) primes in your list. Your main code block (inside the while loop) has constant time (effectively)...so: t(x) ~ x/ln(x) * a + b + t(x-1) where t(x) is the time taken up to and including iteration x, a is the time taken to check each prime in the list (modulous operation), and b is the 'constant' time of the main loop. I faintly remember there is a way to convert such recursive functions to linear ones ;) A: If you want to predict the time an arbitrary process needs until it is finished, you can't do that, as that is basically the problem behind the Halting Problem. In special cases you can estimate the time your script will take, for example if you know that it is generated in a way that doesn't allow loops. In your special case of finding primes, it is even harder to guess the time it will take before running the process, as there is only a lower bound for the number of primes within an intervall, but that doesn't help finding them. A: Well, if you are on linux you can use 'time' command and then parse it's result. For your problem I would do the timing for 1000s of large primes of different size and would draw a chart, so it would be easy to analize. A: Well, there is a large branch of theoretical computer science -- complexity theory -- dedicated to just this sort of problem. The general problem (of deciding on whether a code will finish for arbitrary input) you have here is what is called "NP-complete" and is therefore very hard. But in this case you probably have two options. The first is to use brute force. Run timeit for isprime(a) for a=1, 2, 3, 4, ..., plot the graph of the times, and try to see if it looks like something obvious: a^2, a log a, whatever. The right -- but harder -- answer is to analyze your algorithm and see if you can work out how many operations it takes for a "typical case". A: When you call isprime(pstep) you are looping pstep * ln(pstep) times, if you have a prime, of which the probability is 1/ln(pstep). So the cost of testing the primes is proportional to step. Unknown is the cost of testing the composites, because we don't know the average lowest factor of the composites between 2 and N. If we ignore it, assuming it is dominated by the cost for the primes, we get a total cost of SUM(pstep) for pstep = 3 to N+3, which is about proportional to N**2. You can reduce this to N**1.5 by cutting off the loop in isprime() when checked > sqrt(a).
How Do You Predict A Non-Linear Script's Run Time?
I wrote this simple code in python to calculate a given number of primes. The question I want to ask is whether or not it's possible for me to write a script that calculates how long it will take, in terms of processor cycles, to execute this? If yes then how? primes = [2] pstep = 3 count = 1 def ifprime (a): """ Checking if the passed number is prime or not""" global primes for check in primes: if (a%check) == 0: return False return True while 1000000000>= count: if ifprime(pstep): primes.append (pstep) print pstep count += 1 pstep += 1 The interesting thing about this problem is that whether or not I find primes after x cycles of incrementation is something nearly impossible to predict. Moreover, there's recursion happening in this scenario since the larger 'prime' list grow the longer it will take to execute this function. Any tips?
[ "I think you would have to use an approximation of the distribution of primes, a la PNT which (I think) states that between 1 and x you'll have approximately x/ln(x) primes (ln being natural log). So given rough estimates of the time taken for a single iteration, you should be able to create an estimate.\nYou have ...
[ 2, 2, 0, 0, 0 ]
[]
[]
[ "math", "python", "recursion" ]
stackoverflow_0003657495_math_python_recursion.txt
Q: Django model per table vs model per select I am working with Django for a while and now that my "tree" and whole DB is filled with data (note: existing database), I was wondering if the "one model per table" is really better at this point than "one model per select". I have got one table - objtree. This is the place where I have all nodes (brands, categories, tags, etc.) stored. As you can imagine it is heavily used in my administration. Today I had to add another foreign key for another table, but I have already 2 Foreign keys there. The problem is that I use this model for almost everything, BUT the foreign keys are used rarely, not to mention the third one that would be used this one time. Since each of these tables have 20k+ (minimum) rows and the foreign keys are used rarely, I wonder if it wouldnt be better to use "one model class per select" - speed wise. Would this approach affect the speed at all? So far it worked fine for me (model per table), but isnt that kind of an overkill for such large DB? Any opinion is appreciated. Regards Edit: Here is the model. The 3 foreign keys are needed rarely, but as it is now, they are selected anyway, even if I dont need them (maybe there is an easy way to specify which of them I dont want to use when doing e.g. Model.objects.all()). So the question is if it would be better to have lets say 3 models, where I would use the foreign keys respectively. Would that affect the speed? Or is bad approach? Maybe I am doing something wrong, I dont know. class Objtree(models.Model): node_id = models.AutoField( primary_key = True ) type_id = models.IntegerField() parent_id = models.IntegerField() sort_order = models.IntegerField( null = True, blank = True ) name = models.CharField( unique = True, max_length = 255, blank = True ) lft = models.IntegerField() rgt = models.IntegerField() depth = models.IntegerField() added_on = models.DateTimeField() updated_on = models.DateTimeField() status = models.IntegerField() point_to = models.IntegerField( null = True, blank = True ) node = models.ForeignKey( 'Objtree_labels', verbose_name = 'Objtree_labels', to_field = 'node_id' ) specs = models.ForeignKey( 'OptionSpecs', verbose_name = 'OptionSpecs', db_column = 'node_id', null = True, blank = True ) ct = models.ForeignKey( 'CategoryTemplate', verbose_name = 'CategoryTemplate', db_column = 'node_id', to_field = 'group_id', null = True, blank = True ) A: I was wondering if the "one model per table" is really better at this point than "one model per select". What is "model per select"? It sounds like your model is wrong. The problem is that I use this model for almost everything, BUT the foreign keys are used rarely, not to mention the third one that would be used this one time. What are you doing? This sounds like you're not doing the database modeling part of the job correctly. It sounds -- from this quick description -- like you're throwing attributes at models in a haphazard way. There's no sensible alternative to "model per table". The questions you should be asking are "What am I modeling?" "What is this real-world object?" And "What is the relational database description of this thing?" if it would be better to have lets say 3 models, where I would use the foreign keys respectively? Three models means three copies of the tree structure, each with just one foreign key. The essential questions, however, still remain. What is this? Are these three separate things? Are these three aspects of one thing? These are not technical questions, but reality questions. Don't fret over performance. Fret over modeling reality with a great deal of fidelity. 'Objtree_labels', 'OptionSpecs', 'CategoryTemplate' -- what real-world objects are these? Labels -- usually don't exist in the real world. Option specs may be something tangible. A category template doesn't sound like a real thing. Would that affect the speed? Never. One table with lots of foreign keys and three tables with one foreign key each will be largely indistinguishable in speed. Unless, of course, you are regularly having to match values between separate tables, then the "join" among separate tables will incur some cost. But if the three values are truly independent -- three separate things -- they must be in separate tables to reflect the fact that they are different kinds of things.
Django model per table vs model per select
I am working with Django for a while and now that my "tree" and whole DB is filled with data (note: existing database), I was wondering if the "one model per table" is really better at this point than "one model per select". I have got one table - objtree. This is the place where I have all nodes (brands, categories, tags, etc.) stored. As you can imagine it is heavily used in my administration. Today I had to add another foreign key for another table, but I have already 2 Foreign keys there. The problem is that I use this model for almost everything, BUT the foreign keys are used rarely, not to mention the third one that would be used this one time. Since each of these tables have 20k+ (minimum) rows and the foreign keys are used rarely, I wonder if it wouldnt be better to use "one model class per select" - speed wise. Would this approach affect the speed at all? So far it worked fine for me (model per table), but isnt that kind of an overkill for such large DB? Any opinion is appreciated. Regards Edit: Here is the model. The 3 foreign keys are needed rarely, but as it is now, they are selected anyway, even if I dont need them (maybe there is an easy way to specify which of them I dont want to use when doing e.g. Model.objects.all()). So the question is if it would be better to have lets say 3 models, where I would use the foreign keys respectively. Would that affect the speed? Or is bad approach? Maybe I am doing something wrong, I dont know. class Objtree(models.Model): node_id = models.AutoField( primary_key = True ) type_id = models.IntegerField() parent_id = models.IntegerField() sort_order = models.IntegerField( null = True, blank = True ) name = models.CharField( unique = True, max_length = 255, blank = True ) lft = models.IntegerField() rgt = models.IntegerField() depth = models.IntegerField() added_on = models.DateTimeField() updated_on = models.DateTimeField() status = models.IntegerField() point_to = models.IntegerField( null = True, blank = True ) node = models.ForeignKey( 'Objtree_labels', verbose_name = 'Objtree_labels', to_field = 'node_id' ) specs = models.ForeignKey( 'OptionSpecs', verbose_name = 'OptionSpecs', db_column = 'node_id', null = True, blank = True ) ct = models.ForeignKey( 'CategoryTemplate', verbose_name = 'CategoryTemplate', db_column = 'node_id', to_field = 'group_id', null = True, blank = True )
[ "\nI was wondering if the \"one model per table\" is really better at this point than \"one model per select\".\n\nWhat is \"model per select\"? It sounds like your model is wrong.\n\nThe problem is that I use this model for almost everything, BUT the foreign keys are used rarely, not to mention the third one that ...
[ 3 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0003658944_django_django_models_python.txt
Q: Adding objects to queue without interruption I would like to put two objects into a queue, but I've got to be sure the objects are in both queues at the same time, therefore it should not be interrupted in between - something like an atomic block. Does some one have a solution? Many thanks... queue_01.put(car) queue_02.put(bike) A: You could use a Condition object. You can tell the threads to wait with cond.wait(), and signal when the queues are ready with cond.notify_all(). See, for example, Doug Hellman's wonderful Python Module of the Week blog. His code uses multiprocessing; here I've adapted it for threading: import threading import Queue import time def stage_1(cond,q1,q2): """perform first stage of work, then notify stage_2 to continue""" with cond: q1.put('car') q2.put('bike') print 'stage_1 done and ready for stage 2' cond.notify_all() def stage_2(cond,q): """wait for the condition telling us stage_1 is done""" name=threading.current_thread().name print 'Starting', name with cond: cond.wait() print '%s running' % name def run(): # http://www.doughellmann.com/PyMOTW/multiprocessing/communication.html#synchronizing-threads-with-a-condition-object condition=threading.Condition() queue_01=Queue.Queue() queue_02=Queue.Queue() s1=threading.Thread(name='s1', target=stage_1, args=(condition,queue_01,queue_02)) s2_clients=[ threading.Thread(name='stage_2[1]', target=stage_2, args=(condition,queue_01)), threading.Thread(name='stage_2[2]', target=stage_2, args=(condition,queue_02)), ] # Notice stage2 processes are started before stage1 process, and yet they wait # until stage1 finishes for c in s2_clients: c.start() time.sleep(1) s1.start() s1.join() for c in s2_clients: c.join() run() Running the script yields Starting stage_2[1] Starting stage_2[2] stage_1 done and ready for stage 2 <-- Notice that stage2 is prevented from running until the queues have been packed. stage_2[2] running stage_2[1] running A: To atomically add to two different queues, acquire the locks for both queues first. That's easiest to do by making a subclass of Queue that uses recursive locks. import Queue # Note: module renamed to "queue" in Python 3 import threading class MyQueue(Queue.Queue): "Make a queue that uses a recursive lock instead of a regular lock" def __init__(self): Queue.Queue.__init__(self) self.mutex = threading.RLock() queue_01 = MyQueue() queue_02 = MyQueue() with queue_01.mutex: with queue_02.mutex: queue_01.put(1) queue_02.put(2)
Adding objects to queue without interruption
I would like to put two objects into a queue, but I've got to be sure the objects are in both queues at the same time, therefore it should not be interrupted in between - something like an atomic block. Does some one have a solution? Many thanks... queue_01.put(car) queue_02.put(bike)
[ "You could use a Condition object. You can tell the threads to wait with cond.wait(), and signal when the queues are ready with cond.notify_all(). See, for example, Doug Hellman's wonderful Python Module of the Week blog. His code uses multiprocessing; here I've adapted it for threading:\nimport threading\nimport Q...
[ 1, 0 ]
[]
[]
[ "atomic", "locking", "python", "queue" ]
stackoverflow_0003658511_atomic_locking_python_queue.txt
Q: Numpy matrix operations I want to compute the following values for all i and j: M_ki = Sum[A_ij - A_ik - A_kj + A_kk, 1 <= j <= n] How can I do it using Numpy (Python) without an explicit loop? Thanks! A: Here is a general strategy for solving this kind of problem. First, write a small script, with the loop written explicitly in two different functions, and a test at the end making sure that the two functions are exactly the same: import numpy as np from numpy import newaxis def explicit(a): n = a.shape[0] m = np.zeros_like(a) for k in range(n): for i in range(n): for j in range(n): m[k,i] += a[i,j] - a[i,k] - a[k,j] + a[k,k] return m def implicit(a): n = a.shape[0] m = np.zeros_like(a) for k in range(n): for i in range(n): for j in range(n): m[k,i] += a[i,j] - a[i,k] - a[k,j] + a[k,k] return m a = np.random.randn(10,10) assert np.allclose(explicit(a), implicit(a), atol=1e-10, rtol=0.) Then, vectorize the function step by step by editing implicit, running the script at each step to make sure that they continue staying the same: Step 1 def implicit(a): n = a.shape[0] m = np.zeros_like(a) for k in range(n): for i in range(n): m[k,i] = (a[i,:] - a[k,:]).sum() - n*a[i,k] + n*a[k,k] return m Step 2 def implicit(a): n = a.shape[0] m = np.zeros_like(a) m = - n*a.T + n*np.diag(a)[:,newaxis] for k in range(n): for i in range(n): m[k,i] += (a[i,:] - a[k,:]).sum() return m Step 3 def implicit(a): n = a.shape[0] m = np.zeros_like(a) m = - n*a.T + n*np.diag(a)[:,newaxis] m += (a.T[newaxis,...] - a[...,newaxis]).sum(1) return m Et voila'! No loops in the last one. To vectorize that kind of equations, broadcasting is the way to go! Warning: make sure that explicit is the equation that you wanted to vectorize. I wasn't sure if the terms that do not depend on j should also be summed over.
Numpy matrix operations
I want to compute the following values for all i and j: M_ki = Sum[A_ij - A_ik - A_kj + A_kk, 1 <= j <= n] How can I do it using Numpy (Python) without an explicit loop? Thanks!
[ "Here is a general strategy for solving this kind of problem.\nFirst, write a small script, with the loop written explicitly in two different functions, and a test at the end making sure that the two functions are exactly the same:\nimport numpy as np\nfrom numpy import newaxis\n\ndef explicit(a):\n n = a.shape[...
[ 14 ]
[]
[]
[ "matrix", "numpy", "python" ]
stackoverflow_0003657884_matrix_numpy_python.txt
Q: How to have gantt chart using python or pyqt I'm working on a (asset management) system to handle assets , resources and progress of tasks I want to have a gantt chart in my system I'm using python 2.6 and pyqt . Is there any (already made charts python library)? that can work well with pyqt. or should i make a custom widgets for this ? Please advice. A: These are not pyQt related but you can have a look at http://pypi.python.org/pypi/GanttPV/0.1 or maybe http://pypi.python.org/pypi/xm.charting/0.3 I have not used any of them though so I can not give you more specific info. A: Check out the faces project. It uses little Python scripts to define tasks and dependencies, and generates a number of Gantt and other project management graphics.
How to have gantt chart using python or pyqt
I'm working on a (asset management) system to handle assets , resources and progress of tasks I want to have a gantt chart in my system I'm using python 2.6 and pyqt . Is there any (already made charts python library)? that can work well with pyqt. or should i make a custom widgets for this ? Please advice.
[ "These are not pyQt related but you can have a look at http://pypi.python.org/pypi/GanttPV/0.1\nor maybe http://pypi.python.org/pypi/xm.charting/0.3\nI have not used any of them though so I can not give you more specific info.\n", "Check out the faces project. It uses little Python scripts to define tasks and de...
[ 1, 0 ]
[]
[]
[ "gantt_chart", "pyqt", "python", "qt" ]
stackoverflow_0003657504_gantt_chart_pyqt_python_qt.txt
Q: How to test a web API throttle limit in Python I would like to test a web API throttle limit of a given site using Python. This API throttle limit allows X requests MAX over Y seconds per IP. I would like to be able to test the reliability of this throttle limit, in particular on border cases (X-1 requests, X+1 requests) Could you suggest a good way to do it? A: I would write a script to do the following: Make a burst of X requests, timing each request (I would use time.time()). There should be no evidence of throttling in the timing results. You may need to parallelize to hit the limit if latency is significant. Make another request and time it. It should be throttled, and that should be evident in the time taken. Update: here's sample code for HTTP requests: import time import urllib2 URL = 'http://twitter.com' def request_time(): start_time = time.time() urllib2.urlopen(URL).read() end_time = time.time() return end_time - start_time def throttling_test(n): """Test if processing more than n requests is throttled.""" experiment_start = time.time() for i in range(n): t = request_time() print 'Request #%d took %.5f ms' % (i+1, t * 1000.0) print '--- Throttling limit crossed ---' t = request_time() print 'Request #%d took %.5f ms' % (n+1, t * 1000.0) throttling_test(3)
How to test a web API throttle limit in Python
I would like to test a web API throttle limit of a given site using Python. This API throttle limit allows X requests MAX over Y seconds per IP. I would like to be able to test the reliability of this throttle limit, in particular on border cases (X-1 requests, X+1 requests) Could you suggest a good way to do it?
[ "I would write a script to do the following:\n\nMake a burst of X requests, timing each request (I would use time.time()). There should be no evidence of throttling in the timing results. You may need to parallelize to hit the limit if latency is significant. \nMake another request and time it. It should be throttl...
[ 3 ]
[]
[]
[ "api", "python", "throttling" ]
stackoverflow_0003657894_api_python_throttling.txt
Q: Python Plugin-System - HOWTO I'm writing a Python application which stores some data. For storing the data i've wrote a Connection class with abstract methods (using Python's abc module). This class is the super class all storage back-ends derive from. Each storage back-end has only one purpose, e.g. storing the data in plain text files or in a XML file. All storage backends (inclusive the module where the super class is located) are in one package called 'data_handler'. And each back-end is in one module. My application should be able the store data in multiple back-ends simultaneously and determinate at runtime which storage back-ends are available. To do this i had the idea to write a singleton class where each back-end have to register at their import. But this seems to be not so good in a dynamic language (please correct me if I misinterpret this). Another way could be the import of the package with import data_handler and then get the __file__ attribute of the package and search all Python files in the dir for subclasses of the super Connection class. What method should I use, or are there other (maybe better) methods to do this. Stefan Is discovering the back-ends at runtime a strict requirement or would static enumeration of them in the code do? This feature will be nice to note have to edit the code when I add a new back-end But should your application always write to all backends? I will have a class where I can register available handler. And the data shall be written to each registered handler. But not all available handlers have to be registered. A: Do not walk the filesystem (!) and scan the Python source code of the backends! That's an ugly hack at the best of times, and even worse here because you don't need anything like it at all! Registering all the classes on import is perfectly OK. Store the backends in a class attribute instead of an instance attribute; that way, all Storage instances will look at the same set of backends: >>> class Storage(object): ... backends = set() ... ... def register(self, backend): ... self.backends.add(backend) ... Every backend can register itself by instantiating its own Storage, which has access to the class-level backends attribute: >>> foo = Storage() >>> foo.register("text") >>> bar = Storage() >>> bar.register("xml") You can read this attribute by instantiating another Storage, which will read the same variable: >>> baz = Storage() >>> baz.backends {'xml', 'text'} You could even store the backend instances in a class attribute of Connection, and register each backend upon instantiation: >>> class Connection(object,metaclass=abc.ABCMeta): ... @abc.abstractmethod ... def register(self, backend): ... pass ... ... backends = set() ... >>> class TextBackend(Connection): ... def register(self): ... super().backends.add(self) ... ... def __init__(self): ... self.register() ... >>> class XMLBackend(Connection): ... def register(self): ... super().backends.add(self) ... ... def __init__(self): ... self.register() ... >>> foo = TextBackend() >>> bar = XMLBackend() >>> Connection.backends {<__main__.XMLBackend object at 0x027ADAB0>, \ <__main__.TextBackend object at 0x027ADA50>} A: If these backends are going to be distributed in various Python distributions, you might want to look at setuptools/distribute entry points. Here's an article on how you might use these for dynamic plugin finding services: http://aroberge.blogspot.com/2008/12/plugins-part-6-setuptools-based.html A: But should your application always write to all backends? If not, you could use (as usual) another layer of indirection, e.g. storage = Storage() storage.use(TextBackend, XMLBackend, YamlBackend) storage.write(data) Or something like this, with Storage being a dispatcher, which would just loop over the backends and call the appropriate serializer. This is of course, very coarse. A: you could use a function like this one: def loadClass(fullclassname): sepindex=fullclassname.rindex('.') classname=fullclassname[sepindex+1:] modname=fullclassname[:sepindex] #dynmically import the class in the module imod=__import__(modname,None,None,classname) classtype=getattr(imod,classname) return classtype where fullclassname is the fully dotted qualifiant for the class you want load. example (pseudo code,but the idea is there): for package availability scanning, only perform some globbing , then for finding final class name, you may declare a Plugin class in each of your modules that has a getStorage() #scan for modules , getPluginPackagesUnder (to be defined) returns the dotted name for all packages under a root path (using some globbing, listdir or whatever method) pluginpackages=getPluginPackagesUnder("x/y/z") storagelist=[] for pgpck in plunginpackages: pluginclass=loadClass("%s.Plugin"%pgpck) storageinstance=Plugin().getStorage() storagelist.append(storageinstance) so, you can dynamically scan for your existing storage plugins
Python Plugin-System - HOWTO
I'm writing a Python application which stores some data. For storing the data i've wrote a Connection class with abstract methods (using Python's abc module). This class is the super class all storage back-ends derive from. Each storage back-end has only one purpose, e.g. storing the data in plain text files or in a XML file. All storage backends (inclusive the module where the super class is located) are in one package called 'data_handler'. And each back-end is in one module. My application should be able the store data in multiple back-ends simultaneously and determinate at runtime which storage back-ends are available. To do this i had the idea to write a singleton class where each back-end have to register at their import. But this seems to be not so good in a dynamic language (please correct me if I misinterpret this). Another way could be the import of the package with import data_handler and then get the __file__ attribute of the package and search all Python files in the dir for subclasses of the super Connection class. What method should I use, or are there other (maybe better) methods to do this. Stefan Is discovering the back-ends at runtime a strict requirement or would static enumeration of them in the code do? This feature will be nice to note have to edit the code when I add a new back-end But should your application always write to all backends? I will have a class where I can register available handler. And the data shall be written to each registered handler. But not all available handlers have to be registered.
[ "Do not walk the filesystem (!) and scan the Python source code of the backends! That's an ugly hack at the best of times, and even worse here because you don't need anything like it at all! Registering all the classes on import is perfectly OK. \n\nStore the backends in a class attribute instead of an instance att...
[ 3, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003659773_python.txt
Q: How to By pass WP super cache using python? I'm trying to collecting data from a frequently updating blog, so I simply use a while loop which includes urllib2.urlopen("http:\example.com") to refresh the page every 5 minutes to collect the data I wanted. But I notice that I'm not getting the most recent content by doing this, it's different from what I see via browser such as Firefox, and after checking both the source code of Firefox and the same page I get from python, I found that it's WP Super Cache which is preventing me from getting the most recent result. And I still get the same cache page even if I spoof the headers in my python code. So I wonder is there a way to by pass WP super cache? And why there's no such super cache in Firefox at all? A: Have you tried changing the URL with some harmless data? Something like this: import time urllib2.urlopen("http:\example.com?time=%s" % int(time.time())) It will actually call http:\example.com?time=1283872559. Most caching systems will bypass the cache if there's a querystring or it's something that isn't expected.
How to By pass WP super cache using python?
I'm trying to collecting data from a frequently updating blog, so I simply use a while loop which includes urllib2.urlopen("http:\example.com") to refresh the page every 5 minutes to collect the data I wanted. But I notice that I'm not getting the most recent content by doing this, it's different from what I see via browser such as Firefox, and after checking both the source code of Firefox and the same page I get from python, I found that it's WP Super Cache which is preventing me from getting the most recent result. And I still get the same cache page even if I spoof the headers in my python code. So I wonder is there a way to by pass WP super cache? And why there's no such super cache in Firefox at all?
[ "Have you tried changing the URL with some harmless data? Something like this:\nimport time\nurllib2.urlopen(\"http:\\example.com?time=%s\" % int(time.time()))\n\nIt will actually call http:\\example.com?time=1283872559. Most caching systems will bypass the cache if there's a querystring or it's something that isn'...
[ 2 ]
[]
[]
[ "php", "python", "urllib2", "urlopen", "wordpress" ]
stackoverflow_0003659429_php_python_urllib2_urlopen_wordpress.txt
Q: Django Celery AbortableTask usage I'm trying to use the AbortableTask feature of Celery but the documentation example doesn't seem to be working for me. The example given is: from celery.contrib.abortable import AbortableTask def MyLongRunningTask(AbortableTask): def run(self, **kwargs): logger = self.get_logger(**kwargs) results = [] for x in xrange(100): # Check after every 5 loops.. if x % 5 == 0: # alternatively, check when some timer is due if self.is_aborted(**kwargs): # Respect the aborted status and terminate # gracefully logger.warning("Task aborted.") return None y = do_something_expensive(x) results.append(y) logger.info("Task finished.") return results and from myproject.tasks import MyLongRunningTask def myview(request): async_result = MyLongRunningTask.delay() # async_result is of type AbortableAsyncResult # After 10 seconds, abort the task time.sleep(10) async_result.abort() ... However, I am getting the error: TypeError: MyLongRunningTask() takes exactly 1 argument (0 given) What am I doing wrong? A: Just a guess but I think it should be class MyLongRunningTask(AbortableTask) and not def MyLongRunningTask(AbortableTask)
Django Celery AbortableTask usage
I'm trying to use the AbortableTask feature of Celery but the documentation example doesn't seem to be working for me. The example given is: from celery.contrib.abortable import AbortableTask def MyLongRunningTask(AbortableTask): def run(self, **kwargs): logger = self.get_logger(**kwargs) results = [] for x in xrange(100): # Check after every 5 loops.. if x % 5 == 0: # alternatively, check when some timer is due if self.is_aborted(**kwargs): # Respect the aborted status and terminate # gracefully logger.warning("Task aborted.") return None y = do_something_expensive(x) results.append(y) logger.info("Task finished.") return results and from myproject.tasks import MyLongRunningTask def myview(request): async_result = MyLongRunningTask.delay() # async_result is of type AbortableAsyncResult # After 10 seconds, abort the task time.sleep(10) async_result.abort() ... However, I am getting the error: TypeError: MyLongRunningTask() takes exactly 1 argument (0 given) What am I doing wrong?
[ "Just a guess but I think it should be \nclass MyLongRunningTask(AbortableTask)\n\nand not\ndef MyLongRunningTask(AbortableTask)\n\n" ]
[ 2 ]
[]
[]
[ "celery", "celery_task", "django", "python" ]
stackoverflow_0003659561_celery_celery_task_django_python.txt
Q: how to shift a datetime object by 12 hours in python Datetime objects hurt my head for some reason. I am writing to figure out how to shift a date time object by 12 hours. I also need to know how to figure out if two date time object's differ by say 1 minute or more. A: The datetime library has a timedelta object specifically for this kind of thing: import datetime mydatetime = datetime.now() # or whatever value you want twelvelater = mydatetime + datetime.timedelta(hours=12) twelveearlier = mydatetime - datetime.timedelta(hours=12) difference = abs(some_datetime_A - some_datetime_B) # difference is now a timedelta object # there are a couple of ways to do this comparision: if difference > timedelta(minutes=1): print "Timestamps were more than a minute apart" # or: if difference.total_seconds() > 60: print "Timestamps were more than a minute apart" A: You'd use datetime.timedelta for something like this. from datetime import timedelta datetime arithmetic works kind of like normal arithmetic: you can add a timedelta object to a datetime object to shift its time: dt = # some datetime object dt_plus_12 = dt + timedelta(hours=12) Also you can subtract two datetime objects to get a timedelta representing the difference between them: dt2 = # some other datetime object ONE_MINUTE = timedelta(minutes=1) if abs(dt2 - dt) > ONE_MINUTE: # do something
how to shift a datetime object by 12 hours in python
Datetime objects hurt my head for some reason. I am writing to figure out how to shift a date time object by 12 hours. I also need to know how to figure out if two date time object's differ by say 1 minute or more.
[ "The datetime library has a timedelta object specifically for this kind of thing:\nimport datetime\n\nmydatetime = datetime.now() # or whatever value you want\ntwelvelater = mydatetime + datetime.timedelta(hours=12)\ntwelveearlier = mydatetime - datetime.timedelta(hours=12)\n\ndifference = abs(some_datetime_A - som...
[ 32, 5 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0003660210_datetime_python.txt
Q: When a Web framework isn't convenient to use? When a Web framework ( like django, ruby on rails, zend, etc ) isn't convenient to use ? And so... When a Web programming language ( like PHP, Asp, Python, etc ) is better than a Web Framework ? A: You don't need frameworks when you don't plan to use their features. A: I like the wikipedia description: The framework aims to alleviate the overhead associated with common activities performed in Web development. For example, many frameworks provide libraries for database access, templating frameworks and session management... Basically if you don't need all of the above, you don't need a framework. A: The difference is, in my opinion, the simpleness of what you are trying to build. Are you trying to make a difficult, complicated web app, or are you making a simple script that performs a trivial task? In the first case you absolutely need a framework, in the second case.. don't even bother. A: The rule that I have is that if whatever I'm building is only going to be a single page, I'll usually do it in just PHP. Whenever I need more than one page, I go with a framework (Symfony), because that usually means that I'm going to want things like routing and proper dispatching of requests. This does however depend a lot on the language. In languages like PHP, the time needed to set up a project to use an MVC framework may be a lot more than just solving the problem. Other languages may very well be designed around using an MVC framework, and has a very low setup cost for that. A: A web framework is supposed to provide means to handle certain kind of interaction. If you have site with no interaction or no "adaptation", you don't need either framework or programming language, you simply write HTML files and publish your files. As you start to add features for the back-end (like publishing more plain pages) or in the front end (like sorting a list when the user clicks "order by") you start getting into frameworks/programming languages. Basic interaction was handled with CGI - you write an script which responds with a string to a few parameters passed via a form. Then you have database access. In my experience, if you need simple features AND want your website to be suitable for growth without resorting to rewriting it from scratch, you should start from a web framework like Django. You can do simple things quite easily in Django (granted - it is not trivial) and add very complex behavior with small, incremental steps. A: When you have to build a very complex site, and the functionality is already exists in a CMS (eg Drupal, it has amazingly lot contrib for everything). A: I'm at that stage where, because I spent so much time learning a framework recently, even if I do a one page "website", I will still use one, need to get my ROI up :p
When a Web framework isn't convenient to use?
When a Web framework ( like django, ruby on rails, zend, etc ) isn't convenient to use ? And so... When a Web programming language ( like PHP, Asp, Python, etc ) is better than a Web Framework ?
[ "You don't need frameworks when you don't plan to use their features.\n", "I like the wikipedia description:\n\nThe framework aims to alleviate the\n overhead associated with common\n activities performed in Web\n development. For example, many\n frameworks provide libraries for\n database access, templating...
[ 3, 3, 1, 1, 1, 0, 0 ]
[]
[]
[ "django", "php", "python", "ruby_on_rails", "zend_framework" ]
stackoverflow_0003659687_django_php_python_ruby_on_rails_zend_framework.txt
Q: Query CPU ID from Python? How I can find processor id with py2.6, windows OS? I know that there is pycpuid, but I can't compile this under 2.6. A: Have you tried wmi? (It may require elevated privilege level) Here's a solution (it works for Python 2 and 3): >>> import wmi >>> c = wmi.WMI() >>> for s in c.Win32_Processor(): print (s) instance of Win32_Processor { AddressWidth = 64; Architecture = 9; Availability = 3; Caption = "Intel64 Family 6 Model 26 Stepping 5"; CpuStatus = 1; CreationClassName = "Win32_Processor"; CurrentClockSpeed = 3068; DataWidth = 64; Description = "Intel64 Family 6 Model 26 Stepping 5"; DeviceID = "CPU0"; ExtClock = 133; Family = 1; L2CacheSize = 1024; L3CacheSize = 8192; L3CacheSpeed = 0; Level = 6; LoadPercentage = 3; Manufacturer = "GenuineIntel"; MaxClockSpeed = 3068; Name = "Intel(R) Core(TM) i7 CPU 950 @ 3.07GHz"; NumberOfCores = 4; NumberOfLogicalProcessors = 8; PowerManagementSupported = FALSE; ProcessorId = "BFEBFBFF000106A5"; ProcessorType = 3; Revision = 6661; Role = "CPU"; SocketDesignation = "CPU 1"; Status = "OK"; StatusInfo = 3; SystemCreationClassName = "Win32_ComputerSystem"; SystemName = "RYAN-PC"; UpgradeMethod = 1; Version = ""; VoltageCaps = 0; }; A: I've found that the wmic command is always available on Windows-XP, and use subprocess.Popen to run it, rather than require my users to install any special Python packages. C:\>wmic cpu get ProcessorId /format:csv Node,ProcessorId E100325,BFEBFBFF00000F43 E100325,BFEBFBFF00000F43 A: You can get CPU ID from WMI . VBScript Sample here You can use WMI from Python. Combining these two resources I think you can figure out the rest. A: There seem to be two projects with that name. Did you try both? Bram de Greve arun.sharma
Query CPU ID from Python?
How I can find processor id with py2.6, windows OS? I know that there is pycpuid, but I can't compile this under 2.6.
[ "Have you tried wmi? (It may require elevated privilege level)\nHere's a solution (it works for Python 2 and 3):\n>>> import wmi\n>>> c = wmi.WMI()\n>>> for s in c.Win32_Processor():\n print (s)\n\n\n\ninstance of Win32_Processor\n{\n AddressWidth = 64;\n Architecture = 9;\n Availability = 3;\n Capti...
[ 6, 3, 1, 0 ]
[]
[]
[ "cpu", "python", "windows" ]
stackoverflow_0003056674_cpu_python_windows.txt
Q: python error checking I am using code below. How Do add error checking. If anything is error, replace continue reading Ex: if volume is N\a or missing , replace with 'a value.' Don't skip line, don't stop. reader = csv.reader(idata.split("\r\n")) stocks = [] for line in reader: if line == '': continue stock, price, volume, stime = line price = float(price) volume = int(volume) stocks.append((stock, price, volume, stime)) A: Do something like the following: def isRecordValid(stock,price,volume,stime): #do input validation here, return True if record is fine, False if not. Optionally raise an Error here and catch it in your loop return True reader = csv.reader(idata.split("\r\n")) stocks = [] for line in reader: if line == '': continue stock, price, volume, stime = line try: if isRecordValid(stock,price,volume,stime): price = float(price) volume = int(volume) stocks.append((stock, price, volume, stime)) except Exception as e: print "either print or log and error here, using 'except' means you can continue execution without the exception terminating your current stack frame and being thrown further up" Basically define another method (or do it inline) to validate that stock, price, volume, and stime are all as you expect it. I'd try to catch any Errors here too in case your float() or int() calls to convert the price and volume strings to their expected types fails for whatever reason.
python error checking
I am using code below. How Do add error checking. If anything is error, replace continue reading Ex: if volume is N\a or missing , replace with 'a value.' Don't skip line, don't stop. reader = csv.reader(idata.split("\r\n")) stocks = [] for line in reader: if line == '': continue stock, price, volume, stime = line price = float(price) volume = int(volume) stocks.append((stock, price, volume, stime))
[ "Do something like the following:\ndef isRecordValid(stock,price,volume,stime):\n #do input validation here, return True if record is fine, False if not. Optionally raise an Error here and catch it in your loop\n return True\n\nreader = csv.reader(idata.split(\"\\r\\n\"))\n\nstocks = []\nfor line in reader:\...
[ 2 ]
[]
[]
[ "error_handling", "python" ]
stackoverflow_0003660370_error_handling_python.txt
Q: Top 3 questions to test someones Python level, what would they be? If you had to judge someones level of Python understand in just 3 questions, what would you ask? A: This is pretty much the same as for any language. What projects have you done with Python? What is your favorite Python reference? Have you worked with other people on code written in Python? That's how I would judge. If I wanted to test, it would depend on whether I were looking for someone to write in 2.x or 3.x. Since I'm familiar with the 2.x stuff... How would you create a list containing the result of [insert operation] on another list? How would you do the above if you cared about memory usage? What tool do you use to debug your Python code? CW'd because the question should be. A: Explain generators. Write unit tests for <important-piece-of-code>. Who is Alex Martelli?
Top 3 questions to test someones Python level, what would they be?
If you had to judge someones level of Python understand in just 3 questions, what would you ask?
[ "This is pretty much the same as for any language.\n\nWhat projects have you done with Python?\nWhat is your favorite Python reference?\nHave you worked with other people on code written in Python?\n\nThat's how I would judge. If I wanted to test, it would depend on whether I were looking for someone to write in 2....
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003660503_python.txt
Q: Building a Python extension with bjam (Boost.Build) on Mac OS X So far as I can tell what happens is this: In python.jam, it works out which version of Python I am using and which library directories to look in; It adds -Wl-R arguments to the g++ command line to include those directories; The ld command complains that it does not have a -R option. So either (a) I have a defective version of ld, or (b) I need to tell bjam that it needs to use a different option (-rpath perhaps?) or that this option is not required. I must be missing something—I am surely not the first person in history to try to build a Python extension with Boost on Mac OS X—but I can’t figure out where to look next. Any hints? Update: The command I am using is bjam If I do bjam --version, I get Boost.Build V2 (Milestone 12) Boost.Jam 03.1.18 The toolset used is whatever the default toolset is on Mac OS X. The compiler is the default compiler on Mac OS X (with the developer tools installed), which is GCC version ‘i686-apple-darwin10-gcc-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5664)’. The linker is the default linker on Mac OS X, which is called ld or ld64, but which does not have the -R option that GNU ld has, so I assume it is a special version designed to allow for Mac OS X’s concept of frameworks or whatever. It does not have a --version option. There is a Jamfile, which goes like this: import python ; python-extension _optimor : bill_python.cpp bill_record_python.cpp .. etc ... : <cxxflags>-fPIC ... etc ... <variant>debug:<define>DEBUG <include>/usr/include/python2.6 <include>../ ; It builds OK on Ububtu GNU/Linux. I am not interested in Boost or bjam per se; my only requirement to compile this extension so I can get on with developing the system of which this extension is a small but important part. A: I can't tell which version of Boost you have.. BUt the most likely reason for the problem is that you are using the generic "gcc" toolset to build. There's a special toolset for building with the GCC variant that Apple uses in Xcode. Try building with bjam toolset=darwin instead.
Building a Python extension with bjam (Boost.Build) on Mac OS X
So far as I can tell what happens is this: In python.jam, it works out which version of Python I am using and which library directories to look in; It adds -Wl-R arguments to the g++ command line to include those directories; The ld command complains that it does not have a -R option. So either (a) I have a defective version of ld, or (b) I need to tell bjam that it needs to use a different option (-rpath perhaps?) or that this option is not required. I must be missing something—I am surely not the first person in history to try to build a Python extension with Boost on Mac OS X—but I can’t figure out where to look next. Any hints? Update: The command I am using is bjam If I do bjam --version, I get Boost.Build V2 (Milestone 12) Boost.Jam 03.1.18 The toolset used is whatever the default toolset is on Mac OS X. The compiler is the default compiler on Mac OS X (with the developer tools installed), which is GCC version ‘i686-apple-darwin10-gcc-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5664)’. The linker is the default linker on Mac OS X, which is called ld or ld64, but which does not have the -R option that GNU ld has, so I assume it is a special version designed to allow for Mac OS X’s concept of frameworks or whatever. It does not have a --version option. There is a Jamfile, which goes like this: import python ; python-extension _optimor : bill_python.cpp bill_record_python.cpp .. etc ... : <cxxflags>-fPIC ... etc ... <variant>debug:<define>DEBUG <include>/usr/include/python2.6 <include>../ ; It builds OK on Ububtu GNU/Linux. I am not interested in Boost or bjam per se; my only requirement to compile this extension so I can get on with developing the system of which this extension is a small but important part.
[ "I can't tell which version of Boost you have.. BUt the most likely reason for the problem is that you are using the generic \"gcc\" toolset to build. There's a special toolset for building with the GCC variant that Apple uses in Xcode. Try building with bjam toolset=darwin instead.\n" ]
[ 3 ]
[]
[]
[ "boost", "macos", "python" ]
stackoverflow_0003610286_boost_macos_python.txt
Q: Figure out nested submenu selections in wxPython? Let's say in a larger submenu structure with a depth of 3 levels, I have selected 'car' in the first level, 'type' in the second, and 'suv' in the third and last level. Is there any way I can figure all these three selections in my def OnPopupItemSelected(self, event) method? I hope I have made myself clear enough, if not, please add a comment so I can re-phrase. A: It looks like in the wxPython demo that they "code" the ids in a child parent fashion: # top level menu menu1 = wx.Menu() menu1.Append(11,"11") menu1.Append(12, "12") # sub menu 1 menu2 = wx.Menu() menu2.Append(131, "131") menu2.Append(132, "132") menu1.AppendMenu(13,"13",menu2) # sub menu 2 menu3 = wx.Menu() menu3.Append(1321,"1321") menu3.Append(1322,"1322") menu3.Append(1323,"1323") menu2.AppendMenu(132, "132", menu3) # add top to menubar menubar.Append(menu1, "&Top") I thought surely given the "clicked" menuitem you could walk the submenus backwards. This doesn't seem to be the case, as the clicked menuitem only holds a reference to it's parent menu and not the menuitem it is a submenu of. So, the best I could code up was a nasty recursive function that walks top/down to find the submenu clicked. def MenuClick(self, event): def _menuItemSearch(menu,subMenuTree ,id): if not menu.FindItemById(id): return False # it is in this menu for menuItem in menu.MenuItems: if menuItem.GetId() == id: subMenuTree.append(menuItem.GetLabel()) return True if menuItem.GetSubMenu(): if _menuItemSearch(menuItem.GetSubMenu(),subMenuTree,id): subMenuTree.append(menuItem.GetLabel()) return True return False subMenuTree = [] for menu,name in self.GetMenuBar().GetMenus(): _menuItemSearch(menu,subMenuTree,event.Id) print subMenuTree [u'1321', u'132', u'13']
Figure out nested submenu selections in wxPython?
Let's say in a larger submenu structure with a depth of 3 levels, I have selected 'car' in the first level, 'type' in the second, and 'suv' in the third and last level. Is there any way I can figure all these three selections in my def OnPopupItemSelected(self, event) method? I hope I have made myself clear enough, if not, please add a comment so I can re-phrase.
[ "It looks like in the wxPython demo that they \"code\" the ids in a child parent fashion:\n# top level menu\nmenu1 = wx.Menu()\nmenu1.Append(11,\"11\")\nmenu1.Append(12, \"12\") \n\n# sub menu 1\nmenu2 = wx.Menu()\nmenu2.Append(131, \"131\")\nmenu2.Append(132, \"132\")\nmenu1.AppendMenu(13,\"13\",menu2)\n\n#...
[ 3 ]
[]
[]
[ "nested", "python", "submenu" ]
stackoverflow_0003658747_nested_python_submenu.txt
Q: returning xml documents from cherrypy I am new to web programming and am trying to return an xml document from the cherrypy web server. But, what I see in the browser is a string value stripped off all the xml tags. i.e. <Foo> <Val1> </Foo> <Bar> <Val2> </Bar> shows up in the browser as Val1 Val2 I am sure that I am generating the document correctly but somewhere after cherrypy picks it up and sends it off to the http client, it gets changed. Any ideas on what might be happening? Thanks a lot! A: WebKit-based browsers like Safari and Chrome hide XML markup from the rendered text. You should ask the browser to show you the source (Tools->View Source(CTRL+U) in Chrome). Firefox shows XML markup by default. Anyhow, if you're doing webservice development I'd recommend you to use curl. It will save you a lot of time.
returning xml documents from cherrypy
I am new to web programming and am trying to return an xml document from the cherrypy web server. But, what I see in the browser is a string value stripped off all the xml tags. i.e. <Foo> <Val1> </Foo> <Bar> <Val2> </Bar> shows up in the browser as Val1 Val2 I am sure that I am generating the document correctly but somewhere after cherrypy picks it up and sends it off to the http client, it gets changed. Any ideas on what might be happening? Thanks a lot!
[ "WebKit-based browsers like Safari and Chrome hide XML markup from the rendered text. You should ask the browser to show you the source (Tools->View Source(CTRL+U) in Chrome). Firefox shows XML markup by default.\nAnyhow, if you're doing webservice development I'd recommend you to use curl. It will save you a lot o...
[ 1 ]
[]
[]
[ "cherrypy", "python" ]
stackoverflow_0003660521_cherrypy_python.txt
Q: apropos / find context related information On unix-like systems we have apropos to search the manual page names and descriptions so we can find context related information. For example apropos delete would give me a list of all kinds of software related to "deleting" stuff. Does anybody know if that already exist for Python or do I have to code it? What I basically want is the same semantics seen with the Unix apropos in Python ... find context related modules/functions/etc. I am not talking about doing a search on PyPi but rather find stuff when I am offline for example. Cheers, Markus A: I am not talking about doing a search on PyPI! why not ? that should be the first thing you do if you want to look for Python modules. Otherwise simple search on google/yahoo may yield some results, such as this A: $ apt-cache search <keyword> | grep python
apropos / find context related information
On unix-like systems we have apropos to search the manual page names and descriptions so we can find context related information. For example apropos delete would give me a list of all kinds of software related to "deleting" stuff. Does anybody know if that already exist for Python or do I have to code it? What I basically want is the same semantics seen with the Unix apropos in Python ... find context related modules/functions/etc. I am not talking about doing a search on PyPi but rather find stuff when I am offline for example. Cheers, Markus
[ "\n\nI am not talking about doing a search on PyPI!\n\n\nwhy not ? that should be the first thing you do if you want to look for Python modules. Otherwise simple search on google/yahoo may yield some results, such as this\n", "$ apt-cache search <keyword> | grep python\n\n" ]
[ 1, 1 ]
[]
[]
[ "find", "python" ]
stackoverflow_0003660395_find_python.txt
Q: I get OSError: [Errno 13] Permission denied: , and os.walk exits I have a script to report me about all files, in a directory, so that users will be required to erase them (it's a really badly managed cluster, w/o real superuser). When I run the script I get: OSError: [Errno 13] Permission denied: ' ls: : Permission denied I can't write the dir name (company policy) The code is: #!/depot/Python-3.1.1/bin/python3.1 from stat import * import stat import sys from collections import defaultdict from pwd import getpwuid import sys sys.path.append('/remote/us01home15/ldagan/python') import mailer import os import re import glob import subprocess import pwd def find_owner(file): return pwd.getpwuid(os.stat(file)[stat.ST_UID]).pw_name if (len(sys.argv) < 1): sys.error('''Please input <runda number> <case number>''') files_by_users=defaultdict(list) runda_num="".join(sys.argv[1]) dir_basic='/berry/secure' case_num="".join(sys.argv[2]) secure_dir="".join([dir_basic,"/"]) i=1 dirs=[] runda_case_dir="".join([dir_basic,'/',runda_num,'/',case_num ]) while (os.path.exists(secure_dir)): if (os.path.exists(runda_case_dir)): dirs.append(runda_case_dir) i+=1 secure_dir="".join([dir_basic,str(i)]) runda_dir="/".join([secure_dir,runda_num,case_num]) #now finding list of manager_email='ldagan@synopsys.com zafrany@synopsys.com' def bull (msg): i=1 for dir in dirs: for root,dirs,files in os.walk(dir,onerror=bull): for file in files: file_full_name=os.path.join(root,file) files_by_users[find_owner(file_full_name)].append(file_full_name) for username in files_by_users: sendOffendingNotice(username, file_by+users[username], manager_email) def sendOffendingNotice(username,filenames,managerEmail): """gets file name & manager Email sends an Email to the manager for review. As there are no smtp definitions, mailx shall be used""" user_email=username+'@synopsys.com' message="""The following files \n""" + """\n""".join(filenames) +"""\n""" + \ """ which belongs to user """ + username +""" does not meet the required names's SPEC\nPlease keep it under a directory which has a proper case/star name\n""" message= """echo \"""" + message+ """" | mailx -s "Offending files" """ + managerEmail +" " #+user_email process=subprocess.Popen(message,shell=True) The script does not send the Email, but dies. Thanks for helping a newbe. A: It sounds like your script is running as a normal user, and does not have permission to read a directory. It would help to see the full error message (even if path names are changed), since it would tell us on which line the error was occurring. But basically the solution is to trap the exception in a try...except block: try: # Put the line that causes the exception here # Do not trap more lines than you need to. ... except OSError as err: # handle error (see below) print(err) Especially in light of S.Lott's comment, note that the files or directories which are causing OSErrors might be precisely the files whose owners you need to send email to. But in order to read inside their directories your script may need to run with superuser (or heightened) privileges.
I get OSError: [Errno 13] Permission denied: , and os.walk exits
I have a script to report me about all files, in a directory, so that users will be required to erase them (it's a really badly managed cluster, w/o real superuser). When I run the script I get: OSError: [Errno 13] Permission denied: ' ls: : Permission denied I can't write the dir name (company policy) The code is: #!/depot/Python-3.1.1/bin/python3.1 from stat import * import stat import sys from collections import defaultdict from pwd import getpwuid import sys sys.path.append('/remote/us01home15/ldagan/python') import mailer import os import re import glob import subprocess import pwd def find_owner(file): return pwd.getpwuid(os.stat(file)[stat.ST_UID]).pw_name if (len(sys.argv) < 1): sys.error('''Please input <runda number> <case number>''') files_by_users=defaultdict(list) runda_num="".join(sys.argv[1]) dir_basic='/berry/secure' case_num="".join(sys.argv[2]) secure_dir="".join([dir_basic,"/"]) i=1 dirs=[] runda_case_dir="".join([dir_basic,'/',runda_num,'/',case_num ]) while (os.path.exists(secure_dir)): if (os.path.exists(runda_case_dir)): dirs.append(runda_case_dir) i+=1 secure_dir="".join([dir_basic,str(i)]) runda_dir="/".join([secure_dir,runda_num,case_num]) #now finding list of manager_email='ldagan@synopsys.com zafrany@synopsys.com' def bull (msg): i=1 for dir in dirs: for root,dirs,files in os.walk(dir,onerror=bull): for file in files: file_full_name=os.path.join(root,file) files_by_users[find_owner(file_full_name)].append(file_full_name) for username in files_by_users: sendOffendingNotice(username, file_by+users[username], manager_email) def sendOffendingNotice(username,filenames,managerEmail): """gets file name & manager Email sends an Email to the manager for review. As there are no smtp definitions, mailx shall be used""" user_email=username+'@synopsys.com' message="""The following files \n""" + """\n""".join(filenames) +"""\n""" + \ """ which belongs to user """ + username +""" does not meet the required names's SPEC\nPlease keep it under a directory which has a proper case/star name\n""" message= """echo \"""" + message+ """" | mailx -s "Offending files" """ + managerEmail +" " #+user_email process=subprocess.Popen(message,shell=True) The script does not send the Email, but dies. Thanks for helping a newbe.
[ "It sounds like your script is running as a normal user, and does not have permission to read a directory.\nIt would help to see the full error message (even if path names are changed), since it would tell us on which line the error was occurring.\nBut basically the solution is to trap the exception in a try...exce...
[ 2 ]
[]
[]
[ "os.walk", "python" ]
stackoverflow_0003660706_os.walk_python.txt
Q: same line behaves correctly or gives me an error message depending on file position gives me an error message: class logger: session = web.ctx.session #this line doesn't give me an error message: class create: def GET(self): # loggedout() session = web.ctx.session #this line form = self.createform() return render.create(form) Why? A: web.ctx can't be used in that scope. It's a thread-local object that web.py initializes before it calls GET/POST/etc. and gets discarded afterwards. A: class logger: print('Hi') prints Hi. Statements under a class definition gets run at definition time. A function definition like this one: def GET(self): # loggedout() session = web.ctx.session #this line form = self.createform() return render.create(form) is also a statement. It creates the function object which is named GET. But the code inside the function does not get run until the GET method is called. This is why you get an error message in the first case, but not the second.
same line behaves correctly or gives me an error message depending on file position
gives me an error message: class logger: session = web.ctx.session #this line doesn't give me an error message: class create: def GET(self): # loggedout() session = web.ctx.session #this line form = self.createform() return render.create(form) Why?
[ "web.ctx can't be used in that scope. It's a thread-local object that web.py initializes before it calls GET/POST/etc. and gets discarded afterwards.\n", "class logger:\n print('Hi')\n\nprints Hi. Statements under a class definition gets run at definition time. \nA function definition like this one:\ndef GET(s...
[ 1, 0 ]
[]
[]
[ "python", "web.py" ]
stackoverflow_0003647939_python_web.py.txt
Q: Python 2.7 or 3.1.2? Possible Duplicate: python 2.6 or python 3.1? Hi, I'm new to the python world and it seems that there are currently two parallel versions in development, which would be the 2.7 versus the 3.1.2. I'm wondering what version should I use to start, and why? A: Stay with 3.1.2 if you want to be on the bleeding edge. Stay with 2.7 if you want to leverage any 3rd party libraries that haven't been ported to 3.1.2 yet or can't be backward compatible. A: I'd suggest Python 3 as it has incorporated several fixes to remove some of Python's previous "warts". The primary reason for maintaining the 2.7 version is for older packages that haven't yet made the transition. There are good reasons to use 2.7 but if you're starting out, you might as well start on the path leading to the future.
Python 2.7 or 3.1.2?
Possible Duplicate: python 2.6 or python 3.1? Hi, I'm new to the python world and it seems that there are currently two parallel versions in development, which would be the 2.7 versus the 3.1.2. I'm wondering what version should I use to start, and why?
[ "Stay with 3.1.2 if you want to be on the bleeding edge.\nStay with 2.7 if you want to leverage any 3rd party libraries that haven't been ported to 3.1.2 yet or can't be backward compatible.\n", "I'd suggest Python 3 as it has incorporated several fixes to remove some of Python's previous \"warts\". The primary r...
[ 5, 3 ]
[]
[]
[ "python" ]
stackoverflow_0003661186_python.txt
Q: Testing workflows in Django I really love testing and building unit tests, but I find it quite annoying having to build tests for a website's workflow. e.g. Register -> Check email -> Activate account -> Login or Login -> Edit details -> Submit and view profile manual testing = loads of time + tireing even when using app such as Selenium, going though each iteration and then having to check emails etc... Is there some way of performing an array of tests in a more efficient way? How do you guys do it? :) A: I write "functional unit" tests for individual views using Django's test framework. I have found that integration tests are best done using something like Robot Framework. In one of my projects I came up with a minimal, custom implementation of Ward Cunningham's FIT mechanism. A: You probably want a functional testing framework like Cucumber (written in Ruby) or its Python equivalent, Freshen. These allow you to write workflows in a plain-language text format, and the test runner will execute the steps and check the expected results. A: I usually use the Lettuce framework for this kind of testing. You can find it here: http://lettuce.it/
Testing workflows in Django
I really love testing and building unit tests, but I find it quite annoying having to build tests for a website's workflow. e.g. Register -> Check email -> Activate account -> Login or Login -> Edit details -> Submit and view profile manual testing = loads of time + tireing even when using app such as Selenium, going though each iteration and then having to check emails etc... Is there some way of performing an array of tests in a more efficient way? How do you guys do it? :)
[ "I write \"functional unit\" tests for individual views using Django's test framework. I have found that integration tests are best done using something like Robot Framework. In one of my projects I came up with a minimal, custom implementation of Ward Cunningham's FIT mechanism.\n", "You probably want a function...
[ 3, 3, 2 ]
[]
[]
[ "django", "python", "testing", "unit_testing", "workflow" ]
stackoverflow_0003657934_django_python_testing_unit_testing_workflow.txt
Q: how do matlab do the sort? How is the sort() working in matlab? Code in pure matlab: q is an array: q = -0.2461 2.9531 -15.8867 49.8750 -99.1172 125.8438 -99.1172 49.8750 -15.8867 2.9531 -0.2461 After q = sort(roots(q)), I got: q = 0.3525 0.3371 - 0.1564i 0.3371 + 0.1564i 0.2694 - 0.3547i 0.2694 + 0.3547i 1.3579 - 1.7880i 1.3579 + 1.7880i 2.4410 - 1.1324i 2.4410 + 1.1324i 2.8365 Well, seems to work fine! Then in python, I use (q is the same as above, it is an np.array): import numpy as np q = np.sort(np.roots(q)) And I got: [ 0.26937874-0.35469815j 0.26937874+0.35469815j 0.33711562-0.15638427j 0.33711562+0.15638427j 0.35254298+0.j 1.35792218-1.78801226j 1.35792218+1.78801226j 2.44104520-1.13237431j 2.44104520+1.13237431j 2.83653354+0.j ] Well... These two results seem different in that they sort differently, so what are the reasons? did I make something wrong? thank you in advance! My answer: def sortComplex(complexList): complexList.sort(key=abs) # then sort by the angles, swap those in descending orders return complexList Then call it in the python code, works fine :p A: From the MATLAB documentation for SORT: If A has complex entries r and s, sort orders them according to the following rule: r appears before s in sort(A) if either of the following hold: abs(r) < abs(s) abs(r) = abs(s) and angle(r) < angle(s) In other words, an array that has complex entries is first sorted based on the absolute value (i.e. complex magnitude) of those entries, and any entries that have the same absolute value are sorted based on their phase angles. Python (i.e. numpy) orders things differently. From the documentation Amro linked to in his comment: The sort order for complex numbers is lexicographic. If both the real and imaginary parts are non-nan then the order is determined by the real parts except when they are equal, in which case the order is determined by the imaginary parts. In other words, an array that has complex entries is first sorted based on the real component of the entries, and any entries that have equal real components are sorted based on their imaginary components. EDIT: If you want to reproduce the numpy behavior in MATLAB, one way you can do it is to use the function SORTROWS to create a sort index based on the real and imaginary components of the array entries, then apply that sort index to your array of complex values: >> r = roots(q); %# Compute your roots >> [junk,index] = sortrows([real(r) imag(r)],[1 2]); %# Sort based on real, %# then imaginary parts >> r = r(index) %# Apply the sort index to r r = 0.2694 - 0.3547i 0.2694 + 0.3547i 0.3369 - 0.1564i 0.3369 + 0.1564i 0.3528 1.3579 - 1.7879i 1.3579 + 1.7879i 2.4419 - 1.1332i 2.4419 + 1.1332i 2.8344
how do matlab do the sort?
How is the sort() working in matlab? Code in pure matlab: q is an array: q = -0.2461 2.9531 -15.8867 49.8750 -99.1172 125.8438 -99.1172 49.8750 -15.8867 2.9531 -0.2461 After q = sort(roots(q)), I got: q = 0.3525 0.3371 - 0.1564i 0.3371 + 0.1564i 0.2694 - 0.3547i 0.2694 + 0.3547i 1.3579 - 1.7880i 1.3579 + 1.7880i 2.4410 - 1.1324i 2.4410 + 1.1324i 2.8365 Well, seems to work fine! Then in python, I use (q is the same as above, it is an np.array): import numpy as np q = np.sort(np.roots(q)) And I got: [ 0.26937874-0.35469815j 0.26937874+0.35469815j 0.33711562-0.15638427j 0.33711562+0.15638427j 0.35254298+0.j 1.35792218-1.78801226j 1.35792218+1.78801226j 2.44104520-1.13237431j 2.44104520+1.13237431j 2.83653354+0.j ] Well... These two results seem different in that they sort differently, so what are the reasons? did I make something wrong? thank you in advance! My answer: def sortComplex(complexList): complexList.sort(key=abs) # then sort by the angles, swap those in descending orders return complexList Then call it in the python code, works fine :p
[ "From the MATLAB documentation for SORT:\n\nIf A has complex entries r and s,\n sort orders them according to the\n following rule: r appears before s in\n sort(A) if either of the following\n hold:\n\nabs(r) < abs(s)\nabs(r) = abs(s) and angle(r) < angle(s)\n\n\nIn other words, an array that has complex entrie...
[ 4 ]
[]
[]
[ "matlab", "numpy", "python" ]
stackoverflow_0003662203_matlab_numpy_python.txt
Q: Design question in Python: should this be one generic function or two specific ones? I'm creating a basic database utility class in Python. I'm refactoring an old module into a class. I'm now working on an executeQuery() function, and I'm unsure of whether to keep the old design or change it. Here are the 2 options: (The old design:) Have one generic executeQuery method that takes the query to execute and a boolean commit parameter that indicates whether to commit (insert, update, delete) or not (select), and determines with an if statement whether to commit or to select and return. (This is the way I'm used to, but that might be because you can't have a function that sometimes returns something and sometimes doesn't in the languages I've worked with:) Have 2 functions, executeQuery and executeUpdateQuery (or something equivalent). executeQuery will execute a simple query and return a result set, while executeUpdateQuery will make changes to the DB (insert, update, delete) and return nothing. Is it accepted to use the first way? It seems unclear to me, but maybe it's more Pythonistic...? Python is very flexible, maybe I should take advantage of this feature that can't really be accomplished in this way in more strict languages... And a second part of this question, unrelated to the main idea - what is the best way to return query results in Python? Using which function to query the database, in what format...? A: It's propably just me and my FP fetish, but I think a function executed solely for side effects is very different from a non-destructive function that fetches some data, and therefore have different names. Especially if the generic function would do something different depending on exactly that (the part on the commit parameter seems to imply that). As for how to return results... I'm a huge fan of generators, but if the library you use for database connections returns a list anyway, you might as well pass this list on - a generator wouldn't buy you anything in this case. But if it allows you to iterate over the results (one at a time), seize the opportunity to save a lot of memory on larger queries. A: I don't know how to answer the first part of your question, it seems like a matter of style more than anything else. Maybe you could invoke the Single Responsibility Principle to argue that it should be two separate functions. When you're going to return a sequence of indeterminate length, it's best to use a Generator. A: I'd have two methods, one which updates the database and one which doesn't. Both could delegate to a common private method, if they share a lot of code. By separating the two methods, it becomes clear to callers what the different semantics are between the two, makes documenting the different methods easier, and clarifies what return types to expect. Since you can pull out shared code into private methods on the object, there's no worry about duplicating code. As for returning query results, it'll depend on whether you're loading all the results from the database before returning, or returning a cursor object. I'd be tempted to do something like the following: with db.executeQuery('SELECT * FROM my_table') as results: for row in results: print row['col1'], row['col2'] ... so the executeQuery method returns a ContextManager object (which cleans up any open connections, if needed), which also acts as a Generator. And the results from the generator act as read-only dicts.
Design question in Python: should this be one generic function or two specific ones?
I'm creating a basic database utility class in Python. I'm refactoring an old module into a class. I'm now working on an executeQuery() function, and I'm unsure of whether to keep the old design or change it. Here are the 2 options: (The old design:) Have one generic executeQuery method that takes the query to execute and a boolean commit parameter that indicates whether to commit (insert, update, delete) or not (select), and determines with an if statement whether to commit or to select and return. (This is the way I'm used to, but that might be because you can't have a function that sometimes returns something and sometimes doesn't in the languages I've worked with:) Have 2 functions, executeQuery and executeUpdateQuery (or something equivalent). executeQuery will execute a simple query and return a result set, while executeUpdateQuery will make changes to the DB (insert, update, delete) and return nothing. Is it accepted to use the first way? It seems unclear to me, but maybe it's more Pythonistic...? Python is very flexible, maybe I should take advantage of this feature that can't really be accomplished in this way in more strict languages... And a second part of this question, unrelated to the main idea - what is the best way to return query results in Python? Using which function to query the database, in what format...?
[ "It's propably just me and my FP fetish, but I think a function executed solely for side effects is very different from a non-destructive function that fetches some data, and therefore have different names. Especially if the generic function would do something different depending on exactly that (the part on the co...
[ 4, 2, 2 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0003662134_oop_python.txt
Q: Suspending function calls in Python for passing later (functional paradigm) I'm writing a python command line program which has some interdependent options, I would like for the user to be able to enter the options in whichever order they please. Currently I am using the getopts library to parse the command line options, unfortunately that parses them in-order. I've thrown together a system of boolean flags to leave the processing of certain command line arguments until the one they're dependent on is processed, however I had the idea of using a Priority Queue of function calls which would execute after all the command line options are parsed. I know that Python can store functions under variable names, but that seems to call the function at the same time. For example: help = obj.PrintHelp() heapq.heappush(commandQ, (0, help)) Will print the help dialog immediately. How would I go about implementing my code such that it won't call PrintHelp() immediately upon assigning it a name. EDIT: Oh i just realized I was pushing into a queue called help, that's my mistake. Thanks for the tip on removing the () after PrintHelp. What if I want to now call a function that requires more than the self argument? myFun = obj.parseFile(path) heapq.heappush(commandQ, (1, myFun)) Would I just make the tuple bigger and take the command line argument? A: If you heappush like this: myFun = obj.parseFile heapq.heappush(commandQ, (1, myFun, path)) then to later call the function, you could do this: while commandQ: x=heapq.heappop(commandQ) func=x[1] args=x[2:] func(*args) Use help = obj.PrintHelp without the parentheses. This makes help reference the function. Later, you can call the function with help(). Note also (if I understand your situation correctly), you could just use the optparse or (if you have Python2.7 or better) argparse modules in the standard library to handle the command-line options in any order. PS. help is a built-in function in Python. Naming a variable help overrides the built-in, making it difficult (though not impossible) to access the built-in. Generally, it's a good idea not to overwrite the names of built-ins. A: Instead of using getopts, I would suggest using optparse (argparse, if you are using a newer python version): most probably, you will get everything you need, already implemented. That said, in your example code, you are actually calling the function, while you should simply get its name: help = obj.PrintHelp heapq.heappush(help, (0, help)) A: If you want to store a complete function call in Python, you can do it one of two ways: # option 1: hold the parameters separately # I've also skipped saving the function in a 'help' variable' heapq.heappush(commandQ, (0, obj.PrintHelp, param1, param2)) # later: command = commandQ[0] heapq.heappop(commandQ) command[1](*command[2:]) # call the function (second item) with args (remainder of items) Alternatively, you can use a helper to package the arguments up via lambda: # option 2: build a no-argument anonymous function that knows what arguments # to give the real one # module scope def makeCall(func, *args): return lambda: func(*args) # now you can: help = makeCall(obj.PrintHelp, param1, param2) heapq.heappush(commandQ, (0, help)) If you need keyword arguments, let me know and I'll edit to take care of those too.
Suspending function calls in Python for passing later (functional paradigm)
I'm writing a python command line program which has some interdependent options, I would like for the user to be able to enter the options in whichever order they please. Currently I am using the getopts library to parse the command line options, unfortunately that parses them in-order. I've thrown together a system of boolean flags to leave the processing of certain command line arguments until the one they're dependent on is processed, however I had the idea of using a Priority Queue of function calls which would execute after all the command line options are parsed. I know that Python can store functions under variable names, but that seems to call the function at the same time. For example: help = obj.PrintHelp() heapq.heappush(commandQ, (0, help)) Will print the help dialog immediately. How would I go about implementing my code such that it won't call PrintHelp() immediately upon assigning it a name. EDIT: Oh i just realized I was pushing into a queue called help, that's my mistake. Thanks for the tip on removing the () after PrintHelp. What if I want to now call a function that requires more than the self argument? myFun = obj.parseFile(path) heapq.heappush(commandQ, (1, myFun)) Would I just make the tuple bigger and take the command line argument?
[ "If you heappush like this:\nmyFun = obj.parseFile\nheapq.heappush(commandQ, (1, myFun, path))\n\nthen to later call the function, you could do this:\nwhile commandQ:\n x=heapq.heappop(commandQ)\n func=x[1]\n args=x[2:]\n func(*args)\n\n\nUse\nhelp = obj.PrintHelp\n\nwithout the parentheses. This makes ...
[ 2, 1, 0 ]
[]
[]
[ "functional_programming", "python", "suspend" ]
stackoverflow_0003662115_functional_programming_python_suspend.txt
Q: Making HTTP POST request I'm trying to make a POST request to retrieve information about a book. Here is the code that returns HTTP code: 302, Moved import httplib, urllib params = urllib.urlencode({ 'isbn' : '9780131185838', 'catalogId' : '10001', 'schoolStoreId' : '15828', 'search' : 'Search' }) headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"} conn = httplib.HTTPConnection("bkstr.com:80") conn.request("POST", "/webapp/wcs/stores/servlet/BuybackSearch", params, headers) response = conn.getresponse() print response.status, response.reason data = response.read() conn.close() When I try from a browser, from this page: http://www.bkstr.com/webapp/wcs/stores/servlet/BuybackMaterialsView?langId=-1&catalogId=10001&storeId=10051&schoolStoreId=15828 , it works. What am I missing in my code? EDIT: Here's what I get when I call print response.msg 302 Moved Date: Tue, 07 Sep 2010 16:54:29 GMT Vary: Host,Accept-Encoding,User-Agent Location: http://www.bkstr.com/webapp/wcs/stores/servlet/BuybackSearch X-UA-Compatible: IE=EmulateIE7 Content-Length: 0 Content-Type: text/plain; charset=utf-8 Seems that the location points to the same url I'm trying to access in the first place? EDIT2: I've tried using urllib2 as suggested here. Here is the code: import urllib, urllib2 url = 'http://www.bkstr.com/webapp/wcs/stores/servlet/BuybackSearch' values = {'isbn' : '9780131185838', 'catalogId' : '10001', 'schoolStoreId' : '15828', 'search' : 'Search' } data = urllib.urlencode(values) req = urllib2.Request(url, data) response = urllib2.urlopen(req) print response.geturl() print response.info() the_page = response.read() print the_page And here is the output: http://www.bkstr.com/webapp/wcs/stores/servlet/BuybackSearch Date: Tue, 07 Sep 2010 16:58:35 GMT Pragma: No-cache Cache-Control: no-cache Expires: Thu, 01 Jan 1970 00:00:00 GMT Set-Cookie: JSESSIONID=0001REjqgX2axkzlR6SvIJlgJkt:1311s25dm; Path=/ Vary: Accept-Encoding,User-Agent X-UA-Compatible: IE=EmulateIE7 Content-Length: 0 Connection: close Content-Type: text/html; charset=utf-8 Content-Language: en-US Set-Cookie: TSde3575=225ec58bcb0fdddfad7332c2816f1f152224db2f71e1b0474c866f3b; Path=/ A: Their server seems to want you to acquire the proper cookie. This works: import urllib, urllib2, cookielib cookie_jar = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie_jar)) urllib2.install_opener(opener) # acquire cookie url_1 = 'http://www.bkstr.com/webapp/wcs/stores/servlet/BuybackMaterialsView?langId=-1&catalogId=10001&storeId=10051&schoolStoreId=15828' req = urllib2.Request(url_1) rsp = urllib2.urlopen(req) # do POST url_2 = 'http://www.bkstr.com/webapp/wcs/stores/servlet/BuybackSearch' values = dict(isbn='9780131185838', schoolStoreId='15828', catalogId='10001') data = urllib.urlencode(values) req = urllib2.Request(url_2, data) rsp = urllib2.urlopen(req) content = rsp.read() # print result import re pat = re.compile('Title:.*') print pat.search(content).group() # OUTPUT: Title:&nbsp;&nbsp;Statics & Strength of Materials for Arch (w/CD)<br /> A: You might want to use the urllib2 module which should handle redirects better. Here's an example of POSTING with urllib2. A: Perhaps that's what the browser gets, and you'll just have to follow the 302 redirect. If all else fails, you can monitor the dialogue between Firefox and the Web Server using FireBug or tcpdump or wireshark, and see which HTTP headers are different. Possibly it's just the User Agent: header.
Making HTTP POST request
I'm trying to make a POST request to retrieve information about a book. Here is the code that returns HTTP code: 302, Moved import httplib, urllib params = urllib.urlencode({ 'isbn' : '9780131185838', 'catalogId' : '10001', 'schoolStoreId' : '15828', 'search' : 'Search' }) headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"} conn = httplib.HTTPConnection("bkstr.com:80") conn.request("POST", "/webapp/wcs/stores/servlet/BuybackSearch", params, headers) response = conn.getresponse() print response.status, response.reason data = response.read() conn.close() When I try from a browser, from this page: http://www.bkstr.com/webapp/wcs/stores/servlet/BuybackMaterialsView?langId=-1&catalogId=10001&storeId=10051&schoolStoreId=15828 , it works. What am I missing in my code? EDIT: Here's what I get when I call print response.msg 302 Moved Date: Tue, 07 Sep 2010 16:54:29 GMT Vary: Host,Accept-Encoding,User-Agent Location: http://www.bkstr.com/webapp/wcs/stores/servlet/BuybackSearch X-UA-Compatible: IE=EmulateIE7 Content-Length: 0 Content-Type: text/plain; charset=utf-8 Seems that the location points to the same url I'm trying to access in the first place? EDIT2: I've tried using urllib2 as suggested here. Here is the code: import urllib, urllib2 url = 'http://www.bkstr.com/webapp/wcs/stores/servlet/BuybackSearch' values = {'isbn' : '9780131185838', 'catalogId' : '10001', 'schoolStoreId' : '15828', 'search' : 'Search' } data = urllib.urlencode(values) req = urllib2.Request(url, data) response = urllib2.urlopen(req) print response.geturl() print response.info() the_page = response.read() print the_page And here is the output: http://www.bkstr.com/webapp/wcs/stores/servlet/BuybackSearch Date: Tue, 07 Sep 2010 16:58:35 GMT Pragma: No-cache Cache-Control: no-cache Expires: Thu, 01 Jan 1970 00:00:00 GMT Set-Cookie: JSESSIONID=0001REjqgX2axkzlR6SvIJlgJkt:1311s25dm; Path=/ Vary: Accept-Encoding,User-Agent X-UA-Compatible: IE=EmulateIE7 Content-Length: 0 Connection: close Content-Type: text/html; charset=utf-8 Content-Language: en-US Set-Cookie: TSde3575=225ec58bcb0fdddfad7332c2816f1f152224db2f71e1b0474c866f3b; Path=/
[ "Their server seems to want you to acquire the proper cookie. This works:\nimport urllib, urllib2, cookielib\n\ncookie_jar = cookielib.CookieJar()\nopener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie_jar))\nurllib2.install_opener(opener)\n\n# acquire cookie\nurl_1 = 'http://www.bkstr.com/webapp/wcs/st...
[ 26, 4, 0 ]
[]
[]
[ "http", "post", "python", "urllib" ]
stackoverflow_0003659595_http_post_python_urllib.txt
Q: Python Tkinter Text Widget .get method error I'm very new to Python, sort of following Dive into Python 2 and wanted to dabble with some Tkinter programming. I've tried to make a little program that takes 3 sets of words and makes combinations of each word in the 3 sets to make keywords for websites. When I run the script, the GUI appears as expected, but I get the following error when I click on the Create Combinations button Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1413, in __call__ return self.func(*args) File "combomaker.py", line 34, in makeCombinations primaryraw = primaryKeyWordsBox.get() AttributeError: 'NoneType' object has no attribute 'get' The code I'm trying to fix #!/usr/bin/env python from Tkinter import * primaryKeyWordsLabel = None primaryKeyWordsBox = None secondaryKeyWordsLabel = None secondaryKeyWordsBox = None tertiaryKeyWordsLabel = None tertiaryKeyWordsBox = None class Application(Frame): def __init__(self, master=None, padx = 10, pady= 10): Frame.__init__(self, master) self.grid() self.createWidgets() def createWidgets(self): self.primaryKeyWordsLabel = LabelFrame(text="Primary Key Words", padx=10, pady=10) self.primaryKeyWordsLabel.grid() self.primaryKeyWordsBox = Text(primaryKeyWordsLabel, autoseparators=True, height=5, undo=True) self.primaryKeyWordsBox.grid() self.secondaryKeyWordsLabel = LabelFrame(text="Secondary Key Words", padx=10, pady=10) self.secondaryKeyWordsLabel.grid() self.secondaryKeyWordsBox = Text(secondaryKeyWordsLabel, autoseparators=True, height=5, undo=True) self.secondaryKeyWordsBox.grid() self.tertiaryKeyWordsLabel = LabelFrame(text="Tertiary Key Words", padx=10, pady=10) self.tertiaryKeyWordsLabel.grid() self.tertiaryKeyWordsBox = Text(tertiaryKeyWordsLabel, autoseparators=True, height=5, undo=True) self.tertiaryKeyWordsBox.grid() self.goButton = Button(text="Create Combinations", command=makeCombinations) self.goButton.grid() def makeCombinations(): primaryraw = primaryKeyWordsBox.get() primary = primaryraw.split(', ') secondaryraw = secondaryKeyWordsBox.get() secondary = secondaryraw.split(', ') tertiaryraw = tertiaryKeyWordsBox.get() tertiary = tertiaryraw.split(', ') output=[] filename = "output.txt" for i in range(len(primary)): for j in range(len(secondary)): for k in range(len(tertiary)): rawcombo=str(primary[i])+" "+str(secondary[j])+" "+str(tertiary[k]) output.append(rawcombo) FILE = open(filename, w) for combo in output: FILE.write(combo+",\n") FILE.close() app = Application() app.master.title("Keyword Generator") app.mainloop() I may have thrown myself into GUI programming too fast, this is my first attempt at any GUI work but not my first time programming. Many thanks in advance :) A: You're trying to access primaryKeyWordsBox outside the class Application in the (free) function makeCombinations(..). You could make makeCombinations(..) a member of Application by indenting it like the other member functions and add the self argument: def makeCombinations(self): You should modify the binding of the makeCombinations(..) to the button: ...,command = self.makeCombinations) Then you'll have to add self. when you're trying to access the members of this class: primaryraw = self.primaryKeyWordsBox.get(1.0,END) ... secondaryraw = self.secondaryKeyWordsBox.get(1.0,END) ... tertiaryraw = self.tertiaryKeyWordsBox.get(1.0,END) (I found the examples how to use get here). If you want to open a file for writing, you should do: FILE = open(filename, "w") instead of FILE = open(filename, w)
Python Tkinter Text Widget .get method error
I'm very new to Python, sort of following Dive into Python 2 and wanted to dabble with some Tkinter programming. I've tried to make a little program that takes 3 sets of words and makes combinations of each word in the 3 sets to make keywords for websites. When I run the script, the GUI appears as expected, but I get the following error when I click on the Create Combinations button Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1413, in __call__ return self.func(*args) File "combomaker.py", line 34, in makeCombinations primaryraw = primaryKeyWordsBox.get() AttributeError: 'NoneType' object has no attribute 'get' The code I'm trying to fix #!/usr/bin/env python from Tkinter import * primaryKeyWordsLabel = None primaryKeyWordsBox = None secondaryKeyWordsLabel = None secondaryKeyWordsBox = None tertiaryKeyWordsLabel = None tertiaryKeyWordsBox = None class Application(Frame): def __init__(self, master=None, padx = 10, pady= 10): Frame.__init__(self, master) self.grid() self.createWidgets() def createWidgets(self): self.primaryKeyWordsLabel = LabelFrame(text="Primary Key Words", padx=10, pady=10) self.primaryKeyWordsLabel.grid() self.primaryKeyWordsBox = Text(primaryKeyWordsLabel, autoseparators=True, height=5, undo=True) self.primaryKeyWordsBox.grid() self.secondaryKeyWordsLabel = LabelFrame(text="Secondary Key Words", padx=10, pady=10) self.secondaryKeyWordsLabel.grid() self.secondaryKeyWordsBox = Text(secondaryKeyWordsLabel, autoseparators=True, height=5, undo=True) self.secondaryKeyWordsBox.grid() self.tertiaryKeyWordsLabel = LabelFrame(text="Tertiary Key Words", padx=10, pady=10) self.tertiaryKeyWordsLabel.grid() self.tertiaryKeyWordsBox = Text(tertiaryKeyWordsLabel, autoseparators=True, height=5, undo=True) self.tertiaryKeyWordsBox.grid() self.goButton = Button(text="Create Combinations", command=makeCombinations) self.goButton.grid() def makeCombinations(): primaryraw = primaryKeyWordsBox.get() primary = primaryraw.split(', ') secondaryraw = secondaryKeyWordsBox.get() secondary = secondaryraw.split(', ') tertiaryraw = tertiaryKeyWordsBox.get() tertiary = tertiaryraw.split(', ') output=[] filename = "output.txt" for i in range(len(primary)): for j in range(len(secondary)): for k in range(len(tertiary)): rawcombo=str(primary[i])+" "+str(secondary[j])+" "+str(tertiary[k]) output.append(rawcombo) FILE = open(filename, w) for combo in output: FILE.write(combo+",\n") FILE.close() app = Application() app.master.title("Keyword Generator") app.mainloop() I may have thrown myself into GUI programming too fast, this is my first attempt at any GUI work but not my first time programming. Many thanks in advance :)
[ "You're trying to access\nprimaryKeyWordsBox\n\noutside the class Application in the (free) function makeCombinations(..).\nYou could make makeCombinations(..) a member of Application by indenting it like the other member functions and add the self argument:\n def makeCombinations(self):\n\nYou should modify the bi...
[ 1 ]
[]
[]
[ "python", "tkinter", "user_interface" ]
stackoverflow_0003662902_python_tkinter_user_interface.txt
Q: python comparing dictionaries level: beginner word= 'even' dict2 = {'i': 1, 'n': 1, 'e': 1, 'l': 2, 'v': 2} i want to know if word is entirely composed of letters in dict2 my approach: step 1 : convert word to dictionary(dict1) step2: for k in dict1.keys(): if k in dict2: if dict1[k] != dict2[k]: return False return True by adding a print statement i can see that this simply ends too early e.g. as soon as the first IF condition is met the loop exits and i won't get a correct answer. i think this is easy but google and python doc didn't return any good hints so i'm trying here. Thanks Baba UPDATE the number of times that each letter ocurs in the word needs to be smaller or equal to the number of times it apears in dict2. That way i am guaranteed that word is entirely made up of elements of dict2. for k in word.keys(): # word has ben converted to key already if k not in hand: return False elif k in hand: if word[k] > hand[k]: return False return True A: >>> word= 'even' >>> dict2 = {'i': 1, 'n': 1, 'e': 1, 'l': 2, 'v': 2} >>> set(word).issubset(set(dict2.keys())) True A: Unless you need it for something else, don't bother constructing dict1. Just do this: for c in word: if c not in dict2: return False return True Of course, you could also use a set instead of a dict to hold the letters. A: in your code, just move the "return True" to be outside all the loops. That is, only return true if your loops complete without finding a non-matching value. Whether that's truly what you want for your actual code is hard to say, but moving the "return True" fixes the logic error in the code you posted. A: You only want to return true after all the checks, so stick it after the loop. Here it is as a straight modification of your code: for k in dict1.keys(): if k in dict2: if dict1[k] != dict2[k]: return False return True A: >>> word = {'e':2, 'v':1, 'n':1} >>> hand= {'i': 1, 'n': 1, 'e': 1, 'l': 2, 'v': 2} >>> all(k in hand and v <= hand[k] for k,v in word.items()) False and now see the true case >>> hand['e']+=1 >>> all(k in hand and v <= hand[k] for k,v in word.items()) True
python comparing dictionaries
level: beginner word= 'even' dict2 = {'i': 1, 'n': 1, 'e': 1, 'l': 2, 'v': 2} i want to know if word is entirely composed of letters in dict2 my approach: step 1 : convert word to dictionary(dict1) step2: for k in dict1.keys(): if k in dict2: if dict1[k] != dict2[k]: return False return True by adding a print statement i can see that this simply ends too early e.g. as soon as the first IF condition is met the loop exits and i won't get a correct answer. i think this is easy but google and python doc didn't return any good hints so i'm trying here. Thanks Baba UPDATE the number of times that each letter ocurs in the word needs to be smaller or equal to the number of times it apears in dict2. That way i am guaranteed that word is entirely made up of elements of dict2. for k in word.keys(): # word has ben converted to key already if k not in hand: return False elif k in hand: if word[k] > hand[k]: return False return True
[ ">>> word= 'even'\n>>> dict2 = {'i': 1, 'n': 1, 'e': 1, 'l': 2, 'v': 2}\n>>> set(word).issubset(set(dict2.keys()))\nTrue\n\n", "Unless you need it for something else, don't bother constructing dict1. Just do this:\nfor c in word:\n if c not in dict2:\n return False\nreturn True\n\nOf course, you could ...
[ 4, 1, 0, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0003662297_dictionary_python.txt
Q: Why does my PyQt application open in the background on Mac OS X? I've got a PyQt app which I'm developing in Mac OS X, and whenever I try launching the app, it always is the very bottom application on the stack. So after launching, I always need to command+tab all the way to the end of the application list to switch focus to it. I read that this behavior can be fixed by launching the app with the "pythonw" command, but this doesn't make any difference, nor does renaming my script to have the .pyw extension (or doing both). What could be causing this problem? A: Based on this article http://diotavelli.net/PyQtWiki/PyInstallerOnMacOSX, you need to call app.raise_() after app.show() ui = MainWindow() ui.show() ui.raise_() ref: http://www.mail-archive.com/pyqt@riverbankcomputing.com/msg18945.html
Why does my PyQt application open in the background on Mac OS X?
I've got a PyQt app which I'm developing in Mac OS X, and whenever I try launching the app, it always is the very bottom application on the stack. So after launching, I always need to command+tab all the way to the end of the application list to switch focus to it. I read that this behavior can be fixed by launching the app with the "pythonw" command, but this doesn't make any difference, nor does renaming my script to have the .pyw extension (or doing both). What could be causing this problem?
[ "Based on this article http://diotavelli.net/PyQtWiki/PyInstallerOnMacOSX, you need to call app.raise_() after app.show()\nui = MainWindow()\nui.show()\nui.raise_()\n\nref: http://www.mail-archive.com/pyqt@riverbankcomputing.com/msg18945.html\n" ]
[ 14 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0003662559_pyqt_python.txt
Q: Can i control PSFTP from a Python script? i want to run and control PSFTP from a Python script in order to get log files from a UNIX box onto my Windows machine. I can start up PSFTP and log in but when i try to run a command remotely such as 'cd' it isn't recognised by PSFTP and is just run in the terminal when i close PSFTP. The code which i am trying to run is as follows: import os os.system("<directory> -l <username> -pw <password>" ) os.system("cd <anotherDirectory>") i was just wondering if this is actually possible. Or if there is a better way to do this in Python. Thanks. A: You'll need to run PSFTP as a subprocess and speak directly with the process. os.system spawns a separate subshell each time it's invoked so it doesn't work like typing commands sequentially into a command prompt window. Take a look at the documentation for the standard Python subprocess module. You should be able to accomplish your goal from there. Alternatively, there are a few Python SSH packages available such as paramiko and Twisted. If you're already happy with PSFTP, I'd definitely stick with trying to make it work first though. Subprocess module hint: # The following line spawns the psftp process and binds its standard input # to p.stdin and its standard output to p.stdout p = subprocess.Popen('psftp -l testuser -pw testpass'.split(), stdin=subprocess.PIPE, stdout=subprocess.PIPE) # Send the 'cd some_directory' command to the process as if a user were # typing it at the command line p.stdin.write('cd some_directory\n') A: This has sort of been answered in: SFTP in Python? (platform independent) http://www.lag.net/paramiko/ The advantage to the pure python approach is that you don't always need psftp installed.
Can i control PSFTP from a Python script?
i want to run and control PSFTP from a Python script in order to get log files from a UNIX box onto my Windows machine. I can start up PSFTP and log in but when i try to run a command remotely such as 'cd' it isn't recognised by PSFTP and is just run in the terminal when i close PSFTP. The code which i am trying to run is as follows: import os os.system("<directory> -l <username> -pw <password>" ) os.system("cd <anotherDirectory>") i was just wondering if this is actually possible. Or if there is a better way to do this in Python. Thanks.
[ "You'll need to run PSFTP as a subprocess and speak directly with the process. os.system spawns a separate subshell each time it's invoked so it doesn't work like typing commands sequentially into a command prompt window. Take a look at the documentation for the standard Python subprocess module. You should be able...
[ 2, 1 ]
[]
[]
[ "ftp", "python", "scripting", "sftp", "unix" ]
stackoverflow_0003659395_ftp_python_scripting_sftp_unix.txt
Q: Customize the output of forms in Django I have multiple forms in a Django project. I was trying to use the Django provided as_p for form displaying due to its simplicity but client wants the error list below the field. Django's as_p prints it above the field label. I rather not add a field printing loop in every template just for this small change. It seems like the least efficient way to go about it. Wanted to know what would other Django coders recommend for this. I was thinking there exists at least 3 options: -Customizing the Form object. This seems the most viable solution. Anyone know of any downsides to this? -Including a template which just handles form displaying. The problem is, this template must assume that the form is named a certain name. How about if I have multiple forms being passed with different names? Does anyone know how to address this issue? -Perhaps a custom filter? A quick Google search leads me to believe this is not a viable option but perhaps someone has information to the contrary. Examples would be greatly appreciated! A: Including a template which just handles form displaying. The problem is, this template must assume that the form is named a certain name. How about if I have multiple forms being passed with different names? Does anyone know how to address this issue? You could include your form template inside of with block and thus be able to send a value for a from name. You could also leave out the <form> tags from your form body template and just put them around include. I think these would be the easies solutions, and with taking advantage of template inheritance you could create quite flexible forms.
Customize the output of forms in Django
I have multiple forms in a Django project. I was trying to use the Django provided as_p for form displaying due to its simplicity but client wants the error list below the field. Django's as_p prints it above the field label. I rather not add a field printing loop in every template just for this small change. It seems like the least efficient way to go about it. Wanted to know what would other Django coders recommend for this. I was thinking there exists at least 3 options: -Customizing the Form object. This seems the most viable solution. Anyone know of any downsides to this? -Including a template which just handles form displaying. The problem is, this template must assume that the form is named a certain name. How about if I have multiple forms being passed with different names? Does anyone know how to address this issue? -Perhaps a custom filter? A quick Google search leads me to believe this is not a viable option but perhaps someone has information to the contrary. Examples would be greatly appreciated!
[ "\nIncluding a template which just\n handles form displaying. The problem\n is, this template must assume that the\n form is named a certain name. How\n about if I have multiple forms being\n passed with different names? Does\n anyone know how to address this issue?\n\nYou could include your form template ins...
[ 2 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0003663713_django_django_forms_python.txt
Q: do i need 32bit libxml2 for python on snow leopard? i'm having a hell of a time installing scrapy on my sl mbp. it requires libxml2, so i set about installing that. installing it from macports doesn't seem to pull down the python binding. installing it from source through scrapy's instructions (here) does install the python bindings, but when i run 'python -c "import libxml2"' i get an architecture mismatch: Traceback (most recent call last): File "<string>", line 1, in <module> File "libxml2.py", line 1, in <module> import libxml2mod ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site- packages/libxml2mod.so, 2): no suitable image found. Did find: /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site- packages/libxml2mod.so: mach-o, but wrong architecture when i explicitly build the libxml2 dlls to be 32bit, that error goes away, but then libxslt won't build because of some other library not being 32 bit. i'm afraid to keep pulling on that string. so the question is - is python 32bit only? am i doing something stupid here? edit - this is python 2.6 edit 2 - by popular demand, i'm consolidating @Ned Deily's awesome answer up here. all credit to him, i'm just posting the steps i took based on his response: if you've been screwing around with mac ports, (and haven't installed anything else through them that you need), nuke them. $ sudo rm -r /opt/local add the following to /opt/local/etc/macports/variants.conf to prevent downloading the entire unix library with the next commands +bash_completion +quartz +ssl +no_x11 +no_neon +no_tkinter +universal +libyaml -scientific install the macports version of python $ sudo port install python26 install the pre-reqs for scrapy sudo port install py26-libxml2 py26-twisted py26-openssl py26-simplejson py26-setuptools python_select sudo python_select python26 test that the correct python is selected: run $ which python, which should say something along the lines of '/opt/local/bin/python', and that in its own right should be a link to /opt/local/bin/python2.6. test that the correct architectures are present: run file 'which python' (the single quotes should be backticks, which should spit out (for intel macs running 10.6): /opt/local/bin/python2.6: Mach-O universal binary with 2 architectures /opt/local/bin/python2.6 (for architecture x86_64): Mach-O 64-bit executable x86_64 /opt/local/bin/python2.6 (for architecture i386): Mach-O executable i386 test that libxml installed successfully $ python -c 'import libxml2' if all is well, you should get no output. install scrapy sudo /opt/local/bin/easy_install-2.6 scrapy run through the streets (fully clothed) rejoicing that everything is done. again, thanks to ned for the detailed response. A: From the paths in your traceback, it appears you have installed and are trying to use the python.org python 2.6.4 (installed to /Library/Frameworks/Python.frameworks ...). That python is 32-bit only. By default on 10.6, MacPorts tries to install 64-bit versions of packages. You can change that for most MacPorts packages by specfying the +universal variant on your MacPorts install commands or by adding it to /opt/local/etc/macports/variants.conf. But, since you need a variety of packages, if you just need this for your own machine you'll likely find it much easier to just install a complete python2.6 64-bit solution using MacPorts. Other than scrapy itself, you should find nearly all of the packages you need already there. You'll need to modify your $PATH to add /opt/local/Library/Frameworks/Python.framework/Versions/2.6/bin and /opt/local/bin before any other directories with Python in them. Something like this should work (untested!): sudo port selfupdate # ensure you have the latest ports file information sudo port install py26-libxml2 py26-twisted py26-openssl py26-simplejson py26-setuptools python_select sudo python_select python26 # optionally make /opt/local/bin/python -> python2.6 sudo /opt/local/bin/easy_install-2.6 scrapy # or install manually cd /path/to/scrapy sudo /opt/local/bin/python2.6 setup.py install EDIT: For 10.6, due to some issues with lack of Tk support in 64-bit mode, Tk defaults to the X11 version which you probably neither want nor need. I add the following variants to /opt/local/etc/macports/variants.conf for 10.6 (not all of them are applicable to python and friends): +bash_completion +quartz +ssl +no_x11 +no_neon +no_tkinter +universal +libyaml -scientific EDIT: If MacPorts is installed properly, you should see something like this on 10.6: $ ls -l /opt/local/bin/python2.6 lrwxr-xr-x 1 root wheel 73 Oct 28 20:25 /opt/local/bin/python2.6@ -> /opt/local/Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6 $ file /opt/local/bin/python2.6 /opt/local/bin/python2.6: Mach-O universal binary with 2 architectures /opt/local/bin/python2.6 (for architecture x86_64): Mach-O 64-bit executable x86_64 /opt/local/bin/python2.6 (for architecture i386): Mach-O executable i386 That's if you've added the +universal variant, otherwise you may just see a single x86_64 or i386 architecture. When using relative paths, make sure your shell $PATH has the two MacPorts directories first: $ echo $PATH /opt/local/Library/Frameworks/Python.framework/Versions/2.6/bin:/opt/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin ... You may need to edit your ~/.bash_profile or other shell file to make that change "permanent". If you want the bare python command to refer to the MacPorts Python, make sure to run the python_select command shown above. If you are still having problems, a nice thing about MacPorts is it is easy to delete and start over again; just: $ sudo rm -r /opt/local and download the MacPorts 10.6 installer. But you really shouldn't have to do that. And I think it would really be in your best interests to get this fixed and working as it will likely save you lots of headaches in the future. A: I have a small note to contribute. While attempting to follow-along on this post, I began with three installs of Python: The default Apple Python 2.5.1 located at: /usr/bin/python A version located: /Library/Frameworks/Python.framework/Versions/2.7 And a Macport version located: /opt/local/bin/python2.6 My trouble was that: $ python would always default to the 2.7 when I needed it to use the Macports version. The following did not help: $ sudo python_select python26 I even removed the 2.7 version which caused only an error. I figured out I needed to change the default path to the Macports version using the following: $ PATH=$PATH\:/opt/local/bin ; export PATH And then reinitiate the ports, etc. Finally, I was not able to reference the scrapy-ctl.py file by default through these instructions so I had to reference the scrapy-ctl.py file directly /opt/local/Library/Frameworks/Python.framework/Versions/2.6/bin/scrapy-ctl.py UPDATE A quick addendum to this post with instructions to create the link, found on the Scrapy site (#2 and #3). Starting with #2, "Add Scrapy to your Python Path" sudo ln -s /opt/local/Library/Frameworks/Python.framework/Versions/2.6/bin/scrapy-ctl.py /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scrapy And #3, "Make the scrapy command available" sudo ln -s /opt/local/Library/Frameworks/Python.framework/Versions/2.6/bin/scrapy-ctl.py /usr/local/bin/scrapy A: Trying to install but still struggling. When I: sudo /opt/local/bin/easy_install-2.6 scrapy I get error message and it stops AttributeError: 'NoneType' object has no attribute 'get' Instead I build Scrapy from scratch which works fine. Then I try what you write cd /path/to/scrapy sudo /opt/local/bin/python2.6 setup.py install Where is /path/to/scrapy? Is that: /opt/local/Library/Frameworks/Python.framework/Versions/2.6/bin/scrapy-ctl.py or /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/Scrapy-0.8-py2.6.egg or is somewhere else? A: Credit to @Ned Deily These steps seem to work if you want to run Scrapy 0.8 on OS X 10.6. It uses Macports install of Python 2.6 rather than the one bundled with the OS. Steps assume Macports is not installed yet. Get latest MacPorts installer from here and install: http://www.macports.org/install.php sudo port install py26-libxml2 py26-twisted py26-openssl py26-simplejson py26-setuptools python_select sudo /opt/local/bin/easy_install-2.6 scrapy Change your ~.profile to: export PATH=/opt/local/Library/Frameworks/Python.framework/Versions/2.6/bin:/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:$PATH
do i need 32bit libxml2 for python on snow leopard?
i'm having a hell of a time installing scrapy on my sl mbp. it requires libxml2, so i set about installing that. installing it from macports doesn't seem to pull down the python binding. installing it from source through scrapy's instructions (here) does install the python bindings, but when i run 'python -c "import libxml2"' i get an architecture mismatch: Traceback (most recent call last): File "<string>", line 1, in <module> File "libxml2.py", line 1, in <module> import libxml2mod ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site- packages/libxml2mod.so, 2): no suitable image found. Did find: /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site- packages/libxml2mod.so: mach-o, but wrong architecture when i explicitly build the libxml2 dlls to be 32bit, that error goes away, but then libxslt won't build because of some other library not being 32 bit. i'm afraid to keep pulling on that string. so the question is - is python 32bit only? am i doing something stupid here? edit - this is python 2.6 edit 2 - by popular demand, i'm consolidating @Ned Deily's awesome answer up here. all credit to him, i'm just posting the steps i took based on his response: if you've been screwing around with mac ports, (and haven't installed anything else through them that you need), nuke them. $ sudo rm -r /opt/local add the following to /opt/local/etc/macports/variants.conf to prevent downloading the entire unix library with the next commands +bash_completion +quartz +ssl +no_x11 +no_neon +no_tkinter +universal +libyaml -scientific install the macports version of python $ sudo port install python26 install the pre-reqs for scrapy sudo port install py26-libxml2 py26-twisted py26-openssl py26-simplejson py26-setuptools python_select sudo python_select python26 test that the correct python is selected: run $ which python, which should say something along the lines of '/opt/local/bin/python', and that in its own right should be a link to /opt/local/bin/python2.6. test that the correct architectures are present: run file 'which python' (the single quotes should be backticks, which should spit out (for intel macs running 10.6): /opt/local/bin/python2.6: Mach-O universal binary with 2 architectures /opt/local/bin/python2.6 (for architecture x86_64): Mach-O 64-bit executable x86_64 /opt/local/bin/python2.6 (for architecture i386): Mach-O executable i386 test that libxml installed successfully $ python -c 'import libxml2' if all is well, you should get no output. install scrapy sudo /opt/local/bin/easy_install-2.6 scrapy run through the streets (fully clothed) rejoicing that everything is done. again, thanks to ned for the detailed response.
[ "From the paths in your traceback, it appears you have installed and are trying to use the python.org python 2.6.4 (installed to /Library/Frameworks/Python.frameworks ...). That python is 32-bit only. By default on 10.6, MacPorts tries to install 64-bit versions of packages. You can change that for most MacPort...
[ 5, 1, 0, 0 ]
[]
[]
[ "libxml2", "macos", "osx_snow_leopard", "python" ]
stackoverflow_0002353957_libxml2_macos_osx_snow_leopard_python.txt
Q: Python: why does my list change after I've retrieved it from an object Simple question, I've scaled down a problem I'm having where a list which I've retrieve from an object is changing when I append more data to the object. Not to the list. Can anyone help my understand the behavior of python? class a(): def __init__(self): self.log = [] def clearLog(self): del self.log[:] def appendLog(self, info): self.log.append(str(info)) def getLog(self): return self.log if __name__ == '__main__': obj = a() obj.appendLog("Hello") # get an instance as of this moment.... list = obj.getLog() print list obj.appendLog("World") # print list, BUT we want the instance that was obtained # before the new appendage. print list OutPut: ['Hello'] ['Hello', 'World'] A: When you code `list = obj.getLog()` (ignoring -- just for a second -- what a terrible idea it is to use identifiers that shadow builtins!!!) you're saying: "make name list refer to exactly the same object that obj.getLog() returns" -- which as we know from the code for class a is obj.log. So of course since now you have one list object with two names, when you alter that object through either name, all alterations will be fully visible from both names, of course -- remember, there is just one object, you're just using multiple names for it! You never asked for a copy, so of course Python made no copies. When you want a copy, instead of the original, ask for one! When you know the type you require (here, a list), the best way is to call the type, i.e.: mylist = list(obj.getLog()) This of course becomes impossible if you choose to trample all over the builtins with your identifiers -- -- which is a good part of why such identifier choice is a BAD idea (I can't stress that enough: it's hard to think of any worse style choice, to use in your Python coding, than such naming). So, I've renamed the identifier to mylist (and of course you need to rename it in the two print statements). You could use highly unreadable or slower approaches to make up for the wanton destruction of the normal functionality of built-in identifier list, of course -- e.g.: import copy list = copy.copy(obj.getLog()) # somewhat slower or list = obj.getLog()[:] # traditional, but ECCH or temp = obj.getLog() list = type(temp)(temp) # abstruse but BY FAR the simplest, cleanest, most recommended approach is to NOT name your identifiers the same as Python built-ins (it's also a nice idea to avoid naming them just like modules in the standard Python library, for similar though a bit weaker reasons). A: The only place you create a new list is in the constructor, with the statement: self.log = [] Later, when you do: list = obj.getLog() just puts a reference to the same list in a new variable (note, don't use list as a variable name, since it shadows the type). It does not create or clone a list in any way. If you want to clone it, do: def getLog(self): return list(self.log) You can also use a tuple (read-only sequence), if that's appropriate: def getLog(self): return tuple(self.log) This may help minimize confusion about which should be modified. A: Look at this method: def getLog(self): return self.log You've returned a reference to self.log and assigned it to list. Now they both point to the same list on the heap. When you change self.log, list points to the same location in memory. You'd have to make a clone and assign that to list for the two to be independent. A: Objects are passed around in Python by reference - Python doesn't make copies for you. The line return self.log returns a reference to the list object used internally by obj. This means that after the line list = obj.getLog() your list variable refers to the same object as obj.log. To acquire a copy instead, use Python's slice syntax: list = obj.getLog()[:] A: What this boils down to is that languages like python and ruby try to make it easy for people to refer to arbitrary, complex objects - associative containers of lists of associative containers and such like. These get too complex to index into repeatedly (and it would be slow), so scripters want to be able to say galleries = world['asia']['japan'][3]['Tokyo']['Galleries'] then make queries against or updates to the galleries in Tokyo. That is sometimes convenient (when doing updates), sometimes - as in your case where you think you've made a private copy of some data and want to massage one without affecting the other - very confusing and inconvenient. But, most scripting languages will adopt this same strategy because to make full independent copies of the data each time would be hideously slow for the common case of just wanting a "handle" through which to inspect some part of the larger data structure. It's ugly and inconsistent with the way they handle basic types like numbers and textual strings. As others have said, you need to use: new_list = original_list[:] # slice off a complete copy of a list new_dictionary = original_dictionary.copy() # for dictionaries
Python: why does my list change after I've retrieved it from an object
Simple question, I've scaled down a problem I'm having where a list which I've retrieve from an object is changing when I append more data to the object. Not to the list. Can anyone help my understand the behavior of python? class a(): def __init__(self): self.log = [] def clearLog(self): del self.log[:] def appendLog(self, info): self.log.append(str(info)) def getLog(self): return self.log if __name__ == '__main__': obj = a() obj.appendLog("Hello") # get an instance as of this moment.... list = obj.getLog() print list obj.appendLog("World") # print list, BUT we want the instance that was obtained # before the new appendage. print list OutPut: ['Hello'] ['Hello', 'World']
[ "When you code\n`list = obj.getLog()`\n\n(ignoring -- just for a second -- what a terrible idea it is to use identifiers that shadow builtins!!!) you're saying: \"make name list refer to exactly the same object that obj.getLog() returns\" -- which as we know from the code for class a is obj.log. So of course since...
[ 4, 3, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003663760_python.txt
Q: replace an item in a html tag spanning multiple lines I have a text file with html: Blah, blah, blah some text is here. <div> something here something else </body></html> so far, if the tags are on one line this works: textfile = open("htmlfile.txt", "r+") text = textfile.read() a = re.search('<div.+?<\/html>', text) repstr = c.group(0) text = text.replace(repstr, '', 1) works fine, I don't have nested tags. But if the tags are on multiple lines, like the first example, it doesn't work! what can I use to test multiple lines? A: By default, the dot doesn't match new lines. To make it match new lines, you need to compile the regex with the flag re.DOTALL, eg: a = re.search('<div.+?<\/html>', text, re.DOTALL) That being said, you really shouldn't use regex to parse HTML. Do yourself a favor and use an XML parser like BeautifulSoup.
replace an item in a html tag spanning multiple lines
I have a text file with html: Blah, blah, blah some text is here. <div> something here something else </body></html> so far, if the tags are on one line this works: textfile = open("htmlfile.txt", "r+") text = textfile.read() a = re.search('<div.+?<\/html>', text) repstr = c.group(0) text = text.replace(repstr, '', 1) works fine, I don't have nested tags. But if the tags are on multiple lines, like the first example, it doesn't work! what can I use to test multiple lines?
[ "By default, the dot doesn't match new lines. To make it match new lines, you need to compile the regex with the flag re.DOTALL, eg:\na = re.search('<div.+?<\\/html>', text, re.DOTALL)\n\n\nThat being said, you really shouldn't use regex to parse HTML.\nDo yourself a favor and use an XML parser like BeautifulSoup.\...
[ 0 ]
[]
[]
[ "python", "regex", "replace" ]
stackoverflow_0003664090_python_regex_replace.txt
Q: Calling a function with variable number of arguments with an array in C++ (like python's * operator) I'm trying to write a v8 module in C++; there, the functions receive a variable number of arguments in an array. I want to take that array and call a function like gettext and printf that receives a formatted string and it's necessary args. The thing is, how can one take an array and send the elements as arguments to one of those functions? In python, I'd do something like this: def the_function(s, who, hmany): print s%(who, hmany) the_args = ["Hello, %s from the %d of us", "world", 3] the_function(*the_args) How can that be accomplished in C++? (I'm using v8 and node.js, so maybe there's a function or class somewhere in those namespaces that I'm not aware of) A: Here's one way: void foo(const char *firstArg, ...) { va_list argList; va_start(argList, firstArg); vprintf(firstArg, argList); va_end(argList); } Assuming that you're trying to do a printf. Basically, va_list is the key, and you can use it to either examine the arguments, or pass them to other functions that take va_list.
Calling a function with variable number of arguments with an array in C++ (like python's * operator)
I'm trying to write a v8 module in C++; there, the functions receive a variable number of arguments in an array. I want to take that array and call a function like gettext and printf that receives a formatted string and it's necessary args. The thing is, how can one take an array and send the elements as arguments to one of those functions? In python, I'd do something like this: def the_function(s, who, hmany): print s%(who, hmany) the_args = ["Hello, %s from the %d of us", "world", 3] the_function(*the_args) How can that be accomplished in C++? (I'm using v8 and node.js, so maybe there's a function or class somewhere in those namespaces that I'm not aware of)
[ "Here's one way:\nvoid foo(const char *firstArg, ...) {\n va_list argList;\n va_start(argList, firstArg);\n\n vprintf(firstArg, argList);\n\n va_end(argList);\n}\n\nAssuming that you're trying to do a printf. Basically, va_list is the key, and you can use it to either examine the arguments, or pass them...
[ 2 ]
[]
[]
[ "c++", "gettext", "node.js", "python", "v8" ]
stackoverflow_0003664348_c++_gettext_node.js_python_v8.txt
Q: XML parser syntax error So I'm working with a block of code which communicates with the Flickr API. I'm getting a 'syntax error' in xml.parsers.expat.ExpatError (below). Now I can't figure out how it'd be a syntax error in a Python module. I saw another similar question on SO regarding the Wikipedia API which seemed to return HTML intead of XML. Flickr API returns XML; and I'm also getting the same error when there shouldn't be a response from Flickr (such as flickr.galleries.addPhoto) CODE: def _dopost(method, auth=False, **params): #uncomment to check you aren't killing the flickr server #print "***** do post %s" % method params = _prepare_params(params) url = '%s%s/%s' % (HOST, API, _get_auth_url_suffix(method, auth, params)) payload = 'api_key=%s&method=%s&%s'% \ (API_KEY, method, urlencode(params)) #another useful debug print statement #print url #print payload return _get_data(minidom.parse(urlopen(url, payload))) TRACEBACK: Traceback (most recent call last): File "TESTING.py", line 30, in <module> flickr.galleries_create('test_title', 'test_descriptionn goes here.') File "/home/vlad/Documents/Computers/Programming/LEARNING/curatr/flickr.py", line 1006, in galleries_create primary_photo_id=primary_photo_id) File "/home/vlad/Documents/Computers/Programming/LEARNING/curatr/flickr.py", line 1066, in _dopost return _get_data(minidom.parse(urlopen(url, payload))) File "/usr/lib/python2.6/xml/dom/minidom.py", line 1918, in parse return expatbuilder.parse(file) File "/usr/lib/python2.6/xml/dom/expatbuilder.py", line 928, in parse result = builder.parseFile(file) File "/usr/lib/python2.6/xml/dom/expatbuilder.py", line 207, in parseFile parser.Parse(buffer, 0) xml.parsers.expat.ExpatError: syntax error: line 1, column 62 (Code from http://code.google.com/p/flickrpy/ under New BSD licence) UPDATE: print urlopen(url, payload) == <addinfourl at 43340936 whose fp = <socket._fileobject object at 0x29400d0>> Doing a urlopen(url, payload).read() returns HTML which is hard to read in a terminal :P but I managed to make out a 'You are not signed in.' The strange part is that Flickr shouldn't return anything here, or if permissions are a problem, it should return a 99: User not logged in / Insufficient permissions error as it does with the GET function (which I'd expect would be in valid XML). I'm signed in to Flickr (in the browser) and the program is properly authenticated with delete permissions (dangerous, but I wanted to avoid permission problems.) A: SyntaxError normally means an error in Python syntax, but I think here that expatbuilder is overloading it to mean an XML syntax error. Put a try:except block around it, and print out the contents of payload and to work out what's wrong with the first line of it. My guess would be that flickr is rejecting your request for some reason and giving back a plain-text error message, which has an invalid xml character at column 62, but it could be any number of things. You probably want to check the http status code before parsing it. Also, it's a bit strange this method is called _dopost but you seem to actually be sending an http GET. Perhaps that's why it's failing. A: This seems to fix my problem: url = '%s%s/?api_key=%s&method=%s&%s'% \ (HOST, API, API_KEY, method, _get_auth_url_suffix(method, auth, params)) payload = '%s' % (urlencode(params)) It seems that the API key and method had to be in the URL not in the payload. (Or maybe only one needed to be there, but anyways, it works :-)
XML parser syntax error
So I'm working with a block of code which communicates with the Flickr API. I'm getting a 'syntax error' in xml.parsers.expat.ExpatError (below). Now I can't figure out how it'd be a syntax error in a Python module. I saw another similar question on SO regarding the Wikipedia API which seemed to return HTML intead of XML. Flickr API returns XML; and I'm also getting the same error when there shouldn't be a response from Flickr (such as flickr.galleries.addPhoto) CODE: def _dopost(method, auth=False, **params): #uncomment to check you aren't killing the flickr server #print "***** do post %s" % method params = _prepare_params(params) url = '%s%s/%s' % (HOST, API, _get_auth_url_suffix(method, auth, params)) payload = 'api_key=%s&method=%s&%s'% \ (API_KEY, method, urlencode(params)) #another useful debug print statement #print url #print payload return _get_data(minidom.parse(urlopen(url, payload))) TRACEBACK: Traceback (most recent call last): File "TESTING.py", line 30, in <module> flickr.galleries_create('test_title', 'test_descriptionn goes here.') File "/home/vlad/Documents/Computers/Programming/LEARNING/curatr/flickr.py", line 1006, in galleries_create primary_photo_id=primary_photo_id) File "/home/vlad/Documents/Computers/Programming/LEARNING/curatr/flickr.py", line 1066, in _dopost return _get_data(minidom.parse(urlopen(url, payload))) File "/usr/lib/python2.6/xml/dom/minidom.py", line 1918, in parse return expatbuilder.parse(file) File "/usr/lib/python2.6/xml/dom/expatbuilder.py", line 928, in parse result = builder.parseFile(file) File "/usr/lib/python2.6/xml/dom/expatbuilder.py", line 207, in parseFile parser.Parse(buffer, 0) xml.parsers.expat.ExpatError: syntax error: line 1, column 62 (Code from http://code.google.com/p/flickrpy/ under New BSD licence) UPDATE: print urlopen(url, payload) == <addinfourl at 43340936 whose fp = <socket._fileobject object at 0x29400d0>> Doing a urlopen(url, payload).read() returns HTML which is hard to read in a terminal :P but I managed to make out a 'You are not signed in.' The strange part is that Flickr shouldn't return anything here, or if permissions are a problem, it should return a 99: User not logged in / Insufficient permissions error as it does with the GET function (which I'd expect would be in valid XML). I'm signed in to Flickr (in the browser) and the program is properly authenticated with delete permissions (dangerous, but I wanted to avoid permission problems.)
[ "SyntaxError normally means an error in Python syntax, but I think here that expatbuilder is overloading it to mean an XML syntax error. Put a try:except block around it, and print out the contents of payload and to work out what's wrong with the first line of it. \nMy guess would be that flickr is rejecting your...
[ 6, 2 ]
[]
[]
[ "api", "python", "xml", "xml_parsing" ]
stackoverflow_0003664084_api_python_xml_xml_parsing.txt
Q: django comment system: How to make it more like YouTube's? I like the comment box at the top with the posts going in reverse order. Comment rating, highest rated comments, all great features, remaining character count, spam flag. My question is, is there a open commenting system available for Django that already has these features? A: I suggest Disqus plus django-disqus (http://github.com/arthurk/django-disqus)
django comment system: How to make it more like YouTube's?
I like the comment box at the top with the posts going in reverse order. Comment rating, highest rated comments, all great features, remaining character count, spam flag. My question is, is there a open commenting system available for Django that already has these features?
[ "I suggest Disqus plus django-disqus (http://github.com/arthurk/django-disqus)\n" ]
[ -1 ]
[]
[]
[ "comments", "django", "python", "youtube" ]
stackoverflow_0003662809_comments_django_python_youtube.txt