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:
Read version info from .ABR file (Photoshop brush set)
Is it possible to detect which Photoshop version a brush set (.abr) file is compatible with from its binary data?
There is a open source C# programm called ABRViewer but it doesn't read version info.
Sample brushes:
http://mark-s.deviantart.com/art/Fractal-Brushes-Set-20484978
http://redheadstock.deviantart.com/art/Arcane-Circles-Symbols-Brushes-63580135
A:
If you are on Windows, you may have some luck using Python's win32com to interact with Photoshop programatically (a nice example). Perhaps you could try to load in an ABR file via this API.
Based upon this forum post, it appears that there is a document "Photoshop File Formats," which is included in the Advanced SDK. Apparently you can get the Advanced SDK for free. I would assume this document would expain the ABR file format so that you could write a simple parser.
|
Read version info from .ABR file (Photoshop brush set)
|
Is it possible to detect which Photoshop version a brush set (.abr) file is compatible with from its binary data?
There is a open source C# programm called ABRViewer but it doesn't read version info.
Sample brushes:
http://mark-s.deviantart.com/art/Fractal-Brushes-Set-20484978
http://redheadstock.deviantart.com/art/Arcane-Circles-Symbols-Brushes-63580135
|
[
"If you are on Windows, you may have some luck using Python's win32com to interact with Photoshop programatically (a nice example). Perhaps you could try to load in an ABR file via this API.\nBased upon this forum post, it appears that there is a document \"Photoshop File Formats,\" which is included in the Advanced SDK. Apparently you can get the Advanced SDK for free. I would assume this document would expain the ABR file format so that you could write a simple parser.\n"
] |
[
4
] |
[] |
[] |
[
"binary",
"hex",
"photoshop",
"python"
] |
stackoverflow_0001736396_binary_hex_photoshop_python.txt
|
Q:
Python: data vs. text?
Guido van Rossum's presentation about Python 3000 mentions several things to make a transition from Python 2 to Python 3 easier eventually. He is specifically talking about text handling since the move to Unicode as the only representation of strings in Python 3 is one of the major changes.
As far as text handling goes, one slide (#14) says:
In 2.6:
Use bytes and b'…' for all data (Knowing these are just aliases for str and '…')
Use unicode and u'...' for all text
In 2.5:
'...' for data, u'...' for text
I am using Python 2.6.4. What exactly does this mean for me?
In Python's world, what is the difference between data and text?
A:
In a nutshell, the way text and data is handled in Py3k may arguably be the most "breaking" change in the language. By knowing and avoiding,when possible, the situations where some Python 2.6 logic will work differently than in 3.x, we can facilitate the migration when it happens. Yet we should expect that some parts of the 2.6 logic may require special attention and modifications for example to deal with distinct encodings etc.
The idea behind BDFL's suggestion on slide 14 is probably to start "using" the same types which Py3k supports (and only these), namely unicode strings for strings (str type) and 8-bits byte sequences for "data" (bytes type).
The term "using" in the previous sentence is used rather loosely since the semantics and associated storage/encoding for these types differs between the 2.6 and 3.x versions. In Python 2.6, the bytes type and the associated literal syntax (b'xyz') simply map to the str type. Therefore
# in Py2.6
>>'mykey' == b'mykey'
True
b'mykey'.__class__
<class 'str'>
# in Py3k
>>>'mykey' == b'mykey'
False
b'mykey'.__class__
<class 'bytes'>
To answer your question [in the remarks below], in 2.6 whether you use b'xyz' or 'xyz', Python understands it as the same and one thing : an str. What is important is that you understand these as [potentially/in-the-future] two distinct types with a distinct purpose:
str for text-like info, and
bytes for sequences of octets storing whatever data at hand.
For example, again speaking close to your example/question, in Py3k you'll be able to have a dictionary with two elements which have a similar keys, one with b'mykey' and the other with 'mykey', however under 2.6 this is not possible, since these two keys are really the same; what matters is that you know this kind of things and avoid (or explicitly mark in a special fashion in the code) the situations where the 2.6 code will not work in 3.x.
In Py3k, str is an abstract unicode string, a sequence of unicode code points (characters) and Python deals with converting this to/from its encoded form whatever the encoding might be (as a programmer you do have a say about the encoding but at the time you deal with string operations and such you do not need to worry about these details). In contrast, bytes is a sequence of 8-bits "things" which semantics and encoding are totally left to the programmer.
So, even though Python 2.6 doesn't see a difference, by explicitly using bytes() / b'...' or str() / u'...', you...
... prepare yourself and your program to the upcoming types and semantics of Py3k
... make it easier for the automatic conversion (2to3 tool or other) of the source code, whereby the b in b'...' will remain and the u of u'...' will be removed (since the only string type will be unicode).
For more info:
Python 2.6 What's new (see PEP 3112 Bytes Literals)
Python 3.0 What's New (see Text Vs. Data Instead Of Unicode Vs. 8-bit near the top)
A:
The answer to your first question is simple: In Python 2.6 you can do has you used to. But, if you like, you can switch to Py3k standards by typing:
from __future__ import unicode_literals
Your second question needs more clarification:
Strings are data that prints as human characters. Not only in Python, but every language (I know of) has its way when dealing with strings.
However, the common grounds are encodings. Encodings are the way to map byte sequences to glyphs (ie. mostly printable symbols).
Python offers a simple way to overcome the complexities of managing encodings (when you put string literals in your code).
Let's see a very simple example:
>>> len("Mañana")
7
I only see 6 symbols. So I expect len would have returned 6. Where is this extra "symbol" coming from? Well in UTF-8 the symbol ñ is represented with 2 bytes. Before Py3k, string literals are just sequences of bytes. So, Python sees that string as bytes and it counts them all: Ma\xc3\xb1ana.
However, if I execute the following:
>>> len(u"Mañana")
6
So Python "knows" exactly that the 2-bytes sequences for "ñ" is to be considered as a single letter.
This is by no means exclusive to Python. The following PHP script shows the same behavior:
manu@pavla:~$ php <<EOF
<?php
echo strlen("Mañana")."\n";
?>
EOF
7
The PHP solution happens to be more elaborate:
manu@pavla:~$ php <<EOF
<?php
echo mb_strlen("Mañana", "utf-8")."\n";
?>
EOF
6
Notice I have to substitute mb_strlen for strlen and I have to pass utf-8 (the encoding) as a second argument.
A word of warning: user provided strings come usually as bytes, not unicode strings. So you need to take care of that. See more on http://mail.python.org/pipermail/python-list/2008-July/139193.html
|
Python: data vs. text?
|
Guido van Rossum's presentation about Python 3000 mentions several things to make a transition from Python 2 to Python 3 easier eventually. He is specifically talking about text handling since the move to Unicode as the only representation of strings in Python 3 is one of the major changes.
As far as text handling goes, one slide (#14) says:
In 2.6:
Use bytes and b'…' for all data (Knowing these are just aliases for str and '…')
Use unicode and u'...' for all text
In 2.5:
'...' for data, u'...' for text
I am using Python 2.6.4. What exactly does this mean for me?
In Python's world, what is the difference between data and text?
|
[
"In a nutshell, the way text and data is handled in Py3k may arguably be the most \"breaking\" change in the language. By knowing and avoiding,when possible, the situations where some Python 2.6 logic will work differently than in 3.x, we can facilitate the migration when it happens. Yet we should expect that some parts of the 2.6 logic may require special attention and modifications for example to deal with distinct encodings etc. \nThe idea behind BDFL's suggestion on slide 14 is probably to start \"using\" the same types which Py3k supports (and only these), namely unicode strings for strings (str type) and 8-bits byte sequences for \"data\" (bytes type).\nThe term \"using\" in the previous sentence is used rather loosely since the semantics and associated storage/encoding for these types differs between the 2.6 and 3.x versions. In Python 2.6, the bytes type and the associated literal syntax (b'xyz') simply map to the str type. Therefore\n# in Py2.6\n>>'mykey' == b'mykey'\nTrue\nb'mykey'.__class__\n<class 'str'>\n\n# in Py3k\n>>>'mykey' == b'mykey'\nFalse\nb'mykey'.__class__\n<class 'bytes'> \n\nTo answer your question [in the remarks below], in 2.6 whether you use b'xyz' or 'xyz', Python understands it as the same and one thing : an str. What is important is that you understand these as [potentially/in-the-future] two distinct types with a distinct purpose:\n\nstr for text-like info, and \nbytes for sequences of octets storing whatever data at hand.\n\nFor example, again speaking close to your example/question, in Py3k you'll be able to have a dictionary with two elements which have a similar keys, one with b'mykey' and the other with 'mykey', however under 2.6 this is not possible, since these two keys are really the same; what matters is that you know this kind of things and avoid (or explicitly mark in a special fashion in the code) the situations where the 2.6 code will not work in 3.x.\nIn Py3k, str is an abstract unicode string, a sequence of unicode code points (characters) and Python deals with converting this to/from its encoded form whatever the encoding might be (as a programmer you do have a say about the encoding but at the time you deal with string operations and such you do not need to worry about these details). In contrast, bytes is a sequence of 8-bits \"things\" which semantics and encoding are totally left to the programmer.\nSo, even though Python 2.6 doesn't see a difference, by explicitly using bytes() / b'...' or str() / u'...', you...\n\n... prepare yourself and your program to the upcoming types and semantics of Py3k \n... make it easier for the automatic conversion (2to3 tool or other) of the source code, whereby the b in b'...' will remain and the u of u'...' will be removed (since the only string type will be unicode).\n\nFor more info:\nPython 2.6 What's new (see PEP 3112 Bytes Literals)\nPython 3.0 What's New (see Text Vs. Data Instead Of Unicode Vs. 8-bit near the top)\n",
"The answer to your first question is simple: In Python 2.6 you can do has you used to. But, if you like, you can switch to Py3k standards by typing:\nfrom __future__ import unicode_literals\n\nYour second question needs more clarification:\nStrings are data that prints as human characters. Not only in Python, but every language (I know of) has its way when dealing with strings.\nHowever, the common grounds are encodings. Encodings are the way to map byte sequences to glyphs (ie. mostly printable symbols).\nPython offers a simple way to overcome the complexities of managing encodings (when you put string literals in your code).\nLet's see a very simple example:\n>>> len(\"Mañana\")\n7\n\nI only see 6 symbols. So I expect len would have returned 6. Where is this extra \"symbol\" coming from? Well in UTF-8 the symbol ñ is represented with 2 bytes. Before Py3k, string literals are just sequences of bytes. So, Python sees that string as bytes and it counts them all: Ma\\xc3\\xb1ana.\nHowever, if I execute the following:\n>>> len(u\"Mañana\")\n6\n\nSo Python \"knows\" exactly that the 2-bytes sequences for \"ñ\" is to be considered as a single letter.\nThis is by no means exclusive to Python. The following PHP script shows the same behavior:\nmanu@pavla:~$ php <<EOF\n<?php\necho strlen(\"Mañana\").\"\\n\";\n?>\nEOF\n7\n\nThe PHP solution happens to be more elaborate:\nmanu@pavla:~$ php <<EOF\n<?php\necho mb_strlen(\"Mañana\", \"utf-8\").\"\\n\";\n?>\nEOF\n6\n\nNotice I have to substitute mb_strlen for strlen and I have to pass utf-8 (the encoding) as a second argument.\nA word of warning: user provided strings come usually as bytes, not unicode strings. So you need to take care of that. See more on http://mail.python.org/pipermail/python-list/2008-July/139193.html\n"
] |
[
20,
2
] |
[] |
[] |
[
"python",
"python_3.x",
"unicode"
] |
stackoverflow_0001736228_python_python_3.x_unicode.txt
|
Q:
Quitting matplotlib.pyplot animation gracefully
I have a script that plots data of some photometry apertures, and I want to plot them in an xy plot. I am using matplotlib.pyplot with python 2.5.
The input data is stored in around 500 files and read. I am aware that this is not the most efficient way of inputting the data but that's another issue...
Example code:
import matplotlib.pyplot as plt
xcoords = []
ycoords = []
# lists are populated with data from first file
pltline, = plt.plot(xcoords, ycoords, 'rx')
# then loop populating the data from each file
for file in filelist:
xcoords = [...]
ycoords = [...]
pltline.set_xdata(xcoords)
pltline.set_ydata(ycoords)
plt.draw()
As there are over 500 files, I will occasionally want to close the animation window in the middle of the plotting. My code to plot works but it doesn't exit very gracefully. The plot window does not respond to clicking the close button and I have to Ctrl+C out of it.
Can anyone help me find a way to close the animation window while the script is running whilst looking graceful (well more graceful than a series of python traceback errors)?
A:
If you update the data and do the draw in a loop, you should be able to interrupt it. Here's an example (that draws a stationary circle and then moves a line around the perimeter):
from pylab import *
import time
data = [] # make the data
for i in range(1000):
a = .01*pi*i+.0007
m = -1./tan(a)
x = arange(-3, 3, .1)
y = m*x
data.append((clip(x+cos(a), -3, 3),clip(y+sin(a), -3, 3)))
for x, y in data: # make a dynamic plot from the data
try:
plotdata.set_data(x, y)
except NameError:
ion()
fig = figure()
plot(cos(arange(0, 2.21*pi, .2)), sin(arange(0, 2.21*pi, .2)))
plotdata = plot(x, y)[0]
xlim(-2, 2)
ylim(-2, 2)
draw()
time.sleep(.01)
I put in the time.sleep(.01) command to be extra sure that I could break the run, but in my tests (running Linux) it wasn't necessary.
|
Quitting matplotlib.pyplot animation gracefully
|
I have a script that plots data of some photometry apertures, and I want to plot them in an xy plot. I am using matplotlib.pyplot with python 2.5.
The input data is stored in around 500 files and read. I am aware that this is not the most efficient way of inputting the data but that's another issue...
Example code:
import matplotlib.pyplot as plt
xcoords = []
ycoords = []
# lists are populated with data from first file
pltline, = plt.plot(xcoords, ycoords, 'rx')
# then loop populating the data from each file
for file in filelist:
xcoords = [...]
ycoords = [...]
pltline.set_xdata(xcoords)
pltline.set_ydata(ycoords)
plt.draw()
As there are over 500 files, I will occasionally want to close the animation window in the middle of the plotting. My code to plot works but it doesn't exit very gracefully. The plot window does not respond to clicking the close button and I have to Ctrl+C out of it.
Can anyone help me find a way to close the animation window while the script is running whilst looking graceful (well more graceful than a series of python traceback errors)?
|
[
"If you update the data and do the draw in a loop, you should be able to interrupt it. Here's an example (that draws a stationary circle and then moves a line around the perimeter):\nfrom pylab import *\nimport time\n\ndata = [] # make the data\nfor i in range(1000):\n a = .01*pi*i+.0007\n m = -1./tan(a)\n x = arange(-3, 3, .1)\n y = m*x\n data.append((clip(x+cos(a), -3, 3),clip(y+sin(a), -3, 3)))\n\n\nfor x, y in data: # make a dynamic plot from the data\n try:\n plotdata.set_data(x, y)\n except NameError:\n ion()\n fig = figure()\n plot(cos(arange(0, 2.21*pi, .2)), sin(arange(0, 2.21*pi, .2)))\n plotdata = plot(x, y)[0]\n xlim(-2, 2)\n ylim(-2, 2)\n draw()\n time.sleep(.01)\n\nI put in the time.sleep(.01) command to be extra sure that I could break the run, but in my tests (running Linux) it wasn't necessary.\n"
] |
[
2
] |
[] |
[] |
[
"animation",
"matplotlib",
"python",
"quit"
] |
stackoverflow_0001735370_animation_matplotlib_python_quit.txt
|
Q:
Python binary diff
I'm trying to use bsdiff (or any binary diff implementation you come up with) to compute and apply diff onto random binary data. I would like to use it on data from a database, so it would be better not to have to write those onto disk and pass them to bsdiff.exe.
Is there any wrapper library or way in python to do that?
A:
From the bsdiff website:
It has also been made into a Python extension module, and there is a Windows port available.
Following the link brings you to the module's page.
A:
You can use difflib that is part of Python standard library. You can send any arbitrary data into a difflib.SequenceMatcher.
A:
Also, the SequenceMatcher class (from the Python standard library) can be helpful.
Check out the other contents of the difflib module as well.
|
Python binary diff
|
I'm trying to use bsdiff (or any binary diff implementation you come up with) to compute and apply diff onto random binary data. I would like to use it on data from a database, so it would be better not to have to write those onto disk and pass them to bsdiff.exe.
Is there any wrapper library or way in python to do that?
|
[
"From the bsdiff website:\n\nIt has also been made into a Python extension module, and there is a Windows port available.\n\nFollowing the link brings you to the module's page.\n",
"You can use difflib that is part of Python standard library. You can send any arbitrary data into a difflib.SequenceMatcher.\n",
"Also, the SequenceMatcher class (from the Python standard library) can be helpful.\nCheck out the other contents of the difflib module as well.\n"
] |
[
5,
2,
1
] |
[] |
[] |
[
"diff",
"python"
] |
stackoverflow_0001736348_diff_python.txt
|
Q:
Cannot run appengine-admin on dev_server
I've decided to try out this project:
http://code.google.com/p/appengine-admin/wiki/QuickStart
For the sake of the experiment, I took the demo guest-book shipped with App Engine. The import park look like this:
import cgi
import datetime
import wsgiref.handlers
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google import appengine_admin
The db model and the admin look like this:
class Greeting(db.Model):
author = db.UserProperty()
content = db.StringProperty(multiline=True)
date = db.DateTimeProperty(auto_now_add=True)
class AdminGreeting(appengine_admin.ModelAdmin):
model = Greeting
listFields = ('author','content','date')
editFields = ('author','content','date')
appengine_admin.register(AdminGreeting)
Yet I get this exception, trying to run the site:
File "/home/<username>/python/google_appengine/google/appengine/tools/ dev_appserver.py", line 2875, in _HandleRequest
base_env_dict=env_dict)
File "/home/<username>/python/google_appengine/google/appengine/tools/dev_appserver.py", line 387, in Dispatch
base_env_dict=base_env_dict)
File "/home/<username>/python/google_appengine/google/appengine/tools/dev_appserver.py", line 2162, in Dispatch
self._module_dict)
File "/home/<username>/python/google_appengine/google/appengine/tools/dev_appserver.py", line 2080, in ExecuteCGI
reset_modules = exec_script(handler_path, cgi_path, hook)
File "/home/<username>/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1976, in ExecuteOrImportScript
exec module_code in script_module.__dict__
File "/home/<username>/python/google_appengine/demos/guestbook/guestbook.py", line 37, in <module>
appengine_admin.register(AdminGreeting)
File "/home/<username>/python/google_appengine/google/appengine_admin/model_register.py", line 120, in register
modelAdminInstance = modelAdminClass()
File "/home/<username>/python/google_appengine/google/appengine_admin/model_register.py", line 64, in __init__
self._extractProperties(self.listFields, self._listProperties)
File "/home/<username>/python/google_appengine/google/appengine_admin/model_register.py", line 76, in _extractProperties
storage.append(PropertyWrapper(getattr(self.model, propertyName), propertyName))
File "/home/<username>/python/google_appengine/google/appengine_admin/model_register.py", line 17, in __init__
logging.info("Caching info about property '%s'" % name)
File "/usr/lib/python2.6/logging/__init__.py", line 1451, in info
root.info(*((msg,)+args), **kwargs)
File "/usr/lib/python2.6/logging/__init__.py", line 1030, in info
self._log(INFO, msg, args, **kwargs)
File "/usr/lib/python2.6/logging/__init__.py", line 1142, in _log
record = self.makeRecord(self.name, level, fn, lno, msg, args, exc_info, func, extra)
File "/usr/lib/python2.6/logging/__init__.py", line 1117, in makeRecord
rv = LogRecord(name, level, fn, lno, msg, args, exc_info, func)
File "/usr/lib/python2.6/logging/__init__.py", line 272, in __init__
from multiprocessing import current_process
File "/home/<username>/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1089, in decorate
return func(self, *args, **kwargs)
File "/home/<username>/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1736, in load_module
return self.FindAndLoadModule(submodule, fullname, search_path)
File "/home/<username>/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1089, in decorate
return func(self, *args, **kwargs)
File "/home/<username>/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1638, in FindAndLoadModule
description)
File "/home/<username>/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1089, in decorate
return func(self, *args, **kwargs)
File "/home/<username>/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1589, in LoadModuleRestricted
description)
File "/usr/lib/python2.6/multiprocessing/__init__.py", line 83, in <module>
import _multiprocessing
ImportError: No module named _multiprocessing
INFO 2009-04-25 23:34:27,628 dev_appserver.py:2934] "GET / HTTP/1.1" 500 -
Any idea what could have went wrong?
A:
You appear to be using Python 2.6 (given that some of the messages are from files in /usr/lib/python2.6 ...!), but Google App Engine needs Python 2.5 (any 2.5.x will do for any versions of x), so you should install and use that to run the App Engine SDK.
A:
Google App Engine only supports Python 2.5, and you're on a newer version.
By the look of your directories, you might be on a Linux (or is it a Mac?). On, say, Ubuntu you can "sudo apt-get install python2.5" (it won't affect your Python 2.6 at all), and then rather than:
<path-to-gae>/dev_appserver.py ...
do
python2.5 <path-to-gae>/dev_appserver.py ...
This is better than just blithely developing on 2.6 and deploying on 2.5 which is surely asking for hassles later on.
A:
As others have said, this problem occurs in Python 2.6. I used the fix proposed in this comment in the App Engine issue tracker:
A quickfix is to create a file in your app's root named `_multiprocessing.py' with
the contents:
import multiprocessing
This way it's possible to import the _multiprocessing module.
It worked for me using Python 2.6.2
Cheers,
Kaji
A:
To make this work on my local machine (with 2.6) and on GAE, I used:
import sys, logging
if sys.version[:3] == "2.6": logging.logMultiprocessing = 0
A:
just do the following at the top of your something.py
import logging
logging.logMultiprocessing = 0
A:
import logging
logging.logMultiprocessing = 0
Worked for me
A:
It wired that I have been using GAE with python2.6(probably 2.6.1), and every thing worked fine.
But now I get the same _multiprocess import error.(python2.6.2).
A:
import logging
logging.logMultiprocessing = 0
Worked for me too. Before uploading to GAE, comment those lines.
|
Cannot run appengine-admin on dev_server
|
I've decided to try out this project:
http://code.google.com/p/appengine-admin/wiki/QuickStart
For the sake of the experiment, I took the demo guest-book shipped with App Engine. The import park look like this:
import cgi
import datetime
import wsgiref.handlers
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google import appengine_admin
The db model and the admin look like this:
class Greeting(db.Model):
author = db.UserProperty()
content = db.StringProperty(multiline=True)
date = db.DateTimeProperty(auto_now_add=True)
class AdminGreeting(appengine_admin.ModelAdmin):
model = Greeting
listFields = ('author','content','date')
editFields = ('author','content','date')
appengine_admin.register(AdminGreeting)
Yet I get this exception, trying to run the site:
File "/home/<username>/python/google_appengine/google/appengine/tools/ dev_appserver.py", line 2875, in _HandleRequest
base_env_dict=env_dict)
File "/home/<username>/python/google_appengine/google/appengine/tools/dev_appserver.py", line 387, in Dispatch
base_env_dict=base_env_dict)
File "/home/<username>/python/google_appengine/google/appengine/tools/dev_appserver.py", line 2162, in Dispatch
self._module_dict)
File "/home/<username>/python/google_appengine/google/appengine/tools/dev_appserver.py", line 2080, in ExecuteCGI
reset_modules = exec_script(handler_path, cgi_path, hook)
File "/home/<username>/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1976, in ExecuteOrImportScript
exec module_code in script_module.__dict__
File "/home/<username>/python/google_appengine/demos/guestbook/guestbook.py", line 37, in <module>
appengine_admin.register(AdminGreeting)
File "/home/<username>/python/google_appengine/google/appengine_admin/model_register.py", line 120, in register
modelAdminInstance = modelAdminClass()
File "/home/<username>/python/google_appengine/google/appengine_admin/model_register.py", line 64, in __init__
self._extractProperties(self.listFields, self._listProperties)
File "/home/<username>/python/google_appengine/google/appengine_admin/model_register.py", line 76, in _extractProperties
storage.append(PropertyWrapper(getattr(self.model, propertyName), propertyName))
File "/home/<username>/python/google_appengine/google/appengine_admin/model_register.py", line 17, in __init__
logging.info("Caching info about property '%s'" % name)
File "/usr/lib/python2.6/logging/__init__.py", line 1451, in info
root.info(*((msg,)+args), **kwargs)
File "/usr/lib/python2.6/logging/__init__.py", line 1030, in info
self._log(INFO, msg, args, **kwargs)
File "/usr/lib/python2.6/logging/__init__.py", line 1142, in _log
record = self.makeRecord(self.name, level, fn, lno, msg, args, exc_info, func, extra)
File "/usr/lib/python2.6/logging/__init__.py", line 1117, in makeRecord
rv = LogRecord(name, level, fn, lno, msg, args, exc_info, func)
File "/usr/lib/python2.6/logging/__init__.py", line 272, in __init__
from multiprocessing import current_process
File "/home/<username>/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1089, in decorate
return func(self, *args, **kwargs)
File "/home/<username>/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1736, in load_module
return self.FindAndLoadModule(submodule, fullname, search_path)
File "/home/<username>/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1089, in decorate
return func(self, *args, **kwargs)
File "/home/<username>/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1638, in FindAndLoadModule
description)
File "/home/<username>/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1089, in decorate
return func(self, *args, **kwargs)
File "/home/<username>/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1589, in LoadModuleRestricted
description)
File "/usr/lib/python2.6/multiprocessing/__init__.py", line 83, in <module>
import _multiprocessing
ImportError: No module named _multiprocessing
INFO 2009-04-25 23:34:27,628 dev_appserver.py:2934] "GET / HTTP/1.1" 500 -
Any idea what could have went wrong?
|
[
"You appear to be using Python 2.6 (given that some of the messages are from files in /usr/lib/python2.6 ...!), but Google App Engine needs Python 2.5 (any 2.5.x will do for any versions of x), so you should install and use that to run the App Engine SDK.\n",
"Google App Engine only supports Python 2.5, and you're on a newer version.\nBy the look of your directories, you might be on a Linux (or is it a Mac?). On, say, Ubuntu you can \"sudo apt-get install python2.5\" (it won't affect your Python 2.6 at all), and then rather than:\n<path-to-gae>/dev_appserver.py ...\n\ndo\npython2.5 <path-to-gae>/dev_appserver.py ...\n\nThis is better than just blithely developing on 2.6 and deploying on 2.5 which is surely asking for hassles later on.\n",
"As others have said, this problem occurs in Python 2.6. I used the fix proposed in this comment in the App Engine issue tracker:\nA quickfix is to create a file in your app's root named `_multiprocessing.py' with \nthe contents:\n\n import multiprocessing\n\nThis way it's possible to import the _multiprocessing module.\n\nIt worked for me using Python 2.6.2\n\nCheers,\nKaji\n\n",
"To make this work on my local machine (with 2.6) and on GAE, I used:\nimport sys, logging\nif sys.version[:3] == \"2.6\": logging.logMultiprocessing = 0\n\n",
"just do the following at the top of your something.py \nimport logging\nlogging.logMultiprocessing = 0\n",
"import logging\nlogging.logMultiprocessing = 0\n\nWorked for me\n",
"It wired that I have been using GAE with python2.6(probably 2.6.1), and every thing worked fine.\nBut now I get the same _multiprocess import error.(python2.6.2).\n",
"import logging\nlogging.logMultiprocessing = 0\n\nWorked for me too. Before uploading to GAE, comment those lines.\n"
] |
[
4,
3,
3,
2,
1,
1,
0,
0
] |
[] |
[] |
[
"google_app_engine",
"python"
] |
stackoverflow_0000790001_google_app_engine_python.txt
|
Q:
How to bundle tkinter?
I am distributing an app that uses the Python/C API. I have all standard python modules in python31.zip which is basically an archive of the Lib folder in the python install directory. Here is the problem - most common modules like sys and io work fine. BUT tkinter does not. I get an error "cannot find module _tkinter". I really need tkinter in my project. I'm using Windows if that helps.
A:
why don't you use py2exe to bundle your application as an executable? It should take care of all the dependencies, and will include whatever you need.
A:
I don't the best way to bundle tkinter with your app, but I do know why you're getting the error you are. The relevant section of the zipimport module documentation:
Any files may be present in the ZIP archive, but only files .py and .py[co] are available for import. ZIP import of dynamic modules (.pyd, .so) is disallowed. Note that if an archive only contains .py files, Python will not attempt to modify the archive by adding the corresponding .pyc or .pyo file, meaning that if a ZIP archive doesn’t contain .pyc files, importing may be rather slow.
The module _tkinter is a c-extension / shared library. It can't be imported from a zip file.
|
How to bundle tkinter?
|
I am distributing an app that uses the Python/C API. I have all standard python modules in python31.zip which is basically an archive of the Lib folder in the python install directory. Here is the problem - most common modules like sys and io work fine. BUT tkinter does not. I get an error "cannot find module _tkinter". I really need tkinter in my project. I'm using Windows if that helps.
|
[
"why don't you use py2exe to bundle your application as an executable? It should take care of all the dependencies, and will include whatever you need.\n",
"I don't the best way to bundle tkinter with your app, but I do know why you're getting the error you are. The relevant section of the zipimport module documentation:\n\nAny files may be present in the ZIP archive, but only files .py and .py[co] are available for import. ZIP import of dynamic modules (.pyd, .so) is disallowed. Note that if an archive only contains .py files, Python will not attempt to modify the archive by adding the corresponding .pyc or .pyo file, meaning that if a ZIP archive doesn’t contain .pyc files, importing may be rather slow.\n\nThe module _tkinter is a c-extension / shared library. It can't be imported from a zip file.\n"
] |
[
1,
1
] |
[] |
[] |
[
"python",
"tkinter"
] |
stackoverflow_0001736742_python_tkinter.txt
|
Q:
Programatically saving an image to a Django ImageField is creating an infinite loop of images
I've got a save method on a model that looks like so:
def save(self, force_insert=False, force_update=False):
img_url = "http://example.com/%s.jpg" % (self.title)
name = urlparse(img_url).path.split('/')[-1]
content = urllib.urlretrieve(img_url)
self.image.save(name, File(open(content[0])), save=True)
super(Test, self).save(force_insert, force_update)
For some reason, this is creating an infinite loop of image creations with ever more _s in the filename. I finally figured out it was doing that when I got a Django error that said that the file it was trying to save had too many characters (I found 242 images saved).
I was trying to use information from this question.
Any idea what's going on here?
A:
I think from a browse through the source code that calling ImageFileField.save() (actually FileField.save() due to inheritance) causes the instance (namely the db row) that the file name is stored in to be updated.
This means that in your save method you call ImageFileField.save() which in turn calls your save method, causing the recursion.
From reading the source code, if you want to prevent this, then just pass save=False to self.image.save. This will save the file data to disk, but just won't save the instance (db row) data. However in the next line you save it by calling the superclass, so I think it will be saved to the database then.
In fact it looks like that the save=False on the save method was designed to help with this case!
A:
I'm not 100% certain, but it could be that when self.image.save is called, it calls the save method of the model, by default, as well - Thus creating your infinite loop. I haven't tested it but I could see that happening.
My suggestion if that is the issue: Send a signal from within the models save method containing that instance and then have a seperate function to download/parse the image and save it.
|
Programatically saving an image to a Django ImageField is creating an infinite loop of images
|
I've got a save method on a model that looks like so:
def save(self, force_insert=False, force_update=False):
img_url = "http://example.com/%s.jpg" % (self.title)
name = urlparse(img_url).path.split('/')[-1]
content = urllib.urlretrieve(img_url)
self.image.save(name, File(open(content[0])), save=True)
super(Test, self).save(force_insert, force_update)
For some reason, this is creating an infinite loop of image creations with ever more _s in the filename. I finally figured out it was doing that when I got a Django error that said that the file it was trying to save had too many characters (I found 242 images saved).
I was trying to use information from this question.
Any idea what's going on here?
|
[
"I think from a browse through the source code that calling ImageFileField.save() (actually FileField.save() due to inheritance) causes the instance (namely the db row) that the file name is stored in to be updated.\nThis means that in your save method you call ImageFileField.save() which in turn calls your save method, causing the recursion.\nFrom reading the source code, if you want to prevent this, then just pass save=False to self.image.save. This will save the file data to disk, but just won't save the instance (db row) data. However in the next line you save it by calling the superclass, so I think it will be saved to the database then.\nIn fact it looks like that the save=False on the save method was designed to help with this case!\n",
"I'm not 100% certain, but it could be that when self.image.save is called, it calls the save method of the model, by default, as well - Thus creating your infinite loop. I haven't tested it but I could see that happening.\nMy suggestion if that is the issue: Send a signal from within the models save method containing that instance and then have a seperate function to download/parse the image and save it. \n"
] |
[
5,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001736550_django_python.txt
|
Q:
How Can I Make This Python Code More Usable And Readable?
Beginner in python, but been programming for about 5 years now. I suspect I have a lot to learn about doing things the object oriented way, but I know the basics. I planned on programming a calculator that shows it's work for the challenge and knowledge i'll gain from it. I just started and this is what i've got, and it just looks really ugly to me. How would you have done it differently?
P.S. This is just a simple script to take the problem from inside parenthesis, add it up, show the work, then evaluate the full problem.
import re
def EvalParenths(problem):
contents = ""
if re.match( "\(", problem):
contents = re.match("(\(.*\))", problem)
parenthsAnswer = contents.group(0)
problem = problem.replace(parenthsAnswer, '')
print " \ \n " + str(eval(parenthsAnswer)) + problem
problem = problem.replace(parenthsAnswer, '')
answer = eval(parenthsAnswer+problem)
print " \ \n " + str(answer)
else:
print "Didn't Find Parenthesis"
def ProblemHasParenths(problem):
return re.match( "\(", problem)
"""""
Example Problem: (12/4)*2
"""""
problem = raw_input()
if ProblemHasParenths:
EvalParenths(problem)
A:
Some problems:
contents = re.match("(\(.*\))", problem)
When it's given the input (1+2)/(3+4), it's going to try to evaluate 1+2)/(3+4.
It also doesn't go all the way into nested parentheses, for this you would need to use recursion.
I think you should make another attempt at this before you "look at the answers".
A:
If you want to make a simple calculator you could try implementing Shunting-yard algorithm.
But if you want to go with regex approach I'd still do it a little differently:
import re
#In python functions/methods usually are lowercase
#and words are seperated by _ while classes use CamelCasing
def eval_step_by_step(expression):
"""Evaluates math expression. Doesn't do any error checking.
expression (string) - math expression"""
print expression
#For pretty formating.
expr_len = len(expression)
#While there's parentheses in the expression.
while True:
#re.match checks for a match only at the beginning of the string,
#while re.search checks for a match anywhere in the string.
#Matches all numbers, +, -, *, / and whitespace within parentheses
#lazily (innermost first).
contents = re.search("\(([0-9|\*|/|\+|\-|\s]*?)\)", expression)
#If we didn't find anything, print result and break out of loop.
if not contents:
#string.format() is the Python 3 way of formating strings
#(Also works in Python 2.6).
#Print eval(expression) aligned right in a "field" with width
#of expr_len characters.
print "{0:{1}}".format(eval(expression), expr_len)
break
#group(0) [match] is everything matching our search,
#group(1) [parentheses_text] is just epression withing parentheses.
match, parentheses_text = contents.group(0), contents.group(1)
expression = expression.replace(match, str(eval(parentheses_text)))
#Aligns text to the right. Have to use ">" here
#because expression is not a number.
print "{0:>{1}}".format(expression, expr_len)
#For example try: (4+3+(32-1)*3)*3
problem = raw_input("Input math problem: ")
eval_step_by_step(problem)
It doesn't exactly work the same as your function, but you could easily implement modifications into your function to match mine. As you can see, I've also added a lot of comments to explain some stuff.
A:
I'd probably replace occurrences of
re.match( "\(", problem)
with
problem.startswith("(")
In
contents = re.match("(\(.*\))", problem)
parenthsAnswer = contents.group(0)
you don't check to see whether contents matches or not so if you pass it the input "(1" you'll get an exception when you try to evaluate contents.group(0)
Don't every use eval in a real program!
You could use pyparsing to make a full parser, but I think it is the kind of thing everyone should try on their own as an exercise at least once!
A:
Why don't you match only for the double and matching parentheses? The first match for a single ( is not really necessary because if the match for the doubles fail, this means there are no expression for you to evaluate.
import re
def eval_parentheses(problem):
contents = re.match("(\(.*\))", problem)
if contents:
...
else:
print "Couldn't find parentheses!"
Also, the parentheses selection algorithm could be improved a bit for nested parens etc.
|
How Can I Make This Python Code More Usable And Readable?
|
Beginner in python, but been programming for about 5 years now. I suspect I have a lot to learn about doing things the object oriented way, but I know the basics. I planned on programming a calculator that shows it's work for the challenge and knowledge i'll gain from it. I just started and this is what i've got, and it just looks really ugly to me. How would you have done it differently?
P.S. This is just a simple script to take the problem from inside parenthesis, add it up, show the work, then evaluate the full problem.
import re
def EvalParenths(problem):
contents = ""
if re.match( "\(", problem):
contents = re.match("(\(.*\))", problem)
parenthsAnswer = contents.group(0)
problem = problem.replace(parenthsAnswer, '')
print " \ \n " + str(eval(parenthsAnswer)) + problem
problem = problem.replace(parenthsAnswer, '')
answer = eval(parenthsAnswer+problem)
print " \ \n " + str(answer)
else:
print "Didn't Find Parenthesis"
def ProblemHasParenths(problem):
return re.match( "\(", problem)
"""""
Example Problem: (12/4)*2
"""""
problem = raw_input()
if ProblemHasParenths:
EvalParenths(problem)
|
[
"Some problems:\ncontents = re.match(\"(\\(.*\\))\", problem)\n\nWhen it's given the input (1+2)/(3+4), it's going to try to evaluate 1+2)/(3+4.\nIt also doesn't go all the way into nested parentheses, for this you would need to use recursion.\nI think you should make another attempt at this before you \"look at the answers\".\n",
"If you want to make a simple calculator you could try implementing Shunting-yard algorithm.\nBut if you want to go with regex approach I'd still do it a little differently:\nimport re\n\n#In python functions/methods usually are lowercase\n#and words are seperated by _ while classes use CamelCasing\ndef eval_step_by_step(expression):\n \"\"\"Evaluates math expression. Doesn't do any error checking.\n expression (string) - math expression\"\"\"\n\n print expression\n #For pretty formating.\n expr_len = len(expression)\n #While there's parentheses in the expression.\n while True:\n #re.match checks for a match only at the beginning of the string,\n #while re.search checks for a match anywhere in the string.\n\n #Matches all numbers, +, -, *, / and whitespace within parentheses\n #lazily (innermost first).\n contents = re.search(\"\\(([0-9|\\*|/|\\+|\\-|\\s]*?)\\)\", expression) \n #If we didn't find anything, print result and break out of loop.\n if not contents:\n #string.format() is the Python 3 way of formating strings\n #(Also works in Python 2.6).\n\n #Print eval(expression) aligned right in a \"field\" with width\n #of expr_len characters.\n print \"{0:{1}}\".format(eval(expression), expr_len)\n break\n\n #group(0) [match] is everything matching our search,\n #group(1) [parentheses_text] is just epression withing parentheses.\n match, parentheses_text = contents.group(0), contents.group(1)\n expression = expression.replace(match, str(eval(parentheses_text)))\n #Aligns text to the right. Have to use \">\" here\n #because expression is not a number.\n print \"{0:>{1}}\".format(expression, expr_len)\n\n#For example try: (4+3+(32-1)*3)*3\nproblem = raw_input(\"Input math problem: \")\n\neval_step_by_step(problem)\n\nIt doesn't exactly work the same as your function, but you could easily implement modifications into your function to match mine. As you can see, I've also added a lot of comments to explain some stuff.\n",
"I'd probably replace occurrences of\nre.match( \"\\(\", problem)\n\nwith\nproblem.startswith(\"(\")\n\nIn\ncontents = re.match(\"(\\(.*\\))\", problem)\nparenthsAnswer = contents.group(0)\n\nyou don't check to see whether contents matches or not so if you pass it the input \"(1\" you'll get an exception when you try to evaluate contents.group(0)\nDon't every use eval in a real program!\nYou could use pyparsing to make a full parser, but I think it is the kind of thing everyone should try on their own as an exercise at least once!\n",
"Why don't you match only for the double and matching parentheses? The first match for a single ( is not really necessary because if the match for the doubles fail, this means there are no expression for you to evaluate.\nimport re\n\ndef eval_parentheses(problem):\n contents = re.match(\"(\\(.*\\))\", problem)\n if contents:\n ...\n else:\n print \"Couldn't find parentheses!\"\n\nAlso, the parentheses selection algorithm could be improved a bit for nested parens etc.\n"
] |
[
5,
2,
2,
0
] |
[] |
[] |
[
"oop",
"python",
"readability",
"usability"
] |
stackoverflow_0001737013_oop_python_readability_usability.txt
|
Q:
Tree view GUI widget/gui library that can do multiple icons?
Screenshot
I'm looking to recreate this in Python; I can't find a library that seems to have what I need. Are there any GUI libraries that might possibly have this? - I have scoured wxWidgets (which is my preferred gui library) but they have nothing similar.
I have a script already that uses a standard wxTreeCtrl but it has no provisions for adding additional icons at the tail end like this screen shot.
If no pre-existing gui library exists, any tips for my first steps in trying to create it myself?
A:
you have few options
Use wx.lib.customtreectrl.CustomTreeCtrl
AppendItem of CustomTreeCtrl can take any wx widget, which is shown at end, so you can use that to affect e.g. tree.AppendItem(root, "item1", wnd=yourImageControl)
Use wx.gizmos.TreeListCtrl, you can have icons in separate columns and tree in first column
You can use wx.lib.mvctree , and supply your own Painter class or derive class from TreePainter, and override Paint method
Or most complex but most satisfying way is to write your own tree control, and if you have long term usage for such a control and you may need more custom changes, it will be best way and won't be much difficult. See mvtree for inspiration or customize that.
A:
Instead of CustomTreeCtrl, I'd look into HyperTreeList. It is based on CustomTreeCtrl, but adds support for multiple columns. I'm not sure if it supports multiple icons in one column out of the box though.
|
Tree view GUI widget/gui library that can do multiple icons?
|
Screenshot
I'm looking to recreate this in Python; I can't find a library that seems to have what I need. Are there any GUI libraries that might possibly have this? - I have scoured wxWidgets (which is my preferred gui library) but they have nothing similar.
I have a script already that uses a standard wxTreeCtrl but it has no provisions for adding additional icons at the tail end like this screen shot.
If no pre-existing gui library exists, any tips for my first steps in trying to create it myself?
|
[
"you have few options\n\nUse wx.lib.customtreectrl.CustomTreeCtrl\nAppendItem of CustomTreeCtrl can take any wx widget, which is shown at end, so you can use that to affect e.g. tree.AppendItem(root, \"item1\", wnd=yourImageControl)\nUse wx.gizmos.TreeListCtrl, you can have icons in separate columns and tree in first column\nYou can use wx.lib.mvctree , and supply your own Painter class or derive class from TreePainter, and override Paint method\nOr most complex but most satisfying way is to write your own tree control, and if you have long term usage for such a control and you may need more custom changes, it will be best way and won't be much difficult. See mvtree for inspiration or customize that.\n\n",
"Instead of CustomTreeCtrl, I'd look into HyperTreeList. It is based on CustomTreeCtrl, but adds support for multiple columns. I'm not sure if it supports multiple icons in one column out of the box though.\n"
] |
[
2,
0
] |
[] |
[] |
[
"python",
"user_interface",
"wxpython"
] |
stackoverflow_0001736917_python_user_interface_wxpython.txt
|
Q:
Why is wx.SingleChoiceDialog not subclassing properly
I'm trying to subclass the wxpython SingleChoiceDialog class. I have a TableChoiceDialog class that inherits from SingleChoiceDialog adding generic functionality, and I have 2 sub classes for that add more refined functionality. Basically I'm O.O.P'ing
In my TableChoiceDialog class I have a line which calls the superclass's __init__, i.e.
class TableChoiceDialog(wx.SingleChoiceDialog):
def __init__(self, parent, message, caption, list, ...other args...):
wx.SingleChoiceDialog.__init__(self, parent, message, caption, list)
The problem I'm having is that according to the SingleChoiceDialog.__init__ docstring (and the wxPython API), SingleChoiceDialog does not have the self argument as part of it's __init__ method.
__init__(Window parent, String message, String caption,
List choices=EmptyList, long style=CHOICEDLG_STYLE,
Point pos=DefaultPosition) -> SingleChoiceDialog
As I have it above, the program prints the error:
swig/python detected a memory leak of type 'wxSingleChoiceDialog *', no destructor found.
If I take out the self parameter the system complains that it was expecting a SingleChoiceDialog object as a first argument, which seems to point to it actually wanting a reference to self.
When I take out the parent argument, leaving self (and the other 3 which I'm pretty sure are fine) the system complains that it only recieved 3 arguments, when it needed 4. I'm pretty certain I'm passing 4.
So. What blatantly obvious mistake have I made? Have I totally misunderstood how python handles objects (and hence pretty much misunderstood python)? Have I misunderstood OOP as a whole?
Please help. Thanks in advance
A:
The call to __init__ seems alright (the first argument to __init__ is always self).
You might have a wrong build of wx. The swig's warning message indicates that there is no desctructor was generated for wxSingleChoiceDialog, see this memory leak discussion.
The message may be unrelated to the __init__ call.
A:
Some of the dialogs in wxPython are not subclassable because they are not real classes, but instead wrappers around the platform API method for displaying the dialog. I know this is the case for wx.MessageDialog, it might also be the case for wx.SingleChoiceDialog.
|
Why is wx.SingleChoiceDialog not subclassing properly
|
I'm trying to subclass the wxpython SingleChoiceDialog class. I have a TableChoiceDialog class that inherits from SingleChoiceDialog adding generic functionality, and I have 2 sub classes for that add more refined functionality. Basically I'm O.O.P'ing
In my TableChoiceDialog class I have a line which calls the superclass's __init__, i.e.
class TableChoiceDialog(wx.SingleChoiceDialog):
def __init__(self, parent, message, caption, list, ...other args...):
wx.SingleChoiceDialog.__init__(self, parent, message, caption, list)
The problem I'm having is that according to the SingleChoiceDialog.__init__ docstring (and the wxPython API), SingleChoiceDialog does not have the self argument as part of it's __init__ method.
__init__(Window parent, String message, String caption,
List choices=EmptyList, long style=CHOICEDLG_STYLE,
Point pos=DefaultPosition) -> SingleChoiceDialog
As I have it above, the program prints the error:
swig/python detected a memory leak of type 'wxSingleChoiceDialog *', no destructor found.
If I take out the self parameter the system complains that it was expecting a SingleChoiceDialog object as a first argument, which seems to point to it actually wanting a reference to self.
When I take out the parent argument, leaving self (and the other 3 which I'm pretty sure are fine) the system complains that it only recieved 3 arguments, when it needed 4. I'm pretty certain I'm passing 4.
So. What blatantly obvious mistake have I made? Have I totally misunderstood how python handles objects (and hence pretty much misunderstood python)? Have I misunderstood OOP as a whole?
Please help. Thanks in advance
|
[
"\nThe call to __init__ seems alright (the first argument to __init__ is always self).\nYou might have a wrong build of wx. The swig's warning message indicates that there is no desctructor was generated for wxSingleChoiceDialog, see this memory leak discussion.\n\nThe message may be unrelated to the __init__ call.\n",
"Some of the dialogs in wxPython are not subclassable because they are not real classes, but instead wrappers around the platform API method for displaying the dialog. I know this is the case for wx.MessageDialog, it might also be the case for wx.SingleChoiceDialog.\n"
] |
[
0,
0
] |
[] |
[] |
[
"oop",
"python",
"subclass",
"wxpython"
] |
stackoverflow_0000655662_oop_python_subclass_wxpython.txt
|
Q:
SQLAlchemy 0.5.5 - defining table schema
I used sqlautocode to generate a model.py for an existing MySQL database and here's a table example:
fusion_articles = Table('fusion_articles', metadata,
Column(u'article_id', Integer(), primary_key=True, nullable=False),
Column(u'article_cat', Integer(), primary_key=False, nullable=False),
Column(u'article_subject', String(length=200, convert_unicode=False, assert_unicode=None), primary_key=False, nullable=False),
Column(u'article_snippet', Text(length=None, convert_unicode=False, assert_unicode=None), primary_key=False, nullable=False),
Column(u'article_article', Text(length=None, convert_unicode=False, assert_unicode=None), primary_key=False, nullable=False),
Column(u'article_breaks', CHAR(length=1, convert_unicode=False, assert_unicode=None), primary_key=False, nullable=False),
Column(u'article_name', Integer(), primary_key=False, nullable=False),
Column(u'article_datestamp', Integer(), primary_key=False, nullable=False),
Column(u'article_reads', Integer(), primary_key=False, nullable=False),
Column(u'article_allow_comments', Boolean(), primary_key=False, nullable=False),
Column(u'article_allow_ratings', Boolean(), primary_key=False, nullable=False),
)
Some of the examples I've seen prefixed the Column, Integer() and other similar datatypes with schema that's imported from sqlalchemy. Should I import Column and the rest individually, such as:
>>> from sqlalchemy import Table, Column, Integer, String, MetaData
>>> metadata = MetaData()
Or should I always prefix them?
schema.Table, meta.metadata
A:
It's largely a style preference, but also depends on how complex your code is.
If you're writing a short, isolated script that will likely not be imported elsewhere, bringing lots of names into your namespace (i.e. Table, Column) isn't a problem and makes the code easier to read.
If, on the other hand, you expect your module to be large and imported by other modules or third parties, you want to keep you namespace as clean as possible. Having the Table and MetaData classes in a separate namespace keeps them organized and clearly scoped. That is, if you're using the schema namespace, you can clearly tell that
>>> schema.Table
refers to the Table in the schema module and not another Table defined elsewhere.
Otherwise, the objects are exactly the same.
>>> from sqlalchemy import schema
>>> from sqlalchemy import Table
>>> Table is schema.Table
True
|
SQLAlchemy 0.5.5 - defining table schema
|
I used sqlautocode to generate a model.py for an existing MySQL database and here's a table example:
fusion_articles = Table('fusion_articles', metadata,
Column(u'article_id', Integer(), primary_key=True, nullable=False),
Column(u'article_cat', Integer(), primary_key=False, nullable=False),
Column(u'article_subject', String(length=200, convert_unicode=False, assert_unicode=None), primary_key=False, nullable=False),
Column(u'article_snippet', Text(length=None, convert_unicode=False, assert_unicode=None), primary_key=False, nullable=False),
Column(u'article_article', Text(length=None, convert_unicode=False, assert_unicode=None), primary_key=False, nullable=False),
Column(u'article_breaks', CHAR(length=1, convert_unicode=False, assert_unicode=None), primary_key=False, nullable=False),
Column(u'article_name', Integer(), primary_key=False, nullable=False),
Column(u'article_datestamp', Integer(), primary_key=False, nullable=False),
Column(u'article_reads', Integer(), primary_key=False, nullable=False),
Column(u'article_allow_comments', Boolean(), primary_key=False, nullable=False),
Column(u'article_allow_ratings', Boolean(), primary_key=False, nullable=False),
)
Some of the examples I've seen prefixed the Column, Integer() and other similar datatypes with schema that's imported from sqlalchemy. Should I import Column and the rest individually, such as:
>>> from sqlalchemy import Table, Column, Integer, String, MetaData
>>> metadata = MetaData()
Or should I always prefix them?
schema.Table, meta.metadata
|
[
"It's largely a style preference, but also depends on how complex your code is.\nIf you're writing a short, isolated script that will likely not be imported elsewhere, bringing lots of names into your namespace (i.e. Table, Column) isn't a problem and makes the code easier to read.\nIf, on the other hand, you expect your module to be large and imported by other modules or third parties, you want to keep you namespace as clean as possible. Having the Table and MetaData classes in a separate namespace keeps them organized and clearly scoped. That is, if you're using the schema namespace, you can clearly tell that\n>>> schema.Table\n\nrefers to the Table in the schema module and not another Table defined elsewhere.\nOtherwise, the objects are exactly the same.\n>>> from sqlalchemy import schema\n>>> from sqlalchemy import Table\n>>> Table is schema.Table\nTrue\n\n"
] |
[
1
] |
[] |
[] |
[
"python",
"sqlalchemy"
] |
stackoverflow_0001737351_python_sqlalchemy.txt
|
Q:
File open error by using codec utf-8 in python
I execute following code on windows xp and python 2.6.4
But it show IOError.
How to open file whose name has utf-8 codec.
>>> open( unicode('한글.txt', 'euc-kr').encode('utf-8') )
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
open( unicode('한글.txt', 'euc-kr').encode('utf-8') )
IOError: [Errno 22] invalid mode ('r') or filename: '\xed\x95\x9c\xea\xb8\x80.txt'
But the following code to the normal operation.
>>> open( unicode('한글.txt', 'euc-kr') )
<open file u'\ud55c\uae00.txt', mode 'r' at 0x01DD63E0>
A:
The C runtime interface that Windows exposes to Python uses the system code page to encode filenames. Unlike on OS X and modern Linux versions, on Windows the system code page is never UTF-8. So the UTF-8 byte string won't be any good.
You could encode the filename to the current code page using .encode('mbcs'), which in your case is probably equivalent to .encode('cp949'). To make it compatible with other platforms where filenames are UTF-8, you could look up sys.getfilesystemencoding, which will give you utf-8 there or mbcs on Windows.
However whilst cp949 would work for Korean characters, it would break on anything outside the repertoire of that code page (an extended version of EUC-KR).
So another approach is to keep your filenames as Unicode. On Windows this will use the Unicode-native interfaces to pass filenames to Windows in the UTF-16LE encoding it uses internally. (See PEP277 for more on this feature.)
This does generally still work on other platforms too: Linux and OS X should silently encode the Unicode filenames to UTF-8 for you. This may fail more in older Python versions, but it's the default way to handle filenames in Python 3 (where the default string type has changed to Unicode).
The traps to watch out for with using Unicode filenames on Python 2 are:
if os.path.supports_unicode_filenames is False, as it will be outside Windows, the functions that return filenames, such as os.listdir, will always give you byte strings. You'd have to detect that and decode them using sys.getfilesystemencoding.
if you have a file on Linux/OS X with a name that's not a valid UTF-8 string, you won't be able to get a Unicode filename for it (UnicodeDecodeError if you try). Bit of a corner case, but it can lead to annoying inaccessible files.
Incidentally,
open(unicode('한글.txt', 'euc-kr'))
Probably you would want to say 'cp949' there (as the Windows Korean code page has minor differences to EUC-KR). Or, more generally, 'mbcs', which gives you the system code page which is presumably going to be the same one your console is typing. Anyway, I don't know about PyShell, but normally if the above works then you should just be able to type it directly:
open(u'한글')
|
File open error by using codec utf-8 in python
|
I execute following code on windows xp and python 2.6.4
But it show IOError.
How to open file whose name has utf-8 codec.
>>> open( unicode('한글.txt', 'euc-kr').encode('utf-8') )
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
open( unicode('한글.txt', 'euc-kr').encode('utf-8') )
IOError: [Errno 22] invalid mode ('r') or filename: '\xed\x95\x9c\xea\xb8\x80.txt'
But the following code to the normal operation.
>>> open( unicode('한글.txt', 'euc-kr') )
<open file u'\ud55c\uae00.txt', mode 'r' at 0x01DD63E0>
|
[
"The C runtime interface that Windows exposes to Python uses the system code page to encode filenames. Unlike on OS X and modern Linux versions, on Windows the system code page is never UTF-8. So the UTF-8 byte string won't be any good.\nYou could encode the filename to the current code page using .encode('mbcs'), which in your case is probably equivalent to .encode('cp949'). To make it compatible with other platforms where filenames are UTF-8, you could look up sys.getfilesystemencoding, which will give you utf-8 there or mbcs on Windows.\nHowever whilst cp949 would work for Korean characters, it would break on anything outside the repertoire of that code page (an extended version of EUC-KR).\nSo another approach is to keep your filenames as Unicode. On Windows this will use the Unicode-native interfaces to pass filenames to Windows in the UTF-16LE encoding it uses internally. (See PEP277 for more on this feature.)\nThis does generally still work on other platforms too: Linux and OS X should silently encode the Unicode filenames to UTF-8 for you. This may fail more in older Python versions, but it's the default way to handle filenames in Python 3 (where the default string type has changed to Unicode).\nThe traps to watch out for with using Unicode filenames on Python 2 are:\n\nif os.path.supports_unicode_filenames is False, as it will be outside Windows, the functions that return filenames, such as os.listdir, will always give you byte strings. You'd have to detect that and decode them using sys.getfilesystemencoding.\nif you have a file on Linux/OS X with a name that's not a valid UTF-8 string, you won't be able to get a Unicode filename for it (UnicodeDecodeError if you try). Bit of a corner case, but it can lead to annoying inaccessible files.\n\nIncidentally,\nopen(unicode('한글.txt', 'euc-kr'))\n\nProbably you would want to say 'cp949' there (as the Windows Korean code page has minor differences to EUC-KR). Or, more generally, 'mbcs', which gives you the system code page which is presumably going to be the same one your console is typing. Anyway, I don't know about PyShell, but normally if the above works then you should just be able to type it directly:\nopen(u'한글')\n\n"
] |
[
17
] |
[] |
[] |
[
"python",
"unicode",
"utf_8"
] |
stackoverflow_0001737410_python_unicode_utf_8.txt
|
Q:
How do I make powerpoint play presentations/load up ppts automatically?
I was wondering how I can make a script load powerpoint file, advance slides automatically and put it on full screen. Is there a way to make windows do that? Can I just load powerpoint.exe and maybe use some sort of API/Pipe to give commands from another script.
To make a case: I'm making a script that automatically scans a folder in windows (using python) and loads up the powerpoint presentations and keeps playing them in order.
A:
One solution for you would be to use the PowerPoint Viewer program instead. PPT Viewer is set to open a PowerPoint file straight away in Presentation mode.
Alternatively, you can use the argument /s to start Powerpoint.
"powerpoint.exe /s <filename>.ppt"
This will be equivalent to telling PowerPoint to straight away open up in Presentation mode.
A:
As previously stated, this is more StackOverflow geared, but this can easily be achieved with Python and AutoHotkey.
On the Python side of things, as a general idea on how to go about this (I'm kind of rusty, beware!):
Find files using os.walk()
Append each to a list, then iterate over the list, opening each one with os.system("powerpoint.exe /s filename"). The next one should not open until the previous closes.
AutoHotkey wise:
Once opened, use #IfWinActive to detect an open Powerpoint window, and send mouse clicks to change slides at a set interval
I don't know what you mean by "order", you'll have to determine that in your Python script. If you want them alphabetical, sort the list alphabetically then iterate. If you want them sorted by creation date, then sort by date and iterate and so on.
A:
Save the file with the extension ".pps". That will make powerpoint open the file in presentation mode.
The presentaion needs to designed to advance slides, else you will have to script that part.
A:
If you want more control over the powerpoint slide, you could write something in VB.Net (or other .Net languages) according to this MS support article.
If you wanted direct control from Python, you could probably use pywin32 or comtypes to invoke directly the same interfaces as described in the MS article. My guess is this is the most powerful solution and would probably provide the smoothest transitions between presentations, but is probably a lot more work than using subprocess to call into PowerPoint.
|
How do I make powerpoint play presentations/load up ppts automatically?
|
I was wondering how I can make a script load powerpoint file, advance slides automatically and put it on full screen. Is there a way to make windows do that? Can I just load powerpoint.exe and maybe use some sort of API/Pipe to give commands from another script.
To make a case: I'm making a script that automatically scans a folder in windows (using python) and loads up the powerpoint presentations and keeps playing them in order.
|
[
"One solution for you would be to use the PowerPoint Viewer program instead. PPT Viewer is set to open a PowerPoint file straight away in Presentation mode.\nAlternatively, you can use the argument /s to start Powerpoint.\n\"powerpoint.exe /s <filename>.ppt\"\n\nThis will be equivalent to telling PowerPoint to straight away open up in Presentation mode.\n",
"As previously stated, this is more StackOverflow geared, but this can easily be achieved with Python and AutoHotkey.\nOn the Python side of things, as a general idea on how to go about this (I'm kind of rusty, beware!):\n\nFind files using os.walk()\nAppend each to a list, then iterate over the list, opening each one with os.system(\"powerpoint.exe /s filename\"). The next one should not open until the previous closes.\n\nAutoHotkey wise:\n\nOnce opened, use #IfWinActive to detect an open Powerpoint window, and send mouse clicks to change slides at a set interval\n\nI don't know what you mean by \"order\", you'll have to determine that in your Python script. If you want them alphabetical, sort the list alphabetically then iterate. If you want them sorted by creation date, then sort by date and iterate and so on.\n",
"Save the file with the extension \".pps\". That will make powerpoint open the file in presentation mode.\nThe presentaion needs to designed to advance slides, else you will have to script that part.\n",
"If you want more control over the powerpoint slide, you could write something in VB.Net (or other .Net languages) according to this MS support article.\nIf you wanted direct control from Python, you could probably use pywin32 or comtypes to invoke directly the same interfaces as described in the MS article. My guess is this is the most powerful solution and would probably provide the smoothest transitions between presentations, but is probably a lot more work than using subprocess to call into PowerPoint.\n"
] |
[
3,
1,
1,
0
] |
[] |
[] |
[
"powerpoint",
"python"
] |
stackoverflow_0001635565_powerpoint_python.txt
|
Q:
Manipulate screen buffer in python
I know this is a long shot, but I was wondering if Python had a way to manipulate the screen buffer. Specifically, I want to be able to gray-out my desktop and highlight my windows when I press a key combination. Is this in the realm of possibility?
A:
From your question and the comments that followed, PyQt would be a good choice, you would have a common code for the three platforms.
You have to develop it as a GUI though, using the library functions, it also means you will have to rethink what you exactly want in terms of GUI possibilities, and in a way that respects the usual GUI conventions: users probably don't want your application to modify their favourite desktop background or to behave weirdly.
For example, there is a way to bring your application to the foreground (the examples given in answer are in C++ but equivalent methods are available in Python and the code would be very similar).
Qt is originally a C++ framework, recently acquired by Nokia, if you are also familiar with that language you should think it over before deciding which to choose, but in any case PyQt will not let you down, it is quite mature and stable.
Regarding the license, in case it's one of your concerns, PyQt is GPL and a commercial license is also available. Another Python Qt porting is in the works with a LGPL license, pushed by Nokia following the refusal from the PyQt author to change their license: PySide, but it is still in its early development.
Finally, I have to mention that Qt isn't the only GUI framework for Python, by searching you will find other questions related to that topic on SO, with other suggestions:
https://stackoverflow.com/questions/115495/is-python-any-good-for-gui-development
https://stackoverflow.com/questions/280380/python-gui-programming
A:
Instead of "graying out" the desktop, try to overlay a gray, semi-transparent image over the entire screen and then make sure your window is on top of that. You may face a couple of minor limitations; for example, I don't know off the top of my head if it's possible to overlay the mac menubar (and I'm not sure you'd want to).
|
Manipulate screen buffer in python
|
I know this is a long shot, but I was wondering if Python had a way to manipulate the screen buffer. Specifically, I want to be able to gray-out my desktop and highlight my windows when I press a key combination. Is this in the realm of possibility?
|
[
"From your question and the comments that followed, PyQt would be a good choice, you would have a common code for the three platforms.\nYou have to develop it as a GUI though, using the library functions, it also means you will have to rethink what you exactly want in terms of GUI possibilities, and in a way that respects the usual GUI conventions: users probably don't want your application to modify their favourite desktop background or to behave weirdly.\nFor example, there is a way to bring your application to the foreground (the examples given in answer are in C++ but equivalent methods are available in Python and the code would be very similar).\nQt is originally a C++ framework, recently acquired by Nokia, if you are also familiar with that language you should think it over before deciding which to choose, but in any case PyQt will not let you down, it is quite mature and stable.\nRegarding the license, in case it's one of your concerns, PyQt is GPL and a commercial license is also available. Another Python Qt porting is in the works with a LGPL license, pushed by Nokia following the refusal from the PyQt author to change their license: PySide, but it is still in its early development.\nFinally, I have to mention that Qt isn't the only GUI framework for Python, by searching you will find other questions related to that topic on SO, with other suggestions:\n\nhttps://stackoverflow.com/questions/115495/is-python-any-good-for-gui-development\nhttps://stackoverflow.com/questions/280380/python-gui-programming\n\n",
"Instead of \"graying out\" the desktop, try to overlay a gray, semi-transparent image over the entire screen and then make sure your window is on top of that. You may face a couple of minor limitations; for example, I don't know off the top of my head if it's possible to overlay the mac menubar (and I'm not sure you'd want to).\n"
] |
[
2,
2
] |
[] |
[] |
[
"buffer",
"python",
"screen"
] |
stackoverflow_0001734575_buffer_python_screen.txt
|
Q:
What is this construct called in python: ( x, y )
What is this called in python:
[('/', MainPage)]
Is that an array .. of ... erhm one dictionary?
Is that
()
A tuple? ( or whatever they call it? )
A:
Its a list with a single tuple.
A:
Since no one has answered this bit yet:
A tuple? ( or whatever they call it? )
The word "tuple" comes from maths. In maths, we might talk about (ordered) pairs, if we're doing 2d geometry. Moving to three dimensions means we need triples. In higher dimensions, we need quadruples, quintuples, and, uh, whatever the prefix is for six, and so on. This starts to get to be a pain, and mathematicians also love generalising ("let's work in n dimensions today!"), so they started using the term "n-tuple" for an ordered list of n things (usually numbers).
After that, a bit of natural laziness is all you need to drop the "n-" and we end up with tuples.
A:
Note that this:
("is not a tuple")
A tuple is defined by the commas, except in the case of the zero-length tuple. This:
"is a tuple",
because of the comma at the end. The parentheses just enforce grouping (again, except in the case of a zero-length tuple.
A:
That's a list of tuples.
This is a list of integers: [1, 2, 3, 4, 5]
This is also a list of integers: [1]
This is a (string, integer) tuple: ("hello world", 42)
This is a list of (string, integer) tuples: [("a", 1), ("b", 2), ("c", 3)]
And so is this: [("a", 1)]
In Python, there's not much difference between lists and tuples. However, they are conceptually different. An easy way to think of it is that a list contains lots of items of the same type (homogeneous) , and a tuple contains a fixed number of items of different types (heterogeneous). An easy way to remember this is that lists can be appended to, and tuples cannot, because appending to a list makes sense and appending to a tuple doesn't.
Python doesn't enforce these distinctions -- in Python, you can append to a tuple with +, or store heterogeneous types in a list.
A:
Yes, it's a tuple.
They look like this:
()
(foo,)
(foo, bar)
(foo, bar, baz)
etc.
A:
[('/', MainPage)]
That's a list consisting of a two element tuple.
()
That's a zero element tuple.
A:
It is a list of tuple(s). You can verify that by
x=[('/', MainPage)]
print type(x) # You will find a <list> type here
print type(x[0]) # You will find a <tuple> type here
You can build a dictionary from this type of structure (may be more tuple inside the list) with this code
my_dict = dict(x) # x=[('/',MainPage)]
A:
It is a list of tuples containing one tuple.
A tuple is just like a list except that it is immutable, meaning that it can't be changed once it's created. You can't add, remove, or change elements in a tuple. If you want your tuple to be different, you have to create a new tuple with the new data. This may sound like a pain but in reality tuples have many benefits both in code safety and speed.
A:
It's a list of just one tuple. That tuple has two elements, a string and the object MainPage whatever it is.
Both lists and tuples are ordered groups of object, it doesn't matter what kind of object, they can be heterogeneous in both cases.
The main difference between lists and tuples is that tuples are immutable, just like strings.
For example we can define a list and a tuple:
>>> L = ['a', 1, 5, 'b']
>>> T = ('a', 1, 5, 'b')
we can modify elements of L simply by assigning them a new value
>>> print L
['a', 1, 5, 'b']
>>> L[1] = 'c'
>>> print L
['a', 'c', 5, 'b']
This is not true for tuples
>>> print T
('a', 1, 5, 'b')
>>> T[1] = 'c'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
This is because they are immutable.
Tuples' elements may be mutable, and you can modify them, for example:
>>> T = (3, ['a', 1, 2], 'lol')
>>> T[1]
['a', 1, 2]
>>> T[1][0] = 'b'
>>> T
(3, ['b', 1, 2], 'lol')
but the list we edited is still the same object, we didn't replaced the tuple's element.
|
What is this construct called in python: ( x, y )
|
What is this called in python:
[('/', MainPage)]
Is that an array .. of ... erhm one dictionary?
Is that
()
A tuple? ( or whatever they call it? )
|
[
"Its a list with a single tuple.\n",
"Since no one has answered this bit yet:\n\nA tuple? ( or whatever they call it? ) \n\nThe word \"tuple\" comes from maths. In maths, we might talk about (ordered) pairs, if we're doing 2d geometry. Moving to three dimensions means we need triples. In higher dimensions, we need quadruples, quintuples, and, uh, whatever the prefix is for six, and so on. This starts to get to be a pain, and mathematicians also love generalising (\"let's work in n dimensions today!\"), so they started using the term \"n-tuple\" for an ordered list of n things (usually numbers).\nAfter that, a bit of natural laziness is all you need to drop the \"n-\" and we end up with tuples.\n",
"Note that this:\n(\"is not a tuple\")\n\nA tuple is defined by the commas, except in the case of the zero-length tuple. This:\n\"is a tuple\",\n\nbecause of the comma at the end. The parentheses just enforce grouping (again, except in the case of a zero-length tuple.\n",
"That's a list of tuples.\nThis is a list of integers: [1, 2, 3, 4, 5]\nThis is also a list of integers: [1]\nThis is a (string, integer) tuple: (\"hello world\", 42)\nThis is a list of (string, integer) tuples: [(\"a\", 1), (\"b\", 2), (\"c\", 3)]\nAnd so is this: [(\"a\", 1)]\nIn Python, there's not much difference between lists and tuples. However, they are conceptually different. An easy way to think of it is that a list contains lots of items of the same type (homogeneous) , and a tuple contains a fixed number of items of different types (heterogeneous). An easy way to remember this is that lists can be appended to, and tuples cannot, because appending to a list makes sense and appending to a tuple doesn't.\nPython doesn't enforce these distinctions -- in Python, you can append to a tuple with +, or store heterogeneous types in a list.\n",
"Yes, it's a tuple.\nThey look like this:\n()\n(foo,)\n(foo, bar)\n(foo, bar, baz)\n\netc.\n",
"[('/', MainPage)]\n\nThat's a list consisting of a two element tuple.\n()\n\nThat's a zero element tuple.\n",
"It is a list of tuple(s). You can verify that by\nx=[('/', MainPage)]\nprint type(x) # You will find a <list> type here\nprint type(x[0]) # You will find a <tuple> type here\n\nYou can build a dictionary from this type of structure (may be more tuple inside the list) with this code\nmy_dict = dict(x) # x=[('/',MainPage)]\n\n",
"It is a list of tuples containing one tuple.\nA tuple is just like a list except that it is immutable, meaning that it can't be changed once it's created. You can't add, remove, or change elements in a tuple. If you want your tuple to be different, you have to create a new tuple with the new data. This may sound like a pain but in reality tuples have many benefits both in code safety and speed.\n",
"It's a list of just one tuple. That tuple has two elements, a string and the object MainPage whatever it is.\nBoth lists and tuples are ordered groups of object, it doesn't matter what kind of object, they can be heterogeneous in both cases.\nThe main difference between lists and tuples is that tuples are immutable, just like strings.\nFor example we can define a list and a tuple:\n>>> L = ['a', 1, 5, 'b']\n>>> T = ('a', 1, 5, 'b')\n\nwe can modify elements of L simply by assigning them a new value\n>>> print L\n['a', 1, 5, 'b']\n>>> L[1] = 'c'\n>>> print L\n['a', 'c', 5, 'b']\n\nThis is not true for tuples\n>>> print T\n('a', 1, 5, 'b')\n>>> T[1] = 'c'\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: 'tuple' object does not support item assignment\n\nThis is because they are immutable.\nTuples' elements may be mutable, and you can modify them, for example:\n>>> T = (3, ['a', 1, 2], 'lol')\n>>> T[1]\n['a', 1, 2]\n>>> T[1][0] = 'b'\n>>> T\n(3, ['b', 1, 2], 'lol')\n\nbut the list we edited is still the same object, we didn't replaced the tuple's element.\n"
] |
[
13,
6,
3,
2,
1,
1,
1,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001313805_python.txt
|
Q:
Set Django model field with a method
I'm trying to set title_for_url but it shows up in my database as "<property object at 0x027427E0>". What am I doing wrong?
from django.db import models
class Entry(models.Model):
def _get_title_for_url(self):
title = "%s" % self.get_title_in_url_format()
return title
AUTHOR_CHOICES = (('001', 'John Doe'),)
post_date = models.DateField()
author = models.CharField(max_length=3, choices=AUTHOR_CHOICES)
title = models.CharField(max_length=100, unique=True)
body = models.TextField()
image = models.ImageField(upload_to='image/blog')
image.blank = 'true'
title_for_url = models.CharField(max_length=100, editable=False, default=property(_get_title_for_url))
def __unicode__(self):
return self.title
def get_absolute_url(self):
return "/blog/%s/" % self.get_title_in_url_format()
def get_title_in_url_format(self):
"Returns the title as it will be displayed as a URL, stripped of special characters with spaces replaced by '-'."
import re
pattern = re.compile( '(\'|\(|\)|,)' )
titleForUrl = pattern.sub('', self.title)
pattern = re.compile( '( )' )
titleForUrl = pattern.sub('-', titleForUrl)
return titleForUrl.lower()
A:
title_for_url = models.CharField(max_length=100, editable=False, default=property(_get_title_for_url)
You couldn't do that way.. 'default' should be a value or a calable(with no args)... (property is not calable)
In your case you need to update a save method:
class Entry(models.Model):
def save(self, *args, **kwargs):
self.title_for_url = self.get_title_in_url_format()
super(Entry, self).save(*args, **kwargs)
A:
You can't use property() in a default:
.., default=property(_get_title_for_url))
The default value should be a constant. If you need to compute a missing value, use a pre_save hook.
A:
This is the final version of what worked for me:
def save(self, *args, **kwargs):
self.title = self.title.strip()
self.title_for_url = self.get_title_in_url_format()
super(Entry, self).save(*args, **kwargs)
|
Set Django model field with a method
|
I'm trying to set title_for_url but it shows up in my database as "<property object at 0x027427E0>". What am I doing wrong?
from django.db import models
class Entry(models.Model):
def _get_title_for_url(self):
title = "%s" % self.get_title_in_url_format()
return title
AUTHOR_CHOICES = (('001', 'John Doe'),)
post_date = models.DateField()
author = models.CharField(max_length=3, choices=AUTHOR_CHOICES)
title = models.CharField(max_length=100, unique=True)
body = models.TextField()
image = models.ImageField(upload_to='image/blog')
image.blank = 'true'
title_for_url = models.CharField(max_length=100, editable=False, default=property(_get_title_for_url))
def __unicode__(self):
return self.title
def get_absolute_url(self):
return "/blog/%s/" % self.get_title_in_url_format()
def get_title_in_url_format(self):
"Returns the title as it will be displayed as a URL, stripped of special characters with spaces replaced by '-'."
import re
pattern = re.compile( '(\'|\(|\)|,)' )
titleForUrl = pattern.sub('', self.title)
pattern = re.compile( '( )' )
titleForUrl = pattern.sub('-', titleForUrl)
return titleForUrl.lower()
|
[
"title_for_url = models.CharField(max_length=100, editable=False, default=property(_get_title_for_url)\n\nYou couldn't do that way.. 'default' should be a value or a calable(with no args)... (property is not calable)\nIn your case you need to update a save method:\nclass Entry(models.Model):\n def save(self, *args, **kwargs):\n self.title_for_url = self.get_title_in_url_format()\n super(Entry, self).save(*args, **kwargs)\n\n",
"You can't use property() in a default:\n.., default=property(_get_title_for_url))\n\nThe default value should be a constant. If you need to compute a missing value, use a pre_save hook.\n",
"This is the final version of what worked for me:\ndef save(self, *args, **kwargs):\n self.title = self.title.strip()\n self.title_for_url = self.get_title_in_url_format()\n super(Entry, self).save(*args, **kwargs)\n\n"
] |
[
3,
0,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001735240_django_python.txt
|
Q:
Loading a simple Qt Designer form in to Pyside
I create a simple form in Qt designer and am trying to load it in to a Qt application I'm creating with PySide but without much luck.
Here's the generated code from `pyside-uic':
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'clientEditorForm.ui'
#
# Created: Tue Nov 3 23:46:41 2009
# by: PySide uic UI code generator
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore, QtGui
class Ui_clientEditorForm(object):
def setupUi(self, clientEditorForm):
clientEditorForm.setObjectName("clientEditorForm")
clientEditorForm.resize(575, 446)
self.horizontalLayout_3 = QtGui.QHBoxLayout(clientEditorForm)
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
self.splitter = QtGui.QSplitter(clientEditorForm)
self.splitter.setOrientation(QtCore.Qt.Horizontal)
self.splitter.setObjectName("splitter")
self.layoutWidget = QtGui.QWidget(self.splitter)
self.layoutWidget.setObjectName("layoutWidget")
self.verticalLayout = QtGui.QVBoxLayout(self.layoutWidget)
self.verticalLayout.setObjectName("verticalLayout")
self.horizontalLayout_2 = QtGui.QHBoxLayout()
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.searchLabel = QtGui.QLabel(self.layoutWidget)
self.searchLabel.setObjectName("searchLabel")
self.horizontalLayout_2.addWidget(self.searchLabel)
self.searchEdit = QtGui.QLineEdit(self.layoutWidget)
self.searchEdit.setObjectName("searchEdit")
self.horizontalLayout_2.addWidget(self.searchEdit)
self.clearButton = QtGui.QPushButton(self.layoutWidget)
self.clearButton.setObjectName("clearButton")
self.horizontalLayout_2.addWidget(self.clearButton)
self.verticalLayout.addLayout(self.horizontalLayout_2)
self.clientListView = QtGui.QListView(self.layoutWidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.clientListView.sizePolicy().hasHeightForWidth())
self.clientListView.setSizePolicy(sizePolicy)
self.clientListView.setObjectName("clientListView")
self.verticalLayout.addWidget(self.clientListView)
self.frame = QtGui.QFrame(self.splitter)
self.frame.setFrameShape(QtGui.QFrame.StyledPanel)
self.frame.setFrameShadow(QtGui.QFrame.Raised)
self.frame.setObjectName("frame")
self.verticalLayout_3 = QtGui.QVBoxLayout(self.frame)
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.formLayout = QtGui.QFormLayout()
self.formLayout.setObjectName("formLayout")
self.nameEdit = QtGui.QLineEdit(self.frame)
self.nameEdit.setObjectName("nameEdit")
self.formLayout.setWidget(0, QtGui.QFormLayout.FieldRole, self.nameEdit)
self.nameLabel = QtGui.QLabel(self.frame)
self.nameLabel.setObjectName("nameLabel")
self.formLayout.setWidget(0, QtGui.QFormLayout.LabelRole, self.nameLabel)
self.profileButton = QtGui.QLabel(self.frame)
self.profileButton.setObjectName("profileButton")
self.formLayout.setWidget(1, QtGui.QFormLayout.LabelRole, self.profileButton)
self.addressLabel = QtGui.QLabel(self.frame)
self.addressLabel.setObjectName("addressLabel")
self.formLayout.setWidget(2, QtGui.QFormLayout.LabelRole, self.addressLabel)
self.locationLabel = QtGui.QLabel(self.frame)
self.locationLabel.setObjectName("locationLabel")
self.formLayout.setWidget(3, QtGui.QFormLayout.LabelRole, self.locationLabel)
self.secureLabel = QtGui.QLabel(self.frame)
self.secureLabel.setObjectName("secureLabel")
self.formLayout.setWidget(4, QtGui.QFormLayout.LabelRole, self.secureLabel)
self.UUIDLabel = QtGui.QLabel(self.frame)
self.UUIDLabel.setObjectName("UUIDLabel")
self.formLayout.setWidget(5, QtGui.QFormLayout.LabelRole, self.UUIDLabel)
self.passwordLabel = QtGui.QLabel(self.frame)
self.passwordLabel.setObjectName("passwordLabel")
self.formLayout.setWidget(6, QtGui.QFormLayout.LabelRole, self.passwordLabel)
self.profileComboBox = QtGui.QComboBox(self.frame)
self.profileComboBox.setObjectName("profileComboBox")
self.formLayout.setWidget(1, QtGui.QFormLayout.FieldRole, self.profileComboBox)
self.addressEdit = QtGui.QLineEdit(self.frame)
self.addressEdit.setObjectName("addressEdit")
self.formLayout.setWidget(2, QtGui.QFormLayout.FieldRole, self.addressEdit)
self.locationComboBox = QtGui.QComboBox(self.frame)
self.locationComboBox.setObjectName("locationComboBox")
self.formLayout.setWidget(3, QtGui.QFormLayout.FieldRole, self.locationComboBox)
self.secureComboBox = QtGui.QComboBox(self.frame)
self.secureComboBox.setObjectName("secureComboBox")
self.formLayout.setWidget(4, QtGui.QFormLayout.FieldRole, self.secureComboBox)
self.UUIDEdit = QtGui.QLineEdit(self.frame)
self.UUIDEdit.setObjectName("UUIDEdit")
self.formLayout.setWidget(5, QtGui.QFormLayout.FieldRole, self.UUIDEdit)
self.passwordEdit = QtGui.QLineEdit(self.frame)
self.passwordEdit.setObjectName("passwordEdit")
self.formLayout.setWidget(6, QtGui.QFormLayout.FieldRole, self.passwordEdit)
self.verticalLayout_3.addLayout(self.formLayout)
self.aliasesGroupBox = QtGui.QGroupBox(self.frame)
self.aliasesGroupBox.setFlat(False)
self.aliasesGroupBox.setCheckable(False)
self.aliasesGroupBox.setObjectName("aliasesGroupBox")
self.verticalLayout_2 = QtGui.QVBoxLayout(self.aliasesGroupBox)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.aliasesListView = QtGui.QListView(self.aliasesGroupBox)
self.aliasesListView.setObjectName("aliasesListView")
self.verticalLayout_2.addWidget(self.aliasesListView)
self.horizontalLayout_4 = QtGui.QHBoxLayout()
self.horizontalLayout_4.setObjectName("horizontalLayout_4")
spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_4.addItem(spacerItem)
self.addButton = QtGui.QPushButton(self.aliasesGroupBox)
self.addButton.setObjectName("addButton")
self.horizontalLayout_4.addWidget(self.addButton)
self.removeButton = QtGui.QPushButton(self.aliasesGroupBox)
self.removeButton.setObjectName("removeButton")
self.horizontalLayout_4.addWidget(self.removeButton)
self.verticalLayout_2.addLayout(self.horizontalLayout_4)
self.verticalLayout_3.addWidget(self.aliasesGroupBox)
spacerItem1 = QtGui.QSpacerItem(20, 38, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout_3.addItem(spacerItem1)
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
spacerItem2 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem2)
self.revertButton = QtGui.QPushButton(self.frame)
self.revertButton.setObjectName("revertButton")
self.horizontalLayout.addWidget(self.revertButton)
self.applyButton = QtGui.QPushButton(self.frame)
self.applyButton.setObjectName("applyButton")
self.horizontalLayout.addWidget(self.applyButton)
self.verticalLayout_3.addLayout(self.horizontalLayout)
self.horizontalLayout_3.addWidget(self.splitter)
self.searchLabel.setBuddy(self.searchEdit)
self.nameLabel.setBuddy(self.nameEdit)
self.profileButton.setBuddy(self.profileComboBox)
self.addressLabel.setBuddy(self.addressEdit)
self.locationLabel.setBuddy(self.locationComboBox)
self.secureLabel.setBuddy(self.secureComboBox)
self.UUIDLabel.setBuddy(self.UUIDEdit)
self.passwordLabel.setBuddy(self.passwordEdit)
self.retranslateUi(clientEditorForm)
QtCore.QMetaObject.connectSlotsByName(clientEditorForm)
def retranslateUi(self, clientEditorForm):
clientEditorForm.setWindowTitle(QtGui.QApplication.translate("clientEditorForm", "Form", None, QtGui.QApplication.UnicodeUTF8))
self.searchLabel.setText(QtGui.QApplication.translate("clientEditorForm", "Search", None, QtGui.QApplication.UnicodeUTF8))
self.clearButton.setText(QtGui.QApplication.translate("clientEditorForm", "Clear", None, QtGui.QApplication.UnicodeUTF8))
self.nameLabel.setText(QtGui.QApplication.translate("clientEditorForm", "Name", None, QtGui.QApplication.UnicodeUTF8))
self.profileButton.setText(QtGui.QApplication.translate("clientEditorForm", "Profile", None, QtGui.QApplication.UnicodeUTF8))
self.addressLabel.setText(QtGui.QApplication.translate("clientEditorForm", "Address", None, QtGui.QApplication.UnicodeUTF8))
self.locationLabel.setText(QtGui.QApplication.translate("clientEditorForm", "Location", None, QtGui.QApplication.UnicodeUTF8))
self.secureLabel.setText(QtGui.QApplication.translate("clientEditorForm", "Secure", None, QtGui.QApplication.UnicodeUTF8))
self.UUIDLabel.setText(QtGui.QApplication.translate("clientEditorForm", "UUID", None, QtGui.QApplication.UnicodeUTF8))
self.passwordLabel.setText(QtGui.QApplication.translate("clientEditorForm", "Password", None, QtGui.QApplication.UnicodeUTF8))
self.aliasesGroupBox.setTitle(QtGui.QApplication.translate("clientEditorForm", "Aliases", None, QtGui.QApplication.UnicodeUTF8))
self.addButton.setText(QtGui.QApplication.translate("clientEditorForm", "Add", None, QtGui.QApplication.UnicodeUTF8))
self.removeButton.setText(QtGui.QApplication.translate("clientEditorForm", "Remove", None, QtGui.QApplication.UnicodeUTF8))
self.revertButton.setText(QtGui.QApplication.translate("clientEditorForm", "Revert", None, QtGui.QApplication.UnicodeUTF8))
self.applyButton.setText(QtGui.QApplication.translate("clientEditorForm", "Apply", None, QtGui.QApplication.UnicodeUTF8))
Then my simple application:
import sys
from PySide import QtCore, QtGui
from clientEditorForm import Ui_clientEditorForm
class MyMainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MyMainWindow, self).__init__(parent)
self.ui = Ui_clientEditorForm()
self.ui.setupUi(self)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = MyMainWindow()
myapp.show()
sys.exit(app.exec_())
However, when I try to run it, I get the following:
QLayout: Attempting to add QLayout "" to QMainWindow "clientEditorForm", which already has a layout
and a segmentation fault. I'm following the basic instructions in this tutorial but I can't tell what I'm doing wrong.
A:
Turns out there is a bug in PySide with the QSpacerItem class. Commenting out the QSpacerItem instances in the code above makes it work just fine. There's a bug report on the PySide bugzilla.
A:
Firstly you are using PySide(Nokia) not PyQt4(Riverbank Computing), although their API's are nearly identical they are not the same project. The PySide examples are available here:
git clone git://gitorious.org/pyside/pyside-examples.git
I think the problem may have to do with your call of
super(MyMainWindow, self).__init__(parent)
try
QtGui.QMainWindow.__init__(self, parent)
instead.
I know it seems like it is the same thing, but I've ran into similar problems with super using PyQt4, and from what I can tell Nokia's PySide has the same troubles. It has something to do with weather the Python owns the parent or it's owned by an underlying C++ object. At least give it a try, it'll take less than 5 seconds!
Below is the example I'm basing this off of, it's from the git repo for PySide.
#!/usr/bin/env python
#############################################################################
##
## Copyright (C) 2004-2005 Trolltech AS. All rights reserved.
##
## This file is part of the example classes of the Qt Toolkit.
##
## This file may be used under the terms of the GNU General Public
## License version 2.0 as published by the Free Software Foundation
## and appearing in the file LICENSE.GPL included in the packaging of
## this file. Please review the following information to ensure GNU
## General Public Licensing requirements will be met:
## http://www.trolltech.com/products/qt/opensource.html
##
## If you are unsure which license is appropriate for your use, please
## review the following information:
## http://www.trolltech.com/products/qt/licensing.html or contact the
## sales department at sales@trolltech.com.
##
## This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
## WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
##
#############################################################################
import sys
from PySide import QtCore, QtGui
from ui_calculatorform import Ui_CalculatorForm
class CalculatorForm(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_CalculatorForm()
self.ui.setupUi(self)
@QtCore.pyqtSignature("int")
def on_inputSpinBox1_valueChanged(self, value):
self.ui.outputWidget.setText(QtCore.QString.number(value + self.ui.inputSpinBox2.value()))
@QtCore.pyqtSignature("int")
def on_inputSpinBox2_valueChanged(self, value):
self.ui.outputWidget.setText(QtCore.QString.number(value + self.ui.inputSpinBox1.value()))
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
calculator = CalculatorForm()
calculator.show()
sys.exit(app.exec_())
|
Loading a simple Qt Designer form in to Pyside
|
I create a simple form in Qt designer and am trying to load it in to a Qt application I'm creating with PySide but without much luck.
Here's the generated code from `pyside-uic':
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'clientEditorForm.ui'
#
# Created: Tue Nov 3 23:46:41 2009
# by: PySide uic UI code generator
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore, QtGui
class Ui_clientEditorForm(object):
def setupUi(self, clientEditorForm):
clientEditorForm.setObjectName("clientEditorForm")
clientEditorForm.resize(575, 446)
self.horizontalLayout_3 = QtGui.QHBoxLayout(clientEditorForm)
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
self.splitter = QtGui.QSplitter(clientEditorForm)
self.splitter.setOrientation(QtCore.Qt.Horizontal)
self.splitter.setObjectName("splitter")
self.layoutWidget = QtGui.QWidget(self.splitter)
self.layoutWidget.setObjectName("layoutWidget")
self.verticalLayout = QtGui.QVBoxLayout(self.layoutWidget)
self.verticalLayout.setObjectName("verticalLayout")
self.horizontalLayout_2 = QtGui.QHBoxLayout()
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.searchLabel = QtGui.QLabel(self.layoutWidget)
self.searchLabel.setObjectName("searchLabel")
self.horizontalLayout_2.addWidget(self.searchLabel)
self.searchEdit = QtGui.QLineEdit(self.layoutWidget)
self.searchEdit.setObjectName("searchEdit")
self.horizontalLayout_2.addWidget(self.searchEdit)
self.clearButton = QtGui.QPushButton(self.layoutWidget)
self.clearButton.setObjectName("clearButton")
self.horizontalLayout_2.addWidget(self.clearButton)
self.verticalLayout.addLayout(self.horizontalLayout_2)
self.clientListView = QtGui.QListView(self.layoutWidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.clientListView.sizePolicy().hasHeightForWidth())
self.clientListView.setSizePolicy(sizePolicy)
self.clientListView.setObjectName("clientListView")
self.verticalLayout.addWidget(self.clientListView)
self.frame = QtGui.QFrame(self.splitter)
self.frame.setFrameShape(QtGui.QFrame.StyledPanel)
self.frame.setFrameShadow(QtGui.QFrame.Raised)
self.frame.setObjectName("frame")
self.verticalLayout_3 = QtGui.QVBoxLayout(self.frame)
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.formLayout = QtGui.QFormLayout()
self.formLayout.setObjectName("formLayout")
self.nameEdit = QtGui.QLineEdit(self.frame)
self.nameEdit.setObjectName("nameEdit")
self.formLayout.setWidget(0, QtGui.QFormLayout.FieldRole, self.nameEdit)
self.nameLabel = QtGui.QLabel(self.frame)
self.nameLabel.setObjectName("nameLabel")
self.formLayout.setWidget(0, QtGui.QFormLayout.LabelRole, self.nameLabel)
self.profileButton = QtGui.QLabel(self.frame)
self.profileButton.setObjectName("profileButton")
self.formLayout.setWidget(1, QtGui.QFormLayout.LabelRole, self.profileButton)
self.addressLabel = QtGui.QLabel(self.frame)
self.addressLabel.setObjectName("addressLabel")
self.formLayout.setWidget(2, QtGui.QFormLayout.LabelRole, self.addressLabel)
self.locationLabel = QtGui.QLabel(self.frame)
self.locationLabel.setObjectName("locationLabel")
self.formLayout.setWidget(3, QtGui.QFormLayout.LabelRole, self.locationLabel)
self.secureLabel = QtGui.QLabel(self.frame)
self.secureLabel.setObjectName("secureLabel")
self.formLayout.setWidget(4, QtGui.QFormLayout.LabelRole, self.secureLabel)
self.UUIDLabel = QtGui.QLabel(self.frame)
self.UUIDLabel.setObjectName("UUIDLabel")
self.formLayout.setWidget(5, QtGui.QFormLayout.LabelRole, self.UUIDLabel)
self.passwordLabel = QtGui.QLabel(self.frame)
self.passwordLabel.setObjectName("passwordLabel")
self.formLayout.setWidget(6, QtGui.QFormLayout.LabelRole, self.passwordLabel)
self.profileComboBox = QtGui.QComboBox(self.frame)
self.profileComboBox.setObjectName("profileComboBox")
self.formLayout.setWidget(1, QtGui.QFormLayout.FieldRole, self.profileComboBox)
self.addressEdit = QtGui.QLineEdit(self.frame)
self.addressEdit.setObjectName("addressEdit")
self.formLayout.setWidget(2, QtGui.QFormLayout.FieldRole, self.addressEdit)
self.locationComboBox = QtGui.QComboBox(self.frame)
self.locationComboBox.setObjectName("locationComboBox")
self.formLayout.setWidget(3, QtGui.QFormLayout.FieldRole, self.locationComboBox)
self.secureComboBox = QtGui.QComboBox(self.frame)
self.secureComboBox.setObjectName("secureComboBox")
self.formLayout.setWidget(4, QtGui.QFormLayout.FieldRole, self.secureComboBox)
self.UUIDEdit = QtGui.QLineEdit(self.frame)
self.UUIDEdit.setObjectName("UUIDEdit")
self.formLayout.setWidget(5, QtGui.QFormLayout.FieldRole, self.UUIDEdit)
self.passwordEdit = QtGui.QLineEdit(self.frame)
self.passwordEdit.setObjectName("passwordEdit")
self.formLayout.setWidget(6, QtGui.QFormLayout.FieldRole, self.passwordEdit)
self.verticalLayout_3.addLayout(self.formLayout)
self.aliasesGroupBox = QtGui.QGroupBox(self.frame)
self.aliasesGroupBox.setFlat(False)
self.aliasesGroupBox.setCheckable(False)
self.aliasesGroupBox.setObjectName("aliasesGroupBox")
self.verticalLayout_2 = QtGui.QVBoxLayout(self.aliasesGroupBox)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.aliasesListView = QtGui.QListView(self.aliasesGroupBox)
self.aliasesListView.setObjectName("aliasesListView")
self.verticalLayout_2.addWidget(self.aliasesListView)
self.horizontalLayout_4 = QtGui.QHBoxLayout()
self.horizontalLayout_4.setObjectName("horizontalLayout_4")
spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_4.addItem(spacerItem)
self.addButton = QtGui.QPushButton(self.aliasesGroupBox)
self.addButton.setObjectName("addButton")
self.horizontalLayout_4.addWidget(self.addButton)
self.removeButton = QtGui.QPushButton(self.aliasesGroupBox)
self.removeButton.setObjectName("removeButton")
self.horizontalLayout_4.addWidget(self.removeButton)
self.verticalLayout_2.addLayout(self.horizontalLayout_4)
self.verticalLayout_3.addWidget(self.aliasesGroupBox)
spacerItem1 = QtGui.QSpacerItem(20, 38, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout_3.addItem(spacerItem1)
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
spacerItem2 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem2)
self.revertButton = QtGui.QPushButton(self.frame)
self.revertButton.setObjectName("revertButton")
self.horizontalLayout.addWidget(self.revertButton)
self.applyButton = QtGui.QPushButton(self.frame)
self.applyButton.setObjectName("applyButton")
self.horizontalLayout.addWidget(self.applyButton)
self.verticalLayout_3.addLayout(self.horizontalLayout)
self.horizontalLayout_3.addWidget(self.splitter)
self.searchLabel.setBuddy(self.searchEdit)
self.nameLabel.setBuddy(self.nameEdit)
self.profileButton.setBuddy(self.profileComboBox)
self.addressLabel.setBuddy(self.addressEdit)
self.locationLabel.setBuddy(self.locationComboBox)
self.secureLabel.setBuddy(self.secureComboBox)
self.UUIDLabel.setBuddy(self.UUIDEdit)
self.passwordLabel.setBuddy(self.passwordEdit)
self.retranslateUi(clientEditorForm)
QtCore.QMetaObject.connectSlotsByName(clientEditorForm)
def retranslateUi(self, clientEditorForm):
clientEditorForm.setWindowTitle(QtGui.QApplication.translate("clientEditorForm", "Form", None, QtGui.QApplication.UnicodeUTF8))
self.searchLabel.setText(QtGui.QApplication.translate("clientEditorForm", "Search", None, QtGui.QApplication.UnicodeUTF8))
self.clearButton.setText(QtGui.QApplication.translate("clientEditorForm", "Clear", None, QtGui.QApplication.UnicodeUTF8))
self.nameLabel.setText(QtGui.QApplication.translate("clientEditorForm", "Name", None, QtGui.QApplication.UnicodeUTF8))
self.profileButton.setText(QtGui.QApplication.translate("clientEditorForm", "Profile", None, QtGui.QApplication.UnicodeUTF8))
self.addressLabel.setText(QtGui.QApplication.translate("clientEditorForm", "Address", None, QtGui.QApplication.UnicodeUTF8))
self.locationLabel.setText(QtGui.QApplication.translate("clientEditorForm", "Location", None, QtGui.QApplication.UnicodeUTF8))
self.secureLabel.setText(QtGui.QApplication.translate("clientEditorForm", "Secure", None, QtGui.QApplication.UnicodeUTF8))
self.UUIDLabel.setText(QtGui.QApplication.translate("clientEditorForm", "UUID", None, QtGui.QApplication.UnicodeUTF8))
self.passwordLabel.setText(QtGui.QApplication.translate("clientEditorForm", "Password", None, QtGui.QApplication.UnicodeUTF8))
self.aliasesGroupBox.setTitle(QtGui.QApplication.translate("clientEditorForm", "Aliases", None, QtGui.QApplication.UnicodeUTF8))
self.addButton.setText(QtGui.QApplication.translate("clientEditorForm", "Add", None, QtGui.QApplication.UnicodeUTF8))
self.removeButton.setText(QtGui.QApplication.translate("clientEditorForm", "Remove", None, QtGui.QApplication.UnicodeUTF8))
self.revertButton.setText(QtGui.QApplication.translate("clientEditorForm", "Revert", None, QtGui.QApplication.UnicodeUTF8))
self.applyButton.setText(QtGui.QApplication.translate("clientEditorForm", "Apply", None, QtGui.QApplication.UnicodeUTF8))
Then my simple application:
import sys
from PySide import QtCore, QtGui
from clientEditorForm import Ui_clientEditorForm
class MyMainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MyMainWindow, self).__init__(parent)
self.ui = Ui_clientEditorForm()
self.ui.setupUi(self)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = MyMainWindow()
myapp.show()
sys.exit(app.exec_())
However, when I try to run it, I get the following:
QLayout: Attempting to add QLayout "" to QMainWindow "clientEditorForm", which already has a layout
and a segmentation fault. I'm following the basic instructions in this tutorial but I can't tell what I'm doing wrong.
|
[
"Turns out there is a bug in PySide with the QSpacerItem class. Commenting out the QSpacerItem instances in the code above makes it work just fine. There's a bug report on the PySide bugzilla.\n",
"Firstly you are using PySide(Nokia) not PyQt4(Riverbank Computing), although their API's are nearly identical they are not the same project. The PySide examples are available here:\ngit clone git://gitorious.org/pyside/pyside-examples.git\nI think the problem may have to do with your call of \nsuper(MyMainWindow, self).__init__(parent)\n\ntry\nQtGui.QMainWindow.__init__(self, parent)\n\ninstead.\nI know it seems like it is the same thing, but I've ran into similar problems with super using PyQt4, and from what I can tell Nokia's PySide has the same troubles. It has something to do with weather the Python owns the parent or it's owned by an underlying C++ object. At least give it a try, it'll take less than 5 seconds!\nBelow is the example I'm basing this off of, it's from the git repo for PySide.\n#!/usr/bin/env python\n\n#############################################################################\n##\n## Copyright (C) 2004-2005 Trolltech AS. All rights reserved.\n##\n## This file is part of the example classes of the Qt Toolkit.\n##\n## This file may be used under the terms of the GNU General Public\n## License version 2.0 as published by the Free Software Foundation\n## and appearing in the file LICENSE.GPL included in the packaging of\n## this file. Please review the following information to ensure GNU\n## General Public Licensing requirements will be met:\n## http://www.trolltech.com/products/qt/opensource.html\n##\n## If you are unsure which license is appropriate for your use, please\n## review the following information:\n## http://www.trolltech.com/products/qt/licensing.html or contact the\n## sales department at sales@trolltech.com.\n##\n## This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE\n## WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n##\n#############################################################################\n\nimport sys\nfrom PySide import QtCore, QtGui\n\nfrom ui_calculatorform import Ui_CalculatorForm\n\n\nclass CalculatorForm(QtGui.QWidget):\n def __init__(self, parent=None):\n QtGui.QWidget.__init__(self, parent)\n\n self.ui = Ui_CalculatorForm()\n\n self.ui.setupUi(self)\n\n @QtCore.pyqtSignature(\"int\")\n def on_inputSpinBox1_valueChanged(self, value):\n self.ui.outputWidget.setText(QtCore.QString.number(value + self.ui.inputSpinBox2.value()))\n\n @QtCore.pyqtSignature(\"int\")\n def on_inputSpinBox2_valueChanged(self, value):\n self.ui.outputWidget.setText(QtCore.QString.number(value + self.ui.inputSpinBox1.value()))\n\n\nif __name__ == \"__main__\":\n app = QtGui.QApplication(sys.argv)\n calculator = CalculatorForm()\n calculator.show()\n sys.exit(app.exec_())\n\n"
] |
[
5,
4
] |
[] |
[] |
[
"pyside",
"python",
"qt4"
] |
stackoverflow_0001672271_pyside_python_qt4.txt
|
Q:
Boost::Python Windows 7 64 Bit
I can't seem to build boost::python correctly on my Windows 7 64Bit machine. It's vanilla 32bit python 2.6.4 in the c:\Python26 directory.
Pastebin is here of the debug build output : http://pastebin.com/m7d70f13e
Cheers,
Al
A:
On IRC, we have found the following procedure fixes the problem:
Open tools/build/v2/tools/python.jam
There, locate the following code:
if [ version.check-jam-version 3 1 17 ] || ( [ os.name ] != NT )
{
# Prior to version 3.1.17 Boost Jam's SHELL command did not support
# quoted commands correctly on Windows. This means that on that
# platform we do not support using a Python command interpreter
# executable whose path contains a space character.
python-cmd = \"$(python-cmd)\" ;
}
Remove that code block completely.
I'll create an issue in Boost issue tracker and investigate this.
|
Boost::Python Windows 7 64 Bit
|
I can't seem to build boost::python correctly on my Windows 7 64Bit machine. It's vanilla 32bit python 2.6.4 in the c:\Python26 directory.
Pastebin is here of the debug build output : http://pastebin.com/m7d70f13e
Cheers,
Al
|
[
"On IRC, we have found the following procedure fixes the problem:\n\nOpen tools/build/v2/tools/python.jam\nThere, locate the following code:\nif [ version.check-jam-version 3 1 17 ] || ( [ os.name ] != NT )\n{\n # Prior to version 3.1.17 Boost Jam's SHELL command did not support\n # quoted commands correctly on Windows. This means that on that\n # platform we do not support using a Python command interpreter\n # executable whose path contains a space character.\n python-cmd = \\\"$(python-cmd)\\\" ;\n}\n\nRemove that code block completely.\n\nI'll create an issue in Boost issue tracker and investigate this.\n"
] |
[
6
] |
[] |
[] |
[
"64_bit",
"boost",
"python",
"windows_7"
] |
stackoverflow_0001704046_64_bit_boost_python_windows_7.txt
|
Q:
How should I create a web interface for my application?
First, a little background: I have written a little application in python with SQLAlchemy, which is roughly an improved RSS reader: it selects links that should interest the user, and shows them to him. I already have a very simple command-line interface, and I envision a variety of interfaces: web, instant-messaging, desktop...
For now I'd like to create a simple web interface, but I have absolutely zero experience in the matter (appart from making a simple php forum 5 or 6 years ago...). So I'm comming here for advice on where to start:
Is there a good tutorial on HTML/CSS/Javascript focused on making a website look good simply? I know about w3schools, but it's a terrible tutorial IMHO, since it teaches you about HTML/CSS but doesn't show you how to use them.
Should I use a javascript library? Which one?
Should I use a web framework? I'm guessing either not or a very lightweight one, since I already have an application core with a database and SQLAlchemy, and I don't want to drop it.
Any other advice?
Thanks!
A:
I recommend that you use some kind of web framework, it will make things a lot easier. Since you already know Python you should look into Django framework. It seems that you can use SQLAlchemy with Django, see djange-sqlalchemy project.
I recommend using JQuery framework/library for Javascript stuff. It greatly simplifies coding and takes care of most web browser incompabilities.
This CSS tutorial seems to give you the basics.
I would start by reading the Django tutorial and start trying things out. I wouldn't worry too much about HTML stuff, you should be able to pick up enough from Django tutorial. Make your site first functional with HTML, Django and SQLAlchemy. Only then start worring about Javascript. Who knows, maybe you do not need Javascript at all?
Do not try make your site work and look good at the same time. When you are making your site work, use simple and ugly HTML pages. When you are making you web site look good, work only with static HTML pages and CSS files. It is easier to combine the two in the end.
A:
Just like everyone else here, I'll chime in with "Use my favorite framework, because it's what I use...."
I would start with small goals for a web interface. Get something simple up and running that to make sure you understand how things work.
Write an app that responds to the following url and returns something.
http://localhost:8000/my_links
Once you understand the little bit of machinery it takes to make that possible, what is handed to you as far as information about the request, and what you need to produce to return to the caller, it should be come clear how to fill in the blanks to get from your existing application to data thrown at the web browser.
Learn WSGI for no other reason than most of the libraries that will help you build a web application utilize this to some degree.
One of the links from the above page that I found extremely beneficial in understanding how all this works. was Ian Bickings article "A Do-it Yourself Framework"
Once you get a grasp of that stuff, you may find that dealing with WSGI at such a low level is maybe a little too cumbersome. That's when you'll probably want something like WebOb
which is just one of several ways people have come up with for abstracting away the low level details of the request/response cycle into some convenient objects. In a sense encompassing the HTTP protocol without trying to make it make sense to someone who doesn't want to know what HTTP is.
Depending on the complexity of your application you may decide that handling a request, looking at the path and dispatching off to one of many functions is a drag you'd rather not deal with. This is where everyone's favorite framework starts to be beneficial. And I would suspect that you would know enough by this point to better assess the frameworks that are out there and determine which fits your needs and goals.
Lots prefer django, maybe you will too. Others prefer Turbogears, and or Pylons, maybe bfg, maybe grok, maybe zope, maybe plone. But no one here knows what you want your application to do.
A:
It's an interestingly common mistake: all of the above answers provide technological advise on what's the best technology to do ... what exactly? You should work the other way around.
I think that if you want your application to be successful, you have to make sure it enables its users to get the most out of it in the most natural way to them.
Therefore, i suggest you first "storyline" how things should happen from a user's perspective. Use paper and pen, or more sophisticated wireframing tools such as balsamiq mockups.
So, first lay out what the experience should be, and this will tell you which technology will be the best choice to enable that experience.
Oh, and don't forget to read this.
A:
HTML, CSS and JS Book: DHTML and CSS for the World Wide Web
Javascript Library: JQuery
Web Framework: Not sure, DJango?
Other Advice: Learn to write HTML, CSS, and JS in a a simple text editor with syntax highlighting. Complex IDE's are cool, but for this stuff, they will make you learn slower.
A:
Web applications are not simple.
HTML and CSS: Head First HTML is probably a good starting point. The Head First series are usually excellent tutorials. As Josh said, write your pages by hand.
Javascript: you don't need this to get started. Maybe in a later version. When you have a better idea what you'll need Javascript for, you'll be better equipped to pick a library that suits your needs.
Web framework: You should probably start with Django. That's the opposite of a "very lightweight" framework, but in this context "lightweight" requires more expertise to make something polished. So it's a good idea to aim for "feature rich and well supported" instead.
A:
Here is another option, I feel it's worth mentioning before making any decision.
As web framework I would advise web2py, it is very easy to setup and yet powerful. Here is a document showing the differences between Django, web2py and some others. It is somewhat old but will give you a good overview.
Since you have legacy code, if you really want to keep it there is a fair compatibility between the two although you should double-check. The easiest would be to adapt your code, of course, the differences aren't so big. But that's your call :-)
Regarding the Javascript library, probably jQuery.
A:
The best introduction you could follow is the opera web standards curriculum. Some of the information will be too basic - but a full understanding of all the topics covered will give you a very good grounding.
http://www.opera.com/company/education/curriculum/
Alternatively team up with someone who specialises in front-end development.
|
How should I create a web interface for my application?
|
First, a little background: I have written a little application in python with SQLAlchemy, which is roughly an improved RSS reader: it selects links that should interest the user, and shows them to him. I already have a very simple command-line interface, and I envision a variety of interfaces: web, instant-messaging, desktop...
For now I'd like to create a simple web interface, but I have absolutely zero experience in the matter (appart from making a simple php forum 5 or 6 years ago...). So I'm comming here for advice on where to start:
Is there a good tutorial on HTML/CSS/Javascript focused on making a website look good simply? I know about w3schools, but it's a terrible tutorial IMHO, since it teaches you about HTML/CSS but doesn't show you how to use them.
Should I use a javascript library? Which one?
Should I use a web framework? I'm guessing either not or a very lightweight one, since I already have an application core with a database and SQLAlchemy, and I don't want to drop it.
Any other advice?
Thanks!
|
[
"I recommend that you use some kind of web framework, it will make things a lot easier. Since you already know Python you should look into Django framework. It seems that you can use SQLAlchemy with Django, see djange-sqlalchemy project.\nI recommend using JQuery framework/library for Javascript stuff. It greatly simplifies coding and takes care of most web browser incompabilities.\nThis CSS tutorial seems to give you the basics.\nI would start by reading the Django tutorial and start trying things out. I wouldn't worry too much about HTML stuff, you should be able to pick up enough from Django tutorial. Make your site first functional with HTML, Django and SQLAlchemy. Only then start worring about Javascript. Who knows, maybe you do not need Javascript at all?\nDo not try make your site work and look good at the same time. When you are making your site work, use simple and ugly HTML pages. When you are making you web site look good, work only with static HTML pages and CSS files. It is easier to combine the two in the end.\n",
"Just like everyone else here, I'll chime in with \"Use my favorite framework, because it's what I use....\" \nI would start with small goals for a web interface. Get something simple up and running that to make sure you understand how things work. \nWrite an app that responds to the following url and returns something.\nhttp://localhost:8000/my_links\nOnce you understand the little bit of machinery it takes to make that possible, what is handed to you as far as information about the request, and what you need to produce to return to the caller, it should be come clear how to fill in the blanks to get from your existing application to data thrown at the web browser. \nLearn WSGI for no other reason than most of the libraries that will help you build a web application utilize this to some degree. \nOne of the links from the above page that I found extremely beneficial in understanding how all this works. was Ian Bickings article \"A Do-it Yourself Framework\" \nOnce you get a grasp of that stuff, you may find that dealing with WSGI at such a low level is maybe a little too cumbersome. That's when you'll probably want something like WebOb\n which is just one of several ways people have come up with for abstracting away the low level details of the request/response cycle into some convenient objects. In a sense encompassing the HTTP protocol without trying to make it make sense to someone who doesn't want to know what HTTP is. \nDepending on the complexity of your application you may decide that handling a request, looking at the path and dispatching off to one of many functions is a drag you'd rather not deal with. This is where everyone's favorite framework starts to be beneficial. And I would suspect that you would know enough by this point to better assess the frameworks that are out there and determine which fits your needs and goals. \nLots prefer django, maybe you will too. Others prefer Turbogears, and or Pylons, maybe bfg, maybe grok, maybe zope, maybe plone. But no one here knows what you want your application to do. \n",
"It's an interestingly common mistake: all of the above answers provide technological advise on what's the best technology to do ... what exactly? You should work the other way around. \nI think that if you want your application to be successful, you have to make sure it enables its users to get the most out of it in the most natural way to them. \nTherefore, i suggest you first \"storyline\" how things should happen from a user's perspective. Use paper and pen, or more sophisticated wireframing tools such as balsamiq mockups.\nSo, first lay out what the experience should be, and this will tell you which technology will be the best choice to enable that experience.\nOh, and don't forget to read this.\n",
"HTML, CSS and JS Book: DHTML and CSS for the World Wide Web \nJavascript Library: JQuery\nWeb Framework: Not sure, DJango?\nOther Advice: Learn to write HTML, CSS, and JS in a a simple text editor with syntax highlighting. Complex IDE's are cool, but for this stuff, they will make you learn slower.\n",
"Web applications are not simple.\nHTML and CSS: Head First HTML is probably a good starting point. The Head First series are usually excellent tutorials. As Josh said, write your pages by hand.\nJavascript: you don't need this to get started. Maybe in a later version. When you have a better idea what you'll need Javascript for, you'll be better equipped to pick a library that suits your needs.\nWeb framework: You should probably start with Django. That's the opposite of a \"very lightweight\" framework, but in this context \"lightweight\" requires more expertise to make something polished. So it's a good idea to aim for \"feature rich and well supported\" instead.\n",
"Here is another option, I feel it's worth mentioning before making any decision.\nAs web framework I would advise web2py, it is very easy to setup and yet powerful. Here is a document showing the differences between Django, web2py and some others. It is somewhat old but will give you a good overview.\nSince you have legacy code, if you really want to keep it there is a fair compatibility between the two although you should double-check. The easiest would be to adapt your code, of course, the differences aren't so big. But that's your call :-)\nRegarding the Javascript library, probably jQuery.\n",
"The best introduction you could follow is the opera web standards curriculum. Some of the information will be too basic - but a full understanding of all the topics covered will give you a very good grounding.\nhttp://www.opera.com/company/education/curriculum/\nAlternatively team up with someone who specialises in front-end development.\n"
] |
[
6,
5,
3,
1,
1,
1,
1
] |
[] |
[] |
[
"css",
"javascript",
"python"
] |
stackoverflow_0001737514_css_javascript_python.txt
|
Q:
Dict has key from list
How can I determine if any of the list elements are a key to a dict?
The straight forward way is,
for i in myList:
if i in myDict:
return True
return False
but is there a faster / more concise way?
A:
#!python
any(x in MyDict for x in MyList)
set(MyList).intersection(MyDict)
A:
In addition to any(item in my_dict for item in my_list) from @Ronny's answer:
any(map(my_dict.__contains__, my_list)) # Python 3.x
Or:
from itertools import imap
any(imap(my_dict.__contains__, my_list)) # Python 2.x
Measure relative performance
Cases to consider:
Item from the start of list is in in dictionary.
Item from the end of list is in dictionary.
No items from the list are in dictionary.
Functions to compare (see main.py):
def mgag_loop(myDict, myList):
for i in myList:
if i in myDict:
return True
return False
def ronny_any(myDict, myList):
return any(x in myDict for x in myList)
def ronny_set(myDict, myList):
return set(myDict) & set(myList)
def pablo_len(myDict, myList):
return len([x for x in myList if x in myDict]) > 0
def jfs_map(my_dict, my_list):
return any(map(my_dict.__contains__, my_list))
def jfs_imap(my_dict, my_list):
return any(imap(my_dict.__contains__, my_list))
Results: mgag_loop() is the fastest in all cases.
1. Item from the start of list is in in dictionary.
def args_key_at_start(n):
'Make args for comparison functions "key at start" case.'
d, lst = args_no_key(n)
lst.insert(0, n//2)
assert (n//2) in d and lst[0] == (n//2)
return (d, lst)
2. Item from the end of list is in dictionary.
def args_key_at_end(n):
'Make args for comparison functions "key at end" case.'
d, lst = args_no_key(n)
lst.append(n//2)
assert (n//2) in d and lst[-1] == (n//2)
return (d, lst)
3. No items from the list are in dictionary.
def args_no_key(n):
'Make args for comparison functions "no key" case.'
d = dict.fromkeys(xrange(n))
lst = range(n, 2*n+1)
assert not any(x in d for x in lst)
return (d, lst)
How to reproduce
Download main.py, make-figures.py, run python main.py (numpy, matplotlib should be installed to create plots).
To change maximum size of input list, number of points to plot supply --maxn, --npoints correspondingly. Example:
$ python main.py --maxn 65536 --npoints 16
A:
Assuming you are talking about python, an alternate method of doing this would be:
return len([x for x in myList if x in myDict]) > 0
A:
This was a popular answer to a related question:
>>> if all (k in foo for k in ("foo","bar")):
... print "They're there!"
...
They're there!
You can adapt it to check if any appears in the dictionary:
>>> if any(k in myDict for k in ("foo","bar")):
... print "Found one!"
...
Found one!
You can check against a list of keys:
>>> if any(k in myDict for k in myList):
... print "Found one!"
...
Found one!
A:
Thank you all so much. I tested the performance of all the answers and the fastest was
return len([x for x in myList if x in myDict]) > 0
but I didn't try the "set" answer because I didn't see how to turn it into one line.
|
Dict has key from list
|
How can I determine if any of the list elements are a key to a dict?
The straight forward way is,
for i in myList:
if i in myDict:
return True
return False
but is there a faster / more concise way?
|
[
"#!python\nany(x in MyDict for x in MyList)\nset(MyList).intersection(MyDict)\n\n",
"In addition to any(item in my_dict for item in my_list) from @Ronny's answer:\nany(map(my_dict.__contains__, my_list)) # Python 3.x\n\nOr:\nfrom itertools import imap\nany(imap(my_dict.__contains__, my_list)) # Python 2.x\n\nMeasure relative performance\nCases to consider:\n\nItem from the start of list is in in dictionary.\nItem from the end of list is in dictionary.\nNo items from the list are in dictionary.\n\nFunctions to compare (see main.py):\ndef mgag_loop(myDict, myList):\n for i in myList:\n if i in myDict:\n return True\n return False\n\ndef ronny_any(myDict, myList):\n return any(x in myDict for x in myList)\n\ndef ronny_set(myDict, myList):\n return set(myDict) & set(myList)\n\ndef pablo_len(myDict, myList):\n return len([x for x in myList if x in myDict]) > 0\n\ndef jfs_map(my_dict, my_list):\n return any(map(my_dict.__contains__, my_list))\n\ndef jfs_imap(my_dict, my_list):\n return any(imap(my_dict.__contains__, my_list))\n\nResults: mgag_loop() is the fastest in all cases.\n1. Item from the start of list is in in dictionary.\ndef args_key_at_start(n):\n 'Make args for comparison functions \"key at start\" case.'\n d, lst = args_no_key(n)\n lst.insert(0, n//2)\n assert (n//2) in d and lst[0] == (n//2)\n return (d, lst)\n\n\n2. Item from the end of list is in dictionary.\ndef args_key_at_end(n):\n 'Make args for comparison functions \"key at end\" case.'\n d, lst = args_no_key(n)\n lst.append(n//2)\n assert (n//2) in d and lst[-1] == (n//2)\n return (d, lst)\n\n\n3. No items from the list are in dictionary.\ndef args_no_key(n):\n 'Make args for comparison functions \"no key\" case.'\n d = dict.fromkeys(xrange(n))\n lst = range(n, 2*n+1)\n assert not any(x in d for x in lst)\n return (d, lst)\n\n\nHow to reproduce\nDownload main.py, make-figures.py, run python main.py (numpy, matplotlib should be installed to create plots).\nTo change maximum size of input list, number of points to plot supply --maxn, --npoints correspondingly. Example:\n$ python main.py --maxn 65536 --npoints 16\n\n",
"Assuming you are talking about python, an alternate method of doing this would be:\nreturn len([x for x in myList if x in myDict]) > 0\n\n",
"This was a popular answer to a related question:\n>>> if all (k in foo for k in (\"foo\",\"bar\")):\n... print \"They're there!\"\n...\nThey're there!\n\nYou can adapt it to check if any appears in the dictionary:\n>>> if any(k in myDict for k in (\"foo\",\"bar\")):\n... print \"Found one!\"\n...\nFound one!\n\nYou can check against a list of keys:\n>>> if any(k in myDict for k in myList):\n... print \"Found one!\"\n...\nFound one!\n\n",
"Thank you all so much. I tested the performance of all the answers and the fastest was \nreturn len([x for x in myList if x in myDict]) > 0\n\nbut I didn't try the \"set\" answer because I didn't see how to turn it into one line.\n"
] |
[
20,
6,
2,
1,
1
] |
[] |
[] |
[
"dictionary",
"list",
"python"
] |
stackoverflow_0001737778_dictionary_list_python.txt
|
Q:
What's wrong with this program?
def short_distance(origins,(x,y),gap):
for (i,j) in origins.spilt(“ ”):
h=[]
h.append(float(math.sqrt ((i-x)*(i-x)+(j-y)*(j-y))))
for n in h:
if not gap < n:
print 0
if gap < n :
print n
A:
I would write the code more like this. If you run the code, it will report any failing tests (of which there are none).
import math
def short_distance(origins, point, gap):
"""
Describe origins, point, and gap are and what the
expected outcome is.
Then provide an example that tests the code
>>> short_distance('1,2 3,4', (5,6), 1.5)
5.65685424949
2.82842712475
"""
origins = parse_origins(origins)
distance_to_point = lambda point2: point_distance(point, point2)
# what's a better name for h?
h = map(distance_to_point, origins)
report(h, gap)
def report(h, gap):
"""
Take the results of the distances and report on them
"""
for distance in h:
if not (gap < distance):
print 0
else:
print distance
def point_distance(p1, p2):
"""
Calculate the distance between two points
>>> point_distance((0,0), (1,0))
1.0
more than one test here would be good
"""
x1, y1 = p1
x2, y2 = p2
return math.sqrt((x1-x2)**2 + (y1-y2)**2)
def parse_origins(origin_string):
"""
Parse an origins string.
>>> parse_origins('1,2 3,4')
((1.0, 2.0), (3.0, 4.0))
"""
points = origin_string.split(' ')
return tuple(map(parse_point, points))
def parse_point(point_string):
"""
Take a string like 1,2 and return a tuple of the numbers
in that string.
>>> parse_point('1,2.0')
(1.0, 2.0)
"""
return tuple(map(float, point_string.split(',')))
def test():
import doctest
doctest.testmod()
if __name__ == '__main__':
test()
A:
the indentation is wrong; the for loops should be indented more than the def
typo: origins.spilt(" ") should probably be origins.split(" ")
A:
Your code is perhaps for finding points from origins that are close to (x, y). There is a lot of errors in it:
Indention is wrong.
split() method is spelled wrong.
split() method returns flat list while you are expecting a list of pairs.
The former two are easy to fix. Without knowledge of origins string format I can't be sure what dou you wish ere. See this question for solutions on how to convert flat list to list of pairs.
Also note that if statement has else clause, so you can write:
if gap < n:
print n
else:
print 0
A:
You'll need to import math
The indentation is wrong
If Origins is a string like '1,1 2,2 3,3', Origins.split(" ") will give you a list of strings ["1,1", "2,2", "3,3"]. You will need to do some extra work to be able to use it with the for loop for (i,j) in ... You need a list of tuples like [(1,1), (2,2), (3,3)]
math.sqrt already returns a float, so you can leave that out
A:
Here's the code:
from math import sqrt
def short_distance(origins,(x,y),gap):
def distance(i, j):
ix, iy = i - x, j - y
return sqrt (ix*ix + iy*iy)
all_distances = (distance(float(i), float(j)) for (i,j) in origins)
for n in all_distances:
print (0 if gap >= n else n)
And then use it like this:
>>> origin = (0, 0)
>>> points = [(1, 1), (2, 1), (1, 2), (2, 2)]
>>> gap = 1.5
>>> short_distance(points, origin, gap)
0
2.2360679775
2.2360679775
2.82842712475
My best guess is this does what you want.
|
What's wrong with this program?
|
def short_distance(origins,(x,y),gap):
for (i,j) in origins.spilt(“ ”):
h=[]
h.append(float(math.sqrt ((i-x)*(i-x)+(j-y)*(j-y))))
for n in h:
if not gap < n:
print 0
if gap < n :
print n
|
[
"I would write the code more like this. If you run the code, it will report any failing tests (of which there are none).\nimport math\n\ndef short_distance(origins, point, gap):\n \"\"\"\n Describe origins, point, and gap are and what the \n expected outcome is.\n\n Then provide an example that tests the code\n >>> short_distance('1,2 3,4', (5,6), 1.5)\n 5.65685424949\n 2.82842712475\n \"\"\"\n origins = parse_origins(origins)\n distance_to_point = lambda point2: point_distance(point, point2)\n # what's a better name for h?\n h = map(distance_to_point, origins)\n report(h, gap)\n\ndef report(h, gap):\n \"\"\"\n Take the results of the distances and report on them\n \"\"\"\n for distance in h:\n if not (gap < distance):\n print 0\n else:\n print distance\n\ndef point_distance(p1, p2):\n \"\"\"\n Calculate the distance between two points\n\n >>> point_distance((0,0), (1,0))\n 1.0\n\n more than one test here would be good\n \"\"\"\n x1, y1 = p1\n x2, y2 = p2\n return math.sqrt((x1-x2)**2 + (y1-y2)**2)\n\ndef parse_origins(origin_string):\n \"\"\"\n Parse an origins string.\n >>> parse_origins('1,2 3,4')\n ((1.0, 2.0), (3.0, 4.0))\n \"\"\"\n points = origin_string.split(' ')\n return tuple(map(parse_point, points))\n\ndef parse_point(point_string):\n \"\"\"\n Take a string like 1,2 and return a tuple of the numbers\n in that string.\n\n >>> parse_point('1,2.0')\n (1.0, 2.0)\n \"\"\"\n return tuple(map(float, point_string.split(',')))\n\ndef test():\n import doctest\n doctest.testmod()\n\nif __name__ == '__main__':\n test()\n\n",
"\nthe indentation is wrong; the for loops should be indented more than the def\ntypo: origins.spilt(\" \") should probably be origins.split(\" \")\n\n",
"Your code is perhaps for finding points from origins that are close to (x, y). There is a lot of errors in it:\n\nIndention is wrong.\nsplit() method is spelled wrong.\nsplit() method returns flat list while you are expecting a list of pairs.\n\nThe former two are easy to fix. Without knowledge of origins string format I can't be sure what dou you wish ere. See this question for solutions on how to convert flat list to list of pairs.\nAlso note that if statement has else clause, so you can write:\nif gap < n:\n print n\nelse:\n print 0\n\n",
"\nYou'll need to import math\nThe indentation is wrong\nIf Origins is a string like '1,1 2,2 3,3', Origins.split(\" \") will give you a list of strings [\"1,1\", \"2,2\", \"3,3\"]. You will need to do some extra work to be able to use it with the for loop for (i,j) in ... You need a list of tuples like [(1,1), (2,2), (3,3)]\nmath.sqrt already returns a float, so you can leave that out\n\n",
"Here's the code:\nfrom math import sqrt\ndef short_distance(origins,(x,y),gap):\n def distance(i, j):\n ix, iy = i - x, j - y\n return sqrt (ix*ix + iy*iy)\n all_distances = (distance(float(i), float(j)) for (i,j) in origins)\n for n in all_distances:\n print (0 if gap >= n else n)\n\nAnd then use it like this:\n>>> origin = (0, 0)\n>>> points = [(1, 1), (2, 1), (1, 2), (2, 2)]\n>>> gap = 1.5\n>>> short_distance(points, origin, gap)\n0\n2.2360679775\n2.2360679775\n2.82842712475\n\nMy best guess is this does what you want.\n"
] |
[
4,
2,
2,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001737072_python.txt
|
Q:
Django: debugging entries just disapearing
So, I'm pulling my hair out here, and maybe someone has an insight.
I have a cronjob that loops over all my Link objects, does some stuff, might change properties on the object and does a save(). That's it.
Every so often (around once an hour), one of my rows just disappears. Poof. Nothing in the logs.
So, I'm trying to add debugging statements everywhere, but are there any glaring reasons for an entry to disapear? Is the only way to remove an entry by calling delete()?
Just any general directions to go would be wonderful, thank you.
Some ideas I've had:
git push while the cronjob is running
some cascading delete is wiping them out
some django method is calling delete on an exception
A:
You could override the delete method on your Link class and dump a stack trace or log a message to see if it's indeed happening from within your Django application.
import sys, traceback
def delete(self):
super(Link, self).delete()
try:
assert False
except AssertionError, e
traceback.print_tb(file=sys.stdout)
There may be a better way to get and log a stack trace, but that's the first thing that came to mind.
A:
You could use django-logging with LOGGING_LOG_SQL = True to log all the SQL, so you can see if any DELETE's are occurring.
|
Django: debugging entries just disapearing
|
So, I'm pulling my hair out here, and maybe someone has an insight.
I have a cronjob that loops over all my Link objects, does some stuff, might change properties on the object and does a save(). That's it.
Every so often (around once an hour), one of my rows just disappears. Poof. Nothing in the logs.
So, I'm trying to add debugging statements everywhere, but are there any glaring reasons for an entry to disapear? Is the only way to remove an entry by calling delete()?
Just any general directions to go would be wonderful, thank you.
Some ideas I've had:
git push while the cronjob is running
some cascading delete is wiping them out
some django method is calling delete on an exception
|
[
"You could override the delete method on your Link class and dump a stack trace or log a message to see if it's indeed happening from within your Django application.\nimport sys, traceback\n\ndef delete(self):\n super(Link, self).delete()\n\n try:\n assert False\n except AssertionError, e\n traceback.print_tb(file=sys.stdout)\n\nThere may be a better way to get and log a stack trace, but that's the first thing that came to mind.\n",
"You could use django-logging with LOGGING_LOG_SQL = True to log all the SQL, so you can see if any DELETE's are occurring.\n"
] |
[
2,
1
] |
[] |
[] |
[
"debugging",
"django",
"python"
] |
stackoverflow_0001737424_debugging_django_python.txt
|
Q:
Including package data with Distribute
I'm trying to use Distribute for my project's setup.py. I want it to include all the files in the package folder, which are text and image files, but not .pyc files of course. I read that the files should either be tracked by CVS and SVN, or there should be a MAINFEST.in.
So:
I use neither CVS nor SVN, I use git. I know that it's possible to write a plugin for git, and perhaps someone has, but I'm not going to use some plugin that I don't know if it will be maintained and supported. Also, git is tracking more than the source folder, the repo includes other files which shouldn't be packed in the distribution.
I thought that one of the perks of Distribute is not having to deal with a MANIFEST.in file. Do I really have to? If so, where do I see a guide? I've never written a MANIFEST.in.
Is there any nicer solution?
A:
I've change that behavior in Distutils (in Python trunk (2.7/3.2) )
Now all files mentioned in package_data will be included by default without having to
write a MANIFEST.in file, and without having to use the magic behavior based on DVCS.
Until then, I would recommend using an explicit MANIFEST.in and stick with plain Distutils options, so you don't rely on any VCS, and you don't add files by accidents, that are in your
repository, but that you don't want to see added in your release.
Distribute 0.7.x will probably stick with Distutils upcoming default behavior.
Look for the MANIFEST.in template language in the Distutils doc, it's quite simple.
Tarek
A:
I don't know if there is better documentation yet for distribute so you may have to refer to the documentation for setuptools from which distribute was forked. In particular, see the section on Including Data Files.
|
Including package data with Distribute
|
I'm trying to use Distribute for my project's setup.py. I want it to include all the files in the package folder, which are text and image files, but not .pyc files of course. I read that the files should either be tracked by CVS and SVN, or there should be a MAINFEST.in.
So:
I use neither CVS nor SVN, I use git. I know that it's possible to write a plugin for git, and perhaps someone has, but I'm not going to use some plugin that I don't know if it will be maintained and supported. Also, git is tracking more than the source folder, the repo includes other files which shouldn't be packed in the distribution.
I thought that one of the perks of Distribute is not having to deal with a MANIFEST.in file. Do I really have to? If so, where do I see a guide? I've never written a MANIFEST.in.
Is there any nicer solution?
|
[
"I've change that behavior in Distutils (in Python trunk (2.7/3.2) ) \nNow all files mentioned in package_data will be included by default without having to \nwrite a MANIFEST.in file, and without having to use the magic behavior based on DVCS.\nUntil then, I would recommend using an explicit MANIFEST.in and stick with plain Distutils options, so you don't rely on any VCS, and you don't add files by accidents, that are in your\nrepository, but that you don't want to see added in your release.\nDistribute 0.7.x will probably stick with Distutils upcoming default behavior.\nLook for the MANIFEST.in template language in the Distutils doc, it's quite simple.\nTarek\n",
"I don't know if there is better documentation yet for distribute so you may have to refer to the documentation for setuptools from which distribute was forked. In particular, see the section on Including Data Files.\n"
] |
[
5,
0
] |
[] |
[] |
[
"distribute",
"distribution",
"python",
"setuptools"
] |
stackoverflow_0001734373_distribute_distribution_python_setuptools.txt
|
Q:
Using pyparsing to parse a word escape-split over multiple lines
I'm trying to parse words which can be broken up over multiple lines with a backslash-newline combination ("\\n") using pyparsing. Here's what I have done:
from pyparsing import *
continued_ending = Literal('\\') + lineEnd
word = Word(alphas)
split_word = word + Suppress(continued_ending)
multi_line_word = Forward()
multi_line_word << (word | (split_word + multi_line_word))
print multi_line_word.parseString(
'''super\\
cali\\
fragi\\
listic''')
The output I get is ['super'], while the expected output is ['super', 'cali', fragi', 'listic']. Better still would be all of them joined as one word (which I think I can just do with multi_line_word.parseAction(lambda t: ''.join(t)).
I tried looking at this code in pyparsing helper, but it gives me an error, maximum recursion depth exceeded.
EDIT 2009-11-15: I realized later that pyparsing gets a little generous with regards to white space, and that leads to some poor assumptions that what I thought I was parsing for was a lot looser. That is to say, we want to see no white space between any of the portions of the word, the escape, and the EOL character.
I realized that the little example string above is insufficient as a test case, so I wrote the following unit tests. Code that passes these tests should be able to match what I intuitively think of as a escape-split word—and only an escape-split word. They will not match a basic word that is not escape-split. We can—and I believe should—use a different grammatical construct for that. This keeps it all tidy having the two separate.
import unittest
import pyparsing
# Assumes you named your module 'multiline.py'
import multiline
class MultiLineTests(unittest.TestCase):
def test_continued_ending(self):
case = '\\\n'
expected = ['\\', '\n']
result = multiline.continued_ending.parseString(case).asList()
self.assertEqual(result, expected)
def test_continued_ending_space_between_parse_error(self):
case = '\\ \n'
self.assertRaises(
pyparsing.ParseException,
multiline.continued_ending.parseString,
case
)
def test_split_word(self):
cases = ('shiny\\', 'shiny\\\n', ' shiny\\')
expected = ['shiny']
for case in cases:
result = multiline.split_word.parseString(case).asList()
self.assertEqual(result, expected)
def test_split_word_no_escape_parse_error(self):
case = 'shiny'
self.assertRaises(
pyparsing.ParseException,
multiline.split_word.parseString,
case
)
def test_split_word_space_parse_error(self):
cases = ('shiny \\', 'shiny\r\\', 'shiny\t\\', 'shiny\\ ')
for case in cases:
self.assertRaises(
pyparsing.ParseException,
multiline.split_word.parseString,
case
)
def test_multi_line_word(self):
cases = (
'shiny\\',
'shi\\\nny',
'sh\\\ni\\\nny\\\n',
' shi\\\nny\\',
'shi\\\nny '
'shi\\\nny captain'
)
expected = ['shiny']
for case in cases:
result = multiline.multi_line_word.parseString(case).asList()
self.assertEqual(result, expected)
def test_multi_line_word_spaces_parse_error(self):
cases = (
'shi \\\nny',
'shi\\ \nny',
'sh\\\n iny',
'shi\\\n\tny',
)
for case in cases:
self.assertRaises(
pyparsing.ParseException,
multiline.multi_line_word.parseString,
case
)
if __name__ == '__main__':
unittest.main()
A:
After poking around for a bit more, I came upon this help thread where there was this notable bit
I often see inefficient grammars when
someone implements a pyparsing grammar
directly from a BNF definition. BNF
does not have a concept of "one or
more" or "zero or more" or
"optional"...
With that, I got the idea to change these two lines
multi_line_word = Forward()
multi_line_word << (word | (split_word + multi_line_word))
To
multi_line_word = ZeroOrMore(split_word) + word
This got it to output what I was looking for: ['super', 'cali', fragi', 'listic'].
Next, I added a parse action that would join these tokens together:
multi_line_word.setParseAction(lambda t: ''.join(t))
This gives a final output of ['supercalifragilistic'].
The take home message I learned is that one doesn't simply walk into Mordor.
Just kidding.
The take home message is that one can't simply implement a one-to-one translation of BNF with pyparsing. Some tricks with using the iterative types should be called into use.
EDIT 2009-11-25: To compensate for the more strenuous test cases, I modified the code to the following:
no_space = NotAny(White(' \t\r'))
# make sure that the EOL immediately follows the escape backslash
continued_ending = Literal('\\') + no_space + lineEnd
word = Word(alphas)
# make sure that the escape backslash immediately follows the word
split_word = word + NotAny(White()) + Suppress(continued_ending)
multi_line_word = OneOrMore(split_word + NotAny(White())) + Optional(word)
multi_line_word.setParseAction(lambda t: ''.join(t))
This has the benefit of making sure that no space comes between any of the elements (with the exception of newlines after the escaping backslashes).
A:
You are pretty close with your code. Any of these mods would work:
# '|' means MatchFirst, so you had a left-recursive expression
# reversing the order of the alternatives makes this work
multi_line_word << ((split_word + multi_line_word) | word)
# '^' means Or/MatchLongest, but beware using this inside a Forward
multi_line_word << (word ^ (split_word + multi_line_word))
# an unusual use of delimitedList, but it works
multi_line_word = delimitedList(word, continued_ending)
# in place of your parse action, you can wrap in a Combine
multi_line_word = Combine(delimitedList(word, continued_ending))
As you found in your pyparsing googling, BNF->pyparsing translations should be done with a special view to using pyparsing features in place of BNF, um, shortcomings. I was actually in the middle of composing a longer answer, going into more of the BNF translation issues, but you have already found this material (on the wiki, I assume).
|
Using pyparsing to parse a word escape-split over multiple lines
|
I'm trying to parse words which can be broken up over multiple lines with a backslash-newline combination ("\\n") using pyparsing. Here's what I have done:
from pyparsing import *
continued_ending = Literal('\\') + lineEnd
word = Word(alphas)
split_word = word + Suppress(continued_ending)
multi_line_word = Forward()
multi_line_word << (word | (split_word + multi_line_word))
print multi_line_word.parseString(
'''super\\
cali\\
fragi\\
listic''')
The output I get is ['super'], while the expected output is ['super', 'cali', fragi', 'listic']. Better still would be all of them joined as one word (which I think I can just do with multi_line_word.parseAction(lambda t: ''.join(t)).
I tried looking at this code in pyparsing helper, but it gives me an error, maximum recursion depth exceeded.
EDIT 2009-11-15: I realized later that pyparsing gets a little generous with regards to white space, and that leads to some poor assumptions that what I thought I was parsing for was a lot looser. That is to say, we want to see no white space between any of the portions of the word, the escape, and the EOL character.
I realized that the little example string above is insufficient as a test case, so I wrote the following unit tests. Code that passes these tests should be able to match what I intuitively think of as a escape-split word—and only an escape-split word. They will not match a basic word that is not escape-split. We can—and I believe should—use a different grammatical construct for that. This keeps it all tidy having the two separate.
import unittest
import pyparsing
# Assumes you named your module 'multiline.py'
import multiline
class MultiLineTests(unittest.TestCase):
def test_continued_ending(self):
case = '\\\n'
expected = ['\\', '\n']
result = multiline.continued_ending.parseString(case).asList()
self.assertEqual(result, expected)
def test_continued_ending_space_between_parse_error(self):
case = '\\ \n'
self.assertRaises(
pyparsing.ParseException,
multiline.continued_ending.parseString,
case
)
def test_split_word(self):
cases = ('shiny\\', 'shiny\\\n', ' shiny\\')
expected = ['shiny']
for case in cases:
result = multiline.split_word.parseString(case).asList()
self.assertEqual(result, expected)
def test_split_word_no_escape_parse_error(self):
case = 'shiny'
self.assertRaises(
pyparsing.ParseException,
multiline.split_word.parseString,
case
)
def test_split_word_space_parse_error(self):
cases = ('shiny \\', 'shiny\r\\', 'shiny\t\\', 'shiny\\ ')
for case in cases:
self.assertRaises(
pyparsing.ParseException,
multiline.split_word.parseString,
case
)
def test_multi_line_word(self):
cases = (
'shiny\\',
'shi\\\nny',
'sh\\\ni\\\nny\\\n',
' shi\\\nny\\',
'shi\\\nny '
'shi\\\nny captain'
)
expected = ['shiny']
for case in cases:
result = multiline.multi_line_word.parseString(case).asList()
self.assertEqual(result, expected)
def test_multi_line_word_spaces_parse_error(self):
cases = (
'shi \\\nny',
'shi\\ \nny',
'sh\\\n iny',
'shi\\\n\tny',
)
for case in cases:
self.assertRaises(
pyparsing.ParseException,
multiline.multi_line_word.parseString,
case
)
if __name__ == '__main__':
unittest.main()
|
[
"After poking around for a bit more, I came upon this help thread where there was this notable bit\n\nI often see inefficient grammars when\n someone implements a pyparsing grammar\n directly from a BNF definition. BNF\n does not have a concept of \"one or\n more\" or \"zero or more\" or\n \"optional\"...\n\nWith that, I got the idea to change these two lines\nmulti_line_word = Forward()\nmulti_line_word << (word | (split_word + multi_line_word))\n\nTo\nmulti_line_word = ZeroOrMore(split_word) + word\n\nThis got it to output what I was looking for: ['super', 'cali', fragi', 'listic'].\nNext, I added a parse action that would join these tokens together:\nmulti_line_word.setParseAction(lambda t: ''.join(t))\n\nThis gives a final output of ['supercalifragilistic'].\nThe take home message I learned is that one doesn't simply walk into Mordor.\nJust kidding.\nThe take home message is that one can't simply implement a one-to-one translation of BNF with pyparsing. Some tricks with using the iterative types should be called into use.\nEDIT 2009-11-25: To compensate for the more strenuous test cases, I modified the code to the following:\nno_space = NotAny(White(' \\t\\r'))\n# make sure that the EOL immediately follows the escape backslash\ncontinued_ending = Literal('\\\\') + no_space + lineEnd\nword = Word(alphas)\n# make sure that the escape backslash immediately follows the word\nsplit_word = word + NotAny(White()) + Suppress(continued_ending)\nmulti_line_word = OneOrMore(split_word + NotAny(White())) + Optional(word)\nmulti_line_word.setParseAction(lambda t: ''.join(t))\n\nThis has the benefit of making sure that no space comes between any of the elements (with the exception of newlines after the escaping backslashes).\n",
"You are pretty close with your code. Any of these mods would work:\n# '|' means MatchFirst, so you had a left-recursive expression\n# reversing the order of the alternatives makes this work\nmulti_line_word << ((split_word + multi_line_word) | word)\n\n# '^' means Or/MatchLongest, but beware using this inside a Forward\nmulti_line_word << (word ^ (split_word + multi_line_word))\n\n# an unusual use of delimitedList, but it works\nmulti_line_word = delimitedList(word, continued_ending)\n\n# in place of your parse action, you can wrap in a Combine\nmulti_line_word = Combine(delimitedList(word, continued_ending))\n\nAs you found in your pyparsing googling, BNF->pyparsing translations should be done with a special view to using pyparsing features in place of BNF, um, shortcomings. I was actually in the middle of composing a longer answer, going into more of the BNF translation issues, but you have already found this material (on the wiki, I assume).\n"
] |
[
6,
5
] |
[] |
[] |
[
"parsing",
"pyparsing",
"python"
] |
stackoverflow_0001735722_parsing_pyparsing_python.txt
|
Q:
How do I enforce a UTF8 encoding on a generated CSV report?
How do I enforce a UTF8 encoding on a generated CSV report in web2py?
A:
Use the str.encode function together with the csv module, there is a complete example that will show you that in the Python documentation (or in the link given in comment to your question). Quick example:
row = ["one", "two", "three"]
import csv
with open("report.csv", "wb") as f:
writer = csv.writer(f)
writer.writerow([s.encode("utf-8") for s in row])
|
How do I enforce a UTF8 encoding on a generated CSV report?
|
How do I enforce a UTF8 encoding on a generated CSV report in web2py?
|
[
"Use the str.encode function together with the csv module, there is a complete example that will show you that in the Python documentation (or in the link given in comment to your question). Quick example:\nrow = [\"one\", \"two\", \"three\"]\n\nimport csv\nwith open(\"report.csv\", \"wb\") as f:\n writer = csv.writer(f)\n writer.writerow([s.encode(\"utf-8\") for s in row])\n\n"
] |
[
2
] |
[] |
[] |
[
"python",
"web2py"
] |
stackoverflow_0001737178_python_web2py.txt
|
Q:
wxPython: How should I organize per-widget data in the controller?
I have a widget that displays a filesystem hierarchy for convenient browsing (basically a tree control and some associated toolbar buttons, such as "refresh"). Each of these widgets has a set of base directories for it to display (recursively). Assume that the user may instantiate as many of these widgets as they find convenient. Note that these widgets don't correspond to any business data -- they're independent of the model.
Where should the (per-widget) set of base directories live in good MVC design?
When the refresh button is pushed, an event is trapped by the controller, and the event contains the corresponding filesystem-browser widget. The controller determines the base directories for that particular widget (somehow), walks that directory path, and passes the widget some data to render.
Two places I can think to store the base directories:
The easy solution: make the base directories an instance variable on the widget and have the controller manipulate it to retain state for that widget. There's a conceptual issue with this, though: since the widget never looks at that instance variable, you're just projecting one of the responsibilities of the controller onto the widget.
The more (technically, maybe conceptually) complex solution: Keep a {widget: base_directory_set} mapping in the controller with weak key references.
The second way allows for easy expansion of controller responsibilities later on, as putting things in the controller tends to do -- for example, if I decided I later wanted to determine the set of all the base directories for all those widgets.
There may be some piece of MVC knowledge I'm missing that solves this kind of problem well.
A:
The anomaly (from the MVC viewpoint) that makes this design difficult to make MVC-conformant is that you want to display information that, by your conceptualization, "does not live in a model". There is no such thing as "information that does not live in a model" in MVC: its conceptual root is "the models hold all the information, the views just do presentation tasks, the controllers mediate user interaction".
It's quite possible that the information you're displaying doesn't "correspond to any business data", but (in an MVC worldview) this does not mean that info is "independent of the model", because there is no such thing -- it just means you need another model class (beyond whatever you're using to hold "business data"), to hold this "non-business" data!-)
So when the user "instantiates a widget" (creates a directory-display view, presumably by some user action on some master/coordinating view, possibly on another existing widget if "cloning" is one of the ways to instantiate a widget), the controller's responsible for creating both a widget object and an instance of the "directory-display model class", and establish connection between them (normally by setting on the widget a reference to the relevant model instance), as well as telling the model to do its initial loading of information. When the user action on the widget implies an action on the model, the controller retrieves from the widget involved in the event the reference to the model instance, and sends that instance the appropriate request(s) (it's the model's business to let the view[s] interested in it know about changes to information -- typically by some observer pattern; it's definitely not the controller's business to feed the view with information -- that's really a very different approach from MVC!).
Is the architectural investment required by MVC worth it, in your case, compared to a rougher approach where the information flows are less pristine and the model that should be there just doesn't exist? I'm a pragmatist and I definitely don't worship at the altar of MVC, but I think in this case the (relatively small) investment in sound, clear architecture may indeed repay itself in abundance. It's a question of envisioning the likely directions of change -- for example, what functionality that you don't need right now (but may well enter the picture soon afterwards) will be trivial to add if you go the proper MVC route, and would be a nightmare of ad-hoc kludges otherwise (or require a somewhat painful refactoring of the whole architecture)? All sort of likely things, from wanting to display the same directory information in different widgets to having a smarter "directory-information watching" model that can automatically refresh itself when needed (and supply the new info directly to interested views via the usual observer pattern, with no involvement by the controller), are natural and trivially easy with MVC (hey, that's the whole point of MVC, after all, so this is hardly surprising!-), kludgy and fragile with an ad-hoc corner-cutting architecture -- small investment, large potential returns, go for it!
You may notice from the tone of the previous paragraph that I don't worship at the "extreme programming" altar either -- as a pragmatist, I will do a little "design up front" (especially in terms of putting in place a clean, flexible, extensible architecture, from the start, even if it's not indispensable right now) -- exactly because, in my experience, a little forethought and very modest investment, especially on the architectural front, pays back for itself many times over during a project's life (in such varied currencies as scalability, flexibility, extensibility, maintainability, security, and so forth, though not all of them will apply to every project -- e.g., in your case, security and scalability are not really a concern... but the other aspects will likely be!-).
Just for generality, let me point out that this pragmatic attitude of mine does not justify excessive energy and time spent on picking an architecture (by definition of the word "excessive";-) -- being familiar with a few fundamental architectural patterns (and MVC is surely one of those) often reduces the initial investment in terms of time and effort -- once you recognize that such a classic architecture will serve you well, as in this case, it's really easy to see how to embody it (e.g., reject the idea of an "MVC without a M"!-), and it doesn't really take much more code compared to the kludgiest, ad-hoccest shortcuts!-)
A:
Based on how the MVC methodology operates, I would suggest that you go with a modification the first solution you listed:
make the base directories an instance variable on the widget and have the controller manipulate it to retain state for that widget.
Why? You stated that the widgets are independent of the model, but are they actually referenced from within the models? If you're not binding your widgets to your models, you're straying from the basic concept of MVC.
I don't have any knowledge of wxPython, so I can't speak to how it conforms to MVC, if at all. Even still it seems to me that you should consider integrating the widgets into the models, or treating them as models themselves.
So if we assume that in this context the widgets are effectively part of your model hierarchy, this could possibly not only be the easy solution, as you said, but the right one.
Because one of the core fundamentals of MVC is maintaining loose coupling between each part, you always want to isolate your business logic from data input and presentation. Maintaining widgets that are displayed separately from models breaks this, so putting any kind of informational methods into your controller doesn't fit. You want a model to contain everything it needs to be manipulated or displayed by the controller when presenting data in your views.
Have you considered creating a superclass for all widgets so that there will be a common set of methods they will always inherit?
Example:
import os
WIDGET_PREFIX = '/tmp'
class Widget:
def __init__(self, name):
self.name = name
self.widget_prefix = WIDGET_PREFIX
self.dirs = os.walk(os.path.join(self.widget_prefix, name))
def _get_base_directory_set(self):
return self.dirs
base_directory_set = property(_get_base_directory_set)
I hope this at least gives you something to think about.
A:
The solution I've currently adopted is, "per-widget controllers." (Maybe there's an existing name for it.) It delegates to a "parent" controller for any UI-wide functionality, but exists to control the widget and associate any relevant data on a per-widget basis.
The "per-widget controller" concept avoids projecting any irrelevant properties onto the widget itself. You can extend these controllers to register/unregister the controlled widgets on creation/destruction for those times when you want to perform a many-widget operation, thereby avoiding weakref magic.
For example:
class FSBrowserController(wx.EvtHandler):
"""Widget-specific controller for filesystem browsers.
:ivar parent: Parent controller -- useful when UI-wide control is
necessary to respond to an event.
"""
def __init__(self, parent, frame, tree_ctrl, base_dirs):
self.parent = parent
self.frame = frame
self.tree_ctrl = tree_ctrl
self.base_dirs = base_dirs
frame.Bind(EVT_FS_REFRESH, self.refresh)
frame.Bind(wx.EVT_WINDOW_DESTROY, self._unregister)
self.refresh()
self._register()
def _register(self):
"""Register self with parent controller."""
self.parent._fsb_controllers.append(self)
def _unregister(self, event):
"""Unregister self with parent controller."""
if event.GetEventObject() == self.frame:
self.parent._fsb_controllers.remove(self)
def refresh(self, event=None):
"""Refresh the :ivar:`tree_ctrl` using :ivar:`base_dirs`."""
raise NotImplementedError
class Controller(wx.EvtHandler):
"""Main controller for the application.
Handles UI-wide behaviors.
"""
def __init__(self):
self._fsb_controllers = []
fsb_frame = FSBrowserFrame(parent=None)
FSBrowserController(self, fsb_frame, fsb_frame.tree_ctrl,
initial_base_dirs)
fsb_frame.Show()
This way, when the FSBrowserFrame is destroyed, the controller and associated data will naturally disappear with it.
|
wxPython: How should I organize per-widget data in the controller?
|
I have a widget that displays a filesystem hierarchy for convenient browsing (basically a tree control and some associated toolbar buttons, such as "refresh"). Each of these widgets has a set of base directories for it to display (recursively). Assume that the user may instantiate as many of these widgets as they find convenient. Note that these widgets don't correspond to any business data -- they're independent of the model.
Where should the (per-widget) set of base directories live in good MVC design?
When the refresh button is pushed, an event is trapped by the controller, and the event contains the corresponding filesystem-browser widget. The controller determines the base directories for that particular widget (somehow), walks that directory path, and passes the widget some data to render.
Two places I can think to store the base directories:
The easy solution: make the base directories an instance variable on the widget and have the controller manipulate it to retain state for that widget. There's a conceptual issue with this, though: since the widget never looks at that instance variable, you're just projecting one of the responsibilities of the controller onto the widget.
The more (technically, maybe conceptually) complex solution: Keep a {widget: base_directory_set} mapping in the controller with weak key references.
The second way allows for easy expansion of controller responsibilities later on, as putting things in the controller tends to do -- for example, if I decided I later wanted to determine the set of all the base directories for all those widgets.
There may be some piece of MVC knowledge I'm missing that solves this kind of problem well.
|
[
"The anomaly (from the MVC viewpoint) that makes this design difficult to make MVC-conformant is that you want to display information that, by your conceptualization, \"does not live in a model\". There is no such thing as \"information that does not live in a model\" in MVC: its conceptual root is \"the models hold all the information, the views just do presentation tasks, the controllers mediate user interaction\".\nIt's quite possible that the information you're displaying doesn't \"correspond to any business data\", but (in an MVC worldview) this does not mean that info is \"independent of the model\", because there is no such thing -- it just means you need another model class (beyond whatever you're using to hold \"business data\"), to hold this \"non-business\" data!-)\nSo when the user \"instantiates a widget\" (creates a directory-display view, presumably by some user action on some master/coordinating view, possibly on another existing widget if \"cloning\" is one of the ways to instantiate a widget), the controller's responsible for creating both a widget object and an instance of the \"directory-display model class\", and establish connection between them (normally by setting on the widget a reference to the relevant model instance), as well as telling the model to do its initial loading of information. When the user action on the widget implies an action on the model, the controller retrieves from the widget involved in the event the reference to the model instance, and sends that instance the appropriate request(s) (it's the model's business to let the view[s] interested in it know about changes to information -- typically by some observer pattern; it's definitely not the controller's business to feed the view with information -- that's really a very different approach from MVC!).\nIs the architectural investment required by MVC worth it, in your case, compared to a rougher approach where the information flows are less pristine and the model that should be there just doesn't exist? I'm a pragmatist and I definitely don't worship at the altar of MVC, but I think in this case the (relatively small) investment in sound, clear architecture may indeed repay itself in abundance. It's a question of envisioning the likely directions of change -- for example, what functionality that you don't need right now (but may well enter the picture soon afterwards) will be trivial to add if you go the proper MVC route, and would be a nightmare of ad-hoc kludges otherwise (or require a somewhat painful refactoring of the whole architecture)? All sort of likely things, from wanting to display the same directory information in different widgets to having a smarter \"directory-information watching\" model that can automatically refresh itself when needed (and supply the new info directly to interested views via the usual observer pattern, with no involvement by the controller), are natural and trivially easy with MVC (hey, that's the whole point of MVC, after all, so this is hardly surprising!-), kludgy and fragile with an ad-hoc corner-cutting architecture -- small investment, large potential returns, go for it!\nYou may notice from the tone of the previous paragraph that I don't worship at the \"extreme programming\" altar either -- as a pragmatist, I will do a little \"design up front\" (especially in terms of putting in place a clean, flexible, extensible architecture, from the start, even if it's not indispensable right now) -- exactly because, in my experience, a little forethought and very modest investment, especially on the architectural front, pays back for itself many times over during a project's life (in such varied currencies as scalability, flexibility, extensibility, maintainability, security, and so forth, though not all of them will apply to every project -- e.g., in your case, security and scalability are not really a concern... but the other aspects will likely be!-).\nJust for generality, let me point out that this pragmatic attitude of mine does not justify excessive energy and time spent on picking an architecture (by definition of the word \"excessive\";-) -- being familiar with a few fundamental architectural patterns (and MVC is surely one of those) often reduces the initial investment in terms of time and effort -- once you recognize that such a classic architecture will serve you well, as in this case, it's really easy to see how to embody it (e.g., reject the idea of an \"MVC without a M\"!-), and it doesn't really take much more code compared to the kludgiest, ad-hoccest shortcuts!-)\n",
"Based on how the MVC methodology operates, I would suggest that you go with a modification the first solution you listed:\n\nmake the base directories an instance variable on the widget and have the controller manipulate it to retain state for that widget.\n\nWhy? You stated that the widgets are independent of the model, but are they actually referenced from within the models? If you're not binding your widgets to your models, you're straying from the basic concept of MVC. \nI don't have any knowledge of wxPython, so I can't speak to how it conforms to MVC, if at all. Even still it seems to me that you should consider integrating the widgets into the models, or treating them as models themselves.\nSo if we assume that in this context the widgets are effectively part of your model hierarchy, this could possibly not only be the easy solution, as you said, but the right one.\nBecause one of the core fundamentals of MVC is maintaining loose coupling between each part, you always want to isolate your business logic from data input and presentation. Maintaining widgets that are displayed separately from models breaks this, so putting any kind of informational methods into your controller doesn't fit. You want a model to contain everything it needs to be manipulated or displayed by the controller when presenting data in your views.\nHave you considered creating a superclass for all widgets so that there will be a common set of methods they will always inherit?\nExample:\nimport os\n\nWIDGET_PREFIX = '/tmp'\nclass Widget:\n def __init__(self, name):\n self.name = name\n self.widget_prefix = WIDGET_PREFIX\n self.dirs = os.walk(os.path.join(self.widget_prefix, name))\n\n def _get_base_directory_set(self):\n return self.dirs\n base_directory_set = property(_get_base_directory_set)\n\nI hope this at least gives you something to think about.\n",
"The solution I've currently adopted is, \"per-widget controllers.\" (Maybe there's an existing name for it.) It delegates to a \"parent\" controller for any UI-wide functionality, but exists to control the widget and associate any relevant data on a per-widget basis.\nThe \"per-widget controller\" concept avoids projecting any irrelevant properties onto the widget itself. You can extend these controllers to register/unregister the controlled widgets on creation/destruction for those times when you want to perform a many-widget operation, thereby avoiding weakref magic.\nFor example:\nclass FSBrowserController(wx.EvtHandler):\n\n \"\"\"Widget-specific controller for filesystem browsers.\n\n :ivar parent: Parent controller -- useful when UI-wide control is\n necessary to respond to an event.\n \"\"\"\n\n def __init__(self, parent, frame, tree_ctrl, base_dirs):\n self.parent = parent\n self.frame = frame\n self.tree_ctrl = tree_ctrl\n self.base_dirs = base_dirs\n frame.Bind(EVT_FS_REFRESH, self.refresh)\n frame.Bind(wx.EVT_WINDOW_DESTROY, self._unregister)\n self.refresh()\n self._register()\n\n def _register(self):\n \"\"\"Register self with parent controller.\"\"\"\n self.parent._fsb_controllers.append(self)\n\n def _unregister(self, event):\n \"\"\"Unregister self with parent controller.\"\"\"\n if event.GetEventObject() == self.frame:\n self.parent._fsb_controllers.remove(self)\n\n def refresh(self, event=None):\n \"\"\"Refresh the :ivar:`tree_ctrl` using :ivar:`base_dirs`.\"\"\"\n raise NotImplementedError\n\n\nclass Controller(wx.EvtHandler):\n\n \"\"\"Main controller for the application.\n Handles UI-wide behaviors.\n \"\"\"\n\n def __init__(self):\n self._fsb_controllers = []\n fsb_frame = FSBrowserFrame(parent=None)\n FSBrowserController(self, fsb_frame, fsb_frame.tree_ctrl,\n initial_base_dirs)\n fsb_frame.Show()\n\nThis way, when the FSBrowserFrame is destroyed, the controller and associated data will naturally disappear with it.\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"model_view_controller",
"python",
"user_interface"
] |
stackoverflow_0001686235_model_view_controller_python_user_interface.txt
|
Q:
change 2 byte in a string
I'd like to change 2 byte in a string like this:
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Let's imagine I want to replace 'RS' by 11, I know how to do it with one byte like [:], but for 2 or more in the middle of the string ?
Thanks !
A:
Strings are immutable, you can't change them. You have to make a new string from parts of the old one:
>>> az= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> az= az[:17]+'11'+az[19:]
>>> az
'ABCDEFGHIJKLMNOPQ11TUVWXYZ'
although depending one what you're doing there may be a more appropriate way of handling it than relying on fixed indices, eg.
>>> 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.replace('RS', '11', 1)
'ABCDEFGHIJKLMNOPQ11TUVWXYZ'
A:
I would use string.replace():
>>> import string
>>> az = string.lowercase
>>> az = az.replace('rs', '11')
>>> az
'abcdefghijklmnopq11tuvwxyz'
A:
I think it's a trick question, see "how to do it with one byte":
>>> st="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
>>> st="ABCDEFGHIJKLMNOPQRSTUVWXYZ".replace("R","1").replace("S","1")
>>> print st
ABCDEFGHIJKLMNOPQ11TUVWXYZ
|
change 2 byte in a string
|
I'd like to change 2 byte in a string like this:
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Let's imagine I want to replace 'RS' by 11, I know how to do it with one byte like [:], but for 2 or more in the middle of the string ?
Thanks !
|
[
"Strings are immutable, you can't change them. You have to make a new string from parts of the old one:\n>>> az= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n>>> az= az[:17]+'11'+az[19:]\n>>> az\n'ABCDEFGHIJKLMNOPQ11TUVWXYZ'\n\nalthough depending one what you're doing there may be a more appropriate way of handling it than relying on fixed indices, eg.\n>>> 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.replace('RS', '11', 1)\n'ABCDEFGHIJKLMNOPQ11TUVWXYZ'\n\n",
"I would use string.replace():\n>>> import string\n>>> az = string.lowercase\n>>> az = az.replace('rs', '11')\n>>> az\n'abcdefghijklmnopq11tuvwxyz'\n\n",
"I think it's a trick question, see \"how to do it with one byte\":\n>>> st=\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n>>> st=\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\".replace(\"R\",\"1\").replace(\"S\",\"1\")\n>>> print st\nABCDEFGHIJKLMNOPQ11TUVWXYZ\n\n"
] |
[
4,
1,
0
] |
[] |
[] |
[
"python",
"string"
] |
stackoverflow_0001737782_python_string.txt
|
Q:
Count the number of occurences of letters in a Python string
So I got a DNA sequence.
ACCAGAGCGGCACAGCAGCGACATCAGCACTAGCACTAGCATCAGCATCAGCATCAGC
CTACATCATCACAGCAGCATCAGCATCGACATCAGCATCAGCATCAGCATCGACGACT
ACACCCCCCCCGGTGTGTGTGGGGGGTTAAAAATGATGAGTGATGAGTGAGTTGTGTG
CTACATCATCACAGCAGCATCAGCATCGACATCAGCATCAGCATCAGCATCGACGACT
TTCTATCATCATTCGGCGGGGGGATATATTATAGCGCGCGATTATTGCGCAGTCTACG
TCATCGACTACGATCAGCATCAGCATCAGCATCAGCATCGACTAGCATCAGCTACGAC
I need to count the bases.
Also for some reason it can sometimes it can alternate between upper or lowercase in the same string.
A:
for base in 'ACGT':
print base, thesequence.count(base) + thesequence.count(base.lower())
|
Count the number of occurences of letters in a Python string
|
So I got a DNA sequence.
ACCAGAGCGGCACAGCAGCGACATCAGCACTAGCACTAGCATCAGCATCAGCATCAGC
CTACATCATCACAGCAGCATCAGCATCGACATCAGCATCAGCATCAGCATCGACGACT
ACACCCCCCCCGGTGTGTGTGGGGGGTTAAAAATGATGAGTGATGAGTGAGTTGTGTG
CTACATCATCACAGCAGCATCAGCATCGACATCAGCATCAGCATCAGCATCGACGACT
TTCTATCATCATTCGGCGGGGGGATATATTATAGCGCGCGATTATTGCGCAGTCTACG
TCATCGACTACGATCAGCATCAGCATCAGCATCAGCATCGACTAGCATCAGCTACGAC
I need to count the bases.
Also for some reason it can sometimes it can alternate between upper or lowercase in the same string.
|
[
"for base in 'ACGT':\n print base, thesequence.count(base) + thesequence.count(base.lower())\n\n"
] |
[
7
] |
[] |
[] |
[
"python",
"string"
] |
stackoverflow_0001738452_python_string.txt
|
Q:
Python: how to make two lists from a dictionary
I have a dictionary.
{1 : [1.2, 2.3, 4.9, 2.0], 2 : [4.1, 5.1, 6.3], 3 : [4.9, 6.8, 9.5, 1.1, 7.1]}
I want to pass each key:value pair to an instance of matplotlib.pyplot as two lists: x values and y values.
Each key is an x value associated with each item in its value.
So I want two lists for each key:
[1,1,1,1] [1.2,2.3,4.9,2.0]
[2,2,2] [4.1,5.1,6.3]
[3,3,3,3,3] [4.9,6.8,9.5,1.1,7.1]
Is there an elegant way to do this?
Or perhaps there is a way to pass a dict to matplotlib.pyplot?
A:
for k, v in dictionary.iteritems():
x = [k] * len(v)
y = v
pyplot.plot(x, y)
A:
d = {1 : [1.2, 2.3, 4.9, 2.0], 2 : [4.1, 5.1, 6.3], 3 : [4.9, 6.8, 9.5, 1.1, 7.1]}
res = [([x]*len(y), y) for x, y in d.iteritems()]
res will be a list of tuples, where the first element in the tuple is your list of x-values and second element in the tuple is your list f y-values
A:
Maybe something like:
d = {1 : [1.2, 2.3, 4.9, 2.0], 2 : [4.1, 5.1, 6.3], 3 : [4.9, 6.8, 9.5, 1.1, 7.1]}
result = []
for key, values in d.items():
result.append(([key]*len(values), values))
A:
Use this list comprehension:
[([k]*len(v), v) for k, v in D.iteritems()]
Here's an example of it being used:
>>> from pprint import pprint
>>> D = {1: [1.2, 2.3, 4.9, 2.0], 2: [4.1, 5.1, 6.3], 3: [4.9, 6.8, 9.5, 1.1, 7.1]}
>>> LL = [([k]*len(v), v) for k, v in D.iteritems()]
>>> pprint(LL)
[([1, 1, 1, 1], [1.2, 2.2999999999999998, 4.9000000000000004, 2.0]),
([2, 2, 2], [4.0999999999999996, 5.0999999999999996, 6.2999999999999998]),
([3, 3, 3, 3, 3],
[4.9000000000000004,
6.7999999999999998,
9.5,
1.1000000000000001,
7.0999999999999996])]
A:
As a list comprehension:
r = [([k]*len(v), v) for k,v in d.items()]
If your dictionary is very large, you'd want to use a generator expression:
from itertools import repeat
r = ((repeat(k, len(v)), v) for k,v in d.iteritems())
...though note that using repeat means that the first item in each tuple the generator returns is itself a generator. That's unnecessary if the dictionary's values don't themselves have many items.
A:
>>> d = {1 : [1.2, 2.3, 4.9, 2.0], 2 : [4.1, 5.1, 6.3], 3 : [4.9, 6.8, 9.5, 1.1, 7.1]}
>>> result = [ ([k] * len(d[k]), d[k]) for k in d.keys() ]
>>> print result
[([1, 1, 1, 1], [1.2, 2.2999999999999998, 4.9000000000000004, 2.0]), ([2, 2, 2],
[4.0999999999999996, 5.0999999999999996, 6.2999999999999998]), ([3, 3, 3, 3, 3],
[4.9000000000000004, 6.7999999999999998, 9.5, 1.1000000000000001, 7.0999999999999996])]
A:
I guess that a wizard will put something nicer, but I would do something like:
map(lambda x: ([x]*len(a[x]),a[x]),a)
for a tuple, or
map(lambda x: [[x]*len(a[x]),a[x]],a)
for a list.
btw: a is the dictionary, of course!
I assume that you work with the 2.x series...
Regards
|
Python: how to make two lists from a dictionary
|
I have a dictionary.
{1 : [1.2, 2.3, 4.9, 2.0], 2 : [4.1, 5.1, 6.3], 3 : [4.9, 6.8, 9.5, 1.1, 7.1]}
I want to pass each key:value pair to an instance of matplotlib.pyplot as two lists: x values and y values.
Each key is an x value associated with each item in its value.
So I want two lists for each key:
[1,1,1,1] [1.2,2.3,4.9,2.0]
[2,2,2] [4.1,5.1,6.3]
[3,3,3,3,3] [4.9,6.8,9.5,1.1,7.1]
Is there an elegant way to do this?
Or perhaps there is a way to pass a dict to matplotlib.pyplot?
|
[
"for k, v in dictionary.iteritems():\n x = [k] * len(v)\n y = v\n pyplot.plot(x, y)\n\n",
"d = {1 : [1.2, 2.3, 4.9, 2.0], 2 : [4.1, 5.1, 6.3], 3 : [4.9, 6.8, 9.5, 1.1, 7.1]}\n\nres = [([x]*len(y), y) for x, y in d.iteritems()]\n\nres will be a list of tuples, where the first element in the tuple is your list of x-values and second element in the tuple is your list f y-values\n",
"Maybe something like:\nd = {1 : [1.2, 2.3, 4.9, 2.0], 2 : [4.1, 5.1, 6.3], 3 : [4.9, 6.8, 9.5, 1.1, 7.1]}\nresult = []\nfor key, values in d.items():\n result.append(([key]*len(values), values))\n\n",
"Use this list comprehension:\n[([k]*len(v), v) for k, v in D.iteritems()]\n\nHere's an example of it being used:\n>>> from pprint import pprint\n>>> D = {1: [1.2, 2.3, 4.9, 2.0], 2: [4.1, 5.1, 6.3], 3: [4.9, 6.8, 9.5, 1.1, 7.1]}\n>>> LL = [([k]*len(v), v) for k, v in D.iteritems()]\n>>> pprint(LL)\n[([1, 1, 1, 1], [1.2, 2.2999999999999998, 4.9000000000000004, 2.0]),\n ([2, 2, 2], [4.0999999999999996, 5.0999999999999996, 6.2999999999999998]),\n ([3, 3, 3, 3, 3],\n [4.9000000000000004,\n 6.7999999999999998,\n 9.5,\n 1.1000000000000001,\n 7.0999999999999996])]\n\n",
"As a list comprehension:\nr = [([k]*len(v), v) for k,v in d.items()]\n\nIf your dictionary is very large, you'd want to use a generator expression:\nfrom itertools import repeat\nr = ((repeat(k, len(v)), v) for k,v in d.iteritems())\n\n...though note that using repeat means that the first item in each tuple the generator returns is itself a generator. That's unnecessary if the dictionary's values don't themselves have many items.\n",
">>> d = {1 : [1.2, 2.3, 4.9, 2.0], 2 : [4.1, 5.1, 6.3], 3 : [4.9, 6.8, 9.5, 1.1, 7.1]}\n>>> result = [ ([k] * len(d[k]), d[k]) for k in d.keys() ]\n>>> print result\n[([1, 1, 1, 1], [1.2, 2.2999999999999998, 4.9000000000000004, 2.0]), ([2, 2, 2],\n[4.0999999999999996, 5.0999999999999996, 6.2999999999999998]), ([3, 3, 3, 3, 3],\n[4.9000000000000004, 6.7999999999999998, 9.5, 1.1000000000000001, 7.0999999999999996])]\n\n",
"I guess that a wizard will put something nicer, but I would do something like:\nmap(lambda x: ([x]*len(a[x]),a[x]),a)\n\nfor a tuple, or \nmap(lambda x: [[x]*len(a[x]),a[x]],a)\n\nfor a list.\nbtw: a is the dictionary, of course!\nI assume that you work with the 2.x series...\nRegards\n"
] |
[
13,
3,
2,
2,
2,
1,
0
] |
[
"the map function in python will allow this\nx = [1,2,4]\ny = [1,24,2]\nc = zip(x,y)\nprint c\nd = map(None,x,y)\nprint d\n\ncheck it out. This will give you\n[(1, 1), (2, 24), (4, 2)]\n\nIn the case of zip(), if one of the lists are smaller then the others, values will be truncated:\nx = [1,2,4]\na = [1,2,3,4,5]\nc = zip(x,a)\nprint c\nd = map(None,x,a)\nprint d\n\n[(1, 1), (2, 2), (4, 3)]\n[(1, 1), (2, 2), (4, 3), (None, 4), (None, 5)]\n\n"
] |
[
-1
] |
[
"python"
] |
stackoverflow_0001738392_python.txt
|
Q:
help!for function
I have post the similar question before,but this time the problem is different,I got stuck with the following code..can anyone help with it?thanks in advance
I have fixed mu code as suggested,thanks
from numpy import *
#vs,fs,rs are all m*n matrixs,got initial values in,i.e vs[0],fs[0],rs[0] are known
#want use this foor loop to update them
vs=zeros((10,3))
vs[0]=([1,2,3])
fs=zeros((10,3))
fs[0]=([2,3,4])
vs=zeros((10,3))
vs[0]=([3,4,5])
for i in range(5):
#start looping..
vs[i+1]=vs[i]+fs[i]
fs[i+1]=(rs[i]-re[i])
rs[i+1]=rs[i]+vs[i]
print vs,fs,rs
then this code gives vs,fs,rs in different i,but not update each rows of rs,fs,vs and return me a single array of rs,fs,vs (fully updated). whats the problem here?..what should I add?thanks
A:
Put your inizialization outside the loop! Right now, you're resetting the arrays to all zeros each time through the loop, over and over, which is absurd. You also appear to have a typo -- you set vs twice and rs never -- so I've tried to guess what you meant.
from numpy import *
#vs,fs,rs are all m*n matrixs,got initial values in,i.e vs[0],fs[0],rs[0] are known
#want use this foor loop to update them
vs=zeros((10,3))
vs[0]=([1,2,3])
fs=zeros((10,3))
fs[0]=([2,3,4])
rs=zeros((10,3))
rs[0]=([3,4,5])
for i in range(5):
#start looping..
vs[i+1]=vs[i]+fs[i]
fs[i+1]=rs[i]-re[i]
rs[i+1]=rs[i]+vs[i]
print vs,fs,rs
A:
You do not start looping where the comment indicates it, but at the for i in range(5): line. Everything in the indented block (the "body of the for-loop") is done repeatedly for each i. So setting vs and fs to zero is done repeatedly, each time deleting what was calculated before. These initializations should be done before the for.
Also vs is initialized twice while rs isn't initialized at all, probably that's a typo and it should look like this:
vs=zeros((10,3))
vs[0]=([1,2,3])
fs=zeros((10,3))
fs[0]=([2,3,4])
rs=zeros((10,3))
rs[0]=([3,4,5])
for i in range(5):
#start looping..
...
A:
I don't know exactly what you want to print. If you want to print every matrix every time it is updated, then you're fine. But if you want to print the matrices after all the updates have been completed, then you should bring that print statement out of the for loop.
This and what Alex and sth have said should fix your code fully
|
help!for function
|
I have post the similar question before,but this time the problem is different,I got stuck with the following code..can anyone help with it?thanks in advance
I have fixed mu code as suggested,thanks
from numpy import *
#vs,fs,rs are all m*n matrixs,got initial values in,i.e vs[0],fs[0],rs[0] are known
#want use this foor loop to update them
vs=zeros((10,3))
vs[0]=([1,2,3])
fs=zeros((10,3))
fs[0]=([2,3,4])
vs=zeros((10,3))
vs[0]=([3,4,5])
for i in range(5):
#start looping..
vs[i+1]=vs[i]+fs[i]
fs[i+1]=(rs[i]-re[i])
rs[i+1]=rs[i]+vs[i]
print vs,fs,rs
then this code gives vs,fs,rs in different i,but not update each rows of rs,fs,vs and return me a single array of rs,fs,vs (fully updated). whats the problem here?..what should I add?thanks
|
[
"Put your inizialization outside the loop! Right now, you're resetting the arrays to all zeros each time through the loop, over and over, which is absurd. You also appear to have a typo -- you set vs twice and rs never -- so I've tried to guess what you meant.\nfrom numpy import *\n\n#vs,fs,rs are all m*n matrixs,got initial values in,i.e vs[0],fs[0],rs[0] are known\n#want use this foor loop to update them\nvs=zeros((10,3))\nvs[0]=([1,2,3])\nfs=zeros((10,3))\nfs[0]=([2,3,4])\nrs=zeros((10,3))\nrs[0]=([3,4,5])\n\nfor i in range(5):\n #start looping..\n vs[i+1]=vs[i]+fs[i]\n fs[i+1]=rs[i]-re[i]\n rs[i+1]=rs[i]+vs[i]\n print vs,fs,rs\n\n",
"You do not start looping where the comment indicates it, but at the for i in range(5): line. Everything in the indented block (the \"body of the for-loop\") is done repeatedly for each i. So setting vs and fs to zero is done repeatedly, each time deleting what was calculated before. These initializations should be done before the for.\nAlso vs is initialized twice while rs isn't initialized at all, probably that's a typo and it should look like this:\nvs=zeros((10,3))\nvs[0]=([1,2,3])\nfs=zeros((10,3))\nfs[0]=([2,3,4])\nrs=zeros((10,3))\nrs[0]=([3,4,5])\n\nfor i in range(5):\n #start looping..\n ...\n\n",
"I don't know exactly what you want to print. If you want to print every matrix every time it is updated, then you're fine. But if you want to print the matrices after all the updates have been completed, then you should bring that print statement out of the for loop.\nThis and what Alex and sth have said should fix your code fully\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001738362_python.txt
|
Q:
How to read this file using Python?
I have a DNA file in the following format:
>gi|5524211|gb|AAD44166.1| cytochrome
ACCAGAGCGGCACAGCAGCGACATCAGCACTAGCACTAGCATCAGCATCAGCATCAGC
CTACATCATCACAGCAGCATCAGCATCGACATCAGCATCAGCATCAGCATCGACGACT
ACACCCCCCCCGGTGTGTGTGGGGGGTTAAAAATGATGAGTGATGAGTGAGTTGTGTG
CTACATCATCACAGCAGCATCAGCATCGACATCAGCATCAGCATCAGCATCGACGACT
TTCTATCATCATTCGGCGGGGGGATATATTATAGCGCGCGATTATTGCGCAGTCTACG
TCATCGACTACGATCAGCATCAGCATCAGCATCAGCATCGACTAGCATCAGCTACGAC
How do I read this file and extract the DNA sequence part (ACCAGAGCGG...) without any newlines, for example:
ACCAGAGCGGCACAGCAGCGACATCAGCACTAGCACTAGCATCAGCATCAGCATCAGCCTACATCATCACAGCAGCATCA
Maybe regex isn't needed?
A:
If there's always only one line of header :
dnalines = text.split('\n')[1:]
dna = ''.join(dnalines)
With text = the contents of your file (for example, text = open('yourfile').read())
A:
I did some tests, and it appears that the following is more efficient than delroth's answer:
text.split('\n', 1)[1].replace('\n', '')
Edit: wait, it's not so simple. I timed both methods, twice, using Python 2.6.4 and 3.1.1, on an ~30MB file:
Python 2.6.4, my version:
$ python -m timeit -c "open('x').read().split('\n', 1)[1].replace('\n', '')"
10 loops, best of 3: 221 msec per loop
$ python -m timeit -c "open('x').read().split('\n', 1)[1].replace('\n', '')"
10 loops, best of 3: 219 msec per loop
Python 2.6.4, delroth's version:
$ python -m timeit -c "''.join(open('x').read().split('\n')[1:])"
10 loops, best of 3: 392 msec per loop
$ python -m timeit -c "''.join(open('x').read().split('\n')[1:])"
10 loops, best of 3: 390 msec per loop
Python 3.1.1, my version:
$ python3 -m timeit -c "open('x').read().split('\n', 1)[1].replace('\n', '')"
10 loops, best of 3: 803 msec per loop
$ python3 -m timeit -c "open('x').read().split('\n', 1)[1].replace('\n', '')"
10 loops, best of 3: 798 msec per loop
Python 3.1.1, delroth's version:
$ python3 -m timeit -c "''.join(open('x').read().split('\n')[1:])"
10 loops, best of 3: 610 msec per loop
$ python3 -m timeit -c "''.join(open('x').read().split('\n')[1:])"
10 loops, best of 3: 610 msec per loop
Conclusion: Python 3 is much slower, and it depends on the Python version which of the two code snippets is faster!
|
How to read this file using Python?
|
I have a DNA file in the following format:
>gi|5524211|gb|AAD44166.1| cytochrome
ACCAGAGCGGCACAGCAGCGACATCAGCACTAGCACTAGCATCAGCATCAGCATCAGC
CTACATCATCACAGCAGCATCAGCATCGACATCAGCATCAGCATCAGCATCGACGACT
ACACCCCCCCCGGTGTGTGTGGGGGGTTAAAAATGATGAGTGATGAGTGAGTTGTGTG
CTACATCATCACAGCAGCATCAGCATCGACATCAGCATCAGCATCAGCATCGACGACT
TTCTATCATCATTCGGCGGGGGGATATATTATAGCGCGCGATTATTGCGCAGTCTACG
TCATCGACTACGATCAGCATCAGCATCAGCATCAGCATCGACTAGCATCAGCTACGAC
How do I read this file and extract the DNA sequence part (ACCAGAGCGG...) without any newlines, for example:
ACCAGAGCGGCACAGCAGCGACATCAGCACTAGCACTAGCATCAGCATCAGCATCAGCCTACATCATCACAGCAGCATCA
Maybe regex isn't needed?
|
[
"If there's always only one line of header :\ndnalines = text.split('\\n')[1:]\ndna = ''.join(dnalines)\n\nWith text = the contents of your file (for example, text = open('yourfile').read())\n",
"I did some tests, and it appears that the following is more efficient than delroth's answer:\ntext.split('\\n', 1)[1].replace('\\n', '')\n\nEdit: wait, it's not so simple. I timed both methods, twice, using Python 2.6.4 and 3.1.1, on an ~30MB file:\n\nPython 2.6.4, my version:\n$ python -m timeit -c \"open('x').read().split('\\n', 1)[1].replace('\\n', '')\"\n10 loops, best of 3: 221 msec per loop\n$ python -m timeit -c \"open('x').read().split('\\n', 1)[1].replace('\\n', '')\"\n10 loops, best of 3: 219 msec per loop\n\nPython 2.6.4, delroth's version:\n$ python -m timeit -c \"''.join(open('x').read().split('\\n')[1:])\"\n10 loops, best of 3: 392 msec per loop\n$ python -m timeit -c \"''.join(open('x').read().split('\\n')[1:])\"\n10 loops, best of 3: 390 msec per loop\n\nPython 3.1.1, my version:\n$ python3 -m timeit -c \"open('x').read().split('\\n', 1)[1].replace('\\n', '')\"\n10 loops, best of 3: 803 msec per loop\n$ python3 -m timeit -c \"open('x').read().split('\\n', 1)[1].replace('\\n', '')\"\n10 loops, best of 3: 798 msec per loop\n\nPython 3.1.1, delroth's version:\n$ python3 -m timeit -c \"''.join(open('x').read().split('\\n')[1:])\"\n10 loops, best of 3: 610 msec per loop\n$ python3 -m timeit -c \"''.join(open('x').read().split('\\n')[1:])\"\n10 loops, best of 3: 610 msec per loop\n\n\nConclusion: Python 3 is much slower, and it depends on the Python version which of the two code snippets is faster!\n"
] |
[
8,
3
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0001738524_python_regex.txt
|
Q:
Algorithm to Divide a list of numbers into 2 equal sum lists
There is a list of numbers.
The list is to be divided into 2 equal sized lists, with a minimal difference in sum. The sums have to be printed.
#Example:
>>>que = [2,3,10,5,8,9,7,3,5,2]
>>>make_teams(que)
27 27
Is there an error in the following code algorithm for some case?
How do I optimize and/or pythonize this?
def make_teams(que):
que.sort()
if len(que)%2: que.insert(0,0)
t1,t2 = [],[]
while que:
val = (que.pop(), que.pop())
if sum(t1)>sum(t2):
t2.append(val[0])
t1.append(val[1])
else:
t1.append(val[0])
t2.append(val[1])
print min(sum(t1),sum(t2)), max(sum(t1),sum(t2)), "\n"
Question is from http://www.codechef.com/problems/TEAMSEL/
A:
Dynamic programming is the solution you're looking for.
Example with [4, 3, 10, 3, 2, 5]:
X-Axis: Reachable sum of group. max = sum(all numbers) / 2 (rounded up)
Y-Axis: Count elements in group. max = count numbers / 2 (rounded up)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
1 | | | | 4| | | | | | | | | | | // 4
2 | | | | | | | | | | | | | | |
3 | | | | | | | | | | | | | | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14
1 | | | 3| 4| | | | | | | | | | | // 3
2 | | | | | | | 3| | | | | | | |
3 | | | | | | | | | | | | | | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14
1 | | | 3| 4| | | | | |10| | | | | // 10
2 | | | | | | | 3| | | | | |10|10|
3 | | | | | | | | | | | | | | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14
1 | | | 3| 4| | | | | |10| | | | | // 3
2 | | | | | | 3| 3| | | | | |10|10|
3 | | | | | | | | | | 3| | | | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14
1 | | 2| 3| 4| | | | | |10| | | | | // 2
2 | | | | | 2| 3| 3| | | | | 2|10|10|
3 | | | | | | | | 2| 2| 3| | | | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14
1 | | 2| 3| 4| 5| | | | |10| | | | | // 5
2 | | | | | 2| 3| 3| 5| 5| | | 2|10|10|
3 | | | | | | | | 2| 2| 3| 5| 5| | |
^
12 is our lucky number! Backtracing to get the group:
12 - 5 = 7 {5}
7 - 3 = 4 {5, 3}
4 - 4 = 0 {5, 3, 4}
The other set can then be calculated: {4,3,10,3,2,5} - {5,3,4} = {10,3,2}
All fields with a number are possible solutions for one bag. Choose the one that is furthest in the bottom right corner.
BTW: It's called the knapsack-problem.
If all weights (w1, ..., wn and W) are
nonnegative integers, the knapsack
problem can be solved in
pseudo-polynomial time using dynamic
programming.
A:
New Solution
This is a breadth-first search with heuristics culling. The tree is limited to a depth of players/2. The player sum limit is totalscores/2. With a player pool of 100, it took approximately 10 seconds to solve.
def team(t):
iterations = range(2, len(t)/2+1)
totalscore = sum(t)
halftotalscore = totalscore/2.0
oldmoves = {}
for p in t:
people_left = t[:]
people_left.remove(p)
oldmoves[p] = people_left
if iterations == []:
solution = min(map(lambda i: (abs(float(i)-halftotalscore), i), oldmoves.keys()))
return (solution[1], sum(oldmoves[solution[1]]), oldmoves[solution[1]])
for n in iterations:
newmoves = {}
for total, roster in oldmoves.iteritems():
for p in roster:
people_left = roster[:]
people_left.remove(p)
newtotal = total+p
if newtotal > halftotalscore: continue
newmoves[newtotal] = people_left
oldmoves = newmoves
solution = min(map(lambda i: (abs(float(i)-halftotalscore), i), oldmoves.keys()))
return (solution[1], sum(oldmoves[solution[1]]), oldmoves[solution[1]])
print team([90,200,100])
print team([2,3,10,5,8,9,7,3,5,2])
print team([1,1,1,1,1,1,1,1,1,9])
print team([87,100,28,67,68,41,67,1])
print team([1, 1, 50, 50, 50, 1000])
#output
#(200, 190, [90, 100])
#(27, 27, [3, 9, 7, 3, 5])
#(5, 13, [1, 1, 1, 1, 9])
#(229, 230, [28, 67, 68, 67])
#(150, 1002, [1, 1, 1000])
Also note that I attempted to solve this using GS's description, but it is impossible to get enough information simply by storing the running totals. And if you stored both the number of items and totals, then it would be the same as this solution except you kept needless data. Because you only need to keep the n-1 and n iterations up to numplayers/2.
I had an old exhaustive one based on binomial coefficients (look in history). It solved the example problems of length 10 just fine, but then I saw that the competition had people of up to length 100.
A:
Q. Given a multiset S of integers, is there a way to partition S into two subsets S1 and S2 such that the sum of the numbers in S1 equals the sum of the numbers in S2?
A.Set Partition Problem.
Best of luck approximating. : )
A:
Well, you can find a solution to a percentage precision in polynomial time, but to actually find the optimal (absolute minimal difference) solution, the problem is NP-complete. This means that there is no polynomial time solution to the problem. As a result, even with a relatively small list of numbers, it is too compute intensive to solve. If you really need a solution, take a look at some of the approximation algorithms for this.
http://en.wikipedia.org/wiki/Subset_sum_problem
A:
Note that it is also an heuristic and I moved the sort out of the function.
def g(data):
sums = [0, 0]
for pair in zip(data[::2], data[1::2]):
item1, item2 = sorted(pair)
sums = sorted([sums[0] + item2, sums[1] + item1])
print sums
data = sorted([2,3,10,5,8,9,7,3,5,2])
g(data)
A:
A test case where your method doesn't work is
que = [1, 1, 50, 50, 50, 1000]
The problem is that you're analyzing things in pairs, and in this example, you want all the 50's to be in the same group. This should be solved though if you remove the pair analysis aspect and just do one entry at a time.
Here's the code that does this
def make_teams(que):
que.sort()
que.reverse()
if len(que)%2: que.insert(0,0)
t1,t2 = [],[]
while que:
if abs(len(t1)-len(t2))>=len(que):
[t1, t2][len(t1)>len(t2)].append(que.pop(0))
else:
[t1, t2][sum(t1)>sum(t2)].append(que.pop(0))
print min(sum(t1),sum(t2)), max(sum(t1),sum(t2)), "\n"
if __name__=="__main__":
que = [2,3,10,5,8,9,7,3,5,2]
make_teams(que)
que = [1, 1, 50, 50, 50, 1000]
make_teams(que)
This give 27, 27 and 150, 1002 which are the answers that make sense to me.
Edit: In review, I find this to not actually work, though in the end, I'm not quite sure why. I'll post my test code here though, as it might be useful. The test just generates random sequence that have equal sums, puts these together and compares (with sad results).
Edit #2: Based in the example pointed out by Unknown, [87,100,28,67,68,41,67,1], it's clear why my method doesn't work. Specifically, to solve this example, the two largest numbers need to both be added to the same sequence to get a valid solution.
def make_sequence():
"""return the sums and the sequence that's devided to make this sum"""
while 1:
seq_len = randint(5, 200)
seq_max = [5, 10, 100, 1000, 1000000][randint(0,4)]
seqs = [[], []]
for i in range(seq_len):
for j in (0, 1):
seqs[j].append(randint(1, seq_max))
diff = sum(seqs[0])-sum(seqs[1])
if abs(diff)>=seq_max:
continue
if diff<0:
seqs[0][-1] += -diff
else:
seqs[1][-1] += diff
return sum(seqs[0]), sum(seqs[1]), seqs[0], seqs[1]
if __name__=="__main__":
for i in range(10):
s0, s1, seq0, seq1 = make_sequence()
t0, t1 = make_teams(seq0+seq1)
print s0, s1, t0, t1
if s0 != t0 or s1 != t1:
print "FAILURE", s0, s1, t0, t1
A:
It's actually PARTITION, a special case of KNAPSACK.
It is NP Complete, with pseudo-polynomial dp algorithms. The pseudo in pseudo-polynomial refers to the fact that the run time depends on the range of the weights.
In general you will have to first decide if there is an exact solution before you can admit a heuristic solution.
A:
They are obviously looking for a dynamic programming knapsack solution. So after my first effort (a pretty good original heuristic I thought), and my second effort (a really sneaky exact combinatorial solution that worked for shortish data sets, and even for sets up to 100 elements as long as the number of unique values was low), I finally succumbed to peer pressure and wrote the one they wanted (not too hard - handling duplicated entries was the trickiest part - the underlying algorithm I based it on only works if all the inputs are unique - I'm sure glad that long long is big enough to hold 50 bits!).
So for all the test data and awkward edge cases I put together while testing my first two efforts, it gives the same answer. At least for the ones I checked with the combinatorial solver, I know they're correct. But I'm still failing the submission with some wrong answer!
I'm not asking for anyone to fix my code here, but I would be very greatful if anyone can find a case for which the code below generates the wrong answer.
Thanks,
Graham
PS This code does always execute within the time limit but it is far from optimised. i'm keeping it simple until it passes the test, then I have some ideas to speed it up, maybe by a factor of 10 or more.
#include <stdio.h>
#define TRUE (0==0)
#define FALSE (0!=0)
static int debug = TRUE;
//int simple(const void *a, const void *b) {
// return *(int *)a - *(int *)b;
//}
int main(int argc, char **argv) {
int p[101];
char *s, line[128];
long long mask, c0[45001], c1[45001];
int skill, players, target, i, j, tests, total = 0;
debug = (argc == 2 && argv[1][0] == '-' && argv[1][1] == 'd' && argv[1][2] == '\0');
s = fgets(line, 127, stdin);
tests = atoi(s);
while (tests --> 0) {
for (i = 0; i < 45001; i++) {c0[i] = 0LL;}
s = fgets(line, 127, stdin); /* blank line */
s = fgets(line, 127, stdin); /* no of players */
players = atoi(s);
for (i = 0; i < players; i++) {s = fgets(line, 127, stdin); p[i] = atoi(s);}
if (players == 1) {
printf("0 %d\n", p[0]);
} else {
if (players&1) p[players++] = 0; // odd player fixed by adding a single player of 0 strength
//qsort(p, players, sizeof(int), simple);
total = 0; for ( i = 0; i < players; i++) total += p[i];
target = total/2; // ok if total was odd and result rounded down - teams of n, n+1
mask = 1LL << (((long long)players/2LL)-1LL);
for (i = 0; i < players; i++) {
for (j = 0; j <= target; j++) {c1[j] = 0LL;} // memset would be faster
skill = p[i];
//add this player to every other player and every partial subset
for (j = 0; j <= target-skill; j++) {
if (c0[j]) c1[j+skill] = c0[j]<<1; // highest = highest j+skill for later optimising
}
c0[skill] |= 1; // so we don't add a skill number to itself unless it occurs more than once
for (j = 0; j <= target; j++) {c0[j] |= c1[j];}
if (c0[target]&mask) break; // early return for perfect fit!
}
for (i = target; i > 0; i--) {
if (debug || (c0[i] & mask)) {
fprintf(stdout, "%d %d\n", i, total-i);
if (debug) {
if (c0[i] & mask) printf("******** ["); else
printf(" [");
for (j = 0; j <= players; j++) if (c0[i] & (1LL<<(long long)j)) printf(" %d", j+1);
printf(" ]\n");
} else break;
}
}
}
if (tests) printf("\n");
}
return 0;
}
A:
class Team(object):
def __init__(self):
self.members = []
self.total = 0
def add(self, m):
self.members.append(m)
self.total += m
def __cmp__(self, other):
return cmp(self.total, other.total)
def make_teams(ns):
ns.sort(reverse = True)
t1, t2 = Team(), Team()
for n in ns:
t = t1 if t1 < t2 else t2
t.add(n)
return t1, t2
if __name__ == "__main__":
import sys
t1, t2 = make_teams([int(s) for s in sys.argv[1:]])
print t1.members, sum(t1.members)
print t2.members, sum(t2.members)
>python two_piles.py 1 50 50 100
[50, 50] 100
[100, 1] 101
A:
For performance you save computations by replacing append() and sum() with running totals.
A:
You could tighten your loop up a little by using the following:
def make_teams(que):
que.sort()
t1, t2 = []
while que:
t1.append(que.pop())
if sum(t1) > sum(t2):
t2, t1 = t1, t2
print min(sum(t1),sum(t2)), max(sum(t1),sum(t2))
A:
Since the lists must me equal the problem isn't NP at all.
I split the sorted list with the pattern t1<-que(1st, last), t2<-que(2nd, last-1) ...
def make_teams2(que):
que.sort()
if len(que)%2: que.insert(0,0)
t1 = []
t2 = []
while que:
if len(que) > 2:
t1.append(que.pop(0))
t1.append(que.pop())
t2.append(que.pop(0))
t2.append(que.pop())
else:
t1.append(que.pop(0))
t2.append(que.pop())
print sum(t1), sum(t2), "\n"
Edit: I suppose that this is also a wrong method. Wrong results!
A:
After some thinking, for not too big problem, I think that the best kind of heuristics will be something like:
import random
def f(data, nb_iter=20):
diff = None
sums = (None, None)
for _ in xrange(nb_iter):
random.shuffle(data)
mid = len(data)/2
sum1 = sum(data[:mid])
sum2 = sum(data[mid:])
if diff is None or abs(sum1 - sum2) < diff:
sums = (sum1, sum2)
print sums
You can adjust nb_iter if the problem is bigger.
It solves all the problem mentioned above mostly all the times.
A:
In an earlier comment I hypothesized that the problem as set was tractable because they had carefully chosen the test data to be compatible with various algorithms within the time alloted. This turned out not to be the case - instead it is the problem constraints - numbers no higher than 450 and a final set no larger than 50 numbers is the key. These are compatible with solving the problem using the dynamic programming solution I put up in a later post. None of the other algorithms (heuristics, or exhaustive enumeration by a combinatorial pattern generator) can possibly work because there will be test cases large enough or hard enough to break those algorithms. It's rather annoying to be honest because those other solutions are more challenging and certainly more fun. Note that without a lot of extra work, the dynamic programming solution just says whether a solution is possible with N/2 for any given sum, but it doesn't tell you the contents of either partition.
|
Algorithm to Divide a list of numbers into 2 equal sum lists
|
There is a list of numbers.
The list is to be divided into 2 equal sized lists, with a minimal difference in sum. The sums have to be printed.
#Example:
>>>que = [2,3,10,5,8,9,7,3,5,2]
>>>make_teams(que)
27 27
Is there an error in the following code algorithm for some case?
How do I optimize and/or pythonize this?
def make_teams(que):
que.sort()
if len(que)%2: que.insert(0,0)
t1,t2 = [],[]
while que:
val = (que.pop(), que.pop())
if sum(t1)>sum(t2):
t2.append(val[0])
t1.append(val[1])
else:
t1.append(val[0])
t2.append(val[1])
print min(sum(t1),sum(t2)), max(sum(t1),sum(t2)), "\n"
Question is from http://www.codechef.com/problems/TEAMSEL/
|
[
"Dynamic programming is the solution you're looking for.\nExample with [4, 3, 10, 3, 2, 5]:\n\nX-Axis: Reachable sum of group. max = sum(all numbers) / 2 (rounded up)\nY-Axis: Count elements in group. max = count numbers / 2 (rounded up)\n\n 1 2 3 4 5 6 7 8 9 10 11 12 13 14\n 1 | | | | 4| | | | | | | | | | | // 4\n 2 | | | | | | | | | | | | | | |\n 3 | | | | | | | | | | | | | | |\n\n\n 1 2 3 4 5 6 7 8 9 10 11 12 13 14\n 1 | | | 3| 4| | | | | | | | | | | // 3\n 2 | | | | | | | 3| | | | | | | |\n 3 | | | | | | | | | | | | | | |\n\n\n 1 2 3 4 5 6 7 8 9 10 11 12 13 14\n 1 | | | 3| 4| | | | | |10| | | | | // 10\n 2 | | | | | | | 3| | | | | |10|10|\n 3 | | | | | | | | | | | | | | |\n\n\n 1 2 3 4 5 6 7 8 9 10 11 12 13 14\n 1 | | | 3| 4| | | | | |10| | | | | // 3\n 2 | | | | | | 3| 3| | | | | |10|10|\n 3 | | | | | | | | | | 3| | | | |\n\n\n 1 2 3 4 5 6 7 8 9 10 11 12 13 14\n 1 | | 2| 3| 4| | | | | |10| | | | | // 2\n 2 | | | | | 2| 3| 3| | | | | 2|10|10|\n 3 | | | | | | | | 2| 2| 3| | | | |\n\n\n 1 2 3 4 5 6 7 8 9 10 11 12 13 14\n 1 | | 2| 3| 4| 5| | | | |10| | | | | // 5\n 2 | | | | | 2| 3| 3| 5| 5| | | 2|10|10|\n 3 | | | | | | | | 2| 2| 3| 5| 5| | |\n ^\n\n12 is our lucky number! Backtracing to get the group:\n\n12 - 5 = 7 {5}\n 7 - 3 = 4 {5, 3}\n 4 - 4 = 0 {5, 3, 4}\n\nThe other set can then be calculated: {4,3,10,3,2,5} - {5,3,4} = {10,3,2}\nAll fields with a number are possible solutions for one bag. Choose the one that is furthest in the bottom right corner.\nBTW: It's called the knapsack-problem.\n\nIf all weights (w1, ..., wn and W) are\n nonnegative integers, the knapsack\n problem can be solved in\n pseudo-polynomial time using dynamic\n programming.\n\n",
"New Solution\nThis is a breadth-first search with heuristics culling. The tree is limited to a depth of players/2. The player sum limit is totalscores/2. With a player pool of 100, it took approximately 10 seconds to solve.\ndef team(t):\n iterations = range(2, len(t)/2+1)\n\n totalscore = sum(t)\n halftotalscore = totalscore/2.0\n\n oldmoves = {}\n\n for p in t:\n people_left = t[:]\n people_left.remove(p)\n oldmoves[p] = people_left\n\n if iterations == []:\n solution = min(map(lambda i: (abs(float(i)-halftotalscore), i), oldmoves.keys()))\n return (solution[1], sum(oldmoves[solution[1]]), oldmoves[solution[1]])\n\n for n in iterations:\n newmoves = {}\n for total, roster in oldmoves.iteritems():\n for p in roster:\n people_left = roster[:]\n people_left.remove(p)\n newtotal = total+p\n if newtotal > halftotalscore: continue\n newmoves[newtotal] = people_left\n oldmoves = newmoves\n\n solution = min(map(lambda i: (abs(float(i)-halftotalscore), i), oldmoves.keys()))\n return (solution[1], sum(oldmoves[solution[1]]), oldmoves[solution[1]])\n\nprint team([90,200,100])\nprint team([2,3,10,5,8,9,7,3,5,2])\nprint team([1,1,1,1,1,1,1,1,1,9])\nprint team([87,100,28,67,68,41,67,1])\nprint team([1, 1, 50, 50, 50, 1000])\n\n#output\n#(200, 190, [90, 100])\n#(27, 27, [3, 9, 7, 3, 5])\n#(5, 13, [1, 1, 1, 1, 9])\n#(229, 230, [28, 67, 68, 67])\n#(150, 1002, [1, 1, 1000])\n\nAlso note that I attempted to solve this using GS's description, but it is impossible to get enough information simply by storing the running totals. And if you stored both the number of items and totals, then it would be the same as this solution except you kept needless data. Because you only need to keep the n-1 and n iterations up to numplayers/2.\nI had an old exhaustive one based on binomial coefficients (look in history). It solved the example problems of length 10 just fine, but then I saw that the competition had people of up to length 100.\n",
"Q. Given a multiset S of integers, is there a way to partition S into two subsets S1 and S2 such that the sum of the numbers in S1 equals the sum of the numbers in S2? \nA.Set Partition Problem.\nBest of luck approximating. : )\n",
"Well, you can find a solution to a percentage precision in polynomial time, but to actually find the optimal (absolute minimal difference) solution, the problem is NP-complete. This means that there is no polynomial time solution to the problem. As a result, even with a relatively small list of numbers, it is too compute intensive to solve. If you really need a solution, take a look at some of the approximation algorithms for this. \nhttp://en.wikipedia.org/wiki/Subset_sum_problem \n",
"Note that it is also an heuristic and I moved the sort out of the function.\n def g(data):\n sums = [0, 0]\n for pair in zip(data[::2], data[1::2]):\n item1, item2 = sorted(pair)\n sums = sorted([sums[0] + item2, sums[1] + item1])\n print sums\n\ndata = sorted([2,3,10,5,8,9,7,3,5,2])\ng(data)\n\n",
"A test case where your method doesn't work is \nque = [1, 1, 50, 50, 50, 1000]\n\nThe problem is that you're analyzing things in pairs, and in this example, you want all the 50's to be in the same group. This should be solved though if you remove the pair analysis aspect and just do one entry at a time.\nHere's the code that does this\ndef make_teams(que):\n que.sort()\n que.reverse()\n if len(que)%2: que.insert(0,0)\n t1,t2 = [],[]\n while que:\n if abs(len(t1)-len(t2))>=len(que):\n [t1, t2][len(t1)>len(t2)].append(que.pop(0))\n else:\n [t1, t2][sum(t1)>sum(t2)].append(que.pop(0))\n print min(sum(t1),sum(t2)), max(sum(t1),sum(t2)), \"\\n\"\n\nif __name__==\"__main__\":\n que = [2,3,10,5,8,9,7,3,5,2]\n make_teams(que)\n que = [1, 1, 50, 50, 50, 1000]\n make_teams(que)\n\nThis give 27, 27 and 150, 1002 which are the answers that make sense to me.\nEdit: In review, I find this to not actually work, though in the end, I'm not quite sure why. I'll post my test code here though, as it might be useful. The test just generates random sequence that have equal sums, puts these together and compares (with sad results).\nEdit #2: Based in the example pointed out by Unknown, [87,100,28,67,68,41,67,1], it's clear why my method doesn't work. Specifically, to solve this example, the two largest numbers need to both be added to the same sequence to get a valid solution.\ndef make_sequence():\n \"\"\"return the sums and the sequence that's devided to make this sum\"\"\"\n while 1:\n seq_len = randint(5, 200)\n seq_max = [5, 10, 100, 1000, 1000000][randint(0,4)]\n seqs = [[], []]\n for i in range(seq_len):\n for j in (0, 1):\n seqs[j].append(randint(1, seq_max))\n diff = sum(seqs[0])-sum(seqs[1])\n if abs(diff)>=seq_max: \n continue\n if diff<0:\n seqs[0][-1] += -diff\n else:\n seqs[1][-1] += diff\n return sum(seqs[0]), sum(seqs[1]), seqs[0], seqs[1]\n\nif __name__==\"__main__\":\n\n for i in range(10):\n s0, s1, seq0, seq1 = make_sequence()\n t0, t1 = make_teams(seq0+seq1)\n print s0, s1, t0, t1\n if s0 != t0 or s1 != t1:\n print \"FAILURE\", s0, s1, t0, t1\n\n",
"It's actually PARTITION, a special case of KNAPSACK. \nIt is NP Complete, with pseudo-polynomial dp algorithms. The pseudo in pseudo-polynomial refers to the fact that the run time depends on the range of the weights.\nIn general you will have to first decide if there is an exact solution before you can admit a heuristic solution.\n",
"They are obviously looking for a dynamic programming knapsack solution. So after my first effort (a pretty good original heuristic I thought), and my second effort (a really sneaky exact combinatorial solution that worked for shortish data sets, and even for sets up to 100 elements as long as the number of unique values was low), I finally succumbed to peer pressure and wrote the one they wanted (not too hard - handling duplicated entries was the trickiest part - the underlying algorithm I based it on only works if all the inputs are unique - I'm sure glad that long long is big enough to hold 50 bits!).\nSo for all the test data and awkward edge cases I put together while testing my first two efforts, it gives the same answer. At least for the ones I checked with the combinatorial solver, I know they're correct. But I'm still failing the submission with some wrong answer!\nI'm not asking for anyone to fix my code here, but I would be very greatful if anyone can find a case for which the code below generates the wrong answer.\nThanks,\nGraham\nPS This code does always execute within the time limit but it is far from optimised. i'm keeping it simple until it passes the test, then I have some ideas to speed it up, maybe by a factor of 10 or more.\n\n#include <stdio.h>\n\n#define TRUE (0==0)\n#define FALSE (0!=0)\n\nstatic int debug = TRUE;\n\n//int simple(const void *a, const void *b) {\n// return *(int *)a - *(int *)b;\n//}\n\nint main(int argc, char **argv) {\n int p[101];\n char *s, line[128];\n long long mask, c0[45001], c1[45001];\n int skill, players, target, i, j, tests, total = 0;\n\n debug = (argc == 2 && argv[1][0] == '-' && argv[1][1] == 'd' && argv[1][2] == '\\0');\n\n s = fgets(line, 127, stdin);\n tests = atoi(s);\n while (tests --> 0) {\n\n for (i = 0; i < 45001; i++) {c0[i] = 0LL;}\n\n s = fgets(line, 127, stdin); /* blank line */\n s = fgets(line, 127, stdin); /* no of players */\n players = atoi(s);\n for (i = 0; i < players; i++) {s = fgets(line, 127, stdin); p[i] = atoi(s);}\n\n if (players == 1) {\n printf(\"0 %d\\n\", p[0]);\n } else {\n\n if (players&1) p[players++] = 0; // odd player fixed by adding a single player of 0 strength\n //qsort(p, players, sizeof(int), simple);\n\n total = 0; for ( i = 0; i < players; i++) total += p[i];\n target = total/2; // ok if total was odd and result rounded down - teams of n, n+1\n mask = 1LL << (((long long)players/2LL)-1LL);\n\n for (i = 0; i < players; i++) {\n for (j = 0; j <= target; j++) {c1[j] = 0LL;} // memset would be faster\n skill = p[i];\n //add this player to every other player and every partial subset\n for (j = 0; j <= target-skill; j++) {\n if (c0[j]) c1[j+skill] = c0[j]<<1; // highest = highest j+skill for later optimising\n }\n c0[skill] |= 1; // so we don't add a skill number to itself unless it occurs more than once\n for (j = 0; j <= target; j++) {c0[j] |= c1[j];}\n if (c0[target]&mask) break; // early return for perfect fit!\n }\n\n for (i = target; i > 0; i--) {\n if (debug || (c0[i] & mask)) {\n fprintf(stdout, \"%d %d\\n\", i, total-i);\n if (debug) {\n if (c0[i] & mask) printf(\"******** [\"); else\n printf(\" [\");\n for (j = 0; j <= players; j++) if (c0[i] & (1LL<<(long long)j)) printf(\" %d\", j+1);\n printf(\" ]\\n\");\n } else break;\n }\n }\n }\n if (tests) printf(\"\\n\");\n }\n return 0;\n}\n\n",
"class Team(object):\n def __init__(self):\n self.members = []\n self.total = 0\n\n def add(self, m):\n self.members.append(m)\n self.total += m\n\n def __cmp__(self, other):\n return cmp(self.total, other.total)\n\n\ndef make_teams(ns):\n ns.sort(reverse = True)\n t1, t2 = Team(), Team()\n\n for n in ns:\n t = t1 if t1 < t2 else t2\n t.add(n)\n\n return t1, t2\n\nif __name__ == \"__main__\":\n import sys\n t1, t2 = make_teams([int(s) for s in sys.argv[1:]])\n print t1.members, sum(t1.members)\n print t2.members, sum(t2.members)\n\n>python two_piles.py 1 50 50 100\n[50, 50] 100\n[100, 1] 101\n\n",
"For performance you save computations by replacing append() and sum() with running totals.\n",
"You could tighten your loop up a little by using the following:\ndef make_teams(que):\n que.sort()\n t1, t2 = []\n while que:\n t1.append(que.pop())\n if sum(t1) > sum(t2):\n t2, t1 = t1, t2\n print min(sum(t1),sum(t2)), max(sum(t1),sum(t2))\n\n",
"Since the lists must me equal the problem isn't NP at all.\nI split the sorted list with the pattern t1<-que(1st, last), t2<-que(2nd, last-1) ...\ndef make_teams2(que):\n que.sort()\n if len(que)%2: que.insert(0,0)\n t1 = []\n t2 = []\n while que:\n if len(que) > 2:\n t1.append(que.pop(0))\n t1.append(que.pop())\n t2.append(que.pop(0))\n t2.append(que.pop())\n else:\n t1.append(que.pop(0))\n t2.append(que.pop())\n print sum(t1), sum(t2), \"\\n\"\n\nEdit: I suppose that this is also a wrong method. Wrong results!\n",
"After some thinking, for not too big problem, I think that the best kind of heuristics will be something like:\nimport random\ndef f(data, nb_iter=20):\n diff = None\n sums = (None, None)\n for _ in xrange(nb_iter):\n random.shuffle(data)\n mid = len(data)/2\n sum1 = sum(data[:mid])\n sum2 = sum(data[mid:])\n if diff is None or abs(sum1 - sum2) < diff:\n sums = (sum1, sum2)\n print sums\n\nYou can adjust nb_iter if the problem is bigger.\nIt solves all the problem mentioned above mostly all the times.\n",
"In an earlier comment I hypothesized that the problem as set was tractable because they had carefully chosen the test data to be compatible with various algorithms within the time alloted. This turned out not to be the case - instead it is the problem constraints - numbers no higher than 450 and a final set no larger than 50 numbers is the key. These are compatible with solving the problem using the dynamic programming solution I put up in a later post. None of the other algorithms (heuristics, or exhaustive enumeration by a combinatorial pattern generator) can possibly work because there will be test cases large enough or hard enough to break those algorithms. It's rather annoying to be honest because those other solutions are more challenging and certainly more fun. Note that without a lot of extra work, the dynamic programming solution just says whether a solution is possible with N/2 for any given sum, but it doesn't tell you the contents of either partition.\n"
] |
[
35,
6,
4,
2,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0
] |
[] |
[] |
[
"algorithm",
"dynamic_programming",
"knapsack_problem",
"np_complete",
"python"
] |
stackoverflow_0000890171_algorithm_dynamic_programming_knapsack_problem_np_complete_python.txt
|
Q:
How does the Python's range function work?
If I write
for i in range(5):
print i
Then it gives 0, 1, 2, 3, 4
Does that mean Python assigned 0, 1, 2, 3, 4 to i at the same time?
However if I wrote:
for i in range(5):
a=i+1
Then I call a, it only gives 5
But if I add ''print a'' it gives 1, 2, 3, 4, 5
So my question is what is the difference here?
Is i a string or a list or something else?
Or maybe can anyone help me to sort out:
for l in range(5):
#vs,fs,rs are all m*n matrixs,got initial values in,i.e vs[0],fs[0],rs[0] are known
#want use this foor loop to update them
vs[l+1]=vs[l]+fs[l]
fs[l+1]=((rs[l]-re[l])
rs[l+1]=rs[l]+vs[l]
#then this code gives vs,fs,rs
If I run this kind of code, then I will get the answer only when l=5
How can I make them start looping?
i.e l=0 got values for vs[1],fs[1],rs[1],
then l=1 got values for vs[2],rs[2],fs[2]......and so on.
But python gives different arrays of fs,vs,rs, correspond to different value of l
How can I make them one piece?
A:
A "for loop" in most, if not all, programming languages is a mechanism to run a piece of code more than once.
This code:
for i in range(5):
print i
can be thought of working like this:
i = 0
print i
i = 1
print i
i = 2
print i
i = 3
print i
i = 4
print i
So you see, what happens is not that i gets the value 0, 1, 2, 3, 4 at the same time, but rather sequentially.
I assume that when you say "call a, it gives only 5", you mean like this:
for i in range(5):
a=i+1
print a
this will print the last value that a was given. Every time the loop iterates, the statement a=i+1 will overwrite the last value a had with the new value.
Code basically runs sequentially, from top to bottom, and a for loop is a way to make the code go back and something again, with a different value for one of the variables.
I hope this answered your question.
A:
When I'm teaching someone programming (just about any language) I introduce for loops with terminology similar to this code example:
for eachItem in someList:
doSomething(eachItem)
... which, conveniently enough, is syntactically valid Python code.
The Python range() function simply returns or generates a list of integers from some lower bound (zero, by default) up to (but not including) some upper bound, possibly in increments (steps) of some other number (one, by default).
So range(5) returns (or possibly generates) a sequence: 0, 1, 2, 3, 4 (up to but not including the upper bound).
A call to range(2,10) would return: 2, 3, 4, 5, 6, 7, 8, 9
A call to range(2,12,3) would return: 2, 5, 8, 11
Notice that I said, a couple times, that Python's range() function returns or generates a sequence. This is a relatively advanced distinction which usually won't be an issue for a novice. In older versions of Python range() built a list (allocated memory for it and populated with with values) and returned a reference to that list. This could be inefficient for large ranges which might consume quite a bit of memory and for some situations where you might want to iterate over some potentially large range of numbers but were likely to "break" out of the loop early (after finding some particular item in which you were interested, for example).
Python supports more efficient ways of implementing the same semantics (of doing the same thing) through a programming construct called a generator. Instead of allocating and populating the entire list and return it as a static data structure, Python can instantiate an object with the requisite information (upper and lower bounds and step/increment value) ... and return a reference to that.
The (code) object then keeps track of which number it returned most recently and computes the new values until it hits the upper bound (and which point it signals the end of the sequence to the caller using an exception called "StopIteration"). This technique (computing values dynamically rather than all at once, up-front) is referred to as "lazy evaluation."
Other constructs in the language (such as those underlying the for loop) can then work with that object (iterate through it) as though it were a list.
For most cases you don't have to know whether your version of Python is using the old implementation of range() or the newer one based on generators. You can just use it and be happy.
If you're working with ranges of millions of items, or creating thousands of different ranges of thousands each, then you might notice a performance penalty for using range() on an old version of Python. In such cases you could re-think your design and use while loops, or create objects which implement the "lazy evaluation" semantics of a generator, or use the xrange() version of range() if your version of Python includes it, or the range() function from a version of Python that uses the generators implicitly.
Concepts such as generators, and more general forms of lazy evaluation, permeate Python programming as you go beyond the basics. They are usually things you don't have to know for simple programming tasks but which become significant as you try to work with larger data sets or within tighter constraints (time/performance or memory bounds, for example).
[Update: for Python3 (the currently maintained versions of Python) the range() function always returns the dynamic, "lazy evaluation" iterator; the older versions of Python (2.x) which returned a statically allocated list of integers are now officially obsolete (after years of having been deprecated)].
A:
for i in range(5):
is the same as
for i in [0,1,2,3,4]:
A:
range(x) returns a list of numbers from 0 to x - 1.
>>> range(1)
[0]
>>> range(2)
[0, 1]
>>> range(3)
[0, 1, 2]
>>> range(4)
[0, 1, 2, 3]
for i in range(x): executes the body (which is print i in your first example) once for each element in the list returned by range().
i is used inside the body to refer to the “current” item of the list.
In that case, i refers to an integer, but it could be of any type, depending on the objet on which you loop.
A:
The range function wil give you a list of numbers, while the for loop will iterate through the list and execute the given code for each of its items.
for i in range(5):
print i
This simply executes print i five times, for i ranging from 0 to 4.
for i in range(5):
a=i+1
This will execute a=i+1 five times. Since you are overwriting the value of a on each iteration, at the end you will only get the value for the last iteration, that is 4+1.
Useful links:
http://www.network-theory.co.uk/docs/pytut/rangeFunction.html
http://www.ibiblio.org/swaroopch/byteofpython/read/for-loop.html
A:
It is looping, probably the problem is in the part of the print...
If you can't find the logic where the system prints, just add the folling where you want the content out:
for i in range(len(vs)):
print vs[i]
print fs[i]
print rs[i]
|
How does the Python's range function work?
|
If I write
for i in range(5):
print i
Then it gives 0, 1, 2, 3, 4
Does that mean Python assigned 0, 1, 2, 3, 4 to i at the same time?
However if I wrote:
for i in range(5):
a=i+1
Then I call a, it only gives 5
But if I add ''print a'' it gives 1, 2, 3, 4, 5
So my question is what is the difference here?
Is i a string or a list or something else?
Or maybe can anyone help me to sort out:
for l in range(5):
#vs,fs,rs are all m*n matrixs,got initial values in,i.e vs[0],fs[0],rs[0] are known
#want use this foor loop to update them
vs[l+1]=vs[l]+fs[l]
fs[l+1]=((rs[l]-re[l])
rs[l+1]=rs[l]+vs[l]
#then this code gives vs,fs,rs
If I run this kind of code, then I will get the answer only when l=5
How can I make them start looping?
i.e l=0 got values for vs[1],fs[1],rs[1],
then l=1 got values for vs[2],rs[2],fs[2]......and so on.
But python gives different arrays of fs,vs,rs, correspond to different value of l
How can I make them one piece?
|
[
"A \"for loop\" in most, if not all, programming languages is a mechanism to run a piece of code more than once.\nThis code:\nfor i in range(5):\n print i\n\ncan be thought of working like this:\ni = 0\nprint i\ni = 1\nprint i\ni = 2\nprint i\ni = 3\nprint i\ni = 4\nprint i\n\nSo you see, what happens is not that i gets the value 0, 1, 2, 3, 4 at the same time, but rather sequentially.\nI assume that when you say \"call a, it gives only 5\", you mean like this:\nfor i in range(5):\n a=i+1\nprint a\n\nthis will print the last value that a was given. Every time the loop iterates, the statement a=i+1 will overwrite the last value a had with the new value.\nCode basically runs sequentially, from top to bottom, and a for loop is a way to make the code go back and something again, with a different value for one of the variables.\nI hope this answered your question.\n",
"When I'm teaching someone programming (just about any language) I introduce for loops with terminology similar to this code example:\nfor eachItem in someList:\n doSomething(eachItem)\n\n... which, conveniently enough, is syntactically valid Python code.\nThe Python range() function simply returns or generates a list of integers from some lower bound (zero, by default) up to (but not including) some upper bound, possibly in increments (steps) of some other number (one, by default).\nSo range(5) returns (or possibly generates) a sequence: 0, 1, 2, 3, 4 (up to but not including the upper bound).\nA call to range(2,10) would return: 2, 3, 4, 5, 6, 7, 8, 9\nA call to range(2,12,3) would return: 2, 5, 8, 11\nNotice that I said, a couple times, that Python's range() function returns or generates a sequence. This is a relatively advanced distinction which usually won't be an issue for a novice. In older versions of Python range() built a list (allocated memory for it and populated with with values) and returned a reference to that list. This could be inefficient for large ranges which might consume quite a bit of memory and for some situations where you might want to iterate over some potentially large range of numbers but were likely to \"break\" out of the loop early (after finding some particular item in which you were interested, for example).\nPython supports more efficient ways of implementing the same semantics (of doing the same thing) through a programming construct called a generator. Instead of allocating and populating the entire list and return it as a static data structure, Python can instantiate an object with the requisite information (upper and lower bounds and step/increment value) ... and return a reference to that.\nThe (code) object then keeps track of which number it returned most recently and computes the new values until it hits the upper bound (and which point it signals the end of the sequence to the caller using an exception called \"StopIteration\"). This technique (computing values dynamically rather than all at once, up-front) is referred to as \"lazy evaluation.\"\nOther constructs in the language (such as those underlying the for loop) can then work with that object (iterate through it) as though it were a list.\nFor most cases you don't have to know whether your version of Python is using the old implementation of range() or the newer one based on generators. You can just use it and be happy.\nIf you're working with ranges of millions of items, or creating thousands of different ranges of thousands each, then you might notice a performance penalty for using range() on an old version of Python. In such cases you could re-think your design and use while loops, or create objects which implement the \"lazy evaluation\" semantics of a generator, or use the xrange() version of range() if your version of Python includes it, or the range() function from a version of Python that uses the generators implicitly.\nConcepts such as generators, and more general forms of lazy evaluation, permeate Python programming as you go beyond the basics. They are usually things you don't have to know for simple programming tasks but which become significant as you try to work with larger data sets or within tighter constraints (time/performance or memory bounds, for example).\n[Update: for Python3 (the currently maintained versions of Python) the range() function always returns the dynamic, \"lazy evaluation\" iterator; the older versions of Python (2.x) which returned a statically allocated list of integers are now officially obsolete (after years of having been deprecated)].\n",
"for i in range(5):\n\nis the same as\nfor i in [0,1,2,3,4]:\n\n",
"range(x) returns a list of numbers from 0 to x - 1.\n>>> range(1)\n[0]\n>>> range(2)\n[0, 1]\n>>> range(3)\n[0, 1, 2]\n>>> range(4)\n[0, 1, 2, 3]\n\nfor i in range(x): executes the body (which is print i in your first example) once for each element in the list returned by range().\ni is used inside the body to refer to the “current” item of the list.\nIn that case, i refers to an integer, but it could be of any type, depending on the objet on which you loop.\n",
"The range function wil give you a list of numbers, while the for loop will iterate through the list and execute the given code for each of its items.\nfor i in range(5):\n print i\n\nThis simply executes print i five times, for i ranging from 0 to 4.\nfor i in range(5):\n a=i+1\n\nThis will execute a=i+1 five times. Since you are overwriting the value of a on each iteration, at the end you will only get the value for the last iteration, that is 4+1.\nUseful links:\nhttp://www.network-theory.co.uk/docs/pytut/rangeFunction.html\nhttp://www.ibiblio.org/swaroopch/byteofpython/read/for-loop.html\n",
"It is looping, probably the problem is in the part of the print...\nIf you can't find the logic where the system prints, just add the folling where you want the content out:\nfor i in range(len(vs)):\n print vs[i]\n print fs[i]\n print rs[i]\n\n"
] |
[
52,
22,
7,
6,
0,
0
] |
[] |
[] |
[
"for_loop",
"python",
"range"
] |
stackoverflow_0001738109_for_loop_python_range.txt
|
Q:
Python and iPhone development on Mac - minimum/recommended hardware?
What is the minimum configuration to do some Python and iPhone development on Mac ?
Platform wise: Mac Mini, Mac Pro, Mac Book, Mac Book Pro ?
Memory requirement
CPU speed
Thanks for your advice.
Laurent
A:
Any of those platforms are going to be more than adequate for iPhone development, but since Apple is not allowing anything that requires a VM or an interpreted environment, there is no way to do iPhone development using Python at this time.
EDIT: Looks like I misread that as doing Python development on an iPhone, so just ignore the second part of my answer. Any of those platforms are going to be fine for either iPhone or Python development.
A:
The minimum requirement is an intel mac. Any intel mac will work. iPhone development is unsupported on PPC.
Python can be done on any mac that runs os x.
The minimum requirement, and what's pleasant are different things. Everything you've listed will work pretty great. You might want to bump up the ram a little on what they ship with, but other than that you're good to go.
A:
Rather ephemeral in our requirements, aren't we. 'Some' python/iPhone....
You will be well served by a mini, starting @ $600, they're a steal. Upgrade the processor (2.53ghz), add RAM to 4GB (after purchase, if you're comfortable) throw a generic keyboard, mouse and Monitor on it and you've got a heck of a machine.
Don't bother with a HD upgrade, just get an external USB disk and put all your VM's and extra necessities on it.
A:
Any system that Apple sells is sufficient to do Python and iPhone development on the Mac. I generally consider 2 GB to be the minimum amount of RAM that I would want to use, and 4 GB if I'm going to be doing any significant amount of work in a VM (for instance, VMware Fusion or Parallels for running Windows within Mac OS X). But I think all configurations currently come with at least 2 GB of RAM, so you should be set there, too.
Of course faster machines are always better, so you should get a machine that's fast enough for you, but I have a couple year old Mac Book Pro and find that's fast enough for me.
The biggest help for development is multiple monitors. Having two monitors helps a lot (and three is good, too). I believe that all of Apple's current systems support two monitors.
|
Python and iPhone development on Mac - minimum/recommended hardware?
|
What is the minimum configuration to do some Python and iPhone development on Mac ?
Platform wise: Mac Mini, Mac Pro, Mac Book, Mac Book Pro ?
Memory requirement
CPU speed
Thanks for your advice.
Laurent
|
[
"Any of those platforms are going to be more than adequate for iPhone development, but since Apple is not allowing anything that requires a VM or an interpreted environment, there is no way to do iPhone development using Python at this time.\nEDIT: Looks like I misread that as doing Python development on an iPhone, so just ignore the second part of my answer. Any of those platforms are going to be fine for either iPhone or Python development.\n",
"The minimum requirement is an intel mac. Any intel mac will work. iPhone development is unsupported on PPC.\nPython can be done on any mac that runs os x.\nThe minimum requirement, and what's pleasant are different things. Everything you've listed will work pretty great. You might want to bump up the ram a little on what they ship with, but other than that you're good to go.\n",
"Rather ephemeral in our requirements, aren't we. 'Some' python/iPhone....\nYou will be well served by a mini, starting @ $600, they're a steal. Upgrade the processor (2.53ghz), add RAM to 4GB (after purchase, if you're comfortable) throw a generic keyboard, mouse and Monitor on it and you've got a heck of a machine.\nDon't bother with a HD upgrade, just get an external USB disk and put all your VM's and extra necessities on it.\n",
"Any system that Apple sells is sufficient to do Python and iPhone development on the Mac. I generally consider 2 GB to be the minimum amount of RAM that I would want to use, and 4 GB if I'm going to be doing any significant amount of work in a VM (for instance, VMware Fusion or Parallels for running Windows within Mac OS X). But I think all configurations currently come with at least 2 GB of RAM, so you should be set there, too.\nOf course faster machines are always better, so you should get a machine that's fast enough for you, but I have a couple year old Mac Book Pro and find that's fast enough for me.\nThe biggest help for development is multiple monitors. Having two monitors helps a lot (and three is good, too). I believe that all of Apple's current systems support two monitors.\n"
] |
[
4,
4,
1,
1
] |
[] |
[] |
[
"iphone",
"macos",
"python"
] |
stackoverflow_0001738845_iphone_macos_python.txt
|
Q:
How to tell whether a file is executable on Windows in Python?
I'm writing grepath utility that finds executables in %PATH% that match a pattern.
I need to define whether given filename in the path is executable (emphasis is on command line scripts).
Based on "Tell if a file is executable" I've got:
import os
from pywintypes import error
from win32api import FindExecutable, GetLongPathName
def is_executable_win(path):
try:
_, executable = FindExecutable(path)
ext = lambda p: os.path.splitext(p)[1].lower()
if (ext(path) == ext(executable) # reject *.cmd~, *.bat~ cases
and samefile(GetLongPathName(executable), path)):
return True
# path is a document with assoc. check whether it has extension
# from %PATHEXT%
pathexts = os.environ.get('PATHEXT', '').split(os.pathsep)
return any(ext(path) == e.lower() for e in pathexts)
except error:
return None # not an exe or a document with assoc.
Where samefile is:
try: samefile = os.path.samefile
except AttributeError:
def samefile(path1, path2):
rp = lambda p: os.path.realpath(os.path.normcase(p))
return rp(path1) == rp(path2)
How is_executable_win could be improved in the given context? What functions from Win32 API could help?
P.S.
time performance doesn't matter
subst drives and UNC, unicode paths are not under consideration
C++ answer is OK if it uses functions available on Windows XP
Examples
notepad.exe is executable (as a rule)
which.py is executable if it is associated with some executable (e.g., python.exe) and .PY is in %PATHEXT% i.e., 'C:\> which' could start:
some\path\python.exe another\path\in\PATH\which.py
somefile.doc most probably is not executable (when it is associated with Word for example)
another_file.txt is not executable (as a rule)
ack.pl is executable if it is associated with some executable (most probably perl.exe) and .PL is in %PATHEXT% (i.e. I can run ack without specifing extension if it is in the path)
What is "executable" in this question
def is_executable_win_destructive(path):
#NOTE: it assumes `path` <-> `barename` for the sake of example
barename = os.path.splitext(os.path.basename(path))[0]
p = Popen(barename, stdout=PIPE, stderr=PIPE, shell=True)
stdout, stderr = p.communicate()
return p.poll() != 1 or stdout != '' or stderr != error_message(barename)
Where error_message() depends on language. English version is:
def error_message(barename):
return "'%(barename)s' is not recognized as an internal" \
" or external\r\ncommand, operable program or batch file.\r\n" \
% dict(barename=barename)
If is_executable_win_destructive() returns when it defines whether the path points to an executable for the purpose of this question.
Example:
>>> path = r"c:\docs\somefile.doc"
>>> barename = "somefile"
After that it executes %COMSPEC% (cmd.exe by default):
c:\cwd> cmd.exe /c somefile
If output looks like this:
'somefile' is not recognized as an internal or external
command, operable program or batch file.
Then the path is not an executable else it is (lets assume there is one-to-one correspondence between path and barename for the sake of example).
Another example:
>>> path = r'c:\bin\grepath.py'
>>> barename = 'grepath'
If .PY in %PATHEXT% and c:\bin is in %PATH% then:
c:\docs> grepath
Usage:
grepath.py [options] PATTERN
grepath.py [options] -e PATTERN
grepath.py: error: incorrect number of arguments
The above output is not equal to error_message(barename) therefore 'c:\bin\grepath.py' is an "executable".
So the question is how to find out whether the path will produce the error without actually running it? What Win32 API function and what conditions used to trigger the 'is not recognized as an internal..' error?
A:
shoosh beat me to it :)
If I remember correctly, you should try to read the first 2 characters in the file. If you get back "MZ", you have an exe.
hnd = open(file,"rb")
if hnd.read(2) == "MZ":
print "exe"
A:
I think, that this should be sufficient:
check file extension in PATHEXT - whether file is directly executable
using cmd.exe command "assoc .ext" you can see whether file is associated with some executable (some executable will be launched when you launch this file). You can parse capture output of assoc without arguments and collect all extensions that are associated and check tested file extension.
other file extensions will trigger error "command is not recognized ..." therefore you can assume that such files are NOT executable.
I don't really understand how you can tell the difference between somefile.py and somefile.txt because association can be really the same. You can configure system to run .txt files the same way as .py files.
A:
A windows PE always starts with the characters "MZ". This includes however also any kind of DLLs which are not necessarily executables.
To check for this however you'll have to open the file and read the header so that's probably not what you're looking for.
A:
Here's the grepath.py that I've linked in my question:
#!/usr/bin/env python
"""Find executables in %PATH% that match PATTERN.
"""
#XXX: remove --use-pathext option
import fnmatch, itertools, os, re, sys, warnings
from optparse import OptionParser
from stat import S_IMODE, S_ISREG, ST_MODE
from subprocess import PIPE, Popen
def warn_import(*args):
"""pass '-Wd' option to python interpreter to see these warnings."""
warnings.warn("%r" % (args,), ImportWarning, stacklevel=2)
class samefile_win:
"""
http://timgolden.me.uk/python/win32_how_do_i/see_if_two_files_are_the_same_file.html
"""
@staticmethod
def get_read_handle (filename):
return win32file.CreateFile (
filename,
win32file.GENERIC_READ,
win32file.FILE_SHARE_READ,
None,
win32file.OPEN_EXISTING,
0,
None
)
@staticmethod
def get_unique_id (hFile):
(attributes,
created_at, accessed_at, written_at,
volume,
file_hi, file_lo,
n_links,
index_hi, index_lo
) = win32file.GetFileInformationByHandle (hFile)
return volume, index_hi, index_lo
@staticmethod
def samefile_win(filename1, filename2):
"""Whether filename1 and filename2 represent the same file.
It works for subst, ntfs hardlinks, junction points.
It works unreliably for network drives.
Based on GetFileInformationByHandle() Win32 API call.
http://timgolden.me.uk/python/win32_how_do_i/see_if_two_files_are_the_same_file.html
"""
if samefile_generic(filename1, filename2): return True
try:
hFile1 = samefile_win.get_read_handle (filename1)
hFile2 = samefile_win.get_read_handle (filename2)
are_equal = (samefile_win.get_unique_id (hFile1)
== samefile_win.get_unique_id (hFile2))
hFile2.Close ()
hFile1.Close ()
return are_equal
except win32file.error:
return None
def canonical_path(path):
"""NOTE: it might return wrong path for paths with symbolic links."""
return os.path.realpath(os.path.normcase(path))
def samefile_generic(path1, path2):
return canonical_path(path1) == canonical_path(path2)
class is_executable_destructive:
@staticmethod
def error_message(barename):
r"""
"'%(barename)s' is not recognized as an internal or external\r\n
command, operable program or batch file.\r\n"
in Russian:
"""
return '"%(barename)s" \xad\xa5 \xef\xa2\xab\xef\xa5\xe2\xe1\xef \xa2\xad\xe3\xe2\xe0\xa5\xad\xad\xa5\xa9 \xa8\xab\xa8 \xa2\xad\xa5\xe8\xad\xa5\xa9\r\n\xaa\xae\xac\xa0\xad\xa4\xae\xa9, \xa8\xe1\xaf\xae\xab\xad\xef\xa5\xac\xae\xa9 \xaf\xe0\xae\xa3\xe0\xa0\xac\xac\xae\xa9 \xa8\xab\xa8 \xaf\xa0\xaa\xa5\xe2\xad\xeb\xac \xe4\xa0\xa9\xab\xae\xac.\r\n' % dict(barename=barename)
@staticmethod
def is_executable_win_destructive(path):
# assume path <-> barename that is false in general
barename = os.path.splitext(os.path.basename(path))[0]
p = Popen(barename, stdout=PIPE, stderr=PIPE, shell=True)
stdout, stderr = p.communicate()
return p.poll() != 1 or stdout != '' or stderr != error_message(barename)
def is_executable_win(path):
"""Based on:
http://timgolden.me.uk/python/win32_how_do_i/tell-if-a-file-is-executable.html
Known bugs: treat some "*~" files as executable, e.g. some "*.bat~" files
"""
try:
_, executable = FindExecutable(path)
return bool(samefile(GetLongPathName(executable), path))
except error:
return None # not an exe or a document with assoc.
def is_executable_posix(path):
"""Whether the file is executable.
Based on which.py from stdlib
"""
#XXX it ignores effective uid, guid?
try: st = os.stat(path)
except os.error:
return None
isregfile = S_ISREG(st[ST_MODE])
isexemode = (S_IMODE(st[ST_MODE]) & 0111)
return bool(isregfile and isexemode)
try:
#XXX replace with ctypes?
from win32api import FindExecutable, GetLongPathName, error
is_executable = is_executable_win
except ImportError, e:
warn_import("is_executable: fall back on posix variant", e)
is_executable = is_executable_posix
try: samefile = os.path.samefile
except AttributeError, e:
warn_import("samefile: fallback to samefile_win", e)
try:
import win32file
samefile = samefile_win.samefile_win
except ImportError, e:
warn_import("samefile: fallback to generic", e)
samefile = samefile_generic
def main():
parser = OptionParser(usage="""
%prog [options] PATTERN
%prog [options] -e PATTERN""", description=__doc__)
opt = parser.add_option
opt("-e", "--regex", metavar="PATTERN",
help="use PATTERN as a regular expression")
opt("--ignore-case", action="store_true", default=True,
help="""[default] ignore case when --regex is present; for \
non-regex PATTERN both FILENAME and PATTERN are first \
case-normalized if the operating system requires it otherwise \
unchanged.""")
opt("--no-ignore-case", dest="ignore_case", action="store_false")
opt("--use-pathext", action="store_true", default=True,
help="[default] whether to use %PATHEXT% environment variable")
opt("--no-use-pathext", dest="use_pathext", action="store_false")
opt("--show-non-executable", action="store_true", default=False,
help="show non executable files")
(options, args) = parser.parse_args()
if len(args) != 1 and not options.regex:
parser.error("incorrect number of arguments")
if not options.regex:
pattern = args[0]
del args
if options.regex:
filepred = re.compile(options.regex, options.ignore_case and re.I).search
else:
fnmatch_ = fnmatch.fnmatch if options.ignore_case else fnmatch.fnmatchcase
for file_pattern_symbol in "*?":
if file_pattern_symbol in pattern:
break
else: # match in any place if no explicit file pattern symbols supplied
pattern = "*" + pattern + "*"
filepred = lambda fn: fnmatch_(fn, pattern)
if not options.regex and options.ignore_case:
filter_files = lambda files: fnmatch.filter(files, pattern)
else:
filter_files = lambda files: itertools.ifilter(filepred, files)
if options.use_pathext:
pathexts = frozenset(map(str.upper,
os.environ.get('PATHEXT', '').split(os.pathsep)))
seen = set()
for dirpath in os.environ.get('PATH', '').split(os.pathsep):
if os.path.isdir(dirpath): # assume no expansion needed
# visit "each" directory only once
# it is unaware of subst drives, junction points, symlinks, etc
rp = canonical_path(dirpath)
if rp in seen: continue
seen.add(rp); del rp
for filename in filter_files(os.listdir(dirpath)):
path = os.path.join(dirpath, filename)
isexe = is_executable(path)
if isexe == False and is_executable == is_executable_win:
# path is a document with associated program
# check whether it is a script (.pl, .rb, .py, etc)
if not isexe and options.use_pathext:
ext = os.path.splitext(path)[1]
isexe = ext.upper() in pathexts
if isexe:
print path
elif options.show_non_executable:
print "non-executable:", path
if __name__=="__main__":
main()
A:
Parse the PE format.
http://code.google.com/p/pefile/
This is probably the best solution you will get other than using python to actually try to run the program.
Edit: I see you also want files that have associations. This will require mucking in the registry which I don't have the information for.
Edit2: I also see that you differentiate between .doc and .py. This is a rather arbitrary differentiation which must be specified with manual rules, because to windows, they are both file extensions that a program reads.
|
How to tell whether a file is executable on Windows in Python?
|
I'm writing grepath utility that finds executables in %PATH% that match a pattern.
I need to define whether given filename in the path is executable (emphasis is on command line scripts).
Based on "Tell if a file is executable" I've got:
import os
from pywintypes import error
from win32api import FindExecutable, GetLongPathName
def is_executable_win(path):
try:
_, executable = FindExecutable(path)
ext = lambda p: os.path.splitext(p)[1].lower()
if (ext(path) == ext(executable) # reject *.cmd~, *.bat~ cases
and samefile(GetLongPathName(executable), path)):
return True
# path is a document with assoc. check whether it has extension
# from %PATHEXT%
pathexts = os.environ.get('PATHEXT', '').split(os.pathsep)
return any(ext(path) == e.lower() for e in pathexts)
except error:
return None # not an exe or a document with assoc.
Where samefile is:
try: samefile = os.path.samefile
except AttributeError:
def samefile(path1, path2):
rp = lambda p: os.path.realpath(os.path.normcase(p))
return rp(path1) == rp(path2)
How is_executable_win could be improved in the given context? What functions from Win32 API could help?
P.S.
time performance doesn't matter
subst drives and UNC, unicode paths are not under consideration
C++ answer is OK if it uses functions available on Windows XP
Examples
notepad.exe is executable (as a rule)
which.py is executable if it is associated with some executable (e.g., python.exe) and .PY is in %PATHEXT% i.e., 'C:\> which' could start:
some\path\python.exe another\path\in\PATH\which.py
somefile.doc most probably is not executable (when it is associated with Word for example)
another_file.txt is not executable (as a rule)
ack.pl is executable if it is associated with some executable (most probably perl.exe) and .PL is in %PATHEXT% (i.e. I can run ack without specifing extension if it is in the path)
What is "executable" in this question
def is_executable_win_destructive(path):
#NOTE: it assumes `path` <-> `barename` for the sake of example
barename = os.path.splitext(os.path.basename(path))[0]
p = Popen(barename, stdout=PIPE, stderr=PIPE, shell=True)
stdout, stderr = p.communicate()
return p.poll() != 1 or stdout != '' or stderr != error_message(barename)
Where error_message() depends on language. English version is:
def error_message(barename):
return "'%(barename)s' is not recognized as an internal" \
" or external\r\ncommand, operable program or batch file.\r\n" \
% dict(barename=barename)
If is_executable_win_destructive() returns when it defines whether the path points to an executable for the purpose of this question.
Example:
>>> path = r"c:\docs\somefile.doc"
>>> barename = "somefile"
After that it executes %COMSPEC% (cmd.exe by default):
c:\cwd> cmd.exe /c somefile
If output looks like this:
'somefile' is not recognized as an internal or external
command, operable program or batch file.
Then the path is not an executable else it is (lets assume there is one-to-one correspondence between path and barename for the sake of example).
Another example:
>>> path = r'c:\bin\grepath.py'
>>> barename = 'grepath'
If .PY in %PATHEXT% and c:\bin is in %PATH% then:
c:\docs> grepath
Usage:
grepath.py [options] PATTERN
grepath.py [options] -e PATTERN
grepath.py: error: incorrect number of arguments
The above output is not equal to error_message(barename) therefore 'c:\bin\grepath.py' is an "executable".
So the question is how to find out whether the path will produce the error without actually running it? What Win32 API function and what conditions used to trigger the 'is not recognized as an internal..' error?
|
[
"shoosh beat me to it :)\nIf I remember correctly, you should try to read the first 2 characters in the file. If you get back \"MZ\", you have an exe.\n\nhnd = open(file,\"rb\")\nif hnd.read(2) == \"MZ\":\n print \"exe\"\n\n",
"I think, that this should be sufficient:\n\ncheck file extension in PATHEXT - whether file is directly executable\nusing cmd.exe command \"assoc .ext\" you can see whether file is associated with some executable (some executable will be launched when you launch this file). You can parse capture output of assoc without arguments and collect all extensions that are associated and check tested file extension.\nother file extensions will trigger error \"command is not recognized ...\" therefore you can assume that such files are NOT executable.\n\nI don't really understand how you can tell the difference between somefile.py and somefile.txt because association can be really the same. You can configure system to run .txt files the same way as .py files.\n",
"A windows PE always starts with the characters \"MZ\". This includes however also any kind of DLLs which are not necessarily executables.\nTo check for this however you'll have to open the file and read the header so that's probably not what you're looking for.\n",
"Here's the grepath.py that I've linked in my question:\n#!/usr/bin/env python\n\"\"\"Find executables in %PATH% that match PATTERN.\n\n\"\"\"\n#XXX: remove --use-pathext option\n\nimport fnmatch, itertools, os, re, sys, warnings\nfrom optparse import OptionParser\nfrom stat import S_IMODE, S_ISREG, ST_MODE\nfrom subprocess import PIPE, Popen\n\n\ndef warn_import(*args):\n \"\"\"pass '-Wd' option to python interpreter to see these warnings.\"\"\"\n warnings.warn(\"%r\" % (args,), ImportWarning, stacklevel=2)\n\n\nclass samefile_win:\n \"\"\"\nhttp://timgolden.me.uk/python/win32_how_do_i/see_if_two_files_are_the_same_file.html\n\"\"\"\n @staticmethod\n def get_read_handle (filename):\n return win32file.CreateFile (\n filename,\n win32file.GENERIC_READ,\n win32file.FILE_SHARE_READ,\n None,\n win32file.OPEN_EXISTING,\n 0,\n None\n )\n\n @staticmethod\n def get_unique_id (hFile):\n (attributes,\n created_at, accessed_at, written_at,\n volume,\n file_hi, file_lo,\n n_links,\n index_hi, index_lo\n ) = win32file.GetFileInformationByHandle (hFile)\n return volume, index_hi, index_lo\n\n @staticmethod\n def samefile_win(filename1, filename2):\n \"\"\"Whether filename1 and filename2 represent the same file.\n\nIt works for subst, ntfs hardlinks, junction points.\nIt works unreliably for network drives.\n\nBased on GetFileInformationByHandle() Win32 API call.\nhttp://timgolden.me.uk/python/win32_how_do_i/see_if_two_files_are_the_same_file.html\n\"\"\"\n if samefile_generic(filename1, filename2): return True\n try:\n hFile1 = samefile_win.get_read_handle (filename1)\n hFile2 = samefile_win.get_read_handle (filename2)\n are_equal = (samefile_win.get_unique_id (hFile1)\n == samefile_win.get_unique_id (hFile2))\n hFile2.Close ()\n hFile1.Close ()\n return are_equal\n except win32file.error:\n return None\n\n\ndef canonical_path(path):\n \"\"\"NOTE: it might return wrong path for paths with symbolic links.\"\"\"\n return os.path.realpath(os.path.normcase(path))\n\n\ndef samefile_generic(path1, path2):\n return canonical_path(path1) == canonical_path(path2)\n\n\nclass is_executable_destructive:\n @staticmethod\n def error_message(barename):\n r\"\"\"\n\"'%(barename)s' is not recognized as an internal or external\\r\\n\ncommand, operable program or batch file.\\r\\n\"\n\nin Russian:\n\"\"\"\n return '\"%(barename)s\" \\xad\\xa5 \\xef\\xa2\\xab\\xef\\xa5\\xe2\\xe1\\xef \\xa2\\xad\\xe3\\xe2\\xe0\\xa5\\xad\\xad\\xa5\\xa9 \\xa8\\xab\\xa8 \\xa2\\xad\\xa5\\xe8\\xad\\xa5\\xa9\\r\\n\\xaa\\xae\\xac\\xa0\\xad\\xa4\\xae\\xa9, \\xa8\\xe1\\xaf\\xae\\xab\\xad\\xef\\xa5\\xac\\xae\\xa9 \\xaf\\xe0\\xae\\xa3\\xe0\\xa0\\xac\\xac\\xae\\xa9 \\xa8\\xab\\xa8 \\xaf\\xa0\\xaa\\xa5\\xe2\\xad\\xeb\\xac \\xe4\\xa0\\xa9\\xab\\xae\\xac.\\r\\n' % dict(barename=barename)\n\n @staticmethod\n def is_executable_win_destructive(path):\n # assume path <-> barename that is false in general\n barename = os.path.splitext(os.path.basename(path))[0]\n p = Popen(barename, stdout=PIPE, stderr=PIPE, shell=True)\n stdout, stderr = p.communicate()\n return p.poll() != 1 or stdout != '' or stderr != error_message(barename)\n\n\ndef is_executable_win(path):\n \"\"\"Based on:\nhttp://timgolden.me.uk/python/win32_how_do_i/tell-if-a-file-is-executable.html\n\nKnown bugs: treat some \"*~\" files as executable, e.g. some \"*.bat~\" files\n\"\"\"\n try:\n _, executable = FindExecutable(path)\n return bool(samefile(GetLongPathName(executable), path))\n except error:\n return None # not an exe or a document with assoc.\n\n\ndef is_executable_posix(path):\n \"\"\"Whether the file is executable.\n\nBased on which.py from stdlib\n\"\"\"\n #XXX it ignores effective uid, guid?\n try: st = os.stat(path)\n except os.error:\n return None\n\n isregfile = S_ISREG(st[ST_MODE])\n isexemode = (S_IMODE(st[ST_MODE]) & 0111)\n return bool(isregfile and isexemode)\n\ntry:\n #XXX replace with ctypes?\n from win32api import FindExecutable, GetLongPathName, error\n is_executable = is_executable_win\nexcept ImportError, e:\n warn_import(\"is_executable: fall back on posix variant\", e)\n is_executable = is_executable_posix\n\ntry: samefile = os.path.samefile\nexcept AttributeError, e:\n warn_import(\"samefile: fallback to samefile_win\", e)\n try:\n import win32file\n samefile = samefile_win.samefile_win\n except ImportError, e:\n warn_import(\"samefile: fallback to generic\", e)\n samefile = samefile_generic\n\ndef main():\n parser = OptionParser(usage=\"\"\"\n%prog [options] PATTERN\n%prog [options] -e PATTERN\"\"\", description=__doc__)\n opt = parser.add_option\n opt(\"-e\", \"--regex\", metavar=\"PATTERN\",\n help=\"use PATTERN as a regular expression\")\n opt(\"--ignore-case\", action=\"store_true\", default=True,\n help=\"\"\"[default] ignore case when --regex is present; for \\\nnon-regex PATTERN both FILENAME and PATTERN are first \\\ncase-normalized if the operating system requires it otherwise \\\nunchanged.\"\"\")\n opt(\"--no-ignore-case\", dest=\"ignore_case\", action=\"store_false\")\n opt(\"--use-pathext\", action=\"store_true\", default=True,\n help=\"[default] whether to use %PATHEXT% environment variable\")\n opt(\"--no-use-pathext\", dest=\"use_pathext\", action=\"store_false\")\n opt(\"--show-non-executable\", action=\"store_true\", default=False,\n help=\"show non executable files\")\n\n (options, args) = parser.parse_args()\n\n if len(args) != 1 and not options.regex:\n parser.error(\"incorrect number of arguments\")\n if not options.regex:\n pattern = args[0]\n del args\n\n if options.regex:\n filepred = re.compile(options.regex, options.ignore_case and re.I).search\n else:\n fnmatch_ = fnmatch.fnmatch if options.ignore_case else fnmatch.fnmatchcase\n for file_pattern_symbol in \"*?\":\n if file_pattern_symbol in pattern:\n break\n else: # match in any place if no explicit file pattern symbols supplied\n pattern = \"*\" + pattern + \"*\"\n filepred = lambda fn: fnmatch_(fn, pattern)\n\n if not options.regex and options.ignore_case:\n filter_files = lambda files: fnmatch.filter(files, pattern)\n else:\n filter_files = lambda files: itertools.ifilter(filepred, files)\n\n if options.use_pathext:\n pathexts = frozenset(map(str.upper,\n os.environ.get('PATHEXT', '').split(os.pathsep)))\n\n seen = set()\n for dirpath in os.environ.get('PATH', '').split(os.pathsep):\n if os.path.isdir(dirpath): # assume no expansion needed\n # visit \"each\" directory only once\n # it is unaware of subst drives, junction points, symlinks, etc\n rp = canonical_path(dirpath)\n if rp in seen: continue\n seen.add(rp); del rp\n\n for filename in filter_files(os.listdir(dirpath)):\n path = os.path.join(dirpath, filename)\n isexe = is_executable(path)\n\n if isexe == False and is_executable == is_executable_win:\n # path is a document with associated program\n # check whether it is a script (.pl, .rb, .py, etc)\n if not isexe and options.use_pathext:\n ext = os.path.splitext(path)[1]\n isexe = ext.upper() in pathexts\n\n if isexe:\n print path\n elif options.show_non_executable:\n print \"non-executable:\", path\n\n\nif __name__==\"__main__\":\n main()\n\n",
"Parse the PE format.\nhttp://code.google.com/p/pefile/\nThis is probably the best solution you will get other than using python to actually try to run the program.\nEdit: I see you also want files that have associations. This will require mucking in the registry which I don't have the information for.\nEdit2: I also see that you differentiate between .doc and .py. This is a rather arbitrary differentiation which must be specified with manual rules, because to windows, they are both file extensions that a program reads.\n"
] |
[
3,
3,
2,
1,
0
] |
[
"Your question can't be answered. Windows can't tell the difference between a file which is associated with a scripting language vs. some other arbitrary program. As Windows is concerned, a .PY file is simply a document which is opened by python.exe.\n"
] |
[
-1
] |
[
"c++",
"python",
"winapi",
"windows"
] |
stackoverflow_0000646955_c++_python_winapi_windows.txt
|
Q:
Python: Architecture for url polling and posting
I have a simple problem. I have to fetch a url (about once a minute), check if there is any new content, and if there is, post it to another url.
I have a working system with a cronjob every minute that basically:
for link in models.Link.objects.filter(enabled=True).select_related():
# do it in two phases in case there is cross pollination
# get posts
twitter_posts, meme_posts = [], []
if link.direction == "t2m" or link.direction == "both":
twitter_posts = utils.get_twitter_posts(link)
if link.direction == "m2t" or link.direction == "both":
meme_posts = utils.get_meme_posts(link)
# process them
if len(twitter_posts) > 0:
post_count += views.twitter_link(link, twitter_posts)
if len(meme_posts) > 0:
post_count += views.meme_link(link, meme_posts)
count += 1
msg = "%s links crawled and %s posts updated" % (count, post_count)
This works great for the 150 users I have now, but the synchronousness of it scares me. I have url timeouts built-in, but at some point my cronjob will take > 1 minute, and I'll be left with a million of them running overwriting eachother.
So, how should I rewrite it?
Some issues:
I don't want to hit the APIs too hard incase they block me. So I'd like to have at most 5 open connections to any API at any time.
Users keep registering in the system as this runs, so I need some way to add them
I'd like this to scale as well as possible
I'd like to reuse as much existing code as I can
So, some thoughts I've had:
Spawn a thread for each link
Use python-twisted - Keep one running process, that the cronjob just makes sure is running.
Use stackless - Don't really know much about it.
Ask StackOverflow :)
How would you do this?
A:
Simplest: use a long-running process with sched (on its own thread) to handle the scheduling -- by posting requests to a Queue; have a fixed-size pool of threads (you can find a pre-made thread pool here, but it's easy to tweak it or roll your own) taking requests from the Queue (and returning results via a separate Queue). Registration and other system functions can be handled by a few more dedicated threads, if need be.
Threads aren't so bad, as long as (a) you never have to worry about synchronization among them (just have them communicate by intrinsically thread-safe Queue instances, never sharing access to any structure or subsystem that isn't strictly read-only), and (b) you never have too many (use a few dedicated threads for specialized functions, including scheduling, and a small thread-pool for general work -- never spawn a thread per request or anything like that, that will explode).
Twisted can be more scalable (at low hardware costs), but if you hinge your architecture on threading (and Queues) you have a built-in way to grow the system (by purchasing more hardware) to use the very similar multiprocessing module instead... almost a drop-in replacement, and a potential scaling up of orders of magnitude!-)
|
Python: Architecture for url polling and posting
|
I have a simple problem. I have to fetch a url (about once a minute), check if there is any new content, and if there is, post it to another url.
I have a working system with a cronjob every minute that basically:
for link in models.Link.objects.filter(enabled=True).select_related():
# do it in two phases in case there is cross pollination
# get posts
twitter_posts, meme_posts = [], []
if link.direction == "t2m" or link.direction == "both":
twitter_posts = utils.get_twitter_posts(link)
if link.direction == "m2t" or link.direction == "both":
meme_posts = utils.get_meme_posts(link)
# process them
if len(twitter_posts) > 0:
post_count += views.twitter_link(link, twitter_posts)
if len(meme_posts) > 0:
post_count += views.meme_link(link, meme_posts)
count += 1
msg = "%s links crawled and %s posts updated" % (count, post_count)
This works great for the 150 users I have now, but the synchronousness of it scares me. I have url timeouts built-in, but at some point my cronjob will take > 1 minute, and I'll be left with a million of them running overwriting eachother.
So, how should I rewrite it?
Some issues:
I don't want to hit the APIs too hard incase they block me. So I'd like to have at most 5 open connections to any API at any time.
Users keep registering in the system as this runs, so I need some way to add them
I'd like this to scale as well as possible
I'd like to reuse as much existing code as I can
So, some thoughts I've had:
Spawn a thread for each link
Use python-twisted - Keep one running process, that the cronjob just makes sure is running.
Use stackless - Don't really know much about it.
Ask StackOverflow :)
How would you do this?
|
[
"Simplest: use a long-running process with sched (on its own thread) to handle the scheduling -- by posting requests to a Queue; have a fixed-size pool of threads (you can find a pre-made thread pool here, but it's easy to tweak it or roll your own) taking requests from the Queue (and returning results via a separate Queue). Registration and other system functions can be handled by a few more dedicated threads, if need be.\nThreads aren't so bad, as long as (a) you never have to worry about synchronization among them (just have them communicate by intrinsically thread-safe Queue instances, never sharing access to any structure or subsystem that isn't strictly read-only), and (b) you never have too many (use a few dedicated threads for specialized functions, including scheduling, and a small thread-pool for general work -- never spawn a thread per request or anything like that, that will explode).\nTwisted can be more scalable (at low hardware costs), but if you hinge your architecture on threading (and Queues) you have a built-in way to grow the system (by purchasing more hardware) to use the very similar multiprocessing module instead... almost a drop-in replacement, and a potential scaling up of orders of magnitude!-)\n"
] |
[
2
] |
[] |
[] |
[
"architecture",
"concurrency",
"python"
] |
stackoverflow_0001739185_architecture_concurrency_python.txt
|
Q:
What is a good option for a Non-Blocking "Database" (Using a TCP Socket Server)
In short I'm creating a socket server so I can add multiplayer support to my Flash game (Using Actionscript 3.0 Binary Socket on the Client-End).
I decided to go with Python since I'm the sole developer of the game/server and this will be my first non-blocking socket server. I was going to use Twisted but I deiced that I would use Python's asyncore (Asynchronous socket handler).
If I'm not mistaken connecting to a traditional database is a Blocking process. Since I'm trying to make this a non-blocking server I'm curious as to what solutions might be available to save permanent game related data?
A:
I suggest you use any DB you like (sqlite comes with Python and will probably serve you well!): just have a dedicated thread that accesses said DB, taking requests from a Queue (and using another Queue, passed in as part of the request, to return results if needed). Threads aren't so bad if you have a small number, and they never share access to any structure or system that isn't read-only, communicating only by queues (which are intrinsically thread-safe).
A:
Blocking (in traditional database terms, it's "locking") is inevitable if you want any form of consistency in your data.
Consistency as in "it is impossible for two gamers with distinct scores to both be declared as the winner".
Reducing the locking to a minimum is precisely one of those things in database design that turn it into an art form you (perhaps alas) only get to master after having screwed up so many times.
|
What is a good option for a Non-Blocking "Database" (Using a TCP Socket Server)
|
In short I'm creating a socket server so I can add multiplayer support to my Flash game (Using Actionscript 3.0 Binary Socket on the Client-End).
I decided to go with Python since I'm the sole developer of the game/server and this will be my first non-blocking socket server. I was going to use Twisted but I deiced that I would use Python's asyncore (Asynchronous socket handler).
If I'm not mistaken connecting to a traditional database is a Blocking process. Since I'm trying to make this a non-blocking server I'm curious as to what solutions might be available to save permanent game related data?
|
[
"I suggest you use any DB you like (sqlite comes with Python and will probably serve you well!): just have a dedicated thread that accesses said DB, taking requests from a Queue (and using another Queue, passed in as part of the request, to return results if needed). Threads aren't so bad if you have a small number, and they never share access to any structure or system that isn't read-only, communicating only by queues (which are intrinsically thread-safe).\n",
"Blocking (in traditional database terms, it's \"locking\") is inevitable if you want any form of consistency in your data.\nConsistency as in \"it is impossible for two gamers with distinct scores to both be declared as the winner\".\nReducing the locking to a minimum is precisely one of those things in database design that turn it into an art form you (perhaps alas) only get to master after having screwed up so many times.\n"
] |
[
6,
1
] |
[] |
[] |
[
"database",
"python",
"sockets"
] |
stackoverflow_0001739100_database_python_sockets.txt
|
Q:
Allow / in django url
I want to make a wiki, and i must assign for each url a view. Each url can contain letters (A-Z, a-z), digits and punctuation ('.', ',', '/', '-', '_'). How can I make the expression ?
I want something like this :
(r'^(?P<wiki_page>\w+)/$', 'www.wiki.views.page')
but this works only for letters, digits and '_'.
A:
Try this regexp:
r'^(?P<wiki_page>[\w.,/_\-]+)/$'
A:
You could replace \w in the regex with a regex to match what you're looking for. Perhaps
(r'^(?P<wiki_page>[A-Za-z_/,\.-]+)$, 'www.wiki.views.page')
or similar.
A:
I think it's more of a regex question
r'^(?P<wiki_page>[\w\.,_/\-]+)/$'
you can build character classes on top of existing ones
I think you have to escape the dash, or put it last, because dash defines range of characters and you may get a very unexpected side-effect of dash.
|
Allow / in django url
|
I want to make a wiki, and i must assign for each url a view. Each url can contain letters (A-Z, a-z), digits and punctuation ('.', ',', '/', '-', '_'). How can I make the expression ?
I want something like this :
(r'^(?P<wiki_page>\w+)/$', 'www.wiki.views.page')
but this works only for letters, digits and '_'.
|
[
"Try this regexp:\nr'^(?P<wiki_page>[\\w.,/_\\-]+)/$'\n\n",
"You could replace \\w in the regex with a regex to match what you're looking for. Perhaps\n(r'^(?P<wiki_page>[A-Za-z_/,\\.-]+)$, 'www.wiki.views.page')\n\nor similar.\n",
"I think it's more of a regex question\nr'^(?P<wiki_page>[\\w\\.,_/\\-]+)/$'\n\nyou can build character classes on top of existing ones\nI think you have to escape the dash, or put it last, because dash defines range of characters and you may get a very unexpected side-effect of dash.\n"
] |
[
4,
1,
0
] |
[] |
[] |
[
"django",
"python",
"regex",
"url"
] |
stackoverflow_0001739431_django_python_regex_url.txt
|
Q:
Underscore _ as variable name in Python
Peter Norvig has an essay describing a program to solve sudoku puzzles, even the hardest ones, by combining deterministic logical operations and smart traversal of the possible solutions. The latter is done recursively; here's that function (source):
def search(values):
"Using depth-first search and propagation, try all possible values."
if values is False:
return False ## Failed earlier
if all( len( values[s]) == 1 for s in squares):
return values ## Solved!
## Chose the unfilled square s with the fewest possibilities
_,s = min( (len( values[s]), s)
for s in squares
if len(values[s]) > 1
)
return some( search( assign( values.copy(), s, d))
for d in values[s]
)
(I've added some spaces, CRs, and tabs for the sake of my eyes; apologies to Dr. Norvig.)
Right below the comment there's a line starting with "_,s". That seems to be the unpacked tuple (len(values[s]),s) with the minimal value of s. Is Dr. Norvig using "_" as a variable name just to indicate it's a "don't care" result, or is something else going on? Are there times when "_" is recommended as a variable name? In interactive mode, "_" holds the answer of the previous operation; is there a similar function in non-interactive code?
Update
Thanks for the good answers. I guess The Answer goes to Alex Martelli for "value added"; he points out that the "_, vbl_of_interest" idiom is often a side effect of the DSU idiom, which itself has been made largely unnecessary.
A:
Yep, _ is a traditional name for "don't care" (which unfortunately clashes with its use in I18N, but that's a separate issue;-). BTW, in today's Python, instead of:
_,s = min( (len( values[s]), s)
for s in squares
if len(values[s]) > 1
)
you might code
s = min((s for s in squares if len(values[s])>1),
key=lambda s: len(values[s]))
(not sure what release of Python Peter was writing for, but the idiom he's using is an example of "decorate-sort-undecorate" [[DSU]] except with min instead of sort, and in today's Python the key= optional parameter is generally the best way to do DSU;-).
A:
Your interpretation is correct. Outside of the special meaning in interactive mode _ is just used as a "don't care" variable name, especially in unpacking.
A:
You are correct. In non-interactive mode _ has no special meaning. Indeed, Norvig just wants to convey that he doesn't care about the value of that variable.
Offtopic: That article by Norvig is very nice. A recommended read.
|
Underscore _ as variable name in Python
|
Peter Norvig has an essay describing a program to solve sudoku puzzles, even the hardest ones, by combining deterministic logical operations and smart traversal of the possible solutions. The latter is done recursively; here's that function (source):
def search(values):
"Using depth-first search and propagation, try all possible values."
if values is False:
return False ## Failed earlier
if all( len( values[s]) == 1 for s in squares):
return values ## Solved!
## Chose the unfilled square s with the fewest possibilities
_,s = min( (len( values[s]), s)
for s in squares
if len(values[s]) > 1
)
return some( search( assign( values.copy(), s, d))
for d in values[s]
)
(I've added some spaces, CRs, and tabs for the sake of my eyes; apologies to Dr. Norvig.)
Right below the comment there's a line starting with "_,s". That seems to be the unpacked tuple (len(values[s]),s) with the minimal value of s. Is Dr. Norvig using "_" as a variable name just to indicate it's a "don't care" result, or is something else going on? Are there times when "_" is recommended as a variable name? In interactive mode, "_" holds the answer of the previous operation; is there a similar function in non-interactive code?
Update
Thanks for the good answers. I guess The Answer goes to Alex Martelli for "value added"; he points out that the "_, vbl_of_interest" idiom is often a side effect of the DSU idiom, which itself has been made largely unnecessary.
|
[
"Yep, _ is a traditional name for \"don't care\" (which unfortunately clashes with its use in I18N, but that's a separate issue;-). BTW, in today's Python, instead of:\n_,s = min( (len( values[s]), s) \n for s in squares \n if len(values[s]) > 1\n )\n\nyou might code\ns = min((s for s in squares if len(values[s])>1), \n key=lambda s: len(values[s]))\n\n(not sure what release of Python Peter was writing for, but the idiom he's using is an example of \"decorate-sort-undecorate\" [[DSU]] except with min instead of sort, and in today's Python the key= optional parameter is generally the best way to do DSU;-).\n",
"Your interpretation is correct. Outside of the special meaning in interactive mode _ is just used as a \"don't care\" variable name, especially in unpacking.\n",
"You are correct. In non-interactive mode _ has no special meaning. Indeed, Norvig just wants to convey that he doesn't care about the value of that variable.\nOfftopic: That article by Norvig is very nice. A recommended read.\n"
] |
[
76,
13,
9
] |
[] |
[] |
[
"metasyntactic_variable",
"naming_conventions",
"python",
"variables"
] |
stackoverflow_0001739514_metasyntactic_variable_naming_conventions_python_variables.txt
|
Q:
How to translate python tuple unpacking to Matlab?
I am translating some python code to Matlab, and want to figure out what the best way to translate the python tuple unpacking to Matlab is.
For the purposes of this example, a Body is a class whose constructor takes as input two functionals.
I have the following python code:
X1 = lambda t: cos(t)
Y1 = lambda t: sin(t)
X2 = lambda t: cos(t) + 1
Y2 = lambda t: sin(t) + 1
coords = ((X1,Y1), (X2,Y2))
bodies = [Body(X,Y) for X,Y in coords]
which is translated to the following Matlab code
X1 = @(t) cos(t)
Y1 = @(t) sin(t)
X2 = @(t) cos(t) + 1
Y2 = @(t) sin(t) + 1
coords = {{X1,Y1}, {X2,Y2}}
bodies = {}
for coord = coords,
[X,Y] = deal(coord{1}{:});
bodies{end+1} = Body(X,Y);
end
where Body is
classdef Body < handle
properties
X,Y
end
methods
function self = Body(X,Y)
self.X = X;
self.Y = Y;
end
end
end
Is there a better and more elegant way to express the last line of the python code in Matlab?
A:
Without knowing what Body is, this is my solution:
bodies = cellfun(@(tuple)Body(tuple{1},tuple{2}), coords);
or, if the output has to encapsulated in a cell array:
bodies = cellfun(@(tuple)Body(tuple{1},tuple{2}), coords, 'UniformOutput',false);
And just for testing, I tried it with the following:
X1 = @(t) cos(t);
Y1 = @(t) sin(t);
X2 = @(t) cos(t) + 1;
Y2 = @(t) sin(t) + 1;
coords = {{X1,Y1}, {X2,Y2}};
%# function that returns a struct (like a constructor)
Body = @(X,Y) struct('x',X, 'y',Y);
%# tuples unpacking
bodies = cellfun(@(tuple)Body(tuple{1},tuple{2}), coords);
%# bodies is an array of structs
bodies(1)
bodies(2)
A:
It appears that Amro's answer will work for you. However, if you don't really need or want to create a new Body class, there's a straight-forward way to construct an array of structures using the STRUCT command:
X1 = @(t) cos(t);
Y1 = @(t) sin(t);
X2 = @(t) cos(t) + 1;
Y2 = @(t) sin(t) + 1;
bodies = struct('X',{X1 X2},'Y',{Y1 Y2});
In this case, each element of the array bodies is a structure as opposed to a class object, but you should be able to use it in much the same way.
|
How to translate python tuple unpacking to Matlab?
|
I am translating some python code to Matlab, and want to figure out what the best way to translate the python tuple unpacking to Matlab is.
For the purposes of this example, a Body is a class whose constructor takes as input two functionals.
I have the following python code:
X1 = lambda t: cos(t)
Y1 = lambda t: sin(t)
X2 = lambda t: cos(t) + 1
Y2 = lambda t: sin(t) + 1
coords = ((X1,Y1), (X2,Y2))
bodies = [Body(X,Y) for X,Y in coords]
which is translated to the following Matlab code
X1 = @(t) cos(t)
Y1 = @(t) sin(t)
X2 = @(t) cos(t) + 1
Y2 = @(t) sin(t) + 1
coords = {{X1,Y1}, {X2,Y2}}
bodies = {}
for coord = coords,
[X,Y] = deal(coord{1}{:});
bodies{end+1} = Body(X,Y);
end
where Body is
classdef Body < handle
properties
X,Y
end
methods
function self = Body(X,Y)
self.X = X;
self.Y = Y;
end
end
end
Is there a better and more elegant way to express the last line of the python code in Matlab?
|
[
"Without knowing what Body is, this is my solution:\nbodies = cellfun(@(tuple)Body(tuple{1},tuple{2}), coords);\n\nor, if the output has to encapsulated in a cell array:\nbodies = cellfun(@(tuple)Body(tuple{1},tuple{2}), coords, 'UniformOutput',false);\n\nAnd just for testing, I tried it with the following:\nX1 = @(t) cos(t);\nY1 = @(t) sin(t);\nX2 = @(t) cos(t) + 1;\nY2 = @(t) sin(t) + 1;\n\ncoords = {{X1,Y1}, {X2,Y2}};\n\n%# function that returns a struct (like a constructor)\nBody = @(X,Y) struct('x',X, 'y',Y);\n\n%# tuples unpacking\nbodies = cellfun(@(tuple)Body(tuple{1},tuple{2}), coords);\n\n%# bodies is an array of structs\nbodies(1)\nbodies(2)\n\n",
"It appears that Amro's answer will work for you. However, if you don't really need or want to create a new Body class, there's a straight-forward way to construct an array of structures using the STRUCT command:\nX1 = @(t) cos(t);\nY1 = @(t) sin(t);\nX2 = @(t) cos(t) + 1;\nY2 = @(t) sin(t) + 1;\nbodies = struct('X',{X1 X2},'Y',{Y1 Y2});\n\nIn this case, each element of the array bodies is a structure as opposed to a class object, but you should be able to use it in much the same way.\n"
] |
[
2,
0
] |
[] |
[] |
[
"iterable_unpacking",
"matlab",
"python"
] |
stackoverflow_0001739566_iterable_unpacking_matlab_python.txt
|
Q:
oneliner scramble program
It's that time of year again that programmers want to shuffle a list such that no element resides on its original position (at least in the Netherlands, we celebrate Sinterklaas and pick straws for deciding who writes who a poem). Does anyone have a nice Python single statement for that?
So, input example: range(10)
Output example: [2,8,4,1,3,7,5,9,6,0]
Wrong output would be [2,8,4,1,3,5,7,9,6,0] because the 5 is at its original position. This would mean that person 5 must write a poem to himself and that is less fun.
edit Many people repeat the assignment just as long as needed to get lucky and find that in fact the solution is satisfactory. This is a bad approach as in theory this can take infinitely long. The better approach is indeed suggested by Bart, but I can't get that into a oneliner for one reason or another...
edit By oneliner, I mean single statement. As it appears, Python is also able to compress multiple statements on a single line. I didn't know that. There are currently very nice solutions only using the semicolon to mimic multiline behaviour on a single line. Hence: "can you do it in a single statement?"
A:
I found shuffle can be abused into solving this
from random import shuffle
L = ["Anne", "Beth", "Cath", "Dave", "Emma"]
shuffle(L, int=lambda n: int(n - 1))
print L
The distribution is not uniform however this was not a requirement.
#For 100,000 samples
(('Beth', 'Cath', 'Dave', 'Emma', 'Anne'), 13417)
(('Beth', 'Cath', 'Emma', 'Anne', 'Dave'), 6572)
(('Beth', 'Dave', 'Anne', 'Emma', 'Cath'), 3417)
(('Beth', 'Dave', 'Emma', 'Cath', 'Anne'), 6581)
(('Beth', 'Emma', 'Anne', 'Cath', 'Dave'), 3364)
(('Beth', 'Emma', 'Dave', 'Anne', 'Cath'), 6635)
(('Cath', 'Anne', 'Dave', 'Emma', 'Beth'), 1703)
(('Cath', 'Anne', 'Emma', 'Beth', 'Dave'), 1705)
(('Cath', 'Dave', 'Beth', 'Emma', 'Anne'), 6583)
(('Cath', 'Dave', 'Emma', 'Anne', 'Beth'), 3286)
(('Cath', 'Emma', 'Beth', 'Anne', 'Dave'), 3325)
(('Cath', 'Emma', 'Dave', 'Beth', 'Anne'), 3421)
(('Dave', 'Anne', 'Beth', 'Emma', 'Cath'), 1653)
(('Dave', 'Anne', 'Emma', 'Cath', 'Beth'), 1664)
(('Dave', 'Cath', 'Anne', 'Emma', 'Beth'), 3349)
(('Dave', 'Cath', 'Emma', 'Beth', 'Anne'), 6727)
(('Dave', 'Emma', 'Anne', 'Beth', 'Cath'), 3319)
(('Dave', 'Emma', 'Beth', 'Cath', 'Anne'), 3323)
(('Emma', 'Anne', 'Beth', 'Cath', 'Dave'), 1682)
(('Emma', 'Anne', 'Dave', 'Beth', 'Cath'), 1656)
(('Emma', 'Cath', 'Anne', 'Beth', 'Dave'), 3276)
(('Emma', 'Cath', 'Dave', 'Anne', 'Beth'), 6638)
(('Emma', 'Dave', 'Anne', 'Cath', 'Beth'), 3358)
(('Emma', 'Dave', 'Beth', 'Anne', 'Cath'), 3346)
For a uniform distribution, this (longer) version can be used
from random import shuffle,randint
L=["Anne", "Beth", "Cath", "Dave", "Emma"]
shuffle(L, random=lambda: 1, int=lambda n: randint(0, n - 2))
print L
# For 100,000 samples
(('Beth', 'Cath', 'Dave', 'Emma', 'Anne'), 4157)
(('Beth', 'Cath', 'Emma', 'Anne', 'Dave'), 4155)
(('Beth', 'Dave', 'Anne', 'Emma', 'Cath'), 4099)
(('Beth', 'Dave', 'Emma', 'Cath', 'Anne'), 4141)
(('Beth', 'Emma', 'Anne', 'Cath', 'Dave'), 4243)
(('Beth', 'Emma', 'Dave', 'Anne', 'Cath'), 4208)
(('Cath', 'Anne', 'Dave', 'Emma', 'Beth'), 4219)
(('Cath', 'Anne', 'Emma', 'Beth', 'Dave'), 4087)
(('Cath', 'Dave', 'Beth', 'Emma', 'Anne'), 4117)
(('Cath', 'Dave', 'Emma', 'Anne', 'Beth'), 4127)
(('Cath', 'Emma', 'Beth', 'Anne', 'Dave'), 4198)
(('Cath', 'Emma', 'Dave', 'Beth', 'Anne'), 4210)
(('Dave', 'Anne', 'Beth', 'Emma', 'Cath'), 4179)
(('Dave', 'Anne', 'Emma', 'Cath', 'Beth'), 4119)
(('Dave', 'Cath', 'Anne', 'Emma', 'Beth'), 4143)
(('Dave', 'Cath', 'Emma', 'Beth', 'Anne'), 4203)
(('Dave', 'Emma', 'Anne', 'Beth', 'Cath'), 4252)
(('Dave', 'Emma', 'Beth', 'Cath', 'Anne'), 4159)
(('Emma', 'Anne', 'Beth', 'Cath', 'Dave'), 4193)
(('Emma', 'Anne', 'Dave', 'Beth', 'Cath'), 4177)
(('Emma', 'Cath', 'Anne', 'Beth', 'Dave'), 4087)
(('Emma', 'Cath', 'Dave', 'Anne', 'Beth'), 4150)
(('Emma', 'Dave', 'Anne', 'Cath', 'Beth'), 4268)
(('Emma', 'Dave', 'Beth', 'Anne', 'Cath'), 4109)
How it works
Here is the code for random.shuffle()
def shuffle(self, x, random=None, int=int):
"""x, random=random.random -> shuffle list x in place; return None.
Optional arg random is a 0-argument function returning a random
float in [0.0, 1.0); by default, the standard random.random.
"""
if random is None:
random = self.random
for i in reversed(xrange(1, len(x))):
# pick an element in x[:i+1] with which to exchange x[i]
j = int(random() * (i+1))
x[i], x[j] = x[j], x[i]
Both solutions work by targeting the line j = int(random() * (i+1))
The first(non uniform) effectively makes the line work like this
j = int(random() * (i + 1) - 1)
So instead of a range of (1..i) we obtain (0..i-1)
The second solution replaces random() with a function that always returns 1, and uses randint instead of int. So the line now works like this
j = randint(0, i - 1)
A:
After shuffling the list of numbers, let the [i]th person write a poem (and buy a present!) for the [i+1]th person in the list: that way, there can never be someone who draws him- or herself. Of course, the last one should point to the first...
A:
Shifting every element in the list by one in a circular manner, as suggested by Bart, is easy:
>>> def shift(seq):
... return seq[-1:] + seq[:-1]
...
>>> shift(range(10))
[9, 0, 1, 2, 3, 4, 5, 6, 7, 8]
As for a random solution: in this case the request for a one-liner is not such a good idea, since the obvious function to use, namely random.shuffle, performs its task in place. In other words: it has a side effect, something one usually tries to avoid in list comprehensions. There is a way around this though, as Paul points out, namely by using random.sample. The following code shows two one-liners which use these functions (note the use of not shuffle, to work around the fact that shuffle returns None...):
>>> from itertools import repeat
>>> from random import shuffle
>>> def shake_it(seq):
... return next(c for c in repeat(seq[::]) if not shuffle(c) and all(a != b for a, b in zip(seq, c)))
...
>>> shake_it(range(10))
[7, 9, 0, 2, 6, 8, 5, 1, 4, 3]
>>>
>>> from itertools import count
>>> from random import sample
>>> def shake_it(seq):
... return next(c for c in (sample(seq, len(seq)) for _ in count()) if all(a != b for a, b in zip(seq, c)))
...
>>> shake_it(range(10))
[1, 3, 9, 5, 2, 6, 8, 4, 0, 7]
Myself, I'd go with this one:
>>> def shake_it(seq):
... res = seq[::]
... while any(a == b for a, b in zip(res, seq)):
... shuffle(res)
... return res
...
>>> shake_it(range(10))
[5, 7, 9, 2, 6, 8, 3, 0, 4, 1]
A:
My first Python program in a long while. Unlike many of the above programs, this one takes O(n) time.
s = set(range(10))
r = list()
for i in range(10):
s2 = s - set([i])
val = s2.pop()
r.append(val)
s.discard(val)
print r
UPDATE: Paul showed that the above program was incorrect. Thanks, Paul. Here's a different, better version of the same program:
s = range(10)
for i in range(9):
r = random.randrange(i+1, 10)
s[i], s[r] = s[r], s[i]
print s
A:
Here is how you do it with O(n) time and O(1) extra memory:
Comprehensible code:
def shuffle(a)
n = a.length
(0..n - 2).each do |i|
r = rand(n - i - 1) + i + 1
a[r], a[i] = a[i], a[r]
end
a
end
A one-liner (assumes "a" is the array):
n = a.length and (0..n - 2).each {|i| r = rand(n - i - 1) + i + 1; a[r], a[i] = a[i], a[r]}
The code is in ruby, but without any doubt it's easily translatable to python
Cheers
P.S.: The solution modifies the array.
A:
"One-liner" in fixed O(n) time:
import random; a=range(10) # setup (could read in names instead)
for i in range(len(a)-1,0,-1): j=random.randint(0,i-1); a[j],a[i]=a[i],a[j]
print a # output
The loop picks elements from the maximum index (len(a)-1) down to the next-smallest (1). The choice pool for element k only includes indices from 0 to k-1; once picked, an element will not be moved again.
After the scramble, no element can reside in its original position, because:
if element j is picked for some slot i>j, it will stay there
otherwise, element j will be swapped with some other element from slot i<j, which will stay there
except for the element in slot 0, which will be swapped unconditionally with the element in slot 1 (in the final iteration of the loop) if it has not already been displaced.
[edit: this is logically equivalent to the Ruby answer, I think]
A:
This one is O(N). Having the import in the loops is a bit silly, but you wanted a one liner
L=range(10)
for i in range(1,len(L)):import random;r=random.randint(0,i-1);L[i],L[r]=L[r],L[i]
print L
Here is the output distribution when L=range(5) for 100000 samples
((1, 2, 3, 4, 0), 4231)
((1, 2, 4, 0, 3), 4115)
((1, 3, 0, 4, 2), 4151)
((1, 3, 4, 2, 0), 4108)
((1, 4, 0, 2, 3), 4254)
((1, 4, 3, 0, 2), 4101)
((2, 0, 3, 4, 1), 4158)
((2, 0, 4, 1, 3), 4177)
((2, 3, 1, 4, 0), 4190)
((2, 3, 4, 0, 1), 4117)
((2, 4, 1, 0, 3), 4194)
((2, 4, 3, 1, 0), 4205)
((3, 0, 1, 4, 2), 4325)
((3, 0, 4, 2, 1), 4109)
((3, 2, 0, 4, 1), 4131)
((3, 2, 4, 1, 0), 4153)
((3, 4, 0, 1, 2), 4081)
((3, 4, 1, 2, 0), 4118)
((4, 0, 1, 2, 3), 4294)
((4, 0, 3, 1, 2), 4167)
((4, 2, 0, 1, 3), 4220)
((4, 2, 3, 0, 1), 4179)
((4, 3, 0, 2, 1), 4090)
((4, 3, 1, 0, 2), 4132)
A:
Sorry this isn't a one-liner, but this works
import random
def sinterklaas(n):
l=[]
for a in range(n):
l.append(-1)
i = 0
while i < 10:
index = random.randint(0,n-1)
if l[index] == -1 and index != i:
l[index] = i
i += 1
Cheers
A:
import random; u = range(10)
while sum(u[i]==i for i in range(10)): random.shuffle(u)
(Ok, I have a line 0 in there too...)
A:
For one in O(n):
u=range(10); random.shuffle(u); v=[ u[u[i]] for i in range(10) ]; return [ v[(u[i]+1)%10] for i in u ]
u is the inverse of function v, so v[u[i]+1] is effectively the element following i in array v.
A:
Here's Stephan202's circular shift implemented as a one-liner with a randomly-chosen shift increment:
from random import randrange; s = range(10); r = randrange(1,len(s)-1); print s[-r:] + s[:-r]
|
oneliner scramble program
|
It's that time of year again that programmers want to shuffle a list such that no element resides on its original position (at least in the Netherlands, we celebrate Sinterklaas and pick straws for deciding who writes who a poem). Does anyone have a nice Python single statement for that?
So, input example: range(10)
Output example: [2,8,4,1,3,7,5,9,6,0]
Wrong output would be [2,8,4,1,3,5,7,9,6,0] because the 5 is at its original position. This would mean that person 5 must write a poem to himself and that is less fun.
edit Many people repeat the assignment just as long as needed to get lucky and find that in fact the solution is satisfactory. This is a bad approach as in theory this can take infinitely long. The better approach is indeed suggested by Bart, but I can't get that into a oneliner for one reason or another...
edit By oneliner, I mean single statement. As it appears, Python is also able to compress multiple statements on a single line. I didn't know that. There are currently very nice solutions only using the semicolon to mimic multiline behaviour on a single line. Hence: "can you do it in a single statement?"
|
[
"I found shuffle can be abused into solving this\nfrom random import shuffle\nL = [\"Anne\", \"Beth\", \"Cath\", \"Dave\", \"Emma\"]\nshuffle(L, int=lambda n: int(n - 1))\nprint L\n\nThe distribution is not uniform however this was not a requirement.\n#For 100,000 samples\n\n(('Beth', 'Cath', 'Dave', 'Emma', 'Anne'), 13417)\n(('Beth', 'Cath', 'Emma', 'Anne', 'Dave'), 6572)\n(('Beth', 'Dave', 'Anne', 'Emma', 'Cath'), 3417)\n(('Beth', 'Dave', 'Emma', 'Cath', 'Anne'), 6581)\n(('Beth', 'Emma', 'Anne', 'Cath', 'Dave'), 3364)\n(('Beth', 'Emma', 'Dave', 'Anne', 'Cath'), 6635)\n(('Cath', 'Anne', 'Dave', 'Emma', 'Beth'), 1703)\n(('Cath', 'Anne', 'Emma', 'Beth', 'Dave'), 1705)\n(('Cath', 'Dave', 'Beth', 'Emma', 'Anne'), 6583)\n(('Cath', 'Dave', 'Emma', 'Anne', 'Beth'), 3286)\n(('Cath', 'Emma', 'Beth', 'Anne', 'Dave'), 3325)\n(('Cath', 'Emma', 'Dave', 'Beth', 'Anne'), 3421)\n(('Dave', 'Anne', 'Beth', 'Emma', 'Cath'), 1653)\n(('Dave', 'Anne', 'Emma', 'Cath', 'Beth'), 1664)\n(('Dave', 'Cath', 'Anne', 'Emma', 'Beth'), 3349)\n(('Dave', 'Cath', 'Emma', 'Beth', 'Anne'), 6727)\n(('Dave', 'Emma', 'Anne', 'Beth', 'Cath'), 3319)\n(('Dave', 'Emma', 'Beth', 'Cath', 'Anne'), 3323)\n(('Emma', 'Anne', 'Beth', 'Cath', 'Dave'), 1682)\n(('Emma', 'Anne', 'Dave', 'Beth', 'Cath'), 1656)\n(('Emma', 'Cath', 'Anne', 'Beth', 'Dave'), 3276)\n(('Emma', 'Cath', 'Dave', 'Anne', 'Beth'), 6638)\n(('Emma', 'Dave', 'Anne', 'Cath', 'Beth'), 3358)\n(('Emma', 'Dave', 'Beth', 'Anne', 'Cath'), 3346)\n\nFor a uniform distribution, this (longer) version can be used\nfrom random import shuffle,randint\nL=[\"Anne\", \"Beth\", \"Cath\", \"Dave\", \"Emma\"]\nshuffle(L, random=lambda: 1, int=lambda n: randint(0, n - 2))\nprint L\n\n# For 100,000 samples\n\n(('Beth', 'Cath', 'Dave', 'Emma', 'Anne'), 4157)\n(('Beth', 'Cath', 'Emma', 'Anne', 'Dave'), 4155)\n(('Beth', 'Dave', 'Anne', 'Emma', 'Cath'), 4099)\n(('Beth', 'Dave', 'Emma', 'Cath', 'Anne'), 4141)\n(('Beth', 'Emma', 'Anne', 'Cath', 'Dave'), 4243)\n(('Beth', 'Emma', 'Dave', 'Anne', 'Cath'), 4208)\n(('Cath', 'Anne', 'Dave', 'Emma', 'Beth'), 4219)\n(('Cath', 'Anne', 'Emma', 'Beth', 'Dave'), 4087)\n(('Cath', 'Dave', 'Beth', 'Emma', 'Anne'), 4117)\n(('Cath', 'Dave', 'Emma', 'Anne', 'Beth'), 4127)\n(('Cath', 'Emma', 'Beth', 'Anne', 'Dave'), 4198)\n(('Cath', 'Emma', 'Dave', 'Beth', 'Anne'), 4210)\n(('Dave', 'Anne', 'Beth', 'Emma', 'Cath'), 4179)\n(('Dave', 'Anne', 'Emma', 'Cath', 'Beth'), 4119)\n(('Dave', 'Cath', 'Anne', 'Emma', 'Beth'), 4143)\n(('Dave', 'Cath', 'Emma', 'Beth', 'Anne'), 4203)\n(('Dave', 'Emma', 'Anne', 'Beth', 'Cath'), 4252)\n(('Dave', 'Emma', 'Beth', 'Cath', 'Anne'), 4159)\n(('Emma', 'Anne', 'Beth', 'Cath', 'Dave'), 4193)\n(('Emma', 'Anne', 'Dave', 'Beth', 'Cath'), 4177)\n(('Emma', 'Cath', 'Anne', 'Beth', 'Dave'), 4087)\n(('Emma', 'Cath', 'Dave', 'Anne', 'Beth'), 4150)\n(('Emma', 'Dave', 'Anne', 'Cath', 'Beth'), 4268)\n(('Emma', 'Dave', 'Beth', 'Anne', 'Cath'), 4109)\n\nHow it works\nHere is the code for random.shuffle()\ndef shuffle(self, x, random=None, int=int):\n \"\"\"x, random=random.random -> shuffle list x in place; return None.\n\n Optional arg random is a 0-argument function returning a random\n float in [0.0, 1.0); by default, the standard random.random.\n \"\"\"\n\n if random is None:\n random = self.random\n for i in reversed(xrange(1, len(x))):\n # pick an element in x[:i+1] with which to exchange x[i]\n j = int(random() * (i+1))\n x[i], x[j] = x[j], x[i]\n\nBoth solutions work by targeting the line j = int(random() * (i+1))\nThe first(non uniform) effectively makes the line work like this\nj = int(random() * (i + 1) - 1)\n\nSo instead of a range of (1..i) we obtain (0..i-1)\nThe second solution replaces random() with a function that always returns 1, and uses randint instead of int. So the line now works like this\nj = randint(0, i - 1)\n\n",
"After shuffling the list of numbers, let the [i]th person write a poem (and buy a present!) for the [i+1]th person in the list: that way, there can never be someone who draws him- or herself. Of course, the last one should point to the first...\n",
"Shifting every element in the list by one in a circular manner, as suggested by Bart, is easy:\n>>> def shift(seq):\n... return seq[-1:] + seq[:-1]\n... \n>>> shift(range(10))\n[9, 0, 1, 2, 3, 4, 5, 6, 7, 8]\n\nAs for a random solution: in this case the request for a one-liner is not such a good idea, since the obvious function to use, namely random.shuffle, performs its task in place. In other words: it has a side effect, something one usually tries to avoid in list comprehensions. There is a way around this though, as Paul points out, namely by using random.sample. The following code shows two one-liners which use these functions (note the use of not shuffle, to work around the fact that shuffle returns None...):\n>>> from itertools import repeat\n>>> from random import shuffle\n>>> def shake_it(seq):\n... return next(c for c in repeat(seq[::]) if not shuffle(c) and all(a != b for a, b in zip(seq, c)))\n... \n>>> shake_it(range(10))\n[7, 9, 0, 2, 6, 8, 5, 1, 4, 3]\n>>> \n>>> from itertools import count\n>>> from random import sample\n>>> def shake_it(seq):\n... return next(c for c in (sample(seq, len(seq)) for _ in count()) if all(a != b for a, b in zip(seq, c)))\n... \n>>> shake_it(range(10))\n[1, 3, 9, 5, 2, 6, 8, 4, 0, 7]\n\nMyself, I'd go with this one:\n>>> def shake_it(seq):\n... res = seq[::]\n... while any(a == b for a, b in zip(res, seq)):\n... shuffle(res)\n... return res\n... \n>>> shake_it(range(10))\n[5, 7, 9, 2, 6, 8, 3, 0, 4, 1]\n\n",
"My first Python program in a long while. Unlike many of the above programs, this one takes O(n) time.\ns = set(range(10))\nr = list()\nfor i in range(10):\n s2 = s - set([i])\n val = s2.pop()\n r.append(val)\n s.discard(val)\n\nprint r\n\nUPDATE: Paul showed that the above program was incorrect. Thanks, Paul. Here's a different, better version of the same program:\ns = range(10)\nfor i in range(9):\n r = random.randrange(i+1, 10)\n s[i], s[r] = s[r], s[i]\n\nprint s\n\n",
"Here is how you do it with O(n) time and O(1) extra memory:\nComprehensible code:\ndef shuffle(a)\n n = a.length\n (0..n - 2).each do |i|\n r = rand(n - i - 1) + i + 1\n a[r], a[i] = a[i], a[r]\n end\n a\nend\n\nA one-liner (assumes \"a\" is the array):\nn = a.length and (0..n - 2).each {|i| r = rand(n - i - 1) + i + 1; a[r], a[i] = a[i], a[r]}\n\nThe code is in ruby, but without any doubt it's easily translatable to python\nCheers\nP.S.: The solution modifies the array.\n",
"\"One-liner\" in fixed O(n) time:\nimport random; a=range(10) # setup (could read in names instead)\nfor i in range(len(a)-1,0,-1): j=random.randint(0,i-1); a[j],a[i]=a[i],a[j]\nprint a # output\n\nThe loop picks elements from the maximum index (len(a)-1) down to the next-smallest (1). The choice pool for element k only includes indices from 0 to k-1; once picked, an element will not be moved again.\nAfter the scramble, no element can reside in its original position, because:\n\nif element j is picked for some slot i>j, it will stay there\notherwise, element j will be swapped with some other element from slot i<j, which will stay there\nexcept for the element in slot 0, which will be swapped unconditionally with the element in slot 1 (in the final iteration of the loop) if it has not already been displaced.\n\n[edit: this is logically equivalent to the Ruby answer, I think]\n",
"This one is O(N). Having the import in the loops is a bit silly, but you wanted a one liner\nL=range(10)\nfor i in range(1,len(L)):import random;r=random.randint(0,i-1);L[i],L[r]=L[r],L[i]\nprint L\n\nHere is the output distribution when L=range(5) for 100000 samples\n((1, 2, 3, 4, 0), 4231)\n((1, 2, 4, 0, 3), 4115)\n((1, 3, 0, 4, 2), 4151)\n((1, 3, 4, 2, 0), 4108)\n((1, 4, 0, 2, 3), 4254)\n((1, 4, 3, 0, 2), 4101)\n((2, 0, 3, 4, 1), 4158)\n((2, 0, 4, 1, 3), 4177)\n((2, 3, 1, 4, 0), 4190)\n((2, 3, 4, 0, 1), 4117)\n((2, 4, 1, 0, 3), 4194)\n((2, 4, 3, 1, 0), 4205)\n((3, 0, 1, 4, 2), 4325)\n((3, 0, 4, 2, 1), 4109)\n((3, 2, 0, 4, 1), 4131)\n((3, 2, 4, 1, 0), 4153)\n((3, 4, 0, 1, 2), 4081)\n((3, 4, 1, 2, 0), 4118)\n((4, 0, 1, 2, 3), 4294)\n((4, 0, 3, 1, 2), 4167)\n((4, 2, 0, 1, 3), 4220)\n((4, 2, 3, 0, 1), 4179)\n((4, 3, 0, 2, 1), 4090)\n((4, 3, 1, 0, 2), 4132)\n\n",
"Sorry this isn't a one-liner, but this works\nimport random\ndef sinterklaas(n):\n l=[]\n for a in range(n):\n l.append(-1)\n\n i = 0\n while i < 10:\n index = random.randint(0,n-1)\n if l[index] == -1 and index != i:\n l[index] = i\n i += 1\n\nCheers\n",
"import random; u = range(10)\nwhile sum(u[i]==i for i in range(10)): random.shuffle(u)\n\n(Ok, I have a line 0 in there too...)\n",
"For one in O(n):\nu=range(10); random.shuffle(u); v=[ u[u[i]] for i in range(10) ]; return [ v[(u[i]+1)%10] for i in u ]\n\nu is the inverse of function v, so v[u[i]+1] is effectively the element following i in array v.\n",
"Here's Stephan202's circular shift implemented as a one-liner with a randomly-chosen shift increment:\nfrom random import randrange; s = range(10); r = randrange(1,len(s)-1); print s[-r:] + s[:-r]\n\n"
] |
[
6,
5,
3,
1,
1,
1,
1,
0,
0,
0,
0
] |
[] |
[] |
[
"code_golf",
"python",
"shuffle"
] |
stackoverflow_0001735561_code_golf_python_shuffle.txt
|
Q:
Elixir not creating my tables with default values
class MyObject(Entity):
name = Field(Unicode(256), default=u'default name', nullable=False)
using_options(shortnames=True)
using_mapper_options(save_on_init=False)
def __init__(self):
self.name = None
I am using MySQL in this case, but have also checked against SQLite and I get the same result. It respects nullable, but ignores default entirely. I don't get any error messages, and it creates the tables just fine. I could go back through and add the defaults, but this is a serious pain that I would like to avoid if possible.
I've tried it with other Field types, but still no joy.
A:
default keyword argument in SQLAlchemy is for Python runtime default value, it's used for INSERT statements. Use PassiveDefault() object as positional argument when you really need database level default.
|
Elixir not creating my tables with default values
|
class MyObject(Entity):
name = Field(Unicode(256), default=u'default name', nullable=False)
using_options(shortnames=True)
using_mapper_options(save_on_init=False)
def __init__(self):
self.name = None
I am using MySQL in this case, but have also checked against SQLite and I get the same result. It respects nullable, but ignores default entirely. I don't get any error messages, and it creates the tables just fine. I could go back through and add the defaults, but this is a serious pain that I would like to avoid if possible.
I've tried it with other Field types, but still no joy.
|
[
"default keyword argument in SQLAlchemy is for Python runtime default value, it's used for INSERT statements. Use PassiveDefault() object as positional argument when you really need database level default. \n"
] |
[
2
] |
[] |
[] |
[
"python",
"python_elixir",
"sqlalchemy"
] |
stackoverflow_0001740040_python_python_elixir_sqlalchemy.txt
|
Q:
Problem with pexpect and 'chained' function calls
The class below is designed to manipulate a cisco-like device interface, for the purpose of executing commands and updating configuration elements.
As is currently stands, I can instantiate the class, make a call to the ssh_to_aos_expsh function and get back valid output (e.g. get the config when the command is 'show running-config'). However, when I make a call to the ssh_to_aos_config function (which calls the ssh_to_aos_expsh function), I get a pexpect timeout error.
I've compared the pexpect object (the 'child' in the _ssh_connect, ssh_to_aos_expsh and ssh_to_aos_config) returned by _ssh_connect to ssh_to_aos_expsh to the object returned by ssh_to_aos_expsh to ssh_toaos_config and it appears to be at the same memory location, so I'm not clear why I can't continue to manipulate the object with pexpect.
I'm not the most sophisticated python coder, so it's possible I've made some inadvertent mistake whilst trying to pass the pexpect object between functions, and if so, I would appreciate someone pointing out my mistake.
#!/usr/bin/env python
import os
import traceback
import pexpect
class SSHTool():
def __init__(self):
self.aos_user = 'some_user'
self.aos_passwd = 'some_passwd'
self.aos_init_prompt = 'accelerator>'
self.aos_enable_prompt = 'accelerator#'
self.aos_lnxsh_prompt = 'ACC#'
self.linux_passwd = 'linux_passwd'
self.root_prompt = ''
def _timeout_error(self, child):
print 'SSH could not login. Timeout error.'
print child.before, child.after
return None
def _password_error(self, child):
print 'SSH could not login. Password error.'
print child.before, child.after
return None
def _ssh_connect(self, user, address, passwd):
self.root_prompt = "root@%s's password: " % address
ssh_newkey = "Are you sure you want to continue connecting"
child = pexpect.spawn('ssh -l %s %s' % (user, address))
i = child.expect([pexpect.TIMEOUT, \
ssh_newkey, \
'Password: ', \
self.root_prompt])
if i == 0: # Timeout
return self._timeout_error(child)
elif i == 1: # SSH does not have the public key. Just accept it.
child.sendline ('yes')
i = child.expect([pexpect.TIMEOUT, \
'Password: ', \
self.root_prompt])
if i == 0: # Timeout
return self._timeout_error(child)
else:
child.sendline(passwd)
return child
elif i == 2 or i == 3:
child.sendline(passwd)
return child
else:
return self._password_error(child)
def ssh_to_aos_expsh(self, ip_address, command = ''):
child = self._ssh_connect(self.aos_user, \
ip_address, \
self.aos_passwd)
i = child.expect([pexpect.TIMEOUT, \
self.aos_init_prompt])
if i == 0:
return self._timeout_error(child)
child.sendline('enable')
i = child.expect([pexpect.TIMEOUT, \
self.aos_enable_prompt])
if i == 0:
return self._timeout_error(child)
if command:
child.sendline(command)
i = child.expect([pexpect.TIMEOUT, \
self.aos_enable_prompt])
if i == 0:
return self._timeout_error(child)
else:
return child.before
else:
return child
def ssh_to_aos_config(self, ip_address, command):
child = self.ssh_to_aos_expsh(ip_address)
i = child.expect([pexpect.TIMEOUT, \
self.aos_enable_prompt])
if i == 0:
return self._timeout_error(child)
child.sendline('config')
i = child.expect([pexpect.TIMEOUT, \
self.aos_config_prompt])
if i == 0:
return self._timeout_error(child)
child.sendline(command)
i = child.expect([pexpect.TIMEOUT, \
self.aos_config_prompt])
if i == 0:
return self._timeout_error(child)
else:
return child.before
A:
It turns out that there were two problems, both easy to fix once I knew what the issues were. First, the __init__ method contains no self.aos_config_prompt - something which the pexpect exception stated pretty clearly when I commented out my exception handling code. Second, given a self.aos_config_prompt that looked like 'accelerator(config)#', pexpect compiles that into re module matching code, which will only then match a prompt containing the contents of the parentheses. Simply escape the parentheses in the string and the match works as desired.
A:
I would guess that the timeout happens because ssh_to_aos_config() does not get all the input it expects: the call to ssh_to_aos_expsh() might well work, while subsequent calls to expect would not.
So a question would be: where does the timeout happen? You could track this by raising an exception instead of returning self._timeout_error(child). The location you find would point to an input that pexpect never gets (hence the timeout), and you could update your code there.
A:
If you are getting a timeout it is because you are not getting any of the strings you are expecting. It may be that you are getting an error message instead, or the prompt you are expecting is wrong.
Enable logging to see the whole interaction - in pexpect 2.3 this is done by assigning a file object to the child.logfile attribute - then you can see exactly what is happening. Check the docs for earlier versions, since I think this has changed.
I notice a couple of things in your code:
1) the root_prompt is an empty string. This will always match immediately, even if nothing has been returned from the client. This may be the cause of your problem - the ssh connect function thinks it has seen the prompt and successfully logged in, while the client is still waiting for some other input.
2) there is a syntax error in your code - in ssh_connect you have the sequence:
if i == 0: # Timeout
return self._timeout_error(child)
else:
child.sendline(passwd)
return child
elif i == 2 or i == 3:
child.sendline(passwd)
return child
else:
return self._password_error(child)
The elif does not match up with an if statement, so AFAIK this would never compile. I presume it is a cut & paste error, since you say you have been running the code.
|
Problem with pexpect and 'chained' function calls
|
The class below is designed to manipulate a cisco-like device interface, for the purpose of executing commands and updating configuration elements.
As is currently stands, I can instantiate the class, make a call to the ssh_to_aos_expsh function and get back valid output (e.g. get the config when the command is 'show running-config'). However, when I make a call to the ssh_to_aos_config function (which calls the ssh_to_aos_expsh function), I get a pexpect timeout error.
I've compared the pexpect object (the 'child' in the _ssh_connect, ssh_to_aos_expsh and ssh_to_aos_config) returned by _ssh_connect to ssh_to_aos_expsh to the object returned by ssh_to_aos_expsh to ssh_toaos_config and it appears to be at the same memory location, so I'm not clear why I can't continue to manipulate the object with pexpect.
I'm not the most sophisticated python coder, so it's possible I've made some inadvertent mistake whilst trying to pass the pexpect object between functions, and if so, I would appreciate someone pointing out my mistake.
#!/usr/bin/env python
import os
import traceback
import pexpect
class SSHTool():
def __init__(self):
self.aos_user = 'some_user'
self.aos_passwd = 'some_passwd'
self.aos_init_prompt = 'accelerator>'
self.aos_enable_prompt = 'accelerator#'
self.aos_lnxsh_prompt = 'ACC#'
self.linux_passwd = 'linux_passwd'
self.root_prompt = ''
def _timeout_error(self, child):
print 'SSH could not login. Timeout error.'
print child.before, child.after
return None
def _password_error(self, child):
print 'SSH could not login. Password error.'
print child.before, child.after
return None
def _ssh_connect(self, user, address, passwd):
self.root_prompt = "root@%s's password: " % address
ssh_newkey = "Are you sure you want to continue connecting"
child = pexpect.spawn('ssh -l %s %s' % (user, address))
i = child.expect([pexpect.TIMEOUT, \
ssh_newkey, \
'Password: ', \
self.root_prompt])
if i == 0: # Timeout
return self._timeout_error(child)
elif i == 1: # SSH does not have the public key. Just accept it.
child.sendline ('yes')
i = child.expect([pexpect.TIMEOUT, \
'Password: ', \
self.root_prompt])
if i == 0: # Timeout
return self._timeout_error(child)
else:
child.sendline(passwd)
return child
elif i == 2 or i == 3:
child.sendline(passwd)
return child
else:
return self._password_error(child)
def ssh_to_aos_expsh(self, ip_address, command = ''):
child = self._ssh_connect(self.aos_user, \
ip_address, \
self.aos_passwd)
i = child.expect([pexpect.TIMEOUT, \
self.aos_init_prompt])
if i == 0:
return self._timeout_error(child)
child.sendline('enable')
i = child.expect([pexpect.TIMEOUT, \
self.aos_enable_prompt])
if i == 0:
return self._timeout_error(child)
if command:
child.sendline(command)
i = child.expect([pexpect.TIMEOUT, \
self.aos_enable_prompt])
if i == 0:
return self._timeout_error(child)
else:
return child.before
else:
return child
def ssh_to_aos_config(self, ip_address, command):
child = self.ssh_to_aos_expsh(ip_address)
i = child.expect([pexpect.TIMEOUT, \
self.aos_enable_prompt])
if i == 0:
return self._timeout_error(child)
child.sendline('config')
i = child.expect([pexpect.TIMEOUT, \
self.aos_config_prompt])
if i == 0:
return self._timeout_error(child)
child.sendline(command)
i = child.expect([pexpect.TIMEOUT, \
self.aos_config_prompt])
if i == 0:
return self._timeout_error(child)
else:
return child.before
|
[
"It turns out that there were two problems, both easy to fix once I knew what the issues were. First, the __init__ method contains no self.aos_config_prompt - something which the pexpect exception stated pretty clearly when I commented out my exception handling code. Second, given a self.aos_config_prompt that looked like 'accelerator(config)#', pexpect compiles that into re module matching code, which will only then match a prompt containing the contents of the parentheses. Simply escape the parentheses in the string and the match works as desired. \n",
"I would guess that the timeout happens because ssh_to_aos_config() does not get all the input it expects: the call to ssh_to_aos_expsh() might well work, while subsequent calls to expect would not.\nSo a question would be: where does the timeout happen? You could track this by raising an exception instead of returning self._timeout_error(child). The location you find would point to an input that pexpect never gets (hence the timeout), and you could update your code there.\n",
"If you are getting a timeout it is because you are not getting any of the strings you are expecting. It may be that you are getting an error message instead, or the prompt you are expecting is wrong.\nEnable logging to see the whole interaction - in pexpect 2.3 this is done by assigning a file object to the child.logfile attribute - then you can see exactly what is happening. Check the docs for earlier versions, since I think this has changed.\nI notice a couple of things in your code:\n1) the root_prompt is an empty string. This will always match immediately, even if nothing has been returned from the client. This may be the cause of your problem - the ssh connect function thinks it has seen the prompt and successfully logged in, while the client is still waiting for some other input.\n2) there is a syntax error in your code - in ssh_connect you have the sequence:\nif i == 0: # Timeout\n return self._timeout_error(child)\nelse:\n child.sendline(passwd)\n return child\nelif i == 2 or i == 3:\n child.sendline(passwd)\n return child\nelse:\n return self._password_error(child)\n\nThe elif does not match up with an if statement, so AFAIK this would never compile. I presume it is a cut & paste error, since you say you have been running the code.\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"pexpect",
"python"
] |
stackoverflow_0001727591_pexpect_python.txt
|
Q:
Can i integrate Blender with Phanthom Omni
I have some project about game programming, which have to use blender with phanthom ,Don't know possible to do it
A:
If you mean Phantom Omni, the haptic feedback device, and you mean Blender, the rendering program, then I don't see any reason why you can't use the API for both of them in a program, together to make a game.
In short, if your questions means what I think it does, of course.
|
Can i integrate Blender with Phanthom Omni
|
I have some project about game programming, which have to use blender with phanthom ,Don't know possible to do it
|
[
"If you mean Phantom Omni, the haptic feedback device, and you mean Blender, the rendering program, then I don't see any reason why you can't use the API for both of them in a program, together to make a game.\nIn short, if your questions means what I think it does, of course. \n"
] |
[
0
] |
[] |
[] |
[
"blender",
"python"
] |
stackoverflow_0001740299_blender_python.txt
|
Q:
Integrating a simple web server into a custom main loop in python?
I have an application in python with a custom main loop (I don't believe the details are important). I'd like to integrate a simple non-blocking web server into the application which can introspect the application objects and possibly provide an interface to manipulate them. What's the best way to do this?
I'd like to avoid anything that uses threading. The ideal solution would be a server with a "stepping" function that can be called from my main loop, do its thing, then return program control until the next go-round.
The higher-level the solution, the better (though something as monolithic as Django might be overkill).
Ideally, a solution will look like this:
def main():
"""My main loop."""
http_server = SomeCoolHttpServer(port=8888)
while True:
# Do my stuff here...
# ...
http_server.next() # Server gets it's turn.
# Do more of my stuff here...
# ...
A:
Twisted is designed to make stuff like that fairly simple
import time
from twisted.web import server, resource
from twisted.internet import reactor
class Simple(resource.Resource):
isLeaf = True
def render_GET(self, request):
return "<html>%s Iterations!</html>"%n
def main():
global n
site = server.Site(Simple())
reactor.listenTCP(8080, site)
reactor.startRunning(False)
n=0
while True:
n+=1
if n%1000==0:
print n
time.sleep(0.001)
reactor.iterate()
if __name__=="__main__":
main()
|
Integrating a simple web server into a custom main loop in python?
|
I have an application in python with a custom main loop (I don't believe the details are important). I'd like to integrate a simple non-blocking web server into the application which can introspect the application objects and possibly provide an interface to manipulate them. What's the best way to do this?
I'd like to avoid anything that uses threading. The ideal solution would be a server with a "stepping" function that can be called from my main loop, do its thing, then return program control until the next go-round.
The higher-level the solution, the better (though something as monolithic as Django might be overkill).
Ideally, a solution will look like this:
def main():
"""My main loop."""
http_server = SomeCoolHttpServer(port=8888)
while True:
# Do my stuff here...
# ...
http_server.next() # Server gets it's turn.
# Do more of my stuff here...
# ...
|
[
"Twisted is designed to make stuff like that fairly simple\nimport time\n\nfrom twisted.web import server, resource\nfrom twisted.internet import reactor\n\nclass Simple(resource.Resource):\n isLeaf = True\n def render_GET(self, request):\n return \"<html>%s Iterations!</html>\"%n\n\ndef main():\n global n\n site = server.Site(Simple())\n reactor.listenTCP(8080, site)\n reactor.startRunning(False)\n n=0\n while True:\n n+=1\n if n%1000==0:\n print n\n time.sleep(0.001)\n reactor.iterate()\n\nif __name__==\"__main__\":\n main()\n\n"
] |
[
7
] |
[
"I'd suggest creating a new thread and running a web server (such as Python's built-in SimpleHTTPServer or BaseHTTPServer). Threads really aren't that scary when it comes down to it.\nfrom threading import Event, Thread\nimport BaseHTTPServer\n\nshut_down = Event()\n\ndef http_server():\n server_address = ('', 8000)\n httpd = BaseHTTPServer.HTTPServer(server_address, BaseHTTPServer.BaseHTTPRequestHandler)\n\n while not shut_down.is_set():\n httpd.handle_request()\n\nthread = Thread(target=http_server)\nthread.start()\n\n"
] |
[
-1
] |
[
"loops",
"python"
] |
stackoverflow_0001740235_loops_python.txt
|
Q:
Python threading strange behaviour
from threading import *
from time import *
class MyThread(Thread):
def __init__(self,x):
self.x = x
Thread.__init__(self)
def run(self):
sleep(2)
print(self.x)
if __name__=='__main__':
threads = []
for i in range(5):
threads.append(MyThread('Hello'))
for i in range(5):
threads[i].start()
for i in range(5):
threads[i].join()
This code print 'Hello' 10 times but if I comment "sleep(2)" it prints 'Hello' 5 times.
What is the problems with sleep() function? OR Where is the problem?
I am using Python3000.
A:
It looks like you've run into the problem documented in Python bug tracker issue 6750. Fixes for the problem are checked in and will appear in the next maintenance release of Python 3.1, if there is one, or in Python 3.2.
$ python3.1 test_thread.py
Hello
Hello
Hello
Hello
Hello
Hello
Hello
$ python3.2 test_thread.py
Hello
Hello
Hello
Hello
Hello
A:
I think you've found a bug in Python 3 -- I can reproduce your results running under the latest released Py 3.1, but with 2.6 the results are as expected (only five lines emitted either way, though the newlines can get bunched up surprisingly wrt the contents that's within the specs of threaded behavior). Please open a bug at bugs.python.org!!!
|
Python threading strange behaviour
|
from threading import *
from time import *
class MyThread(Thread):
def __init__(self,x):
self.x = x
Thread.__init__(self)
def run(self):
sleep(2)
print(self.x)
if __name__=='__main__':
threads = []
for i in range(5):
threads.append(MyThread('Hello'))
for i in range(5):
threads[i].start()
for i in range(5):
threads[i].join()
This code print 'Hello' 10 times but if I comment "sleep(2)" it prints 'Hello' 5 times.
What is the problems with sleep() function? OR Where is the problem?
I am using Python3000.
|
[
"It looks like you've run into the problem documented in Python bug tracker issue 6750. Fixes for the problem are checked in and will appear in the next maintenance release of Python 3.1, if there is one, or in Python 3.2.\n$ python3.1 test_thread.py \nHello\nHello\nHello\nHello\nHello\nHello\nHello\n$ python3.2 test_thread.py \nHello\nHello\nHello\nHello\nHello\n\n",
"I think you've found a bug in Python 3 -- I can reproduce your results running under the latest released Py 3.1, but with 2.6 the results are as expected (only five lines emitted either way, though the newlines can get bunched up surprisingly wrt the contents that's within the specs of threaded behavior). Please open a bug at bugs.python.org!!!\n"
] |
[
2,
0
] |
[] |
[] |
[
"multithreading",
"python"
] |
stackoverflow_0001740485_multithreading_python.txt
|
Q:
XML attributes get sorted
When I create a document using the minidom, attributes get sorted alphabetically in the element. Take this example from here:
from xml.dom import minidom
# New document
xml = minidom.Document()
# Creates user element
userElem = xml.createElement("user")
# Set attributes to user element
userElem.setAttribute("name", "Sergio Oliveira")
userElem.setAttribute("nickname", "seocam")
userElem.setAttribute("email", "seocam@taboca.com")
userElem.setAttribute("photo","seocam.png")
# Append user element in xml document
xml.appendChild(userElem)
# Print the xml code
print xml.toprettyxml()
The result is this:
<?xml version="1.0" ?>
<user email="seocam@taboca.com" name="Sergio Oliveira" nickname="seocam" photo="seocam.png"/>
Which is all very well if you wanted the attributes in email/name/nickname/photo order instead of name/nickname/email/photo order as they were created.
How do you get the attributes to show up in the order you created them? Or, how do you control the order at all?
A:
According to the documentation, the order of attributes is arbitrary but consistent for the life of the DOM. This is common across DOM implementations. Sorry.
|
XML attributes get sorted
|
When I create a document using the minidom, attributes get sorted alphabetically in the element. Take this example from here:
from xml.dom import minidom
# New document
xml = minidom.Document()
# Creates user element
userElem = xml.createElement("user")
# Set attributes to user element
userElem.setAttribute("name", "Sergio Oliveira")
userElem.setAttribute("nickname", "seocam")
userElem.setAttribute("email", "seocam@taboca.com")
userElem.setAttribute("photo","seocam.png")
# Append user element in xml document
xml.appendChild(userElem)
# Print the xml code
print xml.toprettyxml()
The result is this:
<?xml version="1.0" ?>
<user email="seocam@taboca.com" name="Sergio Oliveira" nickname="seocam" photo="seocam.png"/>
Which is all very well if you wanted the attributes in email/name/nickname/photo order instead of name/nickname/email/photo order as they were created.
How do you get the attributes to show up in the order you created them? Or, how do you control the order at all?
|
[
"According to the documentation, the order of attributes is arbitrary but consistent for the life of the DOM. This is common across DOM implementations. Sorry.\n"
] |
[
5
] |
[] |
[] |
[
"minidom",
"python",
"xml"
] |
stackoverflow_0001740731_minidom_python_xml.txt
|
Q:
Python: Behavior of the garbage collector
I have a Django application that exhibits some strange garbage collection behavior. There is one view in particular that will just keep growing the VM size significantly every time it is called - up to a certain limit, at which point usage drops back again. The problem is that it's taking considerable time until that point is reached, and in fact the virtual machine running my app doesn't have enough memory for all FCGI processes to take as much memory as they then sometimes do.
I've spent the last two days investigating this and learning about Python garbage collection, and I think I do understand what is happening now - for the most part. When using
gc.set_debug(gc.DEBUG_STATS)
Then for a single request, I see the following output:
>>> c = django.test.Client()
>>> c.get('/the/view/')
gc: collecting generation 0...
gc: objects in each generation: 724 5748 147341
gc: done.
gc: collecting generation 0...
gc: objects in each generation: 731 6460 147341
gc: done.
[...more of the same...]
gc: collecting generation 1...
gc: objects in each generation: 718 8577 147341
gc: done.
gc: collecting generation 0...
gc: objects in each generation: 714 0 156614
gc: done.
[...more of the same...]
gc: collecting generation 0...
gc: objects in each generation: 715 5578 156612
gc: done.
So essentially, a huge amount of objects are allocated, but are initially moved to generation 1, and when gen 1 is sweeped during the same request, they are moved to generation 2. If I do a manual gc.collect(2) afterwards, they are removed. And, as I mentioned, there also removed when the next automatic gen 2 sweep happens, which, if I understand correctly, would in this case something like every 10 requests (at this point the app needs about a 150MB).
Alright, so initially I thought that there might be some cyclic referencing going on within the processing of one request that prevents any of these objects from being collected within the handling of that request. However, I've spent hours trying to find one using pympler.muppy and objgraph, both after and by debugging inside the request processing, and there don't seem to be any. Rather, it seems the 14.000 objects or so that are created during the request are all within a reference chain to some request-global object, i.e. once the request goes away, they can be freed.
That has been my attempt at explaining it, anyway. However, if that's true and there are indeed no cycling dependencies, shouldn't the whole tree of objects be freed once whatever request object that causes them to be held goes away, without the garbage collector being involved, purely by virtue of the reference counts dropping to zero?
With that setup, here are my questions:
Does the above even make sense, or do I have to look for the problem elsewhere? Is it just an unfortunate accident that significant data is kept around for so long in this particular use case?
Is there anything I can do to avoid the issue. I already see some potential to optimize the view, but that appears to be a solution with limited scope - although I am not sure what I generic one would be, either; how advisable is it for example to call gc.collect() or gc.set_threshold() manually?
In terms of how the garbage collector itself works:
Do I understand correctly that an object is always moved to the next generation if a sweep looks at it and determines that the references it has are not cyclic, but can in fact be traced to a root object.
What happens if the gc does a, say, generation 1 sweep, and finds an object that is referenced by an object within generation 2; does it follow that relationship inside generation 2, or does it wait for a generation 2 sweep to occur before analyzing the situation?
When using gc.DEBUG_STATS, I care primarily about the "objects in each generation" info; however, I keep getting hundreds of "gc: 0.0740s elapsed.", "gc: 1258233035.9370s elapsed." messages; they are totally inconvenient - it takes considerable time for them to be printed out, and they make the interesting things a lot harder to find. Is there a way to get rid of them?
I don't suppose there is a way to do a gc.get_objects() by generation, i.e. only retrieve the objects from generation 2, for example?
A:
Does the above even make sense, or do I have to look for the problem elsewhere? Is it just an unfortunate accident that significant data is kept around for so long in this particular use case?
Yes, it does make sense. And yes, there are other issues worth to consider. Django uses threading.local as base for DatabaseWrapper (and some contribs use it to make request object accessible from places where it's not passed explicitly). These global objects survive requests and can keep references to objects till some other view is handled in the thread.
Is there anything I can do to avoid the issue. I already see some potential to optimize the view, but that appears to be a solution with limited scope - although I am not sure what I generic one would be, either; how advisable is it for example to call gc.collect() or gc.set_threshold() manually?
General advice (probably you know it, but anyway): avoid circular references and globals (including threading.local). Try to break cycles and clear globals when django design makes hard to avoid them. gc.get_referrers(obj) might help you to find places requiring attention. Another way it to disable garbage collector and call it manually after each request, when it's the best place to do (this will prevent objects from moving to the next generation).
I don't suppose there is a way to do a gc.get_objects() by generation, i.e. only retrieve the objects from generation 2, for example?
Unfortunately this is not possible with gc interface. But there are several ways to go. You can consider the end of list returned by gc.get_objects() only, since objects in this list are sorted by generation. You can compare the list with one returned from previous call by storing weak references to them (e.g. in WeakKeyDictionary) between calls. You can rewrite gc.get_objects() in your own C module (it's easy, mostly copy-paste programming!) since they are stored by generation internally, or even access internal structures with ctypes (requires quite deep ctypes understanding).
A:
I think your analysis looks sound. I'm not an expert on the gc, so whenever I have a problem like this I just add a call to gc.collect() in an appropriate, non time critical place, and forget about it.
I'd suggest you call gc.collect() in your view(s) and see what effect it has on your response time and your memory usage.
Note also this question which suggests that setting DEBUG=True eats memory like it is nearly past its sell by date.
|
Python: Behavior of the garbage collector
|
I have a Django application that exhibits some strange garbage collection behavior. There is one view in particular that will just keep growing the VM size significantly every time it is called - up to a certain limit, at which point usage drops back again. The problem is that it's taking considerable time until that point is reached, and in fact the virtual machine running my app doesn't have enough memory for all FCGI processes to take as much memory as they then sometimes do.
I've spent the last two days investigating this and learning about Python garbage collection, and I think I do understand what is happening now - for the most part. When using
gc.set_debug(gc.DEBUG_STATS)
Then for a single request, I see the following output:
>>> c = django.test.Client()
>>> c.get('/the/view/')
gc: collecting generation 0...
gc: objects in each generation: 724 5748 147341
gc: done.
gc: collecting generation 0...
gc: objects in each generation: 731 6460 147341
gc: done.
[...more of the same...]
gc: collecting generation 1...
gc: objects in each generation: 718 8577 147341
gc: done.
gc: collecting generation 0...
gc: objects in each generation: 714 0 156614
gc: done.
[...more of the same...]
gc: collecting generation 0...
gc: objects in each generation: 715 5578 156612
gc: done.
So essentially, a huge amount of objects are allocated, but are initially moved to generation 1, and when gen 1 is sweeped during the same request, they are moved to generation 2. If I do a manual gc.collect(2) afterwards, they are removed. And, as I mentioned, there also removed when the next automatic gen 2 sweep happens, which, if I understand correctly, would in this case something like every 10 requests (at this point the app needs about a 150MB).
Alright, so initially I thought that there might be some cyclic referencing going on within the processing of one request that prevents any of these objects from being collected within the handling of that request. However, I've spent hours trying to find one using pympler.muppy and objgraph, both after and by debugging inside the request processing, and there don't seem to be any. Rather, it seems the 14.000 objects or so that are created during the request are all within a reference chain to some request-global object, i.e. once the request goes away, they can be freed.
That has been my attempt at explaining it, anyway. However, if that's true and there are indeed no cycling dependencies, shouldn't the whole tree of objects be freed once whatever request object that causes them to be held goes away, without the garbage collector being involved, purely by virtue of the reference counts dropping to zero?
With that setup, here are my questions:
Does the above even make sense, or do I have to look for the problem elsewhere? Is it just an unfortunate accident that significant data is kept around for so long in this particular use case?
Is there anything I can do to avoid the issue. I already see some potential to optimize the view, but that appears to be a solution with limited scope - although I am not sure what I generic one would be, either; how advisable is it for example to call gc.collect() or gc.set_threshold() manually?
In terms of how the garbage collector itself works:
Do I understand correctly that an object is always moved to the next generation if a sweep looks at it and determines that the references it has are not cyclic, but can in fact be traced to a root object.
What happens if the gc does a, say, generation 1 sweep, and finds an object that is referenced by an object within generation 2; does it follow that relationship inside generation 2, or does it wait for a generation 2 sweep to occur before analyzing the situation?
When using gc.DEBUG_STATS, I care primarily about the "objects in each generation" info; however, I keep getting hundreds of "gc: 0.0740s elapsed.", "gc: 1258233035.9370s elapsed." messages; they are totally inconvenient - it takes considerable time for them to be printed out, and they make the interesting things a lot harder to find. Is there a way to get rid of them?
I don't suppose there is a way to do a gc.get_objects() by generation, i.e. only retrieve the objects from generation 2, for example?
|
[
"\nDoes the above even make sense, or do I have to look for the problem elsewhere? Is it just an unfortunate accident that significant data is kept around for so long in this particular use case?\n\nYes, it does make sense. And yes, there are other issues worth to consider. Django uses threading.local as base for DatabaseWrapper (and some contribs use it to make request object accessible from places where it's not passed explicitly). These global objects survive requests and can keep references to objects till some other view is handled in the thread.\n\nIs there anything I can do to avoid the issue. I already see some potential to optimize the view, but that appears to be a solution with limited scope - although I am not sure what I generic one would be, either; how advisable is it for example to call gc.collect() or gc.set_threshold() manually?\n\nGeneral advice (probably you know it, but anyway): avoid circular references and globals (including threading.local). Try to break cycles and clear globals when django design makes hard to avoid them. gc.get_referrers(obj) might help you to find places requiring attention. Another way it to disable garbage collector and call it manually after each request, when it's the best place to do (this will prevent objects from moving to the next generation).\n\nI don't suppose there is a way to do a gc.get_objects() by generation, i.e. only retrieve the objects from generation 2, for example?\n\nUnfortunately this is not possible with gc interface. But there are several ways to go. You can consider the end of list returned by gc.get_objects() only, since objects in this list are sorted by generation. You can compare the list with one returned from previous call by storing weak references to them (e.g. in WeakKeyDictionary) between calls. You can rewrite gc.get_objects() in your own C module (it's easy, mostly copy-paste programming!) since they are stored by generation internally, or even access internal structures with ctypes (requires quite deep ctypes understanding).\n",
"I think your analysis looks sound. I'm not an expert on the gc, so whenever I have a problem like this I just add a call to gc.collect() in an appropriate, non time critical place, and forget about it.\nI'd suggest you call gc.collect() in your view(s) and see what effect it has on your response time and your memory usage.\nNote also this question which suggests that setting DEBUG=True eats memory like it is nearly past its sell by date.\n"
] |
[
3,
2
] |
[] |
[] |
[
"django",
"garbage_collection",
"memory",
"python"
] |
stackoverflow_0001740394_django_garbage_collection_memory_python.txt
|
Q:
Approaches to resize an uploaded image of unknown format with Python
PIL is great for resizing an image 99% of time. But as there are some formats which PIL cannot handle, e.g. interlaced PNG images, I wonder is there any other libraries to work with as a supplement to PIL when we encounter a unsupported image.
Besides interlaced PNG images, what other formats are not currently supported by PIL? As users may upload whatever images they have, how do we pass those images unrecognized by PIL to correct third party libraries to convert to standard format?
Making system call to ImageMagick's convert command may do the job but it's not convenient to get original image's dimensions before conversion.
A:
You can use the binding python of imagemagick maybe : MagickWand
You might also be interested in PythonMagickWand
|
Approaches to resize an uploaded image of unknown format with Python
|
PIL is great for resizing an image 99% of time. But as there are some formats which PIL cannot handle, e.g. interlaced PNG images, I wonder is there any other libraries to work with as a supplement to PIL when we encounter a unsupported image.
Besides interlaced PNG images, what other formats are not currently supported by PIL? As users may upload whatever images they have, how do we pass those images unrecognized by PIL to correct third party libraries to convert to standard format?
Making system call to ImageMagick's convert command may do the job but it's not convenient to get original image's dimensions before conversion.
|
[
"You can use the binding python of imagemagick maybe : MagickWand\nYou might also be interested in PythonMagickWand\n"
] |
[
1
] |
[] |
[] |
[
"image",
"python",
"python_imaging_library"
] |
stackoverflow_0001740682_image_python_python_imaging_library.txt
|
Q:
translate python method to ruby
What would be the correct translation of the following Python method to Ruby?
def uniqueCombinations(self, items, n):
"""
items: list of elements
n: number in a group
"""
if n == 0:
yield []
else:
for i in range(len(items)-n+1):
for cc in uniqueCombinations(items[i+1:],n-1):
yield [items[i]]+cc
What I want to do is call
uniqueCombinations(['01', '02', '03'], 2)
and get
[['01', '02'], ['01', '03'], ['02', '03']]
This is what I have so far.
def uniq_c(items, n)
if n == 0
yield []
else
puts items.inspect
range_max = items.length-n+1
for i in (0...range_max)
u = uniq_c(items[(i+1)..-1], n-1) { |x| x }
u.each do |cc|
yield [items[i]] + cc
end
end
end
end
but I get this:
in `+': can't convert Fixnum into Array (TypeError)
A:
yield [items[i]] + cc
You are attempting to concatenate an array ([items[i]]) and a Fixnum (cc). You could instead turn both into an array or use the << method to push cc onto [items[i]].
yield [items[i]] << cc
A:
From Ruby 1.8.7 onwards, class Array provides a method to return combinations:
irb> ['01', '02', '03'].combination(2).to_a
=> [["01", "02"], ["01", "03"], ["02", "03"]]
A:
First, it'd be better to do this as a method of the Array class.
Second, you can fix your error by changing [items[i]] + cc to [items[i]] + [cc].
Third, here's a different implementation I had lying around, see what you think. It creates an array of permutations represented by indices, then maps each index to its value.
class Array
def combinations(n)
perms = []
a = (0...n).to_a
while perms.push a.dup
break if a.increment!(a.length - 1, self.length-1).nil?
end
perms.map {|p| p.map {|i| self[i]} }
end
def increment!(i, max)
self[i] += 1
while self[i] > max
return nil if i <= 0
return nil if self.increment!(i - 1, max).nil?
self[i] = self[i - 1] + 1
end
self.dup
end
end
[1,2,3].combinations 3 # => [[1, 2, 3]]
[1,2,3].combinations 2 # => [[1, 2], [1, 3], [2, 3]]
[1,2,3].combinations 1 # => [[1], [2], [3]]
[:foo,:bar,:baz,:quux,:wibble].combinations 3
# => [[:foo, :bar, :baz],
# [:foo, :bar, :quux],
# [:foo, :bar, :wibble],
# [:foo, :baz, :quux],
# [:foo, :baz, :wibble],
# [:foo, :quux, :wibble],
# [:bar, :baz, :quux],
# [:bar, :baz, :wibble],
# [:bar, :quux, :wibble],
# [:baz, :quux, :wibble]]
|
translate python method to ruby
|
What would be the correct translation of the following Python method to Ruby?
def uniqueCombinations(self, items, n):
"""
items: list of elements
n: number in a group
"""
if n == 0:
yield []
else:
for i in range(len(items)-n+1):
for cc in uniqueCombinations(items[i+1:],n-1):
yield [items[i]]+cc
What I want to do is call
uniqueCombinations(['01', '02', '03'], 2)
and get
[['01', '02'], ['01', '03'], ['02', '03']]
This is what I have so far.
def uniq_c(items, n)
if n == 0
yield []
else
puts items.inspect
range_max = items.length-n+1
for i in (0...range_max)
u = uniq_c(items[(i+1)..-1], n-1) { |x| x }
u.each do |cc|
yield [items[i]] + cc
end
end
end
end
but I get this:
in `+': can't convert Fixnum into Array (TypeError)
|
[
"yield [items[i]] + cc\n\nYou are attempting to concatenate an array ([items[i]]) and a Fixnum (cc). You could instead turn both into an array or use the << method to push cc onto [items[i]].\nyield [items[i]] << cc\n\n",
"From Ruby 1.8.7 onwards, class Array provides a method to return combinations:\nirb> ['01', '02', '03'].combination(2).to_a\n=> [[\"01\", \"02\"], [\"01\", \"03\"], [\"02\", \"03\"]]\n",
"First, it'd be better to do this as a method of the Array class.\nSecond, you can fix your error by changing [items[i]] + cc to [items[i]] + [cc].\nThird, here's a different implementation I had lying around, see what you think. It creates an array of permutations represented by indices, then maps each index to its value.\nclass Array\n def combinations(n)\n perms = []\n a = (0...n).to_a\n while perms.push a.dup\n break if a.increment!(a.length - 1, self.length-1).nil?\n end\n perms.map {|p| p.map {|i| self[i]} }\n end\n def increment!(i, max)\n self[i] += 1\n while self[i] > max\n return nil if i <= 0\n return nil if self.increment!(i - 1, max).nil?\n self[i] = self[i - 1] + 1\n end\n self.dup\n end\nend\n\n[1,2,3].combinations 3 # => [[1, 2, 3]]\n[1,2,3].combinations 2 # => [[1, 2], [1, 3], [2, 3]]\n[1,2,3].combinations 1 # => [[1], [2], [3]]\n[:foo,:bar,:baz,:quux,:wibble].combinations 3\n# => [[:foo, :bar, :baz],\n# [:foo, :bar, :quux],\n# [:foo, :bar, :wibble],\n# [:foo, :baz, :quux],\n# [:foo, :baz, :wibble],\n# [:foo, :quux, :wibble],\n# [:bar, :baz, :quux],\n# [:bar, :baz, :wibble],\n# [:bar, :quux, :wibble],\n# [:baz, :quux, :wibble]]\n\n"
] |
[
2,
2,
0
] |
[] |
[] |
[
"python",
"ruby"
] |
stackoverflow_0001740960_python_ruby.txt
|
Q:
Google Eclipse Plugin - Work with Python
Does the Google Eclipse Plugin work at all with Pydev or is it only useful if I am developing in Java?
A:
The App Engine eclipse plugin is for Java development. As Casebash points out, though Pydev now has App Engine integration.
A:
You can, indeed, use Eclipse (and PyDev) for Python development for App Engine -- see here for more, for example!
|
Google Eclipse Plugin - Work with Python
|
Does the Google Eclipse Plugin work at all with Pydev or is it only useful if I am developing in Java?
|
[
"The App Engine eclipse plugin is for Java development. As Casebash points out, though Pydev now has App Engine integration.\n",
"You can, indeed, use Eclipse (and PyDev) for Python development for App Engine -- see here for more, for example!\n"
] |
[
3,
1
] |
[] |
[] |
[
"eclipse",
"google_app_engine",
"python"
] |
stackoverflow_0001739969_eclipse_google_app_engine_python.txt
|
Q:
Google Wave Python Tutorial - Nothing happens
For the Google Wave Python Robot Tutorial, my capabilities.xml is visible and I can add it to a Wave, but the robot isn't actually responding to the events. I checked the logs, but I've fixed it so I'm not getting any more errors. Any suggestions?
A:
There's known issue with Wave API: Issue 158 Fix is ready and is expected to be deployed in "coming days".
|
Google Wave Python Tutorial - Nothing happens
|
For the Google Wave Python Robot Tutorial, my capabilities.xml is visible and I can add it to a Wave, but the robot isn't actually responding to the events. I checked the logs, but I've fixed it so I'm not getting any more errors. Any suggestions?
|
[
"There's known issue with Wave API: Issue 158 Fix is ready and is expected to be deployed in \"coming days\".\n"
] |
[
3
] |
[] |
[] |
[
"google_app_engine",
"google_wave",
"python"
] |
stackoverflow_0001741773_google_app_engine_google_wave_python.txt
|
Q:
Cron job (sending email) in Google App Engine
Possible Duplicate:
cron jobs on google appengine
I have created a Google App Engine app using Python for weekly project and assessment reporting.
I want to check on Fridays who has submitted the report so that I can send a notification email on Monday to those who haven't submitted the report.
Any suggestions on how to set up this cron job?
A:
You can schedule the task using the App Engine Scheduled Tasks feature.
You'll need to add an entry to the cron.yaml file for your application. Something like:
cron:
- description: friday mailout
url: /mail/weekly
schedule: every friday 09:00
You can send email using the App Engine Mail API.
|
Cron job (sending email) in Google App Engine
|
Possible Duplicate:
cron jobs on google appengine
I have created a Google App Engine app using Python for weekly project and assessment reporting.
I want to check on Fridays who has submitted the report so that I can send a notification email on Monday to those who haven't submitted the report.
Any suggestions on how to set up this cron job?
|
[
"You can schedule the task using the App Engine Scheduled Tasks feature.\nYou'll need to add an entry to the cron.yaml file for your application. Something like:\ncron:\n- description: friday mailout\n url: /mail/weekly\n schedule: every friday 09:00\n\nYou can send email using the App Engine Mail API.\n"
] |
[
2
] |
[] |
[] |
[
"cron",
"google_app_engine",
"python"
] |
stackoverflow_0001741897_cron_google_app_engine_python.txt
|
Q:
Can SQLAlchemy update the table structure?
I am working on my first pylons + SQLAlchemy app (I'm new to both).
As I change my mind on the table structure, I wish there was a similar function to metadata.create_all(), that checks if there are new columns definitions and create them in the database.
Does such a function exist ?
A:
I'm not (yet) a SQLAlchemy user, but I've heard good things about sqlalchemy-migrate. The general term of the problem you have is "schema migration", I'm sure a google search containing these terms will help you further.
|
Can SQLAlchemy update the table structure?
|
I am working on my first pylons + SQLAlchemy app (I'm new to both).
As I change my mind on the table structure, I wish there was a similar function to metadata.create_all(), that checks if there are new columns definitions and create them in the database.
Does such a function exist ?
|
[
"I'm not (yet) a SQLAlchemy user, but I've heard good things about sqlalchemy-migrate. The general term of the problem you have is \"schema migration\", I'm sure a google search containing these terms will help you further.\n"
] |
[
5
] |
[] |
[] |
[
"mysql",
"pylons",
"python",
"sqlalchemy"
] |
stackoverflow_0001742157_mysql_pylons_python_sqlalchemy.txt
|
Q:
Python and factories
I cant seem to grasp the proper concepts of a factory.
Can anyone help me code a simple test? I read some texts over the internet and cant code it the same way. Actually i cant understand the process. Copying code is easy, but i need to learn why this wont work.
class Factory:
def __init__(self):
self.msg = "teste"
def fabricateAnotherObject(self,obj,**kwargs):
return apply(obj,**kwargs)
class testClass:
def __init__(self,nome,salario,endereco):
self.nome = nome
self.salario = salario
self.endereco = endereco
def __str__(self):
return "Nome: " + str(self.nome) + "\nEndereco: " + str(self.endereco) + "\nSalario: " + str(self.salario)
a = Factory()
emp = a.fabricateAnotherObject(testClass,"George",2000,"Three Four Five Avenue")
print str(emp)
A:
Your code is counter-productive (sorry, I must say it).
The sense of a factory is, that you don't have to know the class of your constructed object at the position where you create it.
The reason is, that object creation creates a gap in object oriented abstraction. You must be concrete in creating the object. But sometimes you just want to create an object with some behaviour but somebody else should decide (centrally) what concrete class it is.
For example you must create one kind of object in 100 places. But later you might find out, that you must change the class -- you would have to change all those places.
The factory will eliminate this need by defining one place that you must change.
The simplest factory would be:
def fabricateAnotherObject(self, **kwargs):
return testClass(**kwargs)
Of course, this might be of little help in some situations. So some factories might also load the class names from db or some other configuration. But the most simple solution is a hard-coded construction of the object -- only this method must be changed in our example, when you choose to always call this method.
A somewhat more dynamic solution (without need for a db):
class Factory(object):
def __init__(self, theClass):
self.theClass = theClass
def create(self, **kwargs):
self.theClass(**kwargs)
myFactory = Factory(testClass)
The myFactory instance can be used in different locations for creating the correct instances. The problem is, how to initialize myFactory -- in some special module??
A:
Factory pattern is intended for programming languages that don't allow functions (and classes) as first-order values (such as C++ or Java).
The idea is that you pass an instance of a "factory" class as an argument to some function (or method or constructor), which is then used to produce new object instances (typically these are instances of some specific subclass of a superclass that is known in advance).
In Python, you can just pass the class instead (because classes (and functions) are also objects).
A:
See also type()
in docs.python.org/library/functions:
type(name, bases, dict)
Return a new type object. This is essentially a dynamic form of the class statement.
The name string is the class name and becomes the __name__ attribute;
the bases tuple itemizes the base classes and becomes the __bases__ attribute;
and the dict dictionary is the namespace containing definitions for class body
and becomes the __dict__ attribute.
For example, the following two statements create identical type objects:
class X(object):
a = 1
X = type('X', (object,), dict(a=1))
For a short real program with one use of factories (compactly building lots of special dicts), see
ofc2.py .
Experts, more examples please ?
A:
Your fabricate method should look like this:
def fabricateAnotherObject(self, obj, *args):
return apply(obj, args)
apply() takes in a list of args. By taking in *args in your fabricateAnotherObject method, you consume all parameters beyond obj as a list that can be passed to apply().
|
Python and factories
|
I cant seem to grasp the proper concepts of a factory.
Can anyone help me code a simple test? I read some texts over the internet and cant code it the same way. Actually i cant understand the process. Copying code is easy, but i need to learn why this wont work.
class Factory:
def __init__(self):
self.msg = "teste"
def fabricateAnotherObject(self,obj,**kwargs):
return apply(obj,**kwargs)
class testClass:
def __init__(self,nome,salario,endereco):
self.nome = nome
self.salario = salario
self.endereco = endereco
def __str__(self):
return "Nome: " + str(self.nome) + "\nEndereco: " + str(self.endereco) + "\nSalario: " + str(self.salario)
a = Factory()
emp = a.fabricateAnotherObject(testClass,"George",2000,"Three Four Five Avenue")
print str(emp)
|
[
"Your code is counter-productive (sorry, I must say it).\nThe sense of a factory is, that you don't have to know the class of your constructed object at the position where you create it.\nThe reason is, that object creation creates a gap in object oriented abstraction. You must be concrete in creating the object. But sometimes you just want to create an object with some behaviour but somebody else should decide (centrally) what concrete class it is.\nFor example you must create one kind of object in 100 places. But later you might find out, that you must change the class -- you would have to change all those places.\nThe factory will eliminate this need by defining one place that you must change.\nThe simplest factory would be:\ndef fabricateAnotherObject(self, **kwargs):\n return testClass(**kwargs)\n\nOf course, this might be of little help in some situations. So some factories might also load the class names from db or some other configuration. But the most simple solution is a hard-coded construction of the object -- only this method must be changed in our example, when you choose to always call this method.\nA somewhat more dynamic solution (without need for a db):\nclass Factory(object):\n def __init__(self, theClass):\n self.theClass = theClass\n def create(self, **kwargs):\n self.theClass(**kwargs)\n\nmyFactory = Factory(testClass)\n\nThe myFactory instance can be used in different locations for creating the correct instances. The problem is, how to initialize myFactory -- in some special module??\n",
"Factory pattern is intended for programming languages that don't allow functions (and classes) as first-order values (such as C++ or Java).\nThe idea is that you pass an instance of a \"factory\" class as an argument to some function (or method or constructor), which is then used to produce new object instances (typically these are instances of some specific subclass of a superclass that is known in advance).\nIn Python, you can just pass the class instead (because classes (and functions) are also objects).\n",
"See also type()\nin docs.python.org/library/functions:\ntype(name, bases, dict)\nReturn a new type object. This is essentially a dynamic form of the class statement.\nThe name string is the class name and becomes the __name__ attribute;\nthe bases tuple itemizes the base classes and becomes the __bases__ attribute;\nand the dict dictionary is the namespace containing definitions for class body\nand becomes the __dict__ attribute.\nFor example, the following two statements create identical type objects:\nclass X(object):\n a = 1\nX = type('X', (object,), dict(a=1))\n\nFor a short real program with one use of factories (compactly building lots of special dicts), see\nofc2.py .\nExperts, more examples please ?\n",
"Your fabricate method should look like this:\n def fabricateAnotherObject(self, obj, *args):\n return apply(obj, args)\n\napply() takes in a list of args. By taking in *args in your fabricateAnotherObject method, you consume all parameters beyond obj as a list that can be passed to apply().\n"
] |
[
13,
5,
1,
0
] |
[] |
[] |
[
"factory",
"oop",
"python"
] |
stackoverflow_0001651593_factory_oop_python.txt
|
Q:
Calling Method from Different Python File
As I'm currently learning Django / Python, I've not really been using the concept of Classes, yet. As far as I'm aware the method isn't static.. it's just a standard definition.
So let's say I have this Package called Example1 with a views.py that contains this method:
def adder(x,y):
return x + y
Then I have an Example2 which also has a views.py where I'd like to use this method adder.
How would I got about doing this?
EDIT: In Java it would be a simple instantiation then a instantiation.Method() or if it was static it would be SomeClass.Method() however I'm unsure how I should approach this in Python.
A:
Python has module level and class level methods. In this concept a "module" is a very special class that you get by using import instead of Name(). Try
from Example1.views import adder as otherAdder
to get access to the module level method. Now you can call otherAdder() and it will execute the code in the other module. Note that the method will be executed in the context of Example1.views, i.e. when it references things, it will look there.
A:
Try:
from Example2.views import adder as myadder
myadder(x,y)
If you are unsure, you can always start a python shell and then use the dir command to look inside the contents of packages to see what can be used.
Edit: Updated from comments to use 'as'
OR
# use ...views as myviews if you need to avoid name conflict on views
from Example2 import views
views.adder(x,y)
A:
Normally you import "modules"
I would suggest:
from Example2 import views as views2
x = views2.adder(1, 2)
I hope, I got this right, since I did not use packages till now ;-)
|
Calling Method from Different Python File
|
As I'm currently learning Django / Python, I've not really been using the concept of Classes, yet. As far as I'm aware the method isn't static.. it's just a standard definition.
So let's say I have this Package called Example1 with a views.py that contains this method:
def adder(x,y):
return x + y
Then I have an Example2 which also has a views.py where I'd like to use this method adder.
How would I got about doing this?
EDIT: In Java it would be a simple instantiation then a instantiation.Method() or if it was static it would be SomeClass.Method() however I'm unsure how I should approach this in Python.
|
[
"Python has module level and class level methods. In this concept a \"module\" is a very special class that you get by using import instead of Name(). Try\nfrom Example1.views import adder as otherAdder\n\nto get access to the module level method. Now you can call otherAdder() and it will execute the code in the other module. Note that the method will be executed in the context of Example1.views, i.e. when it references things, it will look there.\n",
"Try:\nfrom Example2.views import adder as myadder\nmyadder(x,y)\n\nIf you are unsure, you can always start a python shell and then use the dir command to look inside the contents of packages to see what can be used.\nEdit: Updated from comments to use 'as'\nOR\n# use ...views as myviews if you need to avoid name conflict on views\nfrom Example2 import views\nviews.adder(x,y)\n\n",
"Normally you import \"modules\"\nI would suggest:\nfrom Example2 import views as views2\n\nx = views2.adder(1, 2)\n\nI hope, I got this right, since I did not use packages till now ;-)\n"
] |
[
7,
6,
3
] |
[] |
[] |
[
"django",
"methods",
"python"
] |
stackoverflow_0001742430_django_methods_python.txt
|
Q:
How do I get the selected text in desktop application using python-dbus?
For example, I open a pdf file or a web page in gnome, use mouse double click some text, so a word is selected, how can I get this word in a background running daemon written with python-dbus?
Some simple but working piece of script is appreciated greatly.
Thanks!
A:
You don't need D-Bus, simply listen to changes for the middle-click (Selection) clipboard with for example Gtk:
import gtk
def _clipboard_changed(clipboard, event):
text = clipboard.wait_for_text()
clip = gtk.clipboard_get(gtk.gdk.SELECTION_PRIMARY)
clip.connect("owner-change", _clipboard_changed)
A:
Gnome Do has a few plug-ins that use the selected text. I'm not sure how it is implemented (and if it uses DBus), but the code should reveal all. :)
|
How do I get the selected text in desktop application using python-dbus?
|
For example, I open a pdf file or a web page in gnome, use mouse double click some text, so a word is selected, how can I get this word in a background running daemon written with python-dbus?
Some simple but working piece of script is appreciated greatly.
Thanks!
|
[
"You don't need D-Bus, simply listen to changes for the middle-click (Selection) clipboard with for example Gtk:\nimport gtk\n\ndef _clipboard_changed(clipboard, event):\n text = clipboard.wait_for_text()\n\nclip = gtk.clipboard_get(gtk.gdk.SELECTION_PRIMARY)\nclip.connect(\"owner-change\", _clipboard_changed)\n\n",
"Gnome Do has a few plug-ins that use the selected text. I'm not sure how it is implemented (and if it uses DBus), but the code should reveal all. :)\n"
] |
[
7,
0
] |
[] |
[] |
[
"dbus",
"gtk",
"python",
"selection",
"text"
] |
stackoverflow_0001742264_dbus_gtk_python_selection_text.txt
|
Q:
I am getting this sort of CSV data while making Http request to the CSV file. Very malformed string
I am getting this sort of CSV data while making Http request to the CSV file. Very malformed string.
response = '"Subject";"Start Date";"Start Time";"End Date";"End Time";"All day event";"Description""Play football";"16/11/2009";"10:00 PM";"16/11/2009";"11:00 PM";"false";"""Watch 2012";"20/11/2009";"07:00 PM";"20/11/2009";"08:00 PM";"false";""'
And i want to convert this into list of dictionary
[{"Subject": "Play football", "Start Date": "16/11/2009", "Start Time": "10:00 PM", "End Date": "16/11/2009", "End Time": "11:00 PM", "All day event", false, "Description": ""},
{"Subject": "Watch 2012", "Start Date": "20/11/2009", "Start Time": "07:00 PM", "End Date": "20/11/2009", "End Time": "08:00 PM", "All day event", false, "Description": ""}]
I tried solving this using python csv module but didn't work.
import csv
from cStringIO import StringIO
>>> str_obj = StringIO(response)
>>> reader = csv.reader(str_obj, delimiter=';')
>>> [x for x in reader]
[['Subject',
'Start Date',
'Start Time',
'End Date',
'End Time',
'All day event',
'Description"Play football',
'16/11/2009',
'10:00 PM',
'16/11/2009',
'11:00 PM',
'false',
'"Watch 2012',
'20/11/2009',
'07:00 PM',
'20/11/2009',
'08:00 PM',
'false',
'']]
I get the above result.
Any sort of help will be appreciated. Thanks in advance.
A:
Here's a pyparsing solution:
from pyparsing import QuotedString, Group, delimitedList, OneOrMore
# a row of headings or data is a list of quoted strings, delimited by ';'s
qs = QuotedString('"')
datarow = Group(delimitedList(qs, ';'))
# an entire data set is a single data row containing the headings, followed by
# one or more data rows containing the data
dataset_parser = datarow("headings") + OneOrMore(datarow)("rows")
# parse the returned response
data = dataset_parser.parseString(response)
# create dict by zipping headings with each row's data values
datadict = [dict(zip(data.headings, row)) for row in data.rows]
print datadict
Prints:
[{'End Date': '16/11/2009', 'Description': '', 'All day event': 'false',
'Start Time': '10:00 PM', 'End Time': '11:00 PM', 'Start Date': '16/11/2009',
'Subject': 'Play football'},
{'End Date': '20/11/2009', 'Description': '', 'All day event': 'false',
'Start Time': '07:00 PM', 'End Time': '08:00 PM', 'Start Date': '20/11/2009',
'Subject': 'Watch 2012'}]
This will also handle the case if the quoted strings contain embedded semicolons.
A:
Here's one approach.
I notice there is no delimiter between rows. In an effort to clean up the input data, I make a few assumptions:
The first "row" is the "heading" of a "table", these will be our dictionary keys
There are no empty fields in the first row (ie: no "")
Any other field can be empty (ie: "")
The first occurrence of two successive " indicates the end of the heading row
First I create a response based on your input string:
>>> response = '"Subject";"Start Date";"Start Time";"End Date";"End Time";"All day event";"Description""Play football";"16/11/2009";"10:00 PM";"16/11/2009";"11:00 PM";"false";"""Watch 2012";"20/11/2009";"07:00 PM";"";"08:00 PM";"false";"""";"17/11/2009";"9:00 AM";"17/11/2009";"10:00 AM";"false";""'
Note that
the "End Date" for "Watch 2012" is empty
there is a third event with an empty "Subject" heading
These two modifications illustrate some "edge cases" I'm concerned about.
First I will replace all occurrences of two consecutive " with a pipe (|) and strip out all other " characters because I don't need them:
>>> response.replace('""', '|').replace('"', '')
'Subject;Start Date;Start Time;End Date;End Time;All day event;Description|Play football;16/11/2009;10:00 PM;16/11/2009;11:00 PM;false;|Watch 2012;20/11/2009;07:00 PM;|;08:00 PM;false;||;17/11/2009;9:00 AM;17/11/2009;10:00 AM;false;|'
If we had any empty cells not at the start or end of a row (ie: Watch 2012's End Date), it looks like this: ;|; -- let's simply leave it blank:
>>> response.replace('""', '|').replace('"', '').replace(';|;', ';;')
'Subject;Start Date;Start Time;End Date;End Time;All day event;Description|Play football;16/11/2009;10:00 PM;16/11/2009;11:00 PM;false;|Watch 2012;20/11/2009;07:00 PM;;08:00 PM;false;||;17/11/2009;9:00 AM;17/11/2009;10:00 AM;false;|'
Now the | indicates the split between the heading row and the next row. What happens if we split our string on |?
>>> response.replace('""', '|').replace('"', '').replace(';|;', ';;').split('|')
['Subject;Start Date;Start Time;End Date;End Time;All day event;Description',
'Play football;16/11/2009;10:00 PM;16/11/2009;11:00 PM;false;',
'Watch 2012;20/11/2009;07:00 PM;;08:00 PM;false;',
'',
';17/11/2009;9:00 AM;17/11/2009;10:00 AM;false;',
'']
Looks like we're getting somewhere. There's a problem, though; there are two items in that list that are just the empty string ''. They're there because we sometimes have a | at the end of a row and the beginning of the next row, and splitting creates an empty element:
>>> "a|b||c".split('|')
['a', 'b', '', 'c']
Same goes for a lone delimited at the end of a line, too:
>>> "a||b|c|".split('|')
['a', '', 'b', 'c', '']
Let's filter our list to drop those empty "rows":
>>> rows = [row for row in response.replace('""', '|').replace('"', '').replace(';|;', ';;').split('|') if row]
>>> rows
['Subject;Start Date;Start Time;End Date;End Time;All day event;Description',
'Play football;16/11/2009;10:00 PM;16/11/2009;11:00 PM;false;',
'Watch 2012;20/11/2009;07:00 PM;;08:00 PM;false;',
';17/11/2009;9:00 AM;17/11/2009;10:00 AM;false;']
That's it for massaging the input; now we just need to build the dictionary. First, let's get the dictionary keys:
>>> dict_keys = rows[0].split(';')
>>> dict_keys
['Subject',
'Start Date',
'Start Time',
'End Date',
'End Time',
'All day event',
'Description']
And build a list of dictionaries, one for each event:
>>> import itertools
>>> events = []
>>> for row in rows[1:]:
... d = {}
... for k, v in itertools.izip(dict_keys, row.split(';')):
... d[k] = v
... events.append(d)
...
>>> events
[{'All day event': 'false',
'Description': '',
'End Date': '16/11/2009',
'End Time': '11:00 PM',
'Start Date': '16/11/2009',
'Start Time': '10:00 PM',
'Subject': 'Play football'},
{'All day event': 'false',
'Description': '',
'End Date': '',
'End Time': '08:00 PM',
'Start Date': '20/11/2009',
'Start Time': '07:00 PM',
'Subject': 'Watch 2012'},
{'All day event': 'false',
'Description': '',
'End Date': '17/11/2009',
'End Time': '10:00 AM',
'Start Date': '17/11/2009',
'Start Time': '9:00 AM',
'Subject': ''}]
Hope that helps!
Some notes:
if you expect | to appear in your data, you might want to encode it first; or use a different delimiter
supporting quotes in the data might be tricky (ie: 'Subject': 'Watching "2012"')
I leave conversion of 'All day event' values from string to boolean as an exercise to the reader :D
A:
Are you sure, you got this response.
Looks corrupted to me. In this case, no reader will be able to make sense of it.
First fix the response, then parsing will be better ....
A:
response = response.split(';') # split it into words
response = [w[1:-1] for w in response] # strip off the quotes
response = [w.replace('""','"\n"') for w in response] # add in the newlines
response = ['"%s"'%w for w in response] # add the quotes back
response = ';'.join(response)
But it won't work if you have a ";" character in the data that should have been escaped. You should find what happened to the missing newlines in the first place.
|
I am getting this sort of CSV data while making Http request to the CSV file. Very malformed string
|
I am getting this sort of CSV data while making Http request to the CSV file. Very malformed string.
response = '"Subject";"Start Date";"Start Time";"End Date";"End Time";"All day event";"Description""Play football";"16/11/2009";"10:00 PM";"16/11/2009";"11:00 PM";"false";"""Watch 2012";"20/11/2009";"07:00 PM";"20/11/2009";"08:00 PM";"false";""'
And i want to convert this into list of dictionary
[{"Subject": "Play football", "Start Date": "16/11/2009", "Start Time": "10:00 PM", "End Date": "16/11/2009", "End Time": "11:00 PM", "All day event", false, "Description": ""},
{"Subject": "Watch 2012", "Start Date": "20/11/2009", "Start Time": "07:00 PM", "End Date": "20/11/2009", "End Time": "08:00 PM", "All day event", false, "Description": ""}]
I tried solving this using python csv module but didn't work.
import csv
from cStringIO import StringIO
>>> str_obj = StringIO(response)
>>> reader = csv.reader(str_obj, delimiter=';')
>>> [x for x in reader]
[['Subject',
'Start Date',
'Start Time',
'End Date',
'End Time',
'All day event',
'Description"Play football',
'16/11/2009',
'10:00 PM',
'16/11/2009',
'11:00 PM',
'false',
'"Watch 2012',
'20/11/2009',
'07:00 PM',
'20/11/2009',
'08:00 PM',
'false',
'']]
I get the above result.
Any sort of help will be appreciated. Thanks in advance.
|
[
"Here's a pyparsing solution:\nfrom pyparsing import QuotedString, Group, delimitedList, OneOrMore\n\n# a row of headings or data is a list of quoted strings, delimited by ';'s\nqs = QuotedString('\"')\ndatarow = Group(delimitedList(qs, ';'))\n\n# an entire data set is a single data row containing the headings, followed by\n# one or more data rows containing the data\ndataset_parser = datarow(\"headings\") + OneOrMore(datarow)(\"rows\")\n\n# parse the returned response\ndata = dataset_parser.parseString(response)\n\n# create dict by zipping headings with each row's data values\ndatadict = [dict(zip(data.headings, row)) for row in data.rows]\n\nprint datadict\n\nPrints:\n[{'End Date': '16/11/2009', 'Description': '', 'All day event': 'false', \n 'Start Time': '10:00 PM', 'End Time': '11:00 PM', 'Start Date': '16/11/2009', \n 'Subject': 'Play football'}, \n {'End Date': '20/11/2009', 'Description': '', 'All day event': 'false', \n 'Start Time': '07:00 PM', 'End Time': '08:00 PM', 'Start Date': '20/11/2009', \n 'Subject': 'Watch 2012'}]\n\nThis will also handle the case if the quoted strings contain embedded semicolons.\n",
"Here's one approach.\nI notice there is no delimiter between rows. In an effort to clean up the input data, I make a few assumptions:\n\nThe first \"row\" is the \"heading\" of a \"table\", these will be our dictionary keys\nThere are no empty fields in the first row (ie: no \"\")\nAny other field can be empty (ie: \"\")\nThe first occurrence of two successive \" indicates the end of the heading row\n\nFirst I create a response based on your input string:\n>>> response = '\"Subject\";\"Start Date\";\"Start Time\";\"End Date\";\"End Time\";\"All day event\";\"Description\"\"Play football\";\"16/11/2009\";\"10:00 PM\";\"16/11/2009\";\"11:00 PM\";\"false\";\"\"\"Watch 2012\";\"20/11/2009\";\"07:00 PM\";\"\";\"08:00 PM\";\"false\";\"\"\"\";\"17/11/2009\";\"9:00 AM\";\"17/11/2009\";\"10:00 AM\";\"false\";\"\"' \n\nNote that\n\nthe \"End Date\" for \"Watch 2012\" is empty\nthere is a third event with an empty \"Subject\" heading\n\nThese two modifications illustrate some \"edge cases\" I'm concerned about.\nFirst I will replace all occurrences of two consecutive \" with a pipe (|) and strip out all other \" characters because I don't need them:\n>>> response.replace('\"\"', '|').replace('\"', '')\n'Subject;Start Date;Start Time;End Date;End Time;All day event;Description|Play football;16/11/2009;10:00 PM;16/11/2009;11:00 PM;false;|Watch 2012;20/11/2009;07:00 PM;|;08:00 PM;false;||;17/11/2009;9:00 AM;17/11/2009;10:00 AM;false;|'\n\nIf we had any empty cells not at the start or end of a row (ie: Watch 2012's End Date), it looks like this: ;|; -- let's simply leave it blank:\n>>> response.replace('\"\"', '|').replace('\"', '').replace(';|;', ';;')\n'Subject;Start Date;Start Time;End Date;End Time;All day event;Description|Play football;16/11/2009;10:00 PM;16/11/2009;11:00 PM;false;|Watch 2012;20/11/2009;07:00 PM;;08:00 PM;false;||;17/11/2009;9:00 AM;17/11/2009;10:00 AM;false;|'\n\nNow the | indicates the split between the heading row and the next row. What happens if we split our string on |?\n>>> response.replace('\"\"', '|').replace('\"', '').replace(';|;', ';;').split('|')\n['Subject;Start Date;Start Time;End Date;End Time;All day event;Description',\n 'Play football;16/11/2009;10:00 PM;16/11/2009;11:00 PM;false;',\n 'Watch 2012;20/11/2009;07:00 PM;;08:00 PM;false;',\n '',\n ';17/11/2009;9:00 AM;17/11/2009;10:00 AM;false;',\n '']\n\nLooks like we're getting somewhere. There's a problem, though; there are two items in that list that are just the empty string ''. They're there because we sometimes have a | at the end of a row and the beginning of the next row, and splitting creates an empty element:\n>>> \"a|b||c\".split('|')\n['a', 'b', '', 'c']\n\nSame goes for a lone delimited at the end of a line, too:\n>>> \"a||b|c|\".split('|')\n['a', '', 'b', 'c', '']\n\nLet's filter our list to drop those empty \"rows\":\n>>> rows = [row for row in response.replace('\"\"', '|').replace('\"', '').replace(';|;', ';;').split('|') if row]\n>>> rows\n['Subject;Start Date;Start Time;End Date;End Time;All day event;Description',\n 'Play football;16/11/2009;10:00 PM;16/11/2009;11:00 PM;false;',\n 'Watch 2012;20/11/2009;07:00 PM;;08:00 PM;false;',\n ';17/11/2009;9:00 AM;17/11/2009;10:00 AM;false;']\n\nThat's it for massaging the input; now we just need to build the dictionary. First, let's get the dictionary keys:\n>>> dict_keys = rows[0].split(';')\n>>> dict_keys\n['Subject',\n 'Start Date',\n 'Start Time',\n 'End Date',\n 'End Time',\n 'All day event',\n 'Description']\n\nAnd build a list of dictionaries, one for each event:\n>>> import itertools\n>>> events = []\n>>> for row in rows[1:]:\n... d = {}\n... for k, v in itertools.izip(dict_keys, row.split(';')):\n... d[k] = v\n... events.append(d)\n... \n>>> events\n[{'All day event': 'false',\n 'Description': '',\n 'End Date': '16/11/2009',\n 'End Time': '11:00 PM',\n 'Start Date': '16/11/2009',\n 'Start Time': '10:00 PM',\n 'Subject': 'Play football'},\n {'All day event': 'false',\n 'Description': '',\n 'End Date': '',\n 'End Time': '08:00 PM',\n 'Start Date': '20/11/2009',\n 'Start Time': '07:00 PM',\n 'Subject': 'Watch 2012'},\n {'All day event': 'false',\n 'Description': '',\n 'End Date': '17/11/2009',\n 'End Time': '10:00 AM',\n 'Start Date': '17/11/2009',\n 'Start Time': '9:00 AM',\n 'Subject': ''}]\n\nHope that helps!\nSome notes:\n\nif you expect | to appear in your data, you might want to encode it first; or use a different delimiter\nsupporting quotes in the data might be tricky (ie: 'Subject': 'Watching \"2012\"')\nI leave conversion of 'All day event' values from string to boolean as an exercise to the reader :D\n\n",
"Are you sure, you got this response.\nLooks corrupted to me. In this case, no reader will be able to make sense of it.\nFirst fix the response, then parsing will be better ....\n",
"response = response.split(';') # split it into words\nresponse = [w[1:-1] for w in response] # strip off the quotes \nresponse = [w.replace('\"\"','\"\\n\"') for w in response] # add in the newlines\nresponse = ['\"%s\"'%w for w in response] # add the quotes back\nresponse = ';'.join(response) \n\nBut it won't work if you have a \";\" character in the data that should have been escaped. You should find what happened to the missing newlines in the first place.\n"
] |
[
8,
3,
2,
1
] |
[] |
[] |
[
"csv",
"python"
] |
stackoverflow_0001742236_csv_python.txt
|
Q:
Lightweight python wiki engine with pluggable auth system
I need to add wiki to my Tornado webapp. i'm new to python so i would like it not too intimidating to be learned and integrated and can use my existing authentication system, hence the lightweight. it would be better if can use mongodb backend.
I already take a look at moin-moin and it seems too complex(?). any other alternative?
A:
Have a look at Hatta. Overwrite WikiRequest.get_author() method to plug your authentication system. But it uses mercurial repository to store the data.
A:
Skeletonz is a very nice lightweight Python cms that might be worth a look...
|
Lightweight python wiki engine with pluggable auth system
|
I need to add wiki to my Tornado webapp. i'm new to python so i would like it not too intimidating to be learned and integrated and can use my existing authentication system, hence the lightweight. it would be better if can use mongodb backend.
I already take a look at moin-moin and it seems too complex(?). any other alternative?
|
[
"Have a look at Hatta. Overwrite WikiRequest.get_author() method to plug your authentication system. But it uses mercurial repository to store the data.\n",
"Skeletonz is a very nice lightweight Python cms that might be worth a look...\n"
] |
[
4,
0
] |
[] |
[] |
[
"python",
"wiki_engine"
] |
stackoverflow_0001740957_python_wiki_engine.txt
|
Q:
How to generate a list of 150 cases initialised with a dict in Python?
I would like to create a list like this
list = []
for i in range(150):
list.append({'open': False, 'serve': False})
But is there a better way in Python to do it ?
A:
With a list comprehension (don't use list as a variable name, as it shadows the python built-in):
# use range() in Python 3
l = [{'open': False, 'serve': False} for i in xrange(150)]
A:
Whatever you do, don't try list = [{'open':False,'serve':False}]*150, as you will have the same dictionary 150 times. :D
You will then get fun behavior, like
>>> list[0]['open'] = True
>>> list[1]['open'] = False
>>> print list[0]['open']
False
>>> list[0] is list[1]
True
As gs noted, tn python 2.6, you can use namedtuple, which is easier on memory:
from collections import namedtuple
Socket = namedtuple('Socket', 'open serve')
sockets = [Socket(False,False) for i in range(150)]
A:
The list comprehension to build your data structure is probably slightly more efficient. It's also much much terser. Sometimes the terseness is a nice thing, and sometimes it just obscures what is going on. In this case I think the listcomp is pretty clear.
But the listcomp and the for loop both end up building exactly the same thing for you, so this is really a case where there is no "best" answer.
|
How to generate a list of 150 cases initialised with a dict in Python?
|
I would like to create a list like this
list = []
for i in range(150):
list.append({'open': False, 'serve': False})
But is there a better way in Python to do it ?
|
[
"With a list comprehension (don't use list as a variable name, as it shadows the python built-in):\n# use range() in Python 3\nl = [{'open': False, 'serve': False} for i in xrange(150)]\n\n",
"Whatever you do, don't try list = [{'open':False,'serve':False}]*150, as you will have the same dictionary 150 times. :D\nYou will then get fun behavior, like\n>>> list[0]['open'] = True\n>>> list[1]['open'] = False\n>>> print list[0]['open']\nFalse\n\n>>> list[0] is list[1]\nTrue\n\nAs gs noted, tn python 2.6, you can use namedtuple, which is easier on memory: \nfrom collections import namedtuple\nSocket = namedtuple('Socket', 'open serve')\nsockets = [Socket(False,False) for i in range(150)]\n\n",
"The list comprehension to build your data structure is probably slightly more efficient. It's also much much terser. Sometimes the terseness is a nice thing, and sometimes it just obscures what is going on. In this case I think the listcomp is pretty clear.\nBut the listcomp and the for loop both end up building exactly the same thing for you, so this is really a case where there is no \"best\" answer.\n"
] |
[
5,
1,
0
] |
[] |
[] |
[
"dictionary",
"initialization",
"list",
"python"
] |
stackoverflow_0001553145_dictionary_initialization_list_python.txt
|
Q:
sorting function in python
I'm trying to sort a list of objects according to my criteria.
Here is my sorting function:
def sort_pots(self, pot1, pot2):
coeff1 = ((pot1.movable + pot1.convertible) / pot1.total)
coeff2 = ((pot2.movable + pot2.convertible) / pot2.total)
if coeff1 > coeff2:
return 1
elif coeff1 == coeff2:
return pot1.total - pot2.total
else:
return -1
What i would like to achieve is:
if coeff1 > coeff2, pot1 is before pot2
if coeff1 == coeff2, the one with the highest total is before
else (coeff2 > coeff1), pot2 is before pot2
and the function doesn't seem to work accordingly. I've got a bunch ordered according to total but not with same coeff.
I've (convertible, movable, total): 0, 0, 1 and later 0, 3, 4 and then 31, 228, 1584 and then 1, 0, 1
Here is the beginning of the definition of the class of pot1 and pot2:
class Potential:
def __init__(self,conf_opt):
self.conf_opt = conf_opt
self.total = 0
self.movable = 0
self.convertible = 0
thanks.
A:
Does the following work?
def coef(pot):
return (pot.movable + pot.convertible) / float(pot.total)
l.sort(key=lambda x: (coef(x), x.total), reverse=True)
It should even be faster (key is better than cmp).
A:
Just as a final note, you could override the __cmp__ method as follows:
class Potential(object): # new style classes FTW!
...
def __cmp__(self, other):
coeff1 = (self.movable + self.convertible) / self.total
coeff2 = (other.movable + other.convertible) / other.total
return cmp((coeff1, self.total), (coeff2, other.total))
That way, the normal sorting order is achieved just by calling sort() with no arguments. You might even make the suggested coeff function a part of your class:
class Potential(object):
...
def coeff(self):
return (self.movable + self.convertible) / self.total
def __cmp__(self, other):
return cmp((self.coeff(), self.total), (other.coeff(), other.total))
A:
I think tonfa's answer is the most readable but if you want to do it with the code you have you should try:
def sort_pots(self, pot1, pot2):
coeff1 = ((pot1.movable + pot1.convertible) / pot1.total)
coeff2 = ((pot2.movable + pot2.convertible) / pot2.total)
if coeff1 > coeff2:
return 1
elif coeff1 == coeff2:
return cmp(pot1.total,pot2.total)
else:
return -1
Edit: Used cmp method rather than long form if/else
|
sorting function in python
|
I'm trying to sort a list of objects according to my criteria.
Here is my sorting function:
def sort_pots(self, pot1, pot2):
coeff1 = ((pot1.movable + pot1.convertible) / pot1.total)
coeff2 = ((pot2.movable + pot2.convertible) / pot2.total)
if coeff1 > coeff2:
return 1
elif coeff1 == coeff2:
return pot1.total - pot2.total
else:
return -1
What i would like to achieve is:
if coeff1 > coeff2, pot1 is before pot2
if coeff1 == coeff2, the one with the highest total is before
else (coeff2 > coeff1), pot2 is before pot2
and the function doesn't seem to work accordingly. I've got a bunch ordered according to total but not with same coeff.
I've (convertible, movable, total): 0, 0, 1 and later 0, 3, 4 and then 31, 228, 1584 and then 1, 0, 1
Here is the beginning of the definition of the class of pot1 and pot2:
class Potential:
def __init__(self,conf_opt):
self.conf_opt = conf_opt
self.total = 0
self.movable = 0
self.convertible = 0
thanks.
|
[
"Does the following work?\ndef coef(pot):\n return (pot.movable + pot.convertible) / float(pot.total)\n\nl.sort(key=lambda x: (coef(x), x.total), reverse=True)\n\nIt should even be faster (key is better than cmp).\n",
"Just as a final note, you could override the __cmp__ method as follows:\nclass Potential(object): # new style classes FTW!\n ...\n def __cmp__(self, other):\n coeff1 = (self.movable + self.convertible) / self.total\n coeff2 = (other.movable + other.convertible) / other.total\n return cmp((coeff1, self.total), (coeff2, other.total))\n\nThat way, the normal sorting order is achieved just by calling sort() with no arguments. You might even make the suggested coeff function a part of your class:\nclass Potential(object):\n ...\n def coeff(self):\n return (self.movable + self.convertible) / self.total\n\n def __cmp__(self, other):\n return cmp((self.coeff(), self.total), (other.coeff(), other.total))\n\n",
"I think tonfa's answer is the most readable but if you want to do it with the code you have you should try:\ndef sort_pots(self, pot1, pot2):\n coeff1 = ((pot1.movable + pot1.convertible) / pot1.total)\n coeff2 = ((pot2.movable + pot2.convertible) / pot2.total)\n\n if coeff1 > coeff2:\n return 1\n elif coeff1 == coeff2:\n return cmp(pot1.total,pot2.total)\n else:\n return -1\n\nEdit: Used cmp method rather than long form if/else\n"
] |
[
9,
2,
1
] |
[] |
[] |
[
"python",
"sorting"
] |
stackoverflow_0001742656_python_sorting.txt
|
Q:
How is a union different from a struct? Do other languages have similar constructs?
Possible Duplicate:
Difference between a Structure and a Union in C
I see this code for a union in C:
union time
{
long simpleDate;
double perciseDate;
} mytime;
What is the difference between a union and a structure in C? Where would you use a union, what are its benefits? Is there a similar construct in Java, C++ and/or Python?
A:
A union behaves as if all its members are in the same location in memory, overlapping.
This is useful when you want to represent some kind of "generic" value, or a value that can be of any of a set of types. Because the fields overlap, you can only legally access a field if you know it's been previously initialized. Still, since C doesn't check this, and many compilers emit code that allow it, it is a common trick to do ... interesting type conversions, such as:
union {
int integer;
float real;
} convert;
convert.real = 3.14;
printf("The float %f interpreted as an integer is %08x", convert.real, convert.integer);
For the more well-formed usage, where you keep track of what was last stored in the union, it could look for instance like this:
typedef enum { INTEGER = 0, REAL, BOOLEAN, STRING } ValueType;
typedef struct {
ValueType type;
union {
int integer;
float real;
char boolean;
char *string;
} x;
} Value;
Here, note that the union is actually a field in the surrounding structure, Value. Access could look like this:
void value_set_integer(Value *value, int x)
{
value->type = INTEGER;
value->x.integer = x;
}
This records that the current contents of the union is an integer, and stores the given value. A function to e.g. print a Value can inspect the type member, and do the right thing:
void value_print(const Value *value)
{
switch(value->type)
{
case INTEGER:
printf("%d\n", value->x.integer);
break;
case REAL:
printf("%g\n", value->x.real);
break;
/* ... and so on ... */
}
}
There is no equivalent in Java. C++, being sort of almost a super-set of C, has the same functionality. It even "one-ups" C's implementation, and allows anonymous unions. In C++, the above could have written without naming the inner union (x), which would make the code quite a lot shorter.
A:
So in your example, when I allocate time:
int main()
{
time t;
}
The compiler can interpret the memory at &t as if it is either a long:
t.simpleDate;
or as if its a double:
t.perciseDate;
So if the raw hex of the memory at t looks like
0x12345678;
That value can be "parsed" as either a double or long, depending on how its accessed. So for it to be useful you have to know how a long and a double are going to be packed & formatted exactly in memory. For example, a long is going to be a 2-s complement signed integer, which you can read about here. you can learn how a double is formatted in binary here.
A struct, however, just groups separate variables, with distinct address spacing into one block of memory.
(Note your example might be dangerous as sizeof(long) could be 32 bits whereas sizeof(double) is always 64 bits)
Unions are commonly used when you want a "raw" representation (like a char array) and a "message" representation. For example a message that is to be sent over a socket:
struct Msg
{
int msgType;
double Val1;
double Val2;
}; // assuming packing on 32-bit boundary
union
{
Msg msg;
unsigned char msgAsBinary[20];
};
Hope that helps.
A:
A union lets you interpret one memory location (raw, binary value) in several different ways.
An example I've actually used, is accessing the individual bytes of a uint32.
union {
uint32 int;
char bytes[4];
} uint_bytes;
What a union offers, is multiple ways of accessing (parts of) the same memory.
The size of a union type is equal to the size of the largest type in the union.
A:
A union is a space-saving way of storing "one of" several different types. It does not provide a mechanism for rediscovering the type that was stored in it; this must be determined out-of-line. Technically, accessing the "wrong" type (i.e. one that was not initialized) in a union results in undefined behaviour; in practice, it usually results in a bit-level cast, and is often used as a way of doing just that.
While the "union" type is in C++ (C++ being a superset of C), most C++ types cannot safely be stored in one (specifically, a union can hold only POD types, i.e. classes with default copy constructor, default destructor and no virtual methods). If you want a space-saving, stack-based equivalent to a union in C++, capable of storing complex objects, try Boost.Variant.
In other languages less concerned with stack allocation, polymorphism does the job of a union. In Java, everything inherits from an Object, so Object* can be used to represent any object; or you can use a common superclass or an interface to restrict the set of objects to ones supporting a particular set of operations.
In Python, any variable can hold any object, so in some sense all variables are unions. You generally should not need to determine the type stored in a variable; instead, use duck typing -- that is, look for the methods it supports rather than the type/interface it implements.
A:
A union can be used to store any one of its members, but (unlike a struct) no more than one at the same time. You can think of it as containing enough space to store the largest of its members, and re-using the same storage for whichever member you actually assign a value to.
C++ also has unions. Java doesn't. Object members in Python work completely differently from C, they're stored in a dictionary rather than laid out consecutively in memory. I don't know whether Python has some handy library class somewhere that acts a bit like a union, but it's not fundamental to the object like it is in C.
A:
With a structure each data item has its own memory location, but with unions only one item is used at a time, and memory allocated for each item is in shared memory. Only one memory location will be shared by the data items of a union. The size of a union will be the size of the biggest variable.
This can be beneficial because sometimes we may not need the data of all the (related) data items of a complex data structure and be storing/accessing only one data item at a time. Union helps in such scenarios.
A:
only one member of a union can be used at a time unlike struct where all the members reside in the memory together.for union space is allocated of size of the longest element it contains.
|
How is a union different from a struct? Do other languages have similar constructs?
|
Possible Duplicate:
Difference between a Structure and a Union in C
I see this code for a union in C:
union time
{
long simpleDate;
double perciseDate;
} mytime;
What is the difference between a union and a structure in C? Where would you use a union, what are its benefits? Is there a similar construct in Java, C++ and/or Python?
|
[
"A union behaves as if all its members are in the same location in memory, overlapping.\nThis is useful when you want to represent some kind of \"generic\" value, or a value that can be of any of a set of types. Because the fields overlap, you can only legally access a field if you know it's been previously initialized. Still, since C doesn't check this, and many compilers emit code that allow it, it is a common trick to do ... interesting type conversions, such as:\nunion {\n int integer;\n float real;\n} convert;\n\nconvert.real = 3.14;\nprintf(\"The float %f interpreted as an integer is %08x\", convert.real, convert.integer);\n\nFor the more well-formed usage, where you keep track of what was last stored in the union, it could look for instance like this:\ntypedef enum { INTEGER = 0, REAL, BOOLEAN, STRING } ValueType;\n\ntypedef struct {\n ValueType type;\n union {\n int integer;\n float real;\n char boolean;\n char *string;\n } x;\n} Value;\n\nHere, note that the union is actually a field in the surrounding structure, Value. Access could look like this:\nvoid value_set_integer(Value *value, int x)\n{\n value->type = INTEGER;\n value->x.integer = x;\n}\n\nThis records that the current contents of the union is an integer, and stores the given value. A function to e.g. print a Value can inspect the type member, and do the right thing:\nvoid value_print(const Value *value)\n{\n switch(value->type)\n {\n case INTEGER:\n printf(\"%d\\n\", value->x.integer);\n break;\n case REAL:\n printf(\"%g\\n\", value->x.real);\n break;\n /* ... and so on ... */\n }\n}\n\nThere is no equivalent in Java. C++, being sort of almost a super-set of C, has the same functionality. It even \"one-ups\" C's implementation, and allows anonymous unions. In C++, the above could have written without naming the inner union (x), which would make the code quite a lot shorter.\n",
"So in your example, when I allocate time:\nint main()\n{\n time t;\n}\n\nThe compiler can interpret the memory at &t as if it is either a long:\nt.simpleDate;\n\nor as if its a double:\nt.perciseDate;\n\nSo if the raw hex of the memory at t looks like\n0x12345678;\n\nThat value can be \"parsed\" as either a double or long, depending on how its accessed. So for it to be useful you have to know how a long and a double are going to be packed & formatted exactly in memory. For example, a long is going to be a 2-s complement signed integer, which you can read about here. you can learn how a double is formatted in binary here. \nA struct, however, just groups separate variables, with distinct address spacing into one block of memory.\n(Note your example might be dangerous as sizeof(long) could be 32 bits whereas sizeof(double) is always 64 bits)\nUnions are commonly used when you want a \"raw\" representation (like a char array) and a \"message\" representation. For example a message that is to be sent over a socket:\nstruct Msg\n{\n int msgType;\n double Val1;\n double Val2;\n}; // assuming packing on 32-bit boundary\n\nunion\n{\n Msg msg;\n unsigned char msgAsBinary[20];\n};\n\nHope that helps.\n",
"A union lets you interpret one memory location (raw, binary value) in several different ways.\nAn example I've actually used, is accessing the individual bytes of a uint32.\nunion {\n uint32 int;\n char bytes[4];\n} uint_bytes;\n\nWhat a union offers, is multiple ways of accessing (parts of) the same memory.\nThe size of a union type is equal to the size of the largest type in the union.\n",
"A union is a space-saving way of storing \"one of\" several different types. It does not provide a mechanism for rediscovering the type that was stored in it; this must be determined out-of-line. Technically, accessing the \"wrong\" type (i.e. one that was not initialized) in a union results in undefined behaviour; in practice, it usually results in a bit-level cast, and is often used as a way of doing just that.\nWhile the \"union\" type is in C++ (C++ being a superset of C), most C++ types cannot safely be stored in one (specifically, a union can hold only POD types, i.e. classes with default copy constructor, default destructor and no virtual methods). If you want a space-saving, stack-based equivalent to a union in C++, capable of storing complex objects, try Boost.Variant.\nIn other languages less concerned with stack allocation, polymorphism does the job of a union. In Java, everything inherits from an Object, so Object* can be used to represent any object; or you can use a common superclass or an interface to restrict the set of objects to ones supporting a particular set of operations.\nIn Python, any variable can hold any object, so in some sense all variables are unions. You generally should not need to determine the type stored in a variable; instead, use duck typing -- that is, look for the methods it supports rather than the type/interface it implements.\n",
"A union can be used to store any one of its members, but (unlike a struct) no more than one at the same time. You can think of it as containing enough space to store the largest of its members, and re-using the same storage for whichever member you actually assign a value to.\nC++ also has unions. Java doesn't. Object members in Python work completely differently from C, they're stored in a dictionary rather than laid out consecutively in memory. I don't know whether Python has some handy library class somewhere that acts a bit like a union, but it's not fundamental to the object like it is in C.\n",
"With a structure each data item has its own memory location, but with unions only one item is used at a time, and memory allocated for each item is in shared memory. Only one memory location will be shared by the data items of a union. The size of a union will be the size of the biggest variable.\nThis can be beneficial because sometimes we may not need the data of all the (related) data items of a complex data structure and be storing/accessing only one data item at a time. Union helps in such scenarios.\n",
"only one member of a union can be used at a time unlike struct where all the members reside in the memory together.for union space is allocated of size of the longest element it contains.\n"
] |
[
14,
11,
2,
2,
1,
1,
1
] |
[] |
[] |
[
"c",
"c++",
"java",
"programming_languages",
"python"
] |
stackoverflow_0001742750_c_c++_java_programming_languages_python.txt
|
Q:
How to sort model by values in a dictionary?
In Django, I have a model, and I will have a dictionary having the id's of objects in this model as keys, and a weight as values. I would like to use these weights in an order_by:
MyModel.objects.filter(title__icontains=query).order_by( 'value_from_the_dictionary' )
How to make this work?
I can't put the weights in the model, as they will be different in each call of this view, and I don't want to save them anywhere, they will be calculated on each query of the URL.
A:
Sorting in order_by is done by the database, so if those elements aren't in the database you can't order by them. You will have to get the queryset and then do the ordering in Python.
qs = MyModel.objects.filter(title__icontains=query)
qs.sort(key=lambda x: mydict[x])
|
How to sort model by values in a dictionary?
|
In Django, I have a model, and I will have a dictionary having the id's of objects in this model as keys, and a weight as values. I would like to use these weights in an order_by:
MyModel.objects.filter(title__icontains=query).order_by( 'value_from_the_dictionary' )
How to make this work?
I can't put the weights in the model, as they will be different in each call of this view, and I don't want to save them anywhere, they will be calculated on each query of the URL.
|
[
"Sorting in order_by is done by the database, so if those elements aren't in the database you can't order by them. You will have to get the queryset and then do the ordering in Python.\nqs = MyModel.objects.filter(title__icontains=query)\nqs.sort(key=lambda x: mydict[x])\n\n"
] |
[
5
] |
[] |
[] |
[
"django",
"python",
"sorting",
"sql_order_by"
] |
stackoverflow_0001743288_django_python_sorting_sql_order_by.txt
|
Q:
Convert flat data into a hierarchical python list
I have a data model from my database. This is a flat python list sorted by left values.
> id name left right
> 1 Beginning 1 6
> 2 FOO 2 5
> 3 BAR 3 4
> 4 Programming 6 13
> 5 Python 7 8
> 7 C# 9 12
> 8 XNA 10 11
> 6 About 14 15
I would like to compute this into a hierarchical python list, that in turn will be converted to HTML/XML as a unordered list. The python list with be a lists within lists.
Example
categories = [
["programming", [
["Python", ["pygame"]],
["C#", ["XNA"]],
]
],
["FOO", [
["BAR"]
]
],
]
A:
This is a modified pre-order tree traversal.
http://www.sitepoint.com/print/hierarchical-data-database/
So the input looks like this, a list of dictionaries.
dbrows = [
{'title': 'Food', 'lft': 1, 'rgt': 18},
{'title': 'Fruit', 'lft': 2, 'rgt': 11},
#etc... etc... from the linked article.
]
Using the fruit input from the linked article. This is what I want, sorted as a python list.
tree = [
['Food', [
['Fruit', [
['Red', ['Cherry', 'Strawberry']],
['Yellow', ['Banana']],
]],
['Meat', [
['Beef', 'Pork']
]],
]],
]
|
Convert flat data into a hierarchical python list
|
I have a data model from my database. This is a flat python list sorted by left values.
> id name left right
> 1 Beginning 1 6
> 2 FOO 2 5
> 3 BAR 3 4
> 4 Programming 6 13
> 5 Python 7 8
> 7 C# 9 12
> 8 XNA 10 11
> 6 About 14 15
I would like to compute this into a hierarchical python list, that in turn will be converted to HTML/XML as a unordered list. The python list with be a lists within lists.
Example
categories = [
["programming", [
["Python", ["pygame"]],
["C#", ["XNA"]],
]
],
["FOO", [
["BAR"]
]
],
]
|
[
"This is a modified pre-order tree traversal.\nhttp://www.sitepoint.com/print/hierarchical-data-database/\nSo the input looks like this, a list of dictionaries.\ndbrows = [\n {'title': 'Food', 'lft': 1, 'rgt': 18},\n {'title': 'Fruit', 'lft': 2, 'rgt': 11},\n #etc... etc... from the linked article.\n]\n\nUsing the fruit input from the linked article. This is what I want, sorted as a python list.\ntree = [\n ['Food', [\n ['Fruit', [\n ['Red', ['Cherry', 'Strawberry']],\n ['Yellow', ['Banana']],\n ]],\n ['Meat', [\n ['Beef', 'Pork']\n ]],\n ]],\n]\n\n"
] |
[
0
] |
[] |
[] |
[
"hierarchical",
"python"
] |
stackoverflow_0001740107_hierarchical_python.txt
|
Q:
Conflicting Python Packages How can it be Resolved?
So we went to implement something today, and discovered that there already is several applications relying on the old implementation of our inhouse python library. Called cis_py. Now all applications for our implementation currently sit in a folder called, bin. This is where cis_py currently resides.
Now we went to deploy one of our big python applications, which uses the new version of our inhouse library. We cannot simply overwrite the existing versions of it. Since this will cause all of the existing applications to break.
Basically i cannot update the existing applications, nor can i rewrite the new application. Now i was thinking of trying the following:
cis\cis_py\<python library files>
Then do a search and replace on the existing application and change the following:
cis_py.<some python file>
To
cis.cis_py.<some python file>
Unfortunately this results in several of the __init__.py files in the library breaking, due to the use of this:
from cis_py import rga
from cis_py import util
Today is implementation day, and it must go live today, since in a few hours we start receiving data automatically.
How and what can i possibly do? Everything must reside in a single folder called bin. Due to the automatic processing system. Is there some way i can possibly trick python?
A:
Try import sys; sys.path.insert(0, "cis") as the very start of your main Python file.
A:
It looks like Alex Martelli's solution solved the emergency for you. Here's another solution, one I think better for the long term.
In source files, replace the line
import cis_py
with the line
import cis.cis_py as cis_py
That way, when later code says from cis_py import foo, it will work.
This is less "magical", because each source file will include this changed import line, so someone studying a source file will understand the true source of the cis_py module (without needing to also study the main Python source file).
A:
Step one is to start telling people about this issue. Talk to your co-workers and boss and inform them of the problem you discovered, since it is possible that the go-live will have to be called off or postponed while a solution is worked on. Changes will have to be made somewhere, and it would be good (and may be required) to perform additional testing to verify those changes don't break anything.
Without knowing much about how your system is being run, one guess is that maybe you can run the new version under a modified environment that directs it at the new version of the library?
A:
Add a version to the name: cis_py2. You may have to make changes in the class, but nothing that can't be done with a quick script (don't run this without testing it first):
sed 's/cis_py/cis_py2/g' `find -name '.py$'`
This assumes that cis_py is only the module name and nothing else has the name.
|
Conflicting Python Packages How can it be Resolved?
|
So we went to implement something today, and discovered that there already is several applications relying on the old implementation of our inhouse python library. Called cis_py. Now all applications for our implementation currently sit in a folder called, bin. This is where cis_py currently resides.
Now we went to deploy one of our big python applications, which uses the new version of our inhouse library. We cannot simply overwrite the existing versions of it. Since this will cause all of the existing applications to break.
Basically i cannot update the existing applications, nor can i rewrite the new application. Now i was thinking of trying the following:
cis\cis_py\<python library files>
Then do a search and replace on the existing application and change the following:
cis_py.<some python file>
To
cis.cis_py.<some python file>
Unfortunately this results in several of the __init__.py files in the library breaking, due to the use of this:
from cis_py import rga
from cis_py import util
Today is implementation day, and it must go live today, since in a few hours we start receiving data automatically.
How and what can i possibly do? Everything must reside in a single folder called bin. Due to the automatic processing system. Is there some way i can possibly trick python?
|
[
"Try import sys; sys.path.insert(0, \"cis\") as the very start of your main Python file.\n",
"It looks like Alex Martelli's solution solved the emergency for you. Here's another solution, one I think better for the long term.\nIn source files, replace the line\nimport cis_py\n\nwith the line\nimport cis.cis_py as cis_py\n\nThat way, when later code says from cis_py import foo, it will work.\nThis is less \"magical\", because each source file will include this changed import line, so someone studying a source file will understand the true source of the cis_py module (without needing to also study the main Python source file).\n",
"Step one is to start telling people about this issue. Talk to your co-workers and boss and inform them of the problem you discovered, since it is possible that the go-live will have to be called off or postponed while a solution is worked on. Changes will have to be made somewhere, and it would be good (and may be required) to perform additional testing to verify those changes don't break anything.\nWithout knowing much about how your system is being run, one guess is that maybe you can run the new version under a modified environment that directs it at the new version of the library?\n",
"Add a version to the name: cis_py2. You may have to make changes in the class, but nothing that can't be done with a quick script (don't run this without testing it first):\nsed 's/cis_py/cis_py2/g' `find -name '.py$'`\n\nThis assumes that cis_py is only the module name and nothing else has the name.\n"
] |
[
5,
1,
0,
0
] |
[] |
[] |
[
"package",
"python"
] |
stackoverflow_0001743596_package_python.txt
|
Q:
Does Django cache templates automatically?
I'm new to Django and trying to implement a voting system between two images. However, it looks like the page is being cached or something because when I refresh it, some values are wrong. I have no cache setup in my Settings.
Here is the View:
def rate(request, type):
photos = Photo.objects.order_by('?')[:2]
c = Context({"photos": photos, "type": type})
return render_to_response("base_rate.html", c)
and the template:
{% extends "base.html" %}
{% block body %}
<div class="photo">
<img src="{{photos.0.photo.url}}" alt="Photo" />
<a href="/rate/vote/{{photos.0.id}}/{{photos.1.id}}" class="vote">Vote</a>
<a href="/rate/flag/{{photos.0.id}}" class="flag">Flag</a>
</div>
<div class="photo">
<img src="{{photos.1.photo.url}}" alt="Photo" />
<a href="/rate/vote/{{photos.1.id}}/{{photos.0.id}}" class="vote">Vote</a>
<a href="/rate/flag/{{photos.1.id}}" class="flag">Flag</a>
</div>
{% endblock %}
Some pages will contain wrong info for the objects. Here is an example source that I am getting:
<div class="photo">
<img src="/img/rate/16photo1.jpg" alt="Photo" />
<a href="/rate/vote/16/17" class="vote">Vote</a>
<a href="/rate/flag/16" class="flag">Flag</a>
</div>
<div class="photo">
<img src="/img/rate/17photo2.jpg" alt="Photo" />
<a href="/rate/vote/16/16" class="vote">Vote</a>
<a href="/rate/flag/16" class="flag">Flag</a>
</div>
The second Vote href should be "/rate/vote/17/16" and the flag href should be "/rate/flag/17" but something is going wrong and I am getting inconsistent data.
Any ideas?
A:
Taking a look at this in some of my code, I have this in my template:
{{ mytable.0.pk }}
{{ mytable.1.pk }}
{{ mytable.0.pk }}
{{ mytable.3.pk }}
And I get this output:
91596
54774
156800
23593
Odd, until you consider that django executes database queries very lazily. This is what shows up in my mysql log for one page load:
SELECT `mytable`.`id` FROM `mytable` ORDER BY RAND() LIMIT 1
SELECT `mytable`.`id` FROM `mytable` ORDER BY RAND() LIMIT 1 OFFSET 1
SELECT `mytable`.`id` FROM `mytable` ORDER BY RAND() LIMIT 1
SELECT `mytable`.`id` FROM `mytable` ORDER BY RAND() LIMIT 1 OFFSET 3
Each time you use the dot notation, it is executing an entire new query. I'd suggest modifying your code like so:
def rate(request, type):
photos = list(Photo.objects.order_by('?')[:2])
c = Context({"photos": photos, "type": type})
return render_to_response("base_rate.html", c)
Because the list() is forcing an evaluation, it will execute the query right then and there. In addition, the data for both of those items is already cached, so there is no reason to hit the database again. You should be good to go.
A:
order_by('?') means that the list is ordered in random order, so {{ photos.0 }} will be different each time you load the page.
Also:
<a href="/rate/vote/{{photos.1.id}}/{{photos.0.id}}" class="vote">Vote</a>
^^^ ^^^
Looks like that's probably not correct.
A:
Django doesn't cache these sorts of things by default. Make sure that your browser/isp/etc. isn't caching it.
It looks like your database query isn't returning what you're expecting. Check that directly via your debugger or with print statement debugging if you have to.
That said, you really need to think long and hard about your app design. Using a GET request to make stateful changes to your app is an incredibly bad idea. Especially the way you are doing it. You need to change those links to POST requests to a single form. Otherwise, you'll find that random web spiders destroy your application.
|
Does Django cache templates automatically?
|
I'm new to Django and trying to implement a voting system between two images. However, it looks like the page is being cached or something because when I refresh it, some values are wrong. I have no cache setup in my Settings.
Here is the View:
def rate(request, type):
photos = Photo.objects.order_by('?')[:2]
c = Context({"photos": photos, "type": type})
return render_to_response("base_rate.html", c)
and the template:
{% extends "base.html" %}
{% block body %}
<div class="photo">
<img src="{{photos.0.photo.url}}" alt="Photo" />
<a href="/rate/vote/{{photos.0.id}}/{{photos.1.id}}" class="vote">Vote</a>
<a href="/rate/flag/{{photos.0.id}}" class="flag">Flag</a>
</div>
<div class="photo">
<img src="{{photos.1.photo.url}}" alt="Photo" />
<a href="/rate/vote/{{photos.1.id}}/{{photos.0.id}}" class="vote">Vote</a>
<a href="/rate/flag/{{photos.1.id}}" class="flag">Flag</a>
</div>
{% endblock %}
Some pages will contain wrong info for the objects. Here is an example source that I am getting:
<div class="photo">
<img src="/img/rate/16photo1.jpg" alt="Photo" />
<a href="/rate/vote/16/17" class="vote">Vote</a>
<a href="/rate/flag/16" class="flag">Flag</a>
</div>
<div class="photo">
<img src="/img/rate/17photo2.jpg" alt="Photo" />
<a href="/rate/vote/16/16" class="vote">Vote</a>
<a href="/rate/flag/16" class="flag">Flag</a>
</div>
The second Vote href should be "/rate/vote/17/16" and the flag href should be "/rate/flag/17" but something is going wrong and I am getting inconsistent data.
Any ideas?
|
[
"Taking a look at this in some of my code, I have this in my template:\n{{ mytable.0.pk }}\n{{ mytable.1.pk }}\n{{ mytable.0.pk }}\n{{ mytable.3.pk }}\n\nAnd I get this output:\n91596\n54774\n156800\n23593\n\nOdd, until you consider that django executes database queries very lazily. This is what shows up in my mysql log for one page load:\nSELECT `mytable`.`id` FROM `mytable` ORDER BY RAND() LIMIT 1\nSELECT `mytable`.`id` FROM `mytable` ORDER BY RAND() LIMIT 1 OFFSET 1\nSELECT `mytable`.`id` FROM `mytable` ORDER BY RAND() LIMIT 1\nSELECT `mytable`.`id` FROM `mytable` ORDER BY RAND() LIMIT 1 OFFSET 3\n\nEach time you use the dot notation, it is executing an entire new query. I'd suggest modifying your code like so:\ndef rate(request, type):\n photos = list(Photo.objects.order_by('?')[:2])\n c = Context({\"photos\": photos, \"type\": type})\n return render_to_response(\"base_rate.html\", c)\n\nBecause the list() is forcing an evaluation, it will execute the query right then and there. In addition, the data for both of those items is already cached, so there is no reason to hit the database again. You should be good to go.\n",
"order_by('?') means that the list is ordered in random order, so {{ photos.0 }} will be different each time you load the page. \nAlso:\n<a href=\"/rate/vote/{{photos.1.id}}/{{photos.0.id}}\" class=\"vote\">Vote</a>\n ^^^ ^^^\n\nLooks like that's probably not correct.\n",
"Django doesn't cache these sorts of things by default. Make sure that your browser/isp/etc. isn't caching it.\nIt looks like your database query isn't returning what you're expecting. Check that directly via your debugger or with print statement debugging if you have to.\nThat said, you really need to think long and hard about your app design. Using a GET request to make stateful changes to your app is an incredibly bad idea. Especially the way you are doing it. You need to change those links to POST requests to a single form. Otherwise, you'll find that random web spiders destroy your application.\n"
] |
[
8,
1,
1
] |
[] |
[] |
[
"caching",
"django",
"django_templates",
"python"
] |
stackoverflow_0001744339_caching_django_django_templates_python.txt
|
Q:
ubuntu9.10 : how to use python's lib-dynload and site-packages directories?
In ubuntu 9.10, in usr/lib/ there are the directories python2.4, python2.5, python2.6 and python3.0
Only python 2.6 is actually working.
python2.4 has only a lib-dynload directory,
python2.5 has only lib-dynload and site-packages,
python3.0 has only a dist-packages directory.
Now i'm wondering what is the idea behind this?
Because when i install python2.5 with ./configure, make, make install | altinstall
this goes into usr/local/lib and not usr/lib/ so why were these directories added tu ubuntu, how am i supposed to install python to use them?
A:
j3ll3, in Ubuntu (or any DPKG-based Linux OS) you can ask the question "What package provides XYZ" by typing
dpkg -S /path/to/XYZ
So, for example, in Ubuntu 9.10,
dpkg -S /usr/lib/python2.5/lib-dynload/gdbm.so
returns
python-gdbm: /usr/lib/python2.5/lib-dynload/gdbm.so
You can find out more about the python-gdbm package by typing
apt-cache show python-gdbm
which says that python-gdbm provides "GNU dbm database support for Python".
Perhaps more interestingly, if you type
dpkg --listfiles python-gdbm
you get to see a listing of all the files that python-gdbm installs:
...
/usr/lib/python2.4
/usr/lib/python2.4/lib-dynload
/usr/lib/python2.4/lib-dynload/gdbm.so
/usr/lib/python2.5
/usr/lib/python2.5/lib-dynload
/usr/lib/python2.5/lib-dynload/gdbm.so
/usr/lib/python2.6
/usr/lib/python2.6/lib-dynload
/usr/lib/python2.6/lib-dynload/gdbm.so
...
So it looks like this single package installs 3 .so libraries, one for each version of python.
Python2.6 is the default version of python in Ubuntu 9.10, but it is also possible to install
python2.4, 2.5 and/or 3.0. Unless you do so, only /usr/lib/python2.6/lib-dynload/gdbm.so is used, the others are just wasting space.
Since the unneeded files in python2.4, 2.5, 3.0 are not very large, the package maintainer probably felt it was easier to ship one package rather than one for each version of python.
However, unless you know how to fix future apt-get errors, I'd recommend not manually deleting any files that were installed by packages in Ubuntu.
A:
Sounds like they're an accident from some package(s) you have installed.
The Python version in use determines the locations searched to find installed Python packages/modules, and the "system version" of Python in Ubuntu 9.10 is 2.6, so that's what practically everything should be using. If you were to install the python2.5 package (or it gets installed as a dependency of something else), then it would use /usr/lib/python2.5/*. Try running which python and python --version; also which python2.6 and which python2.5.
From what I understand, though I'm not sure exactly why at all, Debian (from which Ubuntu is derived) uses a dist-packages naming scheme instead of site-packages.
Terminology: Python has packages and Debian (and so Ubuntu) has packages. They aren't the same kind of package, though individual Debian packages will install specific Python packages.
A:
The short answer to your question: when you install packages from source, you should use the packages' setup.py installer to install them automatically and correctly. This installer already knows where to properly install the modules so Python can find them. To use, simply call with the exact Python interpreter you want to use the package with.
A crash course in setup.py. First, run it with the exact Python executable that you want the package to be available to. If you want to use the package with /usr/bin/python2.5, you should use /usr/bin/python2.5 to run setup.py. Second, go to the directory where that package's setup.py is installed. Third, you must install as root, so it's easiest to do the whole tihng as root. Fourth, if you want to install to multiple Python interpreters, you should run setup.py with each, but you should clean it in between. So here's what I would do:
% cd /root/directory/of/untarred/source/package
% sudo su
# /path/to/first/python setup.py build install
# rm -rf build
# /path/to/second/python setup.py build install
# rm -rf build
# exit
%
If you're installing modules by hand... you shouldn't, you should use its setup.py. (If you wrote a new module, you should write a setup.py for it.) If you must install by hand, you'll need to figure out which is the proper directory to install into for each Python, either by exploration and experimentation, or by calling into the same libraries that the installer calls to determine the proper directory. Installers using distutils call distutils.sysconfig.get_python_lib(); installers using setup_tools look in setup_tools.command.easy_install.easy_install.INSTALL_SCHEMES[os.name]["install_dir"].
Regarding dist-packages: I had a conversation with the maintainer of the Python package for Debian earlier this year. He'd implemented this dist-packages in the beta packages picked up by Ubuntu 9.04, but the code had a bug wrt PYTHONUSERBASE which I tripped over. We wound up talking a little. IIRC the reason for dist-packages had something to do with forcing the user to install packages in a different directory from apt-get. I clearly don't really understand the motivation, though, because in practice both the user and apt-get still install into the same directory.
lib-dynload isn't a Debian thing; that's a directory Python itself installs. I believe it was a directory just for shared libraries implementing modules. I'm not sure Python still uses it.
Finally, I don't know what you mean by "only python2.6 is actually working". What about these differently-named directories is "not working"?
A:
I'm not sure what you mean by "Only python 2.6 is actually working." Suppose you run the "terminal emulator" and get a command-line prompt. Is this what you mean:
% python -V
Python 2.6
In other words, when you run Python, you get version 2.6? Well, have you tried this:
% python2.4
If Python 2.4 is correctly installed on your system, it will run. Likewise python2.5 will run Python 2.5.
If these don't run, and that is what you meant by "Only python 2.6 is actually working.", then one thing to try is to make sure that you actually have Ubuntu packages installed for Python 2.4 and Python 2.5.
% sudo apt-get install python2.4 python2.5
If you didn't have them installed before, this should add them. My thought is that you might have various libraries to support the older versions of Python, but you just don't have the actual Ubuntu packages for those older versions.
|
ubuntu9.10 : how to use python's lib-dynload and site-packages directories?
|
In ubuntu 9.10, in usr/lib/ there are the directories python2.4, python2.5, python2.6 and python3.0
Only python 2.6 is actually working.
python2.4 has only a lib-dynload directory,
python2.5 has only lib-dynload and site-packages,
python3.0 has only a dist-packages directory.
Now i'm wondering what is the idea behind this?
Because when i install python2.5 with ./configure, make, make install | altinstall
this goes into usr/local/lib and not usr/lib/ so why were these directories added tu ubuntu, how am i supposed to install python to use them?
|
[
"j3ll3, in Ubuntu (or any DPKG-based Linux OS) you can ask the question \"What package provides XYZ\" by typing\ndpkg -S /path/to/XYZ\n\nSo, for example, in Ubuntu 9.10,\ndpkg -S /usr/lib/python2.5/lib-dynload/gdbm.so\n\nreturns\npython-gdbm: /usr/lib/python2.5/lib-dynload/gdbm.so\n\nYou can find out more about the python-gdbm package by typing\napt-cache show python-gdbm\n\nwhich says that python-gdbm provides \"GNU dbm database support for Python\".\nPerhaps more interestingly, if you type\ndpkg --listfiles python-gdbm\n\nyou get to see a listing of all the files that python-gdbm installs:\n...\n/usr/lib/python2.4\n/usr/lib/python2.4/lib-dynload\n/usr/lib/python2.4/lib-dynload/gdbm.so\n/usr/lib/python2.5\n/usr/lib/python2.5/lib-dynload\n/usr/lib/python2.5/lib-dynload/gdbm.so\n/usr/lib/python2.6\n/usr/lib/python2.6/lib-dynload\n/usr/lib/python2.6/lib-dynload/gdbm.so\n...\n\nSo it looks like this single package installs 3 .so libraries, one for each version of python. \nPython2.6 is the default version of python in Ubuntu 9.10, but it is also possible to install \npython2.4, 2.5 and/or 3.0. Unless you do so, only /usr/lib/python2.6/lib-dynload/gdbm.so is used, the others are just wasting space. \nSince the unneeded files in python2.4, 2.5, 3.0 are not very large, the package maintainer probably felt it was easier to ship one package rather than one for each version of python.\nHowever, unless you know how to fix future apt-get errors, I'd recommend not manually deleting any files that were installed by packages in Ubuntu.\n",
"Sounds like they're an accident from some package(s) you have installed.\nThe Python version in use determines the locations searched to find installed Python packages/modules, and the \"system version\" of Python in Ubuntu 9.10 is 2.6, so that's what practically everything should be using. If you were to install the python2.5 package (or it gets installed as a dependency of something else), then it would use /usr/lib/python2.5/*. Try running which python and python --version; also which python2.6 and which python2.5.\nFrom what I understand, though I'm not sure exactly why at all, Debian (from which Ubuntu is derived) uses a dist-packages naming scheme instead of site-packages.\nTerminology: Python has packages and Debian (and so Ubuntu) has packages. They aren't the same kind of package, though individual Debian packages will install specific Python packages.\n",
"The short answer to your question: when you install packages from source, you should use the packages' setup.py installer to install them automatically and correctly. This installer already knows where to properly install the modules so Python can find them. To use, simply call with the exact Python interpreter you want to use the package with.\nA crash course in setup.py. First, run it with the exact Python executable that you want the package to be available to. If you want to use the package with /usr/bin/python2.5, you should use /usr/bin/python2.5 to run setup.py. Second, go to the directory where that package's setup.py is installed. Third, you must install as root, so it's easiest to do the whole tihng as root. Fourth, if you want to install to multiple Python interpreters, you should run setup.py with each, but you should clean it in between. So here's what I would do:\n% cd /root/directory/of/untarred/source/package\n% sudo su\n# /path/to/first/python setup.py build install\n# rm -rf build\n# /path/to/second/python setup.py build install\n# rm -rf build\n# exit\n%\n\nIf you're installing modules by hand... you shouldn't, you should use its setup.py. (If you wrote a new module, you should write a setup.py for it.) If you must install by hand, you'll need to figure out which is the proper directory to install into for each Python, either by exploration and experimentation, or by calling into the same libraries that the installer calls to determine the proper directory. Installers using distutils call distutils.sysconfig.get_python_lib(); installers using setup_tools look in setup_tools.command.easy_install.easy_install.INSTALL_SCHEMES[os.name][\"install_dir\"].\nRegarding dist-packages: I had a conversation with the maintainer of the Python package for Debian earlier this year. He'd implemented this dist-packages in the beta packages picked up by Ubuntu 9.04, but the code had a bug wrt PYTHONUSERBASE which I tripped over. We wound up talking a little. IIRC the reason for dist-packages had something to do with forcing the user to install packages in a different directory from apt-get. I clearly don't really understand the motivation, though, because in practice both the user and apt-get still install into the same directory.\nlib-dynload isn't a Debian thing; that's a directory Python itself installs. I believe it was a directory just for shared libraries implementing modules. I'm not sure Python still uses it.\nFinally, I don't know what you mean by \"only python2.6 is actually working\". What about these differently-named directories is \"not working\"?\n",
"I'm not sure what you mean by \"Only python 2.6 is actually working.\" Suppose you run the \"terminal emulator\" and get a command-line prompt. Is this what you mean:\n% python -V\nPython 2.6\n\nIn other words, when you run Python, you get version 2.6? Well, have you tried this:\n% python2.4\n\nIf Python 2.4 is correctly installed on your system, it will run. Likewise python2.5 will run Python 2.5.\nIf these don't run, and that is what you meant by \"Only python 2.6 is actually working.\", then one thing to try is to make sure that you actually have Ubuntu packages installed for Python 2.4 and Python 2.5.\n% sudo apt-get install python2.4 python2.5\n\nIf you didn't have them installed before, this should add them. My thought is that you might have various libraries to support the older versions of Python, but you just don't have the actual Ubuntu packages for those older versions.\n"
] |
[
2,
1,
0,
0
] |
[] |
[] |
[
"installation",
"python",
"ubuntu"
] |
stackoverflow_0001733364_installation_python_ubuntu.txt
|
Q:
A multithreaded queue in Python
I need to perform time consuming tasks in an webapplication.
Because the tasks can be so heavy that they run for minutes they have to run on multiple threads so the user won't have to look at a loading page for minutes.
So I thought a multithreaded queue would be a good solution.
Each instance of a object that you add to the queue should run on its own thread.
I've got a basic idea where to start but I bet that there are much much better solutions already written or in your brains ;).
My solution how the queue should look like:
[
[
obj_instance_1,[
(function_1, function_args_1, priority_1),
(function_2, function_args_2, priority_2),
]
],
[
obj_instance_2,[
(function_n, function_args_n, priority_n),
]
]
]
where [] are lists and () are tuples.
A:
The Python standard library Queue module is already thread-safe and aware and should work for your requirements.
Here's a nice paper Task Queue Implementation Pattern that discusses how to use Queue for task queues.
A:
You just need your elements to extend threading.Thread and use Conditions() to implement the producer,consumer system.
I would maintain a thread pool with it's own concurrency control and an add() method, allowing some other code to add threads into the pool.
Here is the documentation for Python threading which pretty much follows the conventions of other thread implementations ... nothing scary.
A:
kamaelia provides tools for abstracting concurrency to threads or process etc.
A:
I'd don't know much about python, but what you're describing sounds like a thread pool - this is from a quick google
http://pypi.python.org/pypi/threadpool/
A:
I'd recommend you look at beanstalkd or gearman.
Let your web server be a web server, and scale your long-running jobs independently and more safely by moving them through a queue to an external worker.
A:
I would recommend using process pools from the multithreading library. This is a built in library and abstracts most of the implementaion you need anyway, especially since pools work on lists and your data is already in the form of a list. You can use it with the map_async member function of the pool and assign a callback to notify the user whenever you have finished a particular task.
|
A multithreaded queue in Python
|
I need to perform time consuming tasks in an webapplication.
Because the tasks can be so heavy that they run for minutes they have to run on multiple threads so the user won't have to look at a loading page for minutes.
So I thought a multithreaded queue would be a good solution.
Each instance of a object that you add to the queue should run on its own thread.
I've got a basic idea where to start but I bet that there are much much better solutions already written or in your brains ;).
My solution how the queue should look like:
[
[
obj_instance_1,[
(function_1, function_args_1, priority_1),
(function_2, function_args_2, priority_2),
]
],
[
obj_instance_2,[
(function_n, function_args_n, priority_n),
]
]
]
where [] are lists and () are tuples.
|
[
"The Python standard library Queue module is already thread-safe and aware and should work for your requirements.\nHere's a nice paper Task Queue Implementation Pattern that discusses how to use Queue for task queues.\n",
"You just need your elements to extend threading.Thread and use Conditions() to implement the producer,consumer system.\nI would maintain a thread pool with it's own concurrency control and an add() method, allowing some other code to add threads into the pool.\nHere is the documentation for Python threading which pretty much follows the conventions of other thread implementations ... nothing scary.\n",
"kamaelia provides tools for abstracting concurrency to threads or process etc.\n",
"I'd don't know much about python, but what you're describing sounds like a thread pool - this is from a quick google\nhttp://pypi.python.org/pypi/threadpool/\n",
"I'd recommend you look at beanstalkd or gearman.\nLet your web server be a web server, and scale your long-running jobs independently and more safely by moving them through a queue to an external worker.\n",
"I would recommend using process pools from the multithreading library. This is a built in library and abstracts most of the implementaion you need anyway, especially since pools work on lists and your data is already in the form of a list. You can use it with the map_async member function of the pool and assign a callback to notify the user whenever you have finished a particular task. \n"
] |
[
6,
2,
2,
1,
0,
0
] |
[] |
[] |
[
"multithreading",
"python",
"queue"
] |
stackoverflow_0001666441_multithreading_python_queue.txt
|
Q:
What's the most Pythonic XHTML/HTML parser/generator/template module that supports DOM like access?
It should be able to create, modify and read X/HTML in a highly object oriented way that still feels DOM like but is not obese, and is really Pythonic.
Preferably it would deal with malformed HTML too, but we can skip this for templates.
For example, I'd like to do this:
>> from someAmazingTemplate import *
>> html = Template('<html><head><title>Hi</title></head><body></body></html>')
>> html.head.append('<link type="text/css" href="main.css" rel="stylesheet" />')
>> html.head.title
Hi
>> html['head']['title']
Hi
I should be able to use/define short functions and use them like this:
>> html.head.append(stylesheet(href="main.css"))
>> html.body.append(h1('BIG TITLE!12',Class="roflol"))
>> html.body.SOURCE
<body>
<h1 class="roflol">
BIG TITLE!12
</h1>
</body>
Note: If it doesn't exist, I'm going to make it under BSD/MIT/Python license. Help is most welcome.
Anything that works towards more Pythonic web app development will be great.
Very much appreciate it!
-Luke Stanley
A:
The first part can for the most part be done by ElementTree, but it takes a few more steps:
>>> import xml.etree.ElementTree as ET
>>> html = ET.XML('<html><head><title>Hi</title></head><body></body></html>')
>>> html.head = html.find('head')
>>> html.head.append(ET.XML('<link type="text/css" href="main.css" rel="stylesheet" />'))
>>> html.head.title = html.head.find('title')
>>> html.head.title.text
'Hi'
The second part can be completed by creating Element objects, but you'd need to do some of your own work to make it happen the way you really want:
>>> html.body = html.find('body')
>>> my_h1 = ET.Element('h1', {'class': 'roflol'})
>>> my_h1.text = 'BIG TITLE!12'
>>> html.body.append(my_h1)
>>> html.body.SOURCE = ET.tostring(html.body)
>>> html.body.SOURCE
'<body><h1 class="roflol">BIG TITLE!12</h1></body>'
You could create a stylesheet function of your own:
>>> def stylesheet(href='', type='text/css', rel='stylesheet', **kwargs):
... elem = ET.Element('link', href=href, type=type, rel=rel)
... return elem
...
>>> html.head.append(stylesheet(href="main.css"))
And the whole document:
>>> ET.tostring(html)
<html><head><title>Hi</title><link href="main.css" rel="stylesheet" type="text/css" /></head><body><h1 class="roflol">BIG TITLE!12</h1></body></html>
But, I think if you're going to end up writing your own thing, this is a good place to start. ElementTree is very powerful.
Edit: I realize that this is probably not exactly what you're looking for. I just wanted to provide something as an available alternative and to also prove that it could actually be done without too much work.
A:
Amara Bindery provides the most Pythonic XML API I've seen. See the quick reference, manual and faq
|
What's the most Pythonic XHTML/HTML parser/generator/template module that supports DOM like access?
|
It should be able to create, modify and read X/HTML in a highly object oriented way that still feels DOM like but is not obese, and is really Pythonic.
Preferably it would deal with malformed HTML too, but we can skip this for templates.
For example, I'd like to do this:
>> from someAmazingTemplate import *
>> html = Template('<html><head><title>Hi</title></head><body></body></html>')
>> html.head.append('<link type="text/css" href="main.css" rel="stylesheet" />')
>> html.head.title
Hi
>> html['head']['title']
Hi
I should be able to use/define short functions and use them like this:
>> html.head.append(stylesheet(href="main.css"))
>> html.body.append(h1('BIG TITLE!12',Class="roflol"))
>> html.body.SOURCE
<body>
<h1 class="roflol">
BIG TITLE!12
</h1>
</body>
Note: If it doesn't exist, I'm going to make it under BSD/MIT/Python license. Help is most welcome.
Anything that works towards more Pythonic web app development will be great.
Very much appreciate it!
-Luke Stanley
|
[
"The first part can for the most part be done by ElementTree, but it takes a few more steps:\n>>> import xml.etree.ElementTree as ET\n>>> html = ET.XML('<html><head><title>Hi</title></head><body></body></html>')\n>>> html.head = html.find('head')\n>>> html.head.append(ET.XML('<link type=\"text/css\" href=\"main.css\" rel=\"stylesheet\" />'))\n>>> html.head.title = html.head.find('title')\n>>> html.head.title.text\n'Hi'\n\nThe second part can be completed by creating Element objects, but you'd need to do some of your own work to make it happen the way you really want:\n>>> html.body = html.find('body')\n>>> my_h1 = ET.Element('h1', {'class': 'roflol'})\n>>> my_h1.text = 'BIG TITLE!12'\n>>> html.body.append(my_h1)\n>>> html.body.SOURCE = ET.tostring(html.body)\n>>> html.body.SOURCE\n'<body><h1 class=\"roflol\">BIG TITLE!12</h1></body>'\n\nYou could create a stylesheet function of your own:\n>>> def stylesheet(href='', type='text/css', rel='stylesheet', **kwargs):\n... elem = ET.Element('link', href=href, type=type, rel=rel) \n... return elem\n... \n>>> html.head.append(stylesheet(href=\"main.css\"))\n\nAnd the whole document:\n>>> ET.tostring(html)\n<html><head><title>Hi</title><link href=\"main.css\" rel=\"stylesheet\" type=\"text/css\" /></head><body><h1 class=\"roflol\">BIG TITLE!12</h1></body></html>\n\nBut, I think if you're going to end up writing your own thing, this is a good place to start. ElementTree is very powerful.\nEdit: I realize that this is probably not exactly what you're looking for. I just wanted to provide something as an available alternative and to also prove that it could actually be done without too much work.\n",
"Amara Bindery provides the most Pythonic XML API I've seen. See the quick reference, manual and faq\n"
] |
[
5,
1
] |
[] |
[] |
[
"dom",
"parsing",
"python",
"template_engine",
"xhtml"
] |
stackoverflow_0001745524_dom_parsing_python_template_engine_xhtml.txt
|
Q:
How to allow a many-to-many relationship to be configured in Python
I have a simple app which requires a many-to-many relationship to be configured as part of its set-up. For example, the app requires a list of repository URLs, a list of users and for each user, a subset of the repository URLs.
I first thought of using a config.py file similar to the following:
repositories = {
'repo1': 'http://svn.example.com/repo1/',
'repo2': 'http://svn.example.com/repo2/',
'repo3': 'http://svn.example.com/repo3/',
}
user_repository_mapping = {
'person_A': ['repo1', 'repo3'],
'person_B': ['repo2'],
'person_C': ['repo1', 'repo2']
}
which I could import. But this is quite messy as the config file lives outside my python-path and I would rather use a standard configuration approach such as using ini files or YAML.
Is there an elegant way of configuring a relationship such as this without importing a Python directly?
A:
I would store the config in JSON format. For example:
cfg = """
{
"repositories": {
"repo1": "http://svn.example.com/repo1/",
"repo2": "http://svn.example.com/repo2/",
"repo3": "http://svn.example.com/repo3/"
},
"user_repository_mapping": {
"person_A": ["repo1", "repo3"],
"person_B": ["repo2"],
"person_C": ["repo1", "repo2"]
}
}
"""
import simplejson as json
config = json.loads(cfg)
person = "person_A"
repos = [config['repositories'][r] for r in config['user_repository_mapping'][person]]
print repos
A:
If you like the idea of representing structure by indentation (like in Python) then YAML will be perfect for you. If you don't want to rely on whitespace and prefer explicit syntax then better go with JSON. Both are easy to understand and popular, which means that there are Python libraries out there.
Additional advantage is the fact that, in contrast to using standard Python code, you can be sure that your configuration file can contains only data and no arbitrary code that will get executed.
|
How to allow a many-to-many relationship to be configured in Python
|
I have a simple app which requires a many-to-many relationship to be configured as part of its set-up. For example, the app requires a list of repository URLs, a list of users and for each user, a subset of the repository URLs.
I first thought of using a config.py file similar to the following:
repositories = {
'repo1': 'http://svn.example.com/repo1/',
'repo2': 'http://svn.example.com/repo2/',
'repo3': 'http://svn.example.com/repo3/',
}
user_repository_mapping = {
'person_A': ['repo1', 'repo3'],
'person_B': ['repo2'],
'person_C': ['repo1', 'repo2']
}
which I could import. But this is quite messy as the config file lives outside my python-path and I would rather use a standard configuration approach such as using ini files or YAML.
Is there an elegant way of configuring a relationship such as this without importing a Python directly?
|
[
"I would store the config in JSON format. For example:\ncfg = \"\"\"\n{\n \"repositories\": {\n \"repo1\": \"http://svn.example.com/repo1/\",\n \"repo2\": \"http://svn.example.com/repo2/\",\n \"repo3\": \"http://svn.example.com/repo3/\"\n },\n \"user_repository_mapping\": {\n \"person_A\": [\"repo1\", \"repo3\"],\n \"person_B\": [\"repo2\"],\n \"person_C\": [\"repo1\", \"repo2\"]\n }\n}\n\"\"\"\n\nimport simplejson as json\nconfig = json.loads(cfg)\nperson = \"person_A\"\nrepos = [config['repositories'][r] for r in config['user_repository_mapping'][person]]\nprint repos\n\n",
"If you like the idea of representing structure by indentation (like in Python) then YAML will be perfect for you. If you don't want to rely on whitespace and prefer explicit syntax then better go with JSON. Both are easy to understand and popular, which means that there are Python libraries out there.\nAdditional advantage is the fact that, in contrast to using standard Python code, you can be sure that your configuration file can contains only data and no arbitrary code that will get executed.\n"
] |
[
2,
1
] |
[
"The tactic I use is to put the whole application in a class, and then instead of having an importable config file, allow the user to pass in configuration to the constructor. Or, in more complicated cases they could even subclass the application class to add members or change behaviours. Although this does require a little knowledge of Python syntax in order to configure the app, it's not really that difficult, and much more flexible than the ini/markup config file approach.\nSo you example you could have an invoke-script outside the pythonpath looking like:\n#!/usr/bin/env python\n\nimport someapplication\n\nclass MySomeApplication(someapplication.Application):\n repositories = {\n 'repo1': 'http://svn.example.com/repo1/',\n 'repo2': 'http://svn.example.com/repo2/',\n 'repo3': 'http://svn.example.com/repo3/',\n }\n user_repository_mapping = {\n 'person_A': ['repo1', 'repo3'],\n 'person_B': ['repo2'],\n 'person_C': ['repo1', 'repo2']\n }\n\nMySomeApplication().run()\n\nThen to have a second configuration they can swap out or even run at the same time, you simply cope the invoke-script and change the settings in it.\n"
] |
[
-1
] |
[
"configuration",
"python"
] |
stackoverflow_0001745479_configuration_python.txt
|
Q:
Connecting to APNS for iPhone Using Python
I'm trying to send push notifications to an iPhone using Python. I've exported my certificate and private key into a p12 file from keychain access and then converted it into pem file using the following command:
openssl pkcs12 -in cred.p12 -out cert.pem -nodes -clcerts
I'm using APNSWrapper in Python for the connection.
I run the following code:
deviceToken = 'Qun\xaa\xd ... c0\x9c\xf6\xca'
# create wrapper
wrapper = APNSNotificationWrapper('/path/to/cert/cert.pem', True)
# create message
message = APNSNotification()
message.token(deviceToken)
message.badge(5)
# add message to tuple and send it to APNS server
wrapper.append(message)
wrapper.notify()
And then I get the error message:
ssl.SSLError: (1, '_ssl.c:485:
error:14094416:SSL routines:SSL3_READ_BYTES:sslv3 alert certificate unknown')
Can anyone help me out on this?
A:
I recently did this using Django - http://leecutsco.de/2009/07/14/push-on-the-iphone/
May be useful? It's making use of no extra libraries other than those included with Python already. Wouldn't take much to extract the send_message() method out.
A:
Have you considered the Twisted package? The below code is taken from here:
from struct import pack
from OpenSSL import SSL
from twisted.internet import reactor
from twisted.internet.protocol import ClientFactory, Protocol
from twisted.internet.ssl import ClientContextFactory
APNS_SERVER_HOSTNAME = "<insert the push hostname from your iPhone developer portal>"
APNS_SERVER_PORT = 2195
APNS_SSL_CERTIFICATE_FILE = "<your ssl certificate.pem>"
APNS_SSL_PRIVATE_KEY_FILE = "<your ssl private key.pem>"
class APNSClientContextFactory(ClientContextFactory):
def __init__(self):
self.ctx = SSL.Context(SSL.SSLv3_METHOD)
self.ctx.use_certificate_file(APNS_SSL_CERTIFICATE_FILE)
self.ctx.use_privatekey_file(APNS_SSL_PRIVATE_KEY_FILE)
def getContext(self):
return self.ctx
class APNSProtocol(Protocol):
def sendMessage(self, deviceToken, payload):
# notification messages are binary messages in network order
# using the following format:
# <1 byte command> <2 bytes length><token> <2 bytes length><payload>
fmt = "!cH32cH%dc" % len(payload)
command = 0
msg = struct.pack(fmt, command, deviceToken,
len(payload), payload)
self.transport.write(msg)
class APNSClientFactory(ClientFactory):
def buildProtocol(self, addr):
print "Connected to APNS Server %s:%u" % (addr.host, addr.port)
return APNSProtocol()
def clientConnectionLost(self, connector, reason):
print "Lost connection. Reason: %s" % reason
def clientConnectionFailed(self, connector, reason):
print "Connection failed. Reason: %s" % reason
if __name__ == '__main__':
reactor.connectSSL(APNS_SERVER_HOSTNAME,
APNS_SERVER_PORT,
APNSClientFactory(),
APNSClientContextFactory())
reactor.run()
A:
there were a few bugs in the originally posted code, so here's a corrected version that works for me.
from struct import pack
from OpenSSL import SSL
from twisted.internet import reactor
from twisted.internet.protocol import ClientFactory, Protocol
from twisted.internet.ssl import ClientContextFactory
import binascii
import struct
APNS_SERVER_HOSTNAME = "gateway.sandbox.push.apple.com"
APNS_SERVER_PORT = 2195
APNS_SSL_CERTIFICATE_FILE = "<your ssl certificate.pem>"
APNS_SSL_PRIVATE_KEY_FILE = "<your ssl private key.pem>"
DEVICE_TOKEN = "<hexlified device token>"
MESSAGE = '{"aps":{"alert":"twisted test"}}'
class APNSClientContextFactory(ClientContextFactory):
def __init__(self):
self.ctx = SSL.Context(SSL.SSLv3_METHOD)
self.ctx.use_certificate_file(APNS_SSL_CERTIFICATE_FILE)
self.ctx.use_privatekey_file(APNS_SSL_PRIVATE_KEY_FILE)
def getContext(self):
return self.ctx
class APNSProtocol(Protocol):
def connectionMade(self):
print "connection made"
self.sendMessage(binascii.unhexlify(DEVICE_TOKEN), MESSAGE)
self.transport.loseConnection()
def sendMessage(self, deviceToken, payload):
# notification messages are binary messages in network order
# using the following format:
# <1 byte command> <2 bytes length><token> <2 bytes length><payload>
fmt = "!cH32sH%ds" % len(payload)
command = '\x00'
msg = struct.pack(fmt, command, 32, deviceToken,
len(payload), payload)
print "%s: %s" %(binascii.hexlify(deviceToken), binascii.hexlify(msg))
self.transport.write(msg)
class APNSClientFactory(ClientFactory):
def buildProtocol(self, addr):
print "Connected to APNS Server %s:%u" % (addr.host, addr.port)
return APNSProtocol()
def clientConnectionLost(self, connector, reason):
print "Lost connection. Reason: %s" % reason
def clientConnectionFailed(self, connector, reason):
print "Connection failed. Reason: %s" % reason
if __name__ == '__main__':
reactor.connectSSL(APNS_SERVER_HOSTNAME,
APNS_SERVER_PORT,
APNSClientFactory(),
APNSClientContextFactory())
reactor.run()
A:
Try to update to latest APNSWrapper version (0.4). There is build-in support of openssl command line tool (openssl s_client) now.
A:
I tried both APNSWrapper and Lee Peckham's code and couldn't get it to work under Snow Leopard with Python 2.6. After a lot of trial and error it finally worked with pyOpenSSL.
I already did a post with details and code snippets here so I'll just refer you there.
|
Connecting to APNS for iPhone Using Python
|
I'm trying to send push notifications to an iPhone using Python. I've exported my certificate and private key into a p12 file from keychain access and then converted it into pem file using the following command:
openssl pkcs12 -in cred.p12 -out cert.pem -nodes -clcerts
I'm using APNSWrapper in Python for the connection.
I run the following code:
deviceToken = 'Qun\xaa\xd ... c0\x9c\xf6\xca'
# create wrapper
wrapper = APNSNotificationWrapper('/path/to/cert/cert.pem', True)
# create message
message = APNSNotification()
message.token(deviceToken)
message.badge(5)
# add message to tuple and send it to APNS server
wrapper.append(message)
wrapper.notify()
And then I get the error message:
ssl.SSLError: (1, '_ssl.c:485:
error:14094416:SSL routines:SSL3_READ_BYTES:sslv3 alert certificate unknown')
Can anyone help me out on this?
|
[
"I recently did this using Django - http://leecutsco.de/2009/07/14/push-on-the-iphone/\nMay be useful? It's making use of no extra libraries other than those included with Python already. Wouldn't take much to extract the send_message() method out.\n",
"Have you considered the Twisted package? The below code is taken from here:\nfrom struct import pack\nfrom OpenSSL import SSL\nfrom twisted.internet import reactor\nfrom twisted.internet.protocol import ClientFactory, Protocol\nfrom twisted.internet.ssl import ClientContextFactory\n\nAPNS_SERVER_HOSTNAME = \"<insert the push hostname from your iPhone developer portal>\"\nAPNS_SERVER_PORT = 2195\nAPNS_SSL_CERTIFICATE_FILE = \"<your ssl certificate.pem>\"\nAPNS_SSL_PRIVATE_KEY_FILE = \"<your ssl private key.pem>\"\n\nclass APNSClientContextFactory(ClientContextFactory):\n def __init__(self):\n self.ctx = SSL.Context(SSL.SSLv3_METHOD)\n self.ctx.use_certificate_file(APNS_SSL_CERTIFICATE_FILE)\n self.ctx.use_privatekey_file(APNS_SSL_PRIVATE_KEY_FILE)\n\n def getContext(self):\n return self.ctx\n\nclass APNSProtocol(Protocol):\n def sendMessage(self, deviceToken, payload):\n # notification messages are binary messages in network order\n # using the following format:\n # <1 byte command> <2 bytes length><token> <2 bytes length><payload>\n fmt = \"!cH32cH%dc\" % len(payload)\n command = 0\n msg = struct.pack(fmt, command, deviceToken,\n len(payload), payload)\n self.transport.write(msg)\n\nclass APNSClientFactory(ClientFactory):\n def buildProtocol(self, addr):\n print \"Connected to APNS Server %s:%u\" % (addr.host, addr.port)\n return APNSProtocol()\n\n def clientConnectionLost(self, connector, reason):\n print \"Lost connection. Reason: %s\" % reason\n\n def clientConnectionFailed(self, connector, reason):\n print \"Connection failed. Reason: %s\" % reason\n\nif __name__ == '__main__':\n reactor.connectSSL(APNS_SERVER_HOSTNAME, \n APNS_SERVER_PORT,\n APNSClientFactory(), \n APNSClientContextFactory())\n reactor.run()\n\n",
"there were a few bugs in the originally posted code, so here's a corrected version that works for me.\nfrom struct import pack\nfrom OpenSSL import SSL\nfrom twisted.internet import reactor\nfrom twisted.internet.protocol import ClientFactory, Protocol\nfrom twisted.internet.ssl import ClientContextFactory\nimport binascii\nimport struct\n\nAPNS_SERVER_HOSTNAME = \"gateway.sandbox.push.apple.com\"\nAPNS_SERVER_PORT = 2195\nAPNS_SSL_CERTIFICATE_FILE = \"<your ssl certificate.pem>\"\nAPNS_SSL_PRIVATE_KEY_FILE = \"<your ssl private key.pem>\"\nDEVICE_TOKEN = \"<hexlified device token>\"\nMESSAGE = '{\"aps\":{\"alert\":\"twisted test\"}}'\n\nclass APNSClientContextFactory(ClientContextFactory):\n def __init__(self):\n self.ctx = SSL.Context(SSL.SSLv3_METHOD)\n self.ctx.use_certificate_file(APNS_SSL_CERTIFICATE_FILE)\n self.ctx.use_privatekey_file(APNS_SSL_PRIVATE_KEY_FILE)\n\n def getContext(self):\n return self.ctx\n\nclass APNSProtocol(Protocol):\n\n def connectionMade(self):\n print \"connection made\"\n self.sendMessage(binascii.unhexlify(DEVICE_TOKEN), MESSAGE)\n self.transport.loseConnection()\n\n def sendMessage(self, deviceToken, payload):\n # notification messages are binary messages in network order\n # using the following format:\n # <1 byte command> <2 bytes length><token> <2 bytes length><payload>\n fmt = \"!cH32sH%ds\" % len(payload)\n command = '\\x00'\n msg = struct.pack(fmt, command, 32, deviceToken,\n len(payload), payload)\n print \"%s: %s\" %(binascii.hexlify(deviceToken), binascii.hexlify(msg))\n self.transport.write(msg)\n\nclass APNSClientFactory(ClientFactory):\n def buildProtocol(self, addr):\n print \"Connected to APNS Server %s:%u\" % (addr.host, addr.port)\n return APNSProtocol()\n\n def clientConnectionLost(self, connector, reason):\n print \"Lost connection. Reason: %s\" % reason\n\n def clientConnectionFailed(self, connector, reason):\n print \"Connection failed. Reason: %s\" % reason\n\nif __name__ == '__main__':\n reactor.connectSSL(APNS_SERVER_HOSTNAME,\n APNS_SERVER_PORT,\n APNSClientFactory(),\n APNSClientContextFactory())\n reactor.run()\n\n",
"Try to update to latest APNSWrapper version (0.4). There is build-in support of openssl command line tool (openssl s_client) now.\n",
"I tried both APNSWrapper and Lee Peckham's code and couldn't get it to work under Snow Leopard with Python 2.6. After a lot of trial and error it finally worked with pyOpenSSL. \nI already did a post with details and code snippets here so I'll just refer you there.\n"
] |
[
8,
2,
2,
1,
0
] |
[] |
[] |
[
"iphone",
"push_notification",
"python",
"ssl"
] |
stackoverflow_0001172769_iphone_push_notification_python_ssl.txt
|
Q:
how can I filter on the second element in a tuple of tuples?
In my model I have a field:
country = models.CharField(_('Country'), max_length=2, choices=COUNTRIES)
Where COUNTRIES is a tuple of tuples like this:
COUNTRIES = (
('AF', _('Afghanistan')),
... and so on
Now I want to filter an instance of that model, by the country name.
This:
i = MyModel.objects.filter(country__iexact=query)
only lets me filter by the country code.
How can I filter by country name?
A:
You cannot filter directly by the country name (the choices are only used in the UI, not in the database).
If you get the full name as an input, lookup the code in the COUNTRIES tuple-of-tuples. For example:
# ... initialize a lookup dictionary
country_to_id_dict = dict((t[1], t[0]) for t in COUNTRIES)
# ... use the dictionary in the query
i = MyModel.objects.filter(country__exact=country_to_id_dict[query])
|
how can I filter on the second element in a tuple of tuples?
|
In my model I have a field:
country = models.CharField(_('Country'), max_length=2, choices=COUNTRIES)
Where COUNTRIES is a tuple of tuples like this:
COUNTRIES = (
('AF', _('Afghanistan')),
... and so on
Now I want to filter an instance of that model, by the country name.
This:
i = MyModel.objects.filter(country__iexact=query)
only lets me filter by the country code.
How can I filter by country name?
|
[
"You cannot filter directly by the country name (the choices are only used in the UI, not in the database).\nIf you get the full name as an input, lookup the code in the COUNTRIES tuple-of-tuples. For example:\n# ... initialize a lookup dictionary\ncountry_to_id_dict = dict((t[1], t[0]) for t in COUNTRIES)\n\n# ... use the dictionary in the query\ni = MyModel.objects.filter(country__exact=country_to_id_dict[query])\n\n"
] |
[
4
] |
[] |
[] |
[
"country",
"django",
"filter",
"python"
] |
stackoverflow_0001745919_country_django_filter_python.txt
|
Q:
Embedding a control in a QTableView?
I'm working a small qt app (using PyQt4) and I've come up with an idea but I'm unsure as to how to implement it. I have a QTableView that represents some data and I'd like to add another column to the QTableView that contains a checkbox control that could be wired up to some piece of the model. For example, something like this:
Note the Delete column has a checkbox widget for each row (although this is a web app, not a desktop Qt app, the principal is the same). Bonus points if I can select multiple rows, right click, and choose "Check/Uncheck Selected".
If any of this is unclear, drop a comment here and I'll clarify.
A:
Implementing your own table model is more work than using QStandardItemModel (as @Andy recommends), but it does give you a fine control over what you want to do, so I'll try to give you a summary of what to do. I assume you know all about Qt's documentation and PyQt's class documentation and can look up whatever classes you need. (I may be overexplaining if you already have a QTableView but better than leaving something out, I think.)
To get checkable states:
Create a subclass of QTableModel.
Select some data structure to store the contents of your rows. This can be pretty simple (a big internal list), or as complex as a SQL database (in which case see QSqlTableModel instead).
Override rowCount, columnCount, data, and setData.
rowCount and columnCount correspond fairly directly to what you use for a data model. If you basically are using a 2D array (or list of lists), they can be as short as one-liners.
data is where things get interesting. Item models store several different fields (which Qt calls roles) and what data returns depends on what role is being asked for. Note that I talk about the data types of what's returned but it always needs to be wrapped into QVariant.
Qt.DisplayRole is whatever text is displayed in the cells of the table. This is your actual data, and is by far the common case (so that this is the default role).
Qt.CheckStateRole is a boolean. Returning Qt.Checked will display a checked check-box, and Qt.Unchecked will return an unchecked one. If all you want a column to contain is check-boxes only handle this role.
The other roles are useful for icons, for background colors, and a number of other features but these.
Any unhandled role should return a QVariant.
setData is symmetric to data. You should handle the roles you handle in data: Qt.DisplayRole for the actual data, and Qt.CheckStateRole for the checkboxes.
To allow multiple selection of rows and columns and cells. To do that you want to understand selection models. The short version is:
Set the selection mode on your table view: view.setSelectionMode( QAbstractItemView.ContiguousSelection). This will let you highlight contiguous cells. You can highlight arbitrary cells as well: see QAbstractView.SelectionMode.
To determine which cells are actually selected following an action ask the table view for its selection model (note the 'l'): view.selectionModel().selectedIndexes(). You can iterate through these with a for loop.
To allow right-clicking:
Override your view's contextMenuEvent.
Create a QMenu and connect it to whatever slots you need.
For a more in-depth understanding read the Qt guide to Model/View if you haven't already. And definitely look at the Qt item view examples. Many of the ones describe are implemented in PyQt in much less code (including the two @Jesse mentions), and the tree model examples carry over to tables but with much less work (you need to implement much less, as described above.)
A:
You could also have a look at the QStandardItemModel, which gives you an interface to interact with items through a "checkable" state !
You could also inherit from QAbstractItemModel and use the role Qt::CheckStateRole...
A:
In Qt/C++ you can create a delegate for custom items in a column. I would assume you can do something very similar in PyQt. See the following examples:
Star Delegate Example
Spin Box Delegate Example
|
Embedding a control in a QTableView?
|
I'm working a small qt app (using PyQt4) and I've come up with an idea but I'm unsure as to how to implement it. I have a QTableView that represents some data and I'd like to add another column to the QTableView that contains a checkbox control that could be wired up to some piece of the model. For example, something like this:
Note the Delete column has a checkbox widget for each row (although this is a web app, not a desktop Qt app, the principal is the same). Bonus points if I can select multiple rows, right click, and choose "Check/Uncheck Selected".
If any of this is unclear, drop a comment here and I'll clarify.
|
[
"Implementing your own table model is more work than using QStandardItemModel (as @Andy recommends), but it does give you a fine control over what you want to do, so I'll try to give you a summary of what to do. I assume you know all about Qt's documentation and PyQt's class documentation and can look up whatever classes you need. (I may be overexplaining if you already have a QTableView but better than leaving something out, I think.)\nTo get checkable states:\n\nCreate a subclass of QTableModel.\n\n\nSelect some data structure to store the contents of your rows. This can be pretty simple (a big internal list), or as complex as a SQL database (in which case see QSqlTableModel instead).\nOverride rowCount, columnCount, data, and setData.\n\n\nrowCount and columnCount correspond fairly directly to what you use for a data model. If you basically are using a 2D array (or list of lists), they can be as short as one-liners.\ndata is where things get interesting. Item models store several different fields (which Qt calls roles) and what data returns depends on what role is being asked for. Note that I talk about the data types of what's returned but it always needs to be wrapped into QVariant.\n\n\nQt.DisplayRole is whatever text is displayed in the cells of the table. This is your actual data, and is by far the common case (so that this is the default role).\nQt.CheckStateRole is a boolean. Returning Qt.Checked will display a checked check-box, and Qt.Unchecked will return an unchecked one. If all you want a column to contain is check-boxes only handle this role.\nThe other roles are useful for icons, for background colors, and a number of other features but these.\nAny unhandled role should return a QVariant.\n\nsetData is symmetric to data. You should handle the roles you handle in data: Qt.DisplayRole for the actual data, and Qt.CheckStateRole for the checkboxes.\n\n\n\nTo allow multiple selection of rows and columns and cells. To do that you want to understand selection models. The short version is:\n\nSet the selection mode on your table view: view.setSelectionMode( QAbstractItemView.ContiguousSelection). This will let you highlight contiguous cells. You can highlight arbitrary cells as well: see QAbstractView.SelectionMode.\nTo determine which cells are actually selected following an action ask the table view for its selection model (note the 'l'): view.selectionModel().selectedIndexes(). You can iterate through these with a for loop.\n\nTo allow right-clicking:\n\nOverride your view's contextMenuEvent.\nCreate a QMenu and connect it to whatever slots you need.\n\nFor a more in-depth understanding read the Qt guide to Model/View if you haven't already. And definitely look at the Qt item view examples. Many of the ones describe are implemented in PyQt in much less code (including the two @Jesse mentions), and the tree model examples carry over to tables but with much less work (you need to implement much less, as described above.)\n",
"You could also have a look at the QStandardItemModel, which gives you an interface to interact with items through a \"checkable\" state !\nYou could also inherit from QAbstractItemModel and use the role Qt::CheckStateRole...\n",
"In Qt/C++ you can create a delegate for custom items in a column. I would assume you can do something very similar in PyQt. See the following examples:\nStar Delegate Example\nSpin Box Delegate Example\n"
] |
[
8,
4,
1
] |
[] |
[] |
[
"pyqt4",
"python",
"qt",
"tableview"
] |
stackoverflow_0001744348_pyqt4_python_qt_tableview.txt
|
Q:
QtPython Qtreewidget Problem
I trying to do a Qtreewidget to attend a customer design suggestion. I am coding it on QtPython. I did a first try using Qt Designer, then generated the code. But when I try to run it, an error comes out:
self.centralwidget.setSortingEnabled(__sortingEnabled)
AttributeError: setSortingEnabled
I googled around, but didn't find any solution for this problem, except some suggestion just to simply delete the lines in the code that results in the compiling error. But it didn't really help, because if you do so, it triggers more error, just like that:
self.treeWidget.topLevelItem(0).child(1).setText(0, QtGui.QApplication.translate("MainWindow", "Item Name", None, QtGui.QApplication.UnicodeUTF8))
AttributeError: 'NoneType' object has no attribute 'setText'
Here is my current code to generate a nice simple QtreeWidget/View:
#//==========================//#
def color_setupUi(self, MainWindow,phrase):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.eqpt_centralwdg(MainWindow)
self.eqpt_retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
#//==========================//#
def eqpt_centralwdg(self,MainWindow):
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.colorTreeWidget = QtGui.QTreeWidget(self.centralwidget)
self.colorTreeWidget.setGeometry(QtCore.QRect(60, 60, 191, 141))
self.colorTreeWidget.setObjectName("colorTreeWidget")
item = QtGui.QTreeWidgetItem(self.colorTreeWidget)
item = QtGui.QTreeWidgetItem(self.colorTreeWidget)
self.centralwidget.setSortingEnabled(__sortingEnabled)
MainWindow.setCentralWidget(self.centralwidget)
#//==========================//#
def eqpt_retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8)
self.colorTreeWidget.headerItem().setText(0, QtGui.QApplication.translate("MainWindow", "color", None, QtGui.QApplication.UnicodeUTF8)
__sortingEnabled = self.colorTreeWidget.isSortingEnabled()
self.colorTreeWidget.setSortingEnabled(False)
self.colorTreeWidget.topLevelItem(0).setText(0, QtGui.QApplication.translate("MainWindow", "Yellow", None, QtGui.QApplication.UnicodeUTF8)
self.colorTreeWidget.topLevelItem(1).setText(0, QtGui.QApplication.translate("MainWindow", "Blue", None, QtGui.QApplication.UnicodeUTF8)
self.colorTreeWidget.setSortingEnabled(__sortingEnabled)
#//==========================//#
All other object I needed to implement on Qt using Designer and a little bit of code has worked fine so far, e.g. inputLine, comboBox, TabWidget. I just got stuck with this TreeWidget error.
Any hints or suggestion are highly appreciated and welcome.
A:
I'm assuming the code you posted is what you got when you ran your UI file through pyuic4. I found the PyQt UI compiler to be buggy sometimes. All you can do is fix the output manually and complain to the vendor.
In your case, the line
self.centralwidget.setSortingEnabled(__sortingEnabled)
should read
self.colorTreeWidget.setSortingEnabled(__sortingEnabled)
I don't understand where the AttributeError: 'NoneType' object has no attribute 'setText' comes from. You're not referencing self.treeWidget.topLevelItem(0) in the code below.
Since the UI doesn't seem too complex yet, it might be worth it to start again from scratch in the QT Designer. Try to avoid cutting and pasting controls, so as not to confuse the Designer / pyuic4. Good luck!
A:
Here is the solution:
delete/comment only the following line:
self.centralwidget.setSortingEnabled(__sortingEnabled)
Then code:
def eqpt_centralwdg(self,MainWindow):
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.colorTreeWidget = QtGui.QTreeWidget(self.centralwidget)
self.colorTreeWidget.setGeometry(QtCore.QRect(60, 60, 191, 141))
self.colorTreeWidget.setObjectName("colorTreeWidget")
item = QtGui.QTreeWidgetItem(self.colorTreeWidget)
item = QtGui.QTreeWidgetItem(self.colorTreeWidget)
self.connect(self.colorTreeWidget, QtCore.SIGNAL('itemClicked(QTreeWidgetItem*, int)'), self.eqpt_activateInput)
MainWindow.setCentralWidget(self.centralwidget)
and to the output
def eqpt_activateInput(self,item,col):
print "Qtree ok! pressed"
print item.text(col)
Hope this may help others too.
ThreaderSlash "at" gmail "dot" com
|
QtPython Qtreewidget Problem
|
I trying to do a Qtreewidget to attend a customer design suggestion. I am coding it on QtPython. I did a first try using Qt Designer, then generated the code. But when I try to run it, an error comes out:
self.centralwidget.setSortingEnabled(__sortingEnabled)
AttributeError: setSortingEnabled
I googled around, but didn't find any solution for this problem, except some suggestion just to simply delete the lines in the code that results in the compiling error. But it didn't really help, because if you do so, it triggers more error, just like that:
self.treeWidget.topLevelItem(0).child(1).setText(0, QtGui.QApplication.translate("MainWindow", "Item Name", None, QtGui.QApplication.UnicodeUTF8))
AttributeError: 'NoneType' object has no attribute 'setText'
Here is my current code to generate a nice simple QtreeWidget/View:
#//==========================//#
def color_setupUi(self, MainWindow,phrase):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.eqpt_centralwdg(MainWindow)
self.eqpt_retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
#//==========================//#
def eqpt_centralwdg(self,MainWindow):
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.colorTreeWidget = QtGui.QTreeWidget(self.centralwidget)
self.colorTreeWidget.setGeometry(QtCore.QRect(60, 60, 191, 141))
self.colorTreeWidget.setObjectName("colorTreeWidget")
item = QtGui.QTreeWidgetItem(self.colorTreeWidget)
item = QtGui.QTreeWidgetItem(self.colorTreeWidget)
self.centralwidget.setSortingEnabled(__sortingEnabled)
MainWindow.setCentralWidget(self.centralwidget)
#//==========================//#
def eqpt_retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8)
self.colorTreeWidget.headerItem().setText(0, QtGui.QApplication.translate("MainWindow", "color", None, QtGui.QApplication.UnicodeUTF8)
__sortingEnabled = self.colorTreeWidget.isSortingEnabled()
self.colorTreeWidget.setSortingEnabled(False)
self.colorTreeWidget.topLevelItem(0).setText(0, QtGui.QApplication.translate("MainWindow", "Yellow", None, QtGui.QApplication.UnicodeUTF8)
self.colorTreeWidget.topLevelItem(1).setText(0, QtGui.QApplication.translate("MainWindow", "Blue", None, QtGui.QApplication.UnicodeUTF8)
self.colorTreeWidget.setSortingEnabled(__sortingEnabled)
#//==========================//#
All other object I needed to implement on Qt using Designer and a little bit of code has worked fine so far, e.g. inputLine, comboBox, TabWidget. I just got stuck with this TreeWidget error.
Any hints or suggestion are highly appreciated and welcome.
|
[
"I'm assuming the code you posted is what you got when you ran your UI file through pyuic4. I found the PyQt UI compiler to be buggy sometimes. All you can do is fix the output manually and complain to the vendor.\nIn your case, the line\nself.centralwidget.setSortingEnabled(__sortingEnabled) \n\nshould read\nself.colorTreeWidget.setSortingEnabled(__sortingEnabled) \n\nI don't understand where the AttributeError: 'NoneType' object has no attribute 'setText' comes from. You're not referencing self.treeWidget.topLevelItem(0) in the code below.\nSince the UI doesn't seem too complex yet, it might be worth it to start again from scratch in the QT Designer. Try to avoid cutting and pasting controls, so as not to confuse the Designer / pyuic4. Good luck!\n",
"Here is the solution:\n\ndelete/comment only the following line:\nself.centralwidget.setSortingEnabled(__sortingEnabled)\n\nThen code:\ndef eqpt_centralwdg(self,MainWindow):\n self.centralwidget = QtGui.QWidget(MainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n\n self.colorTreeWidget = QtGui.QTreeWidget(self.centralwidget)\n self.colorTreeWidget.setGeometry(QtCore.QRect(60, 60, 191, 141))\n self.colorTreeWidget.setObjectName(\"colorTreeWidget\")\n\n item = QtGui.QTreeWidgetItem(self.colorTreeWidget)\n item = QtGui.QTreeWidgetItem(self.colorTreeWidget) \n\n self.connect(self.colorTreeWidget, QtCore.SIGNAL('itemClicked(QTreeWidgetItem*, int)'), self.eqpt_activateInput)\n\n MainWindow.setCentralWidget(self.centralwidget) \n\nand to the output\ndef eqpt_activateInput(self,item,col):\n print \"Qtree ok! pressed\"\n print item.text(col) \n\nHope this may help others too. \nThreaderSlash \"at\" gmail \"dot\" com\n"
] |
[
2,
0
] |
[] |
[] |
[
"pyqt",
"pyqt4",
"python",
"qt",
"qt4"
] |
stackoverflow_0001745661_pyqt_pyqt4_python_qt_qt4.txt
|
Q:
python csv headers
I have a set of csv headers that I am trying to match with uploads. It's not really working. Not all headers are required -- I just have to match what's in the file.
reader = csv.DictReader(open(PathFile))
headers = reader.fieldnames
for header in sorted(set(headers)):
if (header == 'ip') or (header == 'IP'):
print "IP found in Header"
In this case, IP is not found.
for row in reader:
if row.get('IP'):
print "IP found in Row"
It's not found again. I did search on this site -- there was:
IP = row.get('IP', None)
That did not work either.
This is the file I'm using for testing:
Email, IP, Name, City, State, zip, country, garbage
ghfddgf@gfgs.com, 34.4.34.34,Mr GH, chicago, il ,60601, us,erw ewr
5t4g@fdsf.com, 34.45.23.34, Mr 5t,NY,NY,10101, us, er
A:
Based on your edit, you need to skip the initial space after the comma.
This should do it:
>>> reader = csv.DictReader(open(PathFile),skipinitialspace=True)
A:
I am not exactly sure what you want to achieve but if you simply want to know if some columns is in CSV, and you are sure that all rows have same columns, and you want to use dict reader use this
s="""col1,col2,col3
ok,ok,ok
hmm,hmm,hmm
cool,cool,cool"""
import csv
reader = csv.DictReader(s.split("\n"))
print reader.fieldnames
for row in reader:
for colName in ['col3', 'col4']:
print "found %s %s"%(colName, colName in row)
break
It outputs
found col3 True
found col4 False
or something like this will work too
reader = csv.reader(s.split("\n"))
columns = reader.next()
for colName in ['col3', 'col4']:
print "found %s %s"%(colName, colName in columns)
|
python csv headers
|
I have a set of csv headers that I am trying to match with uploads. It's not really working. Not all headers are required -- I just have to match what's in the file.
reader = csv.DictReader(open(PathFile))
headers = reader.fieldnames
for header in sorted(set(headers)):
if (header == 'ip') or (header == 'IP'):
print "IP found in Header"
In this case, IP is not found.
for row in reader:
if row.get('IP'):
print "IP found in Row"
It's not found again. I did search on this site -- there was:
IP = row.get('IP', None)
That did not work either.
This is the file I'm using for testing:
Email, IP, Name, City, State, zip, country, garbage
ghfddgf@gfgs.com, 34.4.34.34,Mr GH, chicago, il ,60601, us,erw ewr
5t4g@fdsf.com, 34.45.23.34, Mr 5t,NY,NY,10101, us, er
|
[
"Based on your edit, you need to skip the initial space after the comma.\nThis should do it:\n>>> reader = csv.DictReader(open(PathFile),skipinitialspace=True)\n\n",
"I am not exactly sure what you want to achieve but if you simply want to know if some columns is in CSV, and you are sure that all rows have same columns, and you want to use dict reader use this\ns=\"\"\"col1,col2,col3\nok,ok,ok\nhmm,hmm,hmm\ncool,cool,cool\"\"\"\n\nimport csv\n\nreader = csv.DictReader(s.split(\"\\n\"))\nprint reader.fieldnames\nfor row in reader:\n for colName in ['col3', 'col4']:\n print \"found %s %s\"%(colName, colName in row)\n break\n\nIt outputs\nfound col3 True\nfound col4 False\n\nor something like this will work too\nreader = csv.reader(s.split(\"\\n\"))\ncolumns = reader.next()\nfor colName in ['col3', 'col4']:\n print \"found %s %s\"%(colName, colName in columns)\n\n"
] |
[
12,
9
] |
[] |
[] |
[
"csv",
"python"
] |
stackoverflow_0001746489_csv_python.txt
|
Q:
Minimal Python Installation
Various software installations on my laptop each require their own particular version of Python. ViewVC requires Python 2.5 and Blender requires Python 2.6. Mercurial (thankfully) comes with its Python interpreter packaged in a DLL in the Mercurial installation itself.
How do I get by without having to install the entire Python environment each time? Is there some minimal installer which will install the bare minimum without affecting other programs? Can I modify the Blender and ViewVC installations so that they too use their own Python-in-a-DLL?
A:
It's hard to know which "bare minimum" the Blender scripts you'll want to use in the future may be counting on (short of the full Python standard library, which isn't all that large in term of disk space after all). Why not install both Python 2.5 and 2.6? They can coexist nicely (if your scriptable apps use hashbangs like #!/usr/bin/env python instead of specifically mentioning python2.5 or python2.6, you may need to trick out their PATHs just a little bit).
A:
You should be able to get away with installing the Python binaries in the same tree as the specific application I believe (Totally untested hunch though).
|
Minimal Python Installation
|
Various software installations on my laptop each require their own particular version of Python. ViewVC requires Python 2.5 and Blender requires Python 2.6. Mercurial (thankfully) comes with its Python interpreter packaged in a DLL in the Mercurial installation itself.
How do I get by without having to install the entire Python environment each time? Is there some minimal installer which will install the bare minimum without affecting other programs? Can I modify the Blender and ViewVC installations so that they too use their own Python-in-a-DLL?
|
[
"It's hard to know which \"bare minimum\" the Blender scripts you'll want to use in the future may be counting on (short of the full Python standard library, which isn't all that large in term of disk space after all). Why not install both Python 2.5 and 2.6? They can coexist nicely (if your scriptable apps use hashbangs like #!/usr/bin/env python instead of specifically mentioning python2.5 or python2.6, you may need to trick out their PATHs just a little bit).\n",
"You should be able to get away with installing the Python binaries in the same tree as the specific application I believe (Totally untested hunch though).\n"
] |
[
2,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001746818_python.txt
|
Q:
Finding the highest key
I'm just confused about why my code would not work, here's the question and the code I have so far (the test run says my answer is wrong).
Given the dictionary d, find the largest key in the dictionary and associate the corresponding value with the variable val_of_max. For example, given the dictionary {5:3, 4:1, 12:2}, 2 would be associated with val_of_max. Assume d is not empty.
d = {5:3, 4:1, 12:2, 14:9}
val_of_max = max(d.keys())
print val_of_max
A:
your code prints the key with the maximum value. What you want is:
d = {5:3, 4:1, 12:2, 14:9}
val_of_max = d[max(d.keys())]
print val_of_max
That is, you have to dereference the key to return the value.
A:
this will do:
>>> d = {5:3, 4:1, 12:2, 14:9}
>>> d[max(d)]
9
>>> max(d) # just in case you're looking for this
14
A:
Same code but remember to call the value of the key:
d = {5:3, 4:1, 12:2, 14:9}
val_of_max = max(d.keys())
print d[val_of_max]
A:
d= {5:3, 4:1, 12:2, 14:9}
To print the value associated with the largest key:
print max(d.iteritems())[1]
To print the key associated with the largest value:
import operator
print max(d.iteritems(), key=operator.itemgetter(1))[0]
|
Finding the highest key
|
I'm just confused about why my code would not work, here's the question and the code I have so far (the test run says my answer is wrong).
Given the dictionary d, find the largest key in the dictionary and associate the corresponding value with the variable val_of_max. For example, given the dictionary {5:3, 4:1, 12:2}, 2 would be associated with val_of_max. Assume d is not empty.
d = {5:3, 4:1, 12:2, 14:9}
val_of_max = max(d.keys())
print val_of_max
|
[
"your code prints the key with the maximum value. What you want is:\nd = {5:3, 4:1, 12:2, 14:9}\nval_of_max = d[max(d.keys())]\nprint val_of_max\n\nThat is, you have to dereference the key to return the value.\n",
"this will do:\n>>> d = {5:3, 4:1, 12:2, 14:9}\n>>> d[max(d)]\n9\n>>> max(d) # just in case you're looking for this\n14\n\n",
"Same code but remember to call the value of the key:\nd = {5:3, 4:1, 12:2, 14:9}\nval_of_max = max(d.keys())\nprint d[val_of_max]\n\n",
"d= {5:3, 4:1, 12:2, 14:9}\n\nTo print the value associated with the largest key:\nprint max(d.iteritems())[1]\n\nTo print the key associated with the largest value:\nimport operator\nprint max(d.iteritems(), key=operator.itemgetter(1))[0]\n\n"
] |
[
12,
5,
1,
0
] |
[] |
[] |
[
"dictionary",
"python"
] |
stackoverflow_0001661621_dictionary_python.txt
|
Q:
Sum and Division example (Python)
>>> sum((1, 2, 3, 4, 5, 6, 7))
28
>>> 28/7
4.0
>>> sum((1,2,3,4,5,6,7,8,9,10,11,12,13,14))
105
>>> 105/7
15.0
>>>
How do I automate this sum and division using a loop maybe?
Edit: Maybe I wasn't clear - I want a loop to keep doing the sum (of multiples of 7, eg 1-7, 1-14, 1-21 etc..) until it reaches x (x is the user input)
Okay, figured it out:
def sum_and_div_of_multiples_of_7(x):
y = 7
while (y <= x):
mof7 = range(1,y)
print ('mof7 is', mof7)
total = sum(mof7)
print ('total =', total)
div = total/7
print ('div =', int(div), '\n')
y = y+7 # increase y
x = 70
sum_and_div_of_multiples_of_7(x)
A:
The direct answer:
def sum_to_number_divided_by_seven(i):
return sum(range(i+1)) / 7
The more efficient answer:
def sum_to_number_divided_by_seven(i):
return (i*(i+1))/14
A:
def sumdiv7(limit):
for i in range(limit):
result = sum(range(i*7)) / 7
print "For", i, ", sumdiv = ", result
Example:
>>> sumdiv7(4)
For 0 , sumdiv = 0
For 1 , sumdiv = 3
For 2 , sumdiv = 13
For 3 , sumdiv = 30
The trick is very simple, you want to sum multiples of 7,
To get the ith multiple of 7, it's just i*7
range is a python function to get a list of numbers from 0 to x
sum sums a list.
Just put these pieces together
A:
I'm not sure what you want, but maybe it is something like:
sum(range(x*7+1))/7
A:
My version:
def sum_of_nums_divided_by_7(num):
return reduce(lambda x, y: x+y, range(num)) / 7
A:
if i understand your problem correctly. You want to be able to accept user input - x, and then sum values 1-7 then devide by 7, if the qoutient is higher than x stop there, otherwise continue to sum up 1-14, devide by 7 and check that quotient - and continute in multiples of 7?
My easy sollution is
x = input('user input - enter your value here')
y = 0
i = 1
while(x > y):
q = sum(range(1, i*7+1))
y = q/7
print y
i+=1
print "userinput: %d" % (x)
print "iterations: %d" %(i)
print "end value: %d" %(y)
|
Sum and Division example (Python)
|
>>> sum((1, 2, 3, 4, 5, 6, 7))
28
>>> 28/7
4.0
>>> sum((1,2,3,4,5,6,7,8,9,10,11,12,13,14))
105
>>> 105/7
15.0
>>>
How do I automate this sum and division using a loop maybe?
Edit: Maybe I wasn't clear - I want a loop to keep doing the sum (of multiples of 7, eg 1-7, 1-14, 1-21 etc..) until it reaches x (x is the user input)
Okay, figured it out:
def sum_and_div_of_multiples_of_7(x):
y = 7
while (y <= x):
mof7 = range(1,y)
print ('mof7 is', mof7)
total = sum(mof7)
print ('total =', total)
div = total/7
print ('div =', int(div), '\n')
y = y+7 # increase y
x = 70
sum_and_div_of_multiples_of_7(x)
|
[
"The direct answer:\ndef sum_to_number_divided_by_seven(i):\n return sum(range(i+1)) / 7\n\nThe more efficient answer:\ndef sum_to_number_divided_by_seven(i):\n return (i*(i+1))/14\n\n",
"def sumdiv7(limit):\n for i in range(limit):\n result = sum(range(i*7)) / 7\n print \"For\", i, \", sumdiv = \", result\n\nExample:\n>>> sumdiv7(4)\nFor 0 , sumdiv = 0\nFor 1 , sumdiv = 3\nFor 2 , sumdiv = 13\nFor 3 , sumdiv = 30\n\nThe trick is very simple, you want to sum multiples of 7,\nTo get the ith multiple of 7, it's just i*7\nrange is a python function to get a list of numbers from 0 to x\nsum sums a list.\nJust put these pieces together\n",
"I'm not sure what you want, but maybe it is something like:\nsum(range(x*7+1))/7\n\n",
"My version: \ndef sum_of_nums_divided_by_7(num):\n return reduce(lambda x, y: x+y, range(num)) / 7\n\n",
"if i understand your problem correctly. You want to be able to accept user input - x, and then sum values 1-7 then devide by 7, if the qoutient is higher than x stop there, otherwise continue to sum up 1-14, devide by 7 and check that quotient - and continute in multiples of 7?\nMy easy sollution is\nx = input('user input - enter your value here')\ny = 0\ni = 1\nwhile(x > y):\n q = sum(range(1, i*7+1))\n y = q/7\n print y\n i+=1\n\nprint \"userinput: %d\" % (x)\nprint \"iterations: %d\" %(i)\nprint \"end value: %d\" %(y)\n\n"
] |
[
5,
1,
0,
0,
0
] |
[] |
[] |
[
"division",
"python",
"sum"
] |
stackoverflow_0001747130_division_python_sum.txt
|
Q:
python reduce error?
The following is my python code:
>>> item = 1
>>> a = []
>>> a.append((1,2,3))
>>> a.append((7,2,4))
>>> sums=reduce(lambda x:abs(item-x[1]),a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: <lambda>() takes exactly 1 argument (2 given)
>>>
How can I fix it?
Thanks!
A:
Your lambda takes only one argument, but reduce requires a function that takes two arguments. Make your lambda take two arguments.
Since you didn't say what you want this code to do, I'll just guess:
the_sum=reduce(lambda x,y:abs(y[1]-x[1]),a)
A:
Your problem itself is a bit unclear. Anyway, i have taken just assumption--
>>> a = []
>>> a.append((1,2,3))
>>> a.append((7,2,4))
>>> a
[(1, 2, 3), (7, 2, 4)] # list of tuples
I am assuming that you might be interested in getting the sum of all the elements in the list. If that is the problem then that could be solved in 2 steps
1) The first step should be to flatten the list.
2) And then add all the elements of the list.
>>> new_list = [y for x in a for y in x] # List comprehension used to flatten the list
[1, 2, 3, 7, 2, 4]
>>> sum(new_list)
19
One liner
>>> sum([y for x in a for y in x])
19
Another assumption, if your problem is to minus every element of tuple by item in the list then use this:
>>> [tuple(map(lambda y: abs(item - y), x)) for x in a]
[(0, 1, 2), (6, 1, 3)] # map function always returns a list so i have used tuple function to convert it into tuple.
If the problem is something else then please elaborate.
PS: Python List comprehension is far better and efficient than anything else.
A:
reduce expects the function it is given to accept 2 arguments. For every item in the iterable it will pass the function the current item, and the previous return value from the function. So, getting the sum of a list is reduce(lambda: x,y: x+y, l, 0)
If I understand correctly, to get the behavior you were trying to get, change the code to:
a_sum = reduce(lambda x,y: x + abs(item-y[1]), a, 0)
But I might be mistaken as to what you were trying to get.
Further information is in the reduce function's docstring.
|
python reduce error?
|
The following is my python code:
>>> item = 1
>>> a = []
>>> a.append((1,2,3))
>>> a.append((7,2,4))
>>> sums=reduce(lambda x:abs(item-x[1]),a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: <lambda>() takes exactly 1 argument (2 given)
>>>
How can I fix it?
Thanks!
|
[
"Your lambda takes only one argument, but reduce requires a function that takes two arguments. Make your lambda take two arguments.\nSince you didn't say what you want this code to do, I'll just guess:\nthe_sum=reduce(lambda x,y:abs(y[1]-x[1]),a)\n\n",
"Your problem itself is a bit unclear. Anyway, i have taken just assumption--\n>>> a = []\n>>> a.append((1,2,3))\n>>> a.append((7,2,4))\n>>> a\n[(1, 2, 3), (7, 2, 4)] # list of tuples\n\nI am assuming that you might be interested in getting the sum of all the elements in the list. If that is the problem then that could be solved in 2 steps\n1) The first step should be to flatten the list.\n2) And then add all the elements of the list.\n>>> new_list = [y for x in a for y in x] # List comprehension used to flatten the list\n[1, 2, 3, 7, 2, 4] \n>>> sum(new_list)\n19\n\nOne liner\n>>> sum([y for x in a for y in x])\n19\n\nAnother assumption, if your problem is to minus every element of tuple by item in the list then use this:\n>>> [tuple(map(lambda y: abs(item - y), x)) for x in a]\n[(0, 1, 2), (6, 1, 3)] # map function always returns a list so i have used tuple function to convert it into tuple.\n\nIf the problem is something else then please elaborate.\nPS: Python List comprehension is far better and efficient than anything else.\n",
"reduce expects the function it is given to accept 2 arguments. For every item in the iterable it will pass the function the current item, and the previous return value from the function. So, getting the sum of a list is reduce(lambda: x,y: x+y, l, 0)\nIf I understand correctly, to get the behavior you were trying to get, change the code to:\na_sum = reduce(lambda x,y: x + abs(item-y[1]), a, 0)\n\nBut I might be mistaken as to what you were trying to get. \nFurther information is in the reduce function's docstring.\n"
] |
[
8,
3,
2
] |
[] |
[] |
[
"arguments",
"lambda",
"python",
"reduce"
] |
stackoverflow_0001746999_arguments_lambda_python_reduce.txt
|
Q:
How to use doctest on a Client script?
I am playing with Google Calendar API, creating some useful function.
I another hand, I want to do it right puting some useful doctest and starting agile development.
How to write doctest since the result of each function is not really predictible (Depending of what is new on the server) :
>>> calendar = GoogleCalendar(user='blabla', password='blablabla')
>>> calendar.list()
login@trunat.fr's Calendar List
0. ...
...
If I don't want to leave the password in the source code, How do I do ?
How to write test for all the function of a class without writing each time the same thing to each function ?
>>> calendar = GoogleCalendar(user='blabla', password='blablabla')
>>> calendar.myFunction()
For each function of GoogleCalendar, I will have to create first the object ?
Thank you for your help
A:
If you do decide to test an external service, you can use a test fixture:
Write a make_test_server() function, which will return a new server connection to simplify your tests.
Make it a test fixture (dummy of the server) make_dummy_test_server() with predictable output.
Test it, and make sure that all cases (connection errors, empty set returned) have been thought of.
It depends on how exhaustive your tests should be. If you are getting a lot of bugs from that area of code, then you might need more tests. If your code works, it might not be worth sweating.
Are you also doing code reviews? Systems testing? Unit testing is great, but make sure that you don't get too myopic.
|
How to use doctest on a Client script?
|
I am playing with Google Calendar API, creating some useful function.
I another hand, I want to do it right puting some useful doctest and starting agile development.
How to write doctest since the result of each function is not really predictible (Depending of what is new on the server) :
>>> calendar = GoogleCalendar(user='blabla', password='blablabla')
>>> calendar.list()
login@trunat.fr's Calendar List
0. ...
...
If I don't want to leave the password in the source code, How do I do ?
How to write test for all the function of a class without writing each time the same thing to each function ?
>>> calendar = GoogleCalendar(user='blabla', password='blablabla')
>>> calendar.myFunction()
For each function of GoogleCalendar, I will have to create first the object ?
Thank you for your help
|
[
"If you do decide to test an external service, you can use a test fixture:\n\nWrite a make_test_server() function, which will return a new server connection to simplify your tests.\nMake it a test fixture (dummy of the server) make_dummy_test_server() with predictable output.\nTest it, and make sure that all cases (connection errors, empty set returned) have been thought of.\n\nIt depends on how exhaustive your tests should be. If you are getting a lot of bugs from that area of code, then you might need more tests. If your code works, it might not be worth sweating.\nAre you also doing code reviews? Systems testing? Unit testing is great, but make sure that you don't get too myopic.\n"
] |
[
1
] |
[] |
[] |
[
"doctest",
"google_api",
"password_protection",
"python"
] |
stackoverflow_0001747371_doctest_google_api_password_protection_python.txt
|
Q:
Is Java or Python better for writing a web-page-source-checking web service on Google App Engines?
I hope you all have a nice day.
I want to write a web service that would check some web page HTML code every 20 minutes and e-mail it to my mail box. Here I was given a suggestion to use Google App Engine for this task. Having briefly read through that site I learned that two languages could be used there: Java and Python.
Which one do you think would fit best for my task and, therefore, I would have to start learning? (I don't know either language).
A:
Both the languages and their App Engine implementations are pretty solid and mature. As a language, Python is faster to learn, but Java comes with richer tools such as Eclipse that may partly compensate. A lot depends on what other languages you have background in -- for example, coming from C#, Java would be simpler than for somebody coming from, say, C. For such a simple task, the issues of power of the two languages and additional libraries &c doesn't really come into play.
A:
I've tried both languages with GAE and here's my general feeling about the choice of language for it:
Python is generally simpler. So, if you're using bare GAE API, Python's one is simpler to learn and simpler to write a webapp in it.
Java is more compatible. Python's API is generally GAE-specific, while Java API resembles some standard Java technologies (servlets, JDO, deployment etc.)
So, Java is a good choice if you either have an experience with web development in Java or if you're going to use third-party libraries extensively. Otherwise, Python is better.
A:
For your particular task, I'd suggest Python, mostly because of the existence of Beautiful Soup, an excellent HTML parser that handles poorly formed documents.
|
Is Java or Python better for writing a web-page-source-checking web service on Google App Engines?
|
I hope you all have a nice day.
I want to write a web service that would check some web page HTML code every 20 minutes and e-mail it to my mail box. Here I was given a suggestion to use Google App Engine for this task. Having briefly read through that site I learned that two languages could be used there: Java and Python.
Which one do you think would fit best for my task and, therefore, I would have to start learning? (I don't know either language).
|
[
"Both the languages and their App Engine implementations are pretty solid and mature. As a language, Python is faster to learn, but Java comes with richer tools such as Eclipse that may partly compensate. A lot depends on what other languages you have background in -- for example, coming from C#, Java would be simpler than for somebody coming from, say, C. For such a simple task, the issues of power of the two languages and additional libraries &c doesn't really come into play.\n",
"I've tried both languages with GAE and here's my general feeling about the choice of language for it: \n\nPython is generally simpler. So, if you're using bare GAE API, Python's one is simpler to learn and simpler to write a webapp in it.\nJava is more compatible. Python's API is generally GAE-specific, while Java API resembles some standard Java technologies (servlets, JDO, deployment etc.)\n\nSo, Java is a good choice if you either have an experience with web development in Java or if you're going to use third-party libraries extensively. Otherwise, Python is better.\n",
"For your particular task, I'd suggest Python, mostly because of the existence of Beautiful Soup, an excellent HTML parser that handles poorly formed documents.\n"
] |
[
5,
3,
2
] |
[] |
[] |
[
"google_app_engine",
"html",
"java",
"python",
"web_services"
] |
stackoverflow_0001746867_google_app_engine_html_java_python_web_services.txt
|
Q:
How to define the help of the CLI program in the __doc__?
I would like to do something like this :
def main():
"""
Display Information about a Google Calendar
-u --user login Google Login
-p --pass password Google Password
-d --debug Set DEBUG = True
-h --help Display this help
"""
print(__doc__)
if __name__ == "__main__":
main()
But the answer is : None ... Why ?
A:
Because __doc__ is an attribute of the function, not a local variable. You need to refer to it as main.__doc__ like this:
def main():
"""Display Information about a Google Calendar
..."""
print(main.__doc__)
if __name__ == "__main__":
main()
A:
If the help that you want to print is "global", you might find it more logical to put it as the main documentation for your program:
#!/usr/bin/env python
"""
Display Information about a Google Calendar
...
"""
if __name__ == '__main__':
print __doc__
__doc__ is a global variable that contains the documentation string of your script.
|
How to define the help of the CLI program in the __doc__?
|
I would like to do something like this :
def main():
"""
Display Information about a Google Calendar
-u --user login Google Login
-p --pass password Google Password
-d --debug Set DEBUG = True
-h --help Display this help
"""
print(__doc__)
if __name__ == "__main__":
main()
But the answer is : None ... Why ?
|
[
"Because __doc__ is an attribute of the function, not a local variable. You need to refer to it as main.__doc__ like this:\ndef main():\n \"\"\"Display Information about a Google Calendar\n\n ...\"\"\"\n print(main.__doc__)\n\nif __name__ == \"__main__\":\n main()\n\n",
"If the help that you want to print is \"global\", you might find it more logical to put it as the main documentation for your program:\n#!/usr/bin/env python\n\"\"\"\nDisplay Information about a Google Calendar\n...\n\"\"\"\n\nif __name__ == '__main__':\n print __doc__\n\n__doc__ is a global variable that contains the documentation string of your script.\n"
] |
[
4,
2
] |
[] |
[] |
[
"command_line_interface",
"documentation_generation",
"python"
] |
stackoverflow_0001747261_command_line_interface_documentation_generation_python.txt
|
Q:
Weird Time Issue in Python
Problem with using times in Python.
Terminal > Python
>>> calendar.timegm(datetime.datetime.now().utctimetuple())
1258449380
This time indicates GMT: Tue, 17 Nov 2009 09:16:20 GMT
Eclipse via Django Server
>>> calendar.timegm(datetime.datetime.now().utctimetuple())
1258427784
This time indicates GMT: Tue, 17 Nov 2009 03:16:24 GMT
My current timezone is infact GMT and the time is 16 minutes past 9, which means the Terminal is correct, however the Eclipse/Django one is 6 hours off. I'm so confused. I thought they'd both be using the same version of Python? As far as I'm aware I only have 2.6.2 installed.
A:
Django is set to Chicago time. You to change it, edit (or add in) TIME_ZONE flag in settings.py.
If you are running on Windows, then Django might mess things up if you don't set it to your local zone - http://docs.djangoproject.com/en/dev/ref/settings/
A:
You can check if it's the same version of python by running python -c "import sys; print sys.path and inspecting the output to see if they are the same.
Otherwise - it might be related to your TZ environment variable, or other timezone setting. Perhaps Django sets a global timezone somewhere in the environment. . To check this you could try using utcnow() instead of now().utctimetuple. If these are the same then it is that each environment thinks it's in a different timezone.
A:
Bordering on silly, are these two running on the same machine? If not, are both machines using NTP to synchronise time?
|
Weird Time Issue in Python
|
Problem with using times in Python.
Terminal > Python
>>> calendar.timegm(datetime.datetime.now().utctimetuple())
1258449380
This time indicates GMT: Tue, 17 Nov 2009 09:16:20 GMT
Eclipse via Django Server
>>> calendar.timegm(datetime.datetime.now().utctimetuple())
1258427784
This time indicates GMT: Tue, 17 Nov 2009 03:16:24 GMT
My current timezone is infact GMT and the time is 16 minutes past 9, which means the Terminal is correct, however the Eclipse/Django one is 6 hours off. I'm so confused. I thought they'd both be using the same version of Python? As far as I'm aware I only have 2.6.2 installed.
|
[
"Django is set to Chicago time. You to change it, edit (or add in) TIME_ZONE flag in settings.py.\nIf you are running on Windows, then Django might mess things up if you don't set it to your local zone - http://docs.djangoproject.com/en/dev/ref/settings/\n",
"You can check if it's the same version of python by running python -c \"import sys; print sys.path and inspecting the output to see if they are the same.\nOtherwise - it might be related to your TZ environment variable, or other timezone setting. Perhaps Django sets a global timezone somewhere in the environment. . To check this you could try using utcnow() instead of now().utctimetuple. If these are the same then it is that each environment thinks it's in a different timezone. \n",
"Bordering on silly, are these two running on the same machine? If not, are both machines using NTP to synchronise time?\n"
] |
[
7,
2,
0
] |
[] |
[] |
[
"datetime",
"django",
"eclipse",
"python"
] |
stackoverflow_0001747559_datetime_django_eclipse_python.txt
|
Q:
Google Wave - Adding a participant to a Wave with the Python API
How do I add a participant to a Wave using the Python API given their email address?
A:
The method to add a participant given a user id (AddParticipant) to waves is in the waveapi.model.OpBasedWavelet subclass, rather than just waveapi.model.Wavelet. This user id is an email address. Look at this sample.
|
Google Wave - Adding a participant to a Wave with the Python API
|
How do I add a participant to a Wave using the Python API given their email address?
|
[
"The method to add a participant given a user id (AddParticipant) to waves is in the waveapi.model.OpBasedWavelet subclass, rather than just waveapi.model.Wavelet. This user id is an email address. Look at this sample.\n"
] |
[
0
] |
[] |
[] |
[
"google_wave",
"python"
] |
stackoverflow_0001747685_google_wave_python.txt
|
Q:
More efficient method for this calculation?
a = 218500000000
s = 6
f = 2
k = 49
d = k + f + s
r = a
i = 0
while (r >= d):
r = r - d
#print ('r = ',r)
i = i+1
#print ('i = ',i)
print (i)
I think it does what I expect it to, but its way too slow to calculate such a large number, I waited 5 mins for i to print (while python used 100% cpu to calculate..), but it didn't. Is there a more efficient way of rewriting this piece of code so I can see how many iterations (i) it takes to complete?
Many thanks
A:
You can use i = a/d. :D
A:
r = (a % d)
i = (a / d)
Use the modulo and division operators.
There is also a divmod function to calculate both together:
i, r = divmod(a,d)
A:
Isn't a division what you're looking for?
A:
try 3833333333.3333333333333333333333. AKA r / d.
A:
Looks like you are doing truncating division to me. That is, you want to find out how many times d goes into a without knowing the remainder.
a = 218500000000
s = 6
f = 2
k = 49
d = k + f + s
i = a // d
print (i)
|
More efficient method for this calculation?
|
a = 218500000000
s = 6
f = 2
k = 49
d = k + f + s
r = a
i = 0
while (r >= d):
r = r - d
#print ('r = ',r)
i = i+1
#print ('i = ',i)
print (i)
I think it does what I expect it to, but its way too slow to calculate such a large number, I waited 5 mins for i to print (while python used 100% cpu to calculate..), but it didn't. Is there a more efficient way of rewriting this piece of code so I can see how many iterations (i) it takes to complete?
Many thanks
|
[
"You can use i = a/d. :D\n",
"r = (a % d)\ni = (a / d)\n\nUse the modulo and division operators.\nThere is also a divmod function to calculate both together:\ni, r = divmod(a,d)\n\n",
"Isn't a division what you're looking for?\n",
"try 3833333333.3333333333333333333333. AKA r / d.\n",
"Looks like you are doing truncating division to me. That is, you want to find out how many times d goes into a without knowing the remainder.\na = 218500000000\ns = 6\nf = 2\nk = 49\nd = k + f + s\n\ni = a // d\n\nprint (i)\n\n"
] |
[
4,
4,
2,
0,
0
] |
[] |
[] |
[
"iteration",
"largenumber",
"long_integer",
"python"
] |
stackoverflow_0001747713_iteration_largenumber_long_integer_python.txt
|
Q:
Scheduling Filter on Database with Time Interval
Let's you have a science experiment called Weather and it records general information about the weather, one of which is recording the humidity every minute. After say 10 hours, you'll have 600 database values stored.
Weather.objects.filter().exclude(time__lt = commence).exclude(time__gt = cease)
This would create a filter for the Weather table, between the commence and cease times.
Let's say the time criteria is equal to -4 hours from present, therefore it would return the last 4 hours worth of data which is equal to 300 values. How would I ask for an interval of 10? Meaning, from these 300 values, how would I receive the 10th one of each, so 10, 20, 30, 40 ... 280, 290, 300... which would mean 30 values are being returned from the filter.
EDIT:
Would it be possible to ask for an interval of say 10 seconds? As opposed to each individual 10th value..
A:
SQL doesn't have a way to ask for every tenth, so ORMs won't typically give you a way to express that need. You could do that work in Python:
samples = list(Weather.objects.filter().exclude(time__lt=commence).exclude(time__gt=cease))
for s10 in samples[::10]:
# do something with every tenth...
This will pull all the samples from the database in one query, then only use 10% of them. You could also pull only the ones you need, one to a query:
sample_count = 600 # Somehow determine how many samples are in your time window.
samples = Weather.objects.filter().exclude(time__lt=commence).exclude(time__gt=cease)
for s_num in range(0, sample_count, 10):
s = samples[s_num]
# Now you have one sample in s.
To elaborate: range takes three arguments, start, stop, and step. For example:
>>> range(0, 100, 10)
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
In the second example, the range expression is used to create the index values of the samples we want. Then samples[s_num] evaluates the QuerySet to get just that one value from the database.
|
Scheduling Filter on Database with Time Interval
|
Let's you have a science experiment called Weather and it records general information about the weather, one of which is recording the humidity every minute. After say 10 hours, you'll have 600 database values stored.
Weather.objects.filter().exclude(time__lt = commence).exclude(time__gt = cease)
This would create a filter for the Weather table, between the commence and cease times.
Let's say the time criteria is equal to -4 hours from present, therefore it would return the last 4 hours worth of data which is equal to 300 values. How would I ask for an interval of 10? Meaning, from these 300 values, how would I receive the 10th one of each, so 10, 20, 30, 40 ... 280, 290, 300... which would mean 30 values are being returned from the filter.
EDIT:
Would it be possible to ask for an interval of say 10 seconds? As opposed to each individual 10th value..
|
[
"SQL doesn't have a way to ask for every tenth, so ORMs won't typically give you a way to express that need. You could do that work in Python:\nsamples = list(Weather.objects.filter().exclude(time__lt=commence).exclude(time__gt=cease))\nfor s10 in samples[::10]:\n # do something with every tenth...\n\nThis will pull all the samples from the database in one query, then only use 10% of them. You could also pull only the ones you need, one to a query:\nsample_count = 600 # Somehow determine how many samples are in your time window.\nsamples = Weather.objects.filter().exclude(time__lt=commence).exclude(time__gt=cease)\nfor s_num in range(0, sample_count, 10):\n s = samples[s_num]\n # Now you have one sample in s.\n\nTo elaborate: range takes three arguments, start, stop, and step. For example:\n>>> range(0, 100, 10)\n[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]\n\nIn the second example, the range expression is used to create the index values of the samples we want. Then samples[s_num] evaluates the QuerySet to get just that one value from the database.\n"
] |
[
2
] |
[] |
[] |
[
"django",
"filter",
"python"
] |
stackoverflow_0001748130_django_filter_python.txt
|
Q:
Is there a speed difference between WSGI and FCGI?
From the web I've gleaned that WSGI is a CGI for python web development/frameworks. FCGI seems to be a more generalised gateway for a variety of languages. Don't know the performance difference between the two in reference to the languages python and C/++.
A:
Correct, WSGI is a Python programmatic API definition and FASTCGI is a language agnostic socket wire protocol definition. Effectively they are at different layers with WSGI being a higher layer. In other words, one can implement WSGI on top of something that so happened to use FASTCGI to communicate with a web server, but not the other way around.
In general, FASTCGI being a socket wire protocol means that you always need some type of programmatic interface on top to use it. For Python one such option is WSGI. As FASTCGI is just a means to an end, one can't really compare its performance to WSGI in that case because WSGI isn't a comparable socket wire protocol, but a user of FASTCGI itself.
One could try and compare performance of different language interfaces on top of FASTCGI, but in general that is quite meaningless in itself as the lower network layer and server request handling aren't the bottleneck. Instead your application code and database will be.
A:
They are two different things. WSGI is a Python specific interface for writing web applications. There are wrappers for about any web server protocol to provide the WSGI interface. FastCGI (FCGI) is one of such web server protocols. So, WSGI is an abstraction layer, while CGI / FastCGI / mod_python are how the actual web servers talk to the application. Some code has to translate the native interface to WSGI (there is a CGI module in wsgiref, there is flup for FastCGI, etc.). There is also mod_wsgi for Apache, which does the translation directly in an Apache module, so you don't need any Python wrapper.
|
Is there a speed difference between WSGI and FCGI?
|
From the web I've gleaned that WSGI is a CGI for python web development/frameworks. FCGI seems to be a more generalised gateway for a variety of languages. Don't know the performance difference between the two in reference to the languages python and C/++.
|
[
"Correct, WSGI is a Python programmatic API definition and FASTCGI is a language agnostic socket wire protocol definition. Effectively they are at different layers with WSGI being a higher layer. In other words, one can implement WSGI on top of something that so happened to use FASTCGI to communicate with a web server, but not the other way around.\nIn general, FASTCGI being a socket wire protocol means that you always need some type of programmatic interface on top to use it. For Python one such option is WSGI. As FASTCGI is just a means to an end, one can't really compare its performance to WSGI in that case because WSGI isn't a comparable socket wire protocol, but a user of FASTCGI itself.\nOne could try and compare performance of different language interfaces on top of FASTCGI, but in general that is quite meaningless in itself as the lower network layer and server request handling aren't the bottleneck. Instead your application code and database will be.\n",
"They are two different things. WSGI is a Python specific interface for writing web applications. There are wrappers for about any web server protocol to provide the WSGI interface. FastCGI (FCGI) is one of such web server protocols. So, WSGI is an abstraction layer, while CGI / FastCGI / mod_python are how the actual web servers talk to the application. Some code has to translate the native interface to WSGI (there is a CGI module in wsgiref, there is flup for FastCGI, etc.). There is also mod_wsgi for Apache, which does the translation directly in an Apache module, so you don't need any Python wrapper.\n"
] |
[
81,
29
] |
[] |
[] |
[
"fastcgi",
"python",
"wsgi"
] |
stackoverflow_0001747266_fastcgi_python_wsgi.txt
|
Q:
Multiprocessing Pool inside Process time out
When ever I use the following code the pool result always returns a timeout, is there something logically incorrect I am doing?
from multiprocessing import Pool, Process, cpu_count
def add(num):
return num+1
def add_wrap(num):
new_num = ppool.apply_async(add, [num])
print new_num.get(timeout=3)
ppool = Pool(processes=cpu_count() )
test = Process(target=add_wrap, args=(5,)).start()
I'm aware of this bug, and would have thought that it would have been fixed in python 2.6.4?
A:
You can't pass Pool objects between processes.
If you try this code, Python will raise a exception : 'NotImplementedError: pool objects cannot be passed between processes or pickled'.
from multiprocessing import Queue, Pool
q = Queue()
ppool = Pool(processes=2)
q.put([ppool])
ppool = q.get()
So if you want your code to work, just create your Pool object in the add_wrap method.
from multiprocessing import Pool, Process, cpu_count
def add(num):
return num+1
def add_wrap(num):
ppool = Pool(processes=cpu_count() )
new_num = ppool.apply_async(add, [num])
print new_num.get(timeout=3)
test = Process(target=add_wrap, args=(5,)).start()
|
Multiprocessing Pool inside Process time out
|
When ever I use the following code the pool result always returns a timeout, is there something logically incorrect I am doing?
from multiprocessing import Pool, Process, cpu_count
def add(num):
return num+1
def add_wrap(num):
new_num = ppool.apply_async(add, [num])
print new_num.get(timeout=3)
ppool = Pool(processes=cpu_count() )
test = Process(target=add_wrap, args=(5,)).start()
I'm aware of this bug, and would have thought that it would have been fixed in python 2.6.4?
|
[
"You can't pass Pool objects between processes.\nIf you try this code, Python will raise a exception : 'NotImplementedError: pool objects cannot be passed between processes or pickled'.\nfrom multiprocessing import Queue, Pool\n\nq = Queue()\nppool = Pool(processes=2) \nq.put([ppool])\nppool = q.get()\n\nSo if you want your code to work, just create your Pool object in the add_wrap method.\nfrom multiprocessing import Pool, Process, cpu_count\n\ndef add(num):\n return num+1\n\ndef add_wrap(num):\n ppool = Pool(processes=cpu_count() )\n new_num = ppool.apply_async(add, [num])\n print new_num.get(timeout=3)\n\ntest = Process(target=add_wrap, args=(5,)).start()\n\n"
] |
[
2
] |
[] |
[] |
[
"multiprocessing",
"pool",
"process",
"python",
"timeout"
] |
stackoverflow_0001747963_multiprocessing_pool_process_python_timeout.txt
|
Q:
Automating old DOS application using Python
Is there a way to automate an old DOS application (16-bit, probably needs an emulator such as DOSBox) from Python (on Windows)? I would like to send keys and strings to the application, detect updates to the DOS "screen" and get the application output.
It would be even better if the DOS application could run "hidden", i.e., not showing in the taskbar.
Note: It is not a game, it is one of those old application where you are given menus with press 1 for something, press 2 for something else, etc... then it asks for some input numbers, and then it shows some results. It is a pure console application.
Note2: It doesn't need to use DOSBox necessarily... could be done with other emulators such as Bochs
A:
I'm not familiar with DosBOX or whether it has an external API. However, for Sun VirtualBox there is a python API, so if it is OK to run DOS on a VM, you could easily use the VirtualBox Python API to control & automate the application you run on the DOS.
You can download the VirtualBox SDK here
|
Automating old DOS application using Python
|
Is there a way to automate an old DOS application (16-bit, probably needs an emulator such as DOSBox) from Python (on Windows)? I would like to send keys and strings to the application, detect updates to the DOS "screen" and get the application output.
It would be even better if the DOS application could run "hidden", i.e., not showing in the taskbar.
Note: It is not a game, it is one of those old application where you are given menus with press 1 for something, press 2 for something else, etc... then it asks for some input numbers, and then it shows some results. It is a pure console application.
Note2: It doesn't need to use DOSBox necessarily... could be done with other emulators such as Bochs
|
[
"I'm not familiar with DosBOX or whether it has an external API. However, for Sun VirtualBox there is a python API, so if it is OK to run DOS on a VM, you could easily use the VirtualBox Python API to control & automate the application you run on the DOS.\nYou can download the VirtualBox SDK here\n"
] |
[
1
] |
[] |
[] |
[
"automation",
"dos",
"dosbox",
"python",
"sendkeys"
] |
stackoverflow_0001744796_automation_dos_dosbox_python_sendkeys.txt
|
Q:
How do you write a program that interacts with others like banlist for warcraft 3?
As in title, what is banlist written in, or can be written in? I have a basic knowledge of Python but I don't see a way to get information from a running program.
A:
To my knowledge, banlist uses winpcap, an open source library for packet capture and network analysis for the Win32 platforms and "understands" (at least partially) the network traffic between the game running on your computer and Battle.net servers. Regarding Battle.net protocol, there is unofficial documentation available, e.g. bnetdocs, and maybe at others places (there was even an open source implementation of a bnet server, bnetd). To reverse engineer the protocol, people used things like whireshark (or the command line version tcpdump). The principle is simple: do something (e.g. move a unit) and analyze the transmitted information.
|
How do you write a program that interacts with others like banlist for warcraft 3?
|
As in title, what is banlist written in, or can be written in? I have a basic knowledge of Python but I don't see a way to get information from a running program.
|
[
"To my knowledge, banlist uses winpcap, an open source library for packet capture and network analysis for the Win32 platforms and \"understands\" (at least partially) the network traffic between the game running on your computer and Battle.net servers. Regarding Battle.net protocol, there is unofficial documentation available, e.g. bnetdocs, and maybe at others places (there was even an open source implementation of a bnet server, bnetd). To reverse engineer the protocol, people used things like whireshark (or the command line version tcpdump). The principle is simple: do something (e.g. move a unit) and analyze the transmitted information.\n"
] |
[
3
] |
[] |
[] |
[
"api",
"python",
"security"
] |
stackoverflow_0001706158_api_python_security.txt
|
Q:
How make Qt Designers autosize layouts work with Pyqt4?
I'm trying a simple example with Qt Designer and Pyqt4, when I preview the UI in Qt Designer (control+R) it looks good, but when I try to execute the generated UI code, layouts don't work properly and instead of autosizing widgets to the max they are so small that they can't be used.
If I use fixed sizes it works well.
The code used to load the window is:
import sys
from PyQt4 import QtCore, QtGui
from table import Ui_table
class Main(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.ui = Ui_table()
self.ui.setupUi(self)
def main():
app = QtGui.QApplication(sys.argv)
window=Main()
window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
And the Qt Designer xml file to generate the ui code with a simple widget maximized:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>table</class>
<widget class="QWidget" name="table">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>457</width>
<height>422</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QTreeWidget" name="list">
<column>
<property name="text">
<string>name</string>
</property>
</column>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>
Any suggestions?
OS: Windows XP
Python: Python 2.6.3
PyQt4: 4.6.1
A:
This is a long shot, but isn't the code using QMainWindow and the XML ui-descripting defines a QWidget. I'm not sure if that is the problem, but it does not look 100% correct to me.
|
How make Qt Designers autosize layouts work with Pyqt4?
|
I'm trying a simple example with Qt Designer and Pyqt4, when I preview the UI in Qt Designer (control+R) it looks good, but when I try to execute the generated UI code, layouts don't work properly and instead of autosizing widgets to the max they are so small that they can't be used.
If I use fixed sizes it works well.
The code used to load the window is:
import sys
from PyQt4 import QtCore, QtGui
from table import Ui_table
class Main(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.ui = Ui_table()
self.ui.setupUi(self)
def main():
app = QtGui.QApplication(sys.argv)
window=Main()
window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
And the Qt Designer xml file to generate the ui code with a simple widget maximized:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>table</class>
<widget class="QWidget" name="table">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>457</width>
<height>422</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QTreeWidget" name="list">
<column>
<property name="text">
<string>name</string>
</property>
</column>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>
Any suggestions?
OS: Windows XP
Python: Python 2.6.3
PyQt4: 4.6.1
|
[
"This is a long shot, but isn't the code using QMainWindow and the XML ui-descripting defines a QWidget. I'm not sure if that is the problem, but it does not look 100% correct to me.\n"
] |
[
0
] |
[] |
[] |
[
"designer",
"pyqt",
"pyqt4",
"python",
"qt"
] |
stackoverflow_0001747475_designer_pyqt_pyqt4_python_qt.txt
|
Q:
Unable to unpickle a file on Mac that was pickled on Windows
I've got a simple class that I am pickling(dumping) to a file. On OS X this works fine, and on Windows this works fine.
However, while on windows I can load/unpickle the object fine - when windows then pickles this file and saves it back to disk, it becomes unreadable on OS X (although in Windows it still behaves as normal).
The error I get back from OS X is that it is unable to import the require class.
I'm confused as this all works fine as long as I don't pickle anything in windows! (Even then it still works fine in Windows)
I've heard it could be line endings, my other thoughts are possibly something to do with the encoding type used being different across operating systems? But I really have no idea what to try to fully diagnose and/or solve this problem, so any help would be appreciated!
A:
Pickle with the newest protocol version and open the files in binary mode in all cases. That should solve the problem.
A:
It will be line endings - if you are using ASCII pickle open file in ascii mode 'r' or 'w' - if you are using a binary pickle open in binary mode 'rb' 'wb'. From the docstring:
The default
protocol is 0, to be backwards compatible. (Protocol 0 is the
only protocol that can be written to a file opened in text
mode and read back successfully. When using a protocol higher
than 0, make sure the file is opened in binary mode, both when
pickling and unpickling.)
|
Unable to unpickle a file on Mac that was pickled on Windows
|
I've got a simple class that I am pickling(dumping) to a file. On OS X this works fine, and on Windows this works fine.
However, while on windows I can load/unpickle the object fine - when windows then pickles this file and saves it back to disk, it becomes unreadable on OS X (although in Windows it still behaves as normal).
The error I get back from OS X is that it is unable to import the require class.
I'm confused as this all works fine as long as I don't pickle anything in windows! (Even then it still works fine in Windows)
I've heard it could be line endings, my other thoughts are possibly something to do with the encoding type used being different across operating systems? But I really have no idea what to try to fully diagnose and/or solve this problem, so any help would be appreciated!
|
[
"Pickle with the newest protocol version and open the files in binary mode in all cases. That should solve the problem.\n",
"It will be line endings - if you are using ASCII pickle open file in ascii mode 'r' or 'w' - if you are using a binary pickle open in binary mode 'rb' 'wb'. From the docstring:\n\nThe default\n protocol is 0, to be backwards compatible. (Protocol 0 is the\n only protocol that can be written to a file opened in text\n mode and read back successfully. When using a protocol higher\n than 0, make sure the file is opened in binary mode, both when\n pickling and unpickling.)\n\n"
] |
[
5,
3
] |
[] |
[] |
[
"macos",
"pickle",
"python",
"windows"
] |
stackoverflow_0001748958_macos_pickle_python_windows.txt
|
Q:
How to implement restful webservice with python/django
i try to setup a ubuntu server with web service that create by django/python , anyone have an resource/tutorial/example code
A:
There is also piston, which is a Django framework for creating RESTful APIs. It has a slight learning curve, but nicely fits into Django.
If you want something more lightweight, Simon Willison has very nice snippet that I have used previously that nicely models the HTTP methods:
class ArticleView(RestView):
def GET(request, article_id):
return render_to_response("article.html", {
'article': get_object_or_404(Article, pk = article_id),
})
def POST(request, article_id):
# Example logic only; should be using django.forms instead
article = get_object_or_404(Article, pk = article_id)
article.headline = request.POST['new_headline']
article.body = request.POST['new_body']
article.save()
return HttpResponseRedirect(request.path)
Jacob Kaplan-Moss has a nice article on Worst Practices in REST that can help guide you away from some common pitfalls.
A:
See the chapter on non-html content in the Django book.
|
How to implement restful webservice with python/django
|
i try to setup a ubuntu server with web service that create by django/python , anyone have an resource/tutorial/example code
|
[
"There is also piston, which is a Django framework for creating RESTful APIs. It has a slight learning curve, but nicely fits into Django. \nIf you want something more lightweight, Simon Willison has very nice snippet that I have used previously that nicely models the HTTP methods:\nclass ArticleView(RestView):\n\n def GET(request, article_id):\n return render_to_response(\"article.html\", {\n 'article': get_object_or_404(Article, pk = article_id),\n })\n\n def POST(request, article_id):\n # Example logic only; should be using django.forms instead\n article = get_object_or_404(Article, pk = article_id)\n article.headline = request.POST['new_headline']\n article.body = request.POST['new_body']\n article.save()\n return HttpResponseRedirect(request.path)\n\nJacob Kaplan-Moss has a nice article on Worst Practices in REST that can help guide you away from some common pitfalls.\n",
"See the chapter on non-html content in the Django book.\n"
] |
[
6,
1
] |
[] |
[] |
[
"django",
"python",
"web_services"
] |
stackoverflow_0001749005_django_python_web_services.txt
|
Q:
Naming Conventions for Methods / Classes / Packages
What naming conventions do you use for everyday code? I'm pondering this because I currently have a project in Python that contains 3 packages, each with a unique purpose. Now, I've been putting general-purpose, 'utility' methods into the first package I created for the project, however I'm contemplating moving these methods to a separate package. The question is what would I call it? Utility, Collection, Assorted?
Is there any standard naming conventions you swear by, and if so can you please provide links? I'm aware each language has it's own naming conventions, however is there any particular one that you find the most useful, that you'd recommend I'd start using?
A:
In general, you should follow the naming convention of the language you're using. It doesn't matter if you like or prefer the standards of another language. Consistency within the context of the language helps make your code more readable, maintainable, and usable by others. In Python, that means you use PEP 8.
Using a personal example:
In Python, I'd call the package "utils" -- or if I intended on redistribution, "coryutils" or something similar to avoid namespace collisions.
In Java or ActionScript, I'd call the package "net.petosky.utils", regardless of whether I intended on redistribution or not.
A:
Unless you have some good reason not to, you should follow the guidelines presented in PEP 8. See, in particular, "Prescriptive: Naming Conventions".
|
Naming Conventions for Methods / Classes / Packages
|
What naming conventions do you use for everyday code? I'm pondering this because I currently have a project in Python that contains 3 packages, each with a unique purpose. Now, I've been putting general-purpose, 'utility' methods into the first package I created for the project, however I'm contemplating moving these methods to a separate package. The question is what would I call it? Utility, Collection, Assorted?
Is there any standard naming conventions you swear by, and if so can you please provide links? I'm aware each language has it's own naming conventions, however is there any particular one that you find the most useful, that you'd recommend I'd start using?
|
[
"In general, you should follow the naming convention of the language you're using. It doesn't matter if you like or prefer the standards of another language. Consistency within the context of the language helps make your code more readable, maintainable, and usable by others. In Python, that means you use PEP 8.\nUsing a personal example:\nIn Python, I'd call the package \"utils\" -- or if I intended on redistribution, \"coryutils\" or something similar to avoid namespace collisions.\nIn Java or ActionScript, I'd call the package \"net.petosky.utils\", regardless of whether I intended on redistribution or not.\n",
"Unless you have some good reason not to, you should follow the guidelines presented in PEP 8. See, in particular, \"Prescriptive: Naming Conventions\".\n"
] |
[
1,
0
] |
[] |
[] |
[
"naming_conventions",
"python"
] |
stackoverflow_0001749232_naming_conventions_python.txt
|
Q:
How to detect whether two files are identical in Python
Is making system call to "md5sum file1" and "md5sum file2" and compare two return values enough in this case?
A:
If you want to do more than just detect if they differ, or don't trust the hashing solution, there are modules in the standard library called difflib and filecmp that doesn't rely on external programs.
A:
Well, that will tell you whether they're definitely different or probably the same. It's possible for two files to have the same hash but not actually have the same data... just very unlikely.
In your situation, what is the impact if you get a false positive (i.e. if you think they're the same, but they're not)? MD5 is probably good enough not to worry about collisions if they would only occur accidentally... but if you've got security (or money) at stake and someone could plant a "bad" file with the same hash as a "good" file, you shouldn't rely on it.
Personally, I'd probably just read both files, comparing each byte - for a one off comparison, both the hashing and this approach will require reading the whole file when they're equal; as Daniel points out in the comments, doing a byte-by-byte comparison lets you exit early as soon as you see a difference. Comparing the file sizes first is another quick optimization :)
The general advantage of hashing occurs when you store the hash of the existing file somewhere, so that next time you can just read the new file.
A:
A hash is useful if you are going to cache it (to compare many different files with each-other). If you just want to compare two files, it's a monstrous waste of cycles. After all - both files will be read in, and a lot of processing will be used on every bite.
If it's a 1:1 compare, just use:
import filecmp
filecmp.cmp(file_name_1,file_name_2)
On the other hand, a good hash is the only way to compare a large number of files with each-other.
SHA-1 and MD5 sort of broken - but not for normal files. A few researchers can generate 2 nonsense files that might clash, but it's unlikely that anyone can clobber an existing file.
git uses SHA-1 to compare text, so it's not a terrible choice.
The following will all work:
import hashlib
hash = hashlib.MD5(your_text_here).hexdigest() # safe*
hash = hashlib.SHA1(your_text_here).hexdigest() # safe*
hash = hashlib.SHA224(your_text_here).hexdigest() # safe
hash = hashlib.SHA512(your_text_here).hexdigest() # paranoid
# now put the hash in a dictionary (or database) for your many-to-many comparison.
# * Meaningful files will not be clobbered. Contrived files can be generated
# which might clash together, but it's difficult to do.
A:
Of course there is a simple test that you should do before comparing the file content at all - if the files are different sizes, then they can not possibly be the same.
Wouldn't it be more efficient to simply read each file and do a byte-by-byte comparison, avoiding the hashing algorithm altogether. This avoids the the (very unlikely) chance that two different files produce the same MD5 hash. Furthermore, you can bail out of the comparison when the first difference is detected, which for very different files will be very early in the comparison (possible on the first byte!)
A:
If you're on a system with md5sum, that's probably good enough.
You can do it with Python standard libraries -- checkout out hashlib.
A:
Depends if you feel comfortable with the probability of collision on the MD5 algorithm. Just note it is highly unlikely: so yes, go ahead.
A:
If there is nobody maliciously trying to create collisions, then you would have to compare about 264 files before you would expect to see a collision by random chance. However, it is possible for someone to carefully construct two files with the same MD5 sum due to cryptographic weaknesses in MD5. Whether the cryptographic weaknesses of MD5 matter or not depends on your application, where the files come from, and what an attacker could stand to gain if he tricked your program into thinking two different files were identical. MD5 is still a very good checksum, just not so great as a cryptographic hash.
|
How to detect whether two files are identical in Python
|
Is making system call to "md5sum file1" and "md5sum file2" and compare two return values enough in this case?
|
[
"If you want to do more than just detect if they differ, or don't trust the hashing solution, there are modules in the standard library called difflib and filecmp that doesn't rely on external programs.\n",
"Well, that will tell you whether they're definitely different or probably the same. It's possible for two files to have the same hash but not actually have the same data... just very unlikely.\nIn your situation, what is the impact if you get a false positive (i.e. if you think they're the same, but they're not)? MD5 is probably good enough not to worry about collisions if they would only occur accidentally... but if you've got security (or money) at stake and someone could plant a \"bad\" file with the same hash as a \"good\" file, you shouldn't rely on it.\nPersonally, I'd probably just read both files, comparing each byte - for a one off comparison, both the hashing and this approach will require reading the whole file when they're equal; as Daniel points out in the comments, doing a byte-by-byte comparison lets you exit early as soon as you see a difference. Comparing the file sizes first is another quick optimization :)\nThe general advantage of hashing occurs when you store the hash of the existing file somewhere, so that next time you can just read the new file.\n",
"A hash is useful if you are going to cache it (to compare many different files with each-other). If you just want to compare two files, it's a monstrous waste of cycles. After all - both files will be read in, and a lot of processing will be used on every bite.\nIf it's a 1:1 compare, just use:\nimport filecmp\nfilecmp.cmp(file_name_1,file_name_2)\n\nOn the other hand, a good hash is the only way to compare a large number of files with each-other.\nSHA-1 and MD5 sort of broken - but not for normal files. A few researchers can generate 2 nonsense files that might clash, but it's unlikely that anyone can clobber an existing file.\ngit uses SHA-1 to compare text, so it's not a terrible choice.\nThe following will all work: \nimport hashlib\nhash = hashlib.MD5(your_text_here).hexdigest() # safe*\nhash = hashlib.SHA1(your_text_here).hexdigest() # safe*\nhash = hashlib.SHA224(your_text_here).hexdigest() # safe\nhash = hashlib.SHA512(your_text_here).hexdigest() # paranoid\n\n# now put the hash in a dictionary (or database) for your many-to-many comparison.\n\n# * Meaningful files will not be clobbered. Contrived files can be generated\n# which might clash together, but it's difficult to do.\n\n",
"Of course there is a simple test that you should do before comparing the file content at all - if the files are different sizes, then they can not possibly be the same.\nWouldn't it be more efficient to simply read each file and do a byte-by-byte comparison, avoiding the hashing algorithm altogether. This avoids the the (very unlikely) chance that two different files produce the same MD5 hash. Furthermore, you can bail out of the comparison when the first difference is detected, which for very different files will be very early in the comparison (possible on the first byte!)\n",
"If you're on a system with md5sum, that's probably good enough.\nYou can do it with Python standard libraries -- checkout out hashlib.\n",
"Depends if you feel comfortable with the probability of collision on the MD5 algorithm. Just note it is highly unlikely: so yes, go ahead.\n",
"If there is nobody maliciously trying to create collisions, then you would have to compare about 264 files before you would expect to see a collision by random chance. However, it is possible for someone to carefully construct two files with the same MD5 sum due to cryptographic weaknesses in MD5. Whether the cryptographic weaknesses of MD5 matter or not depends on your application, where the files come from, and what an attacker could stand to gain if he tricked your program into thinking two different files were identical. MD5 is still a very good checksum, just not so great as a cryptographic hash. \n"
] |
[
15,
13,
13,
7,
3,
0,
0
] |
[
"yes, it is enough\n"
] |
[
-2
] |
[
"compare",
"file",
"md5",
"python"
] |
stackoverflow_0001748923_compare_file_md5_python.txt
|
Q:
Remove one char from a string
I'd like to remove one char from a string like this:
string = "ASDFVGHFJHRSFDZFDJKUYTRDSEADFDHDS"
print len(string)
(33)
So i would like to remove one random char in this string, and then have a len = 32
What's the best way to do so ?
EDIT: thanks for your answers, but i forgot something:
i'd like to print the char removed;
Using Anurag Uniyal technique ?
Thanks !
A:
>>> s="ASDFVGHFJHRSFDZFDJKUYTRDSEADFDHDS"
>>> r=random.randrange(len(string))
>>> print s[:r]+s[r+1:]
ASDFVGHJHRSFDZFDJKUYTRDSEADFDHDS
A:
>>> import random
>>> s = "ASDFVGHFJHRSFDZFDJKUYTRDSEADFDHDS"
>>> i = random.randint(0, len(s)-1)
>>> print s[:i] + s[i+1:]
ASDFVGHFJHRSFDZFDJKUYRDSEADFDHDS
>>> print s[i]
T
Basically get a random number from 0 to len-1 of string and remove the char at that index in string, you may convert string to list, del the item and re join but this will be faster and easier to read
A:
import random
index = random.randint(0, len(yourstring)-1)
yourstring = yourstring[:index] + yourstring[index+1:]
print yourstring[index]
|
Remove one char from a string
|
I'd like to remove one char from a string like this:
string = "ASDFVGHFJHRSFDZFDJKUYTRDSEADFDHDS"
print len(string)
(33)
So i would like to remove one random char in this string, and then have a len = 32
What's the best way to do so ?
EDIT: thanks for your answers, but i forgot something:
i'd like to print the char removed;
Using Anurag Uniyal technique ?
Thanks !
|
[
">>> s=\"ASDFVGHFJHRSFDZFDJKUYTRDSEADFDHDS\"\n>>> r=random.randrange(len(string))\n>>> print s[:r]+s[r+1:]\nASDFVGHJHRSFDZFDJKUYTRDSEADFDHDS\n\n",
">>> import random\n>>> s = \"ASDFVGHFJHRSFDZFDJKUYTRDSEADFDHDS\"\n>>> i = random.randint(0, len(s)-1)\n>>> print s[:i] + s[i+1:]\nASDFVGHFJHRSFDZFDJKUYRDSEADFDHDS\n>>> print s[i]\nT\n\nBasically get a random number from 0 to len-1 of string and remove the char at that index in string, you may convert string to list, del the item and re join but this will be faster and easier to read\n",
"import random\n\nindex = random.randint(0, len(yourstring)-1)\nyourstring = yourstring[:index] + yourstring[index+1:]\n\nprint yourstring[index]\n\n"
] |
[
7,
5,
3
] |
[] |
[] |
[
"python",
"string"
] |
stackoverflow_0001749283_python_string.txt
|
Q:
JavaScript equivalent of Python's __setitem__
var obj = {}
obj.__setitem__ = function(key, value){
this[key] = value * value
}
obj.x = 2 // 4
obj.y = 3 // 9
JavaScript doesn't have __setitem__ and this example obviously doesn't work.
In python __setitem__ works like:
class CustomDict(dict):
def __setitem__(self, key, value):
super(CustomDict, self).__setitem__(key, value * value)
d = CustomDict()
d['x'] = 2 # 4
d['y'] = 3 # 9
Is it possible to implement __setitem__ behavior in JavaScript? All tricky workarounds would be helpful.
A:
Is it possible to implement __setitem__ behavior in JavaScript?
No. There is no getter/setter for arbitrary properties in JavaScript.
In Firefox you can use JavaScript 1.5+'s getters and setters to define x and y properties that square their values on assignment, eg.:
var obj= {
_x: 0,
get x() { return this._x; },
set x(v) { this._x=v*v; }
};
obj.x= 4;
alert(obj.x);
but you would have to declare a setter for each named property you wanted to use in advance. And it won't work cross-browser.
A:
No, but there are plans for supporting a similar feature in JavaScript 2. The following object literal syntax has been suggested on Mozilla bug 312116 and it seems that it might be how it will be done for object literals:
({
get * (property) {
// handle property gets here
}
})
I'm assuming set would also be supported (as set * (property, value) {...}).
A:
you can do this (as objects in javascript are also associative arrays):
var obj = {};
obj._ = function(key, value){
this[key] = value * value;
}
obj._('x', 2); // 4
obj._('y', 3); // 9
alert(obj.x + "," + obj.y); //--> 4,9
A:
There are no true setters and getters in the commonly implemented Javascript versions, so if you want to emulate the effect you have to use some different syntax. For a property obj.x, using obj.x() to access the value of the property and obj.x(123) to set the value seems like a rather convenient syntax.
It can be implemented like this:
// Basic property class
function Property(value) {
this.setter(value);
}
Property.prototype.setter = function(value) {
this.value = value * value;
}
Property.prototype.getter = function() {
return this.value;
}
Property.prototype.access = function(value) {
if (value !== undefined)
this.setter(value);
return this.getter();
}
// generator function to add convenient access syntax
function make_property(value) {
var prop = new Property(value);
function propaccess(value) {
return prop.access(value);
}
return propaccess;
}
Now properties generated by make_property support the desired syntax and square values they are assigned:
var obj = {
x: make_property(2)
};
alert(obj.x()); // 4
obj.x(3); // set value
alert(obj.x()); // 9
A:
I don't think you can override the [] operator in the current version of JavaScript. In current JavaScript, objects are largely just associative arrays, so the [] operator just adds a key/value pair to an array that is the object.
You could write methods that set specific values or even squared a number and added the value as a key/value pair but not by overloading the [] operator.
JavaScript2 has some specifications for operator overloading, but that spec is MIA.
|
JavaScript equivalent of Python's __setitem__
|
var obj = {}
obj.__setitem__ = function(key, value){
this[key] = value * value
}
obj.x = 2 // 4
obj.y = 3 // 9
JavaScript doesn't have __setitem__ and this example obviously doesn't work.
In python __setitem__ works like:
class CustomDict(dict):
def __setitem__(self, key, value):
super(CustomDict, self).__setitem__(key, value * value)
d = CustomDict()
d['x'] = 2 # 4
d['y'] = 3 # 9
Is it possible to implement __setitem__ behavior in JavaScript? All tricky workarounds would be helpful.
|
[
"\nIs it possible to implement __setitem__ behavior in JavaScript? \n\nNo. There is no getter/setter for arbitrary properties in JavaScript.\nIn Firefox you can use JavaScript 1.5+'s getters and setters to define x and y properties that square their values on assignment, eg.:\nvar obj= {\n _x: 0,\n get x() { return this._x; },\n set x(v) { this._x=v*v; }\n};\nobj.x= 4;\nalert(obj.x);\n\nbut you would have to declare a setter for each named property you wanted to use in advance. And it won't work cross-browser.\n",
"No, but there are plans for supporting a similar feature in JavaScript 2. The following object literal syntax has been suggested on Mozilla bug 312116 and it seems that it might be how it will be done for object literals:\n({\n get * (property) {\n // handle property gets here\n }\n})\n\nI'm assuming set would also be supported (as set * (property, value) {...}).\n",
"you can do this (as objects in javascript are also associative arrays):\nvar obj = {};\nobj._ = function(key, value){\n this[key] = value * value;\n}\nobj._('x', 2); // 4\nobj._('y', 3); // 9\n\nalert(obj.x + \",\" + obj.y); //--> 4,9\n\n",
"There are no true setters and getters in the commonly implemented Javascript versions, so if you want to emulate the effect you have to use some different syntax. For a property obj.x, using obj.x() to access the value of the property and obj.x(123) to set the value seems like a rather convenient syntax.\nIt can be implemented like this:\n// Basic property class\nfunction Property(value) {\n this.setter(value);\n}\n\nProperty.prototype.setter = function(value) {\n this.value = value * value;\n}\n\nProperty.prototype.getter = function() {\n return this.value;\n}\n\nProperty.prototype.access = function(value) {\n if (value !== undefined)\n this.setter(value);\n return this.getter();\n}\n\n\n// generator function to add convenient access syntax\nfunction make_property(value) {\n var prop = new Property(value);\n function propaccess(value) {\n return prop.access(value);\n }\n return propaccess;\n}\n\nNow properties generated by make_property support the desired syntax and square values they are assigned:\nvar obj = {\n x: make_property(2)\n};\n\nalert(obj.x()); // 4\nobj.x(3); // set value\nalert(obj.x()); // 9\n\n",
"I don't think you can override the [] operator in the current version of JavaScript. In current JavaScript, objects are largely just associative arrays, so the [] operator just adds a key/value pair to an array that is the object.\nYou could write methods that set specific values or even squared a number and added the value as a key/value pair but not by overloading the [] operator.\nJavaScript2 has some specifications for operator overloading, but that spec is MIA.\n"
] |
[
10,
7,
5,
5,
1
] |
[] |
[] |
[
"javascript",
"python",
"syntactic_sugar"
] |
stackoverflow_0001712074_javascript_python_syntactic_sugar.txt
|
Q:
Cron in Google App Engine
I have made an app using Google App Engine in python of weekly Project and assessment report submitting.
I want to check that on Friday who have submitted the report and who don't just send the scheduled notification mail that he haven't submitted the report in last week.
but i don't want to send the notification mail on Monday who have submitted the report in last week, just to those who haven't submitted the report
so please suggest me some idea for that.
A:
Hard to fathom what you want (your English is very hard to parse), but anyway, besides Task Queues which are much more flexible and powerful (and may be harder to use for simple jobs that cron functionality covers perfectly), you can use cron to schedule App Engine tasks in Python by following the instructions here.
A:
Not sure what you want, but anything you can do with cron can be done via TaskQueues in GAE, so read this http://code.google.com/appengine/docs/python/taskqueue/
App Engine applications can perform background processing by inserting tasks (modeled as web hooks) into a queue. App Engine will detect the presence of new, ready-to-execute tasks and automatically dispatch them for execution, subject to scheduling criteria.
|
Cron in Google App Engine
|
I have made an app using Google App Engine in python of weekly Project and assessment report submitting.
I want to check that on Friday who have submitted the report and who don't just send the scheduled notification mail that he haven't submitted the report in last week.
but i don't want to send the notification mail on Monday who have submitted the report in last week, just to those who haven't submitted the report
so please suggest me some idea for that.
|
[
"Hard to fathom what you want (your English is very hard to parse), but anyway, besides Task Queues which are much more flexible and powerful (and may be harder to use for simple jobs that cron functionality covers perfectly), you can use cron to schedule App Engine tasks in Python by following the instructions here.\n",
"Not sure what you want, but anything you can do with cron can be done via TaskQueues in GAE, so read this http://code.google.com/appengine/docs/python/taskqueue/\nApp Engine applications can perform background processing by inserting tasks (modeled as web hooks) into a queue. App Engine will detect the presence of new, ready-to-execute tasks and automatically dispatch them for execution, subject to scheduling criteria.\n"
] |
[
2,
0
] |
[] |
[] |
[
"cron",
"google_app_engine",
"python"
] |
stackoverflow_0001748074_cron_google_app_engine_python.txt
|
Q:
Python, C: redirected stdout fires [Errno 9]
I try to log all the output of a program written in Python and C. However, printing from Python causes IOError: [Errno 9] Bad file descriptor
Please, does anyone know what the problem is and how to fix it?
PS: It's on Windows XP, Python 2.6 and MinGW GCC
#include <windows.h>
#include <fcntl.h>
#include "Python.h"
int main()
{
int fds[2];
_pipe(fds, 1024, O_BINARY);
_dup2(fds[1], 1);
setvbuf(stdout, NULL, _IONBF, 0);
/* alternative version: */
// HANDLE hReadPipe, hWritePipe;
// int fd;
// DWORD nr;
// CreatePipe(&hReadPipe, &hWritePipe, NULL, 0);
// fd = _open_osfhandle((intptr_t)hWritePipe, _O_BINARY);
// _dup2(fd, 1);
// setvbuf(stdout, NULL, _IONBF, 0);
write(1, "write\n", 6);
printf("printf\n");
Py_Initialize();
PyRun_SimpleString("print 'print'"); // this breaks
Py_Finalize();
char buffer[1024];
fprintf(stderr, "buffer size: %d\n", read(fds[0], buffer, 1024)); // should always be more than 0
/* alternative version: */
// CloseHandle(hWritePipe);
// char buffer[1024];
// ReadFile(hReadPipe, buffer, 1024, &nr, NULL);
// fprintf(stderr, "buffer size: %d\n", nr); // should always be more than 0
}
A:
I think it could be to do with different C runtimes. I know you can't pass file descriptors between different C runtimes - Python is built with MSVC (you will need to check which version) - so you could try to make MinGW build against the same C runtime - I think there is options to do this in MinGW like -lmsvcrt80 (or whichever is the appropriate versions) but for licensing reasons they can't distribute the libraries so you will have to find them on your system. Sorry I don't have any more details on that for now, but hopefully its a start for some googling.
A simpler way would be to just do it all in Python... just make a class which exposes a write and perhaps flush method and assign it to sys.stdout. Eg for a file you can just pass an open file object - it's probably straightfoward to do a similar thing for your pipe. Then just import it and sys and set sys.stdout in a PyRun_SimpleString.
|
Python, C: redirected stdout fires [Errno 9]
|
I try to log all the output of a program written in Python and C. However, printing from Python causes IOError: [Errno 9] Bad file descriptor
Please, does anyone know what the problem is and how to fix it?
PS: It's on Windows XP, Python 2.6 and MinGW GCC
#include <windows.h>
#include <fcntl.h>
#include "Python.h"
int main()
{
int fds[2];
_pipe(fds, 1024, O_BINARY);
_dup2(fds[1], 1);
setvbuf(stdout, NULL, _IONBF, 0);
/* alternative version: */
// HANDLE hReadPipe, hWritePipe;
// int fd;
// DWORD nr;
// CreatePipe(&hReadPipe, &hWritePipe, NULL, 0);
// fd = _open_osfhandle((intptr_t)hWritePipe, _O_BINARY);
// _dup2(fd, 1);
// setvbuf(stdout, NULL, _IONBF, 0);
write(1, "write\n", 6);
printf("printf\n");
Py_Initialize();
PyRun_SimpleString("print 'print'"); // this breaks
Py_Finalize();
char buffer[1024];
fprintf(stderr, "buffer size: %d\n", read(fds[0], buffer, 1024)); // should always be more than 0
/* alternative version: */
// CloseHandle(hWritePipe);
// char buffer[1024];
// ReadFile(hReadPipe, buffer, 1024, &nr, NULL);
// fprintf(stderr, "buffer size: %d\n", nr); // should always be more than 0
}
|
[
"I think it could be to do with different C runtimes. I know you can't pass file descriptors between different C runtimes - Python is built with MSVC (you will need to check which version) - so you could try to make MinGW build against the same C runtime - I think there is options to do this in MinGW like -lmsvcrt80 (or whichever is the appropriate versions) but for licensing reasons they can't distribute the libraries so you will have to find them on your system. Sorry I don't have any more details on that for now, but hopefully its a start for some googling.\nA simpler way would be to just do it all in Python... just make a class which exposes a write and perhaps flush method and assign it to sys.stdout. Eg for a file you can just pass an open file object - it's probably straightfoward to do a similar thing for your pipe. Then just import it and sys and set sys.stdout in a PyRun_SimpleString.\n"
] |
[
2
] |
[] |
[] |
[
"c",
"python",
"stdout",
"windows"
] |
stackoverflow_0001749762_c_python_stdout_windows.txt
|
Q:
Python - Create html page with hyperlinks from os.listdir
I have a script that creates a folder called "videos" on a USB drive, moves 6,500 WMV files over to the "videos" folder. Then it's suppose to create an HTML page with hyperlinks to each file. Here is my current example that's broken. I'm trying to have it crawl the videos directory and create an HTML page with hyperlinks only to the local files on the USB drive.
#!/usr/bin/python
import os.path
import os
import shutil
import re
# Create the videos directory in the current location
# If the directory exists ignore it
def createDirectory():
directory = "videos"
if not os.path.isdir("./" + directory + "/"):
os.mkdir("./" + directory + "/")
print "Videos Folder Created."
else:
print "Video Folder Exists."
print "---------------------"
# Move all the files in the root directory with the .wmv extension
# to the videos folder
def moveVideos():
for file in os.listdir("."):
if os.path.splitext(file)[1] == ".wmv":
print "Moving:", file
shutil.move(file, os.path.join("videos", file))
def createHTML():
videoDirectory = os.listdir("videos")
f = open("videos.html", "w")
f.writelines(videoDirectory)
r = re.compile(r"(\\[^ ]+)")
print r.sub(r'<a href="\1">\1</a>', videoDirectory)
createDirectory()
moveVideos()
createHTML()
A:
import cgi
def is_video_file(filename):
return filename.endswith(".wmv") # customize however you like
def createHTML():
videoDirectory = os.listdir("videos")
with open("videos.html", "w") as f:
f.write("<html><body><ul>\n")
for filename in videoDirectory:
if is_video_file(filename):
f.write('<li><a href="%s">%s</a></li>\n' %
(cgi.escape(filename, True), cgi.escape(filename)))
f.write("</ul></body></html>\n")
A:
Don't do f.writelines(videoDirectory) and then regex. Besides you're only printing to the console with that regex subsitution.
Do
videoDirectory = os.listdir("videos")
f = open("videos.html", "w")
f.write('<html><head></head><body><ul>'
f.writelines(['<li><a href="videos/%s">%s</a></li>' % (f, f) for f in videoDirectory])
f.write('</ul></body></html>')
A:
def createHTML():
h = open("videos.html", 'w')
for vid in os.listdir:
path = "./videos" + vid
f = open(path, r)
h.write("<a href='"+f.name+"'>"+f.name[f.name.rfind('\\') +1 :]+"</a>")
f.close()
h.close()
print "done writing HTML file"
|
Python - Create html page with hyperlinks from os.listdir
|
I have a script that creates a folder called "videos" on a USB drive, moves 6,500 WMV files over to the "videos" folder. Then it's suppose to create an HTML page with hyperlinks to each file. Here is my current example that's broken. I'm trying to have it crawl the videos directory and create an HTML page with hyperlinks only to the local files on the USB drive.
#!/usr/bin/python
import os.path
import os
import shutil
import re
# Create the videos directory in the current location
# If the directory exists ignore it
def createDirectory():
directory = "videos"
if not os.path.isdir("./" + directory + "/"):
os.mkdir("./" + directory + "/")
print "Videos Folder Created."
else:
print "Video Folder Exists."
print "---------------------"
# Move all the files in the root directory with the .wmv extension
# to the videos folder
def moveVideos():
for file in os.listdir("."):
if os.path.splitext(file)[1] == ".wmv":
print "Moving:", file
shutil.move(file, os.path.join("videos", file))
def createHTML():
videoDirectory = os.listdir("videos")
f = open("videos.html", "w")
f.writelines(videoDirectory)
r = re.compile(r"(\\[^ ]+)")
print r.sub(r'<a href="\1">\1</a>', videoDirectory)
createDirectory()
moveVideos()
createHTML()
|
[
"import cgi\n\ndef is_video_file(filename):\n return filename.endswith(\".wmv\") # customize however you like\n\ndef createHTML():\n videoDirectory = os.listdir(\"videos\")\n with open(\"videos.html\", \"w\") as f:\n f.write(\"<html><body><ul>\\n\")\n for filename in videoDirectory:\n if is_video_file(filename):\n f.write('<li><a href=\"%s\">%s</a></li>\\n' %\n (cgi.escape(filename, True), cgi.escape(filename)))\n f.write(\"</ul></body></html>\\n\")\n\n",
"Don't do f.writelines(videoDirectory) and then regex. Besides you're only printing to the console with that regex subsitution.\nDo \nvideoDirectory = os.listdir(\"videos\")\nf = open(\"videos.html\", \"w\")\nf.write('<html><head></head><body><ul>' \nf.writelines(['<li><a href=\"videos/%s\">%s</a></li>' % (f, f) for f in videoDirectory])\nf.write('</ul></body></html>')\n\n",
"def createHTML():\n h = open(\"videos.html\", 'w')\n for vid in os.listdir:\n path = \"./videos\" + vid\n f = open(path, r)\n h.write(\"<a href='\"+f.name+\"'>\"+f.name[f.name.rfind('\\\\') +1 :]+\"</a>\")\n f.close()\n h.close()\n print \"done writing HTML file\"\n\n"
] |
[
9,
1,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001749769_python.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.