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:
Why is IronPython faster than the Official Python Interpreter
According to this:
http://www.codeplex.com/IronPython/Wiki/View.aspx?title=IP20VsCPy25Perf&referringTitle=IronPython%20Performance
IronPython (Python for .Net) is faster than regular Python (cPython) on the same machine. Why is this? I would think compiled C code would always be faster than the equivalent CLI bytecode.
A:
Python code doesn't get compiled to C, Python itself is written in C and interprets Python bytecode. CIL gets compiled to machine code, which is why you see better performance when using IronPython.
A:
You're right, C is a lot faster. That's why in those results CPython is twice as fast when it comes to dictionaries, which are almost pure C. On the other hand, Python code is not compiled, it's interpreted. Function calls in CPython are terribly slow.
But on the other hand:
TryRaiseExcept: +4478.9%
Now, there's where IronPython get is horribly wrong.
And then, there is this PyPy project, with one of the objectives being Just-In-Time compiler. There is even subset of Python, called RPython (Reduced Python) which can be statically compiled. Which of course is a lot faster.
A:
I'm not sure exactly how you're drawing the conclusion that IronPython is faster than CPython. The link that you post seems to indicate that they're good at different things (like exceptions as has been pointed out).
A:
Wandering off your question "Why?", to "Oh, really?" The "good at different things" (Jason Baker) is right on. For example, cpython beats IronPython hands down start up time.
c:\Python26\python.exe Hello.py
c:\IronPython\ipy.exe Hello.py
Cpython executes a basic hello world nearly instantly(<100ms), where IronPython has an startup overhead of 4 or 5 seconds. This annoys me, but not enough to keep me from using IronPython.
A:
Could it be explained by this notation on the page you linked to:
Due to site caching in the Dynamic
Language Runtime, IronPython performs
better with more PyStone passes than
the default value
|
Why is IronPython faster than the Official Python Interpreter
|
According to this:
http://www.codeplex.com/IronPython/Wiki/View.aspx?title=IP20VsCPy25Perf&referringTitle=IronPython%20Performance
IronPython (Python for .Net) is faster than regular Python (cPython) on the same machine. Why is this? I would think compiled C code would always be faster than the equivalent CLI bytecode.
|
[
"Python code doesn't get compiled to C, Python itself is written in C and interprets Python bytecode. CIL gets compiled to machine code, which is why you see better performance when using IronPython.\n",
"You're right, C is a lot faster. That's why in those results CPython is twice as fast when it comes to dictionaries, which are almost pure C. On the other hand, Python code is not compiled, it's interpreted. Function calls in CPython are terribly slow. \nBut on the other hand: \nTryRaiseExcept: +4478.9%\n\nNow, there's where IronPython get is horribly wrong.\nAnd then, there is this PyPy project, with one of the objectives being Just-In-Time compiler. There is even subset of Python, called RPython (Reduced Python) which can be statically compiled. Which of course is a lot faster.\n",
"I'm not sure exactly how you're drawing the conclusion that IronPython is faster than CPython. The link that you post seems to indicate that they're good at different things (like exceptions as has been pointed out).\n",
"Wandering off your question \"Why?\", to \"Oh, really?\" The \"good at different things\" (Jason Baker) is right on. For example, cpython beats IronPython hands down start up time. \nc:\\Python26\\python.exe Hello.py\nc:\\IronPython\\ipy.exe Hello.py\n\nCpython executes a basic hello world nearly instantly(<100ms), where IronPython has an startup overhead of 4 or 5 seconds. This annoys me, but not enough to keep me from using IronPython. \n",
"Could it be explained by this notation on the page you linked to:\n\nDue to site caching in the Dynamic\n Language Runtime, IronPython performs\n better with more PyStone passes than\n the default value\n\n"
] |
[
41,
9,
5,
5,
4
] |
[] |
[] |
[
"ironpython",
"performance",
"python"
] |
stackoverflow_0000504716_ironpython_performance_python.txt
|
Q:
Quick primer on implementing a COM object that implement some custom IDLs in python?
Does anyone have experience using python to create a COM object that implements some custom IDLs?
Basically I'd like to know if it's extremely simple to do compared to c++, and if it is do you know of a good tutorial?
A:
The tutorial you are looking for is in the Python Programming On Win32 book, by Mark Hammond and Andy Robinson. A bit old, and the COM object creation info is distributed across some chapters.
A more recent example, simple COM server using Python, can give you a quick start.
A:
There is also comtypes, which allows to access and implement custom interfaces. An article on codeproject has a nice tutorial.
A:
You should also check Advance COM a free chapter from Python Programming On Win32 mentioned by gimel.
|
Quick primer on implementing a COM object that implement some custom IDLs in python?
|
Does anyone have experience using python to create a COM object that implements some custom IDLs?
Basically I'd like to know if it's extremely simple to do compared to c++, and if it is do you know of a good tutorial?
|
[
"The tutorial you are looking for is in the Python Programming On Win32 book, by Mark Hammond and Andy Robinson. A bit old, and the COM object creation info is distributed across some chapters.\nA more recent example, simple COM server using Python, can give you a quick start.\n",
"There is also comtypes, which allows to access and implement custom interfaces. An article on codeproject has a nice tutorial.\n",
"You should also check Advance COM a free chapter from Python Programming On Win32 mentioned by gimel.\n"
] |
[
3,
2,
1
] |
[] |
[] |
[
"com",
"python"
] |
stackoverflow_0000550450_com_python.txt
|
Q:
Using Beautiful Soup, how do I iterate over all embedded text?
Let's say I wanted to remove vowels from HTML:
<a href="foo">Hello there!</a>Hi!
becomes
<a href="foo">Hll thr!</a>H!
I figure this is a job for Beautiful Soup. How can I select the text in between tags and operate on it like this?
A:
Suppose the variable test_html has the following html content:
<html>
<head><title>Test title</title></head>
<body>
<p>Some paragraph</p>
Useless Text
<a href="http://stackoverflow.com">Some link</a>not a link
<a href="http://python.org">Another link</a>
</body></html>
Just do this:
from BeautifulSoup import BeautifulSoup
test_html = load_html_from_above()
soup = BeautifulSoup(test_html)
for t in soup.findAll(text=True):
text = unicode(t)
for vowel in u'aeiou':
text = text.replace(vowel, u'')
t.replaceWith(text)
print soup
That prints:
<html>
<head><title>Tst ttl</title></head>
<body>
<p>Sm prgrph</p>
Uslss Txt
<a href="http://stackoverflow.com">Sm lnk</a>nt lnk
<a href="http://python.org">Anthr lnk</a>
</body></html>
Note that the tags and attributes are untouched.
|
Using Beautiful Soup, how do I iterate over all embedded text?
|
Let's say I wanted to remove vowels from HTML:
<a href="foo">Hello there!</a>Hi!
becomes
<a href="foo">Hll thr!</a>H!
I figure this is a job for Beautiful Soup. How can I select the text in between tags and operate on it like this?
|
[
"Suppose the variable test_html has the following html content:\n<html>\n<head><title>Test title</title></head>\n<body>\n<p>Some paragraph</p>\nUseless Text\n<a href=\"http://stackoverflow.com\">Some link</a>not a link\n<a href=\"http://python.org\">Another link</a>\n</body></html>\n\nJust do this:\nfrom BeautifulSoup import BeautifulSoup\n\ntest_html = load_html_from_above()\nsoup = BeautifulSoup(test_html)\n\nfor t in soup.findAll(text=True):\n text = unicode(t)\n for vowel in u'aeiou':\n text = text.replace(vowel, u'') \n t.replaceWith(text)\n\nprint soup\n\nThat prints:\n<html>\n<head><title>Tst ttl</title></head>\n<body>\n<p>Sm prgrph</p>\nUslss Txt\n<a href=\"http://stackoverflow.com\">Sm lnk</a>nt lnk\n<a href=\"http://python.org\">Anthr lnk</a>\n</body></html>\n\nNote that the tags and attributes are untouched.\n"
] |
[
11
] |
[] |
[] |
[
"beautifulsoup",
"python"
] |
stackoverflow_0000830997_beautifulsoup_python.txt
|
Q:
A production ready server to serve django on win32
I'd like to serve django application on windows XP/Vista.
The application is an at hoc web interface to a windows program so it won't be put under heavy load (around 100 requests per second).
Do you know any small servers that can be easily deployed on windows to serve a django app? (IIS is not an option as the app should work on all versions of windows)
A:
cherrypy includes a good server. Here's how you set it up to work with django and some benchmarks.
twisted.web has wsgi support and that could be used to run your django application. Here's how you do it.
In fact any wsgi server will do. Here's one more example, this time using spawning:
$ spawn --factory=spawning.django_factory.config_factory mysite.settings
And for using paste, the info is gathered here.
Of course, you could use apache with mod_wsgi. It would be just another wsgi server. Here are the setup instructions.
A:
If you want to give Apache a go, check out XAMPP to see if it'll work for you. You can do a lightweight (read: no installation) "installation." Of course, you'll also want to install mod_python to run Django. This post may help you set everything up. (Note: I have not used python/Django with XAMPP myself.)
Edit: Before someone points this out, XAMPP is not generally a production-ready tool. It's simply a useful way to see whether Apache will work for you. Also, I saw that you're using SQLite after the fact.
A:
Why not Apache ?
Nokia have developed a scaled down version of apache to run on their mobile phones. It supports python.
http://research.nokia.com/research/projects/mobile-web-server/
Also do you need anything else such as database support etc?
|
A production ready server to serve django on win32
|
I'd like to serve django application on windows XP/Vista.
The application is an at hoc web interface to a windows program so it won't be put under heavy load (around 100 requests per second).
Do you know any small servers that can be easily deployed on windows to serve a django app? (IIS is not an option as the app should work on all versions of windows)
|
[
"cherrypy includes a good server. Here's how you set it up to work with django and some benchmarks.\ntwisted.web has wsgi support and that could be used to run your django application. Here's how you do it.\nIn fact any wsgi server will do. Here's one more example, this time using spawning:\n$ spawn --factory=spawning.django_factory.config_factory mysite.settings\n\nAnd for using paste, the info is gathered here.\nOf course, you could use apache with mod_wsgi. It would be just another wsgi server. Here are the setup instructions.\n",
"If you want to give Apache a go, check out XAMPP to see if it'll work for you. You can do a lightweight (read: no installation) \"installation.\" Of course, you'll also want to install mod_python to run Django. This post may help you set everything up. (Note: I have not used python/Django with XAMPP myself.)\nEdit: Before someone points this out, XAMPP is not generally a production-ready tool. It's simply a useful way to see whether Apache will work for you. Also, I saw that you're using SQLite after the fact.\n",
"Why not Apache ? \nNokia have developed a scaled down version of apache to run on their mobile phones. It supports python. \nhttp://research.nokia.com/research/projects/mobile-web-server/\nAlso do you need anything else such as database support etc? \n"
] |
[
5,
1,
0
] |
[] |
[] |
[
"django",
"python",
"windows"
] |
stackoverflow_0000831288_django_python_windows.txt
|
Q:
How do you create an anonymous Python telnet connection?
I am trying to telnet into a server using Python on Windows XP. I can connect successfully by typing 'telnet HOST PORT' which creates an anonymous connection. But Python's telnetlib.Telnet(HOST, PORT) returns 'Connection refused'. Telnetting in Java also fails. Spelunking shows that Python tries to create an anonymous socket connection. My admin says he doesn't allow anonymous connections. But neither Python nor Java allow authentication parameters to be passed in during socket connection creation (not that I could find). Why does Windows' command-line telnet work when Python and Java both fail? Any advice?
A:
It would be a good idea to trace both connection attempts (a failing case and a successful case) with wireshark or similar packet trace tool to see what the difference is at the protocol level.
A:
First, eliminate telnetlib as your problem: import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("remote.host", 23)) If that succeeds, there is a problem in your usage of telnetlib, and we'll need to see an example. If it fails, then you have a basic networking problem, and Lance's suggestion of pulling out ethereal/wireshark is your next step.
|
How do you create an anonymous Python telnet connection?
|
I am trying to telnet into a server using Python on Windows XP. I can connect successfully by typing 'telnet HOST PORT' which creates an anonymous connection. But Python's telnetlib.Telnet(HOST, PORT) returns 'Connection refused'. Telnetting in Java also fails. Spelunking shows that Python tries to create an anonymous socket connection. My admin says he doesn't allow anonymous connections. But neither Python nor Java allow authentication parameters to be passed in during socket connection creation (not that I could find). Why does Windows' command-line telnet work when Python and Java both fail? Any advice?
|
[
"It would be a good idea to trace both connection attempts (a failing case and a successful case) with wireshark or similar packet trace tool to see what the difference is at the protocol level.\n",
"First, eliminate telnetlib as your problem: import socket\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((\"remote.host\", 23)) If that succeeds, there is a problem in your usage of telnetlib, and we'll need to see an example. If it fails, then you have a basic networking problem, and Lance's suggestion of pulling out ethereal/wireshark is your next step.\n"
] |
[
1,
1
] |
[] |
[] |
[
"java",
"python",
"telnet",
"windows"
] |
stackoverflow_0000831679_java_python_telnet_windows.txt
|
Q:
Python imaging, resize Turtle Graphics window
My image is too large for the turtle window. I had to enlarge the image because the text I need at each spot overlaps.
How do I Resize the window in python?
A:
It sounds like you have drawn an image, but it has gone outside the borders of the window, so therefore you need to make the window larger to see the entire image.
To resize the window:
setup( width = 200, height = 200, startx = None, starty = None)
This will make your output window 200X200 (which may be too small for you so you'll need to make those numbers larger.)
Here is the URL where I found this information.
TurtleDocs
|
Python imaging, resize Turtle Graphics window
|
My image is too large for the turtle window. I had to enlarge the image because the text I need at each spot overlaps.
How do I Resize the window in python?
|
[
"It sounds like you have drawn an image, but it has gone outside the borders of the window, so therefore you need to make the window larger to see the entire image. \nTo resize the window:\n\nsetup( width = 200, height = 200, startx = None, starty = None) \n\nThis will make your output window 200X200 (which may be too small for you so you'll need to make those numbers larger.) \nHere is the URL where I found this information.\nTurtleDocs\n"
] |
[
6
] |
[] |
[] |
[
"python",
"turtle_graphics"
] |
stackoverflow_0000831894_python_turtle_graphics.txt
|
Q:
Python: Finding all packages inside a package
Given a package, how can I automatically find all its sub-packages?
A:
You can't rely on introspection of loaded modules, because sub-packages may not have been loaded. You'll have to look at the filesystem, assuming the top level package in question is not an egg, zip file, extension module, or loaded from memory.
def get_subpackages(module):
dir = os.path.dirname(module.__file__)
def is_package(d):
d = os.path.join(dir, d)
return os.path.isdir(d) and glob.glob(os.path.join(d, '__init__.py*'))
return filter(is_package, os.listdir(dir))
A:
Inspired by James Emerton's answer:
def find_subpackages(module):
result=[]
for thing in os.listdir(os.path.dirname(module.__file__)):
full=os.path.join(os.path.dirname(module.__file__),thing)
if os.path.isdir(full):
if glob.glob(os.path.join(full, '__init__.py*'))!=[]:
result.append(thing)
return result
|
Python: Finding all packages inside a package
|
Given a package, how can I automatically find all its sub-packages?
|
[
"You can't rely on introspection of loaded modules, because sub-packages may not have been loaded. You'll have to look at the filesystem, assuming the top level package in question is not an egg, zip file, extension module, or loaded from memory.\ndef get_subpackages(module):\n dir = os.path.dirname(module.__file__)\n def is_package(d):\n d = os.path.join(dir, d)\n return os.path.isdir(d) and glob.glob(os.path.join(d, '__init__.py*'))\n\n return filter(is_package, os.listdir(dir))\n\n",
"Inspired by James Emerton's answer:\ndef find_subpackages(module):\n result=[]\n for thing in os.listdir(os.path.dirname(module.__file__)):\n full=os.path.join(os.path.dirname(module.__file__),thing)\n if os.path.isdir(full):\n if glob.glob(os.path.join(full, '__init__.py*'))!=[]:\n result.append(thing)\n return result\n\n"
] |
[
10,
0
] |
[] |
[] |
[
"import",
"package",
"python"
] |
stackoverflow_0000832004_import_package_python.txt
|
Q:
Django template with jquery: Ajax update on existing page
I have a Google App Engine that has a form. When the user clicks on the submit button, AJAX operation will be called, and the server will output something to append to the end of the very page where it comes from. How, I have a Django template, and I intend to use jquery. I have the following view:
<html>
<head>
<title></title>
<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript" src="scripts/scripts.js"></script>
</head>
<body>
welcome
<form id="SubmitForm" action="/" method="POST">
<input type="file" name="vsprojFiles" />
<br/>
<input type="submit" id="SubmitButton"/>
</form>
<div id="Testing">
{{thebest}}
</div>
</body>
</html>
Here's the script in scripts.js:
$(function() {
$("#SubmitForm").click(submitMe);
});
var submitMe = function(){
//alert('no way');
var f = $('#SubmitForm');
var action = f.attr("action");
var serializedForm = f.serialize();
$.ajax( {
type: 'post',
data: serializedForm,
url: form_action,
success: function( result ) {
$('#SubmitForm').after( "<div><tt>" +
result +
"</tt></div>" );
}
} );
};
And here's my controller code:
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.api.urlfetch_errors import *
import cgi
import wsgiref.handlers
import os
import sys
import re
import urllib
from django.utils import simplejson
class MainPage(webapp.RequestHandler):
def get(self):
path = os.path.join(os.path.dirname(__file__), 'Index.html')
template_values={'thebest': 'thebest'}
tmplRender =template.render(path, template_values)
self.response.out.write(tmplRender)
pass
def Post(self):
print >>sys.__stderr__,'me posting'
result = 'grsgres'
self.response.out.write(simplejson.dumps(result))
As you can see, when the user clicks on the submitbutton, the controller method Mainpage.post will be called.
Now I want to display the content of the 'result' variable right after the form, how can I do it?
A:
Without being able to test the code, what are your results? Have you checked the results returned by the AJAX call? I would suggest you run Firefox with Firebug and log the AJAX results to the Firebug console to see what you get:
//...
success: function( result ) {
console.log( result );
$('#SubmitForm').after( "<div><tt>" +
// ...
You can also use the Net panel of Firebug to see what is being passed back and forth.
Also, what does "simplejson.dumps(result)" result in?
A:
here is an example of my success function
success: function(json){
$('#gallons_cont').html(json['gallons']);
$('#area_cont').html(json['area']);
$('#usage_cont').html(json['usage'])
$('#results_json').show('slow');
},
please note that you do have to debug using firebug or something similar as there might be some issue serializing which will throw and error but will not be vieweable unless you use something like firebug or implement .ajax error
|
Django template with jquery: Ajax update on existing page
|
I have a Google App Engine that has a form. When the user clicks on the submit button, AJAX operation will be called, and the server will output something to append to the end of the very page where it comes from. How, I have a Django template, and I intend to use jquery. I have the following view:
<html>
<head>
<title></title>
<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript" src="scripts/scripts.js"></script>
</head>
<body>
welcome
<form id="SubmitForm" action="/" method="POST">
<input type="file" name="vsprojFiles" />
<br/>
<input type="submit" id="SubmitButton"/>
</form>
<div id="Testing">
{{thebest}}
</div>
</body>
</html>
Here's the script in scripts.js:
$(function() {
$("#SubmitForm").click(submitMe);
});
var submitMe = function(){
//alert('no way');
var f = $('#SubmitForm');
var action = f.attr("action");
var serializedForm = f.serialize();
$.ajax( {
type: 'post',
data: serializedForm,
url: form_action,
success: function( result ) {
$('#SubmitForm').after( "<div><tt>" +
result +
"</tt></div>" );
}
} );
};
And here's my controller code:
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.api.urlfetch_errors import *
import cgi
import wsgiref.handlers
import os
import sys
import re
import urllib
from django.utils import simplejson
class MainPage(webapp.RequestHandler):
def get(self):
path = os.path.join(os.path.dirname(__file__), 'Index.html')
template_values={'thebest': 'thebest'}
tmplRender =template.render(path, template_values)
self.response.out.write(tmplRender)
pass
def Post(self):
print >>sys.__stderr__,'me posting'
result = 'grsgres'
self.response.out.write(simplejson.dumps(result))
As you can see, when the user clicks on the submitbutton, the controller method Mainpage.post will be called.
Now I want to display the content of the 'result' variable right after the form, how can I do it?
|
[
"Without being able to test the code, what are your results? Have you checked the results returned by the AJAX call? I would suggest you run Firefox with Firebug and log the AJAX results to the Firebug console to see what you get:\n//...\n success: function( result ) { \n console.log( result );\n $('#SubmitForm').after( \"<div><tt>\" + \n// ...\n\nYou can also use the Net panel of Firebug to see what is being passed back and forth.\nAlso, what does \"simplejson.dumps(result)\" result in?\n",
"here is an example of my success function \nsuccess: function(json){\n $('#gallons_cont').html(json['gallons']);\n $('#area_cont').html(json['area']);\n $('#usage_cont').html(json['usage'])\n $('#results_json').show('slow'); \n },\n\nplease note that you do have to debug using firebug or something similar as there might be some issue serializing which will throw and error but will not be vieweable unless you use something like firebug or implement .ajax error\n"
] |
[
2,
1
] |
[] |
[] |
[
"django",
"django_templates",
"google_app_engine",
"jquery",
"python"
] |
stackoverflow_0000209023_django_django_templates_google_app_engine_jquery_python.txt
|
Q:
How to set up Python in a web server?
Not exactly about programming, but I need help with this.
I'm running a development sever with WampServer. I want to install Python (because I prefer to use Python over PHP), but it seems there isn't an obvious choice. I've read about mod_python and WSGI, and about how the latter is better.
However, from what I gathered (I may be wrong) you have to do more low-level stuff with WSGI than with PHP. So I researched about Django, but it seems too complex for what I want.
So, what recommendations would you give to a newbie in this area?
Again, sorry if this isn't about programming, but it's related, and this seems like a nice place to ask.
A:
Django is not a web server, but a web application framework.
If you want a bare-bones Python webserver capable of some dynamic and some static content, have a look at CherryPy.
A:
Use mod_wsgi to embed Python in Apache. It works very, very well.
"However, from what I gathered (I may be wrong) you have to do more low-level stuff with WSGI than with PHP. So I researched about Django, but it seems too complex for what I want."
If you try to write your entire application as a WSGI-compliant application, directly accessed via mod_wsgi, you will reinvent the wheel.
If you try to write your application in Django, you will have stuff up and running in the space of a few hours. Django is not "too complex" -- it's complete. You don't have to use all of it, but -- for any realistic application -- you'll need most of it. In particular, the built-in admin will save you mountains of programming.
A:
Werkzeug is a great little python tool (werkzeug) that works with mod_wsgi for creating simple apps that dont need database backends with CMS's, such as calculators .. They've even got a nifty screencast where they create a simple wiki in 30 minutes.
You can always add something like SQLAlchemy/FormAlchemy later on if you eventually do want to have a ORM and CMS.
Avoid mod_python tho, it's got a pretty big memory footprint and it's actually a bit harder to install and set up than mod_wsgi, in my opinion.
A:
To use python with your Apache server you need to install mod_python the following links should help you out a bit.
http://httpd.apache.org/modules/python-download.cgi
http://www.modpython.org/
A:
If it's truly a development server you're setting up, and not a machine that will be promoted to production at some point, Django has a built-in development webserver that requires no Apache configuration.
Your observation about the low-level work reflects some of the differences between PHP and Python. PHP is a language designed from the start for the primary purpose of making web pages. Python is a language. Mod_Python and Mod_WSGI give the input to/output from that language a way to live in a web request/response environment. Django adds web-aware framework conveniences.
You mention that python seems too complex for what you want, which rather begs the question: what do you want? :-)
|
How to set up Python in a web server?
|
Not exactly about programming, but I need help with this.
I'm running a development sever with WampServer. I want to install Python (because I prefer to use Python over PHP), but it seems there isn't an obvious choice. I've read about mod_python and WSGI, and about how the latter is better.
However, from what I gathered (I may be wrong) you have to do more low-level stuff with WSGI than with PHP. So I researched about Django, but it seems too complex for what I want.
So, what recommendations would you give to a newbie in this area?
Again, sorry if this isn't about programming, but it's related, and this seems like a nice place to ask.
|
[
"Django is not a web server, but a web application framework.\nIf you want a bare-bones Python webserver capable of some dynamic and some static content, have a look at CherryPy.\n",
"Use mod_wsgi to embed Python in Apache. It works very, very well.\n\"However, from what I gathered (I may be wrong) you have to do more low-level stuff with WSGI than with PHP. So I researched about Django, but it seems too complex for what I want.\"\n\nIf you try to write your entire application as a WSGI-compliant application, directly accessed via mod_wsgi, you will reinvent the wheel.\nIf you try to write your application in Django, you will have stuff up and running in the space of a few hours. Django is not \"too complex\" -- it's complete. You don't have to use all of it, but -- for any realistic application -- you'll need most of it. In particular, the built-in admin will save you mountains of programming.\n\n",
"Werkzeug is a great little python tool (werkzeug) that works with mod_wsgi for creating simple apps that dont need database backends with CMS's, such as calculators .. They've even got a nifty screencast where they create a simple wiki in 30 minutes. \nYou can always add something like SQLAlchemy/FormAlchemy later on if you eventually do want to have a ORM and CMS.\nAvoid mod_python tho, it's got a pretty big memory footprint and it's actually a bit harder to install and set up than mod_wsgi, in my opinion.\n",
"To use python with your Apache server you need to install mod_python the following links should help you out a bit.\n\nhttp://httpd.apache.org/modules/python-download.cgi\nhttp://www.modpython.org/ \n\n",
"If it's truly a development server you're setting up, and not a machine that will be promoted to production at some point, Django has a built-in development webserver that requires no Apache configuration. \nYour observation about the low-level work reflects some of the differences between PHP and Python. PHP is a language designed from the start for the primary purpose of making web pages. Python is a language. Mod_Python and Mod_WSGI give the input to/output from that language a way to live in a web request/response environment. Django adds web-aware framework conveniences.\nYou mention that python seems too complex for what you want, which rather begs the question: what do you want? :-)\n"
] |
[
5,
3,
2,
0,
0
] |
[] |
[] |
[
"django",
"python",
"windows"
] |
stackoverflow_0000832140_django_python_windows.txt
|
Q:
How to run a script without being in the tasktray?
I have a scheduled task which runs a python script every 10 min
so it turns out that a script pops up on my desktop every 10 min
how can i make it invincible so my script will work in the background ?
I've been told that pythonw will do the work, but I cant figure out how to use it
any help ?
thanks
A:
I've been told that pythonw will do the work, but I cant figure out how to use it
Normally you just have to rename the file extension to .pyw. Then it will be executed by pythonw.
A:
Set the scheduled task to start the script as minimized.
|
How to run a script without being in the tasktray?
|
I have a scheduled task which runs a python script every 10 min
so it turns out that a script pops up on my desktop every 10 min
how can i make it invincible so my script will work in the background ?
I've been told that pythonw will do the work, but I cant figure out how to use it
any help ?
thanks
|
[
"\nI've been told that pythonw will do the work, but I cant figure out how to use it\n\nNormally you just have to rename the file extension to .pyw. Then it will be executed by pythonw.\n",
"Set the scheduled task to start the script as minimized.\n"
] |
[
3,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0000833356_python.txt
|
Q:
Need help for developing facebook app
I am trying to develop a facebook app using django.
The problem I am facing is how to use facebook api and get user friend list.
view.py
def canvas(request):
# Get the User object
user, created = FacebookUser.objects.get_or_create(id = request.facebook.uid)
return direct_to_template(request, 'canvas.fbml', extra_context={'fbuser': user,})
so it's working fine for me. I am getting user info in my page.
Welcome,<fb:name uid="{{ fbuser.id }}" firstnameonly="true" useyou="false" />!
this is canvas.fbml
Help needed.
Thanks.
A:
Try using single quotes when loading up the userID etc.
Failing that it would appear to be either of the following
- Output error from python. The HTML / FBML output should be as follows
Double check the attributes you are adding are correct. Case sensitive.
Are you loading you the correct authentication info (Keys) in this file? I'm assuming as its on the canvas its all ok. Test hte FBML in the FBML console.
|
Need help for developing facebook app
|
I am trying to develop a facebook app using django.
The problem I am facing is how to use facebook api and get user friend list.
view.py
def canvas(request):
# Get the User object
user, created = FacebookUser.objects.get_or_create(id = request.facebook.uid)
return direct_to_template(request, 'canvas.fbml', extra_context={'fbuser': user,})
so it's working fine for me. I am getting user info in my page.
Welcome,<fb:name uid="{{ fbuser.id }}" firstnameonly="true" useyou="false" />!
this is canvas.fbml
Help needed.
Thanks.
|
[
"Try using single quotes when loading up the userID etc. \nFailing that it would appear to be either of the following\n- Output error from python. The HTML / FBML output should be as follows\n\nDouble check the attributes you are adding are correct. Case sensitive. \nAre you loading you the correct authentication info (Keys) in this file? I'm assuming as its on the canvas its all ok. Test hte FBML in the FBML console. \n\n"
] |
[
0
] |
[] |
[] |
[
"django",
"facebook",
"python"
] |
stackoverflow_0000833406_django_facebook_python.txt
|
Q:
What i need to install python 2.5 on SCO 5.0.5
I would love to install python2.5 on sco unix, and am wondering anybody who has attempted to do this?
A:
Did you already try the standard source instructions, and fail? If so, I guess it would be useful to mention what failed. This is almost a non-programming question, as it's phrased now ...
|
What i need to install python 2.5 on SCO 5.0.5
|
I would love to install python2.5 on sco unix, and am wondering anybody who has attempted to do this?
|
[
"Did you already try the standard source instructions, and fail? If so, I guess it would be useful to mention what failed. This is almost a non-programming question, as it's phrased now ...\n"
] |
[
2
] |
[] |
[] |
[
"python",
"unix"
] |
stackoverflow_0000833624_python_unix.txt
|
Q:
design for handling exceptions - google app engine
I'm developing a project on google app engine (webapp framework). I need you people to assess how I handle exceptions.
There are 4 types of exceptions I am handling:
Programming exceptions
Bad user input
Incorrect URLs
Incorrect query strings
Here is how I handle them:
I have subclassed the webapp.requesthandler class and overrode the handle_exceptions method. Whenever an exception occurs, I take the user to a friendly "we're sorry" page and in the meantime send a message with the traceback to the admins.
On the client side I (will) use js and also validate on the server side.
Here I figure (as a coder with non-web experience) in addition to validate inputs according to programming logic (check: cash input is of the float type?) and business rules (check: user has enough points to take that action?), I also have to check against malicious intentions. What measures should I take against malicious actions?
I have a catch-all URL that handles incorrect URLs. That is to say, I take the user to a custom "page does not exist" page. Here I have no problems, I think.
Incorrect query strings presumably raise exceptions if left to themselves. If an ID does not exist, the method returns None (an exception is on the way). if the parameter is inconvenient, the code raises an exception. Here I think I must raise a 404 and take the user to the custom "page does not exist" page. What should I do?
What are your opinions? Thanks in advance..
A:
You seem to have thought things through pretty well. The only thing I would add is that you might want to take a look at Bloog as an example. Bloog is a pretty well written and popular open source blog engine for App Engine written in Python.
Also, on Point #2, watch out for these types of Cross Scripting attacks.
As for #4, keep in mind that 404 pages are an opportunity to add some color and creativity to your design.
A:
Ad. #4: I usually treat query strings as non-essential. If anything is wrong with query string, I'd just present bare resource page (as if no query was present), possibly with some information to user what was wrong with the query string.
This leads to the problem similar to your #3: how did the user got into this wrong query? Did my application produce wrong URL somewhere? Or was it outdated link in some external service, or saved bookmark? HTTP_REFERER might contain some clue, but of course is not authoritative, so I'd log the problematic query (with some additional HTTP headers) and try to investigate the case.
|
design for handling exceptions - google app engine
|
I'm developing a project on google app engine (webapp framework). I need you people to assess how I handle exceptions.
There are 4 types of exceptions I am handling:
Programming exceptions
Bad user input
Incorrect URLs
Incorrect query strings
Here is how I handle them:
I have subclassed the webapp.requesthandler class and overrode the handle_exceptions method. Whenever an exception occurs, I take the user to a friendly "we're sorry" page and in the meantime send a message with the traceback to the admins.
On the client side I (will) use js and also validate on the server side.
Here I figure (as a coder with non-web experience) in addition to validate inputs according to programming logic (check: cash input is of the float type?) and business rules (check: user has enough points to take that action?), I also have to check against malicious intentions. What measures should I take against malicious actions?
I have a catch-all URL that handles incorrect URLs. That is to say, I take the user to a custom "page does not exist" page. Here I have no problems, I think.
Incorrect query strings presumably raise exceptions if left to themselves. If an ID does not exist, the method returns None (an exception is on the way). if the parameter is inconvenient, the code raises an exception. Here I think I must raise a 404 and take the user to the custom "page does not exist" page. What should I do?
What are your opinions? Thanks in advance..
|
[
"You seem to have thought things through pretty well. The only thing I would add is that you might want to take a look at Bloog as an example. Bloog is a pretty well written and popular open source blog engine for App Engine written in Python.\nAlso, on Point #2, watch out for these types of Cross Scripting attacks.\nAs for #4, keep in mind that 404 pages are an opportunity to add some color and creativity to your design.\n",
"Ad. #4: I usually treat query strings as non-essential. If anything is wrong with query string, I'd just present bare resource page (as if no query was present), possibly with some information to user what was wrong with the query string.\nThis leads to the problem similar to your #3: how did the user got into this wrong query? Did my application produce wrong URL somewhere? Or was it outdated link in some external service, or saved bookmark? HTTP_REFERER might contain some clue, but of course is not authoritative, so I'd log the problematic query (with some additional HTTP headers) and try to investigate the case.\n"
] |
[
5,
0
] |
[] |
[] |
[
"exception_handling",
"google_app_engine",
"python",
"web_applications"
] |
stackoverflow_0000830597_exception_handling_google_app_engine_python_web_applications.txt
|
Q:
Scaffold or django-admin without Auth app
I created my own Auth app, and now Admin is not working, what can you suggest?
Exception now is: 'User' object has no attribute 'is_authenticated'
I know my User really have no such method. So I have 2 ways:
- change admin
- adapt my user system
My question was: is there possibility to easily off admin bound to auth
A:
See the file django/contrib/admin/views/decorators.py:
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
These are used in decorator staff_member_required which guards access to admin application.
Admin application requires django.contrib.auth - you might try to monkeypatch it, but it's a bad habit (Django is not RoR, Python is not Ruby).
|
Scaffold or django-admin without Auth app
|
I created my own Auth app, and now Admin is not working, what can you suggest?
Exception now is: 'User' object has no attribute 'is_authenticated'
I know my User really have no such method. So I have 2 ways:
- change admin
- adapt my user system
My question was: is there possibility to easily off admin bound to auth
|
[
"See the file django/contrib/admin/views/decorators.py:\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import authenticate, login\n\nThese are used in decorator staff_member_required which guards access to admin application.\nAdmin application requires django.contrib.auth - you might try to monkeypatch it, but it's a bad habit (Django is not RoR, Python is not Ruby).\n"
] |
[
2
] |
[] |
[] |
[
"django",
"django_admin",
"python",
"scaffolding"
] |
stackoverflow_0000831934_django_django_admin_python_scaffolding.txt
|
Q:
Returning http status codes in Python CGI
Is it possible to send a status code other than 200 via a python cgi script (such as 301 redirect)
A:
via cgi script?
print "Status:301\nLocation: http://www.google.com"
A:
Via wsgi application?
def simple_app(environ, start_response):
status = '301 Moved Permanently' # HTTP Status
headers = [('Location','http://example.com')] # HTTP Headers
start_response(status, headers)
return []
|
Returning http status codes in Python CGI
|
Is it possible to send a status code other than 200 via a python cgi script (such as 301 redirect)
|
[
"via cgi script?\nprint \"Status:301\\nLocation: http://www.google.com\"\n\n",
"Via wsgi application?\ndef simple_app(environ, start_response):\n status = '301 Moved Permanently' # HTTP Status\n headers = [('Location','http://example.com')] # HTTP Headers\n start_response(status, headers)\n\n return []\n\n"
] |
[
23,
0
] |
[] |
[] |
[
"cgi",
"http",
"python"
] |
stackoverflow_0000833715_cgi_http_python.txt
|
Q:
Mapping a database table to an attribute of an object
I've come across a place in my current project where I have created several classes for storing a complicated data structure in memory and a completed SQL schema for storing the same data in a database. I've decided to use SQLAlchemy as an ORM layer as it seems the most flexible solution that I can tailor to my needs.
My problem is that I now need to map an entire table to just an array attribute in memory and am struggling to find out if this is possible and, if it is, how to do it with SQLAlchemy. It is still possible for me to change the data structures in code (although less than ideal) if not, but I would prefer not to.
The table in question is created using the following SQL:
CREATE TABLE `works` (
`id` BIGINT NOT NULL auto_increment,
`uniform_title` VARCHAR(255) NOT NULL,
`created_date` DATE NOT NULL,
`context` TEXT,
`distinguishing_characteristics` TEXT,
PRIMARY KEY (`id`),
INDEX (`uniform_title` ASC),
INDEX (`uniform_title` DESC)
) ENGINE = InnoDB DEFAULT CHARSET = utf8 ;
CREATE TABLE `variant_work_titles` (
`id` BIGINT NOT NULL auto_increment,
`work_id` BIGINT NOT NULL,
`title` VARCHAR(255) NOT NULL,
PRIMARY KEY(`id`),
INDEX (`work_id`),
INDEX (`title` ASC),
INDEX (`title` DESC),
FOREIGN KEY (`work_id`)
REFERENCES `works` (`id`)
ON DELETE CASCADE
ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
This is just a small part of the complete database and the same thing is going to be required in several places.
A:
It seems you want something like
work_instance.variants = [<some iterable of variants>]
If not please clarify in your question.
Ideally you should have 2 mappings to these 2 tables. It doesn't matter if you won't access the second mapping anywhere else. work mapping should have a one-to-many relationship to variant mapping. This would give you a list of variant instances associated with a particular work on whichever attribute you define your relationship.
|
Mapping a database table to an attribute of an object
|
I've come across a place in my current project where I have created several classes for storing a complicated data structure in memory and a completed SQL schema for storing the same data in a database. I've decided to use SQLAlchemy as an ORM layer as it seems the most flexible solution that I can tailor to my needs.
My problem is that I now need to map an entire table to just an array attribute in memory and am struggling to find out if this is possible and, if it is, how to do it with SQLAlchemy. It is still possible for me to change the data structures in code (although less than ideal) if not, but I would prefer not to.
The table in question is created using the following SQL:
CREATE TABLE `works` (
`id` BIGINT NOT NULL auto_increment,
`uniform_title` VARCHAR(255) NOT NULL,
`created_date` DATE NOT NULL,
`context` TEXT,
`distinguishing_characteristics` TEXT,
PRIMARY KEY (`id`),
INDEX (`uniform_title` ASC),
INDEX (`uniform_title` DESC)
) ENGINE = InnoDB DEFAULT CHARSET = utf8 ;
CREATE TABLE `variant_work_titles` (
`id` BIGINT NOT NULL auto_increment,
`work_id` BIGINT NOT NULL,
`title` VARCHAR(255) NOT NULL,
PRIMARY KEY(`id`),
INDEX (`work_id`),
INDEX (`title` ASC),
INDEX (`title` DESC),
FOREIGN KEY (`work_id`)
REFERENCES `works` (`id`)
ON DELETE CASCADE
ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
This is just a small part of the complete database and the same thing is going to be required in several places.
|
[
"It seems you want something like\nwork_instance.variants = [<some iterable of variants>]\n\nIf not please clarify in your question.\nIdeally you should have 2 mappings to these 2 tables. It doesn't matter if you won't access the second mapping anywhere else. work mapping should have a one-to-many relationship to variant mapping. This would give you a list of variant instances associated with a particular work on whichever attribute you define your relationship.\n"
] |
[
1
] |
[] |
[] |
[
"database",
"orm",
"python",
"sqlalchemy"
] |
stackoverflow_0000834722_database_orm_python_sqlalchemy.txt
|
Q:
How to make Satchmo work in Google App Engine
I understand that there are big differences in data-store, but surely since django is bundled and it abstracts data-store away from Satchmo, something can be done?
Truth is that I am not a Python guy, been mostly Java/PHP thus far, but I am willing to learn.
Plus, if this is not possible today, lets band together and form a new Open Source project to "extend" satchmo or perhaps branch it, for compatibility?
A:
You can't. There are alot of dependencies in Satchmo that you aren't allowed to install on AppEngine.
See this thread as well: http://groups.google.com/group/satchmo-users/browse_thread/thread/509265ccd5f5fc1e?pli=1
A:
Possible if:
Someone writes a generic ORM to Bigtable mapper. Most probably, Appengine Patch Guys
Someone rewrites the views and models of Satchmo to remove existing ORM queries and use the minimal functionality of the ORM provided by the patch project, should be either you or the Satchmo guys.
Someone hacks around a lot using the django helper project, can only be helper project guys.
A:
Nothing is impossible - this will just require lots of effort - if there will be somebody wishing to do so - why not? But it might be easier (cheaper) to get Django friendly hosting instead of spending hours on hacking the code.
|
How to make Satchmo work in Google App Engine
|
I understand that there are big differences in data-store, but surely since django is bundled and it abstracts data-store away from Satchmo, something can be done?
Truth is that I am not a Python guy, been mostly Java/PHP thus far, but I am willing to learn.
Plus, if this is not possible today, lets band together and form a new Open Source project to "extend" satchmo or perhaps branch it, for compatibility?
|
[
"You can't. There are alot of dependencies in Satchmo that you aren't allowed to install on AppEngine.\nSee this thread as well: http://groups.google.com/group/satchmo-users/browse_thread/thread/509265ccd5f5fc1e?pli=1\n",
"Possible if:\n\nSomeone writes a generic ORM to Bigtable mapper. Most probably, Appengine Patch Guys\nSomeone rewrites the views and models of Satchmo to remove existing ORM queries and use the minimal functionality of the ORM provided by the patch project, should be either you or the Satchmo guys.\nSomeone hacks around a lot using the django helper project, can only be helper project guys.\n\n",
"Nothing is impossible - this will just require lots of effort - if there will be somebody wishing to do so - why not? But it might be easier (cheaper) to get Django friendly hosting instead of spending hours on hacking the code.\n"
] |
[
3,
3,
2
] |
[] |
[] |
[
"e_commerce",
"google_app_engine",
"python",
"satchmo"
] |
stackoverflow_0000600225_e_commerce_google_app_engine_python_satchmo.txt
|
Q:
Can I use a List Comprehension to get Line Indexes from a file?
I need to identify some locations in a file where certain markers might be. I started off thinking that I would use list.index but I soon discovered that returns the first (and only the first) item. so I decided to implement my own solution which was
count=0
docIndex=[]
for line in open('myfile.txt','r'):
if 'mystring' in line:
docIndex.append(count)
count+=1
But this is Python right. There has to be a simpler solution since well it is Python. Hunting around this site and the web I came up with something slightly better
newDocIndex=[]
for line in fileinput.input('myfile',inplace=1):
if 'mystring' in line:
newDocIndex.append(fileinput.lineno())
I know this is too much info but since I finished grading finals last night I thought well-this is Python and we want to make some headway this summer-lets try a list comprehension
so I did this:
[fileinput.lineno() for line in fileinput.input('myfile',inplace=1) if 'mystring' in line]
and got an empty list. So I first guessed that the problem is that the item in the for has to be the item that is used to build the list. That is if I had line instead of fileinput.lineno() I would have had a non-empty list but that is not the issue.
Can the above process be reduced to a list comprehension?
Using the answer but adjusting it for readability
listOfLines=[lineNumb for lineNumb,dataLine in enumerate(open('myfile')) if 'mystring' in dataLine]
A:
What about this?
[index for index,line in enumerate(open('myfile.txt')) if 'mystring' in line]
|
Can I use a List Comprehension to get Line Indexes from a file?
|
I need to identify some locations in a file where certain markers might be. I started off thinking that I would use list.index but I soon discovered that returns the first (and only the first) item. so I decided to implement my own solution which was
count=0
docIndex=[]
for line in open('myfile.txt','r'):
if 'mystring' in line:
docIndex.append(count)
count+=1
But this is Python right. There has to be a simpler solution since well it is Python. Hunting around this site and the web I came up with something slightly better
newDocIndex=[]
for line in fileinput.input('myfile',inplace=1):
if 'mystring' in line:
newDocIndex.append(fileinput.lineno())
I know this is too much info but since I finished grading finals last night I thought well-this is Python and we want to make some headway this summer-lets try a list comprehension
so I did this:
[fileinput.lineno() for line in fileinput.input('myfile',inplace=1) if 'mystring' in line]
and got an empty list. So I first guessed that the problem is that the item in the for has to be the item that is used to build the list. That is if I had line instead of fileinput.lineno() I would have had a non-empty list but that is not the issue.
Can the above process be reduced to a list comprehension?
Using the answer but adjusting it for readability
listOfLines=[lineNumb for lineNumb,dataLine in enumerate(open('myfile')) if 'mystring' in dataLine]
|
[
"What about this?\n[index for index,line in enumerate(open('myfile.txt')) if 'mystring' in line]\n\n"
] |
[
8
] |
[] |
[] |
[
"list_comprehension",
"python"
] |
stackoverflow_0000835572_list_comprehension_python.txt
|
Q:
why might my pyglet vertex lists and batches be very slow on Windows?
I'm writing opengl code in python using the library pyglet. When I draw to the screen using pyglet.graphics.vertex_list or pyglet.graphics.batch objects, they are very slow (~0.1 fps) compared to plain old pyglet.graphics.draw() or just glVertex() calls, which are about 40fps for the same geometry.
In Linux the vertex_list is about the same speed as glVertex, which is disappointing, and batch methods are about twice as fast, which is a little better but not as much gain as I was hoping for.
A:
Don't forget to invoke your pyglet scripts with 'python -O myscript.py', the '-O' flag can make a huge performance difference.
See pyglet docs here and here.
A:
I don't know personally, but I noticed that you haven't posted to the pyglet mailing list about this. More Pyglet users, as well as the primary developer, read that list.
|
why might my pyglet vertex lists and batches be very slow on Windows?
|
I'm writing opengl code in python using the library pyglet. When I draw to the screen using pyglet.graphics.vertex_list or pyglet.graphics.batch objects, they are very slow (~0.1 fps) compared to plain old pyglet.graphics.draw() or just glVertex() calls, which are about 40fps for the same geometry.
In Linux the vertex_list is about the same speed as glVertex, which is disappointing, and batch methods are about twice as fast, which is a little better but not as much gain as I was hoping for.
|
[
"Don't forget to invoke your pyglet scripts with 'python -O myscript.py', the '-O' flag can make a huge performance difference.\nSee pyglet docs here and here.\n",
"I don't know personally, but I noticed that you haven't posted to the pyglet mailing list about this. More Pyglet users, as well as the primary developer, read that list.\n"
] |
[
5,
1
] |
[] |
[] |
[
"opengl",
"pyglet",
"python"
] |
stackoverflow_0000067223_opengl_pyglet_python.txt
|
Q:
Extending Python's builtin Str
I'm trying to subclass str, but having some difficulties due to its immutability.
class DerivedClass(str):
def __new__(cls, string):
ob = super(DerivedClass, cls).__new__(cls, string)
return ob
def upper(self):
#overridden, new functionality. Return ob of type DerivedClass. Great.
caps = super(DerivedClass, self).upper()
return DerivedClass(caps + '123')
derived = DerivedClass('a')
print derived.upper() #'A123'
print type(derived.upper()) #<class '__main__.DerivedClass'>
print derived.lower() #'a'
print type(derived.lower()) #<type 'str'>
For inherited methods that don't require any new functionality, such as derived.lower(), is there a simple, pythonic way to return an object of type DerivedClass (instead of str)? Or am I stuck manually overriding each str.method(), as I did with derived.upper()?
Edit:
#Any massive flaws in the following?
class DerivedClass(str):
def __new__(cls, string):
ob = super(DerivedClass, cls).__new__(cls, string)
return ob
def upper(self):
caps = super(DerivedClass, self).upper()
return DerivedClass(caps + '123')
def __getattribute__(self, name):
att = super(DerivedClass, self).__getattribute__(name)
if not callable(att):
return att
def call_me_later(*args, **kwargs):
result = att(*args, **kwargs)
if isinstance(result, basestring):
return DerivedClass(result)
return result
return call_me_later
A:
Good use for a class decorator -- roughly (untested code):
@do_overrides
class Myst(str):
def upper(self):
...&c...
and
def do_overrides(cls):
done = set(dir(cls))
base = cls.__bases__[0]
def wrap(f):
def wrapper(*a, **k):
r = f(*a, **k)
if isinstance(r, base):
r = cls(r)
return r
for m in dir(base):
if m in done or not callable(m):
continue
setattr(cls, m, wrap(getattr(base, m)))
A:
You can do this by overriding __getattribute__ as Zr40 suggests, but you will need to have getattribute return a callable function. The sample below should give you what you want; it uses the functools.partial wrapper to make life easier, though you could implement it without partial if you like:
from functools import partial
class DerivedClass(str):
def __new__(cls, string):
ob = super(DerivedClass, cls).__new__(cls, string)
return ob
def upper(self):
#overridden, new functionality. Return ob of type DerivedClass. Great.
caps = super(DerivedClass, self).upper()
return DerivedClass(caps + '123')
def __getattribute__(self, name):
func = str.__getattribute__(self, name)
if name == 'upper':
return func
if not callable(func):
return func
def call_me_later(*args, **kwargs):
result = func(*args, **kwargs)
# Some str functions return lists, ints, etc
if isinstance(result, basestring:
return DerivedClass(result)
return result
return partial(call_me_later)
A:
You're both close, but checking for each doesn't extend well to overriding many methods.
from functools import partial
class DerivedClass(str):
def __new__(cls, string):
ob = super(DerivedClass, cls).__new__(cls, string)
return ob
def upper(self):
caps = super(DerivedClass, self).upper()
return DerivedClass(caps + '123')
def __getattribute__(self, name):
if name in ['__dict__', '__members__', '__methods__', '__class__']:
return object.__getattribute__(self, name)
func = str.__getattribute__(self, name)
if name in self.__dict__.keys() or not callable(func):
return func
def call_me_later(*args, **kwargs):
result = func(*args, **kwargs)
# Some str functions return lists, ints, etc
if isinstance(result, basestring):
return DerivedClass(result)
return result
return partial(call_me_later)
(Improvements suggested by jarret hardie in comments.)
|
Extending Python's builtin Str
|
I'm trying to subclass str, but having some difficulties due to its immutability.
class DerivedClass(str):
def __new__(cls, string):
ob = super(DerivedClass, cls).__new__(cls, string)
return ob
def upper(self):
#overridden, new functionality. Return ob of type DerivedClass. Great.
caps = super(DerivedClass, self).upper()
return DerivedClass(caps + '123')
derived = DerivedClass('a')
print derived.upper() #'A123'
print type(derived.upper()) #<class '__main__.DerivedClass'>
print derived.lower() #'a'
print type(derived.lower()) #<type 'str'>
For inherited methods that don't require any new functionality, such as derived.lower(), is there a simple, pythonic way to return an object of type DerivedClass (instead of str)? Or am I stuck manually overriding each str.method(), as I did with derived.upper()?
Edit:
#Any massive flaws in the following?
class DerivedClass(str):
def __new__(cls, string):
ob = super(DerivedClass, cls).__new__(cls, string)
return ob
def upper(self):
caps = super(DerivedClass, self).upper()
return DerivedClass(caps + '123')
def __getattribute__(self, name):
att = super(DerivedClass, self).__getattribute__(name)
if not callable(att):
return att
def call_me_later(*args, **kwargs):
result = att(*args, **kwargs)
if isinstance(result, basestring):
return DerivedClass(result)
return result
return call_me_later
|
[
"Good use for a class decorator -- roughly (untested code):\n@do_overrides\nclass Myst(str):\n def upper(self):\n ...&c...\n\nand\ndef do_overrides(cls):\n done = set(dir(cls))\n base = cls.__bases__[0]\n def wrap(f):\n def wrapper(*a, **k):\n r = f(*a, **k)\n if isinstance(r, base):\n r = cls(r)\n return r\n for m in dir(base):\n if m in done or not callable(m):\n continue\n setattr(cls, m, wrap(getattr(base, m)))\n\n",
"You can do this by overriding __getattribute__ as Zr40 suggests, but you will need to have getattribute return a callable function. The sample below should give you what you want; it uses the functools.partial wrapper to make life easier, though you could implement it without partial if you like:\nfrom functools import partial\n\nclass DerivedClass(str):\n\n def __new__(cls, string):\n ob = super(DerivedClass, cls).__new__(cls, string)\n return ob\n\n def upper(self):\n #overridden, new functionality. Return ob of type DerivedClass. Great.\n caps = super(DerivedClass, self).upper()\n return DerivedClass(caps + '123')\n\n def __getattribute__(self, name):\n func = str.__getattribute__(self, name)\n if name == 'upper':\n return func\n\n if not callable(func):\n return func\n\n def call_me_later(*args, **kwargs):\n result = func(*args, **kwargs)\n # Some str functions return lists, ints, etc\n if isinstance(result, basestring:\n return DerivedClass(result)\n return result\n\n return partial(call_me_later)\n\n",
"You're both close, but checking for each doesn't extend well to overriding many methods.\nfrom functools import partial\n\nclass DerivedClass(str):\n def __new__(cls, string):\n ob = super(DerivedClass, cls).__new__(cls, string)\n return ob\n\n def upper(self):\n caps = super(DerivedClass, self).upper()\n return DerivedClass(caps + '123')\n\n def __getattribute__(self, name):\n if name in ['__dict__', '__members__', '__methods__', '__class__']:\n return object.__getattribute__(self, name)\n func = str.__getattribute__(self, name)\n if name in self.__dict__.keys() or not callable(func):\n return func\n\n def call_me_later(*args, **kwargs):\n result = func(*args, **kwargs)\n # Some str functions return lists, ints, etc\n if isinstance(result, basestring):\n return DerivedClass(result)\n return result\n\n return partial(call_me_later)\n\n(Improvements suggested by jarret hardie in comments.)\n"
] |
[
7,
5,
5
] |
[
"You might be able to do this by overriding __getattribute__.\ndef __getattribute__(self, name):\n # Simple hardcoded check for upper.\n # I'm sure there are better ways to get the list of defined methods in\n # your class and see if name is contained in it.\n if name == 'upper':\n return object.__getattribute__(self, name)\n\n return DerivedClass(object.__getattribute__(self, name))\n\n"
] |
[
-2
] |
[
"immutability",
"inheritance",
"oop",
"overriding",
"python"
] |
stackoverflow_0000835469_immutability_inheritance_oop_overriding_python.txt
|
Q:
PDF Tables of Arbitrary (within reason) Width
I know PDF generation has been discussed a lot here; however, I've yet to find what I need.
I'm trying to generate PDF reports (mainly tables) from python. Yes I've tried ReportLab and Pisa. Both had column content "break out" in circumstances I didn't think were unreasonable and unrealistic to encounter in production.
When I say reasonable I mean 8 - 12 columns of differing widths. Not 80 - 1200 or some such.
I don't need a native python solution as I will be able to have my script launch off the linux command line.
I have these reports working in XHTML and they look more or less perfect ... I'd prefer to leverage them.
What I'm asking is: does anyone know of a tool I can use that will render tables of arbitrary (again within reason) size in PDF with quality near XHTML browser rendering?
I'd like to use something like PrinceXML; however the size of this project doesn't justify the expense of such a tool.
As an aside I have tried to do what I need in Latex , something I'm not apposed to but if that is a good idea I'd appreciate an example.
Regards, and thanks in advance.
A:
I completely agree with Brandon Craig Rhodes answer.
TeX, plain or with a macro package like LaTeX or ConTeXt, would be a good solution if
you need high quality output. However TeX is a heavy dependency
If you are looking for a lighter alternative you can try to
generate xsl-fo and render it with apache-fop, or
write a Python wrapper around iText.
Both can do arbitrary width tables with borders.
xsl-fo is not too difficult to learn and if you are used to XML easier to
generate than LaTeX code.
iText is a powerful PDF library available under MPL and LGPL
There are versions written in Java and C# but unfortunately
there is none in Python yet.
A:
Using TeX might give you good results. I would be tempted to avoid LaTeX, myself, but that's because it's a really complicated macro package and I've never really understood it when I've tried to use it; plus, at least given my tastes back then, it seemed a very verbose way to mark up my text compared with what I was used to using in plain TeX.
The real trick will be coming up with a way to escape all of the special characters your data might include so that the TeX source file you create won't error out because you, say, use an ampersand somewhere and TeX interprets it as an out-of-place command. It would take sitting down with the TeXBook for half an hour, probably, for me to get a quoting function working perfectly.
But if your data is just normal strings, then we can try printing a table without it. Here's an example:
#!/usr/bin/env python
import os
# Create a 2x3 PDF table of items, using TeX.
format = r"# \hfil & \hfil #"
data = [['Hydrogen', 1],
['Silicon', 14],
['Mercury', 80]]
table_data = r'\cr '.join('&'.join(str(i) for i in row) for row in data)
f = open('table.tex', 'w')
f.write(r"\halign{" + format + r"\cr " + table_data + r"\cr}\end")
f.close()
os.system("tex table.tex")
os.system("dvipdf table.dvi")
The big problem, as you can see from the PDF this products (if you'll run it and take a look), is that the table has no borders, and, if you'll take a look at the TeXBook, you'll find that producing them — while always possible — is not the most natural or obvious of operations.
Come to think of it, maybe LaTeX would have some use, if it had macros to make tables with borders easy to create after all. :-)
Have you, by the way, just looked to see if WebKit or any of the other browser backends can be made to produce PDFs directly from HTML, from the command line? They produce PDFs somehow for printing; there must be a way to take advantage of that to turn your HTML into PDF directly.
A:
The stand alone program : wkhtmltopdf is exactly what I needed. The PDF rendering of XHTML is the best of seen from a free tool.
|
PDF Tables of Arbitrary (within reason) Width
|
I know PDF generation has been discussed a lot here; however, I've yet to find what I need.
I'm trying to generate PDF reports (mainly tables) from python. Yes I've tried ReportLab and Pisa. Both had column content "break out" in circumstances I didn't think were unreasonable and unrealistic to encounter in production.
When I say reasonable I mean 8 - 12 columns of differing widths. Not 80 - 1200 or some such.
I don't need a native python solution as I will be able to have my script launch off the linux command line.
I have these reports working in XHTML and they look more or less perfect ... I'd prefer to leverage them.
What I'm asking is: does anyone know of a tool I can use that will render tables of arbitrary (again within reason) size in PDF with quality near XHTML browser rendering?
I'd like to use something like PrinceXML; however the size of this project doesn't justify the expense of such a tool.
As an aside I have tried to do what I need in Latex , something I'm not apposed to but if that is a good idea I'd appreciate an example.
Regards, and thanks in advance.
|
[
"I completely agree with Brandon Craig Rhodes answer.\nTeX, plain or with a macro package like LaTeX or ConTeXt, would be a good solution if \nyou need high quality output. However TeX is a heavy dependency\nIf you are looking for a lighter alternative you can try to\n\ngenerate xsl-fo and render it with apache-fop, or\nwrite a Python wrapper around iText.\n\nBoth can do arbitrary width tables with borders.\nxsl-fo is not too difficult to learn and if you are used to XML easier to\ngenerate than LaTeX code.\niText is a powerful PDF library available under MPL and LGPL\nThere are versions written in Java and C# but unfortunately \nthere is none in Python yet.\n",
"Using TeX might give you good results. I would be tempted to avoid LaTeX, myself, but that's because it's a really complicated macro package and I've never really understood it when I've tried to use it; plus, at least given my tastes back then, it seemed a very verbose way to mark up my text compared with what I was used to using in plain TeX.\nThe real trick will be coming up with a way to escape all of the special characters your data might include so that the TeX source file you create won't error out because you, say, use an ampersand somewhere and TeX interprets it as an out-of-place command. It would take sitting down with the TeXBook for half an hour, probably, for me to get a quoting function working perfectly.\nBut if your data is just normal strings, then we can try printing a table without it. Here's an example:\n#!/usr/bin/env python\n\nimport os\n\n# Create a 2x3 PDF table of items, using TeX.\n\nformat = r\"# \\hfil & \\hfil #\"\ndata = [['Hydrogen', 1],\n ['Silicon', 14],\n ['Mercury', 80]]\n\ntable_data = r'\\cr '.join('&'.join(str(i) for i in row) for row in data)\n\nf = open('table.tex', 'w')\nf.write(r\"\\halign{\" + format + r\"\\cr \" + table_data + r\"\\cr}\\end\")\nf.close()\n\nos.system(\"tex table.tex\")\nos.system(\"dvipdf table.dvi\")\n\nThe big problem, as you can see from the PDF this products (if you'll run it and take a look), is that the table has no borders, and, if you'll take a look at the TeXBook, you'll find that producing them — while always possible — is not the most natural or obvious of operations.\nCome to think of it, maybe LaTeX would have some use, if it had macros to make tables with borders easy to create after all. :-)\nHave you, by the way, just looked to see if WebKit or any of the other browser backends can be made to produce PDFs directly from HTML, from the command line? They produce PDFs somehow for printing; there must be a way to take advantage of that to turn your HTML into PDF directly.\n",
"The stand alone program : wkhtmltopdf is exactly what I needed. The PDF rendering of XHTML is the best of seen from a free tool.\n"
] |
[
3,
2,
1
] |
[] |
[] |
[
"latex",
"pdf",
"python",
"xhtml"
] |
stackoverflow_0000832693_latex_pdf_python_xhtml.txt
|
Q:
Form Submission in Python Without Name Attribute
Background:
Using urllib and urllib2 in Python, you can do a form submission.
You first create a dictionary.
formdictionary = { 'search' : 'stackoverflow' }
Then you use urlencode method of urllib to transform this dictionary.
params = urllib.urlencode(formdictionary)
You can now make a url request with urllib2 and pass the variable params as a secondary parameter with the first parameter being the url.
open = urllib2.urlopen('www.searchpage.com', params)
From my understanding, urlencode automatically encodes the dictionary in html and adds the input tag. It takes the key to be the name attribute. It takes value in the dictionary to be the value of the name attribute. Urllib2 send this html code via an HTTP POST request.
Problem:
This is alright if the html code you are submitting to is formatted in a standard way with the html tag input having the name attribute.
<input id="32324" type="text" name="search" >
But, there is the situation where the html code is not properly formatted. And the html input tag only has an id attribute no name attribute. Is there may be another way to access the input tag via the id attribute? Or is there may be yet another way?
Solution:
?
A:
According to the W3 standard, for an input field to be submitted, it must have a name attribute. A quick test on Firefox 3 and Safari 3.2 shows that an input field that is missing the name attribute but has an id attribute is not submitted.
With that said, if you have a form that you want to submit, and some of its fields have id but not name attributes, using the id attribute instead seems like the only available option. It could be that other browsers use the id attribute, or perhaps there is some JavaScript code that handles the submission event instead of letting the browser do it.
A:
An input tag without a name won't be submitted as a form parameter.
For example, create an HTML page containing just this:
<form>
<input type="text" name="one" value="foo"/>
<input type="text" value="bar"/>
<input type="submit"/>
</form>
You can see that the second text field is missing a name attribute. If you click "Submit," the page will refresh with the query string:
test.html?one=foo
A good strategy for this would be to look at a live POST request sent by your browser and start by emulating that. Use a tool like the FireBug extension for Firefox to see the POST request and parameters sent by your browser. There might be parameters in there that you didn't notice before -- possibly because they were hidden form elements or they were created/set by JavaScript.
|
Form Submission in Python Without Name Attribute
|
Background:
Using urllib and urllib2 in Python, you can do a form submission.
You first create a dictionary.
formdictionary = { 'search' : 'stackoverflow' }
Then you use urlencode method of urllib to transform this dictionary.
params = urllib.urlencode(formdictionary)
You can now make a url request with urllib2 and pass the variable params as a secondary parameter with the first parameter being the url.
open = urllib2.urlopen('www.searchpage.com', params)
From my understanding, urlencode automatically encodes the dictionary in html and adds the input tag. It takes the key to be the name attribute. It takes value in the dictionary to be the value of the name attribute. Urllib2 send this html code via an HTTP POST request.
Problem:
This is alright if the html code you are submitting to is formatted in a standard way with the html tag input having the name attribute.
<input id="32324" type="text" name="search" >
But, there is the situation where the html code is not properly formatted. And the html input tag only has an id attribute no name attribute. Is there may be another way to access the input tag via the id attribute? Or is there may be yet another way?
Solution:
?
|
[
"According to the W3 standard, for an input field to be submitted, it must have a name attribute. A quick test on Firefox 3 and Safari 3.2 shows that an input field that is missing the name attribute but has an id attribute is not submitted.\nWith that said, if you have a form that you want to submit, and some of its fields have id but not name attributes, using the id attribute instead seems like the only available option. It could be that other browsers use the id attribute, or perhaps there is some JavaScript code that handles the submission event instead of letting the browser do it.\n",
"An input tag without a name won't be submitted as a form parameter.\nFor example, create an HTML page containing just this:\n<form>\n <input type=\"text\" name=\"one\" value=\"foo\"/>\n <input type=\"text\" value=\"bar\"/>\n <input type=\"submit\"/>\n</form>\n\nYou can see that the second text field is missing a name attribute. If you click \"Submit,\" the page will refresh with the query string:\ntest.html?one=foo\n\n\nA good strategy for this would be to look at a live POST request sent by your browser and start by emulating that. Use a tool like the FireBug extension for Firefox to see the POST request and parameters sent by your browser. There might be parameters in there that you didn't notice before -- possibly because they were hidden form elements or they were created/set by JavaScript.\n"
] |
[
2,
0
] |
[] |
[] |
[
"forms",
"python",
"urllib",
"urllib2"
] |
stackoverflow_0000837195_forms_python_urllib_urllib2.txt
|
Q:
Python style iterators in C
The "yield" statement in python allows simple iteration from a procedure, and it also means that sequences don't need to be pre-calculated AND stored in a array of "arbitrary" size.
Is there a there a similar way of iterating (with yield) from a C procedure?
A:
Here follows a community-wiki copy of the self-answer, which can be chosen as "the" answer. Please direct up/downvotes to the actual self-answer
Here is the method I found:
/* Example calculates the sum of the prime factors of the first 32 Fibonacci numbers */
#include <stdio.h>
typedef enum{false=0, true=1}bool;
/* the following line is the only time I have ever required "auto" */
#define FOR(i,iterator) auto bool lambda(i); yield_init = (void *)λ iterator; bool lambda(i)
#define DO {
#define YIELD(x) if(!yield(x))return
#define BREAK return false
#define CONTINUE return true
#define OD CONTINUE; }
/* Warning: _Most_ FOR(,){ } loops _must_ have a CONTINUE as the last statement.
* * Otherwise the lambda will return random value from stack, and may terminate early */
typedef void iterator; /* hint at procedure purpose */
static volatile void *yield_init;
#define YIELDS(type) bool (*yield)(type) = yield_init
iterator fibonacci(int n){
YIELDS(int);
int i;
int pair[2] = {0,1};
YIELD(0); YIELD(1);
for(i=2; i<n; i++){
pair[i%2] = pair[0] + pair[1];
YIELD(pair[i%2]);
}
}
iterator factors(int n){
YIELDS(int);
int i;
for(i=2; i*i<=n; i++){
while(n%i == 0 ){
YIELD(i);
n/=i;
}
}
YIELD(n);
}
main(){
FOR(int i, fibonacci(32)){
printf("%d:", i);
int sum = 0;
FOR(int factor, factors(i)){
sum += factor;
printf(" %d",factor);
CONTINUE;
}
printf(" - sum of factors: %d\n", sum);
CONTINUE;
}
}
Got the idea from http://rosettacode.org/wiki/Prime_decomposition#ALGOL_68 - but it reads better in C
A:
I pull this URL out as a joke from time to time: Coroutines in C.
I think the correct answer to your question is this: there's no direct equivalent, and attempts to fake it probably won't be nearly as clean or easy to use.
A:
No.
Nice and short!
|
Python style iterators in C
|
The "yield" statement in python allows simple iteration from a procedure, and it also means that sequences don't need to be pre-calculated AND stored in a array of "arbitrary" size.
Is there a there a similar way of iterating (with yield) from a C procedure?
|
[
"Here follows a community-wiki copy of the self-answer, which can be chosen as \"the\" answer. Please direct up/downvotes to the actual self-answer\nHere is the method I found:\n /* Example calculates the sum of the prime factors of the first 32 Fibonacci numbers */\n#include <stdio.h>\n\ntypedef enum{false=0, true=1}bool;\n\n/* the following line is the only time I have ever required \"auto\" */\n#define FOR(i,iterator) auto bool lambda(i); yield_init = (void *)λ iterator; bool lambda(i)\n#define DO {\n#define YIELD(x) if(!yield(x))return\n#define BREAK return false\n#define CONTINUE return true\n#define OD CONTINUE; }\n/* Warning: _Most_ FOR(,){ } loops _must_ have a CONTINUE as the last statement. \n * * Otherwise the lambda will return random value from stack, and may terminate early */\n\ntypedef void iterator; /* hint at procedure purpose */\nstatic volatile void *yield_init;\n#define YIELDS(type) bool (*yield)(type) = yield_init\n\niterator fibonacci(int n){\n YIELDS(int);\n int i;\n int pair[2] = {0,1};\n YIELD(0); YIELD(1);\n for(i=2; i<n; i++){\n pair[i%2] = pair[0] + pair[1];\n YIELD(pair[i%2]);\n }\n}\n\niterator factors(int n){\n YIELDS(int); \n int i;\n for(i=2; i*i<=n; i++){\n while(n%i == 0 ){\n YIELD(i);\n n/=i;\n }\n }\n YIELD(n);\n}\n\nmain(){\n FOR(int i, fibonacci(32)){\n printf(\"%d:\", i);\n int sum = 0;\n FOR(int factor, factors(i)){\n sum += factor;\n printf(\" %d\",factor);\n CONTINUE;\n }\n printf(\" - sum of factors: %d\\n\", sum);\n CONTINUE;\n }\n}\n\nGot the idea from http://rosettacode.org/wiki/Prime_decomposition#ALGOL_68 - but it reads better in C\n",
"I pull this URL out as a joke from time to time: Coroutines in C.\nI think the correct answer to your question is this: there's no direct equivalent, and attempts to fake it probably won't be nearly as clean or easy to use.\n",
"No.\nNice and short!\n"
] |
[
6,
3,
0
] |
[] |
[] |
[
"algol68",
"c",
"iterator",
"jit",
"python"
] |
stackoverflow_0000833063_algol68_c_iterator_jit_python.txt
|
Q:
Python cgi and stdin
I'm using pycurl to upload a file via put and python cgi script to receive the file on the server side. Essentially, the code on the server side is:
while True:
next = sys.stdin.read(4096)
if not next:
break
#.... write the buffer
This seems to work with text, but not binary files (I'm on windows).
With binary files, the loop doing stdin.read breaks after receiving anything around 10kb to 100kb. Any ideas?
A:
You need to run Python in binary mode. Change your CGI script from:
#!C:/Python25/python.exe
or whatever it says to:
#!C:/Python25/python.exe -u
Or you can do it programmatically like this:
msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
before starting to read from stdin.
A:
Use mod_wsgi instead of cgi. It will provide you an input file for the upload that's correctly opened.
|
Python cgi and stdin
|
I'm using pycurl to upload a file via put and python cgi script to receive the file on the server side. Essentially, the code on the server side is:
while True:
next = sys.stdin.read(4096)
if not next:
break
#.... write the buffer
This seems to work with text, but not binary files (I'm on windows).
With binary files, the loop doing stdin.read breaks after receiving anything around 10kb to 100kb. Any ideas?
|
[
"You need to run Python in binary mode. Change your CGI script from:\n#!C:/Python25/python.exe\n\nor whatever it says to:\n#!C:/Python25/python.exe -u\n\nOr you can do it programmatically like this:\nmsvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)\n\nbefore starting to read from stdin.\n",
"Use mod_wsgi instead of cgi. It will provide you an input file for the upload that's correctly opened.\n"
] |
[
3,
0
] |
[] |
[] |
[
"cgi",
"python",
"stdin"
] |
stackoverflow_0000838991_cgi_python_stdin.txt
|
Q:
Popen log management question
Problem:
I have a monitor program in Python that uses subprocess' Popen to start new processes. These processes have the potential to run for a very long time (weeks-months). I'm passing a file handle to stdout variable in Popen and I'm worried that this file will get huge easily. Is there a way I can safely move or remove the data in that log file?
Important Note: This is on a windows system so any solution has to be compatible with windows.
Code Snippet:
This is how I create the process.
try:
logFile = file(self.logFileName, 'w')
self.process = Popen(self.command, shell=False, stdout=logFile, stderr=STDOUT)
finally:
logFile.close()
A:
Fix the monitor program so that it is responsible for rotating its own logs, or mediate the data coming from the log program yourself and package it out into separate files.
Those are the two options you have. You can't mess with another process' file descriptors once it's running, so no, you can't "move or remove the data" in that file.
= Mike
|
Popen log management question
|
Problem:
I have a monitor program in Python that uses subprocess' Popen to start new processes. These processes have the potential to run for a very long time (weeks-months). I'm passing a file handle to stdout variable in Popen and I'm worried that this file will get huge easily. Is there a way I can safely move or remove the data in that log file?
Important Note: This is on a windows system so any solution has to be compatible with windows.
Code Snippet:
This is how I create the process.
try:
logFile = file(self.logFileName, 'w')
self.process = Popen(self.command, shell=False, stdout=logFile, stderr=STDOUT)
finally:
logFile.close()
|
[
"Fix the monitor program so that it is responsible for rotating its own logs, or mediate the data coming from the log program yourself and package it out into separate files.\nThose are the two options you have. You can't mess with another process' file descriptors once it's running, so no, you can't \"move or remove the data\" in that file.\n= Mike\n"
] |
[
1
] |
[] |
[] |
[
"logging",
"popen",
"python"
] |
stackoverflow_0000840531_logging_popen_python.txt
|
Q:
authentication method
I am writing a server-client application to receive user message and publish it.
Thinking about authentication method.
Asymmetric encryption, probably RSA.
Hash (salt+password+'msg'+'userid'), SHA256
HMAC, SHA256. seems to be more secured than the method 2. Also involve hashing the password and msg data.
Symmetric Encryption of the 'msg' with static password stored on both sides, probably AES.
There is no need for encryption as the msg would be publish online anyway. So I am more lean to the HMAC or PKI method.
I'm using java to send the request (including whatever authentication method to be implemented)
www.mysite.com/foo?userid=12345&msg=hello&token=abc1234
python on the server side to receive request and make sure the request is from the valid user.
The problems are in integration and make sure both sides understand each other's authentication token. It is a big factor for me. And the availability of the libraries available on both language are taken into account as well.
Or I can choose to rewrite the server side into java. (Why not python? The client side application need to be in java)
What do you think?
EDIT: I would not treat this as a web application. The application does not serve any webpage. Most of the operations are not related to the web. Just the client-server communication go through internet. And sending POST/GET via HTTP is what I thought of as the simpler albeit insecure way to do it. Feel free to suggest me any other alternative.
SSL is a secure way for encryption. But it does not prevent attacker from sending message to the server impose as the user. Anyone can initiate a HTTPS connection. And the content of the communication does not need to be encrypted. It will be published online by the server anyway. What I need is a way to authenticate the message and sender.
For now I am lean to HMAC algorithm. RSA would be more secure but it comes with more developer efforts as well. Will see how it goes.
Thank you.
A:
Can't you just use standard SSL sockets to secure the connection, validate the user with a password, and then send the message to be published? If there won't be many clients, you can even use a self-signed certificate and put it in a KeyStore in the client app, that way you won't need to buy a certificate from Verisign or anyone else.
If you are storing the user's password hash on the server (as I think you should otherwise how are you going to validate the user's password), then you can first reproduce that hash on the client side (let's assume you hash user+pass) and then append that to the message and hash the result. You send the user id, hash and message to the server.
On the server side you receive a request with a user id, you retrieve the user's password (the server only has stored the hash of user+pass), you append that to the message and hash it again, and compare it against the hash in the request. If it matches, the user can publish the message.
Oh and you should use HTTP POST, instead of sending data on the URL. The server should not accept data on the URL for the publish request.
A:
OK, firstly, an option to consider is just going down the "enterprise solution" route and buying into the standard PKI market: buy yourself a certificate from Veri$ign etc and use boring old HTTPS (or at least TLS, the underlying protocol). Then sending the data from the client is (more or less) a doddle, and there'll be a standard library in whatever langauge you choose to interpret things at the other end. I actually think HTTPS/TLS and the whole certificate infrastructure is a complicated waste of space for applications where you know what server you're talking to and you know what encryption system you want to use. But the availability of libraries "out of the box" means it might get you up and running quickly, so it's definitely worth considering one way or the other.
In principle, you don't need a PKI-issued certificate to use HTTPS/TLS. But in practice, it may be easier to just spend the few dollars than try and persuade a standard library to accept a self-issued certificate. (In general, using HTTPS libraries may just mean you end up turning the 2-day "programming my encryption system" problem into a 2-day "why isn't this black box accepting my certificate" problem-- it also kind of depends on what problem you fancy solving...)
Even if you don't use HTTPS/TLS, you may want to read through the spec, to understand how it overcomes certain security threats (and what those threats are).
OK, so then taking your points:
Just to be clear, you DON'T need a certificate or PKI to use RSA or other asymmetric encryption. A PKI (attemptedly) solves the problem of a client needing to talk to a "mystery" server that it can't trust when that server says "here is my public key". If you're writing a dedicated client and you know in advance which server you're talking to, then you can just distribute the public key with your client. The client knows it's talking to the right server, because if it wasn't, that server wouldn't understand things that it encrypted with that public key.
The main thing you need to be careful of when using "raw" hashes is that they're vulnerable to extension attacks. So if you send "a|b|c" plus the hash code for that data, an attacker can work out the hash code for "a|b|c|d" (so in your example (2), they could substitute "userid" for "useridX" and work out a new hash code for this, based on the hash code you supplied for "a|b|c"). HMAC schemes get round this problem.
In any case, if you go for using "raw" encryption tools, still use standard libraries, because they'll have thought about some security issues. For example, with RSA, you have to be careful to use padding (see some info I've written on RSA encryption in Java and the cryptography section it's in-- that might be interesting for you). And when generating any encryption key, you need to be careful about "where the random data is coming from".
You don't have to base the AES encryption key on the password (if you do, read up on password-based encryption schemes: password generally have little entropy, so you need to take extra measures to try and protect against this). But I would go for the more standard approach of using the password to authenticate the connection, and as part of the authentication, negotiate a random AES key.
Make sure that you're addressing the issue of replay attacks in your scheme (generally, the client and server should each send each other a random "nonce" at the start of the communication, and authentication and future communication over that connection will depend on the nonce).
A:
Let me just add a few random thoughts/comments to your proposals.
RSA: Since you are mainly interested in authentication, I assume you'd want to use RSA signatures. This would imply that each user needs his own privat key. To me that sounds a little bit like overkill, especially when user and server already share common secrets (i.e., passwords).
Using SHA256 is a good approach. I have some problems to understand why you include a salt, since a salt is commonly use to avoid that an attacker precomputes hashes of dictionaries. To be clear: dicitionary attacks are a problem here. An attacker could try to hash messages with all passwords from a dictionary. Just he has to reapeat this attack for each user and can't reuse precomputed values. One way to make such an attack a little
more difficult is called key strengthening, e.g. by reapeatedly hashing the result n times
and hence forcing an attacker to perform more work during a dictionary attack.
I completely agree that HMAC is better than just SHA-256. After all HMAC was designed for authentication. I'm not sure why you want to hash the message before computing the HMAC. HMAC does that for you.
Encryption does not always provide authentication. This is specially in cases when the attacker learns the plaintext, as he does in your case. He might be able to exploit properties of the encryption mode to manipulate the ciphertext an know exactly how the resulting plaintext will look like (E.g. the CBC mode allows these kind of manipulations). Your previous proposal (HMAC) is preferable.
Finally, if you can setup an SSL connection between user and server, as others suggest: this would be a much safer solution, since not even the dicionary attack mentioned above would be possible.
A:
RSA protocol is generally used to setup a key exchange for a faster encryption means. That's how SSL works.
If the security requirements for your applications are so sensitive that you require PKI, then it should be said (without any intent to be harsh) that if you need to ask about it on SO, then its probably something you shouldn't attempt to do (given that generally successful attacks on secure channels attack weakpoints of the implementation).
As Chochos has suggested, what's wrong with simply using the existing SSL infrastructure in Java and your server to set up a secure https connection and then simply pass the user password from client to the server?
|
authentication method
|
I am writing a server-client application to receive user message and publish it.
Thinking about authentication method.
Asymmetric encryption, probably RSA.
Hash (salt+password+'msg'+'userid'), SHA256
HMAC, SHA256. seems to be more secured than the method 2. Also involve hashing the password and msg data.
Symmetric Encryption of the 'msg' with static password stored on both sides, probably AES.
There is no need for encryption as the msg would be publish online anyway. So I am more lean to the HMAC or PKI method.
I'm using java to send the request (including whatever authentication method to be implemented)
www.mysite.com/foo?userid=12345&msg=hello&token=abc1234
python on the server side to receive request and make sure the request is from the valid user.
The problems are in integration and make sure both sides understand each other's authentication token. It is a big factor for me. And the availability of the libraries available on both language are taken into account as well.
Or I can choose to rewrite the server side into java. (Why not python? The client side application need to be in java)
What do you think?
EDIT: I would not treat this as a web application. The application does not serve any webpage. Most of the operations are not related to the web. Just the client-server communication go through internet. And sending POST/GET via HTTP is what I thought of as the simpler albeit insecure way to do it. Feel free to suggest me any other alternative.
SSL is a secure way for encryption. But it does not prevent attacker from sending message to the server impose as the user. Anyone can initiate a HTTPS connection. And the content of the communication does not need to be encrypted. It will be published online by the server anyway. What I need is a way to authenticate the message and sender.
For now I am lean to HMAC algorithm. RSA would be more secure but it comes with more developer efforts as well. Will see how it goes.
Thank you.
|
[
"Can't you just use standard SSL sockets to secure the connection, validate the user with a password, and then send the message to be published? If there won't be many clients, you can even use a self-signed certificate and put it in a KeyStore in the client app, that way you won't need to buy a certificate from Verisign or anyone else.\nIf you are storing the user's password hash on the server (as I think you should otherwise how are you going to validate the user's password), then you can first reproduce that hash on the client side (let's assume you hash user+pass) and then append that to the message and hash the result. You send the user id, hash and message to the server.\nOn the server side you receive a request with a user id, you retrieve the user's password (the server only has stored the hash of user+pass), you append that to the message and hash it again, and compare it against the hash in the request. If it matches, the user can publish the message.\nOh and you should use HTTP POST, instead of sending data on the URL. The server should not accept data on the URL for the publish request.\n",
"OK, firstly, an option to consider is just going down the \"enterprise solution\" route and buying into the standard PKI market: buy yourself a certificate from Veri$ign etc and use boring old HTTPS (or at least TLS, the underlying protocol). Then sending the data from the client is (more or less) a doddle, and there'll be a standard library in whatever langauge you choose to interpret things at the other end. I actually think HTTPS/TLS and the whole certificate infrastructure is a complicated waste of space for applications where you know what server you're talking to and you know what encryption system you want to use. But the availability of libraries \"out of the box\" means it might get you up and running quickly, so it's definitely worth considering one way or the other.\nIn principle, you don't need a PKI-issued certificate to use HTTPS/TLS. But in practice, it may be easier to just spend the few dollars than try and persuade a standard library to accept a self-issued certificate. (In general, using HTTPS libraries may just mean you end up turning the 2-day \"programming my encryption system\" problem into a 2-day \"why isn't this black box accepting my certificate\" problem-- it also kind of depends on what problem you fancy solving...)\nEven if you don't use HTTPS/TLS, you may want to read through the spec, to understand how it overcomes certain security threats (and what those threats are).\nOK, so then taking your points:\n\nJust to be clear, you DON'T need a certificate or PKI to use RSA or other asymmetric encryption. A PKI (attemptedly) solves the problem of a client needing to talk to a \"mystery\" server that it can't trust when that server says \"here is my public key\". If you're writing a dedicated client and you know in advance which server you're talking to, then you can just distribute the public key with your client. The client knows it's talking to the right server, because if it wasn't, that server wouldn't understand things that it encrypted with that public key.\nThe main thing you need to be careful of when using \"raw\" hashes is that they're vulnerable to extension attacks. So if you send \"a|b|c\" plus the hash code for that data, an attacker can work out the hash code for \"a|b|c|d\" (so in your example (2), they could substitute \"userid\" for \"useridX\" and work out a new hash code for this, based on the hash code you supplied for \"a|b|c\"). HMAC schemes get round this problem.\nIn any case, if you go for using \"raw\" encryption tools, still use standard libraries, because they'll have thought about some security issues. For example, with RSA, you have to be careful to use padding (see some info I've written on RSA encryption in Java and the cryptography section it's in-- that might be interesting for you). And when generating any encryption key, you need to be careful about \"where the random data is coming from\".\nYou don't have to base the AES encryption key on the password (if you do, read up on password-based encryption schemes: password generally have little entropy, so you need to take extra measures to try and protect against this). But I would go for the more standard approach of using the password to authenticate the connection, and as part of the authentication, negotiate a random AES key.\nMake sure that you're addressing the issue of replay attacks in your scheme (generally, the client and server should each send each other a random \"nonce\" at the start of the communication, and authentication and future communication over that connection will depend on the nonce).\n\n",
"Let me just add a few random thoughts/comments to your proposals.\n\nRSA: Since you are mainly interested in authentication, I assume you'd want to use RSA signatures. This would imply that each user needs his own privat key. To me that sounds a little bit like overkill, especially when user and server already share common secrets (i.e., passwords).\nUsing SHA256 is a good approach. I have some problems to understand why you include a salt, since a salt is commonly use to avoid that an attacker precomputes hashes of dictionaries. To be clear: dicitionary attacks are a problem here. An attacker could try to hash messages with all passwords from a dictionary. Just he has to reapeat this attack for each user and can't reuse precomputed values. One way to make such an attack a little\nmore difficult is called key strengthening, e.g. by reapeatedly hashing the result n times\nand hence forcing an attacker to perform more work during a dictionary attack.\nI completely agree that HMAC is better than just SHA-256. After all HMAC was designed for authentication. I'm not sure why you want to hash the message before computing the HMAC. HMAC does that for you.\nEncryption does not always provide authentication. This is specially in cases when the attacker learns the plaintext, as he does in your case. He might be able to exploit properties of the encryption mode to manipulate the ciphertext an know exactly how the resulting plaintext will look like (E.g. the CBC mode allows these kind of manipulations). Your previous proposal (HMAC) is preferable.\n\nFinally, if you can setup an SSL connection between user and server, as others suggest: this would be a much safer solution, since not even the dicionary attack mentioned above would be possible.\n",
"RSA protocol is generally used to setup a key exchange for a faster encryption means. That's how SSL works. \nIf the security requirements for your applications are so sensitive that you require PKI, then it should be said (without any intent to be harsh) that if you need to ask about it on SO, then its probably something you shouldn't attempt to do (given that generally successful attacks on secure channels attack weakpoints of the implementation).\nAs Chochos has suggested, what's wrong with simply using the existing SSL infrastructure in Java and your server to set up a secure https connection and then simply pass the user password from client to the server?\n"
] |
[
2,
1,
1,
0
] |
[] |
[] |
[
"authentication",
"encryption",
"hash",
"java",
"python"
] |
stackoverflow_0000834932_authentication_encryption_hash_java_python.txt
|
Q:
Sort lexicographically?
I am working on integrating with the Photobucket API and I came across this in their api docs:
"Sort the parameters by name
lexographically [sic] (byte ordering, the
standard sorting, not natural or case
insensitive). If the parameters have
the same name, then sort by the value."
What does that mean? How do I sort something lexicographically? byte ordering?
The rest of their docs have been ok so far, but (to me) it seems like this line bears further explanation. Unfortunately there was none to be had.
Anyway, I'm writing the application in Python (it'll eventually become a Django app) in case you want to recommend specific modules that will handle such sorting for me ^_^
A:
I think that here lexicographic is a "alias" for ascii sort?
Lexicographic Natural
z1.doc z1.doc
z10.doc z2.doc
z100.doc z3.doc
z101.doc z4.doc
z102.doc z5.doc
z11.doc z6.doc
z12.doc z7.doc
z13.doc z8.doc
z14.doc z9.doc
z15.doc z10.doc
z16.doc z11.doc
z17.doc z12.doc
z18.doc z13.doc
z19.doc z14.doc
z2.doc z15.doc
z20.doc z16.doc
z3.doc z17.doc
z4.doc z18.doc
z5.doc z19.doc
z6.doc z20.doc
z7.doc z100.doc
z8.doc z101.doc
z9.doc z102.doc
A:
The word should be "lexicographic"
http://www.thefreedictionary.com/Lexicographic
Dictionary order. Using the letters as they appear in the strings.
As they suggest, don't fold upper- and lower-case together. Just use the Python built-in list.sort() method.
A:
This is similar to the Facebook API — the query string needs to be normalized before generating the signature hash.
You probably have a dictionary of parameters like:
params = {
'consumer_key': "....",
'consumer_secret': "....",
'timestamp': ...,
...
}
Create the query string like so:
urllib.urlencode(sorted(params.items()))
params.items() returns the keys and values of the dictionary as a list tuples, sorted() sorts the list, and urllib.urlencode() concatenates them into a single string while escaping.
A:
Quote a bit more from the section:
2 Generate the Base String:
Normalize the parameters:
Add the OAuth specific parameters for this request to the input parameters, including:
oauth_consumer_key = <consumer_key>
oauth_timestamp = <timestamp>
oauth_nonce = <nonce>
oauth_version = <version>
oauth_signature_method = <signature_method>
Sort the parameters by name lexographically [sic] (byte ordering, the standard sorting, not natural or case insensitive). If the parameters have the same name, then sort by the value.
Encode the parameter values as in RFC3986 Section 2 (i.e., urlencode).
Create parameter string (). This is the same format as HTTP 'postdata' or 'querystring', that is, each parameter represented as name=value separated by &. For example, a=1&b=2&c=hello%20there&c=something%20else
I think that they are saying that the parameters must appear in the sorted order - oauth_consumer_key before oauth_nonce before ...
|
Sort lexicographically?
|
I am working on integrating with the Photobucket API and I came across this in their api docs:
"Sort the parameters by name
lexographically [sic] (byte ordering, the
standard sorting, not natural or case
insensitive). If the parameters have
the same name, then sort by the value."
What does that mean? How do I sort something lexicographically? byte ordering?
The rest of their docs have been ok so far, but (to me) it seems like this line bears further explanation. Unfortunately there was none to be had.
Anyway, I'm writing the application in Python (it'll eventually become a Django app) in case you want to recommend specific modules that will handle such sorting for me ^_^
|
[
"I think that here lexicographic is a \"alias\" for ascii sort?\n\nLexicographic Natural \nz1.doc z1.doc \nz10.doc z2.doc \nz100.doc z3.doc \nz101.doc z4.doc \nz102.doc z5.doc \nz11.doc z6.doc \nz12.doc z7.doc \nz13.doc z8.doc \nz14.doc z9.doc \nz15.doc z10.doc \nz16.doc z11.doc \nz17.doc z12.doc \nz18.doc z13.doc \nz19.doc z14.doc \nz2.doc z15.doc \nz20.doc z16.doc \nz3.doc z17.doc \nz4.doc z18.doc \nz5.doc z19.doc \nz6.doc z20.doc \nz7.doc z100.doc \nz8.doc z101.doc \nz9.doc z102.doc \n\n",
"The word should be \"lexicographic\"\nhttp://www.thefreedictionary.com/Lexicographic\nDictionary order. Using the letters as they appear in the strings. \nAs they suggest, don't fold upper- and lower-case together. Just use the Python built-in list.sort() method.\n",
"This is similar to the Facebook API — the query string needs to be normalized before generating the signature hash.\nYou probably have a dictionary of parameters like:\nparams = {\n 'consumer_key': \"....\",\n 'consumer_secret': \"....\",\n 'timestamp': ...,\n ...\n}\n\nCreate the query string like so:\nurllib.urlencode(sorted(params.items()))\n\nparams.items() returns the keys and values of the dictionary as a list tuples, sorted() sorts the list, and urllib.urlencode() concatenates them into a single string while escaping.\n",
"Quote a bit more from the section:\n\n2 Generate the Base String:\nNormalize the parameters:\n\nAdd the OAuth specific parameters for this request to the input parameters, including:\noauth_consumer_key = <consumer_key>\noauth_timestamp = <timestamp>\noauth_nonce = <nonce>\noauth_version = <version>\noauth_signature_method = <signature_method>\n\nSort the parameters by name lexographically [sic] (byte ordering, the standard sorting, not natural or case insensitive). If the parameters have the same name, then sort by the value.\nEncode the parameter values as in RFC3986 Section 2 (i.e., urlencode).\n Create parameter string (). This is the same format as HTTP 'postdata' or 'querystring', that is, each parameter represented as name=value separated by &. For example, a=1&b=2&c=hello%20there&c=something%20else\n\n\nI think that they are saying that the parameters must appear in the sorted order - oauth_consumer_key before oauth_nonce before ...\n"
] |
[
8,
6,
4,
1
] |
[] |
[] |
[
"api",
"photobucket",
"python",
"sorting"
] |
stackoverflow_0000840637_api_photobucket_python_sorting.txt
|
Q:
mod_python publisher and pretty URLs
I am new to Python (I am getting out of PHP because of how increasingly broken it is), and I am racing through porting my old code. One thing:
I have a file /foo.py with functions index() and bar(), so, with the publisher I can access http://domain/foo/bar and http://domain/foo as the documentation suggests.
How can I have it such that I can do:
http://domain/foo/bar/a1/a2/a3/an/...
Such that the publisher launches bar() and then I can access the URL to obtain /a1/a2/...
All I get is Forbidden :) (I don't want to use mod_rewrite on everything)
Oh, im on 2.5.2
Thanks in advance
UPDATE: The ideal solution would be for the publisher to launch the furthest-right resolution in the URL it can, and simply make a1/a2/a3.. accessible through the apache module. Maybe a combination of an apache directive and publisher?
SOLVED (ish):
The answer of the magic call() method and so on is juicy! Although I think I will modify the publisher or write my own to inspect objects in a similar way using furthest-right matching, then allowing the furthest-right to access the URL using apache module. Thanks all!
A:
You would have to have an object bar.a1.a2.a3.an defined within your foo.py module. Basically, the publisher handler replaces the slashes in the URL with dots, and tries to find some Python object with that name.
You would have to have an object bar.a1.a2.a3.an defined within your foo.py module. Basically, the publisher handler replaces the slashes in the URL with dots, and tries to find some Python object with that name.
Here's something wacky you could try: in foo.py:
class _barclass(object):
def __init__(self, parent, name):
if parent and name:
self.path = parent.path + '/' + name
setattr(parent, name, self)
else:
self.path = ''
def __getattr__(self, name):
return _barclass(self, name)
def __call__(self):
# do your processing here
# url path is contained in self.path
bar = _barclass(None, None)
Although this is kind of straining the bounds of what the publisher is meant to do - you might be better off writing your own handlers from scratch. (Or using something like Django.)
A:
I believe this is beyond the capabilities of the publishing algorithm, as far as I know. (The documentation certainly doesn't mention it.) You could write your own mod_python handler (example here) that extends the publishing algorithm to do so, however.
A better solution would be to look into mod_wsgi and build your web application as an WSGI application instead. You would benefit from the shelves and shelves of WSGI middleware, but in particular you'd be able to use routing software like Routes, which are specifically designed to handle these cases where object publishing isn't strong enough. But I don't know your deadlines, so this may or may not be feasible.
|
mod_python publisher and pretty URLs
|
I am new to Python (I am getting out of PHP because of how increasingly broken it is), and I am racing through porting my old code. One thing:
I have a file /foo.py with functions index() and bar(), so, with the publisher I can access http://domain/foo/bar and http://domain/foo as the documentation suggests.
How can I have it such that I can do:
http://domain/foo/bar/a1/a2/a3/an/...
Such that the publisher launches bar() and then I can access the URL to obtain /a1/a2/...
All I get is Forbidden :) (I don't want to use mod_rewrite on everything)
Oh, im on 2.5.2
Thanks in advance
UPDATE: The ideal solution would be for the publisher to launch the furthest-right resolution in the URL it can, and simply make a1/a2/a3.. accessible through the apache module. Maybe a combination of an apache directive and publisher?
SOLVED (ish):
The answer of the magic call() method and so on is juicy! Although I think I will modify the publisher or write my own to inspect objects in a similar way using furthest-right matching, then allowing the furthest-right to access the URL using apache module. Thanks all!
|
[
"You would have to have an object bar.a1.a2.a3.an defined within your foo.py module. Basically, the publisher handler replaces the slashes in the URL with dots, and tries to find some Python object with that name.\nYou would have to have an object bar.a1.a2.a3.an defined within your foo.py module. Basically, the publisher handler replaces the slashes in the URL with dots, and tries to find some Python object with that name.\nHere's something wacky you could try: in foo.py:\nclass _barclass(object):\n def __init__(self, parent, name):\n if parent and name:\n self.path = parent.path + '/' + name\n setattr(parent, name, self)\n else:\n self.path = ''\n def __getattr__(self, name):\n return _barclass(self, name)\n def __call__(self):\n # do your processing here\n # url path is contained in self.path\n\nbar = _barclass(None, None)\n\nAlthough this is kind of straining the bounds of what the publisher is meant to do - you might be better off writing your own handlers from scratch. (Or using something like Django.)\n",
"I believe this is beyond the capabilities of the publishing algorithm, as far as I know. (The documentation certainly doesn't mention it.) You could write your own mod_python handler (example here) that extends the publishing algorithm to do so, however.\nA better solution would be to look into mod_wsgi and build your web application as an WSGI application instead. You would benefit from the shelves and shelves of WSGI middleware, but in particular you'd be able to use routing software like Routes, which are specifically designed to handle these cases where object publishing isn't strong enough. But I don't know your deadlines, so this may or may not be feasible.\n"
] |
[
1,
1
] |
[] |
[] |
[
"friendly_url",
"mod_python",
"python",
"url"
] |
stackoverflow_0000841068_friendly_url_mod_python_python_url.txt
|
Q:
wxPython: Drawing inside a ScrolledPanel
I'm using a PaintDC to draw inside a ScrolledPanel. However, when I run the program, the scroll bars have no effect. They're the right size, but the picture doesn't move when you scroll with them.
I figured I may have to convert from logical to device coordinates. I tried x=dc.LogicalToDeviceX(x) and y=dc.LogicalToDeviceY(y), but there was no effect.
Any ideas?
A:
Got it:
(new_x,new_y)=self.CalcScrolledPosition((old_x,old_y))
Where self is the ScrolledPanel.
|
wxPython: Drawing inside a ScrolledPanel
|
I'm using a PaintDC to draw inside a ScrolledPanel. However, when I run the program, the scroll bars have no effect. They're the right size, but the picture doesn't move when you scroll with them.
I figured I may have to convert from logical to device coordinates. I tried x=dc.LogicalToDeviceX(x) and y=dc.LogicalToDeviceY(y), but there was no effect.
Any ideas?
|
[
"Got it:\n(new_x,new_y)=self.CalcScrolledPosition((old_x,old_y))\n\nWhere self is the ScrolledPanel.\n"
] |
[
1
] |
[] |
[] |
[
"python",
"scroll",
"wxpython"
] |
stackoverflow_0000841425_python_scroll_wxpython.txt
|
Q:
WinXP button-style with wxPython
I noticed that my programs written with wxPython have Win98 button style.
But Boa Constructor (that is written using wxPython too) got pretty buttons.
How to make buttons look like current Windows buttons style?
A:
Are you packaging the app with py2exe?
If so you may need to specify a manifest file to make Python use the WinXP(Vista?) theme/Common Controls:
http://wiki.wxpython.org/DistributingYourApplication
A:
Expanding on John's answer, you may also be able to create manifest files for python.exe and pythonw.exe to see the new styles without first packaging using py2exe.
A:
The answers so far handle distributing the package as an executable (eg. py2exe), where the answer has already been given.
But since (i think) python 2.6 you have the same problem when just starting the .py file from the commandline (Vista and Windows7). Robin Dunn suggested using update_manifest.py which he distributes with wxPython and puts it in the same directory as python.exe.
After applying update_manifest.py using a copied version of python.exe wxPython apps have the correct themed look and yes it also works using windows7 RC1.
|
WinXP button-style with wxPython
|
I noticed that my programs written with wxPython have Win98 button style.
But Boa Constructor (that is written using wxPython too) got pretty buttons.
How to make buttons look like current Windows buttons style?
|
[
"Are you packaging the app with py2exe?\nIf so you may need to specify a manifest file to make Python use the WinXP(Vista?) theme/Common Controls:\nhttp://wiki.wxpython.org/DistributingYourApplication\n",
"Expanding on John's answer, you may also be able to create manifest files for python.exe and pythonw.exe to see the new styles without first packaging using py2exe.\n",
"The answers so far handle distributing the package as an executable (eg. py2exe), where the answer has already been given.\nBut since (i think) python 2.6 you have the same problem when just starting the .py file from the commandline (Vista and Windows7). Robin Dunn suggested using update_manifest.py which he distributes with wxPython and puts it in the same directory as python.exe.\nAfter applying update_manifest.py using a copied version of python.exe wxPython apps have the correct themed look and yes it also works using windows7 RC1.\n"
] |
[
3,
1,
0
] |
[
"Have you tried running your scripts with pythonw.exe instead of python.exe?\n"
] |
[
-2
] |
[
"coding_style",
"python",
"wxpython"
] |
stackoverflow_0000642853_coding_style_python_wxpython.txt
|
Q:
How to use subversion Ctypes Python Bindings?
Subversion 1.6 introduce something that is called 'Ctypes Python Binding', but it is not documented. Is it any information available what this bindings are and how to use it? For example, i have a fresh windows XP and want to control SVN repository using subversiion 1.6 and this mysterious python bindings. What exactly i need to download/install/compile in order to do something like
import svn from almighty_ctype_subversion_bindings
svn.get( "\\rep\\project" )
And how is this connected to pysvn project? Is this a same technology, or different technologies?
A:
You need the Subversion source distribution, Python (>= 2.5), and ctypesgen.
Instructions for building the ctypes bindings are here.
You will end up with a package called csvn, examples of it's use are here.
A:
The whole point of ctypes is that you shouldn't need to have to compile anything anywhere. That said, the readme for the bindings mentions some dependencies and a build step.
The bindings can be found in the Subversion source distribution at least, in subversion/bindings/ctypes-python/, with a distutils setup.py.
They seem to be a successor / alternative of sorts to pysvn.
|
How to use subversion Ctypes Python Bindings?
|
Subversion 1.6 introduce something that is called 'Ctypes Python Binding', but it is not documented. Is it any information available what this bindings are and how to use it? For example, i have a fresh windows XP and want to control SVN repository using subversiion 1.6 and this mysterious python bindings. What exactly i need to download/install/compile in order to do something like
import svn from almighty_ctype_subversion_bindings
svn.get( "\\rep\\project" )
And how is this connected to pysvn project? Is this a same technology, or different technologies?
|
[
"You need the Subversion source distribution, Python (>= 2.5), and ctypesgen.\nInstructions for building the ctypes bindings are here.\nYou will end up with a package called csvn, examples of it's use are here.\n",
"The whole point of ctypes is that you shouldn't need to have to compile anything anywhere. That said, the readme for the bindings mentions some dependencies and a build step.\nThe bindings can be found in the Subversion source distribution at least, in subversion/bindings/ctypes-python/, with a distutils setup.py.\nThey seem to be a successor / alternative of sorts to pysvn.\n"
] |
[
1,
0
] |
[
"I looked into the python binding for subversion, but in the end I found it to be simpler to just invoke svn.exe like this:\n(stdout, stderr, err) = execute('svn export \"%s\" \"%s\"' \\\n % (exportURL, workingCopyFolder))\n\nwhere execute is a function like this:\ndef execute(cmd):\n import subprocess\n proc = subprocess.Popen(\\\n cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n (stdout, stderr) = proc.communicate()\n return (stdout, stderr, proc.returncode)\n\nThe output of svn.exe is designed to be easily parsed if necessary. There is even a --xml output option.\n"
] |
[
-1
] |
[
"python",
"svn"
] |
stackoverflow_0000815530_python_svn.txt
|
Q:
Python: ODBC Exception Handling
I need to recognize in my application whether table doesn't exist or has no rows to take appropriate action. Can I catch this two errors separately ?
>>>cursor.execute("delete from TABLE")
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
dbi.internal-error: [IBM][CLI Driver][DB2] SQL0100W No row was found for FETCH, UPDATE or DELETE; or the result of a query is an empty table. SQLSTATE=02000
in EXEC
OR
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
dbi.program-error: [IBM][CLI Driver][DB2] SQL0204N "SK77531.TCS_EXCEPTIONS" is an undefined name. SQLSTATE=42704
in EXEC
A:
From the Python documentation:
A try statement may have more than one except clause, to specify handlers for different exceptions.
For example:
try:
do_something_crazy
except AttributeError:
print 'there was an AttributeError'
except NameError:
print 'there was a NameError'
except:
print 'something else failed miserably'
The last except acts as a catch-all here, and is only executed if an exception different than an AttributeError or NameError occurs. In production code it's best to steer clear from such catch-all except clauses, because in general you'll want your code to fail whenever an error that you didn't expect occurs.
In your specific case you'll need to import the different exceptions that can be raised from the dbi module, so you can check for them in different except clauses.
So something like this:
# No idea if this is the right import, but they should be somewhere in that module
import dbi
try:
cursor.execute("delete from TABLE")
except dbi.internal-error:
print 'internal-error'
except dbi.program-error:
print 'program-error'
As you'll see in the above-lined documentation page, you can opt to include additional attributed in each except clause. Doing so will let you access the actual error object, which might be necessary for you at some point when you need to distinguish between two different exceptions of the same class. Even if you don't need such a fine level of distinction, it's still a good idea to do a bit more checking than I outlined above to make sure you're actually dealing with the error you think you're dealing with.
All that said and done about try/except, what I'd really recommend is to search for a method in the database library code you're using to check whether a table exist or not before you try to interact with it. Structured try/excepts are very useful when you're dealing with outside input that needs to be checked and sanitized, but coding defensively around the tentative existence of a database table sounds like something that's going to turn around and bite you later.
|
Python: ODBC Exception Handling
|
I need to recognize in my application whether table doesn't exist or has no rows to take appropriate action. Can I catch this two errors separately ?
>>>cursor.execute("delete from TABLE")
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
dbi.internal-error: [IBM][CLI Driver][DB2] SQL0100W No row was found for FETCH, UPDATE or DELETE; or the result of a query is an empty table. SQLSTATE=02000
in EXEC
OR
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
dbi.program-error: [IBM][CLI Driver][DB2] SQL0204N "SK77531.TCS_EXCEPTIONS" is an undefined name. SQLSTATE=42704
in EXEC
|
[
"From the Python documentation:\n\nA try statement may have more than one except clause, to specify handlers for different exceptions.\n\nFor example:\ntry:\n do_something_crazy\nexcept AttributeError:\n print 'there was an AttributeError'\nexcept NameError:\n print 'there was a NameError'\nexcept:\nprint 'something else failed miserably'\n\nThe last except acts as a catch-all here, and is only executed if an exception different than an AttributeError or NameError occurs. In production code it's best to steer clear from such catch-all except clauses, because in general you'll want your code to fail whenever an error that you didn't expect occurs.\nIn your specific case you'll need to import the different exceptions that can be raised from the dbi module, so you can check for them in different except clauses.\nSo something like this:\n# No idea if this is the right import, but they should be somewhere in that module\nimport dbi\n\ntry:\n cursor.execute(\"delete from TABLE\")\nexcept dbi.internal-error:\n print 'internal-error'\nexcept dbi.program-error:\n print 'program-error'\n\nAs you'll see in the above-lined documentation page, you can opt to include additional attributed in each except clause. Doing so will let you access the actual error object, which might be necessary for you at some point when you need to distinguish between two different exceptions of the same class. Even if you don't need such a fine level of distinction, it's still a good idea to do a bit more checking than I outlined above to make sure you're actually dealing with the error you think you're dealing with.\nAll that said and done about try/except, what I'd really recommend is to search for a method in the database library code you're using to check whether a table exist or not before you try to interact with it. Structured try/excepts are very useful when you're dealing with outside input that needs to be checked and sanitized, but coding defensively around the tentative existence of a database table sounds like something that's going to turn around and bite you later.\n"
] |
[
1
] |
[] |
[] |
[
"odbc",
"python"
] |
stackoverflow_0000841968_odbc_python.txt
|
Q:
Piping Batch File output to a Python script
I'm trying to write a python script (in windows) that runs a batch file and will take the command line output of that batch file as input. The batch file runs processes that I don't have access to and gives output based on whether those processes are successful. I'd like to take those messages from the batch file and use them in the python script. Anyone have any ideas on how to do this ?
A:
import subprocess
output= subprocess.Popen(
("c:\\bin\\batch.bat", "an_argument", "another_argument"),
stdout=subprocess.PIPE).stdout
for line in output:
# do your work here
output.close()
Note that it's preferable to start your batch file with "@echo off".
A:
Here is a sample python script that runs test.bat and displays the output:
import os
fh = os.popen("test.bat")
output = fh.read()
print "This is the output of test.bat:", output
fh.close()
Source of test.bat:
@echo off
echo "This is test.bat"
A:
Try subprocess.Popen(). It allows you to redirect stdout and stderr to files.
|
Piping Batch File output to a Python script
|
I'm trying to write a python script (in windows) that runs a batch file and will take the command line output of that batch file as input. The batch file runs processes that I don't have access to and gives output based on whether those processes are successful. I'd like to take those messages from the batch file and use them in the python script. Anyone have any ideas on how to do this ?
|
[
"import subprocess\n\noutput= subprocess.Popen(\n (\"c:\\\\bin\\\\batch.bat\", \"an_argument\", \"another_argument\"),\n stdout=subprocess.PIPE).stdout\n\nfor line in output:\n # do your work here\n\noutput.close()\n\nNote that it's preferable to start your batch file with \"@echo off\".\n",
"Here is a sample python script that runs test.bat and displays the output:\nimport os\n\nfh = os.popen(\"test.bat\")\noutput = fh.read()\nprint \"This is the output of test.bat:\", output\nfh.close()\n\nSource of test.bat:\n@echo off\necho \"This is test.bat\"\n\n",
"Try subprocess.Popen(). It allows you to redirect stdout and stderr to files.\n"
] |
[
9,
2,
1
] |
[] |
[] |
[
"batch_file",
"io",
"python",
"scripting",
"windows"
] |
stackoverflow_0000842120_batch_file_io_python_scripting_windows.txt
|
Q:
What are some good ways to set a path in a Multi-OS supported Python script
When writing a Python script that can be executed in different operating system environments (Windows/*nix), what are some good ways to set a path? In the example below I would like to have the logfiles stored in the logs folder under the current directory. Is this an acceptable approach (I'm rather new to Python) or are there better ways to achieve this? Thanks
if os.name == 'nt':
logdir=('%s\\logs\\') % (os.getcwd())
else:
logdir=('%s/logs/') % (os.getcwd())
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m-%d-%y %H:%M:%S',
filename='%slogfile.log' % (logdir),
filemode='a')
A:
Definitely have a look at os.path. It contains many of the "safe" cross-OS path manipulation functions you need. For example, I've always done this in the scenario you're outlining:
os.path.join(os.path.abspath(os.path.dirname(__file__)), 'logs')
Also note that if you want to get the path separator, you can use:
os.path.sep
This will yield '\\' on Windows, and '/' on Linux, for example.
A:
First, always use os.path for path manipulation.
More importantly, all paths should be provided in configuration files.
For logging, use the fileConfig function.
For everything else, be sure to have a configuration file or command-line parameter or environment variable.
|
What are some good ways to set a path in a Multi-OS supported Python script
|
When writing a Python script that can be executed in different operating system environments (Windows/*nix), what are some good ways to set a path? In the example below I would like to have the logfiles stored in the logs folder under the current directory. Is this an acceptable approach (I'm rather new to Python) or are there better ways to achieve this? Thanks
if os.name == 'nt':
logdir=('%s\\logs\\') % (os.getcwd())
else:
logdir=('%s/logs/') % (os.getcwd())
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m-%d-%y %H:%M:%S',
filename='%slogfile.log' % (logdir),
filemode='a')
|
[
"Definitely have a look at os.path. It contains many of the \"safe\" cross-OS path manipulation functions you need. For example, I've always done this in the scenario you're outlining:\nos.path.join(os.path.abspath(os.path.dirname(__file__)), 'logs')\n\nAlso note that if you want to get the path separator, you can use:\nos.path.sep\n\nThis will yield '\\\\' on Windows, and '/' on Linux, for example.\n",
"First, always use os.path for path manipulation.\nMore importantly, all paths should be provided in configuration files.\nFor logging, use the fileConfig function.\nFor everything else, be sure to have a configuration file or command-line parameter or environment variable.\n"
] |
[
8,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0000842570_python.txt
|
Q:
find in files using ruby or python
A popular text editor has the following "find in files" feature that opens in a dialog box:
Look For: __searchtext__
File Filter: *.txt; *.htm
Start From: c:/docs/2009
Report: [ ] Filenames [ ]FileCount only
Method: [ ] Regex [ ]Plain Text
In fact, several popular text editors have this.
I would like to do the same thing but using a python or ruby class instead of a text editor.
That way, this same kind of brain-dead simple operation can be run from a script on any platform that supports ruby or python.
Question: I don't feel like writing this myself, so does anyone know of a ruby or python script that accepts the same or similar easy input args and does what you'd expect?
I am looking for something that does a brute-force linear search, nothing to do with indexed searches.
A:
I know you said you don't feel like writing it yourself, but for what it's worth, it would be very easy using os.walk - you could do something like this:
results = []
if regex_search:
p = re.compile(__searchtext__)
for dir, subdirs, subfiles in os.walk('c:/docs/2009'):
for name in fnmatch.filter(subfiles, '*.txt'):
fn = os.path.join(dir, name)
with open(fn, 'r') as f:
if regex_search:
results += [(fn,lineno) for lineno, line in enumerate(f) if p.search(line)]
else:
results += [(fn,lineno) for lineno, line in enumerate(f) if line.find(__searchtext__) >= 0]
(that's Python, btw)
A:
Grepper is a Ruby gem by David A. Black for doing exactly that:
g = Grepper.new
g.files = %w{ one.txt two.txt three.txt }
g.options = %w{ B2 } # two lines of before-context
g.pattern = /__search_string__/
g.run
g.results.each do |file, result|
result.matches.each do |lineno, before, line, after|
etc....
I believe it shells out to grep and wraps the results in Ruby objects, which means it takes the same options as grep. Install with:
sudo gem install grepper
|
find in files using ruby or python
|
A popular text editor has the following "find in files" feature that opens in a dialog box:
Look For: __searchtext__
File Filter: *.txt; *.htm
Start From: c:/docs/2009
Report: [ ] Filenames [ ]FileCount only
Method: [ ] Regex [ ]Plain Text
In fact, several popular text editors have this.
I would like to do the same thing but using a python or ruby class instead of a text editor.
That way, this same kind of brain-dead simple operation can be run from a script on any platform that supports ruby or python.
Question: I don't feel like writing this myself, so does anyone know of a ruby or python script that accepts the same or similar easy input args and does what you'd expect?
I am looking for something that does a brute-force linear search, nothing to do with indexed searches.
|
[
"I know you said you don't feel like writing it yourself, but for what it's worth, it would be very easy using os.walk - you could do something like this:\nresults = []\nif regex_search:\n p = re.compile(__searchtext__)\nfor dir, subdirs, subfiles in os.walk('c:/docs/2009'):\n for name in fnmatch.filter(subfiles, '*.txt'):\n fn = os.path.join(dir, name)\n with open(fn, 'r') as f:\n if regex_search:\n results += [(fn,lineno) for lineno, line in enumerate(f) if p.search(line)]\n else:\n results += [(fn,lineno) for lineno, line in enumerate(f) if line.find(__searchtext__) >= 0]\n\n(that's Python, btw)\n",
"Grepper is a Ruby gem by David A. Black for doing exactly that:\ng = Grepper.new\ng.files = %w{ one.txt two.txt three.txt }\ng.options = %w{ B2 } # two lines of before-context\ng.pattern = /__search_string__/\ng.run\n\ng.results.each do |file, result|\n result.matches.each do |lineno, before, line, after|\n etc....\n\nI believe it shells out to grep and wraps the results in Ruby objects, which means it takes the same options as grep. Install with:\nsudo gem install grepper\n\n"
] |
[
5,
3
] |
[] |
[] |
[
"file",
"grep",
"python",
"ruby",
"search"
] |
stackoverflow_0000842598_file_grep_python_ruby_search.txt
|
Q:
Django equivalent of COUNT with GROUP BY
I know Django 1.1 has some new aggregation methods. However I couldn't figure out equivalent of the following query:
SELECT player_type, COUNT(*) FROM players GROUP BY player_type;
Is it possible with Django 1.1's Model Query API or should I just use plain SQL?
A:
If you are using Django 1.1 beta (trunk):
Player.objects.values('player_type').order_by().annotate(Count('player_type'))
values('player_type') - for inclusion only player_type field into GROUP BY clause.
order_by() - for exclusion possible default ordering that can cause not needed fields inclusion in SELECT and GROUP BY.
A:
Django 1.1 does support aggregation methods like count. You can find the full documentation here.
To answer your question, you can use something along the lines of:
from django.db.models import Count
q = Player.objects.annotate(Count('games'))
print q[0]
print q[0].games__count
This will need slight tweaking depending on your actual model.
Edit: The above snippet generates aggregations on a per-object basis. If you want aggregation on a particular field in the model, you can use the values method:
from django.db.models import Count
q = Player.objects.values('playertype').annotate(Count('games')).order_by()
print q[0]
print q[0].games__count
order_by() is needed because fields that are in the default ordering are automatically selected even if they are not explicitly passed to values(). This call to order_by() clears any ordering and makes the query behave as expected.
Also, if you want to count the field that is used for grouping (equivalent to COUNT(*)), you can use:
from django.db.models import Count
q = Player.objects.values('playertype').annotate(Count('playertype')).order_by()
print q[0]
print q[0].playertype__count
|
Django equivalent of COUNT with GROUP BY
|
I know Django 1.1 has some new aggregation methods. However I couldn't figure out equivalent of the following query:
SELECT player_type, COUNT(*) FROM players GROUP BY player_type;
Is it possible with Django 1.1's Model Query API or should I just use plain SQL?
|
[
"If you are using Django 1.1 beta (trunk):\nPlayer.objects.values('player_type').order_by().annotate(Count('player_type'))\n\n\nvalues('player_type') - for inclusion only player_type field into GROUP BY clause.\norder_by() - for exclusion possible default ordering that can cause not needed fields inclusion in SELECT and GROUP BY.\n\n",
"Django 1.1 does support aggregation methods like count. You can find the full documentation here.\nTo answer your question, you can use something along the lines of:\nfrom django.db.models import Count\nq = Player.objects.annotate(Count('games'))\nprint q[0]\nprint q[0].games__count\n\nThis will need slight tweaking depending on your actual model.\nEdit: The above snippet generates aggregations on a per-object basis. If you want aggregation on a particular field in the model, you can use the values method:\nfrom django.db.models import Count\nq = Player.objects.values('playertype').annotate(Count('games')).order_by()\nprint q[0]\nprint q[0].games__count\n\norder_by() is needed because fields that are in the default ordering are automatically selected even if they are not explicitly passed to values(). This call to order_by() clears any ordering and makes the query behave as expected.\nAlso, if you want to count the field that is used for grouping (equivalent to COUNT(*)), you can use:\nfrom django.db.models import Count\nq = Player.objects.values('playertype').annotate(Count('playertype')).order_by()\nprint q[0]\nprint q[0].playertype__count\n\n"
] |
[
65,
16
] |
[] |
[] |
[
"django",
"django_aggregation",
"django_queryset",
"python",
"sql"
] |
stackoverflow_0000842031_django_django_aggregation_django_queryset_python_sql.txt
|
Q:
How can I use Django admin list and filterering in my own views?
I’m just beginning to learn Django and I like the automatic listing in Django admin and the way you can configure filters and what columns to show. Is it possible to use it in my own applications?
I’ve looked in the source for the admin and figured out that I probably want to subclass the “ChangeList”-object in some way and use it in my own views. Any ideas?
A:
You're better off doing the following.
Define a regular old Django query for your various kinds of filters. These are very easy to write.
Use the supplied generic view functions. These are very easy to use.
Create your own templates with links to your filters. You'll be building a list links based on the results of a query. For a few hard-coded cases, this is very easy. In the super-general admin-interface case, this is not simple.
Do this first. Get it to work. It won't take long. It's very important to understand Django at this level before diving into the way the admin applications work.
Later -- after you have something running -- you can spend several hours learning how the inner mysteries of the admin interface work.
|
How can I use Django admin list and filterering in my own views?
|
I’m just beginning to learn Django and I like the automatic listing in Django admin and the way you can configure filters and what columns to show. Is it possible to use it in my own applications?
I’ve looked in the source for the admin and figured out that I probably want to subclass the “ChangeList”-object in some way and use it in my own views. Any ideas?
|
[
"You're better off doing the following.\n\nDefine a regular old Django query for your various kinds of filters. These are very easy to write.\nUse the supplied generic view functions. These are very easy to use.\nCreate your own templates with links to your filters. You'll be building a list links based on the results of a query. For a few hard-coded cases, this is very easy. In the super-general admin-interface case, this is not simple.\n\nDo this first. Get it to work. It won't take long. It's very important to understand Django at this level before diving into the way the admin applications work.\nLater -- after you have something running -- you can spend several hours learning how the inner mysteries of the admin interface work.\n"
] |
[
1
] |
[] |
[] |
[
"django",
"django_queryset",
"django_views",
"filter",
"python"
] |
stackoverflow_0000843182_django_django_queryset_django_views_filter_python.txt
|
Q:
Pygame cannot find include file "sdl.h"
I am trying to build a downloaded Python app on Windows that uses Pygame. I have installed Python 2.5 and Pygame 1.7.1. I am new to Python, but I just tried typing the name of the top level .py file on a Windows console command line. (I'm using Win XP Pro.)
This is the message that I get.
C:\Python25\include\pygame\pygame.h(68) : fatal error C1083: Cannot open include
file: 'SDL.h': No such file or directory
I thought that Pygame was built on top of SDL and that a separate SDL install was not necessary. Nevertheless, I installed SDL 1.2.13 and added the SDL include folder to my %INCLUDE% environment variable. Still no luck.
I noticed that C:\Python25\Lib\site-packages\pygame includes several SDL*.DLL files, but there is no sdl.h header file anywhere in the python tree. Of course, I could copy the sdl headers into the C:\Python25\include\pygame folder, but that is a distasteful idea.
Anybody know the right way to set things up?
EDIT:
The application is "The Penguin Machine" pygame app.
A:
I tried compiling and got the same errors on my linux box:
$ python setup.py build
DBG> include = ['/usr/include', '/usr/include/python2.6', '/usr/include/SDL']
running build
running build_ext
building 'surfutils' extension
creating build
creating build/temp.linux-i686-2.6
creating build/temp.linux-i686-2.6/src
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include -I/usr/include/python2.6 -I/usr/include/SDL -I/usr/include/python2.6 -c src/surfutils.c -o build/temp.linux-i686-2.6/src/surfutils.o
In file included from src/surfutils.c:1:
/usr/include/python2.6/pygame/pygame.h:68:17: error: SDL.h: Arquivo ou diretório inexistente
In file included from src/surfutils.c:1:
/usr/include/python2.6/pygame/pygame.h:312: error: expected specifier-qualifier-list before ‘SDL_VideoInfo’
/usr/include/python2.6/pygame/pygame.h:350: error: expected specifier-qualifier-list before ‘SDL_Surface’
src/surfutils.c:5: error: expected ‘)’ before ‘*’ token
src/surfutils.c: In function ‘PyCollisionPoint’:
src/surfutils.c:74: error: ‘SDL_Surface’ undeclared (first use in this function)
src/surfutils.c:74: error: (Each undeclared identifier is reported only once
src/surfutils.c:74: error: for each function it appears in.)
src/surfutils.c:74: error: ‘surf1’ undeclared (first use in this function)
src/surfutils.c:74: error: ‘surf2’ undeclared (first use in this function)
src/surfutils.c:74: warning: left-hand operand of comma expression has no effect
src/surfutils.c:92: error: ‘PySurfaceObject’ has no member named ‘surf’
src/surfutils.c:97: error: ‘SDL_SRCALPHA’ undeclared (first use in this function)
src/surfutils.c:111: error: ‘PySurfaceObject’ has no member named ‘surf’
src/surfutils.c:161: warning: implicit declaration of function ‘collisionPoint’
error: command 'gcc' failed with exit status 1
Seems like it tries to compile a extension called surfutils which needs SDL development headers.
So I installed the libsdl1.2-dev package using my distribution package manager and it worked just fine. You must install SDL development headers in order to build it for your system.
So your question really is: How do I install SDL development headers on windows, and how I make the program use them?
Well, I can answer the second question. You must edit setup.py:
#!/usr/bin/env python2.3
from distutils.core import setup, Extension
from distutils.sysconfig import get_config_vars
includes = []
includes.extend(get_config_vars('INCLUDEDIR'))
includes.extend(get_config_vars('INCLUDEPY'))
includes.append('/usr/include/SDL')
print 'DBG> include =', includes
setup(name='surfutils',
version='1.0',
ext_modules=[Extension(
'surfutils',
['src/surfutils.c'],
include_dirs=includes,
)],
)
Change line 9. It says:
includes.append('/usr/include/SDL')
Change this path to wherever your SDL headers are, i.e.:
includes.append(r'C:\mydevelopmentheaders\SDL')
Leave a note to the game developer to say you're having this trouble. It could provide a better way of finding SDL headers on your platform.
A:
When you compile something the compiler looks up header files in several directories, some hardcoded and build in, and typically some given as arguments to the compiler (like for instance "gcc -I/usr/local/include ..."). One guess is that you are missing this. If not check out other possible causes to your error message.
You will need to have the SDL Development Libraries installed, but since you say "I could copy the sdl headers" it sounds like you already have. Then your problem is only to get the compiler to look in the include directory containing those files.
|
Pygame cannot find include file "sdl.h"
|
I am trying to build a downloaded Python app on Windows that uses Pygame. I have installed Python 2.5 and Pygame 1.7.1. I am new to Python, but I just tried typing the name of the top level .py file on a Windows console command line. (I'm using Win XP Pro.)
This is the message that I get.
C:\Python25\include\pygame\pygame.h(68) : fatal error C1083: Cannot open include
file: 'SDL.h': No such file or directory
I thought that Pygame was built on top of SDL and that a separate SDL install was not necessary. Nevertheless, I installed SDL 1.2.13 and added the SDL include folder to my %INCLUDE% environment variable. Still no luck.
I noticed that C:\Python25\Lib\site-packages\pygame includes several SDL*.DLL files, but there is no sdl.h header file anywhere in the python tree. Of course, I could copy the sdl headers into the C:\Python25\include\pygame folder, but that is a distasteful idea.
Anybody know the right way to set things up?
EDIT:
The application is "The Penguin Machine" pygame app.
|
[
"I tried compiling and got the same errors on my linux box:\n$ python setup.py build\nDBG> include = ['/usr/include', '/usr/include/python2.6', '/usr/include/SDL']\nrunning build\nrunning build_ext\nbuilding 'surfutils' extension\ncreating build\ncreating build/temp.linux-i686-2.6\ncreating build/temp.linux-i686-2.6/src\ngcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include -I/usr/include/python2.6 -I/usr/include/SDL -I/usr/include/python2.6 -c src/surfutils.c -o build/temp.linux-i686-2.6/src/surfutils.o\nIn file included from src/surfutils.c:1:\n/usr/include/python2.6/pygame/pygame.h:68:17: error: SDL.h: Arquivo ou diretório inexistente\nIn file included from src/surfutils.c:1:\n/usr/include/python2.6/pygame/pygame.h:312: error: expected specifier-qualifier-list before ‘SDL_VideoInfo’\n/usr/include/python2.6/pygame/pygame.h:350: error: expected specifier-qualifier-list before ‘SDL_Surface’\nsrc/surfutils.c:5: error: expected ‘)’ before ‘*’ token\nsrc/surfutils.c: In function ‘PyCollisionPoint’:\nsrc/surfutils.c:74: error: ‘SDL_Surface’ undeclared (first use in this function)\nsrc/surfutils.c:74: error: (Each undeclared identifier is reported only once\nsrc/surfutils.c:74: error: for each function it appears in.)\nsrc/surfutils.c:74: error: ‘surf1’ undeclared (first use in this function)\nsrc/surfutils.c:74: error: ‘surf2’ undeclared (first use in this function)\nsrc/surfutils.c:74: warning: left-hand operand of comma expression has no effect\nsrc/surfutils.c:92: error: ‘PySurfaceObject’ has no member named ‘surf’\nsrc/surfutils.c:97: error: ‘SDL_SRCALPHA’ undeclared (first use in this function)\nsrc/surfutils.c:111: error: ‘PySurfaceObject’ has no member named ‘surf’\nsrc/surfutils.c:161: warning: implicit declaration of function ‘collisionPoint’\nerror: command 'gcc' failed with exit status 1\n\nSeems like it tries to compile a extension called surfutils which needs SDL development headers.\nSo I installed the libsdl1.2-dev package using my distribution package manager and it worked just fine. You must install SDL development headers in order to build it for your system.\nSo your question really is: How do I install SDL development headers on windows, and how I make the program use them?\nWell, I can answer the second question. You must edit setup.py:\n#!/usr/bin/env python2.3\n\nfrom distutils.core import setup, Extension\nfrom distutils.sysconfig import get_config_vars\n\nincludes = []\nincludes.extend(get_config_vars('INCLUDEDIR'))\nincludes.extend(get_config_vars('INCLUDEPY'))\nincludes.append('/usr/include/SDL')\n\nprint 'DBG> include =', includes\n\nsetup(name='surfutils',\n version='1.0',\n ext_modules=[Extension(\n 'surfutils', \n ['src/surfutils.c'], \n include_dirs=includes,\n )],\n )\n\nChange line 9. It says:\nincludes.append('/usr/include/SDL')\n\nChange this path to wherever your SDL headers are, i.e.:\nincludes.append(r'C:\\mydevelopmentheaders\\SDL')\n\nLeave a note to the game developer to say you're having this trouble. It could provide a better way of finding SDL headers on your platform.\n",
"When you compile something the compiler looks up header files in several directories, some hardcoded and build in, and typically some given as arguments to the compiler (like for instance \"gcc -I/usr/local/include ...\"). One guess is that you are missing this. If not check out other possible causes to your error message.\nYou will need to have the SDL Development Libraries installed, but since you say \"I could copy the sdl headers\" it sounds like you already have. Then your problem is only to get the compiler to look in the include directory containing those files.\n"
] |
[
5,
2
] |
[] |
[] |
[
"pygame",
"python",
"sdl"
] |
stackoverflow_0000841654_pygame_python_sdl.txt
|
Q:
How to render contents of a tag in unicode in BeautifulSoup?
This is a soup from a WordPress post detail page:
content = soup.body.find('div', id=re.compile('post'))
title = content.h2.extract()
item['title'] = unicode(title.string)
item['content'] = u''.join(map(unicode, content.contents))
I want to omit the enclosing div tag when assigning item['content']. Is there any way to render all the child tags of a tag in unicode? Something like:
item['content'] = content.contents.__unicode__()
that will give me a single unicode string instead of a list.
A:
Have you tried:
unicode(content)
It converts content's markup to a single Unicode string.
Edit: If you don't want the enclosing tag, try:
content.renderContents()
|
How to render contents of a tag in unicode in BeautifulSoup?
|
This is a soup from a WordPress post detail page:
content = soup.body.find('div', id=re.compile('post'))
title = content.h2.extract()
item['title'] = unicode(title.string)
item['content'] = u''.join(map(unicode, content.contents))
I want to omit the enclosing div tag when assigning item['content']. Is there any way to render all the child tags of a tag in unicode? Something like:
item['content'] = content.contents.__unicode__()
that will give me a single unicode string instead of a list.
|
[
"Have you tried:\nunicode(content)\n\nIt converts content's markup to a single Unicode string.\nEdit: If you don't want the enclosing tag, try:\ncontent.renderContents()\n\n"
] |
[
6
] |
[] |
[] |
[
"beautifulsoup",
"python",
"screen_scraping",
"web_applications",
"xml"
] |
stackoverflow_0000843227_beautifulsoup_python_screen_scraping_web_applications_xml.txt
|
Q:
Computing the second (mis-match) table in the Boyer-Moore String Search Algorithm
For the Boyer-Moore algorithm to be worst-case linear, the computation of the mis-match table must be O(m). However, a naive implementation would loop through all suffixs O(m) and all positions in that that suffix could go and check for equality... which is O(m3)!
Below is the naive implementation of table building algorithm. So this question becomes: How can I improve this algorithm's runtime to O(m)?
def find(s, sub, no):
n = len(s)
m = len(sub)
for i in range(n, 0, -1):
if s[max(i-m, 0): i] == sub[max(0, m-i):] and \
(i-m < 1 or s[i-m-1] != no):
return n-i
return n
def table(s):
m = len(s)
b = [0]*m
for i in range(m):
b[i] = find(s, s[m-i:], s[m-i-1])
return b
print(table('anpanman'))
To put minds at rest, this isn't homework. I'll add revisions when anyone posts ideas for improvements.
A:
The code under "Preprocessing for the good-suffix heuristics" on this page builds the good-suffix table in O(n) time. It also explains how the code works.
|
Computing the second (mis-match) table in the Boyer-Moore String Search Algorithm
|
For the Boyer-Moore algorithm to be worst-case linear, the computation of the mis-match table must be O(m). However, a naive implementation would loop through all suffixs O(m) and all positions in that that suffix could go and check for equality... which is O(m3)!
Below is the naive implementation of table building algorithm. So this question becomes: How can I improve this algorithm's runtime to O(m)?
def find(s, sub, no):
n = len(s)
m = len(sub)
for i in range(n, 0, -1):
if s[max(i-m, 0): i] == sub[max(0, m-i):] and \
(i-m < 1 or s[i-m-1] != no):
return n-i
return n
def table(s):
m = len(s)
b = [0]*m
for i in range(m):
b[i] = find(s, s[m-i:], s[m-i-1])
return b
print(table('anpanman'))
To put minds at rest, this isn't homework. I'll add revisions when anyone posts ideas for improvements.
|
[
"The code under \"Preprocessing for the good-suffix heuristics\" on this page builds the good-suffix table in O(n) time. It also explains how the code works.\n"
] |
[
1
] |
[] |
[] |
[
"algorithm",
"discrete_mathematics",
"python",
"string_search"
] |
stackoverflow_0000840974_algorithm_discrete_mathematics_python_string_search.txt
|
Q:
How does garbage collection in Python work with class methods?
class example:
def exampleMethod(self):
aVar = 'some string'
return aVar
In this example, how does garbage collection work after each call to example.exampleMethod()? Will aVar be deallocated once the method returns?
A:
The variable is never deallocated.
The object (in this case a string, with a value of 'some string' is reused again and again, so that object can never be deallocated.
Objects are deallocated when no variable refers to the object. Think of this.
a = 'hi mom'
a = 'next value'
In this case, the first object (a string with the value 'hi mom') is no longer referenced anywhere in the script when the second statement is executed. The object ('hi mom') can be removed from memory.
A:
Every time You assign an object to a variable, You increase this object's reference counter.
a = MyObject() # +1, so it's at 1
b = a # +1, so it's now 2
a = 'something else' # -1, so it's 1
b = 'something else' # -1, so it's 0
Noone can access this the MyObject object We have created at the first line anymore.
When the counter reaches zero, the garbage collector frees the memory.
There is a way to make a tricky reference that does not increase reference counter (f.e. if You don't want an object to be hold in memory just because it's in some cache dict).
More on cPython's reference counting can be found here.
Python is language, cPython is it's (quite popular) implementation. Afaik the language itself doesn't specify how the memory is freed.
A:
From your example, if you call example.exampleMethod() , without assigning the results (eg. a = example.exampleMethod()) then it will be deallocated straight away (in CPython), as CPython uses a reference counting mechanism. Strings aren't a very good example to use, because they also have a number of implementation specific optimizations. Strings can be cached, and are not deallocated so that they can be reused. This is especially useful because strings are very common for use as keys in dicts.
Again, garbage collecting is specific to the implementations, so CPython, Jython and IronPython will have different behaviours, most of these being documented on the respective sites/manuals/code/etc. If you want to explore a bit, I'd suggest creating a class where you have defined the del() method, which will be called upon the object being garbage collected (it's the destructor). Make it print something so you can trace it's call :)
A:
As in Nico's answer, it depends on what you do with the result returned by exampleMethod. Python (or CPython anyway) uses reference counting. During the method, aVar references the string, while after that the variable aVar is deleted, which may leave no references, in which case, it is deleted.
Below is an example with a custom class that has a destructor (del(self), that print out "Object 1 being destructed" or similar. The gc is the garbage collector module, that automatically deletes objects with a reference count of 0. It's there for convenience, as otherwise there is no guarantee when the garbage collector is run.
import gc
class Noisy(object):
def __init__(self, n):
self.n = n
def __del__(self):
print "Object " + str(self.n) + " being destructed"
class example(object):
def exampleMethod(self, n):
aVar = Noisy(n)
return aVar
a = example()
a.exampleMethod(1)
b = a.exampleMethod(2)
gc.collect()
print "Before b is deleted"
del b
gc.collect()
print "After b is deleted"
The result should be as follows:
Object 1 being destructed
Before b is deleted
Object 2 being destructed
After b is deleted
Notice that the first Noisy object is deleted after the method is returned, as it is not assigned to a variable, so has a reference count of 0, but the second one is deleted only after the variable b is deleted, leaving a reference count of 0.
|
How does garbage collection in Python work with class methods?
|
class example:
def exampleMethod(self):
aVar = 'some string'
return aVar
In this example, how does garbage collection work after each call to example.exampleMethod()? Will aVar be deallocated once the method returns?
|
[
"The variable is never deallocated.\nThe object (in this case a string, with a value of 'some string' is reused again and again, so that object can never be deallocated.\nObjects are deallocated when no variable refers to the object. Think of this.\na = 'hi mom'\na = 'next value'\n\nIn this case, the first object (a string with the value 'hi mom') is no longer referenced anywhere in the script when the second statement is executed. The object ('hi mom') can be removed from memory.\n",
"Every time You assign an object to a variable, You increase this object's reference counter.\na = MyObject() # +1, so it's at 1\nb = a # +1, so it's now 2\na = 'something else' # -1, so it's 1\nb = 'something else' # -1, so it's 0\n\nNoone can access this the MyObject object We have created at the first line anymore.\nWhen the counter reaches zero, the garbage collector frees the memory.\nThere is a way to make a tricky reference that does not increase reference counter (f.e. if You don't want an object to be hold in memory just because it's in some cache dict).\nMore on cPython's reference counting can be found here.\nPython is language, cPython is it's (quite popular) implementation. Afaik the language itself doesn't specify how the memory is freed.\n",
"From your example, if you call example.exampleMethod() , without assigning the results (eg. a = example.exampleMethod()) then it will be deallocated straight away (in CPython), as CPython uses a reference counting mechanism. Strings aren't a very good example to use, because they also have a number of implementation specific optimizations. Strings can be cached, and are not deallocated so that they can be reused. This is especially useful because strings are very common for use as keys in dicts.\nAgain, garbage collecting is specific to the implementations, so CPython, Jython and IronPython will have different behaviours, most of these being documented on the respective sites/manuals/code/etc. If you want to explore a bit, I'd suggest creating a class where you have defined the del() method, which will be called upon the object being garbage collected (it's the destructor). Make it print something so you can trace it's call :)\n",
"As in Nico's answer, it depends on what you do with the result returned by exampleMethod. Python (or CPython anyway) uses reference counting. During the method, aVar references the string, while after that the variable aVar is deleted, which may leave no references, in which case, it is deleted.\nBelow is an example with a custom class that has a destructor (del(self), that print out \"Object 1 being destructed\" or similar. The gc is the garbage collector module, that automatically deletes objects with a reference count of 0. It's there for convenience, as otherwise there is no guarantee when the garbage collector is run.\nimport gc\nclass Noisy(object):\n def __init__(self, n):\n self.n = n\n def __del__(self):\n print \"Object \" + str(self.n) + \" being destructed\" \nclass example(object):\n def exampleMethod(self, n):\n aVar = Noisy(n)\n return aVar\na = example()\na.exampleMethod(1)\nb = a.exampleMethod(2)\ngc.collect()\nprint \"Before b is deleted\"\ndel b\ngc.collect()\nprint \"After b is deleted\"\n\nThe result should be as follows:\nObject 1 being destructed\nBefore b is deleted\nObject 2 being destructed\nAfter b is deleted\n\nNotice that the first Noisy object is deleted after the method is returned, as it is not assigned to a variable, so has a reference count of 0, but the second one is deleted only after the variable b is deleted, leaving a reference count of 0.\n"
] |
[
7,
5,
3,
0
] |
[] |
[] |
[
"garbage_collection",
"python"
] |
stackoverflow_0000843459_garbage_collection_python.txt
|
Q:
call function between time intervals
In app engine I would like to call a function if the current time is between a particular interval. This is what I am doing now.
ist_time = datetime.utcnow() + timedelta(hours=5, minutes = 30)
ist_midnight = ist_time.replace(hour=0, minute=0, second=0, microsecond=0)
market_open = ist_midnight + timedelta(hours=9, minutes = 55)
market_close = ist_midnight + timedelta(hours=16, minutes = 01)
if ist_time >= market_open and ist_time <= market_close:
check_for_updates()
Any better way of doing this.
A:
This is more compact, but not so obvious:
if '09:55' <= time.strftime(
'%H:%M', time.gmtime((time.time() + 60 * (5 * 60 + 30)))) <= '16:01':
check_for_updates()
Depending on how important it is for you to do the calculations absolutely properly, you may want to consider daylight saving time (use pytz for that -- it is possible to upload pytz bundled to your app to AppEngine) and seconds and millisecods as well (e.g. use < '16:02' instead of <= '16:01', because the former doesn't depend on the second/subsecond precision.
A:
It seems like you might want datetime's "time" type, which doesn't care about date.
import datetime
ist_time = datetime.utcnow() + datetime.timedelta(hours=5, minutes = 30)
# Turn this into a time object (no day information).
ist_time = ist_time.time()
if datetime.time(9, 55) <= ist_time <= datetime.time(16, 1):
...
I'm sure there's a more elegant way to handle the timezone adjustment using tzinfo, but I have to confess I've never dealt with timezones.
|
call function between time intervals
|
In app engine I would like to call a function if the current time is between a particular interval. This is what I am doing now.
ist_time = datetime.utcnow() + timedelta(hours=5, minutes = 30)
ist_midnight = ist_time.replace(hour=0, minute=0, second=0, microsecond=0)
market_open = ist_midnight + timedelta(hours=9, minutes = 55)
market_close = ist_midnight + timedelta(hours=16, minutes = 01)
if ist_time >= market_open and ist_time <= market_close:
check_for_updates()
Any better way of doing this.
|
[
"This is more compact, but not so obvious:\nif '09:55' <= time.strftime(\n '%H:%M', time.gmtime((time.time() + 60 * (5 * 60 + 30)))) <= '16:01':\n check_for_updates()\n\nDepending on how important it is for you to do the calculations absolutely properly, you may want to consider daylight saving time (use pytz for that -- it is possible to upload pytz bundled to your app to AppEngine) and seconds and millisecods as well (e.g. use < '16:02' instead of <= '16:01', because the former doesn't depend on the second/subsecond precision.\n",
"It seems like you might want datetime's \"time\" type, which doesn't care about date.\nimport datetime\nist_time = datetime.utcnow() + datetime.timedelta(hours=5, minutes = 30)\n# Turn this into a time object (no day information).\nist_time = ist_time.time()\nif datetime.time(9, 55) <= ist_time <= datetime.time(16, 1):\n ...\n\nI'm sure there's a more elegant way to handle the timezone adjustment using tzinfo, but I have to confess I've never dealt with timezones.\n"
] |
[
1,
0
] |
[] |
[] |
[
"datetime",
"python",
"time",
"timezone"
] |
stackoverflow_0000843614_datetime_python_time_timezone.txt
|
Q:
python: can I extend the upper bound of the range() method?
What is the upper bound of the range() function and how can I extend it, or alternately what's the best way to do this:
for i in range(1,600851475143):
A:
range(1, 600851475143) wants to generate a very large list in memory, and you'll get an out of memory error. To save memory, use xrange instead of range. Unfortunately, xrange doesn't work with large numbers (it's an implementation restriction) Example (raises OverflowError):
for i in xrange(1, 600851475143):
print i
You can have large minimum or maximum values in your interval with range, if their difference is small. Example:
x = 1 << 200
print list(xrange(x, x + 3))
Output:
[1606938044258990275541962092341162602522202993782792835301376L, 1606938044258990275541962092341162602522202993782792835301377L, 1606938044258990275541962092341162602522202993782792835301378L]
A fancy solution to your original for loop problem:
def bigrange(a, b = None):
if b is None:
b = a
a = 0
while a < b:
yield a
a += 1
for i in bigrange(1, 600851475143):
print i
A less fancy solution, which works even if you have continue in the loop body:
i = 1 - 1
while i < 600851475143 - 1:
i += 1
print i
A:
pts' answer led me to this in the xrange python docs:
Note
xrange() is intended to be simple and
fast. Implementations may impose
restrictions to achieve this. The C
implementation of Python restricts all
arguments to native C longs (“short”
Python integers), and also requires
that the number of elements fit in a
native C long. If a larger range is
needed, an alternate version can be
crafted using the itertools module:
islice(count(start, step), (stop-start+step-1)//step)
looks like it's a limitation of c python in particular.
A:
Have you considered just doing this? Or is there some reason you specifically need range()?
x = 1
while x < 600851475143:
// some code
x += 1
A:
It depends on which version of Python you're using. I'm using 2.5.2 and xrange raises an OverflowError exception for large numbers. One solution is to write your own generator.
def g(start, stop):
i = start
while i < stop:
yield i
i += 1
x = 1<<200
for i in g(x, x+3):
print i
A:
Here's an answer using itertools. It's a little contrived, but it works:
from itertools import repeat, count, izip
for i,_ in izip(count(1), repeat(1, 600851475143)):
...
Another answer would be to write your own generator:
def my_xrange(a, b):
while a < b:
yield a
a += 1
for i in my_xrange(1, 600851475143):
...
|
python: can I extend the upper bound of the range() method?
|
What is the upper bound of the range() function and how can I extend it, or alternately what's the best way to do this:
for i in range(1,600851475143):
|
[
"range(1, 600851475143) wants to generate a very large list in memory, and you'll get an out of memory error. To save memory, use xrange instead of range. Unfortunately, xrange doesn't work with large numbers (it's an implementation restriction) Example (raises OverflowError):\nfor i in xrange(1, 600851475143):\n print i\n\nYou can have large minimum or maximum values in your interval with range, if their difference is small. Example:\nx = 1 << 200\nprint list(xrange(x, x + 3))\n\nOutput:\n[1606938044258990275541962092341162602522202993782792835301376L, 1606938044258990275541962092341162602522202993782792835301377L, 1606938044258990275541962092341162602522202993782792835301378L]\n\nA fancy solution to your original for loop problem:\ndef bigrange(a, b = None):\n if b is None:\n b = a\n a = 0\n while a < b:\n yield a\n a += 1\n\nfor i in bigrange(1, 600851475143):\n print i\n\nA less fancy solution, which works even if you have continue in the loop body:\ni = 1 - 1\nwhile i < 600851475143 - 1:\n i += 1\n print i\n\n",
"pts' answer led me to this in the xrange python docs:\n\nNote\nxrange() is intended to be simple and\n fast. Implementations may impose\n restrictions to achieve this. The C\n implementation of Python restricts all\n arguments to native C longs (“short”\n Python integers), and also requires\n that the number of elements fit in a\n native C long. If a larger range is\n needed, an alternate version can be\n crafted using the itertools module:\n islice(count(start, step), (stop-start+step-1)//step)\n\nlooks like it's a limitation of c python in particular.\n",
"Have you considered just doing this? Or is there some reason you specifically need range()?\nx = 1\nwhile x < 600851475143:\n // some code\n x += 1\n\n",
"It depends on which version of Python you're using. I'm using 2.5.2 and xrange raises an OverflowError exception for large numbers. One solution is to write your own generator.\ndef g(start, stop):\n i = start\n while i < stop:\n yield i\n i += 1\n\nx = 1<<200\nfor i in g(x, x+3):\n print i\n\n",
"Here's an answer using itertools. It's a little contrived, but it works:\nfrom itertools import repeat, count, izip\nfor i,_ in izip(count(1), repeat(1, 600851475143)):\n ...\n\nAnother answer would be to write your own generator:\ndef my_xrange(a, b):\n while a < b:\n yield a\n a += 1\n\nfor i in my_xrange(1, 600851475143):\n ...\n\n"
] |
[
10,
2,
2,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0000841584_python.txt
|
Q:
FastCgi crashes -- Want to catch all exceptions but how?
I have a django app running on apache with fastcgi (uses Flup's WSGIServer).
This gets setup via dispatch.fcgi, concatenated below:
#!/usr/bin/python
import sys, os
sys.path.insert(0, os.path.realpath('/usr/local/django_src/django'))
PROJECT_PATH=os.environ['PROJECT_PATH']
sys.path.insert(0, PROJECT_PATH)
os.chdir(PROJECT_PATH)
os.environ['DJANGO_SETTINGS_MODULE'] = "settings"
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded",daemonize='false',)
The runfastcgi is the one that does the work, eventually running a WSGIServer on a WSGIHandler.
Sometimes an exception happens which crashes fastcgi.
EDIT: I don't know what error crashes fastcgi, or whether fastcgi even crashes. I just know that sometimes the site goes down--consistently down--until I reboot apache. THe only errors that appear in the error.log are the broken pipe and incomplete headers ones, listed below.
Incomplete headers:
note: I've replaced sensitive information or clutter with "..."
[Sat May 09 ...] [error] [client ...] (104)Connection reset by peer: FastCGI: comm with server ".../dispatch.fcgi" aborted: read failed
[Sat May 09 ...] [error] [client ...] FastCGI: incomplete headers (0 bytes) received from server ".../dispatch.fcgi"
[Sat May 09 ...] [error] [client ...] (32)Broken pipe: FastCGI: comm with server ".../dispatch.fcgi" aborted: write failed,
Broken pipe:
note: this happens to be for a trac site not a django app, but it looks the same.
Unhandled exception in thread started by <bound method Connection.run of <trac.web._fcgi.Connection object at 0xb53d7c0c>>
Traceback (most recent call last):
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 654, in run
self.process_input()
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 690, in process_input
self._do_params(rec)
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 789, in _do_params
self._start_request(req)
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 773, in _start_request
req.run()
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 582, in run
self._flush()
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 589, in _flush
self.stdout.close()
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 348, in close
self._conn.writeRecord(rec)
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 705, in writeRecord
rec.write(self._sock)
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 542, in write
self._sendall(sock, header)
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 520, in _sendall
sent = sock.send(data)
socket.error: (32, 'Broken pipe')
I've looked through /var/log/apache2/error.log, but I can't seem to find the cause of the crashing. I sometimes have memory swapping problems, but I think this is different. (Please excuse my ignorance. I am willing to learn how to implement and debug server admin stuff better.)
I'd like to wrap the the runfastcgi with a try/except. What is the best way to handle random exceptions (until I figure out the actual cause(s))?
I believe the WSGIServer handles many requests. If I catch an exception, can I re-call runfastcgi without fear of an infinite loop? Should I return an Error HttpRequest for the offending, exception-calling request? I'm not even sure how to do that.
I've been looking through django/core/servers/fastcgi.py and django/core/handlers/wsgi.py and django/http/init.py
I haven't been able to make progress understanding flup's side of things.
Have ideas or experiences I might learn from?
Thanks!
A:
This is probably a Flup bug. When a flup-based server's client connection is closed before flup is done sending data, it raises a socket.error: (32, 'Broken pipe') exception.
Trying to catch the exception by a try catch around runfastcgi will not work. Simply because the exception is raised by a thread.
OK, I'll explain why the wrapping your own code in a try catch won't work. If you look closely at the exception traceback you'll see that the first statement in the trace is not runfastcgi. That's because the exception is happening in a different thread. If you want to catch the exception you need to wrap any of the statements listed by the trace in a try/catch like this:
# in file /usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 654, in run
try:
self.process_input()
except socket.error:
# ignore or print an error
pass
The point is, you can catch the error by modifing Flup's code. But I don't see any benefit from this. Especial because this exception seems to be harmless and there already is a patch for it.
A:
Broken pipe usually doesn't come deterministically. You get a Broken pipe if a write operation on a pipe or socket fails because the other end has closed the connection. So if your FastCGI gets a Broken pipe, it means that the webserver has closed to connection too early. In some cases this is not an problem, it can be ignored silently.
As a quick hack, try to catch and ignore the socket.error with Broken pipe. You may have to add an except: clause to many more places.
|
FastCgi crashes -- Want to catch all exceptions but how?
|
I have a django app running on apache with fastcgi (uses Flup's WSGIServer).
This gets setup via dispatch.fcgi, concatenated below:
#!/usr/bin/python
import sys, os
sys.path.insert(0, os.path.realpath('/usr/local/django_src/django'))
PROJECT_PATH=os.environ['PROJECT_PATH']
sys.path.insert(0, PROJECT_PATH)
os.chdir(PROJECT_PATH)
os.environ['DJANGO_SETTINGS_MODULE'] = "settings"
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded",daemonize='false',)
The runfastcgi is the one that does the work, eventually running a WSGIServer on a WSGIHandler.
Sometimes an exception happens which crashes fastcgi.
EDIT: I don't know what error crashes fastcgi, or whether fastcgi even crashes. I just know that sometimes the site goes down--consistently down--until I reboot apache. THe only errors that appear in the error.log are the broken pipe and incomplete headers ones, listed below.
Incomplete headers:
note: I've replaced sensitive information or clutter with "..."
[Sat May 09 ...] [error] [client ...] (104)Connection reset by peer: FastCGI: comm with server ".../dispatch.fcgi" aborted: read failed
[Sat May 09 ...] [error] [client ...] FastCGI: incomplete headers (0 bytes) received from server ".../dispatch.fcgi"
[Sat May 09 ...] [error] [client ...] (32)Broken pipe: FastCGI: comm with server ".../dispatch.fcgi" aborted: write failed,
Broken pipe:
note: this happens to be for a trac site not a django app, but it looks the same.
Unhandled exception in thread started by <bound method Connection.run of <trac.web._fcgi.Connection object at 0xb53d7c0c>>
Traceback (most recent call last):
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 654, in run
self.process_input()
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 690, in process_input
self._do_params(rec)
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 789, in _do_params
self._start_request(req)
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 773, in _start_request
req.run()
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 582, in run
self._flush()
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 589, in _flush
self.stdout.close()
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 348, in close
self._conn.writeRecord(rec)
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 705, in writeRecord
rec.write(self._sock)
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 542, in write
self._sendall(sock, header)
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 520, in _sendall
sent = sock.send(data)
socket.error: (32, 'Broken pipe')
I've looked through /var/log/apache2/error.log, but I can't seem to find the cause of the crashing. I sometimes have memory swapping problems, but I think this is different. (Please excuse my ignorance. I am willing to learn how to implement and debug server admin stuff better.)
I'd like to wrap the the runfastcgi with a try/except. What is the best way to handle random exceptions (until I figure out the actual cause(s))?
I believe the WSGIServer handles many requests. If I catch an exception, can I re-call runfastcgi without fear of an infinite loop? Should I return an Error HttpRequest for the offending, exception-calling request? I'm not even sure how to do that.
I've been looking through django/core/servers/fastcgi.py and django/core/handlers/wsgi.py and django/http/init.py
I haven't been able to make progress understanding flup's side of things.
Have ideas or experiences I might learn from?
Thanks!
|
[
"This is probably a Flup bug. When a flup-based server's client connection is closed before flup is done sending data, it raises a socket.error: (32, 'Broken pipe') exception.\nTrying to catch the exception by a try catch around runfastcgi will not work. Simply because the exception is raised by a thread.\nOK, I'll explain why the wrapping your own code in a try catch won't work. If you look closely at the exception traceback you'll see that the first statement in the trace is not runfastcgi. That's because the exception is happening in a different thread. If you want to catch the exception you need to wrap any of the statements listed by the trace in a try/catch like this:\n# in file /usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py\", line 654, in run\ntry:\n self.process_input()\nexcept socket.error:\n # ignore or print an error\n pass\n\nThe point is, you can catch the error by modifing Flup's code. But I don't see any benefit from this. Especial because this exception seems to be harmless and there already is a patch for it.\n",
"Broken pipe usually doesn't come deterministically. You get a Broken pipe if a write operation on a pipe or socket fails because the other end has closed the connection. So if your FastCGI gets a Broken pipe, it means that the webserver has closed to connection too early. In some cases this is not an problem, it can be ignored silently.\nAs a quick hack, try to catch and ignore the socket.error with Broken pipe. You may have to add an except: clause to many more places.\n"
] |
[
3,
0
] |
[] |
[] |
[
"django",
"fastcgi",
"flup",
"python",
"wsgi"
] |
stackoverflow_0000843753_django_fastcgi_flup_python_wsgi.txt
|
Q:
What's the most efficient way to find one of several substrings in Python?
I have a list of possible substrings, e.g. ['cat', 'fish', 'dog']. In practice, the list contains hundreds of entries.
I'm processing a string, and what I'm looking for is to find the index of the first appearance of any of these substrings.
To clarify, for '012cat' the result is 3, and for '0123dog789cat' the result is 4.
I also need to know which substring was found (e.g. its index in the substring list or the text itself), or at least the length of the substring matched.
There are obvious brute-force ways to achieve this, I wondered if there's any elegant Python/regex solution for this.
A:
I would assume a regex is better than checking for each substring individually because conceptually the regular expression is modeled as a DFA, and so as the input is consumed all matches are being tested for at the same time (resulting in one scan of the input string).
So, here is an example:
import re
def work():
to_find = re.compile("cat|fish|dog")
search_str = "blah fish cat dog haha"
match_obj = to_find.search(search_str)
the_index = match_obj.start() # produces 5, the index of fish
which_word_matched = match_obj.group() # "fish"
# Note, if no match, match_obj is None
UPDATE:
Some care should be taken when combining words in to a single pattern of alternative words. The following code builds a regex, but escapes any regex special characters and sorts the words so that longer words get a chance to match before any shorter prefixes of the same word:
def wordlist_to_regex(words):
escaped = map(re.escape, words)
combined = '|'.join(sorted(escaped, key=len, reverse=True))
return re.compile(combined)
>>> r.search('smash atomic particles').span()
(6, 10)
>>> r.search('visit usenet:comp.lang.python today').span()
(13, 29)
>>> r.search('a north\south division').span()
(2, 13)
>>> r.search('012cat').span()
(3, 6)
>>> r.search('0123dog789cat').span()
(4, 7)
END UPDATE
It should be noted that you will want to form the regex (ie - call to re.compile()) as little as possible. The best case would be you know ahead of time what your searches are (or you compute them once/infrequently) and then save the result of re.compile somewhere. My example is just a simple nonsense function so you can see the usage of the regex. There are some more regex docs here:
http://docs.python.org/library/re.html
Hope this helps.
UPDATE: I am unsure about how python implements regular expressions, but to answer Rax's question about whether or not there are limitations of re.compile() (for example, how many words you can try to "|" together to match at once), and the amount of time to run compile: neither of these seem to be an issue. I tried out this code, which is good enough to convince me. (I could have made this better by adding timing and reporting results, as well as throwing the list of words into a set to ensure there are no duplicates... but both of these improvements seem like overkill). This code ran basically instantaneously, and convinced me that I am able to search for 2000 words (of size 10), and that and of them will match appropriately. Here is the code:
import random
import re
import string
import sys
def main(args):
words = []
letters_and_digits = "%s%s" % (string.letters, string.digits)
for i in range(2000):
chars = []
for j in range(10):
chars.append(random.choice(letters_and_digits))
words.append(("%s"*10) % tuple(chars))
search_for = re.compile("|".join(words))
first, middle, last = words[0], words[len(words) / 2], words[-1]
search_string = "%s, %s, %s" % (last, middle, first)
match_obj = search_for.search(search_string)
if match_obj is None:
print "Ahhhg"
return
index = match_obj.start()
which = match_obj.group()
if index != 0:
print "ahhhg"
return
if words[-1] != which:
print "ahhg"
return
print "success!!! Generated 2000 random words, compiled re, and was able to perform matches."
if __name__ == "__main__":
main(sys.argv)
UPDATE: It should be noted that the order of of things ORed together in the regex matters. Have a look at the following test inspired by TZOTZIOY:
>>> search_str = "01catdog"
>>> test1 = re.compile("cat|catdog")
>>> match1 = test1.search(search_str)
>>> match1.group()
'cat'
>>> match1.start()
2
>>> test2 = re.compile("catdog|cat") # reverse order
>>> match2 = test2.search(search_str)
>>> match2.group()
'catdog'
>>> match2.start()
2
This suggests the order matters :-/. I am not sure what this means for Rax's application, but at least the behavior is known.
UPDATE: I posted this questions about the implementation of regular expressions in Python which will hopefully give us some insight into the issues found with this question.
A:
subs = ['cat', 'fish', 'dog']
sentences = ['0123dog789cat']
import re
subs = re.compile("|".join(subs))
def search():
for sentence in sentences:
result = subs.search(sentence)
if result != None:
return (result.group(), result.span()[0])
# ('dog', 4)
A:
I just want to point out the time difference between DisplacedAussie's answer and Tom's answer. Both were fast when used once, so you shouldn't have any noticeable wait for either, but when you time them:
import random
import re
import string
words = []
letters_and_digits = "%s%s" % (string.letters, string.digits)
for i in range(2000):
chars = []
for j in range(10):
chars.append(random.choice(letters_and_digits))
words.append(("%s"*10) % tuple(chars))
search_for = re.compile("|".join(words))
first, middle, last = words[0], words[len(words) / 2], words[-1]
search_string = "%s, %s, %s" % (last, middle, first)
def _search():
match_obj = search_for.search(search_string)
# Note, if no match, match_obj is None
if match_obj is not None:
return (match_obj.start(), match_obj.group())
def _map():
search_for = search_for.pattern.split("|")
found = map(lambda x: (search_string.index(x), x), filter(lambda x: x in search_string, search_for))
if found:
return min(found, key=lambda x: x[0])
if __name__ == '__main__':
from timeit import Timer
t = Timer("_search(search_for, search_string)", "from __main__ import _search, search_for, search_string")
print _search(search_for, search_string)
print t.timeit()
t = Timer("_map(search_for, search_string)", "from __main__ import _map, search_for, search_string")
print _map(search_for, search_string)
print t.timeit()
Outputs:
(0, '841EzpjttV')
14.3660159111
(0, '841EzpjttV')
# I couldn't wait this long
I would go with Tom's answer, for both readability, and speed.
A:
This is a vague, theoretical answer with no code provided, but I hope it can point you in the right direction.
First, you will need a more efficient lookup for your substring list. I would recommend some sort of tree structure. Start with a root, then add an 'a' node if any substrings start with 'a', add a 'b' node if any substrings start with 'b', and so on. For each of these nodes, keep adding subnodes.
For example, if you have a substring with the word "ant", you should have a root node, a child node 'a', a grandchild node 'n', and a great grandchild node 't'.
Nodes should be easy enough to make.
class Node(object):
children = []
def __init__(self, name):
self.name = name
where name is a character.
Iterate through your strings letter by letter. Keep track of which letter you're on. At each letter, try to use the next few letters to traverse the tree. If you're successful, your letter number will be the position of the substring, and your traversal order will indicate the substring that was found.
Clarifying edit: DFAs should be much faster than this method, and so I should endorse Tom's answer. I'm only keeping this answer up in case your substring list changes often, in which case using a tree might be faster.
A:
First of all, I would suggest you to sort the initial list in ascending order. Because scanning for a shorter substring is faster that scanning for a longer substring.
A:
How about this one.
>>> substrings = ['cat', 'fish', 'dog']
>>> _string = '0123dog789cat'
>>> found = map(lambda x: (_string.index(x), x), filter(lambda x: x in _string, substrings))
[(10, 'cat'), (4, 'dog')]
>>> if found:
>>> min(found, key=lambda x: x[0])
(4, 'dog')
Obviously, you could return something other than a tuple.
This works by:
Filtering the list of substrings down to those that are in the string
Building a list of tuples containing the index of the substring, and the substring
If a substring has been found, find the minimum value based on the index
|
What's the most efficient way to find one of several substrings in Python?
|
I have a list of possible substrings, e.g. ['cat', 'fish', 'dog']. In practice, the list contains hundreds of entries.
I'm processing a string, and what I'm looking for is to find the index of the first appearance of any of these substrings.
To clarify, for '012cat' the result is 3, and for '0123dog789cat' the result is 4.
I also need to know which substring was found (e.g. its index in the substring list or the text itself), or at least the length of the substring matched.
There are obvious brute-force ways to achieve this, I wondered if there's any elegant Python/regex solution for this.
|
[
"I would assume a regex is better than checking for each substring individually because conceptually the regular expression is modeled as a DFA, and so as the input is consumed all matches are being tested for at the same time (resulting in one scan of the input string).\nSo, here is an example:\nimport re\n\ndef work():\n to_find = re.compile(\"cat|fish|dog\")\n search_str = \"blah fish cat dog haha\"\n match_obj = to_find.search(search_str)\n the_index = match_obj.start() # produces 5, the index of fish\n which_word_matched = match_obj.group() # \"fish\"\n # Note, if no match, match_obj is None\n\nUPDATE:\nSome care should be taken when combining words in to a single pattern of alternative words. The following code builds a regex, but escapes any regex special characters and sorts the words so that longer words get a chance to match before any shorter prefixes of the same word:\ndef wordlist_to_regex(words):\n escaped = map(re.escape, words)\n combined = '|'.join(sorted(escaped, key=len, reverse=True))\n return re.compile(combined)\n\n>>> r.search('smash atomic particles').span()\n(6, 10)\n>>> r.search('visit usenet:comp.lang.python today').span()\n(13, 29)\n>>> r.search('a north\\south division').span()\n(2, 13)\n>>> r.search('012cat').span()\n(3, 6)\n>>> r.search('0123dog789cat').span()\n(4, 7)\n\nEND UPDATE\nIt should be noted that you will want to form the regex (ie - call to re.compile()) as little as possible. The best case would be you know ahead of time what your searches are (or you compute them once/infrequently) and then save the result of re.compile somewhere. My example is just a simple nonsense function so you can see the usage of the regex. There are some more regex docs here:\nhttp://docs.python.org/library/re.html\nHope this helps.\nUPDATE: I am unsure about how python implements regular expressions, but to answer Rax's question about whether or not there are limitations of re.compile() (for example, how many words you can try to \"|\" together to match at once), and the amount of time to run compile: neither of these seem to be an issue. I tried out this code, which is good enough to convince me. (I could have made this better by adding timing and reporting results, as well as throwing the list of words into a set to ensure there are no duplicates... but both of these improvements seem like overkill). This code ran basically instantaneously, and convinced me that I am able to search for 2000 words (of size 10), and that and of them will match appropriately. Here is the code:\nimport random\nimport re\nimport string\nimport sys\n\ndef main(args):\n words = []\n letters_and_digits = \"%s%s\" % (string.letters, string.digits)\n for i in range(2000):\n chars = []\n for j in range(10):\n chars.append(random.choice(letters_and_digits))\n words.append((\"%s\"*10) % tuple(chars))\n search_for = re.compile(\"|\".join(words))\n first, middle, last = words[0], words[len(words) / 2], words[-1]\n search_string = \"%s, %s, %s\" % (last, middle, first)\n match_obj = search_for.search(search_string)\n if match_obj is None:\n print \"Ahhhg\"\n return\n index = match_obj.start()\n which = match_obj.group()\n if index != 0:\n print \"ahhhg\"\n return\n if words[-1] != which:\n print \"ahhg\"\n return\n\n print \"success!!! Generated 2000 random words, compiled re, and was able to perform matches.\"\n\nif __name__ == \"__main__\":\n main(sys.argv)\n\nUPDATE: It should be noted that the order of of things ORed together in the regex matters. Have a look at the following test inspired by TZOTZIOY:\n>>> search_str = \"01catdog\"\n>>> test1 = re.compile(\"cat|catdog\")\n>>> match1 = test1.search(search_str)\n>>> match1.group()\n'cat'\n>>> match1.start()\n2\n>>> test2 = re.compile(\"catdog|cat\") # reverse order\n>>> match2 = test2.search(search_str)\n>>> match2.group()\n'catdog'\n>>> match2.start()\n2\n\nThis suggests the order matters :-/. I am not sure what this means for Rax's application, but at least the behavior is known.\nUPDATE: I posted this questions about the implementation of regular expressions in Python which will hopefully give us some insight into the issues found with this question.\n",
"subs = ['cat', 'fish', 'dog']\nsentences = ['0123dog789cat']\n\nimport re\n\nsubs = re.compile(\"|\".join(subs))\ndef search():\n for sentence in sentences:\n result = subs.search(sentence)\n if result != None:\n return (result.group(), result.span()[0])\n\n# ('dog', 4)\n\n",
"I just want to point out the time difference between DisplacedAussie's answer and Tom's answer. Both were fast when used once, so you shouldn't have any noticeable wait for either, but when you time them:\nimport random\nimport re\nimport string\n\nwords = []\nletters_and_digits = \"%s%s\" % (string.letters, string.digits)\nfor i in range(2000):\n chars = []\n for j in range(10):\n chars.append(random.choice(letters_and_digits))\n words.append((\"%s\"*10) % tuple(chars))\nsearch_for = re.compile(\"|\".join(words))\nfirst, middle, last = words[0], words[len(words) / 2], words[-1]\nsearch_string = \"%s, %s, %s\" % (last, middle, first)\n\ndef _search():\n match_obj = search_for.search(search_string)\n # Note, if no match, match_obj is None\n if match_obj is not None:\n return (match_obj.start(), match_obj.group())\n\ndef _map():\n search_for = search_for.pattern.split(\"|\")\n found = map(lambda x: (search_string.index(x), x), filter(lambda x: x in search_string, search_for))\n if found:\n return min(found, key=lambda x: x[0])\n\n\nif __name__ == '__main__':\n from timeit import Timer\n\n\n t = Timer(\"_search(search_for, search_string)\", \"from __main__ import _search, search_for, search_string\")\n print _search(search_for, search_string)\n print t.timeit()\n\n t = Timer(\"_map(search_for, search_string)\", \"from __main__ import _map, search_for, search_string\")\n print _map(search_for, search_string)\n print t.timeit()\n\nOutputs:\n(0, '841EzpjttV')\n14.3660159111\n(0, '841EzpjttV')\n# I couldn't wait this long\n\nI would go with Tom's answer, for both readability, and speed.\n",
"This is a vague, theoretical answer with no code provided, but I hope it can point you in the right direction.\nFirst, you will need a more efficient lookup for your substring list. I would recommend some sort of tree structure. Start with a root, then add an 'a' node if any substrings start with 'a', add a 'b' node if any substrings start with 'b', and so on. For each of these nodes, keep adding subnodes.\nFor example, if you have a substring with the word \"ant\", you should have a root node, a child node 'a', a grandchild node 'n', and a great grandchild node 't'.\nNodes should be easy enough to make.\nclass Node(object):\n children = []\n\n def __init__(self, name):\n self.name = name\n\nwhere name is a character.\nIterate through your strings letter by letter. Keep track of which letter you're on. At each letter, try to use the next few letters to traverse the tree. If you're successful, your letter number will be the position of the substring, and your traversal order will indicate the substring that was found.\nClarifying edit: DFAs should be much faster than this method, and so I should endorse Tom's answer. I'm only keeping this answer up in case your substring list changes often, in which case using a tree might be faster.\n",
"First of all, I would suggest you to sort the initial list in ascending order. Because scanning for a shorter substring is faster that scanning for a longer substring.\n",
"How about this one.\n>>> substrings = ['cat', 'fish', 'dog']\n>>> _string = '0123dog789cat'\n>>> found = map(lambda x: (_string.index(x), x), filter(lambda x: x in _string, substrings))\n[(10, 'cat'), (4, 'dog')]\n>>> if found:\n>>> min(found, key=lambda x: x[0])\n(4, 'dog')\n\nObviously, you could return something other than a tuple.\nThis works by: \n\nFiltering the list of substrings down to those that are in the string\nBuilding a list of tuples containing the index of the substring, and the substring\nIf a substring has been found, find the minimum value based on the index\n\n"
] |
[
36,
4,
3,
2,
0,
0
] |
[] |
[] |
[
"python",
"regex",
"string",
"substring"
] |
stackoverflow_0000842856_python_regex_string_substring.txt
|
Q:
Python regex question: stripping multi-line comments but maintaining a line break
I'm parsing a source code file, and I want to remove all line comments (i.e. starting with "//") and multi-line comments (i.e. /..../). However, if the multi-line comment has at least one line-break in it (\n), I want the output to have exactly one line break instead.
For example, the code:
qwe /* 123
456
789 */ asd
should turn exactly into:
qwe
asd
and not "qweasd" or:
qwe
asd
What would be the best way to do so?
Thanks
EDIT:
Example code for testing:
comments_test = "hello // comment\n"+\
"line 2 /* a comment */\n"+\
"line 3 /* a comment*/ /*comment*/\n"+\
"line 4 /* a comment\n"+\
"continuation of a comment*/ line 5\n"+\
"/* comment */line 6\n"+\
"line 7 /*********\n"+\
"********************\n"+\
"**************/\n"+\
"line ?? /*********\n"+\
"********************\n"+\
"********************\n"+\
"********************\n"+\
"********************\n"+\
"**************/\n"+\
"line ??"
Expected results:
hello
line 2
line 3
line 4
line 5
line 6
line 7
line ??
line ??
A:
comment_re = re.compile(
r'(^)?[^\S\n]*/(?:\*(.*?)\*/[^\S\n]*|/[^\n]*)($)?',
re.DOTALL | re.MULTILINE
)
def comment_replacer(match):
start,mid,end = match.group(1,2,3)
if mid is None:
# single line comment
return ''
elif start is not None or end is not None:
# multi line comment at start or end of a line
return ''
elif '\n' in mid:
# multi line comment with line break
return '\n'
else:
# multi line comment without line break
return ' '
def remove_comments(text):
return comment_re.sub(comment_replacer, text)
(^)? will match if the comment starts at the beginning of a line, as long as the MULTILINE-flag is used.
[^\S\n] will match any whitespace character except newline. We don't want to match line breaks if the comment starts on it's own line.
/\*(.*?)\*/ will match a multi-line comment and capture the content. Lazy matching, so we don't match two or more comments. DOTALL-flag makes . match newlines.
//[^\n] will match a single-line comment. Can't use . because of the DOTALL-flag.
($)? will match if the comment stops at the end of a line, as long as the MULTILINE-flag is used.
Examples:
>>> s = ("qwe /* 123\n"
"456\n"
"789 */ asd /* 123 */ zxc\n"
"rty // fgh\n")
>>> print '"' + '"\n"'.join(
... remove_comments(s).splitlines()
... ) + '"'
"qwe"
"asd zxc"
"rty"
>>> comments_test = ("hello // comment\n"
... "line 2 /* a comment */\n"
... "line 3 /* a comment*/ /*comment*/\n"
... "line 4 /* a comment\n"
... "continuation of a comment*/ line 5\n"
... "/* comment */line 6\n"
... "line 7 /*********\n"
... "********************\n"
... "**************/\n"
... "line ?? /*********\n"
... "********************\n"
... "********************\n"
... "********************\n"
... "********************\n"
... "**************/\n")
>>> print '"' + '"\n"'.join(
... remove_comments(comments_test).splitlines()
... ) + '"'
"hello"
"line 2"
"line 3 "
"line 4"
"line 5"
"line 6"
"line 7"
"line ??"
"line ??"
Edits:
Updated to new specification.
Added another example.
A:
The fact that you have to even ask this question, and that the solutions given are, shall we say, less than perfectly readable :-) should be a good indication that REs are not the real answer to this question.
You would be far better, from a readability viewpoint, to actually code this up as a relatively simple parser.
Too often, people try to use REs to be "clever" (I don't mean that in a disparaging way), thinking that a single line is elegant, but all they end up with is an unmaintainable morass of characters. I'd rather have a fully commented 20-line solution that I can understand in an instant.
A:
Is this what you're looking for?
>>> print(s)
qwe /* 123
456
789 */ asd
>>> print(re.sub(r'\s*/\*.*\n.*\*/\s*', '\n', s, flags=re.S))
qwe
asd
This will work only for those comments that are more than one line, but will leave others alone.
A:
How about this:
re.sub(r'\s*/\*(.|\n)*?\*/\s*', '\n', s, re.DOTALL).strip()
It attacks leading whitespace, /*, any text and newline up until the first *\, then any whitespace after that.
Its a little twist on sykora's example but it is also non-greedy on the inside. You also might want to look into the Multiline option.
A:
See can-regular-expressions-be-used-to-match-nested-patterns - if you consider nested comments, regular expressions are not the solution.
|
Python regex question: stripping multi-line comments but maintaining a line break
|
I'm parsing a source code file, and I want to remove all line comments (i.e. starting with "//") and multi-line comments (i.e. /..../). However, if the multi-line comment has at least one line-break in it (\n), I want the output to have exactly one line break instead.
For example, the code:
qwe /* 123
456
789 */ asd
should turn exactly into:
qwe
asd
and not "qweasd" or:
qwe
asd
What would be the best way to do so?
Thanks
EDIT:
Example code for testing:
comments_test = "hello // comment\n"+\
"line 2 /* a comment */\n"+\
"line 3 /* a comment*/ /*comment*/\n"+\
"line 4 /* a comment\n"+\
"continuation of a comment*/ line 5\n"+\
"/* comment */line 6\n"+\
"line 7 /*********\n"+\
"********************\n"+\
"**************/\n"+\
"line ?? /*********\n"+\
"********************\n"+\
"********************\n"+\
"********************\n"+\
"********************\n"+\
"**************/\n"+\
"line ??"
Expected results:
hello
line 2
line 3
line 4
line 5
line 6
line 7
line ??
line ??
|
[
"comment_re = re.compile(\n r'(^)?[^\\S\\n]*/(?:\\*(.*?)\\*/[^\\S\\n]*|/[^\\n]*)($)?',\n re.DOTALL | re.MULTILINE\n)\n\ndef comment_replacer(match):\n start,mid,end = match.group(1,2,3)\n if mid is None:\n # single line comment\n return ''\n elif start is not None or end is not None:\n # multi line comment at start or end of a line\n return ''\n elif '\\n' in mid:\n # multi line comment with line break\n return '\\n'\n else:\n # multi line comment without line break\n return ' '\n\ndef remove_comments(text):\n return comment_re.sub(comment_replacer, text)\n\n\n(^)? will match if the comment starts at the beginning of a line, as long as the MULTILINE-flag is used.\n[^\\S\\n] will match any whitespace character except newline. We don't want to match line breaks if the comment starts on it's own line.\n/\\*(.*?)\\*/ will match a multi-line comment and capture the content. Lazy matching, so we don't match two or more comments. DOTALL-flag makes . match newlines.\n//[^\\n] will match a single-line comment. Can't use . because of the DOTALL-flag.\n($)? will match if the comment stops at the end of a line, as long as the MULTILINE-flag is used.\n\nExamples:\n>>> s = (\"qwe /* 123\\n\"\n \"456\\n\"\n \"789 */ asd /* 123 */ zxc\\n\"\n \"rty // fgh\\n\")\n>>> print '\"' + '\"\\n\"'.join(\n... remove_comments(s).splitlines()\n... ) + '\"'\n\"qwe\"\n\"asd zxc\"\n\"rty\"\n>>> comments_test = (\"hello // comment\\n\"\n... \"line 2 /* a comment */\\n\"\n... \"line 3 /* a comment*/ /*comment*/\\n\"\n... \"line 4 /* a comment\\n\"\n... \"continuation of a comment*/ line 5\\n\"\n... \"/* comment */line 6\\n\"\n... \"line 7 /*********\\n\"\n... \"********************\\n\"\n... \"**************/\\n\"\n... \"line ?? /*********\\n\"\n... \"********************\\n\"\n... \"********************\\n\"\n... \"********************\\n\"\n... \"********************\\n\"\n... \"**************/\\n\")\n>>> print '\"' + '\"\\n\"'.join(\n... remove_comments(comments_test).splitlines()\n... ) + '\"'\n\"hello\"\n\"line 2\"\n\"line 3 \"\n\"line 4\"\n\"line 5\"\n\"line 6\"\n\"line 7\"\n\"line ??\"\n\"line ??\"\n\nEdits:\n\nUpdated to new specification.\nAdded another example.\n\n",
"The fact that you have to even ask this question, and that the solutions given are, shall we say, less than perfectly readable :-) should be a good indication that REs are not the real answer to this question.\nYou would be far better, from a readability viewpoint, to actually code this up as a relatively simple parser.\nToo often, people try to use REs to be \"clever\" (I don't mean that in a disparaging way), thinking that a single line is elegant, but all they end up with is an unmaintainable morass of characters. I'd rather have a fully commented 20-line solution that I can understand in an instant.\n",
"Is this what you're looking for?\n>>> print(s)\nqwe /* 123\n456\n789 */ asd\n>>> print(re.sub(r'\\s*/\\*.*\\n.*\\*/\\s*', '\\n', s, flags=re.S))\nqwe\nasd\n\nThis will work only for those comments that are more than one line, but will leave others alone. \n",
"How about this:\nre.sub(r'\\s*/\\*(.|\\n)*?\\*/\\s*', '\\n', s, re.DOTALL).strip()\n\nIt attacks leading whitespace, /*, any text and newline up until the first *\\, then any whitespace after that.\nIts a little twist on sykora's example but it is also non-greedy on the inside. You also might want to look into the Multiline option.\n",
"See can-regular-expressions-be-used-to-match-nested-patterns - if you consider nested comments, regular expressions are not the solution.\n"
] |
[
12,
5,
1,
1,
0
] |
[] |
[] |
[
"comments",
"parsing",
"python",
"regex"
] |
stackoverflow_0000844681_comments_parsing_python_regex.txt
|
Q:
where to put method that works on a model
I'm working with Django.
I have a model called Agrument. Arguments have sides and owners. I have a function that returns back the side of the most recent argument of a certain user.
like obj.get_current_side(username)
I've added this to the actual Argument model like this
def get_current_side(self, user):
return self.argument_set.latest('pub_date').side
I am starting to think this doesn't make sense because there may not be an instance of an Argument. Is this a place I would use a class method? I thought about making a util class, but I'm thinking that it makes sense to be associated with the Argument class.
A:
It would make more sense to have instance methods on the User model:
def get_current_side(self):
try:
return self.arguments.latest('pub_date').side
except User.DoesNotExist, e:
return None
You can do this by extending the User model as explained here:
Extending the Django User model with inheritance
Edit: I'm not exactly sure which exception gets thrown.
A:
This should be a method on a custom model manager:
# in models.py
class ArgumentManager(models.manager.Manager):
def get_current_side(self, user):
try:
return self.filter(user=user).latest('pub_date').side
except Argument.DoesNotExist:
return None
class Argument(models.Model):
# fields etc...
objects = ArgumentManager()
# Calling:
side = Argument.objects.get_current_side(user)
Alternaticely you can extend contrib.auth.user and add get_current_size() on it. But I wouldn't mess with it until I'm very confident with Django.
BTW: Most of the code in this page is wrong; for example user variable is not used at all on the OP's snipplet.
A:
I think what you are looking for are model managers.
Django docs on managers with managers you can add a function to the model class instead of a model instance.
|
where to put method that works on a model
|
I'm working with Django.
I have a model called Agrument. Arguments have sides and owners. I have a function that returns back the side of the most recent argument of a certain user.
like obj.get_current_side(username)
I've added this to the actual Argument model like this
def get_current_side(self, user):
return self.argument_set.latest('pub_date').side
I am starting to think this doesn't make sense because there may not be an instance of an Argument. Is this a place I would use a class method? I thought about making a util class, but I'm thinking that it makes sense to be associated with the Argument class.
|
[
"It would make more sense to have instance methods on the User model:\ndef get_current_side(self):\n try:\n return self.arguments.latest('pub_date').side\n except User.DoesNotExist, e:\n return None\n\nYou can do this by extending the User model as explained here:\n\nExtending the Django User model with inheritance\n\nEdit: I'm not exactly sure which exception gets thrown.\n",
"This should be a method on a custom model manager:\n# in models.py\nclass ArgumentManager(models.manager.Manager):\n def get_current_side(self, user):\n try:\n return self.filter(user=user).latest('pub_date').side\n except Argument.DoesNotExist:\n return None\n\nclass Argument(models.Model):\n # fields etc...\n\n objects = ArgumentManager()\n\n\n# Calling:\n\nside = Argument.objects.get_current_side(user)\n\nAlternaticely you can extend contrib.auth.user and add get_current_size() on it. But I wouldn't mess with it until I'm very confident with Django.\nBTW: Most of the code in this page is wrong; for example user variable is not used at all on the OP's snipplet.\n",
"I think what you are looking for are model managers. \nDjango docs on managers with managers you can add a function to the model class instead of a model instance. \n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0000844142_django_python.txt
|
Q:
"x Days ago' template filter in Django?
I'm looking for a filter that turns a datetime instance into 'x Days' or 'x years y months' format (as on SO). Suggestions? Am I overlooking something very obvious?
A:
Have a look at the timesince template filter. It's builtin.
The following returns a humanized diff between now and comment_date (e.g. '8 hours'):
{{ comment_date|timesince }}
The following returns a humanized diff between question_date and comment_date:
{{ comment_date|timesince:question_date }}
|
"x Days ago' template filter in Django?
|
I'm looking for a filter that turns a datetime instance into 'x Days' or 'x years y months' format (as on SO). Suggestions? Am I overlooking something very obvious?
|
[
"Have a look at the timesince template filter. It's builtin.\nThe following returns a humanized diff between now and comment_date (e.g. '8 hours'):\n{{ comment_date|timesince }}\n\nThe following returns a humanized diff between question_date and comment_date:\n{{ comment_date|timesince:question_date }}\n\n"
] |
[
34
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0000845009_django_python.txt
|
Q:
VIM: Use python 2.5 with vim 7.2
How can use Python2.5 with to write scripts in vim? I'm using vim 7.2 and have Python 2.5. Vim 7.2 seem to be linked with Python 2.4
Do I have to compile from source?
A:
Here is a link to VIM 7.2 builds with Python 2.5/2.6 support.
|
VIM: Use python 2.5 with vim 7.2
|
How can use Python2.5 with to write scripts in vim? I'm using vim 7.2 and have Python 2.5. Vim 7.2 seem to be linked with Python 2.4
Do I have to compile from source?
|
[
"Here is a link to VIM 7.2 builds with Python 2.5/2.6 support.\n"
] |
[
3
] |
[] |
[] |
[
"python",
"vim"
] |
stackoverflow_0000845068_python_vim.txt
|
Q:
Converting a java System.currentTimeMillis() to date in python
I have timestamp in milliseconds from 1970. I would like to convert it to a human readable date in python. I don't might losing some precision if it comes to that.
How should I do that ?
The following give ValueError: timestamp out of range for platform time_t on Linux 32bit
#!/usr/bin/env python
from datetime import date
print date.fromtimestamp(1241711346274)
Thank you,
Maxim.
A:
Python expects seconds, so divide it by 1000.0 first:
>>> print date.fromtimestamp(1241711346274/1000.0)
2009-05-07
A:
You can preserve the precision, because in Python the timestamp is a float. Here's an example:
import datetime
java_timestamp = 1241959948938
seconds = java_timestamp / 1000
sub_seconds = (java_timestamp % 1000.0) / 1000.0
date = datetime.datetime.fromtimestamp(seconds + sub_seconds)
You can obviously make it more compact than that, but the above is suitable for typing, a line at a time, in the REPL, so see what it does. For example:
Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53)
[GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> java_timestamp = 1241959948938
>>> import datetime
>>> seconds = java_timestamp / 1000
>>> seconds
1241959948L
>>> sub_seconds = (java_timestamp % 1000.0) / 1000.0
>>> sub_seconds
0.93799999999999994
>>> date = datetime.datetime.fromtimestamp(seconds + sub_seconds)
>>> date
datetime.datetime(2009, 5, 10, 8, 52, 28, 938000)
>>>
A:
It's in milliseconds divided the timestamp by 1000 to become in seconds.
date.fromtimestamp(1241711346274/1000)
|
Converting a java System.currentTimeMillis() to date in python
|
I have timestamp in milliseconds from 1970. I would like to convert it to a human readable date in python. I don't might losing some precision if it comes to that.
How should I do that ?
The following give ValueError: timestamp out of range for platform time_t on Linux 32bit
#!/usr/bin/env python
from datetime import date
print date.fromtimestamp(1241711346274)
Thank you,
Maxim.
|
[
"Python expects seconds, so divide it by 1000.0 first:\n>>> print date.fromtimestamp(1241711346274/1000.0)\n2009-05-07\n\n",
"You can preserve the precision, because in Python the timestamp is a float. Here's an example:\nimport datetime\n\njava_timestamp = 1241959948938\nseconds = java_timestamp / 1000\nsub_seconds = (java_timestamp % 1000.0) / 1000.0\ndate = datetime.datetime.fromtimestamp(seconds + sub_seconds)\n\nYou can obviously make it more compact than that, but the above is suitable for typing, a line at a time, in the REPL, so see what it does. For example:\nPython 2.5.2 (r252:60911, Feb 22 2008, 07:57:53) \n[GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> java_timestamp = 1241959948938\n>>> import datetime\n>>> seconds = java_timestamp / 1000\n>>> seconds\n1241959948L\n>>> sub_seconds = (java_timestamp % 1000.0) / 1000.0\n>>> sub_seconds\n0.93799999999999994\n>>> date = datetime.datetime.fromtimestamp(seconds + sub_seconds)\n>>> date\ndatetime.datetime(2009, 5, 10, 8, 52, 28, 938000)\n>>> \n\n",
"It's in milliseconds divided the timestamp by 1000 to become in seconds.\ndate.fromtimestamp(1241711346274/1000)\n\n"
] |
[
17,
4,
1
] |
[] |
[] |
[
"date",
"formatting",
"java",
"python",
"timestamp"
] |
stackoverflow_0000845153_date_formatting_java_python_timestamp.txt
|
Q:
Canonical/Idiomatic "do what I mean" when passed a string that could a filename, URL, or the actual data to work on
It's not uncommon to see Python libraries that expose a universal "opener" function, that accept as their primary argument a string that could either represent a local filename (which it will open and operate on), a URL(which it will download and operate on), or data(which it will operate on).
Here's an example from Feedparser.
My question is: is there a standard "right" way to do that? Or, A module that implements that bit of functionality (maybe as a decorator)?
A:
Ultimately, any module implementing this behaviour is going to parse the string. And act according to the result. In feedparser for example they are parsing the url:
if urlparse.urlparse(url_file_stream_or_string)[0] in ('http', 'https', 'ftp'):
# do something with the url
else:
# This is a file path
return open(url_file_stream_or_string)
Here is a nice decorator that will do this for you:
import urlparse, urllib
def opener(fun):
def wrapper(url):
if urlparse.urlparse(url)[0] in ('http', 'https', 'ftp'):
return fun(urllib.urlopen(url))
return fun(open(url))
return wrapper
@opener
def read(stream):
return stream.read()
read('myfile')
read('http://www.wikipedia.org')
|
Canonical/Idiomatic "do what I mean" when passed a string that could a filename, URL, or the actual data to work on
|
It's not uncommon to see Python libraries that expose a universal "opener" function, that accept as their primary argument a string that could either represent a local filename (which it will open and operate on), a URL(which it will download and operate on), or data(which it will operate on).
Here's an example from Feedparser.
My question is: is there a standard "right" way to do that? Or, A module that implements that bit of functionality (maybe as a decorator)?
|
[
"Ultimately, any module implementing this behaviour is going to parse the string. And act according to the result. In feedparser for example they are parsing the url:\nif urlparse.urlparse(url_file_stream_or_string)[0] in ('http', 'https', 'ftp'):\n # do something with the url\nelse:\n # This is a file path\n return open(url_file_stream_or_string)\n\nHere is a nice decorator that will do this for you:\nimport urlparse, urllib\n\ndef opener(fun):\n def wrapper(url):\n if urlparse.urlparse(url)[0] in ('http', 'https', 'ftp'):\n return fun(urllib.urlopen(url))\n return fun(open(url))\n return wrapper\n\n@opener\ndef read(stream):\n return stream.read()\n\nread('myfile')\nread('http://www.wikipedia.org')\n\n"
] |
[
7
] |
[] |
[] |
[
"python"
] |
stackoverflow_0000845408_python.txt
|
Q:
How to print the comparison of two multiline strings in unified diff format?
Do you know any library that will help doing that?
I would write a function that prints the differences between two multiline strings in the unified diff format. Something like that:
def print_differences(string1, string2):
"""
Prints the comparison of string1 to string2 as unified diff format.
"""
???
An usage example is the following:
string1="""
Usage: trash-empty [days]
Purge trashed files.
Options:
--version show program's version number and exit
-h, --help show this help message and exit
"""
string2="""
Usage: trash-empty [days]
Empty the trash can.
Options:
--version show program's version number and exit
-h, --help show this help message and exit
Report bugs to http://code.google.com/p/trash-cli/issues
"""
print_differences(string1, string2)
This should print something like that:
--- string1
+++ string2
@@ -1,6 +1,6 @@
Usage: trash-empty [days]
-Purge trashed files.
+Empty the trash can.
Options:
--version show program's version number and exit
A:
This is how I solved:
def _unidiff_output(expected, actual):
"""
Helper function. Returns a string containing the unified diff of two multiline strings.
"""
import difflib
expected=expected.splitlines(1)
actual=actual.splitlines(1)
diff=difflib.unified_diff(expected, actual)
return ''.join(diff)
A:
Did you have a look at the built-in python module difflib?
Have a look that this example
|
How to print the comparison of two multiline strings in unified diff format?
|
Do you know any library that will help doing that?
I would write a function that prints the differences between two multiline strings in the unified diff format. Something like that:
def print_differences(string1, string2):
"""
Prints the comparison of string1 to string2 as unified diff format.
"""
???
An usage example is the following:
string1="""
Usage: trash-empty [days]
Purge trashed files.
Options:
--version show program's version number and exit
-h, --help show this help message and exit
"""
string2="""
Usage: trash-empty [days]
Empty the trash can.
Options:
--version show program's version number and exit
-h, --help show this help message and exit
Report bugs to http://code.google.com/p/trash-cli/issues
"""
print_differences(string1, string2)
This should print something like that:
--- string1
+++ string2
@@ -1,6 +1,6 @@
Usage: trash-empty [days]
-Purge trashed files.
+Empty the trash can.
Options:
--version show program's version number and exit
|
[
"This is how I solved:\ndef _unidiff_output(expected, actual):\n \"\"\"\n Helper function. Returns a string containing the unified diff of two multiline strings.\n \"\"\"\n\n import difflib\n expected=expected.splitlines(1)\n actual=actual.splitlines(1)\n\n diff=difflib.unified_diff(expected, actual)\n\n return ''.join(diff)\n\n",
"Did you have a look at the built-in python module difflib?\nHave a look that this example\n"
] |
[
29,
25
] |
[] |
[] |
[
"diff",
"python",
"unified_diff"
] |
stackoverflow_0000845276_diff_python_unified_diff.txt
|
Q:
using Python objects in C#
Is there an easy way to call Python objects from C#, that is without any COM mess?
A:
Yes, by hosting IronPython.
A:
In the current released version of C# there is no great way to achieve this without using some sort of bridge layer. You can host it IronPython to a degree but its hard to take advantage of the dynamic features of IronPython since C# is a very statically typed language
If you're speaking of IronPython though, C# 4.0 will be able to interop with that seemlessly. C# 4.0 is introducing a new feature calldh dynamic which allows it to work with any language running on the DLR.
dynamic d = GetSomePythonObject();
d.SomeMethod();
A:
I know of 3 ways:
1) Use Iron Python, and your Python projects can interact freely with projects written in C#.
2) Expose your Python functions to COM. You would do this if you need to use Python libraries that you don't want to or can't convert to Iron Python (EG, if you just have a DLL.)
The "COM mess" is not really so bad, if your Python code and C# code are running on the same machine.
This code from this tutorial shows that it's not excessively ugly:
class PythonUtilities:
_public_methods_ = [ 'SplitString' ]
_reg_progid_ = "PythonDemos.Utilities"
# NEVER copy the following ID
# Use "print pythoncom.CreateGuid()" to make a new one.
_reg_clsid_ = "{41E24E95-D45A-11D2-852C-204C4F4F5020}"
def SplitString(self, val, item=None):
import string
if item != None: item = str(item)
return string.split(str(val), item)
# Add code so that when this script is run by
# Python.exe, it self-registers.
if __name__=='__main__':
print "Registering COM server..."
import win32com.server.register
win32com.server.register.UseCommandLine(PythonUtilities)
3) Have C# and Python communicate through sockets. You would do this if you have code you can't convert to Iron Python and you need to access it remotely.
This requires the most work because you need to marshall and unmarshall the arguments and return values from bytes or strings, but it is what one team of mine did when we needed to make C# talk to a remote Python process.
|
using Python objects in C#
|
Is there an easy way to call Python objects from C#, that is without any COM mess?
|
[
"Yes, by hosting IronPython.\n",
"In the current released version of C# there is no great way to achieve this without using some sort of bridge layer. You can host it IronPython to a degree but its hard to take advantage of the dynamic features of IronPython since C# is a very statically typed language\nIf you're speaking of IronPython though, C# 4.0 will be able to interop with that seemlessly. C# 4.0 is introducing a new feature calldh dynamic which allows it to work with any language running on the DLR. \ndynamic d = GetSomePythonObject();\nd.SomeMethod();\n\n",
"I know of 3 ways:\n1) Use Iron Python, and your Python projects can interact freely with projects written in C#.\n2) Expose your Python functions to COM. You would do this if you need to use Python libraries that you don't want to or can't convert to Iron Python (EG, if you just have a DLL.) \nThe \"COM mess\" is not really so bad, if your Python code and C# code are running on the same machine.\nThis code from this tutorial shows that it's not excessively ugly: \nclass PythonUtilities:\n _public_methods_ = [ 'SplitString' ]\n _reg_progid_ = \"PythonDemos.Utilities\"\n # NEVER copy the following ID\n # Use \"print pythoncom.CreateGuid()\" to make a new one.\n _reg_clsid_ = \"{41E24E95-D45A-11D2-852C-204C4F4F5020}\"\n\n def SplitString(self, val, item=None):\n import string\n if item != None: item = str(item)\n return string.split(str(val), item)\n\n# Add code so that when this script is run by\n# Python.exe, it self-registers.\nif __name__=='__main__':\n print \"Registering COM server...\"\n import win32com.server.register\n win32com.server.register.UseCommandLine(PythonUtilities)\n\n3) Have C# and Python communicate through sockets. You would do this if you have code you can't convert to Iron Python and you need to access it remotely.\nThis requires the most work because you need to marshall and unmarshall the arguments and return values from bytes or strings, but it is what one team of mine did when we needed to make C# talk to a remote Python process.\n"
] |
[
8,
6,
5
] |
[] |
[] |
[
"c#",
"ironpython",
"python"
] |
stackoverflow_0000845502_c#_ironpython_python.txt
|
Q:
How do I choose which Python installation to run in a PyObjC program?
I use Python 2.6 more than I use Leopard's default python installation, so I have it set as my main Python installation. But I'd rather use the default Python for a PyObjC program I'm working on. Is there any way to specify to only use it instead of Python 2.6?
A:
Finally figured this one out myself. The key to this is to make the final executable link with /System/Library/Frameworks/Python.framework instead of /Library/Frameworks/Python.framework.
A:
Try specifying the full path to the Python interpreter in the command line, something like:
/foo/bar/python2.6 script.py
/baz/python objcscript.py
You can also add a shebang to the beginning of your script (first line):
#! /foo/bar/python2.6 script.py
If you have the environment variable PYTHONPATH set, you might have to unset it or change it.
A:
AFAIR this helped me (in main.m):
NSArray *pythonPathArray = [NSArray arrayWithObjects: resourcePath, [resourcePath stringByAppendingPathComponent:@"PyObjC"], @"/System/Library/Frameworks/Python.framework/Versions/Current/Extras/lib/python/", @"/Library/Python/2.5/site-packages", nil];
Also, make sure that this point to the Python installation you want to use (main.m):
Py_SetProgramName("/usr/bin/python");
|
How do I choose which Python installation to run in a PyObjC program?
|
I use Python 2.6 more than I use Leopard's default python installation, so I have it set as my main Python installation. But I'd rather use the default Python for a PyObjC program I'm working on. Is there any way to specify to only use it instead of Python 2.6?
|
[
"Finally figured this one out myself. The key to this is to make the final executable link with /System/Library/Frameworks/Python.framework instead of /Library/Frameworks/Python.framework.\n",
"Try specifying the full path to the Python interpreter in the command line, something like:\n/foo/bar/python2.6 script.py\n/baz/python objcscript.py\n\nYou can also add a shebang to the beginning of your script (first line):\n#! /foo/bar/python2.6 script.py\n\nIf you have the environment variable PYTHONPATH set, you might have to unset it or change it.\n",
"AFAIR this helped me (in main.m):\n NSArray *pythonPathArray = [NSArray arrayWithObjects: resourcePath, [resourcePath stringByAppendingPathComponent:@\"PyObjC\"], @\"/System/Library/Frameworks/Python.framework/Versions/Current/Extras/lib/python/\", @\"/Library/Python/2.5/site-packages\", nil];\n\nAlso, make sure that this point to the Python installation you want to use (main.m):\n Py_SetProgramName(\"/usr/bin/python\");\n\n"
] |
[
3,
2,
2
] |
[] |
[] |
[
"macos",
"objective_c",
"pyobjc",
"python"
] |
stackoverflow_0000843698_macos_objective_c_pyobjc_python.txt
|
Q:
Get the amplitude at a given time within a sound file?
I'm working on a project where I need to know the amplitude of sound coming in from a microphone on a computer.
I'm currently using Python with the Snack Sound Toolkit and I can record audio coming in from the microphone, but I need to know how loud that audio is. I could save the recording to a file and use another toolkit to read in the amplitude at given points in time from the audio file, or try and get the amplitude while the audio is coming in (which could be more error prone).
Are there any libraries or sample code that can help me out with this? I've been looking and so far the Snack Sound Toolkit seems to be my best hope, yet there doesn't seem to be a way to get direct access to amplitude.
A:
Looking at the Snack Sound Toolkit examples, there seems to be a dbPowerSpectrum function.
From the reference:
dBPowerSpectrum ( )
Computes the log FFT power spectrum of the sound (at the sample number given in the start option) and returns a list of dB values. See the section item for a description of the rest of the options. Optionally an ending point can be given, using the end option. In this case the result is the average of consecutive FFTs in the specified range. Their default spacing is taken from the fftlength but this can be changed using the skip option, which tells how many points to move the FFT window each step. Options:
EDIT: I am assuming when you say amplitude, you mean how "loud" the sound appears to a human, and not the time domain voltage(Which would probably be 0 throughout the entire length since the integral of sine waves is going to be 0. eg: 10 * sin(t) is louder than 5 * sin(t), but their average value over time is 0. (You do not want to send non-AC voltages to a speaker anyways)).
To get how loud the sound is, you will need to determine the amplitudes of each frequency component. This is done with a Fourier Transform (FFT), which breaks down the sound into it's frequency components. The dbPowerSpectrum function seems to give you a list of the magnitudes (forgive me if this differs from the exact definition of a power spectrum) of each frequency. To get the total volume, you can just sum the entire list (Which will be close, xept it still might be different from percieved loudness since the human ear has a frequency response itself).
A:
I disagree completely with this "answer" from CookieOfFortune.
granted, the question is poorly phrased... but this answer is making things much more complex than necessary. I am assuming that by 'amplitude' you mean perceived loudness. as technically each sample in the (PCM) audio stream represents an amplitude of the signal at a given time-slice. to get a loudness representation try a simple RMS calculation:
RMS
|K<
A:
I'm not sure if this will help, but
skimpygimpy
provides facilities for parsing WAVE files into python
sequences and back -- you could potentially use this
to examine the wave form samples directly and do
what you like. You will have to read some source,
these subcomponents are not documented.
|
Get the amplitude at a given time within a sound file?
|
I'm working on a project where I need to know the amplitude of sound coming in from a microphone on a computer.
I'm currently using Python with the Snack Sound Toolkit and I can record audio coming in from the microphone, but I need to know how loud that audio is. I could save the recording to a file and use another toolkit to read in the amplitude at given points in time from the audio file, or try and get the amplitude while the audio is coming in (which could be more error prone).
Are there any libraries or sample code that can help me out with this? I've been looking and so far the Snack Sound Toolkit seems to be my best hope, yet there doesn't seem to be a way to get direct access to amplitude.
|
[
"Looking at the Snack Sound Toolkit examples, there seems to be a dbPowerSpectrum function.\nFrom the reference:\n\ndBPowerSpectrum ( )\nComputes the log FFT power spectrum of the sound (at the sample number given in the start option) and returns a list of dB values. See the section item for a description of the rest of the options. Optionally an ending point can be given, using the end option. In this case the result is the average of consecutive FFTs in the specified range. Their default spacing is taken from the fftlength but this can be changed using the skip option, which tells how many points to move the FFT window each step. Options:\n\nEDIT: I am assuming when you say amplitude, you mean how \"loud\" the sound appears to a human, and not the time domain voltage(Which would probably be 0 throughout the entire length since the integral of sine waves is going to be 0. eg: 10 * sin(t) is louder than 5 * sin(t), but their average value over time is 0. (You do not want to send non-AC voltages to a speaker anyways)).\nTo get how loud the sound is, you will need to determine the amplitudes of each frequency component. This is done with a Fourier Transform (FFT), which breaks down the sound into it's frequency components. The dbPowerSpectrum function seems to give you a list of the magnitudes (forgive me if this differs from the exact definition of a power spectrum) of each frequency. To get the total volume, you can just sum the entire list (Which will be close, xept it still might be different from percieved loudness since the human ear has a frequency response itself).\n",
"I disagree completely with this \"answer\" from CookieOfFortune.\ngranted, the question is poorly phrased... but this answer is making things much more complex than necessary. I am assuming that by 'amplitude' you mean perceived loudness. as technically each sample in the (PCM) audio stream represents an amplitude of the signal at a given time-slice. to get a loudness representation try a simple RMS calculation:\nRMS\n|K<\n",
"I'm not sure if this will help, but \nskimpygimpy\nprovides facilities for parsing WAVE files into python\nsequences and back -- you could potentially use this\nto examine the wave form samples directly and do\nwhat you like. You will have to read some source,\nthese subcomponents are not documented.\n"
] |
[
3,
1,
0
] |
[] |
[] |
[
"amplitude",
"audio",
"input",
"microphone",
"python"
] |
stackoverflow_0000742546_amplitude_audio_input_microphone_python.txt
|
Q:
Unable to make an iterable decimal function in Python
I want to calculate the sum of
1/1 + 1/2 + 1/3 + ... + 1/30
I run the code unsuccessfully
import decimal
import math
var=decimal.Decimal(1/i)
for i in range(1,31):
print(sum(var))
I get the error
'Decimal' object is not iterable
How can you make the iterable function in Python?
A:
What you want is this:
print(sum(decimal.Decimal(1) / i for i in range(1, 31)))
The reason your code doesn't work, is that you try to iterate over one Decimal instance (through the use of sum). Furthermore, your definition of var is invalid. Your intention was probably something like this:
var = lambda i: decimal.Decimal(str(1.0 / i))
(Note the use of str, Decimal does not permit a floating point argument). But even then your loop would not work, because the use of sum inside the loop is inherently flawed. sum should be used after the loop has created all fractions that you want to sum. So that would be either of:
print(sum(var(i) for i in range(1,31)))
print(sum(map(var, range(1, 31))))
For completeness, yet another way to do this is the following:
one = decimal.Decimal(1)
unitFractions = (one / i for i in itertools.count(1))
print(sum(itertools.islice(unitFractions, 30)))
However, as mentioned by gs, the fractions provides an alternative method that yields a fractional answer:
>>> unitFractions = (fractions.Fraction(1, i) for i in itertools.count(1))
>>> print(sum(itertools.islice(unitFractions, 30)))
9304682830147/2329089562800
A:
You write:
var=decimal.Decimal(1/i)
which is weird since 'i' is not defined at that point. How about:
one = decimal.Decimal( "1" )
total = decimal.Decimal( "0" )
for i in range( 1, 31 ):
total += one / decimal.Decimal( "%d" % i )
A:
Your mistake is, that decimal.Decimal(4) isn't a function, but an object.
BTW: It looks like the Fractions (Python 2.6) module is what you really need.
|
Unable to make an iterable decimal function in Python
|
I want to calculate the sum of
1/1 + 1/2 + 1/3 + ... + 1/30
I run the code unsuccessfully
import decimal
import math
var=decimal.Decimal(1/i)
for i in range(1,31):
print(sum(var))
I get the error
'Decimal' object is not iterable
How can you make the iterable function in Python?
|
[
"What you want is this:\nprint(sum(decimal.Decimal(1) / i for i in range(1, 31)))\n\nThe reason your code doesn't work, is that you try to iterate over one Decimal instance (through the use of sum). Furthermore, your definition of var is invalid. Your intention was probably something like this:\nvar = lambda i: decimal.Decimal(str(1.0 / i))\n\n(Note the use of str, Decimal does not permit a floating point argument). But even then your loop would not work, because the use of sum inside the loop is inherently flawed. sum should be used after the loop has created all fractions that you want to sum. So that would be either of:\nprint(sum(var(i) for i in range(1,31)))\nprint(sum(map(var, range(1, 31))))\n\nFor completeness, yet another way to do this is the following:\none = decimal.Decimal(1)\nunitFractions = (one / i for i in itertools.count(1))\nprint(sum(itertools.islice(unitFractions, 30)))\n\nHowever, as mentioned by gs, the fractions provides an alternative method that yields a fractional answer:\n>>> unitFractions = (fractions.Fraction(1, i) for i in itertools.count(1))\n>>> print(sum(itertools.islice(unitFractions, 30)))\n9304682830147/2329089562800\n\n",
"You write:\nvar=decimal.Decimal(1/i)\n\nwhich is weird since 'i' is not defined at that point. How about:\none = decimal.Decimal( \"1\" )\ntotal = decimal.Decimal( \"0\" )\nfor i in range( 1, 31 ):\n total += one / decimal.Decimal( \"%d\" % i )\n\n",
"Your mistake is, that decimal.Decimal(4) isn't a function, but an object.\n\nBTW: It looks like the Fractions (Python 2.6) module is what you really need.\n"
] |
[
11,
3,
2
] |
[] |
[] |
[
"iteration",
"python",
"sum"
] |
stackoverflow_0000845787_iteration_python_sum.txt
|
Q:
Defining dynamic functions to a string
I have a small python script which i use everyday......it basically reads a file and for each line i basically apply different string functions like strip(), replace() etc....im constanstly editing the file and commenting to change the functions. Depending on the file I'm dealing with, I use different functions. For example I got a file where for each line, i need to use line.replace(' ','') and line.strip()...
What's the best way to make all of these as part of my script? So I can just say assign numbers to each functions and just say apply function 1 and 4 for each line.
A:
It is possible to map string operations to numbers:
>>> import string
>>> ops = {1:string.split, 2:string.replace}
>>> my = "a,b,c"
>>> ops[1](",", my)
[',']
>>> ops[1](my, ",")
['a', 'b', 'c']
>>> ops[2](my, ",", "-")
'a-b-c'
>>>
But maybe string descriptions of the operations will be more readable.
>>> ops2={"split":string.split, "replace":string.replace}
>>> ops2["split"](my, ",")
['a', 'b', 'c']
>>>
Note:
Instead of using the string module, you can use the str type for the same effect.
>>> ops={1:str.split, 2:str.replace}
A:
If you insist on numbers, you can't do much better than a dict (as gimel suggests) or list of functions (with indices zero and up). With names, though, you don't necessarily need an auxiliary data structure (such as gimel's suggested dict), since you can simply use getattr to retrieve the method to call from the object itself or its type. E.g.:
def all_lines(somefile, methods):
"""Apply a sequence of methods to all lines of some file and yield the results.
Args:
somefile: an open file or other iterable yielding lines
methods: a string that's a whitespace-separated sequence of method names.
(note that the methods must be callable without arguments beyond the
str to which they're being applied)
"""
tobecalled = [getattr(str, name) for name in methods.split()]
for line in somefile:
for tocall in tobecalled: line = tocall(line)
yield line
A:
First of all, many string functions – including strip and replace – are deprecated. The following answer uses string methods instead. (Instead of string.strip(" Hello "), I use the equivalent of " Hello ".strip().)
Here's some code that will simplify the job for you. The following code assumes that whatever methods you call on your string, that method will return another string.
class O(object):
c = str.capitalize
r = str.replace
s = str.strip
def process_line(line, *ops):
i = iter(ops)
while True:
try:
op = i.next()
args = i.next()
except StopIteration:
break
line = op(line, *args)
return line
The O class exists so that your highly abbreviated method names don't pollute your namespace. When you want to add more string methods, you add them to O in the same format as those given.
The process_line function is where all the interesting things happen. First, here is a description of the argument format:
The first argument is the string to be processed.
The remaining arguments must be given in pairs.
The first argument of the pair is a string method. Use the shortened method names here.
The second argument of the pair is a list representing the arguments to that particular string method.
The process_line function returns the string that emerges after all these operations have performed.
Here is some example code showing how you would use the above code in your own scripts. I've separated the arguments of process_line across multiple lines to show the grouping of the arguments. Of course, if you're just hacking away and using this code in day-to-day scripts, you can compress all the arguments onto one line; this actually makes it a little easier to read.
f = open("parrot_sketch.txt")
for line in f:
p = process_line(
line,
O.r, ["He's resting...", "This is an ex-parrot!"],
O.c, [],
O.s, []
)
print p
Of course, if you very specifically wanted to use numerals, you could name your functions O.f1, O.f2, O.f3… but I'm assuming that wasn't the spirit of your question.
A:
To map names (or numbers) to different string operations, I'd do something like
OPERATIONS = dict(
strip = str.strip,
lower = str.lower,
removespaces = lambda s: s.replace(' ', ''),
maketitle = lamdba s: s.title().center(80, '-'),
# etc
)
def process(myfile, ops):
for line in myfile:
for op in ops:
line = OPERATIONS[op](line)
yield line
which you use like this
for line in process(afile, ['strip', 'removespaces']):
...
|
Defining dynamic functions to a string
|
I have a small python script which i use everyday......it basically reads a file and for each line i basically apply different string functions like strip(), replace() etc....im constanstly editing the file and commenting to change the functions. Depending on the file I'm dealing with, I use different functions. For example I got a file where for each line, i need to use line.replace(' ','') and line.strip()...
What's the best way to make all of these as part of my script? So I can just say assign numbers to each functions and just say apply function 1 and 4 for each line.
|
[
"It is possible to map string operations to numbers:\n>>> import string\n>>> ops = {1:string.split, 2:string.replace}\n>>> my = \"a,b,c\"\n>>> ops[1](\",\", my)\n[',']\n>>> ops[1](my, \",\")\n['a', 'b', 'c']\n>>> ops[2](my, \",\", \"-\")\n'a-b-c'\n>>> \n\nBut maybe string descriptions of the operations will be more readable.\n>>> ops2={\"split\":string.split, \"replace\":string.replace}\n>>> ops2[\"split\"](my, \",\")\n['a', 'b', 'c']\n>>> \n\nNote:\nInstead of using the string module, you can use the str type for the same effect.\n>>> ops={1:str.split, 2:str.replace}\n\n",
"If you insist on numbers, you can't do much better than a dict (as gimel suggests) or list of functions (with indices zero and up). With names, though, you don't necessarily need an auxiliary data structure (such as gimel's suggested dict), since you can simply use getattr to retrieve the method to call from the object itself or its type. E.g.:\ndef all_lines(somefile, methods):\n \"\"\"Apply a sequence of methods to all lines of some file and yield the results.\n Args:\n somefile: an open file or other iterable yielding lines\n methods: a string that's a whitespace-separated sequence of method names.\n (note that the methods must be callable without arguments beyond the\n str to which they're being applied)\n \"\"\"\n tobecalled = [getattr(str, name) for name in methods.split()]\n for line in somefile:\n for tocall in tobecalled: line = tocall(line)\n yield line\n\n",
"First of all, many string functions – including strip and replace – are deprecated. The following answer uses string methods instead. (Instead of string.strip(\" Hello \"), I use the equivalent of \" Hello \".strip().)\nHere's some code that will simplify the job for you. The following code assumes that whatever methods you call on your string, that method will return another string.\nclass O(object):\n c = str.capitalize\n r = str.replace\n s = str.strip\n\ndef process_line(line, *ops):\n i = iter(ops)\n while True:\n try:\n op = i.next()\n args = i.next()\n except StopIteration:\n break\n line = op(line, *args)\n return line\n\nThe O class exists so that your highly abbreviated method names don't pollute your namespace. When you want to add more string methods, you add them to O in the same format as those given.\nThe process_line function is where all the interesting things happen. First, here is a description of the argument format:\n\nThe first argument is the string to be processed.\nThe remaining arguments must be given in pairs.\n\n\nThe first argument of the pair is a string method. Use the shortened method names here.\nThe second argument of the pair is a list representing the arguments to that particular string method.\n\n\nThe process_line function returns the string that emerges after all these operations have performed.\nHere is some example code showing how you would use the above code in your own scripts. I've separated the arguments of process_line across multiple lines to show the grouping of the arguments. Of course, if you're just hacking away and using this code in day-to-day scripts, you can compress all the arguments onto one line; this actually makes it a little easier to read.\nf = open(\"parrot_sketch.txt\")\nfor line in f:\n p = process_line(\n line,\n O.r, [\"He's resting...\", \"This is an ex-parrot!\"],\n O.c, [],\n O.s, []\n )\n print p\n\nOf course, if you very specifically wanted to use numerals, you could name your functions O.f1, O.f2, O.f3… but I'm assuming that wasn't the spirit of your question.\n",
"To map names (or numbers) to different string operations, I'd do something like\nOPERATIONS = dict(\n strip = str.strip,\n lower = str.lower,\n removespaces = lambda s: s.replace(' ', ''),\n maketitle = lamdba s: s.title().center(80, '-'),\n # etc\n)\n\ndef process(myfile, ops):\n for line in myfile:\n for op in ops:\n line = OPERATIONS[op](line)\n yield line\n\nwhich you use like this\nfor line in process(afile, ['strip', 'removespaces']):\n ...\n\n"
] |
[
2,
2,
2,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0000844886_python.txt
|
Q:
What's the quickest way for a Ruby programmer to pick up Python?
I've been programming Ruby pretty extensively for the past four years or so, and I'm extremely comfortable with the language. For no particular reason, I've decided to learn some Python this week. Is there a specific book, tutorial, or reference that would be well-suited to someone coming from a nearly-identical language, or should I just "Dive into Python"?
Thanks!
A:
A safe bet is to just dive into python (skim through some tutorials that explain the syntax), and then get coding. The best way to learn any new language is to write code, lots of it. Your experience in Ruby will make it easy to pick up python's dynamic concepts (which might be harder to get used to for say a Java programmer).
Try a python tutorial or book on learning python.
A:
I started learning from the python tutorial. It is well written and easy to follow. Then I started to solve problems in python challenge. It was a really fun way to start :)
A:
After running through some tutorials on-line (the ones posted so far look pretty good), find a current Ruby project you've done (or are working on) and re-write it in Python. I've used this technique to transition from various languages, and it's helped enormously.
A:
I suggest just diving into Python, it's similar to Ruby so you should have no problems:
http://www.diveintopython.net/
|
What's the quickest way for a Ruby programmer to pick up Python?
|
I've been programming Ruby pretty extensively for the past four years or so, and I'm extremely comfortable with the language. For no particular reason, I've decided to learn some Python this week. Is there a specific book, tutorial, or reference that would be well-suited to someone coming from a nearly-identical language, or should I just "Dive into Python"?
Thanks!
|
[
"A safe bet is to just dive into python (skim through some tutorials that explain the syntax), and then get coding. The best way to learn any new language is to write code, lots of it. Your experience in Ruby will make it easy to pick up python's dynamic concepts (which might be harder to get used to for say a Java programmer).\nTry a python tutorial or book on learning python.\n",
"I started learning from the python tutorial. It is well written and easy to follow. Then I started to solve problems in python challenge. It was a really fun way to start :) \n",
"After running through some tutorials on-line (the ones posted so far look pretty good), find a current Ruby project you've done (or are working on) and re-write it in Python. I've used this technique to transition from various languages, and it's helped enormously.\n",
"I suggest just diving into Python, it's similar to Ruby so you should have no problems:\nhttp://www.diveintopython.net/\n"
] |
[
11,
3,
3,
2
] |
[] |
[] |
[
"python",
"ruby"
] |
stackoverflow_0000846139_python_ruby.txt
|
Q:
Unit tests for automatically generated code: automatic or manual?
I know similar questions have been asked before but they don't really have the information I'm looking for - I'm not asking about the mechanics of how to generate unit tests, but whether it's a good idea.
I've written a module in Python which contains objects representing physical constants and units of measurement. A lot of the units are formed by adding on prefixes to base units - e.g. from m I get cm, dm, mm, hm, um, nm, pm, etc. And the same for s, g, C, etc. Of course I've written a function to do this since the end result is over 1000 individual units and it would be a major pain to write them all out by hand ;-) It works something like this (not the actual code):
def add_unit(name, value):
globals()[name] = value
for pfx, multiplier in prefixes:
globals()[pfx + name] = multiplier * value
add_unit('m', <definition of a meter>)
add_unit('g', <definition of a gram>)
add_unit('s', <definition of a second>)
# etc.
The problem comes in when I want to write unit tests for these units (no pun intended), to make sure they all have the right values. If I write code that automatically generates a test case for every unit individually, any problems that are in the unit generation function are likely to also show up in the test generation function. But given the alternative (writing out all 1000+ tests by hand), should I just go ahead and write a test generation function anyway, check it really carefully and hope it works properly? Or should I only test, say, one series of units (m, cm, dm, km, nm, um, and all other multiples of the meter), just enough to make sure the unit generation function seems to be working? Or something else?
A:
If you auto-generate the tests:
You might find it faster to then read all the tests (to inspect them for correctness) that it would have been to write them all by hand.
They might also be more maintainable (easier to edit, if you want to edit them later).
A:
You're right to identify the weakness of automatically generating test cases. The usefulness of a test comes from taking two different paths (your code, and your own mental reasoning) to come up with what should be the same answer -- if you use the same path both times, nothing is being tested.
In summary: Never write automatically generated tests, unless the algorithm for generating the test results is dramatically simpler than the algorithm that you are testing. (Testing of a sorting algorithm is an example of when automatically generated tests would be a good idea, since it's easy to verify that a list of numbers is in sorted order. Another good example would be a puzzle-solving program as suggested by ChrisW in a comment. In both cases, auto-generation makes sense because it is much easier to verify that a given solution is correct than to generate a correct solution.)
My suggestion for your case: Manually test a small, representative subset of the possibilities.
[Clarification: Certain types of automated tests are appropriate and highly useful, e.g. fuzzing. I mean that that it is unhelpful to auto-generate unit tests for generated code.]
A:
I would say the best approach is to unit test the generation, and as part of the unit test, you might take a sample generated result (only enough to where the test tests something that you would consider significantly different over the other scenarios) and put that under a unit test to make sure that the generation is working correctly. Beyond that, there is little unit test value in defining every scenario in an automated way. There may be functional test value in putting together some functional test which exercise the generated code to perform whatever purpose you have in mind, in order to give wider coverage to the various potential units.
A:
Write only just enough tests to make sure that your code generation works right (just enough to drive the design of the imperative code). Declarative code rarely breaks. You should only test things that can break. Mistakes in declarative code (such as your case and for example user interface layouts) are better found with exploratory testing, so writing extensive automated tests for them is waste of time.
|
Unit tests for automatically generated code: automatic or manual?
|
I know similar questions have been asked before but they don't really have the information I'm looking for - I'm not asking about the mechanics of how to generate unit tests, but whether it's a good idea.
I've written a module in Python which contains objects representing physical constants and units of measurement. A lot of the units are formed by adding on prefixes to base units - e.g. from m I get cm, dm, mm, hm, um, nm, pm, etc. And the same for s, g, C, etc. Of course I've written a function to do this since the end result is over 1000 individual units and it would be a major pain to write them all out by hand ;-) It works something like this (not the actual code):
def add_unit(name, value):
globals()[name] = value
for pfx, multiplier in prefixes:
globals()[pfx + name] = multiplier * value
add_unit('m', <definition of a meter>)
add_unit('g', <definition of a gram>)
add_unit('s', <definition of a second>)
# etc.
The problem comes in when I want to write unit tests for these units (no pun intended), to make sure they all have the right values. If I write code that automatically generates a test case for every unit individually, any problems that are in the unit generation function are likely to also show up in the test generation function. But given the alternative (writing out all 1000+ tests by hand), should I just go ahead and write a test generation function anyway, check it really carefully and hope it works properly? Or should I only test, say, one series of units (m, cm, dm, km, nm, um, and all other multiples of the meter), just enough to make sure the unit generation function seems to be working? Or something else?
|
[
"If you auto-generate the tests:\n\nYou might find it faster to then read all the tests (to inspect them for correctness) that it would have been to write them all by hand.\nThey might also be more maintainable (easier to edit, if you want to edit them later).\n\n",
"You're right to identify the weakness of automatically generating test cases. The usefulness of a test comes from taking two different paths (your code, and your own mental reasoning) to come up with what should be the same answer -- if you use the same path both times, nothing is being tested.\nIn summary: Never write automatically generated tests, unless the algorithm for generating the test results is dramatically simpler than the algorithm that you are testing. (Testing of a sorting algorithm is an example of when automatically generated tests would be a good idea, since it's easy to verify that a list of numbers is in sorted order. Another good example would be a puzzle-solving program as suggested by ChrisW in a comment. In both cases, auto-generation makes sense because it is much easier to verify that a given solution is correct than to generate a correct solution.)\nMy suggestion for your case: Manually test a small, representative subset of the possibilities.\n[Clarification: Certain types of automated tests are appropriate and highly useful, e.g. fuzzing. I mean that that it is unhelpful to auto-generate unit tests for generated code.]\n",
"I would say the best approach is to unit test the generation, and as part of the unit test, you might take a sample generated result (only enough to where the test tests something that you would consider significantly different over the other scenarios) and put that under a unit test to make sure that the generation is working correctly. Beyond that, there is little unit test value in defining every scenario in an automated way. There may be functional test value in putting together some functional test which exercise the generated code to perform whatever purpose you have in mind, in order to give wider coverage to the various potential units.\n",
"Write only just enough tests to make sure that your code generation works right (just enough to drive the design of the imperative code). Declarative code rarely breaks. You should only test things that can break. Mistakes in declarative code (such as your case and for example user interface layouts) are better found with exploratory testing, so writing extensive automated tests for them is waste of time.\n"
] |
[
1,
1,
1,
1
] |
[] |
[] |
[
"code_generation",
"python",
"unit_testing"
] |
stackoverflow_0000845887_code_generation_python_unit_testing.txt
|
Q:
Snapshot Movies
I'm currently learning Python and have taken up several small projects to help learn the language. Are there currently any libraries (possibly PythonMagick) out there that are capable of extracting snapshots from .wmv, .avi, .mpg, or other movie formats with only command-line options (no GUI)? And if so, can anyone provide links to examples of code?
A:
A quick search in google revealed pymedia. It supports avi, dvd, wma, ...
Here is an example on how to get snapshots from videos
A:
Additionally, if the CLI situation is not mandatory Pyglet is exceptionally easy to use to load movies, images, etc. and is very well documented.
|
Snapshot Movies
|
I'm currently learning Python and have taken up several small projects to help learn the language. Are there currently any libraries (possibly PythonMagick) out there that are capable of extracting snapshots from .wmv, .avi, .mpg, or other movie formats with only command-line options (no GUI)? And if so, can anyone provide links to examples of code?
|
[
"A quick search in google revealed pymedia. It supports avi, dvd, wma, ...\nHere is an example on how to get snapshots from videos\n",
"Additionally, if the CLI situation is not mandatory Pyglet is exceptionally easy to use to load movies, images, etc. and is very well documented.\n"
] |
[
1,
0
] |
[] |
[] |
[
"movie",
"python",
"screenshot",
"snapshot"
] |
stackoverflow_0000846343_movie_python_screenshot_snapshot.txt
|
Q:
Is there a mod_python for Apache HTTP Server 2.2 and Python 2.6 or 3.0?
I poked around the mod_python website and I only found the files for Python 2.5 and earlier for Apache HTTP Server 2.2. I Googled around a little, without significant luck. Any suggestions?
A:
Use mod_wsgi.
mod_python has been stagnant for a while now. Most of the effort for python web apps has been going into mod_wsgi.
|
Is there a mod_python for Apache HTTP Server 2.2 and Python 2.6 or 3.0?
|
I poked around the mod_python website and I only found the files for Python 2.5 and earlier for Apache HTTP Server 2.2. I Googled around a little, without significant luck. Any suggestions?
|
[
"Use mod_wsgi.\nmod_python has been stagnant for a while now. Most of the effort for python web apps has been going into mod_wsgi.\n"
] |
[
9
] |
[] |
[] |
[
"apache2",
"mod_python",
"python"
] |
stackoverflow_0000846420_apache2_mod_python_python.txt
|
Q:
How do you store raw bytes as text without losing information in python 2.x?
Suppose I have any data stored in bytes. For example:
0110001100010101100101110101101
How can I store it as printable text? The obvious way would be to convert every 0 to the character '0' and every 1 to the character '1'. In fact this is what I'm currently doing. I'd like to know how I could pack them more tightly, without losing information.
I thought of converting bits in groups of eight to ASCII, but some bit combinations are not
accepted in that format. Any other ideas?
A:
What about an encoding that only uses "safe" characters like base64?
http://en.wikipedia.org/wiki/Base64
EDIT: That is assuming that you want to safely store the data in text files and such?
In Python 2.x, strings should be fine (Python doesn't use null terminated strings, so don't worry about that).
Else in 3.x check out the bytes and bytearray objects.
http://docs.python.org/3.0/library/stdtypes.html#bytes-methods
A:
Not sure what you're talking about.
>>> sample = "".join( chr(c) for c in range(256) )
>>> len(sample)
256
>>> sample
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\
x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABC
DEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83
\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97
\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab
\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf
\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3
\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7
\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb
\xfc\xfd\xfe\xff'
The string sample contains all 256 distinct bytes. There is no such thing as a "bit combinations ... not accepted".
To make it printable, simply use repr(sample) -- non-ASCII characters are escaped. As you see above.
A:
Try the standard array module or the struct module. These support storing bytes in a space efficient way -- but they don't support bits directly.
You can also try http://cobweb.ecn.purdue.edu/~kak/dist/BitVector-1.2.html or http://ilan.schnell-web.net/prog/bitarray/
A:
For Python 2.x, your best bet is to store them in a string. Once you have that string, you can encode it into safe ASCII values using the base64 module that comes with python.
import base64
encoded = base64.b64encode(bytestring)
This will be much more condensed than storing "1" and "0".
For more information on the base64 module, see the python docs.
|
How do you store raw bytes as text without losing information in python 2.x?
|
Suppose I have any data stored in bytes. For example:
0110001100010101100101110101101
How can I store it as printable text? The obvious way would be to convert every 0 to the character '0' and every 1 to the character '1'. In fact this is what I'm currently doing. I'd like to know how I could pack them more tightly, without losing information.
I thought of converting bits in groups of eight to ASCII, but some bit combinations are not
accepted in that format. Any other ideas?
|
[
"What about an encoding that only uses \"safe\" characters like base64?\nhttp://en.wikipedia.org/wiki/Base64\nEDIT: That is assuming that you want to safely store the data in text files and such?\nIn Python 2.x, strings should be fine (Python doesn't use null terminated strings, so don't worry about that).\nElse in 3.x check out the bytes and bytearray objects.\nhttp://docs.python.org/3.0/library/stdtypes.html#bytes-methods\n",
"Not sure what you're talking about.\n>>> sample = \"\".join( chr(c) for c in range(256) )\n>>> len(sample)\n256\n>>> sample\n'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c\\r\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\\nx15\\x16\\x17\\x18\\x19\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f !\"#$%&\\'()*+,-./0123456789:;<=>?@ABC\nDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\x7f\\x80\\x81\\x82\\x83\n\\x84\\x85\\x86\\x87\\x88\\x89\\x8a\\x8b\\x8c\\x8d\\x8e\\x8f\\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97\n\\x98\\x99\\x9a\\x9b\\x9c\\x9d\\x9e\\x9f\\xa0\\xa1\\xa2\\xa3\\xa4\\xa5\\xa6\\xa7\\xa8\\xa9\\xaa\\xab\n\\xac\\xad\\xae\\xaf\\xb0\\xb1\\xb2\\xb3\\xb4\\xb5\\xb6\\xb7\\xb8\\xb9\\xba\\xbb\\xbc\\xbd\\xbe\\xbf\n\\xc0\\xc1\\xc2\\xc3\\xc4\\xc5\\xc6\\xc7\\xc8\\xc9\\xca\\xcb\\xcc\\xcd\\xce\\xcf\\xd0\\xd1\\xd2\\xd3\n\\xd4\\xd5\\xd6\\xd7\\xd8\\xd9\\xda\\xdb\\xdc\\xdd\\xde\\xdf\\xe0\\xe1\\xe2\\xe3\\xe4\\xe5\\xe6\\xe7\n\\xe8\\xe9\\xea\\xeb\\xec\\xed\\xee\\xef\\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9\\xfa\\xfb\n\\xfc\\xfd\\xfe\\xff'\n\nThe string sample contains all 256 distinct bytes. There is no such thing as a \"bit combinations ... not accepted\".\nTo make it printable, simply use repr(sample) -- non-ASCII characters are escaped. As you see above.\n",
"Try the standard array module or the struct module. These support storing bytes in a space efficient way -- but they don't support bits directly.\nYou can also try http://cobweb.ecn.purdue.edu/~kak/dist/BitVector-1.2.html or http://ilan.schnell-web.net/prog/bitarray/\n",
"For Python 2.x, your best bet is to store them in a string. Once you have that string, you can encode it into safe ASCII values using the base64 module that comes with python.\nimport base64\nencoded = base64.b64encode(bytestring)\n\nThis will be much more condensed than storing \"1\" and \"0\".\nFor more information on the base64 module, see the python docs.\n"
] |
[
7,
3,
1,
0
] |
[] |
[] |
[
"bit",
"compression",
"python",
"python_2.7",
"storage"
] |
stackoverflow_0000840981_bit_compression_python_python_2.7_storage.txt
|
Q:
Twisted and p2p applications
Can you tell me: could I use twisted for p2p-applications creating? And what protocols should I choose for this?
A:
The best solution is to use the source code for BitTorrent. It was built with Twisted until they switched over to a C++ implementation called Utorrent.
Last known Twisted version of BitTorrent
http://download.bittorrent.com/dl/archive/BitTorrent-5.2.2.tar.gz
Older versions
http://download.bittorrent.com/dl/archive/
As an alternative, you also might want to take a look at Vertex.
It is a p2p library built on top of Twisted and comes with goodies like bypassing firewalls.
Its probably more complete than the other people's sample.
Link to Vertex
https://github.com/twisted/vertex
A:
bittorrent twisted python client/server
A:
Yes, twisted was used to create the initial version of Bittorrent. There are some opensource libraries to start from.
A:
Yes, you can absolutely use twisted to create a p2p application. The one that comes first to my mind is Dtella (http://dtella.org/). It's uses the Direct Connect protocol.
They provide the source code, so that could get you started. I know that quite a few different university networks have DC hubs running. That seems to be the ideal use of this protocol.
|
Twisted and p2p applications
|
Can you tell me: could I use twisted for p2p-applications creating? And what protocols should I choose for this?
|
[
"The best solution is to use the source code for BitTorrent. It was built with Twisted until they switched over to a C++ implementation called Utorrent.\n\nLast known Twisted version of BitTorrent\n\n\nhttp://download.bittorrent.com/dl/archive/BitTorrent-5.2.2.tar.gz\n\nOlder versions\n\n\nhttp://download.bittorrent.com/dl/archive/\n\n\nAs an alternative, you also might want to take a look at Vertex.\nIt is a p2p library built on top of Twisted and comes with goodies like bypassing firewalls.\nIts probably more complete than the other people's sample.\n\nLink to Vertex\n\n\nhttps://github.com/twisted/vertex\n\n\n",
"bittorrent twisted python client/server\n",
"Yes, twisted was used to create the initial version of Bittorrent. There are some opensource libraries to start from.\n",
"Yes, you can absolutely use twisted to create a p2p application. The one that comes first to my mind is Dtella (http://dtella.org/). It's uses the Direct Connect protocol.\nThey provide the source code, so that could get you started. I know that quite a few different university networks have DC hubs running. That seems to be the ideal use of this protocol.\n"
] |
[
13,
4,
1,
0
] |
[] |
[] |
[
"p2p",
"protocols",
"python",
"twisted"
] |
stackoverflow_0000839384_p2p_protocols_python_twisted.txt
|
Q:
Modelling a swiss tournament in Django
I'm trying to create models that represent a swiss tournament, with multiple rounds. Each round everyone will be paired up with another player, except in the case where there is an odd player out, when one player will get a bye.
I need to keep track of the outcome of each pairing; i.e., which player won. Also, I'd like to be able to efficiently search later for all players who have ever played against a given player.
The obvious stuff:
class Tournament(models.Model):
name = models.CharField(max_length=80)
class Player(models.Model):
name = models.CharField(max_length=80)
At first I was planning to have a "TournamentPairing" class that looked something like this:
class TournamentPairing(models.Model):
tournament = models.ForeignKey(Tournament)
round = models.IntegerKey()
player1 = models.ForeignKey(Player)
player2 = models.ForeignKey(Player, null = True) # In case of a bye, this is None.
outcome = models.CharField(max_length=1) # player1 wins, loses, bye, or tie
But that feels kind of hacky, especially the part about player2 being None sometimes. Also, I don't think it facilitates searching very well (since the player we're looking for could be in the player1 or player2 slot).
Is there a better way? I suspect my django noob-ness is holding me back from finding the right solution here.
A:
You can refactor your TournamentPairing class to be more "round" centric to aid in making queries.
CHOICES = (
('n', 'Normal'),
('b', 'Bye'),
)
class Round(models.Model):
number = models.IntegerField()
round_type = models.CharField(max_length=1, default="n", choices=CHOICES)
tournament = models.ForeignKey(Tournament)
players = models.ManyToManyField(Player, related_name="rounds")
winner = models.ForeignKey(Player, null=True, related_name="round_winner")
In the case of a tie, have winner field point to player called "Tie".
Then, for your search criteria, to see a list of the players that a given player has played against:
# grab a player
p = Player.objects.get(name='Tom')
# see what rounds this player played in
rounds_played = p.rounds.all()
# who did this player play against?
[r.players for r in rounds_played]
# to see all rounds this player won
p.round_winner.all()
A:
I think you should have just a single player list and not split it into player1 and player2, those can be constructed when a round is set up.
Your player class could include a list of players they have played, and the last player on that list would be the current player they are facing. When you pick the next player someone must play, add that player to the list.
class Player(Models.model):
name = models.CharField(max_length=80)
playersPlayed = []
During each round, for a single player, simply iterate through the global list of players and compare a particular player to each element in playersPlayed. If the element does not exist, that person can be played and that player should be then added to the list. If a player cannot be found for a particular round, then that player is given a bye.
I hope this is at least a starting point.
|
Modelling a swiss tournament in Django
|
I'm trying to create models that represent a swiss tournament, with multiple rounds. Each round everyone will be paired up with another player, except in the case where there is an odd player out, when one player will get a bye.
I need to keep track of the outcome of each pairing; i.e., which player won. Also, I'd like to be able to efficiently search later for all players who have ever played against a given player.
The obvious stuff:
class Tournament(models.Model):
name = models.CharField(max_length=80)
class Player(models.Model):
name = models.CharField(max_length=80)
At first I was planning to have a "TournamentPairing" class that looked something like this:
class TournamentPairing(models.Model):
tournament = models.ForeignKey(Tournament)
round = models.IntegerKey()
player1 = models.ForeignKey(Player)
player2 = models.ForeignKey(Player, null = True) # In case of a bye, this is None.
outcome = models.CharField(max_length=1) # player1 wins, loses, bye, or tie
But that feels kind of hacky, especially the part about player2 being None sometimes. Also, I don't think it facilitates searching very well (since the player we're looking for could be in the player1 or player2 slot).
Is there a better way? I suspect my django noob-ness is holding me back from finding the right solution here.
|
[
"You can refactor your TournamentPairing class to be more \"round\" centric to aid in making queries.\nCHOICES = (\n ('n', 'Normal'),\n ('b', 'Bye'),\n )\nclass Round(models.Model): \n number = models.IntegerField()\n round_type = models.CharField(max_length=1, default=\"n\", choices=CHOICES)\n tournament = models.ForeignKey(Tournament)\n players = models.ManyToManyField(Player, related_name=\"rounds\")\n winner = models.ForeignKey(Player, null=True, related_name=\"round_winner\") \n\nIn the case of a tie, have winner field point to player called \"Tie\".\nThen, for your search criteria, to see a list of the players that a given player has played against:\n# grab a player \np = Player.objects.get(name='Tom')\n\n# see what rounds this player played in\nrounds_played = p.rounds.all()\n\n# who did this player play against?\n[r.players for r in rounds_played]\n\n# to see all rounds this player won\np.round_winner.all()\n\n",
"I think you should have just a single player list and not split it into player1 and player2, those can be constructed when a round is set up.\nYour player class could include a list of players they have played, and the last player on that list would be the current player they are facing. When you pick the next player someone must play, add that player to the list.\nclass Player(Models.model):\n name = models.CharField(max_length=80)\n playersPlayed = []\n\nDuring each round, for a single player, simply iterate through the global list of players and compare a particular player to each element in playersPlayed. If the element does not exist, that person can be played and that player should be then added to the list. If a player cannot be found for a particular round, then that player is given a bye.\nI hope this is at least a starting point. \n"
] |
[
5,
1
] |
[] |
[] |
[
"django",
"django_models",
"python"
] |
stackoverflow_0000846485_django_django_models_python.txt
|
Q:
Parsing in Python: what's the most efficient way to suppress/normalize strings?
I'm parsing a source file, and I want to "suppress" strings. What I mean by this is transform every string like "bla bla bla +/*" to something like "string" that is deterministic and does not contain any characters that may confuse my parser, because I don't care about the value of the strings. One of the issues here is string formatting using e.g. "%s", please see my remark about this below.
Take for example the following pseudo code, that may be the contents of a file I'm parsing. Assume strings start with ", and escaping the " character is done by "":
print(i)
print("hello**")
print("hel"+"lo**")
print("h e l l o "+
"hello\n")
print("hell""o")
print(str(123)+"h e l l o")
print(uppercase("h e l l o")+"g o o d b y e")
Should be transformed to the following result:
print(i)
print("string")
print("string"+"string")
print("string"
"string")
print("string")
print(str(123)+"string")
print(uppercase("string")+"string")
Currently I treat it as a special case in the code (i.e. detect beginning of a string, and "manually" run until its end with several sub-special cases on the way). If there's a Python library function i can use or a nice regex that may make my code more efficient, that would be great.
Few remarks:
I would like the "start-of-string" character to be a variable, e.g. ' vs ".
I'm not parsing Python code at this stage, but I plan to, and there the problem obviously becomes more complex because strings can start in several ways and must end in a way corresponding to the start. I'm not attempting to deal with this right now, but if there's any well established best practice I would like to know about it.
The thing bothering me the most about this "suppression" is the case of string formatting with the likes of '%s', that are meaningful tokens. I'm currently not dealing with this and haven't completely thought it through, but if any of you have suggestions about how to deal with this that would be great. Please note I'm not interested in the specific type or formatting of the in-string tokens, it's enough for me to know that there are tokens inside the string (how many). Remark that may be important here: my tokenizer is not nested, because my goal is quite simple (I'm not compiling anything...).
I'm not quite sure about the escaping of the start-string character. What would you say are the common ways this is implemented in most programming languages? Is the assumption of double-occurrence (e.g. "") or any set of two characters (e.g. '\"') to escape enough? Do I need to treat other cases (think of languages like Java, C/C++, PHP, C#)?
A:
Option 1: To sanitize Python source code, try the built-in tokenize module. It can correctly find strings and other tokens in any Python source file.
Option 3: Use pygments with HTML output, and replace anything in blue (etc.) with "string". pygments supports a few dozen languages.
Option 2: For most of the languages, you can build a custom regexp substitution. For example, the following sanitizes Python source code (but it doesn't work if the source file contains """ or '''):
import re
sanitized = re.sub(r'(#.*)|\'(?:[^\'\\]+|\\.)*\'|"(?:[^"\\]+|\\.)*"',
lambda match: match.group(1) or '"string"', source_code)
The regexp above works properly even if the strings contain backslashes (\", \\, \n, \\, \\", \\\" etc. all work fine).
When you are building your regexp, make sure to match comments (so your regexp substitution won't touch strings inside comments) and regular expression literals (e.g. in Perl, Ruby and JavaScript), and pay attention you match backslashes and newlines properly (e.g. in Perl and Ruby a string can contain a newline).
A:
Nowhere do you mention that you take an approach using a lexer and parser. If in fact you do not, have a look at e.g. the tokenize module (which is probably what you want), or the 3rd party module PLY (Python Lex-Yacc). Your problem needs a systematic approach, and these tools (and others) provide it.
(Note that once you have tokenized the code, you can apply another specialized tokenizer to the contents of the strings to detect special formatting directives such as %s. In this case a regular expression may do the job, though.)
A:
Use a dedicated parser for each language — especially since people have already done that work for you. Most of the languages you mentioned have a grammar.
|
Parsing in Python: what's the most efficient way to suppress/normalize strings?
|
I'm parsing a source file, and I want to "suppress" strings. What I mean by this is transform every string like "bla bla bla +/*" to something like "string" that is deterministic and does not contain any characters that may confuse my parser, because I don't care about the value of the strings. One of the issues here is string formatting using e.g. "%s", please see my remark about this below.
Take for example the following pseudo code, that may be the contents of a file I'm parsing. Assume strings start with ", and escaping the " character is done by "":
print(i)
print("hello**")
print("hel"+"lo**")
print("h e l l o "+
"hello\n")
print("hell""o")
print(str(123)+"h e l l o")
print(uppercase("h e l l o")+"g o o d b y e")
Should be transformed to the following result:
print(i)
print("string")
print("string"+"string")
print("string"
"string")
print("string")
print(str(123)+"string")
print(uppercase("string")+"string")
Currently I treat it as a special case in the code (i.e. detect beginning of a string, and "manually" run until its end with several sub-special cases on the way). If there's a Python library function i can use or a nice regex that may make my code more efficient, that would be great.
Few remarks:
I would like the "start-of-string" character to be a variable, e.g. ' vs ".
I'm not parsing Python code at this stage, but I plan to, and there the problem obviously becomes more complex because strings can start in several ways and must end in a way corresponding to the start. I'm not attempting to deal with this right now, but if there's any well established best practice I would like to know about it.
The thing bothering me the most about this "suppression" is the case of string formatting with the likes of '%s', that are meaningful tokens. I'm currently not dealing with this and haven't completely thought it through, but if any of you have suggestions about how to deal with this that would be great. Please note I'm not interested in the specific type or formatting of the in-string tokens, it's enough for me to know that there are tokens inside the string (how many). Remark that may be important here: my tokenizer is not nested, because my goal is quite simple (I'm not compiling anything...).
I'm not quite sure about the escaping of the start-string character. What would you say are the common ways this is implemented in most programming languages? Is the assumption of double-occurrence (e.g. "") or any set of two characters (e.g. '\"') to escape enough? Do I need to treat other cases (think of languages like Java, C/C++, PHP, C#)?
|
[
"Option 1: To sanitize Python source code, try the built-in tokenize module. It can correctly find strings and other tokens in any Python source file.\nOption 3: Use pygments with HTML output, and replace anything in blue (etc.) with \"string\". pygments supports a few dozen languages.\nOption 2: For most of the languages, you can build a custom regexp substitution. For example, the following sanitizes Python source code (but it doesn't work if the source file contains \"\"\" or '''):\nimport re\nsanitized = re.sub(r'(#.*)|\\'(?:[^\\'\\\\]+|\\\\.)*\\'|\"(?:[^\"\\\\]+|\\\\.)*\"',\n lambda match: match.group(1) or '\"string\"', source_code)\n\nThe regexp above works properly even if the strings contain backslashes (\\\", \\\\, \\n, \\\\, \\\\\", \\\\\\\" etc. all work fine).\nWhen you are building your regexp, make sure to match comments (so your regexp substitution won't touch strings inside comments) and regular expression literals (e.g. in Perl, Ruby and JavaScript), and pay attention you match backslashes and newlines properly (e.g. in Perl and Ruby a string can contain a newline).\n",
"Nowhere do you mention that you take an approach using a lexer and parser. If in fact you do not, have a look at e.g. the tokenize module (which is probably what you want), or the 3rd party module PLY (Python Lex-Yacc). Your problem needs a systematic approach, and these tools (and others) provide it.\n(Note that once you have tokenized the code, you can apply another specialized tokenizer to the contents of the strings to detect special formatting directives such as %s. In this case a regular expression may do the job, though.)\n",
"Use a dedicated parser for each language — especially since people have already done that work for you. Most of the languages you mentioned have a grammar.\n"
] |
[
4,
1,
1
] |
[] |
[] |
[
"parsing",
"python",
"string"
] |
stackoverflow_0000846869_parsing_python_string.txt
|
Q:
Is Twisted an httplib2/socket replacement?
Many python libraries, even recently written ones, use httplib2 or the socket interface to perform networking tasks.
Those are obviously easier to code on than Twisted due to their blocking nature, but I think this is a drawback when integrating them with other code, especially GUI one. If you want scalability, concurrency or GUI integration while avoiding multithreading, Twisted is then a natural choice.
So I would be interested in opinions in those matters:
Should new networking code (with the exception of small command line tools) be written with Twisted?
Would you mix Twisted, http2lib or socket code in the same project?
Is Twisted pythonic for most libraries (it is more complex than alternatives, introduce a dependency to a non-standard package...)?
Edit: please let me phrase this in another way. Do you feel writing new library code with Twisted may add a barrier to its adoption? Twisted has obvious benefits (especially portability and scalability as stated by gimel), but the fact that it is not a core python library may be considered by some as a drawback.
A:
See asychronous-programming-in-python-twisted, you'll have to decide if depending on a non-standard (external) library fits your needs. Note the answer by @Glyph, he is the founder of the Twisted project, and can authoritatively answer any Twisted related question.
At the core of libraries like Twisted, the function in the main loop is not sleep, but an operating system call like select() or poll(), as exposed by a module like the Python select module. I say "like" select, because this is an API that varies a lot between platforms, and almost every GUI toolkit has its own version. Twisted currently provides an abstract interface to 14 different variations on this theme. The common thing that such an API provides is provide a way to say "Here are a list of events that I'm waiting for. Go to sleep until one of them happens, then wake up and tell me which one of them it was."
A:
Should new networking code (with the exception of small command line tools) be written with Twisted?
Maybe. It really depends. Sometimes its just easy enough to wrap the blocking calls in their own thread. Twisted is good for large scale network code.
Would you mix Twisted, http2lib or socket code in the same project?
Sure. But just remember that Twisted is single threaded, and that any blocking call in Twisted will block the entire engine.
Is Twisted pythonic for most libraries (it is more complex than alternatives, introduce a dependency to a non-standard package...)?
There are many Twisted zealots that will say it belongs in the Python standard library. But many people can implement decent networking code with asyncore/asynchat.
|
Is Twisted an httplib2/socket replacement?
|
Many python libraries, even recently written ones, use httplib2 or the socket interface to perform networking tasks.
Those are obviously easier to code on than Twisted due to their blocking nature, but I think this is a drawback when integrating them with other code, especially GUI one. If you want scalability, concurrency or GUI integration while avoiding multithreading, Twisted is then a natural choice.
So I would be interested in opinions in those matters:
Should new networking code (with the exception of small command line tools) be written with Twisted?
Would you mix Twisted, http2lib or socket code in the same project?
Is Twisted pythonic for most libraries (it is more complex than alternatives, introduce a dependency to a non-standard package...)?
Edit: please let me phrase this in another way. Do you feel writing new library code with Twisted may add a barrier to its adoption? Twisted has obvious benefits (especially portability and scalability as stated by gimel), but the fact that it is not a core python library may be considered by some as a drawback.
|
[
"See asychronous-programming-in-python-twisted, you'll have to decide if depending on a non-standard (external) library fits your needs. Note the answer by @Glyph, he is the founder of the Twisted project, and can authoritatively answer any Twisted related question.\n\nAt the core of libraries like Twisted, the function in the main loop is not sleep, but an operating system call like select() or poll(), as exposed by a module like the Python select module. I say \"like\" select, because this is an API that varies a lot between platforms, and almost every GUI toolkit has its own version. Twisted currently provides an abstract interface to 14 different variations on this theme. The common thing that such an API provides is provide a way to say \"Here are a list of events that I'm waiting for. Go to sleep until one of them happens, then wake up and tell me which one of them it was.\"\n\n",
"\nShould new networking code (with the exception of small command line tools) be written with Twisted?\n\n\nMaybe. It really depends. Sometimes its just easy enough to wrap the blocking calls in their own thread. Twisted is good for large scale network code.\n\nWould you mix Twisted, http2lib or socket code in the same project?\n\n\nSure. But just remember that Twisted is single threaded, and that any blocking call in Twisted will block the entire engine.\n\nIs Twisted pythonic for most libraries (it is more complex than alternatives, introduce a dependency to a non-standard package...)?\n\n\nThere are many Twisted zealots that will say it belongs in the Python standard library. But many people can implement decent networking code with asyncore/asynchat.\n\n\n"
] |
[
5,
0
] |
[] |
[] |
[
"httplib2",
"networking",
"python",
"sockets",
"twisted"
] |
stackoverflow_0000846950_httplib2_networking_python_sockets_twisted.txt
|
Q:
how to use list of python objects whose representation is unicode
I have a object which contains unicode data and I want to use that in its representaion
e.g.
# -*- coding: utf-8 -*-
class A(object):
def __unicode__(self):
return u"©au"
def __repr__(self):
return unicode(self).encode("utf-8")
__str__ = __repr__
a = A()
s1 = u"%s"%a # works
#s2 = u"%s"%[a] # gives unicode decode error
#s3 = u"%s"%unicode([a]) # gives unicode decode error
Now even if I return unicode from repr it still gives error
so question is how can I use a list of such objects and create another unicode string out of it?
platform details:
"""
Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
'Linux-2.6.24-19-generic-i686-with-debian-lenny-sid'
"""
also not sure why
print a # works
print unicode(a) # works
print [a] # works
print unicode([a]) # doesn't works
python group answers that
http://groups.google.com/group/comp.lang.python/browse_thread/thread/bd7ced9e4017d8de/2e0b07c761604137?lnk=gst&q=unicode#2e0b07c761604137
A:
s1 = u"%s"%a # works
This works, because when dealing with 'a' it is using its unicode representation (i.e. the unicode method),
when however you wrap it in a list such as '[a]' ... when you try to put that list in the string, what is being called is the unicode([a]) (which is the same as repr in the case of list), the string representation of the list, which will use 'repr(a)' to represent your item in its output. This will cause a problem since you are passing a 'str' object (a string of bytes) that contain the utf-8 encoded version of 'a', and when the string format is trying to embed that in your unicode string, it will try to convert it back to a unicode object using hte default encoding, i.e. ASCII. since ascii doesn't have whatever character it's trying to conver, it fails
what you want to do would have to be done this way: u"%s" % repr([a]).decode('utf-8') assuming all your elements encode to utf-8 (or ascii, which is a utf-8 subset from unicode point of view).
for a better solution (if you still want keep the string looking like a list str) you would have to use what was suggested previously, and use join, in something like this:
u'[%s]' % u','.join(unicode(x) for x in [a,a])
though this won't take care of list containing list of your A objects.
My explanation sounds terribly unclear, but I hope you can make some sense out of it.
A:
Try:
s2 = u"%s"%[unicode(a)]
Your main problem is that you are doing more conversions than you expect. Lets consider the following:
s2 = u"%s"%[a] # gives unicode decode error
From Python Documentation,
's' String (converts any python object using str()).
If the object or format provided is a unicode string,
the resulting string will also be unicode.
When the %s format string is being processed, str([a]) is applied. What you have at this point is a string object containg a sequence of unicode bytes. If you try and print this there is no problem, because the bytes pass straight through to your terminal and are rendered by the terminal.
>>> x = "%s" % [a]
>>> print x
[©au]
The problem arises when you try to convert that back to unicode. Essentially, the function unicode is being called on the string which contains the sequence of unicode-encoded bytes, and that is what causes the ascii codec to fail.
>>> u"%s" % x
Traceback (most recent call last):
File "", line 1, in
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 1: ordinal not in range(128)
>>> unicode(x)
Traceback (most recent call last):
File "", line 1, in
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 1: ordinal not in range(128)
A:
First of all, ask yourself what you're trying to achieve. If all you want is a round-trippable representation of the list, you should simply do the following:
class A(object):
def __unicode__(self):
return u"©au"
def __repr__(self):
return repr(unicode(self))
__str__ = __repr__
>>> A()
u'\xa9au'
>>> [A()]
[u'\xa9au']
>>> u"%s" % [A()]
u"[u'\\xa9au']"
>>> "%s" % [A()]
"[u'\\xa9au']"
>>> print u"%s" % [A()]
[u'\xa9au']
That's how it's supposed to work. String representation of python lists are not something a user should see, so it makes sense to have escaped characters in them.
A:
If you want to use a list of unicode()able objects to create a unicode string, try something like:
u''.join([unicode(v) for v in [a,a]])
A:
Since this question involves a lot of confusing unicode stuff, I thought I'd offer an analysis of what was going on here.
It all comes down to the implementation of __unicode__ and __repr__ of the builtin list class. Basically, it is equivalent to:
class list(object):
def __repr__(self):
return "[%s]" % ", ".join(repr(e) for e in self.elements)
def __str__(self):
return repr(self)
def __unicode__(self):
return str(self).decode()
Actually, list doesn't even define the __unicode__ and __str__ methods, which makes sense when you think about it.
When you write:
u"%s" % [a] # it expands to
u"%s" % unicode([a]) # which expands to
u"%s" % repr([a]).decode() # which expands to
u"%s" % ("[%s]" % repr(a)).decode() # (simplified a little bit)
u"%s" % ("[%s]" % unicode(a).encode('utf-8')).decode()
That last line is an expansion of repr(a), using the implementation of __repr__ in the question.
So as you can see, the object is first encoded in utf-8, only to be decoded later with the system default encoding, which usually doesn't support all characters.
As some of the other answers mentioned, you can write your own function, or even subclass list, like so:
class mylist(list):
def __unicode__(self):
return u"[%s]" % u", ".join(map(unicode, self))
Note that this format is not round-trippable. It can even be misleading:
>>> unicode(mylist([]))
u'[]'
>>> unicode(mylist(['']))
u'[]'
Of cource, you can write a quote_unicode function to make it round-trippable, but this is the moment to ask youself what's the point. The unicode and str functions are meant to create a representation of an object that makes sense to a user. For programmers, there's the repr function. Raw lists are not something a user is ever supposed to see. That's why the list class does not implement the __unicode__ method.
To get a somewhat better idea about what happens when, play with this little class:
class B(object):
def __unicode__(self):
return u"unicode"
def __repr__(self):
return "repr"
def __str__(self):
return "str"
>>> b
repr
>>> [b]
[repr]
>>> unicode(b)
u'unicode'
>>> unicode([b])
u'[repr]'
>>> print b
str
>>> print [b]
[repr]
>>> print unicode(b)
unicode
>>> print unicode([b])
[repr]
A:
# -*- coding: utf-8 -*-
class A(object):
def __unicode__(self):
return u"©au"
def __repr__(self):
return unicode(self).encode('ascii', 'replace')
__str__ = __repr__
a = A()
>>> u"%s" % a
u'\xa9au'
>>> u"%s" % [a]
u'[?au]'
A:
repr and str are both supposed to return str objects, at least up to Python 2.6.x. You're getting the decode error because repr() is trying to convert your result into a str, and it's failing.
I believe this has changed in Python 3.x.
|
how to use list of python objects whose representation is unicode
|
I have a object which contains unicode data and I want to use that in its representaion
e.g.
# -*- coding: utf-8 -*-
class A(object):
def __unicode__(self):
return u"©au"
def __repr__(self):
return unicode(self).encode("utf-8")
__str__ = __repr__
a = A()
s1 = u"%s"%a # works
#s2 = u"%s"%[a] # gives unicode decode error
#s3 = u"%s"%unicode([a]) # gives unicode decode error
Now even if I return unicode from repr it still gives error
so question is how can I use a list of such objects and create another unicode string out of it?
platform details:
"""
Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
'Linux-2.6.24-19-generic-i686-with-debian-lenny-sid'
"""
also not sure why
print a # works
print unicode(a) # works
print [a] # works
print unicode([a]) # doesn't works
python group answers that
http://groups.google.com/group/comp.lang.python/browse_thread/thread/bd7ced9e4017d8de/2e0b07c761604137?lnk=gst&q=unicode#2e0b07c761604137
|
[
"s1 = u\"%s\"%a # works\nThis works, because when dealing with 'a' it is using its unicode representation (i.e. the unicode method),\nwhen however you wrap it in a list such as '[a]' ... when you try to put that list in the string, what is being called is the unicode([a]) (which is the same as repr in the case of list), the string representation of the list, which will use 'repr(a)' to represent your item in its output. This will cause a problem since you are passing a 'str' object (a string of bytes) that contain the utf-8 encoded version of 'a', and when the string format is trying to embed that in your unicode string, it will try to convert it back to a unicode object using hte default encoding, i.e. ASCII. since ascii doesn't have whatever character it's trying to conver, it fails\nwhat you want to do would have to be done this way: u\"%s\" % repr([a]).decode('utf-8') assuming all your elements encode to utf-8 (or ascii, which is a utf-8 subset from unicode point of view).\nfor a better solution (if you still want keep the string looking like a list str) you would have to use what was suggested previously, and use join, in something like this:\nu'[%s]' % u','.join(unicode(x) for x in [a,a])\nthough this won't take care of list containing list of your A objects.\nMy explanation sounds terribly unclear, but I hope you can make some sense out of it.\n",
"Try:\ns2 = u\"%s\"%[unicode(a)] \n\nYour main problem is that you are doing more conversions than you expect. Lets consider the following:\ns2 = u\"%s\"%[a] # gives unicode decode error\n\nFrom Python Documentation, \n\n 's' String (converts any python object using str()).\n If the object or format provided is a unicode string, \n the resulting string will also be unicode.\n\nWhen the %s format string is being processed, str([a]) is applied. What you have at this point is a string object containg a sequence of unicode bytes. If you try and print this there is no problem, because the bytes pass straight through to your terminal and are rendered by the terminal.\n>>> x = \"%s\" % [a]\n>>> print x\n[©au]\n\nThe problem arises when you try to convert that back to unicode. Essentially, the function unicode is being called on the string which contains the sequence of unicode-encoded bytes, and that is what causes the ascii codec to fail.\n\n >>> u\"%s\" % x\n Traceback (most recent call last):\n File \"\", line 1, in \n UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 1: ordinal not in range(128)\n >>> unicode(x)\n Traceback (most recent call last):\n File \"\", line 1, in \n UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 1: ordinal not in range(128)\n\n",
"First of all, ask yourself what you're trying to achieve. If all you want is a round-trippable representation of the list, you should simply do the following:\nclass A(object):\n def __unicode__(self):\n return u\"©au\"\n def __repr__(self):\n return repr(unicode(self))\n __str__ = __repr__\n\n>>> A()\nu'\\xa9au'\n>>> [A()]\n[u'\\xa9au']\n>>> u\"%s\" % [A()]\nu\"[u'\\\\xa9au']\"\n>>> \"%s\" % [A()]\n\"[u'\\\\xa9au']\"\n>>> print u\"%s\" % [A()]\n[u'\\xa9au']\n\nThat's how it's supposed to work. String representation of python lists are not something a user should see, so it makes sense to have escaped characters in them. \n",
"If you want to use a list of unicode()able objects to create a unicode string, try something like:\nu''.join([unicode(v) for v in [a,a]])\n\n",
"Since this question involves a lot of confusing unicode stuff, I thought I'd offer an analysis of what was going on here.\nIt all comes down to the implementation of __unicode__ and __repr__ of the builtin list class. Basically, it is equivalent to:\nclass list(object):\n def __repr__(self):\n return \"[%s]\" % \", \".join(repr(e) for e in self.elements)\n def __str__(self):\n return repr(self)\n def __unicode__(self):\n return str(self).decode()\n\nActually, list doesn't even define the __unicode__ and __str__ methods, which makes sense when you think about it. \nWhen you write:\nu\"%s\" % [a] # it expands to\nu\"%s\" % unicode([a]) # which expands to\nu\"%s\" % repr([a]).decode() # which expands to\nu\"%s\" % (\"[%s]\" % repr(a)).decode() # (simplified a little bit)\nu\"%s\" % (\"[%s]\" % unicode(a).encode('utf-8')).decode() \n\nThat last line is an expansion of repr(a), using the implementation of __repr__ in the question.\nSo as you can see, the object is first encoded in utf-8, only to be decoded later with the system default encoding, which usually doesn't support all characters.\nAs some of the other answers mentioned, you can write your own function, or even subclass list, like so:\nclass mylist(list):\n def __unicode__(self):\n return u\"[%s]\" % u\", \".join(map(unicode, self))\n\nNote that this format is not round-trippable. It can even be misleading:\n>>> unicode(mylist([]))\nu'[]'\n>>> unicode(mylist(['']))\nu'[]'\n\nOf cource, you can write a quote_unicode function to make it round-trippable, but this is the moment to ask youself what's the point. The unicode and str functions are meant to create a representation of an object that makes sense to a user. For programmers, there's the repr function. Raw lists are not something a user is ever supposed to see. That's why the list class does not implement the __unicode__ method.\nTo get a somewhat better idea about what happens when, play with this little class:\nclass B(object):\n def __unicode__(self):\n return u\"unicode\"\n def __repr__(self):\n return \"repr\"\n def __str__(self):\n return \"str\"\n\n\n>>> b\nrepr\n>>> [b]\n[repr]\n>>> unicode(b)\nu'unicode'\n>>> unicode([b])\nu'[repr]'\n\n>>> print b\nstr\n>>> print [b]\n[repr]\n>>> print unicode(b)\nunicode\n>>> print unicode([b])\n[repr]\n\n",
"# -*- coding: utf-8 -*-\n\nclass A(object):\n def __unicode__(self):\n return u\"©au\"\n\n def __repr__(self):\n return unicode(self).encode('ascii', 'replace')\n\n __str__ = __repr__\n\na = A()\n\n>>> u\"%s\" % a\nu'\\xa9au'\n>>> u\"%s\" % [a]\nu'[?au]'\n\n",
"repr and str are both supposed to return str objects, at least up to Python 2.6.x. You're getting the decode error because repr() is trying to convert your result into a str, and it's failing.\nI believe this has changed in Python 3.x.\n"
] |
[
4,
3,
2,
1,
1,
0,
0
] |
[] |
[] |
[
"python",
"unicode"
] |
stackoverflow_0000842696_python_unicode.txt
|
Q:
Read Unicode characters from command-line arguments in Python 2.x on Windows
I want my Python script to be able to read Unicode command line arguments in Windows. But it appears that sys.argv is a string encoded in some local encoding, rather than Unicode. How can I read the command line in full Unicode?
Example code: argv.py
import sys
first_arg = sys.argv[1]
print first_arg
print type(first_arg)
print first_arg.encode("hex")
print open(first_arg)
On my PC set up for Japanese code page, I get:
C:\temp>argv.py "PC・ソフト申請書08.09.24.doc"
PC・ソフト申請書08.09.24.doc
<type 'str'>
50438145835c83748367905c90bf8f9130382e30392e32342e646f63
<open file 'PC・ソフト申請書08.09.24.doc', mode 'r' at 0x00917D90>
That's Shift-JIS encoded I believe, and it "works" for that filename. But it breaks for filenames with characters that aren't in the Shift-JIS character set—the final "open" call fails:
C:\temp>argv.py Jörgen.txt
Jorgen.txt
<type 'str'>
4a6f7267656e2e747874
Traceback (most recent call last):
File "C:\temp\argv.py", line 7,
in <module>
print open(first_arg)
IOError: [Errno 2] No such file or directory: 'Jorgen.txt'
Note—I'm talking about Python 2.x, not Python 3.0. I've found that Python 3.0 gives sys.argv as proper Unicode. But it's a bit early yet to transition to Python 3.0 (due to lack of 3rd party library support).
Update:
A few answers have said I should decode according to whatever the sys.argv is encoded in. The problem with that is that it's not full Unicode, so some characters are not representable.
Here's the use case that gives me grief: I have enabled drag-and-drop of files onto .py files in Windows Explorer. I have file names with all sorts of characters, including some not in the system default code page. My Python script doesn't get the right Unicode filenames passed to it via sys.argv in all cases, when the characters aren't representable in the current code page encoding.
There is certainly some Windows API to read the command line with full Unicode (and Python 3.0 does it). I assume the Python 2.x interpreter is not using it.
A:
Here is a solution that is just what I'm looking for, making a call to the Windows GetCommandLineArgvW function:
Get sys.argv with Unicode characters under Windows (from ActiveState)
But I've made several changes, to simplify its usage and better handle certain uses. Here is what I use:
win32_unicode_argv.py
"""
win32_unicode_argv.py
Importing this will replace sys.argv with a full Unicode form.
Windows only.
From this site, with adaptations:
http://code.activestate.com/recipes/572200/
Usage: simply import this module into a script. sys.argv is changed to
be a list of Unicode strings.
"""
import sys
def win32_unicode_argv():
"""Uses shell32.GetCommandLineArgvW to get sys.argv as a list of Unicode
strings.
Versions 2.x of Python don't support Unicode in sys.argv on
Windows, with the underlying Windows API instead replacing multi-byte
characters with '?'.
"""
from ctypes import POINTER, byref, cdll, c_int, windll
from ctypes.wintypes import LPCWSTR, LPWSTR
GetCommandLineW = cdll.kernel32.GetCommandLineW
GetCommandLineW.argtypes = []
GetCommandLineW.restype = LPCWSTR
CommandLineToArgvW = windll.shell32.CommandLineToArgvW
CommandLineToArgvW.argtypes = [LPCWSTR, POINTER(c_int)]
CommandLineToArgvW.restype = POINTER(LPWSTR)
cmd = GetCommandLineW()
argc = c_int(0)
argv = CommandLineToArgvW(cmd, byref(argc))
if argc.value > 0:
# Remove Python executable and commands if present
start = argc.value - len(sys.argv)
return [argv[i] for i in
xrange(start, argc.value)]
sys.argv = win32_unicode_argv()
Now, the way I use it is simply to do:
import sys
import win32_unicode_argv
and from then on, sys.argv is a list of Unicode strings. The Python optparse module seems happy to parse it, which is great.
A:
Dealing with encodings is very confusing.
I believe if your inputing data via the commandline it will encode the data as whatever your system encoding is and is not unicode. (Even copy/paste should do this)
So it should be correct to decode into unicode using the system encoding:
import sys
first_arg = sys.argv[1]
print first_arg
print type(first_arg)
first_arg_unicode = first_arg.decode(sys.getfilesystemencoding())
print first_arg_unicode
print type(first_arg_unicode)
f = codecs.open(first_arg_unicode, 'r', 'utf-8')
unicode_text = f.read()
print type(unicode_text)
print unicode_text.encode(sys.getfilesystemencoding())
running the following Will output:
Prompt> python myargv.py "PC・ソフト申請書08.09.24.txt"
PC・ソフト申請書08.09.24.txt
<type 'str'>
<type 'unicode'>
PC・ソフト申請書08.09.24.txt
<type 'unicode'>
?日本語
Where the "PC・ソフト申請書08.09.24.txt" contained the text, "日本語".
(I encoded the file as utf8 using windows notepad, I'm a little stumped as to why there's a '?' in the begining when printing. Something to do with how notepad saves utf8?)
The strings 'decode' method or the unicode() builtin can be used to convert an encoding into unicode.
unicode_str = utf8_str.decode('utf8')
unicode_str = unicode(utf8_str, 'utf8')
Also, if your dealing with encoded files you may want to use the codecs.open() function in place of the built-in open(). It allows you to define the encoding of the file, and will then use the given encoding to transparently decode the content to unicode.
So when you call content = codecs.open("myfile.txt", "r", "utf8").read() content will be in unicode.
codecs.open:
http://docs.python.org/library/codecs.html?#codecs.open
If I'm miss-understanding something please let me know.
If you haven't already I recommend reading Joel's article on unicode and encoding:
http://www.joelonsoftware.com/articles/Unicode.html
A:
Try this:
import sys
print repr(sys.argv[1].decode('UTF-8'))
Maybe you have to substitute CP437 or CP1252 for UTF-8. You should be able to infer the proper encoding name from the registry key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage\OEMCP
A:
The command line might be in Windows encoding. Try decoding the arguments into unicode objects:
args = [unicode(x, "iso-8859-9") for x in sys.argv]
|
Read Unicode characters from command-line arguments in Python 2.x on Windows
|
I want my Python script to be able to read Unicode command line arguments in Windows. But it appears that sys.argv is a string encoded in some local encoding, rather than Unicode. How can I read the command line in full Unicode?
Example code: argv.py
import sys
first_arg = sys.argv[1]
print first_arg
print type(first_arg)
print first_arg.encode("hex")
print open(first_arg)
On my PC set up for Japanese code page, I get:
C:\temp>argv.py "PC・ソフト申請書08.09.24.doc"
PC・ソフト申請書08.09.24.doc
<type 'str'>
50438145835c83748367905c90bf8f9130382e30392e32342e646f63
<open file 'PC・ソフト申請書08.09.24.doc', mode 'r' at 0x00917D90>
That's Shift-JIS encoded I believe, and it "works" for that filename. But it breaks for filenames with characters that aren't in the Shift-JIS character set—the final "open" call fails:
C:\temp>argv.py Jörgen.txt
Jorgen.txt
<type 'str'>
4a6f7267656e2e747874
Traceback (most recent call last):
File "C:\temp\argv.py", line 7,
in <module>
print open(first_arg)
IOError: [Errno 2] No such file or directory: 'Jorgen.txt'
Note—I'm talking about Python 2.x, not Python 3.0. I've found that Python 3.0 gives sys.argv as proper Unicode. But it's a bit early yet to transition to Python 3.0 (due to lack of 3rd party library support).
Update:
A few answers have said I should decode according to whatever the sys.argv is encoded in. The problem with that is that it's not full Unicode, so some characters are not representable.
Here's the use case that gives me grief: I have enabled drag-and-drop of files onto .py files in Windows Explorer. I have file names with all sorts of characters, including some not in the system default code page. My Python script doesn't get the right Unicode filenames passed to it via sys.argv in all cases, when the characters aren't representable in the current code page encoding.
There is certainly some Windows API to read the command line with full Unicode (and Python 3.0 does it). I assume the Python 2.x interpreter is not using it.
|
[
"Here is a solution that is just what I'm looking for, making a call to the Windows GetCommandLineArgvW function:\nGet sys.argv with Unicode characters under Windows (from ActiveState)\nBut I've made several changes, to simplify its usage and better handle certain uses. Here is what I use:\nwin32_unicode_argv.py\n\"\"\"\nwin32_unicode_argv.py\n\nImporting this will replace sys.argv with a full Unicode form.\nWindows only.\n\nFrom this site, with adaptations:\n http://code.activestate.com/recipes/572200/\n\nUsage: simply import this module into a script. sys.argv is changed to\nbe a list of Unicode strings.\n\"\"\"\n\n\nimport sys\n\ndef win32_unicode_argv():\n \"\"\"Uses shell32.GetCommandLineArgvW to get sys.argv as a list of Unicode\n strings.\n\n Versions 2.x of Python don't support Unicode in sys.argv on\n Windows, with the underlying Windows API instead replacing multi-byte\n characters with '?'.\n \"\"\"\n\n from ctypes import POINTER, byref, cdll, c_int, windll\n from ctypes.wintypes import LPCWSTR, LPWSTR\n\n GetCommandLineW = cdll.kernel32.GetCommandLineW\n GetCommandLineW.argtypes = []\n GetCommandLineW.restype = LPCWSTR\n\n CommandLineToArgvW = windll.shell32.CommandLineToArgvW\n CommandLineToArgvW.argtypes = [LPCWSTR, POINTER(c_int)]\n CommandLineToArgvW.restype = POINTER(LPWSTR)\n\n cmd = GetCommandLineW()\n argc = c_int(0)\n argv = CommandLineToArgvW(cmd, byref(argc))\n if argc.value > 0:\n # Remove Python executable and commands if present\n start = argc.value - len(sys.argv)\n return [argv[i] for i in\n xrange(start, argc.value)]\n\nsys.argv = win32_unicode_argv()\n\nNow, the way I use it is simply to do:\nimport sys\nimport win32_unicode_argv\n\nand from then on, sys.argv is a list of Unicode strings. The Python optparse module seems happy to parse it, which is great.\n",
"Dealing with encodings is very confusing.\nI believe if your inputing data via the commandline it will encode the data as whatever your system encoding is and is not unicode. (Even copy/paste should do this)\nSo it should be correct to decode into unicode using the system encoding:\nimport sys\n\nfirst_arg = sys.argv[1]\nprint first_arg\nprint type(first_arg)\n\nfirst_arg_unicode = first_arg.decode(sys.getfilesystemencoding())\nprint first_arg_unicode\nprint type(first_arg_unicode)\n\nf = codecs.open(first_arg_unicode, 'r', 'utf-8')\nunicode_text = f.read()\nprint type(unicode_text)\nprint unicode_text.encode(sys.getfilesystemencoding())\n\nrunning the following Will output:\n Prompt> python myargv.py \"PC・ソフト申請書08.09.24.txt\"\nPC・ソフト申請書08.09.24.txt\n<type 'str'>\n<type 'unicode'>\nPC・ソフト申請書08.09.24.txt\n<type 'unicode'>\n?日本語\n\nWhere the \"PC・ソフト申請書08.09.24.txt\" contained the text, \"日本語\".\n(I encoded the file as utf8 using windows notepad, I'm a little stumped as to why there's a '?' in the begining when printing. Something to do with how notepad saves utf8?)\nThe strings 'decode' method or the unicode() builtin can be used to convert an encoding into unicode.\nunicode_str = utf8_str.decode('utf8')\nunicode_str = unicode(utf8_str, 'utf8')\n\nAlso, if your dealing with encoded files you may want to use the codecs.open() function in place of the built-in open(). It allows you to define the encoding of the file, and will then use the given encoding to transparently decode the content to unicode.\nSo when you call content = codecs.open(\"myfile.txt\", \"r\", \"utf8\").read() content will be in unicode.\ncodecs.open:\nhttp://docs.python.org/library/codecs.html?#codecs.open\nIf I'm miss-understanding something please let me know.\nIf you haven't already I recommend reading Joel's article on unicode and encoding:\nhttp://www.joelonsoftware.com/articles/Unicode.html\n",
"Try this:\nimport sys\nprint repr(sys.argv[1].decode('UTF-8'))\n\nMaybe you have to substitute CP437 or CP1252 for UTF-8. You should be able to infer the proper encoding name from the registry key HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage\\OEMCP\n",
"The command line might be in Windows encoding. Try decoding the arguments into unicode objects:\nargs = [unicode(x, \"iso-8859-9\") for x in sys.argv]\n\n"
] |
[
30,
12,
2,
0
] |
[] |
[] |
[
"command_line",
"python",
"python_2.x",
"unicode",
"windows"
] |
stackoverflow_0000846850_command_line_python_python_2.x_unicode_windows.txt
|
Q:
Importing a python module to .net - "No module named signal"
I'm trying to import a Python module in a C# code like this:
var setup = Python.CreateRuntimeSetup(null);
var runtime = new ScriptRuntime(setup);
var engine = Python.GetEngine(runtime);
var module = engine.ImportModule("mymodule");
but I get an error saying "No module named signal", does this mean that IronPython just can't load the signal module, is it OS specific?
Can anyone think of a workaround?
A:
The 'signal' module is used to handle all that has to do with ... you guessed it: signals. There are special "messages" that the OS send to a process to tell it something: eg. Break, Kill, Terminate, etc... The exact set of message are generally OS specific, but as the signals python manual page states, python emulates BSD style interface, except for SIGCHLD.
Now, in CPython, the 'signal' module is a built-in as far as I can remember, it could possibly be that IronPython has not implemented it, in fact, a quick google and look on IronPython's site leads to this: IronPython and CPython differences (read it, in particular, the extension modules part!)
Possible workaround: edit your module not to use signals when in IronPython
|
Importing a python module to .net - "No module named signal"
|
I'm trying to import a Python module in a C# code like this:
var setup = Python.CreateRuntimeSetup(null);
var runtime = new ScriptRuntime(setup);
var engine = Python.GetEngine(runtime);
var module = engine.ImportModule("mymodule");
but I get an error saying "No module named signal", does this mean that IronPython just can't load the signal module, is it OS specific?
Can anyone think of a workaround?
|
[
"The 'signal' module is used to handle all that has to do with ... you guessed it: signals. There are special \"messages\" that the OS send to a process to tell it something: eg. Break, Kill, Terminate, etc... The exact set of message are generally OS specific, but as the signals python manual page states, python emulates BSD style interface, except for SIGCHLD.\nNow, in CPython, the 'signal' module is a built-in as far as I can remember, it could possibly be that IronPython has not implemented it, in fact, a quick google and look on IronPython's site leads to this: IronPython and CPython differences (read it, in particular, the extension modules part!)\nPossible workaround: edit your module not to use signals when in IronPython\n"
] |
[
2
] |
[] |
[] |
[
".net",
"ironpython",
"python"
] |
stackoverflow_0000847109_.net_ironpython_python.txt
|
Q:
User-defined derived data in Django
How do I let my users apply their own custom formula to a table of data to derive new fields?
I am working on a Django application which is going to store and process a lot of data for subscribed users on the open web. Think 100-10,000 sensor readings in one page request. I am going to be drawing graphs using this data and also showing tables containing it. I expect groups of sensors to be defined by my users, who will have registered themselves on my website (i.e they correspond with a django model).
I would like to allow the user to be able to create fields that are derived from their sensor data (as part of a setup process). For example, the user might know that their average house temperature is (temperature sensor1 + temperature sensor2) / 2 and want to show that on the graph. They might also want something more interesting like solar hot water heated is (temp out - temp in) * flow * conversion constant. I will then save these defined formulas for them and everyone else who views this page of sensor data.
The main question is how do I define the formula at the centre of the system. Do I just have a user-defined string to define the formula (say 100 chars long) and parse it myself - replace the user defined with an input sample and call it toast?
Update
In the end I got just the answer I asked for : A safe way to evaluate a stored user function on the server. Evaluating the same function also on the client when the function is being defined will be a great way to make the UI intuitive.
A:
I would work out what operations you want to support [+,-,*,/,(,),etc] and develop client side (javascript) to edit and apply those values to new fields of the data. I don't see the need to do any of this server-side and you will end up with a more responsive and enjoyable user experience as a result.
If you allow the user to save their formulas and re-load them when they revisit the site, you can get their browser to do all the calculations. Just provide some generic methods to add columns of data which are generated by applying one of their forumla's to your data.
I imagine the next step would be to allow them to apply those operations to the newly generated columns.
Have you considered posting their data into a google spreadsheet? This would save a lot of the development work as they already allow you to define formulas etc. and apply it to the data. I'm not too sure of the data limit (how much data you can post and operate on) mind you.
A:
Depends on who your clients are.
If this is "open to the public" on the WWW, you have to parse expressions yourself. You can use the Python compiler to compile Python syntax. You can also invent your own compiler for a subset of Python syntax. There are lots of examples; start with the ply project.
If this is in-house ("behind the firewall") let the post a piece of Python code and exec that code.
Give them an environment from math import * functionality available.
Fold the following around their supplied line of code:
def userFunc( col1, col2, col3, ... ):
result1= {{ their code goes here }}
return result1
Then you can exec the function definition and use the defined function without bad things happening.
While some folks like to crow that exec is "security problem", it's no more a security problem than user's sharing passwords, and admin's doing intentionally stupid things like deleting important files or turning the power off randomly while your programming is running.
exec is only a security problem if you allow anyone access to it. For in-house applications, you know the users. Train them.
A:
Another user asked a similar question in C.
In that post, Warren suggested that the formula could be parsed and converted from
(a + c) / b
Into reverse polish notation
a c + b /
Which is easier to process.
In this case, you could intercept the formula model's save and generate the postfix notation from the user-defined formula. Once you have postfix notation, it is fairly straightforward to write a loop that evaluates the formula from left to right.
As for implementation in Django, the core question remaining is how to map different input fields into the formula. The simple solution would be a model representing the derived field uses a many-to-many relationship with the symbol name ("a", "b" or "c") defined per-input.
If performance is really critical, you might somehow further pre-process the postfix formula before applying it to the data.
|
User-defined derived data in Django
|
How do I let my users apply their own custom formula to a table of data to derive new fields?
I am working on a Django application which is going to store and process a lot of data for subscribed users on the open web. Think 100-10,000 sensor readings in one page request. I am going to be drawing graphs using this data and also showing tables containing it. I expect groups of sensors to be defined by my users, who will have registered themselves on my website (i.e they correspond with a django model).
I would like to allow the user to be able to create fields that are derived from their sensor data (as part of a setup process). For example, the user might know that their average house temperature is (temperature sensor1 + temperature sensor2) / 2 and want to show that on the graph. They might also want something more interesting like solar hot water heated is (temp out - temp in) * flow * conversion constant. I will then save these defined formulas for them and everyone else who views this page of sensor data.
The main question is how do I define the formula at the centre of the system. Do I just have a user-defined string to define the formula (say 100 chars long) and parse it myself - replace the user defined with an input sample and call it toast?
Update
In the end I got just the answer I asked for : A safe way to evaluate a stored user function on the server. Evaluating the same function also on the client when the function is being defined will be a great way to make the UI intuitive.
|
[
"I would work out what operations you want to support [+,-,*,/,(,),etc] and develop client side (javascript) to edit and apply those values to new fields of the data. I don't see the need to do any of this server-side and you will end up with a more responsive and enjoyable user experience as a result.\nIf you allow the user to save their formulas and re-load them when they revisit the site, you can get their browser to do all the calculations. Just provide some generic methods to add columns of data which are generated by applying one of their forumla's to your data.\nI imagine the next step would be to allow them to apply those operations to the newly generated columns.\nHave you considered posting their data into a google spreadsheet? This would save a lot of the development work as they already allow you to define formulas etc. and apply it to the data. I'm not too sure of the data limit (how much data you can post and operate on) mind you.\n",
"Depends on who your clients are.\nIf this is \"open to the public\" on the WWW, you have to parse expressions yourself. You can use the Python compiler to compile Python syntax. You can also invent your own compiler for a subset of Python syntax. There are lots of examples; start with the ply project.\nIf this is in-house (\"behind the firewall\") let the post a piece of Python code and exec that code.\nGive them an environment from math import * functionality available.\nFold the following around their supplied line of code:\ndef userFunc( col1, col2, col3, ... ):\n result1= {{ their code goes here }}\n return result1\n\nThen you can exec the function definition and use the defined function without bad things happening.\nWhile some folks like to crow that exec is \"security problem\", it's no more a security problem than user's sharing passwords, and admin's doing intentionally stupid things like deleting important files or turning the power off randomly while your programming is running.\nexec is only a security problem if you allow anyone access to it. For in-house applications, you know the users. Train them.\n",
"Another user asked a similar question in C. \nIn that post, Warren suggested that the formula could be parsed and converted from \n(a + c) / b \n\nInto reverse polish notation\na c + b / \n\nWhich is easier to process. \nIn this case, you could intercept the formula model's save and generate the postfix notation from the user-defined formula. Once you have postfix notation, it is fairly straightforward to write a loop that evaluates the formula from left to right.\nAs for implementation in Django, the core question remaining is how to map different input fields into the formula. The simple solution would be a model representing the derived field uses a many-to-many relationship with the symbol name (\"a\", \"b\" or \"c\") defined per-input. \nIf performance is really critical, you might somehow further pre-process the postfix formula before applying it to the data.\n"
] |
[
2,
2,
0
] |
[] |
[] |
[
"django",
"python",
"user_defined_functions"
] |
stackoverflow_0000847201_django_python_user_defined_functions.txt
|
Q:
Exposing a C++ API to Python
I'm currently working on a project were I had to wrap the C++ classes with Python to be able to script the program. So my specific experience also involved embedding the Python interpreter in our program.
The alternatives I tried were:
Boost.Python
I liked the cleaner API produced by Boost.Python, but the fact that it would have required that users install an additional dependency made us switch to SWIG.
SWIG
SWIG's main advantage for us was that it doesn't require end users to install it to use the final program.
What have you used to do this, and what has been your experience with it?
A:
I've used both (for the same project): Boost is better integrated with the STL, and especially C++ exceptions. Also, its memory management mechanism (which tries to bridge C++ memory management and Python GC) is way more flexible than SWIG's. However, SWIG has much better documentation, no external dependencies, and if you get the library wrapped in SWIG for Python you're more than half-way there to getting a Java/Perl/Ruby wrapper as well.
I don't think there's a clear-cut choice: for smaller projects, I'd go with Boost.Python again, for larger long-lived projects, the extra investment in SWIG is worth it.
A:
EDIT - the Robin project is sadly abandoned, and won't be much use today
I've used Robin with great success.
Great integration with C++ types, and creates a single .cpp file to compile and include in your shared object.
A:
I suggest SIP. SIP is better than SWIG due to the following reasons:
For a given set of files, swig generates more duplicate (overhead) code than SIP. SIP manages to generate less duplicate (overhead) code by using a library file which can be statically or dynamically linked. In other words SIP has better scalability.
Execution time of SIP is much less than that of SWIG. Refer Python Wrapper Tools: A Performance Study. Unfortunately link appears broken. I have a personal copy which can be shared on request.
A:
pyrex or cython are also good and easy ways for mixing the two worlds.
Wrapping C++ using these tools is a bit trickier then wrapping C but it can be done. Here is the wiki page about it.
A:
A big plus for Boost::Python is that it allows for tab completion in the ipython shell: You import a C++ class, exposed by Boost directly, or you subclass it, and from then on, it really behaves like a pure Python class.
The downside: It takes so long to install and use Boost that all the Tab-completion time-saving won't ever amortize ;-(
So I prefer Swig: No bells and whistles, but works reliably after a short introductory example.
|
Exposing a C++ API to Python
|
I'm currently working on a project were I had to wrap the C++ classes with Python to be able to script the program. So my specific experience also involved embedding the Python interpreter in our program.
The alternatives I tried were:
Boost.Python
I liked the cleaner API produced by Boost.Python, but the fact that it would have required that users install an additional dependency made us switch to SWIG.
SWIG
SWIG's main advantage for us was that it doesn't require end users to install it to use the final program.
What have you used to do this, and what has been your experience with it?
|
[
"I've used both (for the same project): Boost is better integrated with the STL, and especially C++ exceptions. Also, its memory management mechanism (which tries to bridge C++ memory management and Python GC) is way more flexible than SWIG's. However, SWIG has much better documentation, no external dependencies, and if you get the library wrapped in SWIG for Python you're more than half-way there to getting a Java/Perl/Ruby wrapper as well.\nI don't think there's a clear-cut choice: for smaller projects, I'd go with Boost.Python again, for larger long-lived projects, the extra investment in SWIG is worth it.\n",
"EDIT - the Robin project is sadly abandoned, and won't be much use today\nI've used Robin with great success. \nGreat integration with C++ types, and creates a single .cpp file to compile and include in your shared object.\n",
"I suggest SIP. SIP is better than SWIG due to the following reasons:\n\nFor a given set of files, swig generates more duplicate (overhead) code than SIP. SIP manages to generate less duplicate (overhead) code by using a library file which can be statically or dynamically linked. In other words SIP has better scalability.\nExecution time of SIP is much less than that of SWIG. Refer Python Wrapper Tools: A Performance Study. Unfortunately link appears broken. I have a personal copy which can be shared on request.\n\n",
"pyrex or cython are also good and easy ways for mixing the two worlds.\nWrapping C++ using these tools is a bit trickier then wrapping C but it can be done. Here is the wiki page about it.\n",
"A big plus for Boost::Python is that it allows for tab completion in the ipython shell: You import a C++ class, exposed by Boost directly, or you subclass it, and from then on, it really behaves like a pure Python class.\nThe downside: It takes so long to install and use Boost that all the Tab-completion time-saving won't ever amortize ;-(\nSo I prefer Swig: No bells and whistles, but works reliably after a short introductory example.\n"
] |
[
23,
18,
7,
5,
2
] |
[] |
[] |
[
"boost",
"c++",
"python",
"swig"
] |
stackoverflow_0000276761_boost_c++_python_swig.txt
|
Q:
How to write a vb.net code to compile C/C++ programs?
I'm trying to make a vb.net application that has got 2 textboxes, 7 radio buttons and 2 buttons(one named compile and the other 'run'). How can I load the content of a C/C++(or any programming language) file into the 1st textbox and on clicking the compile button, i should be able to show the errors or the C/C++ program in the 2nd textbox. On clicking Run, I should be able to show the output in the 2nd textbox. In short, I want to use the 2nd textbox as a terminal/console. The radio buttons are 4 selecting the language C or C++ or python or C# or java or perl or vb.
Are the compilers of all these languages present in .net? If so how can I call them?
A:
Look at the System.IO namespace for clues as to how you go about loading the contents of a file into a text box. In particular, the File class.
System.IO.File Class
Look at the System.Diagnostics namespace for clues as to how to go about launching a process and capturing the output. In particular, the Process class.
System.Diagnostics.Process Class
This SO page...
Capturing the Console Output in .NET (C#)
... will give you some more info around capturing console output.
A:
Compiling can be done by calling cl.exe which comes with Visual Studio. Of course you could also use GCC instead.
|
How to write a vb.net code to compile C/C++ programs?
|
I'm trying to make a vb.net application that has got 2 textboxes, 7 radio buttons and 2 buttons(one named compile and the other 'run'). How can I load the content of a C/C++(or any programming language) file into the 1st textbox and on clicking the compile button, i should be able to show the errors or the C/C++ program in the 2nd textbox. On clicking Run, I should be able to show the output in the 2nd textbox. In short, I want to use the 2nd textbox as a terminal/console. The radio buttons are 4 selecting the language C or C++ or python or C# or java or perl or vb.
Are the compilers of all these languages present in .net? If so how can I call them?
|
[
"Look at the System.IO namespace for clues as to how you go about loading the contents of a file into a text box. In particular, the File class.\nSystem.IO.File Class\nLook at the System.Diagnostics namespace for clues as to how to go about launching a process and capturing the output. In particular, the Process class.\nSystem.Diagnostics.Process Class\nThis SO page...\nCapturing the Console Output in .NET (C#)\n... will give you some more info around capturing console output.\n",
"Compiling can be done by calling cl.exe which comes with Visual Studio. Of course you could also use GCC instead.\n"
] |
[
2,
1
] |
[] |
[] |
[
"c",
"c#",
"c++",
"python",
"vb.net"
] |
stackoverflow_0000847860_c_c#_c++_python_vb.net.txt
|
Q:
Convert C++ Header Files To Python
I have a C++ header that contains #define statements, Enums and Structures. I have tried using the h2py.py script that is included with Python to no avail (except giving me the #defines converted). Any help would be greatly appreciated.
A:
I don't know h2py, but you may want to look at 'ctypes' and 'ctypeslib'. ctypes is included with python 2.5+, and is targeted at creating binary compatibility with c-structs.
If you add ctypeslib, you get a sub-tool called codegen, which has a 'h2xml.py' script, and a 'xml2py.py', the combination of which will auto-generate the python code you're looking for from C++ headers.
ctypeslib:http://pypi.python.org/pypi/ctypeslib/0.5.4a
h2xml.py will require another tool called gccxml: http://www.gccxml.org/HTML/Index.html
it's best to check out (via CVS) the latest version of gccxml and build it yourself (actually easier done than said). The pre-packaged version is old.
A:
Just found pycparser. May be useful.
A:
From what I can tell, h2py.py isn't intended to convert anything other than #define macros. I did run across cppheaderparser, which might be worth a look.
A:
Where did you get the idea that h2py had anything to do with structs or enums?
From the source
# Read #define's and translate to Python code.
# Handle #include statements.
# Handle #define macros with one argument.
The words 'enum' and 'struct' never appear in the module.
|
Convert C++ Header Files To Python
|
I have a C++ header that contains #define statements, Enums and Structures. I have tried using the h2py.py script that is included with Python to no avail (except giving me the #defines converted). Any help would be greatly appreciated.
|
[
"I don't know h2py, but you may want to look at 'ctypes' and 'ctypeslib'. ctypes is included with python 2.5+, and is targeted at creating binary compatibility with c-structs.\nIf you add ctypeslib, you get a sub-tool called codegen, which has a 'h2xml.py' script, and a 'xml2py.py', the combination of which will auto-generate the python code you're looking for from C++ headers.\nctypeslib:http://pypi.python.org/pypi/ctypeslib/0.5.4a\nh2xml.py will require another tool called gccxml: http://www.gccxml.org/HTML/Index.html\nit's best to check out (via CVS) the latest version of gccxml and build it yourself (actually easier done than said). The pre-packaged version is old.\n",
"Just found pycparser. May be useful.\n",
"From what I can tell, h2py.py isn't intended to convert anything other than #define macros. I did run across cppheaderparser, which might be worth a look.\n",
"Where did you get the idea that h2py had anything to do with structs or enums?\nFrom the source\n# Read #define's and translate to Python code.\n# Handle #include statements.\n# Handle #define macros with one argument.\n\nThe words 'enum' and 'struct' never appear in the module.\n"
] |
[
11,
2,
1,
0
] |
[] |
[] |
[
"c++",
"data_structures",
"enums",
"header",
"python"
] |
stackoverflow_0000374217_c++_data_structures_enums_header_python.txt
|
Q:
Rename invalid filename in XP via Python
My problem is similar to Python's os.path choking on Hebrew filenames
however, I don't know the original encoding of the filename I need to rename (unlike the other post he knew it was Hebrew originally).
I was doing data recovery for a client and copied over the files to my XP SP3 machine,
and some of the file names have "?" replacing/representing invalid characters.
I tried to use Python to os.rename the files since I know it has unicode support, however, when I tell python to rename the files, it seems it's unable to pass a valid file name back to the windows API.
i.e.:
>>> os.chdir(r'F:\recovery\My Music')
>>> os.listdir(u'.')
[u'Don?t Be Them.mp3', u'That?s A Soldier.mp3']
>>> blah=os.listdir(u'.')
>>> blah[0]
Don?t Be Them.mp3
>>> os.rename(blah[0],'dont be them.mp3')
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
os.rename(blah[0],'dont be them.mp3')
WindowsError: [Error 123] The filename, directory name, or
volume label syntax is incorrect
I'm using Python 2.6, on Win XP SP3, with whatever encoding is standard XP behavior for US/English.
Is there a way to handle these renames without knowing the original language?
A:
'?' is not valid character for filenames. That is the reason while your approach failed.
You may try to use DOS short filenames:
import win32api
filelist = win32api.FindFiles(r'F:/recovery/My Music/*.*')
# this will extract "short names" from WIN32_FIND_DATA structure
filelist = [i[9] if i[9] else i[8] for i in filelist]
# EXAMPLE:
# this should rename all files in 'filelist' to 1.mp3, 2.mp3, 3.mp3, ...
for (number, filename) in enumerate(filelist):
os.rename(filaname, '%d.mp3' % (number))
A:
Try passing a unicode string:
os.rename(blah[0], u'dont be them.mp3')
|
Rename invalid filename in XP via Python
|
My problem is similar to Python's os.path choking on Hebrew filenames
however, I don't know the original encoding of the filename I need to rename (unlike the other post he knew it was Hebrew originally).
I was doing data recovery for a client and copied over the files to my XP SP3 machine,
and some of the file names have "?" replacing/representing invalid characters.
I tried to use Python to os.rename the files since I know it has unicode support, however, when I tell python to rename the files, it seems it's unable to pass a valid file name back to the windows API.
i.e.:
>>> os.chdir(r'F:\recovery\My Music')
>>> os.listdir(u'.')
[u'Don?t Be Them.mp3', u'That?s A Soldier.mp3']
>>> blah=os.listdir(u'.')
>>> blah[0]
Don?t Be Them.mp3
>>> os.rename(blah[0],'dont be them.mp3')
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
os.rename(blah[0],'dont be them.mp3')
WindowsError: [Error 123] The filename, directory name, or
volume label syntax is incorrect
I'm using Python 2.6, on Win XP SP3, with whatever encoding is standard XP behavior for US/English.
Is there a way to handle these renames without knowing the original language?
|
[
"'?' is not valid character for filenames. That is the reason while your approach failed.\nYou may try to use DOS short filenames:\nimport win32api\nfilelist = win32api.FindFiles(r'F:/recovery/My Music/*.*')\n\n# this will extract \"short names\" from WIN32_FIND_DATA structure\nfilelist = [i[9] if i[9] else i[8] for i in filelist]\n\n# EXAMPLE: \n# this should rename all files in 'filelist' to 1.mp3, 2.mp3, 3.mp3, ...\nfor (number, filename) in enumerate(filelist):\n os.rename(filaname, '%d.mp3' % (number)) \n\n",
"Try passing a unicode string:\nos.rename(blah[0], u'dont be them.mp3')\n\n"
] |
[
2,
0
] |
[] |
[] |
[
"python",
"unicode",
"windows_xp"
] |
stackoverflow_0000845926_python_unicode_windows_xp.txt
|
Q:
OOP: good class design
My question is related to this one: Python tool that builds a dependency diagram for methods of a class.
After not finding any tools I wrote a quick hack myself: I've used the compiler module, I've parsed the source code into an Abstract Source Tree and I've walked it to collect dependencies between class methods. My script generated an input file for graphviz, which was used to generate a dependency graph that looks like this.
At this point I've got stuck. I've realized that I have no idea how to refactor the class to make it less complicated. I simply don't know what should I aim to. For example, in theory of relational databases there are a couple of simple rules that are used to bring a database to a normal form. What about some similar theory concerning the good class design (in terms of dependencies between its methods)? Is this topic covered somewhere so I could study it?
A:
We follow the following principles when designing classes:
The Single Responsibility Principle: A class (or method) should have only one reason to change.
The Open Closed Principle: A class (or method) should be open for extension and closed for modification.
The Liskov Substitution Principle: Subtypes must be substitutable for their base types.
The Interface Segregation Principle: Clients should not be forced to depend upon methods that they do not use. Interfaces should belong to clients.
The Dependency Inversion Principle: Abstractions should not depend on details. Details should depend on abstractions.
Edit: Design patterns are helpful in getting your code to comply with these principles. I have found it very helpful to understand the principles first and then to look at the patterns and understand how the patterns bring your code in line with the principles.
A:
It's often not possible to say whats 'correct' or 'wrong' when it comes to class design. There are many guidelines, patterns, recommendation etc. about this topic, but at the end of the day, imho, it's a lot about experience with past projects. My experience is that it's best to not worry to much about it, and gradually improve your code/structure in small steps. Experiment and see how some ideas/changes feel/look like. And it's of course always a good idea to learn from others. read a lot of code and analyse it, try to understand :).
If you wanna read about the theory I can recommend Craig Larmanns 'Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development' Amazon. He covers several parts of your question, gives some rough guidlines and shows them using an example application. I liked the book.
Could you upload your app somewhere? Perhaps on github or so, perhaps you could ask for some concrete advices.
A:
Design Patterns has become the defacto standard for good class design. Generally, each pattern has a particular use case, or scenario, which it applies to. If you can identify this in your code, you can use the pattern to create something that makes more sense, and usually has less dependencies.
Refactoring is the tool that you would use to accomplish these sweeping changes. A good IDE will help you to refactor.
A:
Try making each method easily unit-testable. I find this always drives my designs towards more readability/understandability. There are numerous OOAD rules -- SRP, DRY, etc. Try to keep those in mind as you refactor.
A:
I recommend the book "Refactoring" by Martin Fowler for tons of practical examples of iteratively converting poor design to good design.
|
OOP: good class design
|
My question is related to this one: Python tool that builds a dependency diagram for methods of a class.
After not finding any tools I wrote a quick hack myself: I've used the compiler module, I've parsed the source code into an Abstract Source Tree and I've walked it to collect dependencies between class methods. My script generated an input file for graphviz, which was used to generate a dependency graph that looks like this.
At this point I've got stuck. I've realized that I have no idea how to refactor the class to make it less complicated. I simply don't know what should I aim to. For example, in theory of relational databases there are a couple of simple rules that are used to bring a database to a normal form. What about some similar theory concerning the good class design (in terms of dependencies between its methods)? Is this topic covered somewhere so I could study it?
|
[
"We follow the following principles when designing classes:\n\nThe Single Responsibility Principle: A class (or method) should have only one reason to change.\nThe Open Closed Principle: A class (or method) should be open for extension and closed for modification.\nThe Liskov Substitution Principle: Subtypes must be substitutable for their base types.\nThe Interface Segregation Principle: Clients should not be forced to depend upon methods that they do not use. Interfaces should belong to clients.\nThe Dependency Inversion Principle: Abstractions should not depend on details. Details should depend on abstractions.\n\nEdit: Design patterns are helpful in getting your code to comply with these principles. I have found it very helpful to understand the principles first and then to look at the patterns and understand how the patterns bring your code in line with the principles.\n",
"It's often not possible to say whats 'correct' or 'wrong' when it comes to class design. There are many guidelines, patterns, recommendation etc. about this topic, but at the end of the day, imho, it's a lot about experience with past projects. My experience is that it's best to not worry to much about it, and gradually improve your code/structure in small steps. Experiment and see how some ideas/changes feel/look like. And it's of course always a good idea to learn from others. read a lot of code and analyse it, try to understand :). \nIf you wanna read about the theory I can recommend Craig Larmanns 'Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development' Amazon. He covers several parts of your question, gives some rough guidlines and shows them using an example application. I liked the book. \nCould you upload your app somewhere? Perhaps on github or so, perhaps you could ask for some concrete advices.\n",
"Design Patterns has become the defacto standard for good class design. Generally, each pattern has a particular use case, or scenario, which it applies to. If you can identify this in your code, you can use the pattern to create something that makes more sense, and usually has less dependencies.\nRefactoring is the tool that you would use to accomplish these sweeping changes. A good IDE will help you to refactor.\n",
"Try making each method easily unit-testable. I find this always drives my designs towards more readability/understandability. There are numerous OOAD rules -- SRP, DRY, etc. Try to keep those in mind as you refactor.\n",
"I recommend the book \"Refactoring\" by Martin Fowler for tons of practical examples of iteratively converting poor design to good design.\n"
] |
[
30,
3,
1,
0,
0
] |
[] |
[] |
[
"language_agnostic",
"oop",
"python"
] |
stackoverflow_0000845966_language_agnostic_oop_python.txt
|
Q:
Javascript graphing library to draw a region
As a keen windsurfer, I'm interested in how windy the next few weeks are going to be. To that end, I've been writing a little app to scrape a popular weather site (personal use only - not relaying the information or anything) and collate the data into a single graph so that I can easily see when's going to be worth heading out.
I have the back end working but need a way to display the data. My scraper currently gives me two series of data which tell me how strong the general wind is and how strong it's likely to gust to. What I'd like to do next is display those two data sets as a pair of lines in a graph and shade the region between them.
I was considering using something like the flot library to display the data. The only problem is that I can't see a way to shade an area between two lines?
If anyone has suggestions of how to do this in flot or other libraries or graphing techniques (I have DJango on my server so anything pythonic or javascripty should be fine), I'd be interested to hear them. Ideally this will be a javascript solution to avoid having to serve up images.
A:
Take a look at the Google chart API's. They make this sort of thing pretty easy. Without some example code, I would have a hard time giving you an example, but Google has nice one on the docs.
A:
You should check out Dojo. It looks like it'd be pretty easy for you to do, just plot the bottom line with the same fill color as the background. That should get you the effect you're going for.
http://dojocampus.org/explorer/#Dojox_Charting_2D
A:
I'd use open flash chart, you just have to create a JSON with the data and then you've to all the flashy coolness in your page....
http://teethgrinder.co.uk/open-flash-chart-2/
|
Javascript graphing library to draw a region
|
As a keen windsurfer, I'm interested in how windy the next few weeks are going to be. To that end, I've been writing a little app to scrape a popular weather site (personal use only - not relaying the information or anything) and collate the data into a single graph so that I can easily see when's going to be worth heading out.
I have the back end working but need a way to display the data. My scraper currently gives me two series of data which tell me how strong the general wind is and how strong it's likely to gust to. What I'd like to do next is display those two data sets as a pair of lines in a graph and shade the region between them.
I was considering using something like the flot library to display the data. The only problem is that I can't see a way to shade an area between two lines?
If anyone has suggestions of how to do this in flot or other libraries or graphing techniques (I have DJango on my server so anything pythonic or javascripty should be fine), I'd be interested to hear them. Ideally this will be a javascript solution to avoid having to serve up images.
|
[
"Take a look at the Google chart API's. They make this sort of thing pretty easy. Without some example code, I would have a hard time giving you an example, but Google has nice one on the docs.\n",
"You should check out Dojo. It looks like it'd be pretty easy for you to do, just plot the bottom line with the same fill color as the background. That should get you the effect you're going for.\nhttp://dojocampus.org/explorer/#Dojox_Charting_2D\n",
"I'd use open flash chart, you just have to create a JSON with the data and then you've to all the flashy coolness in your page....\nhttp://teethgrinder.co.uk/open-flash-chart-2/\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"django",
"graph",
"javascript",
"python",
"screen_scraping"
] |
stackoverflow_0000848604_django_graph_javascript_python_screen_scraping.txt
|
Q:
Deploying Python via CGI
How do I deploy a Python project to a webserver that supports Python via CGI? I'm well versed in PHP, but do not understand CGI's relation to Python in the deployment process.
Any resource links are appreciated.
The web host in question is GoDaddy.
A:
Generally, we use mod_wsgi to make a Python application respond to CGI.
PHP has a special role -- the language runtime IS a CGI application.
Python does not have this special role. Python -- by default -- is not a CGI application. It requires a piece of glue to play well with Apache. mod_wsgi is this glue.
A:
To actually answer your question about deploying python as CGI (while it does not make a lot of sense on a high activity system - there are occasions where it does the job just fine) you just make sure that your files are executable, have the correct extension and then follow this tutorial. It is what I used to learn from.
EDIT: To be clear - I recommend that you look into Django to deploy web based python applications.
|
Deploying Python via CGI
|
How do I deploy a Python project to a webserver that supports Python via CGI? I'm well versed in PHP, but do not understand CGI's relation to Python in the deployment process.
Any resource links are appreciated.
The web host in question is GoDaddy.
|
[
"Generally, we use mod_wsgi to make a Python application respond to CGI. \nPHP has a special role -- the language runtime IS a CGI application.\nPython does not have this special role. Python -- by default -- is not a CGI application. It requires a piece of glue to play well with Apache. mod_wsgi is this glue.\n",
"To actually answer your question about deploying python as CGI (while it does not make a lot of sense on a high activity system - there are occasions where it does the job just fine) you just make sure that your files are executable, have the correct extension and then follow this tutorial. It is what I used to learn from.\nEDIT: To be clear - I recommend that you look into Django to deploy web based python applications.\n"
] |
[
3,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0000849384_python.txt
|
Q:
Standard non-code resource location for python packages
This should be a common scenario, but could not find any relevant post yet..
I plan to deploy a Python library (I guess the same applies to regular applications) which makes use of some images and other resource files. What is the standard location for such items? I imagine, for project Foo, the choices would be
Have resources directory in the source repository and then move files to /usr/share/foo/
Place resources directly inside the python package that goes under /usr/lib/python-<version>/foo/
Any suggestions?
Edit: As suggested, clarifying that the main platform this will be running on is Linux.
A:
This question is somewhat incomplete, because a proper answer would depend on the underlying operating system, as each has its own modus operandi. In linux (and most unix based OSs) for example /usr/share/foo or /usr/local/share/foo would be the standard. In OS X you can do the same, but I would think "/Library/Application Support/Foo" (although that's usually for storing settings and whatnot) would be the place to put such things, though if you're writing libraries following the "Framework" idea, all the resources would be included in the /Library/Frameworks/Foo.Framework" ... Apps on OS X on the other hand should keeps all there resources within the Resources directory inside Foo.app
A:
We put non .py files in /opt/foo/foo-1.2/...
Except, of course, for static media that is served by Apache, that goes to /var/www/html/foo/foo-1.1/media/...
Except, of course, for customer-specific configuration files. They go to
/var/opt/customer/foo/...
Those follow the Linux standards as I understand them.
We try to stay away from /usr/lib/ and /lib kinds of locations because those feel like they're part of the distribution. We lean toward /opt and /var because they're clearly separated from the linux distro directories.
A:
The standard location is where your standard libs goes. But it doesn't sound to me from what you've written, that you'll want your python lib there. I think you should try out Virtualenv.
If you don't want to go through all the trouble (well, it really just amounts to sudo easy_install virtualenv for you), you could try to just dump your python lib in any dir in your ~/ and do something along the lines of
import sys
sys.path.append( '/full/path/to/your/lib/goes/here')
to any given application that uses your lib.
Please bear in mind, that the examples given are for test-purposes only. For anything live-ish, I would recommend that you use distutil. Examples of use are given here.
|
Standard non-code resource location for python packages
|
This should be a common scenario, but could not find any relevant post yet..
I plan to deploy a Python library (I guess the same applies to regular applications) which makes use of some images and other resource files. What is the standard location for such items? I imagine, for project Foo, the choices would be
Have resources directory in the source repository and then move files to /usr/share/foo/
Place resources directly inside the python package that goes under /usr/lib/python-<version>/foo/
Any suggestions?
Edit: As suggested, clarifying that the main platform this will be running on is Linux.
|
[
"This question is somewhat incomplete, because a proper answer would depend on the underlying operating system, as each has its own modus operandi. In linux (and most unix based OSs) for example /usr/share/foo or /usr/local/share/foo would be the standard. In OS X you can do the same, but I would think \"/Library/Application Support/Foo\" (although that's usually for storing settings and whatnot) would be the place to put such things, though if you're writing libraries following the \"Framework\" idea, all the resources would be included in the /Library/Frameworks/Foo.Framework\" ... Apps on OS X on the other hand should keeps all there resources within the Resources directory inside Foo.app\n",
"We put non .py files in /opt/foo/foo-1.2/...\nExcept, of course, for static media that is served by Apache, that goes to /var/www/html/foo/foo-1.1/media/...\nExcept, of course, for customer-specific configuration files. They go to\n/var/opt/customer/foo/...\nThose follow the Linux standards as I understand them. \nWe try to stay away from /usr/lib/ and /lib kinds of locations because those feel like they're part of the distribution. We lean toward /opt and /var because they're clearly separated from the linux distro directories.\n",
"The standard location is where your standard libs goes. But it doesn't sound to me from what you've written, that you'll want your python lib there. I think you should try out Virtualenv.\nIf you don't want to go through all the trouble (well, it really just amounts to sudo easy_install virtualenv for you), you could try to just dump your python lib in any dir in your ~/ and do something along the lines of\nimport sys\nsys.path.append( '/full/path/to/your/lib/goes/here')\n\nto any given application that uses your lib.\nPlease bear in mind, that the examples given are for test-purposes only. For anything live-ish, I would recommend that you use distutil. Examples of use are given here.\n"
] |
[
2,
2,
0
] |
[] |
[] |
[
"location",
"package",
"python",
"resources",
"shared"
] |
stackoverflow_0000849334_location_package_python_resources_shared.txt
|
Q:
Performing Photoshop's "Luminosity" filter programmatically
I have two JPEG's and would like to overlay one on the other with the same results as the "Luminosity" mode available in Photoshop (and Fireworks). You can read more about Luminosity mode here: http://www.adobetutorialz.com/articles/662/1/Photoshop%92s-Luminosity-Mode
How can I do this? Programming language doesn't matter much, but I am most fluent with Python and PHP (in that order). Python Imaging Library seems like a perfect fit, but luminosity is not a built-in function and I do not know the proper procedure. See http://effbot.org/imagingbook/imagechops.htm
A:
First you need to understand what Photoshop does.
It preserves under layer perceptual color information and replaces it's luminosity with the top layer's perceptual luminosity information. To do that, you need to convert the images to the right color space.
Here is the shoping list of things you will need to do if you decide to implement everything by yourself:
Load both the source and target JPEGs
Convert the pixels from RGB color space to Lab color space (or any other color space with luminosirty information)
Preserve target color channels and replace its luminosity channel by source's luminosity
Convert back to RGB space
Save the JPEG
If you think Lab is too complicated, you can also use HSL color space, it's much simpler but it will give inferior results.
A:
In pseudo-code:
foreach rgb_pixel1, rgb_pixel2 in image1, image2 {
hsl1 = RgbToHsl(rgb_pixel1);
hsl2 = RgbToHsl(rgb_pixel2);
hsl3 = hsl(hsl1.h, hsl1.s, hsl2.l);
output_rgb = HslToRgb(hsl3);
}
Conversion from rgb to hsl and back is here.
A:
I don't know about this specific filter but I can tell you how to follow Coincoin steps in PIL. I didn't actually run the code, but you can use it as a reference:
Load both the source and target JPEGs
from PIL import Image
img1 = Image.open('image1.jpg')
img2 = Image.open('image2.jpg')
Convert the pixels from RGB color space to Lab color space (or any other color space with luminosirty information)
# Color matrix for Lab
colorMatrix = (
x1, y1, z1, 0,
x2, y2, z2, 0,
x3, y3, z3, 0
)
img1 = img1.convert("RGB", colorMatrix)
img2 = img2.convert("RGB", colorMatrix)
Preserve target color channels and replace its luminosity channel by source's luminosity
l1, a1, b1 = img1.split()
l2, a2, b2 = img2.split()
img1.putdata(zip(l1.getdata(), a2.getdata(), b2.getdata()))
Convert back to RGB space
# Color matrix for RGB
RGBcolorMatrix = (
x1, y1, z1, 0,
x2, y2, z2, 0,
x3, y3, z3, 0
)
img1 = img1.convert("RGB", RGBcolorMatrix)
Save the JPEG
img1.save('new_image.jpg')
A:
The Gimp would be another option - it has a scripting interface ans a python api - here is an article on luminosity and the Gimp. Not sure if it is the same effect you are going for though.
A:
You could have a look at the OpenCV image processing library. It has Python bindings and handles a lot of these lower level image manipulation tasks for you, or at least makes them easier.
|
Performing Photoshop's "Luminosity" filter programmatically
|
I have two JPEG's and would like to overlay one on the other with the same results as the "Luminosity" mode available in Photoshop (and Fireworks). You can read more about Luminosity mode here: http://www.adobetutorialz.com/articles/662/1/Photoshop%92s-Luminosity-Mode
How can I do this? Programming language doesn't matter much, but I am most fluent with Python and PHP (in that order). Python Imaging Library seems like a perfect fit, but luminosity is not a built-in function and I do not know the proper procedure. See http://effbot.org/imagingbook/imagechops.htm
|
[
"First you need to understand what Photoshop does.\nIt preserves under layer perceptual color information and replaces it's luminosity with the top layer's perceptual luminosity information. To do that, you need to convert the images to the right color space.\nHere is the shoping list of things you will need to do if you decide to implement everything by yourself:\n\nLoad both the source and target JPEGs\nConvert the pixels from RGB color space to Lab color space (or any other color space with luminosirty information)\nPreserve target color channels and replace its luminosity channel by source's luminosity\nConvert back to RGB space\nSave the JPEG\n\nIf you think Lab is too complicated, you can also use HSL color space, it's much simpler but it will give inferior results.\n",
"In pseudo-code:\nforeach rgb_pixel1, rgb_pixel2 in image1, image2 {\n hsl1 = RgbToHsl(rgb_pixel1);\n hsl2 = RgbToHsl(rgb_pixel2);\n hsl3 = hsl(hsl1.h, hsl1.s, hsl2.l);\n output_rgb = HslToRgb(hsl3);\n}\n\nConversion from rgb to hsl and back is here.\n",
"I don't know about this specific filter but I can tell you how to follow Coincoin steps in PIL. I didn't actually run the code, but you can use it as a reference:\nLoad both the source and target JPEGs\nfrom PIL import Image\nimg1 = Image.open('image1.jpg')\nimg2 = Image.open('image2.jpg')\n\nConvert the pixels from RGB color space to Lab color space (or any other color space with luminosirty information)\n# Color matrix for Lab\ncolorMatrix = (\n x1, y1, z1, 0,\n x2, y2, z2, 0,\n x3, y3, z3, 0\n)\nimg1 = img1.convert(\"RGB\", colorMatrix)\nimg2 = img2.convert(\"RGB\", colorMatrix)\n\nPreserve target color channels and replace its luminosity channel by source's luminosity\nl1, a1, b1 = img1.split()\nl2, a2, b2 = img2.split()\nimg1.putdata(zip(l1.getdata(), a2.getdata(), b2.getdata()))\n\nConvert back to RGB space\n# Color matrix for RGB\nRGBcolorMatrix = (\n x1, y1, z1, 0,\n x2, y2, z2, 0,\n x3, y3, z3, 0\n)\nimg1 = img1.convert(\"RGB\", RGBcolorMatrix)\n\nSave the JPEG\nimg1.save('new_image.jpg')\n\n",
"The Gimp would be another option - it has a scripting interface ans a python api - here is an article on luminosity and the Gimp. Not sure if it is the same effect you are going for though.\n",
"You could have a look at the OpenCV image processing library. It has Python bindings and handles a lot of these lower level image manipulation tasks for you, or at least makes them easier.\n"
] |
[
5,
1,
1,
0,
0
] |
[] |
[] |
[
"image",
"image_processing",
"php",
"python",
"python_imaging_library"
] |
stackoverflow_0000849654_image_image_processing_php_python_python_imaging_library.txt
|
Q:
Python multiprocessing on Python 2.6 Win32 (xp)
I tried to copy this example from this Multiprocessing lecture by jesse noller (as recommended in another SO post)[http://pycon.blip.tv/file/1947354?filename=Pycon-IntroductionToMultiprocessingInPython630.mp4]
But for some reason I'm getting an error, as though it's ignoring my function definitions:
I'm on Windows XP (win32) which I know has restrictions with regards to the multiprocessing library in 2.6 that requires everything be pickleable
from multiprocessing import Process
import time
def sleeper(wait):
print 'Sleeping for %d seconds' % (wait,)
time.sleep(wait)
print 'Sleeping complete'
def doIT():
p = Process(target=sleeper, args=(9,))
p.start()
time.sleep(5)
p.join()
if __name__ == '__main__':
doIT()
Output:
Evaluating mypikklez.py
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Python26\lib\multiprocessing\forking.py", line 342, in main
self = load(from_parent)
File "C:\Python26\lib\pickle.py", line 1370, in load
return Unpickler(file).load()
File "C:\Python26\lib\pickle.py", line 858, in load
dispatch[key](self)
File "C:\Python26\lib\pickle.py", line 1090, in load_global
klass = self.find_class(module, name)
File "C:\Python26\lib\pickle.py", line 1126, in find_class
klass = getattr(mod, name)
AttributeError: 'module' object has no attribute 'sleeper'
The error causing the issue is : AttributeError: 'module' object has no attribute 'sleeper'
As simple of a function as it is I can't understand what would be the hold up.
This is just for self-teaching purposes of basic concepts. I'm not trying to pre-optimize any real world issue.
Thanks.
A:
Seems from the traceback that you are running the code directly into the python interpreter (REPL).
Don't do that. Save the code in a file and run it from the file instead, with the command:
python myfile.py
That will solve your issue.
As an unrelated note, this line is wrong:
print 'Sleeping for ' + wait + ' seconds'
It should be:
print 'Sleeping for %d seconds' % (wait,)
Because you can't concatenate string and int objects (python is strongly typed)
|
Python multiprocessing on Python 2.6 Win32 (xp)
|
I tried to copy this example from this Multiprocessing lecture by jesse noller (as recommended in another SO post)[http://pycon.blip.tv/file/1947354?filename=Pycon-IntroductionToMultiprocessingInPython630.mp4]
But for some reason I'm getting an error, as though it's ignoring my function definitions:
I'm on Windows XP (win32) which I know has restrictions with regards to the multiprocessing library in 2.6 that requires everything be pickleable
from multiprocessing import Process
import time
def sleeper(wait):
print 'Sleeping for %d seconds' % (wait,)
time.sleep(wait)
print 'Sleeping complete'
def doIT():
p = Process(target=sleeper, args=(9,))
p.start()
time.sleep(5)
p.join()
if __name__ == '__main__':
doIT()
Output:
Evaluating mypikklez.py
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Python26\lib\multiprocessing\forking.py", line 342, in main
self = load(from_parent)
File "C:\Python26\lib\pickle.py", line 1370, in load
return Unpickler(file).load()
File "C:\Python26\lib\pickle.py", line 858, in load
dispatch[key](self)
File "C:\Python26\lib\pickle.py", line 1090, in load_global
klass = self.find_class(module, name)
File "C:\Python26\lib\pickle.py", line 1126, in find_class
klass = getattr(mod, name)
AttributeError: 'module' object has no attribute 'sleeper'
The error causing the issue is : AttributeError: 'module' object has no attribute 'sleeper'
As simple of a function as it is I can't understand what would be the hold up.
This is just for self-teaching purposes of basic concepts. I'm not trying to pre-optimize any real world issue.
Thanks.
|
[
"Seems from the traceback that you are running the code directly into the python interpreter (REPL).\nDon't do that. Save the code in a file and run it from the file instead, with the command:\npython myfile.py\n\nThat will solve your issue.\n\nAs an unrelated note, this line is wrong:\nprint 'Sleeping for ' + wait + ' seconds'\n\nIt should be:\nprint 'Sleeping for %d seconds' % (wait,)\n\nBecause you can't concatenate string and int objects (python is strongly typed)\n"
] |
[
4
] |
[] |
[] |
[
"multiprocessing",
"python",
"python_2.6",
"winapi"
] |
stackoverflow_0000850424_multiprocessing_python_python_2.6_winapi.txt
|
Q:
Can a Python module use the imports from another file?
I have something like this:
# a.py
import os
class A:
...
# b.py
import a
class B(A):
...
In class B (b.py) I'd like to be able to use the modules imported in a.py (os in this case). Is it possible to achieve this behavior in Python or should I import the modules in both files?
Edit: I'm not worried about the import times, my problem is the visual clutter that the block of imports puts on the files. I end up having stuff like this in every controller (RequestHandler):
from django.utils import simplejson
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext import db
That's what I'd like to avoid.
A:
Yes you can use the imports from the other file by going a.os.
However, the pythonic way is to just import the exact modules you need without making a chain out of it (which can lead to circular references).
When you import a module, the code is compiled and inserted into a dictionary of names -> module objects. The dictionary is located at sys.modules.
import sys
sys.modules
>>> pprint.pprint(sys.modules)
{'UserDict': <module 'UserDict' from 'C:\python26\lib\UserDict.pyc'>,
'__builtin__': <module '__builtin__' (built-in)>,
'__main__': <module '__main__' (built-in)>,
'_abcoll': <module '_abcoll' from 'C:\python26\lib\_abcoll.pyc'>,
# the rest omitted for brevity
When you try to import the module again, Python will check the dictionary to see if its already there. If it is, it will return the already compiled module object to you. Otherwise, it will compile the code, and insert it in sys.modules.
Since dictionaries are implemented as hash tables, this lookup is very quick and takes up negligible time compared to the risk of creating circular references.
Edit: I'm not worried about the import
times, my problem is the visual
clutter that the block of imports puts
on the files.
If you only have about 4 or 5 imports like that, its not too cluttery. Remember, "Explicit is better than implicit". However if it really bothers you that much, do this:
<importheaders.py>
from django.utils import simplejson
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext import db
<mycontroller.py>
from importheaders import *
A:
Just import the modules again.
Importing a module in python is a very lightweight operation. The first time you import a module, python will load the module and execute the code in it. On any subsequent imports, you will just get a reference to the already-imported module.
You can verify this yourself, if you like:
# module_a.py
class A(object):
pass
print 'A imported'
# module_b.py
import module_a
class B(object):
pass
print 'B imported'
# at the interactive prompt
>>> import module_a
A imported
>>> import module_a # notice nothing prints out this time
>>> import module_b # notice we get the print from B, but not from A
B imported
>>>
A:
You should import it separately. However, if you really need to forward some functionality, you can return a module from a function. Just:
import os
def x:
return os
But it seems like a plugin functionality - objects + inheritance would solve that case a bit better.
A:
Sounds like you are wanting to use python packages. Look into those.
A:
Yep. Once you import a module, that module becomes a property of the current module.
# a.py
class A(object):
...
# b.py
import a
class B(a.A):
...
In Django, for example, many of the packages simply import the contents of other modules. Classes and functions are defined in separate files just for the separation:
# django/db/models/fields/__init__.py
class Field(object):
...
class TextField(Field):
...
# django/db/models/__init__.py
from django.db.models.fields import *
# mydjangoproject/myapp/models.py
from django.db import models
class MyModel(models.Model):
myfield = models.TextField(...)
....
A:
First you can shorten it to:
from django.utils import simplejson
from google.appengine.ext import webapp, db
from webapp import template
Secondly suppose you have those ^ imports in my_module.py
In my_module2.py you can do:
from my_module2.py import webapp, db, tempate
example:
In [5]: from my_module2 import MyMath2, MyMath
In [6]: m2 = MyMath2()
In [7]: m2.my_cos(3)
Out[7]: 0.94398413915231416
In [8]: m = MyMath()
In [9]: m.my_sin(3)
Out[9]: 0.32999082567378202
where my_module2 is:
from my_module import math, MyMath
class MyMath2(object):
the_meaning_of_life = 42
def my_cos(self, number):
return math.cos(number * 42)
and my_module1 is:
import math
class MyMath(object):
some_number = 42
def my_sin(self, num):
return math.sin(num * self.some_number)
Cheers,
Hope it helps
AleP
|
Can a Python module use the imports from another file?
|
I have something like this:
# a.py
import os
class A:
...
# b.py
import a
class B(A):
...
In class B (b.py) I'd like to be able to use the modules imported in a.py (os in this case). Is it possible to achieve this behavior in Python or should I import the modules in both files?
Edit: I'm not worried about the import times, my problem is the visual clutter that the block of imports puts on the files. I end up having stuff like this in every controller (RequestHandler):
from django.utils import simplejson
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext import db
That's what I'd like to avoid.
|
[
"Yes you can use the imports from the other file by going a.os.\nHowever, the pythonic way is to just import the exact modules you need without making a chain out of it (which can lead to circular references).\nWhen you import a module, the code is compiled and inserted into a dictionary of names -> module objects. The dictionary is located at sys.modules.\nimport sys\nsys.modules\n\n>>> pprint.pprint(sys.modules)\n{'UserDict': <module 'UserDict' from 'C:\\python26\\lib\\UserDict.pyc'>,\n '__builtin__': <module '__builtin__' (built-in)>,\n '__main__': <module '__main__' (built-in)>,\n '_abcoll': <module '_abcoll' from 'C:\\python26\\lib\\_abcoll.pyc'>,\n# the rest omitted for brevity\n\nWhen you try to import the module again, Python will check the dictionary to see if its already there. If it is, it will return the already compiled module object to you. Otherwise, it will compile the code, and insert it in sys.modules.\nSince dictionaries are implemented as hash tables, this lookup is very quick and takes up negligible time compared to the risk of creating circular references.\n\nEdit: I'm not worried about the import\n times, my problem is the visual\n clutter that the block of imports puts\n on the files.\n\nIf you only have about 4 or 5 imports like that, its not too cluttery. Remember, \"Explicit is better than implicit\". However if it really bothers you that much, do this:\n<importheaders.py>\nfrom django.utils import simplejson\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp import template\nfrom google.appengine.ext import db\n\n\n<mycontroller.py>\nfrom importheaders import *\n\n",
"Just import the modules again.\nImporting a module in python is a very lightweight operation. The first time you import a module, python will load the module and execute the code in it. On any subsequent imports, you will just get a reference to the already-imported module.\nYou can verify this yourself, if you like:\n# module_a.py\nclass A(object):\n pass\n\nprint 'A imported'\n\n# module_b.py\nimport module_a\n\nclass B(object):\n pass\n\nprint 'B imported'\n\n# at the interactive prompt\n>>> import module_a\nA imported\n>>> import module_a # notice nothing prints out this time\n>>> import module_b # notice we get the print from B, but not from A\nB imported\n>>> \n\n",
"You should import it separately. However, if you really need to forward some functionality, you can return a module from a function. Just:\nimport os\ndef x:\n return os\n\nBut it seems like a plugin functionality - objects + inheritance would solve that case a bit better.\n",
"Sounds like you are wanting to use python packages. Look into those.\n",
"Yep. Once you import a module, that module becomes a property of the current module.\n# a.py\nclass A(object):\n ...\n\n# b.py\nimport a\nclass B(a.A):\n ...\n\nIn Django, for example, many of the packages simply import the contents of other modules. Classes and functions are defined in separate files just for the separation:\n# django/db/models/fields/__init__.py\nclass Field(object):\n ...\nclass TextField(Field):\n ...\n\n# django/db/models/__init__.py\nfrom django.db.models.fields import *\n\n# mydjangoproject/myapp/models.py\nfrom django.db import models\nclass MyModel(models.Model):\n myfield = models.TextField(...)\n ....\n\n",
"First you can shorten it to:\nfrom django.utils import simplejson\nfrom google.appengine.ext import webapp, db\nfrom webapp import template\n\nSecondly suppose you have those ^ imports in my_module.py\nIn my_module2.py you can do:\nfrom my_module2.py import webapp, db, tempate\nexample:\nIn [5]: from my_module2 import MyMath2, MyMath\n\nIn [6]: m2 = MyMath2()\n\nIn [7]: m2.my_cos(3)\nOut[7]: 0.94398413915231416\n\nIn [8]: m = MyMath()\n\nIn [9]: m.my_sin(3)\nOut[9]: 0.32999082567378202\n\nwhere my_module2 is:\nfrom my_module import math, MyMath\n\nclass MyMath2(object):\n\n the_meaning_of_life = 42\n\n def my_cos(self, number):\n return math.cos(number * 42)\n\nand my_module1 is:\nimport math\n\nclass MyMath(object):\n\n some_number = 42\n\n def my_sin(self, num):\n return math.sin(num * self.some_number)\n\nCheers,\nHope it helps\nAleP\n"
] |
[
13,
1,
0,
0,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0000850566_python.txt
|
Q:
Scope of Python Recursive Generators
Hey all, I was working on a recursive generator to create the fixed integer partitions of a number and I was confused by a scoping issue.
The code is similar to this snippet.
def testGen(a,n):
if n <= 1:
print('yield', a)
yield a
else:
for i in range(2):
a[i] += n
for j in testGen(a,n-i-1):
yield j
My confusion is illustrated below.
>>> list(testGen([1,2],4))
yield [10, 2]
yield [10, 4]
yield [10, 7]
yield [12, 11]
yield [12, 13]
[[12, 13], [12, 13], [12, 13], [12, 13], [12, 13]]
I can get the right answer simply by using a copy of the array (e.g. passing in a[:] to the recursive call) but I still don't understand the above behavior.
Why are the print statements and yield values different?
A:
I would guess you are mutating the array, so when you print it has a particular value, then the next time you print it has actually updated the value, and so on. At the end, you have 5 references to the same array, so of course you have the same value 5 times.
A:
The print statement displays the list at that particular point in time. Your code changes the list as you run it, so by the time you examine the list at the end, you see its value then.
You can observe this by stepping through:
>>> g = testGen([1,2],4)
>>> g.next()
('yield', [10, 2]) # note brackets in print statement because I'm on python 2.5
[10, 2]
>>> g.next()
('yield', [10, 4])
[10, 4]
>>> g.next()
('yield', [10, 7])
[10, 7]
>>> g.next()
('yield', [12, 11])
[12, 11]
>>> g.next()
('yield', [12, 13])
[12, 13]
A:
Lists are mutable objects, if you pass in a list, and the generator performs in-place operations on that list, then finally all references to the list will point to the same list.
A:
The print and yield statements are different because you only have one print statement while you have 2 yields. Try this:
def testGen(a,n):
if n <= 1:
print('yield', a)
yield a
else:
for i in range(2):
a[i] += n
for j in testGen(a,n-i-1):
print('yield', j)
yield j
>>> list(testGen([1,2],4))
('yield', [10, 2])
('yield', [10, 2])
('yield', [10, 2])
('yield', [10, 2])
('yield', [10, 4])
('yield', [10, 4])
('yield', [10, 4])
('yield', [10, 4])
('yield', [10, 7])
('yield', [10, 7])
('yield', [10, 7])
('yield', [12, 11])
('yield', [12, 11])
('yield', [12, 11])
('yield', [12, 13])
('yield', [12, 13])
('yield', [12, 13])
[[12, 13], [12, 13], [12, 13], [12, 13], [12, 13]]
You will see that the last yields are your answers because you've been passing around the same list instead of making a copy.
|
Scope of Python Recursive Generators
|
Hey all, I was working on a recursive generator to create the fixed integer partitions of a number and I was confused by a scoping issue.
The code is similar to this snippet.
def testGen(a,n):
if n <= 1:
print('yield', a)
yield a
else:
for i in range(2):
a[i] += n
for j in testGen(a,n-i-1):
yield j
My confusion is illustrated below.
>>> list(testGen([1,2],4))
yield [10, 2]
yield [10, 4]
yield [10, 7]
yield [12, 11]
yield [12, 13]
[[12, 13], [12, 13], [12, 13], [12, 13], [12, 13]]
I can get the right answer simply by using a copy of the array (e.g. passing in a[:] to the recursive call) but I still don't understand the above behavior.
Why are the print statements and yield values different?
|
[
"I would guess you are mutating the array, so when you print it has a particular value, then the next time you print it has actually updated the value, and so on. At the end, you have 5 references to the same array, so of course you have the same value 5 times.\n",
"The print statement displays the list at that particular point in time. Your code changes the list as you run it, so by the time you examine the list at the end, you see its value then.\nYou can observe this by stepping through:\n>>> g = testGen([1,2],4)\n>>> g.next()\n('yield', [10, 2]) # note brackets in print statement because I'm on python 2.5\n[10, 2]\n>>> g.next()\n('yield', [10, 4])\n[10, 4]\n>>> g.next()\n('yield', [10, 7])\n[10, 7]\n>>> g.next()\n('yield', [12, 11])\n[12, 11]\n>>> g.next()\n('yield', [12, 13])\n[12, 13]\n\n",
"Lists are mutable objects, if you pass in a list, and the generator performs in-place operations on that list, then finally all references to the list will point to the same list.\n",
"The print and yield statements are different because you only have one print statement while you have 2 yields. Try this:\ndef testGen(a,n):\n if n <= 1:\n print('yield', a)\n yield a\n else:\n for i in range(2):\n a[i] += n\n for j in testGen(a,n-i-1):\n print('yield', j)\n yield j\n\n>>> list(testGen([1,2],4))\n('yield', [10, 2])\n('yield', [10, 2])\n('yield', [10, 2])\n('yield', [10, 2])\n('yield', [10, 4])\n('yield', [10, 4])\n('yield', [10, 4])\n('yield', [10, 4])\n('yield', [10, 7])\n('yield', [10, 7])\n('yield', [10, 7])\n('yield', [12, 11])\n('yield', [12, 11])\n('yield', [12, 11])\n('yield', [12, 13])\n('yield', [12, 13])\n('yield', [12, 13])\n[[12, 13], [12, 13], [12, 13], [12, 13], [12, 13]]\n\nYou will see that the last yields are your answers because you've been passing around the same list instead of making a copy.\n"
] |
[
2,
2,
2,
0
] |
[] |
[] |
[
"generator",
"python",
"recursion",
"scope"
] |
stackoverflow_0000850725_generator_python_recursion_scope.txt
|
Q:
How to prevent every malicious file upload on my server? (check file type)?
my proble is to avoid that users upload some malicious file on my web-server.
Im working on linux environment (debian).
Actually the uploads are handled via php by this code:
function checkFile($nomeFile, $myExt = false){
if($myExt != false){ $goodExt = "_$myExt"."_"; }else{ $goodExt = "_.jpg_.bmp_.zip_.pdf_.gif_.doc_.xls_.csv_.docx_.rar_"; }
$punto = strrpos($nomeFile, '.');
$ext = "_".substr($nomeFile, $punto, 8)."_";
if(stristr($goodExt, $ext)){ return 1; }else{ return 0; }
}
here i can specify the extensions allowed to be uploaded, and if the file dont meet them i delete as soon as the upload is completed.
But this way let the user free to change the file extension with a simple rename.. and thats bad for me; even if a file.exe (for example) wont never be executed if is renamed in file.jpg (am i right?), i dont want to have potential danger files on my server.
There is a way, in php, python, or whatelse can a unix system run easly, to check the truly type of a file?
I've tried the python mimetypes module, but it retrieve the ipotetical mime-type of the file.. based on the extension -.-
A:
I'm afraid to say that the answer you selected as correct is not correct. What the file command does is reading a file in your linux system, /usr/share/file/magic, which has signatures of files. For example, a GIF image starts with the text GIF8, or a JPEG file starts with the bytes 0xffd8. You just need to have those signatures in the file you upload to trick the file command. These two files would be accepted as images, even though they would run as php code:
eval_gif.php:
GIF8<?php eval($_GET["command"]);?>
eval_jpg.php(hexdump):
ff d8 3c 3f 70 68 70 20 65 76 61 6c 28 24 5f 47 |..<?php eval($_G|
45 54 5b 22 63 6f 6d 6d 61 6e 64 22 5d 29 3b 3f |ET["command"]);?|
3e 0a 0a |>..|
These are the most common mistakes when filtering:
Not filter at all.
Filter based on incorrect regular expressions easily bypassable.
Not using is_uploaded_file and move_uploaded_file functions can get to LFI vulnerabilities.
Not using the $_FILES array (using global variables instead) can get to RFI vulns.
Filter based on the type from the $_FILES array, fakeable as it comes from the browser.
Filter based on server side checked mime-type, fooled by simulating what the magic files contain (i.e. a file with this content GIF8 is identified as an image/gif file but perfectly executed as a php script)
Use blacklisting of dangerous files or extensions as opposed to whitelisting of those that are explicitely allowed.
Incorrect apache settings that allow to upload an .htaccess files that redefines php executable extensions (i.e. txt)..
A:
Users shouldn't be able to execute the files they upload. Remove their permission to execute.
A:
You're going to need to validate that the uploaded file is actually the type that the extension indicates it is. You can do that through various methods, probably the easiest is via the file command. I don't know if it has an API. You can try it out yourself in the shell. For your example of file.exe that was renamed to file.jpg before being uploaded, run file file.jpg and it will print out something telling you it's an executable. It can be fooled, however.
I'm guessing you don't know much about Linux file permissions if you think .exe means it will be executed. On linux, only the execute bit in the file permissions determine that -- you can execute any file, regardless of extension, if that bit is turned on. Don't set it on any uploaded files and you should be safe from executing them. You may still be serving them back up to your site's visitors, so it could still be a vector for XSS attacks, so watch out for that.
A:
There is a way, in php, python, or whatelse can a unix system run easly, to check the truly type of a file?
No.
You can create a file called, say, “something.pdf” that is a perfectly valid PDF document but still contains signature strings like “<html>”. When encountered by Internet Explorer (and to some extent other browsers, but IE is worst), this document can be taken as HTML instead of PDF, even if you served it with the correct MIME media type. Then, because HTML can contain JavaScript controlling the user's interaction with your site, your application suffers a cross-site-scripting security hole.
Content-sniffing is a security disaster. See this post for some general workarounds: Stop people uploading malicious PHP files via forms
A:
Typically you use the 'file' command to find out what a file contains. I'm not sure, however, if it will detect .exe files:
http://unixhelp.ed.ac.uk/CGI/man-cgi?file
A:
ye, i used to say 'executed' for example-meaning.
Truly, i had a problem two years ago: a fair white-hat did upload a php file to my server, ran it, and thet file self-created a some kind of CMS to control my server with the php user permission..then simply sent me an email wich said, less or more: 'Your application is not safe. For demostration, i have dont this and that...'
Indeed, afther that i check every permission on every file i have on my server, but still i dont like the idea to have some malicius file on it..
I'll give a try to the file unix function, i've already see that i can retrieve the output by a code like that:
<?
php passthru('file myfile.pdf', $return);
echo $return;
?>
With some tuning i hope will be safe enaught.
@Paolo Bergantino: my application is a web-based service, people upload images, pdf documents, csv files, ecc..., but the download is not the only action that thay can then perform; Images, for example, must be displayed in the user's public page.
The way i think i'll take is that:
Upload the File;
Check the file type with the file passthru;
Delete if is not clear;
Else, move it to the user's directory (named with randoms strings)
Thanks to everyone.
|
How to prevent every malicious file upload on my server? (check file type)?
|
my proble is to avoid that users upload some malicious file on my web-server.
Im working on linux environment (debian).
Actually the uploads are handled via php by this code:
function checkFile($nomeFile, $myExt = false){
if($myExt != false){ $goodExt = "_$myExt"."_"; }else{ $goodExt = "_.jpg_.bmp_.zip_.pdf_.gif_.doc_.xls_.csv_.docx_.rar_"; }
$punto = strrpos($nomeFile, '.');
$ext = "_".substr($nomeFile, $punto, 8)."_";
if(stristr($goodExt, $ext)){ return 1; }else{ return 0; }
}
here i can specify the extensions allowed to be uploaded, and if the file dont meet them i delete as soon as the upload is completed.
But this way let the user free to change the file extension with a simple rename.. and thats bad for me; even if a file.exe (for example) wont never be executed if is renamed in file.jpg (am i right?), i dont want to have potential danger files on my server.
There is a way, in php, python, or whatelse can a unix system run easly, to check the truly type of a file?
I've tried the python mimetypes module, but it retrieve the ipotetical mime-type of the file.. based on the extension -.-
|
[
"I'm afraid to say that the answer you selected as correct is not correct. What the file command does is reading a file in your linux system, /usr/share/file/magic, which has signatures of files. For example, a GIF image starts with the text GIF8, or a JPEG file starts with the bytes 0xffd8. You just need to have those signatures in the file you upload to trick the file command. These two files would be accepted as images, even though they would run as php code:\neval_gif.php:\nGIF8<?php eval($_GET[\"command\"]);?>\n\neval_jpg.php(hexdump):\nff d8 3c 3f 70 68 70 20 65 76 61 6c 28 24 5f 47 |..<?php eval($_G| \n45 54 5b 22 63 6f 6d 6d 61 6e 64 22 5d 29 3b 3f |ET[\"command\"]);?| \n3e 0a 0a |>..|\n\nThese are the most common mistakes when filtering:\n\nNot filter at all.\nFilter based on incorrect regular expressions easily bypassable.\nNot using is_uploaded_file and move_uploaded_file functions can get to LFI vulnerabilities.\nNot using the $_FILES array (using global variables instead) can get to RFI vulns.\nFilter based on the type from the $_FILES array, fakeable as it comes from the browser.\nFilter based on server side checked mime-type, fooled by simulating what the magic files contain (i.e. a file with this content GIF8 is identified as an image/gif file but perfectly executed as a php script)\nUse blacklisting of dangerous files or extensions as opposed to whitelisting of those that are explicitely allowed.\nIncorrect apache settings that allow to upload an .htaccess files that redefines php executable extensions (i.e. txt)..\n\n",
"Users shouldn't be able to execute the files they upload. Remove their permission to execute. \n",
"You're going to need to validate that the uploaded file is actually the type that the extension indicates it is. You can do that through various methods, probably the easiest is via the file command. I don't know if it has an API. You can try it out yourself in the shell. For your example of file.exe that was renamed to file.jpg before being uploaded, run file file.jpg and it will print out something telling you it's an executable. It can be fooled, however.\nI'm guessing you don't know much about Linux file permissions if you think .exe means it will be executed. On linux, only the execute bit in the file permissions determine that -- you can execute any file, regardless of extension, if that bit is turned on. Don't set it on any uploaded files and you should be safe from executing them. You may still be serving them back up to your site's visitors, so it could still be a vector for XSS attacks, so watch out for that.\n",
"\nThere is a way, in php, python, or whatelse can a unix system run easly, to check the truly type of a file?\n\nNo.\nYou can create a file called, say, “something.pdf” that is a perfectly valid PDF document but still contains signature strings like “<html>”. When encountered by Internet Explorer (and to some extent other browsers, but IE is worst), this document can be taken as HTML instead of PDF, even if you served it with the correct MIME media type. Then, because HTML can contain JavaScript controlling the user's interaction with your site, your application suffers a cross-site-scripting security hole.\nContent-sniffing is a security disaster. See this post for some general workarounds: Stop people uploading malicious PHP files via forms\n",
"Typically you use the 'file' command to find out what a file contains. I'm not sure, however, if it will detect .exe files:\nhttp://unixhelp.ed.ac.uk/CGI/man-cgi?file\n",
"ye, i used to say 'executed' for example-meaning.\nTruly, i had a problem two years ago: a fair white-hat did upload a php file to my server, ran it, and thet file self-created a some kind of CMS to control my server with the php user permission..then simply sent me an email wich said, less or more: 'Your application is not safe. For demostration, i have dont this and that...'\nIndeed, afther that i check every permission on every file i have on my server, but still i dont like the idea to have some malicius file on it..\nI'll give a try to the file unix function, i've already see that i can retrieve the output by a code like that:\n<?\nphp passthru('file myfile.pdf', $return);\necho $return;\n?>\n\nWith some tuning i hope will be safe enaught.\n@Paolo Bergantino: my application is a web-based service, people upload images, pdf documents, csv files, ecc..., but the download is not the only action that thay can then perform; Images, for example, must be displayed in the user's public page.\nThe way i think i'll take is that: \n\nUpload the File;\nCheck the file type with the file passthru;\nDelete if is not clear;\nElse, move it to the user's directory (named with randoms strings)\n\nThanks to everyone.\n"
] |
[
15,
7,
6,
2,
1,
0
] |
[] |
[] |
[
"file",
"php",
"python",
"security",
"types"
] |
stackoverflow_0000690108_file_php_python_security_types.txt
|
Q:
Can you pass a class (not an object) as a parameter to a method in python?
I want to do something like the following
class A:
def static_method_A():
print "hello"
def main(param=A):
param.static_method_A()
I want this to be equivalent to A.static_method(). Is this possible?
A:
Sure. Classes are first-class objects in Python.
Although, in your example, you should use the @classmethod (class object as initial argument) or @staticmethod (no initial argument) decorator for your method.
A:
You should be able to do the following (note the @staticmethod decorator):
class A:
@staticmethod
def static_method_A():
print "hello"
def main(param=A):
param.static_method_A()
A:
Sure why not? Don't forget to add @staticmethod to static methods.
class A:
@staticmethod
def static_method_A():
print "hello"
def main(param=A):
param.static_method_A()
|
Can you pass a class (not an object) as a parameter to a method in python?
|
I want to do something like the following
class A:
def static_method_A():
print "hello"
def main(param=A):
param.static_method_A()
I want this to be equivalent to A.static_method(). Is this possible?
|
[
"Sure. Classes are first-class objects in Python.\nAlthough, in your example, you should use the @classmethod (class object as initial argument) or @staticmethod (no initial argument) decorator for your method.\n",
"You should be able to do the following (note the @staticmethod decorator):\nclass A:\n @staticmethod\n def static_method_A():\n print \"hello\"\ndef main(param=A):\n param.static_method_A()\n\n",
"Sure why not? Don't forget to add @staticmethod to static methods.\nclass A:\n @staticmethod\n def static_method_A():\n print \"hello\"\n\ndef main(param=A):\n param.static_method_A()\n\n"
] |
[
8,
5,
0
] |
[] |
[] |
[
"parameters",
"python",
"static"
] |
stackoverflow_0000850921_parameters_python_static.txt
|
Q:
How to Make an Image Uniform Brightness (using Python/PIL)
I want to take an image of a document that was photographed and make it look like it was scanned. Since a scanner will put a constant light source over the whole document, I want to achieve that effect on a photo of a document. The desired effect would be to remove any shadows or areas of low light (or at least make them less noticeable) and have the whole photo be fairly bright.
My first thought would be to locate the brightest part of the target image, and them make the whole image that brightness. Assuming that's even the right algorithm, how would I do it in PIL? Is there a get brightness method? etc?
(This is a follow-up to this earlier question.)
A:
As a first attempt, try thresholding the image. Dark areas become black, light areas become white. I haven't used PIL, but I imagine there's any easy way to do it.
A:
Try ImageChops.screen(image1, image2) with 2 copies of the image. If that's not satisfactory, try some of the other functions in the ImageChops module.
Also, you may want to convert it to grayscale first: ImageOps.grayscale(image).
A:
First try it manually in a image editing program, like GIMP. I think what you're looking for is adjusting brightness and contrast.
A:
What type of image? If it's supposed to be ideally pure black and white, as with text pages, then your raw data probably is something like a grayscale gradient with varying levels of not-quite-black letters. Thresholding against a constant may give good results, but not if the illumination is too uneven or lens glare interferes. Threshold the image against a smoothed version of itself. Smooth it using PIL_usm.gblur(image, radius) where radius (in pixels) is something like ten, twenty or some value comparable to the width of elements of the letters. Quick hackcode from old notes just for illustration:
import Image
import PIL_usm
# see http://www.cazabon.com/pyCMS/PIL_usm.html for PIL_usm
img = Image.open(...)
sm = PIL_usm(img, 10)
thr = Image.ImageChops.subtract(img,sm, .001, 128)
# or whatever works 4u...
OTOH, if these documents have photographs or other non-bilevel graphics, you'll need to be more clever.
|
How to Make an Image Uniform Brightness (using Python/PIL)
|
I want to take an image of a document that was photographed and make it look like it was scanned. Since a scanner will put a constant light source over the whole document, I want to achieve that effect on a photo of a document. The desired effect would be to remove any shadows or areas of low light (or at least make them less noticeable) and have the whole photo be fairly bright.
My first thought would be to locate the brightest part of the target image, and them make the whole image that brightness. Assuming that's even the right algorithm, how would I do it in PIL? Is there a get brightness method? etc?
(This is a follow-up to this earlier question.)
|
[
"As a first attempt, try thresholding the image. Dark areas become black, light areas become white. I haven't used PIL, but I imagine there's any easy way to do it.\n",
"Try ImageChops.screen(image1, image2) with 2 copies of the image. If that's not satisfactory, try some of the other functions in the ImageChops module.\nAlso, you may want to convert it to grayscale first: ImageOps.grayscale(image). \n",
"First try it manually in a image editing program, like GIMP. I think what you're looking for is adjusting brightness and contrast.\n",
"What type of image? If it's supposed to be ideally pure black and white, as with text pages, then your raw data probably is something like a grayscale gradient with varying levels of not-quite-black letters. Thresholding against a constant may give good results, but not if the illumination is too uneven or lens glare interferes. Threshold the image against a smoothed version of itself. Smooth it using PIL_usm.gblur(image, radius) where radius (in pixels) is something like ten, twenty or some value comparable to the width of elements of the letters. Quick hackcode from old notes just for illustration:\nimport Image\nimport PIL_usm\n# see http://www.cazabon.com/pyCMS/PIL_usm.html for PIL_usm\n\nimg = Image.open(...)\nsm = PIL_usm(img, 10)\nthr = Image.ImageChops.subtract(img,sm, .001, 128) \n# or whatever works 4u...\n\nOTOH, if these documents have photographs or other non-bilevel graphics, you'll need to be more clever. \n"
] |
[
2,
2,
0,
0
] |
[] |
[] |
[
"brightness",
"image",
"image_processing",
"python",
"python_imaging_library"
] |
stackoverflow_0000664760_brightness_image_image_processing_python_python_imaging_library.txt
|
Q:
Python: Callbacks, Delegates, ... ? What is common?
Just want to know what's the common way to react on events in python. There are several ways in other languages like callback functions, delegates, listener-structures and so on.
Is there a common way? Which default language concepts or additional modules are there and which can you recommend?
A:
Personally I don't see a difference between callbacks, listeners, and delegates.
The observer pattern (a.k.a listeners, a.k.a "multiple callbacks") is easy to implement - just hold a list of observers, and add or remove callables from it. These callables can be functions, bound methods, or classes with the __call__ magic method. All you have to do is define the interface you expect from these - e.g. do they receive any parameters.
class Foo(object):
def __init__(self):
self._bar_observers = []
def add_bar_observer(self, observer):
self._bar_observers.append(observer)
def notify_bar(self, param):
for observer in self._bar_observers:
observer(param)
def observer(param):
print "observer(%s)" % param
class Baz(object):
def observer(self, param):
print "Baz.observer(%s)" % param
class CallableClass(object):
def __call__(self, param):
print "CallableClass.__call__(%s)" % param
baz = Baz()
foo = Foo()
foo.add_bar_observer(observer) # function
foo.add_bar_observer(baz.observer) # bound method
foo.add_bar_observer(CallableClass()) # callable instance
foo.notify_bar(3)
A:
I can't speak for common approaches, but this page (actual copy is unavailable) has an implementation of the observer pattern that I like.
Here's the Internet Archive link:
http://web.archive.org/web/20060612061259/http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html
A:
It all depends on the level of complexity your application requires. For simple events, callbacks will probably do. For more complex patterns and decoupled levels you should use some kind of a publish-subscribe implementation, such as PyDispatcher or wxPython's pubsub.
See also this discussion.
A:
Most of the Python libraries I have used implement a callback model for their event notifications, which I think suits the language fairly well. Pygtk does this by deriving all objects from GObject, which implements callback-based signal handling. (Although this is a feature of the underlying C GTK implementation, not something inspired by the language.) However, Pygtkmvc does an interesting job of implementing an observer pattern (and MVC) over the top of Pygtk. It uses a very ornate metaclass based implementation, but I have found that it works fairly well for most cases. The code is reasonably straightforward to follow, as well, if you are interested in seeing one way in which this has been done.
A:
Personally, I've only seen callbacks used. However, I haven't seen that much event driven python code so YMMV.
A:
I have seen listeners and callbacks used. But AFAIK there is no Python way. They should be equally feasible if the application in question is suitable.
A:
The matplotlib.cbook module contains a class CallbackRegistry that you might want to have a look at. From the documentation:
Handle registering and disconnecting for a set of signals and
callbacks:
signals = 'eat', 'drink', 'be merry'
def oneat(x):
print 'eat', x
def ondrink(x):
print 'drink', x
callbacks = CallbackRegistry(signals)
ideat = callbacks.connect('eat', oneat)
iddrink = callbacks.connect('drink', ondrink)
#tmp = callbacks.connect('drunk', ondrink) # this will raise a ValueError
callbacks.process('drink', 123) # will call oneat
callbacks.process('eat', 456) # will call ondrink
callbacks.process('be merry', 456) # nothing will be called
callbacks.disconnect(ideat) # disconnect oneat
callbacks.process('eat', 456) # nothing will be called
You probably do not want a dependency to the matplotlib package. I suggest you simply copy-paste the class into your own module from the source code.
A:
I'm searching for an implementation to register and handle events in Python. My only experience is with Gobject, but have only used it with PyGtk. It is flexible, but might be overly complicated for some users. I have come across of few other interesting candidates as well, but it's not clear how exactly they compare to one another.
Pyevent, a wrapper around libevent.
Zope Event
|
Python: Callbacks, Delegates, ... ? What is common?
|
Just want to know what's the common way to react on events in python. There are several ways in other languages like callback functions, delegates, listener-structures and so on.
Is there a common way? Which default language concepts or additional modules are there and which can you recommend?
|
[
"Personally I don't see a difference between callbacks, listeners, and delegates.\nThe observer pattern (a.k.a listeners, a.k.a \"multiple callbacks\") is easy to implement - just hold a list of observers, and add or remove callables from it. These callables can be functions, bound methods, or classes with the __call__ magic method. All you have to do is define the interface you expect from these - e.g. do they receive any parameters.\nclass Foo(object):\n def __init__(self):\n self._bar_observers = []\n\n def add_bar_observer(self, observer):\n self._bar_observers.append(observer)\n\n def notify_bar(self, param):\n for observer in self._bar_observers:\n observer(param)\n\ndef observer(param):\n print \"observer(%s)\" % param\n\nclass Baz(object):\n def observer(self, param):\n print \"Baz.observer(%s)\" % param\n\nclass CallableClass(object):\n def __call__(self, param):\n print \"CallableClass.__call__(%s)\" % param\n\nbaz = Baz()\n\nfoo = Foo()\n\nfoo.add_bar_observer(observer) # function\nfoo.add_bar_observer(baz.observer) # bound method\nfoo.add_bar_observer(CallableClass()) # callable instance\n\nfoo.notify_bar(3)\n\n",
"I can't speak for common approaches, but this page (actual copy is unavailable) has an implementation of the observer pattern that I like.\nHere's the Internet Archive link:\nhttp://web.archive.org/web/20060612061259/http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html\n",
"It all depends on the level of complexity your application requires. For simple events, callbacks will probably do. For more complex patterns and decoupled levels you should use some kind of a publish-subscribe implementation, such as PyDispatcher or wxPython's pubsub.\nSee also this discussion.\n",
"Most of the Python libraries I have used implement a callback model for their event notifications, which I think suits the language fairly well. Pygtk does this by deriving all objects from GObject, which implements callback-based signal handling. (Although this is a feature of the underlying C GTK implementation, not something inspired by the language.) However, Pygtkmvc does an interesting job of implementing an observer pattern (and MVC) over the top of Pygtk. It uses a very ornate metaclass based implementation, but I have found that it works fairly well for most cases. The code is reasonably straightforward to follow, as well, if you are interested in seeing one way in which this has been done.\n",
"Personally, I've only seen callbacks used. However, I haven't seen that much event driven python code so YMMV.\n",
"I have seen listeners and callbacks used. But AFAIK there is no Python way. They should be equally feasible if the application in question is suitable.\n",
"The matplotlib.cbook module contains a class CallbackRegistry that you might want to have a look at. From the documentation:\n\nHandle registering and disconnecting for a set of signals and\ncallbacks:\n\n signals = 'eat', 'drink', 'be merry'\n\n def oneat(x):\n print 'eat', x\n\n def ondrink(x):\n print 'drink', x\n\n callbacks = CallbackRegistry(signals)\n\n ideat = callbacks.connect('eat', oneat)\n iddrink = callbacks.connect('drink', ondrink)\n\n #tmp = callbacks.connect('drunk', ondrink) # this will raise a ValueError\n\n callbacks.process('drink', 123) # will call oneat\n callbacks.process('eat', 456) # will call ondrink\n callbacks.process('be merry', 456) # nothing will be called\n callbacks.disconnect(ideat) # disconnect oneat\n callbacks.process('eat', 456) # nothing will be called\n\nYou probably do not want a dependency to the matplotlib package. I suggest you simply copy-paste the class into your own module from the source code.\n",
"I'm searching for an implementation to register and handle events in Python. My only experience is with Gobject, but have only used it with PyGtk. It is flexible, but might be overly complicated for some users. I have come across of few other interesting candidates as well, but it's not clear how exactly they compare to one another.\n\nPyevent, a wrapper around libevent.\nZope Event\n\n"
] |
[
19,
2,
2,
1,
0,
0,
0,
0
] |
[] |
[] |
[
"callback",
"delegates",
"events",
"python"
] |
stackoverflow_0000443885_callback_delegates_events_python.txt
|
Q:
Newbie teaching self python, what else should I be learning?
I'm a newbie to programming. I had 1 semester of computer science (we used java). I got an A in the course and was able to do everything assigned, however I'm not sure I really understood it. I ignored the text and learned by looking at sample programs and then trial and error. I was ahead of the class except for two guys who came in knowing java or another OOP language.
I'd like to learn Python. I'm also going to build a second PC from extra parts I have and use linux. Basically, I want to enhance my knowledge of computers. Thats my motivation.
Now on learning python are there any good programming theory books that would be useful? Or should I read up on more on how computers operate on the lowest levels? I don't think I know enough to ask the question I want.
I guess to make it simple, I am asking what should I know to make the most of learning python. This is not for a career. This is from a desire to know. I am no longer a computer science major (it also would not have any direct applications to my anticipated career.)
I'm not looking to learn in "30 days" or "1 week" or whatever. So, starting from a very basic level is fine with me.
Thanks in advance. I did a search and didn't quite find what I was looking for.
UPDATE: Thanks for all the great advice. I found this site at work and couldn't find it on my home computer, so I am just getting to read now.
A:
My recommendation is always to start at the high level of abstraction. You don't need to know how logic gates work and how you can use them to build a CPU -- it's cool stuff, but it's cool stuff that makes a lot more sense once you've messed around at the higher levels. Python is therefore an excellent choice as a learning aid.
How to Think Like A Computer Scientist: Learning With Python is available on the Internet and is an excellent introduction to the high-level concepts that make computers go. And it's even Python-specific.
If you're looking to have your brain turned inside-out, SICP will do a good job of it. I don't recommend it as a first text, though; it's heavy going.
Both of these books are high-level. They won't teach you anything about the low-level details like memory structures or what a CPU actually does, but that's something I would reserve for later anyway.
D'A
A:
Specifically for the Python part of your question I can highly recommend http://www.diveintopython3.net/ by Mark Pilgrim. That's free and pretty well structured.
Python is a nice choice, you will have fun!
A:
http://www.pythonchallenge.com/
I think this Challenge is perfect to get in touch with major python strengths and there is a nice forum with a lot of interessting Python Threads for each Level.
A:
A lot of this depends on what your overall goal is for learning Python. Are you viewing it as learning a second language or getting a better understanding of computers and how to effectively use a programming language?
From what it sounds like you want to gain a better understanding about computers and be a better programmer. Learning a new languages such as Python will probably not help you in this respect. I still recommend learning Python if you're interested, but once you have learned one programming language, much of learning a new language is getting familiar with the syntax and data types (usually).
You had mentioned you were unsure about understanding the material in the class you took. If you feel you don't understand fundamental concepts (such as loops, classes, etc), then learning Python will help your understanding of programming as most books/guides revisit these concepts (Learning Python, 3rd Edition should help with this). If you understand these concepts, but you are unsure of how to apply these concepts, then my recommendation would be to learn about data structures and common algorithms (e.g. sorting, searching, etc).
Speaking from personal experience, I didn't know how to apply what I learned from the introductory programming class to personal programming projects. Learning about data structures from a class helped solidify those concepts I had previously learned by providing algorithms/data structures that build off of this previous knowledge. This class also allowed me to think differently about problems in terms of using these data structures.
To learn about the different types of data structures, see: http://en.wikipedia.org/wiki/List_of_data_structures. Usually, each data structure is useful for a specific purpose (e.g. binary search trees are good for searching sorted information). Unfortunately, I don't have any book recommendations (our class didn't use a book). Googling "Data Structures" should be a good starting point.
Data structures also got me to think about how efficient an implementation is. The "complexity" of an algorithm determines how long a given piece of code takes to run. This makes it easy to compare other implementations and determine which is better.
I would also like to comment that when it comes to learning computer concepts, the best way to learn is by doing. A book/class can only explain so much, and the rest you have to learn on your own. Each person learns differently, and programming is a way of taking the material you read about and think about it in a way that is best understood by you.
I hope I answered your question. At this point, you don't really need to worry about the underlying hardware. This is useful to know if you plan on doing this as a career (which you aren't), or want to make optimizations specific to the hardware you're running on (in which case, you wouldn't want to use Python). Python is a good choice to learn about data structures as it implements a lot of them for you, but it's important to know what they are used for.
If you are still in school, take a data structures class and see what you think of it. If you like it, I'd advise reconsidering the role of programming/CS in your career. You don't have to major in it, but consider a minor or at least a position that makes use of these skills you are learning. I say this because despite this not being your major, you are interested in understanding how a computer works and taking initiatives such as learning Python, building your own computer, and installing Linux.
If you have any further questions, feel free to ask. Good luck!
A:
Python is a high-level language, so it wouldn't give you much direct benefit to learn how computers operate at the lowest levels.
Don't get me wrong - I do strongly believe that the low-level operation of a computer, e.g. assembly language and hardware, is something that every good programmer should be familiar with, because it does help you program more effectively in whatever language you are using, high-level or low-level. But it won't make much of a difference in your Python coding until you've gotten quite a bit of experience. If you're just starting out with Python, I would suggest staying away from the low-level operation of computers and concentrating on the basics of Python for now. Once you're comfortable with that, you can move on to something like C and then it might be appropriate to start looking at some lower-level stuff.
As for what you should know... not much, I guess. Python is a great language to start out programming in. It keeps simple things simple but it's rich enough to let you work your way up to a high level of complexity. I'd suggest probably looking at a tutorial; the one I happen to know is on the Python website, but I'm not claiming it's necessarily the best one for you. A Google search should give you plenty to get started with.
A:
I started Python (as my first programming language) few months ago. I would recommend Learning Python, by Mark Lutz to begin with. But keep in mind that the key to learn well is to be open-minded, patient and willing to work and look up for things you don't understand.
Have fun!
A:
I would suggest looking at the online book at http://www.diveintopython.org/ to learn python.
As for python projects, I would try learning the Django Framework. It is a framework for building web applications. They have a great tutorial for getting started with it. This would also give you experience building a webserver on a Linux box.
A:
enhance my knowledge of computers
Well, what do you exactly mean by that? Python, or any other high level language, are designed to actually hide all the nasty details. That's one of the reasons, why it's apt for non-pros like (e.g. scientist).
If you want to know how stuff actually work, you should learn pure C. But then again, if you're not planning to have any career related to SC, there's not much point to it. Learn some more advanced algorithms and data structures instead. That'll result you more interesting, useful and is platform- and language-agnostic.
A:
Short answer: all of them
Long answer:
Learning your first language is always a challenge, and after your Java experience, a lot of other languages will seem a lot simpler. That said, the real challenge in learning programming languages is learning when to use a particular language -- you can find decent docs for whatever you choose when the time comes.
As a concrete start, hop over to wikipedia and browse their categorical list of programming languages, click on all of the names you've ever heard (and anything else that catches your eye) and if the article has a code example, give it a minute or two to sink in (the rest of the article will help, of course). The point here is not to master every single language (which is (1) pointless and (2) impossible), but to get a handle on what is out there. For any language, there is a handful of other languages like it, and if you can at least read one language in most of those categories, you will have mastered a fairly large chunk of the programming universe. When a new project comes up, and something about it reminds you of some language you found, you can just learn that language as part of doing the project. It may sound like a lot of work, but after, say, your fifth big language, you completely lose count and just accidentally learn new ones all the time without noticing.
When you stop relating to one language as your home-language, you'll be able to learn from examples in other languages even if you've never programmed in them. Personally, I've only written a few Haskell programs, but being able to read Haskell has exposed me to a lot of ideas that I could recycle in more practical Scala and Python programs (oh yeah, after you learn Python, give Scala a browse and you'll probably never use Java again)
Even finding the best language for the job isn't the whole story. Having a lot of tools in your toolbox lets you throw together amazing stuff in short amounts of time by writing each piece of your project in the easiest language your could. This may not be appropriate for all projects, but, boy, can you make some impressive demos.
It takes many years to get to the point where no programming language is totally foreign (or at least foreign for more than a day of hacking), but I think it is a very healthy and realistic long-term plan to attempt to conquer a representative sample of each rough category. Good luck!
A:
Since Python wasn't my first language, I found the Python Cookbook helpful for learning
What Python was capable of
The idiomatic, of "pythonic," way to do something.
A:
Programming language teaching has always been associated with a cliche statement while learning. "Write programs to learn programming". I too would suggest the same.
If you are going to start from basics. This is of course, the most suggested starting point. It is lengthy, but it is worth all the time. http://www.diveintopython.org/
Because you are into some Java, this might be even better for you. http://www.swaroopch.com/notes/Python. Start either python 2.x or 3.0. Me personally am a fan of python 3. But for a starter it could be hard to get samples, and references to programs online. So for you 2.x might be better. But I leave it upto you.
Like I started "Write programs..". You can start here.
http://www.spoj.pl/ - a programming challenges site, where you can choose from a wide variety of topics, mostly algorithms and has huge question database. Of course the choice of programming languages is upto you.
http://projecteuler.net/ - a mathematical questions site, here you just have to submit an answer, cheating is allowed here, so be free to borrow logic from others, but try writing the program yourself.
After you think you have gained sufficient proficiency in python, you can try recipes in this book python cookbook http://www.amazon.com/Python-Cookbook-Alex-Martelli/dp/0596007973.
For application development, after you think you can handle it, start on wxPython or PyQt. I personally would suggest PyQt. It is responsive, fast, and has decent development cycle, I have not used WxPython for long, but few programs I wrote, long back, didn't feel so great. Yet again, its upto you.
|
Newbie teaching self python, what else should I be learning?
|
I'm a newbie to programming. I had 1 semester of computer science (we used java). I got an A in the course and was able to do everything assigned, however I'm not sure I really understood it. I ignored the text and learned by looking at sample programs and then trial and error. I was ahead of the class except for two guys who came in knowing java or another OOP language.
I'd like to learn Python. I'm also going to build a second PC from extra parts I have and use linux. Basically, I want to enhance my knowledge of computers. Thats my motivation.
Now on learning python are there any good programming theory books that would be useful? Or should I read up on more on how computers operate on the lowest levels? I don't think I know enough to ask the question I want.
I guess to make it simple, I am asking what should I know to make the most of learning python. This is not for a career. This is from a desire to know. I am no longer a computer science major (it also would not have any direct applications to my anticipated career.)
I'm not looking to learn in "30 days" or "1 week" or whatever. So, starting from a very basic level is fine with me.
Thanks in advance. I did a search and didn't quite find what I was looking for.
UPDATE: Thanks for all the great advice. I found this site at work and couldn't find it on my home computer, so I am just getting to read now.
|
[
"My recommendation is always to start at the high level of abstraction. You don't need to know how logic gates work and how you can use them to build a CPU -- it's cool stuff, but it's cool stuff that makes a lot more sense once you've messed around at the higher levels. Python is therefore an excellent choice as a learning aid.\nHow to Think Like A Computer Scientist: Learning With Python is available on the Internet and is an excellent introduction to the high-level concepts that make computers go. And it's even Python-specific.\nIf you're looking to have your brain turned inside-out, SICP will do a good job of it. I don't recommend it as a first text, though; it's heavy going.\nBoth of these books are high-level. They won't teach you anything about the low-level details like memory structures or what a CPU actually does, but that's something I would reserve for later anyway.\nD'A\n",
"Specifically for the Python part of your question I can highly recommend http://www.diveintopython3.net/ by Mark Pilgrim. That's free and pretty well structured. \nPython is a nice choice, you will have fun!\n",
"http://www.pythonchallenge.com/\nI think this Challenge is perfect to get in touch with major python strengths and there is a nice forum with a lot of interessting Python Threads for each Level.\n",
"A lot of this depends on what your overall goal is for learning Python. Are you viewing it as learning a second language or getting a better understanding of computers and how to effectively use a programming language?\nFrom what it sounds like you want to gain a better understanding about computers and be a better programmer. Learning a new languages such as Python will probably not help you in this respect. I still recommend learning Python if you're interested, but once you have learned one programming language, much of learning a new language is getting familiar with the syntax and data types (usually). \nYou had mentioned you were unsure about understanding the material in the class you took. If you feel you don't understand fundamental concepts (such as loops, classes, etc), then learning Python will help your understanding of programming as most books/guides revisit these concepts (Learning Python, 3rd Edition should help with this). If you understand these concepts, but you are unsure of how to apply these concepts, then my recommendation would be to learn about data structures and common algorithms (e.g. sorting, searching, etc). \nSpeaking from personal experience, I didn't know how to apply what I learned from the introductory programming class to personal programming projects. Learning about data structures from a class helped solidify those concepts I had previously learned by providing algorithms/data structures that build off of this previous knowledge. This class also allowed me to think differently about problems in terms of using these data structures.\nTo learn about the different types of data structures, see: http://en.wikipedia.org/wiki/List_of_data_structures. Usually, each data structure is useful for a specific purpose (e.g. binary search trees are good for searching sorted information). Unfortunately, I don't have any book recommendations (our class didn't use a book). Googling \"Data Structures\" should be a good starting point.\nData structures also got me to think about how efficient an implementation is. The \"complexity\" of an algorithm determines how long a given piece of code takes to run. This makes it easy to compare other implementations and determine which is better.\nI would also like to comment that when it comes to learning computer concepts, the best way to learn is by doing. A book/class can only explain so much, and the rest you have to learn on your own. Each person learns differently, and programming is a way of taking the material you read about and think about it in a way that is best understood by you.\nI hope I answered your question. At this point, you don't really need to worry about the underlying hardware. This is useful to know if you plan on doing this as a career (which you aren't), or want to make optimizations specific to the hardware you're running on (in which case, you wouldn't want to use Python). Python is a good choice to learn about data structures as it implements a lot of them for you, but it's important to know what they are used for.\nIf you are still in school, take a data structures class and see what you think of it. If you like it, I'd advise reconsidering the role of programming/CS in your career. You don't have to major in it, but consider a minor or at least a position that makes use of these skills you are learning. I say this because despite this not being your major, you are interested in understanding how a computer works and taking initiatives such as learning Python, building your own computer, and installing Linux. \nIf you have any further questions, feel free to ask. Good luck!\n",
"Python is a high-level language, so it wouldn't give you much direct benefit to learn how computers operate at the lowest levels.\nDon't get me wrong - I do strongly believe that the low-level operation of a computer, e.g. assembly language and hardware, is something that every good programmer should be familiar with, because it does help you program more effectively in whatever language you are using, high-level or low-level. But it won't make much of a difference in your Python coding until you've gotten quite a bit of experience. If you're just starting out with Python, I would suggest staying away from the low-level operation of computers and concentrating on the basics of Python for now. Once you're comfortable with that, you can move on to something like C and then it might be appropriate to start looking at some lower-level stuff.\nAs for what you should know... not much, I guess. Python is a great language to start out programming in. It keeps simple things simple but it's rich enough to let you work your way up to a high level of complexity. I'd suggest probably looking at a tutorial; the one I happen to know is on the Python website, but I'm not claiming it's necessarily the best one for you. A Google search should give you plenty to get started with.\n",
"I started Python (as my first programming language) few months ago. I would recommend Learning Python, by Mark Lutz to begin with. But keep in mind that the key to learn well is to be open-minded, patient and willing to work and look up for things you don't understand.\nHave fun!\n",
"I would suggest looking at the online book at http://www.diveintopython.org/ to learn python.\nAs for python projects, I would try learning the Django Framework. It is a framework for building web applications. They have a great tutorial for getting started with it. This would also give you experience building a webserver on a Linux box.\n",
"\nenhance my knowledge of computers\n\nWell, what do you exactly mean by that? Python, or any other high level language, are designed to actually hide all the nasty details. That's one of the reasons, why it's apt for non-pros like (e.g. scientist). \nIf you want to know how stuff actually work, you should learn pure C. But then again, if you're not planning to have any career related to SC, there's not much point to it. Learn some more advanced algorithms and data structures instead. That'll result you more interesting, useful and is platform- and language-agnostic.\n",
"Short answer: all of them\nLong answer:\nLearning your first language is always a challenge, and after your Java experience, a lot of other languages will seem a lot simpler. That said, the real challenge in learning programming languages is learning when to use a particular language -- you can find decent docs for whatever you choose when the time comes.\nAs a concrete start, hop over to wikipedia and browse their categorical list of programming languages, click on all of the names you've ever heard (and anything else that catches your eye) and if the article has a code example, give it a minute or two to sink in (the rest of the article will help, of course). The point here is not to master every single language (which is (1) pointless and (2) impossible), but to get a handle on what is out there. For any language, there is a handful of other languages like it, and if you can at least read one language in most of those categories, you will have mastered a fairly large chunk of the programming universe. When a new project comes up, and something about it reminds you of some language you found, you can just learn that language as part of doing the project. It may sound like a lot of work, but after, say, your fifth big language, you completely lose count and just accidentally learn new ones all the time without noticing.\nWhen you stop relating to one language as your home-language, you'll be able to learn from examples in other languages even if you've never programmed in them. Personally, I've only written a few Haskell programs, but being able to read Haskell has exposed me to a lot of ideas that I could recycle in more practical Scala and Python programs (oh yeah, after you learn Python, give Scala a browse and you'll probably never use Java again)\nEven finding the best language for the job isn't the whole story. Having a lot of tools in your toolbox lets you throw together amazing stuff in short amounts of time by writing each piece of your project in the easiest language your could. This may not be appropriate for all projects, but, boy, can you make some impressive demos.\nIt takes many years to get to the point where no programming language is totally foreign (or at least foreign for more than a day of hacking), but I think it is a very healthy and realistic long-term plan to attempt to conquer a representative sample of each rough category. Good luck!\n",
"Since Python wasn't my first language, I found the Python Cookbook helpful for learning\n\nWhat Python was capable of\nThe idiomatic, of \"pythonic,\" way to do something.\n\n",
"Programming language teaching has always been associated with a cliche statement while learning. \"Write programs to learn programming\". I too would suggest the same.\nIf you are going to start from basics. This is of course, the most suggested starting point. It is lengthy, but it is worth all the time. http://www.diveintopython.org/\nBecause you are into some Java, this might be even better for you. http://www.swaroopch.com/notes/Python. Start either python 2.x or 3.0. Me personally am a fan of python 3. But for a starter it could be hard to get samples, and references to programs online. So for you 2.x might be better. But I leave it upto you.\nLike I started \"Write programs..\". You can start here.\n\nhttp://www.spoj.pl/ - a programming challenges site, where you can choose from a wide variety of topics, mostly algorithms and has huge question database. Of course the choice of programming languages is upto you.\nhttp://projecteuler.net/ - a mathematical questions site, here you just have to submit an answer, cheating is allowed here, so be free to borrow logic from others, but try writing the program yourself.\n\nAfter you think you have gained sufficient proficiency in python, you can try recipes in this book python cookbook http://www.amazon.com/Python-Cookbook-Alex-Martelli/dp/0596007973.\nFor application development, after you think you can handle it, start on wxPython or PyQt. I personally would suggest PyQt. It is responsive, fast, and has decent development cycle, I have not used WxPython for long, but few programs I wrote, long back, didn't feel so great. Yet again, its upto you.\n"
] |
[
14,
9,
5,
3,
1,
1,
1,
0,
0,
0,
0
] |
[] |
[] |
[
"python",
"theory"
] |
stackoverflow_0000805720_python_theory.txt
|
Q:
Faster way to sum a list of numbers than with a for-loop?
Is there a way to sum up a list of numbers faster than with a for-loop, perhaps in the Python library? Or is that something really only multi-threading / vector processing can do efficiently?
Edit: Just to clarify, it could be a list of any numbers, unsorted, just input from the user.
A:
You can use sum() to sum the values of an array.
a = [1,9,12]
print sum(a)
A:
Yet another way to sum up a list with the loop time:
s = reduce(lambda x, y: x + y, l)
A:
If each term in the list simply increments by 1, or if you can find a pattern in the series, you could find a formula for summing n terms. For example, the sum of the series {1,2,3,...,n} = n(n+1)/2
Read more here
A:
Well, I don't know if it is faster but you could try a little calculus to make it one operation. (N*(N+1))/2 gives you the sum of every number from 1 to N, and there are other formulas for solving more complex sums.
|
Faster way to sum a list of numbers than with a for-loop?
|
Is there a way to sum up a list of numbers faster than with a for-loop, perhaps in the Python library? Or is that something really only multi-threading / vector processing can do efficiently?
Edit: Just to clarify, it could be a list of any numbers, unsorted, just input from the user.
|
[
"You can use sum() to sum the values of an array.\na = [1,9,12]\nprint sum(a)\n\n",
"Yet another way to sum up a list with the loop time:\n s = reduce(lambda x, y: x + y, l)\n\n",
"If each term in the list simply increments by 1, or if you can find a pattern in the series, you could find a formula for summing n terms. For example, the sum of the series {1,2,3,...,n} = n(n+1)/2\nRead more here\n",
"Well, I don't know if it is faster but you could try a little calculus to make it one operation. (N*(N+1))/2 gives you the sum of every number from 1 to N, and there are other formulas for solving more complex sums.\n"
] |
[
36,
4,
1,
1
] |
[
"For a general list, you have to at least go over every member at least once to get the sum, which is exactly what a for loop does. Using library APIs (like sum) is more convenient, but I doubt it would actually be faster.\n"
] |
[
-1
] |
[
"algorithm",
"for_loop",
"python"
] |
stackoverflow_0000850877_algorithm_for_loop_python.txt
|
Q:
Is a graph library (eg NetworkX) the right solution for my Python problem?
I'm rewriting a data-driven legacy application in Python. One of the primary tables is referred to as a "graph table", and does appear to be a directed graph, so I was exploring the NetworkX package to see whether it would make sense to use it for the graph table manipulations, and really implement it as a graph rather than a complicated set of arrays.
However I'm starting to wonder whether the way we use this table is poorly suited for an actual graph manipulation library. Most of the NetworkX functionality seems to be oriented towards characterizing the graph itself in some way, determining shortest distance between two nodes, and things like that. None of that is relevant to my application.
I'm hoping if I can describe the actual usage here, someone can advise me whether I'm just missing something -- I've never really worked with graphs before so this is quite possible -- or if I should be exploring some other data structure. (And if so, what would you suggest?)
We use the table primarily to transform a user-supplied string of keywords into an ordered list of components. This constitutes 95% of the use cases; the other 5% are "given a partial keyword string, supply all possible completions" and "generate all possible legal keyword strings". Oh, and validate the graph against malformation.
Here's an edited excerpt of the table. Columns are:
keyword innode outnode component
acs 1 20 clear
default 1 100 clear
noota 20 30 clear
default 20 30 hst_ota
ota 20 30 hst_ota
acs 30 10000 clear
cos 30 11000 clear
sbc 10000 10199 clear
hrc 10000 10150 clear
wfc1 10000 10100 clear
default 10100 10101 clear
default 10101 10130 acs_wfc_im123
f606w 10130 10140 acs_f606w
f550m 10130 10140 acs_f550m
f555w 10130 10140 acs_f555w
default 10140 10300 clear
wfc1 10300 10310 acs_wfc_ebe_win12f
default 10310 10320 acs_wfc_ccd1
Given the keyword string "acs,wfc1,f555w" and this table, the traversal logic is:
Start at node 1; "acs" is in the string, so go to node 20.
None of the presented keywords for node 20 are in the string, so choose the default, pick up hst_ota, and go to node 30.
"acs" is in the string, so go to node 10000.
"wfc1" is in the string, so go to node 10100.
Only one choice; go to node 10101.
Only one choice, so pick up acs_wfc_im123 and go to node 10130.
"f555w" is in the string, so pick up acs_f555w and go to node 10140.
Only one choice, so go to node 10300.
"wfc1" is in the string, so pick up acs_wfc_ebe_win12f and go to node 10310.
Only one choice, so pick up acs_wfc_ccd1 and go to node 10320 -- which doesn't exist, so we're done.
Thus the final list of components is
hst_ota
acs_wfc_im123
acs_f555w
acs_wfc_ebe_win12f
acs_wfc_ccd1
I can make a graph from just the innodes and outnodes of this table, but I couldn't for the life of me figure out how to build in the keyword information that determines which choice to make when faced with multiple possibilities.
Updated to add examples of the other use cases:
Given a string "acs", return ("hrc","wfc1") as possible legal next choices
Given a string "acs, wfc1, foo", raise an exception due to an unused keyword
Return all possible legal strings:
cos
acs, hrc
acs, wfc1, f606w
acs, wfc1, f550m
acs, wfc1, f555w
Validate that all nodes can be reached and that there are no loops.
I can tweak Alex's solution for the first two of these, but I don't see how to do it for the last two.
A:
Definitely not suitable for general purpose graph libraries (whatever you're supposed to do if more than one of the words meaningful in a node is in the input string -- is that an error? -- or if none does and there is no default for the node, as for node 30 in the example you supply). Just write the table as a dict from node to tuple (default stuff, dict from word to specific stuff) where each stuff is a tuple (destination, word-to-add) (and use None for the special "word-to-add" clear). So e.g.:
tab = {1: (100, None), {'acs': (20, None)}),
20: ((30, 'hst_ota'), {'ota': (30, 'hst_ota'), 'noota': (30, None)}),
30: ((None, None), {'acs': (10000,None), 'cos':(11000,None)}),
etc etc
Now handling this table and an input comma-separated string is easy, thanks to set operations -- e.g.:
def f(icss):
kws = set(icss.split(','))
N = 1
while N in tab:
stuff, others = tab[N]
found = kws & set(others)
if found:
# maybe error if len(found) > 1 ?
stuff = others[found.pop()]
N, word_to_add = stuff
if word_to_add is not None:
print word_to_add
A:
Adding an answer to respond to the further requirements newly edited in...: I still wouldn't go for a general-purpose library. For "all nodes can be reached and there are no loops", simply reasoning in terms of sets (ignoring the triggering keywords) should do: (again untested code, but the general outline should help even if there's some typo &c):
def add_descendants(someset, node):
"auxiliary function: add all descendants of node to someset"
stuff, others = tab[node]
othernode, _ = stuff
if othernode is not None:
someset.add(othernode)
for othernode, _ in others.values():
if othernode is not None:
someset.add(othernode)
def islegal():
"Return bool, message (bool is True for OK tab, False if not OK)"
# make set of all nodes ever mentioned in the table
all_nodes = set()
for node in tab:
all_nodes.add(node)
add_desendants(all_nodes, node)
# check for loops and connectivity
previously_seen = set()
currently_seen = set([1])
while currently_seen:
node = currently_seen.pop()
if node in previously_seen:
return False, "loop involving node %s" % node
previously_seen.add(node)
add_descendants(currently_seen, node)
unreachable = all_nodes - currently_seen
if unreachable:
return False, "%d unreachable nodes: %s" % (len(unreachable), unreachable)
else:
terminal = currently_seen - set(tab)
if terminal:
return True, "%d terminal nodes: %s" % (len(terminal), terminal)
return True, "Everything hunky-dory"
For the "legal strings" you'll need some other code, but I can't write it for you because I have not yet understood what makes a string legal or otherwise...!
|
Is a graph library (eg NetworkX) the right solution for my Python problem?
|
I'm rewriting a data-driven legacy application in Python. One of the primary tables is referred to as a "graph table", and does appear to be a directed graph, so I was exploring the NetworkX package to see whether it would make sense to use it for the graph table manipulations, and really implement it as a graph rather than a complicated set of arrays.
However I'm starting to wonder whether the way we use this table is poorly suited for an actual graph manipulation library. Most of the NetworkX functionality seems to be oriented towards characterizing the graph itself in some way, determining shortest distance between two nodes, and things like that. None of that is relevant to my application.
I'm hoping if I can describe the actual usage here, someone can advise me whether I'm just missing something -- I've never really worked with graphs before so this is quite possible -- or if I should be exploring some other data structure. (And if so, what would you suggest?)
We use the table primarily to transform a user-supplied string of keywords into an ordered list of components. This constitutes 95% of the use cases; the other 5% are "given a partial keyword string, supply all possible completions" and "generate all possible legal keyword strings". Oh, and validate the graph against malformation.
Here's an edited excerpt of the table. Columns are:
keyword innode outnode component
acs 1 20 clear
default 1 100 clear
noota 20 30 clear
default 20 30 hst_ota
ota 20 30 hst_ota
acs 30 10000 clear
cos 30 11000 clear
sbc 10000 10199 clear
hrc 10000 10150 clear
wfc1 10000 10100 clear
default 10100 10101 clear
default 10101 10130 acs_wfc_im123
f606w 10130 10140 acs_f606w
f550m 10130 10140 acs_f550m
f555w 10130 10140 acs_f555w
default 10140 10300 clear
wfc1 10300 10310 acs_wfc_ebe_win12f
default 10310 10320 acs_wfc_ccd1
Given the keyword string "acs,wfc1,f555w" and this table, the traversal logic is:
Start at node 1; "acs" is in the string, so go to node 20.
None of the presented keywords for node 20 are in the string, so choose the default, pick up hst_ota, and go to node 30.
"acs" is in the string, so go to node 10000.
"wfc1" is in the string, so go to node 10100.
Only one choice; go to node 10101.
Only one choice, so pick up acs_wfc_im123 and go to node 10130.
"f555w" is in the string, so pick up acs_f555w and go to node 10140.
Only one choice, so go to node 10300.
"wfc1" is in the string, so pick up acs_wfc_ebe_win12f and go to node 10310.
Only one choice, so pick up acs_wfc_ccd1 and go to node 10320 -- which doesn't exist, so we're done.
Thus the final list of components is
hst_ota
acs_wfc_im123
acs_f555w
acs_wfc_ebe_win12f
acs_wfc_ccd1
I can make a graph from just the innodes and outnodes of this table, but I couldn't for the life of me figure out how to build in the keyword information that determines which choice to make when faced with multiple possibilities.
Updated to add examples of the other use cases:
Given a string "acs", return ("hrc","wfc1") as possible legal next choices
Given a string "acs, wfc1, foo", raise an exception due to an unused keyword
Return all possible legal strings:
cos
acs, hrc
acs, wfc1, f606w
acs, wfc1, f550m
acs, wfc1, f555w
Validate that all nodes can be reached and that there are no loops.
I can tweak Alex's solution for the first two of these, but I don't see how to do it for the last two.
|
[
"Definitely not suitable for general purpose graph libraries (whatever you're supposed to do if more than one of the words meaningful in a node is in the input string -- is that an error? -- or if none does and there is no default for the node, as for node 30 in the example you supply). Just write the table as a dict from node to tuple (default stuff, dict from word to specific stuff) where each stuff is a tuple (destination, word-to-add) (and use None for the special \"word-to-add\" clear). So e.g.:\ntab = {1: (100, None), {'acs': (20, None)}),\n 20: ((30, 'hst_ota'), {'ota': (30, 'hst_ota'), 'noota': (30, None)}),\n 30: ((None, None), {'acs': (10000,None), 'cos':(11000,None)}),\n etc etc\n\nNow handling this table and an input comma-separated string is easy, thanks to set operations -- e.g.:\ndef f(icss):\n kws = set(icss.split(','))\n N = 1\n while N in tab:\n stuff, others = tab[N]\n found = kws & set(others)\n if found:\n # maybe error if len(found) > 1 ?\n stuff = others[found.pop()]\n N, word_to_add = stuff\n if word_to_add is not None:\n print word_to_add\n\n",
"Adding an answer to respond to the further requirements newly edited in...: I still wouldn't go for a general-purpose library. For \"all nodes can be reached and there are no loops\", simply reasoning in terms of sets (ignoring the triggering keywords) should do: (again untested code, but the general outline should help even if there's some typo &c):\ndef add_descendants(someset, node):\n \"auxiliary function: add all descendants of node to someset\"\n stuff, others = tab[node]\n othernode, _ = stuff\n if othernode is not None:\n someset.add(othernode)\n for othernode, _ in others.values():\n if othernode is not None:\n someset.add(othernode)\n\ndef islegal():\n \"Return bool, message (bool is True for OK tab, False if not OK)\"\n # make set of all nodes ever mentioned in the table\n all_nodes = set()\n for node in tab:\n all_nodes.add(node)\n add_desendants(all_nodes, node)\n\n # check for loops and connectivity\n previously_seen = set()\n currently_seen = set([1])\n while currently_seen:\n node = currently_seen.pop()\n if node in previously_seen:\n return False, \"loop involving node %s\" % node\n previously_seen.add(node)\n add_descendants(currently_seen, node)\n\n unreachable = all_nodes - currently_seen\n if unreachable:\n return False, \"%d unreachable nodes: %s\" % (len(unreachable), unreachable)\n else:\n terminal = currently_seen - set(tab)\n if terminal:\n return True, \"%d terminal nodes: %s\" % (len(terminal), terminal)\n return True, \"Everything hunky-dory\"\n\nFor the \"legal strings\" you'll need some other code, but I can't write it for you because I have not yet understood what makes a string legal or otherwise...!\n"
] |
[
2,
0
] |
[] |
[] |
[
"graph",
"python"
] |
stackoverflow_0000844505_graph_python.txt
|
Q:
Python -- Regex -- How to find a string between two sets of strings
Consider the following:
<div id=hotlinklist>
<a href="foo1.com">Foo1</a>
<div id=hotlink>
<a href="/">Home</a>
</div>
<div id=hotlink>
<a href="/extract">Extract</a>
</div>
<div id=hotlink>
<a href="/sitemap">Sitemap</a>
</div>
</div>
How would you go about taking out the sitemap line with regex in python?
<a href="/sitemap">Sitemap</a>
The following can be used to pull out the anchor tags.
'/<a(.*?)a>/i'
However, there are multiple anchor tags. Also there are multiple hotlink(s) so we can't really use them either?
A:
Don't use a regex. Use BeautfulSoup, an HTML parser.
from BeautifulSoup import BeautifulSoup
html = \
"""
<div id=hotlinklist>
<a href="foo1.com">Foo1</a>
<div id=hotlink>
<a href="/">Home</a>
</div>
<div id=hotlink>
<a href="/extract">Extract</a>
</div>
<div id=hotlink>
<a href="/sitemap">Sitemap</a>
</div>
</div>"""
soup = BeautifulSoup(html)
soup.findAll("div",id="hotlink")[2].a
# <a href="/sitemap">Sitemap</a>
A:
Parsing HTML with regular expression is a bad idea!
Think about the following piece of html
<a></a > <!-- legal html, but won't pass your regex -->
<a href="/sitemap">Sitemap<!-- proof that a>b iff ab>1 --></a>
There are many more such examples. Regular expressions are good for many things, but not for parsing HTML.
You should consider using Beautiful Soup python HTML parser.
Anyhow, a ad-hoc solution using regex is
import re
data = """
<div id=hotlinklist>
<a href="foo1.com">Foo1</a>
<div id=hotlink>
<a href="/">Home</a>
</div>
<div id=hotlink>
<a href="/extract">Extract</a>
</div>
<div id=hotlink>
<a href="/sitemap">Sitemap</a>
</div>
</div>
"""
e = re.compile('<a *[^>]*>.*</a *>')
print e.findall(data)
Output:
>>> e.findall(data)
['<a href="foo1.com">Foo1</a>', '<a href="/">Home</a>', '<a href="/extract">Extract</a>', '<a href="/sitemap">Sitemap</a>']
A:
In order to extract the contents of the tagline:
<a href="/sitemap">Sitemap</a>
... I would use:
>>> import re
>>> s = '''
<div id=hotlinklist>
<a href="foo1.com">Foo1</a>
<div id=hotlink>
<a href="/">Home</a>
</div>
<div id=hotlink>
<a href="/extract">Extract</a>
</div>
<div id=hotlink>
<a href="/sitemap">Sitemap</a>
</div>
</div>'''
>>> m = re.compile(r'<a href="/sitemap">(.*?)</a>').search(s)
>>> m.group(1)
'Sitemap'
A:
Use BeautifulSoup or lxml if you need to parse HTML.
Also, what is it that you really need to do? Find the last link? Find the third link? Find the link that points to /sitemap? It's unclear from you question. What do you need to do with the data?
If you really have to use regular expressions, have a look at findall.
|
Python -- Regex -- How to find a string between two sets of strings
|
Consider the following:
<div id=hotlinklist>
<a href="foo1.com">Foo1</a>
<div id=hotlink>
<a href="/">Home</a>
</div>
<div id=hotlink>
<a href="/extract">Extract</a>
</div>
<div id=hotlink>
<a href="/sitemap">Sitemap</a>
</div>
</div>
How would you go about taking out the sitemap line with regex in python?
<a href="/sitemap">Sitemap</a>
The following can be used to pull out the anchor tags.
'/<a(.*?)a>/i'
However, there are multiple anchor tags. Also there are multiple hotlink(s) so we can't really use them either?
|
[
"Don't use a regex. Use BeautfulSoup, an HTML parser.\nfrom BeautifulSoup import BeautifulSoup\n\nhtml = \\\n\"\"\"\n<div id=hotlinklist>\n <a href=\"foo1.com\">Foo1</a>\n <div id=hotlink>\n <a href=\"/\">Home</a>\n </div>\n <div id=hotlink>\n <a href=\"/extract\">Extract</a>\n </div>\n <div id=hotlink>\n <a href=\"/sitemap\">Sitemap</a>\n </div>\n</div>\"\"\"\n\nsoup = BeautifulSoup(html)\nsoup.findAll(\"div\",id=\"hotlink\")[2].a\n\n# <a href=\"/sitemap\">Sitemap</a>\n\n",
"Parsing HTML with regular expression is a bad idea!\nThink about the following piece of html\n<a></a > <!-- legal html, but won't pass your regex -->\n\n<a href=\"/sitemap\">Sitemap<!-- proof that a>b iff ab>1 --></a>\n\nThere are many more such examples. Regular expressions are good for many things, but not for parsing HTML.\nYou should consider using Beautiful Soup python HTML parser.\nAnyhow, a ad-hoc solution using regex is\nimport re\n\ndata = \"\"\"\n<div id=hotlinklist>\n <a href=\"foo1.com\">Foo1</a>\n <div id=hotlink>\n <a href=\"/\">Home</a>\n </div>\n <div id=hotlink>\n <a href=\"/extract\">Extract</a>\n </div>\n <div id=hotlink>\n <a href=\"/sitemap\">Sitemap</a>\n </div>\n</div>\n\"\"\"\n\ne = re.compile('<a *[^>]*>.*</a *>')\n\nprint e.findall(data)\n\nOutput:\n>>> e.findall(data)\n['<a href=\"foo1.com\">Foo1</a>', '<a href=\"/\">Home</a>', '<a href=\"/extract\">Extract</a>', '<a href=\"/sitemap\">Sitemap</a>']\n\n",
"In order to extract the contents of the tagline:\n <a href=\"/sitemap\">Sitemap</a>\n\n... I would use:\n >>> import re\n >>> s = '''\n <div id=hotlinklist>\n <a href=\"foo1.com\">Foo1</a>\n <div id=hotlink>\n <a href=\"/\">Home</a>\n </div>\n <div id=hotlink>\n <a href=\"/extract\">Extract</a>\n </div>\n <div id=hotlink>\n <a href=\"/sitemap\">Sitemap</a>\n </div>\n </div>'''\n >>> m = re.compile(r'<a href=\"/sitemap\">(.*?)</a>').search(s)\n >>> m.group(1)\n 'Sitemap'\n\n",
"Use BeautifulSoup or lxml if you need to parse HTML.\nAlso, what is it that you really need to do? Find the last link? Find the third link? Find the link that points to /sitemap? It's unclear from you question. What do you need to do with the data?\nIf you really have to use regular expressions, have a look at findall.\n"
] |
[
13,
6,
5,
1
] |
[] |
[] |
[
"python",
"regex",
"string",
"tags"
] |
stackoverflow_0000849912_python_regex_string_tags.txt
|
Q:
What's the most efficient way to insert thousands of records into a table (MySQL, Python, Django)
I have a database table with a unique string field and a couple of integer fields. The string field is usually 10-100 characters long.
Once every minute or so I have the following scenario: I receive a list of 2-10 thousand tuples corresponding to the table's record structure, e.g.
[("hello", 3, 4), ("cat", 5, 3), ...]
I need to insert all these tuples to the table (assume I verified neither of these strings appear in the database). For clarification, I'm using InnoDB, and I have an auto-incremental primary key for this table, the string is not the PK.
My code currently iterates through this list, for each tuple creates a Python module object with the appropriate values, and calls ".save()", something like so:
@transaction.commit_on_success
def save_data_elements(input_list):
for (s, i1, i2) in input_list:
entry = DataElement(string=s, number1=i1, number2=i2)
entry.save()
This code is currently one of the performance bottlenecks in my system, so I'm looking for ways to optimize it.
For example, I could generate SQL codes each containing an INSERT command for 100 tuples ("hard-coded" into the SQL) and execute it, but I don't know if it will improve anything.
Do you have any suggestion to optimize such a process?
Thanks
A:
For MySQL specifically, the fastest way to load data is using LOAD DATA INFILE, so if you could convert the data into the format that expects, it'll probably be the fastest way to get it into the table.
A:
You can write the rows to a file in the format
"field1", "field2", .. and then use LOAD DATA to load them
data = '\n'.join(','.join('"%s"' % field for field in row) for row in data)
f= open('data.txt', 'w')
f.write(data)
f.close()
Then execute this:
LOAD DATA INFILE 'data.txt' INTO TABLE db2.my_table;
Reference
A:
If you don't LOAD DATA INFILE as some of the other suggestions mention, two things you can do to speed up your inserts are :
Use prepared statements - this cuts out the overhead of parsing the SQL for every insert
Do all of your inserts in a single transaction - this would require using a DB engine that supports transactions (like InnoDB)
A:
If you can do a hand-rolled INSERT statement, then that's the way I'd go. A single INSERT statement with multiple value clauses is much much faster than lots of individual INSERT statements.
A:
Regardless of the insert method, you will want to use the InnoDB engine for maximum read/write concurrency. MyISAM will lock the entire table for the duration of the insert whereas InnoDB (under most circumstances) will only lock the affected rows, allowing SELECT statements to proceed.
A:
what format do you receive? if it is a file, you can do some sort of bulk load: http://www.classes.cs.uchicago.edu/archive/2005/fall/23500-1/mysql-load.html
A:
This is unrelated to the actual load of data into the DB, but...
If providing a "The data is loading... The load will be done shortly" type of message to the user is an option, then you can run the INSERTs or LOAD DATA asynchronously in a different thread.
Just something else to consider.
A:
I donot know the exact details, but u can use json style data representation and use it as fixtures or something. I saw something similar on Django Video Workshop by Douglas Napoleone. See the videos at http://www.linux-magazine.com/online/news/django_video_workshop. and http://www.linux-magazine.com/online/features/django_reloaded_workshop_part_1. Hope this one helps.
Hope you can work it out. I just started learning django, so I can just point you to resources.
|
What's the most efficient way to insert thousands of records into a table (MySQL, Python, Django)
|
I have a database table with a unique string field and a couple of integer fields. The string field is usually 10-100 characters long.
Once every minute or so I have the following scenario: I receive a list of 2-10 thousand tuples corresponding to the table's record structure, e.g.
[("hello", 3, 4), ("cat", 5, 3), ...]
I need to insert all these tuples to the table (assume I verified neither of these strings appear in the database). For clarification, I'm using InnoDB, and I have an auto-incremental primary key for this table, the string is not the PK.
My code currently iterates through this list, for each tuple creates a Python module object with the appropriate values, and calls ".save()", something like so:
@transaction.commit_on_success
def save_data_elements(input_list):
for (s, i1, i2) in input_list:
entry = DataElement(string=s, number1=i1, number2=i2)
entry.save()
This code is currently one of the performance bottlenecks in my system, so I'm looking for ways to optimize it.
For example, I could generate SQL codes each containing an INSERT command for 100 tuples ("hard-coded" into the SQL) and execute it, but I don't know if it will improve anything.
Do you have any suggestion to optimize such a process?
Thanks
|
[
"For MySQL specifically, the fastest way to load data is using LOAD DATA INFILE, so if you could convert the data into the format that expects, it'll probably be the fastest way to get it into the table.\n",
"You can write the rows to a file in the format\n\"field1\", \"field2\", .. and then use LOAD DATA to load them\ndata = '\\n'.join(','.join('\"%s\"' % field for field in row) for row in data)\nf= open('data.txt', 'w')\nf.write(data)\nf.close()\n\nThen execute this:\nLOAD DATA INFILE 'data.txt' INTO TABLE db2.my_table;\n\nReference\n",
"If you don't LOAD DATA INFILE as some of the other suggestions mention, two things you can do to speed up your inserts are :\n\nUse prepared statements - this cuts out the overhead of parsing the SQL for every insert\nDo all of your inserts in a single transaction - this would require using a DB engine that supports transactions (like InnoDB)\n\n",
"If you can do a hand-rolled INSERT statement, then that's the way I'd go. A single INSERT statement with multiple value clauses is much much faster than lots of individual INSERT statements.\n",
"Regardless of the insert method, you will want to use the InnoDB engine for maximum read/write concurrency. MyISAM will lock the entire table for the duration of the insert whereas InnoDB (under most circumstances) will only lock the affected rows, allowing SELECT statements to proceed.\n",
"what format do you receive? if it is a file, you can do some sort of bulk load: http://www.classes.cs.uchicago.edu/archive/2005/fall/23500-1/mysql-load.html\n",
"This is unrelated to the actual load of data into the DB, but...\nIf providing a \"The data is loading... The load will be done shortly\" type of message to the user is an option, then you can run the INSERTs or LOAD DATA asynchronously in a different thread.\nJust something else to consider.\n",
"I donot know the exact details, but u can use json style data representation and use it as fixtures or something. I saw something similar on Django Video Workshop by Douglas Napoleone. See the videos at http://www.linux-magazine.com/online/news/django_video_workshop. and http://www.linux-magazine.com/online/features/django_reloaded_workshop_part_1. Hope this one helps.\nHope you can work it out. I just started learning django, so I can just point you to resources.\n"
] |
[
12,
12,
4,
4,
2,
1,
1,
1
] |
[] |
[] |
[
"django",
"insert",
"mysql",
"python",
"sql"
] |
stackoverflow_0000850117_django_insert_mysql_python_sql.txt
|
Q:
Django ImageField issue
I have a similar model
Class Student(models.Model):
"""A simple class which holds the basic info
of a student."""
name = models.CharField(max_length=50)
age = models.PositiveIntegerField()
photo = models.ImageField(upload_to='foobar', blank=True, null=True)
As we can see photo field is optional. I wanted all the students who have their images saved in the college DB. For that i did this
>>> Student.objects.exclude(photo__name=None)
But i am getting this error :
FieldError: Join on field 'photo' not permitted.
So, How can i extract all those students having their photos?
Any sort of help regarding this would be appreciated.
Thanks in advance.
A:
It doesn't work because field lookups only work on other models. Here, name is an attribute on the return value of your photo field.
Try this instead:
Student.objects.exclude(photo__isnull=True)
It is preferred to use isnull instead of comparing equality to None.
EDIT:
Jeff Ober's suggestion:
Student.objects.exclude(photo='')
He says filtering is performed on the actual values stored in DB. In a file field's case the path to the file.
|
Django ImageField issue
|
I have a similar model
Class Student(models.Model):
"""A simple class which holds the basic info
of a student."""
name = models.CharField(max_length=50)
age = models.PositiveIntegerField()
photo = models.ImageField(upload_to='foobar', blank=True, null=True)
As we can see photo field is optional. I wanted all the students who have their images saved in the college DB. For that i did this
>>> Student.objects.exclude(photo__name=None)
But i am getting this error :
FieldError: Join on field 'photo' not permitted.
So, How can i extract all those students having their photos?
Any sort of help regarding this would be appreciated.
Thanks in advance.
|
[
"It doesn't work because field lookups only work on other models. Here, name is an attribute on the return value of your photo field.\nTry this instead:\nStudent.objects.exclude(photo__isnull=True)\n\nIt is preferred to use isnull instead of comparing equality to None.\nEDIT:\nJeff Ober's suggestion:\nStudent.objects.exclude(photo='')\n\nHe says filtering is performed on the actual values stored in DB. In a file field's case the path to the file.\n"
] |
[
13
] |
[] |
[] |
[
"django",
"django_models",
"python"
] |
stackoverflow_0000851830_django_django_models_python.txt
|
Q:
Reverse proxy capable pure python webserver?
I am looking for a pure python based web server has the capability for reverse proxy as well?
A:
pretty sure you can do that with twisted,
twisted web
but why not just use apache?
|
Reverse proxy capable pure python webserver?
|
I am looking for a pure python based web server has the capability for reverse proxy as well?
|
[
"pretty sure you can do that with twisted,\ntwisted web\nbut why not just use apache?\n"
] |
[
2
] |
[] |
[] |
[
"proxy",
"python",
"reverse",
"webserver"
] |
stackoverflow_0000852541_proxy_python_reverse_webserver.txt
|
Q:
Python equivalent of perl's dbi/DBD::Proxy access? (Perl DBI/DBD::Proxy for Python)
I have a Perl script that interfaces with an existing database (type of database is unknown) through the DBI module, that I would like to access in python 2.6 on WinXP.
The Perl code is:
use DBI;
my $DSN = "DBI:Proxy:hostname=some.dot.com;port=12345;dsn=DBI:XXXX:ZZZZZ";
my $dbh = DBI->connect($DSN);
Can this be translated into a python equivalent?
Following an example at (Is there any pywin32 odbc connector documentation available? ), I've put together the following:
import odbc
DSN = "DBI:Proxy:hostname=some.dot.com;port=12345;dsn=DBI:XXXX:ZZZZZ"
db = odbc.odbc(DSN)
But I get the error:
dbi.operation-error: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified in LOGIN
UPDATE
It appears that another Perl module, DBD::Proxy is providing the actual interface to a Perl DBI::ProxyServer (server-side) implementation that handles the actual queries.
Can python be used to interface with the Perl-based DBI::ProxyServer?
http://metacpan.org/pod/DBD::Proxy
http://hell.org.ua/Docs/oreilly/weblinux/dbi/ch08_02.htm
A:
Your python script doesn't have to be a line by line translation of your Perl script.
Why not just use the Python DB-API compatible module for the database you want to access? For MySQL, use MySQLdb. For PostgreSQL, use PyGreSQL.
Or search Google for "YourDatabaseName + python"
A:
sqlalchemy is pretty nice.
|
Python equivalent of perl's dbi/DBD::Proxy access? (Perl DBI/DBD::Proxy for Python)
|
I have a Perl script that interfaces with an existing database (type of database is unknown) through the DBI module, that I would like to access in python 2.6 on WinXP.
The Perl code is:
use DBI;
my $DSN = "DBI:Proxy:hostname=some.dot.com;port=12345;dsn=DBI:XXXX:ZZZZZ";
my $dbh = DBI->connect($DSN);
Can this be translated into a python equivalent?
Following an example at (Is there any pywin32 odbc connector documentation available? ), I've put together the following:
import odbc
DSN = "DBI:Proxy:hostname=some.dot.com;port=12345;dsn=DBI:XXXX:ZZZZZ"
db = odbc.odbc(DSN)
But I get the error:
dbi.operation-error: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified in LOGIN
UPDATE
It appears that another Perl module, DBD::Proxy is providing the actual interface to a Perl DBI::ProxyServer (server-side) implementation that handles the actual queries.
Can python be used to interface with the Perl-based DBI::ProxyServer?
http://metacpan.org/pod/DBD::Proxy
http://hell.org.ua/Docs/oreilly/weblinux/dbi/ch08_02.htm
|
[
"Your python script doesn't have to be a line by line translation of your Perl script.\nWhy not just use the Python DB-API compatible module for the database you want to access? For MySQL, use MySQLdb. For PostgreSQL, use PyGreSQL. \nOr search Google for \"YourDatabaseName + python\"\n",
"sqlalchemy is pretty nice.\n"
] |
[
5,
0
] |
[] |
[] |
[
"dbi",
"odbc",
"perl",
"python"
] |
stackoverflow_0000847032_dbi_odbc_perl_python.txt
|
Q:
Reverse proxy capable pure python webserver?
I am looking for a pure python based web server has the capability for reverse proxy as well?
A:
Have a look at Twisted, especially its ReverseProxyResource.
Twisted Web also provides various facilities for being set up behind a reverse-proxy, which is the suggested mechanism to integrate your Twisted application with an existing site.
A:
http://pypi.python.org/pypi/proxylet/
From http://www.rfk.id.au/blog/entry/proxylet-lightweight-HTTP-reverse-proxy
proxylet is a lightweight reverse proxy for HTTP with nonblocking IO courtesy of eventlet.
Looks like source is available as well. I've never used it, as we use IHS for all our reverse proxy needs.
|
Reverse proxy capable pure python webserver?
|
I am looking for a pure python based web server has the capability for reverse proxy as well?
|
[
"Have a look at Twisted, especially its ReverseProxyResource.\n\nTwisted Web also provides various facilities for being set up behind a reverse-proxy, which is the suggested mechanism to integrate your Twisted application with an existing site.\n\n",
"http://pypi.python.org/pypi/proxylet/\nFrom http://www.rfk.id.au/blog/entry/proxylet-lightweight-HTTP-reverse-proxy\n\nproxylet is a lightweight reverse proxy for HTTP with nonblocking IO courtesy of eventlet.\n\nLooks like source is available as well. I've never used it, as we use IHS for all our reverse proxy needs.\n"
] |
[
3,
0
] |
[] |
[] |
[
"proxy",
"python",
"reverse",
"webserver"
] |
stackoverflow_0000852690_proxy_python_reverse_webserver.txt
|
Q:
Python: getting a reference to a function from inside itself
If I define a function:
def f(x):
return x+3
I can later store objects as attributes of the function, like so:
f.thing="hello!"
I would like to do this from inside the code of the function itself. Problem is, how do I get a reference to the function from inside itself?
A:
The same way, just use its name.
>>> def g(x):
... g.r = 4
...
>>> g
<function g at 0x0100AD68>
>>> g(3)
>>> g.r
4
A:
If you are trying to do memoization, you can use a dictionary as a default parameter:
def f(x, memo={}):
if x not in memo:
memo[x] = x + 3
return memo[x]
A:
Or use a closure:
def gen_f():
memo = dict()
def f(x):
try:
return memo[x]
except KeyError:
memo[x] = x + 3
return f
f = gen_f()
f(123)
Somewhat nicer IMHO
|
Python: getting a reference to a function from inside itself
|
If I define a function:
def f(x):
return x+3
I can later store objects as attributes of the function, like so:
f.thing="hello!"
I would like to do this from inside the code of the function itself. Problem is, how do I get a reference to the function from inside itself?
|
[
"The same way, just use its name.\n>>> def g(x):\n... g.r = 4\n...\n>>> g\n<function g at 0x0100AD68>\n>>> g(3)\n>>> g.r\n4\n\n",
"If you are trying to do memoization, you can use a dictionary as a default parameter:\ndef f(x, memo={}):\n if x not in memo:\n memo[x] = x + 3\n return memo[x]\n\n",
"Or use a closure:\ndef gen_f():\n memo = dict()\n def f(x):\n try:\n return memo[x]\n except KeyError:\n memo[x] = x + 3\n return f\nf = gen_f()\nf(123)\n\nSomewhat nicer IMHO\n"
] |
[
21,
3,
3
] |
[] |
[] |
[
"function",
"python",
"self_reference"
] |
stackoverflow_0000852401_function_python_self_reference.txt
|
Q:
Tokenizing left over data with lex/yacc
Forgive me, I'm completely new to parsing and lex/yacc, and I'm probably in way over my head, but nonetheless:
I'm writing a pretty basic calculator with PLY, but it's input might not always be an equation, and I need to determine if it is or not when parsing. The extremes of the input would be something that evaluates perfectly to an equation, which it parses fine and calculates, or something that is nothing like an equation, which fails parsing and is also fine.
The gray area is an input that has equation-like parts, of which the parser will grab and work out. This isn't what I want - I need to be able to tell if parts of the string didn't get picked up and tokenized so I can throw back an error, but I have no idea how to do this.
Does anyone know how I can define, basically, a 'catch anything that's left' token? Or is there a better way I can handle this?
A:
There is a built-in error token in yacc. You would normally do something like:
line: goodline | badline ;
badline : error '\n' /* Error-handling action, if needed */
goodline : equation '\n' ;
Any line that doesn't match equation will be handled by badline.
You might want to use yyerrok in the error handling action to ensure error processing is reset for the next line.
A:
Define a token (end of input), and make your lexer output it at the end of the input.
So before, if you had these tokens:
'1' 'PLUS' '1'
You'll now have:
'1' 'PLUS' '1' 'END_OF_INPUT'
Now, you can define your top-level rule in your parser. Instead of (for example):
Equation ::= EXPRESSION
You'll have
Equation ::= EXPRESSION END_OF_INPUT
Obviously you'll have to rewrite these in PLY syntax, but this should get you most of the way.
A:
I typically use a separate 'command reader' to obtain a complete command - probably a line in your case - into a host variable string, and then arrange for the lexical analyzer to analyze the string, including telling me when it didn't reach the end. This is hard to set up, but make some classes of error reporting easier. One of the places I've used this technique routinely has multi-line commands with 3 comment conventions, two sets of quoted strings, and some other nasties to set my teeth on edge (context sensitive tokenization - yuck!).
Otherwise, Don's advice with the Yacc 'error' token is good.
A:
It looks like you've already found a solution but I'll add another suggestion in case you or others are interested in an alternative approach.
You say you are using PLY but is that because you want the compiler to run in a Python environment? If so, you might consider other tools as well. For such jobs I often use ANTLR (http://www.antlr.org) which has a Python code generator. ANTLR has lots of tricks for doing things like eating a bunch of input at the lexer level so the parser never sees it (e.g. comments), ability to call a sub-rule (e.g. equation) within a larger grammar (which should terminate once the rule has been matched without processing any more input...sounds somewhat like what you want to do) and a very nice left-factoring algorithm.
ANTLRs parsing capability combined with the use of the StringTemplate (http://www.stringtemplate.org) engine makes a nice combination and both support Python (among many others).
|
Tokenizing left over data with lex/yacc
|
Forgive me, I'm completely new to parsing and lex/yacc, and I'm probably in way over my head, but nonetheless:
I'm writing a pretty basic calculator with PLY, but it's input might not always be an equation, and I need to determine if it is or not when parsing. The extremes of the input would be something that evaluates perfectly to an equation, which it parses fine and calculates, or something that is nothing like an equation, which fails parsing and is also fine.
The gray area is an input that has equation-like parts, of which the parser will grab and work out. This isn't what I want - I need to be able to tell if parts of the string didn't get picked up and tokenized so I can throw back an error, but I have no idea how to do this.
Does anyone know how I can define, basically, a 'catch anything that's left' token? Or is there a better way I can handle this?
|
[
"There is a built-in error token in yacc. You would normally do something like:\n\nline: goodline | badline ;\nbadline : error '\\n' /* Error-handling action, if needed */\ngoodline : equation '\\n' ;\n\nAny line that doesn't match equation will be handled by badline.\nYou might want to use yyerrok in the error handling action to ensure error processing is reset for the next line.\n",
"Define a token (end of input), and make your lexer output it at the end of the input.\nSo before, if you had these tokens:\n'1' 'PLUS' '1'\n\nYou'll now have:\n'1' 'PLUS' '1' 'END_OF_INPUT'\n\nNow, you can define your top-level rule in your parser. Instead of (for example):\nEquation ::= EXPRESSION\n\nYou'll have\nEquation ::= EXPRESSION END_OF_INPUT\n\nObviously you'll have to rewrite these in PLY syntax, but this should get you most of the way.\n",
"I typically use a separate 'command reader' to obtain a complete command - probably a line in your case - into a host variable string, and then arrange for the lexical analyzer to analyze the string, including telling me when it didn't reach the end. This is hard to set up, but make some classes of error reporting easier. One of the places I've used this technique routinely has multi-line commands with 3 comment conventions, two sets of quoted strings, and some other nasties to set my teeth on edge (context sensitive tokenization - yuck!).\nOtherwise, Don's advice with the Yacc 'error' token is good.\n",
"It looks like you've already found a solution but I'll add another suggestion in case you or others are interested in an alternative approach.\nYou say you are using PLY but is that because you want the compiler to run in a Python environment? If so, you might consider other tools as well. For such jobs I often use ANTLR (http://www.antlr.org) which has a Python code generator. ANTLR has lots of tricks for doing things like eating a bunch of input at the lexer level so the parser never sees it (e.g. comments), ability to call a sub-rule (e.g. equation) within a larger grammar (which should terminate once the rule has been matched without processing any more input...sounds somewhat like what you want to do) and a very nice left-factoring algorithm.\nANTLRs parsing capability combined with the use of the StringTemplate (http://www.stringtemplate.org) engine makes a nice combination and both support Python (among many others).\n"
] |
[
1,
1,
0,
0
] |
[] |
[] |
[
"lex",
"ply",
"python",
"yacc"
] |
stackoverflow_0000841159_lex_ply_python_yacc.txt
|
Q:
How to establish communication between flex and python code build on Google App Engine
I want to communicate using flex client with GAE, I am able to communicate using XMl from GAE to FLex but how should I post from flex3 to python code present on App Engine.
Can anyone give me a hint about how to send login information from Flex to python
Any ideas suggest me some examples.....please provide me some help
Regards,
Radhika
A:
I've been able to use flex on GAE using the examples found at The GAE SWF Project which uses PyAMF.
A:
Do a HTTP post from Flex to your AppEngine app using the URLRequest class.
|
How to establish communication between flex and python code build on Google App Engine
|
I want to communicate using flex client with GAE, I am able to communicate using XMl from GAE to FLex but how should I post from flex3 to python code present on App Engine.
Can anyone give me a hint about how to send login information from Flex to python
Any ideas suggest me some examples.....please provide me some help
Regards,
Radhika
|
[
"I've been able to use flex on GAE using the examples found at The GAE SWF Project which uses PyAMF.\n",
"Do a HTTP post from Flex to your AppEngine app using the URLRequest class.\n"
] |
[
2,
0
] |
[] |
[] |
[
"apache_flex",
"google_app_engine",
"python"
] |
stackoverflow_0000854353_apache_flex_google_app_engine_python.txt
|
Q:
Strange python behaviour
I was bored and playing around with the ipython console and came upon the following behaviour I don't really understand
In [1]: 2**2
Out[1]: 4
In [2]: 2**2**2
Out[2]: 16
In [3]: 2**2**2**2
Out[3]: 65536
In [4]: 2**2**2**2**2
The answer to [4] is not 4294967296L, it's a very long number, but I can't really figure out why.
The number can be found here: http://pastie.org/475714
(Ubuntu 8.10, python 2.5.2, ipython 0.8.4)
(Mac OS X 10.5.6, Python 2.5.1)
A:
Python is going right to left on the mathematical power operation. For example, IN[2] is doing:
2**(4) = 16
IN[3] = 2222 = 22**(4) = 2**16 = 65536
You would need parenthesis if you want it to calculate from left to right. The reason OUT[4] is not outputting the answer you want is because the number is astronomical and Python cannot print it out.
2^65536 = extremely huge
A:
The precedence of the ** operator makes the evaluation goes from right-to-left (instead of the expected left-to-right). In other words:
2**2**2**2 == (2**(2**(2**2)))
A:
This is because the order of precedence in Python causes this equation to be evaluated from right-to-left.
>>> 2**2
4
>>> 2**2**2
16
>>> 2**(2**2)
16
>>> 2**2**2**2
65536
>>> 2**2**(2**2)
65536
>>> 2**(2**(2**2))
65536
>>> 2**2**2**2**2
57896044618658097711785492504343953926634992332820282019728792003956564819968L
>>> 2**2**2**(2**2)
57896044618658097711785492504343953926634992332820282019728792003956564819968L
>>> 2**2**(2**(2**2))
57896044618658097711785492504343953926634992332820282019728792003956564819968L
>>> 2**(2**(2**(2**2)))
57896044618658097711785492504343953926634992332820282019728792003956564819968L
>>> 2**255
57896044618658097711785492504343953926634992332820282019728792003956564819968L
A:
As the other answers already said, it's because ** is evaluated from right to left.
Here is the documentation link, where all the precedences are described.
A:
Evaluating right-to-left, let's look at the steps Python is going through to get these answers:
2**2
4
2**(2**2)
2**(4)
16
2**(2**(2**2))
2**(2**(4))
2**(16)
65536
2**(2**(2**(2**2)))
2**(2**(2**(4)))
2**(2**(16))
2**(65536)
2.0035299304068464649790723515603e+19728
|
Strange python behaviour
|
I was bored and playing around with the ipython console and came upon the following behaviour I don't really understand
In [1]: 2**2
Out[1]: 4
In [2]: 2**2**2
Out[2]: 16
In [3]: 2**2**2**2
Out[3]: 65536
In [4]: 2**2**2**2**2
The answer to [4] is not 4294967296L, it's a very long number, but I can't really figure out why.
The number can be found here: http://pastie.org/475714
(Ubuntu 8.10, python 2.5.2, ipython 0.8.4)
(Mac OS X 10.5.6, Python 2.5.1)
|
[
"Python is going right to left on the mathematical power operation. For example, IN[2] is doing:\n2**(4) = 16\nIN[3] = 2222 = 22**(4) = 2**16 = 65536\nYou would need parenthesis if you want it to calculate from left to right. The reason OUT[4] is not outputting the answer you want is because the number is astronomical and Python cannot print it out. \n2^65536 = extremely huge\n",
"The precedence of the ** operator makes the evaluation goes from right-to-left (instead of the expected left-to-right). In other words:\n2**2**2**2 == (2**(2**(2**2)))\n\n",
"This is because the order of precedence in Python causes this equation to be evaluated from right-to-left.\n>>> 2**2\n4\n>>> 2**2**2\n16\n>>> 2**(2**2)\n16\n>>> 2**2**2**2\n65536\n>>> 2**2**(2**2)\n65536\n>>> 2**(2**(2**2))\n65536\n>>> 2**2**2**2**2\n57896044618658097711785492504343953926634992332820282019728792003956564819968L\n>>> 2**2**2**(2**2)\n57896044618658097711785492504343953926634992332820282019728792003956564819968L\n>>> 2**2**(2**(2**2))\n57896044618658097711785492504343953926634992332820282019728792003956564819968L\n>>> 2**(2**(2**(2**2)))\n57896044618658097711785492504343953926634992332820282019728792003956564819968L\n>>> 2**255\n57896044618658097711785492504343953926634992332820282019728792003956564819968L\n\n",
"As the other answers already said, it's because ** is evaluated from right to left.\nHere is the documentation link, where all the precedences are described.\n",
"Evaluating right-to-left, let's look at the steps Python is going through to get these answers:\n2**2\n4\n\n2**(2**2)\n2**(4)\n16\n\n2**(2**(2**2))\n2**(2**(4))\n2**(16)\n65536\n\n2**(2**(2**(2**2)))\n2**(2**(2**(4)))\n2**(2**(16))\n2**(65536)\n2.0035299304068464649790723515603e+19728\n\n"
] |
[
16,
7,
4,
4,
3
] |
[] |
[] |
[
"ipython",
"python"
] |
stackoverflow_0000853407_ipython_python.txt
|
Q:
Can I Pass Dictionary Values/Entry and Keys to function
I am writing a function and intended to use a dictionary key and its value as parameters. For example:
testDict={'x':2,'xS':4}
def newFunct(key,testDict['key']):
newvalue=key+str(testDict['key'])
return newValue
for key in testDict:
newValue=newFunct(key,testDict[key])
print newValue
I get a SyntaxError: invalid syntax when I hit the return button after typing the semicolon. I am guessing this is telling me I can't pass a dictionary value in that form. Presumably I can define a new variable
for key in testDict:
xdixt=testDict[key]
newValue=newFunct(key,xdixt)
and def the function using xdixt
but I am hoping there is some trick that I am missing. I Googled and found some reference to unpacking a dictionary but that didn't seem to work.
This Python stuff is really cool. My question was came about because I am trying to use some values I stored in a dictionary to create a new directory. Based on the material I read from Stephan's answer I wondered about how to generalize the information I learned. My directory name has five different pieces to it, each piece is the result of processing the values from myDict. The expression to create the directory name was getting too complicated and in my opinion too complicated to easily read. so I wondered if I could use the same approach to put the pieces into a list and then unpack them when it came time to create the directory name and it worked!
def createDirectory(myKey,**myDict):
pathList=[]
pathList.append(myDict['subKey1'])
pathList.append(myDict['subKey2'].lstrip('0'))
pathList.append(myDict['subKey3'])
etc
myPath=os.path.join(*myList)
os.makedirs(myPath)
return(myPath)
A:
Is this what you want?
def func(**kwargs):
for key, value in kwargs.items():
pass # Do something
func(**myDict) # Call func with the given dict as key/value parameters
(See the documentation for more about keyword arguments. The keys in myDict must be strings.)
Edit: you edited your question to include the following:
I think the ** notation in front of myDict instructs the function to expect a dictionary and to unpack the key (the first *) and the value, the second *
This is not correct. To understand what is happening, you must consider the following:
A function can have multiple formal parameters (a and b in this case):
def f1(a, b): pass
We can pass positional arguments to such function (like in most other languages):
f1(2, 3)
We can also pass keyword arguments:
f1(a=2, b=3)
We can also mix these, but the positional arguments must come first:
f1(2, b=3)
f1(a=2, 3) # SyntaxError: non-keyword arg after keyword arg
There is a way to let a function accept an arbitrary number of positional arguments, which it can access as a tuple (args in this case):
def f2(*args): assert isinstance(args, tuple)
Now we can call f2 using separately specified arguments, or using a list whose contents first need to be unpacked, using a syntax similar to the notation used for *args:
f2(2, 3)
f2(*[2, 3])
Likewise, an arbitrary number of keyword arguments may be accepted:
def f3(**kwargs): pass
Note that f3 does not ask for a single argument of type dict. This is the kind of invocations it expects:
f3(a=2, b=3)
f3(**{'a': 2, 'b': 3})
All arguments to f3 must be named:
f3(2, 3) # TypeError: f3() takes exactly 0 arguments (2 given)
Putting all of this together, and remembering that positional arguments must come first, we may have:
>>> def f4(a, b, *args, **kwargs):
... print('%r, %r' % (args, kwargs))
...
>>> f4(2, 3)
(), {}
>>> f4(2, 3, 4, 5)
(4, 5), {}
>>> f4(2, 3, x=4, y=5)
(), {'y': 5, 'x': 4}
>>> f4(2, 3, 4, 5, x=6, y=7)
(4, 5), {'y': 7, 'x': 6}
>>> f4(2, *[3, 4, 5], **{'x': 6, 'y': 7})
(4, 5), {'y': 7, 'x': 6}
Pay special attention to the following two errors:
>>> f4(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f4() takes at least 2 arguments (1 given)
>>> f4(2, 3, a=4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f4() got multiple values for keyword argument 'a'
The second error should help you explain this behavior:
>>> f4(**{'foo': 0, 'a': 2, 'b': 3, 'c': 4})
(), {'c': 4, 'foo': 0}
A:
Not sure why we are bringing in kwargs, this is much simpler than that. You said you're new to Python, I think you just need some Python fundamentals here.
def newFunct(key,testDict['key']):
Should be:
def newFunct(key, val):
There's no reason to use any special syntax on your second parameter to indicate that it's coming from a dictionary. It's just a parameter, you just happen to be passing the value from a dictionary item into it.
Further, once it's in the function, there's no reason to treat it in a special way either. At this point it's just a value. Which means that:
newvalue=key+str(testDict[key])
Can now just be:
newvalue=key+str(val)
So when you call it like this (as you did):
newValue=newFunct(key,testDict[key])
testDict[key] resolves to the value at 'key', which just becomes "val" in the function.
An alternate way, if you see it fit for whatever reason (and this is just something that's good to know), you could define the function thusly:
def newFunct(key, testDict):
Again, the second parameter is just a parameter, so we use the same syntax, but now we're expecting it to be a dict, so we should use it like one:
newvalue=key+str(testDict[key])
(Note: don't put quotes around 'key' in this case. We're referring to the variable called 'key', not a key called 'key'). When you call the function, it looks like this:
newValue=newFunct(key,testDict)
So unlike the first case where you're just passing one variable from the dictionary, you're passing a reference to the whole dictionary into the function this time.
Hope that helps.
A:
why don't you just do:
[k + str(v) for k, v in test_dict.iteritems()]
or for py3k:
[k + str(v) for k, v in test_dict.items()]
edit
def f(k, v):
print(k, v) # or do something much more complicated
for k, v in testDict.items():
f(k, v)
A:
From your description is seems like testDict is some sort of global variable with respect to the function. If this is the case - why do you even need to pass it to the function?
Instead of your code:
testDict={'x':2,'xS':4}
def newFunct(key,testDict[key]):
newvalue=key+str(testDict[key])
return newValue
for key in testDict:
newValue=newFunct(key,testDict[key])
print newValue
You can simply use:
testDict={'x':2,'xS':4}
def newFunct(key):
newvalue=key+str(testDict[key])
return newValue
for key in testDict:
newValue=newFunct(key)
print newValue
If testDict is not meant to be in the global scope (which makes sense...), I would recommend simply passing a name for the dictionary and not "messing around" with variable length argument lists in this case:
testDict={'x':2,'xS':4}
def newFunct(key,dictionary):
newvalue=key+str(dictionary[key])
return newValue
for key in testDict:
newValue=newFunct(key,testDict)
print newValue
|
Can I Pass Dictionary Values/Entry and Keys to function
|
I am writing a function and intended to use a dictionary key and its value as parameters. For example:
testDict={'x':2,'xS':4}
def newFunct(key,testDict['key']):
newvalue=key+str(testDict['key'])
return newValue
for key in testDict:
newValue=newFunct(key,testDict[key])
print newValue
I get a SyntaxError: invalid syntax when I hit the return button after typing the semicolon. I am guessing this is telling me I can't pass a dictionary value in that form. Presumably I can define a new variable
for key in testDict:
xdixt=testDict[key]
newValue=newFunct(key,xdixt)
and def the function using xdixt
but I am hoping there is some trick that I am missing. I Googled and found some reference to unpacking a dictionary but that didn't seem to work.
This Python stuff is really cool. My question was came about because I am trying to use some values I stored in a dictionary to create a new directory. Based on the material I read from Stephan's answer I wondered about how to generalize the information I learned. My directory name has five different pieces to it, each piece is the result of processing the values from myDict. The expression to create the directory name was getting too complicated and in my opinion too complicated to easily read. so I wondered if I could use the same approach to put the pieces into a list and then unpack them when it came time to create the directory name and it worked!
def createDirectory(myKey,**myDict):
pathList=[]
pathList.append(myDict['subKey1'])
pathList.append(myDict['subKey2'].lstrip('0'))
pathList.append(myDict['subKey3'])
etc
myPath=os.path.join(*myList)
os.makedirs(myPath)
return(myPath)
|
[
"Is this what you want?\ndef func(**kwargs):\n for key, value in kwargs.items():\n pass # Do something\n\nfunc(**myDict) # Call func with the given dict as key/value parameters\n\n(See the documentation for more about keyword arguments. The keys in myDict must be strings.)\n\nEdit: you edited your question to include the following:\n\nI think the ** notation in front of myDict instructs the function to expect a dictionary and to unpack the key (the first *) and the value, the second *\n\nThis is not correct. To understand what is happening, you must consider the following:\n\nA function can have multiple formal parameters (a and b in this case):\n\ndef f1(a, b): pass\n\nWe can pass positional arguments to such function (like in most other languages):\n\nf1(2, 3)\n\nWe can also pass keyword arguments:\n\nf1(a=2, b=3)\n\nWe can also mix these, but the positional arguments must come first:\n\nf1(2, b=3)\nf1(a=2, 3) # SyntaxError: non-keyword arg after keyword arg\n\nThere is a way to let a function accept an arbitrary number of positional arguments, which it can access as a tuple (args in this case):\n\ndef f2(*args): assert isinstance(args, tuple)\n\nNow we can call f2 using separately specified arguments, or using a list whose contents first need to be unpacked, using a syntax similar to the notation used for *args:\n\nf2(2, 3)\nf2(*[2, 3])\n\nLikewise, an arbitrary number of keyword arguments may be accepted:\n\ndef f3(**kwargs): pass\n\nNote that f3 does not ask for a single argument of type dict. This is the kind of invocations it expects:\n\nf3(a=2, b=3)\nf3(**{'a': 2, 'b': 3})\n\nAll arguments to f3 must be named:\n\nf3(2, 3) # TypeError: f3() takes exactly 0 arguments (2 given)\nPutting all of this together, and remembering that positional arguments must come first, we may have:\n>>> def f4(a, b, *args, **kwargs):\n... print('%r, %r' % (args, kwargs))\n... \n>>> f4(2, 3)\n(), {}\n>>> f4(2, 3, 4, 5)\n(4, 5), {}\n>>> f4(2, 3, x=4, y=5)\n(), {'y': 5, 'x': 4}\n>>> f4(2, 3, 4, 5, x=6, y=7)\n(4, 5), {'y': 7, 'x': 6}\n>>> f4(2, *[3, 4, 5], **{'x': 6, 'y': 7})\n(4, 5), {'y': 7, 'x': 6}\n\nPay special attention to the following two errors:\n>>> f4(2)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: f4() takes at least 2 arguments (1 given)\n>>> f4(2, 3, a=4)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: f4() got multiple values for keyword argument 'a'\n\nThe second error should help you explain this behavior:\n>>> f4(**{'foo': 0, 'a': 2, 'b': 3, 'c': 4})\n(), {'c': 4, 'foo': 0}\n\n",
"Not sure why we are bringing in kwargs, this is much simpler than that. You said you're new to Python, I think you just need some Python fundamentals here.\ndef newFunct(key,testDict['key']):\n\nShould be:\ndef newFunct(key, val):\n\nThere's no reason to use any special syntax on your second parameter to indicate that it's coming from a dictionary. It's just a parameter, you just happen to be passing the value from a dictionary item into it.\nFurther, once it's in the function, there's no reason to treat it in a special way either. At this point it's just a value. Which means that:\nnewvalue=key+str(testDict[key])\n\nCan now just be:\nnewvalue=key+str(val)\n\nSo when you call it like this (as you did):\nnewValue=newFunct(key,testDict[key])\n\ntestDict[key] resolves to the value at 'key', which just becomes \"val\" in the function.\n\nAn alternate way, if you see it fit for whatever reason (and this is just something that's good to know), you could define the function thusly:\ndef newFunct(key, testDict):\n\nAgain, the second parameter is just a parameter, so we use the same syntax, but now we're expecting it to be a dict, so we should use it like one:\nnewvalue=key+str(testDict[key])\n\n(Note: don't put quotes around 'key' in this case. We're referring to the variable called 'key', not a key called 'key'). When you call the function, it looks like this:\nnewValue=newFunct(key,testDict)\n\nSo unlike the first case where you're just passing one variable from the dictionary, you're passing a reference to the whole dictionary into the function this time.\nHope that helps.\n",
"why don't you just do:\n[k + str(v) for k, v in test_dict.iteritems()]\n\nor for py3k:\n[k + str(v) for k, v in test_dict.items()]\n\nedit\ndef f(k, v):\n print(k, v) # or do something much more complicated\n\nfor k, v in testDict.items():\n f(k, v)\n\n",
"From your description is seems like testDict is some sort of global variable with respect to the function. If this is the case - why do you even need to pass it to the function?\nInstead of your code:\ntestDict={'x':2,'xS':4}\n\ndef newFunct(key,testDict[key]):\n newvalue=key+str(testDict[key])\n return newValue\n\nfor key in testDict:\n newValue=newFunct(key,testDict[key])\n print newValue\n\nYou can simply use:\ntestDict={'x':2,'xS':4}\n\ndef newFunct(key):\n newvalue=key+str(testDict[key])\n return newValue\n\nfor key in testDict:\n newValue=newFunct(key)\n print newValue\n\nIf testDict is not meant to be in the global scope (which makes sense...), I would recommend simply passing a name for the dictionary and not \"messing around\" with variable length argument lists in this case:\ntestDict={'x':2,'xS':4}\n\ndef newFunct(key,dictionary):\n newvalue=key+str(dictionary[key])\n return newValue\n\nfor key in testDict:\n newValue=newFunct(key,testDict)\n print newValue\n\n"
] |
[
7,
2,
0,
0
] |
[] |
[] |
[
"dictionary",
"function",
"python"
] |
stackoverflow_0000853483_dictionary_function_python.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.