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: How can I query Google's Safebrowsing API to check a URL with Python? I have a list of domains that I need to check for malware. Is there a way I could use Python to query Google's Safebrowsing API to get that information without the need for a database? A: Google's Safe Browsing API page contains a Python reference client, take a look at that.
How can I query Google's Safebrowsing API to check a URL with Python?
I have a list of domains that I need to check for malware. Is there a way I could use Python to query Google's Safebrowsing API to get that information without the need for a database?
[ "Google's Safe Browsing API page contains a Python reference client, take a look at that.\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0003056265_python.txt
Q: Gathering mac addresses with Python is there a good way to gather the mac addresses of machines on a local network using Python. If it helps I'm trying to execute this python script from the DHCP server for the network. I'm new to Python but would it be a bad idea to look at the DHCP leases file for this info? I'd like to use this inside a Django app eventually. Thanks. A: Really a unix question (one will assume) You can either look at the arp addresses registered "/sbin/arp -a" or a DHCP lease table. If you go the arp route you will on find addresses that your system has recently received/sent packets to, the DHCP lease table will give you the ability to see everything. Though if it's static configured it won't show up. A: The easiest thing to do would be to run a tool that can achieve this and parse its output (e.g. nmap). Depending on your needs, you could run it periodically and keep a file with the mac addresses. Looking at the leases file could work, assuming that all your machines are in there. If you want to actively look for machines, do a nmap scan.
Gathering mac addresses with Python
is there a good way to gather the mac addresses of machines on a local network using Python. If it helps I'm trying to execute this python script from the DHCP server for the network. I'm new to Python but would it be a bad idea to look at the DHCP leases file for this info? I'd like to use this inside a Django app eventually. Thanks.
[ "Really a unix question (one will assume)\nYou can either look at the arp addresses registered \"/sbin/arp -a\" or a DHCP lease table. If you go the arp route you will on find addresses that your system has recently received/sent packets to, the DHCP lease table will give you the ability to see everything. Though if it's static configured it won't show up.\n", "The easiest thing to do would be to run a tool that can achieve this and parse its output (e.g. nmap). Depending on your needs, you could run it periodically and keep a file with the mac addresses. \nLooking at the leases file could work, assuming that all your machines are in there. If you want to actively look for machines, do a nmap scan.\n" ]
[ 1, 1 ]
[]
[]
[ "django", "mac_address", "networking", "python" ]
stackoverflow_0003056324_django_mac_address_networking_python.txt
Q: How to correlate gtk.ListStore items with my own models I have a list of Project objects, that I display in a GtkTreeView. I am trying to open a dialog with a Project's details when the user double-clicks on the item's row in the TreeView. Right now I get the selected value from the TreeView (which is the name of the Project) via get_selection(), and search for that Project by name in my own list to corelate the selection with my own model. However, this doesn't feel quite right (plus, it assumes that a Project's name is unique), and I was wondering if there is a more elegant way of doing it. A: Not with the default models. You could try using Py-gtktree models written specifically to use the same objects in backend and presentation. Its documentation outlines an alternative way to make this work with standard models (i.e. without using Py-gtktree at all), by the way, but I wouldn't call it elegant. A: What I ended up doing was extending gtk.ListStore and use my custom list. I also hijacked the append() method so that not only it will append a [str, str, etc] into the ListStore, but also the actual model inside a custom list property of the class that extends ListStore. Then, when the user double clicks the row, I fetch the requested model by the row's index in the ListStore, which corresponds to the model's index in the custom list.
How to correlate gtk.ListStore items with my own models
I have a list of Project objects, that I display in a GtkTreeView. I am trying to open a dialog with a Project's details when the user double-clicks on the item's row in the TreeView. Right now I get the selected value from the TreeView (which is the name of the Project) via get_selection(), and search for that Project by name in my own list to corelate the selection with my own model. However, this doesn't feel quite right (plus, it assumes that a Project's name is unique), and I was wondering if there is a more elegant way of doing it.
[ "Not with the default models. You could try using Py-gtktree models written specifically to use the same objects in backend and presentation.\nIts documentation outlines an alternative way to make this work with standard models (i.e. without using Py-gtktree at all), by the way, but I wouldn't call it elegant.\n", "What I ended up doing was extending gtk.ListStore and use my custom list. I also hijacked the append() method so that not only it will append a [str, str, etc] into the ListStore, but also the actual model inside a custom list property of the class that extends ListStore.\nThen, when the user double clicks the row, I fetch the requested model by the row's index in the ListStore, which corresponds to the model's index in the custom list.\n" ]
[ 1, 1 ]
[]
[]
[ "gtktreeview", "pygtk", "python" ]
stackoverflow_0003032905_gtktreeview_pygtk_python.txt
Q: Linking IronPython to WPF I just installed VS2010 and the great new IronPython Tools extension. Currently this extension doesn't yet generate event handlers in code upon double-clicking wpf visual controls. Is there anyone that can provide or point me to an example as to how to code wpf event handlers manually in python. I've had no luck finding any and I am new to visual studio. Upon generating a new ipython wpf project the auto-generated code is: import clr clr.AddReference('PresentationFramework') from System.Windows.Markup import XamlReader from System.Windows import Application from System.IO import FileStream, FileMode app = Application() app.Run(XamlReader.Load(FileStream('WpfApplication7.xaml', FileMode.Open))) and the XAML is: <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="WpfApplication7" Height="300" Width="300"> <Button>Click Me</Button> </Window> Any help would be appreciated. A: You can't use something like <Button Click="Foo"> here, because there is no class in code corresponding to your window, and you can't get one, because IronPython classes do not directly map to CLR classes. Also, XamlReader, which is used to load the XAML file here, does not support event wireup. If you need events, you'll have to register handlers from Python code, not in XAML - which is done by the usual += syntax once you've obtained the control for which you want the event to be registered. Also have a look at this sample for some helpers that might make this easier.
Linking IronPython to WPF
I just installed VS2010 and the great new IronPython Tools extension. Currently this extension doesn't yet generate event handlers in code upon double-clicking wpf visual controls. Is there anyone that can provide or point me to an example as to how to code wpf event handlers manually in python. I've had no luck finding any and I am new to visual studio. Upon generating a new ipython wpf project the auto-generated code is: import clr clr.AddReference('PresentationFramework') from System.Windows.Markup import XamlReader from System.Windows import Application from System.IO import FileStream, FileMode app = Application() app.Run(XamlReader.Load(FileStream('WpfApplication7.xaml', FileMode.Open))) and the XAML is: <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="WpfApplication7" Height="300" Width="300"> <Button>Click Me</Button> </Window> Any help would be appreciated.
[ "You can't use something like <Button Click=\"Foo\"> here, because there is no class in code corresponding to your window, and you can't get one, because IronPython classes do not directly map to CLR classes. Also, XamlReader, which is used to load the XAML file here, does not support event wireup. If you need events, you'll have to register handlers from Python code, not in XAML - which is done by the usual += syntax once you've obtained the control for which you want the event to be registered.\nAlso have a look at this sample for some helpers that might make this easier.\n" ]
[ 5 ]
[]
[]
[ "ironpython", "python", "visual_studio_2010", "xaml" ]
stackoverflow_0003057044_ironpython_python_visual_studio_2010_xaml.txt
Q: Design an Application That Stores and Processes Files I'm tasked with writing an application that acts as a central storage point for files (usually document formats) as provided by other applications. It also needs to take commands like "file 395 needs a copy in X format", at which point some work is offloaded to a 3rd party application. I'm having trouble coming up with a strategy for this. I'd like to keep the design as simple as possible, so I'd like to avoid big extra frameworks or techniques like threads for as long as it makes sense. The clients are expected to be web applications (for example, one is a django application that receives files from our customers; the others are not yet implemented). The platform it will be running on is likely going to be Python on Linux, unless I have a strong argument to use something else. In the beginning I thought I could fit the information I wanted to communicate in the filenames, and let my application parse the filename to figure out what it needed to do, but this is proving too inflexible with the amount of information I'm realizing I need to make available. Another idea is to pair FTP with a database used as a communication medium (client uploads a file and updates the database with a command as a row in a table) but I don't like this idea because adding commands (a known change) looks like it will require adding code as well as changing database schemas. It will also muddy up the interface my clients will have to use. I looked into Pyro to let applications communicate more directly but I don't like the idea of running an extra nameserver for this one purpose. I also don't see a good way to do file transfer within this framework. What I'm looking for is techniques and/or technologies applicable to my problem. At the simplest level, I need the ability to accept files and messages with them. A: What you need to research is a BPEL Rules engine. Here is a list of open source rules engines written in Java. There are alternatives in other languages as well, even Python. This is definitely not something you want to tackle re-inventing yourself. This problem domain gets very complicated very quickly, any "simple" solution will be naive about scalability and performance and will just get thrown out sooner than later. A: You should be able to implement this in a fairly RESTful way with HTTP PUT and GET operations. This would be very useful for several reasons: Able to link to the storage directly from internal websites Easy testing Lots of libraries available to help you implement this No need to worry about what platform the client application uses I would suggest implementing it so that getting a file in a specific format is as simple as navigating to: http://www.myserver.com/filestore/documents/docname&format=xxx Within the server of course I would use a database of documents, file formats and cached versions of already converted files. I would invoke the third party translators on demand, i.e. when a request comes in for a document in a specific format and the document is not already in the cache. A: Your issues seem to cry out for a RESTful web app. As to what framework will let you implement it best, some people do like Django even for that (maybe with django-rest-interface), others prefer lighter-weight frameworks for this purpose -- see some discussion on this SO question. Another possible framework not mentioned there is RIP -- doesn't appear to be currently maintained, unfortunately (indeed, its link to its SVN repository is dangling), but may be worth downloading the sources from pypi, having a look, maybe adapting it.
Design an Application That Stores and Processes Files
I'm tasked with writing an application that acts as a central storage point for files (usually document formats) as provided by other applications. It also needs to take commands like "file 395 needs a copy in X format", at which point some work is offloaded to a 3rd party application. I'm having trouble coming up with a strategy for this. I'd like to keep the design as simple as possible, so I'd like to avoid big extra frameworks or techniques like threads for as long as it makes sense. The clients are expected to be web applications (for example, one is a django application that receives files from our customers; the others are not yet implemented). The platform it will be running on is likely going to be Python on Linux, unless I have a strong argument to use something else. In the beginning I thought I could fit the information I wanted to communicate in the filenames, and let my application parse the filename to figure out what it needed to do, but this is proving too inflexible with the amount of information I'm realizing I need to make available. Another idea is to pair FTP with a database used as a communication medium (client uploads a file and updates the database with a command as a row in a table) but I don't like this idea because adding commands (a known change) looks like it will require adding code as well as changing database schemas. It will also muddy up the interface my clients will have to use. I looked into Pyro to let applications communicate more directly but I don't like the idea of running an extra nameserver for this one purpose. I also don't see a good way to do file transfer within this framework. What I'm looking for is techniques and/or technologies applicable to my problem. At the simplest level, I need the ability to accept files and messages with them.
[ "What you need to research is a BPEL Rules engine. Here is a list of open source rules engines written in Java. There are alternatives in other languages as well, even Python. This is definitely not something you want to tackle re-inventing yourself. This problem domain gets very complicated very quickly, any \"simple\" solution will be naive about scalability and performance and will just get thrown out sooner than later.\n", "You should be able to implement this in a fairly RESTful way with HTTP PUT and GET operations. This would be very useful for several reasons:\n\nAble to link to the storage directly from internal websites\nEasy testing\nLots of libraries available to help you implement this\nNo need to worry about what platform the client application uses\n\nI would suggest implementing it so that getting a file in a specific format is as simple as navigating to:\nhttp://www.myserver.com/filestore/documents/docname&format=xxx\nWithin the server of course I would use a database of documents, file formats and cached versions of already converted files. I would invoke the third party translators on demand, i.e. when a request comes in for a document in a specific format and the document is not already in the cache.\n", "Your issues seem to cry out for a RESTful web app. As to what framework will let you implement it best, some people do like Django even for that (maybe with django-rest-interface), others prefer lighter-weight frameworks for this purpose -- see some discussion on this SO question. Another possible framework not mentioned there is RIP -- doesn't appear to be currently maintained, unfortunately (indeed, its link to its SVN repository is dangling), but may be worth downloading the sources from pypi, having a look, maybe adapting it.\n" ]
[ 3, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003057088_django_python.txt
Q: Continuous build framework for java+python+ruby? Our technology set includes java, python, and ruby code (no, we're not google ;-) ). Recommendations on good CI framework to use? Hudson? Other? dwh A: I would recommend Hudson. It's written in Java so it runs on most platforms, has a very pleasant web-interface and excellent usability, and plugins for Python and Ruby as well as supporting shell scripts out of the box. It integrates well with SCM - for example, it can be triggered by checking in changes to a repository. It has lots of useful plugins. A: I've had good luck with CruiseControl. It's based on ANT, so it's easy to write your build xml files for any language that you want... It also has builder support for Rake and a bunch of others (NANT, Maven, Phing and XCode, not to mention anything that can be run from the command line), so you should be good to go.
Continuous build framework for java+python+ruby?
Our technology set includes java, python, and ruby code (no, we're not google ;-) ). Recommendations on good CI framework to use? Hudson? Other? dwh
[ "I would recommend Hudson. It's written in Java so it runs on most platforms, has a very pleasant web-interface and excellent usability, and plugins for Python and Ruby as well as supporting shell scripts out of the box. It integrates well with SCM - for example, it can be triggered by checking in changes to a repository. It has lots of useful plugins.\n", "I've had good luck with CruiseControl. It's based on ANT, so it's easy to write your build xml files for any language that you want... It also has builder support for Rake and a bunch of others (NANT, Maven, Phing and XCode, not to mention anything that can be run from the command line), so you should be good to go.\n" ]
[ 3, 0 ]
[]
[]
[ "continuous_integration", "java", "python", "ruby" ]
stackoverflow_0003056830_continuous_integration_java_python_ruby.txt
Q: Running Trac 0.12 on Ubuntu 10.04 - Error I've installed trac 0.12 on my ubuntu 10.04, running the tracd internal webserver. When i access the page at http://127.0.0.1/myTracProject, I get the error message: Traceback (most recent call last): File "/usr/local/lib/python2.6/dist-packages/Trac-0.11.7-py2.6.egg/trac/web/api.py", line 376, in send_error 'text/html') File "/usr/local/lib/python2.6/dist-packages/Trac-0.11.7-py2.6.egg/trac/web/chrome.py", line 733, in render_template message = req.session.pop('chrome.%s.%d' % (type_, i)) File "/usr/local/lib/python2.6/dist-packages/Trac-0.11.7-py2.6.egg/trac/web/api.py", line 195, in __getattr__ value = self.callbacks[name](self) File "/usr/local/lib/python2.6/dist-packages/Trac-0.11.7-py2.6.egg/trac/web/main.py", line 265, in _get_session return Session(self.env, req) File "/usr/local/lib/python2.6/dist-packages/Trac-0.11.7-py2.6.egg/trac/web/session.py", line 157, in __init__ self.get_session(sid) File "/usr/local/lib/python2.6/dist-packages/Trac-0.11.7-py2.6.egg/trac/web/session.py", line 178, in get_session super(Session, self).get_session(sid, authenticated) File "/usr/local/lib/python2.6/dist-packages/Trac-0.11.7-py2.6.egg/trac/web/session.py", line 59, in get_session (sid, int(authenticated))) File "/usr/local/lib/python2.6/dist-packages/Trac-0.11.7-py2.6.egg/trac/db/util.py", line 64, in execute return self.cursor.execute(sql_escape_percent(sql), args) File "/usr/local/lib/python2.6/dist-packages/Trac-0.11.7-py2.6.egg/trac/db/util.py", line 64, in execute return self.cursor.execute(sql_escape_percent(sql), args) InternalError: current transaction is aborted, commands ignored until end of transaction block A: You installed Trac 0.12? Your traceback shows "Trac-0.11.7-py2.6.egg". Looks like you need to do some cleanup.
Running Trac 0.12 on Ubuntu 10.04 - Error
I've installed trac 0.12 on my ubuntu 10.04, running the tracd internal webserver. When i access the page at http://127.0.0.1/myTracProject, I get the error message: Traceback (most recent call last): File "/usr/local/lib/python2.6/dist-packages/Trac-0.11.7-py2.6.egg/trac/web/api.py", line 376, in send_error 'text/html') File "/usr/local/lib/python2.6/dist-packages/Trac-0.11.7-py2.6.egg/trac/web/chrome.py", line 733, in render_template message = req.session.pop('chrome.%s.%d' % (type_, i)) File "/usr/local/lib/python2.6/dist-packages/Trac-0.11.7-py2.6.egg/trac/web/api.py", line 195, in __getattr__ value = self.callbacks[name](self) File "/usr/local/lib/python2.6/dist-packages/Trac-0.11.7-py2.6.egg/trac/web/main.py", line 265, in _get_session return Session(self.env, req) File "/usr/local/lib/python2.6/dist-packages/Trac-0.11.7-py2.6.egg/trac/web/session.py", line 157, in __init__ self.get_session(sid) File "/usr/local/lib/python2.6/dist-packages/Trac-0.11.7-py2.6.egg/trac/web/session.py", line 178, in get_session super(Session, self).get_session(sid, authenticated) File "/usr/local/lib/python2.6/dist-packages/Trac-0.11.7-py2.6.egg/trac/web/session.py", line 59, in get_session (sid, int(authenticated))) File "/usr/local/lib/python2.6/dist-packages/Trac-0.11.7-py2.6.egg/trac/db/util.py", line 64, in execute return self.cursor.execute(sql_escape_percent(sql), args) File "/usr/local/lib/python2.6/dist-packages/Trac-0.11.7-py2.6.egg/trac/db/util.py", line 64, in execute return self.cursor.execute(sql_escape_percent(sql), args) InternalError: current transaction is aborted, commands ignored until end of transaction block
[ "You installed Trac 0.12? Your traceback shows \"Trac-0.11.7-py2.6.egg\". Looks like you need to do some cleanup.\n" ]
[ 0 ]
[]
[]
[ "python", "trac", "ubuntu_10.04" ]
stackoverflow_0003055850_python_trac_ubuntu_10.04.txt
Q: Python Regular Expression TypeError I am writing my first python program and I am running into a problem with regex. I am using regular expression to search for a specific value in a registry key. import _winreg import re key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{26A24AE4-039D-4CA4-87B4-2F83216020FF}") results=[] v = re.compile(r"(?i)Java") try: i = 0 while 1: name, value, type = _winreg.EnumValue(key, i) if v.search(value): results.append((name,value,type)) i += 1 except WindowsError: print for x in results: print "%-50s%-80s%-20s" % x I am getting the following error: exceptions.TypeError: expected string or buffer I can use the "name" variable and my regex works fine. For example if I make the following changes regex doesn't complain: v = re.compile(r"(?i)DisplayName") if v.search(name): Thanks for any help. A: The documentation for EnumValue explains that the 3-tuple returned is a string, an object that can be any of the Value Types, then an integer. As the error explained, you must pass in a string or a buffer, so that's why v.search(value) fails. You should be able to get away with v.search(str(value)) to convert value to a string.
Python Regular Expression TypeError
I am writing my first python program and I am running into a problem with regex. I am using regular expression to search for a specific value in a registry key. import _winreg import re key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{26A24AE4-039D-4CA4-87B4-2F83216020FF}") results=[] v = re.compile(r"(?i)Java") try: i = 0 while 1: name, value, type = _winreg.EnumValue(key, i) if v.search(value): results.append((name,value,type)) i += 1 except WindowsError: print for x in results: print "%-50s%-80s%-20s" % x I am getting the following error: exceptions.TypeError: expected string or buffer I can use the "name" variable and my regex works fine. For example if I make the following changes regex doesn't complain: v = re.compile(r"(?i)DisplayName") if v.search(name): Thanks for any help.
[ "The documentation for EnumValue explains that the 3-tuple returned is a string, an object that can be any of the Value Types, then an integer. As the error explained, you must pass in a string or a buffer, so that's why v.search(value) fails.\nYou should be able to get away with v.search(str(value)) to convert value to a string.\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0003057365_python.txt
Q: A daemon to call a function every 2 minutes with start and stop capablities I am working on a django web application. A function 'xyx' (it updates a variable) needs to be called every 2 minutes. I want one http request should start the daemon and keep calling xyz (every 2 minutes) until I send another http request to stop it. Appreciate your ideas. Thanks Vishal Rana A: There are a number of ways to achieve this. Assuming the correct server resources I would write a python script that calls function xyz "outside" of your django directory (although importing the necessary stuff) that only runs if /var/run/django-stuff/my-daemon.run exists. Get cron to run this every two minutes. Then, for your django functions, your start function creates the above mentioned file if it doesn't already exist and the stop function destroys it. As I say, there are other ways to achieve this. You could have a python script on loop waiting for approx 2 minutes... etc. In either case, you're up against the fact that two python scripts run on two different invocations of cpython (no idea if this is the case with mod_wsgi) cannot communicate with each other and as such IPC between python scripts is not simple, so you need to use some sort of formal IPC (like semaphores, files etc) rather than just common variables (which won't work). A: Probably a little hacked but you could try this: Set up a crontab entry that runs a script every two minutes. This script will check for some sort of flag (file existence, contents of a file, etc.) on the disk to decide whether to run a given python module. The problem with this is it could take up to 1:59 to run the function the first time after it is started. I think if you started a daemon in the view function it would keep the httpd worker process alive as well as the connection unless you figure out how to send a connection close without terminating the django view function. This could be very bad if you want to be able to do this in parallel for different users. Also to kill the function this way, you would have to somehow know which python and/or httpd process you want to kill later so you don't kill all of them. The real way to do it would be to code an actual daemon in w/e language and just make a system call to "/etc/init.d/daemon_name start" and "... stop" in the django views. For this, you need to make sure your web server user has permission to execute the daemon. A: If the easy solutions (loop in a script, crontab signaled by a temp file) are too fragile for your intended usage, you could use Twisted facilities for process handling and scheduling and networking. Your Django app (using a Twisted client) would simply communicate via TCP (locally) with the Twisted server.
A daemon to call a function every 2 minutes with start and stop capablities
I am working on a django web application. A function 'xyx' (it updates a variable) needs to be called every 2 minutes. I want one http request should start the daemon and keep calling xyz (every 2 minutes) until I send another http request to stop it. Appreciate your ideas. Thanks Vishal Rana
[ "There are a number of ways to achieve this. Assuming the correct server resources I would write a python script that calls function xyz \"outside\" of your django directory (although importing the necessary stuff) that only runs if /var/run/django-stuff/my-daemon.run exists. Get cron to run this every two minutes.\nThen, for your django functions, your start function creates the above mentioned file if it doesn't already exist and the stop function destroys it.\nAs I say, there are other ways to achieve this. You could have a python script on loop waiting for approx 2 minutes... etc. In either case, you're up against the fact that two python scripts run on two different invocations of cpython (no idea if this is the case with mod_wsgi) cannot communicate with each other and as such IPC between python scripts is not simple, so you need to use some sort of formal IPC (like semaphores, files etc) rather than just common variables (which won't work).\n", "Probably a little hacked but you could try this:\nSet up a crontab entry that runs a script every two minutes. This script will check for some sort of flag (file existence, contents of a file, etc.) on the disk to decide whether to run a given python module. The problem with this is it could take up to 1:59 to run the function the first time after it is started.\nI think if you started a daemon in the view function it would keep the httpd worker process alive as well as the connection unless you figure out how to send a connection close without terminating the django view function. This could be very bad if you want to be able to do this in parallel for different users. Also to kill the function this way, you would have to somehow know which python and/or httpd process you want to kill later so you don't kill all of them.\nThe real way to do it would be to code an actual daemon in w/e language and just make a system call to \"/etc/init.d/daemon_name start\" and \"... stop\" in the django views. For this, you need to make sure your web server user has permission to execute the daemon.\n", "If the easy solutions (loop in a script, crontab signaled by a temp file) are too fragile for your intended usage, you could use Twisted facilities for process handling and scheduling and networking. Your Django app (using a Twisted client) would simply communicate via TCP (locally) with the Twisted server.\n" ]
[ 4, 2, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003057507_django_python.txt
Q: Access to an "upper" instance of a class from another instance of a different class I'd like to know if there's a way to access to the class (or its fields) where an object is instantiated. Let's say I have: def Class1: def __init__(self): self.title = "randomTitle" self.anotherField = float() self.class2Field = Class2() and the class whose type will be the class2Field: def Class2: def __init__(self): self.field1 = "" self.field2 = "" # . . . # I'd like to know if there's a way to access the instance of Class1 from the instance of Class2 that is declared in Class1 (meaning, accessing the fields of Class1 from the variable self.class2Field in that Class1 instance) I know I can always change the __init__ in Class2 to accept a Class1 parameter, but I'd like to know if there's another way of "climbing" through the class hierarchy. Thank you very much! A: Yes, but don't do it. Pass the object explicitly. A: There's no "class hierarchy" to speak of, here. Your Class1 objects contain Class2 objects, but your Class2 objects don't know that. You could define self.parent in Class2 to be the instance of Class1 that refers to the object in self.class2Field, and have your Class1 instance passed in by __init__: def Class1: def __init__(self): self.title = "randomTitle" self.anotherField = float() self.class2Field = Class2(self) # . . . # def Class2: def __init__(self, parent): self.parent = parent self.field1 = "" self.field2 = "" # . . . # It's ugly, it's more overhead, and it requires that Class2 always be contained (at least the way that I wrote it above), but it might do what you want. A: You don't have to mess with definition of child class (Class2). Just attach another property to its instance after creating the instance. def Class1: def __init__(self): self.title = "randomTitle" self.anotherField = float() self.class2Field = Class2() self.class2Field.parent = self # <- This is where you attach the pointer to parent. # . . . # def Class2: def __init__(self): self.field1 = "" self.field2 = "" def mess_with_parent(self): '''Example of access to instance-level property "parent"''' if hasattr(self, 'parent') and self.parent != None: # instead of "!= None" insert your way of checking that .parent is right type self.parent.anotherField = 5.0 # . . . # a = Class1() <instance of class1> = a.class2Field.parent b = a.class2Field <instance of class1> = b.parent
Access to an "upper" instance of a class from another instance of a different class
I'd like to know if there's a way to access to the class (or its fields) where an object is instantiated. Let's say I have: def Class1: def __init__(self): self.title = "randomTitle" self.anotherField = float() self.class2Field = Class2() and the class whose type will be the class2Field: def Class2: def __init__(self): self.field1 = "" self.field2 = "" # . . . # I'd like to know if there's a way to access the instance of Class1 from the instance of Class2 that is declared in Class1 (meaning, accessing the fields of Class1 from the variable self.class2Field in that Class1 instance) I know I can always change the __init__ in Class2 to accept a Class1 parameter, but I'd like to know if there's another way of "climbing" through the class hierarchy. Thank you very much!
[ "Yes, but don't do it. Pass the object explicitly.\n", "There's no \"class hierarchy\" to speak of, here. Your Class1 objects contain Class2 objects, but your Class2 objects don't know that.\nYou could define self.parent in Class2 to be the instance of Class1 that refers to the object in self.class2Field, and have your Class1 instance passed in by __init__:\ndef Class1:\n def __init__(self):\n self.title = \"randomTitle\"\n self.anotherField = float()\n self.class2Field = Class2(self)\n # . . . #\n\ndef Class2:\n def __init__(self, parent):\n self.parent = parent\n self.field1 = \"\"\n self.field2 = \"\"\n # . . . #\n\nIt's ugly, it's more overhead, and it requires that Class2 always be contained (at least the way that I wrote it above), but it might do what you want.\n", "You don't have to mess with definition of child class (Class2). Just attach another property to its instance after creating the instance. \ndef Class1:\n def __init__(self):\n self.title = \"randomTitle\"\n self.anotherField = float()\n self.class2Field = Class2()\n self.class2Field.parent = self # <- This is where you attach the pointer to parent.\n # . . . #\n\ndef Class2:\n def __init__(self):\n self.field1 = \"\"\n self.field2 = \"\"\n\n def mess_with_parent(self):\n '''Example of access to instance-level property \"parent\"'''\n if hasattr(self, 'parent') and self.parent != None: \n # instead of \"!= None\" insert your way of checking that .parent is right type\n self.parent.anotherField = 5.0\n # . . . #\n\na = Class1()\n<instance of class1> = a.class2Field.parent\nb = a.class2Field\n<instance of class1> = b.parent\n\n" ]
[ 4, 1, 0 ]
[]
[]
[ "field", "oop", "python" ]
stackoverflow_0003055200_field_oop_python.txt
Q: How do I set a property in python using its string name How can I set an object property given its name in a string? I have a dictionary being passed to me and I wish to transfer its values into namesake properties using code like this: for entry in src_dict: if entry.startswith('can_'): tgt_obj[entry] = src_dict_profile[entry] A: setattr(some_object, 'some_attribute', 42) A: Sounds like you're looking for setattr. Example: for entry in src_dict: if entry.startswith('can_'): setattr(tgt_obj, entry, src_dict_profile[entry]) A: On objects that have "dict" property if "__dict__" in dir(obj): you may do fun things like: obj.__dict__.update(src_dict)
How do I set a property in python using its string name
How can I set an object property given its name in a string? I have a dictionary being passed to me and I wish to transfer its values into namesake properties using code like this: for entry in src_dict: if entry.startswith('can_'): tgt_obj[entry] = src_dict_profile[entry]
[ "setattr(some_object, 'some_attribute', 42)\n\n", "Sounds like you're looking for setattr.\nExample:\nfor entry in src_dict:\n if entry.startswith('can_'):\n setattr(tgt_obj, entry, src_dict_profile[entry])\n\n", "On objects that have \"dict\" property\nif \"__dict__\" in dir(obj):\n\nyou may do fun things like:\nobj.__dict__.update(src_dict)\n\n" ]
[ 24, 7, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003053718_python.txt
Q: problem reading a csv file in python I am trying to read a very simple but somehow large(800Mb) csv file using the csv library in python. The delimiter is a single tab and each line consists of some numbers. Each line is a record, and I have 20681 rows in my file. I had some problems during my calculations using this file,it always stops at a certain row. I got suspicious about the number of rows in the file.I used the code below to count the number of row in this file: tfdf_Reader = csv.reader(open('v2-host_tfdf_en.txt'),delimiter=' ') c = 0 for row in tfdf_Reader: c = c + 1 print c To my surprise c is printed with the value of 61722!!! Why is this happening? What am I doing wrong? A: 800 million bytes in the file and 20681 rows means that the average row size is over 38 THOUSAND bytes. Are you sure? How many numbers do you expect in each line? How do you know that you have 20681 rows? That the file is 800 Mb? 61722 rows is almost exactly 3 times 20681 -- is the number 3 of any significance e.g. 3 logical sub-sections of each record? To find out what you really have in your file, don't rely on what it looks like. Python's repr() function is your friend. Are you on Windows? Even if not, always open(filename, 'rb'). If the fields are tab-separated, then don't put delimeter=" " (whatever is between the quotes appears not to be a tab). Put delimiter="\t". Try putting some debug statements in your code, like this: DEBUG = True f = open('v2-host_tfdf_en.txt', 'rb') if DEBUG: rawdata = f.read(200) f.seek(0) print 'rawdata', repr(rawdata) # what is the delimiter between fields? between rows? tfdf_Reader = csv.reader(f,delimiter=' ') c = 0 for row in tfdf_Reader: c = c + 1 if DEBUG and c <= 10: print "row", c, repr(row) # Are you getting rows like you expect? print "rowcount", c Note: if you are getting Error: field larger than field limit (131072), that means your file has 128Kb of data with no delimiters. I'd suspect that: (a) your file has random junk or a big chunk of binary zeroes apppended to it -- this should be obvious in a hex editor; it also should be obvious in a TEXT editor. Print all the rows that you do get to help identify where the trouble starts. or (b) the delimiter is a string of one or more whitespace characters (space, tab), the first few rows have tabs, and the remaining rows have spaces. If so, this should be obvious in a hex editor (or in Notepad++, especially if you do View/Show Symbol/Show all characters). If this is the case, you can't use csv, you'd need something simple like: f = open('v2-host_tfdf_en.txt', 'r') # NOT 'rb' rows = [line.split() for line in f] A: My first guess would be the delimeter. How are you ensuring the delimeter is a tab? What is actually the value you are passing? (the code your pased lists a space, but I'm sure you intended to pass something else). If your file is tab separated, then look specifically for '\t' as your delimeter. Looking for a space would mess up situations where there is space in your data that is not a column separator. Also, if your file is an excel-tab, then there is a special "dialect" for that.
problem reading a csv file in python
I am trying to read a very simple but somehow large(800Mb) csv file using the csv library in python. The delimiter is a single tab and each line consists of some numbers. Each line is a record, and I have 20681 rows in my file. I had some problems during my calculations using this file,it always stops at a certain row. I got suspicious about the number of rows in the file.I used the code below to count the number of row in this file: tfdf_Reader = csv.reader(open('v2-host_tfdf_en.txt'),delimiter=' ') c = 0 for row in tfdf_Reader: c = c + 1 print c To my surprise c is printed with the value of 61722!!! Why is this happening? What am I doing wrong?
[ "800 million bytes in the file and 20681 rows means that the average row size is over 38 THOUSAND bytes. Are you sure? How many numbers do you expect in each line? How do you know that you have 20681 rows? That the file is 800 Mb?\n61722 rows is almost exactly 3 times 20681 -- is the number 3 of any significance e.g. 3 logical sub-sections of each record?\nTo find out what you really have in your file, don't rely on what it looks like. Python's repr() function is your friend.\nAre you on Windows? Even if not, always open(filename, 'rb').\nIf the fields are tab-separated, then don't put delimeter=\" \" (whatever is between the quotes appears not to be a tab). Put delimiter=\"\\t\".\nTry putting some debug statements in your code, like this:\nDEBUG = True\nf = open('v2-host_tfdf_en.txt', 'rb')\nif DEBUG:\n rawdata = f.read(200)\n f.seek(0)\n print 'rawdata', repr(rawdata)\n # what is the delimiter between fields? between rows?\ntfdf_Reader = csv.reader(f,delimiter=' ')\nc = 0\nfor row in tfdf_Reader:\n c = c + 1\n if DEBUG and c <= 10:\n print \"row\", c, repr(row)\n # Are you getting rows like you expect?\nprint \"rowcount\", c\n\nNote: if you are getting Error: field larger than field limit (131072), that means your file has 128Kb of data with no delimiters.\nI'd suspect that: \n(a) your file has random junk or a big chunk of binary zeroes apppended to it -- this should be obvious in a hex editor; it also should be obvious in a TEXT editor. Print all the rows that you do get to help identify where the trouble starts.\nor (b) the delimiter is a string of one or more whitespace characters (space, tab), the first few rows have tabs, and the remaining rows have spaces. If so, this should be obvious in a hex editor (or in Notepad++, especially if you do View/Show Symbol/Show all characters). If this is the case, you can't use csv, you'd need something simple like:\nf = open('v2-host_tfdf_en.txt', 'r') # NOT 'rb'\nrows = [line.split() for line in f]\n\n", "My first guess would be the delimeter. How are you ensuring the delimeter is a tab? \nWhat is actually the value you are passing? (the code your pased lists a space, but I'm sure you intended to pass something else).\nIf your file is tab separated, then look specifically for '\\t' as your delimeter. Looking for a space would mess up situations where there is space in your data that is not a column separator.\nAlso, if your file is an excel-tab, then there is a special \"dialect\" for that.\n" ]
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003057373_python.txt
Q: Converting Numpy Lstsq residual value to R^2 I am performing a least squares regression as below (univariate). I would like to express the significance of the result in terms of R^2. Numpy returns a value of unscaled residual, what would be a sensible way of normalizing this. field_clean,back_clean = rid_zeros(backscatter,field_data) num_vals = len(field_clean) x = field_clean[:,row:row+1] y = 10*log10(back_clean) A = hstack([x, ones((num_vals,1))]) soln = lstsq(A, y ) m, c = soln [0] residues = soln [1] print residues A: See http://en.wikipedia.org/wiki/Coefficient_of_determination Your R2 value = 1 - residual / sum((y - y.mean())**2) which is equivalent to 1 - residual / (n * y.var()) As an example: import numpy as np # Make some data... n = 10 x = np.arange(n) y = 3 * x + 5 + np.random.random(n) # Note that polyfit is an easier way to do this... # It would just be "model, resid = np.polyfit(x,y,1,full=True)[:2]" A = np.vstack((x, np.ones(n))).T model, resid = np.linalg.lstsq(A, y)[:2] r2 = 1 - resid / (y.size * y.var()) print r2
Converting Numpy Lstsq residual value to R^2
I am performing a least squares regression as below (univariate). I would like to express the significance of the result in terms of R^2. Numpy returns a value of unscaled residual, what would be a sensible way of normalizing this. field_clean,back_clean = rid_zeros(backscatter,field_data) num_vals = len(field_clean) x = field_clean[:,row:row+1] y = 10*log10(back_clean) A = hstack([x, ones((num_vals,1))]) soln = lstsq(A, y ) m, c = soln [0] residues = soln [1] print residues
[ "See http://en.wikipedia.org/wiki/Coefficient_of_determination\nYour R2 value = \n1 - residual / sum((y - y.mean())**2) \n\nwhich is equivalent to \n1 - residual / (n * y.var())\n\nAs an example:\nimport numpy as np\n\n# Make some data...\nn = 10\nx = np.arange(n)\ny = 3 * x + 5 + np.random.random(n)\n\n# Note that polyfit is an easier way to do this...\n# It would just be \"model, resid = np.polyfit(x,y,1,full=True)[:2]\" \nA = np.vstack((x, np.ones(n))).T\nmodel, resid = np.linalg.lstsq(A, y)[:2]\n\nr2 = 1 - resid / (y.size * y.var())\nprint r2\n\n" ]
[ 22 ]
[]
[]
[ "linear_regression", "numpy", "python" ]
stackoverflow_0003054191_linear_regression_numpy_python.txt
Q: Scipy interpolation on a numpy array I have a lookup table that is defined the following way: | <1 2 3 4 5+ -------|---------------------------- <10000 | 3.6 6.5 9.1 11.5 13.8 20000 | 3.9 7.3 10.0 13.1 15.9 20000+ | 4.5 9.2 12.2 14.8 18.2 TR_ua1 = np.array([ [3.6, 6.5, 9.1, 11.5, 13.8], [3.9, 7.3, 10.0, 13.1, 15.9], [4.5, 9.2, 12.2, 14.8, 18.2] ]) The header row elements are (hh) < 1,2,3,4,5+ The header column (inc) elements are <10000, 20000, 20001+ The user will input a value example (1.3, 25,000), (0.2, 50,000), so on. scipy.interpolate() should interpolate to determine the correct value. Currently, the only way I can do this is with a bunch of if/elifs as exemplified below. I'm pretty sure there is a better, more efficient way of doing this Here's what I've got so far: import numpy as np from scipy import interpolate if (ua == 1): if (inc <= low_inc): # low_inc = 10,000 if (hh <= 1): return TR_ua1[0][0] elif (hh >= 1 & hh < 2): return interpolate( (1, 2), (TR_ua1[0][1], TR_ua1[0][2]) ) A: Edit: Updated things to reflect your clarifications above. Your question is much clearer now, thanks! Basically, you're just wanting to interpolate a 2D array at an arbitrary point. scipy.ndimage.map_coordinates is what you want.... As I understand your question, you have a 2D array of "z" values that ranges from some xmin to xmax, and ymin to ymax in each direction. Anything outside of those bounding coordinates you want to return values from the edges of the array. map_coordinates has several options to handle points outside the boundaries of the grid, but none of them do exactly what you want. Instead, we can just set anything outside the boundaries to lie on the edge, and use map_coordinates as usual. So, to use map_coordinates, you need to turn your actual coodinates: | <1 2 3 4 5+ -------|---------------------------- <10000 | 3.6 6.5 9.1 11.5 13.8 20000 | 3.9 7.3 10.0 13.1 15.9 20000+ | 4.5 9.2 12.2 14.8 18.2 Into index coordinates: | 0 1 2 3 4 -------|---------------------------- 0 | 3.6 6.5 9.1 11.5 13.8 1 | 3.9 7.3 10.0 13.1 15.9 2 | 4.5 9.2 12.2 14.8 18.2 Note that your boundaries behave differently in each direction... In the x-direction, things behave smoothly, but in the y-direction, you're asking for a "hard" break, where y=20000 --> 3.9, but y=20000.000001 --> 4.5. As an example: import numpy as np from scipy.ndimage import map_coordinates #-- Setup --------------------------- z = np.array([ [3.6, 6.5, 9.1, 11.5, 13.8], [3.9, 7.3, 10.0, 13.1, 15.9], [4.5, 9.2, 12.2, 14.8, 18.2] ]) ny, nx = z.shape xmin, xmax = 1, 5 ymin, ymax = 10000, 20000 # Points we want to interpolate at x1, y1 = 1.3, 25000 x2, y2 = 0.2, 50000 x3, y3 = 2.5, 15000 # To make our lives easier down the road, let's # turn these into arrays of x & y coords xi = np.array([x1, x2, x3], dtype=np.float) yi = np.array([y1, y2, y3], dtype=np.float) # Now, we'll set points outside the boundaries to lie along an edge xi[xi > xmax] = xmax xi[xi < xmin] = xmin # To deal with the "hard" break, we'll have to treat y differently, # so we're ust setting the min here... yi[yi < ymin] = ymin # We need to convert these to (float) indicies # (xi should range from 0 to (nx - 1), etc) xi = (nx - 1) * (xi - xmin) / (xmax - xmin) # Deal with the "hard" break in the y-direction yi = (ny - 2) * (yi - ymin) / (ymax - ymin) yi[yi > 1] = 2.0 # Now we actually interpolate # map_coordinates does cubic interpolation by default, # use "order=1" to preform bilinear interpolation instead... z1, z2, z3 = map_coordinates(z, [yi, xi]) # Display the results for X, Y, Z in zip((x1, x2, x3), (y1, y2, y3), (z1, z2, z3)): print X, ',', Y, '-->', Z This yields: 1.3 , 25000 --> 5.1807375 0.2 , 50000 --> 4.5 2.5 , 15000 --> 8.12252371652 Hopefully that helps...
Scipy interpolation on a numpy array
I have a lookup table that is defined the following way: | <1 2 3 4 5+ -------|---------------------------- <10000 | 3.6 6.5 9.1 11.5 13.8 20000 | 3.9 7.3 10.0 13.1 15.9 20000+ | 4.5 9.2 12.2 14.8 18.2 TR_ua1 = np.array([ [3.6, 6.5, 9.1, 11.5, 13.8], [3.9, 7.3, 10.0, 13.1, 15.9], [4.5, 9.2, 12.2, 14.8, 18.2] ]) The header row elements are (hh) < 1,2,3,4,5+ The header column (inc) elements are <10000, 20000, 20001+ The user will input a value example (1.3, 25,000), (0.2, 50,000), so on. scipy.interpolate() should interpolate to determine the correct value. Currently, the only way I can do this is with a bunch of if/elifs as exemplified below. I'm pretty sure there is a better, more efficient way of doing this Here's what I've got so far: import numpy as np from scipy import interpolate if (ua == 1): if (inc <= low_inc): # low_inc = 10,000 if (hh <= 1): return TR_ua1[0][0] elif (hh >= 1 & hh < 2): return interpolate( (1, 2), (TR_ua1[0][1], TR_ua1[0][2]) )
[ "Edit: Updated things to reflect your clarifications above. Your question is much clearer now, thanks!\nBasically, you're just wanting to interpolate a 2D array at an arbitrary point.\nscipy.ndimage.map_coordinates is what you want....\nAs I understand your question, you have a 2D array of \"z\" values that ranges from some xmin to xmax, and ymin to ymax in each direction.\nAnything outside of those bounding coordinates you want to return values from the edges of the array.\nmap_coordinates has several options to handle points outside the boundaries of the grid, but none of them do exactly what you want. Instead, we can just set anything outside the boundaries to lie on the edge, and use map_coordinates as usual.\nSo, to use map_coordinates, you need to turn your actual coodinates:\n | <1 2 3 4 5+\n-------|----------------------------\n<10000 | 3.6 6.5 9.1 11.5 13.8\n20000 | 3.9 7.3 10.0 13.1 15.9\n20000+ | 4.5 9.2 12.2 14.8 18.2\n\nInto index coordinates:\n | 0 1 2 3 4\n-------|----------------------------\n 0 | 3.6 6.5 9.1 11.5 13.8\n 1 | 3.9 7.3 10.0 13.1 15.9\n 2 | 4.5 9.2 12.2 14.8 18.2\n\nNote that your boundaries behave differently in each direction... In the x-direction, things behave smoothly, but in the y-direction, you're asking for a \"hard\" break, where y=20000 --> 3.9, but y=20000.000001 --> 4.5. \nAs an example:\nimport numpy as np\nfrom scipy.ndimage import map_coordinates\n\n#-- Setup ---------------------------\nz = np.array([ [3.6, 6.5, 9.1, 11.5, 13.8],\n [3.9, 7.3, 10.0, 13.1, 15.9],\n [4.5, 9.2, 12.2, 14.8, 18.2] ])\nny, nx = z.shape\nxmin, xmax = 1, 5\nymin, ymax = 10000, 20000\n\n# Points we want to interpolate at\nx1, y1 = 1.3, 25000\nx2, y2 = 0.2, 50000\nx3, y3 = 2.5, 15000\n\n# To make our lives easier down the road, let's \n# turn these into arrays of x & y coords\nxi = np.array([x1, x2, x3], dtype=np.float)\nyi = np.array([y1, y2, y3], dtype=np.float)\n\n# Now, we'll set points outside the boundaries to lie along an edge\nxi[xi > xmax] = xmax\nxi[xi < xmin] = xmin\n\n# To deal with the \"hard\" break, we'll have to treat y differently, \n# so we're ust setting the min here...\nyi[yi < ymin] = ymin\n\n# We need to convert these to (float) indicies\n# (xi should range from 0 to (nx - 1), etc)\nxi = (nx - 1) * (xi - xmin) / (xmax - xmin)\n\n# Deal with the \"hard\" break in the y-direction\nyi = (ny - 2) * (yi - ymin) / (ymax - ymin)\nyi[yi > 1] = 2.0\n\n# Now we actually interpolate\n# map_coordinates does cubic interpolation by default, \n# use \"order=1\" to preform bilinear interpolation instead...\nz1, z2, z3 = map_coordinates(z, [yi, xi])\n\n# Display the results\nfor X, Y, Z in zip((x1, x2, x3), (y1, y2, y3), (z1, z2, z3)):\n print X, ',', Y, '-->', Z\n\nThis yields:\n1.3 , 25000 --> 5.1807375\n0.2 , 50000 --> 4.5\n2.5 , 15000 --> 8.12252371652\n\nHopefully that helps...\n" ]
[ 8 ]
[]
[]
[ "interpolation", "numpy", "python", "scipy" ]
stackoverflow_0003057015_interpolation_numpy_python_scipy.txt
Q: Data structure in python for 2d range counting queries I need a data structure for doing 2d range counting queries (i.e. how many points are in a given rectangle). I think my best bet is range tree (it can count in log^2, or even log after some optimizations). Does it sound like a good choice? Does anybody know about a python implementation or will I have to write one myself? A: See scipy.spatial.KDTree for one implementation. There's also a less generic (but occasionally more useful, particularly with regards to what you have in mind) implementation using shapelib's quadtree. See this blog and the corresponding package in PyPi. There are probably other implementations, too, but those are the two that I've used...
Data structure in python for 2d range counting queries
I need a data structure for doing 2d range counting queries (i.e. how many points are in a given rectangle). I think my best bet is range tree (it can count in log^2, or even log after some optimizations). Does it sound like a good choice? Does anybody know about a python implementation or will I have to write one myself?
[ "See scipy.spatial.KDTree for one implementation.\nThere's also a less generic (but occasionally more useful, particularly with regards to what you have in mind) implementation using shapelib's quadtree. See this blog and the corresponding package in PyPi.\nThere are probably other implementations, too, but those are the two that I've used...\n" ]
[ 2 ]
[]
[]
[ "python", "spatial_query" ]
stackoverflow_0003058100_python_spatial_query.txt
Q: On Ubuntu, how do you install a newer version of python and keep the older python version? Background: I am using Ubuntu The newer python version is not in the apt-get repository (or synaptic) I plan on keeping the old version as the default python when you call "python" from the command line I plan on calling the new python using pythonX.X (X.X is the new version). Given the background, how do you install a newer version of python and keep the older python version? I have downloaded from python.org the "install from source" *.tgz package. The readme is pretty simple and says "execute three commands: ./configure; make; make test; sudo make install;" If I do the above commands, will the installation overwrite the old version of python I have (I definitely need the old version)? A: When you install from source, by default, the installation goes in /usr/local -- the executable in particular becomes /usr/local/bin/pythonX.Y with a symlink to it that's named /usr/local/python. Ubuntu's own installation is in /usr/ (e.g., /usr/bin/python), so the new installation won't overwrite it. Take care that the PATH environment variable doesn't have /usr/local/bin before /usr/bin, or else simple mentions of python would execute the new one, not the old one. A: I'm just going to assume that by "newer version" you mean "released version that is newer than the default version in Ubuntu". That means python 3.1, which is in the repositories. sudo apt-get install python3 Different python versions in the Ubuntu repositories can coexist with one another just fine. If you're on a version of Ubuntu older than Lucid, you'll have to upgrade your OS or enable the universe repository in order for python3 to show up in your package manager. If you mean python 2.7, you should be aware that it hasn't been released yet. A: Just installed Python2.6 on Ubuntu 8.04. first get all the required dependencies "apt-get build-dep python2.5" (The python 2.6 dependencies are the same as for 2.5) apply the patch from http://www.lysium.de/sw/python2.6-disable-old-modules.patch: patch -p1 < python2.6-disable-old-modules.patch then ./configure --prefix=/opt/python2.6 make sudo make install sudo ln -s /opt/python2.6/bin/python2.6 /usr/local/bin/python2.6 it seems just works, default Python version is still 2.5. I save it at here, hope this helps. A: The Easy Way Open up 'Synaptic Package Manager' from the menu Search for 'python' in the 'Quick Search' field Select and install whatever versions of python you choose to use To use a specific version of python (Ex. 2.4) just type python followed by the version number in the terminal: python2.4 run_some_script.py To install libraries to a particular version of python just run setup.py the same way. Ex. Install to python2.5 python2.5 setup.py install In this day and age, there's really no need to build from source or worry about dependency tracking on most programs unless you're developing it directly or you're using a bleeding-edge non-stable branch. If the newer stable revisions of python aren't showing up in apt-get or synaptic, update your repository. in Synaptic press ctrl-r in apt type 'apt-get update' Note: You really should be able to get all the stable releases of python from 2.4 - 3.1 except 3.0 (because 3.0 has mainly been ditched as a result of the 'throw away' nature of the changes on that particular branch and the emergence of 3.1).
On Ubuntu, how do you install a newer version of python and keep the older python version?
Background: I am using Ubuntu The newer python version is not in the apt-get repository (or synaptic) I plan on keeping the old version as the default python when you call "python" from the command line I plan on calling the new python using pythonX.X (X.X is the new version). Given the background, how do you install a newer version of python and keep the older python version? I have downloaded from python.org the "install from source" *.tgz package. The readme is pretty simple and says "execute three commands: ./configure; make; make test; sudo make install;" If I do the above commands, will the installation overwrite the old version of python I have (I definitely need the old version)?
[ "When you install from source, by default, the installation goes in /usr/local -- the executable in particular becomes /usr/local/bin/pythonX.Y with a symlink to it that's named /usr/local/python. Ubuntu's own installation is in /usr/ (e.g., /usr/bin/python), so the new installation won't overwrite it. Take care that the PATH environment variable doesn't have /usr/local/bin before /usr/bin, or else simple mentions of python would execute the new one, not the old one.\n", "I'm just going to assume that by \"newer version\" you mean \"released version that is newer than the default version in Ubuntu\". That means python 3.1, which is in the repositories.\nsudo apt-get install python3\n\nDifferent python versions in the Ubuntu repositories can coexist with one another just fine. If you're on a version of Ubuntu older than Lucid, you'll have to upgrade your OS or enable the universe repository in order for python3 to show up in your package manager.\nIf you mean python 2.7, you should be aware that it hasn't been released yet.\n", "Just installed Python2.6 on Ubuntu 8.04.\nfirst get all the required dependencies \"apt-get build-dep python2.5\" (The python 2.6 dependencies are the same as for 2.5)\napply the patch from http://www.lysium.de/sw/python2.6-disable-old-modules.patch:\npatch -p1 < python2.6-disable-old-modules.patch \nthen ./configure --prefix=/opt/python2.6\nmake\nsudo make install \nsudo ln -s /opt/python2.6/bin/python2.6 /usr/local/bin/python2.6\nit seems just works, default Python version is still 2.5.\nI save it at here, hope this helps.\n", "The Easy Way\n\nOpen up 'Synaptic Package Manager' from the menu\nSearch for 'python' in the 'Quick Search' field\nSelect and install whatever versions of python you choose to use\n\nTo use a specific version of python (Ex. 2.4) just type python followed by the version number in the terminal:\npython2.4 run_some_script.py\n\nTo install libraries to a particular version of python just run setup.py the same way.\nEx. Install to python2.5\npython2.5 setup.py install\n\nIn this day and age, there's really no need to build from source or worry about dependency tracking on most programs unless you're developing it directly or you're using a bleeding-edge non-stable branch.\nIf the newer stable revisions of python aren't showing up in apt-get or synaptic, update your repository. \n\nin Synaptic press ctrl-r\nin apt type 'apt-get update'\n\nNote: You really should be able to get all the stable releases of python from 2.4 - 3.1 except 3.0 (because 3.0 has mainly been ditched as a result of the 'throw away' nature of the changes on that particular branch and the emergence of 3.1).\n" ]
[ 10, 3, 1, 0 ]
[]
[]
[ "configure", "gnu", "installation", "python", "ubuntu" ]
stackoverflow_0003050512_configure_gnu_installation_python_ubuntu.txt
Q: Losing control of GUI upon playing a wav file I can't understand why I am loosing control of my GUI even though I am implementing a thread to play a .wav file. Can someone pin point what is incorrect? #!/usr/bin/env python import wx, pyaudio, wave, easygui, thread, time, os, sys, traceback, threading import wx.lib.delayedresult as inbg isPaused = False isStopped = False class Frame(wx.Frame): def __init__(self): print 'Frame' wx.Frame.__init__(self, parent=None, id=-1, title="Jasmine", size=(720, 300)) #initialize panel panel = wx.Panel(self, -1) #initialize grid bag sizer = wx.GridBagSizer(hgap=20, vgap=20) #initialize buttons exitButton = wx.Button(panel, wx.ID_ANY, "Exit") pauseButton = wx.Button(panel, wx.ID_ANY, 'Pause') prevButton = wx.Button(panel, wx.ID_ANY, 'Prev') nextButton = wx.Button(panel, wx.ID_ANY, 'Next') stopButton = wx.Button(panel, wx.ID_ANY, 'Stop') #add widgets to sizer sizer.Add(pauseButton, pos=(1,10)) sizer.Add(prevButton, pos=(1,11)) sizer.Add(nextButton, pos=(1,12)) sizer.Add(stopButton, pos=(1,13)) sizer.Add(exitButton, pos=(5,13)) #initialize song time gauge #timeGauge = wx.Gauge(panel, 20) #sizer.Add(timeGauge, pos=(3,10), span=(0, 0)) #initialize menuFile widget menuFile = wx.Menu() menuFile.Append(0, "L&oad") menuFile.Append(1, "E&xit") menuBar = wx.MenuBar() menuBar.Append(menuFile, "&File") menuAbout = wx.Menu() menuAbout.Append(2, "A&bout...") menuAbout.AppendSeparator() menuBar.Append(menuAbout, "Help") self.SetMenuBar(menuBar) self.CreateStatusBar() self.SetStatusText("Welcome to Jasime!") #place sizer on panel panel.SetSizer(sizer) #initialize icon self.cd_image = wx.Image('cd_icon.png', wx.BITMAP_TYPE_PNG) self.temp = self.cd_image.ConvertToBitmap() self.size = self.temp.GetWidth(), self.temp.GetHeight() wx.StaticBitmap(parent=panel, bitmap=self.temp) #set binding self.Bind(wx.EVT_BUTTON, self.OnQuit, id=exitButton.GetId()) self.Bind(wx.EVT_BUTTON, self.pause, id=pauseButton.GetId()) self.Bind(wx.EVT_BUTTON, self.stop, id=stopButton.GetId()) self.Bind(wx.EVT_MENU, self.loadFile, id=0) self.Bind(wx.EVT_MENU, self.OnQuit, id=1) self.Bind(wx.EVT_MENU, self.OnAbout, id=2) #Load file using FileDialog, and create a thread for user control while running the file def loadFile(self, event): foo = wx.FileDialog(self, message="Open a .wav file...", defaultDir=os.getcwd(), defaultFile="", style=wx.FD_MULTIPLE) foo.ShowModal() self.queue = foo.GetPaths() self.threadID = 1 while len(self.queue) != 0: self.song = myThread(self.threadID, self.queue[0]) self.song.start() while self.song.isAlive(): time.sleep(2) self.queue.pop(0) self.threadID += 1 def OnQuit(self, event): self.Close() def OnAbout(self, event): wx.MessageBox("This is a great cup of tea.", "About Jasmine", wx.OK | wx.ICON_INFORMATION, self) def pause(self, event): global isPaused isPaused = not isPaused def stop(self, event): global isStopped isStopped = not isStopped class myThread (threading.Thread): def __init__(self, threadID, wf): self.threadID = threadID self.wf = wf threading.Thread.__init__(self) def run(self): global isPaused global isStopped self.waveFile = wave.open(self.wf, 'rb') #initialize stream self.p = pyaudio.PyAudio() self.stream = self.p.open(format = self.p.get_format_from_width(self.waveFile.getsampwidth()), channels = self.waveFile.getnchannels(), rate = self.waveFile.getframerate(), output = True) self.data = self.waveFile.readframes(1024) isPaused = False isStopped = False #main play loop, with pause event checking while self.data != '': # while isPaused != True: # if isStopped == False: self.stream.write(self.data) self.data = self.waveFile.readframes(1024) # elif isStopped == True: # self.stream.close() # self.p.terminate() self.stream.close() self.p.terminate() class App(wx.App): def OnInit(self): self.frame = Frame() self.frame.Show() self.SetTopWindow(self.frame) return True def main(): app = App() app.MainLoop() if __name__=='__main__': main() A: Your loadFile method, quite independently of the fact that it delegates song-playing to many threads (which it waits for in strange ways, but, that's another issue), is still monopolizing the wx event loop until it returns. Where you currently have a time.sleep, try adding app.Yield(True) (of course you need to make app visible at that point in your code: simplest though inelegant is to add a global app at the start of main. Event-driven systems typically serve the event loop only when your various event handler methods return: if you have a long-running event handler, you need to explicitly yield control to the event loop once in a while. Various event systems offer different ways to do it: in wx, it's the Yield method which I just recommended you try. See the brief description un the docs.
Losing control of GUI upon playing a wav file
I can't understand why I am loosing control of my GUI even though I am implementing a thread to play a .wav file. Can someone pin point what is incorrect? #!/usr/bin/env python import wx, pyaudio, wave, easygui, thread, time, os, sys, traceback, threading import wx.lib.delayedresult as inbg isPaused = False isStopped = False class Frame(wx.Frame): def __init__(self): print 'Frame' wx.Frame.__init__(self, parent=None, id=-1, title="Jasmine", size=(720, 300)) #initialize panel panel = wx.Panel(self, -1) #initialize grid bag sizer = wx.GridBagSizer(hgap=20, vgap=20) #initialize buttons exitButton = wx.Button(panel, wx.ID_ANY, "Exit") pauseButton = wx.Button(panel, wx.ID_ANY, 'Pause') prevButton = wx.Button(panel, wx.ID_ANY, 'Prev') nextButton = wx.Button(panel, wx.ID_ANY, 'Next') stopButton = wx.Button(panel, wx.ID_ANY, 'Stop') #add widgets to sizer sizer.Add(pauseButton, pos=(1,10)) sizer.Add(prevButton, pos=(1,11)) sizer.Add(nextButton, pos=(1,12)) sizer.Add(stopButton, pos=(1,13)) sizer.Add(exitButton, pos=(5,13)) #initialize song time gauge #timeGauge = wx.Gauge(panel, 20) #sizer.Add(timeGauge, pos=(3,10), span=(0, 0)) #initialize menuFile widget menuFile = wx.Menu() menuFile.Append(0, "L&oad") menuFile.Append(1, "E&xit") menuBar = wx.MenuBar() menuBar.Append(menuFile, "&File") menuAbout = wx.Menu() menuAbout.Append(2, "A&bout...") menuAbout.AppendSeparator() menuBar.Append(menuAbout, "Help") self.SetMenuBar(menuBar) self.CreateStatusBar() self.SetStatusText("Welcome to Jasime!") #place sizer on panel panel.SetSizer(sizer) #initialize icon self.cd_image = wx.Image('cd_icon.png', wx.BITMAP_TYPE_PNG) self.temp = self.cd_image.ConvertToBitmap() self.size = self.temp.GetWidth(), self.temp.GetHeight() wx.StaticBitmap(parent=panel, bitmap=self.temp) #set binding self.Bind(wx.EVT_BUTTON, self.OnQuit, id=exitButton.GetId()) self.Bind(wx.EVT_BUTTON, self.pause, id=pauseButton.GetId()) self.Bind(wx.EVT_BUTTON, self.stop, id=stopButton.GetId()) self.Bind(wx.EVT_MENU, self.loadFile, id=0) self.Bind(wx.EVT_MENU, self.OnQuit, id=1) self.Bind(wx.EVT_MENU, self.OnAbout, id=2) #Load file using FileDialog, and create a thread for user control while running the file def loadFile(self, event): foo = wx.FileDialog(self, message="Open a .wav file...", defaultDir=os.getcwd(), defaultFile="", style=wx.FD_MULTIPLE) foo.ShowModal() self.queue = foo.GetPaths() self.threadID = 1 while len(self.queue) != 0: self.song = myThread(self.threadID, self.queue[0]) self.song.start() while self.song.isAlive(): time.sleep(2) self.queue.pop(0) self.threadID += 1 def OnQuit(self, event): self.Close() def OnAbout(self, event): wx.MessageBox("This is a great cup of tea.", "About Jasmine", wx.OK | wx.ICON_INFORMATION, self) def pause(self, event): global isPaused isPaused = not isPaused def stop(self, event): global isStopped isStopped = not isStopped class myThread (threading.Thread): def __init__(self, threadID, wf): self.threadID = threadID self.wf = wf threading.Thread.__init__(self) def run(self): global isPaused global isStopped self.waveFile = wave.open(self.wf, 'rb') #initialize stream self.p = pyaudio.PyAudio() self.stream = self.p.open(format = self.p.get_format_from_width(self.waveFile.getsampwidth()), channels = self.waveFile.getnchannels(), rate = self.waveFile.getframerate(), output = True) self.data = self.waveFile.readframes(1024) isPaused = False isStopped = False #main play loop, with pause event checking while self.data != '': # while isPaused != True: # if isStopped == False: self.stream.write(self.data) self.data = self.waveFile.readframes(1024) # elif isStopped == True: # self.stream.close() # self.p.terminate() self.stream.close() self.p.terminate() class App(wx.App): def OnInit(self): self.frame = Frame() self.frame.Show() self.SetTopWindow(self.frame) return True def main(): app = App() app.MainLoop() if __name__=='__main__': main()
[ "Your loadFile method, quite independently of the fact that it delegates song-playing to many threads (which it waits for in strange ways, but, that's another issue), is still monopolizing the wx event loop until it returns. Where you currently have a time.sleep, try adding app.Yield(True) (of course you need to make app visible at that point in your code: simplest though inelegant is to add a global app at the start of main.\nEvent-driven systems typically serve the event loop only when your various event handler methods return: if you have a long-running event handler, you need to explicitly yield control to the event loop once in a while. Various event systems offer different ways to do it: in wx, it's the Yield method which I just recommended you try. See the brief description un the docs.\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0003058128_python.txt
Q: Where do I put utility functions in my Python project? I need to create a function to rotate a given matrix (list of lists) clockwise, and I need to use it in my Table class. Where should I put this utility function (called rotateMatrixClockwise) so I can call it easily from within a function in my Table class? A: Make it a static function... add the @staticmethod decorator don't include 'self' as the first argument Your definition would be: @staticmethod def rotateMatrixClockwise(): # enter code here... Which will make it callable everywhere you imported 'table' by calling: table.rotateMatrixClockwise() The decorator is only necessary to tell python that no implicit first argument is expected. If you wanted to make method definitions act like C#/Java where self is always implicit you could also use the '@classmethod' decorator. Here's the documentation for this coming directly from the python manual. Note: I'd recommend using Utility classes only where their code can't be coupled directly to a module because they generally violate the 'Single Responsibility Principle' of OOP. It's almost always best to tie the functionality of a class as a method/member to the class. A: If you don't want to make it a member of the Table class you could put it into a utilities module.
Where do I put utility functions in my Python project?
I need to create a function to rotate a given matrix (list of lists) clockwise, and I need to use it in my Table class. Where should I put this utility function (called rotateMatrixClockwise) so I can call it easily from within a function in my Table class?
[ "Make it a static function...\n\nadd the @staticmethod decorator\ndon't include 'self' as the first argument \n\nYour definition would be: \n@staticmethod\ndef rotateMatrixClockwise():\n # enter code here...\n\nWhich will make it callable everywhere you imported 'table' by calling:\ntable.rotateMatrixClockwise()\n\nThe decorator is only necessary to tell python that no implicit first argument is expected. If you wanted to make method definitions act like C#/Java where self is always implicit you could also use the '@classmethod' decorator.\nHere's the documentation for this coming directly from the python manual.\nNote: I'd recommend using Utility classes only where their code can't be coupled directly to a module because they generally violate the 'Single Responsibility Principle' of OOP. It's almost always best to tie the functionality of a class as a method/member to the class.\n", "If you don't want to make it a member of the Table class you could put it into a utilities module.\n" ]
[ 14, 4 ]
[]
[]
[ "function", "import", "python", "utilities" ]
stackoverflow_0003049569_function_import_python_utilities.txt
Q: Removing python and then re-installing on Mac OSX I was wondering if anyone had tips on how to completely remove a python installation form Mac OSX (10.5.8) ... including virtual environments and its related binaries. Over the past few years I've completely messed up the installed site-packages, virtual-environments, etc. and the only way I can see to fix it is to just uninstall everything and re-install. I'd like to completely re-do everything and use virtualenv, pip, etc. from the beginning. On the other hand if anyone knows a way to do this without removing python and re-installing I'd be happy to here about it. Thanks, Will A: Just for everyone else's reference. I found this in the Python documentation here: Mac OS X 10.5 comes with Python 2.5.1 pre-installed by Apple. If you wish, you are invited to install the most recent version of Python from the Python website (http://www.python.org). A current “universal binary” build of Python, which runs natively on the Mac’s new Intel and legacy PPC CPU’s, is available there. What you get after installing is a number of things: * A MacPython 2.5 folder in your Applications folder. In here you find IDLE, the development environment that is a standard part of official Python distributions; PythonLauncher, which handles double-clicking Python scripts from the Finder; and the “Build Applet” tool, which allows you to package Python scripts as standalone applications on your system. * A framework /Library/Frameworks/Python.framework, which includes the Python executable and libraries. The installer adds this location to your shell path. To uninstall MacPython, you can simply remove these three things. A symlink to the Python executable is placed in /usr/local/bin/. I removed these and the virtualenv directories. Then I re-installed everything and its working fine now. A: You should be able to delete the packages you've installed from /Library/Python/2.*/site-packages/. I do not think any package installers will install by default to /System/Library, which should save you from needing to remove Python itself. That said, you could also use virtualenv with --no-site-packages, and just ignore whatever packages you've installed system-wide without needing to remove them.
Removing python and then re-installing on Mac OSX
I was wondering if anyone had tips on how to completely remove a python installation form Mac OSX (10.5.8) ... including virtual environments and its related binaries. Over the past few years I've completely messed up the installed site-packages, virtual-environments, etc. and the only way I can see to fix it is to just uninstall everything and re-install. I'd like to completely re-do everything and use virtualenv, pip, etc. from the beginning. On the other hand if anyone knows a way to do this without removing python and re-installing I'd be happy to here about it. Thanks, Will
[ "Just for everyone else's reference. I found this in the Python documentation here:\n\n\nMac OS X 10.5 comes with Python 2.5.1 pre-installed by Apple. If you wish, you are invited to install the\n most recent version of Python from the\n Python website\n (http://www.python.org). A current\n “universal binary” build of Python,\n which runs natively on the Mac’s new\n Intel and legacy PPC CPU’s, is\n available there.\n\nWhat you get after installing is a\n number of things:\n* A MacPython 2.5 folder in your Applications folder. In here you find\n\nIDLE, the development environment that\n is a standard part of official Python\n distributions; PythonLauncher, which\n handles double-clicking Python scripts\n from the Finder; and the “Build\n Applet” tool, which allows you to\n package Python scripts as standalone\n applications on your system.\n * A framework /Library/Frameworks/Python.framework,\n which includes the Python executable\n and libraries. The installer adds this\n location to your shell path. To\n uninstall MacPython, you can simply\n remove these three things. A symlink\n to the Python executable is placed in\n /usr/local/bin/.\n\nI removed these and the virtualenv directories. Then I re-installed everything and its working fine now.\n", "You should be able to delete the packages you've installed from /Library/Python/2.*/site-packages/. I do not think any package installers will install by default to /System/Library, which should save you from needing to remove Python itself.\nThat said, you could also use virtualenv with --no-site-packages, and just ignore whatever packages you've installed system-wide without needing to remove them.\n" ]
[ 1, 0 ]
[]
[]
[ "installation", "macos", "python" ]
stackoverflow_0003034304_installation_macos_python.txt
Q: Python CLI tool - general parsing question If possible I would like to use the following structure for a command however I can't seem to figure out how to achieve this in Python: ./somescript.py arg <optional argument> -- "some long argument" Would it be possible to achieve this in a feasible manner without too much dirty code? Or should I just reconsider the syntax (which is primarily preference). Thanks! A: I think optparse can do this. A: If you don't want to use dashes in front of your arg and optional_argument, that's kind of strange by typical Unix command-line behavior, but I don't understand why every answer appears to believe you have to use the dashes. Avoiding them is kind of trivial, actually...: import sys def before_and_after_doubledashes(args=sys.argv): where_doubledashes = args.index('--') if '--' in args else len(args) return args[:where_doubledashes], args[where_doubledashes+1:] This completely ignores whether args start with dashes or not, just singles out the first occurrence of an arg that's exactly a double dash (if any) and returns a tuple of two lists, one all the args that are before that double dash if any, one all the args that are after it (empty if there's no double dash argument). You can assign these lists from the call: before, after = before_and_after_doubledashes() then treat them as you will (check their lengths, assign variables from part of them, etc). A: You just need to stick something like this on the first line: #/usr/local/bin/python Just make yours be wherever your python binary is located. As for args look at getopt or optparser And remember to chmod your file to make it executable.
Python CLI tool - general parsing question
If possible I would like to use the following structure for a command however I can't seem to figure out how to achieve this in Python: ./somescript.py arg <optional argument> -- "some long argument" Would it be possible to achieve this in a feasible manner without too much dirty code? Or should I just reconsider the syntax (which is primarily preference). Thanks!
[ "I think optparse can do this.\n", "If you don't want to use dashes in front of your arg and optional_argument, that's kind of strange by typical Unix command-line behavior, but I don't understand why every answer appears to believe you have to use the dashes. Avoiding them is kind of trivial, actually...:\nimport sys\n\ndef before_and_after_doubledashes(args=sys.argv):\n where_doubledashes = args.index('--') if '--' in args else len(args)\n return args[:where_doubledashes], args[where_doubledashes+1:]\n\nThis completely ignores whether args start with dashes or not, just singles out the first occurrence of an arg that's exactly a double dash (if any) and returns a tuple of two lists, one all the args that are before that double dash if any, one all the args that are after it (empty if there's no double dash argument). You can assign these lists from the call:\nbefore, after = before_and_after_doubledashes()\n\nthen treat them as you will (check their lengths, assign variables from part of them, etc).\n", "You just need to stick something like this on the first line:\n #/usr/local/bin/python\nJust make yours be wherever your python binary is located.\nAs for args look at getopt or optparser \nAnd remember to chmod your file to make it executable.\n" ]
[ 3, 1, 0 ]
[]
[]
[ "command_line_interface", "python", "shell" ]
stackoverflow_0003057805_command_line_interface_python_shell.txt
Q: How do I get user input to refer to a variable in Python? I would like to get user input to refer to some list in my code. I think it's called namespace? So, what would I have to do to this code for me to print whatever the user inputs, supposing they input 'list1' or 'list2'? list1 = ['cat', 'dog', 'juice'] list2 = ['skunk', 'bats', 'pogo stick'] x = raw_input('which list would you like me to print?') I plan to have many such lists, so a series of if...then statements seems unruly. A: In the cases I can think of right now it would probably be better to have a dictionary containing what you want the user to be able to reference, for example: my_dict = { 'list1': ['cat', 'dog', 'juice'] 'list2': ['skunk', 'bats', 'pogo stick'] } key = raw_input('which list would you like me to print?') print my_dict[key] In fact, you can take advantage of the built-in globals(), like this: list1 = ['cat', 'dog', 'juice'] list2 = ['skunk', 'bats', 'pogo stick'] x = raw_input() print globals()[x] A: The general idea of using a dict is good, but the best specific implementation is probably something like: def pick_one(prompt, **kwds): while True: x = raw_input(prompt) if x in kwds: return kwds[x] else: print 'Please choose one of: ', for k in sorted(kwds): print k, print To be used, e.g., as: print pick_one('which list would you like me to print?', list1 = ['cat', 'dog', 'juice'] list2 = ['skunk', 'bats', 'pogo stick']) The point is that, when you're asking the user to select one among a limited number of possibilities, you'll always want to check that the choice was one of them (it is after all easy to mis-spell, etc), and, if not, prompt accurately (giving the list of available choices) and give the user another chance. All sorts of refinements (have a maximum number of attempts, for example, after which you decide the user just can't type and pick one at random;-) are left as (not too hard but not too interesting either;-) exercises for the reader.
How do I get user input to refer to a variable in Python?
I would like to get user input to refer to some list in my code. I think it's called namespace? So, what would I have to do to this code for me to print whatever the user inputs, supposing they input 'list1' or 'list2'? list1 = ['cat', 'dog', 'juice'] list2 = ['skunk', 'bats', 'pogo stick'] x = raw_input('which list would you like me to print?') I plan to have many such lists, so a series of if...then statements seems unruly.
[ "In the cases I can think of right now it would probably be better to have a dictionary containing what you want the user to be able to reference, for example:\nmy_dict = {\n 'list1': ['cat', 'dog', 'juice']\n 'list2': ['skunk', 'bats', 'pogo stick']\n}\n\nkey = raw_input('which list would you like me to print?')\n\nprint my_dict[key]\n\nIn fact, you can take advantage of the built-in globals(), like this:\nlist1 = ['cat', 'dog', 'juice']\nlist2 = ['skunk', 'bats', 'pogo stick']\nx = raw_input()\n\nprint globals()[x]\n\n", "The general idea of using a dict is good, but the best specific implementation is probably something like:\ndef pick_one(prompt, **kwds):\n while True:\n x = raw_input(prompt)\n if x in kwds:\n return kwds[x]\n else:\n print 'Please choose one of: ',\n for k in sorted(kwds): print k,\n print\n\nTo be used, e.g., as:\nprint pick_one('which list would you like me to print?',\n list1 = ['cat', 'dog', 'juice']\n list2 = ['skunk', 'bats', 'pogo stick'])\n\nThe point is that, when you're asking the user to select one among a limited number of possibilities, you'll always want to check that the choice was one of them (it is after all easy to mis-spell, etc), and, if not, prompt accurately (giving the list of available choices) and give the user another chance.\nAll sorts of refinements (have a maximum number of attempts, for example, after which you decide the user just can't type and pick one at random;-) are left as (not too hard but not too interesting either;-) exercises for the reader.\n" ]
[ 4, 2 ]
[]
[]
[ "list", "namespaces", "python", "raw_input" ]
stackoverflow_0003058457_list_namespaces_python_raw_input.txt
Q: How to get bit rotation function to accept any bit size? i have these 2 functions i got from some other code def ROR(x, n): mask = (2L**n) - 1 mask_bits = x & mask return (x >> n) | (mask_bits << (32 - n)) def ROL(x, n): return ROR(x, 32 - n) and i wanted to use them in a program, where 16 bit rotations are required. however, there are also other functions that require 32 bit rotations, so i wanted to leave the 32 in the equation, so i got: def ROR(x, n, bits = 32): mask = (2L**n) - 1 mask_bits = x & mask return (x >> n) | (mask_bits << (bits - n)) def ROL(x, n, bits = 32): return ROR(x, bits - n) however, the answers came out wrong when i tested this set out. yet, the values came out correctly when the code is def ROR(x, n): mask = (2L**n) - 1 mask_bits = x & mask return (x >> n) | (mask_bits << (16 - n)) def ROL(x, n,bits): return ROR(x, 16 - n) what is going on and how do i fix this? A: Well, just look at what happens when you call ROL(x, n, 16). It calls ROR(x,16-n), which is equivalent to ROR(x,16-n,32), but what you really wanted was ROR(x, 16-n, 16). A: Basically, the implication of @GregS's correct answers are that you need to fix one detail in your second implementation: def ROL(x, n, bits=32): return ROR(x, bits - n, bits) (I'd make this a comment, but then I couldn't have readably formatted code in it!-).
How to get bit rotation function to accept any bit size?
i have these 2 functions i got from some other code def ROR(x, n): mask = (2L**n) - 1 mask_bits = x & mask return (x >> n) | (mask_bits << (32 - n)) def ROL(x, n): return ROR(x, 32 - n) and i wanted to use them in a program, where 16 bit rotations are required. however, there are also other functions that require 32 bit rotations, so i wanted to leave the 32 in the equation, so i got: def ROR(x, n, bits = 32): mask = (2L**n) - 1 mask_bits = x & mask return (x >> n) | (mask_bits << (bits - n)) def ROL(x, n, bits = 32): return ROR(x, bits - n) however, the answers came out wrong when i tested this set out. yet, the values came out correctly when the code is def ROR(x, n): mask = (2L**n) - 1 mask_bits = x & mask return (x >> n) | (mask_bits << (16 - n)) def ROL(x, n,bits): return ROR(x, 16 - n) what is going on and how do i fix this?
[ "Well, just look at what happens when you call ROL(x, n, 16). It calls ROR(x,16-n), which is equivalent to ROR(x,16-n,32), but what you really wanted was ROR(x, 16-n, 16).\n", "Basically, the implication of @GregS's correct answers are that you need to fix one detail in your second implementation:\ndef ROL(x, n, bits=32):\n return ROR(x, bits - n, bits)\n\n(I'd make this a comment, but then I couldn't have readably formatted code in it!-).\n" ]
[ 6, 3 ]
[]
[]
[ "math", "python", "rotation" ]
stackoverflow_0003057726_math_python_rotation.txt
Q: Python: What is the most feature-rich library for loading audio metadata from various formats? I'm looking for a good, feature-rich, library for reading metadata from various audio formats (MP3, FLAC, OGG, WAV, etc.). I have already looked at Mutagen, but the documentation is nearly nonexistent, and it seems incapable of loading basic information such as artist and audio title. A: Are the artist and audio title encoded properly? What particular formats is it failing one - often ID3 information is poorly encoded. http://wiki.python.org/moin/UsefulModules#ID3Handling (A List of ID3 modules) I would try ID3Reader, which has support for ID3v1, which Mutagen seems to be missing. A: see taglib and it's python bindings A: another binding based on taglib (maybe the same as python-taglib?) called tagpy by Andreas -- http://mathema.tician.de/software/tagpy . I used it a while ago, and it's not bad... the following rough code should give you an idea how to copy tags from one file to the other (thus any other manipulation) def copy_tags(src_file, dst_file): # args both strings tag0 = tagpy.FileRef(src_file).file().tag() file1 = tagpy.FileRef(dst_file) tag1 = file1.file().tag() for info in ['album', 'artist', 'comment', 'genre', 'title', 'track', 'year']: setattr(tag1, info, getattr(tag0, info)) print file1.save() A: gstreamer is also an excellent option, if you don't mind the gnome dependency and a bit more effort coding. it supports just about every filetype known to man.
Python: What is the most feature-rich library for loading audio metadata from various formats?
I'm looking for a good, feature-rich, library for reading metadata from various audio formats (MP3, FLAC, OGG, WAV, etc.). I have already looked at Mutagen, but the documentation is nearly nonexistent, and it seems incapable of loading basic information such as artist and audio title.
[ "Are the artist and audio title encoded properly? What particular formats is it failing one - often ID3 information is poorly encoded.\nhttp://wiki.python.org/moin/UsefulModules#ID3Handling (A List of ID3 modules)\nI would try ID3Reader, which has support for ID3v1, which Mutagen seems to be missing. \n", "see taglib and it's python bindings\n", "another binding based on taglib (maybe the same as python-taglib?) called tagpy by Andreas -- http://mathema.tician.de/software/tagpy . I used it a while ago, and it's not bad... the following rough code should give you an idea how to copy tags from one file to the other (thus any other manipulation)\ndef copy_tags(src_file, dst_file): # args both strings\n tag0 = tagpy.FileRef(src_file).file().tag()\n file1 = tagpy.FileRef(dst_file)\n tag1 = file1.file().tag()\n for info in ['album', 'artist', 'comment', 'genre', 'title', 'track', 'year']:\n setattr(tag1, info, getattr(tag0, info))\n print file1.save()\n\n", "gstreamer is also an excellent option, if you don't mind the gnome dependency and a bit more effort coding. it supports just about every filetype known to man.\n" ]
[ 1, 1, 1, 0 ]
[]
[]
[ "audio", "metadata", "python" ]
stackoverflow_0002985641_audio_metadata_python.txt
Q: scraping blog contents After obtaining the urls for various blogspots, tumblr and wordpress pages, I faced some problems processing the html pages. The thing is, i wish to distinguish between the content,title and date for each blog post. I might be able to get the date through regex, but there are so many custom scripts people are using now that the html classes and structure is so different. Does anyone has a solution that may help? A: If at all feasible, use the blogs' RSS or Atom feeds instead -- they're well-structured XML, rather than not-so-well structured HTML, and Universal Feed Parser is enormously helpful at getting to feeds' contents in Python. If some blog lacks a feed (or the feed is really scarce), so you have to parse its HTML (sigh!), the best approach is BeautifulSoup (use the latest 3.0.*, not a 3.1 -- for why, see here) - not the fastest, but the most resilient in front of very badly formed HTML (and the same kind of blog that lacks a feed, I suspect, may be liable to have rotten HTML). lxml, the library @Hank recommends, does include a copy of BeautifulSoup I believe, but, if that's all you're going to get, why go to the bother of installing the whole when you only need a part?-) A: Don't use regex. Use a parser. lxml is really fast. Actually, if your sites publish atom or rss feeds, parse those instead; they have well-defined structure that makes it easy to get the data you're trying to get. UPDATE: Often times, you can find a <link> to the feed in the HTML of the blog post. Look for something resembling the following (the exact value of type is likely to vary depending on Atom vs. RSS, etc.): <link rel="alternate" type="application/atom+xml" title="My Weblog feed" href="/feed/" /> in the <head> of the document. If you find a feed, use the Universal Feed Parser, as @Alex Martelli recommends. Oh, and you may want to watch this PyCon video. A: I think you should change your approach. Instead of parsing the html page, why not parse the RSS feed? Wordpress has this built in, and it already contains the info you need such as titles, author, dates etc. You can still use regex for parsing the RSS feeds or you can use existing python modules such as Universal Feed Parser
scraping blog contents
After obtaining the urls for various blogspots, tumblr and wordpress pages, I faced some problems processing the html pages. The thing is, i wish to distinguish between the content,title and date for each blog post. I might be able to get the date through regex, but there are so many custom scripts people are using now that the html classes and structure is so different. Does anyone has a solution that may help?
[ "If at all feasible, use the blogs' RSS or Atom feeds instead -- they're well-structured XML, rather than not-so-well structured HTML, and Universal Feed Parser is enormously helpful at getting to feeds' contents in Python.\nIf some blog lacks a feed (or the feed is really scarce), so you have to parse its HTML (sigh!), the best approach is BeautifulSoup (use the latest 3.0.*, not a 3.1 -- for why, see here) - not the fastest, but the most resilient in front of very badly formed HTML (and the same kind of blog that lacks a feed, I suspect, may be liable to have rotten HTML). lxml, the library @Hank recommends, does include a copy of BeautifulSoup I believe, but, if that's all you're going to get, why go to the bother of installing the whole when you only need a part?-)\n", "Don't use regex. Use a parser. lxml is really fast.\nActually, if your sites publish atom or rss feeds, parse those instead; they have well-defined structure that makes it easy to get the data you're trying to get.\nUPDATE:\nOften times, you can find a <link> to the feed in the HTML of the blog post. Look for something resembling the following (the exact value of type is likely to vary depending on Atom vs. RSS, etc.):\n<link rel=\"alternate\" type=\"application/atom+xml\" title=\"My Weblog feed\" href=\"/feed/\" />\n\nin the <head> of the document.\nIf you find a feed, use the Universal Feed Parser, as @Alex Martelli recommends.\nOh, and you may want to watch this PyCon video.\n", "I think you should change your approach. Instead of parsing the html page, why not parse the RSS feed? Wordpress has this built in, and it already contains the info you need such as titles, author, dates etc.\nYou can still use regex for parsing the RSS feeds or you can use existing python modules such as Universal Feed Parser\n" ]
[ 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003058562_python.txt
Q: Python Numpy Structured Array (recarray) assigning values into slices The following example shows what I want to do: >>> test rec.array([(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0)], dtype=[('ifAction', '|i1'), ('ifDocu', '|i1'), ('ifComedy', '|i1')]) >>> test[['ifAction', 'ifDocu']][0] (0, 0) >>> test[['ifAction', 'ifDocu']][0] = (1,1) >>> test[['ifAction', 'ifDocu']][0] (0, 0) So, I want to assign the values (1,1) to test[['ifAction', 'ifDocu']][0]. (Eventually, I want to do something like test[['ifAction', 'ifDocu']][0:10] = (1,1), assigning the same values for for 0:10. I have tried many ways but never succeeded. Is there any way to do this? Thank you, Joon A: When you say test['ifAction'] you get a view of the data. When you say test[['ifAction','ifDocu']] you are using fancy-indexing and thus get a copy of the data. The copy doesn't help you since modifying the copy leaves the original data unchanged. So a way around this is to assign values to test['ifAction'] and test['ifDocu'] individually: test['ifAction'][0]=1 test['ifDocu'][0]=1 For example: import numpy as np test=np.rec.array([(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0)], dtype=[('ifAction', '|i1'), ('ifDocu', '|i1'), ('ifComedy', '|i1')]) print(test[['ifAction','ifDocu']]) # [(0, 0) (0, 0) (0, 0) (0, 0) (0, 0) (0, 0) (0, 0) (0, 0) (0, 0) (0, 0)] test['ifAction'][0]=1 test['ifDocu'][0]=1 print(test[['ifAction','ifDocu']][0]) # (1, 1) test['ifAction'][0:10]=1 test['ifDocu'][0:10]=1 print(test[['ifAction','ifDocu']]) # [(1, 1) (1, 1) (1, 1) (1, 1) (1, 1) (1, 1) (1, 1) (1, 1) (1, 1) (1, 1)] For a deeper look under the hood, see this post by Robert Kern .
Python Numpy Structured Array (recarray) assigning values into slices
The following example shows what I want to do: >>> test rec.array([(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0)], dtype=[('ifAction', '|i1'), ('ifDocu', '|i1'), ('ifComedy', '|i1')]) >>> test[['ifAction', 'ifDocu']][0] (0, 0) >>> test[['ifAction', 'ifDocu']][0] = (1,1) >>> test[['ifAction', 'ifDocu']][0] (0, 0) So, I want to assign the values (1,1) to test[['ifAction', 'ifDocu']][0]. (Eventually, I want to do something like test[['ifAction', 'ifDocu']][0:10] = (1,1), assigning the same values for for 0:10. I have tried many ways but never succeeded. Is there any way to do this? Thank you, Joon
[ "When you say test['ifAction'] you get a view of the data.\nWhen you say test[['ifAction','ifDocu']] you are using fancy-indexing and thus get a copy of the data. The copy doesn't help you since modifying the copy leaves the original data unchanged.\nSo a way around this is to assign values to test['ifAction'] and test['ifDocu'] individually:\ntest['ifAction'][0]=1\ntest['ifDocu'][0]=1\n\nFor example:\nimport numpy as np\ntest=np.rec.array([(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),\n (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0)], \n dtype=[('ifAction', '|i1'), ('ifDocu', '|i1'), ('ifComedy', '|i1')])\n\nprint(test[['ifAction','ifDocu']])\n# [(0, 0) (0, 0) (0, 0) (0, 0) (0, 0) (0, 0) (0, 0) (0, 0) (0, 0) (0, 0)]\ntest['ifAction'][0]=1\ntest['ifDocu'][0]=1\n\nprint(test[['ifAction','ifDocu']][0])\n# (1, 1)\ntest['ifAction'][0:10]=1\ntest['ifDocu'][0:10]=1\n\nprint(test[['ifAction','ifDocu']])\n# [(1, 1) (1, 1) (1, 1) (1, 1) (1, 1) (1, 1) (1, 1) (1, 1) (1, 1) (1, 1)]\n\nFor a deeper look under the hood, see this post by Robert Kern .\n" ]
[ 5 ]
[]
[]
[ "numpy", "python", "recarray", "slice" ]
stackoverflow_0003058602_numpy_python_recarray_slice.txt
Q: Is there a way to accept '%' as part of input that works both in python 2.6 & 3.0? In 2.6, if I needed to accept input that allowed a percent sign (such as "foo % bar"), I used raw_input() which worked as expected. In 3.0, input() accomplishes that same (with raw_input() having left the building). As an exercise, I'm hoping that I can have a backward-compatible version that will work with both 2.6 and 3.0. When I use input() in 2.6 and enter "foo % bar", the following error is returned: File "<string>", line 1, in <module> NameError: name "foo" is not defined ...which is expected. Anyway to to accomplish acceptance of input containing a percent sign that works in both 2.6 and 3.0? Thx. A: You can use sys.version_info to detect which version of Python is running. import sys if sys.version_info[0] == 2: input = raw_input # Now you can use input() Alternatively, if you don't want to override Python 2.X's builtin input function, you can write import sys if sys.version_info[0] == 2: my_input = raw_input else: my_input = input # Now you can use my_input() Although, even in my first code sample, the original builtin input is always available as __builtins__.input. A: Although not an elegant (and rather ugly) solution, I would just do something like this: try: input = raw_input except: pass
Is there a way to accept '%' as part of input that works both in python 2.6 & 3.0?
In 2.6, if I needed to accept input that allowed a percent sign (such as "foo % bar"), I used raw_input() which worked as expected. In 3.0, input() accomplishes that same (with raw_input() having left the building). As an exercise, I'm hoping that I can have a backward-compatible version that will work with both 2.6 and 3.0. When I use input() in 2.6 and enter "foo % bar", the following error is returned: File "<string>", line 1, in <module> NameError: name "foo" is not defined ...which is expected. Anyway to to accomplish acceptance of input containing a percent sign that works in both 2.6 and 3.0? Thx.
[ "You can use sys.version_info to detect which version of Python is running.\nimport sys\nif sys.version_info[0] == 2:\n input = raw_input\n# Now you can use\ninput()\n\nAlternatively, if you don't want to override Python 2.X's builtin input function, you can write\nimport sys\nif sys.version_info[0] == 2:\n my_input = raw_input\nelse:\n my_input = input\n# Now you can use\nmy_input()\n\nAlthough, even in my first code sample, the original builtin input is always available as __builtins__.input.\n", "Although not an elegant (and rather ugly) solution, I would just do something like this:\ntry:\n input = raw_input\nexcept:\n pass\n\n" ]
[ 2, 2 ]
[]
[]
[ "python", "python_2.6" ]
stackoverflow_0003058649_python_python_2.6.txt
Q: represent binary search trees in python how do i represent binary search trees in python? A: class Node(object): def __init__(self, payload): self.payload = payload self.left = self.right = 0 # this concludes the "how to represent" asked in the question. Once you # represent a BST tree like this, you can of course add a variety of # methods to modify it, "walk" over it, and so forth, such as: def insert(self, othernode): "Insert Node `othernode` under Node `self`." if self.payload <= othernode.payload: if self.left: self.left.insert(othernode) else: self.left = othernode else: if self.right: self.right.insert(othernode) else: self.right = othernode def inorderwalk(self): "Yield this Node and all under it in increasing-payload order." if self.left: for x in self.left.inorderwalk(): yield x yield self if self.right: for x in self.right.inorderwalk(): yield x def sillywalk(self): "Tiny, silly subset of `inorderwalk` functionality as requested." if self.left: self.left.sillywalk() print(self.payload) if self.right: self.right.sillywalk() etc, etc -- basically like in any other language which uses references rather than pointers (such as Java, C#, etc). Edit: Of course, the very existence of sillywalk is silly indeed, because exactly the same functionality is a singe-liner external snippet on top of the walk method: for x in tree.walk(): print(x.payload) and with walk you can obtain just about any other functionality on the nodes-in-order stream, while, with sillywalk, you can obtain just about diddly-squat. But, hey, the OP says yield is "intimidating" (I wonder how many of Python 2.6's other 30 keywords deserve such scare words in the OP's judgment?-) so I'm hoping print isn't! This is all completely beyond the actual question, on representing BSTs: that question is entirely answered in the __init__ -- a payload attribute to hold the node's payload, left and right attribute to hold either None (meaning, this node has no descendants on that side) or a Node (the top of the sub-tree of descendants on the appropriate side). Of course, the BST constraint is that every left descendant of each node (if any) has a payload less or equal than that of the node in question, every right one (again, if any) has a greater payload -- I added insert just to show how trivial it is to maintain that constraint, walk (and now sillywalk) to show how trivial it is to get all nodes in increasing order of payloads. Again, the general idea is just identical to the way you'd represent a BST in any language which uses references rather than pointers, like, for example, C# and Java.
represent binary search trees in python
how do i represent binary search trees in python?
[ "class Node(object):\n\n def __init__(self, payload):\n self.payload = payload\n self.left = self.right = 0\n\n # this concludes the \"how to represent\" asked in the question. Once you\n # represent a BST tree like this, you can of course add a variety of\n # methods to modify it, \"walk\" over it, and so forth, such as:\n\n def insert(self, othernode):\n \"Insert Node `othernode` under Node `self`.\"\n if self.payload <= othernode.payload:\n if self.left: self.left.insert(othernode)\n else: self.left = othernode\n else:\n if self.right: self.right.insert(othernode)\n else: self.right = othernode\n\n def inorderwalk(self):\n \"Yield this Node and all under it in increasing-payload order.\"\n if self.left:\n for x in self.left.inorderwalk(): yield x\n yield self\n if self.right:\n for x in self.right.inorderwalk(): yield x\n\n def sillywalk(self):\n \"Tiny, silly subset of `inorderwalk` functionality as requested.\"\n if self.left:\n self.left.sillywalk()\n print(self.payload)\n if self.right:\n self.right.sillywalk()\n\netc, etc -- basically like in any other language which uses references rather than pointers (such as Java, C#, etc).\nEdit:\nOf course, the very existence of sillywalk is silly indeed, because exactly the same functionality is a singe-liner external snippet on top of the walk method:\nfor x in tree.walk(): print(x.payload)\n\nand with walk you can obtain just about any other functionality on the nodes-in-order stream, while, with sillywalk, you can obtain just about diddly-squat. But, hey, the OP says yield is \"intimidating\" (I wonder how many of Python 2.6's other 30 keywords deserve such scare words in the OP's judgment?-) so I'm hoping print isn't!\nThis is all completely beyond the actual question, on representing BSTs: that question is entirely answered in the __init__ -- a payload attribute to hold the node's payload, left and right attribute to hold either None (meaning, this node has no descendants on that side) or a Node (the top of the sub-tree of descendants on the appropriate side). Of course, the BST constraint is that every left descendant of each node (if any) has a payload less or equal than that of the node in question, every right one (again, if any) has a greater payload -- I added insert just to show how trivial it is to maintain that constraint, walk (and now sillywalk) to show how trivial it is to get all nodes in increasing order of payloads. Again, the general idea is just identical to the way you'd represent a BST in any language which uses references rather than pointers, like, for example, C# and Java.\n" ]
[ 12 ]
[]
[]
[ "binary_search_tree", "binary_tree", "data_structures", "python" ]
stackoverflow_0003058665_binary_search_tree_binary_tree_data_structures_python.txt
Q: How to manually create a DBRef using pymongo? I want to create a DBRef manually so that I can add an additional field to it. However, when I try to pass the following: {'$ref': 'projects', '$id': '1029412409721', 'project_name': 'My Project'} Pymongo raises an error: pymongo.errors.InvalidName: key '$id' must not start with '$' It would seem that pymongo reserve the $ for the special key, leading me to wonder if it is even possible to do what I'm trying to do? A: Probably don't want to be creating them manually like that, since keys in DBRefs need to be ordered. We could add an option to create a DBRef instance w/ custom kwargs though, which would solve your problem. If you file a jira for this we should be able to get it out in an upcoming release.
How to manually create a DBRef using pymongo?
I want to create a DBRef manually so that I can add an additional field to it. However, when I try to pass the following: {'$ref': 'projects', '$id': '1029412409721', 'project_name': 'My Project'} Pymongo raises an error: pymongo.errors.InvalidName: key '$id' must not start with '$' It would seem that pymongo reserve the $ for the special key, leading me to wonder if it is even possible to do what I'm trying to do?
[ "Probably don't want to be creating them manually like that, since keys in DBRefs need to be ordered. We could add an option to create a DBRef instance w/ custom kwargs though, which would solve your problem. If you file a jira for this we should be able to get it out in an upcoming release.\n" ]
[ 3 ]
[]
[]
[ "dbref", "mongodb", "pymongo", "python" ]
stackoverflow_0003056809_dbref_mongodb_pymongo_python.txt
Q: How to substitute into a regular expression group in Python >>> s = 'foo: "apples", bar: "oranges"' >>> pattern = 'foo: "(.*)"' I want to be able to substitute into the group like this: >>> re.sub(pattern, 'pears', s, group=1) 'foo: "pears", bar: "oranges"' Is there a nice way to do this? A: For me works something like: rx = re.compile(r'(foo: ")(.*?)(".*)') s_new = rx.sub(r'\g<1>pears\g<3>', s) print(s_new) Notice ?in re, so it ends with first ", also notice " in groups 1 and 3 because they must be in output. Instead of \g<1> (or \g<number>) you can use just \1, but remember to use "raw" strings and that g<1> form is preffered because \1 could be ambiguous (look for examples in Python doc) . A: re.sub(r'(?<=foo: ")[^"]+(?=")', 'pears', s) The regex matches a sequence of chars that Follows the string foo: ", doesn't contain double quotation marks and is followed by " (?<=) and (?=) are lookbehind and lookahead This regex will fail if the value of foo contains escaped quots. Use the following one to catch them too: re.sub(r'(?<=foo: ")(\\"|[^"])+(?=")', 'pears', s) Sample code >>> s = 'foo: "apples \\\"and\\\" more apples", bar: "oranges"' >>> print s foo: "apples \"and\" more apples", bar: "oranges" >>> print re.sub(r'(?<=foo: ")(\\"|[^"])+(?=")', 'pears', s) foo: "pears", bar: "oranges"
How to substitute into a regular expression group in Python
>>> s = 'foo: "apples", bar: "oranges"' >>> pattern = 'foo: "(.*)"' I want to be able to substitute into the group like this: >>> re.sub(pattern, 'pears', s, group=1) 'foo: "pears", bar: "oranges"' Is there a nice way to do this?
[ "For me works something like:\nrx = re.compile(r'(foo: \")(.*?)(\".*)')\ns_new = rx.sub(r'\\g<1>pears\\g<3>', s)\nprint(s_new)\n\nNotice ?in re, so it ends with first \", also notice \" in groups 1 and 3 because they must be in output.\nInstead of \\g<1> (or \\g<number>) you can use just \\1, but remember to use \"raw\" strings and that g<1> form is preffered because \\1 could be ambiguous (look for examples in Python doc) .\n", "re.sub(r'(?<=foo: \")[^\"]+(?=\")', 'pears', s)\n\nThe regex matches a sequence of chars that \n\nFollows the string foo: \",\ndoesn't contain double quotation marks and\nis followed by \"\n\n(?<=) and (?=) are lookbehind and lookahead\nThis regex will fail if the value of foo contains escaped quots. Use the following one to catch them too:\nre.sub(r'(?<=foo: \")(\\\\\"|[^\"])+(?=\")', 'pears', s)\n\nSample code\n>>> s = 'foo: \"apples \\\\\\\"and\\\\\\\" more apples\", bar: \"oranges\"'\n>>> print s\nfoo: \"apples \\\"and\\\" more apples\", bar: \"oranges\"\n>>> print re.sub(r'(?<=foo: \")(\\\\\"|[^\"])+(?=\")', 'pears', s)\nfoo: \"pears\", bar: \"oranges\"\n\n" ]
[ 10, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003059151_python_regex.txt
Q: python streaming TCP server with RPC I have written a little streaming mp3 server in python. So far all it does is accept a ServerSocket connection, and begin streaming all mp3 data in its queue to the request using socket.send(). I have implemented this to chunk in stream icy metadata, so the name of the playing song shows up in the client. I would like to add playlist management to the server, so that I can manipulate the playlist of the running server. I have a vague idea that xmlrpclib would be suited to doing this, but I'm confused about two things: Whether it's possible/advisable to integrate ICY and XMLRPC on a single server and a single port. How to share state between the stream thread and the playlist, and manipulation thereof via xmlrpc. A: Your initial attempt might be easier if you use two separate ports, each with its own server running in a separate thread. However, managing synchronization between the threads might be an annoying task in the long run. ICY and HTTP are very similar, and if you've already implemented ICY on top of SocketServer, you could probably extend BaseHTTPServer.BaseHTTPRequestHandler to respond to both ICY and HTTP requests on the same port. Take a look at the standard library code for the BaseHTTPRequestHandler.parse_request() method, and think about how to override it in a subclass for a split personality. Also, when you want to handle multiple concurrent requests using these classes, take a look at the SocketServer mixin classes.
python streaming TCP server with RPC
I have written a little streaming mp3 server in python. So far all it does is accept a ServerSocket connection, and begin streaming all mp3 data in its queue to the request using socket.send(). I have implemented this to chunk in stream icy metadata, so the name of the playing song shows up in the client. I would like to add playlist management to the server, so that I can manipulate the playlist of the running server. I have a vague idea that xmlrpclib would be suited to doing this, but I'm confused about two things: Whether it's possible/advisable to integrate ICY and XMLRPC on a single server and a single port. How to share state between the stream thread and the playlist, and manipulation thereof via xmlrpc.
[ "Your initial attempt might be easier if you use two separate ports, each with its own server running in a separate thread. However, managing synchronization between the threads might be an annoying task in the long run.\nICY and HTTP are very similar, and if you've already implemented ICY on top of SocketServer, you could probably extend BaseHTTPServer.BaseHTTPRequestHandler to respond to both ICY and HTTP requests on the same port. Take a look at the standard library code for the BaseHTTPRequestHandler.parse_request() method, and think about how to override it in a subclass for a split personality.\nAlso, when you want to handle multiple concurrent requests using these classes, take a look at the SocketServer mixin classes.\n" ]
[ 0 ]
[]
[]
[ "python", "sockets", "xml_rpc" ]
stackoverflow_0003059374_python_sockets_xml_rpc.txt
Q: Django Template Inheritance -- Missing Images? I have got the following file heirarchy: project   other stuff   templates       images           images for site       app1           templates for app1       registration           login template       base.html (base for entire site)       style.css (for base.html) In the login template, I am extending 'base.html.' 'base.html' uses 'style.css' along with all of the images in the 'templates/images' directory. For some reason, none of the CSS styles or images will show up in the login template, even though I'm extending it. Does this missing image issue have something to do with screwed up "media" settings somewhere? I never understood those, but this is a major roadblock in my proof-of-concept, so any help is appreciated. Thanks! A: I recommend not putting the styles and images there. For development, your MEDIA_ROOT may point to an arbitrary local directory on your machine containing the files, it need not even be below your django project's root folder (see http://docs.djangoproject.com/en/dev/ref/settings/#media-root). For production, you'll have to choose a different approach to serving static content anyway (http://docs.djangoproject.com/en/dev/howto/static-files/#the-big-fat-disclaimer).
Django Template Inheritance -- Missing Images?
I have got the following file heirarchy: project   other stuff   templates       images           images for site       app1           templates for app1       registration           login template       base.html (base for entire site)       style.css (for base.html) In the login template, I am extending 'base.html.' 'base.html' uses 'style.css' along with all of the images in the 'templates/images' directory. For some reason, none of the CSS styles or images will show up in the login template, even though I'm extending it. Does this missing image issue have something to do with screwed up "media" settings somewhere? I never understood those, but this is a major roadblock in my proof-of-concept, so any help is appreciated. Thanks!
[ "I recommend not putting the styles and images there. For development, your MEDIA_ROOT may point to an arbitrary local directory on your machine containing the files, it need not even be below your django project's root folder (see http://docs.djangoproject.com/en/dev/ref/settings/#media-root).\nFor production, you'll have to choose a different approach to serving static content anyway (http://docs.djangoproject.com/en/dev/howto/static-files/#the-big-fat-disclaimer).\n" ]
[ 3 ]
[]
[]
[ "django", "image", "inheritance", "python", "templates" ]
stackoverflow_0003059713_django_image_inheritance_python_templates.txt
Q: Python, Thread never exiting I'm developing a small media player in Python. A problem I have run into is that my thread which plays the .wav file never exits. I've provided the thread class, and how I handle the create of thread below. class myThread (threading.Thread): def __init__(self, threadID, wf): self.threadID = threadID self.wf = wf threading.Thread.__init__(self) def run(self): global isPaused global isStopped self.waveFile = wave.open(self.wf, 'rb') #initialize stream self.p = pyaudio.PyAudio() self.stream = self.p.open(format = self.p.get_format_from_width(self.waveFile.getsampwidth()), channels = self.waveFile.getnchannels(), rate = self.waveFile.getframerate(), output = True) self.data = self.waveFile.readframes(1024) isPaused = False isStopped = False #main play loop, with pause event checking while self.data != '': while isPaused != True: if isStopped == False: self.stream.write(self.data) self.data = self.waveFile.readframes(1024) elif isStopped == True: self.stream.close() self.p.terminate() self.stream.close() self.p.terminate() And I control the thread creation with: foo = wx.FileDialog(self, message="Open a .wav file...", defaultDir=os.getcwd(), defaultFile="", style=wx.FD_MULTIPLE) foo.ShowModal() self.queue = foo.GetPaths() self.threadID = 1 while len(self.queue) != 0: self.song = myThread(self.threadID, self.queue[0]) self.song.start() while self.song.isAlive(): time.sleep(2) self.queue.pop(0) self.threadID += 1 If you have any idea, I'd appreciate it. A: Is it this code in the thread that never exits? Or the main while loop? while self.data != '': while isPaused != True: if isStopped == False: self.stream.write(self.data) self.data = self.waveFile.readframes(1024) elif isStopped == True: self.stream.close() self.p.terminate() Just a thought - from what this looks like, surely the while loop will not exit if stopped, since self.data != '' because it has been set by the self.data = line. Just a thought. A: You need to ensure you set self.data to nothing if isStopped is True. while self.data != '': while isPaused != True: if isStopped == False: self.stream.write(self.data) self.data = self.waveFile.readframes(1024) elif isStopped == True: self.data = '' self.stream.close() self.p.terminate() self.stream.close() self.p.terminate()
Python, Thread never exiting
I'm developing a small media player in Python. A problem I have run into is that my thread which plays the .wav file never exits. I've provided the thread class, and how I handle the create of thread below. class myThread (threading.Thread): def __init__(self, threadID, wf): self.threadID = threadID self.wf = wf threading.Thread.__init__(self) def run(self): global isPaused global isStopped self.waveFile = wave.open(self.wf, 'rb') #initialize stream self.p = pyaudio.PyAudio() self.stream = self.p.open(format = self.p.get_format_from_width(self.waveFile.getsampwidth()), channels = self.waveFile.getnchannels(), rate = self.waveFile.getframerate(), output = True) self.data = self.waveFile.readframes(1024) isPaused = False isStopped = False #main play loop, with pause event checking while self.data != '': while isPaused != True: if isStopped == False: self.stream.write(self.data) self.data = self.waveFile.readframes(1024) elif isStopped == True: self.stream.close() self.p.terminate() self.stream.close() self.p.terminate() And I control the thread creation with: foo = wx.FileDialog(self, message="Open a .wav file...", defaultDir=os.getcwd(), defaultFile="", style=wx.FD_MULTIPLE) foo.ShowModal() self.queue = foo.GetPaths() self.threadID = 1 while len(self.queue) != 0: self.song = myThread(self.threadID, self.queue[0]) self.song.start() while self.song.isAlive(): time.sleep(2) self.queue.pop(0) self.threadID += 1 If you have any idea, I'd appreciate it.
[ "Is it this code in the thread that never exits? Or the main while loop?\nwhile self.data != '':\n while isPaused != True:\n if isStopped == False:\n self.stream.write(self.data)\n self.data = self.waveFile.readframes(1024)\n elif isStopped == True:\n self.stream.close()\n self.p.terminate()\n\nJust a thought - from what this looks like, surely the while loop will not exit if stopped, since self.data != '' because it has been set by the self.data = line. Just a thought.\n", "You need to ensure you set self.data to nothing if isStopped is True.\nwhile self.data != '':\n while isPaused != True:\n if isStopped == False:\n self.stream.write(self.data)\n self.data = self.waveFile.readframes(1024)\n elif isStopped == True:\n self.data = ''\n self.stream.close()\n self.p.terminate()\n\nself.stream.close()\nself.p.terminate()\n\n" ]
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003053397_python.txt
Q: Traditional SQL vs MongoDB/CouchDB for simple python app Say I got an traditional SQL structure like so: create table tags (id PRIMARY KEY int, tag varchar(100)); create table files (id PRIMARY KEY int, filename varchar(500)); create table tagged_files (tag_id int, file_id int); I add some tags: insert into table tags (tag) values ('places'); insert into table tags (tag) values ('locations'); And some files: insert into table files (filename) values ('/tmp/somefile'); insert into table files (filename) values ('/tmp/someotherfile'); and then tag these files: insert into table tagged_files (tag_id, file_id) values (1,1); insert into table tagged_files (tag_id, file_id) values (1,2); Then I can find all the files tagged with the first tag like so: select * from files, tagged_files where id = file_id and tag_id = 1 But how do I do the same thing using NoSQL solutions like MongoDB and CouchDB?? And what NoSQL project is best suited for something like this? A: For MongoDB. Chances are you'd simply save them with the tags as: db.Files.save({ "fn" : "/tmp/somefile", "ts" : [ { "t" : "places" }, { "t" : "locations" }] }); db.Files.save({ "fn" : "/tmp/someotherfile", "ts" : [ { "t" : "locations" }] }); Alternative is to save tags separately (ObjectId's are 12 bytes iirc): db.Tags.save({ "t" : "places" }); db.Tags.save({ "t" : "locations" }); db.Files.save({ "fn" : "/tmp/somefile", "t" : [ { "i" : ObjectId("IdOfPlaces") }, { "i" : ObjectId("IdOfLocations") }] }); In both cases to get a file it's db.Files.find({ "_id" : ObjectId("4c19e79e244f000000007e0d") }); db.Files.find({ "fn" : "/tmp/somefile" }); Or a couple files based on tags: db.Files.find({ ts : { t : "locations" } }) db.Files.find({ t : { i : ObjectId("4c19e79e244f000000007e0d") } }) Examples are from the mongo console. And if you store tags with Id's you'd obviously have to read the tags up based on the Id's once you got the file(s).
Traditional SQL vs MongoDB/CouchDB for simple python app
Say I got an traditional SQL structure like so: create table tags (id PRIMARY KEY int, tag varchar(100)); create table files (id PRIMARY KEY int, filename varchar(500)); create table tagged_files (tag_id int, file_id int); I add some tags: insert into table tags (tag) values ('places'); insert into table tags (tag) values ('locations'); And some files: insert into table files (filename) values ('/tmp/somefile'); insert into table files (filename) values ('/tmp/someotherfile'); and then tag these files: insert into table tagged_files (tag_id, file_id) values (1,1); insert into table tagged_files (tag_id, file_id) values (1,2); Then I can find all the files tagged with the first tag like so: select * from files, tagged_files where id = file_id and tag_id = 1 But how do I do the same thing using NoSQL solutions like MongoDB and CouchDB?? And what NoSQL project is best suited for something like this?
[ "For MongoDB.\nChances are you'd simply save them with the tags as:\ndb.Files.save({ \"fn\" : \"/tmp/somefile\", \"ts\" : [ { \"t\" : \"places\" }, { \"t\" : \"locations\" }] });\ndb.Files.save({ \"fn\" : \"/tmp/someotherfile\", \"ts\" : [ { \"t\" : \"locations\" }] });\n\nAlternative is to save tags separately (ObjectId's are 12 bytes iirc):\ndb.Tags.save({ \"t\" : \"places\" });\ndb.Tags.save({ \"t\" : \"locations\" });\ndb.Files.save({ \"fn\" : \"/tmp/somefile\", \"t\" : [ { \"i\" : ObjectId(\"IdOfPlaces\") }, { \"i\" : ObjectId(\"IdOfLocations\") }] });\n\nIn both cases to get a file it's\ndb.Files.find({ \"_id\" : ObjectId(\"4c19e79e244f000000007e0d\") });\ndb.Files.find({ \"fn\" : \"/tmp/somefile\" });\n\nOr a couple files based on tags:\ndb.Files.find({ ts : { t : \"locations\" } })\ndb.Files.find({ t : { i : ObjectId(\"4c19e79e244f000000007e0d\") } })\n\nExamples are from the mongo console. And if you store tags with Id's you'd obviously have to read the tags up based on the Id's once you got the file(s).\n" ]
[ 1 ]
[]
[]
[ "couchdb", "mongodb", "python", "sql" ]
stackoverflow_0003060189_couchdb_mongodb_python_sql.txt
Q: asynchronous writing and reading of a file I have two processes. One processes is redirecting output of some unix command to a file on server side.The data is always appended to the file. e.g. find / > tmp.txt Another process is opening and reading the same file and storing it in a string and sending the entire string to the client. Now, this things take simultaneously. I am using python. Any suggestion as in what can be possible ways to implement this scenario. Please explain with sample code. Thanks in advance. Tazim. A: If what you want is having the Output of a Unix command in a file and displaying it at the same time, you can [tee][1] it to stdout and read it from there, like: >>> command_line = '/bin/find / |tee tmp.txt' >>> args = shlex.split(command_line) >>> p = subprocess.Popen(args,stdout=subprocess.PIPE) From there you can either use commuicate() or directly read the stdout from the POpen object. See how it can be used here.
asynchronous writing and reading of a file
I have two processes. One processes is redirecting output of some unix command to a file on server side.The data is always appended to the file. e.g. find / > tmp.txt Another process is opening and reading the same file and storing it in a string and sending the entire string to the client. Now, this things take simultaneously. I am using python. Any suggestion as in what can be possible ways to implement this scenario. Please explain with sample code. Thanks in advance. Tazim.
[ "If what you want is having the Output of a Unix command in a file and displaying it at the same time, you can [tee][1] it to stdout and read it from there, like:\n>>> command_line = '/bin/find / |tee tmp.txt'\n>>> args = shlex.split(command_line)\n>>> p = subprocess.Popen(args,stdout=subprocess.PIPE)\n\nFrom there you can either use commuicate() or directly read the stdout from the POpen object. See how it can be used here.\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003058899_django_python.txt
Q: Adding contextual information to your logging output in Python 2.5 I am using Python 2.5. The Python logging module allows adding contextual information to your logging output. Is something similar possible in Python 2.5? A: You can simply rip off the source code of LoggerAdapter from Python 2.6 and plug it in your own source code to get the exact same functionality. This is how others do it.
Adding contextual information to your logging output in Python 2.5
I am using Python 2.5. The Python logging module allows adding contextual information to your logging output. Is something similar possible in Python 2.5?
[ "You can simply rip off the source code of LoggerAdapter from Python 2.6 and plug it in your own source code to get the exact same functionality. This is how others do it.\n" ]
[ 2 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0003060242_logging_python.txt
Q: logger chain in python I'm writing python package/module and would like the logging messages mention what module/class/function they come from. I.e. if I run this code: import mymodule.utils.worker as worker w = worker.Worker() w.run() I'd like to logging messages looks like this: 2010-06-07 15:15:29 INFO mymodule.utils.worker.Worker.run <pid/threadid>: Hello from worker How can I accomplish this? Thanks. A: I tend to use the logging module in my packages/modules like so: import logging log = logging.getLogger(__name__) log.info("Whatever your info message.") This sets the name of your logger to the name of the module for inclusion in the log message. You can control where the name is by where %(name)s is found in the format string. Similarly you can place the pid with %(process)d and the thread id with %(thread)d. See the docs for all the options. Formatting example: import logging logging.basicConfig(format="%(asctime)s %(levelname)s %(name)s %(process)d/%(threadName)s: %(message)s") logging.getLogger('this.is.the.module').warning('Testing for SO') Gives me: 2010-06-07 08:43:10,494 WARNING this.is.the.module 14980/MainThread: Testing for SO A: Here is my solution that came out of this discussion. Thanks to everyone for suggestions. Usage: >>> import logging >>> logging.basicConfig(level=logging.DEBUG) >>> from hierlogger import hierlogger as logger >>> def main(): ... logger().debug("test") ... >>> main() DEBUG:main:test By default it will name logger as ... You can also control the depth by providing parameter: 3 - module.class.method default 2 - module.class 1 - module only Logger instances are also cached to prevent calculating logger name on each call. I hope someone will enjoy it. The code: import logging import inspect class NullHandler(logging.Handler): def emit(self, record): pass def hierlogger(level=3): callerFrame = inspect.stack()[1] caller = callerFrame[0] lname = '__heirlogger'+str(level)+'__' if lname not in caller.f_locals: loggerName = str() if level >= 1: try: loggerName += inspect.getmodule(inspect.stack()[1][0]).__name__ except: pass if 'self' in caller.f_locals and (level >= 2): loggerName += ('.' if len(loggerName) > 0 else '') + caller.f_locals['self'].__class__.__name__ if callerFrame[3] != '' and level >= 3: loggerName += ('.' if len(loggerName) > 0 else '') + callerFrame[3] caller.f_locals[lname] = logging.getLogger(loggerName) caller.f_locals[lname].addHandler(NullHandler()) return caller.f_locals[lname]
logger chain in python
I'm writing python package/module and would like the logging messages mention what module/class/function they come from. I.e. if I run this code: import mymodule.utils.worker as worker w = worker.Worker() w.run() I'd like to logging messages looks like this: 2010-06-07 15:15:29 INFO mymodule.utils.worker.Worker.run <pid/threadid>: Hello from worker How can I accomplish this? Thanks.
[ "I tend to use the logging module in my packages/modules like so:\nimport logging\nlog = logging.getLogger(__name__)\nlog.info(\"Whatever your info message.\")\n\nThis sets the name of your logger to the name of the module for inclusion in the log message. You can control where the name is by where %(name)s is found in the format string. Similarly you can place the pid with %(process)d and the thread id with %(thread)d. See the docs for all the options.\nFormatting example:\nimport logging\nlogging.basicConfig(format=\"%(asctime)s %(levelname)s %(name)s %(process)d/%(threadName)s: %(message)s\")\nlogging.getLogger('this.is.the.module').warning('Testing for SO')\n\nGives me:\n2010-06-07 08:43:10,494 WARNING this.is.the.module 14980/MainThread: Testing for SO\n\n", "Here is my solution that came out of this discussion. Thanks to everyone for suggestions.\nUsage:\n\n>>> import logging\n>>> logging.basicConfig(level=logging.DEBUG)\n>>> from hierlogger import hierlogger as logger\n>>> def main():\n... logger().debug(\"test\")\n...\n>>> main()\nDEBUG:main:test\n\nBy default it will name logger as ... You can also control the depth by providing parameter:\n3 - module.class.method default\n2 - module.class\n1 - module only\nLogger instances are also cached to prevent calculating logger name on each call.\nI hope someone will enjoy it.\nThe code:\n\nimport logging\nimport inspect\n\nclass NullHandler(logging.Handler):\n def emit(self, record): pass\n\ndef hierlogger(level=3):\n callerFrame = inspect.stack()[1]\n caller = callerFrame[0]\n lname = '__heirlogger'+str(level)+'__'\n if lname not in caller.f_locals:\n loggerName = str()\n if level >= 1:\n try:\n loggerName += inspect.getmodule(inspect.stack()[1][0]).__name__\n except: pass\n if 'self' in caller.f_locals and (level >= 2):\n loggerName += ('.' if len(loggerName) > 0 else '') + \n caller.f_locals['self'].__class__.__name__\n if callerFrame[3] != '' and level >= 3:\n loggerName += ('.' if len(loggerName) > 0 else '') + callerFrame[3]\n caller.f_locals[lname] = logging.getLogger(loggerName)\n caller.f_locals[lname].addHandler(NullHandler())\n return caller.f_locals[lname]\n\n" ]
[ 8, 2 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0002989398_logging_python.txt
Q: Python - add a column to an existing tab separated file I wish to add a column of data to a file. The file currently has three tab delimited columns. abbd 1234 0.987 affr 2345 0.465 I have a list of length 8,800 comprising floats. li = [-1.0099876, 34.87659] I wish to add this list as a fourth column to the file. abbd 1234 0.987 -1.0099876 Note - my file is open in r+ mode. Thanks, S :-) A: import fileinput for fl, line in zip(li, fileinput.input(['a.txt'], inplace=True)): print(line.strip() + '\t' + str(fl)) A: I'm with MattH, in-place operations are usually a bad idea. The alternative approach could be: import itertools def add_column(lines, values, column_delimiter="\t"): for line, value in itertools.izip(lines, values): yield line.rstrip() + column_delimiter + str(value) li = [-1.0099876, 34.87659] for line in add_column(open("a.txt"), li): print line
Python - add a column to an existing tab separated file
I wish to add a column of data to a file. The file currently has three tab delimited columns. abbd 1234 0.987 affr 2345 0.465 I have a list of length 8,800 comprising floats. li = [-1.0099876, 34.87659] I wish to add this list as a fourth column to the file. abbd 1234 0.987 -1.0099876 Note - my file is open in r+ mode. Thanks, S :-)
[ "import fileinput\n\nfor fl, line in zip(li, fileinput.input(['a.txt'], inplace=True)):\n print(line.strip() + '\\t' + str(fl))\n\n", "I'm with MattH, in-place operations are usually a bad idea. The alternative approach could be:\nimport itertools\n\ndef add_column(lines, values, column_delimiter=\"\\t\"):\n for line, value in itertools.izip(lines, values):\n yield line.rstrip() + column_delimiter + str(value)\n\nli = [-1.0099876, 34.87659] \nfor line in add_column(open(\"a.txt\"), li):\n print line\n\n" ]
[ 3, 1 ]
[]
[]
[ "append", "file", "python" ]
stackoverflow_0003060367_append_file_python.txt
Q: Where to get consumer secret required by buzz-python-client? I am using buzz-python-client and there is the following line in the examples: client.build_oauth_consumer('your-app.appspot.com', 'consumer_secret') Where can I get a 'consumer_secret'? A: as docs explain: secret (string) - Your consumer secret. This is issued to you by Google. Official guide to registration with Google.
Where to get consumer secret required by buzz-python-client?
I am using buzz-python-client and there is the following line in the examples: client.build_oauth_consumer('your-app.appspot.com', 'consumer_secret') Where can I get a 'consumer_secret'?
[ "as docs explain:\n\nsecret (string) - Your consumer secret. This is issued to you by Google.\n\nOfficial guide to registration with Google.\n" ]
[ 6 ]
[]
[]
[ "google_buzz", "python" ]
stackoverflow_0003061188_google_buzz_python.txt
Q: Massage with BeautifulSoup or clean with Regex Could someone tell me whats a better way to clean up bad HTML so BeautifulSoup can handle it - should one use the massage methods of BeautifulSoup or clean it up using regular expressions? A: Thought I should reword my answer. The built-in massages are good for light damage (extra whitespace, no closing slashes, etc). I would certainly try and get away with these before getting any more involved. You can pass in your own massages and I would suggest you extend the default set: import copy, re myMassage = [(re.compile('<!-([^-])'), lambda match: '<!--' + match.group(1))] myNewMassage = copy.copy(BeautifulSoup.MARKUP_MASSAGE) myNewMassage.extend(myMassage) BeautifulSoup(badString, markupMassage=myNewMassage) # Foo<!--This comment is malformed.-->Bar<br />Baz You're probably better off doing it this way as it all goes into one parsing pot, gaining BeautifulSoups optimisations... Although the runtime performance is probably pretty similar. A: From the documentation, massage methods are just pairs of (regular expression, replacement function) so I don't think it's really a case of use massaging or regexps. e.g. to tidy up malformed comments: (re.compile('<!-([^-])'), lambda match: '<!--' + match.group(1)) If you look at the source of the _feed method in BeautifulSoup.py you will see that these are just run in sequence against the markup: for fix, m in self.markupMassage: markup = fix.sub(m, markup) So whilst you could do some regexp processing of your own before BeautifulSoup gets to see the markup you are probably better combining any additional tidying needed with the default builtin MARKUP_MASSAGE as shown in Oli's answer.
Massage with BeautifulSoup or clean with Regex
Could someone tell me whats a better way to clean up bad HTML so BeautifulSoup can handle it - should one use the massage methods of BeautifulSoup or clean it up using regular expressions?
[ "Thought I should reword my answer.\nThe built-in massages are good for light damage (extra whitespace, no closing slashes, etc). I would certainly try and get away with these before getting any more involved.\nYou can pass in your own massages and I would suggest you extend the default set:\nimport copy, re\n\nmyMassage = [(re.compile('<!-([^-])'), lambda match: '<!--' + match.group(1))]\nmyNewMassage = copy.copy(BeautifulSoup.MARKUP_MASSAGE)\nmyNewMassage.extend(myMassage)\n\nBeautifulSoup(badString, markupMassage=myNewMassage)\n# Foo<!--This comment is malformed.-->Bar<br />Baz\n\nYou're probably better off doing it this way as it all goes into one parsing pot, gaining BeautifulSoups optimisations... Although the runtime performance is probably pretty similar.\n", "From the documentation, massage methods are just pairs of (regular expression, replacement function) so I don't think it's really a case of use massaging or regexps.\ne.g. to tidy up malformed comments:\n(re.compile('<!-([^-])'), lambda match: '<!--' + match.group(1))\n\nIf you look at the source of the _feed method in BeautifulSoup.py you will see that these are just run in sequence against the markup:\nfor fix, m in self.markupMassage:\n markup = fix.sub(m, markup)\n\nSo whilst you could do some regexp processing of your own before BeautifulSoup gets to see the markup you are probably better combining any additional tidying needed with the default builtin MARKUP_MASSAGE as shown in Oli's answer.\n" ]
[ 3, 2 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0003061245_beautifulsoup_python.txt
Q: Named pipe is using 100% CPU I'm starting the script with ./file.py < pipe >> logfile and the script is: while True: try: I = raw_input().strip().split() except EOFError: continue doSomething() How could I better handle named pipe? This script always run at 100% CPU and it need to be real-time so I cannot use time.sleep. A: At EOF you will loop forever getting yet another EOF. No more input will be done after EOF. EOF does not mean a "gap" in the data. It means the named socket was disconnected and can no longer be used. If you want "real-time" data, you have to read individual bytes from the socket until you get a complete "message". Perhaps a message ends with a '\n'. You can't use raw_input. You have to use sys.stdin.read(1) to get bytes. Pipes, BTW, are buffered. So you won't get real-time anything. If you want "real-time" you have to use UDP sockets, not TCP pipes. A: "Real-time" (since it's obviously "soft" real-time given you have multiple processes going, not "hard" real-time!) does not mean "you cannot use time.sleep": even a tiny amount of sleep will make things a little bit better -- try adding a time.sleep(0.01) in your loop, just to give other processes a better chance to run. The lack of sleep may actually be making you take a longer time by giving other processes very little chance to fill the pipe! Beyond this, @S.Lott has it just right: for "real-timeoid" behavior, you have to read from sys.stdin (though it probably need not be a byte at a time, depending on the platform: typically sys.stdin.read(1024) will read up to 1024 bytes, when sys.stdin is a pipe or other "raw" as opposed to "cooked" FD, returning however many bytes are in the pipe, if <100, rather than waiting -- you can set the FD to non-blocking to help assure that) directly, and perform string manipulation (e.g. to put lines together, strip them, etc) later in your code.
Named pipe is using 100% CPU
I'm starting the script with ./file.py < pipe >> logfile and the script is: while True: try: I = raw_input().strip().split() except EOFError: continue doSomething() How could I better handle named pipe? This script always run at 100% CPU and it need to be real-time so I cannot use time.sleep.
[ "At EOF you will loop forever getting yet another EOF. No more input will be done after EOF.\nEOF does not mean a \"gap\" in the data. It means the named socket was disconnected and can no longer be used.\nIf you want \"real-time\" data, you have to read individual bytes from the socket until you get a complete \"message\". Perhaps a message ends with a '\\n'. You can't use raw_input.\nYou have to use sys.stdin.read(1) to get bytes.\nPipes, BTW, are buffered. So you won't get real-time anything. If you want \"real-time\" you have to use UDP sockets, not TCP pipes.\n", "\"Real-time\" (since it's obviously \"soft\" real-time given you have multiple processes going, not \"hard\" real-time!) does not mean \"you cannot use time.sleep\": even a tiny amount of sleep will make things a little bit better -- try adding a time.sleep(0.01) in your loop, just to give other processes a better chance to run. The lack of sleep may actually be making you take a longer time by giving other processes very little chance to fill the pipe!\nBeyond this, @S.Lott has it just right: for \"real-timeoid\" behavior, you have to read from sys.stdin (though it probably need not be a byte at a time, depending on the platform: typically sys.stdin.read(1024) will read up to 1024 bytes, when sys.stdin is a pipe or other \"raw\" as opposed to \"cooked\" FD, returning however many bytes are in the pipe, if <100, rather than waiting -- you can set the FD to non-blocking to help assure that) directly, and perform string manipulation (e.g. to put lines together, strip them, etc) later in your code.\n" ]
[ 2, 2 ]
[]
[]
[ "python", "unix" ]
stackoverflow_0003062134_python_unix.txt
Q: How to set Content-Type automatically when i download the data that i uploaded. This is my code : import os from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext import db #from login import htmlPrefix,get_current_user class MyModel(db.Model): blob = db.BlobProperty() class BaseRequestHandler(webapp.RequestHandler): def render_template(self, filename, template_args=None): if not template_args: template_args = {} path = os.path.join(os.path.dirname(__file__), 'templates', filename) self.response.out.write(template.render(path, template_args)) class upload(BaseRequestHandler): def get(self): self.render_template('index.html',) def post(self): file=self.request.get('file') obj = MyModel() obj.blob = db.Blob(file.encode('utf8')) obj.put() self.response.out.write('upload ok') class download(BaseRequestHandler): def get(self): #id=self.request.get('id') o = MyModel.all().get() #self.response.out.write(''.join('%s: %s <br/>' % (a, getattr(o, a)) for a in dir(o))) self.response.out.write(o) application = webapp.WSGIApplication( [ ('/?', upload), ('/download',download), ], debug=True ) def main(): run_wsgi_app(application) if __name__ == "__main__": main() My index.html is : <form action="/" method="post"> <input type="file" name="file" /> <input type="submit" /> </form> And it show : <__main__.MyModel object at 0x02506830> But I don't want to see this, I want to download it. How to change my code to run? Thanks updated It is ok now : class upload(BaseRequestHandler): def get(self): self.render_template('index.html',) def post(self): file=self.request.get('file') obj = MyModel() obj.blob = db.Blob(file) obj.put() self.response.out.write('upload ok') class download(BaseRequestHandler): def get(self): #id=self.request.get('id') o = MyModel.all().order('-').get() #self.response.out.write(''.join('%s: %s <br/>' % (a, getattr(o, a)) for a in dir(o))) self.response.headers['Content-Type'] = "image/png" self.response.out.write(o.blob) And new question is : if you upload a 'png' file, it will show successful, but when I upload a rar file I will run error. So how to set Content-Type automatically and what is the Content-Type of the 'rar' file? Thanks A: See Nick's blog for a working example. Basically on upload you need to pull the file from self.request.POST instead of get in order to get the more useful cgi.FieldStorage object. You can then read the mime type from file.type, save the type string to your entity along with the blob, and write it out with the response headers on download. Another option is to save file.name to your entity on upload, and then plug it into mimetypes.guess_type() to guess a type based on the file extension upon download. A: What kind of data is stored in your blob? Is it an image? Because you would need to convert it to an image before writing it back in the response. What you're doing now is writing the object straight to the response, which results in it printing a string with the object's address and type. [edit] The correct content type for RAR files would be application/x-rar-compressed. And I don't think you can automatically determine the content type from a blob. You would have to manually set the correct content type for each file type you want users to be able to download.
How to set Content-Type automatically when i download the data that i uploaded.
This is my code : import os from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext import db #from login import htmlPrefix,get_current_user class MyModel(db.Model): blob = db.BlobProperty() class BaseRequestHandler(webapp.RequestHandler): def render_template(self, filename, template_args=None): if not template_args: template_args = {} path = os.path.join(os.path.dirname(__file__), 'templates', filename) self.response.out.write(template.render(path, template_args)) class upload(BaseRequestHandler): def get(self): self.render_template('index.html',) def post(self): file=self.request.get('file') obj = MyModel() obj.blob = db.Blob(file.encode('utf8')) obj.put() self.response.out.write('upload ok') class download(BaseRequestHandler): def get(self): #id=self.request.get('id') o = MyModel.all().get() #self.response.out.write(''.join('%s: %s <br/>' % (a, getattr(o, a)) for a in dir(o))) self.response.out.write(o) application = webapp.WSGIApplication( [ ('/?', upload), ('/download',download), ], debug=True ) def main(): run_wsgi_app(application) if __name__ == "__main__": main() My index.html is : <form action="/" method="post"> <input type="file" name="file" /> <input type="submit" /> </form> And it show : <__main__.MyModel object at 0x02506830> But I don't want to see this, I want to download it. How to change my code to run? Thanks updated It is ok now : class upload(BaseRequestHandler): def get(self): self.render_template('index.html',) def post(self): file=self.request.get('file') obj = MyModel() obj.blob = db.Blob(file) obj.put() self.response.out.write('upload ok') class download(BaseRequestHandler): def get(self): #id=self.request.get('id') o = MyModel.all().order('-').get() #self.response.out.write(''.join('%s: %s <br/>' % (a, getattr(o, a)) for a in dir(o))) self.response.headers['Content-Type'] = "image/png" self.response.out.write(o.blob) And new question is : if you upload a 'png' file, it will show successful, but when I upload a rar file I will run error. So how to set Content-Type automatically and what is the Content-Type of the 'rar' file? Thanks
[ "See Nick's blog for a working example.\nBasically on upload you need to pull the file from self.request.POST instead of get in order to get the more useful cgi.FieldStorage object. You can then read the mime type from file.type, save the type string to your entity along with the blob, and write it out with the response headers on download.\nAnother option is to save file.name to your entity on upload, and then plug it into mimetypes.guess_type() to guess a type based on the file extension upon download.\n", "What kind of data is stored in your blob? Is it an image? Because you would need to convert it to an image before writing it back in the response. \nWhat you're doing now is writing the object straight to the response, which results in it printing a string with the object's address and type.\n[edit] The correct content type for RAR files would be application/x-rar-compressed. And I don't think you can automatically determine the content type from a blob. You would have to manually set the correct content type for each file type you want users to be able to download.\n" ]
[ 1, 0 ]
[]
[]
[ "content_type", "download", "google_app_engine", "python", "upload" ]
stackoverflow_0003059684_content_type_download_google_app_engine_python_upload.txt
Q: How to get the level of the logging record in a custom logging.Handler in Python? I would like to make custom logger methods either by a custom logging handlers or a custom logger class and dispatch the logging records to different targets. For example: log = logging.getLogger('application') log.progress('time remaining %d sec' % i) custom method for logging to: - database status filed - console custom handler showing changes in a single console line log.data(kindOfObject) custom method for logging to: - database - special data format log.info log.debug log.error log.critical all standard logging methods: - database status/error/debug filed - console: append text line - logfile If I use a custom LoggerHandler by overriding the emit method, I can not distinguishe the level of the logging record. Is there any other posibility to get in runtime information of the record level? class ApplicationLoggerHandler(logging.Handler): def emit(self, record): # at this place I need to know the level of the record (info, error, debug, critical)? Any suggestions? A: record is an instance of LogRecord: >>> import logging >>> rec = logging.LogRecord('bob', 1, 'foo', 23, 'ciao', (), False) and your method can just access the attributes of interest (I'm splitting dir's result for ease of reading): >>> dir(rec) ['__doc__', '__init__', '__module__', '__str__', 'args', 'created', 'exc_info', 'exc_text', 'filename', 'funcName', 'getMessage', 'levelname', 'levelno', 'lineno', 'module', 'msecs', 'msg', 'name', 'pathname', 'process', 'processName', 'relativeCreated', 'thread', 'threadName'] >>> rec.levelno 1 >>> rec.levelname 'Level 1' and so on. (rec.getMessage() is the one method you use on rec -- it formats the message into a string, interpolating the arguments).
How to get the level of the logging record in a custom logging.Handler in Python?
I would like to make custom logger methods either by a custom logging handlers or a custom logger class and dispatch the logging records to different targets. For example: log = logging.getLogger('application') log.progress('time remaining %d sec' % i) custom method for logging to: - database status filed - console custom handler showing changes in a single console line log.data(kindOfObject) custom method for logging to: - database - special data format log.info log.debug log.error log.critical all standard logging methods: - database status/error/debug filed - console: append text line - logfile If I use a custom LoggerHandler by overriding the emit method, I can not distinguishe the level of the logging record. Is there any other posibility to get in runtime information of the record level? class ApplicationLoggerHandler(logging.Handler): def emit(self, record): # at this place I need to know the level of the record (info, error, debug, critical)? Any suggestions?
[ "record is an instance of LogRecord:\n>>> import logging\n>>> rec = logging.LogRecord('bob', 1, 'foo', 23, 'ciao', (), False)\n\nand your method can just access the attributes of interest (I'm splitting dir's result for ease of reading):\n>>> dir(rec)\n['__doc__', '__init__', '__module__', '__str__', 'args', 'created',\n 'exc_info', 'exc_text', 'filename', 'funcName', 'getMessage', 'levelname',\n 'levelno', 'lineno', 'module', 'msecs', 'msg', 'name', 'pathname', 'process',\n 'processName', 'relativeCreated', 'thread', 'threadName']\n>>> rec.levelno\n1\n>>> rec.levelname\n'Level 1'\n\nand so on. (rec.getMessage() is the one method you use on rec -- it formats the message into a string, interpolating the arguments).\n" ]
[ 12 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0003061924_logging_python.txt
Q: LDAP query using Python: always no result I am trying to use python to query LDAP server, and it always returns me no result. and anyone help me find what wrong with my python code? it runs fine without excpetions, and it always has no result. i played around with the filter like "cn=partofmyname" but just no luck. thanks for help import ldap try: l = ldap.open("server") l.protocol_version = ldap.VERSION3 l.set_option(ldap.OPT_REFERRALS, 0) output =l.simple_bind("cn=username,cn=Users,dc=domian, dc=net",'password$R') print output except ldap.LDAPError, e: print e baseDN = "DC=domain,DC=net" searchScope = ldap.SCOPE_SUBTREE ## retrieve all attributes - again adjust to your needs - see documentation for more options retrieveAttributes = None Filter = "(&(objectClass=user)(sAMAccountName=myaccount))" try: ldap_result_id = l.search(baseDN, searchScope, Filter, retrieveAttributes) print ldap_result_id result_set = [] while 1: result_type, result_data = l.result(ldap_result_id, 0) if len(result_data) == 0: print 'no reslut' break else: for i in range(len(result_set)): for entry in result_set[i]: try: name = entry[1]['cn'][0] email = entry[1]['mail'][0] phone = entry[1]['telephonenumber'][0] desc = entry[1]['description'][0] count = count + 1 print "%d.\nName: %s\nDescription: %s\nE-mail: %s\nPhone: %s\n" %\ (count, name, desc, email, phone) except: pass ## here you don't have to append to a list ## you could do whatever you want with the individual entry #if result_type == ldap.RES_SEARCH_ENTRY: # result_set.append(result_data) # print result_set except ldap.LDAPError, e: print e l.unbind() A: i found my problem. simple_bind("cn=username,cn=Users,dc=domian, dc=net",'password$R') should be simple_bind("domain/username",'password$R') A: I would highly recommend that you examine the network traffic using Wireshark (www.wireshark.org) to see what's happening at the protocol level. Also, get a tool such as Softerra LDAP browser 2.6 (the free version at http://www.ldapbrowser.com/download.htm) to check the A/D server and directory organization. If you still have problems, post a summary of what you find using these tools.
LDAP query using Python: always no result
I am trying to use python to query LDAP server, and it always returns me no result. and anyone help me find what wrong with my python code? it runs fine without excpetions, and it always has no result. i played around with the filter like "cn=partofmyname" but just no luck. thanks for help import ldap try: l = ldap.open("server") l.protocol_version = ldap.VERSION3 l.set_option(ldap.OPT_REFERRALS, 0) output =l.simple_bind("cn=username,cn=Users,dc=domian, dc=net",'password$R') print output except ldap.LDAPError, e: print e baseDN = "DC=domain,DC=net" searchScope = ldap.SCOPE_SUBTREE ## retrieve all attributes - again adjust to your needs - see documentation for more options retrieveAttributes = None Filter = "(&(objectClass=user)(sAMAccountName=myaccount))" try: ldap_result_id = l.search(baseDN, searchScope, Filter, retrieveAttributes) print ldap_result_id result_set = [] while 1: result_type, result_data = l.result(ldap_result_id, 0) if len(result_data) == 0: print 'no reslut' break else: for i in range(len(result_set)): for entry in result_set[i]: try: name = entry[1]['cn'][0] email = entry[1]['mail'][0] phone = entry[1]['telephonenumber'][0] desc = entry[1]['description'][0] count = count + 1 print "%d.\nName: %s\nDescription: %s\nE-mail: %s\nPhone: %s\n" %\ (count, name, desc, email, phone) except: pass ## here you don't have to append to a list ## you could do whatever you want with the individual entry #if result_type == ldap.RES_SEARCH_ENTRY: # result_set.append(result_data) # print result_set except ldap.LDAPError, e: print e l.unbind()
[ "i found my problem.\nsimple_bind(\"cn=username,cn=Users,dc=domian, dc=net\",'password$R')\n\nshould be \n simple_bind(\"domain/username\",'password$R')\n\n", "I would highly recommend that you examine the network traffic using Wireshark (www.wireshark.org) to see what's happening at the protocol level. Also, get a tool such as Softerra LDAP browser 2.6 (the free version at http://www.ldapbrowser.com/download.htm) to check the A/D server and directory organization.\nIf you still have problems, post a summary of what you find using these tools.\n" ]
[ 2, 0 ]
[]
[]
[ "apache", "django", "ldap", "python" ]
stackoverflow_0003057039_apache_django_ldap_python.txt
Q: Python: Dennis Nedry - Security Has anyone seen Jurrassic Park where Dennis Nedry has protected the system with an animation that says 'You didn't say the magic word' where after the system goes down. Is it possible to do something similar ikn Python ? To describe it less humoristic: A response screen which waits for a condition fulfilled by the user. And encrypts and locks the system after a certain time. Is that possible on a linux system by the use of Python ? A: Yes, it is possible. A: In which I attempt to answer the implied question, "And if so, how?" I think this is really a Linux administration question. You'd have to figure out how to suspend a user's account on the system you're using and then log the current user out. It's likely going to involve the Python script running as a user with privileges greater than the user you're locking out. You don't really want to encrypt, do you? Just prevent access. Once you know how to accomplish all those things (suspend account / deny login, log out user, run script as privileged user, etc.,) it's easy to perform those tasks from a Python script.
Python: Dennis Nedry - Security
Has anyone seen Jurrassic Park where Dennis Nedry has protected the system with an animation that says 'You didn't say the magic word' where after the system goes down. Is it possible to do something similar ikn Python ? To describe it less humoristic: A response screen which waits for a condition fulfilled by the user. And encrypts and locks the system after a certain time. Is that possible on a linux system by the use of Python ?
[ "Yes, it is possible.\n", "In which I attempt to answer the implied question, \"And if so, how?\"\nI think this is really a Linux administration question. You'd have to figure out how to suspend a user's account on the system you're using and then log the current user out. It's likely going to involve the Python script running as a user with privileges greater than the user you're locking out. You don't really want to encrypt, do you? Just prevent access. Once you know how to accomplish all those things (suspend account / deny login, log out user, run script as privileged user, etc.,) it's easy to perform those tasks from a Python script.\n" ]
[ 7, 1 ]
[]
[]
[ "code_access_security", "python" ]
stackoverflow_0003061459_code_access_security_python.txt
Q: how to get files as they are added to a remote server I am using a bash script (below) on a remote server (so far using ssh to connect) to execute a python script that downloads a lot of pdf files one at a time (getting the download locations from a text file with the URL's) in a loop. I would like to move the files from the remote server to my local computer as they are downloaded, and then delete the file from the remote server. Is there a way that I can expand my bash script to do this? Or are there alternatives for completing this task? while read line; do python python_script.py -l $line; done < pdfURLs.txt A: [Edited to reflect the fact that the original poster can't scp into his local computer from the server; I assume it's behind NAT or something of the sort] [Edit 2: I'm keeping the current tunnel-based answer, for reference; but, since the original poster is unable to ssh back into his local machine, I'll assume something else is blocking the tunnel. See the suggestion at the end]. Ok, you'll need to open up a tunnel between the server and your home computer. So, ssh from your local computer (I assume it's Unix-based, you mentioned is a Mac, so that's fine) into the server with this command: ssh -R 10022:localhost:22 your_server_address In brief, this will forward the server's port 10022 (it's a high (> 1024) port, so it's likely to be available) to your local computer's port 22 (which is where ssh usually listens). That is, once you've done that, if you ssh into the server's 10022 port, you're actually sshing into your local computer. If you want to test it, from the server, do: ssh -p 10022 localhost login with your local computer's username and password, and you should see its shell prompt. If you do this test, remeber to log out, so as not to confuse yourself. Once you've opened the tunnel, keep that connection open. You may use it to run the bash command line that downloads the PDF etc, but that's not necessary. Then, try the following command-line: while read line; do python python_script.py -l "$line"; scp -P 10022 *.pdf localhost:path/to/put/files/; rm *.pdf; done < pdfURLs.txt A few things to keep in mind: This waits until scp has finished and only then will the python script downloaded the next PDF. You mentioned you effectively wanted this, not to keep the PDF files on the server for long. This copies all PDF files from the current directory to your local computer (and then erases them), so preferably run this from a previously empty directory. I assume you can scp without having to type a password (using shared key authentication, for instance), otherwise it might get a bit annoying, having to retype your password all the time. That should do it. [Edited to add this alternative, for when the tunnel doesn't work] If that fails, I can only assume something else is blocking your ssh/scp from the server to your local machine. In that case, you may try something different: from you local machine, do while read line; do ssh -n server_address "cd tmp_download_directory && rm -f *.pdf && python python_script.py -l $line" && scp server_address:tmp_download_directory/*.pdf /local/path/to/put/files/; done < pdfURLs.txt; ssh server_address "rm -f tmp_download_directory/*.pdf" (The "-n" switch to ssh is necessary, not to feed subsequente $lines into the ssh shell.)
how to get files as they are added to a remote server
I am using a bash script (below) on a remote server (so far using ssh to connect) to execute a python script that downloads a lot of pdf files one at a time (getting the download locations from a text file with the URL's) in a loop. I would like to move the files from the remote server to my local computer as they are downloaded, and then delete the file from the remote server. Is there a way that I can expand my bash script to do this? Or are there alternatives for completing this task? while read line; do python python_script.py -l $line; done < pdfURLs.txt
[ "[Edited to reflect the fact that the original poster can't scp into his local computer from the server; I assume it's behind NAT or something of the sort]\n[Edit 2: I'm keeping the current tunnel-based answer, for reference; but, since the original poster is unable to ssh back into his local machine, I'll assume something else is blocking the tunnel. See the suggestion at the end].\nOk, you'll need to open up a tunnel between the server and your home computer. So, ssh from your local computer (I assume it's Unix-based, you mentioned is a Mac, so that's fine) into the server with this command:\nssh -R 10022:localhost:22 your_server_address\n\nIn brief, this will forward the server's port 10022 (it's a high (> 1024) port, so it's likely to be available) to your local computer's port 22 (which is where ssh usually listens). That is, once you've done that, if you ssh into the server's 10022 port, you're actually sshing into your local computer. If you want to test it, from the server, do:\nssh -p 10022 localhost\n\nlogin with your local computer's username and password, and you should see its shell prompt. If you do this test, remeber to log out, so as not to confuse yourself.\nOnce you've opened the tunnel, keep that connection open. You may use it to run the bash command line that downloads the PDF etc, but that's not necessary.\nThen, try the following command-line:\nwhile read line; do python python_script.py -l \"$line\"; scp -P 10022 *.pdf localhost:path/to/put/files/; rm *.pdf; done < pdfURLs.txt\n\nA few things to keep in mind:\n\nThis waits until scp has finished and only then will the python script downloaded the next PDF. You mentioned you effectively wanted this, not to keep the PDF files on the server for long.\nThis copies all PDF files from the current directory to your local computer (and then erases them), so preferably run this from a previously empty directory.\nI assume you can scp without having to type a password (using shared key authentication, for instance), otherwise it might get a bit annoying, having to retype your password all the time.\n\nThat should do it.\n[Edited to add this alternative, for when the tunnel doesn't work]\nIf that fails, I can only assume something else is blocking your ssh/scp from the server to your local machine. In that case, you may try something different: from you local machine, do\nwhile read line; do ssh -n server_address \"cd tmp_download_directory && rm -f *.pdf && python python_script.py -l $line\" && scp server_address:tmp_download_directory/*.pdf /local/path/to/put/files/; done < pdfURLs.txt; ssh server_address \"rm -f tmp_download_directory/*.pdf\"\n\n(The \"-n\" switch to ssh is necessary, not to feed subsequente $lines into the ssh shell.)\n" ]
[ 1 ]
[]
[]
[ "bash", "python", "scp", "ssh" ]
stackoverflow_0003063235_bash_python_scp_ssh.txt
Q: I created a Python egg; now what? I've finally figured out how to create a Python egg and gotten it to work. Now... what do I do with it? How do I use it? How do I ensure that everything was correctly included? (Simple steps please... not just redirection to another site. I've googled, but it's confusing me, and I was hoping someone could explain it in a couple of simple bullet points or sentences.) Edit: I asked this question a couple of weeks ago, and I'm clarifying now in the hope of getting clearer answers... basically, I have an egg, I want to take it to another machine and be able to use it and import modules from it from my (other, unrelated) code. How do I do this? A: I'd advise only using python setup.py sdist to create zips and/or tarballs, and skip eggs. If you want to look at the egg it is a zip file; you can use unzip -v MyEgg-0.1.egg and see its contents to see if includes all the files you expect. You can also try installing it. Use virtualenv to create a new environment (use --no-site-packages to make it isolated) and try installing it into that environment, like: $ virtualenv --no-site-packages test-env $ ./test-env/bin/easy_install path/to/MyEgg-0.1.egg $ ./test-env/bin/python And then see if you can import it and use your package like you expect. You can do all the same things to test an sdist too. A: What I ended up doing was: Ran PYTHONPATH=fullPathOfMyEgg in command line Was then able to do import someModuleInMyEgg from my Python code I'm not sure if this is the most standard or accepted way to do it, but it worked. If anyone has any comments or other methods, please feel free to add...
I created a Python egg; now what?
I've finally figured out how to create a Python egg and gotten it to work. Now... what do I do with it? How do I use it? How do I ensure that everything was correctly included? (Simple steps please... not just redirection to another site. I've googled, but it's confusing me, and I was hoping someone could explain it in a couple of simple bullet points or sentences.) Edit: I asked this question a couple of weeks ago, and I'm clarifying now in the hope of getting clearer answers... basically, I have an egg, I want to take it to another machine and be able to use it and import modules from it from my (other, unrelated) code. How do I do this?
[ "I'd advise only using python setup.py sdist to create zips and/or tarballs, and skip eggs.\nIf you want to look at the egg it is a zip file; you can use unzip -v MyEgg-0.1.egg and see its contents to see if includes all the files you expect. You can also try installing it. Use virtualenv to create a new environment (use --no-site-packages to make it isolated) and try installing it into that environment, like:\n$ virtualenv --no-site-packages test-env\n$ ./test-env/bin/easy_install path/to/MyEgg-0.1.egg\n$ ./test-env/bin/python\n\nAnd then see if you can import it and use your package like you expect. You can do all the same things to test an sdist too.\n", "What I ended up doing was:\n\nRan PYTHONPATH=fullPathOfMyEgg in command line\nWas then able to do import someModuleInMyEgg from my Python code\n\nI'm not sure if this is the most standard or accepted way to do it, but it worked. If anyone has any comments or other methods, please feel free to add...\n" ]
[ 6, 0 ]
[]
[]
[ "distribution", "egg", "python" ]
stackoverflow_0002968809_distribution_egg_python.txt
Q: Python: convert 2 ints to 32 float How can I combine 2 ints to a single 32bit IEEE floating point ? (each of the 2 ints represent 16 bit) And in the opposite direction: How can I transform a python float into 2 16 bit ints? (I need this because of modbus protocol - where 2x16 bit registers are treated as single 32 floating point number) A: This code takes the 16 bits integers i1 and i2 and convert them to the floating point number 3.14, and vice versa. from struct import * # Two integers to a floating point i1 = 0xC3F5 i2 = 0x4840 f = unpack('f',pack('>HH',i1,i2))[0] # Floating point to two integers i1, i2 = unpack('>HH',pack('f',3.14)) A: The standard struct module can be used to do this easily. Just be careful of your platform endianess but, other than that, it should be a pretty straight-forward application of pack() and unpack().
Python: convert 2 ints to 32 float
How can I combine 2 ints to a single 32bit IEEE floating point ? (each of the 2 ints represent 16 bit) And in the opposite direction: How can I transform a python float into 2 16 bit ints? (I need this because of modbus protocol - where 2x16 bit registers are treated as single 32 floating point number)
[ "This code takes the 16 bits integers i1 and i2 and convert them to the floating point number 3.14, and vice versa.\nfrom struct import *\n# Two integers to a floating point\ni1 = 0xC3F5\ni2 = 0x4840\nf = unpack('f',pack('>HH',i1,i2))[0]\n\n# Floating point to two integers\ni1, i2 = unpack('>HH',pack('f',3.14))\n\n", "The standard struct module can be used to do this easily. Just be careful of your platform endianess but, other than that, it should be a pretty straight-forward application of pack() and unpack().\n" ]
[ 5, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003063078_python.txt
Q: How do you suppress Python DeprecationWarnings on Linux Terminal? I installed i18ndude (an internationalization utility to be used in Plone) using easy_install. When I try to run the utility i18ndude on my terminal, I get: /usr/local/lib/python2.6/dist-packages/i18ndude-3.1.2-py2.6.egg/i18ndude/odict.py:7: DeprecationWarning: object.__init__() takes no parameters dict.__init__(self, dict) How do I suppress these warning messages when calling the utility from command line? Is it possible? I know in theory I should install other Python interpreter, and call i18ndude from that, but I would like a simpler approach (like a parameter or something like that). BTW, I'm using a i18ndude script from Plone official site. A: Redirection can be used, but it would suppress all the messages sent to that "stream"; e.g. i178ndude 2>/dev/null sends to the null device the stream 2 (normally the stderr of a program, but deprecation warnings could be sent to other streams). This is the "fix it even though you don't know how" fix. Indeed there's an option, -W, that can be used like this: -W ignore::DeprecationWarning or simply -W ignore that ignores all warnings. You can write a script that call the python interpreter on your program, or more logically modify the #! of the prog with something like #!/usr/bin/env python -W ignore::DeprecationWarning A: If running as a script you could use: #!/usr/bin/env python -W ignore::DeprecationWarning A: You can temporarily suppress warnings: If you are using code that you know will raise a warning, such as a deprecated function, but do not want to see the warning, then it is possible to suppress the warning using the catch_warnings context manager: import warnings def fxn(): warnings.warn("deprecated", DeprecationWarning) with warnings.catch_warnings(): warnings.simplefilter("ignore") fxn() While within the context manager all warnings will simply be ignored. This allows you to use known-deprecated code without having to see the warning while not suppressing the warning for other code that might not be aware of its use of deprecated code. Note: this can only be guaranteed in a single-threaded application. If two or more threads use the catch_warnings context manager at the same time, the behavior is undefined. A: See cmdoption-W: -W arg Warning control. Python’s warning machinery by default prints warning messages to sys.stderr. A typical warning message has the following form: file:line: category: message By default, each warning is printed once for each source line where it occurs. This option controls how often warnings are printed. Multiple -W options may be given; when a warning matches more than one option, the action for the last matching option is performed. Invalid -W options are ignored (though, a warning message is printed about invalid options when the first warning is issued).
How do you suppress Python DeprecationWarnings on Linux Terminal?
I installed i18ndude (an internationalization utility to be used in Plone) using easy_install. When I try to run the utility i18ndude on my terminal, I get: /usr/local/lib/python2.6/dist-packages/i18ndude-3.1.2-py2.6.egg/i18ndude/odict.py:7: DeprecationWarning: object.__init__() takes no parameters dict.__init__(self, dict) How do I suppress these warning messages when calling the utility from command line? Is it possible? I know in theory I should install other Python interpreter, and call i18ndude from that, but I would like a simpler approach (like a parameter or something like that). BTW, I'm using a i18ndude script from Plone official site.
[ "Redirection can be used, but it would suppress all the messages sent to that \"stream\"; e.g.\ni178ndude 2>/dev/null\nsends to the null device the stream 2 (normally the stderr of a program, but deprecation warnings could be sent to other streams). This is the \"fix it even though you don't know how\" fix. Indeed there's an option, -W, that can be used like this: -W ignore::DeprecationWarning or simply -W ignore that ignores all warnings. You can write a script that call the python interpreter on your program, or more logically modify the #! of the prog with something like #!/usr/bin/env python -W ignore::DeprecationWarning\n", "If running as a script you could use:\n#!/usr/bin/env python -W ignore::DeprecationWarning\n\n", "You can temporarily suppress warnings:\n\nIf you are using code that you know will raise a warning, such as a deprecated function, but do not want to see the warning, then it is possible to suppress the warning using the catch_warnings context manager:\n\nimport warnings\n\ndef fxn():\n warnings.warn(\"deprecated\", DeprecationWarning)\n\nwith warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n fxn()\n\n\nWhile within the context manager all warnings will simply be ignored. This allows you to use known-deprecated code without having to see the warning while not suppressing the warning for other code that might not be aware of its use of deprecated code. Note: this can only be guaranteed in a single-threaded application. If two or more threads use the catch_warnings context manager at the same time, the behavior is undefined.\n\n", "See cmdoption-W:\n\n-W arg\nWarning control. Python’s warning machinery by default prints warning messages to sys.stderr. A typical warning message has the following form:\nfile:line: category: message\nBy default, each warning is printed once for each source line where it occurs. This option controls how often warnings are printed.\nMultiple -W options may be given; when a warning matches more than one option, the action for the last matching option is performed. Invalid -W options are ignored (though, a warning message is printed about invalid options when the first warning is issued).\n\n" ]
[ 5, 4, 3, 1 ]
[]
[]
[ "deprecated", "linux", "python", "warnings" ]
stackoverflow_0003063414_deprecated_linux_python_warnings.txt
Q: Running "source" from python I have a file a.txt with lines of commands I want to run, say: echo 1 echo 2 echo 3 If I was on csh (unix), I would have done source a.txt and it would run. From python I want to run os.execl with it, however I get: >>> os.execl("source", "a.txt") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.5/os.py", line 322, in execl execv(file, args) OSError: [Errno 2] No such file or directory How to do it? A: source is not an executable program, so you can't execute it directly. Rather, it is a builtin command in the shell. You would need to launch that shell instead if you really needed access to it. But if you just want to run the script, you don't need to use source at all – just have the shell execute your script directly: os.execl("/bin/bash", "a.txt") A: Do you just want to run a script? In that case, you can replace "source" with "bash" and probably get what you want. If you want the thing-being-sourced to have side-effects on the Python process, like setting environment variables or something, you are probably out of luck. A: You are not supplying the full path to source, and os.execl needs the path. If you want to use the PATH env variable, you should use os.execlp. See the os module documentation. Although, as @Walter mentions, you probably want /bin/bash instead of source: os.execl("/bin/bash", "a.txt")
Running "source" from python
I have a file a.txt with lines of commands I want to run, say: echo 1 echo 2 echo 3 If I was on csh (unix), I would have done source a.txt and it would run. From python I want to run os.execl with it, however I get: >>> os.execl("source", "a.txt") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.5/os.py", line 322, in execl execv(file, args) OSError: [Errno 2] No such file or directory How to do it?
[ "source is not an executable program, so you can't execute it directly. Rather, it is a builtin command in the shell. You would need to launch that shell instead if you really needed access to it. But if you just want to run the script, you don't need to use source at all – just have the shell execute your script directly:\nos.execl(\"/bin/bash\", \"a.txt\")\n\n", "Do you just want to run a script? In that case, you can replace \"source\" with \"bash\" and probably get what you want.\nIf you want the thing-being-sourced to have side-effects on the Python process, like setting environment variables or something, you are probably out of luck.\n", "You are not supplying the full path to source, and os.execl needs the path.\nIf you want to use the PATH env variable, you should use os.execlp.\nSee the os module documentation.\nAlthough, as @Walter mentions, you probably want /bin/bash instead of source:\nos.execl(\"/bin/bash\", \"a.txt\")\n\n" ]
[ 2, 1, 1 ]
[]
[]
[ "csh", "os.execl", "python" ]
stackoverflow_0003063629_csh_os.execl_python.txt
Q: Day names or first 3 characters I want my regex to catch: monday mon thursday thu ... So it's possible to write something like this: (?P<day>monday|mon|thursday|thu ... But I guess that there should be a more elegant solution. A: You can write mon(day)?|tue(sday)?|wed(nesday)?, etc. The ? is "zero-or-one repetition of"; so it's sort of "optional". If you don't need all the suffix captures, you can use the (?:___) non-capturing groups, so: mon(?:day)?|tue(?:sday)?|wed(?:nesday)? You can group Monday/Friday/Sunday together if you wish: (?:mon|fri|sun)(?:day)? I'm not sure if that's more readable, though. References regular-expressions.info/Repetition and Grouping Another option Java's Matcher lets you test if there's a partial match. If Python does too, then you can use that and see if at least (or perhaps exactly) 3 characters matched on monday|tuesday|.... (i.e. all complete names). Here's an example: import java.util.regex.*; public class PartialMatch { public static void main(String[] args) { String[] tests = { "sunday", "sundae", "su", "mon", "mondayyyy", "frida" }; Pattern p = Pattern.compile("(?:sun|mon|tues|wednes|thurs|fri|satur)day"); for (String test : tests) { Matcher m = p.matcher(test); System.out.printf("%s = %s%n", test, m.matches() ? "Exact match!" : m.hitEnd() ? "Partial match of " + test.length(): "No match!" ); } } } This prints (as seen on ideone.com): sunday = Exact match! sundae = No match! su = Partial match of 2 mon = Partial match of 3 mondayyyy = No match! frida = Partial match of 5 Related questions Can java.util.regex.Pattern do partial matches? How can I perform a partial match with java.util.regex.*?
Day names or first 3 characters
I want my regex to catch: monday mon thursday thu ... So it's possible to write something like this: (?P<day>monday|mon|thursday|thu ... But I guess that there should be a more elegant solution.
[ "You can write mon(day)?|tue(sday)?|wed(nesday)?, etc.\nThe ? is \"zero-or-one repetition of\"; so it's sort of \"optional\".\nIf you don't need all the suffix captures, you can use the (?:___) non-capturing groups, so:\nmon(?:day)?|tue(?:sday)?|wed(?:nesday)?\nYou can group Monday/Friday/Sunday together if you wish:\n(?:mon|fri|sun)(?:day)?\nI'm not sure if that's more readable, though.\nReferences\n\nregular-expressions.info/Repetition and Grouping\n\n\nAnother option\nJava's Matcher lets you test if there's a partial match. If Python does too, then you can use that and see if at least (or perhaps exactly) 3 characters matched on monday|tuesday|.... (i.e. all complete names).\nHere's an example:\nimport java.util.regex.*;\npublic class PartialMatch {\n public static void main(String[] args) {\n String[] tests = {\n \"sunday\", \"sundae\", \"su\", \"mon\", \"mondayyyy\", \"frida\"\n };\n Pattern p = Pattern.compile(\"(?:sun|mon|tues|wednes|thurs|fri|satur)day\");\n for (String test : tests) {\n Matcher m = p.matcher(test);\n System.out.printf(\"%s = %s%n\", test, \n m.matches() ? \"Exact match!\" :\n m.hitEnd() ? \"Partial match of \" + test.length():\n \"No match!\"\n );\n }\n }\n}\n\nThis prints (as seen on ideone.com):\nsunday = Exact match!\nsundae = No match!\nsu = Partial match of 2\nmon = Partial match of 3\nmondayyyy = No match!\nfrida = Partial match of 5\n\nRelated questions\n\n Can java.util.regex.Pattern do partial matches? \n How can I perform a partial match with java.util.regex.*? \n\n" ]
[ 3 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003063818_python_regex.txt
Q: How do I export GUI mockups to Python GUI code (e.g. wxpython)? I want to take my mockups and export them to code using any python GUI library (wxpython, pyqt, etc). For example, this capability already exists for mockups->HTML/Javascript here: http://www.balsamiq.com/products/mockups/community I need a fast, easy, high level mockup tool like balsamiq, not a slow, low level tool like boa constructor. Is there any combination of mockups/exporter tools like this for python? A: You can use the Qt Designer tool to do your mock-ups and then use the pyuic4 command line tool to convert the .pro file into Python code. Here are some references if you get stuck: http://diotavelli.net/PyQtWiki/Creating_GUI_Applications_with_PyQt_and_Qt_Designer http://wiki.python.org/moin/JonathanGardnerPyQtTutorial
How do I export GUI mockups to Python GUI code (e.g. wxpython)?
I want to take my mockups and export them to code using any python GUI library (wxpython, pyqt, etc). For example, this capability already exists for mockups->HTML/Javascript here: http://www.balsamiq.com/products/mockups/community I need a fast, easy, high level mockup tool like balsamiq, not a slow, low level tool like boa constructor. Is there any combination of mockups/exporter tools like this for python?
[ "You can use the Qt Designer tool to do your mock-ups and then use the pyuic4 command line tool to convert the .pro file into Python code.\nHere are some references if you get stuck:\nhttp://diotavelli.net/PyQtWiki/Creating_GUI_Applications_with_PyQt_and_Qt_Designer\nhttp://wiki.python.org/moin/JonathanGardnerPyQtTutorial\n" ]
[ 2 ]
[]
[]
[ "mockups", "pyqt", "python", "user_interface", "wxpython" ]
stackoverflow_0003054186_mockups_pyqt_python_user_interface_wxpython.txt
Q: creating events in my classes, and allowing others to hook into them in my django app I want to create events for my classes. Say I create a CMS application that has a Article object. I create events like: OnEdit OnCreate OnDelete PreCreate PreDelete Now I want someone to be able to hook into these events, and add their custom functionality at each event they wish. I don't want them touching the core source code, so they would have to wire these custom methods to fire somewhere else. I'm new to both python and django so please be as detailed as possible if you can. A: Signals are what you want. You can define custom signals in your application and send them when certain events happen, then users can get their code to listen to these signals and take any action they want.
creating events in my classes, and allowing others to hook into them in my django app
I want to create events for my classes. Say I create a CMS application that has a Article object. I create events like: OnEdit OnCreate OnDelete PreCreate PreDelete Now I want someone to be able to hook into these events, and add their custom functionality at each event they wish. I don't want them touching the core source code, so they would have to wire these custom methods to fire somewhere else. I'm new to both python and django so please be as detailed as possible if you can.
[ "Signals are what you want. You can define custom signals in your application and send them when certain events happen, then users can get their code to listen to these signals and take any action they want.\n" ]
[ 1 ]
[]
[]
[ "django", "events", "plugins", "python" ]
stackoverflow_0003063911_django_events_plugins_python.txt
Q: Can't parse XML effectively using Python import urllib import xml.etree.ElementTree as ET def getWeather(city): #create google weather api url url = "http://www.google.com/ig/api?weather=" + urllib.quote(city) try: # open google weather api url f = urllib.urlopen(url) except: # if there was an error opening the url, return return "Error opening url" # read contents to a string s = f.read() tree=ET.parse(s) current= tree.find("current_condition/condition") condition_data = current.get("data") weather = condition_data if weather == "<?xml version=": return "Invalid city" #return the weather condition #return weather def main(): while True: city = raw_input("Give me a city: ") weather = getWeather(city) print(weather) if __name__ == "__main__": main() gives error , I actually wanted to find values from google weather xml site tags A: Instead of tree=ET.parse(s) try tree=ET.fromstring(s) Also, your path to the data you want is incorrect. It should be: weather/current_conditions/condition This should work: import urllib import xml.etree.ElementTree as ET def getWeather(city): #create google weather api url url = "http://www.google.com/ig/api?weather=" + urllib.quote(city) try: # open google weather api url f = urllib.urlopen(url) except: # if there was an error opening the url, return return "Error opening url" # read contents to a string s = f.read() tree=ET.fromstring(s) current= tree.find("weather/current_conditions/condition") condition_data = current.get("data") weather = condition_data if weather == "<?xml version=": return "Invalid city" #return the weather condition return weather def main(): while True: city = raw_input("Give me a city: ") weather = getWeather(city) print(weather) A: I'll give the same answer here I did in my comment on your previous question. In the future, kindly update the existing question instead of posting a new one. Original I'm sorry - I didn't mean that my code would work exactly as you desired. Your error is because s is a string and parse takes a file or file-like object. So, "tree = ET.parse(f)" may work better. I would suggest reading up on the ElementTree api so you understand what the functions I've used above do in practice. Hope that helps, and let me know if it works.
Can't parse XML effectively using Python
import urllib import xml.etree.ElementTree as ET def getWeather(city): #create google weather api url url = "http://www.google.com/ig/api?weather=" + urllib.quote(city) try: # open google weather api url f = urllib.urlopen(url) except: # if there was an error opening the url, return return "Error opening url" # read contents to a string s = f.read() tree=ET.parse(s) current= tree.find("current_condition/condition") condition_data = current.get("data") weather = condition_data if weather == "<?xml version=": return "Invalid city" #return the weather condition #return weather def main(): while True: city = raw_input("Give me a city: ") weather = getWeather(city) print(weather) if __name__ == "__main__": main() gives error , I actually wanted to find values from google weather xml site tags
[ "Instead of \ntree=ET.parse(s)\n\ntry\ntree=ET.fromstring(s)\n\nAlso, your path to the data you want is incorrect. It should be: weather/current_conditions/condition\nThis should work:\nimport urllib\nimport xml.etree.ElementTree as ET\ndef getWeather(city):\n\n #create google weather api url\n url = \"http://www.google.com/ig/api?weather=\" + urllib.quote(city)\n\n try:\n # open google weather api url\n f = urllib.urlopen(url)\n except:\n # if there was an error opening the url, return\n return \"Error opening url\"\n\n # read contents to a string\n s = f.read()\n\n tree=ET.fromstring(s)\n\n current= tree.find(\"weather/current_conditions/condition\")\n condition_data = current.get(\"data\") \n weather = condition_data \n if weather == \"<?xml version=\":\n return \"Invalid city\"\n\n #return the weather condition\n return weather\n\ndef main():\n while True:\n city = raw_input(\"Give me a city: \")\n weather = getWeather(city)\n print(weather)\n\n", "I'll give the same answer here I did in my comment on your previous question. In the future, kindly update the existing question instead of posting a new one.\nOriginal\nI'm sorry - I didn't mean that my code would work exactly as you desired. Your error is because s is a string and parse takes a file or file-like object. So, \"tree = ET.parse(f)\" may work better. I would suggest reading up on the ElementTree api so you understand what the functions I've used above do in practice. Hope that helps, and let me know if it works.\n" ]
[ 3, 0 ]
[]
[]
[ "elementtree", "python", "xml" ]
stackoverflow_0003064247_elementtree_python_xml.txt
Q: Python: disabling $HOME/.python-eggs? Is there an easy way to disable Python egg caching? We have the situation where a system account needs to run a python program which imports a module. Since this is a non-login robot account, it does not have a home directory, and dies trying to create the directory /.python-eggs. What's the best way to fix this? Can I convert my eggs in site-files to something which will not be cached in .python-eggs? A: The best way to fix it is by creating a directory where it can write it's egg cache. You can specify the directory with the PYTHON_EGG_CACHE variable. [edit] And yes, you can convert your apps so they won't need an egg-cache. If you install the python packages with easy_install you can use easy_install -Z so it won't zip the eggs and it won't need to extract them. You should be able to unzip the current eggs to make sure you won't need them. But personally I would just create the egg cache directory.
Python: disabling $HOME/.python-eggs?
Is there an easy way to disable Python egg caching? We have the situation where a system account needs to run a python program which imports a module. Since this is a non-login robot account, it does not have a home directory, and dies trying to create the directory /.python-eggs. What's the best way to fix this? Can I convert my eggs in site-files to something which will not be cached in .python-eggs?
[ "The best way to fix it is by creating a directory where it can write it's egg cache. You can specify the directory with the PYTHON_EGG_CACHE variable.\n[edit]\nAnd yes, you can convert your apps so they won't need an egg-cache. If you install the python packages with easy_install you can use easy_install -Z so it won't zip the eggs and it won't need to extract them. You should be able to unzip the current eggs to make sure you won't need them.\nBut personally I would just create the egg cache directory.\n" ]
[ 3 ]
[]
[]
[ "egg", "python" ]
stackoverflow_0003064405_egg_python.txt
Q: Python and Plone help Im using the plone cms and am having trouble with a python script. I get a name error "the global name 'open' is not defined". When i put the code in a seperate python script it works fine and the information is being passed to the python script becuase i can print the query. Code is below: #Import a standard function, and get the HTML request and response objects. from Products.PythonScripts.standard import html_quote request = container.REQUEST RESPONSE = request.RESPONSE # Insert data that was passed from the form query=request.query #print query f = open("blast_query.txt","w") for i in query: f.write(i) return printed I also have a second question, can i tell python to open a file in in a certain directory for example, If the script is in a certain loaction i.e. home folder, but i want the script to open a file at home/some_directory/some_directory can it be done? A: Python Scripts in Plone are restricted and have no access to the filesystem. The open call is thus not available. You'll have to use an External Method or full python module to have full access to the filesystem.
Python and Plone help
Im using the plone cms and am having trouble with a python script. I get a name error "the global name 'open' is not defined". When i put the code in a seperate python script it works fine and the information is being passed to the python script becuase i can print the query. Code is below: #Import a standard function, and get the HTML request and response objects. from Products.PythonScripts.standard import html_quote request = container.REQUEST RESPONSE = request.RESPONSE # Insert data that was passed from the form query=request.query #print query f = open("blast_query.txt","w") for i in query: f.write(i) return printed I also have a second question, can i tell python to open a file in in a certain directory for example, If the script is in a certain loaction i.e. home folder, but i want the script to open a file at home/some_directory/some_directory can it be done?
[ "Python Scripts in Plone are restricted and have no access to the filesystem. The open call is thus not available. You'll have to use an External Method or full python module to have full access to the filesystem.\n" ]
[ 3 ]
[]
[]
[ "nameerror", "plone", "python" ]
stackoverflow_0003064272_nameerror_plone_python.txt
Q: Display form in Django not based on Models/Form My view calls some backend classes which need some user input. When user input is required, i halt processing and store the questions into the session - request.session['questions']. request.session['questions'] is a list of dictionaries. e.g. request.session['question'] = [] request.session['question'].append({'question' : 'Whats your firstname', 'answer' : ''}) request.session['question'].append({'question' : 'Whats your firstname', 'answer' : ''}) I need to display these questions to the user along with an input box for each question. When the user submits the form, I need to dump the input into the answers part of the session variable. Could someone show me how to do this? I'm a little lost as this isn't really based on Django forms or models as such. Thanks A: You could use forms that aren't associated with models, like this: class QuestionForm(forms.Form): answer = forms.CharField() def questions(request): if request.method == 'POST': form = QuestionForm(request.POST) if form.is_valid(): # Process the data in form.cleaned_data return HttpResponseRedirect('/done/') else: form = QuestionForm() # An unbound form return render_to_response('questions.html', {'form': form,}) More documentation here.
Display form in Django not based on Models/Form
My view calls some backend classes which need some user input. When user input is required, i halt processing and store the questions into the session - request.session['questions']. request.session['questions'] is a list of dictionaries. e.g. request.session['question'] = [] request.session['question'].append({'question' : 'Whats your firstname', 'answer' : ''}) request.session['question'].append({'question' : 'Whats your firstname', 'answer' : ''}) I need to display these questions to the user along with an input box for each question. When the user submits the form, I need to dump the input into the answers part of the session variable. Could someone show me how to do this? I'm a little lost as this isn't really based on Django forms or models as such. Thanks
[ "You could use forms that aren't associated with models, like this:\nclass QuestionForm(forms.Form):\n answer = forms.CharField()\n\ndef questions(request):\n if request.method == 'POST':\n form = QuestionForm(request.POST) \n if form.is_valid():\n # Process the data in form.cleaned_data\n return HttpResponseRedirect('/done/')\n else:\n form = QuestionForm() # An unbound form\n\n return render_to_response('questions.html', {'form': form,})\n\nMore documentation here.\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003065002_django_python.txt
Q: Python: Cannot concatenate str and NoneType objects sql = """ INSERT INTO [SCHOOLINFO] VALUES( '""" + self.accountNo + """', '""" + self.altName + """', '""" + self.address1 + """', '""" + self.address2 + """', '""" + self.city + """', '""" + self.state + """', '""" + self.zipCode + """', '""" + self.phone1 + """', '""" + self.phone2 + """', '""" + self.fax + """', '""" + self.contactName + """', '""" + self.contactEmail + """', '""" + self.prize_id + """', '""" + self.shipping + """', '""" + self.chairTempPass + """', '""" + self.studentCount + """' ) """; I have the following code and Python keeps throwing the error that it cannon concatenate strings and nonetype objects. The thing is I have verified every variable here is in fact a string and is not null. I have been stuck on this for quite some time today, and any help would be greatly appreciated. A: Use bind variables instead. Here's the spec for working with DBs in Python: PEP 249: Python Database API Specification v2.0. UPDATE: Based on the docs for pymssql, you need something like: sql = """ INSERT INTO [SCHOOLINFO] VALUES( %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %d, %s, %s, %d )""" cur.execute(sql, self.accountNo, self.altName, self.address1, self.address2, self.city, self.state, self.zipCode, self.phone1, self.phone2, self.fax, self.contactName, self.contactEmail, self.prize_id, self.shipping, self.chairTempPass, self.studentCount) A: All these answers so far focus not on your problem but on what is right to do. Yes, yes - bind variables is better and safer. And yes, using % for formatting is faster and likely better. But on your question what gives you that error - it must be that one of the values is None at some point, there is no other explanation. Just put a debug print in front of that, something like: for v in 'accountNo altName address1 address2 city state zipCode phone1 phone2 fax contactName contactEmail prize_id shipping chairTempPass studentCount'.split(): if getattr(self, v) is None: print 'PANIC: %s is None' % v I bet it will print something at some point ;-) A: Composing the SQL query like this is very dangerous, especially due to sql-injection If using MySqldb a better alternative would be like this: db.query("INSERT INTO [SCHOOLINFO] VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", [self.accountNo, self.altName, self.address1, self.address2, self.city, self.state, self.zipCode, self.phone1, self.phone2, self.fax, self.contactName, self.contactEmail, self.prize_id, self.shipping, self.chairTempPass, self.studentCount]) A: I'm going to assume you're using a library like MySQLdb. The best way to handle these kind of statements is like so: import _mysql db = _mysql.connect("localhost","user","password","database_name") cursor = db.cursor() sql = """ INSERT INTO [SCHOOLINFO] VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) """ cursor.execute(sql, [self.accountNo, self.altName, self.address1, \ self.address2, self.city, self.state, self.zipCode, \ self.phone1, self.phone2, self.fax, self.contactName, \ self.contactEmail, self.prize_id, self.shipping, \ self.chairTempPass, self.studentCount]) This way the database library handles properly entering the values in the INSERT query. It'll even make None values be entered as NULL into the new row. Plus the original way you were doing it was pretty susceptible to SQL injection attacks. If you aren't using mysql, your library probably has similar functionality. EDIT - If you're connecting to a SQL Server database, use the pyodbc library. You can get it at http://code.google.com/p/pyodbc/. Here's what the code would look like: import pyodbc conn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=database_name;UID=user;PWD=password') cursor = conn.cursor() sql = """ INSERT INTO [SCHOOLINFO] VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """ cursor.execute(sql, self.accountNo, self.altName, self.address1, \ self.address2, self.city, self.state, self.zipCode, \ self.phone1, self.phone2, self.fax, self.contactName, \ self.contactEmail, self.prize_id, self.shipping, \ self.chairTempPass, self.studentCount) conn.commit() A: You should not be concatenating values into SQL statements, because doing so leaves you wide open to (accidental or deliberate) SQL injection. Instead, you should be passing SQL statements with parameter markers where the values should go, and letting your database connector insert the values into the correct places. All database connectors support this in some form. For example, psycopg2 (a PostgreSQL connector which follows the Python DB API) would accept something like this: cursor.execute( "insert into schoolinfo (accountno, altname) values (%s, %s)", (self.accountNo, self.altName)) A side benefit of doing it this way: Values that are not strings (e.g. None) will be converted automatically and you won't get the error you described in your question.
Python: Cannot concatenate str and NoneType objects
sql = """ INSERT INTO [SCHOOLINFO] VALUES( '""" + self.accountNo + """', '""" + self.altName + """', '""" + self.address1 + """', '""" + self.address2 + """', '""" + self.city + """', '""" + self.state + """', '""" + self.zipCode + """', '""" + self.phone1 + """', '""" + self.phone2 + """', '""" + self.fax + """', '""" + self.contactName + """', '""" + self.contactEmail + """', '""" + self.prize_id + """', '""" + self.shipping + """', '""" + self.chairTempPass + """', '""" + self.studentCount + """' ) """; I have the following code and Python keeps throwing the error that it cannon concatenate strings and nonetype objects. The thing is I have verified every variable here is in fact a string and is not null. I have been stuck on this for quite some time today, and any help would be greatly appreciated.
[ "Use bind variables instead. Here's the spec for working with DBs in Python: PEP 249: Python Database API Specification v2.0.\nUPDATE: Based on the docs for pymssql, you need something like:\nsql = \"\"\"\n INSERT INTO [SCHOOLINFO] \n VALUES(\n %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %d, %s, %s, %d\n )\"\"\"\ncur.execute(sql, self.accountNo, self.altName, self.address1, self.address2, self.city, self.state, self.zipCode, self.phone1, self.phone2, self.fax, self.contactName, self.contactEmail, self.prize_id, self.shipping, self.chairTempPass, self.studentCount)\n\n", "All these answers so far focus not on your problem but on what is right to do. Yes, yes - bind variables is better and safer. And yes, using % for formatting is faster and likely better.\nBut on your question what gives you that error - it must be that one of the values is None at some point, there is no other explanation. Just put a debug print in front of that, something like:\nfor v in 'accountNo altName address1 address2 city state zipCode phone1 phone2 fax contactName contactEmail prize_id shipping chairTempPass studentCount'.split():\n if getattr(self, v) is None:\n print 'PANIC: %s is None' % v\n\nI bet it will print something at some point ;-)\n", "Composing the SQL query like this is very dangerous, especially due to sql-injection\nIf using MySqldb a better alternative would be like this:\ndb.query(\"INSERT INTO [SCHOOLINFO] VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\",\n[self.accountNo, self.altName, self.address1, self.address2, self.city, self.state, self.zipCode, self.phone1, self.phone2, self.fax, self.contactName, self.contactEmail, self.prize_id, self.shipping, self.chairTempPass, self.studentCount])\n\n", "I'm going to assume you're using a library like MySQLdb. The best way to handle these kind of statements is like so:\nimport _mysql\n\ndb = _mysql.connect(\"localhost\",\"user\",\"password\",\"database_name\")\ncursor = db.cursor()\n\nsql = \"\"\"\n INSERT INTO [SCHOOLINFO] \n VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\n\"\"\"\ncursor.execute(sql, [self.accountNo, self.altName, self.address1, \\\n self.address2, self.city, self.state, self.zipCode, \\\n self.phone1, self.phone2, self.fax, self.contactName, \\\n self.contactEmail, self.prize_id, self.shipping, \\\n self.chairTempPass, self.studentCount])\n\nThis way the database library handles properly entering the values in the INSERT query. It'll even make None values be entered as NULL into the new row. Plus the original way you were doing it was pretty susceptible to SQL injection attacks.\nIf you aren't using mysql, your library probably has similar functionality.\nEDIT -\nIf you're connecting to a SQL Server database, use the pyodbc library. You can get it at http://code.google.com/p/pyodbc/. Here's what the code would look like:\nimport pyodbc\n\nconn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=database_name;UID=user;PWD=password')\ncursor = conn.cursor()\n\nsql = \"\"\"\n INSERT INTO [SCHOOLINFO] \n VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n\"\"\"\ncursor.execute(sql, self.accountNo, self.altName, self.address1, \\\n self.address2, self.city, self.state, self.zipCode, \\\n self.phone1, self.phone2, self.fax, self.contactName, \\\n self.contactEmail, self.prize_id, self.shipping, \\\n self.chairTempPass, self.studentCount)\nconn.commit()\n\n", "You should not be concatenating values into SQL statements, because doing so leaves you wide open to (accidental or deliberate) SQL injection. Instead, you should be passing SQL statements with parameter markers where the values should go, and letting your database connector insert the values into the correct places.\nAll database connectors support this in some form. For example, psycopg2 (a PostgreSQL connector which follows the Python DB API) would accept something like this:\ncursor.execute( \"insert into schoolinfo (accountno, altname) values (%s, %s)\",\n (self.accountNo, self.altName))\n\nA side benefit of doing it this way: Values that are not strings (e.g. None) will be converted automatically and you won't get the error you described in your question.\n" ]
[ 4, 3, 1, 1, 0 ]
[]
[]
[ "python", "sql" ]
stackoverflow_0003064233_python_sql.txt
Q: Python what's the data structure for triple data I've got a set of data that has three attributes, say A, B, and C, where A is kind of the index (i.e., A is used to look up the other two attributes.) What would be the best data structure for such data? I used two dictionaries, with A as the index of each. However, there's key errors when the query to the data doesn't match any instance of A. A: Could you use a dictionary with A as the key, and the item in the dictionary as a 2-item tuple or list? If you're working with any of that data in a consistent way, you could also consider storing a class that has 2 properties in the dictionary. A: AtoB = {"A1":"B1", "A2":"B2"} AtoB.get("A3", None) => None A: As an alternative to a dict of tuples, you could use an object to store B and C: class Thing: def __init__(self, B=None, C=None): self.B = B self.C = C stuff = {A1: Thing(B1, C1)} B1 = stuff[A1].B processTriple(A1, stuff[A1].B, stuff[A1].C) nothing = stuff.get(A2) While it's a tiny bit wasteful, you could store A in the object too so that each instance represents a complete triple. Then you can pass those around more effectively than the sample above. A: I would suggest using a dictionary with A keyed to (B, C), so d = {A : (B, C)}. Your problem of nonexistent keys resulting in errors can be solved in the following manner (thanks to intuited for the has_key function I forgot about): if d.has_key(A): # do whatever you want else: # A does not exist in your dictionary and you can handle this properly Another option is the to do it in a try: except: block, but I tend to agree with intuited that if keys will be missing at a rate that isn't completely unusual, has_key will show better performance and (arguably) make better conceptual sense.
Python what's the data structure for triple data
I've got a set of data that has three attributes, say A, B, and C, where A is kind of the index (i.e., A is used to look up the other two attributes.) What would be the best data structure for such data? I used two dictionaries, with A as the index of each. However, there's key errors when the query to the data doesn't match any instance of A.
[ "Could you use a dictionary with A as the key, and the item in the dictionary as a 2-item tuple or list? If you're working with any of that data in a consistent way, you could also consider storing a class that has 2 properties in the dictionary.\n", "AtoB = {\"A1\":\"B1\", \"A2\":\"B2\"}\nAtoB.get(\"A3\", None)\n=> None\n\n", "As an alternative to a dict of tuples, you could use an object to store B and C:\nclass Thing:\n def __init__(self, B=None, C=None):\n self.B = B\n self.C = C\n\nstuff = {A1: Thing(B1, C1)}\nB1 = stuff[A1].B\n\nprocessTriple(A1, stuff[A1].B, stuff[A1].C)\n\nnothing = stuff.get(A2)\n\nWhile it's a tiny bit wasteful, you could store A in the object too so that each instance represents a complete triple. Then you can pass those around more effectively than the sample above.\n", "I would suggest using a dictionary with A keyed to (B, C), so d = {A : (B, C)}.\nYour problem of nonexistent keys resulting in errors can be solved in the following manner (thanks to intuited for the has_key function I forgot about):\nif d.has_key(A):\n # do whatever you want\nelse:\n # A does not exist in your dictionary and you can handle this properly\n\nAnother option is the to do it in a try: except: block, but I tend to agree with intuited that if keys will be missing at a rate that isn't completely unusual, has_key will show better performance and (arguably) make better conceptual sense.\n" ]
[ 3, 3, 2, 0 ]
[]
[]
[ "data_structures", "python" ]
stackoverflow_0003064169_data_structures_python.txt
Q: AES Encryption. From Python (pyCrypto) to .NET I am currently trying to port a legacy Python app over to .NET which contains AES encrpytion using from what I can tell pyCrpyto. I have very limited Python and Crypto experience. The code uses the snippet from the following page. http://www.djangosnippets.org/snippets/1095/ So far I believe I have managed to work out that it that it calls Crypto.Cipher with AES and the first 32 character of our secret key as the password, but no mode or IV. It also puts a prefix on the encrpyed text when it is added to database. What I can't work out is how I can decrypt the existing ecrypted database records in .NET. I have been looking at RijndaelManaged but it requires an IV and can't see any reference to one in python. Can anyone point me in the dirrection to what method could be used in .NET to get the desired result. A: AES (and Rijndael) requires a mode and an IV. The IV may be a vector of zeroes, but it is still an IV. the mode may not be explicitly specified... but if it's using AES, there's still a mode. Try this answer for some background: Which AES library to use in Ruby/Python?
AES Encryption. From Python (pyCrypto) to .NET
I am currently trying to port a legacy Python app over to .NET which contains AES encrpytion using from what I can tell pyCrpyto. I have very limited Python and Crypto experience. The code uses the snippet from the following page. http://www.djangosnippets.org/snippets/1095/ So far I believe I have managed to work out that it that it calls Crypto.Cipher with AES and the first 32 character of our secret key as the password, but no mode or IV. It also puts a prefix on the encrpyed text when it is added to database. What I can't work out is how I can decrypt the existing ecrypted database records in .NET. I have been looking at RijndaelManaged but it requires an IV and can't see any reference to one in python. Can anyone point me in the dirrection to what method could be used in .NET to get the desired result.
[ "AES (and Rijndael) requires a mode and an IV. The IV may be a vector of zeroes, but it is still an IV. the mode may not be explicitly specified... but if it's using AES, there's still a mode.\nTry this answer for some background:\nWhich AES library to use in Ruby/Python?\n" ]
[ 1 ]
[]
[]
[ ".net", "aes", "c#", "pycrypto", "python" ]
stackoverflow_0002973546_.net_aes_c#_pycrypto_python.txt
Q: How to implement python to find value between xml tags? I am using google site to retrieve weather information , I want to find values between XML tags. Following code give me weather condition of a city , but I am unable to obtain other parameters such as temperature and if possible explain working of split function implied in the code: import urllib def getWeather(city): #create google weather api url url = "http://www.google.com/ig/api?weather=" + urllib.quote(city) try: # open google weather api url f = urllib.urlopen(url) except: # if there was an error opening the url, return return "Error opening url" # read contents to a string s = f.read() # extract weather condition data from xml string weather = s.split("<current_conditions><condition data=\"")[-1].split("\"")[0] # if there was an error getting the condition, the city is invalid if weather == "<?xml version=": return "Invalid city" #return the weather condition return weather def main(): while True: city = raw_input("Give me a city: ") weather = getWeather(city) print(weather) if __name__ == "__main__": main() Thank You A: USE A PARSER You can't parse XML using regex(es), so don't try. Here's a start to finding an XML parser in Python. Here's a good site for learning about parsing XML in Python. UPDATE: Given the new info about PyS60, here's the documentation for using XML from Nokia's website. UPDATE 2: @Nas Banov has requested sample code, so here it is: import urllib from xml.parsers import expat def start_element_handler(name, attrs): """ My handler for the event that fires when the parser sees an opening tag in the XML. """ # If we care about more than just the temp data, we can extend this # logic with ``elif``. If the XML gets really hairy, we can create a # ``dict`` of handler functions and index it by tag name, e.g., # { 'humidity': humidity_handler } if 'temp_c' == name: print "The current temperature is %(data)s degrees Celsius." % attrs def process_weather_conditions(): """ Main logic of the POC; set up the parser and handle resource cleanup. """ my_parser = expat.ParserCreate() my_parser.StartElementHandler = start_element_handler # I don't know if the S60 supports try/finally, but that's not # the point of the POC. try: f = urllib.urlopen("http://www.google.com/ig/api?weather=30096") my_parser.ParseFile(f) finally: f.close() if __name__ == '__main__': process_weather_conditions() A: I would suggest using an XML Parser, just like Hank Gay suggested. My personal suggestion would be lxml, as I'm currently using it on a project and it extends the very usable ElementTree interface already present in the standard lib (xml.etree). Lxml includes added support for xpath, xslt, and various other features lacking in the standard ElementTree module. Regardless of which you choose, an XML parser is by far the best option, as you'll be able to deal with the XML document as a Python object. This means your code would be something like: # existing code up to... s = f.read() import lxml.etree as ET tree = ET.parse(s) current = tree.find("current_condition/condition") condition_data = current.get("data") weather = condition_data return weather A: XML is structured data. You can do much better than using string manipulation to fetch data out of it. There are the sax, dom and elementree modules in the standard library as well as the high quality lxml library which can do your work for you in a much more reliable fashion. A: Well, here goes - a non-full parser solution for your particular case: import urllib def getWeather(city): ''' given city name or postal code, return dictionary with current weather conditions ''' url = 'http://www.google.com/ig/api?weather=' try: f = urllib.urlopen(url + urllib.quote(city)) except: return "Error opening url" s = f.read().replace('\r','').replace('\n','') if '<problem' in s: return "Problem retreaving weather (invalid city?)" weather = s.split('</current_conditions>')[0] \ .split('<current_conditions>')[-1] \ .strip('</>') wdict = dict(i.split(' data="') for i in weather.split('"/><')) return wdict and example of use: >>> weather = getWeather('94043') >>> weather {'temp_f': '67', 'temp_c': '19', 'humidity': 'Humidity: 61%', 'wind_condition': 'Wind: N at 21 mph', 'condition': 'Sunny', 'icon': '/ig/images/weather/sunny.gif'} >>> weather['humidity'] 'Humidity: 61%' >>> print '%(condition)s\nTemperature %(temp_c)s C (%(temp_f)s F)\n%(humidity)s\n%(wind_condition)s' % weather Sunny Temperature 19 C (67 F) Humidity: 61% Wind: N at 21 mph PS. Note that a fairly trivial change in Google output format will break this - say if they were to add extra spaces or tabs between tags or attributes. Which they avoid to decrease size of http response. But if they did, we'd have to get acquainted with regular expressions and re.split() PPS. how str.split(sep) works is explained in the documentation, here is a excerpt: Return a list of the words in the string, using sep as the delimiter string. ... The sep argument may consist of multiple characters (for example, '1<>2<>3'.split('<>') returns ['1', '2', '3']). So 'text1<tag>text2</tag>text3'.split('</tag>') gives us ['text1<tag>text2', 'text3'], then [0] picks up the 1st element 'text1<tag>text2', then we split at and pick up 'text2' which contains the data we are interested in. Quite trite really.
How to implement python to find value between xml tags?
I am using google site to retrieve weather information , I want to find values between XML tags. Following code give me weather condition of a city , but I am unable to obtain other parameters such as temperature and if possible explain working of split function implied in the code: import urllib def getWeather(city): #create google weather api url url = "http://www.google.com/ig/api?weather=" + urllib.quote(city) try: # open google weather api url f = urllib.urlopen(url) except: # if there was an error opening the url, return return "Error opening url" # read contents to a string s = f.read() # extract weather condition data from xml string weather = s.split("<current_conditions><condition data=\"")[-1].split("\"")[0] # if there was an error getting the condition, the city is invalid if weather == "<?xml version=": return "Invalid city" #return the weather condition return weather def main(): while True: city = raw_input("Give me a city: ") weather = getWeather(city) print(weather) if __name__ == "__main__": main() Thank You
[ "USE\nA\nPARSER\nYou can't parse XML using regex(es), so don't try. Here's a start to finding an XML parser in Python. Here's a good site for learning about parsing XML in Python.\nUPDATE: Given the new info about PyS60, here's the documentation for using XML from Nokia's website.\nUPDATE 2: @Nas Banov has requested sample code, so here it is:\nimport urllib\n\nfrom xml.parsers import expat\n\ndef start_element_handler(name, attrs):\n \"\"\"\n My handler for the event that fires when the parser sees an\n opening tag in the XML.\n \"\"\"\n # If we care about more than just the temp data, we can extend this\n # logic with ``elif``. If the XML gets really hairy, we can create a\n # ``dict`` of handler functions and index it by tag name, e.g.,\n # { 'humidity': humidity_handler }\n if 'temp_c' == name:\n print \"The current temperature is %(data)s degrees Celsius.\" % attrs\n\ndef process_weather_conditions():\n \"\"\"\n Main logic of the POC; set up the parser and handle resource\n cleanup.\n \"\"\"\n my_parser = expat.ParserCreate()\n my_parser.StartElementHandler = start_element_handler\n\n # I don't know if the S60 supports try/finally, but that's not\n # the point of the POC.\n try:\n f = urllib.urlopen(\"http://www.google.com/ig/api?weather=30096\")\n my_parser.ParseFile(f)\n finally:\n f.close()\n\nif __name__ == '__main__':\n process_weather_conditions()\n\n", "I would suggest using an XML Parser, just like Hank Gay suggested. My personal suggestion would be lxml, as I'm currently using it on a project and it extends the very usable ElementTree interface already present in the standard lib (xml.etree).\nLxml includes added support for xpath, xslt, and various other features lacking in the standard ElementTree module.\nRegardless of which you choose, an XML parser is by far the best option, as you'll be able to deal with the XML document as a Python object. This means your code would be something like:\n# existing code up to...\ns = f.read()\nimport lxml.etree as ET\ntree = ET.parse(s)\ncurrent = tree.find(\"current_condition/condition\")\ncondition_data = current.get(\"data\")\nweather = condition_data\nreturn weather\n\n", "XML is structured data. You can do much better than using string manipulation to fetch data out of it. There are the sax, dom and elementree modules in the standard library as well as the high quality lxml library which can do your work for you in a much more reliable fashion.\n", "Well, here goes - a non-full parser solution for your particular case:\nimport urllib\n\ndef getWeather(city):\n ''' given city name or postal code,\n return dictionary with current weather conditions\n '''\n url = 'http://www.google.com/ig/api?weather='\n try:\n f = urllib.urlopen(url + urllib.quote(city))\n except:\n return \"Error opening url\"\n s = f.read().replace('\\r','').replace('\\n','')\n if '<problem' in s:\n return \"Problem retreaving weather (invalid city?)\"\n\n weather = s.split('</current_conditions>')[0] \\\n .split('<current_conditions>')[-1] \\\n .strip('</>') \n wdict = dict(i.split(' data=\"') for i in weather.split('\"/><'))\n return wdict\n\nand example of use:\n>>> weather = getWeather('94043')\n>>> weather\n{'temp_f': '67', 'temp_c': '19', 'humidity': 'Humidity: 61%', 'wind_condition': 'Wind: N at 21 mph', 'condition': 'Sunny', 'icon': '/ig/images/weather/sunny.gif'}\n>>> weather['humidity']\n'Humidity: 61%'\n>>> print '%(condition)s\\nTemperature %(temp_c)s C (%(temp_f)s F)\\n%(humidity)s\\n%(wind_condition)s' % weather\nSunny\nTemperature 19 C (67 F)\nHumidity: 61%\nWind: N at 21 mph\n\nPS. Note that a fairly trivial change in Google output format will break this - say if they were to add extra spaces or tabs between tags or attributes. Which they avoid to decrease size of http response. But if they did, we'd have to get acquainted with regular expressions and re.split()\nPPS. how str.split(sep) works is explained in the documentation, here is a excerpt: Return a list of the words in the string, using sep as the delimiter string. ... The sep argument may consist of multiple characters (for example, '1<>2<>3'.split('<>') returns ['1', '2', '3']). So 'text1<tag>text2</tag>text3'.split('</tag>') gives us ['text1<tag>text2', 'text3'], then [0] picks up the 1st element 'text1<tag>text2', then we split at and pick up 'text2' which contains the data we are interested in. Quite trite really.\n" ]
[ 8, 4, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003063319_python.txt
Q: What Is The Replace Function In Python I want to write a python code that open a text file and Replace with a word that i want send to it . May you give me an example ? Thanks . A: surprised that MarteliBot has not replied yet :-) (i learned about fileinput from him here in some other thread) - so in a hurry, you can do the following: import fileinput for line in fileinput.input('somefile.txt', inplace=1): print line.replace('OldWord', 'NewWord'), ps. this actually redirects stdout to the same file in a safe way (i.e. writes to tempfile and later renames etc). ain't it pretty? A: There are so many ways to do this, but make sure you look at Template Strings to see if they're a good fit for your application. From the documentation: >>> from string import Template >>> s = Template('$who likes $what') >>> s.substitute(who='tim', what='kung pao') 'tim likes kung pao' >>> d = dict(who='tim') >>> Template('Give $who $100').substitute(d) Traceback (most recent call last): [...] ValueError: Invalid placeholder in string: line 1, col 10 >>> Template('$who likes $what').substitute(d) Traceback (most recent call last): [...] KeyError: 'what' >>> Template('$who likes $what').safe_substitute(d) 'tim likes $what' A: It can be as simple as this: data = open('input_file').read() open('output_file', 'w').write(data.replace('old_word', 'new_word')) A cleaner version: fh = open('input_file') data = fh.read() fh.close() data = data.replace('old_word', 'new_word') fh = open('output_file', 'w') fh.write(data) fh.close() A: you can do it this way using the with-statement: PATH = "/home/Eva/test.txt" with open(PATH) as f: # read the file content content = f.read() with open(PATH, "w+") as f: # w+ stands for (re)write content = content.replace("abc", "test") f.write(content) (abc is the old text, test the new text, which will replace old) You can read more about files here. I hope that helps you. A: sed s/oldword/newword/g originalfile.txt > fixedfile.txt :-)
What Is The Replace Function In Python
I want to write a python code that open a text file and Replace with a word that i want send to it . May you give me an example ? Thanks .
[ "surprised that MarteliBot has not replied yet :-) (i learned about fileinput from him here in some other thread) - so in a hurry, you can do the following:\nimport fileinput\nfor line in fileinput.input('somefile.txt', inplace=1):\n print line.replace('OldWord', 'NewWord'),\n\nps. this actually redirects stdout to the same file in a safe way (i.e. writes to tempfile and later renames etc). ain't it pretty?\n", "There are so many ways to do this, but make sure you look at Template Strings to see if they're a good fit for your application.\nFrom the documentation:\n>>> from string import Template\n>>> s = Template('$who likes $what')\n>>> s.substitute(who='tim', what='kung pao')\n'tim likes kung pao'\n>>> d = dict(who='tim')\n>>> Template('Give $who $100').substitute(d)\nTraceback (most recent call last):\n[...]\nValueError: Invalid placeholder in string: line 1, col 10\n>>> Template('$who likes $what').substitute(d)\nTraceback (most recent call last):\n[...]\nKeyError: 'what'\n>>> Template('$who likes $what').safe_substitute(d)\n'tim likes $what'\n\n", "It can be as simple as this:\ndata = open('input_file').read()\nopen('output_file', 'w').write(data.replace('old_word', 'new_word'))\n\nA cleaner version:\nfh = open('input_file')\ndata = fh.read()\nfh.close()\n\ndata = data.replace('old_word', 'new_word')\n\nfh = open('output_file', 'w')\nfh.write(data)\nfh.close()\n\n", "you can do it this way using the with-statement:\nPATH = \"/home/Eva/test.txt\"\n\nwith open(PATH) as f: # read the file content\n content = f.read()\n\nwith open(PATH, \"w+\") as f: # w+ stands for (re)write\n content = content.replace(\"abc\", \"test\")\n f.write(content)\n\n(abc is the old text, test the new text, which will replace old)\nYou can read more about files here. I hope that helps you.\n", "sed s/oldword/newword/g originalfile.txt > fixedfile.txt\n:-)\n" ]
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "file_io", "python", "replace" ]
stackoverflow_0003064392_file_io_python_replace.txt
Q: Assignment in python for loop possible? I have a dictionary d (and a seperate sorted list of keys, keys). I wanted the loop to only process entries where the value is False - so i tried the following: for key in keys and not d[key]: #do foo I suppose my understanding of python sytax is not what i thought it was - because the assignment doesnt suppose to have happened above, and a i get an instanciation error. The below works of course, but I'd really like to be able to use something like the code above.. possible? for key in keys: if d[key]: continue #foo time! Thanks! A: Use a genex for this. for key in (k for k in keys if not d[k]): .... A: If you dict was opposite (True iff the value should be scanned) you could use: for key in filter(d.get, keys): ... A: import itertools as it for key in it.ifilterfalse(d.get, keys): ... itertools often offers the best ways to pack functionality into iterations (==loops;-).
Assignment in python for loop possible?
I have a dictionary d (and a seperate sorted list of keys, keys). I wanted the loop to only process entries where the value is False - so i tried the following: for key in keys and not d[key]: #do foo I suppose my understanding of python sytax is not what i thought it was - because the assignment doesnt suppose to have happened above, and a i get an instanciation error. The below works of course, but I'd really like to be able to use something like the code above.. possible? for key in keys: if d[key]: continue #foo time! Thanks!
[ "Use a genex for this.\nfor key in (k for k in keys if not d[k]):\n ....\n\n", "If you dict was opposite (True iff the value should be scanned) you could use:\nfor key in filter(d.get, keys):\n ...\n\n", "import itertools as it\n\nfor key in it.ifilterfalse(d.get, keys):\n ...\n\nitertools often offers the best ways to pack functionality into iterations (==loops;-).\n" ]
[ 5, 2, 2 ]
[]
[]
[ "python", "syntactic_sugar" ]
stackoverflow_0003066668_python_syntactic_sugar.txt
Q: How to speed-up nested loop? I'm performing a nested loop in python that is included below. This serves as a basic way of searching through existing financial time series and looking for periods in the time series that match certain characteristics. In this case there are two separate, equally sized, arrays representing the 'close' (i.e. the price of an asset) and the 'volume' (i.e. the amount of the asset that was exchanged over the period). For each period in time I would like to look forward at all future intervals with lengths between 1 and INTERVAL_LENGTH and see if any of those intervals have characteristics that match my search (in this case the ratio of the close values is greater than 1.0001 and less than 1.5 and the summed volume is greater than 100). My understanding is that one of the major reasons for the speedup when using NumPy is that the interpreter doesn't need to type-check the operands each time it evaluates something so long as you're operating on the array as a whole (e.g. numpy_array * 2), but obviously the code below is not taking advantage of that. Is there a way to replace the internal loop with some kind of window function which could result in a speedup, or any other way using numpy/scipy to speed this up substantially in native python? Alternatively, is there a better way to do this in general (e.g. will it be much faster to write this loop in C++ and use weave)? ARRAY_LENGTH = 500000 INTERVAL_LENGTH = 15 close = np.array( xrange(ARRAY_LENGTH) ) volume = np.array( xrange(ARRAY_LENGTH) ) close, volume = close.astype('float64'), volume.astype('float64') results = [] for i in xrange(len(close) - INTERVAL_LENGTH): for j in xrange(i+1, i+INTERVAL_LENGTH): ret = close[j] / close[i] vol = sum( volume[i+1:j+1] ) if ret > 1.0001 and ret < 1.5 and vol > 100: results.append( [i, j, ret, vol] ) print results A: Update: (almost) completely vectorized version below in "new_function2"... I'll add comments to explain things in a bit. It gives a ~50x speedup, and a larger speedup is possible if you're okay with the output being numpy arrays instead of lists. As is: In [86]: %timeit new_function2(close, volume, INTERVAL_LENGTH) 1 loops, best of 3: 1.15 s per loop You can replace your inner loop with a call to np.cumsum()... See my "new_function" function below. This gives a considerable speedup... In [61]: %timeit new_function(close, volume, INTERVAL_LENGTH) 1 loops, best of 3: 15.7 s per loop vs In [62]: %timeit old_function(close, volume, INTERVAL_LENGTH) 1 loops, best of 3: 53.1 s per loop It should be possible to vectorize the entire thing and avoid for loops entirely, though... Give me an minute, and I'll see what I can do... import numpy as np ARRAY_LENGTH = 500000 INTERVAL_LENGTH = 15 close = np.arange(ARRAY_LENGTH, dtype=np.float) volume = np.arange(ARRAY_LENGTH, dtype=np.float) def old_function(close, volume, INTERVAL_LENGTH): results = [] for i in xrange(len(close) - INTERVAL_LENGTH): for j in xrange(i+1, i+INTERVAL_LENGTH): ret = close[j] / close[i] vol = sum( volume[i+1:j+1] ) if (ret > 1.0001) and (ret < 1.5) and (vol > 100): results.append( (i, j, ret, vol) ) return results def new_function(close, volume, INTERVAL_LENGTH): results = [] for i in xrange(close.size - INTERVAL_LENGTH): vol = volume[i+1:i+INTERVAL_LENGTH].cumsum() ret = close[i+1:i+INTERVAL_LENGTH] / close[i] filter = (ret > 1.0001) & (ret < 1.5) & (vol > 100) j = np.arange(i+1, i+INTERVAL_LENGTH)[filter] tmp_results = zip(j.size * [i], j, ret[filter], vol[filter]) results.extend(tmp_results) return results def new_function2(close, volume, INTERVAL_LENGTH): vol, ret = [], [] I, J = [], [] for k in xrange(1, INTERVAL_LENGTH): start = k end = volume.size - INTERVAL_LENGTH + k vol.append(volume[start:end]) ret.append(close[start:end]) J.append(np.arange(start, end)) I.append(np.arange(volume.size - INTERVAL_LENGTH)) vol = np.vstack(vol) ret = np.vstack(ret) J = np.vstack(J) I = np.vstack(I) vol = vol.cumsum(axis=0) ret = ret / close[:-INTERVAL_LENGTH] filter = (ret > 1.0001) & (ret < 1.5) & (vol > 100) vol = vol[filter] ret = ret[filter] I = I[filter] J = J[filter] output = zip(I.flat,J.flat,ret.flat,vol.flat) return output results = old_function(close, volume, INTERVAL_LENGTH) results2 = new_function(close, volume, INTERVAL_LENGTH) results3 = new_function(close, volume, INTERVAL_LENGTH) # Using sets to compare, as the output # is in a different order than the original function print set(results) == set(results2) print set(results) == set(results3) A: One speedup would be to remove the sum portion, as in this implementation it sums a list of length 2 through INTERVAL_LENGTH. Instead, just add volume[j+1] to the previous result of vol from the last iteration of the loop. Thus, you're just adding two integers each time instead of summing an entire list AND slicing it each time. Also, instead of starting by doing sum(volume[i+1:j+1]), just do vol = volume[i+1] + volume[j+1], as you know the initial case here will always be just two indices. Another speedup would be to use .extend instead of .append, as the python implementation has extend running significantly faster. You could also break up the final if statement so as to only do certain computation if required. For instance, you know if vol <= 100, you don't need to compute ret. This doesn't answer your problem exactly, but I think especially with the sum issue that you should see significant speedups with these changes. Edit - you also don't need len, since you know specifically the length of the list already (unless that was just for the example). Defining it as a number rather than len(something) is always faster. Edit - implementation (this is untested): ARRAY_LENGTH = 500000 INTERVAL_LENGTH = 15 close = np.array( xrange(ARRAY_LENGTH) ) volume = np.array( xrange(ARRAY_LENGTH) ) close, volume = close.astype('float64'), volume.astype('float64') results = [] ex = results.extend for i in xrange(ARRAY_LENGTH - INTERVAL_LENGTH): vol = volume[i+1] for j in xrange(i+1, i+INTERVAL_LENGTH): vol += volume[j+1] if vol > 100: ret = close[j] / close[i] if 1.0001 < ret < 1.5: ex( [i, j, ret, vol] ) print results A: Why don't you try to generate the result as a single list (much faster than appending or extending), something like: results = [ t for t in ( (i, j, close[j]/close[i], sum(volume[i+1:j+1])) for i in xrange(len(close)-INT_LEN) for j in xrange(i+1, i+INT_LEN) ) if t[3] > 100 and 1.0001 < t[2] < 1.5 ]
How to speed-up nested loop?
I'm performing a nested loop in python that is included below. This serves as a basic way of searching through existing financial time series and looking for periods in the time series that match certain characteristics. In this case there are two separate, equally sized, arrays representing the 'close' (i.e. the price of an asset) and the 'volume' (i.e. the amount of the asset that was exchanged over the period). For each period in time I would like to look forward at all future intervals with lengths between 1 and INTERVAL_LENGTH and see if any of those intervals have characteristics that match my search (in this case the ratio of the close values is greater than 1.0001 and less than 1.5 and the summed volume is greater than 100). My understanding is that one of the major reasons for the speedup when using NumPy is that the interpreter doesn't need to type-check the operands each time it evaluates something so long as you're operating on the array as a whole (e.g. numpy_array * 2), but obviously the code below is not taking advantage of that. Is there a way to replace the internal loop with some kind of window function which could result in a speedup, or any other way using numpy/scipy to speed this up substantially in native python? Alternatively, is there a better way to do this in general (e.g. will it be much faster to write this loop in C++ and use weave)? ARRAY_LENGTH = 500000 INTERVAL_LENGTH = 15 close = np.array( xrange(ARRAY_LENGTH) ) volume = np.array( xrange(ARRAY_LENGTH) ) close, volume = close.astype('float64'), volume.astype('float64') results = [] for i in xrange(len(close) - INTERVAL_LENGTH): for j in xrange(i+1, i+INTERVAL_LENGTH): ret = close[j] / close[i] vol = sum( volume[i+1:j+1] ) if ret > 1.0001 and ret < 1.5 and vol > 100: results.append( [i, j, ret, vol] ) print results
[ "Update: (almost) completely vectorized version below in \"new_function2\"... \nI'll add comments to explain things in a bit. \nIt gives a ~50x speedup, and a larger speedup is possible if you're okay with the output being numpy arrays instead of lists. As is:\nIn [86]: %timeit new_function2(close, volume, INTERVAL_LENGTH)\n1 loops, best of 3: 1.15 s per loop\n\nYou can replace your inner loop with a call to np.cumsum()... See my \"new_function\" function below. This gives a considerable speedup...\nIn [61]: %timeit new_function(close, volume, INTERVAL_LENGTH)\n1 loops, best of 3: 15.7 s per loop\n\nvs\nIn [62]: %timeit old_function(close, volume, INTERVAL_LENGTH)\n1 loops, best of 3: 53.1 s per loop\n\nIt should be possible to vectorize the entire thing and avoid for loops entirely, though... Give me an minute, and I'll see what I can do...\nimport numpy as np\n\nARRAY_LENGTH = 500000\nINTERVAL_LENGTH = 15\nclose = np.arange(ARRAY_LENGTH, dtype=np.float)\nvolume = np.arange(ARRAY_LENGTH, dtype=np.float)\n\ndef old_function(close, volume, INTERVAL_LENGTH):\n results = []\n for i in xrange(len(close) - INTERVAL_LENGTH):\n for j in xrange(i+1, i+INTERVAL_LENGTH):\n ret = close[j] / close[i]\n vol = sum( volume[i+1:j+1] )\n if (ret > 1.0001) and (ret < 1.5) and (vol > 100):\n results.append( (i, j, ret, vol) )\n return results\n\n\ndef new_function(close, volume, INTERVAL_LENGTH):\n results = []\n for i in xrange(close.size - INTERVAL_LENGTH):\n vol = volume[i+1:i+INTERVAL_LENGTH].cumsum()\n ret = close[i+1:i+INTERVAL_LENGTH] / close[i]\n\n filter = (ret > 1.0001) & (ret < 1.5) & (vol > 100)\n j = np.arange(i+1, i+INTERVAL_LENGTH)[filter]\n\n tmp_results = zip(j.size * [i], j, ret[filter], vol[filter])\n results.extend(tmp_results)\n return results\n\ndef new_function2(close, volume, INTERVAL_LENGTH):\n vol, ret = [], []\n I, J = [], []\n for k in xrange(1, INTERVAL_LENGTH):\n start = k\n end = volume.size - INTERVAL_LENGTH + k\n vol.append(volume[start:end])\n ret.append(close[start:end])\n J.append(np.arange(start, end))\n I.append(np.arange(volume.size - INTERVAL_LENGTH))\n\n vol = np.vstack(vol)\n ret = np.vstack(ret)\n J = np.vstack(J)\n I = np.vstack(I)\n\n vol = vol.cumsum(axis=0)\n ret = ret / close[:-INTERVAL_LENGTH]\n\n filter = (ret > 1.0001) & (ret < 1.5) & (vol > 100)\n\n vol = vol[filter]\n ret = ret[filter]\n I = I[filter]\n J = J[filter]\n\n output = zip(I.flat,J.flat,ret.flat,vol.flat)\n return output\n\nresults = old_function(close, volume, INTERVAL_LENGTH)\nresults2 = new_function(close, volume, INTERVAL_LENGTH)\nresults3 = new_function(close, volume, INTERVAL_LENGTH)\n\n# Using sets to compare, as the output \n# is in a different order than the original function\nprint set(results) == set(results2)\nprint set(results) == set(results3)\n\n", "One speedup would be to remove the sum portion, as in this implementation it sums a list of length 2 through INTERVAL_LENGTH. Instead, just add volume[j+1] to the previous result of vol from the last iteration of the loop. Thus, you're just adding two integers each time instead of summing an entire list AND slicing it each time. Also, instead of starting by doing sum(volume[i+1:j+1]), just do vol = volume[i+1] + volume[j+1], as you know the initial case here will always be just two indices.\nAnother speedup would be to use .extend instead of .append, as the python implementation has extend running significantly faster.\nYou could also break up the final if statement so as to only do certain computation if required. For instance, you know if vol <= 100, you don't need to compute ret.\nThis doesn't answer your problem exactly, but I think especially with the sum issue that you should see significant speedups with these changes.\nEdit - you also don't need len, since you know specifically the length of the list already (unless that was just for the example). Defining it as a number rather than len(something) is always faster.\nEdit - implementation (this is untested):\nARRAY_LENGTH = 500000\nINTERVAL_LENGTH = 15\nclose = np.array( xrange(ARRAY_LENGTH) )\nvolume = np.array( xrange(ARRAY_LENGTH) )\nclose, volume = close.astype('float64'), volume.astype('float64')\n\nresults = []\nex = results.extend\nfor i in xrange(ARRAY_LENGTH - INTERVAL_LENGTH):\n vol = volume[i+1]\n for j in xrange(i+1, i+INTERVAL_LENGTH):\n vol += volume[j+1]\n if vol > 100:\n ret = close[j] / close[i]\n if 1.0001 < ret < 1.5:\n ex( [i, j, ret, vol] )\nprint results\n\n", "Why don't you try to generate the result as a single list (much faster than appending or extending), something like:\nresults = [ t for t in ( (i, j, close[j]/close[i], sum(volume[i+1:j+1]))\n for i in xrange(len(close)-INT_LEN)\n for j in xrange(i+1, i+INT_LEN)\n )\n if t[3] > 100 and 1.0001 < t[2] < 1.5\n ]\n\n" ]
[ 7, 3, 1 ]
[]
[]
[ "finance", "numpy", "python", "scipy" ]
stackoverflow_0003065624_finance_numpy_python_scipy.txt
Q: Python access an object byref / Need tagging I need to suck data from stdin and create a object. The incoming data is between 5 and 10 lines long. Each line has a process number and either an IP address or a hash. For example: pid=123 ip=192.168.0.1 - some data pid=123 hash=ABCDEF0123 - more data hash=ABCDEF123 - More data ip=192.168.0.1 - even more data I need to put this data into a class like: class MyData(): pid = None hash = None ip = None lines = [] I need to be able to look up the object by IP, HASH, or PID. The tough part is that there are multiple streams of data intermixed coming from stdin. (There could be hundreds or thousands of processes writing data at the same time.) I have regular expressions pulling out the PID, IP, and HASH that I need, but how can I access the object by any of those values? My thought was to do something like this: myarray = {} for each line in sys.stdin.readlines(): if pid and ip: #If we can get a PID out of the line myarray[pid] = MyData().pid = pid #Create a new MyData object, assign the PID, and stick it in myarray accessible by PID. myarray[pid].ip = ip #Add the IP address to the new object myarray[pid].lines.append(data) #Append the data myarray[ip] = myarray[pid] #Take the object by PID and create a key from the IP. <snip>do something similar for pid and hash, hash and ip, etc...</snip> This gives my an array with two keys (a PID and an IP) and they both point to the same object. But on the next iteration of the loop, if I find (for example) an IP and HASH and do: myarray[hash] = myarray[ip] The following is False: myarray[hash] == myarray[ip] Hopefully that was clear. I hate to admit that waaay back in the VB days, I remember being able handle objects byref instead of byval. Is there something similar in Python? Or am I just approaching this wrong? A: Python only has references. Create the object once, and add it to all relevant keys at once. class MyData(object): def __init__(self, pid, ip, hash): self.pid = pid ... for line in sys.stdin: pid, ip, hash = process(line) obj = MyData(pid=pid, ip=ip, hash=hash) if pid: mydict[pid] = obj if ip: mydict[ip] = obj if hash: mydict[hash] = obj A: Make two separate dicts (and don't call them arrays!), byip and byhash -- why do you need to smoosh everything together and risk conflicts?! BTW, you't possibly can have the following two lines back to back: myarray[hash] = myarray[ip] assert not(myarray[hash] == myarray[ip]) To make the assert hold you must be doing something else in between (perturbing the misnamed myarray). BTW squared, assignments in Python are always by reference to an object -- if you want a copy you must explicitly ask for one.
Python access an object byref / Need tagging
I need to suck data from stdin and create a object. The incoming data is between 5 and 10 lines long. Each line has a process number and either an IP address or a hash. For example: pid=123 ip=192.168.0.1 - some data pid=123 hash=ABCDEF0123 - more data hash=ABCDEF123 - More data ip=192.168.0.1 - even more data I need to put this data into a class like: class MyData(): pid = None hash = None ip = None lines = [] I need to be able to look up the object by IP, HASH, or PID. The tough part is that there are multiple streams of data intermixed coming from stdin. (There could be hundreds or thousands of processes writing data at the same time.) I have regular expressions pulling out the PID, IP, and HASH that I need, but how can I access the object by any of those values? My thought was to do something like this: myarray = {} for each line in sys.stdin.readlines(): if pid and ip: #If we can get a PID out of the line myarray[pid] = MyData().pid = pid #Create a new MyData object, assign the PID, and stick it in myarray accessible by PID. myarray[pid].ip = ip #Add the IP address to the new object myarray[pid].lines.append(data) #Append the data myarray[ip] = myarray[pid] #Take the object by PID and create a key from the IP. <snip>do something similar for pid and hash, hash and ip, etc...</snip> This gives my an array with two keys (a PID and an IP) and they both point to the same object. But on the next iteration of the loop, if I find (for example) an IP and HASH and do: myarray[hash] = myarray[ip] The following is False: myarray[hash] == myarray[ip] Hopefully that was clear. I hate to admit that waaay back in the VB days, I remember being able handle objects byref instead of byval. Is there something similar in Python? Or am I just approaching this wrong?
[ "Python only has references.\nCreate the object once, and add it to all relevant keys at once.\nclass MyData(object):\n def __init__(self, pid, ip, hash):\n self.pid = pid\n ...\n\nfor line in sys.stdin:\n pid, ip, hash = process(line)\n obj = MyData(pid=pid, ip=ip, hash=hash)\n if pid:\n mydict[pid] = obj\n if ip:\n mydict[ip] = obj\n if hash:\n mydict[hash] = obj\n\n", "Make two separate dicts (and don't call them arrays!), byip and byhash -- why do you need to smoosh everything together and risk conflicts?!\nBTW, you't possibly can have the following two lines back to back:\nmyarray[hash] = myarray[ip]\nassert not(myarray[hash] == myarray[ip])\n\nTo make the assert hold you must be doing something else in between (perturbing the misnamed myarray).\nBTW squared, assignments in Python are always by reference to an object -- if you want a copy you must explicitly ask for one.\n" ]
[ 2, 2 ]
[]
[]
[ "byref", "object", "python", "tags" ]
stackoverflow_0003067220_byref_object_python_tags.txt
Q: Render page initially and update via AJAX using the same template HTML Let's say you have a view called "View Story" which is just a web page rendered on the backend via Python/Django. On that page there's a list of comments at the bottom rendered as part of the "View Story" template using Django's templating system (in a loop). This page also allows you to add a comment to the list. This is done through AJAX and the page is updated with the new comment (without sending a new full page request). Now, when adding the new comment to the end of the list I want the HTML that's generated for this new comment (something inside an <li>) to use the exact same code that was used to generate the original comments sent to the client via the original request. There's multiple ways to do this: Have the initial rendering throw the comment data into a javascript variable and once the page is rendered add the content via javascript. Then when new comments are added that same javascript can be used to render the new one. The problem: from a search engine perspective I'm not sure google would be able to index the comments if they're generated after the page has been rendered - I'm guessing not Each time a new comment is added via AJAX, have the ajax request return the actual HTML to put on the page rather than just the JSON data of the new comment. The HTML can be generated using the same template snippet that was used to render the original page. The problem with this is that it ties that AJAX request to a particular view or a way of rendering it which I don't like. Similar to #2 except that a separate request is made to retrieve the HTML for the new comment or maybe all the comments and the list is just wiped and re-rendered. Don't like that cause it's deeply inefficient and unnecessarily time-consuming. So, to summarize, I want a way to avoid duplicating Template/HTML code for a single view. And I would like some advice on what has worked for others because I'm pretty sure this is a common case irregardless of the technology on the back-end. Thanks! A: Here is what you should do: view_story.html: bla bla bla Comments: <ul id="comments"> {% for comment in comments %} <li>{% include "comment_item.html" %}</li> {% endfor %} </ul> <from>Ajax form here</form> than you need to create view for adding comments(ajax): def add_comment(request): comment = Comment(...) return render_to_response('comment_item.html', {'comment': comment}) So after you submit your ajax query to add_comment view you will get the content of the comment(one comment).. after that just push it to list.. f.e. using jQuery like this: $('ul#comments').append('<li>'+comment_content+'</li>') A: I think option 2 is best. It's incremental (only renders one more comment when a comment is added), and re-uses the rendering. If you don't like returning just HTML from an Ajax request, then have the response be a JSON structure which includes the HTML as just one component. Then you can also carry status (or whatever) without an extra request to get the HTML. Option 1 is wasteful: the server should render the page as it should first appear. Option 3 is also wasteful: why make two requests to add a single comment? A: There is also option 4: Copy an existing element in the list and change its values. This is of course less flexible than templates. You can copy a hidden element instead to handle the case where the list is empty. You could also try option 2b: Generate the HTML on the server like option 2, but instead of directly accessing the database, pass the generation routine the JSON (or an object that can easily be converted to JSON). This involves more work, but means that you are effectively writing an API at the same time you are writing your own website. Option 1 is what any non-web application would use. Even though search engines are improving in their ability to handle AJAX, it is still strongly recommended to return all the content in HTML. I think Javascript is fast enough in all modern browsers that except for huge pages 1 would be quite reasonable except for the SEO issue. There is also option 5 - use Javascript on the server to generate the page and use the same code on the client. This is probably the most complicated approach and I wouldn't recommend it unless you really have a good reason.
Render page initially and update via AJAX using the same template HTML
Let's say you have a view called "View Story" which is just a web page rendered on the backend via Python/Django. On that page there's a list of comments at the bottom rendered as part of the "View Story" template using Django's templating system (in a loop). This page also allows you to add a comment to the list. This is done through AJAX and the page is updated with the new comment (without sending a new full page request). Now, when adding the new comment to the end of the list I want the HTML that's generated for this new comment (something inside an <li>) to use the exact same code that was used to generate the original comments sent to the client via the original request. There's multiple ways to do this: Have the initial rendering throw the comment data into a javascript variable and once the page is rendered add the content via javascript. Then when new comments are added that same javascript can be used to render the new one. The problem: from a search engine perspective I'm not sure google would be able to index the comments if they're generated after the page has been rendered - I'm guessing not Each time a new comment is added via AJAX, have the ajax request return the actual HTML to put on the page rather than just the JSON data of the new comment. The HTML can be generated using the same template snippet that was used to render the original page. The problem with this is that it ties that AJAX request to a particular view or a way of rendering it which I don't like. Similar to #2 except that a separate request is made to retrieve the HTML for the new comment or maybe all the comments and the list is just wiped and re-rendered. Don't like that cause it's deeply inefficient and unnecessarily time-consuming. So, to summarize, I want a way to avoid duplicating Template/HTML code for a single view. And I would like some advice on what has worked for others because I'm pretty sure this is a common case irregardless of the technology on the back-end. Thanks!
[ "Here is what you should do:\nview_story.html:\nbla bla bla\n\nComments:\n<ul id=\"comments\">\n{% for comment in comments %}\n <li>{% include \"comment_item.html\" %}</li>\n{% endfor %}\n</ul>\n<from>Ajax form here</form>\n\nthan you need to create view for adding comments(ajax):\ndef add_comment(request):\n comment = Comment(...)\n return render_to_response('comment_item.html', {'comment': comment})\n\nSo after you submit your ajax query to add_comment view you will get the content of the comment(one comment).. after that just push it to list.. f.e. using jQuery like this:\n$('ul#comments').append('<li>'+comment_content+'</li>')\n\n", "I think option 2 is best. It's incremental (only renders one more comment when a comment is added), and re-uses the rendering. If you don't like returning just HTML from an Ajax request, then have the response be a JSON structure which includes the HTML as just one component. Then you can also carry status (or whatever) without an extra request to get the HTML.\nOption 1 is wasteful: the server should render the page as it should first appear.\nOption 3 is also wasteful: why make two requests to add a single comment?\n", "There is also option 4:\nCopy an existing element in the list and change its values. This is of course less flexible than templates. You can copy a hidden element instead to handle the case where the list is empty.\nYou could also try option 2b: \nGenerate the HTML on the server like option 2, but instead of directly accessing the database, pass the generation routine the JSON (or an object that can easily be converted to JSON). This involves more work, but means that you are effectively writing an API at the same time you are writing your own website.\nOption 1 is what any non-web application would use. Even though search engines are improving in their ability to handle AJAX, it is still strongly recommended to return all the content in HTML. I think Javascript is fast enough in all modern browsers that except for huge pages 1 would be quite reasonable except for the SEO issue.\nThere is also option 5 - use Javascript on the server to generate the page and use the same code on the client. This is probably the most complicated approach and I wouldn't recommend it unless you really have a good reason.\n" ]
[ 6, 3, 1 ]
[]
[]
[ "ajax", "django", "javascript", "python" ]
stackoverflow_0001718784_ajax_django_javascript_python.txt
Q: Update facebook status using pyfacebook offline access I'm trying to update a user status from a django python app. The user went thru facebook connect and registers to the app. I got sessionkey and fbuid. fb = Facebook(FACEBOOK_API_KEY, FACEBOOK_SECRET_KEY) if fbsessionkey: fb.session_key = fbsessionkey fb.uid = fbuid fb.auth.createToken() fb.auth.getSession() #update the facebook status fb.users.setStatus(status="testing",clear=False) else: pass What am i doing wrong? im getting: Error 104: Incorrect signature Please note the user already granted offline access also. Please help... A: You have to add signature. It is MD5 hash of the current request and your secret key. I was mistaken about the issue first sorry :p Please check http://wiki.developers.facebook.com/index.php/Users.setStatus and know about how to get the signature
Update facebook status using pyfacebook offline access
I'm trying to update a user status from a django python app. The user went thru facebook connect and registers to the app. I got sessionkey and fbuid. fb = Facebook(FACEBOOK_API_KEY, FACEBOOK_SECRET_KEY) if fbsessionkey: fb.session_key = fbsessionkey fb.uid = fbuid fb.auth.createToken() fb.auth.getSession() #update the facebook status fb.users.setStatus(status="testing",clear=False) else: pass What am i doing wrong? im getting: Error 104: Incorrect signature Please note the user already granted offline access also. Please help...
[ "You have to add signature. It is MD5 hash of the current request and your secret key. I was mistaken about the issue first sorry :p\nPlease check http://wiki.developers.facebook.com/index.php/Users.setStatus and know about how to get the signature\n" ]
[ 0 ]
[]
[]
[ "facebook", "python" ]
stackoverflow_0003002308_facebook_python.txt
Q: Not getting exact result in python with the values leading zero. Please tell me what is going on there zipcode = 02132 print zipcode result = 1114 A: A leading zero means octal. 2132 in octal equals 1114 in decimal. They removed this behavior in Python 3.0. A: In Python 2.x, number with a leading zero is interpreted as octal (base-eight). Python 3.x requires a leading "0o" to indicate an octal number. You probably want to treat a zipcode as a string to keep the leading zeroes intact. A: Quite apart from the octal caper: Zip codes, social security "numbers", credit card "numbers", phone "numbers", etc are NOT numbers in the sense that you can do meaningful arithmetic on them, so don't keep them as integers, keep them as strings. A: The leading 0 makes it assume 02132 is octal. A: leading zero means octal as other have said. one way to keep your zero is to strip the leading zeros and just use a zero padded string when you display it, >>> myInt = 2132 >>> print myInt 2132 >>> myString = "%05d" % myInt >>> print myString 02132 >>> print int(myString) 2132 you probably get the idea. A: What is your question? I guess, why is that. The answer is octal numbers. If a number starts with a zero, Python thinks you mean an octal number. (Base 8)
Not getting exact result in python with the values leading zero. Please tell me what is going on there
zipcode = 02132 print zipcode result = 1114
[ "A leading zero means octal. 2132 in octal equals 1114 in decimal.\nThey removed this behavior in Python 3.0.\n", "In Python 2.x, number with a leading zero is interpreted as octal (base-eight). Python 3.x requires a leading \"0o\" to indicate an octal number. You probably want to treat a zipcode as a string to keep the leading zeroes intact.\n", "Quite apart from the octal caper:\nZip codes, social security \"numbers\", credit card \"numbers\", phone \"numbers\", etc are NOT numbers in the sense that you can do meaningful arithmetic on them, so don't keep them as integers, keep them as strings.\n", "The leading 0 makes it assume 02132 is octal.\n", "leading zero means octal as other have said. one way to keep your zero is to strip the leading zeros and just use a zero padded string when you display it,\n\n>>> myInt = 2132\n>>> print myInt\n2132\n>>> myString = \"%05d\" % myInt\n>>> print myString\n02132\n>>> print int(myString)\n2132\n\nyou probably get the idea.\n", "What is your question? I guess, why is that. The answer is octal numbers. If a number starts with a zero, Python thinks you mean an octal number. (Base 8)\n" ]
[ 15, 9, 6, 5, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003067409_python.txt
Q: How to transfer url parameters to repoze custom predicate checkers I would like to create a repoze custom predicate checker that is capable to access url parameters and validate something. But I would like to use allow_only to set this permission checker in all the controller's scope. Something like: class MyController(BaseController): allow_only = All(not_anonymous(msg=l_(u'You must be logged on')), my_custom_predicate(msg=l_(u'something wrong'))) def index(self, **kw): return dict() then, my_custom_predicate should check the url paramters for every request in every MyController method, and do whatever it do. The problem is just that: how to allow my_custom_predicate to check the url parameters, using it in that way I wrote above. A: May be you need to use ControllerProtector from repoze.what.plugins.pylonshq import ControllerProtector allow_only = All(not_anonymous(msg=l_(u'You must be logged on')), my_custom_predicate(msg=l_(u'something wrong'))) @ControllerProtector(allow_only) class MyController(BaseController): def index(self, **kw): return dict() See docs at http://code.gustavonarea.net/repoze.what-pylons/API.html
How to transfer url parameters to repoze custom predicate checkers
I would like to create a repoze custom predicate checker that is capable to access url parameters and validate something. But I would like to use allow_only to set this permission checker in all the controller's scope. Something like: class MyController(BaseController): allow_only = All(not_anonymous(msg=l_(u'You must be logged on')), my_custom_predicate(msg=l_(u'something wrong'))) def index(self, **kw): return dict() then, my_custom_predicate should check the url paramters for every request in every MyController method, and do whatever it do. The problem is just that: how to allow my_custom_predicate to check the url parameters, using it in that way I wrote above.
[ "May be you need to use ControllerProtector\nfrom repoze.what.plugins.pylonshq import ControllerProtector\n\nallow_only = All(not_anonymous(msg=l_(u'You must be logged on')),\n my_custom_predicate(msg=l_(u'something wrong')))\n\n@ControllerProtector(allow_only)\nclass MyController(BaseController):\n\n def index(self, **kw):\n return dict()\n\nSee docs at http://code.gustavonarea.net/repoze.what-pylons/API.html\n" ]
[ 0 ]
[]
[]
[ "authentication", "permissions", "python", "repoze.who", "turbogears2" ]
stackoverflow_0003064576_authentication_permissions_python_repoze.who_turbogears2.txt
Q: Extending Django Flatpages to accept template tags I use django flatpages for a lot of content on our site, I'd like to extend it to accept django template tags in the content as well. I found this snippet but after much larking about I couldn't get it to work. Am I correct in assuming that you would need too "subclass" the django flatpages app to get this to work? Is this best way of doing it? I'm not quite sure how to structure it, as I don't really want to directly modify the django distribution. A: 1. A simple page view wich will render template tags by loading a template for each page: in url.py url(r'^page/(?P<slug>.*)/$','my_app.views.page_detail', name='page_url'), in my_app/views.py def page_detail (request, slug): return render_to_response('page/' + slug + '.html', {}, context_instance=RequestContext(request)) 2. Another method with flat pages stored in database, is to use a "template evaluation tag" in your template like this one. edit You just have to modify flatpages template like this: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html> <head> <title>{{ flatpage.title }}</title> </head> <body> {% load evaluate_tag %} {% evaluate flatpage.content %} </body> </html> A: An alternative approach could be to write a simple app based on the direct_to_template generic view.
Extending Django Flatpages to accept template tags
I use django flatpages for a lot of content on our site, I'd like to extend it to accept django template tags in the content as well. I found this snippet but after much larking about I couldn't get it to work. Am I correct in assuming that you would need too "subclass" the django flatpages app to get this to work? Is this best way of doing it? I'm not quite sure how to structure it, as I don't really want to directly modify the django distribution.
[ "1. A simple page view wich will render template tags by loading a template for each page:\nin url.py\nurl(r'^page/(?P<slug>.*)/$','my_app.views.page_detail', name='page_url'),\n\nin my_app/views.py\ndef page_detail (request, slug):\n return render_to_response('page/' + slug + '.html', {},\n context_instance=RequestContext(request))\n\n2. Another method with flat pages stored in database, is to use a \"template evaluation tag\" in your template like this one.\nedit You just have to modify flatpages template like this:\n<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"\n \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n<html>\n<head>\n<title>{{ flatpage.title }}</title>\n</head>\n<body>\n{% load evaluate_tag %} \n{% evaluate flatpage.content %} \n</body>\n</html>\n\n", "An alternative approach could be to write a simple app based on the direct_to_template generic view.\n" ]
[ 8, 0 ]
[]
[]
[ "django", "django_flatpages", "python" ]
stackoverflow_0003066270_django_django_flatpages_python.txt
Q: Jython java call throws exception asking for 2 args when only one arg is coded I have an Java method I want to call within my Jython servlet running on tomcat5. It looks like this: @SuppressWarnings("unchecked") public School loadByName(String name) { List<School> school; school = getHibernateTemplate().find("from " + getPersistentClass().getName() + " where name = ?", name); return uniqueResult(school); } I call it in Jython using: foobar = SchoolDAOHibernate.loadByName('University') It throws an error that says loadByName() expects 2 args; got 1. What other argument could it be looking for? If i try to create an instance first such as: foo = com.dc.sports.dao.hibernate.SchoolDaoHibernate() foo.loadByName('University') The first call throws an exception saying: No visible constructors for class (com.dc.sports.dao.hibernate.SchoolDaoHibernate) I'm assuming this is because it is a private-package: package com.dc.sports.dao.hibernate; ... @SuppressWarnings("unchecked") class SchoolDaoHibernate extends AbstractDaoHibernate<School> implements SchoolDao { So how can I get at the method? A: loadByName is not static. You need a instance to call it. sdh = SchoolDAOHibernate(...) # ... any args for construction ?? sdh.loadByName('Univeristy') # 2 args :-) self (sdh) and 'University' clearer ? A: Because the loadByName method isn't static, Jython might be expecting the first argument to be an instance of SchoolDAOHibernate. If it makes sense for your design, make that method static.
Jython java call throws exception asking for 2 args when only one arg is coded
I have an Java method I want to call within my Jython servlet running on tomcat5. It looks like this: @SuppressWarnings("unchecked") public School loadByName(String name) { List<School> school; school = getHibernateTemplate().find("from " + getPersistentClass().getName() + " where name = ?", name); return uniqueResult(school); } I call it in Jython using: foobar = SchoolDAOHibernate.loadByName('University') It throws an error that says loadByName() expects 2 args; got 1. What other argument could it be looking for? If i try to create an instance first such as: foo = com.dc.sports.dao.hibernate.SchoolDaoHibernate() foo.loadByName('University') The first call throws an exception saying: No visible constructors for class (com.dc.sports.dao.hibernate.SchoolDaoHibernate) I'm assuming this is because it is a private-package: package com.dc.sports.dao.hibernate; ... @SuppressWarnings("unchecked") class SchoolDaoHibernate extends AbstractDaoHibernate<School> implements SchoolDao { So how can I get at the method?
[ "loadByName is not static.\nYou need a instance to call it.\nsdh = SchoolDAOHibernate(...) # ... any args for construction ??\nsdh.loadByName('Univeristy') # 2 args :-) self (sdh) and 'University'\n\nclearer ?\n", "Because the loadByName method isn't static, Jython might be expecting the first argument to be an instance of SchoolDAOHibernate. If it makes sense for your design, make that method static.\n" ]
[ 2, 1 ]
[]
[]
[ "java", "jython", "python", "tomcat" ]
stackoverflow_0003067731_java_jython_python_tomcat.txt
Q: Screen overlay with Python, paint over an active window with background python script I'm writing a python script that runs in the background and takes screenshots of another application that is active. Then it analyses the screenshots and now it should overlay a certain image over the active app or the screen. I still need to be able to make mouse and keyboard inputs in the active app. So I need a way to overlay/paint on another window or on the screen, and still keep the other window the active window so that I can make inputs. I would prefer to do that with python in Mac OS, but if it isn't possible, other languages and even Windows (if really necessary) would also be ok. Can anybody help me? Thanks in advance! A: http://www.michaelfogleman.com/2009/12/drawing-on-the-windows-desktop-using-python-and-wxpython/ Seems to do what you want, but is windows only, as are some other answers to similar questions here on stackoverflow
Screen overlay with Python, paint over an active window with background python script
I'm writing a python script that runs in the background and takes screenshots of another application that is active. Then it analyses the screenshots and now it should overlay a certain image over the active app or the screen. I still need to be able to make mouse and keyboard inputs in the active app. So I need a way to overlay/paint on another window or on the screen, and still keep the other window the active window so that I can make inputs. I would prefer to do that with python in Mac OS, but if it isn't possible, other languages and even Windows (if really necessary) would also be ok. Can anybody help me? Thanks in advance!
[ "http://www.michaelfogleman.com/2009/12/drawing-on-the-windows-desktop-using-python-and-wxpython/\nSeems to do what you want, but is windows only, as are some other answers to similar questions here on stackoverflow\n" ]
[ 4 ]
[]
[]
[ "macos", "overlay", "paint", "python", "screen" ]
stackoverflow_0003067812_macos_overlay_paint_python_screen.txt
Q: Jython saying "No visible constructors for class" I have a jython servlet as part of a large application running in tomcat5. I tested a few Spring Framework classes and create the objects in the Jython servlet. When I try to create objects of classes in the application I catch an Exception message "No visible constructors for class". These java classes do have a public constructor class, such as: public SchoolImpl() { } I create the object in python: from com.dc.sports.entity import SchoolImpl ... school = SchoolImpl() What am I doing wrong? A: doublep / cluch answered the question :-) in the comment adding just a little info: From the Jython FAQ : 3.3 Why can't I execute a 'protected' or 'private' Java instance method or access a 'protected' or 'private' attribute in a Java package? By default, as in Java, these methods are protected from external access. Access to all Java fields and methods can be enabled with the python.security.respectJavaAccessibility registry setting: # Setting this to false will allow Jython to provide access to # non-public fields, methods, and constructors of Java objects. python.security.respectJavaAccessibility = false
Jython saying "No visible constructors for class"
I have a jython servlet as part of a large application running in tomcat5. I tested a few Spring Framework classes and create the objects in the Jython servlet. When I try to create objects of classes in the application I catch an Exception message "No visible constructors for class". These java classes do have a public constructor class, such as: public SchoolImpl() { } I create the object in python: from com.dc.sports.entity import SchoolImpl ... school = SchoolImpl() What am I doing wrong?
[ "doublep / cluch answered the question :-) in the comment \nadding just a little info:\nFrom the Jython FAQ :\n3.3 Why can't I execute a 'protected' or 'private' Java instance method or access a 'protected' or 'private' attribute in a Java package?\nBy default, as in Java, these methods are protected from external access. Access to all Java fields and methods can be enabled with the python.security.respectJavaAccessibility registry setting:\n# Setting this to false will allow Jython to provide access to\n# non-public fields, methods, and constructors of Java objects.\npython.security.respectJavaAccessibility = false\n\n" ]
[ 3 ]
[]
[]
[ "java", "jython", "python", "servlets", "tomcat" ]
stackoverflow_0003065573_java_jython_python_servlets_tomcat.txt
Q: A set union find algorithm I have thousands of lines of 1 to 100 numbers, every line define a group of numbers and a relationship among them. I need to get the sets of related numbers. Little Example: If I have this 7 lines of data T1 T2 T3 T4 T5 T6 T1 T5 T4 T3 T4 T7 I need a not so slow algorithm to know that the sets here are: T1 T2 T6 (because T1 is related with T2 in the first line and T1 related with T6 in the line 5) T3 T4 T5 T7 (because T5 is with T4 in line 6 and T3 is with T4 and T7 in line 7) but when you have very big sets is painfully slow to do a search of a T(x) in every big set, and do unions of sets... etc. Do you have a hint to do this in a not so brute force manner? I'm trying to do this in Python. A: Once you have built the data structure, exactly what queries do you want to run against it? Show us your existing code. What is a T(x)? You talk about "groups of numbers" but your sample data shows T1, T2, etc; please explain. Have you read this: http://en.wikipedia.org/wiki/Disjoint-set_data_structure Try looking at this Python implementation: http://code.activestate.com/recipes/215912-union-find-data-structure/ OR you can lash up something rather simple and understandable yourself, e.g. [Update: totally new code] class DisjointSet(object): def __init__(self): self.leader = {} # maps a member to the group's leader self.group = {} # maps a group leader to the group (which is a set) def add(self, a, b): leadera = self.leader.get(a) leaderb = self.leader.get(b) if leadera is not None: if leaderb is not None: if leadera == leaderb: return # nothing to do groupa = self.group[leadera] groupb = self.group[leaderb] if len(groupa) < len(groupb): a, leadera, groupa, b, leaderb, groupb = b, leaderb, groupb, a, leadera, groupa groupa |= groupb del self.group[leaderb] for k in groupb: self.leader[k] = leadera else: self.group[leadera].add(b) self.leader[b] = leadera else: if leaderb is not None: self.group[leaderb].add(a) self.leader[a] = leaderb else: self.leader[a] = self.leader[b] = a self.group[a] = set([a, b]) data = """T1 T2 T3 T4 T5 T1 T3 T6 T7 T8 T3 T7 T9 TA T1 T9""" # data is chosen to demonstrate each of 5 paths in the code from pprint import pprint as pp ds = DisjointSet() for line in data.splitlines(): x, y = line.split() ds.add(x, y) print print x, y pp(ds.leader) pp(ds.group) and here is the output from the last step: T1 T9 {'T1': 'T1', 'T2': 'T1', 'T3': 'T3', 'T4': 'T3', 'T5': 'T1', 'T6': 'T3', 'T7': 'T3', 'T8': 'T3', 'T9': 'T1', 'TA': 'T1'} {'T1': set(['T1', 'T2', 'T5', 'T9', 'TA']), 'T3': set(['T3', 'T4', 'T6', 'T7', 'T8'])} A: Treat your numbers T1, T2, etc. as graph vertices. Any two numbers appearing together on a line are joined by an edge. Then your problem amounts to finding all the connected components in this graph. You can do this by starting with T1, then doing a breadth-first or depth-first search to find all vertices reachable from that point. Mark all these vertices as belonging to equivalence class T1. Then find the next unmarked vertex Ti, find all the yet-unmarked nodes reachable from there, and label them as belonging to equivalence class Ti. Continue until all the vertices are marked. For a graph with n vertices and e edges, this algorithm requires O(e) time and space to build the adjacency lists, and O(n) time and space to identify all the connected components once the graph structure is built. A: You can use a union find data structure to achieve this goal. The pseudo code for such an algorithm is as follows: func find( var element ) while ( element is not the root ) element = element's parent return element end func func union( var setA, var setB ) var rootA = find( setA ), rootB = find( setB ) if ( rootA is equal to rootB ) return else set rootB as rootA's parent end func (Taken from http://www.algorithmist.com/index.php/Union_Find) A: As Jim pointed out above, you are essentially looking for the connected components of a simple undirected graph where the nodes are your entities (T1, T2 and so), and edges represent the pairwise relations between them. A simple implementation for connected component search is based on the breadth-first search: you start a BFS from the first entity, find all the related entities, then start another BFS from the first yet unfound entity and so on, until you have found them all. A simple implementation of BFS looks like this: class BreadthFirstSearch(object): """Breadth-first search implementation using an adjacency list""" def __init__(self, adj_list): self.adj_list = adj_list def run(self, start_vertex): """Runs a breadth-first search from the given start vertex and yields the visited vertices one by one.""" queue = deque([start_vertex]) visited = set([start_vertex]) adj_list = self.adj_list while queue: vertex = queue.popleft() yield vertex unseen_neis = adj_list[vertex]-visited visited.update(unseen_neis) queue.extend(unseen_neis) def connected_components(graph): seen_vertices = set() bfs = BreadthFirstSearch(graph) for start_vertex in graph: if start_vertex in seen_vertices: continue component = list(bfs.run(start_vertex)) yield component seen_vertices.update(component) Here, adj_list or graph is an adjacency list data structure, basically it gives you the neighbours of a given vertex in the graph. To build it from your file, you can do this: adj_list = defaultdict(set) for line in open("your_file.txt"): parts = line.strip().split() v1 = parts.pop(0) adj_list[v1].update(parts) for v2 in parts: adj_list[v2].add(v1) Then you can run: components = list(connected_components(adj_list)) Of course, implementing the whole algorithm in pure Python tends to be slower than an implementation in C with a more efficient graph data structure. You might consider using igraph or some other graph library like NetworkX to do the job instead. Both libraries contain implementations for connected component search; in igraph, it boils down to this (assuming that your file does not contain lines with single entries, only pairwise entries are accepted): >>> from igraph import load >>> graph = load("edge_list.txt", format="ncol", directed=False) >>> components = graph.clusters() >>> print graph.vs[components[0]]["name"] ['T1', 'T2', 'T6'] >>> print graph.vs[components[1]]["name"] ['T3', 'T4', 'T5'] Disclaimer: I am one of the authors of igraph A: You can model a group using a set. In the example below, I've put the set into a Group class to make it easier to keep references to them and to track some notional 'head' item. class Group: def __init__(self,head): self.members = set() self.head = head self.add(head) def add(self,member): self.members.add(member) def union(self,other): self.members = other.members.union(self.members) groups = {} for line in open("sets.dat"): line = line.split() if len(line) == 0: break # find the group of the first item on the row head = line[0] if head not in groups: group = Group(head) groups[head] = group else: group = groups[head] # for each other item on the row, merge the groups for node in line[1:]: if node not in groups: # its a new node, straight into the group group.add(node) groups[node] = group elif head not in groups[node].members: # merge two groups new_members = groups[node] group.union(new_members) for migrate in new_members.members: groups[migrate] = group # list them for k,v in groups.iteritems(): if k == v.head: print v.members Output is: set(['T6', 'T2', 'T1']) set(['T4', 'T5', 'T3'])
A set union find algorithm
I have thousands of lines of 1 to 100 numbers, every line define a group of numbers and a relationship among them. I need to get the sets of related numbers. Little Example: If I have this 7 lines of data T1 T2 T3 T4 T5 T6 T1 T5 T4 T3 T4 T7 I need a not so slow algorithm to know that the sets here are: T1 T2 T6 (because T1 is related with T2 in the first line and T1 related with T6 in the line 5) T3 T4 T5 T7 (because T5 is with T4 in line 6 and T3 is with T4 and T7 in line 7) but when you have very big sets is painfully slow to do a search of a T(x) in every big set, and do unions of sets... etc. Do you have a hint to do this in a not so brute force manner? I'm trying to do this in Python.
[ "Once you have built the data structure, exactly what queries do you want to run against it? Show us your existing code. What is a T(x)? You talk about \"groups of numbers\" but your sample data shows T1, T2, etc; please explain.\nHave you read this: http://en.wikipedia.org/wiki/Disjoint-set_data_structure\nTry looking at this Python implementation: http://code.activestate.com/recipes/215912-union-find-data-structure/\nOR you can lash up something rather simple and understandable yourself, e.g.\n[Update: totally new code]\nclass DisjointSet(object):\n\n def __init__(self):\n self.leader = {} # maps a member to the group's leader\n self.group = {} # maps a group leader to the group (which is a set)\n\n def add(self, a, b):\n leadera = self.leader.get(a)\n leaderb = self.leader.get(b)\n if leadera is not None:\n if leaderb is not None:\n if leadera == leaderb: return # nothing to do\n groupa = self.group[leadera]\n groupb = self.group[leaderb]\n if len(groupa) < len(groupb):\n a, leadera, groupa, b, leaderb, groupb = b, leaderb, groupb, a, leadera, groupa\n groupa |= groupb\n del self.group[leaderb]\n for k in groupb:\n self.leader[k] = leadera\n else:\n self.group[leadera].add(b)\n self.leader[b] = leadera\n else:\n if leaderb is not None:\n self.group[leaderb].add(a)\n self.leader[a] = leaderb\n else:\n self.leader[a] = self.leader[b] = a\n self.group[a] = set([a, b])\n\ndata = \"\"\"T1 T2\nT3 T4\nT5 T1\nT3 T6\nT7 T8\nT3 T7\nT9 TA\nT1 T9\"\"\"\n# data is chosen to demonstrate each of 5 paths in the code\nfrom pprint import pprint as pp\nds = DisjointSet()\nfor line in data.splitlines():\n x, y = line.split()\n ds.add(x, y)\n print\n print x, y\n pp(ds.leader)\n pp(ds.group)\n\nand here is the output from the last step:\nT1 T9\n{'T1': 'T1',\n 'T2': 'T1',\n 'T3': 'T3',\n 'T4': 'T3',\n 'T5': 'T1',\n 'T6': 'T3',\n 'T7': 'T3',\n 'T8': 'T3',\n 'T9': 'T1',\n 'TA': 'T1'}\n{'T1': set(['T1', 'T2', 'T5', 'T9', 'TA']),\n 'T3': set(['T3', 'T4', 'T6', 'T7', 'T8'])}\n\n", "Treat your numbers T1, T2, etc. as graph vertices. Any two numbers appearing together on a line are joined by an edge. Then your problem amounts to finding all the connected components in this graph. You can do this by starting with T1, then doing a breadth-first or depth-first search to find all vertices reachable from that point.\nMark all these vertices as belonging to equivalence class T1. Then find the next unmarked vertex Ti, find all the yet-unmarked nodes reachable from there, and label them as belonging to equivalence class Ti. Continue until all the vertices are marked.\nFor a graph with n vertices and e edges, this algorithm requires O(e) time and space to build the adjacency lists, and O(n) time and space to identify all the connected components\nonce the graph structure is built.\n", "You can use a union find data structure to achieve this goal.\nThe pseudo code for such an algorithm is as follows:\nfunc find( var element )\n while ( element is not the root ) element = element's parent\n return element\nend func\n\nfunc union( var setA, var setB )\n var rootA = find( setA ), rootB = find( setB )\n if ( rootA is equal to rootB ) return\n else\n set rootB as rootA's parent\nend func\n\n(Taken from http://www.algorithmist.com/index.php/Union_Find)\n", "As Jim pointed out above, you are essentially looking for the connected components of a simple undirected graph where the nodes are your entities (T1, T2 and so), and edges represent the pairwise relations between them. A simple implementation for connected component search is based on the breadth-first search: you start a BFS from the first entity, find all the related entities, then start another BFS from the first yet unfound entity and so on, until you have found them all. A simple implementation of BFS looks like this:\nclass BreadthFirstSearch(object):\n \"\"\"Breadth-first search implementation using an adjacency list\"\"\"\n\n def __init__(self, adj_list):\n self.adj_list = adj_list\n\n def run(self, start_vertex):\n \"\"\"Runs a breadth-first search from the given start vertex and\n yields the visited vertices one by one.\"\"\"\n queue = deque([start_vertex])\n visited = set([start_vertex])\n adj_list = self.adj_list\n\n while queue:\n vertex = queue.popleft()\n yield vertex\n unseen_neis = adj_list[vertex]-visited\n visited.update(unseen_neis)\n queue.extend(unseen_neis)\n\ndef connected_components(graph):\n seen_vertices = set()\n bfs = BreadthFirstSearch(graph)\n for start_vertex in graph:\n if start_vertex in seen_vertices:\n continue\n component = list(bfs.run(start_vertex))\n yield component\n seen_vertices.update(component)\n\nHere, adj_list or graph is an adjacency list data structure, basically it gives you the neighbours of a given vertex in the graph. To build it from your file, you can do this:\nadj_list = defaultdict(set)\nfor line in open(\"your_file.txt\"):\n parts = line.strip().split()\n v1 = parts.pop(0)\n adj_list[v1].update(parts)\n for v2 in parts:\n adj_list[v2].add(v1)\n\nThen you can run:\ncomponents = list(connected_components(adj_list))\n\nOf course, implementing the whole algorithm in pure Python tends to be slower than an implementation in C with a more efficient graph data structure. You might consider using igraph or some other graph library like NetworkX to do the job instead. Both libraries contain implementations for connected component search; in igraph, it boils down to this (assuming that your file does not contain lines with single entries, only pairwise entries are accepted):\n>>> from igraph import load\n>>> graph = load(\"edge_list.txt\", format=\"ncol\", directed=False)\n>>> components = graph.clusters()\n>>> print graph.vs[components[0]][\"name\"]\n['T1', 'T2', 'T6']\n>>> print graph.vs[components[1]][\"name\"]\n['T3', 'T4', 'T5']\n\nDisclaimer: I am one of the authors of igraph\n", "You can model a group using a set. In the example below, I've put the set into a Group class to make it easier to keep references to them and to track some notional 'head' item. \nclass Group:\n def __init__(self,head):\n self.members = set()\n self.head = head\n self.add(head)\n def add(self,member):\n self.members.add(member)\n def union(self,other):\n self.members = other.members.union(self.members)\n\ngroups = {}\n\nfor line in open(\"sets.dat\"):\n line = line.split()\n if len(line) == 0:\n break\n # find the group of the first item on the row\n head = line[0]\n if head not in groups:\n group = Group(head)\n groups[head] = group\n else:\n group = groups[head]\n # for each other item on the row, merge the groups\n for node in line[1:]:\n if node not in groups:\n # its a new node, straight into the group\n group.add(node)\n groups[node] = group\n elif head not in groups[node].members:\n # merge two groups\n new_members = groups[node]\n group.union(new_members)\n for migrate in new_members.members:\n groups[migrate] = group\n# list them\nfor k,v in groups.iteritems():\n if k == v.head:\n print v.members\n\nOutput is:\nset(['T6', 'T2', 'T1'])\nset(['T4', 'T5', 'T3'])\n\n" ]
[ 16, 14, 5, 1, 0 ]
[]
[]
[ "algorithm", "python", "set" ]
stackoverflow_0003067529_algorithm_python_set.txt
Q: get n records at a time from a temporary table I have a temporary table with about 1 million entries. The temporary table stores the result of a larger query. I want to process these records 1000 at a time, for example. What's the best way to set up queries such that I get the first 1000 rows, then the next 1000, etc.? They are not inherently ordered, but the temporary table just has one column with an ID, so I can order it if necessary. I was thinking of creating an extra column with the temporary table to number all the rows, something like: CREATE TEMP TABLE tmptmp AS SELECT ##autonumber somehow##, id FROM .... --complicated query then I can do: SELECT * FROM tmptmp WHERE autonumber>=0 AND autonumber < 1000 etc... how would I actually accomplish this? Or is there a better way? I'm using Python and PostgreSQL. A: Use a cursor and fetch the to rows you need. Offset ... limit will become slow when you have a lot of records, a cursor will do a much better job. http://www.postgresql.org/docs/8.4/interactive/sql-fetch.html A: Perhaps you could use something like this (we use when batch updating a table with +20 million rows and don't want to hog the replication). import sys import psycopg2 from datetime import datetime firstid = 0 splitsize = 50 # Size of each batch # Complicated query query_complex = """ CREATE TEMP TABLE tmptmp AS SELECT * FROM schema.massive_table """ # Query to be run at intervals query = """ SELECT * FROM tmptmp WHERE id BETWEEN %(startid)s AND %(endid)s """ conn = psycopg2.connect("dbname=database_name user=postgres") curs = conn.cursor() # Run complicated query curs.execute(query_complex) # Get highest id curs.execute("SELECT max(id) FROM tmptmp") maxid = curs.fetchall()[0][0] print "Max id: %s" % maxid for startid in range(firstid, maxid, splitsize): endid = startid + splitsize - 1 print "%s: Running query on range %s to %s" % (datetime.now(), startid, endid) curs.execute(query, {'startid':startid, 'endid':endid}) print "%s: Affected rows: %s. Total completed: %s%%" % (datetime.now(), curs.rowcount, round((endid * 100) / maxid, 3)) print "Done." The output that follows: Max id: 308 2010-06-18 11:59:11.271000: Running query on range 0 to 49 2010-06-18 11:59:11.271000: Affected rows: 49. Total completed: 15.0% 2010-06-18 11:59:11.271000: Running query on range 50 to 99 2010-06-18 11:59:11.271000: Affected rows: 50. Total completed: 32.0% 2010-06-18 11:59:11.271000: Running query on range 100 to 149 2010-06-18 11:59:11.271000: Affected rows: 50. Total completed: 48.0% 2010-06-18 11:59:11.271000: Running query on range 150 to 199 2010-06-18 11:59:11.271000: Affected rows: 49. Total completed: 64.0% 2010-06-18 11:59:11.271000: Running query on range 200 to 249 2010-06-18 11:59:11.271000: Affected rows: 42. Total completed: 80.0% 2010-06-18 11:59:11.271000: Running query on range 250 to 299 2010-06-18 11:59:11.318000: Affected rows: 3. Total completed: 97.0% 2010-06-18 11:59:11.318000: Running query on range 300 to 349 2010-06-18 11:59:11.318000: Affected rows: 1. Total completed: 113.0% Done. // John
get n records at a time from a temporary table
I have a temporary table with about 1 million entries. The temporary table stores the result of a larger query. I want to process these records 1000 at a time, for example. What's the best way to set up queries such that I get the first 1000 rows, then the next 1000, etc.? They are not inherently ordered, but the temporary table just has one column with an ID, so I can order it if necessary. I was thinking of creating an extra column with the temporary table to number all the rows, something like: CREATE TEMP TABLE tmptmp AS SELECT ##autonumber somehow##, id FROM .... --complicated query then I can do: SELECT * FROM tmptmp WHERE autonumber>=0 AND autonumber < 1000 etc... how would I actually accomplish this? Or is there a better way? I'm using Python and PostgreSQL.
[ "Use a cursor and fetch the to rows you need. Offset ... limit will become slow when you have a lot of records, a cursor will do a much better job.\nhttp://www.postgresql.org/docs/8.4/interactive/sql-fetch.html\n", "Perhaps you could use something like this (we use when batch updating a table with +20 million rows and don't want to hog the replication).\nimport sys\nimport psycopg2\nfrom datetime import datetime\n\nfirstid = 0\nsplitsize = 50 # Size of each batch\n\n\n# Complicated query\nquery_complex = \"\"\"\n CREATE TEMP TABLE tmptmp AS\n SELECT * FROM schema.massive_table\n\"\"\"\n# Query to be run at intervals\nquery = \"\"\"\n SELECT * FROM tmptmp WHERE id BETWEEN %(startid)s AND %(endid)s\n\"\"\"\n\nconn = psycopg2.connect(\"dbname=database_name user=postgres\")\ncurs = conn.cursor()\n# Run complicated query\ncurs.execute(query_complex)\n# Get highest id\ncurs.execute(\"SELECT max(id) FROM tmptmp\")\nmaxid = curs.fetchall()[0][0]\nprint \"Max id: %s\" % maxid\n\nfor startid in range(firstid, maxid, splitsize):\n endid = startid + splitsize - 1\n print \"%s: Running query on range %s to %s\" % (datetime.now(), startid, endid)\n curs.execute(query, {'startid':startid, 'endid':endid})\n print \"%s: Affected rows: %s. Total completed: %s%%\" % (datetime.now(), curs.rowcount, round((endid * 100) / maxid, 3))\n\nprint \"Done.\"\n\nThe output that follows:\nMax id: 308\n2010-06-18 11:59:11.271000: Running query on range 0 to 49\n2010-06-18 11:59:11.271000: Affected rows: 49. Total completed: 15.0%\n2010-06-18 11:59:11.271000: Running query on range 50 to 99\n2010-06-18 11:59:11.271000: Affected rows: 50. Total completed: 32.0%\n2010-06-18 11:59:11.271000: Running query on range 100 to 149\n2010-06-18 11:59:11.271000: Affected rows: 50. Total completed: 48.0%\n2010-06-18 11:59:11.271000: Running query on range 150 to 199\n2010-06-18 11:59:11.271000: Affected rows: 49. Total completed: 64.0%\n2010-06-18 11:59:11.271000: Running query on range 200 to 249\n2010-06-18 11:59:11.271000: Affected rows: 42. Total completed: 80.0%\n2010-06-18 11:59:11.271000: Running query on range 250 to 299\n2010-06-18 11:59:11.318000: Affected rows: 3. Total completed: 97.0%\n2010-06-18 11:59:11.318000: Running query on range 300 to 349\n2010-06-18 11:59:11.318000: Affected rows: 1. Total completed: 113.0%\nDone.\n\n// John\n" ]
[ 4, 1 ]
[]
[]
[ "database", "postgresql", "python", "sql" ]
stackoverflow_0003065826_database_postgresql_python_sql.txt
Q: How to build a index table (python dict like) in python with sqlite3 Suppose I have one string list may have duplicated items: A B C A A C D E F F I want to make a list can assign an unique index for each item, looks like: 1 A 2 B 3 C 4 D 5 E 6 F now I created sqlite3 database with below SQL statement: CREATE TABLE aa ( myid INTEGER PRIMARY KEY AUTOINCREMENT, name STRING, UNIQUE (myid) ON CONFLICT FAIL, UNIQUE (name) ON CONFLICT FAIL); The plan is insert each row into the database in python. My question is how to handle the error when conflict do happened when insert in python module sqlite3? For example: the program will printing a warning message which item is conflicted and continue next insert action when inserting in python? Thanks A: You could use a set, to filter double entries in your list and just insert the values: >>> set(['A', 'B', 'C', 'D', 'A', 'A', 'A', 1, 2, 1, 3, object(), object()]) set(['A', 1, 'C', 'B', 'D', 2, <object object at 0x100274590>, 3, <object object at 0x1002746a0>]) or use a try-except clause on each commit to check, whether the value is already in the database. A: Why not try it out and check which Exception is raised? That's not too hard I think, but... try: conn.excecute('...') except IntegrityError: pass
How to build a index table (python dict like) in python with sqlite3
Suppose I have one string list may have duplicated items: A B C A A C D E F F I want to make a list can assign an unique index for each item, looks like: 1 A 2 B 3 C 4 D 5 E 6 F now I created sqlite3 database with below SQL statement: CREATE TABLE aa ( myid INTEGER PRIMARY KEY AUTOINCREMENT, name STRING, UNIQUE (myid) ON CONFLICT FAIL, UNIQUE (name) ON CONFLICT FAIL); The plan is insert each row into the database in python. My question is how to handle the error when conflict do happened when insert in python module sqlite3? For example: the program will printing a warning message which item is conflicted and continue next insert action when inserting in python? Thanks
[ "You could use a set, to filter double entries in your list and just insert the values:\n>>> set(['A', 'B', 'C', 'D', 'A', 'A', 'A', 1, 2, 1, 3, object(), object()])\nset(['A', 1, 'C', 'B', 'D', 2, <object object at 0x100274590>, 3, <object object\n at 0x1002746a0>])\n\nor use a try-except clause on each commit to check, whether the value is already in the database.\n", "Why not try it out and check which Exception is raised? That's not too hard I think, but...\ntry:\n conn.excecute('...')\nexcept IntegrityError:\n pass\n\n" ]
[ 1, 1 ]
[]
[]
[ "dictionary", "python", "sqlite" ]
stackoverflow_0003067494_dictionary_python_sqlite.txt
Q: python: sending information between two scripts I have two Python scripts in two different locations and cannot be moved. What is the best way to send information between the two scripts? say for example in script1.py i had a string e.g. x = 'teststring' then i need variable 'x' passed to script2.py, which saves the variable 'x' to a text file? Any ideas? A: You just import it. #script2.py from script1 import x To make the script2 find the script1, the script1 file must be in the module search path edit Here's an example: First we create a dir and display the value of the module search path: $mkdir some_dir $echo $PYTHONPATH It's nothig. Then we create a file with the variable x initialized to "hola" in that directory: $cat >some_dir/module_a.py <<. > x = "hola" > . And we create another python file to use it: $cat >module_b.py<<. > from module_a import x > print x > . If we run that second script we got an error: $python module_b.py Traceback (most recent call last): File "module_b.py", line 1, in <module> from module_a import x ImportError: No module named module_a But, if we specify the some_dir in the module search path, and run it again, should work: $export PYTHONPATH=some_dir $python module_b.py hola A: How about using a socket? This is a good tutorial about network programming in Python. It includes client/server sample scripts: http://heather.cs.ucdavis.edu/~matloff/Python/PyNet.pdf A: Here is the standard way of doing what you want: import sys sys.path.append('/path/to/the_other_module_dir') import script1 print script1.x In fact, if you modify the environment variable PYTHONPATH for each single project that involves modules that are not in the same directory, you'll have an unnecessarily long PYTHONPATH variable and users of your script will also have to modify their PYTHONPATH. The above canonical method solves these problems. Alternatively, you might want to directly import x: from script1 import x print x
python: sending information between two scripts
I have two Python scripts in two different locations and cannot be moved. What is the best way to send information between the two scripts? say for example in script1.py i had a string e.g. x = 'teststring' then i need variable 'x' passed to script2.py, which saves the variable 'x' to a text file? Any ideas?
[ "You just import it. \n#script2.py\nfrom script1 import x\n\nTo make the script2 find the script1, the script1 file must be in the module search path\nedit\nHere's an example:\nFirst we create a dir and display the value of the module search path:\n$mkdir some_dir\n$echo $PYTHONPATH\n\nIt's nothig. Then we create a file with the variable x initialized to \"hola\" in that directory:\n$cat >some_dir/module_a.py <<.\n> x = \"hola\"\n> .\n\nAnd we create another python file to use it:\n$cat >module_b.py<<.\n> from module_a import x\n> print x\n> .\n\nIf we run that second script we got an error:\n$python module_b.py \nTraceback (most recent call last):\n File \"module_b.py\", line 1, in <module>\n from module_a import x\nImportError: No module named module_a\n\nBut, if we specify the some_dir in the module search path, and run it again, should work:\n$export PYTHONPATH=some_dir\n$python module_b.py \n hola\n\n", "How about using a socket?\nThis is a good tutorial about network programming in Python. It includes client/server sample scripts:\nhttp://heather.cs.ucdavis.edu/~matloff/Python/PyNet.pdf\n", "Here is the standard way of doing what you want:\nimport sys\nsys.path.append('/path/to/the_other_module_dir')\nimport script1\n\nprint script1.x\n\nIn fact, if you modify the environment variable PYTHONPATH for each single project that involves modules that are not in the same directory, you'll have an unnecessarily long PYTHONPATH variable and users of your script will also have to modify their PYTHONPATH. The above canonical method solves these problems.\nAlternatively, you might want to directly import x:\nfrom script1 import x\nprint x\n\n" ]
[ 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003066951_python.txt
Q: i can use this 'zipme' to download source code from gae , but can not i download another file around me i follow this article : zipme and i download my file successful , and i want to download another file that ex: the parent file so i change this: dirname=os.path.dirname folder = dirname(__file__) to dirname=os.path.dirname folder = dirname(dirname(__file__)) but the error is : firefox can't find the file why ? thanks A: You get the error, because something fails in the script and it won't return a valid ZIP file back in the response. The most probable reason is because your zipme.py will be in the root of your application. So if you try to get the parent folder of your root folder (returned by dirname(__file__)) it will fail because there is no parent folder (or at least not accessible by your code). As far as I can see there would be no reason to execute the code you want to execute, because the original dirname(__file__) should already ZIP all your application's files.
i can use this 'zipme' to download source code from gae , but can not i download another file around me
i follow this article : zipme and i download my file successful , and i want to download another file that ex: the parent file so i change this: dirname=os.path.dirname folder = dirname(__file__) to dirname=os.path.dirname folder = dirname(dirname(__file__)) but the error is : firefox can't find the file why ? thanks
[ "You get the error, because something fails in the script and it won't return a valid ZIP file back in the response.\nThe most probable reason is because your zipme.py will be in the root of your application. So if you try to get the parent folder of your root folder (returned by dirname(__file__)) it will fail because there is no parent folder (or at least not accessible by your code).\nAs far as I can see there would be no reason to execute the code you want to execute, because the original dirname(__file__) should already ZIP all your application's files.\n" ]
[ 1 ]
[]
[]
[ "download", "google_app_engine", "parent", "python", "zip" ]
stackoverflow_0003068503_download_google_app_engine_parent_python_zip.txt
Q: can i upload all data to gae without bulkloader i can use this code to download all data from my app on gae : appcfg.py download_data --application=zjm1126 --url=http://zjm1126.appspot.com/remote_api --filename=a.csv it is not use bulkloader , so can i upload all data without bulkloader , thanks A: Yes, you can use the upload_data command as described here, but this and your download_data command are deprecated from SDK 1.3.4 onwards. So it's better to look into using the bulkloader API as described here.
can i upload all data to gae without bulkloader
i can use this code to download all data from my app on gae : appcfg.py download_data --application=zjm1126 --url=http://zjm1126.appspot.com/remote_api --filename=a.csv it is not use bulkloader , so can i upload all data without bulkloader , thanks
[ "Yes, you can use the upload_data command as described here, but this and your download_data command are deprecated from SDK 1.3.4 onwards. So it's better to look into using the bulkloader API as described here.\n" ]
[ 1 ]
[]
[]
[ "bulkloader", "google_app_engine", "python" ]
stackoverflow_0003068675_bulkloader_google_app_engine_python.txt
Q: Display image in Django Form I need to display an image in a Django form. My Django form is quite simple - a single text input field. When I initialise my Django form in a view, I would like to pass the image path as a parameter, and the form when rendered in the template displays the image. Is is possible with Django forms or would i have to display the image separately? Thanks. A: This template responsibility to display this image in your case, I believe. If you form need to be able to send image related information (path, url..), you'll need to create a dedicated widget. A: If the image is related to the form itself, not to any field in particular, then you can make a custom form class and override one of as_table(), as_ul(), as_p() methods. Or you can just use a custom template instead of leaving the form to render itself. If it is field related then a custom widget is appropriate, as Pierre suggested.
Display image in Django Form
I need to display an image in a Django form. My Django form is quite simple - a single text input field. When I initialise my Django form in a view, I would like to pass the image path as a parameter, and the form when rendered in the template displays the image. Is is possible with Django forms or would i have to display the image separately? Thanks.
[ "This template responsibility to display this image in your case, I believe.\nIf you form need to be able to send image related information (path, url..), you'll need to create a dedicated widget.\n", "If the image is related to the form itself, not to any field in particular, then you can make a custom form class and override one of as_table(), as_ul(), as_p() methods. Or you can just use a custom template instead of leaving the form to render itself.\nIf it is field related then a custom widget is appropriate, as Pierre suggested.\n" ]
[ 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003068827_django_python.txt
Q: Creating a tiled map with blender I'm looking at creating map tiles based on a 3D model made in blender, The map is 16 x 16 in blender. I've got 4 different zoom levels and each tile is 100 x 100 pixels. The entire map at the most zoomed out level is 4 x 4 tiles constructing an image of 400 x 400. The most zoomed in level is 256 x 256 obviously constructing an image of 25600 x 25600 What I need is a script for blender that can create the tiles from the model. I've never written in python before so I've been trying to adapt a couple of the scripts which are already there. So far I've come up with a script, but it doesn't work very well. I'm having real difficulties getting the tiles to line up seamlessly. I'm not too concerned about changing the height of the camera as I can always create the same zoomed out tiles at 6400 x 6400 images and split the resulting images into the correct tiles. Here is what I've got so far... #!BPY """ Name: 'Export Map Tiles' Blender: '242' Group: 'Export' Tip: 'Export to Map' """ import Blender from Blender import Scene,sys from Blender.Scene import Render def init(): thumbsize = 200 CameraHeight = 4.4 YStart = -8 YMove = 4 XStart = -8 XMove = 4 ZoomLevel = 1 Path = "/Images/Map/" Blender.drawmap = [thumbsize,CameraHeight,YStart,YMove,XStart,XMove,ZoomLevel,Path] def show_prefs(): buttonthumbsize = Blender.Draw.Create(Blender.drawmap[0]); buttonCameraHeight = Blender.Draw.Create(Blender.drawmap[1]) buttonYStart = Blender.Draw.Create(Blender.drawmap[2]) buttonYMove = Blender.Draw.Create(Blender.drawmap[3]) buttonXStart = Blender.Draw.Create(Blender.drawmap[4]) buttonXMove = Blender.Draw.Create(Blender.drawmap[5]) buttonZoomLevel = Blender.Draw.Create(Blender.drawmap[6]) buttonPath = Blender.Draw.Create(Blender.drawmap[7]) block = [] block.append(("Image Size", buttonthumbsize, 0, 500)) block.append(("Camera Height", buttonCameraHeight, -0, 10)) block.append(("Y Start", buttonYStart, -10, 10)) block.append(("Y Move", buttonYMove, 0, 5)) block.append(("X Start", buttonXStart,-10, 10)) block.append(("X Move", buttonXMove, 0, 5)) block.append(("Zoom Level", buttonZoomLevel, 1, 10)) block.append(("Export Path", buttonPath,0,200,"The Path to save the tiles")) retval = Blender.Draw.PupBlock("Draw Map: Preferences" , block) if retval: Blender.drawmap[0] = buttonthumbsize.val Blender.drawmap[1] = buttonCameraHeight.val Blender.drawmap[2] = buttonYStart.val Blender.drawmap[3] = buttonYMove.val Blender.drawmap[4] = buttonXStart.val Blender.drawmap[5] = buttonXMove.val Blender.drawmap[6] = buttonZoomLevel.val Blender.drawmap[7] = buttonPath.val Export() def Export(): scn = Scene.GetCurrent() context = scn.getRenderingContext() def cutStr(str): #cut off path leaving name c = str.find("\\") while c != -1: c = c + 1 str = str[c:] c = str.find("\\") str = str[:-6] return str #variables from gui: thumbsize,CameraHeight,YStart,YMove,XStart,XMove,ZoomLevel,Path = Blender.drawmap XMove = XMove / ZoomLevel YMove = YMove / ZoomLevel Camera = Scene.GetCurrent().getCurrentCamera() Camera.LocZ = CameraHeight / ZoomLevel YStart = YStart + (YMove / 2) XStart = XStart + (XMove / 2) #Point it straight down Camera.RotX = 0 Camera.RotY = 0 Camera.RotZ = 0 TileCount = 4**ZoomLevel #Because the first thing we do is move the camera, start it off the map Camera.LocY = YStart - YMove for i in range(0,TileCount): Camera.LocY = Camera.LocY + YMove Camera.LocX = XStart - XMove for j in range(0,TileCount): Camera.LocX = Camera.LocX + XMove Render.EnableDispWin() context.extensions = True context.renderPath = Path #setting thumbsize context.imageSizeX(thumbsize) context.imageSizeY(thumbsize) #could be put into a gui. context.imageType = Render.PNG context.enableOversampling(0) #render context.render() #save image ZasString = '%s' %(int(ZoomLevel)) XasString = '%s' %(int(j+1)) YasString = '%s' %(int((3-i)+1)) context.saveRenderedImage("Z" + ZasString + "X" + XasString + "Y" + YasString) #close the windows Render.CloseRenderWindow() try: type(Blender.drawmap) except: #print 'initialize extern variables' init() show_prefs() A: This was relatively simple in the end. I scaled up the model so that 1 tile on the map was 1 grid in blender. Set the camera to be orthographic. Set the scale on the camera to 1 for the highest zoom, 4 for the next one, 16 for the next one and so on. Updated the start coordinates and move values accordingly.
Creating a tiled map with blender
I'm looking at creating map tiles based on a 3D model made in blender, The map is 16 x 16 in blender. I've got 4 different zoom levels and each tile is 100 x 100 pixels. The entire map at the most zoomed out level is 4 x 4 tiles constructing an image of 400 x 400. The most zoomed in level is 256 x 256 obviously constructing an image of 25600 x 25600 What I need is a script for blender that can create the tiles from the model. I've never written in python before so I've been trying to adapt a couple of the scripts which are already there. So far I've come up with a script, but it doesn't work very well. I'm having real difficulties getting the tiles to line up seamlessly. I'm not too concerned about changing the height of the camera as I can always create the same zoomed out tiles at 6400 x 6400 images and split the resulting images into the correct tiles. Here is what I've got so far... #!BPY """ Name: 'Export Map Tiles' Blender: '242' Group: 'Export' Tip: 'Export to Map' """ import Blender from Blender import Scene,sys from Blender.Scene import Render def init(): thumbsize = 200 CameraHeight = 4.4 YStart = -8 YMove = 4 XStart = -8 XMove = 4 ZoomLevel = 1 Path = "/Images/Map/" Blender.drawmap = [thumbsize,CameraHeight,YStart,YMove,XStart,XMove,ZoomLevel,Path] def show_prefs(): buttonthumbsize = Blender.Draw.Create(Blender.drawmap[0]); buttonCameraHeight = Blender.Draw.Create(Blender.drawmap[1]) buttonYStart = Blender.Draw.Create(Blender.drawmap[2]) buttonYMove = Blender.Draw.Create(Blender.drawmap[3]) buttonXStart = Blender.Draw.Create(Blender.drawmap[4]) buttonXMove = Blender.Draw.Create(Blender.drawmap[5]) buttonZoomLevel = Blender.Draw.Create(Blender.drawmap[6]) buttonPath = Blender.Draw.Create(Blender.drawmap[7]) block = [] block.append(("Image Size", buttonthumbsize, 0, 500)) block.append(("Camera Height", buttonCameraHeight, -0, 10)) block.append(("Y Start", buttonYStart, -10, 10)) block.append(("Y Move", buttonYMove, 0, 5)) block.append(("X Start", buttonXStart,-10, 10)) block.append(("X Move", buttonXMove, 0, 5)) block.append(("Zoom Level", buttonZoomLevel, 1, 10)) block.append(("Export Path", buttonPath,0,200,"The Path to save the tiles")) retval = Blender.Draw.PupBlock("Draw Map: Preferences" , block) if retval: Blender.drawmap[0] = buttonthumbsize.val Blender.drawmap[1] = buttonCameraHeight.val Blender.drawmap[2] = buttonYStart.val Blender.drawmap[3] = buttonYMove.val Blender.drawmap[4] = buttonXStart.val Blender.drawmap[5] = buttonXMove.val Blender.drawmap[6] = buttonZoomLevel.val Blender.drawmap[7] = buttonPath.val Export() def Export(): scn = Scene.GetCurrent() context = scn.getRenderingContext() def cutStr(str): #cut off path leaving name c = str.find("\\") while c != -1: c = c + 1 str = str[c:] c = str.find("\\") str = str[:-6] return str #variables from gui: thumbsize,CameraHeight,YStart,YMove,XStart,XMove,ZoomLevel,Path = Blender.drawmap XMove = XMove / ZoomLevel YMove = YMove / ZoomLevel Camera = Scene.GetCurrent().getCurrentCamera() Camera.LocZ = CameraHeight / ZoomLevel YStart = YStart + (YMove / 2) XStart = XStart + (XMove / 2) #Point it straight down Camera.RotX = 0 Camera.RotY = 0 Camera.RotZ = 0 TileCount = 4**ZoomLevel #Because the first thing we do is move the camera, start it off the map Camera.LocY = YStart - YMove for i in range(0,TileCount): Camera.LocY = Camera.LocY + YMove Camera.LocX = XStart - XMove for j in range(0,TileCount): Camera.LocX = Camera.LocX + XMove Render.EnableDispWin() context.extensions = True context.renderPath = Path #setting thumbsize context.imageSizeX(thumbsize) context.imageSizeY(thumbsize) #could be put into a gui. context.imageType = Render.PNG context.enableOversampling(0) #render context.render() #save image ZasString = '%s' %(int(ZoomLevel)) XasString = '%s' %(int(j+1)) YasString = '%s' %(int((3-i)+1)) context.saveRenderedImage("Z" + ZasString + "X" + XasString + "Y" + YasString) #close the windows Render.CloseRenderWindow() try: type(Blender.drawmap) except: #print 'initialize extern variables' init() show_prefs()
[ "This was relatively simple in the end. \nI scaled up the model so that 1 tile on the map was 1 grid in blender.\nSet the camera to be orthographic.\nSet the scale on the camera to 1 for the highest zoom, 4 for the next one, 16 for the next one and so on.\nUpdated the start coordinates and move values accordingly.\n" ]
[ 0 ]
[]
[]
[ "blender", "blender_2.49", "map", "python", "scripting" ]
stackoverflow_0002957702_blender_blender_2.49_map_python_scripting.txt
Q: Is there a way to watch all COM activity on a computer? I'm trying to deal with a piece of specialized hardware, that presents it's interface as a COM object, using win32com in Python. However, the documentation for how to actually set up the hardware through the COM object is sparse (it requires a significant amount of initialization), and entirely oriented at using a bunch of pre-built libraries for Visual Studio, which are not accessible through python. That said, is there any way to watch all local COM activity, so I can sort through the activity logs to try and figure out how the existing demo programs properly initialize the hardware, and replicate the behavior in my python script? Ideally, there would be something in the vein of wireshark for doing this. Note: I have very little (read: basically no) experience using COM, as my focus is mostly embedded hardware (and a little python dev on the side). However, I'm stuck with this particular device. A: Try Deviare COM Spy Console. Com Spy Console allows users to monitor applications using Component Object Model's interfaces. You are able to spy which interfaces are being created and see how the applications are using them by intercepting the calls to its member functions. Spy on any ActiveX / OLE32 calls monitoring all members of these COM objects. You can download it for free. A: Another nice trick is to use Process Monitor to watch registry activity related to COM/COM+. Basically access to keys like HKLM\Software\Classes\CLSID{SOME-GUID}. This helped me tons of times to find problems with components not correctly registered in the system.
Is there a way to watch all COM activity on a computer?
I'm trying to deal with a piece of specialized hardware, that presents it's interface as a COM object, using win32com in Python. However, the documentation for how to actually set up the hardware through the COM object is sparse (it requires a significant amount of initialization), and entirely oriented at using a bunch of pre-built libraries for Visual Studio, which are not accessible through python. That said, is there any way to watch all local COM activity, so I can sort through the activity logs to try and figure out how the existing demo programs properly initialize the hardware, and replicate the behavior in my python script? Ideally, there would be something in the vein of wireshark for doing this. Note: I have very little (read: basically no) experience using COM, as my focus is mostly embedded hardware (and a little python dev on the side). However, I'm stuck with this particular device.
[ "Try Deviare COM Spy Console.\n\nCom Spy Console allows users to\n monitor applications using Component\n Object Model's interfaces. You are\n able to spy which interfaces are being\n created and see how the applications\n are using them by intercepting the\n calls to its member functions.\nSpy on any ActiveX / OLE32 calls\n monitoring all members of these COM\n objects.\n\nYou can download it for free.\n", "Another nice trick is to use Process Monitor to watch registry activity related to COM/COM+. Basically access to keys like HKLM\\Software\\Classes\\CLSID{SOME-GUID}.\nThis helped me tons of times to find problems with components not correctly registered in the system.\n" ]
[ 3, 0 ]
[]
[]
[ "com", "python", "visual_studio" ]
stackoverflow_0003067784_com_python_visual_studio.txt
Q: How fast are App Engine db.get(keys) and A.all(keys_only=True).filter('b =', b).fetch(1000)? A db.get() of 50 keys seems to take me 5-6 seconds. Is that normal? What is the time a function of? I also did a A.all(keys_only=True).filter('b =', b).fetch(1000) where A.b is a ReferenceProperty. I did 50 such round trips to the datastore, with different values of b, and the total time was only 3-4 seconds. How is this possible? db.get() is done in parallel, with only one trip to the datastore, and I would think that looking up an entity by key is a faster operation than fetch. Here is the definition for my class A: class App(db.Model): name_atom = db.ReferenceProperty(AppName) author = db.ReferenceProperty(Author) short_desc = db.StringProperty() description = db.TextProperty() url = db.StringProperty() rating_avg = properties.RangeProperty(0, 1000, default=0) rating_count = properties.RangeProperty(min_value=0, default=0) add_dt = db.DateTimeProperty(auto_now_add=True) modify_dt = db.DateTimeProperty(auto_now=True) Update OK, AppStats says: datastore_v3.Get real=2272ms api=416ms I think what's happening is that I'm doing this db.get([50 keys]) right after a ton of other inefficient datastore calls in the same request handler, and it's just rate limiting me or something. Other times I've done the same db.get() and it returned in 200ms :) A: A db.get() of 50 keys seems to take me 5-6 seconds. Is that normal? What is the time a function of? No. It should take a couple of hundred milliseconds. How are you timing it, though? I also did a A.all(keys_only=True).filter('b =', b).fetch(1000) where A.b is a ReferenceProperty. I did 50 such round trips to the datastore, with different values of b, and the total time was only 3-4 seconds. That's not unreasonable, for 50 roundtrips. How is this possible? db.get() is done in parallel, with only one trip to the datastore, and I would think that looking up an entity by key is a faster operation than fetch. It's an extremely odd result, and I think that there are likely confounding factors at work. As David suggests, you should use AppStats to discover where the time is going. A: When fetching entities by key, query time should primarily be dependent on the size of your entities. The entities have to be transferred to you over the network and then decoded. Perhaps your entities are quite large? This might explain why your keys_only query is faster despite the fact it includes a filter and fetches many more results. You might consider using AppStats so you can see exactly why your request is taking so long. You could even post it along with your question.
How fast are App Engine db.get(keys) and A.all(keys_only=True).filter('b =', b).fetch(1000)?
A db.get() of 50 keys seems to take me 5-6 seconds. Is that normal? What is the time a function of? I also did a A.all(keys_only=True).filter('b =', b).fetch(1000) where A.b is a ReferenceProperty. I did 50 such round trips to the datastore, with different values of b, and the total time was only 3-4 seconds. How is this possible? db.get() is done in parallel, with only one trip to the datastore, and I would think that looking up an entity by key is a faster operation than fetch. Here is the definition for my class A: class App(db.Model): name_atom = db.ReferenceProperty(AppName) author = db.ReferenceProperty(Author) short_desc = db.StringProperty() description = db.TextProperty() url = db.StringProperty() rating_avg = properties.RangeProperty(0, 1000, default=0) rating_count = properties.RangeProperty(min_value=0, default=0) add_dt = db.DateTimeProperty(auto_now_add=True) modify_dt = db.DateTimeProperty(auto_now=True) Update OK, AppStats says: datastore_v3.Get real=2272ms api=416ms I think what's happening is that I'm doing this db.get([50 keys]) right after a ton of other inefficient datastore calls in the same request handler, and it's just rate limiting me or something. Other times I've done the same db.get() and it returned in 200ms :)
[ "\nA db.get() of 50 keys seems to take me\n 5-6 seconds. Is that normal? What is\n the time a function of?\n\nNo. It should take a couple of hundred milliseconds. How are you timing it, though?\n\nI also did a\n A.all(keys_only=True).filter('b =',\n b).fetch(1000) where A.b is a\n ReferenceProperty. I did 50 such round\n trips to the datastore, with different\n values of b, and the total time was\n only 3-4 seconds.\n\nThat's not unreasonable, for 50 roundtrips.\n\nHow is this possible? db.get() is done\n in parallel, with only one trip to the\n datastore, and I would think that\n looking up an entity by key is a\n faster operation than fetch.\n\nIt's an extremely odd result, and I think that there are likely confounding factors at work. As David suggests, you should use AppStats to discover where the time is going.\n", "When fetching entities by key, query time should primarily be dependent on the size of your entities. The entities have to be transferred to you over the network and then decoded.\nPerhaps your entities are quite large? This might explain why your keys_only query is faster despite the fact it includes a filter and fetches many more results.\nYou might consider using AppStats so you can see exactly why your request is taking so long. You could even post it along with your question.\n" ]
[ 3, 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003066300_google_app_engine_python.txt
Q: Django -- User.DoesNotExist does not exist? I'm trying to get hold of Django. I use Pydev on Eclipse. I have written a simple signup page that I can't get to work. Eclipse complains that User.DoesNotExist is undefined. Most likely, I am missing something trivial. Here's the relevant portion of the code: from django.contrib.auth.models import User ... class SignUpForm (forms.Form): ... def clean_username (self): try: User.objects.get(username=self.cleaned_data['username']) except User.DoesNotExist: return self.cleaned_data['username'] raise forms.ValidationError(USERNAME_ALREADY_IN_USE) ... A: The problem is really with PyDev, not your code. What you have done is absolutely correct, but IDEs will always have difficulty resolving attributes in a dynamic language like Python. In the case of the DoesNotExist exception, it is added via a __metaclass__ rather than through normal object inheritance, so PyDev is unlikely to be able to find it. However, it should definitely work. A: I just discovered Pydev actually has a nice workaround for this. Go to Window > Preferences, then Pydev > Editor > Code Analysis. Click the Undefined tab and add "DoesNotExist" to the text box titled Consider the following names as globals. A: Pydev has a workaround for such cases (when the members are defined at runtime). Just add #@UndefinedVariable at the end of the string which cause the warning (or ctrl+1 on keyboard when the cursor is at "DoesNotExist"), and it won't complain. A: Can Eclipse resolve attributes created runtime via __metaclass__es? Notice that you never define a DoesNotExist on any of your models and it is not defined on django.db.models.base.Model either. A: You can also solve it in a different way: just go to the User class, and add @DynamicAttrs in the docstring. This will tell PyDev that attributes of the class are added dynamically, and will make it not complain any longer for "issues" like DoesNotExist. A: Eclipse complains that User.DoesNotExist is undefined. What do you mean by that? Do you have python error and stack trace? This code have to work (as in documentation). Looks like an eclipse issue. Just run dev server and see if it works or not: manage.py runserver A: I have same problem on Ubuntu in a VirtualEnv to solve problem I have used this snippets. http://djangosnippets.org/snippets/191/#c3091 In parituclar he make custom User Fields with code: class UserField(forms.CharField): def clean(self, value): super(UserField, self).clean(value) try: User.objects.get(username=value) raise forms.ValidationError("Someone is already using this username. Please pick an other.") except User.DoesNotExist: return value
Django -- User.DoesNotExist does not exist?
I'm trying to get hold of Django. I use Pydev on Eclipse. I have written a simple signup page that I can't get to work. Eclipse complains that User.DoesNotExist is undefined. Most likely, I am missing something trivial. Here's the relevant portion of the code: from django.contrib.auth.models import User ... class SignUpForm (forms.Form): ... def clean_username (self): try: User.objects.get(username=self.cleaned_data['username']) except User.DoesNotExist: return self.cleaned_data['username'] raise forms.ValidationError(USERNAME_ALREADY_IN_USE) ...
[ "The problem is really with PyDev, not your code. What you have done is absolutely correct, but IDEs will always have difficulty resolving attributes in a dynamic language like Python. In the case of the DoesNotExist exception, it is added via a __metaclass__ rather than through normal object inheritance, so PyDev is unlikely to be able to find it. However, it should definitely work.\n", "I just discovered Pydev actually has a nice workaround for this.\nGo to Window > Preferences, then Pydev > Editor > Code Analysis.\nClick the Undefined tab and add \"DoesNotExist\" to the text box titled Consider the following names as globals.\n", "Pydev has a workaround for such cases (when the members are defined at runtime).\nJust add #@UndefinedVariable at the end of the string which cause the warning (or ctrl+1 on keyboard when the cursor is at \"DoesNotExist\"), and it won't complain.\n", "Can Eclipse resolve attributes created runtime via __metaclass__es?\nNotice that you never define a DoesNotExist on any of your models and it is not defined on django.db.models.base.Model either.\n", "You can also solve it in a different way: just go to the User class, and add @DynamicAttrs in the docstring.\nThis will tell PyDev that attributes of the class are added dynamically, and will make it not complain any longer for \"issues\" like DoesNotExist.\n", "\nEclipse complains that User.DoesNotExist is undefined.\n\nWhat do you mean by that? Do you have python error and stack trace? This code have to work (as in documentation). Looks like an eclipse issue. Just run dev server and see if it works or not:\nmanage.py runserver\n\n", "I have same problem on Ubuntu in a VirtualEnv to solve problem I have used this snippets.\n\nhttp://djangosnippets.org/snippets/191/#c3091\n\nIn parituclar he make custom User Fields with code: \nclass UserField(forms.CharField):\n def clean(self, value):\n super(UserField, self).clean(value)\n try:\n User.objects.get(username=value)\n raise forms.ValidationError(\"Someone is already using this username. Please pick an other.\")\n except User.DoesNotExist:\n return value\n\n" ]
[ 26, 19, 8, 2, 2, 1, 1 ]
[]
[]
[ "authentication", "django", "django_models", "pydev", "python" ]
stackoverflow_0000851628_authentication_django_django_models_pydev_python.txt
Q: new to mac and textmate, can someone explain these shortcuts? I'm using textmate for the first time basically, and I am lost as to what keys map to these funny symbols. using python bundles, what keys do I press for: run run with tests run project unit tests Also, with textmate, do I actually define a project in textmate or do I just work on the files and textmate doesn't create its own .project type file ? A: Check out this link for some of the translations to some of the keyboard symbols. This should help you out :) Also here is a link from the Apple site for an exhaustive list of shortcuts. (source: osxkeyboardshortcuts.com) A: Also, with textmate, do I actually define a project in textmate or do I just work on the files and textmate doesn't create its own .project type file ? You can do both. You can create a new project in TextMate by going to File -> New Project and add your files manually, or you can drag a folder into TextMate and it will create a project from those files (you can add other files later). Note that the second method will not create a .tmproj file, though, so if you want to "keep" that project, you'll have to save it (File -> Save Project).
new to mac and textmate, can someone explain these shortcuts?
I'm using textmate for the first time basically, and I am lost as to what keys map to these funny symbols. using python bundles, what keys do I press for: run run with tests run project unit tests Also, with textmate, do I actually define a project in textmate or do I just work on the files and textmate doesn't create its own .project type file ?
[ "Check out this link for some of the translations to some of the keyboard symbols. This should help you out :)\nAlso here is a link from the Apple site for an exhaustive list of shortcuts.\n\n(source: osxkeyboardshortcuts.com) \n", "\nAlso, with textmate, do I actually define a project in textmate or do I just work on the files and textmate doesn't create its own .project type file ?\n\nYou can do both. You can create a new project in TextMate by going to File -> New Project and add your files manually, or you can drag a folder into TextMate and it will create a project from those files (you can add other files later). Note that the second method will not create a .tmproj file, though, so if you want to \"keep\" that project, you'll have to save it (File -> Save Project).\n" ]
[ 6, 2 ]
[]
[]
[ "python", "textmate" ]
stackoverflow_0003034640_python_textmate.txt
Q: Why don't we require interfaces in dynamic languages? Is it just because of dynamic typing we don't require a concept of interfaces(like in Java and C#) in python? A: The interface as a keyword and artifact was introduced by Java1 ( and C# took it from there ) to describe what the contract an object must adhere was. But, interface has always been a key part of Object Oriented Paradigm and basically it represents the methods an object has to respond. Java just enforces this mechanism to provide statically type checking. So, dynamic ( OO ) programming languages do use interfaces, even thought they don't statically check them. Just like other data types, for instance in Ruby: @i = 1; You don't have to declare i of type FixNum you just use it. Same goes for interfaces, they just flow. The trade-off is, you can't have a static check on that and failures are only show at runtime. In the other hand Structural type ( or static duck type as I call it :P ) used by languages as Go or Scala, gives the best of both worlds. 1. See Daniel Earwicker comment about CORBA interface keyword A: We don't require them, but we do support them. Check out Zope Interfaces (which can be and are used outside of Zope). A: It's worth noting that, contrary to what many people will say as a first response, interfaces can be used to do more than document "what methods a class supports". Grzenio touches on this with his wording on "implement the same behaviour". As a specific example of this, look at the Java interface Serializable. It doesn't implement any methods; rather it's used as a "marker" to indicate that the class can be serialized safely. When considered this way, it could be reasonable to have a dynamic language that uses interfaces. That being said, something akin to annotations might be a more reasonable approach. A: Interfaces are used in statically typed languages to describe that two otherwise independent objects "implement the same behaviour". In dynamically typed languages one implicitly assumes that when two objects have a method with the same name/params it does the same thing, so interfaces are of no use. A: Interface constructs are used in statically typed languages to teach the type system which objects are substitutable for each other in a particular method-calling context. If two objects implement the same method but aren't related through inheritance from a common base class or implementation of a common interface, the type system will raise an error at compile time if you substitute one for the other. Dynamic languages use "duck typing", which means the method is simply looked up at runtime and if it exists with the right signature, it's used; otherwise a runtime error results. If two objects both "quack like a duck" by implementing the same method, they are substitutable. Thus, there's no explicit need for the language to relate them via base class or interface. That being said, interfaces as a concept are still very important in the dynamic world, but they're often just defined in documentation and not enforced by the language. Occasionally, I see programmers actually make a base class that sketches out the interface for this purpose as well; this helps formalize the documentation, and is of particular use if part of the interface can be implemented in terms of the rest of the interface. A: One key thing about at least some dynamic languages that makes explicit interfaces more than a little awkward is that dynamic languages can often respond to messages (err, “method calls”) that they don't know about beforehand, even doing things like creating methods on the fly. The only real way to know whether an object will respond to a message correctly is by sending it the message. That's OK, because dynamic languages consider it better to be able to support that sort of thing rather than static type checking; an object is considered to be usable in a particular protocol because it is “known” to be able to participate in that protocol (e.g., by virtue of being given by another message). A: Perl has Roles (or traits ), It is more than interfaces unlike java perl roles we can have a implementation check out these links for more on perl roles http://en.wikipedia.org/wiki/Perl_6#Roles http://use.perl.org/~Ovid/journal/38649 A: In C# and Java, interfaces are just abstract classes with all abstract methods. They exist to allow pseudo multiple-inheritance without actually supporting full-blown multiple inheritance and the ambiguity multiple inheritance creates. Python supports multiple inheritance and has its own way of determining which parent's method should be called when a method exists in multiple parents. A: Dynamic languages are Duck Typed If it walks like a duck and quacks like a duck, it must be a duck http://en.wikipedia.org/wiki/Duck_typing In other words, If you exect an object to suport the Delete() method, than you can just use the obj.Delete() method but if the object doesn't support Delete() you get a Runtime error. Statically typed languages wouldn't allow that and throw a compile time error. So you basically trade type safty against faster developement time and flexibility. Without interfaces you can do something like that in static languages: void Save(MyBaseClass item) { if (item.HasChanges) item.Save() } but that would require every object that you pass to this method to inherit from MyBaseClass. Since Java or C# don't support muliinheritance that isn't very flexible because if your class already inherits another class it cannot inherit from MyBaseClass, too. So the better choise would be to create a ISavable interface and accept that as a input parameter to ensure that item can be saved. Then you have best of both: type safety and flexibility. public interface ISavable { bool HasChanges {get;set;} void Save(); } void Save(ISavable item) { if (item.HasChanges) item.Save() } The last backdoor is to use object as a parameter if you cannot expect every item that will use your save method to implement the interface. void Save(object item) { if (item.HasChanges) item.Save() } But than again, you don't have compile time checking and probably get a runtime error if someone uses your method with an incompatible class.
Why don't we require interfaces in dynamic languages?
Is it just because of dynamic typing we don't require a concept of interfaces(like in Java and C#) in python?
[ "The interface as a keyword and artifact was introduced by Java1 ( and C# took it from there ) to describe what the contract an object must adhere was. \nBut, interface has always been a key part of Object Oriented Paradigm and basically it represents the methods an object has to respond. Java just enforces this mechanism to provide statically type checking.\nSo, dynamic ( OO ) programming languages do use interfaces, even thought they don't statically check them. Just like other data types, for instance in Ruby:\n @i = 1;\n\nYou don't have to declare i of type FixNum you just use it. Same goes for interfaces, they just flow. The trade-off is, you can't have a static check on that and failures are only show at runtime. \nIn the other hand Structural type ( or static duck type as I call it :P ) used by languages as Go or Scala, gives the best of both worlds. \n\n1. See Daniel Earwicker comment about CORBA interface keyword\n\n", "We don't require them, but we do support them. Check out Zope Interfaces (which can be and are used outside of Zope).\n", "It's worth noting that, contrary to what many people will say as a first response, interfaces can be used to do more than document \"what methods a class supports\". Grzenio touches on this with his wording on \"implement the same behaviour\". As a specific example of this, look at the Java interface Serializable. It doesn't implement any methods; rather it's used as a \"marker\" to indicate that the class can be serialized safely.\nWhen considered this way, it could be reasonable to have a dynamic language that uses interfaces. That being said, something akin to annotations might be a more reasonable approach.\n", "Interfaces are used in statically typed languages to describe that two otherwise independent objects \"implement the same behaviour\". In dynamically typed languages one implicitly assumes that when two objects have a method with the same name/params it does the same thing, so interfaces are of no use.\n", "Interface constructs are used in statically typed languages to teach the type system which objects are substitutable for each other in a particular method-calling context. If two objects implement the same method but aren't related through inheritance from a common base class or implementation of a common interface, the type system will raise an error at compile time if you substitute one for the other.\nDynamic languages use \"duck typing\", which means the method is simply looked up at runtime and if it exists with the right signature, it's used; otherwise a runtime error results. If two objects both \"quack like a duck\" by implementing the same method, they are substitutable. Thus, there's no explicit need for the language to relate them via base class or interface.\nThat being said, interfaces as a concept are still very important in the dynamic world, but they're often just defined in documentation and not enforced by the language. Occasionally, I see programmers actually make a base class that sketches out the interface for this purpose as well; this helps formalize the documentation, and is of particular use if part of the interface can be implemented in terms of the rest of the interface.\n", "One key thing about at least some dynamic languages that makes explicit interfaces more than a little awkward is that dynamic languages can often respond to messages (err, “method calls”) that they don't know about beforehand, even doing things like creating methods on the fly. The only real way to know whether an object will respond to a message correctly is by sending it the message. That's OK, because dynamic languages consider it better to be able to support that sort of thing rather than static type checking; an object is considered to be usable in a particular protocol because it is “known” to be able to participate in that protocol (e.g., by virtue of being given by another message).\n", "Perl has Roles (or traits ), It is more than interfaces unlike java perl roles we can have a implementation check out these links for more on perl roles\n\nhttp://en.wikipedia.org/wiki/Perl_6#Roles\nhttp://use.perl.org/~Ovid/journal/38649\n\n", "In C# and Java, interfaces are just abstract classes with all abstract methods. They exist to allow pseudo multiple-inheritance without actually supporting full-blown multiple inheritance and the ambiguity multiple inheritance creates.\nPython supports multiple inheritance and has its own way of determining which parent's method should be called when a method exists in multiple parents.\n", "Dynamic languages are Duck Typed\n\nIf it walks like a duck and quacks\n like a duck, it must be a duck\n\nhttp://en.wikipedia.org/wiki/Duck_typing\nIn other words, If you exect an object to suport the Delete() method, than you can just use the\nobj.Delete()\n\nmethod but if the object doesn't support Delete() you get a Runtime error. Statically typed languages wouldn't allow that and throw a compile time error. So you basically trade type safty against faster developement time and flexibility.\nWithout interfaces you can do something like that in static languages:\nvoid Save(MyBaseClass item)\n{\n if (item.HasChanges)\n item.Save()\n}\n\nbut that would require every object that you pass to this method to inherit from MyBaseClass. Since Java or C# don't support muliinheritance that isn't very flexible because if your class already inherits another class it cannot inherit from MyBaseClass, too. So the better choise would be to create a ISavable interface and accept that as a input parameter to ensure that item can be saved. Then you have best of both: type safety and flexibility.\npublic interface ISavable\n{\n bool HasChanges {get;set;}\n void Save();\n}\n\nvoid Save(ISavable item)\n{\n if (item.HasChanges)\n item.Save()\n}\n\nThe last backdoor is to use object as a parameter if you cannot expect every item that will use your save method to implement the interface.\nvoid Save(object item)\n{\n if (item.HasChanges)\n item.Save()\n}\n\nBut than again, you don't have compile time checking and probably get a runtime error if someone uses your method with an incompatible class.\n" ]
[ 23, 5, 2, 1, 1, 1, 1, 0, 0 ]
[]
[]
[ "c#", "dynamic_languages", "java", "python" ]
stackoverflow_0003062701_c#_dynamic_languages_java_python.txt
Q: How to store an integer leaded by zeros in django I'm trying to store a number in django that looks like this: 000001 My problem is that if I type this inside an IntegerField it gets converted to "1" without the leading zeros. I've tried also with a DecimalField with the same result. How can I store the leading zeros whithout using a CharField? (I need to manipulate that number in it's integer form) A: Don't store it with the leading zeros. Format it on output instead: (in view: value = 1) {{ value|stringformat:"04d" }} # displays as 0001 A: I think you should use a CharField and do something like that : try: value = int(field) # do something with value except valueError: # raise a ValidationError if you are in the *clean* methods of the form # or raise an other exception # or handle the error # or just raise :-)
How to store an integer leaded by zeros in django
I'm trying to store a number in django that looks like this: 000001 My problem is that if I type this inside an IntegerField it gets converted to "1" without the leading zeros. I've tried also with a DecimalField with the same result. How can I store the leading zeros whithout using a CharField? (I need to manipulate that number in it's integer form)
[ "Don't store it with the leading zeros. Format it on output instead:\n(in view: value = 1)\n{{ value|stringformat:\"04d\" }} # displays as 0001\n\n", "I think you should use a CharField and do something like that :\ntry:\n value = int(field)\n # do something with value\nexcept valueError:\n # raise a ValidationError if you are in the *clean* methods of the form\n # or raise an other exception\n # or handle the error\n # or just raise :-)\n\n" ]
[ 21, 2 ]
[]
[]
[ "django", "django_admin", "django_models", "python" ]
stackoverflow_0003069989_django_django_admin_django_models_python.txt
Q: Reduce list of Python objects to dict of object.id -> object You have list of objects and each of them has an id property. Here's my way to convert it to dict where keys are ids and values are objects: reduce( lambda x,y: dict(x.items() + { y.id : y}.items()), list, {} ) Suggest better way to do it. A: In Python 3.x: object_dict = {x.id: x for x in object_list} In both Python 3.x and Python 2.4+: object_dict = dict((x.id, x) for x in object_list) (x.id, x) for x in object_list is a generator comprehension (and, nicely, does not need to be wrapped in parentheses like a list comprehension needs to be wrapped in brackets if it's being used as a single argument for a call; of course, this means that in other circumstances the expression I used would have to be ((x.id, x) for x in object_list)). Unlike a list comprehension, it will not generate an actual list of all the items, and is thus more efficient in situations such as this. As a side note, Python has a built-in method id(): Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value. (Implementation note: this is the address of the object.) So if you wanted to let Python handle the ids on its own, you could do it as: object_dict = {id(x): x for x in object_list} or object_dict = dict((id(x), x) for x in object_list) A: dict([(x.id, x) for x in list]) A: dict(map(lambda x: [x.id, x], list))
Reduce list of Python objects to dict of object.id -> object
You have list of objects and each of them has an id property. Here's my way to convert it to dict where keys are ids and values are objects: reduce( lambda x,y: dict(x.items() + { y.id : y}.items()), list, {} ) Suggest better way to do it.
[ "In Python 3.x:\nobject_dict = {x.id: x for x in object_list}\n\nIn both Python 3.x and Python 2.4+:\nobject_dict = dict((x.id, x) for x in object_list)\n\n(x.id, x) for x in object_list is a generator comprehension (and, nicely, does not need to be wrapped in parentheses like a list comprehension needs to be wrapped in brackets if it's being used as a single argument for a call; of course, this means that in other circumstances the expression I used would have to be ((x.id, x) for x in object_list)). Unlike a list comprehension, it will not generate an actual list of all the items, and is thus more efficient in situations such as this.\nAs a side note, Python has a built-in method id():\n\nReturn the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value. (Implementation note: this is the address of the object.)\n\nSo if you wanted to let Python handle the ids on its own, you could do it as:\nobject_dict = {id(x): x for x in object_list}\n\nor\nobject_dict = dict((id(x), x) for x in object_list)\n\n", "dict([(x.id, x) for x in list])\n\n", "dict(map(lambda x: [x.id, x], list))\n\n" ]
[ 107, 13, 6 ]
[]
[]
[ "dictionary", "lambda", "python" ]
stackoverflow_0003070242_dictionary_lambda_python.txt
Q: Python Logging across multiple classes and files; how to configure so as to be easily disabled? Currently, I have osmething like this in all of my classes: # Import logging to log information import logging # Set up the logger LOG_FILENAME = 'log.txt' logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG) This works well, and I get the output I want, but I would really like to have all this sort of information in one place, and be able to just do something like import myLogger and then start logging, and then hopefully be able to just go into that file and turn off logging when I need an extra performance boost. Thanks in advance A: To disable all logging from the root logger (which is all you're setting up with basicConfig), logging.getLogger().setLevel(logging.CRITICAL) If you want, you can encapsulate that into a function of your myLogger module, but that hardly seems worth it. A: To simply the setting up of logging, check out logging.config. To disable logging, you could use the command logging.disable(logging.CRITICAL)
Python Logging across multiple classes and files; how to configure so as to be easily disabled?
Currently, I have osmething like this in all of my classes: # Import logging to log information import logging # Set up the logger LOG_FILENAME = 'log.txt' logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG) This works well, and I get the output I want, but I would really like to have all this sort of information in one place, and be able to just do something like import myLogger and then start logging, and then hopefully be able to just go into that file and turn off logging when I need an extra performance boost. Thanks in advance
[ "To disable all logging from the root logger (which is all you're setting up with basicConfig),\nlogging.getLogger().setLevel(logging.CRITICAL)\n\nIf you want, you can encapsulate that into a function of your myLogger module, but that hardly seems worth it.\n", "To simply the setting up of logging, check out logging.config.\nTo disable logging, you could use the command\nlogging.disable(logging.CRITICAL)\n\n" ]
[ 3, 3 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0003070331_logging_python.txt
Q: multiline checkbox in wxpython I'm working with wxpython (2.8) with python 2.5. is it possible to force a wx.CheckBox to display its label on multiple lines? I'd like to be able to do the same as wx.StaticText.Wrap(width) See the attached example: the wx.CheckBox is 200 px wide, but it's label does not fit in this space. Any help is really appreciated! Thanks a lot Mauro #example starts here import wx class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, title="Hello World", size= (300,200)) self.panel = wx.Panel(self, -1) myVSizer = wx.BoxSizer(wx.VERTICAL) #instantiating a checkbox 200 px wide. but the label is too long cb = wx.CheckBox(self.panel, -1, label="This is a very very long label for 200 pixel wide cb!", size =wx.Size(200, -1)) myVSizer.Add( cb, 1) self.panel.SetSizer(myVSizer) myVSizer.Layout() app = wx.App(redirect=True) top = MyFrame() top.Show() app.MainLoop() A: what about something like this? Flex! (I've made it a radio button to show that it still behaves like one) import wx import textwrap class MultilineRadioButton(wx.RadioButton): def __init__(self, parent, id=-1, label=wx.EmptyString, wrap=10, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, validator=wx.DefaultValidator, name=wx.RadioButtonNameStr): wx.RadioButton.__init__(self,parent,id,'',pos,size,style,validator,name) self._label = label self._wrap = wrap lines = self._label.split('\n') self._wrappedLabel = [] for line in lines: self._wrappedLabel.extend(textwrap.wrap(line,self._wrap)) self._textHOffset = 20 dc = wx.ClientDC(self) font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) dc.SetFont(font) maxWidth = 0 totalHeight = 0 lineHeight = 0 for line in self._wrappedLabel: width, height = dc.GetTextExtent(line) maxWidth = max(maxWidth,width) lineHeight = height totalHeight += lineHeight self._textHeight = totalHeight self.SetInitialSize(wx.Size(self._textHOffset + maxWidth,totalHeight)) self.Bind(wx.EVT_PAINT, self.OnPaint) def OnPaint(self, event): dc = wx.PaintDC(self) self.Draw(dc) self.RefreshRect(wx.Rect(0,0,self._textHOffset,self.GetSize().height)) event.Skip() def Draw(self, dc): dc.Clear() font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) dc.SetFont(font) height = self.GetSize().height if height > self._textHeight: offset = height / 2 - self._textHeight / 2 else: offset = 0 for line in self._wrappedLabel: width, height = dc.GetTextExtent(line) dc.DrawText(line,self._textHOffset,offset) offset += height class HFrame(wx.Frame): def __init__(self,pos=wx.DefaultPosition): wx.Frame.__init__(self,None,title="Hello World",size=wx.Size(600,400),pos=pos) self.panel = wx.Panel(self,-1) sizer = wx.BoxSizer(wx.HORIZONTAL) cb = RadioButton(self.panel,-1,label="This is a very very long label for the control!",wrap=10) sizer.Add(cb,1) cb = RadioButton(self.panel,-1,label="This is a very very long label for the control!",wrap=10) sizer.Add(cb,1) cb = RadioButton(self.panel,-1,label="This is a very very long label for the control!",wrap=10) sizer.Add(cb,1) self.panel.SetSizer(sizer) sizer.Layout() class VFrame(wx.Frame): def __init__(self,pos=wx.DefaultPosition): wx.Frame.__init__(self,None,title="Hello World",size=wx.Size(600,400),pos=pos) self.panel = wx.Panel(self,-1) sizer = wx.BoxSizer(wx.VERTICAL) cb = RadioButton(self.panel,-1,label="This is a very very long label for the control!",wrap=10) sizer.Add(cb,1) cb = RadioButton(self.panel,-1,label="This is a very very long label for the control!",wrap=10) sizer.Add(cb,1) cb = RadioButton(self.panel,-1,label="This is a very very long label for the control!",wrap=10) sizer.Add(cb,1) self.panel.SetSizer(sizer) sizer.Layout() app = wx.App(redirect=False) htop = HFrame(pos=wx.Point(0,50)) htop.Show() vtop = VFrame(pos=wx.Point(650,50)) vtop.Show() app.MainLoop() A: Changing your label to label="This is a very very\n long label for 200\n pixel wide cb!" should do it. That is, put in explicit \n characters. A: Instead of using checkbox with text, use a no label checkbox with static text for desired effect e.g. import wx class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, title="Hello World", size=(300,200)) self.panel = wx.Panel(self, -1) myVSizer = wx.BoxSizer(wx.VERTICAL) # use checkbox + static text to wrap the text myHSizer = wx.BoxSizer(wx.HORIZONTAL) cb = wx.CheckBox(self.panel, -1, label="") label = wx.StaticText(self.panel, label="This is a very very long label for 100 pixel wide cb!", size=(100,-1)) label.Wrap(100) myHSizer.Add(cb, border=5, flag=wx.ALL) myHSizer.Add(label, border=5, flag=wx.ALL) myVSizer.Add(myHSizer) self.panel.SetSizer(myVSizer) myVSizer.Layout() app = wx.App(redirect=True) top = MyFrame() top.Show() app.MainLoop() this has added benefit that with different layouts you can make text centre to checkbox, or on left or right or any other place
multiline checkbox in wxpython
I'm working with wxpython (2.8) with python 2.5. is it possible to force a wx.CheckBox to display its label on multiple lines? I'd like to be able to do the same as wx.StaticText.Wrap(width) See the attached example: the wx.CheckBox is 200 px wide, but it's label does not fit in this space. Any help is really appreciated! Thanks a lot Mauro #example starts here import wx class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, title="Hello World", size= (300,200)) self.panel = wx.Panel(self, -1) myVSizer = wx.BoxSizer(wx.VERTICAL) #instantiating a checkbox 200 px wide. but the label is too long cb = wx.CheckBox(self.panel, -1, label="This is a very very long label for 200 pixel wide cb!", size =wx.Size(200, -1)) myVSizer.Add( cb, 1) self.panel.SetSizer(myVSizer) myVSizer.Layout() app = wx.App(redirect=True) top = MyFrame() top.Show() app.MainLoop()
[ "what about something like this? Flex!\n(I've made it a radio button to show that it still behaves like one)\nimport wx\nimport textwrap\n\nclass MultilineRadioButton(wx.RadioButton):\n def __init__(self, parent, id=-1, label=wx.EmptyString, wrap=10, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, validator=wx.DefaultValidator, name=wx.RadioButtonNameStr):\n wx.RadioButton.__init__(self,parent,id,'',pos,size,style,validator,name)\n self._label = label\n self._wrap = wrap\n lines = self._label.split('\\n')\n self._wrappedLabel = []\n for line in lines:\n self._wrappedLabel.extend(textwrap.wrap(line,self._wrap))\n\n self._textHOffset = 20\n dc = wx.ClientDC(self)\n font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)\n dc.SetFont(font)\n maxWidth = 0\n totalHeight = 0\n lineHeight = 0\n for line in self._wrappedLabel:\n width, height = dc.GetTextExtent(line)\n maxWidth = max(maxWidth,width)\n lineHeight = height\n totalHeight += lineHeight \n\n self._textHeight = totalHeight\n\n self.SetInitialSize(wx.Size(self._textHOffset + maxWidth,totalHeight))\n self.Bind(wx.EVT_PAINT, self.OnPaint)\n\n def OnPaint(self, event):\n dc = wx.PaintDC(self)\n self.Draw(dc)\n self.RefreshRect(wx.Rect(0,0,self._textHOffset,self.GetSize().height))\n event.Skip()\n\n def Draw(self, dc):\n dc.Clear()\n font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)\n dc.SetFont(font)\n height = self.GetSize().height\n if height > self._textHeight:\n offset = height / 2 - self._textHeight / 2\n else:\n offset = 0\n for line in self._wrappedLabel:\n width, height = dc.GetTextExtent(line)\n dc.DrawText(line,self._textHOffset,offset)\n offset += height\n\n\nclass HFrame(wx.Frame):\n def __init__(self,pos=wx.DefaultPosition):\n wx.Frame.__init__(self,None,title=\"Hello World\",size=wx.Size(600,400),pos=pos)\n\n self.panel = wx.Panel(self,-1)\n sizer = wx.BoxSizer(wx.HORIZONTAL)\n\n cb = RadioButton(self.panel,-1,label=\"This is a very very long label for the control!\",wrap=10)\n sizer.Add(cb,1)\n\n cb = RadioButton(self.panel,-1,label=\"This is a very very long label for the control!\",wrap=10)\n sizer.Add(cb,1)\n\n cb = RadioButton(self.panel,-1,label=\"This is a very very long label for the control!\",wrap=10)\n sizer.Add(cb,1)\n\n self.panel.SetSizer(sizer)\n sizer.Layout()\n\n\nclass VFrame(wx.Frame):\n def __init__(self,pos=wx.DefaultPosition):\n wx.Frame.__init__(self,None,title=\"Hello World\",size=wx.Size(600,400),pos=pos)\n\n self.panel = wx.Panel(self,-1)\n sizer = wx.BoxSizer(wx.VERTICAL)\n\n cb = RadioButton(self.panel,-1,label=\"This is a very very long label for the control!\",wrap=10)\n sizer.Add(cb,1)\n\n cb = RadioButton(self.panel,-1,label=\"This is a very very long label for the control!\",wrap=10)\n sizer.Add(cb,1)\n\n cb = RadioButton(self.panel,-1,label=\"This is a very very long label for the control!\",wrap=10)\n sizer.Add(cb,1)\n\n self.panel.SetSizer(sizer)\n sizer.Layout()\n\n\napp = wx.App(redirect=False)\nhtop = HFrame(pos=wx.Point(0,50))\nhtop.Show()\nvtop = VFrame(pos=wx.Point(650,50))\nvtop.Show()\napp.MainLoop()\n\n", "Changing your label to\nlabel=\"This is a very very\\n long label for 200\\n pixel wide cb!\"\n\nshould do it.\nThat is, put in explicit \\n characters.\n\n\n", "Instead of using checkbox with text, use a no label checkbox with static text for desired effect e.g.\nimport wx\n\n\nclass MyFrame(wx.Frame):\n def __init__(self):\n wx.Frame.__init__(self, None, title=\"Hello World\", size=(300,200))\n\n self.panel = wx.Panel(self, -1)\n myVSizer = wx.BoxSizer(wx.VERTICAL)\n\n # use checkbox + static text to wrap the text\n myHSizer = wx.BoxSizer(wx.HORIZONTAL)\n cb = wx.CheckBox(self.panel, -1, label=\"\")\n label = wx.StaticText(self.panel, label=\"This is a very very long label for 100 pixel wide cb!\", size=(100,-1))\n label.Wrap(100)\n myHSizer.Add(cb, border=5, flag=wx.ALL)\n myHSizer.Add(label, border=5, flag=wx.ALL)\n\n myVSizer.Add(myHSizer)\n\n self.panel.SetSizer(myVSizer)\n myVSizer.Layout()\n\n\napp = wx.App(redirect=True)\ntop = MyFrame()\ntop.Show()\napp.MainLoop()\n\nthis has added benefit that with different layouts you can make text centre to checkbox, or on left or right or any other place\n" ]
[ 3, 1, 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0001466140_python_wxpython.txt
Q: Can I use python ast module for this? I'd like to write a program that modify python programs in this way: change "some literal string %" % SOMETHING to functioncall("some literal string %") % SOMETHING Thanks, A: It may be simpler with tokenize -- adapting the example in the docs, import cStringIO import tokenize class Lookahead(object): def __init__(self, s): self._t = tokenize.generate_tokens(cStringIO.StringIO(s).readline) self.lookahead = next(self._t, None) def __iter__(self): return self def next(self): result = self.lookahead if result is None: raise StopIteration self.lookahead = next(self._t, None) return result def doit(s): toks = Lookahead(s) result = [] for toktype, tokvalue, _, _, _ in toks: if toktype == tokenize.STRING: pk = toks.lookahead if pk is not None and pk[0] == tokenize.OP and pk[1] == '%': result.extend([ (tokenize.NAME, 'functioncall'), (tokenize.OP, '('), (tokenize.STRING, repr(tokvalue)), (tokenize.OP, ')') ]) continue result.append((toktype, tokvalue)) return tokenize.untokenize(result) print doit('"some literal string %" % SOMETHING') This prints functioncall ('"some literal string %"')%SOMETHING. The spacing is pretty peculiar (it takes much more effort to get the spacing just right -- but that is even worse for reconstructing sources from a modified AST), but it's just fine if all you're going to do is import / run the resulting code (not so fine if you want to get nicely readable and editable code -- but that's a big enough problem that I'd suggest a separate Q;-). A: You can solve this with having to write a program. Instead simply use the best editor ever made: Emacs. Worth learning if you haven't already. With it you can solve this by using its regex-replace capability. The only trouble is that I rarely use regex's so I always forget the details of the cryptic syntax and have to still look it up :P I'll try to figure it again for you. Here's a link to the Search & Replace Info for Emacs - scroll down for using regex's A: Here is another SO question that may be useful. I gather that the ast module doesn't have a facility for returning to source code, but Armin Ronacher has written a module codegen which implements a to_source function for doing just that for ast nodes. I haven't tried to do this myself. A: import re pattern = r'(".+? %")(?= %)' oldstr = '"some literal string %" % SOMETHING' newstr = re.sub(pattern, r'functioncall(\1)', oldstr) Try something like that. (Though with file I/O, of course.) I haven't worked with ast at all yet, so I don't really know if using that would be any easier for something like this, but it seems to me that if you're just doing a simple search-replace and not actually doing a lot of complex parsing then there's no need to use ast.
Can I use python ast module for this?
I'd like to write a program that modify python programs in this way: change "some literal string %" % SOMETHING to functioncall("some literal string %") % SOMETHING Thanks,
[ "It may be simpler with tokenize -- adapting the example in the docs,\nimport cStringIO\nimport tokenize\n\nclass Lookahead(object):\n\n def __init__(self, s):\n self._t = tokenize.generate_tokens(cStringIO.StringIO(s).readline)\n self.lookahead = next(self._t, None)\n\n def __iter__(self):\n return self\n\n def next(self):\n result = self.lookahead\n if result is None: raise StopIteration\n self.lookahead = next(self._t, None)\n return result\n\n\ndef doit(s):\n toks = Lookahead(s)\n result = []\n for toktype, tokvalue, _, _, _ in toks:\n if toktype == tokenize.STRING:\n pk = toks.lookahead\n if pk is not None and pk[0] == tokenize.OP and pk[1] == '%':\n result.extend([\n (tokenize.NAME, 'functioncall'),\n (tokenize.OP, '('),\n (tokenize.STRING, repr(tokvalue)),\n (tokenize.OP, ')')\n ])\n continue\n result.append((toktype, tokvalue))\n return tokenize.untokenize(result)\n\n\nprint doit('\"some literal string %\" % SOMETHING')\n\nThis prints functioncall ('\"some literal string %\"')%SOMETHING. The spacing is pretty peculiar (it takes much more effort to get the spacing just right -- but that is even worse for reconstructing sources from a modified AST), but it's just fine if all you're going to do is import / run the resulting code (not so fine if you want to get nicely readable and editable code -- but that's a big enough problem that I'd suggest a separate Q;-).\n", "You can solve this with having to write a program. Instead simply use the best editor ever made: Emacs. Worth learning if you haven't already. With it you can solve this by using its regex-replace capability. The only trouble is that I rarely use regex's so I always forget the details of the cryptic syntax and have to still look it up :P I'll try to figure it again for you. Here's a link to the Search & Replace Info for Emacs - scroll down for using regex's\n", "Here is another SO question that may be useful.\nI gather that the ast module doesn't have a facility for returning to source code, but Armin Ronacher has written a module codegen which implements a to_source function for doing just that for ast nodes. \nI haven't tried to do this myself.\n", "import re\n\npattern = r'(\".+? %\")(?= %)'\noldstr = '\"some literal string %\" % SOMETHING'\n\nnewstr = re.sub(pattern, r'functioncall(\\1)', oldstr)\n\nTry something like that. (Though with file I/O, of course.) I haven't worked with ast at all yet, so I don't really know if using that would be any easier for something like this, but it seems to me that if you're just doing a simple search-replace and not actually doing a lot of complex parsing then there's no need to use ast.\n" ]
[ 2, 1, 0, 0 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0003069695_parsing_python.txt
Q: Access static class variable of parent class in Python I have someting like this class A: __a = 0 def __init__(self): A.__a = A.__a + 1 def a(self): return A.__a class B(A): def __init__(self): # how can I access / modify A.__a here? A.__a = A.__a + 1 # does not work def a(self): return A.__a Can I access the __a class variable in B? It's possible writing a instead of __a, is this the only way? (I guess the answer might be rather short: yes :) A: So, __a isn't a static variable, it's a class variable. And because of the double leading underscore, it's a name mangled variable. That is, to make it pseudo-private, it's been automagically renamed to _<classname>__<variablename> instead of __<variablename>. It can still be accessed by instances of that class only as __<variablename>, subclasses don't get this special treatment. I would recommend that you not use the double leading underscore, just a single underscore to (a) mark that it is private, and (b) to avoid the name mangling. A: Refer to it as A._A__a. In Python, symbols with a __ prefix occurring inside a class definition are prefixed with _<class-name> to make them somewhat "private". Thus the reference A.__a that appears in the definition of B is, counterintuitively, a reference to A._B__a: >>> class Foo(object): _Bar__a = 42 ... >>> class Bar(object): a = Foo.__a ... >>> Bar.a 42 A: There are Python decorators @staticmethod and @classmethod, which you can use to declare a method static or class-related. This should help accessing your class data element: class MyClass: __a = 0 @staticmethod def getA(): return MyClass.__a class MyOtherClass: def DoSomething(self): print MyClass.getA() + 1 Example inspired by this source: http://www.rexx.com/~dkuhlman/python_101/python_101.html
Access static class variable of parent class in Python
I have someting like this class A: __a = 0 def __init__(self): A.__a = A.__a + 1 def a(self): return A.__a class B(A): def __init__(self): # how can I access / modify A.__a here? A.__a = A.__a + 1 # does not work def a(self): return A.__a Can I access the __a class variable in B? It's possible writing a instead of __a, is this the only way? (I guess the answer might be rather short: yes :)
[ "So, __a isn't a static variable, it's a class variable. And because of the double leading underscore, it's a name mangled variable. That is, to make it pseudo-private, it's been automagically renamed to _<classname>__<variablename> instead of __<variablename>. It can still be accessed by instances of that class only as __<variablename>, subclasses don't get this special treatment.\nI would recommend that you not use the double leading underscore, just a single underscore to (a) mark that it is private, and (b) to avoid the name mangling.\n", "Refer to it as A._A__a. In Python, symbols with a __ prefix occurring inside a class definition are prefixed with _<class-name> to make them somewhat \"private\". Thus the reference A.__a that appears in the definition of B is, counterintuitively, a reference to A._B__a:\n>>> class Foo(object): _Bar__a = 42\n... \n>>> class Bar(object): a = Foo.__a\n... \n>>> Bar.a\n42\n\n", "There are Python decorators @staticmethod and @classmethod, which you can use to declare a method static or class-related. This should help accessing your class data element:\nclass MyClass:\n __a = 0\n\n @staticmethod\n def getA():\n return MyClass.__a\n\nclass MyOtherClass:\n\n def DoSomething(self):\n print MyClass.getA() + 1\n\nExample inspired by this source:\nhttp://www.rexx.com/~dkuhlman/python_101/python_101.html\n" ]
[ 11, 3, 1 ]
[]
[]
[ "class", "inheritance", "python", "static_variables" ]
stackoverflow_0003070543_class_inheritance_python_static_variables.txt
Q: Does REGEX differ from PHP to Python I found this post: Python Regex vs PHP Regex but I actually did not get if Python's REGEX syntax matches PHP's REGEX syntax. I started to convert some of my old PHP code to python (due to g's appengine etc.), and now I would like to know whether the regex is 100% convertable, by simple copy & paste. regards, A: Python uses a syntax similar to the Perl syntax and PHP uses the Perl Compatible Regular Expressions syntax, so it should be nearly the same. Read about the possible differences. The only real difference is that in PHP, the expression must be enclosed in delimiters. A: They are compatible for the most part. There are some differences, though, apart from the different syntax (/regex/ in PHP vs. re.compile(r"regex") in Python): PCRE supports \Q...E to escape metacharacters, Python doesn't. PCRE supports \cA-\cZ control character matching, Python doesn't. Hyphen in [\d-z] or [a-\d] is a literal in PHP, not in Python. PCRE supports \z (end-of-string), Python doesn't, only \Z (end-of-string before optional final linefeed). \b will match word boundaries only around ASCII characters in PCRE, in Python it can match locale-dependently if the option is set. You can refer to \1 etc. backreferences ahead of their capturing parentheses in PCRE, you can't in Python. You can't turn off mode modifiers within the regex ((?-s) etc.) in Python. You don't get atomic grouping (?>...) or possessive quantifiers (.++) in Python, only in PCRE. Lookbehind can be finite-length in PCRE, must be fixed-length in Python. There is no \G pattern (location of previous match). No conditional matching in Python, only in PCRE: (?(?=regex)then|else). No \x1234 for Unicode code points matching in Python. No p{L} and other Unicode property matching, either. In PHP, it depends how it's configured/compiled. No [:alpha:] POSIX character classes in Python. Collected from regular-expressions.info, leaving out some of the more esoteric stuff. But not much. Moral: Buy RegexBuddy and use it to translate the regexes for you. A: I believe they're at least mostly compatible, i.e. > 2/3. There may be some language-specific extensions on both sides, but the core is definitely the same. This assertion is based solely on my (limited) personal experience, so take it with a grain of salt. Both implementations are based on Perl regexes, if I'm not mistaken. A: Not certain of the right answer, but I found a nice tool that will help with your testing. http://re.dabase.com/ Cheers! A: After a very quick research, I found out that the main difference is: PHP (has delimiters) / REGEX / # "/" in front and at the end Python (has no delimiters) REGEX # no surrounding by any characters A: Regular expression engines which are built into various languages usually have differences even if the general syntax is the same. PHP happens have multiple regular expression engines built in (POSIX and PCRE), so depending on which regular expression functions you are using will depend on how well they'll convert over. If you mainly used preg_* functions then those should mainly convert over without an issue, however I believe the python implementation of regular expressions lacks some more advanced features which are included in the PHP implementation. You can read about PHP's regular expressions here and Python's regular expressions here and figure out some more specific stuff. Good question, but difficult to give a complete answer to as there are a lot of variables.
Does REGEX differ from PHP to Python
I found this post: Python Regex vs PHP Regex but I actually did not get if Python's REGEX syntax matches PHP's REGEX syntax. I started to convert some of my old PHP code to python (due to g's appengine etc.), and now I would like to know whether the regex is 100% convertable, by simple copy & paste. regards,
[ "Python uses a syntax similar to the Perl syntax and PHP uses the Perl Compatible Regular Expressions syntax, so it should be nearly the same. Read about the possible differences.\nThe only real difference is that in PHP, the expression must be enclosed in delimiters.\n", "They are compatible for the most part. There are some differences, though, apart from the different syntax (/regex/ in PHP vs. re.compile(r\"regex\") in Python):\n\nPCRE supports \\Q...E to escape metacharacters, Python doesn't.\nPCRE supports \\cA-\\cZ control character matching, Python doesn't.\nHyphen in [\\d-z] or [a-\\d] is a literal in PHP, not in Python.\nPCRE supports \\z (end-of-string), Python doesn't, only \\Z (end-of-string before optional final linefeed).\n\\b will match word boundaries only around ASCII characters in PCRE, in Python it can match locale-dependently if the option is set.\nYou can refer to \\1 etc. backreferences ahead of their capturing parentheses in PCRE, you can't in Python.\nYou can't turn off mode modifiers within the regex ((?-s) etc.) in Python.\nYou don't get atomic grouping (?>...) or possessive quantifiers (.++) in Python, only in PCRE.\nLookbehind can be finite-length in PCRE, must be fixed-length in Python.\nThere is no \\G pattern (location of previous match).\nNo conditional matching in Python, only in PCRE: (?(?=regex)then|else).\nNo \\x1234 for Unicode code points matching in Python. No p{L} and other Unicode property matching, either. In PHP, it depends how it's configured/compiled.\nNo [:alpha:] POSIX character classes in Python.\n\nCollected from regular-expressions.info, leaving out some of the more esoteric stuff. But not much.\nMoral: Buy RegexBuddy and use it to translate the regexes for you.\n", "I believe they're at least mostly compatible, i.e. > 2/3. There may be some language-specific extensions on both sides, but the core is definitely the same. This assertion is based solely on my (limited) personal experience, so take it with a grain of salt.\nBoth implementations are based on Perl regexes, if I'm not mistaken.\n", "Not certain of the right answer, but I found a nice tool that will help with your testing.\nhttp://re.dabase.com/\nCheers!\n", "After a very quick research, I found out that the main difference is:\nPHP (has delimiters)\n/ REGEX / # \"/\" in front and at the end\n\nPython (has no delimiters)\nREGEX # no surrounding by any characters\n\n", "Regular expression engines which are built into various languages usually have differences even if the general syntax is the same. PHP happens have multiple regular expression engines built in (POSIX and PCRE), so depending on which regular expression functions you are using will depend on how well they'll convert over.\nIf you mainly used preg_* functions then those should mainly convert over without an issue, however I believe the python implementation of regular expressions lacks some more advanced features which are included in the PHP implementation.\nYou can read about PHP's regular expressions here and Python's regular expressions here and figure out some more specific stuff.\nGood question, but difficult to give a complete answer to as there are a lot of variables.\n" ]
[ 11, 11, 1, 1, 1, 1 ]
[]
[]
[ "php", "python", "regex" ]
stackoverflow_0003070655_php_python_regex.txt
Q: Some kind of event functionality in Django? I have a view my Django application which when invoked calls my backend. My backend logic sometimes reaches a point when it needs user input to continue. When this happens, I pickle dump my backend data into the session so that i can resume it later on. Currently i have defined the scenario when user input is required as a custom exception which i raise. This exception bubbles up all the way to the view where I trap it and do the needful. This works but it isn't really an exception. Is there some kind of event functionality in Django that I could use? Is there a better way to accomplish this? A: Personnaly, I use the exception mechanism for this kind of stuff and I don't really see why I shouldn't A: I'd say there are two ways: You assume that data should be present and if they are not, custom exception should be raised as mentioned. However, if it's part of expected workflow and it may just be present in a state, I'd handle it accordingly, i.e. by checking results from view calls. (And I'd say that continuations from Seaside are best solution for this, as far as I understand them) Definitely, signals are not for this; they are designed to "hook" on specific events, which is not what You want.
Some kind of event functionality in Django?
I have a view my Django application which when invoked calls my backend. My backend logic sometimes reaches a point when it needs user input to continue. When this happens, I pickle dump my backend data into the session so that i can resume it later on. Currently i have defined the scenario when user input is required as a custom exception which i raise. This exception bubbles up all the way to the view where I trap it and do the needful. This works but it isn't really an exception. Is there some kind of event functionality in Django that I could use? Is there a better way to accomplish this?
[ "Personnaly, I use the exception mechanism for this kind of stuff and I don't really see why I shouldn't\n", "I'd say there are two ways: You assume that data should be present and if they are not, custom exception should be raised as mentioned.\nHowever, if it's part of expected workflow and it may just be present in a state, I'd handle it accordingly, i.e. by checking results from view calls.\n(And I'd say that continuations from Seaside are best solution for this, as far as I understand them)\nDefinitely, signals are not for this; they are designed to \"hook\" on specific events, which is not what You want.\n" ]
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003069583_django_python.txt
Q: Joining the previous and next sentence using python I'm trying to join a set of sentences contained in a list. I have a function which determines whether a sentence in worth saving. However, in order to keep the context of the sentence I need to also keep the sentence before and after it. In the edge cases, where its either the first or last sentence then, I'll just keep the sentence and its only neighbor. An example is best: ex_paragraph = ['The quick brown fox jumps over the fence.', 'Where there is another red fox.', 'They run off together.', 'They live hapily ever after.'] t1 = lambda x: x.startswith('Where') t2 = lambda x: x'startswith('The ') The result for t1 should be: ['The quick brown fox jumps over the fence. Where there is another red fox. They run off together.'] The result for t2 should be: ['The quick brown fox jumps over the fence. Where there is another red fox.'] My solution is: def YieldContext(sent_list, cont_fun): def JoinSent(sent_list, ind): if ind == 0: return sent_list[ind]+sent_list[ind+1] elif ind == len(sent_list)-1: return sent_list[ind-1]+sent_list[ind] else: return ' '.join(sent_list[ind-1:ind+1]) for sent, sentnum in izip(sent_list, count(0)): if cont_fun(sent): yield JoinSent(sent_list, sent_num) Does anyone know a "cleaner" or more pythonic way to do something like this. The if-elif-else seems a little forced. Thanks, Will PS. I'm obviously doing this with a more complicated "context-function" but this is just for a simple example. A: Appending an empty string to the beginning and end of the list is actually a good idea, but there is actually no need to use fancy list comprehension or such. You can build a generator very easily: def yieldContext(l, func): l = [''] + l + [''] for i, s in enumerate(l): if func(s): yield ' '.join(l[i-1:i+2]).strip() gives: >>> print list(yieldContext(ex_paragraph, t1)) ['The quick brown fox jumps over the fence. Where there is another red fox. They run off together.'] >>> print list(yieldContext(ex_paragraph, t2)) ['The quick brown fox jumps over the fence. Where there is another red fox.'] (If you really want to create a list, there is not much of a difference. It depends mostly on how many sentences you have and what you want to do with the "context") def yieldContext(l, func): l = [''] + l + [''] return [' '.join(l[i-1:i+2]).strip() for i, s in enumerate(l) if func(s)] A: I might do something like this: from itertools import izip, tee prev, this, next = tee([''] + ex_paragraph + [''], 3) this.next() next.next() next.next() [' '.join(ctx).strip() for ctx in izip(prev, this, next) if cont_fun(this)] where cont_fun is one of t1 or t2. A: Well, I'd probably only write iffs on oneline: def join_send(sent_list, ind): items = [sent_list[i] for i in (ind-1, ind, ind+1) if i >= 0 and i < len(sent_list)] return ' '.join(items) But it's probably disputable if this is readable. P.S.: What would be certainly more pythonic would be to use PEP 8-style names, i.e. yield_context. Or hey, even yieldContext would be feasable in some libraries...but YieldContext? A: return ' '.join(sent_list[max(0,ind-1):min(len(ind),ind+2)])
Joining the previous and next sentence using python
I'm trying to join a set of sentences contained in a list. I have a function which determines whether a sentence in worth saving. However, in order to keep the context of the sentence I need to also keep the sentence before and after it. In the edge cases, where its either the first or last sentence then, I'll just keep the sentence and its only neighbor. An example is best: ex_paragraph = ['The quick brown fox jumps over the fence.', 'Where there is another red fox.', 'They run off together.', 'They live hapily ever after.'] t1 = lambda x: x.startswith('Where') t2 = lambda x: x'startswith('The ') The result for t1 should be: ['The quick brown fox jumps over the fence. Where there is another red fox. They run off together.'] The result for t2 should be: ['The quick brown fox jumps over the fence. Where there is another red fox.'] My solution is: def YieldContext(sent_list, cont_fun): def JoinSent(sent_list, ind): if ind == 0: return sent_list[ind]+sent_list[ind+1] elif ind == len(sent_list)-1: return sent_list[ind-1]+sent_list[ind] else: return ' '.join(sent_list[ind-1:ind+1]) for sent, sentnum in izip(sent_list, count(0)): if cont_fun(sent): yield JoinSent(sent_list, sent_num) Does anyone know a "cleaner" or more pythonic way to do something like this. The if-elif-else seems a little forced. Thanks, Will PS. I'm obviously doing this with a more complicated "context-function" but this is just for a simple example.
[ "Appending an empty string to the beginning and end of the list is actually a good idea, but there is actually no need to use fancy list comprehension or such. You can build a generator very easily:\ndef yieldContext(l, func):\n l = [''] + l + ['']\n for i, s in enumerate(l):\n if func(s):\n yield ' '.join(l[i-1:i+2]).strip()\n\ngives:\n>>> print list(yieldContext(ex_paragraph, t1))\n['The quick brown fox jumps over the fence. Where there is another red fox. They run off together.']\n\n>>> print list(yieldContext(ex_paragraph, t2))\n['The quick brown fox jumps over the fence. Where there is another red fox.']\n\n\n(If you really want to create a list, there is not much of a difference. It depends mostly on how many sentences you have and what you want to do with the \"context\")\ndef yieldContext(l, func):\n l = [''] + l + ['']\n return [' '.join(l[i-1:i+2]).strip() for i, s in enumerate(l) if func(s)]\n\n", "I might do something like this:\nfrom itertools import izip, tee\nprev, this, next = tee([''] + ex_paragraph + [''], 3)\nthis.next()\nnext.next()\nnext.next()\n[' '.join(ctx).strip() for ctx in izip(prev, this, next) if cont_fun(this)]\n\nwhere cont_fun is one of t1 or t2.\n", "Well, I'd probably only write iffs on oneline:\ndef join_send(sent_list, ind):\n items = [sent_list[i] for i in (ind-1, ind, ind+1) if i >= 0 and i < len(sent_list)]\n return ' '.join(items)\n\nBut it's probably disputable if this is readable.\nP.S.: What would be certainly more pythonic would be to use PEP 8-style names, i.e. yield_context. Or hey, even yieldContext would be feasable in some libraries...but YieldContext?\n", "return ' '.join(sent_list[max(0,ind-1):min(len(ind),ind+2)])\n\n" ]
[ 4, 1, 1, 0 ]
[]
[]
[ "iterator", "python" ]
stackoverflow_0003070695_iterator_python.txt
Q: Problem accessing config files within a Python egg I have a Python project that has the following structure: package1 class.py class2.py ... package2 otherClass.py otherClass2.py ... config dev_settings.ini prod_settings.ini I wrote a setup.py file that converts this into an egg with the same file structure. (When I examine it using a zip program the structure seems identical.) The funny thing is, when I run the Python code from my IDE it works fine and can access the config files; but when I try to run it from a different Python script using the egg, it can't seem to find the config files in the egg. If I put the config files into a directory relative to the calling Python script (external to the egg), it works - but that sort of defeats the purpose of having a self-contained egg that has all the functionality of the program and can be called from anywhere. I can use any classes/modules and run any functions from the egg as long as they don't use the config files... but if they do, the egg can't find them and so the functions don't work. Any help would be really appreciated! We're kind of new to the egg thing here and don't really know where to start. A: The problem is, the config files are not files anymore - they're packaged within the egg. It's not easy to find the answer in the docs, but it is there. From the setuptools developer's guide: Typically, existing programs manipulate a package's __file__ attribute in order to find the location of data files. However, this manipulation isn't compatible with PEP 302-based import hooks, including importing from zip files and Python Eggs. To access them, you need to follow the instructions for the Resource Management API. In my own code, I had this problem with a logging configuration file. I used the API successfully like this: from pkg_resources import resource_stream _log_config_file = 'logging.conf' _log_config_location = resource_stream(__name__, _log_config_file) logging.config.fileConfig(_log_config_location) _log = logging.getLogger('package.module') A: See Setuptools' discussion of accessing pacakged data files at runtime. You have to get at your configuration file a different way if you want the script to work inside an egg. Also, for that to work, you may need to make your config directory a Python package by tossing in an empty __init__.py file.
Problem accessing config files within a Python egg
I have a Python project that has the following structure: package1 class.py class2.py ... package2 otherClass.py otherClass2.py ... config dev_settings.ini prod_settings.ini I wrote a setup.py file that converts this into an egg with the same file structure. (When I examine it using a zip program the structure seems identical.) The funny thing is, when I run the Python code from my IDE it works fine and can access the config files; but when I try to run it from a different Python script using the egg, it can't seem to find the config files in the egg. If I put the config files into a directory relative to the calling Python script (external to the egg), it works - but that sort of defeats the purpose of having a self-contained egg that has all the functionality of the program and can be called from anywhere. I can use any classes/modules and run any functions from the egg as long as they don't use the config files... but if they do, the egg can't find them and so the functions don't work. Any help would be really appreciated! We're kind of new to the egg thing here and don't really know where to start.
[ "The problem is, the config files are not files anymore - they're packaged within the egg. It's not easy to find the answer in the docs, but it is there. From the setuptools developer's guide:\n\nTypically, existing programs manipulate a package's __file__ attribute in order to find the location of data files. However, this manipulation isn't compatible with PEP 302-based import hooks, including importing from zip files and Python Eggs.\n\nTo access them, you need to follow the instructions for the Resource Management API.\nIn my own code, I had this problem with a logging configuration file. I used the API successfully like this:\nfrom pkg_resources import resource_stream\n\n_log_config_file = 'logging.conf'\n_log_config_location = resource_stream(__name__, _log_config_file)\nlogging.config.fileConfig(_log_config_location)\n_log = logging.getLogger('package.module')\n\n", "See Setuptools' discussion of accessing pacakged data files at runtime. You have to get at your configuration file a different way if you want the script to work inside an egg. Also, for that to work, you may need to make your config directory a Python package by tossing in an empty __init__.py file.\n" ]
[ 12, 2 ]
[]
[]
[ "egg", "file", "python" ]
stackoverflow_0003071327_egg_file_python.txt
Q: Yield only as many are required from a generator I wish to yield from a generator only as many items are required. In the following code a, b, c = itertools.count() I receive this exception: ValueError: too many values to unpack I've seen several related questions, however I have zero interest in the remaining items from the generator, I only wish to receive as many as I ask for, without providing that quantity in advance. It seems to me that Python determines the number of items you want, but then proceeds to try to read and store more than that number (generating ValueError). How can I yield only as many items as I require, without passing in how many items I want? Update0 To aid in understanding the approximate behaviour I believe should be possible, here's a code sample: def unpack_seq(ctx, items, seq): for name in items: setattr(ctx, name, seq.next()) import itertools, sys unpack_seq(sys.modules[__name__], ["a", "b", "c"], itertools.count()) print a, b, c If you can improve this code please do. Alex Martelli's answer suggests to me the byte op UNPACK_SEQUENCE is responsible for the limitation. I don't see why this operation should require that generated sequences must also exactly match in length. Note that Python 3 has different unpack syntaxes which probably invalidate technical discussion in this question. A: You need to make sure that the number of items on both sides matches. One way is to use islice from the itertools module: from itertools import islice a, b, c = islice(itertools.count(), 3) A: You need a deep bytecode hack - what you request cannot be done at Python source code level, but (if you're willing to commit to a specific version and release of Python) may be doable by post-processing the bytecode after Python has compiled it. Consider, e.g.: >>> def f(someit): ... a, b, c = someit() ... >>> dis.dis(f) 2 0 LOAD_FAST 0 (someit) 3 CALL_FUNCTION 0 6 UNPACK_SEQUENCE 3 9 STORE_FAST 1 (a) 12 STORE_FAST 2 (b) 15 STORE_FAST 3 (c) 18 LOAD_CONST 0 (None) 21 RETURN_VALUE >>> As you see, the UNPACK_SEQUENCE 3 bytecode occurs without the iterator someit being given the least indication of it (the iterator has already been called!) -- so you must prefix it in the bytecode with a "get exactly N bytes" operation, e.g.: >>> def g(someit): ... a, b, c = limit(someit(), 3) ... >>> dis.dis(g) 2 0 LOAD_GLOBAL 0 (limit) 3 LOAD_FAST 0 (someit) 6 CALL_FUNCTION 0 9 LOAD_CONST 1 (3) 12 CALL_FUNCTION 2 15 UNPACK_SEQUENCE 3 18 STORE_FAST 1 (a) 21 STORE_FAST 2 (b) 24 STORE_FAST 3 (c) 27 LOAD_CONST 0 (None) 30 RETURN_VALUE where limit is your own function, easily implemented (e.g via itertools.slice). So, the original 2-bytecode "load fast; call function" sequence (just before the unpack-sequence bytecode) must become this kind of 5-bytecode sequence, with a load-global bytecode for limit before the original sequence, and the load-const; call function sequence after it. You can of course implement this bytecode munging in a decorator. Alternatively (for generality) you could work on altering the function's original source, e.g. via parsing and alteration of the AST, and recompiling to byte code (but that does require the source to be available at decoration time, of course). Is this worth it for production use? Absolutely not, of course -- ridiculous amount of work for a tiny "syntax sugar" improvement. However, it can be an instructive project to pursue to gain mastery in bytecode hacking, ast hacking, and other black magic tricks that you will probably never need but are surely cool to know when you want to move beyond the language of mere language wizard to that of world-class guru -- indeed I suspect that those who are motivated to become gurus are typically people who can't fail to yield to the fascination of such "language internals' mechanics"... and those who actually make it to that exalted level are the subset wise enough to realize such endeavors are "just play", and pursue them as a spare-time activity (mental equivalent of weight lifting, much like, say, sudoku or crosswords;-) without letting them interfere with the important tasks (delivering value to users by deploying solid, clear, simple, well-performing, well-tested, well-documented code, most often without even the slightest hint of black magic to it;-). A: Python does not work the way you desire. In any assignment, like a, b, c = itertools.count() the right-hand side is evaluated first, before the left-hand side. The right-hand side can not know how many items are on the left-hand side unless you tell it. A: Or use a list comprehension, since you know the desired number of items: ic = itertools.count() a,b,c = [ic.next() for i in range(3)] or even simpler: a,b,c = range(3)
Yield only as many are required from a generator
I wish to yield from a generator only as many items are required. In the following code a, b, c = itertools.count() I receive this exception: ValueError: too many values to unpack I've seen several related questions, however I have zero interest in the remaining items from the generator, I only wish to receive as many as I ask for, without providing that quantity in advance. It seems to me that Python determines the number of items you want, but then proceeds to try to read and store more than that number (generating ValueError). How can I yield only as many items as I require, without passing in how many items I want? Update0 To aid in understanding the approximate behaviour I believe should be possible, here's a code sample: def unpack_seq(ctx, items, seq): for name in items: setattr(ctx, name, seq.next()) import itertools, sys unpack_seq(sys.modules[__name__], ["a", "b", "c"], itertools.count()) print a, b, c If you can improve this code please do. Alex Martelli's answer suggests to me the byte op UNPACK_SEQUENCE is responsible for the limitation. I don't see why this operation should require that generated sequences must also exactly match in length. Note that Python 3 has different unpack syntaxes which probably invalidate technical discussion in this question.
[ "You need to make sure that the number of items on both sides matches. One way is to use islice from the itertools module:\nfrom itertools import islice\na, b, c = islice(itertools.count(), 3)\n\n", "You need a deep bytecode hack - what you request cannot be done at Python source code level, but (if you're willing to commit to a specific version and release of Python) may be doable by post-processing the bytecode after Python has compiled it. Consider, e.g.:\n>>> def f(someit):\n... a, b, c = someit()\n... \n>>> dis.dis(f)\n 2 0 LOAD_FAST 0 (someit)\n 3 CALL_FUNCTION 0\n 6 UNPACK_SEQUENCE 3\n 9 STORE_FAST 1 (a)\n 12 STORE_FAST 2 (b)\n 15 STORE_FAST 3 (c)\n 18 LOAD_CONST 0 (None)\n 21 RETURN_VALUE \n>>> \n\nAs you see, the UNPACK_SEQUENCE 3 bytecode occurs without the iterator someit being given the least indication of it (the iterator has already been called!) -- so you must prefix it in the bytecode with a \"get exactly N bytes\" operation, e.g.:\n>>> def g(someit):\n... a, b, c = limit(someit(), 3)\n... \n>>> dis.dis(g)\n 2 0 LOAD_GLOBAL 0 (limit)\n 3 LOAD_FAST 0 (someit)\n 6 CALL_FUNCTION 0\n 9 LOAD_CONST 1 (3)\n 12 CALL_FUNCTION 2\n 15 UNPACK_SEQUENCE 3\n 18 STORE_FAST 1 (a)\n 21 STORE_FAST 2 (b)\n 24 STORE_FAST 3 (c)\n 27 LOAD_CONST 0 (None)\n 30 RETURN_VALUE \n\nwhere limit is your own function, easily implemented (e.g via itertools.slice). So, the original 2-bytecode \"load fast; call function\" sequence (just before the unpack-sequence bytecode) must become this kind of 5-bytecode sequence, with a load-global bytecode for limit before the original sequence, and the load-const; call function sequence after it.\nYou can of course implement this bytecode munging in a decorator.\nAlternatively (for generality) you could work on altering the function's original source, e.g. via parsing and alteration of the AST, and recompiling to byte code (but that does require the source to be available at decoration time, of course).\nIs this worth it for production use? Absolutely not, of course -- ridiculous amount of work for a tiny \"syntax sugar\" improvement. However, it can be an instructive project to pursue to gain mastery in bytecode hacking, ast hacking, and other black magic tricks that you will probably never need but are surely cool to know when you want to move beyond the language of mere language wizard to that of world-class guru -- indeed I suspect that those who are motivated to become gurus are typically people who can't fail to yield to the fascination of such \"language internals' mechanics\"... and those who actually make it to that exalted level are the subset wise enough to realize such endeavors are \"just play\", and pursue them as a spare-time activity (mental equivalent of weight lifting, much like, say, sudoku or crosswords;-) without letting them interfere with the important tasks (delivering value to users by deploying solid, clear, simple, well-performing, well-tested, well-documented code, most often without even the slightest hint of black magic to it;-).\n", "Python does not work the way you desire. In any assignment, like\na, b, c = itertools.count()\n\nthe right-hand side is evaluated first, before the left-hand side.\nThe right-hand side can not know how many items are on the left-hand side unless you tell it.\n", "Or use a list comprehension, since you know the desired number of items:\nic = itertools.count()\na,b,c = [ic.next() for i in range(3)]\n\nor even simpler:\na,b,c = range(3)\n\n" ]
[ 6, 6, 3, 1 ]
[]
[]
[ "generator", "python", "python_2.x", "yield" ]
stackoverflow_0003070164_generator_python_python_2.x_yield.txt
Q: How to use float ** from C in Python? after having no success with my question on How to use float ** in Python with Swig?, I started thinking that swig might not be the weapon of choice. I need bindings for some c functions. One of these functions takes a float**. What would you recomend? Ctypes? Interface file: extern int read_data(const char *file,int *n_,int *m_,float **data_,int **classes_); A: I've used ctypes for several projects now and have been quite happy with the results. I don't think I've personally needed a pointer-to-pointer wrapper yet but, in theory, you should be able to do the following: from ctypes import * your_dll = cdll.LoadLibrary("your_dll.dll") PFloat = POINTER(c_float) PInt = POINTER(c_int) p_data = PFloat() p_classes = PInt() buff = create_string_buffer(1024) n1 = c_int( 0 ) n2 = c_int( 0 ) ret = your_dll.read_data( buff, byref(n1), byref(n2), byref(p_data), byref(p_classes) ) print('Data: ', p_data.contents) print('Classes: ', p_classes.contents)
How to use float ** from C in Python?
after having no success with my question on How to use float ** in Python with Swig?, I started thinking that swig might not be the weapon of choice. I need bindings for some c functions. One of these functions takes a float**. What would you recomend? Ctypes? Interface file: extern int read_data(const char *file,int *n_,int *m_,float **data_,int **classes_);
[ "I've used ctypes for several projects now and have been quite happy with the results. I don't think I've personally needed a pointer-to-pointer wrapper yet but, in theory, you should be able to do the following:\nfrom ctypes import *\n\nyour_dll = cdll.LoadLibrary(\"your_dll.dll\")\n\nPFloat = POINTER(c_float)\nPInt = POINTER(c_int)\n\np_data = PFloat()\np_classes = PInt()\nbuff = create_string_buffer(1024)\nn1 = c_int( 0 )\nn2 = c_int( 0 )\n\nret = your_dll.read_data( buff, byref(n1), byref(n2), byref(p_data), byref(p_classes) )\n\nprint('Data: ', p_data.contents)\nprint('Classes: ', p_classes.contents)\n\n" ]
[ 2 ]
[]
[]
[ "c", "ctypes", "pointers", "python", "swig" ]
stackoverflow_0003069967_c_ctypes_pointers_python_swig.txt
Q: How do I get all of the values from a GWT multiselect ListBox on a post? I have a multiselect ListBox in a FormPanel in GWT. I have set the name of the listbox to "foo" via ListBox.setName(). When I post the form, I see that all of the selected values get posted, but all are bound to the same name "foo". So I seemingly cannot get each of the posted values (I am using Django/Python server-side to handle the post). When I access params['foo'] in Django, I only pick up the last posted value. How do I get to all of the values? Thanks. A: Use params.getlist('foo'). See the documentation for QueryDict objects.
How do I get all of the values from a GWT multiselect ListBox on a post?
I have a multiselect ListBox in a FormPanel in GWT. I have set the name of the listbox to "foo" via ListBox.setName(). When I post the form, I see that all of the selected values get posted, but all are bound to the same name "foo". So I seemingly cannot get each of the posted values (I am using Django/Python server-side to handle the post). When I access params['foo'] in Django, I only pick up the last posted value. How do I get to all of the values? Thanks.
[ "Use params.getlist('foo').\nSee the documentation for QueryDict objects.\n" ]
[ 0 ]
[]
[]
[ "django", "gwt", "listbox", "post", "python" ]
stackoverflow_0003071449_django_gwt_listbox_post_python.txt
Q: Convert python variables into javascript variables I want to use Google Chart API using javascript. (I don't want to use the python wrapper) So how do I send data from my python code into the javascript to create graphs? A: You can translate Python data to Javascript data types with JSON ( http://docs.python.org/library/json.html ). I assume you're using this alongside a Python-based web server?
Convert python variables into javascript variables
I want to use Google Chart API using javascript. (I don't want to use the python wrapper) So how do I send data from my python code into the javascript to create graphs?
[ "You can translate Python data to Javascript data types with JSON ( http://docs.python.org/library/json.html ). I assume you're using this alongside a Python-based web server?\n" ]
[ 2 ]
[]
[]
[ "google_visualization", "javascript", "python" ]
stackoverflow_0003071411_google_visualization_javascript_python.txt
Q: Cookie not accepted on IE when authenticating with Graph API (oauth) - iframe app I started playing with the new graph api with the python sdk. I'm trying to use the python-sdk in an iframe app to make the authentication (I successfully did it with JS - although the popup is blocked on IE and chrome by default). I'm following this example: http://github.com/facebook/python-sdk/blob/master/examples/oauth/facebookoauth.py It works on chrome and firefox, but in safari and IE it only works if I set the cookie permissions in the browser to the lowest possible (which is impractical for average users) Any ideas ? Ze A: IE Make sure the P3P header is set on all responses served through the iframe Safari Don't know. Some indicate that there is no better way than what you've already figured out. A: response.headers['P3P'] = 'CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"'
Cookie not accepted on IE when authenticating with Graph API (oauth) - iframe app
I started playing with the new graph api with the python sdk. I'm trying to use the python-sdk in an iframe app to make the authentication (I successfully did it with JS - although the popup is blocked on IE and chrome by default). I'm following this example: http://github.com/facebook/python-sdk/blob/master/examples/oauth/facebookoauth.py It works on chrome and firefox, but in safari and IE it only works if I set the cookie permissions in the browser to the lowest possible (which is impractical for average users) Any ideas ? Ze
[ "IE\nMake sure the P3P header is set on all responses served through the iframe\nSafari\nDon't know. Some indicate that there is no better way than what you've already figured out.\n", "response.headers['P3P'] = 'CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\"'\n\n" ]
[ 0, 0 ]
[]
[]
[ "facebook", "oauth", "python" ]
stackoverflow_0003071462_facebook_oauth_python.txt