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:
Redirect realtime common line output to Django HttpResponse
In a long run command line execution, like uncompressing a large .zip archive, how to redirect the realtime output of unzip command to browser via Django's HttpResponse?
EDIT:
According to paul's suggestion, I did a search and found this question has answers to how to return a HttpResponse by using a generator.
Update HttpResponse Every Few Seconds
Now, remaining problem is how to capture and create a generator from the output of unzip.
A:
The HttpResponse constructor takes either a string or an iterable.
To trickle content down, you can make the iterable a generator.
Provided, of course, your middleware isn't interfering.
|
Redirect realtime common line output to Django HttpResponse
|
In a long run command line execution, like uncompressing a large .zip archive, how to redirect the realtime output of unzip command to browser via Django's HttpResponse?
EDIT:
According to paul's suggestion, I did a search and found this question has answers to how to return a HttpResponse by using a generator.
Update HttpResponse Every Few Seconds
Now, remaining problem is how to capture and create a generator from the output of unzip.
|
[
"The HttpResponse constructor takes either a string or an iterable.\nTo trickle content down, you can make the iterable a generator.\nProvided, of course, your middleware isn't interfering.\n"
] |
[
1
] |
[] |
[] |
[
"django",
"httpresponse",
"python"
] |
stackoverflow_0001767675_django_httpresponse_python.txt
|
Q:
Separating Business Layer Errors from API errors
The title is horrible, i know; I'm terrible at titles on SO here.
I'm wondering what would be the best way to present unified error responses in a webapi when errors could be raised deep inside the application.
The errors deep down in the app don't know anything about the web layer (nor should they), so how can the web layer classify myapp.PermissionError into a 403, json.DecodeError into a 400, myapp.driver.InvalidValue into 500, etc.
I have a few ideas, but I'm not a big fan of any of them.
(As the snippets might imply, this is a python app on linux)
Use a lot of except blocks to match the exception type i want. This is what i'm currently doing but its growing unwieldy (i'm already up to 8, and there are plenty more to go).
try
business.DoIt()
except DecodingError:
respond(400)
except PermissionError:
response(403)
...etc...
Creating a mapping or list of exception types and map them to response codes. This doesn't seem much better than (1) in the end, but it does clean up the code.
error_map = [(DecodingError, 400), (PermissionError, 403)]
try:
DoIt()
except Exception, exc:
for type, code in error_map:
if isinstance(exc, type):
response(code)
return
Add an interface to every exception class that provides the response code, but I don't like this because then the exceptions are carrying web-layer specific information (even if they live deep down in a driver that doesn't care about the web layer at all). I do like how "automatic" the web error response is, though.
class PermissionError(Exception):
web_status_code = 403
try:
Doit()
except:
response(exc.web_status_code)
A:
I like option 1. It may be a little more verbose, but it's also very clear.
Option 2 separates the point at which the exception is thrown from where the decision about what to do with it is made. In reality, that likely wouldn't be too much of an issue, but why split it up if you don't have to?
I agree that option 3 is pretty ugly. No need to deal with the error behavior at that level, just throw the exception.
|
Separating Business Layer Errors from API errors
|
The title is horrible, i know; I'm terrible at titles on SO here.
I'm wondering what would be the best way to present unified error responses in a webapi when errors could be raised deep inside the application.
The errors deep down in the app don't know anything about the web layer (nor should they), so how can the web layer classify myapp.PermissionError into a 403, json.DecodeError into a 400, myapp.driver.InvalidValue into 500, etc.
I have a few ideas, but I'm not a big fan of any of them.
(As the snippets might imply, this is a python app on linux)
Use a lot of except blocks to match the exception type i want. This is what i'm currently doing but its growing unwieldy (i'm already up to 8, and there are plenty more to go).
try
business.DoIt()
except DecodingError:
respond(400)
except PermissionError:
response(403)
...etc...
Creating a mapping or list of exception types and map them to response codes. This doesn't seem much better than (1) in the end, but it does clean up the code.
error_map = [(DecodingError, 400), (PermissionError, 403)]
try:
DoIt()
except Exception, exc:
for type, code in error_map:
if isinstance(exc, type):
response(code)
return
Add an interface to every exception class that provides the response code, but I don't like this because then the exceptions are carrying web-layer specific information (even if they live deep down in a driver that doesn't care about the web layer at all). I do like how "automatic" the web error response is, though.
class PermissionError(Exception):
web_status_code = 403
try:
Doit()
except:
response(exc.web_status_code)
|
[
"I like option 1. It may be a little more verbose, but it's also very clear. \nOption 2 separates the point at which the exception is thrown from where the decision about what to do with it is made. In reality, that likely wouldn't be too much of an issue, but why split it up if you don't have to? \nI agree that option 3 is pretty ugly. No need to deal with the error behavior at that level, just throw the exception.\n"
] |
[
1
] |
[] |
[] |
[
"error_handling",
"python"
] |
stackoverflow_0001767504_error_handling_python.txt
|
Q:
To understand Python's optparse
Thank you for quack in pointing out the off-by-one!
The following code is my first attempt in writing code with Optparse.
How can you fix the following bug in getting the help by Optparse?
#!/usr/bin/env python
import sys
import os
from optparse import OptionParser
e = sys.argv[1]
b = sys.argv[2]
no = sys.argv[3]
def set_figu(figu):
sum = 777
return sum
def main():
usage = "Usage: negative_bin_base.py <eksponentti> <siirre> <figu>"
parser = OptionParser(usage)
parser.add_option("-h", "--help", dest="help",
help="get synopsis of parameters")
# print the output of the work-horse
print set_figu(no)
(options, args) = parser.parse_args()
if len(args) < 4:
parser.error("incorrect number of arguments")
if options.informative:
print "reading %s..." % options.help
if __name__ == "__main__":
main()
Example of wrong output with correct number of parameters
python negative_bin_base.py 13 13 332
Traceback (most recent call last):
File "negative_bin_base.py", line 37, in <module>
main()
File "negative_bin_base.py", line 26, in main
help="get synopsis of parameters")
File "/usr/lib/python2.6/optparse.py", line 1020, in add_option
self._check_conflict(option)
File "/usr/lib/python2.6/optparse.py", line 995, in _check_conflict
option)
optparse.OptionConflictError: option -h/--help: conflicting option string(s): -h, --help
A:
Constructor for class optparse.OptionParser(...) has optional named parameter 'add_help_option', which defaults to 'True'. You will have to explicitly reject default help option and message, if you want to provide your own.
parser = OptionParser(usage, add_help_option=False)
A:
The bug is that your arguments array includes the name of the script as sys.argv[0]. Thus your if is off-by-one:
# python sys.argv[0] sys.argv[1] sys.argv[2] sys.argv[3]
if len(sys.argv) < 4:
sys.exit(usage)
A:
This should do what you require, based on your example above:
#!/usr/bin/env python
from optparse import OptionParser
def main():
usage = "Usage: negative_bin_base.py <eksponentti> <siirre> <figu>"
parser = OptionParser(usage)
(options, args) = parser.parse_args()
if len(args) != 3:
parser.error("incorrect number of arguments")
e = args[0]
b = args[1]
no = args[2]
# ...
if __name__ == "__main__":
main()
A:
For using optparse here's what I normally do:
separate command line parsing from your main code base for better modularization.
(Put the processing right after "if __name__ == "__main__"")
Let optparse handle your help.
(Use parser.print_help())
Use the optparse constructs, if you don't like them just parse sys.argv yourself.
(use add_option to define your necessary options)
Here's how I would write your sample using the optparse library:
def main():
print 'Welcome to the main event!'
if __name__ == '__main__':
import optparse
parser = optparse.OptionParser()
parser.add_option("-e", "--eksponentti", dest="eksponentti",
help="This is help for <eksponentti>.",
default=None)
parser.add_option("-s", "--siirre", dest="siirre",
help="This is help for <siirre>.",
default=None)
parser.add_option("-f", "--figu", dest="figu",
help="This is help for <figu>.",
default=None)
(options, args) = parser.parse_args()
if options.eksponentti and options.siirre and options.figu:
main()
else:
print "ERROR -- Expected Arguments not given!"
parser.print_help()
Running this without the necessary options will give the following output:
(It's a little prettier than I can format it here...)
ERROR -- Expected Arguments not given! Usage: parm.py [options]
Options:
-h, --help show this help message and exit
-e EKSPONENTTI, --eksponentti=EKSPONENTTI This is help for <eksponentti>.
-s SIIRRE, --siirre=SIIRRE This is help for <siirre>.
-f FIGU, --figu=FIGU This is help for <figu>.
|
To understand Python's optparse
|
Thank you for quack in pointing out the off-by-one!
The following code is my first attempt in writing code with Optparse.
How can you fix the following bug in getting the help by Optparse?
#!/usr/bin/env python
import sys
import os
from optparse import OptionParser
e = sys.argv[1]
b = sys.argv[2]
no = sys.argv[3]
def set_figu(figu):
sum = 777
return sum
def main():
usage = "Usage: negative_bin_base.py <eksponentti> <siirre> <figu>"
parser = OptionParser(usage)
parser.add_option("-h", "--help", dest="help",
help="get synopsis of parameters")
# print the output of the work-horse
print set_figu(no)
(options, args) = parser.parse_args()
if len(args) < 4:
parser.error("incorrect number of arguments")
if options.informative:
print "reading %s..." % options.help
if __name__ == "__main__":
main()
Example of wrong output with correct number of parameters
python negative_bin_base.py 13 13 332
Traceback (most recent call last):
File "negative_bin_base.py", line 37, in <module>
main()
File "negative_bin_base.py", line 26, in main
help="get synopsis of parameters")
File "/usr/lib/python2.6/optparse.py", line 1020, in add_option
self._check_conflict(option)
File "/usr/lib/python2.6/optparse.py", line 995, in _check_conflict
option)
optparse.OptionConflictError: option -h/--help: conflicting option string(s): -h, --help
|
[
"Constructor for class optparse.OptionParser(...) has optional named parameter 'add_help_option', which defaults to 'True'. You will have to explicitly reject default help option and message, if you want to provide your own.\n\n\nparser = OptionParser(usage, add_help_option=False)\n",
"The bug is that your arguments array includes the name of the script as sys.argv[0]. Thus your if is off-by-one:\n# python sys.argv[0] sys.argv[1] sys.argv[2] sys.argv[3]\nif len(sys.argv) < 4:\n sys.exit(usage)\n\n",
"This should do what you require, based on your example above:\n#!/usr/bin/env python\nfrom optparse import OptionParser\n\ndef main():\n usage = \"Usage: negative_bin_base.py <eksponentti> <siirre> <figu>\"\n parser = OptionParser(usage)\n (options, args) = parser.parse_args()\n if len(args) != 3:\n parser.error(\"incorrect number of arguments\")\n e = args[0]\n b = args[1]\n no = args[2]\n # ...\n\nif __name__ == \"__main__\":\n main()\n\n",
"For using optparse here's what I normally do:\n\nseparate command line parsing from your main code base for better modularization.\n(Put the processing right after \"if __name__ == \"__main__\"\")\nLet optparse handle your help.\n(Use parser.print_help())\nUse the optparse constructs, if you don't like them just parse sys.argv yourself.\n(use add_option to define your necessary options)\n\nHere's how I would write your sample using the optparse library:\ndef main():\n print 'Welcome to the main event!'\n\n\nif __name__ == '__main__':\n import optparse\n parser = optparse.OptionParser()\n parser.add_option(\"-e\", \"--eksponentti\", dest=\"eksponentti\",\n help=\"This is help for <eksponentti>.\",\n default=None)\n parser.add_option(\"-s\", \"--siirre\", dest=\"siirre\",\n help=\"This is help for <siirre>.\",\n default=None)\n parser.add_option(\"-f\", \"--figu\", dest=\"figu\",\n help=\"This is help for <figu>.\",\n default=None)\n\n (options, args) = parser.parse_args()\n if options.eksponentti and options.siirre and options.figu:\n main()\n else:\n print \"ERROR -- Expected Arguments not given!\"\n parser.print_help()\n\nRunning this without the necessary options will give the following output:\n(It's a little prettier than I can format it here...)\nERROR -- Expected Arguments not given! Usage: parm.py [options]\n\nOptions: \n -h, --help show this help message and exit \n -e EKSPONENTTI, --eksponentti=EKSPONENTTI This is help for <eksponentti>. \n -s SIIRRE, --siirre=SIIRRE This is help for <siirre>. \n -f FIGU, --figu=FIGU This is help for <figu>.\n\n"
] |
[
8,
6,
1,
1
] |
[] |
[] |
[
"arguments",
"debugging",
"python"
] |
stackoverflow_0001767210_arguments_debugging_python.txt
|
Q:
BWSplitView and PyObjc
I'm trying to use Brandon Walkin's BWSplitView from BWToolkit in a Cocoa PyObjc project. When I run the project I get the following error message:
NSInvalidUnarchiveOperationException - *** -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (BWSplitView)
Does this mean his toolkit is incompatible with a PyObc project, so I should just use the default interface builder views? BWToolkit seems pretty much perfect for my program, and I plan to use it elsewhere in my interface.
A:
I suspect that you got that error because you had a BWSplitView in a nib/xib file that you were attempting to load. In order to unarchive the objects in a nib file, the runtime needs to be able to create instances of the archived classes (e.g. BWSplitView). The exception that's being thrown is because BWSplitView isn't available to the runtime. In an Objective-C app you would link to the BWToolkit framework and the dynamic linker would do the work of making BWSplitView available to the runtime. In a PyObjC app, you have to explicitly import classes that you want available to the runtime (that aren't linked behind the scenes for you, such as the Cocoa classes). Fortunately, BWToolkit has a bridge support file so you can import it directly (assuming it's in a standard framework location such as /Library/Frameworks). If you need to load a framework that does not have a bridge support file, you can use objc.loadBundle and then use NSClassFromString to get a class object.
On a side note, /System/Library/Frameworks is reserved for Apple-supplied system frameworks. You should not put third-party frameworks in that folder as Apple may wipe that folder at a system update (unlikely but possible). Thrid-party frameworks that are made available to all users on a system should be put in /Library/Frameworks, user-specific frameworks similarly in ~/Library/Frameworks and application specific frameworks in Contents/Frameworks, where within the application's app bundle.
A:
I've fixed this using the following steps:
1. Download and install http://github.com/jrydberg/pyobjc-bwtoolkitframework/tree/master
2. Ensure you have BWToolkit.framework installed in /System/Library/Frameworks (this can be done by redownloading BWToolkit and copying the folder across)
3. Use import BWToolkitFramework in main.py
A:
We had a similar message:
*** Terminating app due to uncaught exception ‘NSInvalidUnarchiveOperationException’, reason: ‘*** -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (MKMapView)’
In our case it was due to a stray entry in the "Framework Search Paths" setting under the target's build settings. When that entry was cleared, the problem went away.
|
BWSplitView and PyObjc
|
I'm trying to use Brandon Walkin's BWSplitView from BWToolkit in a Cocoa PyObjc project. When I run the project I get the following error message:
NSInvalidUnarchiveOperationException - *** -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (BWSplitView)
Does this mean his toolkit is incompatible with a PyObc project, so I should just use the default interface builder views? BWToolkit seems pretty much perfect for my program, and I plan to use it elsewhere in my interface.
|
[
"I suspect that you got that error because you had a BWSplitView in a nib/xib file that you were attempting to load. In order to unarchive the objects in a nib file, the runtime needs to be able to create instances of the archived classes (e.g. BWSplitView). The exception that's being thrown is because BWSplitView isn't available to the runtime. In an Objective-C app you would link to the BWToolkit framework and the dynamic linker would do the work of making BWSplitView available to the runtime. In a PyObjC app, you have to explicitly import classes that you want available to the runtime (that aren't linked behind the scenes for you, such as the Cocoa classes). Fortunately, BWToolkit has a bridge support file so you can import it directly (assuming it's in a standard framework location such as /Library/Frameworks). If you need to load a framework that does not have a bridge support file, you can use objc.loadBundle and then use NSClassFromString to get a class object.\nOn a side note, /System/Library/Frameworks is reserved for Apple-supplied system frameworks. You should not put third-party frameworks in that folder as Apple may wipe that folder at a system update (unlikely but possible). Thrid-party frameworks that are made available to all users on a system should be put in /Library/Frameworks, user-specific frameworks similarly in ~/Library/Frameworks and application specific frameworks in Contents/Frameworks, where within the application's app bundle.\n",
"I've fixed this using the following steps:\n 1. Download and install http://github.com/jrydberg/pyobjc-bwtoolkitframework/tree/master\n 2. Ensure you have BWToolkit.framework installed in /System/Library/Frameworks (this can be done by redownloading BWToolkit and copying the folder across)\n3. Use import BWToolkitFramework in main.py\n",
"We had a similar message:\n*** Terminating app due to uncaught exception ‘NSInvalidUnarchiveOperationException’, reason: ‘*** -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (MKMapView)’\n\nIn our case it was due to a stray entry in the \"Framework Search Paths\" setting under the target's build settings. When that entry was cleared, the problem went away.\n"
] |
[
5,
0,
0
] |
[] |
[] |
[
"bwtoolkit",
"cocoa",
"pyobjc",
"python"
] |
stackoverflow_0000869912_bwtoolkit_cocoa_pyobjc_python.txt
|
Q:
How do I move data from local appengine datastore to remote datastore?
I can see how to download the remote datastore to local, and how to upload a CSV to the remote app engine server as outlined here:
Uploading and Downloading Data
But is there a way to export my local data to a CSV that is ready for the remote upload script? Of course I could write a custom exporter, but is there no way to automate this process?
A:
The answer is to use the bulkloader.py pointing at your local box:
bulkloader.py --dump --url=http://localhost:8080/remote_api --filename=test.csv --kind=KindHere --app_id=app-id-here
Then you can use the bulkloader.py --restore command to send it to production
A:
Look at the Python Standard Library's csv module.
|
How do I move data from local appengine datastore to remote datastore?
|
I can see how to download the remote datastore to local, and how to upload a CSV to the remote app engine server as outlined here:
Uploading and Downloading Data
But is there a way to export my local data to a CSV that is ready for the remote upload script? Of course I could write a custom exporter, but is there no way to automate this process?
|
[
"The answer is to use the bulkloader.py pointing at your local box:\nbulkloader.py --dump --url=http://localhost:8080/remote_api --filename=test.csv --kind=KindHere --app_id=app-id-here\nThen you can use the bulkloader.py --restore command to send it to production\n",
"Look at the Python Standard Library's csv module.\n"
] |
[
5,
0
] |
[] |
[] |
[
"google_app_engine",
"google_cloud_datastore",
"python"
] |
stackoverflow_0001768011_google_app_engine_google_cloud_datastore_python.txt
|
Q:
Different response by screen solutions using Django and jQuery
In a thumbnail website, if I want to display 100x100 thumbs on screnn resolutions lower than 1280x1024 while display 150x150 thumbs for screens higher than 1280x1024, is the following procedure correct?
Render a page frame with no thumbs by view1()
On page frame loaded, it detects client's screen resolution and pass it to another Django view call fetchthumb()
View fetchthumb() create html code containing the thumb images and return to page frame.
jQuery on page frame render thumb html on browser.
Are there any better methods?
A:
i think you have few options
Just change thumbnail at runtime based on $(window).width(); using jquery
Pass on screen resolution to django first time from client side, and later store it in session and render templates accordingly
Sometime you may get screen resolution in request headers, i am not sure though
Best would be to design a general solution which doesn't depend on screen resolution, and scaling 150x150 to 100x100 shouldn't be a problem on client side.
|
Different response by screen solutions using Django and jQuery
|
In a thumbnail website, if I want to display 100x100 thumbs on screnn resolutions lower than 1280x1024 while display 150x150 thumbs for screens higher than 1280x1024, is the following procedure correct?
Render a page frame with no thumbs by view1()
On page frame loaded, it detects client's screen resolution and pass it to another Django view call fetchthumb()
View fetchthumb() create html code containing the thumb images and return to page frame.
jQuery on page frame render thumb html on browser.
Are there any better methods?
|
[
"i think you have few options\n\nJust change thumbnail at runtime based on $(window).width(); using jquery\nPass on screen resolution to django first time from client side, and later store it in session and render templates accordingly\nSometime you may get screen resolution in request headers, i am not sure though\nBest would be to design a general solution which doesn't depend on screen resolution, and scaling 150x150 to 100x100 shouldn't be a problem on client side.\n\n"
] |
[
2
] |
[] |
[] |
[
"django",
"jquery",
"python"
] |
stackoverflow_0001768179_django_jquery_python.txt
|
Q:
Web timer using Python
I would like to create web page which will print simple message
x minutes to shutdown
where 'x' would decrease once a minute automatically without clicking 'refresh' in web browser. The value will be counted from data downloaded from SNMP source (that is why I wanted to use Python). AFAIK I should use Javascript (am I right ?).
Is it possible to use Python to this sort of task (dynamic web page)? If not what other language would you suggest ?
A:
You could use a scripting language of your choice to load the initial time on the server side, and just serve your page with a Javascript timer that modifies the time every minute.
You would need to look into the setTimeout() Javascript function to manage the timer.
Something like this:
<script type="text/javascript">
var timer = setTimeout ( "changeTime()", 60000 );
function changeTime(){
//modify time logic
clearTimeout ( timer );
timer = setTimeout ( "changeTime()", 60000 );
}
</script>
A:
Javascript is the only language the works well on the web. So yes, you have to use it.
A:
Not very Web 2.0, and also discouraged by the W3C, but you could add this to your HTML header:
<meta http-equiv="refresh" content="60" />
That will automatically refresh the page for you every 60 seconds without the user having to click refresh.
To implement this you would create a CGI script using Python, which gets the result via SNMP and generates the webpage with your message. If this script also outputs the meta refresh above, it will be updated by the browser every minute, generating the new content.
The proper way of doing this is probably using AJAX. It all depends on how much time you want to spend on it.
|
Web timer using Python
|
I would like to create web page which will print simple message
x minutes to shutdown
where 'x' would decrease once a minute automatically without clicking 'refresh' in web browser. The value will be counted from data downloaded from SNMP source (that is why I wanted to use Python). AFAIK I should use Javascript (am I right ?).
Is it possible to use Python to this sort of task (dynamic web page)? If not what other language would you suggest ?
|
[
"You could use a scripting language of your choice to load the initial time on the server side, and just serve your page with a Javascript timer that modifies the time every minute. \nYou would need to look into the setTimeout() Javascript function to manage the timer.\nSomething like this:\n<script type=\"text/javascript\">\n\n var timer = setTimeout ( \"changeTime()\", 60000 );\n\n function changeTime(){\n //modify time logic \n\n clearTimeout ( timer );\n timer = setTimeout ( \"changeTime()\", 60000 );\n }\n\n</script>\n\n",
"Javascript is the only language the works well on the web. So yes, you have to use it.\n",
"Not very Web 2.0, and also discouraged by the W3C, but you could add this to your HTML header:\n<meta http-equiv=\"refresh\" content=\"60\" />\n\nThat will automatically refresh the page for you every 60 seconds without the user having to click refresh.\nTo implement this you would create a CGI script using Python, which gets the result via SNMP and generates the webpage with your message. If this script also outputs the meta refresh above, it will be updated by the browser every minute, generating the new content.\nThe proper way of doing this is probably using AJAX. It all depends on how much time you want to spend on it.\n"
] |
[
3,
1,
1
] |
[] |
[] |
[
"python",
"timer"
] |
stackoverflow_0001769028_python_timer.txt
|
Q:
Python Programming Help
#!/usr/bin/env python
import math
def primeTest(isPrime):
print(' {0}=testnum'.format(testnum))
if testnum%2 == 0 and testnum != 2: #if divisible by 2 and not 2
isPrime = False
print('{0} a'.format(isPrime))
print('a')
else:
numroot = round(math.sqrt(testnum))
i = 2
while i <= numroot:
if testnum%i == 0:
isPrime = False
i+=1
print('b')
global testnum
global isPrime
testnum=2
numPrimesSoFar=0
reqPrimes=int(input('How many primes would you like? \n'))
while numPrimesSoFar < reqPrimes:
isPrime=True
primeTest(isPrime)
print(isPrime)
if isPrime:
print(' {0}'.format(isPrime))
print(' {0}'.format(testnum))
numPrimesSoFar+=1
testnum+=1
(sorry about the formatting I'm not really sure why it's not working right, but assume I have the tab-formatting correct)
Now this outputs this:
How many primes would you like?
4
2=testnum
b
True
True
2
3=testnum
b
True
True
3
4=testnum
False a
a
True
True
4
5=testnum
b
True
True
5
Alright... so why is isPrime true still when I set it to false?
EDIT: Okay... so is THAT what you guys are talking about?
A:
global isPrime needs to be inside the function where you assign to isPrime.
A:
I think that, since you are declaring the isPrime global variable after the definition of primeTest(), the Python interpreter treats the isPrime within the function as a local variable.
I was mistaken.. you have to declare it as global isPrime from within the function. Order of declaration (function or variable first) doesn't matter. Something like this:
def primeTest():
global isPrime
isPrime = False
isPrime = True
print isPrime # returns True
primeTest()
print isPrime # returns False
Note that you cannot write global isPrime = False; it must be two statements.
Anyway, it is rather bad practice to be changing global variables like that. Why don't you pass isPrime as an argument to primeTest()?
Edit:
Okay, my answer was still too hasty. Simply passing isPrime as an argument doesn't work, because boolean values are immutable types. The best way to handle your current problem is to have isPrime as a return value:
def primeTest(testnum):
... do your calculations here, set a variable ret_val to True or False ...
return ret_val
Now you can do isPrime = primeTest(10) to find out if any number is a prime.
However, if you pass your function a mutable type (like a list), you can modify it from within the function. This post covers it quite well. But you needn't concern yourself with that just yet.
A:
global foo means, in this scope, let me say foo to refer to a foo accessible from outside this scope and persistent after this scope closes. It does not mean, let all variables named foo everywhere and forever refer to this foo.
This is different from what you might expect if you're coming from, say, a C/C++ background where declaring a variable at the top level makes it global without requiring the explicit global declaration in each scope.
A:
Although you have set isPrime to be a global, you are modifying it inside the local bounds of the primeTest function. As a result, it won't be modified.
If you need it changing, try passing it in as a parameter and having it modified that way.
|
Python Programming Help
|
#!/usr/bin/env python
import math
def primeTest(isPrime):
print(' {0}=testnum'.format(testnum))
if testnum%2 == 0 and testnum != 2: #if divisible by 2 and not 2
isPrime = False
print('{0} a'.format(isPrime))
print('a')
else:
numroot = round(math.sqrt(testnum))
i = 2
while i <= numroot:
if testnum%i == 0:
isPrime = False
i+=1
print('b')
global testnum
global isPrime
testnum=2
numPrimesSoFar=0
reqPrimes=int(input('How many primes would you like? \n'))
while numPrimesSoFar < reqPrimes:
isPrime=True
primeTest(isPrime)
print(isPrime)
if isPrime:
print(' {0}'.format(isPrime))
print(' {0}'.format(testnum))
numPrimesSoFar+=1
testnum+=1
(sorry about the formatting I'm not really sure why it's not working right, but assume I have the tab-formatting correct)
Now this outputs this:
How many primes would you like?
4
2=testnum
b
True
True
2
3=testnum
b
True
True
3
4=testnum
False a
a
True
True
4
5=testnum
b
True
True
5
Alright... so why is isPrime true still when I set it to false?
EDIT: Okay... so is THAT what you guys are talking about?
|
[
"global isPrime needs to be inside the function where you assign to isPrime.\n",
"I think that, since you are declaring the isPrime global variable after the definition of primeTest(), the Python interpreter treats the isPrime within the function as a local variable.\nI was mistaken.. you have to declare it as global isPrime from within the function. Order of declaration (function or variable first) doesn't matter. Something like this:\ndef primeTest():\n global isPrime\n isPrime = False\n\nisPrime = True\nprint isPrime # returns True\nprimeTest()\nprint isPrime # returns False\n\nNote that you cannot write global isPrime = False; it must be two statements.\nAnyway, it is rather bad practice to be changing global variables like that. Why don't you pass isPrime as an argument to primeTest()?\nEdit:\nOkay, my answer was still too hasty. Simply passing isPrime as an argument doesn't work, because boolean values are immutable types. The best way to handle your current problem is to have isPrime as a return value:\ndef primeTest(testnum):\n ... do your calculations here, set a variable ret_val to True or False ...\n return ret_val\n\nNow you can do isPrime = primeTest(10) to find out if any number is a prime.\nHowever, if you pass your function a mutable type (like a list), you can modify it from within the function. This post covers it quite well. But you needn't concern yourself with that just yet.\n",
"global foo means, in this scope, let me say foo to refer to a foo accessible from outside this scope and persistent after this scope closes. It does not mean, let all variables named foo everywhere and forever refer to this foo. \nThis is different from what you might expect if you're coming from, say, a C/C++ background where declaring a variable at the top level makes it global without requiring the explicit global declaration in each scope.\n",
"Although you have set isPrime to be a global, you are modifying it inside the local bounds of the primeTest function. As a result, it won't be modified.\nIf you need it changing, try passing it in as a parameter and having it modified that way.\n"
] |
[
3,
2,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001769278_python.txt
|
Q:
django.utils.encoding.DjangoUnicodeDecodeError
I got the following error when tried to add an entry to a Django model via generic relations.
django.utils.encoding.DjangoUnicodeDecodeError: 'utf8' codec can't decode byte 0xb8 in position 24: unexpected code byte. You passed in 'ASL/60Styles_Timeless-3_\xb8 CaLe.asl' (<type 'str'>)
The model is like this:
class MD5(models.Model):
value = models.CharField(max_length=32, db_index=True)
filename = models.CharField(max_length=100)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey()
Table's charset is utf8 and collation is utf8_general_ci.
Does it mean that the filename is not a valid utf8 string? How to fix this error or can we convert the invalid string to a valid format?
A:
Your file system is apparently not using UTF-8 encoding:
>>> a = 'ASL/60Styles_Timeless-3_\xb8 CaLe.asl'
>>> print a.decode('utf-8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.5/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xb8 in position 24: unexpected code byte
>>> a.decode('iso8859-2')
u'ASL/60Styles_Timeless-3_\xb8 CaLe.asl'
>>> print a.decode('iso8859-2')
ASL/60Styles_Timeless-3_¸ CaLe.asl
Only now I've realized that the string you got is actually already unicode. Try using this to get unicode:
>>> a.decode('raw_unicode_escape')
u'ASL/60Styles_Timeless-3_\xb8 CaLe.asl'
|
django.utils.encoding.DjangoUnicodeDecodeError
|
I got the following error when tried to add an entry to a Django model via generic relations.
django.utils.encoding.DjangoUnicodeDecodeError: 'utf8' codec can't decode byte 0xb8 in position 24: unexpected code byte. You passed in 'ASL/60Styles_Timeless-3_\xb8 CaLe.asl' (<type 'str'>)
The model is like this:
class MD5(models.Model):
value = models.CharField(max_length=32, db_index=True)
filename = models.CharField(max_length=100)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey()
Table's charset is utf8 and collation is utf8_general_ci.
Does it mean that the filename is not a valid utf8 string? How to fix this error or can we convert the invalid string to a valid format?
|
[
"Your file system is apparently not using UTF-8 encoding:\n>>> a = 'ASL/60Styles_Timeless-3_\\xb8 CaLe.asl'\n>>> print a.decode('utf-8')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"/usr/lib/python2.5/encodings/utf_8.py\", line 16, in decode\n return codecs.utf_8_decode(input, errors, True)\nUnicodeDecodeError: 'utf8' codec can't decode byte 0xb8 in position 24: unexpected code byte\n>>> a.decode('iso8859-2')\nu'ASL/60Styles_Timeless-3_\\xb8 CaLe.asl'\n>>> print a.decode('iso8859-2')\nASL/60Styles_Timeless-3_¸ CaLe.asl\n\nOnly now I've realized that the string you got is actually already unicode. Try using this to get unicode:\n>>> a.decode('raw_unicode_escape')\nu'ASL/60Styles_Timeless-3_\\xb8 CaLe.asl'\n\n"
] |
[
4
] |
[] |
[] |
[
"django",
"python",
"utf_8"
] |
stackoverflow_0001767848_django_python_utf_8.txt
|
Q:
Using Numpy to find average value across data sets, with some missing data
I have several (10 or so) CSV-formatted data sets. Each column of a data set represents one aspect of a running system (available RAM, CPU usage, open TCP connections, and so forth). Each row contains the values for these columns at one moment in time.
The data sets were captured during individual runs of the same test. The number of rows is not guaranteed to be the same in each data set (i.e.: some tests ran longer than others).
I want to produce a new CSV file that represents the "average" value, across all data sets, for a given time offset and a given column. Ideally, values missing in one data set would be ignored. If necessary, though, missing values could be assumed to be the same as the last known value, or the average of known values for that row.
A simplified example:
+---------------+ +---------------+ +---------------+
| Set 1 | | Set 2 | | Average |
+---+-----+-----+ +---+-----+-----+ +---+-----+-----+
| t | A | B | | t | A | B | | t | A | B |
+---+-----+-----+ +---+-----+-----+ +---+-----+-----+
| 1 | 10 | 50 | | 1 | 12 | 48 | | 1 | 11 | 49 |
| 2 | 13 | 58 | | 2 | 7 | 60 | | 2 | 10 | 59 |
| 3 | 9 | 43 | | 3 | 17 | 51 | => | 3 | 13 | 47 |
| 4 | 14 | 61 | | 4 | 12 | 57 | | 4 | 13 | 59 |
| : | : | : | | : | : | : | | : | : | : |
| 7 | 4 | 82 | | 7 | 10 | 88 | | 7 | 7 | 86 |
+---+-----+-----+ | 8 | 15 | 92 | | 8 | 15 | 92 |
| 9 | 6 | 63 | | 9 | 6 | 63 |
+---+-----+-----+ +---+-----+-----+
I'm new to numpy, having picked it up specifically for this project. What's the best way to do this? For data sets with the same number of rows (which I've been forcing by chopping longer data sets short), I just do:
d_avg = sum(dsets) / float(len(dsets))
where "dsets" is a list of the ndarrays containing the data from each CSV file. This works well, but I don't want to discard the data from the longer runs.
I can also resize the shorter runs to the length of the longest, but all the new fields are filled with "NoneType". Later operations then error when adding (for example) a float and a NoneType.
Any suggestions?
A:
Why not just us numpy's ma (masked array) module?
maxLen = reduce(lambda a,b : max(a, b.shape[0]),
dSets, 0)
all = N.ma.zeros((maxLen,)+ dSets[0].shape[1:] + (len(dSets),),
dtype=float) # set the dtype to whatever
all.mask = True
for i, set in enumerate(dSets):
all.mask[:len(set),...,i] = False
all[:len(set),...,i] = set
mean = all.mean(axis=-1)
Of course, this only works if you can guarantee that the time in each row is the same across all arrays, i.e. set[i,0] == set[j,0] for all i,j
A:
Edit: I've revised my method, abandoning scipy.nanmean in favor of masked arrays.
If it is unclear what the code is doing at any point, first try putting
print statements in. If it is still unclear, feel free to ask;
I'll try my best to explain. The trick part is getting the t-values merged. (That was done with numpy array's searchsorted method.)
Playing with numpy has led me to believe that its speed advantages
may not exist until the datasets get quite big (maybe you'll need at least 10,000 rows per data set). Otherwise, a pure python solution may be both easier to write and faster.
Here are the toy datasets I used:
% cat set1
1, 10, 50
2, 13, 58
3,9,43
4,14,61
7, 4, 82
% cat set2
1, 12, 48
2, 7, 60
3,17,51
4,12,57
7,10,88
8,15,92
9,6,63
And here is the code:
#!/usr/bin/env python
import numpy as np
filenames=('set1','set2') # change this to list all your csv files
column_names=('t','a','b')
# slurp the csv data files into a list of numpy arrays
data=[np.loadtxt(filename, delimiter=',') for filename in filenames]
# Find the complete list of t-values
# For each elt in data, elt[a,b] is the value in the a_th row and b_th column
t_values=np.array(list(reduce(set.union,(set(elt[:,0]) for elt in data))))
t_values.sort()
# print(t_values)
# [ 1. 2. 3. 4. 7. 8. 9.]
num_rows=len(t_values)
num_columns=len(column_names)
num_datasets=len(filenames)
# For each data set, we compute the indices of the t_values that are used.
idx=[(t_values.searchsorted(data[n][:,0])) for n in range(num_datasets)]
data2=np.ma.zeros((num_rows,num_columns,num_datasets))
for n in range(num_datasets):
data2[idx[n],:,n]=data[n][:,:]
data2=np.ma.masked_equal(data2, 0)
averages=data2.mean(axis=-1)
print(averages)
# [[1.0 11.0 49.0]
# [2.0 10.0 59.0]
# [3.0 13.0 47.0]
# [4.0 13.0 59.0]
# [7.0 7.0 85.0]
# [8.0 15.0 92.0]
# [9.0 6.0 63.0]]
A:
Well, one way to do it would be to iterate over each row of each data set and append a given column value to an array that's stored in a dictionary, where the time index is used for its key value. You then iterate over the dictionary and pull the average for each array stored there.
This isn't particularly efficient -- the other option is to find the longest array, iterate over it, and query the other datasets to create an temporary array to average. This way you save the secondary iteration over the dictionary.
|
Using Numpy to find average value across data sets, with some missing data
|
I have several (10 or so) CSV-formatted data sets. Each column of a data set represents one aspect of a running system (available RAM, CPU usage, open TCP connections, and so forth). Each row contains the values for these columns at one moment in time.
The data sets were captured during individual runs of the same test. The number of rows is not guaranteed to be the same in each data set (i.e.: some tests ran longer than others).
I want to produce a new CSV file that represents the "average" value, across all data sets, for a given time offset and a given column. Ideally, values missing in one data set would be ignored. If necessary, though, missing values could be assumed to be the same as the last known value, or the average of known values for that row.
A simplified example:
+---------------+ +---------------+ +---------------+
| Set 1 | | Set 2 | | Average |
+---+-----+-----+ +---+-----+-----+ +---+-----+-----+
| t | A | B | | t | A | B | | t | A | B |
+---+-----+-----+ +---+-----+-----+ +---+-----+-----+
| 1 | 10 | 50 | | 1 | 12 | 48 | | 1 | 11 | 49 |
| 2 | 13 | 58 | | 2 | 7 | 60 | | 2 | 10 | 59 |
| 3 | 9 | 43 | | 3 | 17 | 51 | => | 3 | 13 | 47 |
| 4 | 14 | 61 | | 4 | 12 | 57 | | 4 | 13 | 59 |
| : | : | : | | : | : | : | | : | : | : |
| 7 | 4 | 82 | | 7 | 10 | 88 | | 7 | 7 | 86 |
+---+-----+-----+ | 8 | 15 | 92 | | 8 | 15 | 92 |
| 9 | 6 | 63 | | 9 | 6 | 63 |
+---+-----+-----+ +---+-----+-----+
I'm new to numpy, having picked it up specifically for this project. What's the best way to do this? For data sets with the same number of rows (which I've been forcing by chopping longer data sets short), I just do:
d_avg = sum(dsets) / float(len(dsets))
where "dsets" is a list of the ndarrays containing the data from each CSV file. This works well, but I don't want to discard the data from the longer runs.
I can also resize the shorter runs to the length of the longest, but all the new fields are filled with "NoneType". Later operations then error when adding (for example) a float and a NoneType.
Any suggestions?
|
[
"Why not just us numpy's ma (masked array) module?\nmaxLen = reduce(lambda a,b : max(a, b.shape[0]),\n dSets, 0)\nall = N.ma.zeros((maxLen,)+ dSets[0].shape[1:] + (len(dSets),),\n dtype=float) # set the dtype to whatever\nall.mask = True\nfor i, set in enumerate(dSets):\n all.mask[:len(set),...,i] = False\n all[:len(set),...,i] = set\n\nmean = all.mean(axis=-1)\n\nOf course, this only works if you can guarantee that the time in each row is the same across all arrays, i.e. set[i,0] == set[j,0] for all i,j\n",
"Edit: I've revised my method, abandoning scipy.nanmean in favor of masked arrays.\nIf it is unclear what the code is doing at any point, first try putting\nprint statements in. If it is still unclear, feel free to ask; \nI'll try my best to explain. The trick part is getting the t-values merged. (That was done with numpy array's searchsorted method.)\nPlaying with numpy has led me to believe that its speed advantages\nmay not exist until the datasets get quite big (maybe you'll need at least 10,000 rows per data set). Otherwise, a pure python solution may be both easier to write and faster.\nHere are the toy datasets I used:\n% cat set1\n1, 10, 50\n2, 13, 58\n3,9,43\n4,14,61\n7, 4, 82\n\n% cat set2\n1, 12, 48\n2, 7, 60\n3,17,51\n4,12,57\n7,10,88\n8,15,92\n9,6,63\n\nAnd here is the code:\n#!/usr/bin/env python\nimport numpy as np\n\nfilenames=('set1','set2') # change this to list all your csv files\ncolumn_names=('t','a','b')\n\n# slurp the csv data files into a list of numpy arrays\ndata=[np.loadtxt(filename, delimiter=',') for filename in filenames]\n\n# Find the complete list of t-values\n# For each elt in data, elt[a,b] is the value in the a_th row and b_th column\nt_values=np.array(list(reduce(set.union,(set(elt[:,0]) for elt in data))))\nt_values.sort()\n# print(t_values)\n# [ 1. 2. 3. 4. 7. 8. 9.]\n\nnum_rows=len(t_values)\nnum_columns=len(column_names)\nnum_datasets=len(filenames)\n\n# For each data set, we compute the indices of the t_values that are used.\nidx=[(t_values.searchsorted(data[n][:,0])) for n in range(num_datasets)]\n\ndata2=np.ma.zeros((num_rows,num_columns,num_datasets))\nfor n in range(num_datasets):\n data2[idx[n],:,n]=data[n][:,:]\ndata2=np.ma.masked_equal(data2, 0)\naverages=data2.mean(axis=-1)\nprint(averages)\n# [[1.0 11.0 49.0]\n# [2.0 10.0 59.0]\n# [3.0 13.0 47.0]\n# [4.0 13.0 59.0]\n# [7.0 7.0 85.0]\n# [8.0 15.0 92.0]\n# [9.0 6.0 63.0]]\n\n",
"Well, one way to do it would be to iterate over each row of each data set and append a given column value to an array that's stored in a dictionary, where the time index is used for its key value. You then iterate over the dictionary and pull the average for each array stored there. \nThis isn't particularly efficient -- the other option is to find the longest array, iterate over it, and query the other datasets to create an temporary array to average. This way you save the secondary iteration over the dictionary.\n"
] |
[
3,
2,
0
] |
[] |
[] |
[
"numpy",
"python"
] |
stackoverflow_0001767865_numpy_python.txt
|
Q:
__unicode__(self) doesn't get called by logging
Long story short:
# this works as expected:
logging.error(my_object.__unicode__())
# this doesn't:
logging.error(my_object)
Same result with __str__(self).
Why?
EDIT: __str__ actually works.
A:
>>> class MyClass(object):
... def __str__(self):
... return "foobar"
...
>>> import logging
>>> logging.error(MyClass())
ERROR:root:foobar
Works as expected?!
A:
Logging will call str() (which uses __str__() which falls back to __repr__() when it's not defined). This is because the logging framework is not Unicode safe (i.e. you can get errors when you try to write Unicode to the various logging sinks).
|
__unicode__(self) doesn't get called by logging
|
Long story short:
# this works as expected:
logging.error(my_object.__unicode__())
# this doesn't:
logging.error(my_object)
Same result with __str__(self).
Why?
EDIT: __str__ actually works.
|
[
">>> class MyClass(object):\n... def __str__(self):\n... return \"foobar\"\n...\n>>> import logging\n>>> logging.error(MyClass())\nERROR:root:foobar\n\nWorks as expected?!\n",
"Logging will call str() (which uses __str__() which falls back to __repr__() when it's not defined). This is because the logging framework is not Unicode safe (i.e. you can get errors when you try to write Unicode to the various logging sinks).\n"
] |
[
1,
1
] |
[] |
[] |
[
"logging",
"python"
] |
stackoverflow_0001769759_logging_python.txt
|
Q:
What is the best way to crawl a login based sites?
I've to automate a file download activity from a website (similar to, let's say, yahoomail.com). To reach a page which has this file download link, i've to login, jump from page to page to provide some parameters like dates etc., and finally click on download link.
I am thinking of three approaches:
Using WatIN and develop a windows service that periodically executes some WatiN code to traverse through the page and download the file.
Using AutoIT (no much idea)
Using a simple HTML parsing technique (there are several questions here eg., how to maintain a session after doing a login? how to do a logout after doing it?
A:
I use scrapy.org, it's a python library. It's quiet good actually. Easy to write spiders and it's very extensive in it's functionality. Scraping sites after login is available in the package.
Here is an example of a spider that would crawl a site after authentication.
class LoginSpider(BaseSpider):
domain_name = 'example.com'
start_urls = ['http://www.example.com/users/login.php']
def parse(self, response):
return [FormRequest.from_response(response,
formdata={'username': 'john', 'password': 'secret'},
callback=self.after_login)]
def after_login(self, response):
# check login succeed before going on
if "authentication failed" in response.body:
self.log("Login failed", level=log.ERROR)
return
# continue scraping with authenticated session...
A:
I used mechanize for Python with success for a few things. It's easy to use and supports HTTP authentication, form handling, cookies, automatic HTTP redirection (30X), ... Basically the only thing missing is JavaScript, but if you need to rely on JS you're pretty much screwed anyway.
A:
Free Download Manager is great for crawling, and you could use wget.
A:
Try a Selenium script, automated with Selenium Remote Control.
|
What is the best way to crawl a login based sites?
|
I've to automate a file download activity from a website (similar to, let's say, yahoomail.com). To reach a page which has this file download link, i've to login, jump from page to page to provide some parameters like dates etc., and finally click on download link.
I am thinking of three approaches:
Using WatIN and develop a windows service that periodically executes some WatiN code to traverse through the page and download the file.
Using AutoIT (no much idea)
Using a simple HTML parsing technique (there are several questions here eg., how to maintain a session after doing a login? how to do a logout after doing it?
|
[
"I use scrapy.org, it's a python library. It's quiet good actually. Easy to write spiders and it's very extensive in it's functionality. Scraping sites after login is available in the package.\nHere is an example of a spider that would crawl a site after authentication.\nclass LoginSpider(BaseSpider):\n domain_name = 'example.com'\n start_urls = ['http://www.example.com/users/login.php']\n\n def parse(self, response):\n return [FormRequest.from_response(response,\n formdata={'username': 'john', 'password': 'secret'},\n callback=self.after_login)]\n\n def after_login(self, response):\n # check login succeed before going on\n if \"authentication failed\" in response.body:\n self.log(\"Login failed\", level=log.ERROR)\n return\n\n # continue scraping with authenticated session...\n\n",
"I used mechanize for Python with success for a few things. It's easy to use and supports HTTP authentication, form handling, cookies, automatic HTTP redirection (30X), ... Basically the only thing missing is JavaScript, but if you need to rely on JS you're pretty much screwed anyway.\n",
"Free Download Manager is great for crawling, and you could use wget.\n",
"Try a Selenium script, automated with Selenium Remote Control.\n"
] |
[
5,
3,
0,
0
] |
[] |
[] |
[
"c#",
"html_parsing",
"python",
"watin",
"web_crawler"
] |
stackoverflow_0001768373_c#_html_parsing_python_watin_web_crawler.txt
|
Q:
General Purpose Progressbar in Django
I want to make a little web-frontend for copying (rsync) and encoding (ffmpeg) files for my Server using Django.
And I want to keep track of the progress of the processes.
I saw a few jquery-scripts, but they are designed to be used with uploads, and I don't know enough javascript to modify these scripts for my needs.
I want to write a script that retrieves the task status from a textfile and outputs a progressbar, but I've got no idea where to start.
Does somebody know a good tutorial to start with?
And sorry for my poor english.
A:
See the code here http://www.djangosnippets.org/snippets/679/, it says "upload progress for multipart forms" but there is nothing specific to forms, you can use it anywhere with few tweaks.
General concept is:
Write a web-service which can return data(e.g. JSON) about the progress.
On client side use JavaScript to call progress API periodically use that info to update some client side element e.g. a text, width of an image, color of some div etc.
|
General Purpose Progressbar in Django
|
I want to make a little web-frontend for copying (rsync) and encoding (ffmpeg) files for my Server using Django.
And I want to keep track of the progress of the processes.
I saw a few jquery-scripts, but they are designed to be used with uploads, and I don't know enough javascript to modify these scripts for my needs.
I want to write a script that retrieves the task status from a textfile and outputs a progressbar, but I've got no idea where to start.
Does somebody know a good tutorial to start with?
And sorry for my poor english.
|
[
"See the code here http://www.djangosnippets.org/snippets/679/, it says \"upload progress for multipart forms\" but there is nothing specific to forms, you can use it anywhere with few tweaks.\nGeneral concept is:\n\nWrite a web-service which can return data(e.g. JSON) about the progress.\nOn client side use JavaScript to call progress API periodically use that info to update some client side element e.g. a text, width of an image, color of some div etc.\n\n"
] |
[
9
] |
[] |
[] |
[
"django",
"javascript",
"jquery",
"progress_bar",
"python"
] |
stackoverflow_0001770205_django_javascript_jquery_progress_bar_python.txt
|
Q:
Regex to Split 1st Colon
I have a time in ISO 8601 ( 2009-11-19T19:55:00 ) which is also paired with a name commence. I'm trying to parse this into two. I'm currently up to here:
import re
sColon = re.compile('[:]')
aString = sColon.split("commence:2009-11-19T19:55:00")
Obviously this returns:
>>> aString
['commence','2009-11-19T19','55','00']
What I'd like it to return is this:
>>>aString
['commence','2009-11-19T19:55:00']
How would I go about do this in the original creation of sColon? Also, do you recommend any Regular Expression links or books that you have found useful, as I can see myself needing it in the future!
EDIT:
To clarify... I'd need a regular expression that would just parse at the very first instance of :, is this possible? The text ( commence ) before the colon can chance, yes...
A:
>>> first, colon, rest = "commence:2009-11-19T19:55:00".partition(':')
>>> print (first, colon, rest)
('commence', ':', '2009-11-19T19:55:00')
A:
You could put maximum split parameter in split function
>>> "commence:2009-11-19T19:55:00".split(":",1)
['commence', '2009-11-19T19:55:00']
Official Docs
S.split([sep [,maxsplit]]) -> list of strings
Return a list of the words in the string S, using sep as the
delimiter string. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator and empty strings are removed
from the result.
A:
Looks like you need .IndexOf(":"), then .Substring()?
A:
@OP, don't do the unnecessary. Regex is not needed with what you are doing. Python has very good string manipulation methods that you can use. All you need is split(), and slicing. Those are the very basics of Python.
>>> "commence:2009-11-19T19:55:00".split(":",1)
['commence', '2009-11-19T19:55:00']
>>>
|
Regex to Split 1st Colon
|
I have a time in ISO 8601 ( 2009-11-19T19:55:00 ) which is also paired with a name commence. I'm trying to parse this into two. I'm currently up to here:
import re
sColon = re.compile('[:]')
aString = sColon.split("commence:2009-11-19T19:55:00")
Obviously this returns:
>>> aString
['commence','2009-11-19T19','55','00']
What I'd like it to return is this:
>>>aString
['commence','2009-11-19T19:55:00']
How would I go about do this in the original creation of sColon? Also, do you recommend any Regular Expression links or books that you have found useful, as I can see myself needing it in the future!
EDIT:
To clarify... I'd need a regular expression that would just parse at the very first instance of :, is this possible? The text ( commence ) before the colon can chance, yes...
|
[
">>> first, colon, rest = \"commence:2009-11-19T19:55:00\".partition(':')\n\n>>> print (first, colon, rest)\n('commence', ':', '2009-11-19T19:55:00')\n\n",
"You could put maximum split parameter in split function\n>>> \"commence:2009-11-19T19:55:00\".split(\":\",1)\n['commence', '2009-11-19T19:55:00']\n\nOfficial Docs\n\nS.split([sep [,maxsplit]]) -> list of strings\nReturn a list of the words in the string S, using sep as the\ndelimiter string. If maxsplit is given, at most maxsplit\nsplits are done. If sep is not specified or is None, any\nwhitespace string is a separator and empty strings are removed\nfrom the result.\n\n\n",
"Looks like you need .IndexOf(\":\"), then .Substring()?\n",
"@OP, don't do the unnecessary. Regex is not needed with what you are doing. Python has very good string manipulation methods that you can use. All you need is split(), and slicing. Those are the very basics of Python.\n>>> \"commence:2009-11-19T19:55:00\".split(\":\",1)\n['commence', '2009-11-19T19:55:00']\n>>>\n\n"
] |
[
5,
5,
0,
0
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0001770569_python_regex.txt
|
Q:
How to insert repeated message in google protocol buffer _pb2.py file
How to insert repeated message in google protocol buffer _pb2.py file
A:
make changes to your .proto file. Look at the example : http://code.google.com/apis/protocolbuffers/docs/pythontutorial.html
|
How to insert repeated message in google protocol buffer _pb2.py file
|
How to insert repeated message in google protocol buffer _pb2.py file
|
[
"make changes to your .proto file. Look at the example : http://code.google.com/apis/protocolbuffers/docs/pythontutorial.html\n"
] |
[
0
] |
[] |
[] |
[
"buffer",
"protocols",
"python"
] |
stackoverflow_0001543904_buffer_protocols_python.txt
|
Q:
Metaclass not being called in subclasses
Here is a python session.
>>> class Z(type):
def __new__(cls, name, bases, attrs):
print cls
print name
return type(name, bases, attrs)
...
>>> class Y(object):
__metaclass__ = Z
...
<class '__main__.Z'>
Y
>>> class X(Y):
... pass
...
>>> class W(Y):
... __metaclass__ = Z
...
<class '__main__.Z'>
W
>>>
After I define class X I expect Z._new__ to be called for it, and to print the two line, which is not happening, (as metaclass are inherited?)
A:
The problem is that the cls argument (which is the metaclass object) is not passed on when you call type, therefore the class object Y that is created and returned does not have any reference to the metaclass Z.
If you replace the last line in __new__ with
return super(Z, cls).__new__(cls, name, bases, attrs)
then it works. Note that even though cls is used in super we still have to provide cls as an argument as well, since super here returns an unbound method (see here for more).
As an alternative to using super one could use:
return type.__new__(cls, name, bases, attrs)
The important thing is that we give cls (our metaclass object Z) to the classmethod __new__. The shorter form type(name, bases, attrs) fills in type itself for the cls argument, which is of course wrong. This error is similar to calling an instance method with the wrong self argument.
I prefer using super, since this is better style.
|
Metaclass not being called in subclasses
|
Here is a python session.
>>> class Z(type):
def __new__(cls, name, bases, attrs):
print cls
print name
return type(name, bases, attrs)
...
>>> class Y(object):
__metaclass__ = Z
...
<class '__main__.Z'>
Y
>>> class X(Y):
... pass
...
>>> class W(Y):
... __metaclass__ = Z
...
<class '__main__.Z'>
W
>>>
After I define class X I expect Z._new__ to be called for it, and to print the two line, which is not happening, (as metaclass are inherited?)
|
[
"The problem is that the cls argument (which is the metaclass object) is not passed on when you call type, therefore the class object Y that is created and returned does not have any reference to the metaclass Z.\nIf you replace the last line in __new__ with\nreturn super(Z, cls).__new__(cls, name, bases, attrs)\n\nthen it works. Note that even though cls is used in super we still have to provide cls as an argument as well, since super here returns an unbound method (see here for more).\nAs an alternative to using super one could use:\n return type.__new__(cls, name, bases, attrs)\n\nThe important thing is that we give cls (our metaclass object Z) to the classmethod __new__. The shorter form type(name, bases, attrs) fills in type itself for the cls argument, which is of course wrong. This error is similar to calling an instance method with the wrong self argument.\nI prefer using super, since this is better style.\n"
] |
[
14
] |
[] |
[] |
[
"metaclass",
"python"
] |
stackoverflow_0001770712_metaclass_python.txt
|
Q:
reactor.iterate seems to block a program with Py2exe
I'm currently using an application in python which works quite well but when I'm converting it with py2exe, the application seems to be suspended at the first "reactor.iterate"
Each time I press Ctrl+C to stop the application, the error is always the same and the application seems to be bloqued on a "reactor.iterate(4)"
This problem never occur with normal python interpreter.
Have you got an idea ?
A:
The typical use of the reactor is not to call reactor.iterate. It's hard to say why exactly you're getting the behavior you are without seeing your program, but for a wild guess, I'd say switching to reactor.run might help.
|
reactor.iterate seems to block a program with Py2exe
|
I'm currently using an application in python which works quite well but when I'm converting it with py2exe, the application seems to be suspended at the first "reactor.iterate"
Each time I press Ctrl+C to stop the application, the error is always the same and the application seems to be bloqued on a "reactor.iterate(4)"
This problem never occur with normal python interpreter.
Have you got an idea ?
|
[
"The typical use of the reactor is not to call reactor.iterate. It's hard to say why exactly you're getting the behavior you are without seeing your program, but for a wild guess, I'd say switching to reactor.run might help.\n"
] |
[
1
] |
[] |
[] |
[
"py2exe",
"python",
"twisted"
] |
stackoverflow_0001770754_py2exe_python_twisted.txt
|
Q:
Is there a more pythonic way to open a file if given one as an argument or stdin if not?
I'm trying to write a python script which follows the common unix command line pattern of accepting input from stdin if no file name is given. This is what I've been using:
if __name__ == "__main__":
if len(sys.argv) > 1:
stream = open(sys.argv[1])
else:
stream = sys.stdin
Is there a more pythonic way to do that?
A:
The fileinput module is perfect for this.
A:
similar but one-line solution
stream = sys.argv[1] if len(sys.argv)>1 else sys.stdin
A:
how about this one?
stream=sys.argv[1:] and open(sys.argv[1]) or sys.stdin
A:
I would suggest you make it more unixy instead:
if len(sys.argv) > 1:
sys.stdin = open(sys.argv[1])
|
Is there a more pythonic way to open a file if given one as an argument or stdin if not?
|
I'm trying to write a python script which follows the common unix command line pattern of accepting input from stdin if no file name is given. This is what I've been using:
if __name__ == "__main__":
if len(sys.argv) > 1:
stream = open(sys.argv[1])
else:
stream = sys.stdin
Is there a more pythonic way to do that?
|
[
"The fileinput module is perfect for this.\n",
"similar but one-line solution\nstream = sys.argv[1] if len(sys.argv)>1 else sys.stdin\n\n",
"how about this one?\nstream=sys.argv[1:] and open(sys.argv[1]) or sys.stdin\n\n",
"I would suggest you make it more unixy instead:\nif len(sys.argv) > 1:\n sys.stdin = open(sys.argv[1])\n\n"
] |
[
10,
5,
2,
0
] |
[] |
[] |
[
"command_line",
"python",
"unix"
] |
stackoverflow_0001770789_command_line_python_unix.txt
|
Q:
Reading a csv file in Python with different line terminator
I have a file in CSV format where the delimiter is the ASCII unit separator ^_ and the line terminator is the ASCII record separator ^^ (obviously, since these are nonprinting characters, I've just used one of the standard ways of writing them here). I've written plenty of code that reads and writes CSV files, so my issue isn't with Python's csv module per se. The problem is that the csv module doesn't support reading (but it does support writing) line terminators other than a carriage return or line feed, at least as of Python 2.6 where I just tested it. The documentation says that this is because it's hard coded, which I take to mean it's done in the C code that underlies the module, since I didn't see anything in the csv.py file that I could change.
Does anyone know a way around this limitation (patch, another CSV module, etc.)? I really need to read in a file where I can't use carriage returns or new lines as the line terminator because those characters will appear in some of the fields, and I'd like to avoid writing my own custom reader code if possible, even though that would be rather simple to meet my needs.
A:
Why not supply a custom iterable to the csv.reader function? Here is a naive implementation which reads the entire contents of the CSV file into memory at once (which may or may not be desirable, depending on the size of the file):
def records(path):
with open(path) as f:
contents = f.read()
return (record for record in contents.split('^^'))
csv.reader(records('input.csv'))
I think that should work.
|
Reading a csv file in Python with different line terminator
|
I have a file in CSV format where the delimiter is the ASCII unit separator ^_ and the line terminator is the ASCII record separator ^^ (obviously, since these are nonprinting characters, I've just used one of the standard ways of writing them here). I've written plenty of code that reads and writes CSV files, so my issue isn't with Python's csv module per se. The problem is that the csv module doesn't support reading (but it does support writing) line terminators other than a carriage return or line feed, at least as of Python 2.6 where I just tested it. The documentation says that this is because it's hard coded, which I take to mean it's done in the C code that underlies the module, since I didn't see anything in the csv.py file that I could change.
Does anyone know a way around this limitation (patch, another CSV module, etc.)? I really need to read in a file where I can't use carriage returns or new lines as the line terminator because those characters will appear in some of the fields, and I'd like to avoid writing my own custom reader code if possible, even though that would be rather simple to meet my needs.
|
[
"Why not supply a custom iterable to the csv.reader function? Here is a naive implementation which reads the entire contents of the CSV file into memory at once (which may or may not be desirable, depending on the size of the file):\ndef records(path):\n with open(path) as f:\n contents = f.read()\n return (record for record in contents.split('^^'))\n\ncsv.reader(records('input.csv'))\n\nI think that should work.\n"
] |
[
3
] |
[] |
[] |
[
"csv",
"delimiter",
"python"
] |
stackoverflow_0001770934_csv_delimiter_python.txt
|
Q:
Using Python/Selenium/Best Tool For The Job to get URI of image requests generated through JavaScript?
I have some JavaScript from a 3rd party vendor that is initiating an image request. I would like to figure out the URI of this image request.
I can load the page in my browser, and then monitor "Live HTTP Headers" or "Tamper Data" in order to figure out the image request URI, but I would prefer to create a command line process to do this.
My intuition is that it might be possible using python + qtwebkit, but perhaps there is a better way.
To clarify: I might have this (overly simplified code).
<script>
suffix = magicNumberFunctionIDontHaveAccessTo();
url = "http://foobar.com/function?parameter=" + suffix
img = document.createElement('img'); img.src=url; document.all.body.appendChild(img);
</script>
Then once the page is loaded, I can go figure out the url by sniffing the packets. But I can't just figure it out from the source, because I can't predict the outcome of magicNumberFunction...().
Any help would be muchly appreciated!
Thank you.
A:
The simplest thing to do might be to use something like HtmlUnit and skip a real browser entirely. By using Rhino, it can evaluate JavaScript and likely be used to extract that URL out.
That said, if you can't get that working, try out Selenium RC and use the captureNetworkTraffic command (which requires the Selenium instant be started with an option of captureNetworkTraffic=true). This will launch Firefox with a proxy configured and then let you pull the request info back out as JSON/XML/plain text. Then you can parse that content and get what you want.
Try out the instant test tool that my company offers. If the data you're looking for is in our results (after you click View Details), you'll be able to get it from Selenium. I know, since I wrote the captureNetworkTraffic API for Selenium for my company, BrowserMob.
A:
I would pick any one of the many http proxy servers written in Python -- probably one of the simplest ones at the very top of the list -- and tweak it to record all URLs requested (as well as proxy-serve them) e.g. appending them to a text file -- without loss of generality, call that text file 'XXX.txt'.
Now all you need is a script that: starts the proxy server in question; starts Firefox (or whatever) on your main desired URL with the proxy in question set as your proxy (see e.g. this SO question for how), though I'm sure other browsers would work just as well; waits a bit (e.g. until the proxy's XXX.txt file has not been altered for more than N seconds); reads XXX.txt to extract only the URLs you care about and record them wherever you wish; turns down the proxy and Firefox processes.
I think this will be much faster to put in place and make work correctly, for your specific requirements, than any more general solution based on qtwebkit, selenium, or other "automation kits".
A:
Use Firebug Firefox plugin. It will show you all requests in real time and you can even debug the JS in your Browser or run it step-by-step.
A:
Ultimately, I did it in python, using Selenium-RC. This solution requires the python files for selenium-rc, and you need to start the java server ("java -jar selenium-server.jar")
from selenium import selenium
import unittest
import lxml.html
class TestMyDomain(unittest.TestCase):
def setUp(self):
self.selenium = selenium("localhost", \
4444, "*firefox", "http://www.MyDomain.com")
self.selenium.start()
def test_mydomain(self):
htmldoc = open('site-list.html').read()
url_list = [link for (element, attribute,link,pos) in lxml.html.iterlinks(htmldoc)]
for url in url_list:
try:
sel = self.selenium
sel.open(url)
sel.select_window("null")
js_code = '''
myDomainWindow = this.browserbot.getUserWindow();
for(obj in myDomainWindow) {
/* This code grabs the OMNITURE tracking pixel img */
if ((obj.substring(0,4) == 's_i_') && (myDomainWindow[obj].src)) {
var ret = myDomainWindow[obj].src;
}
}
ret;
'''
omniture_url = sel.get_eval(js_code) #parse&process this however you want
except Exception, e:
print 'We ran into an error: %s' % (e,)
self.assertEqual("expectedValue", observedValue)
def tearDown(self):
self.selenium.stop()
if __name__ == "__main__":
unittest.main()
A:
Why can't you just read suffix, or url for that matter? Is the image loaded in an iframe or in your page?
If it is loaded in your page, then this may be a dirty hack (substitute document.body for whatever element is considered):
var ac = document.body.appendChild;
var sources = [];
document.body.appendChild = function(child) {
if (/^img$/i.test(child.tagName)) {
sources.push(child.getAttribute('src'));
}
ac(child);
}
|
Using Python/Selenium/Best Tool For The Job to get URI of image requests generated through JavaScript?
|
I have some JavaScript from a 3rd party vendor that is initiating an image request. I would like to figure out the URI of this image request.
I can load the page in my browser, and then monitor "Live HTTP Headers" or "Tamper Data" in order to figure out the image request URI, but I would prefer to create a command line process to do this.
My intuition is that it might be possible using python + qtwebkit, but perhaps there is a better way.
To clarify: I might have this (overly simplified code).
<script>
suffix = magicNumberFunctionIDontHaveAccessTo();
url = "http://foobar.com/function?parameter=" + suffix
img = document.createElement('img'); img.src=url; document.all.body.appendChild(img);
</script>
Then once the page is loaded, I can go figure out the url by sniffing the packets. But I can't just figure it out from the source, because I can't predict the outcome of magicNumberFunction...().
Any help would be muchly appreciated!
Thank you.
|
[
"The simplest thing to do might be to use something like HtmlUnit and skip a real browser entirely. By using Rhino, it can evaluate JavaScript and likely be used to extract that URL out.\nThat said, if you can't get that working, try out Selenium RC and use the captureNetworkTraffic command (which requires the Selenium instant be started with an option of captureNetworkTraffic=true). This will launch Firefox with a proxy configured and then let you pull the request info back out as JSON/XML/plain text. Then you can parse that content and get what you want.\nTry out the instant test tool that my company offers. If the data you're looking for is in our results (after you click View Details), you'll be able to get it from Selenium. I know, since I wrote the captureNetworkTraffic API for Selenium for my company, BrowserMob.\n",
"I would pick any one of the many http proxy servers written in Python -- probably one of the simplest ones at the very top of the list -- and tweak it to record all URLs requested (as well as proxy-serve them) e.g. appending them to a text file -- without loss of generality, call that text file 'XXX.txt'.\nNow all you need is a script that: starts the proxy server in question; starts Firefox (or whatever) on your main desired URL with the proxy in question set as your proxy (see e.g. this SO question for how), though I'm sure other browsers would work just as well; waits a bit (e.g. until the proxy's XXX.txt file has not been altered for more than N seconds); reads XXX.txt to extract only the URLs you care about and record them wherever you wish; turns down the proxy and Firefox processes.\nI think this will be much faster to put in place and make work correctly, for your specific requirements, than any more general solution based on qtwebkit, selenium, or other \"automation kits\".\n",
"Use Firebug Firefox plugin. It will show you all requests in real time and you can even debug the JS in your Browser or run it step-by-step.\n",
"Ultimately, I did it in python, using Selenium-RC. This solution requires the python files for selenium-rc, and you need to start the java server (\"java -jar selenium-server.jar\")\nfrom selenium import selenium\nimport unittest\nimport lxml.html\n\nclass TestMyDomain(unittest.TestCase):\n def setUp(self):\n self.selenium = selenium(\"localhost\", \\\n 4444, \"*firefox\", \"http://www.MyDomain.com\")\n self.selenium.start()\n\n def test_mydomain(self):\n\n htmldoc = open('site-list.html').read()\n url_list = [link for (element, attribute,link,pos) in lxml.html.iterlinks(htmldoc)]\n for url in url_list:\n\n try: \n sel = self.selenium\n sel.open(url) \n sel.select_window(\"null\")\n js_code = '''\n myDomainWindow = this.browserbot.getUserWindow();\n for(obj in myDomainWindow) { \n\n /* This code grabs the OMNITURE tracking pixel img */\n if ((obj.substring(0,4) == 's_i_') && (myDomainWindow[obj].src)) { \n var ret = myDomainWindow[obj].src;\n } \n } \n ret;\n '''\n omniture_url = sel.get_eval(js_code) #parse&process this however you want\n\n\n except Exception, e:\n print 'We ran into an error: %s' % (e,)\n\n\n self.assertEqual(\"expectedValue\", observedValue)\n\n\n def tearDown(self):\n self.selenium.stop()\n\nif __name__ == \"__main__\":\n unittest.main()\n\n",
"Why can't you just read suffix, or url for that matter? Is the image loaded in an iframe or in your page?\nIf it is loaded in your page, then this may be a dirty hack (substitute document.body for whatever element is considered):\nvar ac = document.body.appendChild;\nvar sources = [];\n\ndocument.body.appendChild = function(child) {\n if (/^img$/i.test(child.tagName)) {\n sources.push(child.getAttribute('src'));\n }\n ac(child);\n}\n\n"
] |
[
4,
3,
1,
1,
0
] |
[] |
[] |
[
"analytics",
"http_headers",
"python",
"selenium"
] |
stackoverflow_0001709711_analytics_http_headers_python_selenium.txt
|
Q:
Fixing a type-error in Python's Pg
Thank you for bobince in solving the first bugs!
How can you use pg.escape_bytea or pg.escape_string in the following?
#1 With both pg.escape_string and pg.escape_bytea
con1.query(
"INSERT INTO files (file, file_name) VALUES ('%s', '%s')" %
(pg.escape_bytea(pg.espace_string(f.read())), pg.espace_string(pg.escape_bytea(f.name)))
I get the error
AttributeError: 'module' object has no attribute 'espace_string'
I tested the two escapes in the reverse order unsuccessfully too.
#2 Without pg.escape_string()
con1.query(
"INSERT INTO files (file, file_name) VALUES ('%s', '%s')" %
(pg.escape_bytea(f.read()), pg.escape_bytea(f.name))
)
I get
WARNING: nonstandard use of \\ in a string literal
LINE 1: INSERT INTO files (file, file_name) VALUES ('%PDF-1.4\\012%\...
^
HINT: Use the escape string syntax for backslashes, e.g., E'\\'.
------------------------
-- Putting pdf files in
I get the following error
# 3 With only pg.escape_string
------------------------
-- Putting pdf files in
------------------------
Traceback (most recent call last):
File "<stdin>", line 30, in <module>
File "<stdin>", line 27, in put_pdf_files_in
File "/usr/lib/python2.6/dist-packages/pg.py", line 313, in query
return self.db.query(qstr)
pg.ProgrammingError: ERROR: invalid byte sequence for encoding "UTF8": 0xc7ec
HINT: This error can also happen if the byte sequence does not match the encoding expected by the server, which is controlled by "client_encoding".
A:
INSERT INTO files('binf','file_name') VALUES(file,file_name)
You've got the (...) sections the wrong way round, you're trying to insert the columns (file, filename) into the string literals ('binf', 'file_name'). You're also not actually inserting the contents of the variables binf and file_name into the query.
The pg module's query call does not support parameterisation. You would have to make the string yourself:
con1.query(
"INSERT INTO files (file, file_name) VALUES ('%s', '%s')" %
(pg.escape_string(f.read()), pg.escape_string(f.name))
)
This is assuming f is a file object; I'm not sure where file is coming from in the code above or what .read(binf) is supposed to mean. If you are using a bytea column to hold your file data you must use escape_bytea instead of escape_string.
Better than creating your own queries is letting pg do it for you with the insert method:
con1.insert('files', file= f.read(), file_name= f.name)
Alternatively, consider using the pgdb interface or one of the other DB-API-compliant interfaces that is not PostgreSQL-specific, if you ever want to consider running your app on a different database. DB-API gives you parameterisation in the execute method:
cursor.execute(
'INSERT INTO files (file, file_name) VALUES (%(content)s, %(name)s)',
{'content': f.read(), 'name': f.name }
)
|
Fixing a type-error in Python's Pg
|
Thank you for bobince in solving the first bugs!
How can you use pg.escape_bytea or pg.escape_string in the following?
#1 With both pg.escape_string and pg.escape_bytea
con1.query(
"INSERT INTO files (file, file_name) VALUES ('%s', '%s')" %
(pg.escape_bytea(pg.espace_string(f.read())), pg.espace_string(pg.escape_bytea(f.name)))
I get the error
AttributeError: 'module' object has no attribute 'espace_string'
I tested the two escapes in the reverse order unsuccessfully too.
#2 Without pg.escape_string()
con1.query(
"INSERT INTO files (file, file_name) VALUES ('%s', '%s')" %
(pg.escape_bytea(f.read()), pg.escape_bytea(f.name))
)
I get
WARNING: nonstandard use of \\ in a string literal
LINE 1: INSERT INTO files (file, file_name) VALUES ('%PDF-1.4\\012%\...
^
HINT: Use the escape string syntax for backslashes, e.g., E'\\'.
------------------------
-- Putting pdf files in
I get the following error
# 3 With only pg.escape_string
------------------------
-- Putting pdf files in
------------------------
Traceback (most recent call last):
File "<stdin>", line 30, in <module>
File "<stdin>", line 27, in put_pdf_files_in
File "/usr/lib/python2.6/dist-packages/pg.py", line 313, in query
return self.db.query(qstr)
pg.ProgrammingError: ERROR: invalid byte sequence for encoding "UTF8": 0xc7ec
HINT: This error can also happen if the byte sequence does not match the encoding expected by the server, which is controlled by "client_encoding".
|
[
"\nINSERT INTO files('binf','file_name') VALUES(file,file_name)\n\nYou've got the (...) sections the wrong way round, you're trying to insert the columns (file, filename) into the string literals ('binf', 'file_name'). You're also not actually inserting the contents of the variables binf and file_name into the query.\nThe pg module's query call does not support parameterisation. You would have to make the string yourself:\ncon1.query(\n \"INSERT INTO files (file, file_name) VALUES ('%s', '%s')\" %\n (pg.escape_string(f.read()), pg.escape_string(f.name))\n)\n\nThis is assuming f is a file object; I'm not sure where file is coming from in the code above or what .read(binf) is supposed to mean. If you are using a bytea column to hold your file data you must use escape_bytea instead of escape_string.\nBetter than creating your own queries is letting pg do it for you with the insert method:\ncon1.insert('files', file= f.read(), file_name= f.name)\n\nAlternatively, consider using the pgdb interface or one of the other DB-API-compliant interfaces that is not PostgreSQL-specific, if you ever want to consider running your app on a different database. DB-API gives you parameterisation in the execute method:\ncursor.execute(\n 'INSERT INTO files (file, file_name) VALUES (%(content)s, %(name)s)', \n {'content': f.read(), 'name': f.name }\n)\n\n"
] |
[
4
] |
[] |
[] |
[
"postgresql",
"python",
"types"
] |
stackoverflow_0001770786_postgresql_python_types.txt
|
Q:
Compare string and floats in python
I have a two lists with values that I want to compare. If the value can be converted to a float, I want to compare the floats else I just want to compare the values as strings. How can I make that distinction to check whether a value can be converted to float or not?
A:
The easiest way should be to just try to convert them to floats, and if that fails, fall back to a compare on strings:
def floatstrcmp(left, right):
try:
return cmp(float(left), float(right))
except ValueError:
return cmp(left, right)
|
Compare string and floats in python
|
I have a two lists with values that I want to compare. If the value can be converted to a float, I want to compare the floats else I just want to compare the values as strings. How can I make that distinction to check whether a value can be converted to float or not?
|
[
"The easiest way should be to just try to convert them to floats, and if that fails, fall back to a compare on strings:\ndef floatstrcmp(left, right):\n try:\n return cmp(float(left), float(right))\n except ValueError:\n return cmp(left, right)\n\n"
] |
[
4
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001771374_python.txt
|
Q:
Template system for RDF?
RDF is a schema-free system to represent data. However, most of the time I find myself writing a sort of well-known graph structure, and I have to build triple by triple.
In the more general case, this well known graph structure is of course not guaranteed to be complete nor fixed (e.g. something else can be added). However, if a more or less invariant backbone exists, it would be nice to describe this backbone with placeholders and then pass a context to produce the fully deployed RDF graph.
Does something like this exist in Python?
A:
Sounds a little like using a SPARQL CONSTRUCT query to make the final graph. Run a regular query (WHERE {} ) against a graph to form some variable bindings and then use the CONSTRUCT {} block to make the templated graph into your final answer. Any modern rdf library should have support for SPARQL.
|
Template system for RDF?
|
RDF is a schema-free system to represent data. However, most of the time I find myself writing a sort of well-known graph structure, and I have to build triple by triple.
In the more general case, this well known graph structure is of course not guaranteed to be complete nor fixed (e.g. something else can be added). However, if a more or less invariant backbone exists, it would be nice to describe this backbone with placeholders and then pass a context to produce the fully deployed RDF graph.
Does something like this exist in Python?
|
[
"Sounds a little like using a SPARQL CONSTRUCT query to make the final graph. Run a regular query (WHERE {} ) against a graph to form some variable bindings and then use the CONSTRUCT {} block to make the templated graph into your final answer. Any modern rdf library should have support for SPARQL.\n"
] |
[
3
] |
[] |
[] |
[
"python",
"rdf"
] |
stackoverflow_0001768921_python_rdf.txt
|
Q:
Choosing a Path for Python File Access
One of the features of my project is to allow users to create their own little .txt file, put it somewhere on their HDD, which can then be used as criteria for a part of my application.
Is there a Fixed, 'generic'(?) path for most OSs that I could use? Or does anyone have any kind of advice or guidance that could help me?
FYI, during development, I've just been using a fixed location (/home/user/Desktop/folder1/"), to which I then specify the filename, in order to complete the path.
A:
os.path.expanduser is a good start -- a leading ~/ expands to "the user's home directory", which is computer by reasonable heuristics on both Unix-y and Windows systems. Of course, you don't want to put your file in the home directly, but a subdirectory of that (which you'll have to make if not already there) is a reasonable default.
Of course, do allow this setting to be overridden by an environment variable or a command line flag passed to your program, because some platforms are rather finicky about where an application is supposed, by convention, to park such auxiliary data files.
Edit: the OP asks for an example:
Suppose I wanted it in ~/tempfoler/
and the file being passed to it was
args1.txt?
I'd suggest locating the exact path through a function such as:
import errno
import os
def getfilepath(filename, foldername='tempfoler', envar='MYAPPDIR'):
# check for environmental override
if envar is not None and envar in os.environ:
dirpath = os.environ[envar]
else:
dirpath = '~/%s' % foldername
# expand and ensure it's a directory
expanded = os.path.expanduser(dirpath)
if not os.path.isdir(expanded):
if os.path.lexists(expanded):
# we're in dire trouble: the path is a file, not a directory!
# you could punt to some default value, but I prefer to raise
# an exception and allow higher levels to deal with this
raise IOError(errno.EEXISTS, "Path is a file, not a dir", expanded)
# the following may also raise (permission issues, &c)
os.makedirs(expanded)
# now the directory exists, the file may or may not (doesn't matter)
return os.path.join(expanded, filename)
There are some design choices embedded here -- raise exceptions for all kinds of problems (higher levels may catch them and handle them appropriately, e.g. ask the user for an alternative -- this lower level function couldn't do that properly!), return the path to the file which may or may not exist (thus suitable for both reading an existing file or writing a new one), and so on.
You might also choose to do fewer checks and rely more on automatic exceptions being raised for all kinds of anomalies (or vice versa), I just think this one strikes a reasonable balance (and of course it's easy for you to tweak if you prefer a somewhat different approach to such issues). But the key idea is to always focus on what could go wrong and how it will be dealt with (often by higher-level code, the only proper point for possibly asking the user for alternatives) to make your software robust.
A:
The wx.StandardPaths module contains methods that return various standard locations in the file system and transparently tries to do "the right thing" under Unix, Mac OS X, and Windows.
A:
For the copy/paste crowd out there...
import os
file_obj = open(os.path.expanduser('~/yourapp/file.txt'), 'w')
Good luck.
|
Choosing a Path for Python File Access
|
One of the features of my project is to allow users to create their own little .txt file, put it somewhere on their HDD, which can then be used as criteria for a part of my application.
Is there a Fixed, 'generic'(?) path for most OSs that I could use? Or does anyone have any kind of advice or guidance that could help me?
FYI, during development, I've just been using a fixed location (/home/user/Desktop/folder1/"), to which I then specify the filename, in order to complete the path.
|
[
"os.path.expanduser is a good start -- a leading ~/ expands to \"the user's home directory\", which is computer by reasonable heuristics on both Unix-y and Windows systems. Of course, you don't want to put your file in the home directly, but a subdirectory of that (which you'll have to make if not already there) is a reasonable default.\nOf course, do allow this setting to be overridden by an environment variable or a command line flag passed to your program, because some platforms are rather finicky about where an application is supposed, by convention, to park such auxiliary data files.\nEdit: the OP asks for an example:\n\nSuppose I wanted it in ~/tempfoler/\n and the file being passed to it was\n args1.txt?\n\nI'd suggest locating the exact path through a function such as:\nimport errno\nimport os\n\ndef getfilepath(filename, foldername='tempfoler', envar='MYAPPDIR'):\n # check for environmental override\n if envar is not None and envar in os.environ:\n dirpath = os.environ[envar]\n else:\n dirpath = '~/%s' % foldername\n # expand and ensure it's a directory\n expanded = os.path.expanduser(dirpath)\n if not os.path.isdir(expanded):\n if os.path.lexists(expanded):\n # we're in dire trouble: the path is a file, not a directory!\n # you could punt to some default value, but I prefer to raise\n # an exception and allow higher levels to deal with this\n raise IOError(errno.EEXISTS, \"Path is a file, not a dir\", expanded)\n # the following may also raise (permission issues, &c)\n os.makedirs(expanded)\n # now the directory exists, the file may or may not (doesn't matter)\n return os.path.join(expanded, filename)\n\nThere are some design choices embedded here -- raise exceptions for all kinds of problems (higher levels may catch them and handle them appropriately, e.g. ask the user for an alternative -- this lower level function couldn't do that properly!), return the path to the file which may or may not exist (thus suitable for both reading an existing file or writing a new one), and so on.\nYou might also choose to do fewer checks and rely more on automatic exceptions being raised for all kinds of anomalies (or vice versa), I just think this one strikes a reasonable balance (and of course it's easy for you to tweak if you prefer a somewhat different approach to such issues). But the key idea is to always focus on what could go wrong and how it will be dealt with (often by higher-level code, the only proper point for possibly asking the user for alternatives) to make your software robust.\n",
"The wx.StandardPaths module contains methods that return various standard locations in the file system and transparently tries to do \"the right thing\" under Unix, Mac OS X, and Windows.\n",
"For the copy/paste crowd out there...\nimport os\nfile_obj = open(os.path.expanduser('~/yourapp/file.txt'), 'w')\n\nGood luck.\n"
] |
[
7,
3,
0
] |
[] |
[] |
[
"path",
"python"
] |
stackoverflow_0001771099_path_python.txt
|
Q:
Effective Interpreted Programming Language for File/Image manipulation
I need to make a script to read images from a directory, rename them, resize them to a MAX_HEIGHT, MAX_WIDTH, put a watermark logo and save them in JPG.
I was thinking on doing this with an interpreted language, like Ruby, PHP, Perl, Python, or any with the image manipulation capabilities.
Which language would you recommend for this?
A:
It seems, ImageMagick with PerlMagick fits your task nicely.
A:
Any language + ImageMagick set of programs. Using them via libraries (like PerlMagick) proved to be less than optimal, but doing it via system() calls worked incredibly well. You can find a set of scripts that:
perform several useful tasks
show less known features of ImageMagick
A:
Offhand, Python with the Python Imaging Library.
More answers here: What is the best image manipulation library?
A:
In the past, I've found the Imager Perl module to be hugely useful. It has a better API than GD and ImageMagick (IMHO) and is very fast. It also doesn't necessarily require external libraries such as libgd or ImageMagick except potentially the system library for reading/writing your desired file format.
I'm not going to try to answer the "which language is best" part of your question because I'm biased and that's the wrong question to ask anyway. It should be "How can I do X with any of these languages" and then decide for yourself based on the language specific answers. Judging from answers that pit one language against another is not advised. Usually, the bias and agenda of the person providing the answer isn't clear and thus the value of the answer for deciding is nil.
A:
You could look at what "phatch" does (http://photobatch.stani.be/), that's a python image batch pocessor.
It tries to use all the various open source image manipulation libraries (imagemagick, python's PIL, exiftools, etc) for the parts where they are good in. So even if you (probably) end up not using phatch itself, you can get a good idea of which tools are good for what. (See summary of a talk by phatch's author)
A:
Yet another alternative: shell of your choice, using netpbm.
|
Effective Interpreted Programming Language for File/Image manipulation
|
I need to make a script to read images from a directory, rename them, resize them to a MAX_HEIGHT, MAX_WIDTH, put a watermark logo and save them in JPG.
I was thinking on doing this with an interpreted language, like Ruby, PHP, Perl, Python, or any with the image manipulation capabilities.
Which language would you recommend for this?
|
[
"It seems, ImageMagick with PerlMagick fits your task nicely.\n",
"Any language + ImageMagick set of programs. Using them via libraries (like PerlMagick) proved to be less than optimal, but doing it via system() calls worked incredibly well. You can find a set of scripts that:\n\nperform several useful tasks\nshow less known features of ImageMagick\n\n",
"Offhand, Python with the Python Imaging Library.\nMore answers here: What is the best image manipulation library?\n",
"In the past, I've found the Imager Perl module to be hugely useful. It has a better API than GD and ImageMagick (IMHO) and is very fast. It also doesn't necessarily require external libraries such as libgd or ImageMagick except potentially the system library for reading/writing your desired file format.\nI'm not going to try to answer the \"which language is best\" part of your question because I'm biased and that's the wrong question to ask anyway. It should be \"How can I do X with any of these languages\" and then decide for yourself based on the language specific answers. Judging from answers that pit one language against another is not advised. Usually, the bias and agenda of the person providing the answer isn't clear and thus the value of the answer for deciding is nil.\n",
"You could look at what \"phatch\" does (http://photobatch.stani.be/), that's a python image batch pocessor.\nIt tries to use all the various open source image manipulation libraries (imagemagick, python's PIL, exiftools, etc) for the parts where they are good in. So even if you (probably) end up not using phatch itself, you can get a good idea of which tools are good for what. (See summary of a talk by phatch's author)\n",
"Yet another alternative: shell of your choice, using netpbm.\n"
] |
[
10,
9,
6,
5,
2,
2
] |
[] |
[] |
[
"image_manipulation",
"perl",
"php",
"python",
"ruby"
] |
stackoverflow_0001768749_image_manipulation_perl_php_python_ruby.txt
|
Q:
List of specific class names in Python
Is there a way to flag class declarations so that later you can get a list of them flagged?
Or a way to get all classes starting with a certain string ?
Or all classes that are a subclass of a specific class?
A:
Note: in the following I assume Python 3.x. For Python 2.x, use new style classes, i.e. write class T(object): pass instead of class T: pass.
First, define some classes:
>>> class T: pass
...
>>> class S: pass
...
>>> class U(T): pass
...
To get a list of classes defined in the current scope, iterate over the globals (or locals) and test whether they are an instance of type (thus a class!) using isinstance:
>>> [n for n, o in globals().items() if isinstance(o, type)]
['S', 'U', 'T']
Use issubclass to restrict your search to the subclasses of a given class (in this case T):
>>> [n for n, o in globals().items() if isinstance(o, type) and issubclass(o, (T,))]
['U', 'T']
You may want to omit T itself:
>>> [n for n, o in globals().items() if o != T and isinstance(o, type) and issubclass(o, (T,))]
['U']
To get all classes starting with a certain string, call startswith on the class name:
>>> [n for n, o in globals().items() if n.startswith('T') and isinstance(o, type)]
['T']
To flag certain classes at creation, use a class decorator† to add an attribute, e.g. __flagged__:
>>> def flag(cls):
... cls.__flag__ = 'flagged'
... return cls
...
>>> @flag
... class X: pass
...
>>> @flag
... class Y: pass
...
>>> class Z: pass
...
Now you can just select only those classed with the __flag__ attribute:
>>> [n for n, o in globals().items() if isinstance(o, type) and hasattr(o, '__flag__')]
['X', 'Y']
†: As bobince notes, class decorators are new in Python 2.6.
A:
You can also use metaclasses to collect up the classes as they are defined:
class AllSeeingMetaClass(type):
# This will be a list of all the classes that use us as a metaclass.
the_classes = []
def __new__(meta, classname, bases, classDict):
# Invoked as new classes are defined.
print "Defining %r" % classname
new_class = type.__new__(meta, classname, bases, classDict)
meta.the_classes.append(new_class)
return new_class
class MyBase(object):
# A base class that pulls in our metaclass.
__metaclass__ = AllSeeingMetaClass
class Cat(MyBase):
def __init__(self):
pass
class Dog(MyBase):
def __init__(self):
pass
print AllSeeingMetaClass.the_classes
prints:
Defining 'MyBase'
Defining 'Cat'
Defining 'Dog'
[<class '__main__.MyBase'>, <class '__main__.Cat'>, <class '__main__.Dog'>]
A:
To get a list of subclasses of your class from within itself, use the __subclasses__ method from the parent class.
>>>class Parent(object):
... pass
...
>>>class Child(Parent):
... pass
...
>>>Parent.__subclasses__()
>>>[<class '__main__.Child'>]
Unfortunately there is a dearth of documentation on this method.
|
List of specific class names in Python
|
Is there a way to flag class declarations so that later you can get a list of them flagged?
Or a way to get all classes starting with a certain string ?
Or all classes that are a subclass of a specific class?
|
[
"Note: in the following I assume Python 3.x. For Python 2.x, use new style classes, i.e. write class T(object): pass instead of class T: pass.\n\nFirst, define some classes:\n>>> class T: pass\n... \n>>> class S: pass\n... \n>>> class U(T): pass\n...\n\nTo get a list of classes defined in the current scope, iterate over the globals (or locals) and test whether they are an instance of type (thus a class!) using isinstance:\n>>> [n for n, o in globals().items() if isinstance(o, type)]\n['S', 'U', 'T']\n\nUse issubclass to restrict your search to the subclasses of a given class (in this case T):\n>>> [n for n, o in globals().items() if isinstance(o, type) and issubclass(o, (T,))]\n['U', 'T']\n\nYou may want to omit T itself:\n>>> [n for n, o in globals().items() if o != T and isinstance(o, type) and issubclass(o, (T,))]\n['U']\n\nTo get all classes starting with a certain string, call startswith on the class name:\n>>> [n for n, o in globals().items() if n.startswith('T') and isinstance(o, type)]\n['T']\n\nTo flag certain classes at creation, use a class decorator† to add an attribute, e.g. __flagged__:\n>>> def flag(cls):\n... cls.__flag__ = 'flagged'\n... return cls\n... \n>>> @flag\n... class X: pass\n... \n>>> @flag\n... class Y: pass\n... \n>>> class Z: pass\n... \n\nNow you can just select only those classed with the __flag__ attribute:\n>>> [n for n, o in globals().items() if isinstance(o, type) and hasattr(o, '__flag__')]\n['X', 'Y']\n\n\n\n †: As bobince notes, class decorators are new in Python 2.6.\n",
"You can also use metaclasses to collect up the classes as they are defined:\nclass AllSeeingMetaClass(type):\n # This will be a list of all the classes that use us as a metaclass.\n the_classes = []\n\n def __new__(meta, classname, bases, classDict):\n # Invoked as new classes are defined.\n print \"Defining %r\" % classname\n new_class = type.__new__(meta, classname, bases, classDict)\n meta.the_classes.append(new_class)\n return new_class\n\n\nclass MyBase(object):\n # A base class that pulls in our metaclass.\n __metaclass__ = AllSeeingMetaClass\n\n\nclass Cat(MyBase):\n def __init__(self):\n pass\n\nclass Dog(MyBase):\n def __init__(self):\n pass\n\nprint AllSeeingMetaClass.the_classes\n\nprints:\nDefining 'MyBase'\nDefining 'Cat'\nDefining 'Dog'\n[<class '__main__.MyBase'>, <class '__main__.Cat'>, <class '__main__.Dog'>]\n\n",
"To get a list of subclasses of your class from within itself, use the __subclasses__ method from the parent class.\n>>>class Parent(object):\n... pass\n...\n>>>class Child(Parent):\n... pass\n...\n>>>Parent.__subclasses__()\n>>>[<class '__main__.Child'>]\n\nUnfortunately there is a dearth of documentation on this method.\n"
] |
[
3,
1,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001770701_python.txt
|
Q:
Collecting usage data for a desktop application
I'm going to be running some large scale usability tests of my software for a science project. We have a lab of about 30 computers running Windows XP. Our application is written in Python and PyGTK.
We want to be able to collect the following without staff intervention (automatically on our application start):
A recording of the user session (a la GtkRecordMyDesktop)
All tracebacks and errors produced by our application
Amount of time till the user reaches a certain point in the application.
A short survey presented at application exit
I think the last point is pretty straightforward, and I know how I'd store the data, but I don't know how I'd implement the other points.
A:
For your first point, I believe you can drive recordMyDesktop directly from your Python code pretty easily -- I haven't done so, myself, but the docs make it look easy (and both existing frontends to it are in Python).
For your second point, set sys.excepthook to intercept the exceptions and prepare your report via the traceback module.
For your third point, register the time at start (e.g. via datetime.datetime.now) and again at the point you care about, and log the difference.
|
Collecting usage data for a desktop application
|
I'm going to be running some large scale usability tests of my software for a science project. We have a lab of about 30 computers running Windows XP. Our application is written in Python and PyGTK.
We want to be able to collect the following without staff intervention (automatically on our application start):
A recording of the user session (a la GtkRecordMyDesktop)
All tracebacks and errors produced by our application
Amount of time till the user reaches a certain point in the application.
A short survey presented at application exit
I think the last point is pretty straightforward, and I know how I'd store the data, but I don't know how I'd implement the other points.
|
[
"For your first point, I believe you can drive recordMyDesktop directly from your Python code pretty easily -- I haven't done so, myself, but the docs make it look easy (and both existing frontends to it are in Python).\nFor your second point, set sys.excepthook to intercept the exceptions and prepare your report via the traceback module.\nFor your third point, register the time at start (e.g. via datetime.datetime.now) and again at the point you care about, and log the difference.\n"
] |
[
2
] |
[] |
[] |
[
"analytics",
"metrics",
"python",
"usability",
"windows"
] |
stackoverflow_0001771765_analytics_metrics_python_usability_windows.txt
|
Q:
How do I make text wrapping match current indentation level in vim?
Does anyone know of a way to get vim to wrap long lines of text such that the position of the wrapped text is based on the indentation of the current line? I don't want to reformat my code, just for it to be displayed prettily.
For instance, if I set my settings so that the line:
print 'ProcessorError(%r, %r, %r)' % (self.file, self.index, self.message)
is displayed when wrapped as:
print 'ProcessorError(%r, %r, %r)' % (self.file, self.index,
self.message)
then if I write a block of code like this:
def __repr__(self):
return 'ProcessorError(%r, %r, %r)' % (self.file, self.index, self.message)
it wraps to something like this:
def __repr__(self):
return 'ProcessorError(%r, %r, %r)' % (self.file, self.index,
self.message)
I would prefer for it to be displayed as:
def __repr__(self):
return 'ProcessorError(%r, %r, %r)' % (self.file, self.index,
self.message)
Edit: after reading Don Werve's response, it seems that I am indeed looking for the breakindent option, but the option is still on the "Awaiting updated patches" list (see Vim TODO). So what I'd like to know is what is the easiest way to get vim working with breakindent? (I don't care what version of vim I have to use.)
A:
I asked the same question on SuperUser, eventually found this question, found the patch, and updated the patch to work with Vim 7.2.148 from Fedora 11.
You can use yumdownloader --source vim to get the source RPM. Then add a Patch3312: line and a %patch3012 -p1 line to the spec file, and build the rpm.
A:
You're looking for breakindent
You may want to also refer to this thread.
A:
I recommend this vimscript:
http://www.vim.org/scripts/script.php?script_id=974
"This indentation script for python tries to match more closely what is suggested in PEP 8 (http://www.python.org/peps/pep-0008.html). In particular, it handles continuation lines implied by open (parentheses), [brackets] and {braces} correctly and it indents multiline if/for/while statements differently."
A:
For controlling the indentation of Python code, see :h ft-python-indent. This for example will make Vim indent two times the shiftwidth if you do a newline while there's an unclosed paren:
let g:pyindent_open_paren = '&sw * 2'
However &sw * 2 is the default, so not sure why it's not working for you. It works for me with manual newlines or with textwidth-induced newlines.
The above setting needs to be in .vimrc or needs to be set somehow before Vim enters Python mode. Be sure to :setf python or that you're otherwise in Python mode.
|
How do I make text wrapping match current indentation level in vim?
|
Does anyone know of a way to get vim to wrap long lines of text such that the position of the wrapped text is based on the indentation of the current line? I don't want to reformat my code, just for it to be displayed prettily.
For instance, if I set my settings so that the line:
print 'ProcessorError(%r, %r, %r)' % (self.file, self.index, self.message)
is displayed when wrapped as:
print 'ProcessorError(%r, %r, %r)' % (self.file, self.index,
self.message)
then if I write a block of code like this:
def __repr__(self):
return 'ProcessorError(%r, %r, %r)' % (self.file, self.index, self.message)
it wraps to something like this:
def __repr__(self):
return 'ProcessorError(%r, %r, %r)' % (self.file, self.index,
self.message)
I would prefer for it to be displayed as:
def __repr__(self):
return 'ProcessorError(%r, %r, %r)' % (self.file, self.index,
self.message)
Edit: after reading Don Werve's response, it seems that I am indeed looking for the breakindent option, but the option is still on the "Awaiting updated patches" list (see Vim TODO). So what I'd like to know is what is the easiest way to get vim working with breakindent? (I don't care what version of vim I have to use.)
|
[
"I asked the same question on SuperUser, eventually found this question, found the patch, and updated the patch to work with Vim 7.2.148 from Fedora 11.\nYou can use yumdownloader --source vim to get the source RPM. Then add a Patch3312: line and a %patch3012 -p1 line to the spec file, and build the rpm.\n",
"You're looking for breakindent\nYou may want to also refer to this thread.\n",
"I recommend this vimscript:\nhttp://www.vim.org/scripts/script.php?script_id=974\n\"This indentation script for python tries to match more closely what is suggested in PEP 8 (http://www.python.org/peps/pep-0008.html). In particular, it handles continuation lines implied by open (parentheses), [brackets] and {braces} correctly and it indents multiline if/for/while statements differently.\"\n",
"For controlling the indentation of Python code, see :h ft-python-indent. This for example will make Vim indent two times the shiftwidth if you do a newline while there's an unclosed paren:\nlet g:pyindent_open_paren = '&sw * 2'\n\nHowever &sw * 2 is the default, so not sure why it's not working for you. It works for me with manual newlines or with textwidth-induced newlines.\nThe above setting needs to be in .vimrc or needs to be set somehow before Vim enters Python mode. Be sure to :setf python or that you're otherwise in Python mode. \n"
] |
[
7,
4,
1,
0
] |
[
"I think set textwidth=80 should do it.\n"
] |
[
-2
] |
[
"python",
"vim",
"word_wrap"
] |
stackoverflow_0000759577_python_vim_word_wrap.txt
|
Q:
Is there a way to parse html with lxml, but manipulate it with minidom?
I have an application where I've been using html5lib to liberally parse html. I use the minidom interface, because I need a real DOM API and ElementTree is not appropriate for what I'm doing.
Here's how I do this:
parser = html5lib.XHTMLParser(tree=html5lib.treebuilders.getTreeBuilder('dom'))
parser.parse(html)
However, parsing huge files is becoming a performance bottleneck, and lxml parsing is about 80 times faster than html5lib (I benchmarked it).
How do I parse with lxml or a similarly fast bad-html-tolerant library, and manipulate with a DOM-compatible API?
A:
Think I found a solution:
from xml.dom.pulldom import SAX2DOM
import lxml.sax
def parse_lxml_dom(html):
tree = lxml.html.document_fromstring(html)
handler = SAX2DOM()
lxml.sax.saxify(tree, handler)
return handler.document
However, this is only about 7 times faster than html5lib. The saxify call takes quite a while.
|
Is there a way to parse html with lxml, but manipulate it with minidom?
|
I have an application where I've been using html5lib to liberally parse html. I use the minidom interface, because I need a real DOM API and ElementTree is not appropriate for what I'm doing.
Here's how I do this:
parser = html5lib.XHTMLParser(tree=html5lib.treebuilders.getTreeBuilder('dom'))
parser.parse(html)
However, parsing huge files is becoming a performance bottleneck, and lxml parsing is about 80 times faster than html5lib (I benchmarked it).
How do I parse with lxml or a similarly fast bad-html-tolerant library, and manipulate with a DOM-compatible API?
|
[
"Think I found a solution:\nfrom xml.dom.pulldom import SAX2DOM\nimport lxml.sax\ndef parse_lxml_dom(html):\n tree = lxml.html.document_fromstring(html)\n handler = SAX2DOM()\n lxml.sax.saxify(tree, handler)\n return handler.document\n\nHowever, this is only about 7 times faster than html5lib. The saxify call takes quite a while.\n"
] |
[
4
] |
[] |
[] |
[
"dom",
"html",
"lxml",
"parsing",
"python"
] |
stackoverflow_0001772031_dom_html_lxml_parsing_python.txt
|
Q:
List in a dictionary, looping in Python
I have the following code:
TYPES = {'hotmail':{'type':'hotmail', 'lookup':'mixed', 'dkim': 'no', 'signatures':['|S|Return-Path: postmaster@hotmail.com','|R|^Return-Path:\s*[^@]+@(?:hot|msn)','^Received: from .*hotmail.com$']},
'gmail':{'type':'gmail', 'lookup':'mixed', 'dkim': 'yes', 'signatures':['|S|Subject: unsubscribe','','','']}
}
for type_key, type in TYPES.iteritems():
for sub_type_key, sub_type in type.iteritems():
for sig in sub_type['signatures']:
if ("|S|" in sig):
#String based matching
clean_sig = sig[3:len(sig)]
if (clean_sig in file_contents):
sig_match += 1
elif ("|R|" in sig):
clean_sig = sig[3:len(sig)]
#REGMATCH later
if (sig_match == sig.count):
return sub_type['type']
return None
However, it generates the error:
for sig in sub_type['signatures']:
TypeError: string indices must be integers, not str
I assume that it would see the list being pulled from dictionary element, and allow me to loop over that?
Python newbie is a newbie :(
A:
for type_key, type in TYPES.iteritems():
for sub_type_key, sub_type in type.iteritems():
for sig in sub_type['signatures']:
should be:
for type_key, type in TYPES.iteritems():
for sig in type['signatures']:
But 'type' is a poor name choice in this case... you don't want to shadow a builtin.
Essentially, 'type_key' has the name (either 'hotmail' or 'gmail'), and 'type' has the dictionary that is the value associated with that key. So type['signatures'] is what you're wanting.
Also, you may not need to have 'gmail' inside the nested dictionary; just return 'type_key' instead of type['type'].
Bringing it all together, maybe this will work better: (Warning: untested)
providers = {
'hotmail':{
'type':'hotmail',
'lookup':'mixed',
'dkim': 'no',
'signatures':[
'|S|Return-Path: postmaster@hotmail.com',
'|R|^Return-Path:\s*[^@]+@(?:hot|msn)',
'^Received: from .*hotmail.com$']
},
'gmail':{
'type':'gmail',
'lookup':'mixed',
'dkim': 'yes',
'signatures':['|S|Subject: unsubscribe','','','']
}
}
for provider, provider_info in providers.iteritems():
for sig in provicer_info['signatures']:
if ("|S|" in sig):
#String based matching
clean_sig = sig[3:len(sig)]
if (clean_sig in file_contents):
sig_match += 1
elif ("|R|" in sig):
clean_sig = sig[3:len(sig)]
#REGMATCH later
if (sig_match == sig.count):
return provider
return None
A:
[Posted as an answer instead of a comment because retracile beat me to the answer, but the formatting is still a point worth making.]
Laying out the data helps to visualize it:
TYPES = {
'hotmail': {
'type': 'hotmail',
'lookup': 'mixed',
'dkim': 'no',
'signatures': ['|S|Return-Path: postmaster@hotmail.com',
'|R|^Return-Path:\s*[^@]+@(?:hot|msn)',
'^Received: from .*hotmail.com$'],
},
'gmail': {
'type': 'gmail',
'lookup': 'mixed',
'dkim': 'yes',
'signatures': ['|S|Subject: unsubscribe', '', '', ''],
},
}
Note: You can have an ending comma after the last item in a dict, list, or tuple (used above only for the dicts—it's not always more clear), and you don't have to worry about screwing around with that comma, which is a Good Thing™.
|
List in a dictionary, looping in Python
|
I have the following code:
TYPES = {'hotmail':{'type':'hotmail', 'lookup':'mixed', 'dkim': 'no', 'signatures':['|S|Return-Path: postmaster@hotmail.com','|R|^Return-Path:\s*[^@]+@(?:hot|msn)','^Received: from .*hotmail.com$']},
'gmail':{'type':'gmail', 'lookup':'mixed', 'dkim': 'yes', 'signatures':['|S|Subject: unsubscribe','','','']}
}
for type_key, type in TYPES.iteritems():
for sub_type_key, sub_type in type.iteritems():
for sig in sub_type['signatures']:
if ("|S|" in sig):
#String based matching
clean_sig = sig[3:len(sig)]
if (clean_sig in file_contents):
sig_match += 1
elif ("|R|" in sig):
clean_sig = sig[3:len(sig)]
#REGMATCH later
if (sig_match == sig.count):
return sub_type['type']
return None
However, it generates the error:
for sig in sub_type['signatures']:
TypeError: string indices must be integers, not str
I assume that it would see the list being pulled from dictionary element, and allow me to loop over that?
Python newbie is a newbie :(
|
[
"for type_key, type in TYPES.iteritems():\n for sub_type_key, sub_type in type.iteritems():\n for sig in sub_type['signatures']:\n\nshould be:\nfor type_key, type in TYPES.iteritems():\n for sig in type['signatures']:\n\nBut 'type' is a poor name choice in this case... you don't want to shadow a builtin.\nEssentially, 'type_key' has the name (either 'hotmail' or 'gmail'), and 'type' has the dictionary that is the value associated with that key. So type['signatures'] is what you're wanting.\nAlso, you may not need to have 'gmail' inside the nested dictionary; just return 'type_key' instead of type['type'].\nBringing it all together, maybe this will work better: (Warning: untested)\nproviders = {\n 'hotmail':{\n 'type':'hotmail',\n 'lookup':'mixed',\n 'dkim': 'no',\n 'signatures':[\n '|S|Return-Path: postmaster@hotmail.com',\n '|R|^Return-Path:\\s*[^@]+@(?:hot|msn)',\n '^Received: from .*hotmail.com$']\n },\n 'gmail':{\n 'type':'gmail',\n 'lookup':'mixed',\n 'dkim': 'yes',\n 'signatures':['|S|Subject: unsubscribe','','','']\n }\n}\n\nfor provider, provider_info in providers.iteritems():\n for sig in provicer_info['signatures']:\n if (\"|S|\" in sig):\n #String based matching\n clean_sig = sig[3:len(sig)]\n if (clean_sig in file_contents):\n sig_match += 1\n elif (\"|R|\" in sig):\n clean_sig = sig[3:len(sig)]\n #REGMATCH later\n if (sig_match == sig.count):\n return provider\n\n return None\n\n",
"[Posted as an answer instead of a comment because retracile beat me to the answer, but the formatting is still a point worth making.]\nLaying out the data helps to visualize it:\nTYPES = {\n 'hotmail': {\n 'type': 'hotmail',\n 'lookup': 'mixed',\n 'dkim': 'no', \n 'signatures': ['|S|Return-Path: postmaster@hotmail.com',\n '|R|^Return-Path:\\s*[^@]+@(?:hot|msn)',\n '^Received: from .*hotmail.com$'],\n },\n 'gmail': {\n 'type': 'gmail',\n 'lookup': 'mixed',\n 'dkim': 'yes', \n 'signatures': ['|S|Subject: unsubscribe', '', '', ''],\n },\n}\n\nNote: You can have an ending comma after the last item in a dict, list, or tuple (used above only for the dicts—it's not always more clear), and you don't have to worry about screwing around with that comma, which is a Good Thing™.\n"
] |
[
7,
3
] |
[] |
[] |
[
"dictionary",
"list",
"python"
] |
stackoverflow_0001772068_dictionary_list_python.txt
|
Q:
Python equivalent of ruby's __method__?
I want to be able to do this:
def asdf():
print __method__
"asdf"
Thanks,
Noah
A:
You need to specify your usecase in order for us to give you a better answer.
Why do you want to do this?
You can get a string with the name of a function by using __name__:
def asdf():
print asdf.__name__
"asdf"
But, what would be the point? You might aswell just print the name directly in that case.
What would happen in this case?
def asdf():
print __method__
foo = asdf
foo()
Print "foo" or "asdf"?
A:
Use the traceback module:
#!/usr/bin/env python
import traceback
def asdf():
(filename,line_number,function_name,text)=traceback.extract_stack()[-1]
print function_name
asdf()
|
Python equivalent of ruby's __method__?
|
I want to be able to do this:
def asdf():
print __method__
"asdf"
Thanks,
Noah
|
[
"You need to specify your usecase in order for us to give you a better answer.\nWhy do you want to do this?\nYou can get a string with the name of a function by using __name__:\ndef asdf():\n print asdf.__name__\n\"asdf\"\n\nBut, what would be the point? You might aswell just print the name directly in that case.\nWhat would happen in this case?\ndef asdf():\n print __method__\n\nfoo = asdf\nfoo()\n\nPrint \"foo\" or \"asdf\"?\n",
"Use the traceback module:\n#!/usr/bin/env python\nimport traceback\ndef asdf():\n (filename,line_number,function_name,text)=traceback.extract_stack()[-1]\n print function_name\nasdf()\n\n"
] |
[
8,
4
] |
[] |
[] |
[
"python",
"ruby"
] |
stackoverflow_0001772070_python_ruby.txt
|
Q:
IOError with Python and OpenCV
I want to do some OpenCV Basic Operations using Python. My Problem is that the Pythoninterpreter says that the file I want to open with cv.LoadImage() dont exists.
But as you can see in my code and the and the Interpreter Output this file exists and the Program should be able to read it.
Likly the answer is simple (I am new at Python Programming!).
Thanks for answers!
Here my Code:
import cv, sys, os
print sys.argv[1]
print os.getcwd()
print os.access(sys.argv[1], os.F_OK)
img = cv.LoadImage(sys.argv[1], 1)
cv.NamedWindow("orginal", CV_WINDOW_AUTOSIZE)
cv.ShowImage("orginal", img)
cv.waitKey(0)
here is the Pythoninterpreter Output:
dennis@Powertux:~/opencv/showPicture$ python2.5 showPicture.py google-de02.jpg google-de02.jpg
/home/steffke/opencv/showPicture
True
Traceback (most recent call last):
File "showPicture.py", line 7, in <module>
img = cv.LoadImage(sys.argv[1], 1)
IOError: [Errno 2] No such file or directory: 'google-de02.jpg'
A:
I've tried both suggestions, but its the same like before. the os.access returns a TRUE but the function cv.LoadImage produce the same error.
Any other solutions?
anyhow thanks fpr answer...
A:
Try giving it the whole path instead of the name only, or maybe using .\google-de02.jpg.
A:
Try using the repr function when the exception happens.
|
IOError with Python and OpenCV
|
I want to do some OpenCV Basic Operations using Python. My Problem is that the Pythoninterpreter says that the file I want to open with cv.LoadImage() dont exists.
But as you can see in my code and the and the Interpreter Output this file exists and the Program should be able to read it.
Likly the answer is simple (I am new at Python Programming!).
Thanks for answers!
Here my Code:
import cv, sys, os
print sys.argv[1]
print os.getcwd()
print os.access(sys.argv[1], os.F_OK)
img = cv.LoadImage(sys.argv[1], 1)
cv.NamedWindow("orginal", CV_WINDOW_AUTOSIZE)
cv.ShowImage("orginal", img)
cv.waitKey(0)
here is the Pythoninterpreter Output:
dennis@Powertux:~/opencv/showPicture$ python2.5 showPicture.py google-de02.jpg google-de02.jpg
/home/steffke/opencv/showPicture
True
Traceback (most recent call last):
File "showPicture.py", line 7, in <module>
img = cv.LoadImage(sys.argv[1], 1)
IOError: [Errno 2] No such file or directory: 'google-de02.jpg'
|
[
"I've tried both suggestions, but its the same like before. the os.access returns a TRUE but the function cv.LoadImage produce the same error.\nAny other solutions?\nanyhow thanks fpr answer...\n",
"Try giving it the whole path instead of the name only, or maybe using .\\google-de02.jpg.\n",
"Try using the repr function when the exception happens.\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"opencv",
"python"
] |
stackoverflow_0001772103_opencv_python.txt
|
Q:
Python/MySQL fails under Windows
I'm trying to get Python 2.6 to communicate with MySQL Server 5.1, under Windows XP, but I keep getting a strange error, "SystemError: NULL object passed to Py_BuildValue":
>>> import MySQLdb as mysql
>>> db = mysql.connect(user = "root", passwd="whatever", db="mysql", host="localh
ost")
>>> cu = db.cursor()
>>> cu.execute("show tables")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\dirr\lib\site-packages\MySQLdb\cursors.py", line 173, in execu
te
self.errorhandler(self, exc, value)
File "C:\ dirr\lib\site-packages\MySQLdb\connections.py", line 36, in de
faulterrorhandler
raise errorclass, errorvalue
SystemError: NULL object passed to Py_BuildValue
I thought it might be a character set problem, but I've tried setting and setting MySQL as UTF-8, and it hasn't made a difference.
I guess there must be a problem with python-mysql. Can anyone help?
UPDATE
OK, python-mysql under windows is a bit of a nightmare, particularly with Python 2.6 it seems. Rather than installing python-mysql with pip, use this installer instead. That fixed it.
A:
Something wrong with MySQLdb part written in C. According to errors message it tries to pass NULL where pointer to object is expected. It's probably a bug in MySQLdb, unless you are using some broken build. What version are you using? Try to download latest stable version of MySQLdb for exactly your python version and reinstall it. Try installing previous version. And fill in bug report if latest version doesn't work.
This and this reports are probably relevant to you error. According to them you mysql returns some error that triggers a bug in MySQLdb. Unfortunately it's not so easy to discover what this error is.
|
Python/MySQL fails under Windows
|
I'm trying to get Python 2.6 to communicate with MySQL Server 5.1, under Windows XP, but I keep getting a strange error, "SystemError: NULL object passed to Py_BuildValue":
>>> import MySQLdb as mysql
>>> db = mysql.connect(user = "root", passwd="whatever", db="mysql", host="localh
ost")
>>> cu = db.cursor()
>>> cu.execute("show tables")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\dirr\lib\site-packages\MySQLdb\cursors.py", line 173, in execu
te
self.errorhandler(self, exc, value)
File "C:\ dirr\lib\site-packages\MySQLdb\connections.py", line 36, in de
faulterrorhandler
raise errorclass, errorvalue
SystemError: NULL object passed to Py_BuildValue
I thought it might be a character set problem, but I've tried setting and setting MySQL as UTF-8, and it hasn't made a difference.
I guess there must be a problem with python-mysql. Can anyone help?
UPDATE
OK, python-mysql under windows is a bit of a nightmare, particularly with Python 2.6 it seems. Rather than installing python-mysql with pip, use this installer instead. That fixed it.
|
[
"Something wrong with MySQLdb part written in C. According to errors message it tries to pass NULL where pointer to object is expected. It's probably a bug in MySQLdb, unless you are using some broken build. What version are you using? Try to download latest stable version of MySQLdb for exactly your python version and reinstall it. Try installing previous version. And fill in bug report if latest version doesn't work.\nThis and this reports are probably relevant to you error. According to them you mysql returns some error that triggers a bug in MySQLdb. Unfortunately it's not so easy to discover what this error is.\n"
] |
[
1
] |
[] |
[] |
[
"mysql",
"python"
] |
stackoverflow_0001772001_mysql_python.txt
|
Q:
How to click a link in win32com.client IE?
I'm using win32com.client to control an IE instance in Python. How can I click a link on a certain page (e.g. using navigate to link href isn't acceptable since it won't trigger referrer sending)?
Here is the base:
import random
import time
from win32com.client import Dispatch
ie = Dispatch("InternetExplorer.Application")
ie.visible = 1
ie.navigate('http://digg.com')
while (ie.ReadyState != 4):
time.sleep(0.05)
hrefs = ie.document.getElementsByTagName("A")
href = hrefs[random.randrange(hrefs.length)]
#How to click this one?
A:
Turns out it has .click() method.
http://msdn.microsoft.com/en-us/library/ms535173(VS.85).aspx
A:
Have you tried using the Headers parameter of the navigate method to manually set the Referrer header like:
Referrer: http://example.com
|
How to click a link in win32com.client IE?
|
I'm using win32com.client to control an IE instance in Python. How can I click a link on a certain page (e.g. using navigate to link href isn't acceptable since it won't trigger referrer sending)?
Here is the base:
import random
import time
from win32com.client import Dispatch
ie = Dispatch("InternetExplorer.Application")
ie.visible = 1
ie.navigate('http://digg.com')
while (ie.ReadyState != 4):
time.sleep(0.05)
hrefs = ie.document.getElementsByTagName("A")
href = hrefs[random.randrange(hrefs.length)]
#How to click this one?
|
[
"Turns out it has .click() method.\nhttp://msdn.microsoft.com/en-us/library/ms535173(VS.85).aspx\n",
"Have you tried using the Headers parameter of the navigate method to manually set the Referrer header like:\n\nReferrer: http://example.com\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"internet_explorer",
"python"
] |
stackoverflow_0001661107_internet_explorer_python.txt
|
Q:
Using Jython From Eclipse Plugin
I am having a tough time getting jython to work properly when run from an Eclipse plugin. I have a simple object factory that loads a python module conforming to a Java Interface. All of this works fine in standalone mode. However, when I package this as an eclipse plugin, I get a different error based on a few variables:
Given that my java package is com.foo.
1) If I run without modifying any paths, I get: "No module named foo"
2) If I then add my java jars to the sys.path using:
PythonInterpreter interp = new PythonInterpreter(null, new PySystemState());
PySystemState sys = Py.getSystemState();
sys.path.append(new PyString("myjar..."));
I get:
a) My python module's constructor gets called (print in the constr shows up)
b) I get a PySingleton returned from the call to tojava. The name field is "Error".
3) At this point, I try to make the classpath exactly the same in Eclipse as Standalone, so I add my jars to the classpath at runtime just before the python interpreter is called.
I get my favorite error message: SystemError: Automatic proxy initialization should only occur on proxy classes
This one is driving me crazy. I was impressed with how fast I got this going in standalone mode. Should running under Eclipse be that much different? I believe it should only be a matter of the classpath, but so far, that doesn't seem to be it.
A:
Finally figure this one out. Here is what I had to do:
1) I used the JSR223 ScriptEngine instead of PythonInterpreter:
engine.get(module_name); //gets the class object of the module
getConstructors[0].newInstance(null) on the class to get an object
//cast it to your interface!
2) Make sure your Eclipse plugin isn't packaged as a jar (in 3.5 set Eclipse-BundleShape: dir)
3) Add jython.jar and any paths where you want to locate modules to your Runtime Classpath in the Manifest.
Hope this helps someone.
|
Using Jython From Eclipse Plugin
|
I am having a tough time getting jython to work properly when run from an Eclipse plugin. I have a simple object factory that loads a python module conforming to a Java Interface. All of this works fine in standalone mode. However, when I package this as an eclipse plugin, I get a different error based on a few variables:
Given that my java package is com.foo.
1) If I run without modifying any paths, I get: "No module named foo"
2) If I then add my java jars to the sys.path using:
PythonInterpreter interp = new PythonInterpreter(null, new PySystemState());
PySystemState sys = Py.getSystemState();
sys.path.append(new PyString("myjar..."));
I get:
a) My python module's constructor gets called (print in the constr shows up)
b) I get a PySingleton returned from the call to tojava. The name field is "Error".
3) At this point, I try to make the classpath exactly the same in Eclipse as Standalone, so I add my jars to the classpath at runtime just before the python interpreter is called.
I get my favorite error message: SystemError: Automatic proxy initialization should only occur on proxy classes
This one is driving me crazy. I was impressed with how fast I got this going in standalone mode. Should running under Eclipse be that much different? I believe it should only be a matter of the classpath, but so far, that doesn't seem to be it.
|
[
"Finally figure this one out. Here is what I had to do:\n1) I used the JSR223 ScriptEngine instead of PythonInterpreter:\nengine.get(module_name); //gets the class object of the module\ngetConstructors[0].newInstance(null) on the class to get an object\n//cast it to your interface!\n2) Make sure your Eclipse plugin isn't packaged as a jar (in 3.5 set Eclipse-BundleShape: dir)\n3) Add jython.jar and any paths where you want to locate modules to your Runtime Classpath in the Manifest.\nHope this helps someone.\n"
] |
[
5
] |
[] |
[] |
[
"java",
"jython",
"python"
] |
stackoverflow_0001765802_java_jython_python.txt
|
Q:
Find following tag with pyparsing
I'm using pyparsing to parse HTML. I'm grabbing all embed tags, but in some cases there's an a tag directly following that I also want to grab if it's available.
example:
import pyparsing
target = pyparsing.makeHTMLTags("embed")[0]
target.setParseAction(pyparsing.withAttribute(src=pyparsing.withAttribute.ANY_VALUE))
target.ignore(pyparsing.htmlComment)
result = target.searchString(""".....
<object....><embed>.....</embed></object><br /><a href="blah">blah</a>
""")
I haven't been able to find any character offset in the result objects, otherwise I could just grab a slice of the original input string and work from there.
EDIT:
Someone asked why I don't use BeautifulSoup. That's a good question, let me show you why I chose not to use it with a code sample:
import BeautifulSoup
import urllib
import re
import socket
socket.setdefaulttimeout(3)
# get some random blogs
xml = urllib.urlopen('http://rpc.weblogs.com/shortChanges.xml').read()
success, failure = 0.0, 0.0
for url in re.compile(r'\burl="([^"]+)"').findall(xml)[:30]:
print url
try:
BeautifulSoup.BeautifulSoup(urllib.urlopen(url).read())
except IOError:
pass
except Exception, e:
print e
failure += 1
else:
success += 1
print failure / (failure + success)
When I try this, BeautifulSoup fails with parse errors 20-30% of the time. These aren't rare edge cases. pyparsing is slow and cumbersome but it hasn't blown up no matter what I throw at it. If I can be enlightened as to a better way to use BeautifulSoup then I would be really interested in knowing that.
A:
If there is an optional <a> tag that would be interesting if it follows an <embed> tag, then add it to your search pattern:
embedTag = pyparsing.makeHTMLTags("embed")[0]
aTag = pyparsing.makeHTMLTags("a")[0]
target = embedTag + pyparsing.Optional(aTag)
result = target.searchString(""".....
<object....><embed>.....</embed></object><br /><a href="blah">blah</a>
""")
print result.dump()
If you want to capture the character location of an expression within your parser, insert one of these, with a results name:
loc = pyparsing.Empty().setParseAction(lambda s,locn,toks: locn)
target = loc("beforeEmbed") + embedTag + loc("afterEmbed") +
pyparsing.Optional(aTag)
A:
Why would you write your own HTML parser? The standard library includes HTMLParser, and BeautifulSoup can handle any job HTMLParser can't.
A:
you don't prefer using normal regex? or because its bad habit to parse html? :D
re.findall("<object.*?</object>(?:<br /><a.*?</a>)?",a)
A:
I was able to run your BeautifulSoup code and received no errors. I'm running BeautifulSoup 3.0.7a
Please use BeautifulSoup 3.0.7a; 3.1.0.1 has bugs that prevent it from working at all in some cases (such as yours).
|
Find following tag with pyparsing
|
I'm using pyparsing to parse HTML. I'm grabbing all embed tags, but in some cases there's an a tag directly following that I also want to grab if it's available.
example:
import pyparsing
target = pyparsing.makeHTMLTags("embed")[0]
target.setParseAction(pyparsing.withAttribute(src=pyparsing.withAttribute.ANY_VALUE))
target.ignore(pyparsing.htmlComment)
result = target.searchString(""".....
<object....><embed>.....</embed></object><br /><a href="blah">blah</a>
""")
I haven't been able to find any character offset in the result objects, otherwise I could just grab a slice of the original input string and work from there.
EDIT:
Someone asked why I don't use BeautifulSoup. That's a good question, let me show you why I chose not to use it with a code sample:
import BeautifulSoup
import urllib
import re
import socket
socket.setdefaulttimeout(3)
# get some random blogs
xml = urllib.urlopen('http://rpc.weblogs.com/shortChanges.xml').read()
success, failure = 0.0, 0.0
for url in re.compile(r'\burl="([^"]+)"').findall(xml)[:30]:
print url
try:
BeautifulSoup.BeautifulSoup(urllib.urlopen(url).read())
except IOError:
pass
except Exception, e:
print e
failure += 1
else:
success += 1
print failure / (failure + success)
When I try this, BeautifulSoup fails with parse errors 20-30% of the time. These aren't rare edge cases. pyparsing is slow and cumbersome but it hasn't blown up no matter what I throw at it. If I can be enlightened as to a better way to use BeautifulSoup then I would be really interested in knowing that.
|
[
"If there is an optional <a> tag that would be interesting if it follows an <embed> tag, then add it to your search pattern:\nembedTag = pyparsing.makeHTMLTags(\"embed\")[0]\naTag = pyparsing.makeHTMLTags(\"a\")[0]\ntarget = embedTag + pyparsing.Optional(aTag)\nresult = target.searchString(\"\"\"..... \n <object....><embed>.....</embed></object><br /><a href=\"blah\">blah</a>\n \"\"\")\n\nprint result.dump()\n\nIf you want to capture the character location of an expression within your parser, insert one of these, with a results name:\nloc = pyparsing.Empty().setParseAction(lambda s,locn,toks: locn)\ntarget = loc(\"beforeEmbed\") + embedTag + loc(\"afterEmbed\") + \n pyparsing.Optional(aTag)\n\n",
"Why would you write your own HTML parser? The standard library includes HTMLParser, and BeautifulSoup can handle any job HTMLParser can't.\n",
"you don't prefer using normal regex? or because its bad habit to parse html? :D\nre.findall(\"<object.*?</object>(?:<br /><a.*?</a>)?\",a)\n\n",
"I was able to run your BeautifulSoup code and received no errors. I'm running BeautifulSoup 3.0.7a\nPlease use BeautifulSoup 3.0.7a; 3.1.0.1 has bugs that prevent it from working at all in some cases (such as yours).\n"
] |
[
5,
1,
1,
1
] |
[] |
[] |
[
"html",
"parsing",
"pyparsing",
"python"
] |
stackoverflow_0001767673_html_parsing_pyparsing_python.txt
|
Q:
Are there any examples of a Python PyGTK Pango editor toolbar?
I am looking for an example application written in Python and PyGTK.
There should be an editor out there somewhere that already does this.
Some app with a text editor row of buttons:
- Font
- Bold/italic/underline
- etc
I am hoping to avoid reinventing the wheel on this one!
thanks
A:
I couldn't find any pygtk programs that do what you want, but here is a good tutorial to using pango: http://zetcode.com/tutorials/pygtktutorial/pango/
A:
I found some related examples: KeepNote, which has a custom rich edit, and Rednotebook which implements KeepNote's richedit.
|
Are there any examples of a Python PyGTK Pango editor toolbar?
|
I am looking for an example application written in Python and PyGTK.
There should be an editor out there somewhere that already does this.
Some app with a text editor row of buttons:
- Font
- Bold/italic/underline
- etc
I am hoping to avoid reinventing the wheel on this one!
thanks
|
[
"I couldn't find any pygtk programs that do what you want, but here is a good tutorial to using pango: http://zetcode.com/tutorials/pygtktutorial/pango/\n",
"I found some related examples: KeepNote, which has a custom rich edit, and Rednotebook which implements KeepNote's richedit.\n"
] |
[
2,
2
] |
[] |
[] |
[
"pango",
"pygtk",
"python"
] |
stackoverflow_0001665288_pango_pygtk_python.txt
|
Q:
pysvn with svn+ssh
I'm working with pysvn, and I'm trying to find a decent way to handle repositories that are only accessible via svn+ssh. Obviously SSH keys make this all incredibly easy, but I can't guarantee the end user will be using an SSH key. This also has to be able to run without user interaction, because it's going to be doing some svn log parsing.
The big issue is that, with svn+ssh an interactive prompt is popped up for authentication. Obviously I'd like to be able to have pysvn automatically login with a set of given credentials, but set_default_username and set_default_password aren't doing me any good in that respect. If I can't have that, I'd at least like to able to just fail out, and log a message to tell the user to setup an SSH key. However, set_interactive seems to have no bearing on this either, and I'm still prompted for a password with client.log('svn+ssh://path').
Any thoughts on how to tackle this issue? Is it even really possible to handle this without SSH keys, since it's SSH that's throwing the prompts?
A:
Check out ssh configuration option PasswordAuthentication.
I'm not sure how pysvn interacts with ssh, but if you set this to no in your ~/.ssh/config (or maybe global config?) then it shouldn't prompt for a password.
|
pysvn with svn+ssh
|
I'm working with pysvn, and I'm trying to find a decent way to handle repositories that are only accessible via svn+ssh. Obviously SSH keys make this all incredibly easy, but I can't guarantee the end user will be using an SSH key. This also has to be able to run without user interaction, because it's going to be doing some svn log parsing.
The big issue is that, with svn+ssh an interactive prompt is popped up for authentication. Obviously I'd like to be able to have pysvn automatically login with a set of given credentials, but set_default_username and set_default_password aren't doing me any good in that respect. If I can't have that, I'd at least like to able to just fail out, and log a message to tell the user to setup an SSH key. However, set_interactive seems to have no bearing on this either, and I'm still prompted for a password with client.log('svn+ssh://path').
Any thoughts on how to tackle this issue? Is it even really possible to handle this without SSH keys, since it's SSH that's throwing the prompts?
|
[
"Check out ssh configuration option PasswordAuthentication.\nI'm not sure how pysvn interacts with ssh, but if you set this to no in your ~/.ssh/config (or maybe global config?) then it shouldn't prompt for a password.\n"
] |
[
2
] |
[] |
[] |
[
"pysvn",
"python",
"ssh",
"svn"
] |
stackoverflow_0001772133_pysvn_python_ssh_svn.txt
|
Q:
Linking Tcl/Tk to Python 2.5
I have an existing Python 2.4 and it is working properly with tkinter as I tested it using
python
import _tkinter
import Tkinter
Tkinter._test()
Now, I have installed python 2.5.2 but when I try the same tests (with the newer version), it returns (but the same tests are working for the previous version)
ImportError: No module named _tkinter
I know that tcl8.5 and tk8.5 are installed on my machine as the following commands return there locations
whereis tcl
tcl: /usr/lib/tcl8.4 /usr/local/lib/tcl8.5 /usr/local/lib/tcl8.4 /usr/share/tcl8.4
whereis tk
tk: /usr/lib/tk8.4 /usr/local/lib/tk8.5 /usr/share/tk8.4
Any ideas how do I make my newer python version work with tkinter?
A:
The files you found are for linking directly to tcl/tk. Python depends on another library as well: _tkinter.so. It should be in /usr/lib/python2.5/lib-dynload/_tkinter.so.
How did you install python2.5? If you are using Debian or Ubuntu you need to install the python-tk package to get Tkinter support.
If the _tkinter.so file is there, your environment could be causing problems.
If
python -E -c "import
Tkinter;Tkinter._test()"
suceeds, but
python -c "import
Tkinter;Tkinter._test()"
fails, then the problem is with how your environment is set up. Check the value of PYTHONPATH is set correctly.
|
Linking Tcl/Tk to Python 2.5
|
I have an existing Python 2.4 and it is working properly with tkinter as I tested it using
python
import _tkinter
import Tkinter
Tkinter._test()
Now, I have installed python 2.5.2 but when I try the same tests (with the newer version), it returns (but the same tests are working for the previous version)
ImportError: No module named _tkinter
I know that tcl8.5 and tk8.5 are installed on my machine as the following commands return there locations
whereis tcl
tcl: /usr/lib/tcl8.4 /usr/local/lib/tcl8.5 /usr/local/lib/tcl8.4 /usr/share/tcl8.4
whereis tk
tk: /usr/lib/tk8.4 /usr/local/lib/tk8.5 /usr/share/tk8.4
Any ideas how do I make my newer python version work with tkinter?
|
[
"The files you found are for linking directly to tcl/tk. Python depends on another library as well: _tkinter.so. It should be in /usr/lib/python2.5/lib-dynload/_tkinter.so.\nHow did you install python2.5? If you are using Debian or Ubuntu you need to install the python-tk package to get Tkinter support.\nIf the _tkinter.so file is there, your environment could be causing problems.\nIf \n\npython -E -c \"import\n Tkinter;Tkinter._test()\"\n\nsuceeds, but \n\npython -c \"import\n Tkinter;Tkinter._test()\"\n\nfails, then the problem is with how your environment is set up. Check the value of PYTHONPATH is set correctly.\n"
] |
[
3
] |
[] |
[] |
[
"python",
"tcl",
"tk_toolkit",
"tkinter"
] |
stackoverflow_0001773222_python_tcl_tk_toolkit_tkinter.txt
|
Q:
Importing python classes in the Google App Engine
I am writing a GAE application and have run into an import problem.
My app.yaml has the following lines:
- url: /py/classes/
static_dir: py/classes
- url: /py/lib
static_dir: py/lib
- url: /py/bin/signin
script: py/bin/signin.py
I am keeping a python file, titled employee.py, containing the class employee, in the classes folder, and a signin.py script in the bin folder which tries - at the moment unsuccessfully - to import the employee class. I have tried, amongst others:
import employee
import py.classes.employee
Neither option works. Could you please let me know what I am doing wrong?
Thank you in advance.
A:
The static_dir configuration option can not be used to extend PYTHONPATH. Using it you can serve static files like images, stylesheet, or Javascript files.
If you want to use normal Python modules just put them next to your main Python files.
Edit:
Are your directories Python packages that include the necessary __init__.py files?
A:
Any files specified as static files get uploaded separately from your code - they're not accessible by your Python code, so even with the PYTHONPATH set correctly, you won't be able to import them.
|
Importing python classes in the Google App Engine
|
I am writing a GAE application and have run into an import problem.
My app.yaml has the following lines:
- url: /py/classes/
static_dir: py/classes
- url: /py/lib
static_dir: py/lib
- url: /py/bin/signin
script: py/bin/signin.py
I am keeping a python file, titled employee.py, containing the class employee, in the classes folder, and a signin.py script in the bin folder which tries - at the moment unsuccessfully - to import the employee class. I have tried, amongst others:
import employee
import py.classes.employee
Neither option works. Could you please let me know what I am doing wrong?
Thank you in advance.
|
[
"The static_dir configuration option can not be used to extend PYTHONPATH. Using it you can serve static files like images, stylesheet, or Javascript files.\nIf you want to use normal Python modules just put them next to your main Python files.\nEdit:\nAre your directories Python packages that include the necessary __init__.py files? \n",
"Any files specified as static files get uploaded separately from your code - they're not accessible by your Python code, so even with the PYTHONPATH set correctly, you won't be able to import them.\n"
] |
[
3,
1
] |
[] |
[] |
[
"google_app_engine",
"python"
] |
stackoverflow_0001770037_google_app_engine_python.txt
|
Q:
What is the best browser automation tool for Python?
I want to write a following script: given a text file with the list of actions to be executed on a certain site it would use some browser's (IE probably, because I don't know anything about other drive-able ones) CSS rendering and JS executing capabilities to imitate a user doing those actions on a site.
So I've found this page and the "web testing" section of it and it lists:
PAMIE
PYXPCOM
Windmill
Selenium
The latter two run some sort of a server on the localhost (which doesn't seem to be well suitable decision).
Pamie has some sort of the worst documentation ever and lots of "Under Construction" pages on their site last updated in 2006.
And PyXPCOM seems to be created not specifically for FF. I may be a bad Googler but I still didn't find a decent example of using PyXPCOM for something like using FF.
Which way to guide the browser would you prefer for my purposes and why? TIA
Update:
I need to be able to render the JavaScript on the page. I guess using some server-based library is not a good solution since it is limited to one instance of browser at a time, so I won't be able to, for example, set 2 browser instances to 2 different proxies without having to make 2 servers (is this correct?).
A:
I'd encourage you to look again at Selenium...that's really what you want to do. Do you need to actually render the page in a browser, or just emulate navigation and clicking?
Mechanize gives you stateful programmatic web browsing, and might be what you're looking for.
A:
You should try Win32Com as it gives you the possibility to drive programs using their COM server, and if they don't have one you can make it execute simple actions like emulate the pression of a key or move a window from foreground to background and back.
In the case of IE, since it has a COM server, you can use functions of the IE Python object to make it write things in forms, check boxes, download files and almost everything you could imagine.
A:
I'm not sure if Qt's Webkit through PyQt can solve your issue but I can usually control a simple browser with Python in that way, for instance:
import sys
import time
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
app = QApplication(sys.argv)
web = QWebView()
settings = web.settings()
settings.setAttribute(QWebSettings.PluginsEnabled, True)
settings.setAttribute(QWebSettings.JavaEnabled, True)
settings.setAttribute(QWebSettings.JavascriptCanOpenWindows, True)
settings.setAttribute(QWebSettings.JavascriptCanAccessClipboard, True)
settings.setAttribute(QWebSettings.DeveloperExtrasEnabled, True)
settings.setAttribute(QWebSettings.ZoomTextOnly, True)
settings.setOfflineStoragePath('.')
settings.setIconDatabasePath (".")
url = 'http://stackoverflow.com'
web.load(QUrl(url))
web.show()
sys.exit(app.exec_())
A:
Check out MozMill, it's for Firefox. Uses JavaScript, should be easier than COM.
A:
You can use autoit COM object using pywin32.
Another option is to use selenium 2 (aka webdriver) python bindings.
|
What is the best browser automation tool for Python?
|
I want to write a following script: given a text file with the list of actions to be executed on a certain site it would use some browser's (IE probably, because I don't know anything about other drive-able ones) CSS rendering and JS executing capabilities to imitate a user doing those actions on a site.
So I've found this page and the "web testing" section of it and it lists:
PAMIE
PYXPCOM
Windmill
Selenium
The latter two run some sort of a server on the localhost (which doesn't seem to be well suitable decision).
Pamie has some sort of the worst documentation ever and lots of "Under Construction" pages on their site last updated in 2006.
And PyXPCOM seems to be created not specifically for FF. I may be a bad Googler but I still didn't find a decent example of using PyXPCOM for something like using FF.
Which way to guide the browser would you prefer for my purposes and why? TIA
Update:
I need to be able to render the JavaScript on the page. I guess using some server-based library is not a good solution since it is limited to one instance of browser at a time, so I won't be able to, for example, set 2 browser instances to 2 different proxies without having to make 2 servers (is this correct?).
|
[
"I'd encourage you to look again at Selenium...that's really what you want to do. Do you need to actually render the page in a browser, or just emulate navigation and clicking? \nMechanize gives you stateful programmatic web browsing, and might be what you're looking for.\n",
"You should try Win32Com as it gives you the possibility to drive programs using their COM server, and if they don't have one you can make it execute simple actions like emulate the pression of a key or move a window from foreground to background and back. \nIn the case of IE, since it has a COM server, you can use functions of the IE Python object to make it write things in forms, check boxes, download files and almost everything you could imagine.\n",
"I'm not sure if Qt's Webkit through PyQt can solve your issue but I can usually control a simple browser with Python in that way, for instance:\nimport sys\nimport time\n\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtWebKit import *\n\napp = QApplication(sys.argv)\n\nweb = QWebView()\n\nsettings = web.settings()\nsettings.setAttribute(QWebSettings.PluginsEnabled, True)\nsettings.setAttribute(QWebSettings.JavaEnabled, True)\nsettings.setAttribute(QWebSettings.JavascriptCanOpenWindows, True)\nsettings.setAttribute(QWebSettings.JavascriptCanAccessClipboard, True)\nsettings.setAttribute(QWebSettings.DeveloperExtrasEnabled, True)\nsettings.setAttribute(QWebSettings.ZoomTextOnly, True)\n\n\nsettings.setOfflineStoragePath('.')\nsettings.setIconDatabasePath (\".\")\n\nurl = 'http://stackoverflow.com'\n\nweb.load(QUrl(url))\nweb.show()\n\nsys.exit(app.exec_())\n\n",
"Check out MozMill, it's for Firefox. Uses JavaScript, should be easier than COM.\n",
"You can use autoit COM object using pywin32.\nAnother option is to use selenium 2 (aka webdriver) python bindings.\n"
] |
[
3,
2,
2,
1,
1
] |
[] |
[] |
[
"browser_automation",
"python"
] |
stackoverflow_0001771898_browser_automation_python.txt
|
Q:
Are there any libraries for Python to simulate keyboard action?
The problem I have is that I have this Python script to launch a application. After the application is launched (the GUI is shown on screen), I want to make it de-activated. It can be done manually by activating another window, or minimizing this app, or pressing the Show Desktop key for WindowsXP.
So is there any way that I can do this by Python? Core or 3rd party library would be all ok.
Thanks!
A:
Take a look at SendKeys. It is in the pypi, so you can install it via easy_install.
A:
You can use pywin32 to send a minimize event.
A:
I've used AutoIt (via it's COM interface) a lot of times
|
Are there any libraries for Python to simulate keyboard action?
|
The problem I have is that I have this Python script to launch a application. After the application is launched (the GUI is shown on screen), I want to make it de-activated. It can be done manually by activating another window, or minimizing this app, or pressing the Show Desktop key for WindowsXP.
So is there any way that I can do this by Python? Core or 3rd party library would be all ok.
Thanks!
|
[
"Take a look at SendKeys. It is in the pypi, so you can install it via easy_install.\n",
"You can use pywin32 to send a minimize event.\n",
"I've used AutoIt (via it's COM interface) a lot of times\n"
] |
[
4,
0,
0
] |
[] |
[] |
[
"keyboard",
"python",
"windows"
] |
stackoverflow_0001767575_keyboard_python_windows.txt
|
Q:
Class attribute evaluation and generators
How exactly does Python evaluate class attributes? I've stumbled across an interesting quirk (in Python 2.5.2) that I'd like explained.
I have a class with some attributes that are defined in terms of other, previously defined attributes. When I try using a generator object, Python throws an error, but if I use a plain ordinary list comprehension, there's no problem.
Here's the pared-down example. Note that the only difference is that Brie uses a generator expression, while Cheddar uses a list comprehension.
# Using a generator expression as the argument to list() fails
>>> class Brie :
... base = 2
... powers = list(base**i for i in xrange(5))
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in Brie
File "<stdin>", line 3, in <genexpr>
NameError: global name 'base' is not defined
# Using a list comprehension works
>>> class Cheddar :
... base = 2
... powers = [base**i for i in xrange(5)]
...
>>> Cheddar.powers
[1, 2, 4, 8, 16]
# Using a list comprehension as the argument to list() works
>>> class Edam :
... base = 2
... powers = list([base**i for i in xrange(5)])
...
>>> Edam.powers
[1, 2, 4, 8, 16]
(My actual case was more complicated, and I was creating a dict, but this is the minimum example I could find.)
My only guess is that the list comprehensions are computed at that line, but the generator expressions are computed after the end of the class, at which point the scope has changed. But I'm not sure why the generator expression doesn't act as a closure and store the reference to base in the scope at the line.
Is there a reason for this, and if so, how should I be thinking of the evaluation mechanics of class attributes?
A:
Yeah, it's a bit dodgy, this. A class doesn't really introduce a new scope, it just sort of looks a little bit like it does; constructs like this expose the difference.
The idea is that when you're using a generator expression it's equivalent to doing it with a lambda:
class Brie(object):
base= 2
powers= map(lambda i: base**i, xrange(5))
or explicitly as a function statement:
class Brie(object):
base= 2
def __generatePowers():
for i in xrange(5):
yield base**i
powers= list(__generatePowers())
In this case it's clear that base isn't in scope for __generatePowers; an exception results for both (unless you were unlucky enough to also have a base global, in which case you get a wrongness).
This doesn't happen for list comprehensions due to some internal details on how they're evaluated, however that behaviour goes away in Python 3 which will fail equally for both cases. Some discussion here.
A workaround can be had using a lambda with the same technique we relied on back in the bad old days before nested_scopes:
class Brie(object):
base= 2
powers= map(lambda i, base= base: base**i, xrange(5))
A:
From PEP 289:
After exploring many possibilities, a
consensus emerged that binding issues
were hard to understand and that users
should be strongly encouraged to use
generator expressions inside functions
that consume their arguments
immediately. For more complex
applications, full generator
definitions are always superior in
terms of being obvious about scope,
lifetime, and binding [6].
[6] (1, 2) Patch discussion and alternative patches on Source Forge http://www.python.org/sf/872326
It's how generator expressions are scoped as far as I can make out.
|
Class attribute evaluation and generators
|
How exactly does Python evaluate class attributes? I've stumbled across an interesting quirk (in Python 2.5.2) that I'd like explained.
I have a class with some attributes that are defined in terms of other, previously defined attributes. When I try using a generator object, Python throws an error, but if I use a plain ordinary list comprehension, there's no problem.
Here's the pared-down example. Note that the only difference is that Brie uses a generator expression, while Cheddar uses a list comprehension.
# Using a generator expression as the argument to list() fails
>>> class Brie :
... base = 2
... powers = list(base**i for i in xrange(5))
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in Brie
File "<stdin>", line 3, in <genexpr>
NameError: global name 'base' is not defined
# Using a list comprehension works
>>> class Cheddar :
... base = 2
... powers = [base**i for i in xrange(5)]
...
>>> Cheddar.powers
[1, 2, 4, 8, 16]
# Using a list comprehension as the argument to list() works
>>> class Edam :
... base = 2
... powers = list([base**i for i in xrange(5)])
...
>>> Edam.powers
[1, 2, 4, 8, 16]
(My actual case was more complicated, and I was creating a dict, but this is the minimum example I could find.)
My only guess is that the list comprehensions are computed at that line, but the generator expressions are computed after the end of the class, at which point the scope has changed. But I'm not sure why the generator expression doesn't act as a closure and store the reference to base in the scope at the line.
Is there a reason for this, and if so, how should I be thinking of the evaluation mechanics of class attributes?
|
[
"Yeah, it's a bit dodgy, this. A class doesn't really introduce a new scope, it just sort of looks a little bit like it does; constructs like this expose the difference.\nThe idea is that when you're using a generator expression it's equivalent to doing it with a lambda:\nclass Brie(object):\n base= 2\n powers= map(lambda i: base**i, xrange(5))\n\nor explicitly as a function statement:\nclass Brie(object):\n base= 2\n\n def __generatePowers():\n for i in xrange(5):\n yield base**i\n\n powers= list(__generatePowers())\n\nIn this case it's clear that base isn't in scope for __generatePowers; an exception results for both (unless you were unlucky enough to also have a base global, in which case you get a wrongness).\nThis doesn't happen for list comprehensions due to some internal details on how they're evaluated, however that behaviour goes away in Python 3 which will fail equally for both cases. Some discussion here.\nA workaround can be had using a lambda with the same technique we relied on back in the bad old days before nested_scopes:\nclass Brie(object):\n base= 2\n powers= map(lambda i, base= base: base**i, xrange(5))\n\n",
"From PEP 289:\n\nAfter exploring many possibilities, a\n consensus emerged that binding issues\n were hard to understand and that users\n should be strongly encouraged to use\n generator expressions inside functions\n that consume their arguments\n immediately. For more complex\n applications, full generator\n definitions are always superior in\n terms of being obvious about scope,\n lifetime, and binding [6].\n[6] (1, 2) Patch discussion and alternative patches on Source Forge http://www.python.org/sf/872326\n\nIt's how generator expressions are scoped as far as I can make out.\n"
] |
[
15,
1
] |
[] |
[] |
[
"attributes",
"class",
"class_attributes",
"python"
] |
stackoverflow_0001773636_attributes_class_class_attributes_python.txt
|
Q:
My python program executes faster than my java version of the same program. What gives?
Update: 2009-05-29
Thanks for all the suggestions and advice. I used your suggestions to make my production code execute 2.5 times faster on average than my best result a couple of days ago. In the end I was able to make the java code the fastest.
Lessons:
My example code below shows the insertion of primitive ints but the production code is actually storing strings (my bad). When I corrected that the python execution time went from 2.8 seconds to 9.6. So right off the bat, the java was actually faster when storing objects.
But it doesn't stop there. I had been executing the java program as follows:
java -Xmx1024m SpeedTest
But if you set the initial heap size as follows you get a huge improvement:
java -Xms1024m -Xmx1024m SpeedTest
This simple change reduced the execution time by more than 50%. So the final result for my SpeedTest is python 9.6 seconds. Java 6.5 seconds.
Original Question:
I had the following python code:
import time
import sys
def main(args):
iterations = 10000000
counts = set()
startTime = time.time();
for i in range(0, iterations):
counts.add(i)
totalTime = time.time() - startTime
print 'total time =',totalTime
print len(counts)
if __name__ == "__main__":
main(sys.argv)
And it executed in about 3.3 seconds on my machine but I wanted to make it faster so I decided to program it in java. I assumed that because java is compiled and is generally considered to be faster than python I would see some big paybacks.
Here is the java code:
import java.util.*;
class SpeedTest
{
public static void main(String[] args)
{
long startTime;
long totalTime;
int iterations = 10000000;
HashSet counts = new HashSet((2*iterations), 0.75f);
startTime = System.currentTimeMillis();
for(int i=0; i<iterations; i++)
{
counts.add(i);
}
totalTime = System.currentTimeMillis() - startTime;
System.out.println("TOTAL TIME = "+( totalTime/1000f) );
System.out.println(counts.size());
}
}
So this java code does basically the same thing as the python code. But it executed in 8.3 seconds instead of 3.3.
I have extracted this simple example from a real-world example to simplify things. The critical element is that I have (set or hashSet) that ends up with a lot of members much like the example.
Here are my questions:
How come my python implementation is faster than my java implementation?
Is there a better data structure to use than the hashSet (java) to hold a unique collection?
What would make the python implementation faster?
What would make the java implementation faster?
UPDATE:
Thanks to all who have contributed so far. Please allow me to add some details.
I have not included my production code because it is quite complex. And would generate a lot of distraction. The case I present above is the most simplified possible. By that I mean that the java put call seems to be much slower than the python set`s add().
The java implementation of the production code is also about 2.5 - 3 times slower than the python version -- just like the above.
I am not concerned about vm warmup or startup overhead. I just want to compare the code from my startTime to my totalTime. Please do not concern yourselves with other matters.
I initialized the hashset with more than enough buckets so that it should never have to rehash. (I will always know ahead of time how many elements the collection will ultimately contain.) I suppose one could argue that I should have initialized it to iterations/0.75. But if you try it you will see that execution time is not significantly impacted.
I set Xmx1024m for those that were curious (my machine has 4GB of ram).
I am using java version: Java(TM) SE Runtime Environment (build 1.6.0_13-b03).
In the production version of I am storing a string (2-15 chars) in the hashSet so I cannot use primitives, although that is an interesting case.
I have run the code many, many times. I have very high confidence that the python code is between 2.5 and 3 times faster than the java code.
A:
You're not really testing Java vs. Python, you're testing java.util.HashSet using autoboxed Integers vs. Python's native set and integer handling.
Apparently, the Python side in this particular microbenchmark is indeed faster.
I tried replacing HashSet with TIntHashSet from GNU trove and achieved a speedup factor between 3 and 4, bringing Java slightly ahead of Python.
The real question is whether your example code is really as representative of your application code as you think. Have you run a profiler and determined that most of the CPU time is spent in putting a huge number of ints into a HashSet? If not, the example is irrelevant. Even if the only difference is that your production code stores other objects than ints, their creation and the computation of their hashcode could easily dominate the set insertion (and totally destroy Python's advantage in handling ints specially), making this whole question pointless.
A:
I suspect that is that Python uses the integer value itself as its hash and the hashtable based implementation of set uses that value directly. From the comments in the source:
This isn't necessarily bad! To the contrary, in a table of size 2**i, taking
the low-order i bits as the initial table index is extremely fast, and there
are no collisions at all for dicts indexed by a contiguous range of ints.
The same is approximately true when keys are "consecutive" strings. So this
gives better-than-random behavior in common cases, and that's very desirable.
This microbenchmark is somewhat of a best case for Python because it results in exactly zero hash collisions. Whereas, if Javas HashSet is rehashing the keys it has to perform the additional work and also gets much worse behavior with collisions.
If you store the range(iterations) in a temporary variable and do a random.shuffle on it before the loop the runtime is more than 2x slower even if the shuffle and list creation is done outside the loop.
A:
It has generally been my experience that python programs run faster than java programs, despite the fact that java is a bit "lower level" language. Incidently, both languages are compiled into byte code (that's what those .pyc file are -- you can think of them as kind of like .class files). Both languages are byte-code interpreted on a virtual stack machine.
You would expect python to be slower at things like, for example, a.b. In java, that a.b will resolve into a dereference. Python, on the other hand, has to do one or more hash table lookups: check the local scope, check the module scope, check global scope, check builtins.
On the other hand, java is notoriously bad at certain operations such as object creation (which is probably the culprit in your example) and serialization.
In summary, there's no simple answer. I wouldn't expect either language to be faster for all code examples.
Correction: several people have pointed out that java isn't so bad at object creation any more. So, in your example, it's something else. Perhaps it's autoboxing that's expensive, perhaps python's default hashing algorithm is better in this case. In my practical experience, when I rewrite java code to python, I always see a performance increase, but that could be as much due to the language as it is due to rewritng in general leads to performance improvements.
A:
Another possible explanation is that sets in Python are implemented natively in C code, while HashSet's in Java are implemented in Java itself. So, sets in Python should be inherently much faster.
A:
I'd like to dispel a couple myths I saw in the answers:
Java is compiled, yes, to bytecode but ultimately to native code in most runtime environments. People who say C is inherently faster aren't telling the entire story, I could make a case that byte compiled languages are inherently faster because the JIT compiler can make machine-specific optimizations that are unavailable to way-ahead-of-time compilers.
A number of things that could make the differences are:
Python's hash tables and sets are the most heavily optimized objects in Python, and Python's hash function is designed to return similar results for similar inputs: hashing an integer just returns the integer, guaranteeing that you will NEVER see a collision in a hash table of consecutive integers in Python.
A secondary effect of the above is that the Python code will have high locality of reference as you'll be accessing the hash table in sequence.
Java does some fancy boxing and unboxing of integers when you add them to collections. On the bonus side, this makes arithmetic way faster in Java than Python (as long as you stay away from bignums) but on the downside it means more allocations than you're used to.
A:
Edit: A TreeSet might be faster for the real use case, depending on allocation patterns. My comments below deals only with this simplified scenario. However, I do not believe that it would make a very significant difference. The real issue lays elsewhere.
Several people here has recommended replacing the HashSet with a TreeSet. This sounds like a very strange advice to me, since there's no way that a data structure with O(log n) insertion time is faster then a O(1) structure that preallocates enough buckets to store all the elements.
Here's some code to benchmark this:
import java.util.*;
class SpeedTest
{
public static void main(String[] args)
{
long startTime;
long totalTime;
int iterations = 10000000;
Set counts;
System.out.println("HashSet:");
counts = new HashSet((2*iterations), 0.75f);
startTime = System.currentTimeMillis();
for(int i=0; i<iterations; i++) {
counts.add(i);
}
totalTime = System.currentTimeMillis() - startTime;
System.out.println("TOTAL TIME = "+( totalTime/1000f) );
System.out.println(counts.size());
counts.clear();
System.out.println("TreeSet:");
counts = new TreeSet();
startTime = System.currentTimeMillis();
for(int i=0; i<iterations; i++) {
counts.add(i);
}
totalTime = System.currentTimeMillis() - startTime;
System.out.println("TOTAL TIME = "+( totalTime/1000f) );
System.out.println(counts.size());
}
}
And here's the result on my machine:
$ java -Xmx1024M SpeedTest
HashSet:
TOTAL TIME = 4.436
10000000
TreeSet:
TOTAL TIME = 8.163
10000000
Several people also argued that boxing isn't a performance issue and that object creation is inexpensive. While it's true that object creation is fast, it's definitely not as fast as primitives:
import java.util.*;
class SpeedTest2
{
public static void main(String[] args)
{
long startTime;
long totalTime;
int iterations = 10000000;
System.out.println("primitives:");
startTime = System.currentTimeMillis();
int[] primitive = new int[iterations];
for (int i = 0; i < iterations; i++) {
primitive[i] = i;
}
totalTime = System.currentTimeMillis() - startTime;
System.out.println("TOTAL TIME = "+( totalTime/1000f) );
System.out.println("primitives:");
startTime = System.currentTimeMillis();
Integer[] boxed = new Integer[iterations];
for (int i = 0; i < iterations; i++) {
boxed[i] = i;
}
totalTime = System.currentTimeMillis() - startTime;
System.out.println("TOTAL TIME = "+( totalTime/1000f) );
}
}
Result:
$ java -Xmx1024M SpeedTest2
primitives:
TOTAL TIME = 0.058
primitives:
TOTAL TIME = 1.402
Moreover, creating a lot of objects results in additional overhead from the garbage collector. This becomes significant when you start keeping tens of millions of live objects in memory.
A:
I find benchmarks like this to be meaningless. I don't solve problems that look like the test case. It's not terribly interesting.
I'd much rather see a solution for a meaningful linear algebra solution using NumPy and JAMA. Maybe I'll try it and report back with results.
A:
I'm not too familiar with python, but I do know HashSet can't contain primitives, so when you say counts.add(i) the i there is getting autoboxed into a new Integer(i) call. That's probably your problem.
If for some reason you really needed a 'set' of integers between 0 and some large n, its probably best declared as an 'boolean[] set = new boolean[n]'. Then you could go through the array and mark items that are in the set as 'true' without incurring the overhead of creating n Integer wrapper objects. If you wanted to go further than that you could use a byte[] of size n/8 and use the individual bits directly. Or perhaps BigInteger.
EDIT
Stop voting my answer up. Its wrong.
EDIT
No really, its wrong. I get comparable performance if I do what the question suggest, populate the set with N Integers. if I replace the contents of the for loop with this:
Integer[] ints = new Integer[N];
for (int i = 0; i < N; ++i) {
ints[i] = i;
}
Then it only takes 2 seconds. If you don't store the Integer at all then it takes less than 200 millis. Forcing the allocation of 10000000 Integer objects does take some time, but it looks like most of the time is spent inside the HashSet put operation.
A:
There's a number of issues here which I'd like to bring together.
First if it's a program that you are only going to run once, does it matter it takes an extra few seconds?
Secondly, this is just one microbenchmarks. Microbenchmarks are pointless for comparing performance.
Startup has a number of issues.
The Java runtime is much bigger than Python so takes longer to load from disk and takes up more memory which may be important if you are swapping.
If you haven't set -Xms you may be running the GC only to resize the heap. Might as well have the heap properly sized at the start.
It is true that Java starts off interpreting and then compiles. Around 1,500 iterations for Sun client [C1] Hotspot and 10,000 for server [C2]. Server Hotspot will give you better performance eventually, but take more memory. We may see client Hotspot use server for very frequently executed code for best of both worlds. However, this should not usually be a question of seconds.
Most importantly you may be creating two objects per iteration. For most code, you wouldn't be creating these tiny objects for such a proportion of the execution. TreeSet may be better on number of objects score, with 6u14 and Harmony getting even better.
Python may possibly be winning by storing small integer objects in references instead of actually have an object. That is undoubtably a good optimisation.
A problem with a lot of benchmarks is you are mixing a lot of different code up in one method. You wouldn't write code you cared about like that, would you? So why are you attempting to performance test which is unlike code you would actually like to run fast?
Better data structure: Something like BitSet would seem to make sense (although that has ynchronisation on it, which may or may not impact performance).
A:
You need to run it multiple times to get a real idea of "how fast" each runs. The JVM startup time [for one] is adding to the single running time of the Java version.
You're also creating a HashSet with a large initial capacity, which means the backing HashMap will be created with that many available slots, unlike the Python where you create a basic Set. Hard to tell if that would hinder though, as when your HashSet grows it will have to reallocate the stored objects.
A:
Are you using the -server flag with the jvm? You can't test for performance without it. (You also have to warm up the jvm before doing the test.)
Also, you probably want to use TreeSet<Integer>. HashSet will be slower in the long run.
And which jvm are you using? The newest I hope.
EDIT
When I say use TreeSet, I mean in general, not for this benchmark. TreeSet handles the real world issue of non even hashing of objects. If you get too many objects in the same bin in a HashSet, you will perform about O(n).
A:
If you really want to store primitive types in a set, and do heavy work on it, roll your own set in Java. The generic classes are not fast enough for scientific computing.
As Ants Aasma mentions, Python bypasses hashing and uses the integer directly. Java creates an Integer object (autoboxing), and then casts it to an Object (in your implementation). This object must be hashed, as well, for use in a hash set.
For a fun comparision, try this:
Java
import java.util.HashSet;
class SpeedTest
{
public static class Element {
private int m_i;
public Element(int i) {
m_i = i;
}
}
public static void main(String[] args)
{
long startTime;
long totalTime;
int iterations = 1000000;
HashSet<Element> counts = new HashSet<Element>((int)(2*iterations), 0.75f);
startTime = System.currentTimeMillis();
for(int i=0; i<iterations; ++i)
{
counts.add(new Element(i));
}
totalTime = System.currentTimeMillis() - startTime;
System.out.println("TOTAL TIME = "+( totalTime/1000f) );
System.out.println(counts.size());
}
}
Results:
$java SpeedTest
TOTAL TIME = 3.028
1000000
$java -Xmx1G -Xms1G SpeedTest
TOTAL TIME = 0.578
1000000
Python
#!/usr/bin/python
import time
import sys
class Element(object):
def __init__(self, i):
self.num = i
def main(args):
iterations = 1000000
counts = set()
startTime = time.time();
for i in range(0, iterations):
counts.add(Element(i))
totalTime = time.time() - startTime
print 'total time =',totalTime
print len(counts)
if __name__ == "__main__":
main(sys.argv)
Results:
$./speedtest.py
total time = 20.6943161488
1000000
How's that for 'python is faster than java'?
A:
How much memory did you start the JVM with? It depends? When I run the JVM with your program with 1 Gig of RAM:
$ java -Xmx1024M -Xms1024M -classpath . SpeedTest
TOTAL TIME = 5.682
10000000
$ python speedtest.py
total time = 4.48310899734
10000000
If I run the JVM with less memory, it takes longer ... considerably longer:
$ java -Xmx768M -Xms768M -classpath . SpeedTest
TOTAL TIME = 6.706
10000000
$ java -Xmx600M -Xms600M -classpath . SpeedTest
TOTAL TIME = 14.086
10000000
I think the HashSet is the performance bottleneck in this particular instance. If I replace the HashSet with a LinkedList, the program gets substantially faster.
Finally -- note that Java programs are initially interpreted and only those methods that are called many times are compiled. Thus, you're probably comparing Python to Java's interpreter, not the compiler.
A:
Just a stab in the dark here, but some optimizations that Python is making that Java probably isn't:
The range() call in Python is creating all 10000000 integer objects at once, in optimized C code. Java must create an Integer object each iteration, which may be slower.
In Python, ints are immutable, so you can just store a reference to a global "42", for example, rather than allocating a slot for the object. I'm not sure how Java boxed Integer objects compare.
Many of the built-in Python algorithms and data structures are rather heavily optimized for special cases. For instance, the hash function for integers is, simply the identity function. If Java is using a more "clever" hash function, this could slow things down quite a bit. If most of your time is spent in data structure code, I wouldn't be surprised at all to see Python beat Java given the amount of effort that has been spent over the years hand-tuning the Python C implementation.
A:
A few changes for faster Python.
#!/usr/bin/python
import time
import sys
import psyco #<<<<
psyco.full()
class Element(object):
__slots__=["num"] #<<<<
def __init__(self, i):
self.num = i
def main(args):
iterations = 1000000
counts = set()
startTime = time.time();
for i in xrange(0, iterations):
counts.add(Element(i))
totalTime = time.time() - startTime
print 'total time =',totalTime
print len(counts)
if __name__ == "__main__":
main(sys.argv)
Before
(env)~$ python speedTest.py
total time = 8.82906794548
1000000
After
(env)~$ python speedTest.py
total time = 2.44039201736
1000000
Now some good old cheating and ...
#!/usr/bin/python
import time
import sys
import psyco
psyco.full()
class Element(object):
__slots__=["num"]
def __init__(self, i):
self.num = i
def main(args):
iterations = 1000000
counts = set()
elements = [Element(i) for i in range(0, iterations)]
startTime = time.time();
for e in elements:
counts.add(e)
totalTime = time.time() - startTime
print 'total time =',totalTime
print len(counts)
if __name__ == "__main__":
main(sys.argv)
(env)~$ python speedTest.py
total time = 0.526521921158
1000000
A:
Well, if you're going to tune the Java program, you might as well tune the Python program too.
>>> import timeit
>>> timeit.Timer('x = set()\nfor i in range(10000000):\n x.add(i)').repeat(3, 1)
[2.1174559593200684, 2.0019571781158447, 1.9973630905151367]
>>> timeit.Timer('x = set()\nfor i in xrange(10000000):\n x.add(i)').repeat(3, 1)
[1.8742368221282959, 1.8714439868927002, 1.869229793548584]
>>> timeit.Timer('x = set(xrange(10000000))').repeat(3, 1)
[0.74582195281982422, 0.73061800003051758, 0.73396801948547363]
Just using xrange makes it about 8% faster on my machine. And the expression set(xrange(10000000)) builds exactly the same set, but 2.5x faster (from 1.87 seconds to 0.74).
I like how tuning a Python program makes it shorter. :) But Java can do the same trick. As everyone knows, if you want a dense set of smallish integers in Java, you don't use a hash table. You use a java.util.BitSet!
BitSet bits = new BitSet(iterations);
startTime = System.currentTimeMillis();
bits.set(0, iterations, true);
totalTime = System.currentTimeMillis() - startTime;
System.out.println("TOTAL TIME = "+( totalTime/1000f) );
System.out.println(bits.cardinality());
That should be fairly quick. Unfortunately I don't have the time to test it right now.
A:
I agree with Gandalf about the startup time. Also, you are allocating a huge HashSet which is not at all similar to your python code. I imaging if you put this under a profiler, a good chunk of time would be spent there. Also, inserting new elements is really going to be slow with this size. I would look into TreeSet as suggested.
A:
The biggest issue is probably that what the given code measures is wall time -- what your watch measures -- but what should be measured to compare code runtime is process time -- the amount of time the cpu spend executing that particular code and not other tasks.
A:
You can make the Java microbenchamrk much faster, by adding just a simple little extra.
HashSet counts = new HashSet((2*iterations), 0.75f);
becomes
HashSet counts = new HashSet((2*iterations), 0.75f) {
@Override public boolean add(Object element) { return false; }
};
Simple, faster and gets the same result.
A:
You might want to see if you can "prime" the JIT compiler into compiling the section of code you're interested in, by perhaps running it as a function once beforehand and sleeping briefly afterwords. This might allow the JVM to compile the function down to native code.
|
My python program executes faster than my java version of the same program. What gives?
|
Update: 2009-05-29
Thanks for all the suggestions and advice. I used your suggestions to make my production code execute 2.5 times faster on average than my best result a couple of days ago. In the end I was able to make the java code the fastest.
Lessons:
My example code below shows the insertion of primitive ints but the production code is actually storing strings (my bad). When I corrected that the python execution time went from 2.8 seconds to 9.6. So right off the bat, the java was actually faster when storing objects.
But it doesn't stop there. I had been executing the java program as follows:
java -Xmx1024m SpeedTest
But if you set the initial heap size as follows you get a huge improvement:
java -Xms1024m -Xmx1024m SpeedTest
This simple change reduced the execution time by more than 50%. So the final result for my SpeedTest is python 9.6 seconds. Java 6.5 seconds.
Original Question:
I had the following python code:
import time
import sys
def main(args):
iterations = 10000000
counts = set()
startTime = time.time();
for i in range(0, iterations):
counts.add(i)
totalTime = time.time() - startTime
print 'total time =',totalTime
print len(counts)
if __name__ == "__main__":
main(sys.argv)
And it executed in about 3.3 seconds on my machine but I wanted to make it faster so I decided to program it in java. I assumed that because java is compiled and is generally considered to be faster than python I would see some big paybacks.
Here is the java code:
import java.util.*;
class SpeedTest
{
public static void main(String[] args)
{
long startTime;
long totalTime;
int iterations = 10000000;
HashSet counts = new HashSet((2*iterations), 0.75f);
startTime = System.currentTimeMillis();
for(int i=0; i<iterations; i++)
{
counts.add(i);
}
totalTime = System.currentTimeMillis() - startTime;
System.out.println("TOTAL TIME = "+( totalTime/1000f) );
System.out.println(counts.size());
}
}
So this java code does basically the same thing as the python code. But it executed in 8.3 seconds instead of 3.3.
I have extracted this simple example from a real-world example to simplify things. The critical element is that I have (set or hashSet) that ends up with a lot of members much like the example.
Here are my questions:
How come my python implementation is faster than my java implementation?
Is there a better data structure to use than the hashSet (java) to hold a unique collection?
What would make the python implementation faster?
What would make the java implementation faster?
UPDATE:
Thanks to all who have contributed so far. Please allow me to add some details.
I have not included my production code because it is quite complex. And would generate a lot of distraction. The case I present above is the most simplified possible. By that I mean that the java put call seems to be much slower than the python set`s add().
The java implementation of the production code is also about 2.5 - 3 times slower than the python version -- just like the above.
I am not concerned about vm warmup or startup overhead. I just want to compare the code from my startTime to my totalTime. Please do not concern yourselves with other matters.
I initialized the hashset with more than enough buckets so that it should never have to rehash. (I will always know ahead of time how many elements the collection will ultimately contain.) I suppose one could argue that I should have initialized it to iterations/0.75. But if you try it you will see that execution time is not significantly impacted.
I set Xmx1024m for those that were curious (my machine has 4GB of ram).
I am using java version: Java(TM) SE Runtime Environment (build 1.6.0_13-b03).
In the production version of I am storing a string (2-15 chars) in the hashSet so I cannot use primitives, although that is an interesting case.
I have run the code many, many times. I have very high confidence that the python code is between 2.5 and 3 times faster than the java code.
|
[
"You're not really testing Java vs. Python, you're testing java.util.HashSet using autoboxed Integers vs. Python's native set and integer handling.\nApparently, the Python side in this particular microbenchmark is indeed faster.\nI tried replacing HashSet with TIntHashSet from GNU trove and achieved a speedup factor between 3 and 4, bringing Java slightly ahead of Python.\nThe real question is whether your example code is really as representative of your application code as you think. Have you run a profiler and determined that most of the CPU time is spent in putting a huge number of ints into a HashSet? If not, the example is irrelevant. Even if the only difference is that your production code stores other objects than ints, their creation and the computation of their hashcode could easily dominate the set insertion (and totally destroy Python's advantage in handling ints specially), making this whole question pointless.\n",
"I suspect that is that Python uses the integer value itself as its hash and the hashtable based implementation of set uses that value directly. From the comments in the source:\n\nThis isn't necessarily bad! To the contrary, in a table of size 2**i, taking\n the low-order i bits as the initial table index is extremely fast, and there\n are no collisions at all for dicts indexed by a contiguous range of ints.\n The same is approximately true when keys are \"consecutive\" strings. So this\n gives better-than-random behavior in common cases, and that's very desirable.\n\nThis microbenchmark is somewhat of a best case for Python because it results in exactly zero hash collisions. Whereas, if Javas HashSet is rehashing the keys it has to perform the additional work and also gets much worse behavior with collisions.\nIf you store the range(iterations) in a temporary variable and do a random.shuffle on it before the loop the runtime is more than 2x slower even if the shuffle and list creation is done outside the loop.\n",
"It has generally been my experience that python programs run faster than java programs, despite the fact that java is a bit \"lower level\" language. Incidently, both languages are compiled into byte code (that's what those .pyc file are -- you can think of them as kind of like .class files). Both languages are byte-code interpreted on a virtual stack machine.\nYou would expect python to be slower at things like, for example, a.b. In java, that a.b will resolve into a dereference. Python, on the other hand, has to do one or more hash table lookups: check the local scope, check the module scope, check global scope, check builtins.\nOn the other hand, java is notoriously bad at certain operations such as object creation (which is probably the culprit in your example) and serialization. \nIn summary, there's no simple answer. I wouldn't expect either language to be faster for all code examples.\nCorrection: several people have pointed out that java isn't so bad at object creation any more. So, in your example, it's something else. Perhaps it's autoboxing that's expensive, perhaps python's default hashing algorithm is better in this case. In my practical experience, when I rewrite java code to python, I always see a performance increase, but that could be as much due to the language as it is due to rewritng in general leads to performance improvements. \n",
"Another possible explanation is that sets in Python are implemented natively in C code, while HashSet's in Java are implemented in Java itself. So, sets in Python should be inherently much faster.\n",
"I'd like to dispel a couple myths I saw in the answers:\nJava is compiled, yes, to bytecode but ultimately to native code in most runtime environments. People who say C is inherently faster aren't telling the entire story, I could make a case that byte compiled languages are inherently faster because the JIT compiler can make machine-specific optimizations that are unavailable to way-ahead-of-time compilers.\nA number of things that could make the differences are:\n\nPython's hash tables and sets are the most heavily optimized objects in Python, and Python's hash function is designed to return similar results for similar inputs: hashing an integer just returns the integer, guaranteeing that you will NEVER see a collision in a hash table of consecutive integers in Python.\nA secondary effect of the above is that the Python code will have high locality of reference as you'll be accessing the hash table in sequence. \nJava does some fancy boxing and unboxing of integers when you add them to collections. On the bonus side, this makes arithmetic way faster in Java than Python (as long as you stay away from bignums) but on the downside it means more allocations than you're used to.\n\n",
"Edit: A TreeSet might be faster for the real use case, depending on allocation patterns. My comments below deals only with this simplified scenario. However, I do not believe that it would make a very significant difference. The real issue lays elsewhere. \nSeveral people here has recommended replacing the HashSet with a TreeSet. This sounds like a very strange advice to me, since there's no way that a data structure with O(log n) insertion time is faster then a O(1) structure that preallocates enough buckets to store all the elements.\nHere's some code to benchmark this:\nimport java.util.*;\nclass SpeedTest\n{ \n public static void main(String[] args)\n { \n long startTime;\n long totalTime;\n int iterations = 10000000;\n Set counts;\n\n System.out.println(\"HashSet:\");\n counts = new HashSet((2*iterations), 0.75f);\n startTime = System.currentTimeMillis();\n for(int i=0; i<iterations; i++) {\n counts.add(i);\n }\n totalTime = System.currentTimeMillis() - startTime;\n System.out.println(\"TOTAL TIME = \"+( totalTime/1000f) );\n System.out.println(counts.size());\n\n counts.clear();\n\n System.out.println(\"TreeSet:\");\n counts = new TreeSet();\n startTime = System.currentTimeMillis();\n for(int i=0; i<iterations; i++) {\n counts.add(i);\n }\n totalTime = System.currentTimeMillis() - startTime;\n System.out.println(\"TOTAL TIME = \"+( totalTime/1000f) );\n System.out.println(counts.size());\n }\n}\n\nAnd here's the result on my machine:\n$ java -Xmx1024M SpeedTest\nHashSet:\nTOTAL TIME = 4.436\n10000000\nTreeSet:\nTOTAL TIME = 8.163\n10000000\n\nSeveral people also argued that boxing isn't a performance issue and that object creation is inexpensive. While it's true that object creation is fast, it's definitely not as fast as primitives:\nimport java.util.*;\nclass SpeedTest2\n{ \n public static void main(String[] args)\n { \n long startTime;\n long totalTime;\n int iterations = 10000000;\n\n System.out.println(\"primitives:\");\n startTime = System.currentTimeMillis();\n int[] primitive = new int[iterations];\n for (int i = 0; i < iterations; i++) {\n primitive[i] = i;\n }\n totalTime = System.currentTimeMillis() - startTime;\n System.out.println(\"TOTAL TIME = \"+( totalTime/1000f) );\n\n System.out.println(\"primitives:\");\n startTime = System.currentTimeMillis();\n Integer[] boxed = new Integer[iterations];\n for (int i = 0; i < iterations; i++) {\n boxed[i] = i;\n }\n totalTime = System.currentTimeMillis() - startTime;\n System.out.println(\"TOTAL TIME = \"+( totalTime/1000f) );\n }\n}\n\nResult:\n$ java -Xmx1024M SpeedTest2\nprimitives:\nTOTAL TIME = 0.058\nprimitives:\nTOTAL TIME = 1.402\n\nMoreover, creating a lot of objects results in additional overhead from the garbage collector. This becomes significant when you start keeping tens of millions of live objects in memory.\n",
"I find benchmarks like this to be meaningless. I don't solve problems that look like the test case. It's not terribly interesting.\nI'd much rather see a solution for a meaningful linear algebra solution using NumPy and JAMA. Maybe I'll try it and report back with results.\n",
"I'm not too familiar with python, but I do know HashSet can't contain primitives, so when you say counts.add(i) the i there is getting autoboxed into a new Integer(i) call. That's probably your problem. \nIf for some reason you really needed a 'set' of integers between 0 and some large n, its probably best declared as an 'boolean[] set = new boolean[n]'. Then you could go through the array and mark items that are in the set as 'true' without incurring the overhead of creating n Integer wrapper objects. If you wanted to go further than that you could use a byte[] of size n/8 and use the individual bits directly. Or perhaps BigInteger. \nEDIT\nStop voting my answer up. Its wrong. \nEDIT \nNo really, its wrong. I get comparable performance if I do what the question suggest, populate the set with N Integers. if I replace the contents of the for loop with this:\n Integer[] ints = new Integer[N];\n for (int i = 0; i < N; ++i) {\n ints[i] = i;\n }\n\nThen it only takes 2 seconds. If you don't store the Integer at all then it takes less than 200 millis. Forcing the allocation of 10000000 Integer objects does take some time, but it looks like most of the time is spent inside the HashSet put operation.\n",
"There's a number of issues here which I'd like to bring together.\nFirst if it's a program that you are only going to run once, does it matter it takes an extra few seconds?\nSecondly, this is just one microbenchmarks. Microbenchmarks are pointless for comparing performance.\nStartup has a number of issues.\nThe Java runtime is much bigger than Python so takes longer to load from disk and takes up more memory which may be important if you are swapping.\nIf you haven't set -Xms you may be running the GC only to resize the heap. Might as well have the heap properly sized at the start.\nIt is true that Java starts off interpreting and then compiles. Around 1,500 iterations for Sun client [C1] Hotspot and 10,000 for server [C2]. Server Hotspot will give you better performance eventually, but take more memory. We may see client Hotspot use server for very frequently executed code for best of both worlds. However, this should not usually be a question of seconds.\nMost importantly you may be creating two objects per iteration. For most code, you wouldn't be creating these tiny objects for such a proportion of the execution. TreeSet may be better on number of objects score, with 6u14 and Harmony getting even better.\nPython may possibly be winning by storing small integer objects in references instead of actually have an object. That is undoubtably a good optimisation.\nA problem with a lot of benchmarks is you are mixing a lot of different code up in one method. You wouldn't write code you cared about like that, would you? So why are you attempting to performance test which is unlike code you would actually like to run fast?\nBetter data structure: Something like BitSet would seem to make sense (although that has ynchronisation on it, which may or may not impact performance).\n",
"You need to run it multiple times to get a real idea of \"how fast\" each runs. The JVM startup time [for one] is adding to the single running time of the Java version.\nYou're also creating a HashSet with a large initial capacity, which means the backing HashMap will be created with that many available slots, unlike the Python where you create a basic Set. Hard to tell if that would hinder though, as when your HashSet grows it will have to reallocate the stored objects.\n",
"Are you using the -server flag with the jvm? You can't test for performance without it. (You also have to warm up the jvm before doing the test.)\nAlso, you probably want to use TreeSet<Integer>. HashSet will be slower in the long run.\nAnd which jvm are you using? The newest I hope.\nEDIT\nWhen I say use TreeSet, I mean in general, not for this benchmark. TreeSet handles the real world issue of non even hashing of objects. If you get too many objects in the same bin in a HashSet, you will perform about O(n).\n",
"If you really want to store primitive types in a set, and do heavy work on it, roll your own set in Java. The generic classes are not fast enough for scientific computing.\nAs Ants Aasma mentions, Python bypasses hashing and uses the integer directly. Java creates an Integer object (autoboxing), and then casts it to an Object (in your implementation). This object must be hashed, as well, for use in a hash set.\nFor a fun comparision, try this:\nJava\nimport java.util.HashSet;\nclass SpeedTest\n{ \n public static class Element {\n private int m_i;\n public Element(int i) {\n m_i = i;\n }\n }\n\n public static void main(String[] args)\n { \n long startTime;\n long totalTime;\n int iterations = 1000000;\n HashSet<Element> counts = new HashSet<Element>((int)(2*iterations), 0.75f);\n\n startTime = System.currentTimeMillis();\n for(int i=0; i<iterations; ++i)\n {\n counts.add(new Element(i));\n }\n totalTime = System.currentTimeMillis() - startTime;\n System.out.println(\"TOTAL TIME = \"+( totalTime/1000f) );\n System.out.println(counts.size());\n }\n}\n\nResults:\n$java SpeedTest\nTOTAL TIME = 3.028\n1000000\n\n$java -Xmx1G -Xms1G SpeedTest\nTOTAL TIME = 0.578\n1000000\n\nPython\n#!/usr/bin/python\nimport time\nimport sys\n\nclass Element(object):\n def __init__(self, i):\n self.num = i\n\ndef main(args): \n iterations = 1000000\n counts = set()\n startTime = time.time(); \n for i in range(0, iterations):\n counts.add(Element(i))\n totalTime = time.time() - startTime\n print 'total time =',totalTime\n print len(counts)\n\n\nif __name__ == \"__main__\":\n main(sys.argv)\n\nResults:\n$./speedtest.py \ntotal time = 20.6943161488\n1000000\n\nHow's that for 'python is faster than java'?\n",
"How much memory did you start the JVM with? It depends? When I run the JVM with your program with 1 Gig of RAM:\n$ java -Xmx1024M -Xms1024M -classpath . SpeedTest \nTOTAL TIME = 5.682\n10000000\n$ python speedtest.py \ntotal time = 4.48310899734\n10000000\n\nIf I run the JVM with less memory, it takes longer ... considerably longer:\n$ java -Xmx768M -Xms768M -classpath . SpeedTest \nTOTAL TIME = 6.706\n10000000\n$ java -Xmx600M -Xms600M -classpath . SpeedTest \nTOTAL TIME = 14.086\n10000000\n\nI think the HashSet is the performance bottleneck in this particular instance. If I replace the HashSet with a LinkedList, the program gets substantially faster.\nFinally -- note that Java programs are initially interpreted and only those methods that are called many times are compiled. Thus, you're probably comparing Python to Java's interpreter, not the compiler.\n",
"Just a stab in the dark here, but some optimizations that Python is making that Java probably isn't:\n\nThe range() call in Python is creating all 10000000 integer objects at once, in optimized C code. Java must create an Integer object each iteration, which may be slower. \nIn Python, ints are immutable, so you can just store a reference to a global \"42\", for example, rather than allocating a slot for the object. I'm not sure how Java boxed Integer objects compare.\nMany of the built-in Python algorithms and data structures are rather heavily optimized for special cases. For instance, the hash function for integers is, simply the identity function. If Java is using a more \"clever\" hash function, this could slow things down quite a bit. If most of your time is spent in data structure code, I wouldn't be surprised at all to see Python beat Java given the amount of effort that has been spent over the years hand-tuning the Python C implementation.\n\n",
"A few changes for faster Python. \n#!/usr/bin/python\nimport time\nimport sys\n\nimport psyco #<<<< \npsyco.full()\n\nclass Element(object):\n __slots__=[\"num\"] #<<<<\n def __init__(self, i):\n self.num = i\n\ndef main(args): \n iterations = 1000000\n counts = set()\n startTime = time.time();\n for i in xrange(0, iterations):\n counts.add(Element(i))\n totalTime = time.time() - startTime\n print 'total time =',totalTime\n print len(counts)\n\nif __name__ == \"__main__\":\n main(sys.argv)\n\nBefore\n(env)~$ python speedTest.py\ntotal time = 8.82906794548\n1000000\n\nAfter\n(env)~$ python speedTest.py\ntotal time = 2.44039201736\n1000000\n\nNow some good old cheating and ...\n#!/usr/bin/python\nimport time\nimport sys\nimport psyco\n\npsyco.full()\n\nclass Element(object):\n __slots__=[\"num\"]\n def __init__(self, i):\n self.num = i\n\ndef main(args): \n iterations = 1000000\n counts = set()\n elements = [Element(i) for i in range(0, iterations)]\n startTime = time.time();\n for e in elements:\n counts.add(e)\n totalTime = time.time() - startTime\n print 'total time =',totalTime\n print len(counts)\n\nif __name__ == \"__main__\":\n main(sys.argv)\n\n(env)~$ python speedTest.py\ntotal time = 0.526521921158\n1000000\n\n",
"Well, if you're going to tune the Java program, you might as well tune the Python program too.\n>>> import timeit\n>>> timeit.Timer('x = set()\\nfor i in range(10000000):\\n x.add(i)').repeat(3, 1)\n[2.1174559593200684, 2.0019571781158447, 1.9973630905151367]\n>>> timeit.Timer('x = set()\\nfor i in xrange(10000000):\\n x.add(i)').repeat(3, 1)\n[1.8742368221282959, 1.8714439868927002, 1.869229793548584]\n>>> timeit.Timer('x = set(xrange(10000000))').repeat(3, 1)\n[0.74582195281982422, 0.73061800003051758, 0.73396801948547363]\n\nJust using xrange makes it about 8% faster on my machine. And the expression set(xrange(10000000)) builds exactly the same set, but 2.5x faster (from 1.87 seconds to 0.74).\nI like how tuning a Python program makes it shorter. :) But Java can do the same trick. As everyone knows, if you want a dense set of smallish integers in Java, you don't use a hash table. You use a java.util.BitSet!\nBitSet bits = new BitSet(iterations);\n\nstartTime = System.currentTimeMillis();\nbits.set(0, iterations, true);\ntotalTime = System.currentTimeMillis() - startTime;\nSystem.out.println(\"TOTAL TIME = \"+( totalTime/1000f) );\nSystem.out.println(bits.cardinality());\n\nThat should be fairly quick. Unfortunately I don't have the time to test it right now.\n",
"I agree with Gandalf about the startup time. Also, you are allocating a huge HashSet which is not at all similar to your python code. I imaging if you put this under a profiler, a good chunk of time would be spent there. Also, inserting new elements is really going to be slow with this size. I would look into TreeSet as suggested.\n",
"The biggest issue is probably that what the given code measures is wall time -- what your watch measures -- but what should be measured to compare code runtime is process time -- the amount of time the cpu spend executing that particular code and not other tasks.\n",
"You can make the Java microbenchamrk much faster, by adding just a simple little extra.\n HashSet counts = new HashSet((2*iterations), 0.75f);\n\nbecomes\n HashSet counts = new HashSet((2*iterations), 0.75f) {\n @Override public boolean add(Object element) { return false; }\n };\n\nSimple, faster and gets the same result.\n",
"You might want to see if you can \"prime\" the JIT compiler into compiling the section of code you're interested in, by perhaps running it as a function once beforehand and sleeping briefly afterwords. This might allow the JVM to compile the function down to native code.\n"
] |
[
21,
12,
7,
7,
6,
5,
4,
3,
3,
2,
2,
2,
1,
1,
1,
1,
0,
0,
0,
0
] |
[] |
[] |
[
"java",
"microbenchmark",
"python"
] |
stackoverflow_0000918359_java_microbenchmark_python.txt
|
Q:
What Python features will excite the interest of a C# developer?
For someone who’s been happily programming in C# for quite some time now and planning to learn a new language I find the Python community more closely knit than many others.
Personally dynamic typing puts me off, but I am fascinated by the way the Python community rallies around it. There are a lot of other things I expect I would miss in Python (LINQ, expression trees, etc.)
What are the good things about Python that developers love? Stuff that’ll excite me more than C#.
A:
For me its the flexibility and elegance, but there are a handful of things I wish could be pulled in from other languages though (better threading, more robust expressions).
In typical I can write a little bit of code in python and do a lot more than the same amount of lines in many other languages. Also, in python code form is of utmost importance and the syntax lends its self to highly readable, clean looking code. That of course helps out with maintenance.
I love having a command line interpreter that I can quickly prototype an algorithm in rather than having to start up a new project, code, compile, test, repeat. Not to mention the fact I can use it to help me automate my server maintenance as well (I double as a SA for my company).
The last thing that comes to mind immediately is the vast amounts of libraries. There are a lot of things already solved out there, the built-in library has a lot to offer, and the third party ones are many times very good (not always though).
A:
Being able to type in some code and get the result back immediately.
(Disclaimer: I use both C# and Python regularly, and I think both have their good and bad points.)
A:
I'm primarily .NET developer and using Python for me personal projects.
What are the good things about python that developers love?
I can say for myself - Python is like a breath of fresh air.
1) It's simple to learn, took about a week for me in the evenings. I'm saying about Python + Django. Python syntax is quite simple.
2) It's simple to use. No troubles installing Python + Django on Windows at all.
3) It can be run on Windows and UNIX.
4) I need it for web, so I get cheaper hosting than ASP.NET.
5) All the advantages of Python language over C#. Like tuples - so useful!
The only thing I don't like is that my favorite IDE Visual Studio doesn't support it (I know about IronPython, don't you worry).
A:
I'm a very heavy user of both C# and Python; I've built very complicated applications in both languages, and I've also embedded Python scripting in my major C# application. I'm not using either to do much in the way of web work right now, but other than that I feel like I'm pretty qualified to answer the question.
The things about Python that excite me, in particular:
The deep integration of generators into the language. This was the first thing that made me realize that I needed to take a long, serious look at Python. My appreciation for this has deepened considerably since I've become conversant with the itertools module, which looks like a nifty set of tools but is in fact a new way of life.
The coupling of dynamic typing and the fact that everything's an object makes pretty sophisticated techniques extremely simple to implement. It's so easy to replace logic with tables in Python (e.g. o = class_map[k]() instead of if k='foo': o = Foo()) that it becomes a basic technique. It's so normal in Python to write methods that take methods as parameters that you don't raise an eyebrow when you see d = defaultdict(list).
zip, and the methods that are designed with it in mind. It takes a while before you can intuitively grasp what dict(zip(k, v)) and d.update(zip(k, v)) are doing, but it's a paradigm-shifting moment when you get there. An entire universe of uninteresting and potentially error-laden code eliminated, just by using one function. Then you start designing functions and classes with the expectation that they'll be used in conjunction with zip, and suddenly your code gets simpler and easier. (Protip: Or itertools.izip. Or itertools.izip_longest.)
Speaking of dictionaries, the way that they're deeply integrated into the language. Understanding what a line of code like self.__dict__.update(**kwargs) does is another one of those paradigm-shifting moments.
List comprehensions and generator expressions, of course.
Inexpensive exceptions.
An interactive intepreter.
Function decorators.
IronPython, which is so much simpler to use than we have any right to expect.
And that's without even getting into the remarkable array of functionality in the standard modules, or the ridiculous bounty of third-party tools like BeautifulSoup or SQL Alchemy or Pylons.
One of the most direct benefits that I've gotten from getting deeply into Python is that it has greatly improved my C# code. I could generally understand code that had a variable of type Dictionary<string, Action<Foo>> in it, but it didn't seem natural to write it. (I use static dictionaries to replace hard-coded logic far more frequently today than I did a year ago.) I have no difficulty understanding what LINQ is doing now, or how IEnumerable<T> and return yield work.
So what don't I like about Python?
Dynamic typing really limits what you can do with static code analysis. Not only isn't there a tool like Resharper for Python, in a language where it's possible to write getattr(x, y)() there really can't be.
It has a bunch of inelegant conventions. How I would love to be able to go back in time and try to talk GVR out of the idea that lambda expressions should be introduced with the word lambda - it's pretty damning that something as fundamental as lambda expressions should be more concise in C# than they are in Python. The leading and trailing double-underscore convention is horrible, and the fact that people mutely acquiesce to it is testimony to Dostoevsky's observation that man is the animal who can get used to anything. And don't get me started on the fact that a module with the name of StringIO was allowed to get out the door.
Some of the features that make Python work on multiple platforms also make it kind of baffling. It's easy to use import, but it's really not easy to understand what the hell it's actually doing. (Where is it looking? What does __init__.py do? Etc.)
The amazingly rich library of standard modules is so amazingly rich that it's hard to know what's in it. It's often easier to write a function than it is to find out whether or not there's something in the standard library that does the same thing - I'm looking at you, itertools.chain.
A:
Your question is kind of like a plumber asking why carpenters are always going on and on about hammers. After all the plumber doesn't have a hammer and has never missed it. Python (even IronPython) and C# target different types of developers and different types of programs. I am very comfortable in Python and enjoy the freedom to focus on the business rules without being distracted by the syntax requirements of the language. On the other hand I have written some fairly substantial code in C# and would be very concerned about the lack of type safety had I taken on the same task in Python. This is not to say that Python is a "toy" language. You can (and people have) write a complete medium or large application in Python. You have the freedom of dynamic typing, but you also have the responsibility to keep it all straight (frameworks help here). Similarly you can write a small application in C#, but you will bring along some overhead you do not likely need.
So if the problem is a nail use a hammer, if the problem is a screw use a screw driver. In other words spend some time to learn Python, get to know it's streangths (text processing, quick coding cycles, simple clean code, etc) and then when you are looking at tackling a new problem ask whether you would be better off in Python or C#. One thing is certain. So long as C# is the only programming language you know, it is the only one you will ever use.
Pat O
A:
My language of choice is C#, and I didn't quite see the point for me to learn Python so far. This talk from PDC09 really piqued my interest: the guy demonstrates how you can use IronPython (or IronRuby) to make a C# app scriptable (in his demo, drop a Python script in a text box, and it works with/extends your C# code). I found this really fascinating: I don't even know where I would start to do something similar in C#, and this made me at least appreciate that it brings something different to the table, which could really enrich what I can develop!
A:
I'm an asymmetrical user of both languages, in a sense that I use C# mostly professionally and Python for all my "fun" projects (not that work is never fun, but... you know...)
This difference of context may skew my perspective, including my opinion that they are two distinct types (pun intended) of languages for, generally, distinct purposes.
This said, it may not be a coincidence that Python is, at this point in time, [one of?] the languages of choice for all kinds of cutting edge, somewhat scholarly, technology/science oriented projects. (And BTW, this "scholarly" keyword here doesNOT imply, that Python is a university toy, plenty of "serious" applications in plenty of domains/industry are proof to the contrary). This may be due to several factors:
(I don't develop most points, readily well expressed in other responses)
the openness and quasi universal availability of Python (unlike C# !)
the lightweight / ease of use / low learning curve
the extensive, high quality, "standard" library and the extensiver (and occasionally bum quality, but on the whole available, open-sourced, etc.) additional library.
the wide array of open source projects in Python language
the relative ease to bind with C/C++ for reusing legacy code, but also for placing performance-critical portions of a project
the generally higher level of abstraction of may constructs of the language
the multi-paradigms (imperative, object oriented and functional)
the availability of practitioners in so many domain of science and technology
and, yes, the
"herd mentality effect" mentioned in a remark, possibly in a [self?] deriding way. The fact that a language attracts a broad, "closely knit" community, makes it attractive too, beyond the superficial ("look cool" and such) traits of herd mentality. Put in broader context, sometimes the best technology/language to use is not measured on the its intrinsic merits but on the overall "picture", including the user community.
A:
I like all stuff with [] and {}. Selectors like this [-1:1]. Possibility to write less code, but more something meaningfull, that gives to write Models and other declarative things very DRY.
A:
Like any programming language, it is just a tool in the box or a brush by which you may paint your creation. Any creative endeavour requires that the artist loves the tools he uses; otherwise, the outcome suffers. Some people like Python for the same reason others love Perl. Incidentally, I have found that most Python lovers loathe Perl's flexible and expressive syntax. As a Perl lover, I don't hate Python, but consider it to be overly structured and restrictive.
If you ask me, all of these throngs of people who seem to love Python were silently suffering under the tool choices before Python came into being. Some suffered under Perl, others under something else. In other words, I believe that when Python came along, it found a large group of silent sufferers longing for a tool like Python.
I can't program in Python because I can't "think" in Python. I can "think" in Perl, therefore, it is the tool I prefer. The silently suffering mass of, now, Python users seem to have found some long lost salvation. Now if they could only keep their evangelism to themselves :).
A:
If you are familiar with the .NET CLR and prefer a statically-typed language, but you like Python's lightweight syntax, then perhaps Boo is the language for you.
A:
The main thing I like about Python is its very concise, readable syntax. Though using indentation as a block delimiter can seem strange at first, once you begin to code a lot in the language I find it begins to make sense. Though the core language is quite simple, its more advanced features, e.g. list comprehension, decorators and generators, are rather useful too.
In addition, the Python standard library is just fantastic; its documentation is very well written, and it contains a lot of very useful packages. I also find that there are plenty of good bindings for C libraries, such as PyGTK, Webkit and Qt, to name but a few.
One caveat is that Python, like most dynamic languages, is quite slow in comparison with compiled, statically-typed languages. However, you can easily extend it with C, allowing you to write code requiring better performance in C and the rest in Python.
It's a great language overall, and (for me at least) makes coding more productive and enjoyable.
A:
Don't get me wrong, I am and will always be a devoted fan of C#.
But sometimes there are things I can't do in C#. lthough C# keeps reducing those gaps, Python is still the language I go to to fill them.
It's dynamic, flexible, powerful, and clean. Lovely language. Whenever I need to script or build dynamic or functional (as in functional programming) software, I go Python.
A:
For me Python is the most elegant language I've used. The syntax is minimalist (significantly less punctuation than most) and intentionally modeled after the psuedo-code conventions which are ubiquitously used by programmer to outline their intentions.
Python's if __name__ == '__main__': suite encourages re-use and test driven development.
For example, the night before last I hacked together to run thousands of ssh jobs (with about 100 concurrently) and gather up all the results (output, error messages, exit values) ... and record the time take on each. It also handles timeouts (An ssh command can stall indefinitely on connection to a thrashing system --- it's connection timeouts and retry options don't apply after the socket connection is made, not matter if the authentication stalls). This only takes a few dozen lines of Python and it's really is easiest to create it as a class (defined above the __main__ suite) and do my command line parsing in a simple wrapper down inside __main__. That's sufficient to do the job at hand (I ran the script on 25,000 hosts the next day, in about two hours). It I can now use this code in other scripts as easily as:
from sshwrap import SSHJobMan
cmd = '/etc/init.d/foo restart'
targets = queryDB(some_criteria)
job = SSHJobMan(cmd, targets)
job.start()
while not job.done():
completed = job.poll()
# ...
# Deal with incremental disposition of of completed jobs
for each in sorted(job.results):
# ...
# Summarize results
... and so on.
So my script can be used for simple jobs ... and it can be imported as a module for more specialized work that couldn't be described on my wrapper's command line. (For example I could start up "consumer" subprocesses for handling other work on each host where the job was successful while spitting out service tickets or automated reboot requests for all hosts reporting timeouts or failures, etc).
For modules which have no standalone usage I can use the __main__ suite to contain unit-tests. Thus every module can contain its own tests ... which, in fact, can be integrated into the "doc strings" using the doctest module from the standard libraries. (Which, incidentally, means that properly formatted examples in the documentary comments can be kept in sync with the implementation ... since they are parts of the unit-test suite).
|
What Python features will excite the interest of a C# developer?
|
For someone who’s been happily programming in C# for quite some time now and planning to learn a new language I find the Python community more closely knit than many others.
Personally dynamic typing puts me off, but I am fascinated by the way the Python community rallies around it. There are a lot of other things I expect I would miss in Python (LINQ, expression trees, etc.)
What are the good things about Python that developers love? Stuff that’ll excite me more than C#.
|
[
"For me its the flexibility and elegance, but there are a handful of things I wish could be pulled in from other languages though (better threading, more robust expressions).\nIn typical I can write a little bit of code in python and do a lot more than the same amount of lines in many other languages. Also, in python code form is of utmost importance and the syntax lends its self to highly readable, clean looking code. That of course helps out with maintenance. \nI love having a command line interpreter that I can quickly prototype an algorithm in rather than having to start up a new project, code, compile, test, repeat. Not to mention the fact I can use it to help me automate my server maintenance as well (I double as a SA for my company).\nThe last thing that comes to mind immediately is the vast amounts of libraries. There are a lot of things already solved out there, the built-in library has a lot to offer, and the third party ones are many times very good (not always though).\n",
"Being able to type in some code and get the result back immediately.\n(Disclaimer: I use both C# and Python regularly, and I think both have their good and bad points.)\n",
"I'm primarily .NET developer and using Python for me personal projects.\n\nWhat are the good things about python that developers love?\n\nI can say for myself - Python is like a breath of fresh air. \n1) It's simple to learn, took about a week for me in the evenings. I'm saying about Python + Django. Python syntax is quite simple.\n2) It's simple to use. No troubles installing Python + Django on Windows at all.\n3) It can be run on Windows and UNIX.\n4) I need it for web, so I get cheaper hosting than ASP.NET.\n5) All the advantages of Python language over C#. Like tuples - so useful!\nThe only thing I don't like is that my favorite IDE Visual Studio doesn't support it (I know about IronPython, don't you worry).\n",
"I'm a very heavy user of both C# and Python; I've built very complicated applications in both languages, and I've also embedded Python scripting in my major C# application. I'm not using either to do much in the way of web work right now, but other than that I feel like I'm pretty qualified to answer the question.\nThe things about Python that excite me, in particular:\n\nThe deep integration of generators into the language. This was the first thing that made me realize that I needed to take a long, serious look at Python. My appreciation for this has deepened considerably since I've become conversant with the itertools module, which looks like a nifty set of tools but is in fact a new way of life.\nThe coupling of dynamic typing and the fact that everything's an object makes pretty sophisticated techniques extremely simple to implement. It's so easy to replace logic with tables in Python (e.g. o = class_map[k]() instead of if k='foo': o = Foo()) that it becomes a basic technique. It's so normal in Python to write methods that take methods as parameters that you don't raise an eyebrow when you see d = defaultdict(list).\nzip, and the methods that are designed with it in mind. It takes a while before you can intuitively grasp what dict(zip(k, v)) and d.update(zip(k, v)) are doing, but it's a paradigm-shifting moment when you get there. An entire universe of uninteresting and potentially error-laden code eliminated, just by using one function. Then you start designing functions and classes with the expectation that they'll be used in conjunction with zip, and suddenly your code gets simpler and easier. (Protip: Or itertools.izip. Or itertools.izip_longest.)\nSpeaking of dictionaries, the way that they're deeply integrated into the language. Understanding what a line of code like self.__dict__.update(**kwargs) does is another one of those paradigm-shifting moments.\nList comprehensions and generator expressions, of course.\nInexpensive exceptions.\nAn interactive intepreter.\nFunction decorators.\nIronPython, which is so much simpler to use than we have any right to expect.\n\nAnd that's without even getting into the remarkable array of functionality in the standard modules, or the ridiculous bounty of third-party tools like BeautifulSoup or SQL Alchemy or Pylons.\nOne of the most direct benefits that I've gotten from getting deeply into Python is that it has greatly improved my C# code. I could generally understand code that had a variable of type Dictionary<string, Action<Foo>> in it, but it didn't seem natural to write it. (I use static dictionaries to replace hard-coded logic far more frequently today than I did a year ago.) I have no difficulty understanding what LINQ is doing now, or how IEnumerable<T> and return yield work.\nSo what don't I like about Python?\n\nDynamic typing really limits what you can do with static code analysis. Not only isn't there a tool like Resharper for Python, in a language where it's possible to write getattr(x, y)() there really can't be.\nIt has a bunch of inelegant conventions. How I would love to be able to go back in time and try to talk GVR out of the idea that lambda expressions should be introduced with the word lambda - it's pretty damning that something as fundamental as lambda expressions should be more concise in C# than they are in Python. The leading and trailing double-underscore convention is horrible, and the fact that people mutely acquiesce to it is testimony to Dostoevsky's observation that man is the animal who can get used to anything. And don't get me started on the fact that a module with the name of StringIO was allowed to get out the door.\nSome of the features that make Python work on multiple platforms also make it kind of baffling. It's easy to use import, but it's really not easy to understand what the hell it's actually doing. (Where is it looking? What does __init__.py do? Etc.)\nThe amazingly rich library of standard modules is so amazingly rich that it's hard to know what's in it. It's often easier to write a function than it is to find out whether or not there's something in the standard library that does the same thing - I'm looking at you, itertools.chain.\n\n",
"Your question is kind of like a plumber asking why carpenters are always going on and on about hammers. After all the plumber doesn't have a hammer and has never missed it. Python (even IronPython) and C# target different types of developers and different types of programs. I am very comfortable in Python and enjoy the freedom to focus on the business rules without being distracted by the syntax requirements of the language. On the other hand I have written some fairly substantial code in C# and would be very concerned about the lack of type safety had I taken on the same task in Python. This is not to say that Python is a \"toy\" language. You can (and people have) write a complete medium or large application in Python. You have the freedom of dynamic typing, but you also have the responsibility to keep it all straight (frameworks help here). Similarly you can write a small application in C#, but you will bring along some overhead you do not likely need.\nSo if the problem is a nail use a hammer, if the problem is a screw use a screw driver. In other words spend some time to learn Python, get to know it's streangths (text processing, quick coding cycles, simple clean code, etc) and then when you are looking at tackling a new problem ask whether you would be better off in Python or C#. One thing is certain. So long as C# is the only programming language you know, it is the only one you will ever use.\nPat O\n",
"My language of choice is C#, and I didn't quite see the point for me to learn Python so far. This talk from PDC09 really piqued my interest: the guy demonstrates how you can use IronPython (or IronRuby) to make a C# app scriptable (in his demo, drop a Python script in a text box, and it works with/extends your C# code). I found this really fascinating: I don't even know where I would start to do something similar in C#, and this made me at least appreciate that it brings something different to the table, which could really enrich what I can develop!\n",
"I'm an asymmetrical user of both languages, in a sense that I use C# mostly professionally and Python for all my \"fun\" projects (not that work is never fun, but... you know...)\nThis difference of context may skew my perspective, including my opinion that they are two distinct types (pun intended) of languages for, generally, distinct purposes.\nThis said, it may not be a coincidence that Python is, at this point in time, [one of?] the languages of choice for all kinds of cutting edge, somewhat scholarly, technology/science oriented projects. (And BTW, this \"scholarly\" keyword here doesNOT imply, that Python is a university toy, plenty of \"serious\" applications in plenty of domains/industry are proof to the contrary). This may be due to several factors:\n(I don't develop most points, readily well expressed in other responses)\n\nthe openness and quasi universal availability of Python (unlike C# !)\nthe lightweight / ease of use / low learning curve\nthe extensive, high quality, \"standard\" library and the extensiver (and occasionally bum quality, but on the whole available, open-sourced, etc.) additional library.\nthe wide array of open source projects in Python language\nthe relative ease to bind with C/C++ for reusing legacy code, but also for placing performance-critical portions of a project\nthe generally higher level of abstraction of may constructs of the language\nthe multi-paradigms (imperative, object oriented and functional)\nthe availability of practitioners in so many domain of science and technology\n\nand, yes, the\n\n\"herd mentality effect\" mentioned in a remark, possibly in a [self?] deriding way. The fact that a language attracts a broad, \"closely knit\" community, makes it attractive too, beyond the superficial (\"look cool\" and such) traits of herd mentality. Put in broader context, sometimes the best technology/language to use is not measured on the its intrinsic merits but on the overall \"picture\", including the user community.\n\n",
"I like all stuff with [] and {}. Selectors like this [-1:1]. Possibility to write less code, but more something meaningfull, that gives to write Models and other declarative things very DRY.\n",
"Like any programming language, it is just a tool in the box or a brush by which you may paint your creation. Any creative endeavour requires that the artist loves the tools he uses; otherwise, the outcome suffers. Some people like Python for the same reason others love Perl. Incidentally, I have found that most Python lovers loathe Perl's flexible and expressive syntax. As a Perl lover, I don't hate Python, but consider it to be overly structured and restrictive.\nIf you ask me, all of these throngs of people who seem to love Python were silently suffering under the tool choices before Python came into being. Some suffered under Perl, others under something else. In other words, I believe that when Python came along, it found a large group of silent sufferers longing for a tool like Python. \nI can't program in Python because I can't \"think\" in Python. I can \"think\" in Perl, therefore, it is the tool I prefer. The silently suffering mass of, now, Python users seem to have found some long lost salvation. Now if they could only keep their evangelism to themselves :).\n",
"If you are familiar with the .NET CLR and prefer a statically-typed language, but you like Python's lightweight syntax, then perhaps Boo is the language for you.\n",
"The main thing I like about Python is its very concise, readable syntax. Though using indentation as a block delimiter can seem strange at first, once you begin to code a lot in the language I find it begins to make sense. Though the core language is quite simple, its more advanced features, e.g. list comprehension, decorators and generators, are rather useful too. \nIn addition, the Python standard library is just fantastic; its documentation is very well written, and it contains a lot of very useful packages. I also find that there are plenty of good bindings for C libraries, such as PyGTK, Webkit and Qt, to name but a few.\nOne caveat is that Python, like most dynamic languages, is quite slow in comparison with compiled, statically-typed languages. However, you can easily extend it with C, allowing you to write code requiring better performance in C and the rest in Python.\nIt's a great language overall, and (for me at least) makes coding more productive and enjoyable.\n",
"Don't get me wrong, I am and will always be a devoted fan of C#.\nBut sometimes there are things I can't do in C#. lthough C# keeps reducing those gaps, Python is still the language I go to to fill them.\nIt's dynamic, flexible, powerful, and clean. Lovely language. Whenever I need to script or build dynamic or functional (as in functional programming) software, I go Python. \n",
"For me Python is the most elegant language I've used. The syntax is minimalist (significantly less punctuation than most) and intentionally modeled after the psuedo-code conventions which are ubiquitously used by programmer to outline their intentions.\nPython's if __name__ == '__main__': suite encourages re-use and test driven development.\nFor example, the night before last I hacked together to run thousands of ssh jobs (with about 100 concurrently) and gather up all the results (output, error messages, exit values) ... and record the time take on each. It also handles timeouts (An ssh command can stall indefinitely on connection to a thrashing system --- it's connection timeouts and retry options don't apply after the socket connection is made, not matter if the authentication stalls). This only takes a few dozen lines of Python and it's really is easiest to create it as a class (defined above the __main__ suite) and do my command line parsing in a simple wrapper down inside __main__. That's sufficient to do the job at hand (I ran the script on 25,000 hosts the next day, in about two hours). It I can now use this code in other scripts as easily as:\nfrom sshwrap import SSHJobMan\n\ncmd = '/etc/init.d/foo restart'\ntargets = queryDB(some_criteria)\n\njob = SSHJobMan(cmd, targets)\njob.start()\n\nwhile not job.done():\n completed = job.poll()\n # ...\n # Deal with incremental disposition of of completed jobs\nfor each in sorted(job.results):\n # ...\n # Summarize results\n\n... and so on.\nSo my script can be used for simple jobs ... and it can be imported as a module for more specialized work that couldn't be described on my wrapper's command line. (For example I could start up \"consumer\" subprocesses for handling other work on each host where the job was successful while spitting out service tickets or automated reboot requests for all hosts reporting timeouts or failures, etc).\nFor modules which have no standalone usage I can use the __main__ suite to contain unit-tests. Thus every module can contain its own tests ... which, in fact, can be integrated into the \"doc strings\" using the doctest module from the standard libraries. (Which, incidentally, means that properly formatted examples in the documentary comments can be kept in sync with the implementation ... since they are parts of the unit-test suite).\n"
] |
[
18,
15,
11,
11,
10,
4,
2,
1,
1,
1,
0,
0,
0
] |
[] |
[] |
[
"c#",
"programming_languages",
"python"
] |
stackoverflow_0001773063_c#_programming_languages_python.txt
|
Q:
Sort a CSV by date in Python
I'm trying to sort a CSV file and I want the items sorted by date in reverse order: newest first.
def SortCsvByField( filename, fieldNo, sep = ',' ):
records = [line.split(sep) for line in file(filename)]
As far as that it's pretty easy, but how do I compare dates?
A:
I'd recommend installing the excellent dateutil module. (In Ubuntu/Debian, it is provided by the python-dateutil package).
dateutil can parse date strings into datetime objects: It can handle many different date formats without you having to lift a finger(*):
import dateutil.parser as dparser
date=dparser.parse("Mon May 7 1883 10:36:28")
print(date)
# 1883-05-07 10:36:28
date=dparser.parse("1685-3-21")
print(date)
# 1685-03-21 00:00:00
date=dparser.parse("12/17/1770")
print(date)
# 1770-12-17 00:00:00
Note that parse is interpretting "12/17/1770" as being of the form "MM/DD/YYYY". You can change this behavior using parse's dayfirst and yearfirst options. (See http://labix.org/python-dateutil)
print(type(date))
# <type 'datetime.datetime'>
datetime objects can be sorted easily:
dates=[dparser.parse("Mon May 7 1883 10:36:28"),dparser.parse("1685-3-21"),dparser.parse("12/17/1770"),]
dates.sort()
print(dates)
# [datetime.date(1685, 3, 21), datetime.date(1770, 12, 17), datetime.date(1833, 5, 7)]
If you prefer to not install the dateutil package, then you'll
have to roll your own method of converting date strings into datetime objects. This requires more work since you'll have to define the format. Below, '%Y-%m-%d' defines the YYYY-MM-DD format. See http://au2.php.net/strftime (or the man page of strftime) for more information on available format codes.
For example,
dates=[datetime.datetime.strptime(date_str,'%Y-%m-%d') for date_str in
('1883-5-7','1685-3-21','1770-12-17',)]
print([str(date) for date in dates])
# ['1883-05-07 00:00:00', '1685-03-21 00:00:00', '1770-12-17 00:00:00']
dates.sort()
print([str(date) for date in dates])
# ['1685-03-21 00:00:00', '1770-12-17 00:00:00', '1883-05-07 00:00:00']
To control the format when converting datetime objects back into printable strings, you can use the datetime.datetime.strftime() method.
A:
If your dates are in ISO-8601 format (YYYY-MM-DD) then you can sort them as strings, otherwise you will have to parse them first (datetime.strptime).
Then you can sort using for example sorted(records, key=lambda a:a[1]), if the date is the second field.
A:
Assuming that you know the format of the dates, and that they're in column 1 of your CSV file:
>>> import csv
>>> from datetime import datetime
>>> def date_key(row):
return datetime.strptime(row[1].strip(), "%m/%d/%Y")
>>> with open('c:\\temp\\test\\date_test.csv', 'rb') as f:
data = list(csv.reader(f))
>>> data
[['foo', ' 3/11/2004'], ['bar', ' 2/15/2001'], ['baz', '11/15/2007'], ['bat', '10/13/2002']]
>>> data.sort(key=date_key)
>>> data
[['bar', ' 2/15/2001'], ['bat', '10/13/2002'], ['foo', ' 3/11/2004'], ['baz', '11/15/2007']]
|
Sort a CSV by date in Python
|
I'm trying to sort a CSV file and I want the items sorted by date in reverse order: newest first.
def SortCsvByField( filename, fieldNo, sep = ',' ):
records = [line.split(sep) for line in file(filename)]
As far as that it's pretty easy, but how do I compare dates?
|
[
"I'd recommend installing the excellent dateutil module. (In Ubuntu/Debian, it is provided by the python-dateutil package).\ndateutil can parse date strings into datetime objects: It can handle many different date formats without you having to lift a finger(*):\nimport dateutil.parser as dparser\ndate=dparser.parse(\"Mon May 7 1883 10:36:28\")\nprint(date)\n# 1883-05-07 10:36:28\n\ndate=dparser.parse(\"1685-3-21\")\nprint(date)\n# 1685-03-21 00:00:00\n\ndate=dparser.parse(\"12/17/1770\")\nprint(date)\n# 1770-12-17 00:00:00\n\nNote that parse is interpretting \"12/17/1770\" as being of the form \"MM/DD/YYYY\". You can change this behavior using parse's dayfirst and yearfirst options. (See http://labix.org/python-dateutil)\nprint(type(date))\n# <type 'datetime.datetime'>\n\ndatetime objects can be sorted easily:\ndates=[dparser.parse(\"Mon May 7 1883 10:36:28\"),dparser.parse(\"1685-3-21\"),dparser.parse(\"12/17/1770\"),]\ndates.sort()\nprint(dates)\n# [datetime.date(1685, 3, 21), datetime.date(1770, 12, 17), datetime.date(1833, 5, 7)]\n\nIf you prefer to not install the dateutil package, then you'll \nhave to roll your own method of converting date strings into datetime objects. This requires more work since you'll have to define the format. Below, '%Y-%m-%d' defines the YYYY-MM-DD format. See http://au2.php.net/strftime (or the man page of strftime) for more information on available format codes.\nFor example,\ndates=[datetime.datetime.strptime(date_str,'%Y-%m-%d') for date_str in\n ('1883-5-7','1685-3-21','1770-12-17',)]\nprint([str(date) for date in dates])\n# ['1883-05-07 00:00:00', '1685-03-21 00:00:00', '1770-12-17 00:00:00']\ndates.sort()\nprint([str(date) for date in dates])\n# ['1685-03-21 00:00:00', '1770-12-17 00:00:00', '1883-05-07 00:00:00']\n\nTo control the format when converting datetime objects back into printable strings, you can use the datetime.datetime.strftime() method.\n",
"If your dates are in ISO-8601 format (YYYY-MM-DD) then you can sort them as strings, otherwise you will have to parse them first (datetime.strptime).\nThen you can sort using for example sorted(records, key=lambda a:a[1]), if the date is the second field.\n",
"Assuming that you know the format of the dates, and that they're in column 1 of your CSV file:\n>>> import csv\n>>> from datetime import datetime\n>>> def date_key(row):\n return datetime.strptime(row[1].strip(), \"%m/%d/%Y\")\n\n>>> with open('c:\\\\temp\\\\test\\\\date_test.csv', 'rb') as f:\n data = list(csv.reader(f))\n\n>>> data\n[['foo', ' 3/11/2004'], ['bar', ' 2/15/2001'], ['baz', '11/15/2007'], ['bat', '10/13/2002']]\n>>> data.sort(key=date_key)\n>>> data\n[['bar', ' 2/15/2001'], ['bat', '10/13/2002'], ['foo', ' 3/11/2004'], ['baz', '11/15/2007']]\n\n"
] |
[
5,
2,
2
] |
[] |
[] |
[
"csv",
"python",
"sorting"
] |
stackoverflow_0001773909_csv_python_sorting.txt
|
Q:
Emacs customization
I'm new to the whole Emacs thing, and one of the things that gets me is that out-of-the-box Emacs doesn't keep you within blocks when programming. I program in mostly Python and C++ and hitting enter sends the cursor back to column 1 on a new line rather than keeping you in the block you're working in. I managed to find this:
(add-hook 'python-mode-hook '(lambda () (define-key python-mode-map "\C-m" 'newline-and-indent)))
Which binds the enter key to newline-and-indent in Python mode, but how do I extend this to cover C/C++ mode too?
A:
The following is from my init.el for xemacs, it might or might not work for emacs:
(add-hook 'c-mode-common-hook
'(lambda ()
(define-key c-mode-base-map (kbd "RET") 'newline-and-indent)))
|
Emacs customization
|
I'm new to the whole Emacs thing, and one of the things that gets me is that out-of-the-box Emacs doesn't keep you within blocks when programming. I program in mostly Python and C++ and hitting enter sends the cursor back to column 1 on a new line rather than keeping you in the block you're working in. I managed to find this:
(add-hook 'python-mode-hook '(lambda () (define-key python-mode-map "\C-m" 'newline-and-indent)))
Which binds the enter key to newline-and-indent in Python mode, but how do I extend this to cover C/C++ mode too?
|
[
"The following is from my init.el for xemacs, it might or might not work for emacs:\n(add-hook 'c-mode-common-hook\n '(lambda () \n (define-key c-mode-base-map (kbd \"RET\") 'newline-and-indent)))\n\n"
] |
[
5
] |
[] |
[] |
[
"c++",
"customization",
"emacs",
"python"
] |
stackoverflow_0001774320_c++_customization_emacs_python.txt
|
Q:
How to resize just uploaded image?
In VIEW I want to resize uploaded image and save 2 copies of it in model real and changed
A:
Sorl has great thumbnailing capabilities that can also be used in templates ... it will also check to see if an image is already in the filesystem if not it will create the new resized file.
Depends really where your trying to call the image from.
http://thumbnail.sorl.net/docs
def image_thumb(self):
thumb = DjangoThumbnail(self.image_file, (380, 246))
return '<img src="%s" alt="%s" border="0" />' % (thumb.absolute_url, self.alt)
image_thumb.allow_tags = True
def get_thumb_url(self):
thumb = DjangoThumbnail(self.image_file, (380, 246))
return thumb.absolute_url
Also as I mentioned you can call it directly from the template to load any image.
{% load thumbnail %}
{% thumbnail url 100x100 crop,upscale %}
Obviously you will call the load at the top of your file and the thumbnail where ever you wish for one to appear. The great thing about this too is that you can replace url with python objects such as this
{% thumbnail image.get_absolute_url 150x150 crop %}
The size is self explanatory I would hope and the final crop,upscale are functions of sorl-thumbnail that will have various effects on the final image.
A:
There's 1 things to note at beginning here:
in your model (database) it's better to save the paths to images, not images themselves. Those should be kept in the filesystem and served directly from there, if possible (unless you don't have the access to the filesystem).
So, in your view, you should do the following:
Save the uploaded file somewhere (unless it's saved alredy, then you have it's path, goto 2),
Put the original image path to database,
Resize it,
Save the resized image to filesystem,
Save the path to resized image to your database.
About the points 3 and 4, I do this like that:
orig_img = Image.open(self.imageFile)
orig_img_dim = orig_img.size # (orig_img_dim[0], orig_img_dim[1]) is (y, x) size of image
if (orig_img_dim[0] > 600) or (orig_img_dim[1] > 1000): # only resize images too large
orig_img.thumbnail((600, 1000), Image.ANTIALIAS)
orig_img.save(DESTINATION_FILENAME)
Note that I only resize images that are too large (larger then the 'thumbnail' size).
A:
Use sorl - http://thumbnail.sorl.net/docs/
for you task See this
class MyModel(models.Model):
name = models.TextField(max_length=50)
photo = ImageWithThumbnailsField(
upload_to='profiles',
thumbnail={'size': (50, 50)},
extra_thumbnails={
'icon': {'size': (16, 16), 'options': ['crop', 'upscale']},
'large': {'size': (200, 400)},
},
)
This code doing all you want
A:
Look at this http://biohackers.net/wiki/Django1.0/Thumbnail
A:
Django Imagekit allows you to specify multiple image sizes. The resized images are cached, then you can access them and the original image file in your views and templates.
|
How to resize just uploaded image?
|
In VIEW I want to resize uploaded image and save 2 copies of it in model real and changed
|
[
"Sorl has great thumbnailing capabilities that can also be used in templates ... it will also check to see if an image is already in the filesystem if not it will create the new resized file.\nDepends really where your trying to call the image from.\nhttp://thumbnail.sorl.net/docs\ndef image_thumb(self):\n thumb = DjangoThumbnail(self.image_file, (380, 246))\n return '<img src=\"%s\" alt=\"%s\" border=\"0\" />' % (thumb.absolute_url, self.alt)\nimage_thumb.allow_tags = True\n\ndef get_thumb_url(self):\n thumb = DjangoThumbnail(self.image_file, (380, 246))\n return thumb.absolute_url\n\nAlso as I mentioned you can call it directly from the template to load any image.\n{% load thumbnail %}\n{% thumbnail url 100x100 crop,upscale %}\n\nObviously you will call the load at the top of your file and the thumbnail where ever you wish for one to appear. The great thing about this too is that you can replace url with python objects such as this\n{% thumbnail image.get_absolute_url 150x150 crop %}\n\nThe size is self explanatory I would hope and the final crop,upscale are functions of sorl-thumbnail that will have various effects on the final image. \n",
"There's 1 things to note at beginning here:\n\nin your model (database) it's better to save the paths to images, not images themselves. Those should be kept in the filesystem and served directly from there, if possible (unless you don't have the access to the filesystem). \n\nSo, in your view, you should do the following:\n\nSave the uploaded file somewhere (unless it's saved alredy, then you have it's path, goto 2),\nPut the original image path to database,\nResize it, \nSave the resized image to filesystem,\nSave the path to resized image to your database.\n\nAbout the points 3 and 4, I do this like that:\norig_img = Image.open(self.imageFile)\norig_img_dim = orig_img.size # (orig_img_dim[0], orig_img_dim[1]) is (y, x) size of image\nif (orig_img_dim[0] > 600) or (orig_img_dim[1] > 1000): # only resize images too large\n orig_img.thumbnail((600, 1000), Image.ANTIALIAS)\norig_img.save(DESTINATION_FILENAME)\n\nNote that I only resize images that are too large (larger then the 'thumbnail' size). \n",
"Use sorl - http://thumbnail.sorl.net/docs/\nfor you task See this \nclass MyModel(models.Model):\n name = models.TextField(max_length=50)\n photo = ImageWithThumbnailsField(\n upload_to='profiles',\n thumbnail={'size': (50, 50)},\n extra_thumbnails={\n 'icon': {'size': (16, 16), 'options': ['crop', 'upscale']},\n 'large': {'size': (200, 400)},\n },\n)\n\nThis code doing all you want\n",
"Look at this http://biohackers.net/wiki/Django1.0/Thumbnail\n",
"Django Imagekit allows you to specify multiple image sizes. The resized images are cached, then you can access them and the original image file in your views and templates.\n"
] |
[
8,
3,
3,
2,
1
] |
[] |
[] |
[
"django",
"python",
"python_imaging_library"
] |
stackoverflow_0001769683_django_python_python_imaging_library.txt
|
Q:
How can I program software using Python for Linux/Windows?
For example, using C# I can make software fairly easily for Windows.
I downloaded Python but all I get is a terminal like window for executing single lines of code.
Is there a free IDE/Visual editor for designing GUI's in conjunction with Python?
Thank SO. :D
A:
The character-based terminal (console) interface isn't the only one Python affords. It is often the most visible because it is
"built-in"
often used in the early stages of learning the language, allowing one to focus on various idioms of the language, without the added complexity of the object model and API associated with a GUI
quite handy for many quick jobs, script-like / awk-like type applications, whether ad-hoc or more permanent.
GUIs for Python are aplenty, in fact overwhelmingly so, which can be handicap as people try and decide which one to use. Often, the choice may be driven by one's familiarity with these GUI frameworks, for as you can see they are not specific to Python (recognize their names, often with a Py prefix). Another criteria may be their support (or lack thereof) on various Operating Systems. And yet another criteria may be the way these framework tie-in with broader systems such as MVC frameworks etc..
Anyway the arguably most popular one may be:
TkInter (tk/tcl)
PyQT
WxPython
and if you want more...
here's a "complete" list
Similarly, there are several IDEs for developing in Python, although many of these do not include GUI designer features. Here's a representative but certainly incomplete list. They are listed in no particular order (do comment on possible significant omissions or errors with regard to features). Most are either free or inexpensive.
IDLE
Eric
PyDev
Wing IDE
Netbeans IDE
the following have some GUI design features (underlying GUI in parenthesis)
BlackAdder (Qt)
Boa Constructor (Wx)
Komodo (Tk) (I think commerical, now)
Eclipse
The capabilities of these IDEs vary greatly, and some may cover some areas of development rather well (ex debugging, or unittesting) while being weak in other areas (say auto-completion). Many Python developers also manage rather well with "plain" (but well featured) text editors and a few macros/plug-ins.
A:
Yes, lots.
http://wiki.python.org/moin/GuiProgramming
A:
If you know .Net and C#, you could use IronPython and WPF. Then you can use Visual Studio 2010 Beta 2 as your development environment. Here's an example of how it can be done.
|
How can I program software using Python for Linux/Windows?
|
For example, using C# I can make software fairly easily for Windows.
I downloaded Python but all I get is a terminal like window for executing single lines of code.
Is there a free IDE/Visual editor for designing GUI's in conjunction with Python?
Thank SO. :D
|
[
"The character-based terminal (console) interface isn't the only one Python affords. It is often the most visible because it is\n\n\"built-in\"\noften used in the early stages of learning the language, allowing one to focus on various idioms of the language, without the added complexity of the object model and API associated with a GUI\nquite handy for many quick jobs, script-like / awk-like type applications, whether ad-hoc or more permanent.\n\nGUIs for Python are aplenty, in fact overwhelmingly so, which can be handicap as people try and decide which one to use. Often, the choice may be driven by one's familiarity with these GUI frameworks, for as you can see they are not specific to Python (recognize their names, often with a Py prefix). Another criteria may be their support (or lack thereof) on various Operating Systems. And yet another criteria may be the way these framework tie-in with broader systems such as MVC frameworks etc..\nAnyway the arguably most popular one may be:\n\nTkInter (tk/tcl)\nPyQT\nWxPython\nand if you want more...\nhere's a \"complete\" list\n\nSimilarly, there are several IDEs for developing in Python, although many of these do not include GUI designer features. Here's a representative but certainly incomplete list. They are listed in no particular order (do comment on possible significant omissions or errors with regard to features). Most are either free or inexpensive.\n\nIDLE\nEric \nPyDev\nWing IDE \nNetbeans IDE\nthe following have some GUI design features (underlying GUI in parenthesis)\nBlackAdder (Qt)\nBoa Constructor (Wx)\nKomodo (Tk) (I think commerical, now)\nEclipse \n\nThe capabilities of these IDEs vary greatly, and some may cover some areas of development rather well (ex debugging, or unittesting) while being weak in other areas (say auto-completion). Many Python developers also manage rather well with \"plain\" (but well featured) text editors and a few macros/plug-ins.\n",
"Yes, lots.\nhttp://wiki.python.org/moin/GuiProgramming\n",
"If you know .Net and C#, you could use IronPython and WPF. Then you can use Visual Studio 2010 Beta 2 as your development environment. Here's an example of how it can be done.\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"ide",
"linux",
"python",
"user_interface",
"windows"
] |
stackoverflow_0001774384_ide_linux_python_user_interface_windows.txt
|
Q:
Module import error using IDLE
I'm an absolute beginner using IDLE (Python 2.6.4) to learn the basics. I recently found a Python program that I want to run but it throws an error although the code looks fine (i.e all modules exist):
from css.parse import parse
data = """
em {
padding: 2px;
margin: 1em;
border-width: medium;
border-style: dashed;
line-height: 2.4em;
}
p { color: red; font-size: 12pt }
p:first-letter { color: green; font-size: 200% }
p:first-line { color: blue }"""
for rule in parse(data):
print rule
for decl in parse(data)[0]:
print decl
Error:
ImportError: No module named parse
How do I fix this? I'm using Snow Leopard.
Edit: I guess its a PATH issue, where should I place the modules, which directory?
A:
You should have your test.py script in the same folder as the folder, not in the folder.
So it should look like this:
../
test.py
css/
A:
A generic but useful reference regarding the way Python module search path is
this brief but informative section of Python Documentation
The default paths and the environmental variables which allow configuring this important feature of the interpreter varies with different Operating Systems, so it is important to know this info for troubleshooting situations similar to that of Nimbuz.
Also the IDEs themselves can add yet another layer of configuration/indirection...
|
Module import error using IDLE
|
I'm an absolute beginner using IDLE (Python 2.6.4) to learn the basics. I recently found a Python program that I want to run but it throws an error although the code looks fine (i.e all modules exist):
from css.parse import parse
data = """
em {
padding: 2px;
margin: 1em;
border-width: medium;
border-style: dashed;
line-height: 2.4em;
}
p { color: red; font-size: 12pt }
p:first-letter { color: green; font-size: 200% }
p:first-line { color: blue }"""
for rule in parse(data):
print rule
for decl in parse(data)[0]:
print decl
Error:
ImportError: No module named parse
How do I fix this? I'm using Snow Leopard.
Edit: I guess its a PATH issue, where should I place the modules, which directory?
|
[
"You should have your test.py script in the same folder as the folder, not in the folder.\nSo it should look like this:\n../\n test.py\n css/\n\n",
"A generic but useful reference regarding the way Python module search path is\nthis brief but informative section of Python Documentation\nThe default paths and the environmental variables which allow configuring this important feature of the interpreter varies with different Operating Systems, so it is important to know this info for troubleshooting situations similar to that of Nimbuz.\nAlso the IDEs themselves can add yet another layer of configuration/indirection...\n"
] |
[
1,
1
] |
[] |
[] |
[
"path",
"python",
"python_idle"
] |
stackoverflow_0001774453_path_python_python_idle.txt
|
Q:
Call from Objective-C into Python
bbum posted an outline of how to do this, but I'm unable to complete the details. Where does the Python code go, and how will my Objective-C code know about it? How would I do it compiling on the command line?
A:
Source here:
Calling Python From Objective-C
I have posted a full explanation of how to do this to my weblog as it is quite a bit longer than something I would post here.
The abstract summary remains the same: use an abstract class to provide the type information necessary to make the C compiler happy and the metadata necessary to make the bridge happy.
A:
Unfortunately the story for using Python via PyObjC from within an Objective-C app is not very good at the moment. py2app which ships with PyObjC can compile loadable bundles (i.e. can be loaded via NSBundle), which seems like the best approach: define an NSObject subclass in python that implements a protocol (obtained via objc.protocolNamed) that you define in Objective-C, then compile this python file into a loadable bundle via py2app (which uses a standard setup.py). Unfortunately, py2app hasn't had much love, especially the plugin (loadable bundle) target, and a serious memory leak was introduced sometime around 10.5 such that any data passed from python to Objective-C from a py2app-compiled bundle leaks. Yuck.
PyObjC manipulates the Objective-C runtime in accordance with the ObjC-related code executed in Python, thus to be able to call python code from Objective-C, the general outline goes like
Write PyObjC wrapper around python code
Execute code declaring PyObjC wrapper to add these definitions to the ObjC runtime
Call PyObjC wrapper from Objective-C. Because it's declared at runtime, the symbols aren't available at compile time, so you'll have to use NSClassFromString et al. to instantiate the class. It's helpful to declare a @protocol with the appropriate methods so that the Objective-C compiler doesn't complain about missing methods.
If you have flexibility, the best option is to use the Cocoa-Python app templates (i.e. create a Python app), and then load your Objective-C code as a loadable bundle from within Python. This takes care of managing the Python interpreter for you.
Otherwise, with the code in main.m of the Cocoa-Python app template, you should be able to create a Python interpreter, execute your PyObjC code and then continue on. Obviously, the interpreter needs to be kept running so that your python code can execute, so you'll likely have to do this from a separate thread. As you can see this can get a little hairy. Better to go with the Python app, as described above.
Keep in mind that PyObjC is not guaranteed to play well with the Objective-C garbage collector, so all of these options require that your Objective-C code not use GC.
A:
Google is your friend. Performing a search on the string "Cocoa Python" quickly turned up PyObjc.
|
Call from Objective-C into Python
|
bbum posted an outline of how to do this, but I'm unable to complete the details. Where does the Python code go, and how will my Objective-C code know about it? How would I do it compiling on the command line?
|
[
"Source here:\nCalling Python From Objective-C\nI have posted a full explanation of how to do this to my weblog as it is quite a bit longer than something I would post here.\nThe abstract summary remains the same: use an abstract class to provide the type information necessary to make the C compiler happy and the metadata necessary to make the bridge happy.\n",
"Unfortunately the story for using Python via PyObjC from within an Objective-C app is not very good at the moment. py2app which ships with PyObjC can compile loadable bundles (i.e. can be loaded via NSBundle), which seems like the best approach: define an NSObject subclass in python that implements a protocol (obtained via objc.protocolNamed) that you define in Objective-C, then compile this python file into a loadable bundle via py2app (which uses a standard setup.py). Unfortunately, py2app hasn't had much love, especially the plugin (loadable bundle) target, and a serious memory leak was introduced sometime around 10.5 such that any data passed from python to Objective-C from a py2app-compiled bundle leaks. Yuck.\nPyObjC manipulates the Objective-C runtime in accordance with the ObjC-related code executed in Python, thus to be able to call python code from Objective-C, the general outline goes like\n\nWrite PyObjC wrapper around python code\nExecute code declaring PyObjC wrapper to add these definitions to the ObjC runtime\nCall PyObjC wrapper from Objective-C. Because it's declared at runtime, the symbols aren't available at compile time, so you'll have to use NSClassFromString et al. to instantiate the class. It's helpful to declare a @protocol with the appropriate methods so that the Objective-C compiler doesn't complain about missing methods.\n\nIf you have flexibility, the best option is to use the Cocoa-Python app templates (i.e. create a Python app), and then load your Objective-C code as a loadable bundle from within Python. This takes care of managing the Python interpreter for you.\nOtherwise, with the code in main.m of the Cocoa-Python app template, you should be able to create a Python interpreter, execute your PyObjC code and then continue on. Obviously, the interpreter needs to be kept running so that your python code can execute, so you'll likely have to do this from a separate thread. As you can see this can get a little hairy. Better to go with the Python app, as described above.\nKeep in mind that PyObjC is not guaranteed to play well with the Objective-C garbage collector, so all of these options require that your Objective-C code not use GC.\n",
"Google is your friend. Performing a search on the string \"Cocoa Python\" quickly turned up PyObjc.\n"
] |
[
12,
3,
0
] |
[] |
[] |
[
"objective_c",
"python"
] |
stackoverflow_0001772491_objective_c_python.txt
|
Q:
Fixtures for Google App Engine
Are there any Python tools to create fixtures on Google App Engine? I tried Fixture(http://farmdev.com/projects/fixture/). It is the most awesome tool I have come across. I love the clean approach and the consistency of the APIs. But it is LGPL licensed. Our project is licensed under Apache License 2.0 and AFAIK LGPL is incompatible with this license. Can some one please suggest any other tool similar to Fixture but with Apache compatible license?
A:
Are you using the fixtures just for testing your app? If so, I don't think the license of your app matters at all. It would only be important if you were redistributing the fixtures functionality.
|
Fixtures for Google App Engine
|
Are there any Python tools to create fixtures on Google App Engine? I tried Fixture(http://farmdev.com/projects/fixture/). It is the most awesome tool I have come across. I love the clean approach and the consistency of the APIs. But it is LGPL licensed. Our project is licensed under Apache License 2.0 and AFAIK LGPL is incompatible with this license. Can some one please suggest any other tool similar to Fixture but with Apache compatible license?
|
[
"Are you using the fixtures just for testing your app? If so, I don't think the license of your app matters at all. It would only be important if you were redistributing the fixtures functionality.\n"
] |
[
1
] |
[] |
[] |
[
"fixture",
"google_app_engine",
"python",
"testing"
] |
stackoverflow_0001770755_fixture_google_app_engine_python_testing.txt
|
Q:
Appending to a List
L = ['abc', 'ADB', 'aBe']
L[len(L):]=['a1', 'a2'] # append items at the end...
L[-1:]=['a3', 'a4'] # append more items at the end...
... works, but 'a2' is missing in the output:
['abc', 'ADB', 'aBe', 'append', 'a1', 'a3', 'a4']
A:
I think that the -1 is pointing at the last element of the list, which gets overwritten by 'a3'. As described here, you can do a
list.extend(['a3', 'a4'])
A:
Use L.append (for a single element) or L.extend (for a sequence) -- there's absolutely no call for playing fancy "assign-to-slice" tricks (especially if you don't master them!-). The slice [-1:] means "last element included onwards" -- so, by assigning to that slice, you're obviously "overwriting" the last element!
A:
What is wrong with:
L.append('a1')
or
L += ['a1', 'a2']
A:
to append items to a list, you can use +
L + ["a1","a2"]
A:
Your 3rd assignment is overwriting the 'a2' value.
Perhaps you should be using a more straightforward method:
L = ['abc', 'ADB', 'aBe']
L += ['a1', 'a2']
L += ['a3', 'a4']
Etc.
A:
Use the extend method
L = ['abc', 'ADB', 'aBe']
L.extend(['a1', 'a2'])
L.extend(['a3', 'a4'])
|
Appending to a List
|
L = ['abc', 'ADB', 'aBe']
L[len(L):]=['a1', 'a2'] # append items at the end...
L[-1:]=['a3', 'a4'] # append more items at the end...
... works, but 'a2' is missing in the output:
['abc', 'ADB', 'aBe', 'append', 'a1', 'a3', 'a4']
|
[
"I think that the -1 is pointing at the last element of the list, which gets overwritten by 'a3'. As described here, you can do a \nlist.extend(['a3', 'a4'])\n\n",
"Use L.append (for a single element) or L.extend (for a sequence) -- there's absolutely no call for playing fancy \"assign-to-slice\" tricks (especially if you don't master them!-). The slice [-1:] means \"last element included onwards\" -- so, by assigning to that slice, you're obviously \"overwriting\" the last element!\n",
"What is wrong with:\nL.append('a1')\n\nor\nL += ['a1', 'a2']\n\n",
"to append items to a list, you can use +\nL + [\"a1\",\"a2\"]\n\n",
"Your 3rd assignment is overwriting the 'a2' value.\nPerhaps you should be using a more straightforward method:\nL = ['abc', 'ADB', 'aBe']\nL += ['a1', 'a2']\nL += ['a3', 'a4']\nEtc.\n\n",
"Use the extend method\nL = ['abc', 'ADB', 'aBe']\nL.extend(['a1', 'a2'])\nL.extend(['a3', 'a4'])\n\n"
] |
[
3,
3,
1,
1,
1,
0
] |
[] |
[] |
[
"list",
"python"
] |
stackoverflow_0001774616_list_python.txt
|
Q:
Subversion post-commit hook
I have created a subversion post-commit hook to send out an email everytime a commit is made.Im calling a python script from the file post-commit in /var/svn/repos/hooks .
REPOS="$1"
REV="$2"
~/svnnotify.py $REV
But the problem is that the svn commit command is taking a longer time to terminate as it waits for the python script to terminate first . Is there any way around this ?
Thank You
A:
Try adding an ampersand (&) after the line that calls your script to put it in the background and return immediately.
A:
Call a batch file and in that batch file execute python script to run in the background by adding ampersand at end of command in batch file( & ).
A:
Maybe put the update in a simple queue that gets scooped up by a script run invoked from cron and sends a message if something is sitting in the queue.
Queue could be a simple file in /tmp, an sqlite file, or a MySQL table.
If it's taking noticeably long to send the e-mail, maybe there's something up with the code in the notify script. It shouldn't take that long to put an e-email in the local mail queue.
|
Subversion post-commit hook
|
I have created a subversion post-commit hook to send out an email everytime a commit is made.Im calling a python script from the file post-commit in /var/svn/repos/hooks .
REPOS="$1"
REV="$2"
~/svnnotify.py $REV
But the problem is that the svn commit command is taking a longer time to terminate as it waits for the python script to terminate first . Is there any way around this ?
Thank You
|
[
"Try adding an ampersand (&) after the line that calls your script to put it in the background and return immediately.\n",
"Call a batch file and in that batch file execute python script to run in the background by adding ampersand at end of command in batch file( & ).\n",
"Maybe put the update in a simple queue that gets scooped up by a script run invoked from cron and sends a message if something is sitting in the queue.\nQueue could be a simple file in /tmp, an sqlite file, or a MySQL table.\nIf it's taking noticeably long to send the e-mail, maybe there's something up with the code in the notify script. It shouldn't take that long to put an e-email in the local mail queue.\n"
] |
[
4,
0,
0
] |
[] |
[] |
[
"python",
"svn",
"svn_hooks",
"unix"
] |
stackoverflow_0001774646_python_svn_svn_hooks_unix.txt
|
Q:
Python ctypes & libspeex.dll/libspeex.so; what are the equivilents to #define, typedef, and structs?
I have a reference of the dll file here:
http://speex.org/docs/api/speex-api-reference/group__Codec.html
What I'm wondering is, in that list, there are a lot of defines. What is the python equivalent, same for the struct class, what are my options for implementing all of this with ctypes? Typedefs?
I'm relatively inexperienced with python so please pardon me if I'm less than adequate in my skill. No colleges teach it around here so I'm trying to learn via asking & google.
Right now I'm just trying to basically figure out how to interface with this speex library so I can at least start using the encode/decode functions. But I am unsure of implementation of those 3 things. I'm sure I'm over my head with this but in the end it seems I always come out on top learning something new. Anyone mind giving me a brief rundown?
From what I take it #define in all practical purposes is basically just foo = bar?And Class:Struct SpeexMode would be a class, that has all of the listed functions?
Or is all of this already defined in the compiled DLL? If so, I've already done a small dll file call with ctypes via a tutorial I ran across. Would it be as simple as setting up the environment (passing these variables into the functions to set things such as codec quality, invoking the encoder, then using the encoder?)
A:
To use structs, you indeed should declare them with ctypes.Structure to let Python know about them.
>>> from ctypes import *
>>> class POINT(Structure):
... _fields_ = [("x", c_int),
... ("y", c_int)]
...
>>> point = POINT(10, 20)
>>> print point.x, point.y
10 20
>>> point = POINT(y=5)
>>> print point.x, point.y
0 5
>>> POINT(1, 2, 3)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: too many initializers
>>>
As for defines, they're part of the include file usually, so you'll just have to define them yourself in the Python code, because the C compiler doesn't even see them (defines are converted to their values by the pre-processor).
If you're looking for a more automatic converter from C/C++ interfaces to Python, look at SWIG. SWIG, unlike ctypes, requires you to use a C compiler in addition to pure Python.
A:
I figured out structs at least, and how to basically convert them.
Basically you just make a class, pass it ctypes.Structure, then make your array of fields.
like so:
class PASSWD(ctypes.Structure):
_fields_ = [("name", ctypes.c_char_p),
("passwd", ctypes.c_char_p),
("uid", ctypes.c_int),
("gid", ctypes.c_int),
("change", ctypes.c_long),
("class", ctypes.c_char_p),
("gecos", ctypes.c_char_p),
("dir", ctypes.c_char_p),
("shell", ctypes.c_char_p),
("expire", ctypes.c_long),
("fields", ctypes.c_int) ]
But I'm not so sure I even need to set these all up. I'm pretty sure they're all defined in the DLL and setup, no?
|
Python ctypes & libspeex.dll/libspeex.so; what are the equivilents to #define, typedef, and structs?
|
I have a reference of the dll file here:
http://speex.org/docs/api/speex-api-reference/group__Codec.html
What I'm wondering is, in that list, there are a lot of defines. What is the python equivalent, same for the struct class, what are my options for implementing all of this with ctypes? Typedefs?
I'm relatively inexperienced with python so please pardon me if I'm less than adequate in my skill. No colleges teach it around here so I'm trying to learn via asking & google.
Right now I'm just trying to basically figure out how to interface with this speex library so I can at least start using the encode/decode functions. But I am unsure of implementation of those 3 things. I'm sure I'm over my head with this but in the end it seems I always come out on top learning something new. Anyone mind giving me a brief rundown?
From what I take it #define in all practical purposes is basically just foo = bar?And Class:Struct SpeexMode would be a class, that has all of the listed functions?
Or is all of this already defined in the compiled DLL? If so, I've already done a small dll file call with ctypes via a tutorial I ran across. Would it be as simple as setting up the environment (passing these variables into the functions to set things such as codec quality, invoking the encoder, then using the encoder?)
|
[
"To use structs, you indeed should declare them with ctypes.Structure to let Python know about them. \n>>> from ctypes import *\n>>> class POINT(Structure):\n... _fields_ = [(\"x\", c_int),\n... (\"y\", c_int)]\n...\n>>> point = POINT(10, 20)\n>>> print point.x, point.y\n10 20\n>>> point = POINT(y=5)\n>>> print point.x, point.y\n0 5\n>>> POINT(1, 2, 3)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in ?\nValueError: too many initializers\n>>>\n\nAs for defines, they're part of the include file usually, so you'll just have to define them yourself in the Python code, because the C compiler doesn't even see them (defines are converted to their values by the pre-processor).\nIf you're looking for a more automatic converter from C/C++ interfaces to Python, look at SWIG. SWIG, unlike ctypes, requires you to use a C compiler in addition to pure Python.\n",
"I figured out structs at least, and how to basically convert them.\nBasically you just make a class, pass it ctypes.Structure, then make your array of fields.\nlike so:\nclass PASSWD(ctypes.Structure):\n_fields_ = [(\"name\", ctypes.c_char_p),\n (\"passwd\", ctypes.c_char_p),\n (\"uid\", ctypes.c_int),\n (\"gid\", ctypes.c_int),\n (\"change\", ctypes.c_long),\n (\"class\", ctypes.c_char_p),\n (\"gecos\", ctypes.c_char_p),\n (\"dir\", ctypes.c_char_p),\n (\"shell\", ctypes.c_char_p),\n (\"expire\", ctypes.c_long),\n (\"fields\", ctypes.c_int) ]\n\nBut I'm not so sure I even need to set these all up. I'm pretty sure they're all defined in the DLL and setup, no?\n"
] |
[
2,
0
] |
[] |
[] |
[
"api",
"c",
"ctypes",
"python",
"speex"
] |
stackoverflow_0001774383_api_c_ctypes_python_speex.txt
|
Q:
Python 2.6 DB error
I'm trying to get the Yahoo! BOSS package working, but when I try to run the example file I get the following error:
$ python examples/ex5.py
File "examples/ex5.py", line 28
tb = db.group(by=["yn$title"], key="rank", reducer=lambda d1,d2: d1+d2, as="total", table=tb, norm=text.norm)
^
SyntaxError: invalid syntax
This particular error only occurs in Python 2.6. When I attempt to run in Python 2.5, this error does not occur (but it throws other errors because I was haven't installed a number of other supporting packages in 2.5).
Note that all the example files fail on this db.group function, with the carat highlighting "as" in each case.
Is there a 2.6-related change that could be causing this error?
A:
as was a pseudo-keyword in 2.5, it's become a full-fledged keyword in 2.6 -- that's definitely the cause of your problem!
As for the workaround, try adding a **{'as': 'total'} at the end of your call and remove the plain as='total' -- that should work.
|
Python 2.6 DB error
|
I'm trying to get the Yahoo! BOSS package working, but when I try to run the example file I get the following error:
$ python examples/ex5.py
File "examples/ex5.py", line 28
tb = db.group(by=["yn$title"], key="rank", reducer=lambda d1,d2: d1+d2, as="total", table=tb, norm=text.norm)
^
SyntaxError: invalid syntax
This particular error only occurs in Python 2.6. When I attempt to run in Python 2.5, this error does not occur (but it throws other errors because I was haven't installed a number of other supporting packages in 2.5).
Note that all the example files fail on this db.group function, with the carat highlighting "as" in each case.
Is there a 2.6-related change that could be causing this error?
|
[
"as was a pseudo-keyword in 2.5, it's become a full-fledged keyword in 2.6 -- that's definitely the cause of your problem!\nAs for the workaround, try adding a **{'as': 'total'} at the end of your call and remove the plain as='total' -- that should work.\n"
] |
[
1
] |
[] |
[] |
[
"python",
"python_2.6",
"yahoo_boss_api"
] |
stackoverflow_0001774752_python_python_2.6_yahoo_boss_api.txt
|
Q:
Does a exception with just a raise have any use?
For example, here is some code from django.templates.loader.app_directories.py.[1]
try:
yield safe_join(template_dir, template_name)
except UnicodeDecodeError:
# The template dir name was a bytestring that wasn't valid UTF-8.
raise
If you catch an exception just to re raise it, what purpose does it serve?
[1] http://code.djangoproject.com/browser/django/trunk/django/template/loaders/app_directories.py
A:
In the code you linked to is another additional exception handler:
try:
yield safe_join(template_dir, template_name)
except UnicodeDecodeError:
# The template dir name was a bytestring that wasn't valid UTF-8.
raise
except ValueError:
# The joined path was located outside of template_dir.
pass
Since UnicodeDecodeError is a subclass of ValueError, the second exception handler would cause any UnicodeDecodeError to be ignored. It looks like this would not be the intended effect and to avoid it the UnicodeDecodeError is processed explicitly by the first handler. So with both handlers together a ValueError is only ignored if it's not a UnicodeDecodeError.
A:
None at all, that I can think of, except if you're debugging that source code and set a breakpoint on the raise statement.
A:
Strictly speaking, it's unneeded.
Some possibilities:
For documentation purposes - just to make it explicit which exceptions are expected
As a placeholder for a future (or past) more serious handling before re-raising
A:
The most common use is to propagate some one particular exception and handle all the rest. You can find a lot of examples for propagating KeyboardInterrupt and SystemExit (e.g. look at asyncore source): it's convenient for servers to log and continue in case of error in request handler, but you shouldn't catch KeyboardInterrupt to exit on SIGINT.
|
Does a exception with just a raise have any use?
|
For example, here is some code from django.templates.loader.app_directories.py.[1]
try:
yield safe_join(template_dir, template_name)
except UnicodeDecodeError:
# The template dir name was a bytestring that wasn't valid UTF-8.
raise
If you catch an exception just to re raise it, what purpose does it serve?
[1] http://code.djangoproject.com/browser/django/trunk/django/template/loaders/app_directories.py
|
[
"In the code you linked to is another additional exception handler:\ntry:\n yield safe_join(template_dir, template_name)\nexcept UnicodeDecodeError:\n # The template dir name was a bytestring that wasn't valid UTF-8.\n raise\nexcept ValueError:\n # The joined path was located outside of template_dir.\n pass\n\nSince UnicodeDecodeError is a subclass of ValueError, the second exception handler would cause any UnicodeDecodeError to be ignored. It looks like this would not be the intended effect and to avoid it the UnicodeDecodeError is processed explicitly by the first handler. So with both handlers together a ValueError is only ignored if it's not a UnicodeDecodeError.\n",
"None at all, that I can think of, except if you're debugging that source code and set a breakpoint on the raise statement.\n",
"Strictly speaking, it's unneeded. \nSome possibilities:\n\nFor documentation purposes - just to make it explicit which exceptions are expected\nAs a placeholder for a future (or past) more serious handling before re-raising\n\n",
"The most common use is to propagate some one particular exception and handle all the rest. You can find a lot of examples for propagating KeyboardInterrupt and SystemExit (e.g. look at asyncore source): it's convenient for servers to log and continue in case of error in request handler, but you shouldn't catch KeyboardInterrupt to exit on SIGINT.\n"
] |
[
17,
3,
2,
1
] |
[] |
[] |
[
"exception_handling",
"python"
] |
stackoverflow_0001774792_exception_handling_python.txt
|
Q:
Unable to use PIL after installing using pythononmac.org package (Mac OS Leopard)
I'm trying to use PIL for a Google App Engine project. I've installed PIL using the installer from pythononmac.org but it doesn't seem to do anything, or at least neither I nor Python can find the files. I'm running Python 2.5.1.
A:
The installers found on that page were designed to be used with the python 2.5 installer found there. Note that most of the packages are now out-of-date. The PIL installer uses the site-packages library in the framework used by the 2.5 Python on that page and by the more up-to-date python.org installer: /Library/Frameworks/Python.framework/Versions/2.5. The Apple-supplied Python 2.5 (/usr/bin/python2.5 in OS X 10.5) looks for site-packages in a different location: /Library/Python/2.5. If you first install the python.org (or the pythonmac.org) 2.5, that python can be invoked by /usr/local/bin/python2.5 and the PIL installer package should work with it.
Unfortunately, installing PIL on OS X is more complicated than many other python packages because of its dependence on third-party libraries not supplied by Apple in OS X. While it is possible to build it on your own, you may be better off using a more up-to-date version of python with PIL from MacPorts, for example (see packages py25-pil or py26-pil).
I do not recommend using the symlink trick advocated by some bloggers (for instance, here) as this can end up contaminating the Apple-supplied Python and complicating support of multiple Python versions when you want to upgrade to python 2.6 and/or 3.1.
|
Unable to use PIL after installing using pythononmac.org package (Mac OS Leopard)
|
I'm trying to use PIL for a Google App Engine project. I've installed PIL using the installer from pythononmac.org but it doesn't seem to do anything, or at least neither I nor Python can find the files. I'm running Python 2.5.1.
|
[
"The installers found on that page were designed to be used with the python 2.5 installer found there. Note that most of the packages are now out-of-date. The PIL installer uses the site-packages library in the framework used by the 2.5 Python on that page and by the more up-to-date python.org installer: /Library/Frameworks/Python.framework/Versions/2.5. The Apple-supplied Python 2.5 (/usr/bin/python2.5 in OS X 10.5) looks for site-packages in a different location: /Library/Python/2.5. If you first install the python.org (or the pythonmac.org) 2.5, that python can be invoked by /usr/local/bin/python2.5 and the PIL installer package should work with it.\nUnfortunately, installing PIL on OS X is more complicated than many other python packages because of its dependence on third-party libraries not supplied by Apple in OS X. While it is possible to build it on your own, you may be better off using a more up-to-date version of python with PIL from MacPorts, for example (see packages py25-pil or py26-pil). \nI do not recommend using the symlink trick advocated by some bloggers (for instance, here) as this can end up contaminating the Apple-supplied Python and complicating support of multiple Python versions when you want to upgrade to python 2.6 and/or 3.1.\n"
] |
[
3
] |
[] |
[] |
[
"installation",
"macos",
"osx_leopard",
"python",
"python_imaging_library"
] |
stackoverflow_0001774825_installation_macos_osx_leopard_python_python_imaging_library.txt
|
Q:
Python detect USB drive then assign drive letter?
Here is the problem. We have 100s of external 500gb USB drives. Each drive will travel to a new location through the year. What is the best way to automatically detect that a USB drive has been plugged into a Windows system, then assign a Z:\ drive letter? These USB drives will be plugged into lots of different computers so a script like this
import subprocess
diskpart_data = "z-drive.txt"
open (diskpart_data, "w").write ("""
select volume F:
assign letter=Z
""")
subprocess.call ('diskpart /s %s' % diskpart_data)
is hard to use due to the dynamic nature of the mobile USB drive on different Windows systems all the time? Could you autodetect through WMI or do some kind of volume mount with NTFS?
A:
as terabytest said, you may run a script from an autorun.inf in the root of the drive. personally, i would do with a batch script:
(echo select volume %~d0 && echo assign letter=Z) | diskpart
the %~d0 retrieves the drive letter of the currently executing batch file.
if this is not sufficient, there is a way of being informed when a removable drive is inserted by using the device management functions of the Windows API. you have to first register for notification using RegisterDeviceNotification() then process the WM_DEVICECHANGE message in the event loop. unfortunately, this needs an event loop, and i don't know how you can easily create one in python (apart from creating it from scratch: here is an example message loop, note that in your case you should not need to create a window, only have a message loop).
A:
You could try compiling that script to an exe and make an autorun file in the USB key which runs the script. Then the script does its things.
For the assigning the Z:\ letter thing, I'd suggest using Win32Com (even though I don't know if it can handle this) or use ctypes which will give you control on the windows dlls.
|
Python detect USB drive then assign drive letter?
|
Here is the problem. We have 100s of external 500gb USB drives. Each drive will travel to a new location through the year. What is the best way to automatically detect that a USB drive has been plugged into a Windows system, then assign a Z:\ drive letter? These USB drives will be plugged into lots of different computers so a script like this
import subprocess
diskpart_data = "z-drive.txt"
open (diskpart_data, "w").write ("""
select volume F:
assign letter=Z
""")
subprocess.call ('diskpart /s %s' % diskpart_data)
is hard to use due to the dynamic nature of the mobile USB drive on different Windows systems all the time? Could you autodetect through WMI or do some kind of volume mount with NTFS?
|
[
"as terabytest said, you may run a script from an autorun.inf in the root of the drive. personally, i would do with a batch script:\n(echo select volume %~d0 && echo assign letter=Z) | diskpart\n\nthe %~d0 retrieves the drive letter of the currently executing batch file.\nif this is not sufficient, there is a way of being informed when a removable drive is inserted by using the device management functions of the Windows API. you have to first register for notification using RegisterDeviceNotification() then process the WM_DEVICECHANGE message in the event loop. unfortunately, this needs an event loop, and i don't know how you can easily create one in python (apart from creating it from scratch: here is an example message loop, note that in your case you should not need to create a window, only have a message loop).\n",
"You could try compiling that script to an exe and make an autorun file in the USB key which runs the script. Then the script does its things.\nFor the assigning the Z:\\ letter thing, I'd suggest using Win32Com (even though I don't know if it can handle this) or use ctypes which will give you control on the windows dlls.\n"
] |
[
2,
1
] |
[] |
[] |
[
"python",
"windows"
] |
stackoverflow_0001771200_python_windows.txt
|
Q:
Can this be made more pythonic?
I came across this (really) simple program a while ago. It just outputs the first x primes. I'm embarrassed to ask, is there any way to make it more "pythonic" ie condense it while making it (more) readable? Switching functions is fine; I'm only interested in readability.
Thanks
from math import sqrt
def isprime(n):
if n ==2:
return True
if n % 2 ==0 : # evens
return False
max = int(sqrt(n))+1 #only need to search up to sqrt n
i=3
while i <= max: # range starts with 3 and for odd i
if n % i == 0:
return False
i+=2
return True
reqprimes = int(input('how many primes: '))
primessofar = 0
currentnumber = 2
while primessofar < reqprimes:
result = isprime(currentnumber)
if result:
primessofar+=1
print currentnumber
#print '\n'
currentnumber += 1
A:
Your algorithm itself may be implemented pythonically, but it's often useful to re-write algorithms in a functional way - You might end up with a completely different but more readable solution at all (which is even more pythonic).
def primes(upper):
n = 2; found = []
while n < upper:
# If a number is not divisble through all preceding primes, it's prime
if all(n % div != 0 for div in found):
yield n
found.append( n )
n += 1
Usage:
for pr in primes(1000):
print pr
Or, with Alasdair's comment taken into account, a more efficient version:
from math import sqrt
from itertools import takewhile
def primes(upper):
n = 2; foundPrimes = []
while n < upper:
sqrtN = int(sqrt(n))
# If a number n is not divisble through all preceding primes up to sqrt(n), it's prime
if all(n % div != 0 for div in takewhile(lambda div: div <= sqrtN, foundPrimes)):
yield n
foundPrimes.append(n)
n += 1
A:
The given code is not very efficient. Alternative solution (just as inefficient):†
>>> from math import sqrt
>>> def is_prime(n):
... return all(n % d for d in range(2, int(sqrt(n)) + 1))
...
>>> def primes_up_to(n):
... return filter(is_prime, range(2, n))
...
>>> list(primes_up_to(20))
[2, 3, 5, 7, 11, 13, 17, 19]
This code uses all, range, int, math.sqrt, filter and list. It is not completely identical to your code, as it prints primes up to a certain number, not exactly n primes. For that, you can do:
>>> from itertools import count, islice
>>> def n_primes(n):
... return islice(filter(is_prime, count(2)), n)
...
>>> list(n_primes(10))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
That introduces another two functions, namely itertools.count and itertools.islice. (That last piece of code works only in Python 3.x; in Python 2.x, use itertools.ifilter instead of filter.)
†: A more efficient method is to use the Sieve of Eratosthenes.
A:
A few minor things from the style guide.
Uses four spaces, not two. (Personally I prefer tabs, but that's not the Pythonic way.)
Fewer blank lines.
Consistent whitespace: n ==2: => n == 2:
Use underscores in your variables names: currentnumber => current_number
A:
Firstly, you should not assign max to a variable as it is an inbuilt function used to find the maximum value from an iterable. Also, that entire section of code can instead be written as
for i in xrange(3, int(sqrt(n))+1, 2):
if n%i==0: return False
Also, instead of defining a new variable result and putting the value returned by isprime into it, you can just directly do
if isprime(currentnumber):
A:
I recently found Project Euler solutions in functional python and it has some really nice examples of working with primes like this. Number 7 is pretty close to your problem:
def isprime(n):
"""Return True if n is a prime number"""
if n < 3:
return (n == 2)
elif n % 2 == 0:
return False
elif any(((n % x) == 0) for x in xrange(3, int(sqrt(n))+1, 2)):
return False
return True
def primes(start=2):
"""Generate prime numbers from 'start'"""
return ifilter(isprime, count(start))
A:
Usually you don't use while loops for simple things like this. You rather create a range object and get the elements from there. So you could rewrite the first loop to this for example:
for i in range( 3, int( sqrt( n ) ) + 1, 2 ):
if n % i == 0:
return False
And it would be a lot better if you would cache your prime numbers and only check the previous prime numbers when checking a new number. You can save a lot time by that (and easily calculate larger prime numbers this way). Here is some code I wrote before to get all prime numbers up to n easily:
def primeNumbers ( end ):
primes = []
primes.append( 2 )
for i in range( 3, end, 2 ):
isPrime = True
for j in primes:
if i % j == 0:
isPrime = False
break
if isPrime:
primes.append( i )
return primes
print primeNumbers( 20 )
A:
You can make it more pythonic with sieve algorithm (all primes small than 100):
def primes(n):
sieved = set()
for i in range(2, n):
if not(i in sieved):
for j in range(i + i, n, i):
sieved.add(j)
return set(range(2, n)) - sieved
print primes(100)
A very small trick will turn it to your goal.
A:
Translated from the brilliant guys at stacktrace.it (Daniele Varrazzo, specifically), this version takes advantage of a binary min-heap to solve this problem:
from heapq import heappush, heapreplace
def yield_primes():
"""Endless prime number generator."""
# Yield 2, so we don't have to handle the empty heap special case
yield 2
# Heap of (non-prime, prime factor) tuples.
todel = [ (4, 2) ]
n = 3
while True:
if todel[0][0] != n:
# This number is not on the head of the heap: prime!
yield n
heappush(todel, (n*n, n)) # add to heap
else:
# Not prime: add to heap
while todel[0][0] == n:
p = todel[0][1]
heapreplace(todel, (n+p, p))
# heapreplace pops the minimum value then pushes:
# heap size is unchanged
n += 1
This code isn't mine and I don't understand it fully (but the explaination is here :) ), so I'm marking this answer as community wiki.
|
Can this be made more pythonic?
|
I came across this (really) simple program a while ago. It just outputs the first x primes. I'm embarrassed to ask, is there any way to make it more "pythonic" ie condense it while making it (more) readable? Switching functions is fine; I'm only interested in readability.
Thanks
from math import sqrt
def isprime(n):
if n ==2:
return True
if n % 2 ==0 : # evens
return False
max = int(sqrt(n))+1 #only need to search up to sqrt n
i=3
while i <= max: # range starts with 3 and for odd i
if n % i == 0:
return False
i+=2
return True
reqprimes = int(input('how many primes: '))
primessofar = 0
currentnumber = 2
while primessofar < reqprimes:
result = isprime(currentnumber)
if result:
primessofar+=1
print currentnumber
#print '\n'
currentnumber += 1
|
[
"Your algorithm itself may be implemented pythonically, but it's often useful to re-write algorithms in a functional way - You might end up with a completely different but more readable solution at all (which is even more pythonic).\ndef primes(upper):\n n = 2; found = []\n while n < upper:\n # If a number is not divisble through all preceding primes, it's prime\n if all(n % div != 0 for div in found):\n yield n\n found.append( n )\n n += 1\n\nUsage:\nfor pr in primes(1000):\n print pr\n\nOr, with Alasdair's comment taken into account, a more efficient version:\nfrom math import sqrt\nfrom itertools import takewhile\n\ndef primes(upper):\n n = 2; foundPrimes = []\n while n < upper:\n sqrtN = int(sqrt(n))\n # If a number n is not divisble through all preceding primes up to sqrt(n), it's prime\n if all(n % div != 0 for div in takewhile(lambda div: div <= sqrtN, foundPrimes)):\n yield n\n foundPrimes.append(n)\n n += 1\n\n",
"The given code is not very efficient. Alternative solution (just as inefficient):†\n>>> from math import sqrt\n>>> def is_prime(n):\n... return all(n % d for d in range(2, int(sqrt(n)) + 1))\n... \n>>> def primes_up_to(n):\n... return filter(is_prime, range(2, n))\n... \n>>> list(primes_up_to(20))\n[2, 3, 5, 7, 11, 13, 17, 19]\n\nThis code uses all, range, int, math.sqrt, filter and list. It is not completely identical to your code, as it prints primes up to a certain number, not exactly n primes. For that, you can do:\n>>> from itertools import count, islice\n>>> def n_primes(n):\n... return islice(filter(is_prime, count(2)), n)\n... \n>>> list(n_primes(10))\n[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]\n\nThat introduces another two functions, namely itertools.count and itertools.islice. (That last piece of code works only in Python 3.x; in Python 2.x, use itertools.ifilter instead of filter.)\n\n †: A more efficient method is to use the Sieve of Eratosthenes.\n",
"A few minor things from the style guide.\n\nUses four spaces, not two. (Personally I prefer tabs, but that's not the Pythonic way.)\nFewer blank lines.\nConsistent whitespace: n ==2: => n == 2:\nUse underscores in your variables names: currentnumber => current_number\n",
"Firstly, you should not assign max to a variable as it is an inbuilt function used to find the maximum value from an iterable. Also, that entire section of code can instead be written as\nfor i in xrange(3, int(sqrt(n))+1, 2):\n if n%i==0: return False\n\nAlso, instead of defining a new variable result and putting the value returned by isprime into it, you can just directly do\nif isprime(currentnumber):\n\n",
"I recently found Project Euler solutions in functional python and it has some really nice examples of working with primes like this. Number 7 is pretty close to your problem:\ndef isprime(n):\n \"\"\"Return True if n is a prime number\"\"\"\n if n < 3:\n return (n == 2)\n elif n % 2 == 0:\n return False\n elif any(((n % x) == 0) for x in xrange(3, int(sqrt(n))+1, 2)):\n return False\n return True\n\ndef primes(start=2):\n \"\"\"Generate prime numbers from 'start'\"\"\"\n return ifilter(isprime, count(start))\n\n",
"Usually you don't use while loops for simple things like this. You rather create a range object and get the elements from there. So you could rewrite the first loop to this for example:\n\nfor i in range( 3, int( sqrt( n ) ) + 1, 2 ):\n if n % i == 0:\n return False\n\nAnd it would be a lot better if you would cache your prime numbers and only check the previous prime numbers when checking a new number. You can save a lot time by that (and easily calculate larger prime numbers this way). Here is some code I wrote before to get all prime numbers up to n easily:\n\ndef primeNumbers ( end ):\n primes = []\n primes.append( 2 )\n\n for i in range( 3, end, 2 ):\n isPrime = True\n\n for j in primes:\n if i % j == 0:\n isPrime = False\n break\n\n if isPrime:\n primes.append( i )\n\n return primes\n\nprint primeNumbers( 20 )\n\n",
"You can make it more pythonic with sieve algorithm (all primes small than 100):\ndef primes(n):\n sieved = set()\n for i in range(2, n):\n if not(i in sieved):\n for j in range(i + i, n, i):\n sieved.add(j)\n return set(range(2, n)) - sieved\n\nprint primes(100)\n\nA very small trick will turn it to your goal.\n",
"Translated from the brilliant guys at stacktrace.it (Daniele Varrazzo, specifically), this version takes advantage of a binary min-heap to solve this problem:\nfrom heapq import heappush, heapreplace\n\ndef yield_primes():\n \"\"\"Endless prime number generator.\"\"\"\n\n # Yield 2, so we don't have to handle the empty heap special case\n yield 2\n\n # Heap of (non-prime, prime factor) tuples.\n todel = [ (4, 2) ]\n\n n = 3\n while True:\n if todel[0][0] != n:\n # This number is not on the head of the heap: prime!\n yield n\n heappush(todel, (n*n, n)) # add to heap\n\n else:\n # Not prime: add to heap\n while todel[0][0] == n:\n p = todel[0][1]\n heapreplace(todel, (n+p, p))\n # heapreplace pops the minimum value then pushes: \n # heap size is unchanged\n\n n += 1\n\nThis code isn't mine and I don't understand it fully (but the explaination is here :) ), so I'm marking this answer as community wiki.\n"
] |
[
7,
6,
5,
2,
2,
1,
1,
1
] |
[] |
[] |
[
"primes",
"python"
] |
stackoverflow_0001775459_primes_python.txt
|
Q:
Continuously redraw wxPython element
I have a chat client that continuously polls a server and fetches new messages.
From my def __init__() I have:
wx.CallAfter(self.pollServer)
Which is defined:
def pollServer(self):
t = self.updateMessages()
time.sleep(5)
self.pollServer()
Now printing the messages into the Terminal shows that it works but the GUI is 'frozen' instead of being continuously refreshed and I thought CallAfter takes care of that. Could you help?
A:
instead of
time.sleep(5)
self.pollServer()
try with
wx.CallLater(5,self.pollServer)
|
Continuously redraw wxPython element
|
I have a chat client that continuously polls a server and fetches new messages.
From my def __init__() I have:
wx.CallAfter(self.pollServer)
Which is defined:
def pollServer(self):
t = self.updateMessages()
time.sleep(5)
self.pollServer()
Now printing the messages into the Terminal shows that it works but the GUI is 'frozen' instead of being continuously refreshed and I thought CallAfter takes care of that. Could you help?
|
[
"instead of \ntime.sleep(5)\nself.pollServer()\n\ntry with\nwx.CallLater(5,self.pollServer)\n\n"
] |
[
2
] |
[] |
[] |
[
"python",
"refresh",
"timer",
"wxpython"
] |
stackoverflow_0001775921_python_refresh_timer_wxpython.txt
|
Q:
python reload function and syntactically incorrect module
What happens when I reload a module in python and the new code for the module is syntactically incorrect? The reload(module) function doesn't seem to be throwing any exception. Is there any way to determine if the reload was successful or failed?
A:
The reload() command should raise a SyntaxError:
In [34]: import test
# This works fine
After making a syntax error in test.py: (changed import --> pimport)
In [35]: reload(test)
------------------------------------------------------------
File "/home/unutbu/pybin/test.py", line 2
pimport itertools
^
SyntaxError: invalid syntax
|
python reload function and syntactically incorrect module
|
What happens when I reload a module in python and the new code for the module is syntactically incorrect? The reload(module) function doesn't seem to be throwing any exception. Is there any way to determine if the reload was successful or failed?
|
[
"The reload() command should raise a SyntaxError:\nIn [34]: import test\n# This works fine\n\nAfter making a syntax error in test.py: (changed import --> pimport)\nIn [35]: reload(test)\n------------------------------------------------------------\n File \"/home/unutbu/pybin/test.py\", line 2\n pimport itertools\n ^\nSyntaxError: invalid syntax\n\n"
] |
[
3
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001776153_python.txt
|
Q:
Select statement with SqlAlchemy
Yes, very basic question.
I've successfully created my db using declarative_base, and can perform inserts into the db too. I just have a few questions about SqlAlchemy sql statements.
I've create a table called Location.
A few issues/questions (see code below):
For statement, "print row", I have to specify each column name that I want to have output. i.e. "print row.name, row.lat, etc" Why? (Otherwise the print statement outputs "<classname.Location at <...>>"
Also, what is the preferred way to interact with a db and perform queries (select, insert, update, etc.)- there seem to be a bunch of options: using sqlalchemy.orm.select for example, or engine.text(<sql query>).execute().fetchall(), or even conn.execute(<select>). Options are great, but right now they're all just confusing me.
Thanks so much for the tips!
Here's my code:
from sqlalchemy import create_engine
from sqlalchemy.sql import select
from location_db_setup import *
db_path = "sqlite:////volumes/users/shared/programming/python/web/map.db"
engine = create_engine(db_path, echo= True)
Session = sessionmaker(bind= engine)
session = Session()
session.query(Location).fetchall()
for row in locations:
print row
A:
You code in sample is incomplete and has errors. So it's impossible to say for sure what is Location here. I assume it's a mapped class, so you are requesting a list of all Location objects, not rows. When you print an object you get its string representation. String representation of objects can be changed by defining custom __str__ method.
Although ORM is the most important part of SQLAlchemy, it's not the only. It also expose a lot of functionality not related to ORM directly. When you work with objects the preferred way to create queries are corresponding session method. But sometimes you need selectable objects not bound to particular session (they are not executed directly, but are used in expressions passed to session methods). That's why there are functions in sqlalchemy.orm package.
A:
The preferred way to interact with a db when using an ORM is not to use queries but to use objects that correspond to the tables you are manipulating, typically in conjunction with the session object. SELECT queries become get() or find() calls in some ORMs, query() calls in others. INSERT becomes creating a new object of the type you want (and maybe explicitly adding it, eg session.add() in sqlalchemy). UPDATE becomes editing such an object, and DELETE becomes deleting an object (eg. session.delete() ). The ORM is meant to handle the hard work of translating these operations into SQL for you.
Have you read the tutorial?
A:
Denis and Kylotan gave you good answers. I'm just gonna focus on point 2.
Sometimes depends on your taste. There are times when you need database specific features that an ORM can't do, that's a case when you should use Session(<sql here>).execute() or conn.execute(<sql here>). Another case is when you have a very complex query which is beyond you and you don't find a suitable ORM expression.
Usually, using ORM features like select([...]).where(... or Session.query(<Model here>).filter(... (declarative base) are enough. Almost every sql query has an ORM equivalent.
|
Select statement with SqlAlchemy
|
Yes, very basic question.
I've successfully created my db using declarative_base, and can perform inserts into the db too. I just have a few questions about SqlAlchemy sql statements.
I've create a table called Location.
A few issues/questions (see code below):
For statement, "print row", I have to specify each column name that I want to have output. i.e. "print row.name, row.lat, etc" Why? (Otherwise the print statement outputs "<classname.Location at <...>>"
Also, what is the preferred way to interact with a db and perform queries (select, insert, update, etc.)- there seem to be a bunch of options: using sqlalchemy.orm.select for example, or engine.text(<sql query>).execute().fetchall(), or even conn.execute(<select>). Options are great, but right now they're all just confusing me.
Thanks so much for the tips!
Here's my code:
from sqlalchemy import create_engine
from sqlalchemy.sql import select
from location_db_setup import *
db_path = "sqlite:////volumes/users/shared/programming/python/web/map.db"
engine = create_engine(db_path, echo= True)
Session = sessionmaker(bind= engine)
session = Session()
session.query(Location).fetchall()
for row in locations:
print row
|
[
"\nYou code in sample is incomplete and has errors. So it's impossible to say for sure what is Location here. I assume it's a mapped class, so you are requesting a list of all Location objects, not rows. When you print an object you get its string representation. String representation of objects can be changed by defining custom __str__ method.\nAlthough ORM is the most important part of SQLAlchemy, it's not the only. It also expose a lot of functionality not related to ORM directly. When you work with objects the preferred way to create queries are corresponding session method. But sometimes you need selectable objects not bound to particular session (they are not executed directly, but are used in expressions passed to session methods). That's why there are functions in sqlalchemy.orm package.\n\n",
"The preferred way to interact with a db when using an ORM is not to use queries but to use objects that correspond to the tables you are manipulating, typically in conjunction with the session object. SELECT queries become get() or find() calls in some ORMs, query() calls in others. INSERT becomes creating a new object of the type you want (and maybe explicitly adding it, eg session.add() in sqlalchemy). UPDATE becomes editing such an object, and DELETE becomes deleting an object (eg. session.delete() ). The ORM is meant to handle the hard work of translating these operations into SQL for you.\nHave you read the tutorial?\n",
"Denis and Kylotan gave you good answers. I'm just gonna focus on point 2.\nSometimes depends on your taste. There are times when you need database specific features that an ORM can't do, that's a case when you should use Session(<sql here>).execute() or conn.execute(<sql here>). Another case is when you have a very complex query which is beyond you and you don't find a suitable ORM expression. \nUsually, using ORM features like select([...]).where(... or Session.query(<Model here>).filter(... (declarative base) are enough. Almost every sql query has an ORM equivalent.\n"
] |
[
2,
1,
1
] |
[] |
[] |
[
"orm",
"python",
"sqlalchemy"
] |
stackoverflow_0001761194_orm_python_sqlalchemy.txt
|
Q:
Strategies for debugging numerical stability issues?
I'm trying to write an implementation of Wilson's spectral density factorization algorithm [1] for Python. The algorithm iteratively factorizes a [QxQ] matrix function into its square root (it's sort of an extension of the Newton-Raphson square-root finder for spectral density matrices).
The problem is that my implementation only converges for matrices of size 45x45 and smaller. So after 20 iterations, the summed squared difference between matrices is about 2.45e-13. However, if I make an input of size 46x46, it does not converge until the 100th or so iteration. For 47x47 or larger, the matrices never converge; the error fluctuates between 100 and 1000 for about 100 iterations, and then starts to grow very quickly.
How would you go about trying to debug something like this? There doesn't appear to be any specific point at which it goes crazy, and the matrices are too large for me to actually attempt to do the calculation by hand. Does anyone have tips / tutorials / heuristics for find bizarre numerical bugs like this?
I've never dealt with anything like this before but I'm hoping some of you have...
Thanks,
- Dan
[1] G. T. Wilson. "The Factorization of Matricial Spectral Densities". SIAM J. Appl. Math (Vol 23, No. 4, Dec. 1972)
A:
I would recommend asking this question on the scipy-user mailing list, perhaps with an example of your code. Generally the people on the list seem to be highly experienced with numerical computation and are really helpful, just following the list is an education in itself.
Otherwise, I'm afraid I don't have any ideas... If you think it is a numerical precision/floating point rounding issue, the first thing you could try is bump all the dtypes up to float128 and see if makes any difference.
A:
Interval arithmetic can help, but I'm not sure if performance will be sufficient to actually allow meaningful debugging at the matrix sizes of your interest (you have to figure on a couple orders of magnitude worth of slowdown, what between replacing highly-HW-helped "scalar" floating point operations with SW-heavy "interval" ones, and adding the checks about which intervals are growing too wide, when, where, and why).
|
Strategies for debugging numerical stability issues?
|
I'm trying to write an implementation of Wilson's spectral density factorization algorithm [1] for Python. The algorithm iteratively factorizes a [QxQ] matrix function into its square root (it's sort of an extension of the Newton-Raphson square-root finder for spectral density matrices).
The problem is that my implementation only converges for matrices of size 45x45 and smaller. So after 20 iterations, the summed squared difference between matrices is about 2.45e-13. However, if I make an input of size 46x46, it does not converge until the 100th or so iteration. For 47x47 or larger, the matrices never converge; the error fluctuates between 100 and 1000 for about 100 iterations, and then starts to grow very quickly.
How would you go about trying to debug something like this? There doesn't appear to be any specific point at which it goes crazy, and the matrices are too large for me to actually attempt to do the calculation by hand. Does anyone have tips / tutorials / heuristics for find bizarre numerical bugs like this?
I've never dealt with anything like this before but I'm hoping some of you have...
Thanks,
- Dan
[1] G. T. Wilson. "The Factorization of Matricial Spectral Densities". SIAM J. Appl. Math (Vol 23, No. 4, Dec. 1972)
|
[
"I would recommend asking this question on the scipy-user mailing list, perhaps with an example of your code. Generally the people on the list seem to be highly experienced with numerical computation and are really helpful, just following the list is an education in itself.\nOtherwise, I'm afraid I don't have any ideas... If you think it is a numerical precision/floating point rounding issue, the first thing you could try is bump all the dtypes up to float128 and see if makes any difference. \n",
"Interval arithmetic can help, but I'm not sure if performance will be sufficient to actually allow meaningful debugging at the matrix sizes of your interest (you have to figure on a couple orders of magnitude worth of slowdown, what between replacing highly-HW-helped \"scalar\" floating point operations with SW-heavy \"interval\" ones, and adding the checks about which intervals are growing too wide, when, where, and why).\n"
] |
[
4,
2
] |
[] |
[] |
[
"matrix",
"numerical_stability",
"python",
"scipy",
"spectral_density"
] |
stackoverflow_0001776409_matrix_numerical_stability_python_scipy_spectral_density.txt
|
Q:
Python plugin in netbeans manually
Can install python plugin in netbeans 6.7 manually (without Tools/Plugin) ?
if yes (with .nbi package ) which url can use ?
A:
find one Netbeans that downloaded python plug-in and go to Netbeans folder and copy python folder. In computer that need to install python plug-in copy that folder in Netbeans root folder and go to Tools/Plugin and activate python .
|
Python plugin in netbeans manually
|
Can install python plugin in netbeans 6.7 manually (without Tools/Plugin) ?
if yes (with .nbi package ) which url can use ?
|
[
"find one Netbeans that downloaded python plug-in and go to Netbeans folder and copy python folder. In computer that need to install python plug-in copy that folder in Netbeans root folder and go to Tools/Plugin and activate python . \n"
] |
[
0
] |
[] |
[] |
[
"netbeans",
"netbeans6.7",
"netbeans_plugins",
"python"
] |
stackoverflow_0001163531_netbeans_netbeans6.7_netbeans_plugins_python.txt
|
Q:
Accessing Facebook Connect FBML cookie via PyFacebook?
Is it possible, having logged in via a Facebook Connect FBML button, to retrieve and use the session details via PyFacebook? Can i use auth.getSession() in the same way as if I'd fired the login via Python?
Basically I'm trying to work out if it's possible to replace the stages up to and including raw_input() in the example below:
import facebook
API_KEY = 'xxx'
SECRET_KEY = 'xxx'
facebook = facebook.Facebook(API_KEY, SECRET_KEY)
facebook.auth.createToken()
facebook.login()
# Login to the window, then press enter
print 'After logging in, press enter...'
raw_input()
# This is where FBML button should get me
facebook.auth.getSession()
print 'Session Key: ', facebook.session_key
print 'Your UID: ', facebook.uid
A:
Using the Verifying the Facebook User page on the developer wiki I tracked down the PyFacebook getSession, validate_signature and getLoggedInUser methods and along with the code found in PyFacebook's example.py for Django:
if 'session_key' in request.session and 'uid' in request.session:
fb.session_key = request.session['session_key']
fb.uid = request.session['uid']
else:
try:
fb.auth_token = request.GET['auth_token']
except KeyError:
# Send user to the Facebook to login
return HttpResponseRedirect(fb.get_login_url())
# getSession sets the session_key and uid
# Store these in the cookie so we don't have to get them again
fb.auth.getSession()
request.session['session_key'] = fb.session_key
request.session['uid'] = fb.uid
Got the following quick test for Zope3 working using the FBML button:
import facebook
API_KEY = 'your_api_key'
SECRET_KEY = 'your_secret_key'
fb = odb.facebook.Facebook(API_KEY, SECRET_KEY)
fb_uid = self.request[API_KEY+'_user']
fb_session_key = self.request[API_KEY+'_session_key']
fb_ss = self.request[API_KEY+'_ss']
fb_signature = self.request[API_KEY] #no suffix for signature
fb.session_key = fb_session_key
fb.uid = fb_uid
fb.friends.get() # Results in list of friends
A:
I'm not sure if this answers your question and, admittedly, I might be leading you astray because I'm new at this (just rolled my own facebook auth backend using pyfacebook about 30 minutes ago):
First, I installed the pyfacebook middleware (letting me call request.facebook in any view):
'facebook.djangofb.FacebookMiddleware'
Then, I setup a view with a facebook connect button and the appropriate settings for it to redirect where I need it to upon authorization completion.
In my facebook connect login done view, I authenticate to facebook with the facebook connect cookies by passing the request variable to request.facebook.check_session(). If it returns True, the object is ready to be used to retrieve data.
def myview(request):
fb = request.facebook
ready_to_rock = fb.check_session(request)
if ready_to_rock:
user_info = fb.users.getInfo([fb.uid],['first_name','last_name'])
|
Accessing Facebook Connect FBML cookie via PyFacebook?
|
Is it possible, having logged in via a Facebook Connect FBML button, to retrieve and use the session details via PyFacebook? Can i use auth.getSession() in the same way as if I'd fired the login via Python?
Basically I'm trying to work out if it's possible to replace the stages up to and including raw_input() in the example below:
import facebook
API_KEY = 'xxx'
SECRET_KEY = 'xxx'
facebook = facebook.Facebook(API_KEY, SECRET_KEY)
facebook.auth.createToken()
facebook.login()
# Login to the window, then press enter
print 'After logging in, press enter...'
raw_input()
# This is where FBML button should get me
facebook.auth.getSession()
print 'Session Key: ', facebook.session_key
print 'Your UID: ', facebook.uid
|
[
"Using the Verifying the Facebook User page on the developer wiki I tracked down the PyFacebook getSession, validate_signature and getLoggedInUser methods and along with the code found in PyFacebook's example.py for Django:\nif 'session_key' in request.session and 'uid' in request.session:\n fb.session_key = request.session['session_key']\n fb.uid = request.session['uid']\nelse:\n\n try:\n fb.auth_token = request.GET['auth_token']\n except KeyError:\n # Send user to the Facebook to login\n return HttpResponseRedirect(fb.get_login_url())\n\n # getSession sets the session_key and uid\n # Store these in the cookie so we don't have to get them again\n fb.auth.getSession()\n request.session['session_key'] = fb.session_key\n request.session['uid'] = fb.uid\n\nGot the following quick test for Zope3 working using the FBML button:\nimport facebook\n\nAPI_KEY = 'your_api_key'\nSECRET_KEY = 'your_secret_key'\n\nfb = odb.facebook.Facebook(API_KEY, SECRET_KEY)\n\nfb_uid = self.request[API_KEY+'_user']\nfb_session_key = self.request[API_KEY+'_session_key']\nfb_ss = self.request[API_KEY+'_ss']\nfb_signature = self.request[API_KEY] #no suffix for signature\n\nfb.session_key = fb_session_key\nfb.uid = fb_uid\n\nfb.friends.get() # Results in list of friends\n\n",
"I'm not sure if this answers your question and, admittedly, I might be leading you astray because I'm new at this (just rolled my own facebook auth backend using pyfacebook about 30 minutes ago):\nFirst, I installed the pyfacebook middleware (letting me call request.facebook in any view):\n'facebook.djangofb.FacebookMiddleware'\n\nThen, I setup a view with a facebook connect button and the appropriate settings for it to redirect where I need it to upon authorization completion.\nIn my facebook connect login done view, I authenticate to facebook with the facebook connect cookies by passing the request variable to request.facebook.check_session(). If it returns True, the object is ready to be used to retrieve data.\ndef myview(request): \n fb = request.facebook \n ready_to_rock = fb.check_session(request)\n if ready_to_rock:\n user_info = fb.users.getInfo([fb.uid],['first_name','last_name'])\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"cookies",
"facebook",
"python"
] |
stackoverflow_0001613772_cookies_facebook_python.txt
|
Q:
How can a python base class tell whether a sub class has overridden its methods?
Here is my guess, which doesn't work:
class BaseClass(object):
def foo(self):
return 'foo'
def bar(self):
return 'bar'
def methods_implemented(self):
"""This doesn't work..."""
overriden = []
for method in ('foo', 'bar'):
this_method = getattr(self, method)
base_method = getattr(BaseClass, method)
if this_method is not base_method:
overriden.append(method)
return overriden
class SubClass(BaseClass):
def foo(self):
return 'override foo'
o = SubClass()
o.methods_implemented()
Ideally, methods_implemented() would return ['foo'].
How?
(Why would I want to do this? My base class is an HTTP Resource class which has methods GET, POST etc. By default they return 405 Method Not Implemented. It also has a method OPTIONS which should return a 200 response with the header Allow set to the methods which any subclass implements.)
A:
Perhaps this?
>>> class BaseClass(object):
... def foo(self):
... return 'foo'
... def bar(self):
... return 'bar'
... def methods_implemented(self):
... """This does work."""
... overriden = []
... for method in ('foo', 'bar'):
... this_method = getattr(self, method)
... base_method = getattr(BaseClass, method)
... if this_method.__func__ is not base_method.__func__:
... overriden.append(method)
... return overriden
...
>>> class SubClass(BaseClass):
... def foo(self):
... return 'override foo'
...
>>> o = SubClass()
>>> o.methods_implemented()
['foo']
This checks whether the function objects behind the bound methods are the same.
Note, prior to Python 2.6, the __func__ attribute was named im_func.
A:
The methods, even though calling the same object, are NOT the same object. You must test to see if the functions wrapped in the unbound method are the same object.
I'm using 2.6 over here, so I also changed the class to inherit from object.
>>> class BaseClass(object):
... def foo(self):
... return 'foo'
... def bar(self):
... return 'bar'
... def methods_implemented(self):
... """This doesn't work..."""
... overriden = []
... for method in ('foo', 'bar'):
... this_method = getattr(self, method).__func__
... base_method = getattr(BaseClass, method).__func__
... if this_method is base_method:
... overriden.append(method)
... return overriden
...
>>> class SubClass(BaseClass):
... def foo(self):
... return 'override foo'
...
>>> o = SubClass()
>>> o.methods_implemented()
['bar']
|
How can a python base class tell whether a sub class has overridden its methods?
|
Here is my guess, which doesn't work:
class BaseClass(object):
def foo(self):
return 'foo'
def bar(self):
return 'bar'
def methods_implemented(self):
"""This doesn't work..."""
overriden = []
for method in ('foo', 'bar'):
this_method = getattr(self, method)
base_method = getattr(BaseClass, method)
if this_method is not base_method:
overriden.append(method)
return overriden
class SubClass(BaseClass):
def foo(self):
return 'override foo'
o = SubClass()
o.methods_implemented()
Ideally, methods_implemented() would return ['foo'].
How?
(Why would I want to do this? My base class is an HTTP Resource class which has methods GET, POST etc. By default they return 405 Method Not Implemented. It also has a method OPTIONS which should return a 200 response with the header Allow set to the methods which any subclass implements.)
|
[
"Perhaps this?\n>>> class BaseClass(object):\n... def foo(self):\n... return 'foo'\n... def bar(self):\n... return 'bar'\n... def methods_implemented(self):\n... \"\"\"This does work.\"\"\"\n... overriden = []\n... for method in ('foo', 'bar'):\n... this_method = getattr(self, method)\n... base_method = getattr(BaseClass, method)\n... if this_method.__func__ is not base_method.__func__:\n... overriden.append(method)\n... return overriden\n... \n>>> class SubClass(BaseClass):\n... def foo(self):\n... return 'override foo'\n... \n>>> o = SubClass()\n>>> o.methods_implemented()\n['foo']\n\nThis checks whether the function objects behind the bound methods are the same.\nNote, prior to Python 2.6, the __func__ attribute was named im_func.\n",
"The methods, even though calling the same object, are NOT the same object. You must test to see if the functions wrapped in the unbound method are the same object.\nI'm using 2.6 over here, so I also changed the class to inherit from object.\n>>> class BaseClass(object):\n... def foo(self):\n... return 'foo'\n... def bar(self):\n... return 'bar'\n... def methods_implemented(self):\n... \"\"\"This doesn't work...\"\"\"\n... overriden = []\n... for method in ('foo', 'bar'):\n... this_method = getattr(self, method).__func__\n... base_method = getattr(BaseClass, method).__func__\n... if this_method is base_method:\n... overriden.append(method)\n... return overriden\n... \n>>> class SubClass(BaseClass):\n... def foo(self):\n... return 'override foo'\n... \n>>> o = SubClass()\n>>> o.methods_implemented()\n['bar']\n\n"
] |
[
11,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001776994_python.txt
|
Q:
How to auto log into gmail atom feed with Python?
Gmail has this sweet thing going on to get an atom feed:
def gmail_url(user, pwd):
return "https://"+str(user)+":"+str(pwd)+"@gmail.google.com/gmail/feed/atom"
Now when you do this in a browser, it authenticates and forwards you. But in Python, at least what I'm trying, isn't working right.
url = gmail_url(settings.USER, settings.PASS)
print url
opener = urllib.FancyURLopener()
f = opener.open(url)
print f.read()
Instead of forwarding correctly, it's doing this:
>>>
https://user:pass@gmail.google.com/gmail/feed/atom
Enter username for New mail feed at mail.google.com:
This is BAD! I shouldn't have to type in the username and password again!! How can I make it just auto-forward in python as it does in my web browser, so I can get the feed contents without all the BS?
A:
You can use the HTTPBasicAuthHandler, I tried the following and it worked:
import urllib2
def get_unread_msgs(user, passwd):
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(
realm='New mail feed',
uri='https://mail.google.com',
user='%s@gmail.com' % user,
passwd=passwd
)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
feed = urllib2.urlopen('https://mail.google.com/mail/feed/atom')
return feed.read()
|
How to auto log into gmail atom feed with Python?
|
Gmail has this sweet thing going on to get an atom feed:
def gmail_url(user, pwd):
return "https://"+str(user)+":"+str(pwd)+"@gmail.google.com/gmail/feed/atom"
Now when you do this in a browser, it authenticates and forwards you. But in Python, at least what I'm trying, isn't working right.
url = gmail_url(settings.USER, settings.PASS)
print url
opener = urllib.FancyURLopener()
f = opener.open(url)
print f.read()
Instead of forwarding correctly, it's doing this:
>>>
https://user:pass@gmail.google.com/gmail/feed/atom
Enter username for New mail feed at mail.google.com:
This is BAD! I shouldn't have to type in the username and password again!! How can I make it just auto-forward in python as it does in my web browser, so I can get the feed contents without all the BS?
|
[
"You can use the HTTPBasicAuthHandler, I tried the following and it worked:\nimport urllib2\n\ndef get_unread_msgs(user, passwd):\n auth_handler = urllib2.HTTPBasicAuthHandler()\n auth_handler.add_password(\n realm='New mail feed',\n uri='https://mail.google.com',\n user='%s@gmail.com' % user,\n passwd=passwd\n )\n opener = urllib2.build_opener(auth_handler)\n urllib2.install_opener(opener)\n feed = urllib2.urlopen('https://mail.google.com/mail/feed/atom')\n return feed.read()\n\n"
] |
[
13
] |
[] |
[] |
[
"atom_feed",
"gmail",
"python",
"rss",
"urllib"
] |
stackoverflow_0001777081_atom_feed_gmail_python_rss_urllib.txt
|
Q:
Which programming language has very short context-free Grammar in its formal specification?
What programming language has short and beautiful grammars (in EBNF)?
Some languages are easer to be parsed. Some time ago I have created a simple VHDL parser, but it was very slow. Not because it is implemented completely in Python, but because VHDL grammar (in EBNF) is huge. The EBNF of Python is beautiful but it is not very short.
I suggest that many functional programming languages like LISP have short simple grammars, but I am interested in a more popular simple imperative language like C or Bash.
A:
I haven't compared, but Lua is a language renowned for its simple syntax. The BNF is at the very end of this reference manual: http://www.lua.org/manual/5.1/manual.html .
A:
Assembly languages!
...in general, and particularly for CPUs which have a simple architecture (few instructions, few addressing modes, few registers) have a relatively short grammar.
In fact, specialized processors, such as these found in programmable logic controllers can have a language with even simpler grammars. But then again the most simple of the PLCs are little more than Boolean equation calculators.
A:
One of the simplest imperative languages is Oberon-2. Syntax of Oberon-2.
Also take a look at Oberon-07 (The Programming Language Oberon-07, PDF) and Component Pascal.
A:
Pascal has only 2-3 pages of BNF notations
A:
What about GL Shading language? Language Specification (PDF)
However for these kind of hobbies I always preferred to implement a subset of a known language by myself without choosing anything "premade"..
|
Which programming language has very short context-free Grammar in its formal specification?
|
What programming language has short and beautiful grammars (in EBNF)?
Some languages are easer to be parsed. Some time ago I have created a simple VHDL parser, but it was very slow. Not because it is implemented completely in Python, but because VHDL grammar (in EBNF) is huge. The EBNF of Python is beautiful but it is not very short.
I suggest that many functional programming languages like LISP have short simple grammars, but I am interested in a more popular simple imperative language like C or Bash.
|
[
"I haven't compared, but Lua is a language renowned for its simple syntax. The BNF is at the very end of this reference manual: http://www.lua.org/manual/5.1/manual.html .\n",
"Assembly languages!\n...in general, and particularly for CPUs which have a simple architecture (few instructions, few addressing modes, few registers) have a relatively short grammar.\nIn fact, specialized processors, such as these found in programmable logic controllers can have a language with even simpler grammars. But then again the most simple of the PLCs are little more than Boolean equation calculators.\n",
"One of the simplest imperative languages is Oberon-2. Syntax of Oberon-2.\nAlso take a look at Oberon-07 (The Programming Language Oberon-07, PDF) and Component Pascal.\n",
"Pascal has only 2-3 pages of BNF notations \n",
"What about GL Shading language? Language Specification (PDF)\nHowever for these kind of hobbies I always preferred to implement a subset of a known language by myself without choosing anything \"premade\"..\n"
] |
[
5,
4,
3,
1,
0
] |
[
"Lisp is probably pretty small.\nlisp ::= `(´ exp `)´\n\n"
] |
[
-1
] |
[
"bash",
"c",
"python",
"vhdl"
] |
stackoverflow_0001777011_bash_c_python_vhdl.txt
|
Q:
Why do I get this error in this Python code?
I am trying to extract the first words in a file by Python.
My code
import re
con1 = pg.DB('tk', 'localhost', 5432, None, None, 'masi', '123')
f1="/home/masi/fy.txt"
print re.findall(r"\w+", f1.read())
I get the error
Traceback (most recent call last):
File "<stdin>", line 7, in <module>
AttributeError: 'str' object has no attribute 'read'
A:
f1.read() should be open(f1).read()
A:
I don't know Python but it looks like you need to open the file which is
f=open('/tmp/workfile', 'r')
According to this site
A:
When you assign f1 to the filepath, you are actually saying the f1 is the string referring to the filepath. Instead, if you were to assign it to the return value of the 'open' method called on that filepath (as Jonathan suggests), then f1 would be an open file.
|
Why do I get this error in this Python code?
|
I am trying to extract the first words in a file by Python.
My code
import re
con1 = pg.DB('tk', 'localhost', 5432, None, None, 'masi', '123')
f1="/home/masi/fy.txt"
print re.findall(r"\w+", f1.read())
I get the error
Traceback (most recent call last):
File "<stdin>", line 7, in <module>
AttributeError: 'str' object has no attribute 'read'
|
[
"f1.read() should be open(f1).read()\n",
"I don't know Python but it looks like you need to open the file which is \nf=open('/tmp/workfile', 'r')\n\nAccording to this site\n",
"When you assign f1 to the filepath, you are actually saying the f1 is the string referring to the filepath. Instead, if you were to assign it to the return value of the 'open' method called on that filepath (as Jonathan suggests), then f1 would be an open file.\n"
] |
[
5,
4,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001777592_python.txt
|
Q:
Python importing & using cdll (with a linux .so file)
After one of my last questions about python&c++ integration i was told to use dlls at windows.
(Previous question)
That worked ok doing:
cl /LD A.cpp B.cpp C.pp
in windows enviroment, after setting the include path for boost, cryptopp sources and cryptopp libraries.
Now i'm tryting to do the same in linux, creating a .so file to import through ctypes on python2.5.
I did:
gcc -Wall -Wextra -pedantic A.cpp B.cpp C.cpp /usr/lib/libcryptopp.so -shared -o /test/decoding.so
and the so object is created ok. If removed "-shared" compilation is OK but stops as no main in there (obviously ;) ). Of course libcryptopp.so exists too.
But when i go to python and import the "so" file, it said that the attribute has no object "decrypt", "encrypt" or whatever i put there. using "dir" over the dll objects confirms that they are not there.
external functions are defined in A.cpp as:
int encrypt (params...)
//..
return num;
int decrypt (params...)
//..
return num;
also tried using:
extern "C" encrypt (params...)
.....
Could anyone tell me what i'm doing wrong?
Thanks in advance!
Rag
A:
C++ compiler mangles names of functions. To do what you are trying to do you must have the declaration prototype inside
extern "C" {...}
it's hard to tell from your samples what exactly you have in a source file.
As someone already mentioned, use nm utility to see what objects that are in your shared object.
Do not compile your object without -shared. Python load library does not support statically linked objects as far as am aware.
compile your object with g++ compiler instead, it will link to standard C++ Library, gcc does not.
A:
just to doublecheck something since you using boost.
#include <string>
#include <boost/python.hpp>
using namespace std;
string hello(string s){
return "Hello World!";
}
BOOST_PYTHON_MODULE(pyhello){
using namespace boost::python;
def("hello", hello);
}
in python
>>> import pyhello
>>> print pyhello.hello()
Hello World!
just my 2 cents, sorry if this couldn't help you.
|
Python importing & using cdll (with a linux .so file)
|
After one of my last questions about python&c++ integration i was told to use dlls at windows.
(Previous question)
That worked ok doing:
cl /LD A.cpp B.cpp C.pp
in windows enviroment, after setting the include path for boost, cryptopp sources and cryptopp libraries.
Now i'm tryting to do the same in linux, creating a .so file to import through ctypes on python2.5.
I did:
gcc -Wall -Wextra -pedantic A.cpp B.cpp C.cpp /usr/lib/libcryptopp.so -shared -o /test/decoding.so
and the so object is created ok. If removed "-shared" compilation is OK but stops as no main in there (obviously ;) ). Of course libcryptopp.so exists too.
But when i go to python and import the "so" file, it said that the attribute has no object "decrypt", "encrypt" or whatever i put there. using "dir" over the dll objects confirms that they are not there.
external functions are defined in A.cpp as:
int encrypt (params...)
//..
return num;
int decrypt (params...)
//..
return num;
also tried using:
extern "C" encrypt (params...)
.....
Could anyone tell me what i'm doing wrong?
Thanks in advance!
Rag
|
[
"C++ compiler mangles names of functions. To do what you are trying to do you must have the declaration prototype inside \nextern \"C\" {...}\n\nit's hard to tell from your samples what exactly you have in a source file.\nAs someone already mentioned, use nm utility to see what objects that are in your shared object.\nDo not compile your object without -shared. Python load library does not support statically linked objects as far as am aware.\ncompile your object with g++ compiler instead, it will link to standard C++ Library, gcc does not.\n",
"just to doublecheck something since you using boost.\n#include <string>\n#include <boost/python.hpp>\nusing namespace std;\n\nstring hello(string s){\n return \"Hello World!\";\n}\n\nBOOST_PYTHON_MODULE(pyhello){\n using namespace boost::python;\n\n def(\"hello\", hello);\n}\n\nin python\n>>> import pyhello\n>>> print pyhello.hello()\nHello World!\n\njust my 2 cents, sorry if this couldn't help you.\n"
] |
[
3,
1
] |
[] |
[] |
[
"c++",
"file",
"linux",
"python",
"shared_libraries"
] |
stackoverflow_0001777752_c++_file_linux_python_shared_libraries.txt
|
Q:
postgresql and python
I need to visualize spatial data (20 polygons) from "postgis" database (postgresql), with python. I know how to connect postgresql database with python only, but I don`t how to visualize those polygons. It is project for my university. We need to use for example matplotlib and create application in python which will visualize shapefiles (.shp) from postgresql database.
I started with this code but I dont know how to continue:
import psycopg2
conn = psycopg2.connect("dbname='***' user='***' host='***' password='***'")
print 'Succesfully connected'
cur = conn.cursor()
cur.execute("""SELECT astext(the_geom) from buildings;""")
listpoly = cur.fetchall()
conn.close()
A:
I've had good luck using the Python Imaging Library when I've needed to create raster (bitmap) graphics. It's got a pretty simple interface and makes it pretty easy to overlay graphics on top of another image. Unfortunately, PIL isn't updated that often. Probably because it just works. Here's how to do a simple polygon (lifted from Nadia Alrami's excellent little intro to PIL):
im = Image.new('RGBA', (100, 100), (0, 0, 0, 0)) # Create a blank image
draw = ImageDraw.Draw(im)
lines = [(50, 0), (0, 40), (20, 100), (80, 100), (100, 40)]
draw.polygon(lines, fill="black")
For more complex images, I tend to render them in SVG using the svgfig package for python. Because it's SVG they're great for scaling and sharing on a web browser. Unfortunately, I don't believe that svgfig has a nice polygon function, so you'll need to hack your own by doing something like this:
def polygon(points):
for x in xrange(len(points)-1):
line(points[x][0], points[x][1], points[x+1][0], points[x+1][1])
line(points[-1][0], points[-1][1], points[0][0], points[0][1])
A:
There are many plotting packages for Python (and of course they support plotting polygons, it's one of the most fundamental features in that space;-), and the most popular one, I believe, is matplotlib.
A:
With matplotlib, you can draw polygons with the fill() command.
For example, to create a polygon with vertices (3,2),(4,2),(4,4),(3,4),
you define x=[3,4,4,3], y=[2,2,4,4] (the respective x and y coordinates)
and use fill(x,y). For example,
import pylab
z=[(3,2),(4,2),(4,4),(3,4)]
x,y=zip(*z)
pylab.fill(x,y, 'b', alpha=0.2, edgecolor='r')
pylab.show()
See http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.fill for more about the fill() command, and the pylab API.
A:
maybe u can try the patch_collection example. I have copy it here with matplotlib.pyplot and only Polygon part:
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111)
patches = []
for x in xrange(2):
polygon = Polygon(np.random.rand(3, 2), True)
patches.append(polygon)
p = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=0.4)
colors = 100*np.random.rand(len(patches))
p.set_array(np.array(colors))
ax.add_collection(p)
plt.colorbar(p)
plt.show()
The output pic is here:
I think document matplotlib.patches.Polygon worth a look too. Hope this helps.
A:
What is the purpose you are trying to achieve here? Do you just want to look at the data in the .shp files? There is an open source application called Quantum GIS that allows you to open spatial data directly from PostGIS (and directly from a shapefile for that matter). If all you need to do is look at the polygons, this is probably the simplest way to do it. If this is not what you're trying to do, perhaps you can clarify your question.
|
postgresql and python
|
I need to visualize spatial data (20 polygons) from "postgis" database (postgresql), with python. I know how to connect postgresql database with python only, but I don`t how to visualize those polygons. It is project for my university. We need to use for example matplotlib and create application in python which will visualize shapefiles (.shp) from postgresql database.
I started with this code but I dont know how to continue:
import psycopg2
conn = psycopg2.connect("dbname='***' user='***' host='***' password='***'")
print 'Succesfully connected'
cur = conn.cursor()
cur.execute("""SELECT astext(the_geom) from buildings;""")
listpoly = cur.fetchall()
conn.close()
|
[
"I've had good luck using the Python Imaging Library when I've needed to create raster (bitmap) graphics. It's got a pretty simple interface and makes it pretty easy to overlay graphics on top of another image. Unfortunately, PIL isn't updated that often. Probably because it just works. Here's how to do a simple polygon (lifted from Nadia Alrami's excellent little intro to PIL):\nim = Image.new('RGBA', (100, 100), (0, 0, 0, 0)) # Create a blank image\ndraw = ImageDraw.Draw(im)\nlines = [(50, 0), (0, 40), (20, 100), (80, 100), (100, 40)]\ndraw.polygon(lines, fill=\"black\")\n\nFor more complex images, I tend to render them in SVG using the svgfig package for python. Because it's SVG they're great for scaling and sharing on a web browser. Unfortunately, I don't believe that svgfig has a nice polygon function, so you'll need to hack your own by doing something like this:\ndef polygon(points):\n for x in xrange(len(points)-1):\n line(points[x][0], points[x][1], points[x+1][0], points[x+1][1])\n line(points[-1][0], points[-1][1], points[0][0], points[0][1])\n\n",
"There are many plotting packages for Python (and of course they support plotting polygons, it's one of the most fundamental features in that space;-), and the most popular one, I believe, is matplotlib.\n",
"With matplotlib, you can draw polygons with the fill() command.\nFor example, to create a polygon with vertices (3,2),(4,2),(4,4),(3,4),\nyou define x=[3,4,4,3], y=[2,2,4,4] (the respective x and y coordinates)\nand use fill(x,y). For example,\nimport pylab\nz=[(3,2),(4,2),(4,4),(3,4)]\nx,y=zip(*z)\npylab.fill(x,y, 'b', alpha=0.2, edgecolor='r')\npylab.show()\n\nSee http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.fill for more about the fill() command, and the pylab API.\n",
"maybe u can try the patch_collection example. I have copy it here with matplotlib.pyplot and only Polygon part: \nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Polygon\nfrom matplotlib.collections import PatchCollection\nimport numpy as np\nfig = plt.figure()\nax = fig.add_subplot(111)\npatches = []\nfor x in xrange(2):\n polygon = Polygon(np.random.rand(3, 2), True)\n patches.append(polygon)\np = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=0.4)\ncolors = 100*np.random.rand(len(patches))\np.set_array(np.array(colors))\nax.add_collection(p)\nplt.colorbar(p)\n\nplt.show()\n\nThe output pic is here: \n\nI think document matplotlib.patches.Polygon worth a look too. Hope this helps.\n",
"What is the purpose you are trying to achieve here? Do you just want to look at the data in the .shp files? There is an open source application called Quantum GIS that allows you to open spatial data directly from PostGIS (and directly from a shapefile for that matter). If all you need to do is look at the polygons, this is probably the simplest way to do it. If this is not what you're trying to do, perhaps you can clarify your question.\n"
] |
[
3,
2,
1,
1,
0
] |
[] |
[] |
[
"postgresql",
"python"
] |
stackoverflow_0001776511_postgresql_python.txt
|
Q:
Module import path
I'm unable to test-run a cssparser that I'd like to use.
test.py:
from css.parse import parse
data = """
em {
padding: 2px;
margin: 1em;
border-width: medium;
border-style: dashed;
line-height: 2.4em;
}
p { color: red; font-size: 12pt }
p:first-letter { color: green; font-size: 200% }
p:first-line { color: blue }"""
for rule in parse(data):
print (rule)
..gives an error:
Traceback (most recent call last):
method <module> in test.py at line 1
from css.parse import parse
method <module> in test.py at line 6
from . import css, csslex, cssyacc
method <module> in test.py at line 8
from . import serialize
method <module> in test.py at line 6
from . import css
ImportError: cannot import name css
Directory structure (/Users/nimbuz/Documents/python31):
/Users/nimbuz/Documents/python31/**csspy**/
|
+-- css/ (*has __init__.py*)
|
+-- uri/ (*has __init__.py*)
|
+-- test.py
print(sys.path) shows:
['/Users/nimbuz/Documents/python31/csspy', '/Library/Frameworks/Python.framework/Versions/3.1/lib/python31.zip', '/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1', '/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/plat-darwin', '/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/site-packages']
A:
Here is few steps I just tested.
readme says its python 2.5, so you need python 2.x series
I have created a folder C:/TEST/
I have downloaded all files from css-py svn to C:/TEST/, so C:/TEST/css/ and C:/TEST/uri/ folders exists now.
I have downloaded ply's tar gz file and extract only ply folder into C:/TEST/css/, so C:/TEST/css/ply/ folder exists now.
I have created test.py in C:/TEST/ with the content
from css.parse import parse
print dir(parse)
and I run it and the results is like this, without import errors:
C:\TEST>test.py
['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__format__', '__get__', '__getattribute__', '__globals__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']
Hope this helps. sorry If my explanation is bad.
A:
Do you have __init__.py files in the cssparser and css directories, to turn the directories into packages? Is there a css/parse.py file with some function or class named parse in it? What's on your sys.path, and what's the current directory, when you execute test.py? All of these questions may be important, and you give us the answer to none of them, so it's hard to be of any specific help!-)
A:
python 3 version of css-py
http://ifile.it/v32n70s/css.zip
A:
Does your css/ have an __init__.py?
A:
Don't call your own file css.py. Name it something else, like css_test.py. Delete the css.pyc file also.
|
Module import path
|
I'm unable to test-run a cssparser that I'd like to use.
test.py:
from css.parse import parse
data = """
em {
padding: 2px;
margin: 1em;
border-width: medium;
border-style: dashed;
line-height: 2.4em;
}
p { color: red; font-size: 12pt }
p:first-letter { color: green; font-size: 200% }
p:first-line { color: blue }"""
for rule in parse(data):
print (rule)
..gives an error:
Traceback (most recent call last):
method <module> in test.py at line 1
from css.parse import parse
method <module> in test.py at line 6
from . import css, csslex, cssyacc
method <module> in test.py at line 8
from . import serialize
method <module> in test.py at line 6
from . import css
ImportError: cannot import name css
Directory structure (/Users/nimbuz/Documents/python31):
/Users/nimbuz/Documents/python31/**csspy**/
|
+-- css/ (*has __init__.py*)
|
+-- uri/ (*has __init__.py*)
|
+-- test.py
print(sys.path) shows:
['/Users/nimbuz/Documents/python31/csspy', '/Library/Frameworks/Python.framework/Versions/3.1/lib/python31.zip', '/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1', '/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/plat-darwin', '/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/site-packages']
|
[
"Here is few steps I just tested.\n\nreadme says its python 2.5, so you need python 2.x series\nI have created a folder C:/TEST/\nI have downloaded all files from css-py svn to C:/TEST/, so C:/TEST/css/ and C:/TEST/uri/ folders exists now.\nI have downloaded ply's tar gz file and extract only ply folder into C:/TEST/css/, so C:/TEST/css/ply/ folder exists now.\nI have created test.py in C:/TEST/ with the content \nfrom css.parse import parse\nprint dir(parse)\n\nand I run it and the results is like this, without import errors:\nC:\\TEST>test.py\n['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__format__', '__get__', '__getattribute__', '__globals__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']\n\nHope this helps. sorry If my explanation is bad.\n",
"Do you have __init__.py files in the cssparser and css directories, to turn the directories into packages? Is there a css/parse.py file with some function or class named parse in it? What's on your sys.path, and what's the current directory, when you execute test.py? All of these questions may be important, and you give us the answer to none of them, so it's hard to be of any specific help!-)\n",
"python 3 version of css-py\nhttp://ifile.it/v32n70s/css.zip\n",
"Does your css/ have an __init__.py?\n",
"Don't call your own file css.py. Name it something else, like css_test.py. Delete the css.pyc file also.\n"
] |
[
4,
2,
2,
0,
0
] |
[] |
[] |
[
"import",
"module",
"path",
"python"
] |
stackoverflow_0001777838_import_module_path_python.txt
|
Q:
Automatically pick tags from context using Python
How can I pick tags from an article or a user's post using Python?
Is the following method ok?
Build a list of word frequency from the text and sort them.
Remove some common words and pick the top 10 words remained in the list as the tags.
If the above method is ok, what library can detect if which words are common, like "the, if, you, etc" and which are descriptive words?
A:
Here's an article on removing stop words. The link to the stop word list in the article is broken but here's another one.
A:
The Natural Language Toolkit offers a broad variety of methods for this kind of stuff. I can't give you hands-on advice as I'm not familiar with this subject, but I think it's worth the effort to read a few articles about this topic first before you start: just picking words from the text directly won't get you very far I think, you should probably try to find similar words to the ones for that tags already exist. And of course you need to filter out the common words of the language like "the" and stuff. Again, this Python library can help you with this, at least for a few common languages.
A:
I'd suggest you download the Stack Overflow data dump. There you get a lot of real world posts, with appropriate tags, to test different algorithms of tag selection.
But generally I doubt it will work too well. For your own question "words" is the clear winner in word count, followed by a list of words with two appearances each, like "common", "list", "method", "pick" and "tags". Which of those would you automatically choose as tags? Also the tags you chose manually contain "python" and "context", none of which shows up with high word frequency.
A:
Train Bayes or Fischer filter with already tagged data (e.g. with Stackoverflow data dump suggested by sth) and use it to classify new posts. I'd recommend reading excellent Programming Collective Intelligence book by Toby Segaran for more information and python examples on this topic.
A:
Instead of blacklisting words that shouldn't be tags, why don't you instead build a whitelist of words that would make for good tags?
Start with an handful of tags that you would like to have, like Python, off-topic, football, rickroll or whatnot (depends on the kind of site you are building!) and have the system only suggest between those, then let users handpick appropriate tags and also let them type in their own tags.
When enough users suggest a tag, it gets into the pool of "known good" tags for auto suggestion -- maybe after some sort of moderation, so that you can still blacklist stupid tags like the, lolol, or typoed tags like objectoriented when you have object-oriented.
Only show few suggestions. Offer autocompletion. Limit the number of tags per item. If this will be about coding, maybe some sort of language detection system (the file linux command is not too shabby on this) will help your suggestion system.
|
Automatically pick tags from context using Python
|
How can I pick tags from an article or a user's post using Python?
Is the following method ok?
Build a list of word frequency from the text and sort them.
Remove some common words and pick the top 10 words remained in the list as the tags.
If the above method is ok, what library can detect if which words are common, like "the, if, you, etc" and which are descriptive words?
|
[
"Here's an article on removing stop words. The link to the stop word list in the article is broken but here's another one.\n",
"The Natural Language Toolkit offers a broad variety of methods for this kind of stuff. I can't give you hands-on advice as I'm not familiar with this subject, but I think it's worth the effort to read a few articles about this topic first before you start: just picking words from the text directly won't get you very far I think, you should probably try to find similar words to the ones for that tags already exist. And of course you need to filter out the common words of the language like \"the\" and stuff. Again, this Python library can help you with this, at least for a few common languages.\n",
"I'd suggest you download the Stack Overflow data dump. There you get a lot of real world posts, with appropriate tags, to test different algorithms of tag selection.\nBut generally I doubt it will work too well. For your own question \"words\" is the clear winner in word count, followed by a list of words with two appearances each, like \"common\", \"list\", \"method\", \"pick\" and \"tags\". Which of those would you automatically choose as tags? Also the tags you chose manually contain \"python\" and \"context\", none of which shows up with high word frequency.\n",
"Train Bayes or Fischer filter with already tagged data (e.g. with Stackoverflow data dump suggested by sth) and use it to classify new posts. I'd recommend reading excellent Programming Collective Intelligence book by Toby Segaran for more information and python examples on this topic.\n",
"Instead of blacklisting words that shouldn't be tags, why don't you instead build a whitelist of words that would make for good tags?\nStart with an handful of tags that you would like to have, like Python, off-topic, football, rickroll or whatnot (depends on the kind of site you are building!) and have the system only suggest between those, then let users handpick appropriate tags and also let them type in their own tags.\nWhen enough users suggest a tag, it gets into the pool of \"known good\" tags for auto suggestion -- maybe after some sort of moderation, so that you can still blacklist stupid tags like the, lolol, or typoed tags like objectoriented when you have object-oriented.\nOnly show few suggestions. Offer autocompletion. Limit the number of tags per item. If this will be about coding, maybe some sort of language detection system (the file linux command is not too shabby on this) will help your suggestion system.\n"
] |
[
4,
3,
2,
1,
0
] |
[] |
[] |
[
"python",
"tags"
] |
stackoverflow_0001775637_python_tags.txt
|
Q:
Is there precision in this number that Python isn't showing me?
I've run into something odd, here, and I'm at a loss -- I have a feeling this has something to do with floating precision, but I'm surprised Python would not display the approximation error, if so.
I'm working on Project Euler problem 62. As a simple test (I've since solved using a different approach), I had a is_cube which I intended to check if a number cubes perfectly. So, to try the sample given, I did this:
def is_cube(i):
c = i ** (1./3)
print "c is", c
When I ran this with i = 41063625, the expected output was:
c is 345.0
Here's where the unexpected happened:
def is_cube(i):
c = i ** (1./3)
print "c is", int(c)
Suddenly, I had this:
c is 344
The value c does not compare against my 345.0 literal, either -- c < 345.0 is True.
Is there precision in this number that Python is not showing me? I seem to recall reading about a change to make floats appear more sane when printed; is this it? What is different about these two cases?
>>> def is_cube(i):
... c = i ** (1./3)
... print "c is", c
...
>>> is_cube(41063625)
c is 345.0
>>> 41063625 ** (1./3)
344.99999999999989
Edit: Still had the window open and did this:
>>> print _
345.0
Now I'm starting to think I should have known all along that print was to blame.
A:
This is using c.__str__() (aka. str(c)) :
print "c is", c
This is using c.__repr__() (aka. repr(c)) :
>>> c # In the Python shell
IIRC, __str__ truncates to 10 decimals, whereas __repr__ goes further. To get the same behavior as in the Python shell, you could do :
print repr(c)
# Or
print "%r" % c
# Or
print "%.16f" % c
The change you're talking about in your message is only about Python 3.1 and do not alter the precision of the output : Gay's algorithm which is used for __repr__ on floating point numbers in Python 3.1 will, when given two representation choices which yields the same floating point value (like 0.2 and 0.2000000000000001), choose the shortest one.
A:
print "c is", int(c)
The integer conversion will simply drop anything after the decimal point so even if you have 344.99999999999989 it will always round down.
you could use old school print %
print'c is %5.0f' % c
or you could use round if you want an integer
print'c is %d' % round(c,0)
Also you might be interested in other solutions for the cube root problem
here
|
Is there precision in this number that Python isn't showing me?
|
I've run into something odd, here, and I'm at a loss -- I have a feeling this has something to do with floating precision, but I'm surprised Python would not display the approximation error, if so.
I'm working on Project Euler problem 62. As a simple test (I've since solved using a different approach), I had a is_cube which I intended to check if a number cubes perfectly. So, to try the sample given, I did this:
def is_cube(i):
c = i ** (1./3)
print "c is", c
When I ran this with i = 41063625, the expected output was:
c is 345.0
Here's where the unexpected happened:
def is_cube(i):
c = i ** (1./3)
print "c is", int(c)
Suddenly, I had this:
c is 344
The value c does not compare against my 345.0 literal, either -- c < 345.0 is True.
Is there precision in this number that Python is not showing me? I seem to recall reading about a change to make floats appear more sane when printed; is this it? What is different about these two cases?
>>> def is_cube(i):
... c = i ** (1./3)
... print "c is", c
...
>>> is_cube(41063625)
c is 345.0
>>> 41063625 ** (1./3)
344.99999999999989
Edit: Still had the window open and did this:
>>> print _
345.0
Now I'm starting to think I should have known all along that print was to blame.
|
[
"This is using c.__str__() (aka. str(c)) :\nprint \"c is\", c\n\nThis is using c.__repr__() (aka. repr(c)) :\n>>> c # In the Python shell\n\nIIRC, __str__ truncates to 10 decimals, whereas __repr__ goes further. To get the same behavior as in the Python shell, you could do :\nprint repr(c)\n# Or\nprint \"%r\" % c\n# Or\nprint \"%.16f\" % c\n\nThe change you're talking about in your message is only about Python 3.1 and do not alter the precision of the output : Gay's algorithm which is used for __repr__ on floating point numbers in Python 3.1 will, when given two representation choices which yields the same floating point value (like 0.2 and 0.2000000000000001), choose the shortest one.\n",
" print \"c is\", int(c)\n\nThe integer conversion will simply drop anything after the decimal point so even if you have 344.99999999999989 it will always round down. \nyou could use old school print % \n print'c is %5.0f' % c\n\nor you could use round if you want an integer\nprint'c is %d' % round(c,0)\n\nAlso you might be interested in other solutions for the cube root problem \nhere\n"
] |
[
4,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001778179_python.txt
|
Q:
If you had the time and inclination to create a programming language, what characteristics would it have?
Just curious. If you had the time and inclination to create a programming language, what characteristics would it have?
One language I would like to see would borrow as much from the syntax of Python as possible but compile to machine code that runs as fast as C or C++.
A:
I would limit my language to one statement:
Solve my problem.
Maybe i'd add one modifier though, in case its urgent:
Solve my problem, please.
A:
A mix of COBOL and XML, for the lulz
<program>
<data>
<const>
<name>myStr</name>
<value><[CDATA[Hello, World!]]></value>
</const>
</data>
<sub>
<name>main</name>
<params />
<return />
<code>
<call>
<name>writeline</name>
<params>
<var>myStr</var>
</params>
<giving />
</call>
</code>
</sub>
<meta>
<entrypoint>main</entrypoint>
</meta>
</program>
A:
Programmer would be able to explicitly set the types of vars. And of the arguments in a cool way, like
(string str, array(int)|int someint_or_more, any some_strange_argument)
something like this :)
Programmer would be able to use lambdas, closures, etc at least as in JS
It would have protytipes-based OOP (like in JS)
Blocks (if { ... }, etc) would act like a closures!
It would have a special keyword to define a function which return constant value (if arguments haven't been changed) so It can be cached by compiler/interpreter without any programmers thought about it. It would be very useful, you would be able to use recursion for almost anything and don't really suck with perfomance!
A:
It should be fast and lightweight (not like the .NET Framework), but you should still be able to create fully functional and flexible GUI apps.
A:
A simple block for defining things that can run in parallel, so if I write:
parallel{
do_x();
do_y();
}
something_else();
do_x() and do_y() would be executed in parallel, but something_else() would only be run after both of them complete.
|
If you had the time and inclination to create a programming language, what characteristics would it have?
|
Just curious. If you had the time and inclination to create a programming language, what characteristics would it have?
One language I would like to see would borrow as much from the syntax of Python as possible but compile to machine code that runs as fast as C or C++.
|
[
"I would limit my language to one statement:\nSolve my problem.\n\nMaybe i'd add one modifier though, in case its urgent:\nSolve my problem, please.\n\n",
"A mix of COBOL and XML, for the lulz\n<program>\n <data>\n <const>\n <name>myStr</name>\n <value><[CDATA[Hello, World!]]></value>\n </const>\n </data>\n <sub>\n <name>main</name>\n <params />\n <return />\n <code>\n <call>\n <name>writeline</name>\n <params>\n <var>myStr</var>\n </params>\n <giving />\n </call>\n </code>\n </sub>\n <meta>\n <entrypoint>main</entrypoint>\n </meta>\n</program>\n\n",
"\nProgrammer would be able to explicitly set the types of vars. And of the arguments in a cool way, like\n(string str, array(int)|int someint_or_more, any some_strange_argument)\n\nsomething like this :)\nProgrammer would be able to use lambdas, closures, etc at least as in JS\nIt would have protytipes-based OOP (like in JS)\nBlocks (if { ... }, etc) would act like a closures!\nIt would have a special keyword to define a function which return constant value (if arguments haven't been changed) so It can be cached by compiler/interpreter without any programmers thought about it. It would be very useful, you would be able to use recursion for almost anything and don't really suck with perfomance!\n\n",
"It should be fast and lightweight (not like the .NET Framework), but you should still be able to create fully functional and flexible GUI apps.\n",
"A simple block for defining things that can run in parallel, so if I write:\nparallel{\n do_x();\n do_y();\n}\nsomething_else();\n\ndo_x() and do_y() would be executed in parallel, but something_else() would only be run after both of them complete.\n"
] |
[
5,
4,
0,
0,
0
] |
[] |
[] |
[
"c++",
"python"
] |
stackoverflow_0001778278_c++_python.txt
|
Q:
Where can I find a (current) example of code to bulk upload data to Google AppEngine? (For localhost, too.)
I've tried to do it like they describe in the AppEngine docs but I can't get it to accept my upload. (I haven't tried to download.) I want to get it working in the development environment before I tried on the live site.
It's kind of confusing, because I don't know if I should be trying appcfg.py or bulkloader.py. (I mostly tried appcfg.py.) I think it's an authentication problem, as it keeps asking me for the email/password. (Even after I removed 'login: admin' from app.yaml.)
I did --dry_run and it seemed to work, so I think my stuff is well formed.
Before asking for specific debugging help, I thought I would ask if anyone knows of working sample code that I can download. I run OS X 10.6, if anyone cares. I'm not new to Python, and have a lot of web.py experience, so it's probably not unfamiliarity with the language that's tripping me up.
A:
The docs have a section on uploading and downloading data, with examples. You should be using appcfg.py unless you need one of the features of bulkloader.py that are not yet integrated, such as --dump/--restore functionality.
It sounds like the authentication problems you're having are related to Google Apps: If you have an App Engine app that allows any Google account to authenticate, and you have a Google Apps account as administrator, you won't be able to authenticate against your app as an administrator with it, even if you have created a Google account for that email address. You need to create a gmail account, and add that account as an administrator, so you can use that address when you need to authenticate against your app.
|
Where can I find a (current) example of code to bulk upload data to Google AppEngine? (For localhost, too.)
|
I've tried to do it like they describe in the AppEngine docs but I can't get it to accept my upload. (I haven't tried to download.) I want to get it working in the development environment before I tried on the live site.
It's kind of confusing, because I don't know if I should be trying appcfg.py or bulkloader.py. (I mostly tried appcfg.py.) I think it's an authentication problem, as it keeps asking me for the email/password. (Even after I removed 'login: admin' from app.yaml.)
I did --dry_run and it seemed to work, so I think my stuff is well formed.
Before asking for specific debugging help, I thought I would ask if anyone knows of working sample code that I can download. I run OS X 10.6, if anyone cares. I'm not new to Python, and have a lot of web.py experience, so it's probably not unfamiliarity with the language that's tripping me up.
|
[
"The docs have a section on uploading and downloading data, with examples. You should be using appcfg.py unless you need one of the features of bulkloader.py that are not yet integrated, such as --dump/--restore functionality.\nIt sounds like the authentication problems you're having are related to Google Apps: If you have an App Engine app that allows any Google account to authenticate, and you have a Google Apps account as administrator, you won't be able to authenticate against your app as an administrator with it, even if you have created a Google account for that email address. You need to create a gmail account, and add that account as an administrator, so you can use that address when you need to authenticate against your app.\n"
] |
[
1
] |
[] |
[] |
[
"google_app_engine",
"python"
] |
stackoverflow_0001777949_google_app_engine_python.txt
|
Q:
Why does Python allow comparison of a callable and a number?
I used python to write an assignment last week, here is a code snippet
def departTime():
'''
Calculate the time to depart a packet.
'''
if(random.random < 0.8):
t = random.expovariate(1.0 / 2.5)
else:
t = random.expovariate(1.0 / 10.5)
return t
Can you see the problem? I compare random.random with 0.8, which
should be random.random().
Of course this because of my careless, but I don't get it. In my
opinion, this kind of comparison should invoke a least a warning in
any programming language.
So why does python just ignore it and return False?
A:
This isn't always a mistake
Firstly, just to make things clear, this isn't always a mistake.
In this particular case, it's pretty clear the comparison is an error.
However, because of the dynamic nature of Python, consider the following (perfectly valid, if terrible) code:
import random
random.random = 9 # Very weird but legal assignment.
random.random < 10 # True
random.random > 10 # False
What actually happens when comparing objects?
As for your actual case, comparing a function object to a number, have a look at Python documentation: Python Documentation: Expressions. Check out section 5.9, titled "Comparisons", which states:
The operators <, >, ==, >=, <=, and != compare the values of two objects. The objects need not have the same type. If both are numbers, they are converted to a common type. Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily. You can control comparison behavior of objects of non-built-in types by defining a cmp method or rich comparison methods like gt, described in section Special method names.
(This unusual definition of comparison was used to simplify the definition of operations like sorting and the in and not in operators. In the future, the comparison rules for objects of different types are likely to change.)
That should explain both what happens and the reasoning for it.
BTW, I'm not sure what happens in newer versions of Python.
Edit: If you're wondering, Debilski's answer gives info about Python 3.
A:
This is ‘fixed’ in Python 3 http://docs.python.org/3.1/whatsnew/3.0.html#ordering-comparisons.
A:
Because in Python that is a perfectly valid comparison. Python can't know if you really want to make that comparison or if you've just made a mistake. It's your job to supply Python with the right objects to compare.
Because of the dynamic nature of Python you can compare and sort almost everything with almost everything (this is a feature). You've compared a function to a float in this case.
An example:
list = ["b","a",0,1, random.random, random.random()]
print sorted(list)
This will give the following output:
[0, 0.89329568818188976, 1, <built-in method random of Random object at 0x8c6d66c>, 'a', 'b']
A:
I think python allows this because the random.random object could be overriding the > operator by including a __gt__ method in the object which might be accepting or even expecting a number. So, python thinks you know what you are doing... and does not report it.
If you try check for it, you can see that __gt__ exists for random.random...
>>> random.random.__gt__
<method-wrapper '__gt__' of builtin_function_or_method object at 0xb765c06c>
But, that might not be something you want to do.
|
Why does Python allow comparison of a callable and a number?
|
I used python to write an assignment last week, here is a code snippet
def departTime():
'''
Calculate the time to depart a packet.
'''
if(random.random < 0.8):
t = random.expovariate(1.0 / 2.5)
else:
t = random.expovariate(1.0 / 10.5)
return t
Can you see the problem? I compare random.random with 0.8, which
should be random.random().
Of course this because of my careless, but I don't get it. In my
opinion, this kind of comparison should invoke a least a warning in
any programming language.
So why does python just ignore it and return False?
|
[
"This isn't always a mistake\nFirstly, just to make things clear, this isn't always a mistake.\nIn this particular case, it's pretty clear the comparison is an error.\nHowever, because of the dynamic nature of Python, consider the following (perfectly valid, if terrible) code:\nimport random\nrandom.random = 9 # Very weird but legal assignment.\nrandom.random < 10 # True\nrandom.random > 10 # False\n\nWhat actually happens when comparing objects?\nAs for your actual case, comparing a function object to a number, have a look at Python documentation: Python Documentation: Expressions. Check out section 5.9, titled \"Comparisons\", which states:\n\nThe operators <, >, ==, >=, <=, and != compare the values of two objects. The objects need not have the same type. If both are numbers, they are converted to a common type. Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily. You can control comparison behavior of objects of non-built-in types by defining a cmp method or rich comparison methods like gt, described in section Special method names.\n(This unusual definition of comparison was used to simplify the definition of operations like sorting and the in and not in operators. In the future, the comparison rules for objects of different types are likely to change.)\n\nThat should explain both what happens and the reasoning for it.\nBTW, I'm not sure what happens in newer versions of Python.\nEdit: If you're wondering, Debilski's answer gives info about Python 3.\n",
"This is ‘fixed’ in Python 3 http://docs.python.org/3.1/whatsnew/3.0.html#ordering-comparisons.\n",
"Because in Python that is a perfectly valid comparison. Python can't know if you really want to make that comparison or if you've just made a mistake. It's your job to supply Python with the right objects to compare.\nBecause of the dynamic nature of Python you can compare and sort almost everything with almost everything (this is a feature). You've compared a function to a float in this case.\nAn example:\nlist = [\"b\",\"a\",0,1, random.random, random.random()]\nprint sorted(list)\n\nThis will give the following output:\n[0, 0.89329568818188976, 1, <built-in method random of Random object at 0x8c6d66c>, 'a', 'b']\n\n",
"I think python allows this because the random.random object could be overriding the > operator by including a __gt__ method in the object which might be accepting or even expecting a number. So, python thinks you know what you are doing... and does not report it.\nIf you try check for it, you can see that __gt__ exists for random.random...\n>>> random.random.__gt__\n<method-wrapper '__gt__' of builtin_function_or_method object at 0xb765c06c>\n\nBut, that might not be something you want to do.\n"
] |
[
9,
7,
3,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001778521_python.txt
|
Q:
Data visualization in python - after connecting to a database
Can you help me to connect to my postgresql database with python? I need to create graphic interface with python which will visualize shapefile data from my database (i have about 50 polygons in shapefile format in that database). Can you help me with creating such application? I am begginer in python.
A:
For communicating with the database, use psycopg2. It's quick, easy and efficient if you are familiar with basic DB concepts.
You have several options from here. You can use shpUtils, which is supposed to be a nice package for parsing shapefiles. You can then visualize the data using numerous python graphics packages, like pil.
PIL image source code here.
Every option suits a different need, depending on what you define as "create graphic interface". If you need to create a simple graphics output, build the polygons from text using one of the graphics utilities mentioned above. If you need to create a professional-looking image, try using mapnik (mentioned in some other answers), which easily reads shapefiles. If you need to create a fully functional GUI, it's probably not a beginner's task - you should start with programming basic GUI applications before diving into shapefiles and polygons.
If, however, you just need to view the polygons - skip python and just use qgis, which will very easily visualize your polygons. It also comes with a handful of other nice features, like colors, zooms and so on.
(source: sourceforge.net)
A:
I would approach this by breaking it up into smaller problems and solving each of them
a) How do I connect to a postgresql database with python?
https://stackoverflow.com/search?q=postgresql+database+python - Looks like psycopg2 is a good option as Adam Matan suggested.
b) Drawing shapefile data in python
postgresql and python
A:
Mapnik is great for drawing maps. It can handle various formats and shapefiles, too. As far as I know it also supports PostgreSQL (at least PostGIS).
And least but not last: it comes with a Python interface (see Getting started)
|
Data visualization in python - after connecting to a database
|
Can you help me to connect to my postgresql database with python? I need to create graphic interface with python which will visualize shapefile data from my database (i have about 50 polygons in shapefile format in that database). Can you help me with creating such application? I am begginer in python.
|
[
"For communicating with the database, use psycopg2. It's quick, easy and efficient if you are familiar with basic DB concepts.\nYou have several options from here. You can use shpUtils, which is supposed to be a nice package for parsing shapefiles. You can then visualize the data using numerous python graphics packages, like pil.\n\nPIL image source code here.\nEvery option suits a different need, depending on what you define as \"create graphic interface\". If you need to create a simple graphics output, build the polygons from text using one of the graphics utilities mentioned above. If you need to create a professional-looking image, try using mapnik (mentioned in some other answers), which easily reads shapefiles. If you need to create a fully functional GUI, it's probably not a beginner's task - you should start with programming basic GUI applications before diving into shapefiles and polygons.\nIf, however, you just need to view the polygons - skip python and just use qgis, which will very easily visualize your polygons. It also comes with a handful of other nice features, like colors, zooms and so on.\n\n(source: sourceforge.net) \n",
"I would approach this by breaking it up into smaller problems and solving each of them\na) How do I connect to a postgresql database with python?\nhttps://stackoverflow.com/search?q=postgresql+database+python - Looks like psycopg2 is a good option as Adam Matan suggested.\nb) Drawing shapefile data in python\npostgresql and python\n",
"Mapnik is great for drawing maps. It can handle various formats and shapefiles, too. As far as I know it also supports PostgreSQL (at least PostGIS). \nAnd least but not last: it comes with a Python interface (see Getting started)\n"
] |
[
6,
0,
0
] |
[] |
[] |
[
"database",
"postgresql",
"python",
"visualization"
] |
stackoverflow_0001778663_database_postgresql_python_visualization.txt
|
Q:
Arched Relationship Infographic In Python
This is a very specific inforgraphic challange altough the fundemental question is how do you build archs between words using matplotlib, cario or an other python libary.
Given a the following data structure.
me, you, 7 |
me, apple, 9 |
apple, you, 1 |
bike, me, 5
Names would be displayed horizontally the names with the most relationships larger than the others and then there would be weighted archs between the names. A 10 weighted arch would be twice as thick as a 5 weighted arch.
Inspiration comes from: similar diverstiy. http://similardiversity.net/
Let the challange commence!
A:
matplotlib isn't the right library here, since it's not a general purpose graphics library. What you need here is either something like Cairo, or much simpler, you can do with the graphics capabilities of any GUI toolkit, such as PyQt. Another feasible approach is PyGame, which has good drawing capabilities as well.
If you want an example, see this Cairo samples page, the first sample - arc. You just write the text words and then use the arc code for an arc of any width and color between them.
A:
There are several libraries, at least one of which relies on Matplotlib, that will do what you want. I recommend Networkx (www.networkx.lanl.gov) to build your graph structure, and which you can then use to call the relevant Matplotlib methods to plot. Networkx and Matplotlib work very well together.
import networkx as NX
import matplotlib.pyplot as PLT
Gh = NX.Graph()
Gh.add_edge("You", "Bike", weight=1.0)
Gh.add_edge("Bike", "Apple", weight=0.9)
Gh.add_edge("Me", "Bike", weight=1.1)
all_nodes = Gh.nodes()
# to scale node size with degree:
scaled_node_size = lambda(node) : NX.degree(Gh, node) * 700
position = NX.spring_layout(Gh) # just choose a layout scheme
NX.draw_networkx_nodes(Gh, position, node_size=map(scaled_node_size, all_nodes))
NX.draw_network_edges(Gh, position, Gh.edges(), width=1.0, alpha=1.0, edge_color="red")
# now for the Matplotlib part:
PLT.axis("off")
PLT.show()
As you can see, you could scale the edges by applying a factor to vary the 'weight' parameter to any of the 'edge' methods, just the same way as i did it for node scaling.
I would also recommend pygraphviz (obviously using graphviz as its backend). It is very similar to Netwworkx (same lead developer).
A:
I don't really see where the difficulty or challenge is. All you need is a graphics library that can draw text and half circles, which is possible in pretty much everything. There is no need for Bezier curves. For example you could simply create an SVG file (then you don't even need any library and can nicely embed this in a webpage and use some JavaScript to make it interactive).
The actual plotting is simple: the center of a circle is in the middle between the two words, the radius is half the distance between them. You can then adjust the stroke to reflect other quantities.
|
Arched Relationship Infographic In Python
|
This is a very specific inforgraphic challange altough the fundemental question is how do you build archs between words using matplotlib, cario or an other python libary.
Given a the following data structure.
me, you, 7 |
me, apple, 9 |
apple, you, 1 |
bike, me, 5
Names would be displayed horizontally the names with the most relationships larger than the others and then there would be weighted archs between the names. A 10 weighted arch would be twice as thick as a 5 weighted arch.
Inspiration comes from: similar diverstiy. http://similardiversity.net/
Let the challange commence!
|
[
"matplotlib isn't the right library here, since it's not a general purpose graphics library. What you need here is either something like Cairo, or much simpler, you can do with the graphics capabilities of any GUI toolkit, such as PyQt. Another feasible approach is PyGame, which has good drawing capabilities as well. \nIf you want an example, see this Cairo samples page, the first sample - arc. You just write the text words and then use the arc code for an arc of any width and color between them.\n",
"There are several libraries, at least one of which relies on Matplotlib, that will do what you want. I recommend Networkx (www.networkx.lanl.gov) to build your graph structure, and which you can then use to call the relevant Matplotlib methods to plot. Networkx and Matplotlib work very well together. \nimport networkx as NX\nimport matplotlib.pyplot as PLT\nGh = NX.Graph()\nGh.add_edge(\"You\", \"Bike\", weight=1.0)\nGh.add_edge(\"Bike\", \"Apple\", weight=0.9)\nGh.add_edge(\"Me\", \"Bike\", weight=1.1)\nall_nodes = Gh.nodes()\n# to scale node size with degree:\nscaled_node_size = lambda(node) : NX.degree(Gh, node) * 700\nposition = NX.spring_layout(Gh) # just choose a layout scheme\nNX.draw_networkx_nodes(Gh, position, node_size=map(scaled_node_size, all_nodes))\nNX.draw_network_edges(Gh, position, Gh.edges(), width=1.0, alpha=1.0, edge_color=\"red\")\n# now for the Matplotlib part:\nPLT.axis(\"off\")\nPLT.show()\n\nAs you can see, you could scale the edges by applying a factor to vary the 'weight' parameter to any of the 'edge' methods, just the same way as i did it for node scaling.\nI would also recommend pygraphviz (obviously using graphviz as its backend). It is very similar to Netwworkx (same lead developer).\n",
"I don't really see where the difficulty or challenge is. All you need is a graphics library that can draw text and half circles, which is possible in pretty much everything. There is no need for Bezier curves. For example you could simply create an SVG file (then you don't even need any library and can nicely embed this in a webpage and use some JavaScript to make it interactive).\nThe actual plotting is simple: the center of a circle is in the middle between the two words, the radius is half the distance between them. You can then adjust the stroke to reflect other quantities.\n"
] |
[
4,
1,
0
] |
[] |
[] |
[
"graphic",
"graphviz",
"matplotlib",
"python"
] |
stackoverflow_0001679917_graphic_graphviz_matplotlib_python.txt
|
Q:
Populating values in module namespace
I have a python module.
I want to populate some values to it at runtime, how do I do it.
Eg. I have a list,
['A', 'B', 'C']
I am creating there classes with these names, and want them to available as if I created them normally
for el in ['A', 'B', 'C']:
type(el, (object,), {})
A:
I can think of a couple ways to do this... In order of (what I believe to be) best to worst we have:
First, setting attributes on the current module
# The first way I had of grabbing the module:
mod = __import__(__name__, fromlist=['nonempty'])
# From Roger's suggestion:
import sys
mod = sys.modules[__name__]
for name in ['A', 'B', 'C']:
class_ = type(name, (object, ), {})
setattr(mod, name, class_)
print A, B, C
Second, setting into the current globals dict:
for name in ['A', 'B', 'C']:
class_ = type(name, (object, ), {})
globals()[name] = class_
print A, B, C
Last, using exec (eww):
for name in ['A', 'B', 'C']:
class_ = type(name, (object, ), {})
exec "%s = class_" % name
print A, B, C
I have tested all three of these work in a stand alone script (where __name__ == "__main__") and as a module in a larger package.
EDIT: With regards to the discussion of method 1 vs method 2 in the comments, they both do EXACTLY the same thing. The name space of a module is defined in a dict stored on the module (here are the docs). From module level you can get this via globals() and from outside you can access it via attributes, or the __dict__ attribute of the module.
An interactive session to demonstrate:
Python 2.6.4 (r264:75706, Nov 8 2009, 17:35:59)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> mod = sys.modules[__name__]
>>> mod.__dict__ is globals()
True
A:
To create your classes dynamically and make them available in the module mymodule:
import mymodule
for el in ['A', 'B', 'C']:
setattr(mymodule, el, type(el, (object,), {}))
To create the classes in the current module, use the approach in Mike's answer.
|
Populating values in module namespace
|
I have a python module.
I want to populate some values to it at runtime, how do I do it.
Eg. I have a list,
['A', 'B', 'C']
I am creating there classes with these names, and want them to available as if I created them normally
for el in ['A', 'B', 'C']:
type(el, (object,), {})
|
[
"I can think of a couple ways to do this... In order of (what I believe to be) best to worst we have:\nFirst, setting attributes on the current module\n# The first way I had of grabbing the module:\nmod = __import__(__name__, fromlist=['nonempty'])\n\n# From Roger's suggestion:\nimport sys\nmod = sys.modules[__name__]\n\nfor name in ['A', 'B', 'C']:\n class_ = type(name, (object, ), {})\n setattr(mod, name, class_)\n\nprint A, B, C\n\nSecond, setting into the current globals dict:\nfor name in ['A', 'B', 'C']:\n class_ = type(name, (object, ), {})\n globals()[name] = class_\n\nprint A, B, C\n\nLast, using exec (eww):\nfor name in ['A', 'B', 'C']:\n class_ = type(name, (object, ), {})\n exec \"%s = class_\" % name\n\nprint A, B, C\n\nI have tested all three of these work in a stand alone script (where __name__ == \"__main__\") and as a module in a larger package.\nEDIT: With regards to the discussion of method 1 vs method 2 in the comments, they both do EXACTLY the same thing. The name space of a module is defined in a dict stored on the module (here are the docs). From module level you can get this via globals() and from outside you can access it via attributes, or the __dict__ attribute of the module.\nAn interactive session to demonstrate:\nPython 2.6.4 (r264:75706, Nov 8 2009, 17:35:59) \n[GCC 4.2.1 (Apple Inc. build 5646)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import sys\n>>> mod = sys.modules[__name__]\n>>> mod.__dict__ is globals()\nTrue\n\n",
"To create your classes dynamically and make them available in the module mymodule:\nimport mymodule\nfor el in ['A', 'B', 'C']:\n setattr(mymodule, el, type(el, (object,), {}))\n\nTo create the classes in the current module, use the approach in Mike's answer.\n"
] |
[
5,
2
] |
[] |
[] |
[
"metaprogramming",
"module",
"python"
] |
stackoverflow_0001778846_metaprogramming_module_python.txt
|
Q:
When should I drop support for python2.4 on my public python library?
I maintain an open source python project. Right now it supports python 2.4, 2.5, 2.6. I am looking for to add support for python 3. I guess it will be easier if I drop 2.4 support.
I know it is possible to support all but it is very annoying if I have to install 4 or 5 python versions on my machine and run the tests on all of them. Although it is easy to avoid new features introduced in the language I would like to make use of them! And what is the point of supporting something that possible nobody uses? I do want to drop it, but also dont want to loose users (existing and new).
When should I drop support for python 2.4? Is there any recommendation on this?
A:
I'd say it depends on your target audience. For enterprise stuff I think RedHat (certainly CentOS 5) are still on 2.4 - so if you want typical RedHat/CentOS using people to able to install without resorting to third party python installations then I think you need to keep 2.4 for a while. If most of your users are more 'desktop' based running Fedora/Ubuntu then they probably have 2.5/2.6 already so it wouldn't be an issue for them.
A:
You don't have to drop support for 2.4 in order to add support for 3.x, as I'm sure you know. I've made coverage.py run on 2.3 through 3.1 with the same code. It's not always pretty, but it's possible: Running the same code on Python 2.x and 3.x.
A:
It's a matter of weighing pros and cons.
I suppose the real answer to this question is how many features there are in 2.5/2.6 that would really improve your library. It seems as though 2.4 becomes less and less worth supporting as time goes by.
On the other hand, there are still some people on Python 2.4. You have to decide if it's worth it to drop support for them to take advantage of newer features of Python 2.5.
A:
You don't have to drop anything, what works on 2.4, works on 2.5 and 2.6. You can easily avoid incompatibilities skipping "with", the ternary operation, et "import future".
Now, once you have a very stable and full featured version of your code and need to make a big achitectural change, start writting for Python 3.0. No rush, it won't be massively used before one year or two.
A good indicator is to focus on project that have the same audience as yours. When do they switch on the roadmap ?
GNOME ?
Django ?
Inkscape ?
A:
Track downloads of each version of your project. Graph the daily traffic (or weekly if there is too much variation day to day) for each version separately. Keep an eye on the trends and at some point you will see a distinctly downward trend for 2.4 compared to the rest. When that downward trend is well established, discontinue upgrades to the 2.4 version, but keep it available for download. You should include some kind of note in the README for the last 2.4 version, and maybe display a message when it is installed.
At this point, your work is done, unless you find some really glaring error that you want to fix. You don't ever have to actually discontinue the 2.4 version, just cease upgrading it.
And the graphs that you now produce every week will tell you when it is time to do the same for 2.5, and eventually 2.6.
A:
Any answer here is going to be subjective. I suggest you make a feature and user list. There are 2 things to consider here.
1: How will your program benefit - what features are better nicer/faster/less buggy in newer versions of Python ? What extra dependent libraries can your program utilize by sticking to an older version ? Not everything is ported to 3.x or even 2.5 yet.
2: How will your user benefit - What benefits do users gain from older versions. How much bigger / smaller does your user base get by dropping 2.4 and adding 3.x ? What does your user base look like currently.
The third is not really a point since direct benefit from Open Source to developers is kinda iffy - but what do you gain ? i.e. less time needed to maintain, faster development etc.
Hope making a summary will help you put things in perspective.
|
When should I drop support for python2.4 on my public python library?
|
I maintain an open source python project. Right now it supports python 2.4, 2.5, 2.6. I am looking for to add support for python 3. I guess it will be easier if I drop 2.4 support.
I know it is possible to support all but it is very annoying if I have to install 4 or 5 python versions on my machine and run the tests on all of them. Although it is easy to avoid new features introduced in the language I would like to make use of them! And what is the point of supporting something that possible nobody uses? I do want to drop it, but also dont want to loose users (existing and new).
When should I drop support for python 2.4? Is there any recommendation on this?
|
[
"I'd say it depends on your target audience. For enterprise stuff I think RedHat (certainly CentOS 5) are still on 2.4 - so if you want typical RedHat/CentOS using people to able to install without resorting to third party python installations then I think you need to keep 2.4 for a while. If most of your users are more 'desktop' based running Fedora/Ubuntu then they probably have 2.5/2.6 already so it wouldn't be an issue for them.\n",
"You don't have to drop support for 2.4 in order to add support for 3.x, as I'm sure you know. I've made coverage.py run on 2.3 through 3.1 with the same code. It's not always pretty, but it's possible: Running the same code on Python 2.x and 3.x.\n",
"It's a matter of weighing pros and cons.\nI suppose the real answer to this question is how many features there are in 2.5/2.6 that would really improve your library. It seems as though 2.4 becomes less and less worth supporting as time goes by. \nOn the other hand, there are still some people on Python 2.4. You have to decide if it's worth it to drop support for them to take advantage of newer features of Python 2.5.\n",
"You don't have to drop anything, what works on 2.4, works on 2.5 and 2.6. You can easily avoid incompatibilities skipping \"with\", the ternary operation, et \"import future\".\nNow, once you have a very stable and full featured version of your code and need to make a big achitectural change, start writting for Python 3.0. No rush, it won't be massively used before one year or two.\nA good indicator is to focus on project that have the same audience as yours. When do they switch on the roadmap ? \n\nGNOME ?\nDjango ?\nInkscape ?\n\n",
"Track downloads of each version of your project. Graph the daily traffic (or weekly if there is too much variation day to day) for each version separately. Keep an eye on the trends and at some point you will see a distinctly downward trend for 2.4 compared to the rest. When that downward trend is well established, discontinue upgrades to the 2.4 version, but keep it available for download. You should include some kind of note in the README for the last 2.4 version, and maybe display a message when it is installed.\nAt this point, your work is done, unless you find some really glaring error that you want to fix. You don't ever have to actually discontinue the 2.4 version, just cease upgrading it.\nAnd the graphs that you now produce every week will tell you when it is time to do the same for 2.5, and eventually 2.6.\n",
"Any answer here is going to be subjective. I suggest you make a feature and user list. There are 2 things to consider here.\n1: How will your program benefit - what features are better nicer/faster/less buggy in newer versions of Python ? What extra dependent libraries can your program utilize by sticking to an older version ? Not everything is ported to 3.x or even 2.5 yet.\n2: How will your user benefit - What benefits do users gain from older versions. How much bigger / smaller does your user base get by dropping 2.4 and adding 3.x ? What does your user base look like currently.\nThe third is not really a point since direct benefit from Open Source to developers is kinda iffy - but what do you gain ? i.e. less time needed to maintain, faster development etc.\nHope making a summary will help you put things in perspective.\n"
] |
[
7,
3,
2,
1,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001778670_python.txt
|
Q:
To insert to Pg by Psycopg
How can you fix the SQL-statement in Python?
The db connection works. However, cur.execute returns none which is false.
My code
import os, pg, sys, re, psycopg2
try:
conn = psycopg2.connect("dbname='tk' host='localhost' port='5432' user='naa' password='123'")
except: print "unable to connect to db"
cur = conn.cursor()
print cur.execute("SELECT * FROM courses") # problem here
The SQL-command in Psql returns me the correct output.
I can similarly run INSERT in Psql, but not by Python's scripts.
I get no warning/error to /var/log.
Possible bugs are
cursor(), seems to be right however
the syntax of the method connect(), seems to be ok however
A:
You have to call one of the fetch methods on cur (fetchone, fetchmany, fetchall) to actually get the results of the query.
You should probably have a read through the a tutorial for DB-API.
A:
You have to call cur.fetchall() method (or one of other fetch*() methods) to get results from query.
|
To insert to Pg by Psycopg
|
How can you fix the SQL-statement in Python?
The db connection works. However, cur.execute returns none which is false.
My code
import os, pg, sys, re, psycopg2
try:
conn = psycopg2.connect("dbname='tk' host='localhost' port='5432' user='naa' password='123'")
except: print "unable to connect to db"
cur = conn.cursor()
print cur.execute("SELECT * FROM courses") # problem here
The SQL-command in Psql returns me the correct output.
I can similarly run INSERT in Psql, but not by Python's scripts.
I get no warning/error to /var/log.
Possible bugs are
cursor(), seems to be right however
the syntax of the method connect(), seems to be ok however
|
[
"You have to call one of the fetch methods on cur (fetchone, fetchmany, fetchall) to actually get the results of the query.\nYou should probably have a read through the a tutorial for DB-API.\n",
"You have to call cur.fetchall() method (or one of other fetch*() methods) to get results from query.\n"
] |
[
2,
2
] |
[] |
[] |
[
"postgresql",
"psycopg",
"python"
] |
stackoverflow_0001779009_postgresql_psycopg_python.txt
|
Q:
Python subclass with C++ baseclass
I have some C++ I have exposed to Python through SWIG. In there is a base class with a single pure virtual function.
In Python, I import my module and define a class that uses the abstract class as base.
import mymodule
class Foo(mymodule.mybase):
...
In that module is also a manager class, I want to add my new defined class to the manager.
m = mymodule.mymanager()
m.add(Foo())
Definition of add:
void add(mybase* b) { ... }
Didn't work as I would expect:
TypeError: in method 'mymanager_add', argument 2 of type 'mymodule::mybase *'
What did I miss? It seems it's not sure that my Foo class is a "mybase". I tried adding a call to the base class constructor in Python but that didn't work, said the class was abstract.
def __init__(self):
mymodule.mybase.__init__(self)
A:
My guess is that Foo is not derived from mybase in the eyes of the C++ environment. I'm not sure if SWIG can pull this off since it requires a bidirectional understanding of inheritance - Python class uses C++ class as base and C++ code recognizes the inheritance relationship. I would take a serious look into Boost.python since it seems to support the functionality that you are after. Here's an entry on wiki.python.org about it.
A:
Not really an answer, but you might have better luck with boost.python. Don't know how much work it would be for you to switch, but you could probably get a simple inheritence test case for your problem going pretty quickly.
|
Python subclass with C++ baseclass
|
I have some C++ I have exposed to Python through SWIG. In there is a base class with a single pure virtual function.
In Python, I import my module and define a class that uses the abstract class as base.
import mymodule
class Foo(mymodule.mybase):
...
In that module is also a manager class, I want to add my new defined class to the manager.
m = mymodule.mymanager()
m.add(Foo())
Definition of add:
void add(mybase* b) { ... }
Didn't work as I would expect:
TypeError: in method 'mymanager_add', argument 2 of type 'mymodule::mybase *'
What did I miss? It seems it's not sure that my Foo class is a "mybase". I tried adding a call to the base class constructor in Python but that didn't work, said the class was abstract.
def __init__(self):
mymodule.mybase.__init__(self)
|
[
"My guess is that Foo is not derived from mybase in the eyes of the C++ environment. I'm not sure if SWIG can pull this off since it requires a bidirectional understanding of inheritance - Python class uses C++ class as base and C++ code recognizes the inheritance relationship. I would take a serious look into Boost.python since it seems to support the functionality that you are after. Here's an entry on wiki.python.org about it.\n",
"Not really an answer, but you might have better luck with boost.python. Don't know how much work it would be for you to switch, but you could probably get a simple inheritence test case for your problem going pretty quickly.\n"
] |
[
2,
0
] |
[] |
[] |
[
"c++",
"python",
"swig"
] |
stackoverflow_0001778487_c++_python_swig.txt
|
Q:
expand users table with django
I'm using the authentication that ships with django, and as such, it comes with its own SQL table. I have a few more attributes I'd like to use with the User model that are custom to my app such as a user photo or a random user blob where users can type in notes.
what's the best way of extending the existing user table that ships with django's authentication/authorization modeling to allow for my custom fields?
A:
Please see my (and others) answer to this question:
A:
The other way to handle this is to do table inheritance on the User model and develop your own derived EnhancedUser model. Typically a custom wrapper backend is also written to make sure the auth subsystem returns the EnhancedUser model as well.
There's a very good blog post answer here.
|
expand users table with django
|
I'm using the authentication that ships with django, and as such, it comes with its own SQL table. I have a few more attributes I'd like to use with the User model that are custom to my app such as a user photo or a random user blob where users can type in notes.
what's the best way of extending the existing user table that ships with django's authentication/authorization modeling to allow for my custom fields?
|
[
"Please see my (and others) answer to this question: \n",
"The other way to handle this is to do table inheritance on the User model and develop your own derived EnhancedUser model. Typically a custom wrapper backend is also written to make sure the auth subsystem returns the EnhancedUser model as well.\nThere's a very good blog post answer here.\n"
] |
[
2,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001778025_django_python.txt
|
Q:
There is no spawnl function in python 2.6?
I just noticed that my old codes written in python 2.5 does not work now. I am in python 2.6 btw.
>>> os.spawnl(os.P_NOWAIT,"setup.exe")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\python26\lib\os.py", line 612, in spawnl
return spawnv(mode, file, args)
OSError: [Errno 22] Invalid argument
>>>
Any clue? or do you have any working sample of os.spawn* with NOWAIT option.
Update:
Even I put full path in os.spawnl(), Its still error.
A:
thrope is right about subprocess being preferred. But the spawn* stuff is still there in 2.6. In fact, you can see that in your error message. Your first arg seems to be valid. I'd check the second arg, which is the path.
A:
I got it work by adding DUMMY parameter finally, a bit funky though
This is not working
os.spawnl(os.P_NOWAIT,"Setup.exe")
This is also not working
os.spawnl(os.P_NOWAIT,"Setup.exe","")
But this is working
os.spawnl(os.P_NOWAIT,"Setup.exe","DUMMY")
Thanks all anyway.
A:
I think its recommended to use the subprocess module these days rather than the os.spawn* functions. (I can't reproduce your problem, but I'm not on windows).
A:
os.spawnl() requires full path to executable, while os.spawnlp() uses PATH environment variable to find it.
Update: Also it's common error to use unescaped backslashes in the path literal (try printing it to see whether it's interpreted right).
A:
A Google search brings up this page about the same problem happening when there is a space in the Python installation path. I couldn't reproduce it here, but maybe it's the problem?
In any case, according to MS documentation this error value (EINVAL) should only be returned if the mode argument is invalid, which isn't the case here.
|
There is no spawnl function in python 2.6?
|
I just noticed that my old codes written in python 2.5 does not work now. I am in python 2.6 btw.
>>> os.spawnl(os.P_NOWAIT,"setup.exe")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\python26\lib\os.py", line 612, in spawnl
return spawnv(mode, file, args)
OSError: [Errno 22] Invalid argument
>>>
Any clue? or do you have any working sample of os.spawn* with NOWAIT option.
Update:
Even I put full path in os.spawnl(), Its still error.
|
[
"thrope is right about subprocess being preferred. But the spawn* stuff is still there in 2.6. In fact, you can see that in your error message. Your first arg seems to be valid. I'd check the second arg, which is the path.\n",
"I got it work by adding DUMMY parameter finally, a bit funky though\nThis is not working\nos.spawnl(os.P_NOWAIT,\"Setup.exe\")\n\nThis is also not working\nos.spawnl(os.P_NOWAIT,\"Setup.exe\",\"\")\n\nBut this is working\nos.spawnl(os.P_NOWAIT,\"Setup.exe\",\"DUMMY\")\n\nThanks all anyway.\n",
"I think its recommended to use the subprocess module these days rather than the os.spawn* functions. (I can't reproduce your problem, but I'm not on windows). \n",
"os.spawnl() requires full path to executable, while os.spawnlp() uses PATH environment variable to find it. \nUpdate: Also it's common error to use unescaped backslashes in the path literal (try printing it to see whether it's interpreted right). \n",
"A Google search brings up this page about the same problem happening when there is a space in the Python installation path. I couldn't reproduce it here, but maybe it's the problem?\nIn any case, according to MS documentation this error value (EINVAL) should only be returned if the mode argument is invalid, which isn't the case here.\n"
] |
[
5,
5,
3,
2,
2
] |
[] |
[] |
[
"python",
"python_2.6"
] |
stackoverflow_0001779081_python_python_2.6.txt
|
Q:
What does abstract mean in this context?
I need some help in understanding a python concept.
class TilePuzzleProblem(search.Problem):
""" This class is the class for the NxN - blanks tile puzzle problem """
def __init__(self, N, blanks, initial, goal):
""" Initialize """
search.Problem.__init__(self, initial, goal)
self.N = N
self.blanks = blanks
def successor(self, state):
""" Generate the successors of the given state. Returns a list of (move, successor) pairs"""
abstract
def h(self, node):
abstract
Currently the code hangs at the abstract part of the function h(...), but I have no idea what abstract means, hence can not understand what the problem is.
A:
This is a trick described here. There's not keyword abstract in Python, so, if you won't override this method in some subclass, it'll cause NotImplementedError.
A:
An abstract method is one which a class doesn't implement, making it an abstract class; subclasses must override all abstract methods (i.e., provide concrete implementations) to be concrete classes, i.e., ones for which you can make instances. The normal way in Python to express "this method is abstract" is to have the method's body be raise NotImplementedError.
For more about the general concept, apart from its specifics in Python, see wikipedia.
So, formally, you need to subclass this and implement those two methods marked as "abstract". (Depending on your TA's hints, he or she may actually mean that you should replace the word "abstract" with a working body of code, but that would be quite a stretch with respect the normal meaning of "abstract" in OOP!-).
A:
An abstract function is a function with no implementation. It's a placeholder, just there to fill out the class contract so that you know what methods subclass should provide. What you need to do here is create a descendant of TilePuzzleProblem and fill in your own implementation of h. If you want to run it as is, create a descendant and make your h do nothing.
A:
Abstract means the class must be inherited. Abstract or "base" classes are there to provide a base type which you can extend through inheritance. You cannot instantiate an abstract class, only the classes that inherit it.
See this Wikipedia article for more information.
One reason you'd want to use an abstract base class is if you want to categorize or group your sub-types. For example, Car, Truck and Plane would all inherit from the Vehicle abstract base class. You can't just instantiate a "vehicle", you have to instantiate a car, truck or plane. Being abstract protects it from being instantiated.
|
What does abstract mean in this context?
|
I need some help in understanding a python concept.
class TilePuzzleProblem(search.Problem):
""" This class is the class for the NxN - blanks tile puzzle problem """
def __init__(self, N, blanks, initial, goal):
""" Initialize """
search.Problem.__init__(self, initial, goal)
self.N = N
self.blanks = blanks
def successor(self, state):
""" Generate the successors of the given state. Returns a list of (move, successor) pairs"""
abstract
def h(self, node):
abstract
Currently the code hangs at the abstract part of the function h(...), but I have no idea what abstract means, hence can not understand what the problem is.
|
[
"This is a trick described here. There's not keyword abstract in Python, so, if you won't override this method in some subclass, it'll cause NotImplementedError. \n",
"An abstract method is one which a class doesn't implement, making it an abstract class; subclasses must override all abstract methods (i.e., provide concrete implementations) to be concrete classes, i.e., ones for which you can make instances. The normal way in Python to express \"this method is abstract\" is to have the method's body be raise NotImplementedError.\nFor more about the general concept, apart from its specifics in Python, see wikipedia.\nSo, formally, you need to subclass this and implement those two methods marked as \"abstract\". (Depending on your TA's hints, he or she may actually mean that you should replace the word \"abstract\" with a working body of code, but that would be quite a stretch with respect the normal meaning of \"abstract\" in OOP!-).\n",
"An abstract function is a function with no implementation. It's a placeholder, just there to fill out the class contract so that you know what methods subclass should provide. What you need to do here is create a descendant of TilePuzzleProblem and fill in your own implementation of h. If you want to run it as is, create a descendant and make your h do nothing.\n",
"Abstract means the class must be inherited. Abstract or \"base\" classes are there to provide a base type which you can extend through inheritance. You cannot instantiate an abstract class, only the classes that inherit it.\nSee this Wikipedia article for more information.\nOne reason you'd want to use an abstract base class is if you want to categorize or group your sub-types. For example, Car, Truck and Plane would all inherit from the Vehicle abstract base class. You can't just instantiate a \"vehicle\", you have to instantiate a car, truck or plane. Being abstract protects it from being instantiated.\n"
] |
[
11,
5,
1,
0
] |
[] |
[] |
[
"abstract",
"python"
] |
stackoverflow_0001779365_abstract_python.txt
|
Q:
How do I save to a field that is specified in a variable?
I want to do something like this:
# models.py
class Model(models.Model):
name_in_my_model = models.CharField(max_length=100)
# later
fieldname = 'name_in_my_model'
# this is what I want to do somehow:
obj = Model.objects.get(pk=1)
obj.fieldname = 'new name'
obj.save()
Is this possible? I'm making a reusable application, and the user needs to specify a name of a field that is going to be updated by my app.
A:
You can use: setattr(obj, fieldname, 'new name').
|
How do I save to a field that is specified in a variable?
|
I want to do something like this:
# models.py
class Model(models.Model):
name_in_my_model = models.CharField(max_length=100)
# later
fieldname = 'name_in_my_model'
# this is what I want to do somehow:
obj = Model.objects.get(pk=1)
obj.fieldname = 'new name'
obj.save()
Is this possible? I'm making a reusable application, and the user needs to specify a name of a field that is going to be updated by my app.
|
[
"You can use: setattr(obj, fieldname, 'new name').\n"
] |
[
5
] |
[] |
[] |
[
"django",
"django_models",
"python"
] |
stackoverflow_0001779567_django_django_models_python.txt
|
Q:
Problem with logic in Django template
Supose this portion of a Django template. regs is a list of Reg objects. Reg.editable is a BooleanField.
I want to render a radio button per element in the list. If r.editable is False, the radio button must be disabled:
{% for r in regs %}
<input type="radio" value="{{ forloop.counter }}"
{% if forloop.first %}checked="checked"{% endif %}
{% if not r.editable %}disabled="disabled"{% endif %}/>
{% endfor %}
As you can see, I'm using forloop.first to check the first radio button, but this has a problem! What about if the first element has editable == False? The first radio button will be rendered disabled and chequed. If then a user submit "the form" I'll receive a value not expected.
Am I clear with the problem here? How can I rewrite this template to render as checked the FIRST ENABLED radio button?
Thanks
A:
Djangos templating language doesn't give you a lot in the way of logic in the template (I've heard positive things about Jinja2 if you want to change that). There's also the "Smart" {% if %} tag which adds some more functionality and incidentally is being proposed for inclusion in Django 1.2.
As for solving this problem I would most likely move the logic over to the view. (Disclaimer: don't have the time to test this code snippet but it should provide the general idea)
def my_view(request, *args, **kwargs):
# QuerySet is fetched however it's done...
regs = Regs.objects.all()
# Wrap regs in display information
checked = False
radio_buttons = []
for r in regs:
if r.editable:
if not checked:
radio_buttons.append( { 'checked':True, 'enabled':True, 'object':r } )
# Set to true once
checked = True
else:
radio_buttons.append( { 'checked':False, 'enabled':True, 'object':r } )
else:
radio_buttons.append( { 'checked':False, 'enabled':False, 'object':r } )
# Then pass in radio_buttons for the value of regs down here
render_to_whatever(..., { 'regs':radio_buttons } )
In this case we've wrapped the QuerySet which will give our template some more details about rendering. The template becomes "dumb" now.
{% for r in regs %}
<input type="radio" value="{{ forloop.counter }}"
{% if r.checked %}checked="checked"{% endif %}
{% if not r.enabled %}disabled="disabled"{% endif %}/>
{% comment %} To access the original object use: {{ r.object }} {% endcomment %}
{% endfor %}
A:
Just adjust your ifs
{% for r in regs %}
{% if forloop.first %}
<input type="radio" value="{{ forloop.counter }}" checked="checked"/>
{% else %}
{% if not r.editable %}
<input type="radio" value="{{ forloop.counter }}" disabled="disabled"/>
{% endif %}
{% endif %}
{% endfor %}
PS: Your question did not clearly explain what you wanted. I made some reasonable assumption. Update the question if what you want is something else.
A:
The real answer to this question is as follows:
Such logic has no place in the template. You can preprocess the context before passing it to the template, thus eleminating the need to do this using the (intentionally) crippled template engine logic.
In my opinion, what you are doing is wrong. I mean, django has perfectly fine forms api, why render the inputs directly then? Some might argue, that django's forms api is inflexible, but for this specific need it will undoubtely be sufficient.
And to reiterate - this kind of logic does not belong in the presentation layer. So don't put it there, it will bite you. In fact it already did.
A:
Similar to T. Stone's answer of doing this logic in the view, you could just add a new template variable that indicated the first checked radio:
def my_view(request, *args, **kwargs):
regs = Regs.objects.all()
checked_index = None
for i, reg in enumerate(regs):
if reg.enabled:
checked_index = i
break
# pass checked_index into the template...
Template:
{% for r in regs %}
{% ifequal forloop.counter0 checked_index %}
<input type="radio" value="{{ forloop.counter }}" checked="checked"/>
{% else %}
<input type="radio" value="{{ forloop.counter }}" {% if not r.editable %}disabled="disabled"{% endif %}/>
{% endif %}
{% endfor %}
A:
Similar to becomingGuru but solving your problems:
{% for r in regs %}
{% if not r.editable %}
<input type="radio" value="{{ forloop.counter }}" disabled="disabled"/>
{% else %}
{% if forloop.first %}
<input type="radio" value="{{ forloop.counter }}" checked="checked"/>
{% endif %}
{% endif %}
{% endfor %}
It first checks if r is editable, and then checks if it is the first.
Regards.
|
Problem with logic in Django template
|
Supose this portion of a Django template. regs is a list of Reg objects. Reg.editable is a BooleanField.
I want to render a radio button per element in the list. If r.editable is False, the radio button must be disabled:
{% for r in regs %}
<input type="radio" value="{{ forloop.counter }}"
{% if forloop.first %}checked="checked"{% endif %}
{% if not r.editable %}disabled="disabled"{% endif %}/>
{% endfor %}
As you can see, I'm using forloop.first to check the first radio button, but this has a problem! What about if the first element has editable == False? The first radio button will be rendered disabled and chequed. If then a user submit "the form" I'll receive a value not expected.
Am I clear with the problem here? How can I rewrite this template to render as checked the FIRST ENABLED radio button?
Thanks
|
[
"Djangos templating language doesn't give you a lot in the way of logic in the template (I've heard positive things about Jinja2 if you want to change that). There's also the \"Smart\" {% if %} tag which adds some more functionality and incidentally is being proposed for inclusion in Django 1.2.\nAs for solving this problem I would most likely move the logic over to the view. (Disclaimer: don't have the time to test this code snippet but it should provide the general idea)\ndef my_view(request, *args, **kwargs):\n\n # QuerySet is fetched however it's done...\n regs = Regs.objects.all()\n\n # Wrap regs in display information \n checked = False\n radio_buttons = []\n\n for r in regs:\n if r.editable:\n if not checked:\n radio_buttons.append( { 'checked':True, 'enabled':True, 'object':r } )\n # Set to true once\n checked = True\n else:\n radio_buttons.append( { 'checked':False, 'enabled':True, 'object':r } )\n else:\n radio_buttons.append( { 'checked':False, 'enabled':False, 'object':r } ) \n\n # Then pass in radio_buttons for the value of regs down here\n render_to_whatever(..., { 'regs':radio_buttons } )\n\nIn this case we've wrapped the QuerySet which will give our template some more details about rendering. The template becomes \"dumb\" now.\n{% for r in regs %}\n <input type=\"radio\" value=\"{{ forloop.counter }}\"\n {% if r.checked %}checked=\"checked\"{% endif %}\n {% if not r.enabled %}disabled=\"disabled\"{% endif %}/> \n {% comment %} To access the original object use: {{ r.object }} {% endcomment %}\n{% endfor %}\n\n",
"Just adjust your ifs\n{% for r in regs %}\n {% if forloop.first %}\n <input type=\"radio\" value=\"{{ forloop.counter }}\" checked=\"checked\"/>\n {% else %}\n {% if not r.editable %}\n <input type=\"radio\" value=\"{{ forloop.counter }}\" disabled=\"disabled\"/> \n {% endif %}\n {% endif %}\n{% endfor %}\n\nPS: Your question did not clearly explain what you wanted. I made some reasonable assumption. Update the question if what you want is something else.\n",
"The real answer to this question is as follows:\nSuch logic has no place in the template. You can preprocess the context before passing it to the template, thus eleminating the need to do this using the (intentionally) crippled template engine logic.\nIn my opinion, what you are doing is wrong. I mean, django has perfectly fine forms api, why render the inputs directly then? Some might argue, that django's forms api is inflexible, but for this specific need it will undoubtely be sufficient.\nAnd to reiterate - this kind of logic does not belong in the presentation layer. So don't put it there, it will bite you. In fact it already did.\n",
"Similar to T. Stone's answer of doing this logic in the view, you could just add a new template variable that indicated the first checked radio:\ndef my_view(request, *args, **kwargs):\n regs = Regs.objects.all()\n checked_index = None\n for i, reg in enumerate(regs):\n if reg.enabled:\n checked_index = i\n break\n # pass checked_index into the template...\n\nTemplate:\n{% for r in regs %}\n {% ifequal forloop.counter0 checked_index %}\n <input type=\"radio\" value=\"{{ forloop.counter }}\" checked=\"checked\"/>\n {% else %}\n <input type=\"radio\" value=\"{{ forloop.counter }}\" {% if not r.editable %}disabled=\"disabled\"{% endif %}/> \n {% endif %}\n{% endfor %}\n\n",
"Similar to becomingGuru but solving your problems:\n{% for r in regs %}\n {% if not r.editable %}\n <input type=\"radio\" value=\"{{ forloop.counter }}\" disabled=\"disabled\"/> \n {% else %}\n {% if forloop.first %}\n <input type=\"radio\" value=\"{{ forloop.counter }}\" checked=\"checked\"/>\n {% endif %}\n {% endif %}\n{% endfor %}\n\nIt first checks if r is editable, and then checks if it is the first.\nRegards.\n"
] |
[
2,
1,
1,
0,
0
] |
[] |
[] |
[
"django",
"django_templates",
"python",
"templates"
] |
stackoverflow_0001779055_django_django_templates_python_templates.txt
|
Q:
Making ORM with Python's Storm
The question is based on the thread, since I observed that Storm allows me reuse my SQL-schemas.
How can you solve the following error message in Storm?
The code is based on Jason's answer and on Storm's manual.
import os, pg, sys, re, psycopg2, storm
from storm.locals import *
from storm import *
class Courses():
subject = Unicode()
database = create_database("postgres://naa:123@localhost:5432/tk")
store = Store(database)
course = Courses()
course.subject = 'abcd'
store.add(course)
It gives you
Traceback (most recent call last):
File "<stdin>", line 13, in <module>
File "/usr/lib/python2.6/dist-packages/storm/store.py", line 245, in add
obj_info = get_obj_info(obj)
File "/usr/lib/python2.6/dist-packages/storm/info.py", line 40, in get_obj_info
obj_info = ObjectInfo(obj)
File "/usr/lib/python2.6/dist-packages/storm/info.py", line 162, in __init__
self.cls_info = get_cls_info(type(obj))
File "/usr/lib/python2.6/dist-packages/storm/info.py", line 51, in get_cls_info
cls.__storm_class_info__ = ClassInfo(cls)
File "/usr/lib/python2.6/dist-packages/storm/info.py", line 69, in __init__
raise ClassInfoError("%s.__storm_table__ missing" % repr(cls))
storm.exceptions.ClassInfoError: <type 'instance'>.__storm_table__ missing
This suggests to me that some module is missing. There is no module instance in Storm.
A:
I'll leave out the connection details because I'm not terribly familiar with Postgres.
from storm.locals import *
class Courses(object):
__storm_table__ = 'courses'
pkey = Int(primary=True)
course_nro = Unicode()
course = Courses()
course.course_nro = 'abcd'
store.add(course)
store.commit()
Of course, if you want to do the constructor and initialization on one line, you can use pysistence's expandos:
from storm.locals import *
from pysistence import Expando
class Courses(Expando):
__storm_table__ = 'courses'
pkey = Int(primary=True)
course_nro = Unicode()
course = Courses(course_nro='abcd')
store.add(course)
store.commit()
|
Making ORM with Python's Storm
|
The question is based on the thread, since I observed that Storm allows me reuse my SQL-schemas.
How can you solve the following error message in Storm?
The code is based on Jason's answer and on Storm's manual.
import os, pg, sys, re, psycopg2, storm
from storm.locals import *
from storm import *
class Courses():
subject = Unicode()
database = create_database("postgres://naa:123@localhost:5432/tk")
store = Store(database)
course = Courses()
course.subject = 'abcd'
store.add(course)
It gives you
Traceback (most recent call last):
File "<stdin>", line 13, in <module>
File "/usr/lib/python2.6/dist-packages/storm/store.py", line 245, in add
obj_info = get_obj_info(obj)
File "/usr/lib/python2.6/dist-packages/storm/info.py", line 40, in get_obj_info
obj_info = ObjectInfo(obj)
File "/usr/lib/python2.6/dist-packages/storm/info.py", line 162, in __init__
self.cls_info = get_cls_info(type(obj))
File "/usr/lib/python2.6/dist-packages/storm/info.py", line 51, in get_cls_info
cls.__storm_class_info__ = ClassInfo(cls)
File "/usr/lib/python2.6/dist-packages/storm/info.py", line 69, in __init__
raise ClassInfoError("%s.__storm_table__ missing" % repr(cls))
storm.exceptions.ClassInfoError: <type 'instance'>.__storm_table__ missing
This suggests to me that some module is missing. There is no module instance in Storm.
|
[
"I'll leave out the connection details because I'm not terribly familiar with Postgres.\nfrom storm.locals import *\n\nclass Courses(object):\n __storm_table__ = 'courses'\n pkey = Int(primary=True)\n course_nro = Unicode()\n\ncourse = Courses()\ncourse.course_nro = 'abcd'\nstore.add(course)\nstore.commit()\n\nOf course, if you want to do the constructor and initialization on one line, you can use pysistence's expandos:\nfrom storm.locals import *\nfrom pysistence import Expando\n\nclass Courses(Expando):\n __storm_table__ = 'courses'\n pkey = Int(primary=True)\n course_nro = Unicode()\n\ncourse = Courses(course_nro='abcd')\nstore.add(course)\nstore.commit()\n\n"
] |
[
4
] |
[] |
[] |
[
"orm",
"python",
"storm_orm"
] |
stackoverflow_0001779750_orm_python_storm_orm.txt
|
Q:
What is wrong with the pearson algorithm from “Programming Collective Intelligence”?
This function is from the book "Programming Collective Intelligence”, and is supposed to calculate the Pearson correlation coefficient for p1 and p2, which is supposed to be a number between -1 and 1.
If two critics rate items very similarly the function should return 1, or close to 1.
With real user data I sometimes get weird results. In the following example the dataset critics2 should return 1 - instead it returns 0.
Does anyone spot a mistake?
(This is not a duplicate of What is wrong with this python function from “Programming Collective Intelligence”)
from __future__ import division
from math import sqrt
def sim_pearson(prefs,p1,p2):
si={}
for item in prefs[p1]:
if item in prefs[p2]: si[item]=1
if len(si)==0: return 0
n=len(si)
sum1=sum([prefs[p1][it] for it in si])
sum2=sum([prefs[p2][it] for it in si])
sum1Sq=sum([pow(prefs[p1][it],2) for it in si])
sum2Sq=sum([pow(prefs[p2][it],2) for it in si])
pSum=sum([prefs[p1][it]*prefs[p2][it] for it in si])
num=pSum-(sum1*sum2/n)
den=sqrt((sum1Sq-pow(sum1,2)/n)*(sum2Sq-pow(sum2,2)/n))
if den==0: return 0
r=num/den
return r
critics = {
'user1':{
'item1': 3,
'item2': 5,
'item3': 5,
},
'user2':{
'item1': 4,
'item2': 5,
'item3': 5,
}
}
critics2 = {
'user1':{
'item1': 5,
'item2': 5,
'item3': 5,
},
'user2':{
'item1': 5,
'item2': 5,
'item3': 5,
}
}
critics3 = {
'user1':{
'item1': 1,
'item2': 3,
'item3': 5,
},
'user2':{
'item1': 5,
'item2': 3,
'item3': 1,
}
}
print sim_pearson(critics, 'user1', 'user2', )
result: 1.0 (expected)
print sim_pearson(critics2, 'user1', 'user2', )
result: 0 (unexpected)
print sim_pearson(critics3, 'user1', 'user2', )
result: -1 (expected)
A:
There is nothing wrong in your result. You are trying to plot a line through 3 points. In second case you have all three points with the same coordinates, i.e. effectively one point. You can't say do these points correlate or anti-correlate, because you can draw infinite number of lines through one point (den in your code equals to zero).
A:
If you look up Pearson correlation on wikipedia, you'll see that the formula uses the difference between each item in a series and the mean of the series. When all the items in the series are the same, you get division by zero, so your calculation fails.
If it is any clearer, you can use this code:
def simplified_sim_pearson(p1, p2):
n = len(p1)
assert (n != 0)
sum1 = sum(p1)
sum2 = sum(p2)
m1 = float(sum1) / n
m2 = float(sum2) / n
p1mean = [(x - m1) for x in p1]
p2mean = [(y - m2) for y in p2]
numerator = sum(x * y for x, y in zip(p1mean, p2mean))
denominator = math.sqrt(sum(x * x for x in p1mean) * sum(y * y for y in p2mean))
return numerator / denominator if denominator else 0
def sim_pearson(prefs,p1,p2):
p1 = prefs[p1]
p2 = prefs[p2]
si = set(p1.keys()).intersection(set(p2.keys()))
p1_x = [p1[k] for k in sorted(si)]
p2_x = [p2[k] for k in sorted(si)]
return simplified_sim_pearson(p1_x, p2_x)
critics = {
'user1':{
'item1': 3,
'item2': 5,
'item3': 5,
},
'user2':{
'item1': 4,
'item2': 5,
'item3': 5,
}
}
critics2 = {
'user1':{
'item1': 5,
'item2': 5,
'item3': 5,
},
'user2':{
'item1': 5,
'item2': 5,
'item3': 5,
}
}
critics3 = {
'user1':{
'item1': 1,
'item2': 3,
'item3': 5,
},
'user2':{
'item1': 5,
'item2': 3,
'item3': 1,
}
}
print sim_pearson(critics, 'user1', 'user2', )
print sim_pearson(critics2, 'user1', 'user2', )
print sim_pearson(critics3, 'user1', 'user2', )
By the way, using Excel to determine the correct answer is a good way to validate most calculations. In this case, you would have used correl.
A:
The algorithm gives the correct result. 0 means that there is no correlation between them (or at least you can't tell from what you know).
Generally (depending on what domain you apply this algorithm) you can consider everything between -0.9 < x < 0.09 as "No correlation observable".
A:
Correlation does not imply causation. Had to say it. You need to develop an understanding of correlation statistics. Correlation can be between -1 and 1 and a value of 0 falls in this range and is a perfectly reasonable result. A correlation of 0 implies that there is not statistically significant relationship between the 2 variables. Remember to avoid doing statistics with less that 30 samples.
|
What is wrong with the pearson algorithm from “Programming Collective Intelligence”?
|
This function is from the book "Programming Collective Intelligence”, and is supposed to calculate the Pearson correlation coefficient for p1 and p2, which is supposed to be a number between -1 and 1.
If two critics rate items very similarly the function should return 1, or close to 1.
With real user data I sometimes get weird results. In the following example the dataset critics2 should return 1 - instead it returns 0.
Does anyone spot a mistake?
(This is not a duplicate of What is wrong with this python function from “Programming Collective Intelligence”)
from __future__ import division
from math import sqrt
def sim_pearson(prefs,p1,p2):
si={}
for item in prefs[p1]:
if item in prefs[p2]: si[item]=1
if len(si)==0: return 0
n=len(si)
sum1=sum([prefs[p1][it] for it in si])
sum2=sum([prefs[p2][it] for it in si])
sum1Sq=sum([pow(prefs[p1][it],2) for it in si])
sum2Sq=sum([pow(prefs[p2][it],2) for it in si])
pSum=sum([prefs[p1][it]*prefs[p2][it] for it in si])
num=pSum-(sum1*sum2/n)
den=sqrt((sum1Sq-pow(sum1,2)/n)*(sum2Sq-pow(sum2,2)/n))
if den==0: return 0
r=num/den
return r
critics = {
'user1':{
'item1': 3,
'item2': 5,
'item3': 5,
},
'user2':{
'item1': 4,
'item2': 5,
'item3': 5,
}
}
critics2 = {
'user1':{
'item1': 5,
'item2': 5,
'item3': 5,
},
'user2':{
'item1': 5,
'item2': 5,
'item3': 5,
}
}
critics3 = {
'user1':{
'item1': 1,
'item2': 3,
'item3': 5,
},
'user2':{
'item1': 5,
'item2': 3,
'item3': 1,
}
}
print sim_pearson(critics, 'user1', 'user2', )
result: 1.0 (expected)
print sim_pearson(critics2, 'user1', 'user2', )
result: 0 (unexpected)
print sim_pearson(critics3, 'user1', 'user2', )
result: -1 (expected)
|
[
"There is nothing wrong in your result. You are trying to plot a line through 3 points. In second case you have all three points with the same coordinates, i.e. effectively one point. You can't say do these points correlate or anti-correlate, because you can draw infinite number of lines through one point (den in your code equals to zero).\n",
"If you look up Pearson correlation on wikipedia, you'll see that the formula uses the difference between each item in a series and the mean of the series. When all the items in the series are the same, you get division by zero, so your calculation fails.\nIf it is any clearer, you can use this code:\ndef simplified_sim_pearson(p1, p2):\n n = len(p1)\n assert (n != 0)\n sum1 = sum(p1)\n sum2 = sum(p2)\n m1 = float(sum1) / n\n m2 = float(sum2) / n\n p1mean = [(x - m1) for x in p1]\n p2mean = [(y - m2) for y in p2]\n numerator = sum(x * y for x, y in zip(p1mean, p2mean))\n denominator = math.sqrt(sum(x * x for x in p1mean) * sum(y * y for y in p2mean))\n return numerator / denominator if denominator else 0\n\ndef sim_pearson(prefs,p1,p2):\n p1 = prefs[p1]\n p2 = prefs[p2]\n si = set(p1.keys()).intersection(set(p2.keys()))\n p1_x = [p1[k] for k in sorted(si)]\n p2_x = [p2[k] for k in sorted(si)]\n return simplified_sim_pearson(p1_x, p2_x)\n\n\n\ncritics = {\n 'user1':{\n 'item1': 3,\n 'item2': 5,\n 'item3': 5,\n },\n 'user2':{\n 'item1': 4,\n 'item2': 5,\n 'item3': 5,\n }\n}\ncritics2 = {\n 'user1':{\n 'item1': 5,\n 'item2': 5,\n 'item3': 5,\n },\n 'user2':{\n 'item1': 5,\n 'item2': 5,\n 'item3': 5,\n }\n}\ncritics3 = {\n 'user1':{\n 'item1': 1,\n 'item2': 3,\n 'item3': 5,\n },\n 'user2':{\n 'item1': 5,\n 'item2': 3,\n 'item3': 1,\n }\n}\n\nprint sim_pearson(critics, 'user1', 'user2', )\nprint sim_pearson(critics2, 'user1', 'user2', )\nprint sim_pearson(critics3, 'user1', 'user2', )\n\nBy the way, using Excel to determine the correct answer is a good way to validate most calculations. In this case, you would have used correl.\n",
"The algorithm gives the correct result. 0 means that there is no correlation between them (or at least you can't tell from what you know).\nGenerally (depending on what domain you apply this algorithm) you can consider everything between -0.9 < x < 0.09 as \"No correlation observable\".\n",
"Correlation does not imply causation. Had to say it. You need to develop an understanding of correlation statistics. Correlation can be between -1 and 1 and a value of 0 falls in this range and is a perfectly reasonable result. A correlation of 0 implies that there is not statistically significant relationship between the 2 variables. Remember to avoid doing statistics with less that 30 samples.\n"
] |
[
11,
3,
0,
0
] |
[] |
[] |
[
"algorithm",
"pearson",
"python"
] |
stackoverflow_0001778411_algorithm_pearson_python.txt
|
Q:
How do I encode a 4-byte string as a single 32-bit integer?
First, a disclaimer. I'm not a CS grad nor a math major, so simplicity is important.
I have a four-character string (e.g. "isoy") that I need to pass as a single 32-bit integer field. Of course at the other end, I need to decode it back to a string. The string will only contain A-Z, and case is not important, if that helps.
The funny part is that I'm starting with PowerShell on the sending end and Linux at the receiving end. I can use Perl or Python there, with a preference for Python. I don't actually need answers in each language, I'm most interested in a PowerShell (C# also good) example for going both ways.
A:
To 32-bit unsigned integer:
uint x = BitConverter.ToUInt32(Encoding.ASCII.GetBytes("isoy"), 0); // 2037347177
To string:
string s = Encoding.ASCII.GetString(BitConverter.GetBytes(x)); // "isoy"
BitConverter uses the native endianness of the machine.
A:
For Python, struct.unpack does the job (to make a 4-byte string into an int -- struct.pack goes the other way):
>>> import struct
>>> struct.unpack('i', 'isoy')[0]
2037347177
>>> struct.pack('i', 2037347177)
'isoy'
>>>
(you can use different formats to ensure big-endian or little-endian encoding, if you need that -- '>i' and '<i' respectively -- instead of just plain 'i' which uses whatever encoding is native to the machine).
A:
// string -> int
uint ret = 0;
for ( int i = 0; i < 4; ++i )
{
ret |= ( str[i] << ( i * 8 ) );
}
// int -> string
for ( int i = 0; i < 4; ++i )
{
str[i] = ( ret >> ( i * 8 ) ) & 0xff;
}
A:
Using PowerShell syntax you can do it this way (pretty much like dtb solution):
PS> $x = [BitConverter]::ToUInt32([byte[]][char[]]'isoy', 0)
PS> [char[]][BitConverter]::GetBytes($x) -join ''
isoy
You do have to watch out for endian-ness on the Linux side. If it is running on an Intel processor I believe should be fine (same endian-ness as the PowerShell side).
A:
Please take a look at the struct standard library module in Python's Manual. It has two functions for this: struct.pack and struct.unpack. You can use the 'L' (unsigned long) format character for this.
A:
Aside from byte packing, you can also consider that your 26-character alphabet can be encoded as 0-25 instead of A-Z.
So without worrying about big and little endians, you can go from "letters" to a number like this:
val=letter0+letter1*26+letter2*26*26+letter3*26*26*26;
to go from val back to letters, you do something like this:
letter0=val%26;
letter1=(val/26)%26;
letter2=(val/(26*26))%26;
letter3=(val/(26*26*26))%26;
where "%" is your language's modulus operator and "/" is an integer division.
You'll obviously need a way to get from 'A'-'Z' to 0-25 and back. That's language dependent.
You can easily put this into loops. I show the loops unrolled to make things a bit more obvious.
It's more common to pack letters into bytes, so you can use shift and and bitwise operations to encode and decode. But by doing it the way I show above, you could pack six letters into a 32-bit number, rather than just four. Which is nice, since you can hold things like stock market ticker symbols in a single 32-bit value (mutual funds ticker symbols are 5 characters).
|
How do I encode a 4-byte string as a single 32-bit integer?
|
First, a disclaimer. I'm not a CS grad nor a math major, so simplicity is important.
I have a four-character string (e.g. "isoy") that I need to pass as a single 32-bit integer field. Of course at the other end, I need to decode it back to a string. The string will only contain A-Z, and case is not important, if that helps.
The funny part is that I'm starting with PowerShell on the sending end and Linux at the receiving end. I can use Perl or Python there, with a preference for Python. I don't actually need answers in each language, I'm most interested in a PowerShell (C# also good) example for going both ways.
|
[
"To 32-bit unsigned integer:\nuint x = BitConverter.ToUInt32(Encoding.ASCII.GetBytes(\"isoy\"), 0); // 2037347177\n\nTo string:\nstring s = Encoding.ASCII.GetString(BitConverter.GetBytes(x)); // \"isoy\"\n\nBitConverter uses the native endianness of the machine.\n",
"For Python, struct.unpack does the job (to make a 4-byte string into an int -- struct.pack goes the other way):\n>>> import struct\n>>> struct.unpack('i', 'isoy')[0]\n2037347177\n>>> struct.pack('i', 2037347177)\n'isoy'\n>>> \n\n(you can use different formats to ensure big-endian or little-endian encoding, if you need that -- '>i' and '<i' respectively -- instead of just plain 'i' which uses whatever encoding is native to the machine).\n",
"// string -> int \n\nuint ret = 0;\nfor ( int i = 0; i < 4; ++i )\n{\n ret |= ( str[i] << ( i * 8 ) );\n}\n\n// int -> string\nfor ( int i = 0; i < 4; ++i )\n{\n str[i] = ( ret >> ( i * 8 ) ) & 0xff;\n}\n\n",
"Using PowerShell syntax you can do it this way (pretty much like dtb solution):\nPS> $x = [BitConverter]::ToUInt32([byte[]][char[]]'isoy', 0)\nPS> [char[]][BitConverter]::GetBytes($x) -join ''\nisoy\n\nYou do have to watch out for endian-ness on the Linux side. If it is running on an Intel processor I believe should be fine (same endian-ness as the PowerShell side).\n",
"Please take a look at the struct standard library module in Python's Manual. It has two functions for this: struct.pack and struct.unpack. You can use the 'L' (unsigned long) format character for this.\n",
"Aside from byte packing, you can also consider that your 26-character alphabet can be encoded as 0-25 instead of A-Z.\nSo without worrying about big and little endians, you can go from \"letters\" to a number like this:\nval=letter0+letter1*26+letter2*26*26+letter3*26*26*26;\n\nto go from val back to letters, you do something like this:\nletter0=val%26;\nletter1=(val/26)%26;\nletter2=(val/(26*26))%26;\nletter3=(val/(26*26*26))%26;\n\nwhere \"%\" is your language's modulus operator and \"/\" is an integer division.\nYou'll obviously need a way to get from 'A'-'Z' to 0-25 and back. That's language dependent.\nYou can easily put this into loops. I show the loops unrolled to make things a bit more obvious.\nIt's more common to pack letters into bytes, so you can use shift and and bitwise operations to encode and decode. But by doing it the way I show above, you could pack six letters into a 32-bit number, rather than just four. Which is nice, since you can hold things like stock market ticker symbols in a single 32-bit value (mutual funds ticker symbols are 5 characters).\n"
] |
[
10,
8,
3,
3,
2,
2
] |
[] |
[] |
[
"algorithm",
"c#",
"powershell",
"python"
] |
stackoverflow_0001780922_algorithm_c#_powershell_python.txt
|
Q:
How to access Firefox cache from webdriver?
I'm able to access pages like about:cache-entry?client=HTTP&sb=1&key=(some URL) directly in Firefox, but when it renders the page, it certainly gets the data from some storage. How can I access the latter from Python Firefox Webdriver?
A:
The page returned by such an about:cache-entry?... URL contains a line like this one:
file on disk: /home/fviktor/.mozilla/firefox/7jx6k3hx.default/Cache/CF7379D8d01
It is the full pathname of the cache file if any. I think you'll be able to read that file from Python as usual, but I haven't tested it yet. The pathname can also be none in the case of small files cached only in memory. You can get the file contents by parsing the hex dump on the returned page in this case.
|
How to access Firefox cache from webdriver?
|
I'm able to access pages like about:cache-entry?client=HTTP&sb=1&key=(some URL) directly in Firefox, but when it renders the page, it certainly gets the data from some storage. How can I access the latter from Python Firefox Webdriver?
|
[
"The page returned by such an about:cache-entry?... URL contains a line like this one:\nfile on disk: /home/fviktor/.mozilla/firefox/7jx6k3hx.default/Cache/CF7379D8d01\n\nIt is the full pathname of the cache file if any. I think you'll be able to read that file from Python as usual, but I haven't tested it yet. The pathname can also be none in the case of small files cached only in memory. You can get the file contents by parsing the hex dump on the returned page in this case.\n"
] |
[
2
] |
[] |
[] |
[
"caching",
"firefox",
"python",
"webdriver"
] |
stackoverflow_0001778816_caching_firefox_python_webdriver.txt
|
Q:
Ugly Code: Amusing comment?
Here's a fragment of code I'm prototyping that should, by all accounts, never see the light of day. I'll refactor it and clean it up before I merge it into my project.
However, it seems to be working and I happened to be listening to Arlo Guthrie when I was working on it.
#!/usr/bin/env python
import re
expr = re.compile(r'\[[0-9][-0-9,[]*\]')
def range2list(s):
'''Given [x-y,a,b-c] return: range(x,y) + [a] + range(b,c)
Handle decrements and zero-filling if necessary.
'''
assert s.startswith('[') and s.endswith(']') and len(s) > 2
results = []
r = s[1:-1] # extract from enclosing brackets
for i in r.split(','): # each p
if '-' not in i:
results.append(i)
continue
# Else: (it's a range
t = i.split('-')
if len(t) != 2: # punt on degenerate expressions
results.append(i)
continue
# Else:
if len(t[0]) > 1 and t[0].startswith('0'):
fmt = "%%0%sd" % len(t[0]) ## Handle zero fill
else:
fmt = "%s"
try:
l, u = int(t[0]), int(t[1])
except ValueError: # punt on stuff that can't be converted
results.append(i) # remember i? There's a song about i.
continue
if l > u:
step=-1
else:
step=1
results.extend([fmt % x for x in range(l,u,step)])
return results
... and a test suite for it:
if __name__ == '__main__':
import sys
testcases = [ '[0-5]', '[1]', '[1,2,3]', '[1-3,01-3,9,9-7]',
'[01-20]', '[020-1]', '[a,b,c,9-]' ]
for i in testcases:
print
print 'range2list(%s)' % i
print "\t" + ' '.join(range2list(i))
... which produces:
range2list([0-5])
0:1:2:3:4
range2list([1])
1
range2list([1,2,3])
1:2:3
range2list([1-3,01-3,9,9-7])
1:2:01:02:9:9:8
range2list([01-20])
01:02:03:04:05:06:07:08:09:10:11:12:13:14:15:16:17:18:19
range2list([020-1])
020:019:018:017:016:015:014:013:012:011:010:009:008:007:006:005:004:003:002
range2list([a,b,c,9-])
a:b:c:9-
I really don't like the convoluted mess in there (especially at the point where I'm
writing the comment "remember i, there's a song about i."
When I get this cleaned up I'll merge it into a function which expands hostname range patterns (ww[020-040,091,099].sfarm.mycorp.com ... and so on). (Actually the compile regexp shown here is part of that other function, it extracts the [...] expressions from a string for expansion).
So, my questions:
How can I clean up this mess?
What's the most interesting, obscure, amusing, etc. musical reference you've seen in a source code comment?
Has anyone written a parser/expander out there that already does something like this? In Python? Would anyone else ever use such a thing? Is it worth making available separately?
What alternative syntaxes would make sense? '{0:9,12,23,090:099}'? .. instead of -?
A:
If you could switch your current a-b syntax (which seems likely to get hopelessly confused by negative numbers!) to a:b, then Python's slice syntax would do the parsing for you -- you'd end up (e.g. through a fake class with an indexing method) with a tuple including slices and scalars:
>>> class x(object):
... def __getitem__(self, x): return x
...
>>> x()[2, 3:6, 4]
(2, slice(3, 6, None), 4)
and you could just process that tuple sequentially to produce the results you want (by successively appending to, or appropriately extending, a list that starts as []).
A:
I posted a parser for this format here.
|
Ugly Code: Amusing comment?
|
Here's a fragment of code I'm prototyping that should, by all accounts, never see the light of day. I'll refactor it and clean it up before I merge it into my project.
However, it seems to be working and I happened to be listening to Arlo Guthrie when I was working on it.
#!/usr/bin/env python
import re
expr = re.compile(r'\[[0-9][-0-9,[]*\]')
def range2list(s):
'''Given [x-y,a,b-c] return: range(x,y) + [a] + range(b,c)
Handle decrements and zero-filling if necessary.
'''
assert s.startswith('[') and s.endswith(']') and len(s) > 2
results = []
r = s[1:-1] # extract from enclosing brackets
for i in r.split(','): # each p
if '-' not in i:
results.append(i)
continue
# Else: (it's a range
t = i.split('-')
if len(t) != 2: # punt on degenerate expressions
results.append(i)
continue
# Else:
if len(t[0]) > 1 and t[0].startswith('0'):
fmt = "%%0%sd" % len(t[0]) ## Handle zero fill
else:
fmt = "%s"
try:
l, u = int(t[0]), int(t[1])
except ValueError: # punt on stuff that can't be converted
results.append(i) # remember i? There's a song about i.
continue
if l > u:
step=-1
else:
step=1
results.extend([fmt % x for x in range(l,u,step)])
return results
... and a test suite for it:
if __name__ == '__main__':
import sys
testcases = [ '[0-5]', '[1]', '[1,2,3]', '[1-3,01-3,9,9-7]',
'[01-20]', '[020-1]', '[a,b,c,9-]' ]
for i in testcases:
print
print 'range2list(%s)' % i
print "\t" + ' '.join(range2list(i))
... which produces:
range2list([0-5])
0:1:2:3:4
range2list([1])
1
range2list([1,2,3])
1:2:3
range2list([1-3,01-3,9,9-7])
1:2:01:02:9:9:8
range2list([01-20])
01:02:03:04:05:06:07:08:09:10:11:12:13:14:15:16:17:18:19
range2list([020-1])
020:019:018:017:016:015:014:013:012:011:010:009:008:007:006:005:004:003:002
range2list([a,b,c,9-])
a:b:c:9-
I really don't like the convoluted mess in there (especially at the point where I'm
writing the comment "remember i, there's a song about i."
When I get this cleaned up I'll merge it into a function which expands hostname range patterns (ww[020-040,091,099].sfarm.mycorp.com ... and so on). (Actually the compile regexp shown here is part of that other function, it extracts the [...] expressions from a string for expansion).
So, my questions:
How can I clean up this mess?
What's the most interesting, obscure, amusing, etc. musical reference you've seen in a source code comment?
Has anyone written a parser/expander out there that already does something like this? In Python? Would anyone else ever use such a thing? Is it worth making available separately?
What alternative syntaxes would make sense? '{0:9,12,23,090:099}'? .. instead of -?
|
[
"If you could switch your current a-b syntax (which seems likely to get hopelessly confused by negative numbers!) to a:b, then Python's slice syntax would do the parsing for you -- you'd end up (e.g. through a fake class with an indexing method) with a tuple including slices and scalars:\n>>> class x(object):\n... def __getitem__(self, x): return x\n... \n>>> x()[2, 3:6, 4]\n(2, slice(3, 6, None), 4)\n\nand you could just process that tuple sequentially to produce the results you want (by successively appending to, or appropriately extending, a list that starts as []).\n",
"I posted a parser for this format here.\n"
] |
[
4,
1
] |
[] |
[] |
[
"comments",
"python"
] |
stackoverflow_0001780721_comments_python.txt
|
Q:
Error while installing Poster (Python Module)
I'm trying to install Chris Atlee's python Poster library so I can upload a file using a HTTP POST query from within my script.
On python 2.3, when I type # python setup.py install, I get the following error. The install continues, but I can't >>> import poster later on.
byte-compiling build/bdist.linux-x86_64/egg/poster/encode.py to encode.pyc
File "build/bdist.linux-x86_64/egg/poster/encode.py", line 112
@classmethod
^
SyntaxError: invalid syntax
byte-compiling build/bdist.linux-x86_64/egg/poster/streaminghttp.py to streaminghttp.pyc
File "build/bdist.linux-x86_64/egg/poster/streaminghttp.py", line 114
newheaders = dict((k,v) for k,v in req.headers.items()
^
SyntaxError: invalid syntax
byte-compiling build/bdist.linux-x86_64/egg/poster/__init__.py to __init__.pyc
Any pointers?
A:
Python 2.3 didn't have support for decorators (that's what @classmethod is) or list comprehensions (which is the second error), so you're either going to have to find an older version of Poster, or stick with urllib/urllib2 for doing your HTTP work.
Actually, it looks like Poster was created around July, 2008, so there's unlikely to be a version that supports Python 2.3 even if you could find the original source. Any particular reason you can't upgrade to the latest Python 2.x at least?
|
Error while installing Poster (Python Module)
|
I'm trying to install Chris Atlee's python Poster library so I can upload a file using a HTTP POST query from within my script.
On python 2.3, when I type # python setup.py install, I get the following error. The install continues, but I can't >>> import poster later on.
byte-compiling build/bdist.linux-x86_64/egg/poster/encode.py to encode.pyc
File "build/bdist.linux-x86_64/egg/poster/encode.py", line 112
@classmethod
^
SyntaxError: invalid syntax
byte-compiling build/bdist.linux-x86_64/egg/poster/streaminghttp.py to streaminghttp.pyc
File "build/bdist.linux-x86_64/egg/poster/streaminghttp.py", line 114
newheaders = dict((k,v) for k,v in req.headers.items()
^
SyntaxError: invalid syntax
byte-compiling build/bdist.linux-x86_64/egg/poster/__init__.py to __init__.pyc
Any pointers?
|
[
"Python 2.3 didn't have support for decorators (that's what @classmethod is) or list comprehensions (which is the second error), so you're either going to have to find an older version of Poster, or stick with urllib/urllib2 for doing your HTTP work.\nActually, it looks like Poster was created around July, 2008, so there's unlikely to be a version that supports Python 2.3 even if you could find the original source. Any particular reason you can't upgrade to the latest Python 2.x at least?\n"
] |
[
1
] |
[] |
[] |
[
"http_post",
"http_post_vars",
"httppostedfile",
"post",
"python"
] |
stackoverflow_0001781158_http_post_http_post_vars_httppostedfile_post_python.txt
|
Q:
Resize image twice in Django using PIL
I have a function in which I'm trying to resize a photo twice from request.FILES['image']. I'm using the image.thumbnail() with the Parser as well. This works fine when I create one thumbnail, but in my view if I repeat the exact same thing again, it fails in the parser via IOError cannot parse image. I'm very confused. I've created StringIO files in memory instead of using Django's UploadedFile object as-is and it still does the same thing. Any help is much appreciated.
Suppose I wanted to do the following twice (with two different thumbnailing sizes) all without retrieving the URL twice:
import urllib2
from PIL import Image, ImageFile, ImageEnhance
# create Image instance
file = urllib2.urlopen(r'http://animals.nationalgeographic.com/staticfiles/NGS/Shared/StaticFiles/animals/images/primary/kemps-ridley-sea-turtle.jpg')
parser = ImageFile.Parser()
while True:
s = file.read(1024)
if not s:
break
parser.feed(s)
image = parser.close()
# make thumbnail
size = (75, 75)
image.thumbnail(size, Image.ANTIALIAS)
background = Image.new('RGBA', size, (255, 255, 255, 0))
background.paste(
image,
((size[0] - image.size[0]) / 2, (size[1] - image.size[1]) / 2))
background.save('copy.jpg')
For instance:
image = parser.close()
image2 = parser.close() # Obviously this doens't work
image2 = image # Obviously this doesn't either but you get what I need to do here
# Do 2 thumbnails with only one original source.
... other code ommitted ...
image.save('copy.jpg')
image2.save('copy.jpg')
A:
If this works once, as you say, the image you retrieved is just fine. There are at least two different ways to get multiple thumbnails out of single PIL images.
You can use PIL's resize method, which will return a resized copy of the original. You just have to calculate the dimensions you'll need if you want to keep the proportions intact.
Use Image.copy() to get a copy of the image.
Like this:
original = parser.close()
...
thumb1 = original.copy()
size = (75,75)
thumb1.thumbnail(size, Image.ANTIALIAS)
...
thumb2 = original.copy()
thumbnail2 = original.resize(size2, Image.ANTIALIAS)
...
This way, the original will not be altered and you can get as many copies as you need.
A:
A simpler solution than copying the original image is to instead reset the file pointer between calls to thumbnail(...) like so:
original.seek(0)
A:
I'm assuming it's failing on the image = parser.close() line with an IOError. so there's probably something wrong with the way ImageFile is getting the image data. Have you tried making reading from a local file instead?
If the parser managed to decode an image, it returns an Image object.
Otherwise, this method raises an IOError exception.
Source.
|
Resize image twice in Django using PIL
|
I have a function in which I'm trying to resize a photo twice from request.FILES['image']. I'm using the image.thumbnail() with the Parser as well. This works fine when I create one thumbnail, but in my view if I repeat the exact same thing again, it fails in the parser via IOError cannot parse image. I'm very confused. I've created StringIO files in memory instead of using Django's UploadedFile object as-is and it still does the same thing. Any help is much appreciated.
Suppose I wanted to do the following twice (with two different thumbnailing sizes) all without retrieving the URL twice:
import urllib2
from PIL import Image, ImageFile, ImageEnhance
# create Image instance
file = urllib2.urlopen(r'http://animals.nationalgeographic.com/staticfiles/NGS/Shared/StaticFiles/animals/images/primary/kemps-ridley-sea-turtle.jpg')
parser = ImageFile.Parser()
while True:
s = file.read(1024)
if not s:
break
parser.feed(s)
image = parser.close()
# make thumbnail
size = (75, 75)
image.thumbnail(size, Image.ANTIALIAS)
background = Image.new('RGBA', size, (255, 255, 255, 0))
background.paste(
image,
((size[0] - image.size[0]) / 2, (size[1] - image.size[1]) / 2))
background.save('copy.jpg')
For instance:
image = parser.close()
image2 = parser.close() # Obviously this doens't work
image2 = image # Obviously this doesn't either but you get what I need to do here
# Do 2 thumbnails with only one original source.
... other code ommitted ...
image.save('copy.jpg')
image2.save('copy.jpg')
|
[
"If this works once, as you say, the image you retrieved is just fine. There are at least two different ways to get multiple thumbnails out of single PIL images.\n\nYou can use PIL's resize method, which will return a resized copy of the original. You just have to calculate the dimensions you'll need if you want to keep the proportions intact.\nUse Image.copy() to get a copy of the image.\n\nLike this: \noriginal = parser.close()\n...\n\nthumb1 = original.copy()\nsize = (75,75)\nthumb1.thumbnail(size, Image.ANTIALIAS)\n...\n\nthumb2 = original.copy()\nthumbnail2 = original.resize(size2, Image.ANTIALIAS)\n...\n\nThis way, the original will not be altered and you can get as many copies as you need.\n",
"A simpler solution than copying the original image is to instead reset the file pointer between calls to thumbnail(...) like so:\noriginal.seek(0)\n\n",
"I'm assuming it's failing on the image = parser.close() line with an IOError. so there's probably something wrong with the way ImageFile is getting the image data. Have you tried making reading from a local file instead?\n\nIf the parser managed to decode an image, it returns an Image object.\n Otherwise, this method raises an IOError exception.\n\nSource.\n"
] |
[
2,
2,
0
] |
[] |
[] |
[
"django",
"image_manipulation",
"python",
"python_imaging_library"
] |
stackoverflow_0001485569_django_image_manipulation_python_python_imaging_library.txt
|
Q:
How to load DLL using ctypes in Python?
Please provide me a sample explaining how to load & call a functions in c++ dll using Python?
I found some articles saying we can use "ctypes" to load and call a function in DLL using Python. But i am not able to find a working sample?
It would be great if anyone provide me an sample of how to do it.
A:
Here is some actual code I used in a project to load a DLL, lookup a function and set up and call that function.
import ctypes
# Load DLL into memory.
hllDll = ctypes.WinDLL ("c:\\PComm\\ehlapi32.dll")
# Set up prototype and parameters for the desired function call
# in the DLL, `HLLAPI()` (the high-level language API). This
# particular function returns an `int` and takes four `void *`
# arguments.
hllApiProto = ctypes.WINFUNCTYPE (
ctypes.c_int,
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_void_p)
hllApiParams = (1, "p1", 0), (1, "p2", 0), (1, "p3",0), (1, "p4",0)
# Actually map the DLL function to a Python name `hllApi`.
hllApi = hllApiProto (("HLLAPI", hllDll), hllApiParams)
# This is how you can actually call the DLL function. Set up the
# variables to pass in, then call the Python name with them.
p1 = ctypes.c_int (1)
p2 = ctypes.c_char_p ("Z")
p3 = ctypes.c_int (1)
p4 = ctypes.c_int (0)
hllApi (ctypes.byref (p1), p2, ctypes.byref (p3), ctypes.byref (p4))
The function in this case was one in a terminal emulator package and it was a very simple one - it took four parameters and returned no value (some was actually returned via pointer parameters). The first parameter (1) is to indicate that we want to connect to the host.
The second parameter ("Z") is the session ID. This particular terminal emulator allowed short-name sessions of "A" through "Z".
The other two parameters were simply a length and another byte the use of which escapes me at the moment (I should have documented that code a little better).
The steps were to:
load the DLL.
Set up the prototype and parameters for a function.
Map that to a Python name (for ease of calling).
Create the necessary parameters.
Call the function.
The ctypes library has all the C data types (int, char, short, void* and so on), and can pass parameters either by value or reference. There's a tutorial located here.
|
How to load DLL using ctypes in Python?
|
Please provide me a sample explaining how to load & call a functions in c++ dll using Python?
I found some articles saying we can use "ctypes" to load and call a function in DLL using Python. But i am not able to find a working sample?
It would be great if anyone provide me an sample of how to do it.
|
[
"Here is some actual code I used in a project to load a DLL, lookup a function and set up and call that function.\nimport ctypes\n\n# Load DLL into memory.\n\nhllDll = ctypes.WinDLL (\"c:\\\\PComm\\\\ehlapi32.dll\")\n\n# Set up prototype and parameters for the desired function call\n# in the DLL, `HLLAPI()` (the high-level language API). This\n# particular function returns an `int` and takes four `void *`\n# arguments.\n\nhllApiProto = ctypes.WINFUNCTYPE (\n ctypes.c_int,\n ctypes.c_void_p,\n ctypes.c_void_p,\n ctypes.c_void_p,\n ctypes.c_void_p)\nhllApiParams = (1, \"p1\", 0), (1, \"p2\", 0), (1, \"p3\",0), (1, \"p4\",0)\n\n# Actually map the DLL function to a Python name `hllApi`.\n\nhllApi = hllApiProto ((\"HLLAPI\", hllDll), hllApiParams)\n\n# This is how you can actually call the DLL function. Set up the\n# variables to pass in, then call the Python name with them.\n\np1 = ctypes.c_int (1)\np2 = ctypes.c_char_p (\"Z\")\np3 = ctypes.c_int (1)\np4 = ctypes.c_int (0)\n\nhllApi (ctypes.byref (p1), p2, ctypes.byref (p3), ctypes.byref (p4))\n\nThe function in this case was one in a terminal emulator package and it was a very simple one - it took four parameters and returned no value (some was actually returned via pointer parameters). The first parameter (1) is to indicate that we want to connect to the host.\nThe second parameter (\"Z\") is the session ID. This particular terminal emulator allowed short-name sessions of \"A\" through \"Z\".\nThe other two parameters were simply a length and another byte the use of which escapes me at the moment (I should have documented that code a little better).\nThe steps were to:\n\nload the DLL.\nSet up the prototype and parameters for a function.\nMap that to a Python name (for ease of calling).\nCreate the necessary parameters.\nCall the function.\n\nThe ctypes library has all the C data types (int, char, short, void* and so on), and can pass parameters either by value or reference. There's a tutorial located here.\n"
] |
[
6
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001781531_python.txt
|
Q:
Regular expression matching everything except a given regular expression
I am trying to figure out a regular expression which matches any string that doesn't start with mpeg. A generalization of this is matching any string which doesn't start with a given regular expression.
I tried something like as follows:
[^m][^p][^e][^g].*
The problem with this is that it requires at least 4 characters to be present in the string. I was not able to figure out a good way to handle this and a generalized way to handle this in a general purpose manner.
I will be using this in Python.
A:
^(?!mpeg).*
This uses a negative lookahead to only match a string where the beginning doesn't match mpeg. Essentially, it requires that "the position at the beginning of the string cannot be a position where if we started matching the regex mpeg, we could successfully match" - thus matching anything which doesn't start with mpeg, and not matching anything that does.
However, I'd be curious about the context in which you're using this - there might be other options aside from regex which would be either more efficient or more readable, such as...
if not inputstring.startswith("mpeg"):
A:
don't lose your mind with regex.
if len(mystring) >=4 and mystring[:4]=="mpeg":
print "do something"
or use startswith() with "not" keyword
if len(mystring)>=4 and not mystring.startswith("mpeg")
A:
Try a look-ahead assertion:
(?!mpeg)^.*
Or if you want to use negated classes only:
^(.{0,3}$|[^m]|m([^p]|p([^e]|e([^g])))).*$
A:
Your regexp wouldn't match "npeg", I think you would need come up with
^($|[^m]|m($|[^p]|p($|[^e]|e($|[^g])))), which is quite horrible.
Another alternative would be ^(.{0,3}$|[^m]|.[^p]|..[^e]|...[^g])
which is only slightly better.
So I think you should really use a look-ahead assertion as suggested by Dav and Gumbo :-)
|
Regular expression matching everything except a given regular expression
|
I am trying to figure out a regular expression which matches any string that doesn't start with mpeg. A generalization of this is matching any string which doesn't start with a given regular expression.
I tried something like as follows:
[^m][^p][^e][^g].*
The problem with this is that it requires at least 4 characters to be present in the string. I was not able to figure out a good way to handle this and a generalized way to handle this in a general purpose manner.
I will be using this in Python.
|
[
"^(?!mpeg).*\n\nThis uses a negative lookahead to only match a string where the beginning doesn't match mpeg. Essentially, it requires that \"the position at the beginning of the string cannot be a position where if we started matching the regex mpeg, we could successfully match\" - thus matching anything which doesn't start with mpeg, and not matching anything that does.\nHowever, I'd be curious about the context in which you're using this - there might be other options aside from regex which would be either more efficient or more readable, such as...\nif not inputstring.startswith(\"mpeg\"):\n\n",
"don't lose your mind with regex. \nif len(mystring) >=4 and mystring[:4]==\"mpeg\":\n print \"do something\"\n\nor use startswith() with \"not\" keyword\nif len(mystring)>=4 and not mystring.startswith(\"mpeg\")\n\n",
"Try a look-ahead assertion:\n(?!mpeg)^.*\n\nOr if you want to use negated classes only:\n^(.{0,3}$|[^m]|m([^p]|p([^e]|e([^g])))).*$\n\n",
"Your regexp wouldn't match \"npeg\", I think you would need come up with\n^($|[^m]|m($|[^p]|p($|[^e]|e($|[^g])))), which is quite horrible.\nAnother alternative would be ^(.{0,3}$|[^m]|.[^p]|..[^e]|...[^g])\nwhich is only slightly better.\nSo I think you should really use a look-ahead assertion as suggested by Dav and Gumbo :-)\n"
] |
[
34,
11,
3,
0
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0001781554_python_regex.txt
|
Q:
How does the layout of a Python application look?
In most programming environments it's clear how the code is distributed into several parts and how everything interacts. In Python I seem to be completely lost.
How should the layout of a Python application look?
Currently I have:
setup.py
application_name/
__main__.py
__init__.py
views/
controllers/
model/
resources/ <- images, videos, ...
How does one execute the application?
I've got a runner script with the following content
#!/usr/bin/env python -m "application_name"
Should one even use __main__.py for this purpose? Is a runner script necessary?
How should one import parts of the application? (Python 2.6)
For example in application_name/__main__.py
from . import controllers.MainWindow
How do you layout your applications?
A:
There are several parts to this question so I'll try to answer them in turn:
1: Its really up to you, there are no hard-and-fast rules beyond those for establishing that a directory should be treated as a package and so on. Some frameworks will prescribe a directory structure using a script to generate scaffolding (a bit like Rails does in the Ruby world) but this is purely a convenience or convention of the given framework. Organise your code and modules so they make sense logically as you would in any other language.
2: What you have there is absolutely fine. Alternatively you can use an installed script if you are using distutils, a console_script as part of a .egg install, or as a last resort just call the main.py (or whatever you name it) script directly. The console_script is quite common though and is used by tools such as the nose testing framework for example.
3: There is a PEP for this specific topic. In my experience though you should really prefer absolute imports to relative ones. To force this behaviour you can do:
from __future__ import absolute_import
|
How does the layout of a Python application look?
|
In most programming environments it's clear how the code is distributed into several parts and how everything interacts. In Python I seem to be completely lost.
How should the layout of a Python application look?
Currently I have:
setup.py
application_name/
__main__.py
__init__.py
views/
controllers/
model/
resources/ <- images, videos, ...
How does one execute the application?
I've got a runner script with the following content
#!/usr/bin/env python -m "application_name"
Should one even use __main__.py for this purpose? Is a runner script necessary?
How should one import parts of the application? (Python 2.6)
For example in application_name/__main__.py
from . import controllers.MainWindow
How do you layout your applications?
|
[
"There are several parts to this question so I'll try to answer them in turn:\n1: Its really up to you, there are no hard-and-fast rules beyond those for establishing that a directory should be treated as a package and so on. Some frameworks will prescribe a directory structure using a script to generate scaffolding (a bit like Rails does in the Ruby world) but this is purely a convenience or convention of the given framework. Organise your code and modules so they make sense logically as you would in any other language. \n2: What you have there is absolutely fine. Alternatively you can use an installed script if you are using distutils, a console_script as part of a .egg install, or as a last resort just call the main.py (or whatever you name it) script directly. The console_script is quite common though and is used by tools such as the nose testing framework for example.\n3: There is a PEP for this specific topic. In my experience though you should really prefer absolute imports to relative ones. To force this behaviour you can do:\n from __future__ import absolute_import\n\n"
] |
[
5
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001781657_python.txt
|
Q:
To understand: From PHP Array to Python?
This is Common task In PHP and other programming languages.I moved from PHP developer.
I want to make sure with this collections.
Anyone have who good in python please help me to understand clearly .
This is my collections from PHP code.
<?php
$php = array(1,2,3,4,5,6,7,8,9,10);
for ($i = 0; $i < 10 ; $i ++)
echo $php[$i]."<br>";
?>
=>What is in Python?
<?php
for ($i = 0; $i < 10 ; $i ++)
echo $php[$i] = $i +1 ;
?>
=>What is in Python?
<?php
$php = array(1,2,3,4,5,6,7,8,9,10);
foreach ($php as $value)
echo $value."<br>";
?>
=>What is in Python?
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
?>
=>What is in Python?
<?php
$arr = array("mot"=>"one", "hai"=>"two","ba"=> "three");
foreach ($arr as $key => $value) {
echo "Key: $key; Value: $value<br />\n";
}
?>
=>What is in Python?
<?php
$arr = array("one", "two","three");
while (list($key, $value) = each($arr)) {
echo "Key: $key; Value: $value<br />\n";
}
?>
=>What is in Python?
<?php
$arr = array("one", "two","three");
while ($element = each($arr)) {
echo "Key: $element['key']; Value: $element['value']<br />\n";
}
?>
=>What is in Python?
<?php
$products = array( array("ITL","INTEL","HARD"),
array("MIR", "MICROSOFT","SOFT"),
array("Py4C", "pythonkhmer.wordpress.com","TUTORIAL")
);
for ($row = 0; $row < 3; $row++)
{
for ($col = 0; $col <3; $col++)
{
echo "|".$products[$row][$col];
}
echo "<br>";
}
?>
=>What is in Python?
A:
All of these are quite obvious really. I'm only listing the Pythonic ways to do these things. Update: Examples should now work in both Python 2 and Python 3. In Python 2 you could substitute xrange() for range() and iteritems() for items() for efficiency.
Example 1
PHP
$php = array(1,2,3,4,5,6,7,8,9,10);
for ($i = 0; $i < 10 ; $i ++)
echo $php[$i]."<br>";
Python (generally you iterate over lists in Python, instead of accessing by index):
lst = [1,2,3,4,5,6,7,8,9,10]
for item in lst:
print(str(item) + "<br>")
Example 2
for ($i = 0; $i < 10 ; $i ++)
echo $php[$i] = $i +1 ;
Python:
lst = range(1, 11)
for item in lst:
print(item)
Or maybe:
lst = []
for i in range(10):
lst.append(i + 1)
print(lst[-1]) # prints out last element
Example 3
$php = array(1,2,3,4,5,6,7,8,9,10);
foreach ($php as $value)
echo $value."<br>";
Same as 1st
Example 4
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
Python:
lst = [1, 2, 3, 4]
lst = [val * 2 for val in lst]
Example 5
$arr = array("mot"=>"one", "hai"=>"two","ba"=> "three");
foreach ($arr as $key => $value) {
echo "Key: $key; Value: $value<br />\n";
}
Python (note that {...} creates a dict [dictionary] in Python, not a list/):
dct = {'mot': 'one', 'hai': 'two', 'ba': 'three'}
for key, value in dct.items():
print("Key: %s; Value: %s<br />" % (key, value))
Example 6
$arr = array("one", "two","three");
while (list($key, $value) = each($arr)) {
echo "Key: $key; Value: $value<br />\n";
}
Python:
lst = ['one', 'two', 'three']
for key, value in enumerate(lst):
print("Key: %d; Value: %s<br />" % (key, value))
Example 7
$arr = array("one", "two","three");
while ($element = each($arr)) {
echo "Key: $element['key']; Value: $element['value']<br />\n";
}
There is no direct Python equivalent to this.
Example 8
$products = array( array("ITL","INTEL","HARD"),
array("MIR", "MICROSOFT","SOFT"),
array("Py4C", "pythonkhmer.wordpress.com","TUTORIAL")
);
for ($row = 0; $row < 3; $row++)
{
for ($col = 0; $col <3; $col++)
{
echo "|".$products[$row][$col];
}
echo "<br>";
}
Python:
products = [['ITL', 'INTEL', 'HARD'],
['MIR', 'MICROSOFT', 'SOFT'],
['Py4C', 'pythonkhmer.wordpress.com', 'TUTORIAL']]
for product in products:
for item in product:
print('|' + item)
print('<br>')
Or maybe a more Pythonic version:
for product in products:
print('|%s<br>' % ('|'.join(product)))
A:
"What is in Python?", quite a philosophical question, always a great way to start a day. I think what is in Python can best be answered by the Zen of Python (type import this in an interactive shell):
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Sorry, couldnt resist. To answer the question you meant to ask, I direct you to the Python documentation, specifically the section about looping techniques as linked to by lutz.
Unless the syntax in the documentation manage to completely confuse you (though I doubt it) you will see how a loop is defined in Python. And once you have understood that, you will understand, by definition, how they differ (syntactically) from the loops youre used to in PHP.
Still not satisfied? Hmm... I guess you should read the tutorial again. Then, come back and ask specific questions that could yield specific answers. You wont find any silver bullets for a question this broad.
A:
You can read an introduction to loops in the Python tutorial.
A:
This question reminds me of a wise man who had said, "Give a man a fish; you have fed him for today. Teach a man to fish; and you have fed him for a lifetime..."
|
To understand: From PHP Array to Python?
|
This is Common task In PHP and other programming languages.I moved from PHP developer.
I want to make sure with this collections.
Anyone have who good in python please help me to understand clearly .
This is my collections from PHP code.
<?php
$php = array(1,2,3,4,5,6,7,8,9,10);
for ($i = 0; $i < 10 ; $i ++)
echo $php[$i]."<br>";
?>
=>What is in Python?
<?php
for ($i = 0; $i < 10 ; $i ++)
echo $php[$i] = $i +1 ;
?>
=>What is in Python?
<?php
$php = array(1,2,3,4,5,6,7,8,9,10);
foreach ($php as $value)
echo $value."<br>";
?>
=>What is in Python?
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
?>
=>What is in Python?
<?php
$arr = array("mot"=>"one", "hai"=>"two","ba"=> "three");
foreach ($arr as $key => $value) {
echo "Key: $key; Value: $value<br />\n";
}
?>
=>What is in Python?
<?php
$arr = array("one", "two","three");
while (list($key, $value) = each($arr)) {
echo "Key: $key; Value: $value<br />\n";
}
?>
=>What is in Python?
<?php
$arr = array("one", "two","three");
while ($element = each($arr)) {
echo "Key: $element['key']; Value: $element['value']<br />\n";
}
?>
=>What is in Python?
<?php
$products = array( array("ITL","INTEL","HARD"),
array("MIR", "MICROSOFT","SOFT"),
array("Py4C", "pythonkhmer.wordpress.com","TUTORIAL")
);
for ($row = 0; $row < 3; $row++)
{
for ($col = 0; $col <3; $col++)
{
echo "|".$products[$row][$col];
}
echo "<br>";
}
?>
=>What is in Python?
|
[
"All of these are quite obvious really. I'm only listing the Pythonic ways to do these things. Update: Examples should now work in both Python 2 and Python 3. In Python 2 you could substitute xrange() for range() and iteritems() for items() for efficiency.\nExample 1\nPHP\n$php = array(1,2,3,4,5,6,7,8,9,10);\nfor ($i = 0; $i < 10 ; $i ++)\necho $php[$i].\"<br>\";\n\nPython (generally you iterate over lists in Python, instead of accessing by index):\nlst = [1,2,3,4,5,6,7,8,9,10]\nfor item in lst:\n print(str(item) + \"<br>\")\n\nExample 2\nfor ($i = 0; $i < 10 ; $i ++)\necho $php[$i] = $i +1 ;\n\nPython:\nlst = range(1, 11)\nfor item in lst:\n print(item)\n\nOr maybe:\nlst = []\nfor i in range(10):\n lst.append(i + 1)\n print(lst[-1]) # prints out last element\n\nExample 3\n$php = array(1,2,3,4,5,6,7,8,9,10);\nforeach ($php as $value)\necho $value.\"<br>\";\n\nSame as 1st\nExample 4\n$arr = array(1, 2, 3, 4);\nforeach ($arr as &$value) {\n $value = $value * 2;\n}\n\nPython:\nlst = [1, 2, 3, 4]\nlst = [val * 2 for val in lst]\n\nExample 5\n$arr = array(\"mot\"=>\"one\", \"hai\"=>\"two\",\"ba\"=> \"three\");\nforeach ($arr as $key => $value) {\n echo \"Key: $key; Value: $value<br />\\n\";\n}\n\nPython (note that {...} creates a dict [dictionary] in Python, not a list/):\ndct = {'mot': 'one', 'hai': 'two', 'ba': 'three'}\nfor key, value in dct.items():\n print(\"Key: %s; Value: %s<br />\" % (key, value))\n\nExample 6\n$arr = array(\"one\", \"two\",\"three\");\nwhile (list($key, $value) = each($arr)) {\n echo \"Key: $key; Value: $value<br />\\n\";\n}\n\nPython:\nlst = ['one', 'two', 'three']\nfor key, value in enumerate(lst):\n print(\"Key: %d; Value: %s<br />\" % (key, value))\n\nExample 7\n$arr = array(\"one\", \"two\",\"three\");\nwhile ($element = each($arr)) {\n echo \"Key: $element['key']; Value: $element['value']<br />\\n\";\n}\n\nThere is no direct Python equivalent to this.\nExample 8\n$products = array( array(\"ITL\",\"INTEL\",\"HARD\"),\n array(\"MIR\", \"MICROSOFT\",\"SOFT\"),\n array(\"Py4C\", \"pythonkhmer.wordpress.com\",\"TUTORIAL\")\n );\nfor ($row = 0; $row < 3; $row++)\n{\n for ($col = 0; $col <3; $col++)\n {\n echo \"|\".$products[$row][$col];\n }\n echo \"<br>\";\n}\n\nPython:\nproducts = [['ITL', 'INTEL', 'HARD'],\n ['MIR', 'MICROSOFT', 'SOFT'],\n ['Py4C', 'pythonkhmer.wordpress.com', 'TUTORIAL']]\n\nfor product in products:\n for item in product:\n print('|' + item)\n print('<br>')\n\nOr maybe a more Pythonic version:\nfor product in products:\n print('|%s<br>' % ('|'.join(product)))\n\n",
"\"What is in Python?\", quite a philosophical question, always a great way to start a day. I think what is in Python can best be answered by the Zen of Python (type import this in an interactive shell):\n\nBeautiful is better than ugly.\nExplicit is better than implicit.\nSimple is better than complex.\nComplex is better than complicated.\nFlat is better than nested.\nSparse is better than dense.\nReadability counts.\nSpecial cases aren't special enough to break the rules.\nAlthough practicality beats purity.\nErrors should never pass silently.\nUnless explicitly silenced.\nIn the face of ambiguity, refuse the temptation to guess.\nThere should be one-- and preferably only one --obvious way to do it.\nAlthough that way may not be obvious at first unless you're Dutch.\nNow is better than never.\nAlthough never is often better than right now.\nIf the implementation is hard to explain, it's a bad idea.\nIf the implementation is easy to explain, it may be a good idea.\nNamespaces are one honking great idea -- let's do more of those!\n\nSorry, couldnt resist. To answer the question you meant to ask, I direct you to the Python documentation, specifically the section about looping techniques as linked to by lutz.\nUnless the syntax in the documentation manage to completely confuse you (though I doubt it) you will see how a loop is defined in Python. And once you have understood that, you will understand, by definition, how they differ (syntactically) from the loops youre used to in PHP.\nStill not satisfied? Hmm... I guess you should read the tutorial again. Then, come back and ask specific questions that could yield specific answers. You wont find any silver bullets for a question this broad. \n",
"You can read an introduction to loops in the Python tutorial. \n",
"This question reminds me of a wise man who had said, \"Give a man a fish; you have fed him for today. Teach a man to fish; and you have fed him for a lifetime...\"\n"
] |
[
30,
10,
3,
0
] |
[] |
[] |
[
"arrays",
"loops",
"php",
"python"
] |
stackoverflow_0001781617_arrays_loops_php_python.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.