title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Clojure equivalent to Python's lxml library?
1,569,223
<p>I'm looking for the Clojure/Java equivalent to Python's lxml library. </p> <p>I've used it a ton in the past for parsing all sorts of html (as a replacement for BeautifulSoup) and it's great to be able to use the same elementtree api for xml as well -- really a trusted friend! Can anyone recommend a similar Java/Clojure library?</p> <p>About lxml</p> <p>lxml is an xml and html processing library based off of libxml2. It handles broken html pages very well so it is excellent for screen scraping tasks. It also implements the ElementTree api, so the xml/html structure is represented as a tree object with full support for xpath and css selectors among other things. </p> <p>It also has some really handy utility functions such as the "cleaner" module which will strip out unwanted tags from the "soup" (ie script tags, style tags, etc...).</p> <p>So it is simple to use, robust, and VERY fast...!</p>
10
2009-10-14T21:51:49Z
1,572,391
<p>Enlive: <a href="http://github.com/cgrand/enlive">http://github.com/cgrand/enlive</a></p> <p>I've used it for screen-scraping and it works quite well for that. It uses a CSS selector like syntax for getting at elements in the document.</p>
7
2009-10-15T13:31:22Z
[ "java", "python", "clojure", "lxml" ]
"setup.py upload" is failing with "Upload failed (401): You must be identified to edit package information"
1,569,315
<p>When running..</p> <pre><code>python setup.py sdist register upload </code></pre> <p>..I get the following output:</p> <pre><code>running register We need to know who you are, so please choose either: 1. use your existing login, 2. register as a new user, 3. have the server generate a new password for you (and email it to you), or 4. quit Your selection [default 1]: 1 Username: example Password: ... Registering mypackage to http://pypi.python.org/pypi Server response (200): OK I can store your PyPI login so future submissions will be faster. (the login will be stored in /Users/dbr/.pypirc) Save your login (y/N)?y running upload Submitting dist/mypackage-1.2.1.tar.gz to http://pypi.python.org/pypi Upload failed (401): You must be identified to edit package information </code></pre> <p>It's prompting to save the login details, despite <code>~/.pypirc</code> already containing this. It then fails to upload files for a package I own, and have full write-access to.</p>
42
2009-10-14T22:15:41Z
1,569,331
<p>Just found <a href="http://www.davidcramer.net/code/python/443/problems-uploading-packages-with-setuptools-on-os-x.html">this page</a>, which solves the issue:</p> <blockquote> <p>I also noticed that while it was asking me to save my login information, and I hit Y everytime, it still asked me for the username and password. It turned out that it was saving the information incorrectly as follows:</p> <pre><code>[pypi] username:dcramer password:******* </code></pre> <p>Changing it out to this solved the problems:</p> <pre><code>[server-login] username:dcramer password:******** </code></pre> </blockquote> <p>The above content goes into the <a href="https://docs.python.org/3/distutils/packageindex.html#pypirc"><code>.pypirc</code> file</a> in the user's home directory.</p> <p>Ugh.. I think this may be a good time to give <a href="http://pypi.python.org/pypi/distribute">distribute</a> a try..</p>
61
2009-10-14T22:19:24Z
[ "python", "packaging", "setuptools" ]
"setup.py upload" is failing with "Upload failed (401): You must be identified to edit package information"
1,569,315
<p>When running..</p> <pre><code>python setup.py sdist register upload </code></pre> <p>..I get the following output:</p> <pre><code>running register We need to know who you are, so please choose either: 1. use your existing login, 2. register as a new user, 3. have the server generate a new password for you (and email it to you), or 4. quit Your selection [default 1]: 1 Username: example Password: ... Registering mypackage to http://pypi.python.org/pypi Server response (200): OK I can store your PyPI login so future submissions will be faster. (the login will be stored in /Users/dbr/.pypirc) Save your login (y/N)?y running upload Submitting dist/mypackage-1.2.1.tar.gz to http://pypi.python.org/pypi Upload failed (401): You must be identified to edit package information </code></pre> <p>It's prompting to save the login details, despite <code>~/.pypirc</code> already containing this. It then fails to upload files for a package I own, and have full write-access to.</p>
42
2009-10-14T22:15:41Z
27,559,197
<p>I have the same problem, This is my solution.</p> <p>The python version is 2.7.7, my windows version is Windows-7-6.1.7601-SP1.</p> <p>here is my .pypirc file</p> <pre><code>[distutils] index-servers=pypi [pypi] repository = https://pypi.python.org/pypi [server-login] username = user password = password </code></pre> <p><strong>Notice:</strong></p> <p>In windows, A file is not allowed named as “.pypirc”,plz,refer to:</p> <p><a href="http://serverfault.com/questions/22626/rename-files-to-empty-filename-in-windows-vista">Rename files to empty filename in Windows</a> </p> <p>Then put you ".pypirc" file in the same folder with "setup.py"</p> <p>At last:</p> <p>run : </p> <pre><code>python setup.py sdist upload </code></pre> <p>or:</p> <pre><code>python setup.py sdist register upload </code></pre> <p>I hope this will be help,thank you!</p>
4
2014-12-19T03:10:32Z
[ "python", "packaging", "setuptools" ]
"setup.py upload" is failing with "Upload failed (401): You must be identified to edit package information"
1,569,315
<p>When running..</p> <pre><code>python setup.py sdist register upload </code></pre> <p>..I get the following output:</p> <pre><code>running register We need to know who you are, so please choose either: 1. use your existing login, 2. register as a new user, 3. have the server generate a new password for you (and email it to you), or 4. quit Your selection [default 1]: 1 Username: example Password: ... Registering mypackage to http://pypi.python.org/pypi Server response (200): OK I can store your PyPI login so future submissions will be faster. (the login will be stored in /Users/dbr/.pypirc) Save your login (y/N)?y running upload Submitting dist/mypackage-1.2.1.tar.gz to http://pypi.python.org/pypi Upload failed (401): You must be identified to edit package information </code></pre> <p>It's prompting to save the login details, despite <code>~/.pypirc</code> already containing this. It then fails to upload files for a package I own, and have full write-access to.</p>
42
2009-10-14T22:15:41Z
29,389,352
<p>I have this problem and solved it by putting the file .pypirc under my home directory (~/), as the last past of the first comment suggests. </p> <p>I didn't have the need to modify the name of the section "pypi" of the file pypirc for "server-login", as suggested also in the first comment.</p>
1
2015-04-01T11:16:27Z
[ "python", "packaging", "setuptools" ]
"setup.py upload" is failing with "Upload failed (401): You must be identified to edit package information"
1,569,315
<p>When running..</p> <pre><code>python setup.py sdist register upload </code></pre> <p>..I get the following output:</p> <pre><code>running register We need to know who you are, so please choose either: 1. use your existing login, 2. register as a new user, 3. have the server generate a new password for you (and email it to you), or 4. quit Your selection [default 1]: 1 Username: example Password: ... Registering mypackage to http://pypi.python.org/pypi Server response (200): OK I can store your PyPI login so future submissions will be faster. (the login will be stored in /Users/dbr/.pypirc) Save your login (y/N)?y running upload Submitting dist/mypackage-1.2.1.tar.gz to http://pypi.python.org/pypi Upload failed (401): You must be identified to edit package information </code></pre> <p>It's prompting to save the login details, despite <code>~/.pypirc</code> already containing this. It then fails to upload files for a package I own, and have full write-access to.</p>
42
2009-10-14T22:15:41Z
36,268,165
<p>I changed <code>[distutils]</code> to <code>[pypirc]</code> as per the <a href="https://pythonhosted.org/an_example_pypi_project/setuptools.html#intermezzo-pypirc-file-and-gpg" rel="nofollow">docs</a> and this worked for me.</p> <p>Here is my <code>~/.pypirc</code> file:</p> <pre><code>[pypirc] index-servers = pypi pypitest [pypi] repository=https://pypi.python.org/pypi [pypitest] repository=https://testpypi.python.org/pypi [server-login] username:stav password:**** </code></pre>
0
2016-03-28T18:07:54Z
[ "python", "packaging", "setuptools" ]
"setup.py upload" is failing with "Upload failed (401): You must be identified to edit package information"
1,569,315
<p>When running..</p> <pre><code>python setup.py sdist register upload </code></pre> <p>..I get the following output:</p> <pre><code>running register We need to know who you are, so please choose either: 1. use your existing login, 2. register as a new user, 3. have the server generate a new password for you (and email it to you), or 4. quit Your selection [default 1]: 1 Username: example Password: ... Registering mypackage to http://pypi.python.org/pypi Server response (200): OK I can store your PyPI login so future submissions will be faster. (the login will be stored in /Users/dbr/.pypirc) Save your login (y/N)?y running upload Submitting dist/mypackage-1.2.1.tar.gz to http://pypi.python.org/pypi Upload failed (401): You must be identified to edit package information </code></pre> <p>It's prompting to save the login details, despite <code>~/.pypirc</code> already containing this. It then fails to upload files for a package I own, and have full write-access to.</p>
42
2009-10-14T22:15:41Z
37,899,752
<p>None of the changes to ~/.pypirc listed here worked for me.</p> <p>This worked for me, with no changes to ~/.pypirc. I added "-r <a href="https://www.python.org/pypi" rel="nofollow">https://www.python.org/pypi</a>" to the command line:</p> <pre><code>python setup.py register sdist upload -r https://www.python.org/pypi </code></pre> <p>My ~/.pypirc looks like this</p> <pre><code>[distutils] index-servers: pypi [pypi] username: dlink password: ******** (the real one) </code></pre>
4
2016-06-18T17:25:16Z
[ "python", "packaging", "setuptools" ]
How can I build the Boost.Python example on Ubuntu 9.10?
1,569,490
<p>I am using Ubuntu 9.10 beta, whose repositories contain boost 1.38. I would like to build the hello-world example. I followed the instructions here (<a href="http://www.boost.org/doc/libs/1%5F40%5F0/libs/python/doc/tutorial/doc/html/python/hello.html" rel="nofollow">http://www.boost.org/doc/libs/1%5F40%5F0/libs/python/doc/tutorial/doc/html/python/hello.html</a>), found the example project, and issued the "bjam" command. I have installed bjam and boost-build. </p> <p>I get the following output:</p> <pre><code>Jamroot:18: in modules.load rule python-extension unknown in module Jamfile&lt;/usr/share/doc/libboost1.38-doc/examples/libs/python/example&gt;. /usr/share/boost-build/build/project.jam:312: in load-jamfile /usr/share/boost-build/build/project.jam:68: in load /usr/share/boost-build/build/project.jam:170: in project.find /usr/share/boost-build/build-system.jam:248: in load /usr/share/boost-build/kernel/modules.jam:261: in import /usr/share/boost-build/kernel/bootstrap.jam:132: in boost-build /usr/share/doc/libboost1.38-doc/examples/libs/python/example/boost-build.jam:7: in module scope </code></pre> <p>I do not know enough about Boost (this is an exploratory exercise for myself) to understand why the python-extension macro in the included Jamroot is not valid. I am running this example from the install directory, so I have not altered the Jamroot's use-project setting. </p> <p>As a side question, if I were to just willy-nilly start a project in an arbitrary directory, how would I write my jamroot? </p>
4
2009-10-14T23:05:16Z
1,694,664
<p>The problem comes from using Ubuntu package instead of boost compiled from source. You have to edit you Jamroot to say it to use global libboost-python, instead of looking for lib in relative boost source tree.</p> <p>Summarily you should have these lines at the beginning of your Jamroot:</p> <pre><code>using python ; lib libboost_python : : &lt;name&gt;boost_python ; project : requirements &lt;library&gt;libboost_python ; </code></pre> <p>It was reported as a bug on Debian and corrected at least on lenny with libboost-python1.40 ...mostly. The example in libboost_python still refers to boost_python-mt instead of boost_python, but /usr/lib/libboost_python.so exists but not /usr/lib/libboost_python-mt.so.</p> <p>Hopefully Ubuntu will soon have the same fix and the next user won't stumble on this... I know the answer to your question because I <strong>did</strong> had the exact same problem not long ago.</p>
4
2009-11-07T22:30:57Z
[ "python", "boost", "ubuntu" ]
How to create a custom 404 page for my Django/Apache?
1,569,682
<p>I know that you use .htaccess in the document-root directory in standard apache. What if I use Django? Can someone give me step by step how to create a custom 404 page?</p> <p>THanks.</p>
3
2009-10-15T00:22:32Z
1,569,694
<p>The default 404 handler calls 404.html . You could edit that if you don't need anything fancy or can override the 404 handler by setting the handler404 view -- <a href="http://docs.djangoproject.com/en/dev/topics/http/views/#the-404-page-not-found-view">more here</a></p>
14
2009-10-15T00:26:36Z
[ "python", "django", "apache" ]
How to create a custom 404 page for my Django/Apache?
1,569,682
<p>I know that you use .htaccess in the document-root directory in standard apache. What if I use Django? Can someone give me step by step how to create a custom 404 page?</p> <p>THanks.</p>
3
2009-10-15T00:22:32Z
1,569,940
<p>In general the Django documentation is really great. Have a look at the <a href="http://www.djangobook.com/en/2.0/" rel="nofollow">Django Book</a> for a great intoduction to Django. They cover the 404 page in <a href="http://www.djangobook.com/en/2.0/chapter03/" rel="nofollow">chapter 3</a></p>
3
2009-10-15T02:00:41Z
[ "python", "django", "apache" ]
Relative imports from __init__ in multi-file Django apps
1,569,703
<p>I have a Django project located at /var/django/project/ where /var/django/ is in the PATH</p> <p>within that project I have:</p> <pre><code>___init__.py manage.py utils/ __init__.py tools.py </code></pre> <p><code>utils/__init__.py</code> contains a function named <code>get_preview</code></p> <p><code>utils/tools.py</code> contains a function named <code>get_related</code></p> <p>How can <code>utils/__init__.py</code> import <code>get_related</code> from <code>utils/tools.py</code>?</p> <p>How can <code>utils/tools.py</code> import <code>get_preview</code> from <code>utils/__init_.py</code>?</p> <p>I have tried relative imports as well as static imports but seem to get an error in <code>tools.py</code> when I try to <code>from project.utils import get_preview</code></p>
0
2009-10-15T00:29:20Z
1,569,725
<p>You can't (and shouldn't). You are structuring your code very poorly if files in your module are referencing code in the <code>__init__.py</code> associated with it. Either move both functions into <code>__init__.py</code> or both of them out of <code>__init__.py</code> or put them into separate modules. Those are your only options.</p>
2
2009-10-15T00:35:13Z
[ "python", "django", "import" ]
Relative imports from __init__ in multi-file Django apps
1,569,703
<p>I have a Django project located at /var/django/project/ where /var/django/ is in the PATH</p> <p>within that project I have:</p> <pre><code>___init__.py manage.py utils/ __init__.py tools.py </code></pre> <p><code>utils/__init__.py</code> contains a function named <code>get_preview</code></p> <p><code>utils/tools.py</code> contains a function named <code>get_related</code></p> <p>How can <code>utils/__init__.py</code> import <code>get_related</code> from <code>utils/tools.py</code>?</p> <p>How can <code>utils/tools.py</code> import <code>get_preview</code> from <code>utils/__init_.py</code>?</p> <p>I have tried relative imports as well as static imports but seem to get an error in <code>tools.py</code> when I try to <code>from project.utils import get_preview</code></p>
0
2009-10-15T00:29:20Z
1,569,784
<p>Yeah, this is bad structure. You gotta watch out here with creating a circular import between the two files. <a href="http://effbot.org/zone/import-confusion.htm" rel="nofollow" title="Import Confusion">About circular imports</a>.</p>
2
2009-10-15T00:58:48Z
[ "python", "django", "import" ]
Relative imports from __init__ in multi-file Django apps
1,569,703
<p>I have a Django project located at /var/django/project/ where /var/django/ is in the PATH</p> <p>within that project I have:</p> <pre><code>___init__.py manage.py utils/ __init__.py tools.py </code></pre> <p><code>utils/__init__.py</code> contains a function named <code>get_preview</code></p> <p><code>utils/tools.py</code> contains a function named <code>get_related</code></p> <p>How can <code>utils/__init__.py</code> import <code>get_related</code> from <code>utils/tools.py</code>?</p> <p>How can <code>utils/tools.py</code> import <code>get_preview</code> from <code>utils/__init_.py</code>?</p> <p>I have tried relative imports as well as static imports but seem to get an error in <code>tools.py</code> when I try to <code>from project.utils import get_preview</code></p>
0
2009-10-15T00:29:20Z
1,569,827
<p>You can do it, you just need to make one of the imports happen at runtime to avoid the circular import.</p> <p>For example, <code>__init__.py</code>:</p> <pre><code>from project.utils.tools import get_related def get_preview(): # ... </code></pre> <p>and <code>tools.py</code>:</p> <pre><code>def get_related(): from project.utils import get_preview # ... get_preview() </code></pre>
0
2009-10-15T01:17:57Z
[ "python", "django", "import" ]
Django - how can I get permalink to work with "throwaway" slug
1,569,837
<p>I'm trying to add slugs to the url in my django app, much like SO does.</p> <p>Currently, I have pages that work just fine with a url like this:</p> <pre><code>http://example.com/foo/123/ </code></pre> <p>I'd like to add 'slugified' urls like so:</p> <pre><code>http://example.com/foo/123/foo-name-here </code></pre> <p>I can get it to work just fine, by simply modifying the urlconf and adding a throwaway value to the view function:</p> <pre><code>#urls.py ulpatterns = patterns('project.app.views', url(r'^foo/(?P&lt;foo_id&gt;\d+)/(?P&lt;name_slug&gt;\w+)/$', 'foo_detail', name='foo_detail'), ) #views.py: def foo_detail(request, foo_id, name_slug): # stuff here, name slug is just discarded </code></pre> <p>Visting the url with the slug works just fine.</p> <p>However, my problem is when I am using <code>@models.permalink</code>.</p> <p>For my <code>Foo</code> model, I used to have the following, which worked just fine:</p> <pre><code>@models.permalink def get_absolute_url(self): return ('foo_detail', [str(self.id),]) </code></pre> <p>However, after my change, whenever I call <code>{{ foo.get_absolute_url }}</code> in my templates, the result is always an empty string.</p> <p>I have tried the following two replacements for <code>get_absolute_url</code>, neither of which is working:</p> <pre><code>from django.template.defaultfilters import slugify # attempt 1 @models.permalink def get_absolute_url(self): return ('foo_detail', [str(self.id), slugify(self.name)]) # attempt 2 @models.permalink def get_absolute_url(self): return ('foo_detail', (), { 'foo_id': str(self.id), 'name_slug': slugify(self.name), }) </code></pre> <p>Note that if I add a <code>print slugify(self.name)</code> before returning, the slugified name is showing up in the console just fine.</p> <p>When invoking <code>{{ foo.get_absolute_url }}</code> in my templates, the result is always an empty string, and I don't get any errors.</p> <p>I know I could replace the method with <code>return '/foo/%s/%s' % (str(self.id), slugify(self.name))</code>, but I'm trying to get the permalink working so that my URL is only defined in one place. What am I doing wrong?</p>
4
2009-10-15T01:21:36Z
1,569,882
<p>One thing to check for, because I also ran into this problem:</p> <pre><code>(?P&lt;name_slug&gt;\w+) </code></pre> <p>Is slugify adding hyphens anywhere? If so the regex won't match, hypens are a non-word character. To fix use <code>[\w-]+</code> or similar.</p>
7
2009-10-15T01:40:24Z
[ "python", "django", "django-urls", "permalinks" ]
How to write a RESTful URL path regex in GAE/Python for n parameters?
1,570,198
<p>Currently I have three URL paths that map to ServiceHandler. How do I combine the three into one neat regex that can pass n number of arguments to ServiceHandler?</p> <pre><code>(r'/s/([^/]*)', ServiceHandler), (r'/s/([^/]*)/([^/]*)', ServiceHandler), (r'/s/([^/]*)/([^/]*)/([^/]*)', ServiceHandler) </code></pre>
1
2009-10-15T03:49:54Z
1,570,358
<p>You can try something like</p> <p><code>(r'/s/([^/]*)/?([^/]*)/?([^/]*)', ServiceHandler)</code></p> <p>I think you will always get 3 parameters to ServiceHandler but the ones that aren't used will be empty strings</p>
0
2009-10-15T05:01:42Z
[ "python", "regex", "google-app-engine", "url-mapping" ]
How to write a RESTful URL path regex in GAE/Python for n parameters?
1,570,198
<p>Currently I have three URL paths that map to ServiceHandler. How do I combine the three into one neat regex that can pass n number of arguments to ServiceHandler?</p> <pre><code>(r'/s/([^/]*)', ServiceHandler), (r'/s/([^/]*)/([^/]*)', ServiceHandler), (r'/s/([^/]*)/([^/]*)/([^/]*)', ServiceHandler) </code></pre>
1
2009-10-15T03:49:54Z
1,572,298
<pre><code>(r'^/s/(([^/]*)((/[^/]+)*))$', ServiceHandler) </code></pre> <p>Should do the trick to match any amount of </p> <p>/s/foo/bar/baz/to/infinity/and/beyond/</p> <p>You can also limit it to a range by doing something like</p> <pre><code>^/s/(([^/]*)((/[^/]+){0,2}))$ </code></pre> <p>Which would only match things like</p> <pre><code>/s/foo/bar/baz /s/foo/bar /s/foo </code></pre> <p>but not </p> <pre><code>/s/foo/bar/baz/pirate /s </code></pre>
1
2009-10-15T13:15:12Z
[ "python", "regex", "google-app-engine", "url-mapping" ]
How to write a RESTful URL path regex in GAE/Python for n parameters?
1,570,198
<p>Currently I have three URL paths that map to ServiceHandler. How do I combine the three into one neat regex that can pass n number of arguments to ServiceHandler?</p> <pre><code>(r'/s/([^/]*)', ServiceHandler), (r'/s/([^/]*)/([^/]*)', ServiceHandler), (r'/s/([^/]*)/([^/]*)/([^/]*)', ServiceHandler) </code></pre>
1
2009-10-15T03:49:54Z
1,575,045
<p>This should work for any number</p> <pre><code>(r'(?&lt;!^)/([^/]+)', ServiceHandler) </code></pre> <p>Since I've looked in urlresolvers.py, I see this won't work although you could patch the correct behaviour into urlresolvers.py using regex.findall instead of re.search.</p>
0
2009-10-15T21:01:47Z
[ "python", "regex", "google-app-engine", "url-mapping" ]
In Python, how do I transform a string into a file?
1,570,230
<p>There is a read-only library function that takes a file as an argument. But I have a string.</p> <p>How do I convert a string to a file, that if you read the file it will return this string? I don't want to write to disk.</p>
3
2009-10-15T04:05:54Z
1,570,244
<p>The <code>StringIO</code> module:</p> <pre><code>&gt;&gt;&gt; import StringIO &gt;&gt;&gt; f = StringIO.StringIO("foo") &gt;&gt;&gt; f.read() 'foo' </code></pre> <p>The <code>cStringIO</code> module has the same interface, and is faster, but can't deal with Unicode strings that have non-ASCII characters.</p> <p><a href="http://docs.python.org/library/stringio.html" rel="nofollow">StringIO documentation</a></p>
15
2009-10-15T04:15:29Z
[ "python", "string", "file", "types" ]
In Python, how do I transform a string into a file?
1,570,230
<p>There is a read-only library function that takes a file as an argument. But I have a string.</p> <p>How do I convert a string to a file, that if you read the file it will return this string? I don't want to write to disk.</p>
3
2009-10-15T04:05:54Z
1,570,892
<p>what do you want? if you want to read from file just use:</p> <pre><code>file('/path/to/file').read() </code></pre> <p>or</p> <pre><code>open('/path/to/file','r').read() </code></pre> <p>if you want to read string,just do as suggest by Phil</p>
0
2009-10-15T07:54:18Z
[ "python", "string", "file", "types" ]
Finding words from random input letters in python. What algorithm to use/code already there?
1,570,242
<p>I am trying to code a word descrambler like this one <a href="http://www.thewordfinder.com/scrabble.php" rel="nofollow">here</a> and was wondering what algorithms I should use to implement this. Also, if anyone can find existing code for this that would be great as well. Basically the functionality is going to be like a boggle solver but without being a matrix, just searching for all word possibilities from a string of characters. I do already have adequate dictionaries.</p> <p>I was planning to do this in either python or ruby. Thanks in advance for your help guys!</p>
2
2009-10-15T04:13:00Z
1,570,248
<p>I'd use a <a href="http://en.wikipedia.org/wiki/Trie" rel="nofollow">Trie</a>. Here's an implementation in Python: <a href="http://jtauber.com/2005/02/trie.py" rel="nofollow">http://jtauber.com/2005/02/trie.py</a> (credit to James Tauber)</p>
3
2009-10-15T04:17:00Z
[ "python", "ruby", "word", "anagram" ]
Finding words from random input letters in python. What algorithm to use/code already there?
1,570,242
<p>I am trying to code a word descrambler like this one <a href="http://www.thewordfinder.com/scrabble.php" rel="nofollow">here</a> and was wondering what algorithms I should use to implement this. Also, if anyone can find existing code for this that would be great as well. Basically the functionality is going to be like a boggle solver but without being a matrix, just searching for all word possibilities from a string of characters. I do already have adequate dictionaries.</p> <p>I was planning to do this in either python or ruby. Thanks in advance for your help guys!</p>
2
2009-10-15T04:13:00Z
1,570,386
<p>I may be missing an understanding of the game but barring some complications in the rules, such as with the introduction of "joker" (wildcard) letters, missing or additional letters, multiple words etc... I think the following ideas would help turn the problem in a somewhat relatively uninteresting thing. :-(</p> <p>Main idea <strong>index words by the <em>ordered</em> sequence of their letters</strong>.<br> For example "computer" gets keyed as "cemoprtu". Whatever the random drawings provide is sorting in kind, and used as key to find possible matches. Using <a href="http://en.wikipedia.org/wiki/Trie" rel="nofollow"><strong>trie</strong></a> structures as suggested by perimosocordiae, as the underlying storage for these sorted keys and associated words(s)/wordIds in the "leaf" nodes, Word <strong>lookup can be done in O(n) time</strong>, where n is the number of letters (or better, on average due to non-existing words). </p> <p>To further help with indexing we can have several tables/dictionaries, one per number of letters. Also depending on statistics the vowels and consonants could be handled separately. Another trick would be to have a custom sort order, placing the most selective letters first.</p> <p>Additional twists to the game (such as finding words made from a subset of the letters) is mostly a matter of <strong>iterating the</strong> <a href="http://en.wikipedia.org/wiki/Power%5Fset" rel="nofollow"><strong>power set</strong></a> <strong>of these letters</strong> and checking the dictionary for each combination. </p> <p><strong>A few heuristics can be introduced</strong> to help prune some of the combinations (for example combinations without vowels [and of a given length] are not possible solutions etc. One should manage these heuristics carefully for the lookup cost is relatively small.</p>
2
2009-10-15T05:08:19Z
[ "python", "ruby", "word", "anagram" ]
Finding words from random input letters in python. What algorithm to use/code already there?
1,570,242
<p>I am trying to code a word descrambler like this one <a href="http://www.thewordfinder.com/scrabble.php" rel="nofollow">here</a> and was wondering what algorithms I should use to implement this. Also, if anyone can find existing code for this that would be great as well. Basically the functionality is going to be like a boggle solver but without being a matrix, just searching for all word possibilities from a string of characters. I do already have adequate dictionaries.</p> <p>I was planning to do this in either python or ruby. Thanks in advance for your help guys!</p>
2
2009-10-15T04:13:00Z
1,570,490
<p>For your dictionary index, build a map (Map[Bag[Char], List[String]]). It should be a hash map so you can get O(1) word lookup. A Bag[Char] is an identifier for a word that is unique up to character order. It's is basically a hash map from Char to Int. The Char is a given character in the word and the Int is the number of times that character appears in the word.</p> <p>Example:</p> <pre><code>{'a'=&gt;3, 'n'=&gt;1, 'g'=&gt;1, 'r'=&gt;1, 'm'=&gt;1} =&gt; ["anagram"] {'s'=&gt;3, 't'=&gt;1, 'r'=&gt;1, 'e'=&gt;2, 'd'=&gt;1} =&gt; ["stressed", "desserts"] </code></pre> <p>To find words, take every combination of characters from the input string and look it up in this map. The complexity of this algorithm is O(2^n) in the length of the input string. Notably, the complexity does not depend on the length of the dictionary.</p>
2
2009-10-15T05:43:39Z
[ "python", "ruby", "word", "anagram" ]
Finding words from random input letters in python. What algorithm to use/code already there?
1,570,242
<p>I am trying to code a word descrambler like this one <a href="http://www.thewordfinder.com/scrabble.php" rel="nofollow">here</a> and was wondering what algorithms I should use to implement this. Also, if anyone can find existing code for this that would be great as well. Basically the functionality is going to be like a boggle solver but without being a matrix, just searching for all word possibilities from a string of characters. I do already have adequate dictionaries.</p> <p>I was planning to do this in either python or ruby. Thanks in advance for your help guys!</p>
2
2009-10-15T04:13:00Z
1,571,927
<p>This sounds like <a href="http://en.wikipedia.org/wiki/Rabin-Karp%5Fstring%5Fsearch%5Falgorithm#Rabin-Karp%5Fand%5Fmultiple%5Fpattern%5Fsearch" rel="nofollow">Rabin-Karp string search</a> would be a good choice. If you use a rolling hash-function then at each position you need one hash value update and one dictionary lookup. You also need to create a good way to cope with different word lengths, like truncating all words to the shortest word in the set and rechecking possible matches. Splitting the word set into separate length ranges will reduce the amount of false positives at the expense of increasing the hashing work.</p>
1
2009-10-15T11:58:10Z
[ "python", "ruby", "word", "anagram" ]
Finding words from random input letters in python. What algorithm to use/code already there?
1,570,242
<p>I am trying to code a word descrambler like this one <a href="http://www.thewordfinder.com/scrabble.php" rel="nofollow">here</a> and was wondering what algorithms I should use to implement this. Also, if anyone can find existing code for this that would be great as well. Basically the functionality is going to be like a boggle solver but without being a matrix, just searching for all word possibilities from a string of characters. I do already have adequate dictionaries.</p> <p>I was planning to do this in either python or ruby. Thanks in advance for your help guys!</p>
2
2009-10-15T04:13:00Z
1,574,996
<p>There are two ways to do this. One is to check every candidate permutation of letters in the word to see if the candidate is in your dictionary of words. That's an O(N!) operation, depending on the length of the word.</p> <p>The other way is to check every candidate word in your dictionary to see if it's contained within the word. This can be sped up by aggregating the dictionary; instead of every candidate word, you check all words that are anagrams of each other at once, since if any one of them is contained in your word, all of them are.</p> <p>So start by building a dictionary whose key is a sorted string of letters and whose value is a list of the words that are anagrams of the key:</p> <pre><code>&gt;&gt;&gt; from collections import defaultdict &gt;&gt;&gt; d = defaultdict(list) &gt;&gt;&gt; with open(r"c:\temp\words.txt", "r") as f: for line in f.readlines(): if line[0].isupper(): continue word = line.strip() key = "".join(sorted(word.lower())) d[key].append(word) </code></pre> <p>Now we need a function to see if a word contains a candidate. This function assumes that the word and candidate are both sorted, so that it can go through them both letter by letter and give up quickly when it finds that they don't match.</p> <pre><code>&gt;&gt;&gt; def contains(sorted_word, sorted_candidate): wchars = (c for c in sorted_word) for cc in sorted_candidate: while(True): try: wc = wchars.next() except StopIteration: return False if wc &lt; cc: continue if wc == cc: break return False return True </code></pre> <p>Now find all the candidate keys in the dictionary that are contained by the word, and aggregate all of their values into a single list:</p> <pre><code>&gt;&gt;&gt; w = sorted("mythopoetic") &gt;&gt;&gt; result = [] &gt;&gt;&gt; for k in d.keys(): if contains(w, k): result.extend(d[k]) &gt;&gt;&gt; len(result) 429 &gt;&gt;&gt; sorted(result)[:20] ['c', 'ce', 'cep', 'ceti', 'che', 'chetty', 'chi', 'chime', 'chip', 'chit', 'chitty', 'cho', 'chomp', 'choop', 'chop', 'chott', 'chyme', 'cipo', 'cit', 'cite'] </code></pre> <p>That last step takes about a quarter second on my laptop; there are 195K keys in my dictionary (I'm using the BSD Unix words file).</p>
1
2009-10-15T20:52:16Z
[ "python", "ruby", "word", "anagram" ]
Does configuring django's setting.TIME_ZONE affect datetime.datetime.now()?
1,570,339
<p>The documentation says:</p> <p><a href="http://docs.djangoproject.com/en/dev/ref/settings/#time-zone" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/settings/#time-zone</a></p> <blockquote> <p>Note that this is the time zone to which Django will convert all dates/times -- not necessarily the timezone of the server. For example, one server may serve multiple Django-powered sites, each with a separate time-zone setting. Normally, Django sets the os.environ['TZ'] variable to the time zone you specify in the TIME_ZONE setting. Thus, all your views and models will automatically operate in the correct time zone.</p> </blockquote> <p>I've read this several times and it's not clear to me what's going on with the TIME_ZONE setting.</p> <p>Should I be managing UTC offsets if I want models with a date-time stamp to display to the users local-time zone? </p> <p>For example on save use, datetime.datetime.utcnow() instead of datetime.datetime.now(), and in the view do something like:</p> <pre><code>display_datetime = model.date_time + datetime.timedelta(USER_UTC_OFFSET) </code></pre>
4
2009-10-15T04:53:56Z
1,570,466
<p>Much to my surprise, it does appear to.</p> <pre><code>web81:~/webapps/dominicrodger2/dominicrodger$ python2.5 manage.py shell Python 2.5.4 (r254:67916, Aug 5 2009, 12:42:40) [GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) &gt;&gt;&gt; import settings &gt;&gt;&gt; settings.TIME_ZONE 'Europe/London' &gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; datetime.now() datetime.datetime(2009, 10, 15, 6, 29, 58, 85662) &gt;&gt;&gt; exit() web81:~/webapps/dominicrodger2/dominicrodger$ date Thu Oct 15 00:31:10 CDT 2009 </code></pre> <p>And yes, I did get distracted whilst writing this answer :-)</p> <p>I use the <code>TIME_ZONE</code> setting so that my automatically added timestamps on object creation (using <code>auto_now_add</code>, which I believe is soon to be deprecated) show creation times in the timezone I set.</p> <p>If you want to convert those times into the timezones of your website visitors, you'll need to do a bit more work, as per the example you gave. If you want to do lots of timezone conversion to display times in your website visitors' timezones, then I'd strongly advise you to set your <code>TIME_ZONE</code> settings to store times in UTC, because it'll make your life easier in the long run (you can just use UTC-offsets, rather than having to worry about daylight savings).</p> <p>If you're interested, I believe the timezone is set from the <code>TIME_ZONE</code> setting <a href="http://code.djangoproject.com/browser/django/trunk/django/conf/__init__.py#L109" rel="nofollow">here</a>.</p> <p>Edit, per your comment that it doesn't work on Windows, this is because of the following in the Django source:</p> <pre><code>if hasattr(time, 'tzset'): # Move the time zone info into os.environ. See ticket #2315 for why # we don't do this unconditionally (breaks Windows). os.environ['TZ'] = self.TIME_ZONE time.tzset() </code></pre> <p><strong>Windows:</strong></p> <pre><code>C:\Documents and Settings\drodger&gt;python ActivePython 2.6.1.1 (ActiveState Software Inc.) based on Python 2.6.1 (r261:67515, Dec 5 2008, 13:58:38) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import time &gt;&gt;&gt; hasattr(time, 'tzset') False </code></pre> <p><strong>Linux:</strong></p> <pre><code>web81:~$ python2.5 Python 2.5.4 (r254:67916, Aug 5 2009, 12:42:40) [GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import time &gt;&gt;&gt; hasattr(time, 'tzset') True </code></pre>
4
2009-10-15T05:34:56Z
[ "python", "django", "datetime" ]
Does configuring django's setting.TIME_ZONE affect datetime.datetime.now()?
1,570,339
<p>The documentation says:</p> <p><a href="http://docs.djangoproject.com/en/dev/ref/settings/#time-zone" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/settings/#time-zone</a></p> <blockquote> <p>Note that this is the time zone to which Django will convert all dates/times -- not necessarily the timezone of the server. For example, one server may serve multiple Django-powered sites, each with a separate time-zone setting. Normally, Django sets the os.environ['TZ'] variable to the time zone you specify in the TIME_ZONE setting. Thus, all your views and models will automatically operate in the correct time zone.</p> </blockquote> <p>I've read this several times and it's not clear to me what's going on with the TIME_ZONE setting.</p> <p>Should I be managing UTC offsets if I want models with a date-time stamp to display to the users local-time zone? </p> <p>For example on save use, datetime.datetime.utcnow() instead of datetime.datetime.now(), and in the view do something like:</p> <pre><code>display_datetime = model.date_time + datetime.timedelta(USER_UTC_OFFSET) </code></pre>
4
2009-10-15T04:53:56Z
5,718,301
<p>With <code>TIME_ZONE</code> as UTC, utcnow() and now() are the same. This is probably what you want. Then you can record times as now/utcnow and functions like <code>timesince</code> will work perfectly for every user. To display absolute times to specific users, you can use utc offsets as you suggest.</p>
1
2011-04-19T14:48:39Z
[ "python", "django", "datetime" ]
Create a user-group in linux using python
1,570,401
<p>I want to create a user group using python on CentOS system. When I say 'using python' I mean I don't want to do something like os.system and give the unix command to create a new group. I would like to know if there is any python module that deals with this.</p> <p>Searching on the net did not reveal much about what I want, except for python user groups.. so I had to ask this.</p> <p>I learned about the grp module by searching here on SO, but couldn't find anything about creating a group.</p> <p><strong>EDIT</strong>: I dont know if I have to start a new question for this, but I would also like to know how to add (existing) users to the newly created group.</p> <p>Any help appreciated. Thank you.</p>
5
2009-10-15T05:13:02Z
1,570,429
<p>I think you <em>should</em> use the commandline programs from your program, a lot of care has gone into making sure that they don't break the groups file if something goes wrong. </p> <p>However the file format is quite straight forward to write something yourself if you choose to go that way</p>
4
2009-10-15T05:20:29Z
[ "python", "linux", "usergroups" ]
Create a user-group in linux using python
1,570,401
<p>I want to create a user group using python on CentOS system. When I say 'using python' I mean I don't want to do something like os.system and give the unix command to create a new group. I would like to know if there is any python module that deals with this.</p> <p>Searching on the net did not reveal much about what I want, except for python user groups.. so I had to ask this.</p> <p>I learned about the grp module by searching here on SO, but couldn't find anything about creating a group.</p> <p><strong>EDIT</strong>: I dont know if I have to start a new question for this, but I would also like to know how to add (existing) users to the newly created group.</p> <p>Any help appreciated. Thank you.</p>
5
2009-10-15T05:13:02Z
1,570,448
<p>I don't know of a python module to do it, but the /etc/group and /etc/gshadow format is pretty standard, so if you wanted you could just open the files, parse their current contents and then add the new group if necessary.</p> <p>Before you go doing this, consider:</p> <ul> <li>What happens if you try to add a group that already exists on the system</li> <li>What happens when multiple instances of your program try to add a group at the same time</li> <li>What happens to your code when an incompatible change is made to the group format a couple releases down the line</li> <li>NIS, LDAP, Kerberos, ...</li> </ul> <p>If you're not willing to deal with these kinds of problems, just use the subprocess module and run groupadd. It will be way less likely to break your customers machines.</p> <p>Another thing you could do that would be less fragile than writing your own would be to wrap the code in groupadd.c (in the shadow package) in Python and do it that way. I don't see this buying you much versus just exec'ing it, though, and it would add more complexity and fragility to your build.</p>
9
2009-10-15T05:26:09Z
[ "python", "linux", "usergroups" ]
Create a user-group in linux using python
1,570,401
<p>I want to create a user group using python on CentOS system. When I say 'using python' I mean I don't want to do something like os.system and give the unix command to create a new group. I would like to know if there is any python module that deals with this.</p> <p>Searching on the net did not reveal much about what I want, except for python user groups.. so I had to ask this.</p> <p>I learned about the grp module by searching here on SO, but couldn't find anything about creating a group.</p> <p><strong>EDIT</strong>: I dont know if I have to start a new question for this, but I would also like to know how to add (existing) users to the newly created group.</p> <p>Any help appreciated. Thank you.</p>
5
2009-10-15T05:13:02Z
1,571,882
<p>There are no library calls for creating a group. This is because there's really no such thing as creating a group. A GID is simply a number assigned to a process or a file. All these numbers exist already - there is nothing you need to do to start using a GID. With the appropriate privileges, you can call chown(2) to set the GID of a file to any number, or setgid(2) to set the GID of the current process (there's a little more to it than that, with effective IDs, supplementary IDs, etc).</p> <p>Giving a name to a GID is done by an entry in /etc/group on basic Unix/Linux/POSIX systems, but that's really just a convention adhered to by the Unix/Linux/POSIX userland tools. Other network-based directories also exist, as mentioned by Jack Lloyd.</p> <p>The man page group(5) describes the format of the /etc/group file, but it is not recommended that you write to it directly. Your distribution will have policies on how unnamed GIDs are allocated, such as reserving certain spaces for different purposes (fixed system groups, dynamic system groups, user groups, etc). The range of these number spaces differs on different distributions. These policies are usually encoded in the command-line tools that a sysadmin uses to assign unnamed GIDs.</p> <p>This means the best way to add a group locally is to use the command-line tools.</p>
1
2009-10-15T11:47:13Z
[ "python", "linux", "usergroups" ]
Create a user-group in linux using python
1,570,401
<p>I want to create a user group using python on CentOS system. When I say 'using python' I mean I don't want to do something like os.system and give the unix command to create a new group. I would like to know if there is any python module that deals with this.</p> <p>Searching on the net did not reveal much about what I want, except for python user groups.. so I had to ask this.</p> <p>I learned about the grp module by searching here on SO, but couldn't find anything about creating a group.</p> <p><strong>EDIT</strong>: I dont know if I have to start a new question for this, but I would also like to know how to add (existing) users to the newly created group.</p> <p>Any help appreciated. Thank you.</p>
5
2009-10-15T05:13:02Z
2,426,777
<p>If you are looking at Python, then try this program. Its fairly simple to use, and the code can easily be customized <a href="http://aleph-null.tv/downloads/mpb-adduser-1.tgz" rel="nofollow">http://aleph-null.tv/downloads/mpb-adduser-1.tgz</a></p>
0
2010-03-11T16:33:03Z
[ "python", "linux", "usergroups" ]
Please help install matplotlib. It won't work! (Python)
1,570,495
<p>I downloaded the source. Untarred it. "sudo python setup.py install". And below are the errors I get. Can someone help? By the way, Numpy is installed. Thanks a lot.</p> <pre><code>src/_image.cpp:5:17: error: png.h: No such file or directory src/_image.cpp: In member function 'Py::Object Image::write_png(const Py::Tuple&amp;)': src/_image.cpp:646: error: 'png_structp' was not declared in this scope src/_image.cpp:646: error: expected `;' before 'png_ptr' src/_image.cpp:647: error: 'png_infop' was not declared in this scope src/_image.cpp:647: error: expected `;' before 'info_ptr' src/_image.cpp:648: error: aggregate 'png_color_8_struct sig_bit' has incomplete type and cannot be defined src/_image.cpp:649: error: 'png_uint_32' was not declared in this scope src/_image.cpp:649: error: expected `;' before 'row' src/_image.cpp:652: error: 'png_bytep' was not declared in this scope src/_image.cpp:652: error: 'row_pointers' was not declared in this scope src/_image.cpp:652: error: expected type-specifier before 'png_bytep' src/_image.cpp:652: error: expected `;' before 'png_bytep' src/_image.cpp:654: error: 'row' was not declared in this scope src/_image.cpp:660: error: type '&lt;type error&gt;' argument given to 'delete', expected pointer src/_image.cpp:665: error: 'png_ptr' was not declared in this scope src/_image.cpp:665: error: 'PNG_LIBPNG_VER_STRING' was not declared in this scope src/_image.cpp:665: error: 'png_create_write_struct' was not declared in this scope src/_image.cpp:669: error: type '&lt;type error&gt;' argument given to 'delete', expected pointer src/_image.cpp:673: error: 'info_ptr' was not declared in this scope src/_image.cpp:673: error: 'png_create_info_struct' was not declared in this scope src/_image.cpp:677: error: 'png_destroy_write_struct' was not declared in this scope src/_image.cpp:678: error: type '&lt;type error&gt;' argument given to 'delete', expected pointer src/_image.cpp:685: error: 'png_destroy_write_struct' was not declared in this scope src/_image.cpp:686: error: type '&lt;type error&gt;' argument given to 'delete', expected pointer src/_image.cpp:690: error: 'png_init_io' was not declared in this scope src/_image.cpp:693: error: 'PNG_COLOR_TYPE_RGB_ALPHA' was not declared in this scope src/_image.cpp:693: error: 'PNG_INTERLACE_NONE' was not declared in this scope src/_image.cpp:694: error: 'PNG_COMPRESSION_TYPE_BASE' was not declared in this scope src/_image.cpp:694: error: 'PNG_FILTER_TYPE_BASE' was not declared in this scope src/_image.cpp:694: error: 'png_set_IHDR' was not declared in this scope src/_image.cpp:703: error: 'png_set_sBIT' was not declared in this scope src/_image.cpp:705: error: 'png_write_info' was not declared in this scope src/_image.cpp:706: error: 'png_write_image' was not declared in this scope src/_image.cpp:707: error: 'png_write_end' was not declared in this scope src/_image.cpp:708: error: 'png_destroy_write_struct' was not declared in this scope src/_image.cpp:711: error: type '&lt;type error&gt;' argument given to 'delete', expected pointer src/_image.cpp: In member function 'Py::Object _image_module::readpng(const Py::Tuple&amp;)': src/_image.cpp:860: error: 'png_byte' was not declared in this scope src/_image.cpp:860: error: expected `;' before 'header' src/_image.cpp:866: error: 'header' was not declared in this scope src/_image.cpp:868: error: 'header' was not declared in this scope src/_image.cpp:868: error: 'png_sig_cmp' was not declared in this scope src/_image.cpp:873: error: 'png_structp' was not declared in this scope src/_image.cpp:873: error: expected `;' before 'png_ptr' src/_image.cpp:875: error: 'png_ptr' was not declared in this scope src/_image.cpp:878: error: 'png_infop' was not declared in this scope src/_image.cpp:878: error: expected `;' before 'info_ptr' src/_image.cpp:879: error: 'info_ptr' was not declared in this scope src/_image.cpp:882: error: 'png_ptr' was not declared in this scope src/_image.cpp:882: error: 'png_jmpbuf' was not declared in this scope src/_image.cpp:885: error: 'png_ptr' was not declared in this scope src/_image.cpp:885: error: 'png_init_io' was not declared in this scope src/_image.cpp:886: error: 'png_set_sig_bytes' was not declared in this scope src/_image.cpp:888: error: 'info_ptr' was not declared in this scope src/_image.cpp:888: error: 'png_read_info' was not declared in this scope src/_image.cpp:890: error: 'png_uint_32' was not declared in this scope src/_image.cpp:890: error: expected `;' before 'width' src/_image.cpp:891: error: expected `;' before 'height' src/_image.cpp:894: error: 'PNG_COLOR_TYPE_GRAY' was not declared in this scope src/_image.cpp:895: error: 'PNG_COLOR_TYPE_GRAY_ALPHA' was not declared in this scope src/_image.cpp:896: error: 'png_set_gray_to_rgb' was not declared in this scope src/_image.cpp:897: error: 'PNG_COLOR_TYPE_PALETTE' was not declared in this scope src/_image.cpp:898: error: 'png_set_palette_to_rgb' was not declared in this scope src/_image.cpp:902: error: 'png_set_strip_16' was not declared in this scope src/_image.cpp:905: error: 'png_set_interlace_handling' was not declared in this scope src/_image.cpp:906: error: 'png_read_update_info' was not declared in this scope src/_image.cpp:908: error: 'PNG_COLOR_TYPE_RGBA' was not declared in this scope src/_image.cpp:909: error: 'PNG_COLOR_TYPE_RGB' was not declared in this scope src/_image.cpp:915: error: 'png_jmpbuf' was not declared in this scope src/_image.cpp:918: error: 'png_bytep' was not declared in this scope src/_image.cpp:918: error: 'row_pointers' was not declared in this scope src/_image.cpp:918: error: expected type-specifier before 'png_bytep' src/_image.cpp:918: error: expected `;' before 'png_bytep' src/_image.cpp:919: error: expected `;' before 'row' src/_image.cpp:921: error: 'row' was not declared in this scope src/_image.cpp:921: error: 'height' was not declared in this scope src/_image.cpp:922: error: expected type-specifier before 'png_byte' src/_image.cpp:922: error: expected `;' before 'png_byte' src/_image.cpp:924: error: 'png_read_image' was not declared in this scope src/_image.cpp:929: error: 'height' was not declared in this scope src/_image.cpp:930: error: 'width' was not declared in this scope src/_image.cpp:936: error: expected `;' before 'y' src/_image.cpp:936: error: 'y' was not declared in this scope src/_image.cpp:938: error: expected `;' before 'x' src/_image.cpp:938: error: 'x' was not declared in this scope src/_image.cpp:940: error: 'ptr' was not declared in this scope src/_image.cpp:951: error: 'png_read_end' was not declared in this scope src/_image.cpp:952: error: 'png_infopp_NULL' was not declared in this scope src/_image.cpp:952: error: 'png_destroy_read_struct' was not declared in this scope src/_image.cpp:956: error: type '&lt;type error&gt;' argument given to 'delete', expected pointer error: command 'gcc' failed with exit status 1 </code></pre>
8
2009-10-15T05:45:29Z
1,570,501
<p>Those particular errors stem from the lack of the development package for libpng.</p> <p>If you use Debian/Ubuntu, try <code>apt-get install libpng-dev</code> first.</p>
20
2009-10-15T05:47:56Z
[ "python", "installation", "matplotlib" ]
Please help install matplotlib. It won't work! (Python)
1,570,495
<p>I downloaded the source. Untarred it. "sudo python setup.py install". And below are the errors I get. Can someone help? By the way, Numpy is installed. Thanks a lot.</p> <pre><code>src/_image.cpp:5:17: error: png.h: No such file or directory src/_image.cpp: In member function 'Py::Object Image::write_png(const Py::Tuple&amp;)': src/_image.cpp:646: error: 'png_structp' was not declared in this scope src/_image.cpp:646: error: expected `;' before 'png_ptr' src/_image.cpp:647: error: 'png_infop' was not declared in this scope src/_image.cpp:647: error: expected `;' before 'info_ptr' src/_image.cpp:648: error: aggregate 'png_color_8_struct sig_bit' has incomplete type and cannot be defined src/_image.cpp:649: error: 'png_uint_32' was not declared in this scope src/_image.cpp:649: error: expected `;' before 'row' src/_image.cpp:652: error: 'png_bytep' was not declared in this scope src/_image.cpp:652: error: 'row_pointers' was not declared in this scope src/_image.cpp:652: error: expected type-specifier before 'png_bytep' src/_image.cpp:652: error: expected `;' before 'png_bytep' src/_image.cpp:654: error: 'row' was not declared in this scope src/_image.cpp:660: error: type '&lt;type error&gt;' argument given to 'delete', expected pointer src/_image.cpp:665: error: 'png_ptr' was not declared in this scope src/_image.cpp:665: error: 'PNG_LIBPNG_VER_STRING' was not declared in this scope src/_image.cpp:665: error: 'png_create_write_struct' was not declared in this scope src/_image.cpp:669: error: type '&lt;type error&gt;' argument given to 'delete', expected pointer src/_image.cpp:673: error: 'info_ptr' was not declared in this scope src/_image.cpp:673: error: 'png_create_info_struct' was not declared in this scope src/_image.cpp:677: error: 'png_destroy_write_struct' was not declared in this scope src/_image.cpp:678: error: type '&lt;type error&gt;' argument given to 'delete', expected pointer src/_image.cpp:685: error: 'png_destroy_write_struct' was not declared in this scope src/_image.cpp:686: error: type '&lt;type error&gt;' argument given to 'delete', expected pointer src/_image.cpp:690: error: 'png_init_io' was not declared in this scope src/_image.cpp:693: error: 'PNG_COLOR_TYPE_RGB_ALPHA' was not declared in this scope src/_image.cpp:693: error: 'PNG_INTERLACE_NONE' was not declared in this scope src/_image.cpp:694: error: 'PNG_COMPRESSION_TYPE_BASE' was not declared in this scope src/_image.cpp:694: error: 'PNG_FILTER_TYPE_BASE' was not declared in this scope src/_image.cpp:694: error: 'png_set_IHDR' was not declared in this scope src/_image.cpp:703: error: 'png_set_sBIT' was not declared in this scope src/_image.cpp:705: error: 'png_write_info' was not declared in this scope src/_image.cpp:706: error: 'png_write_image' was not declared in this scope src/_image.cpp:707: error: 'png_write_end' was not declared in this scope src/_image.cpp:708: error: 'png_destroy_write_struct' was not declared in this scope src/_image.cpp:711: error: type '&lt;type error&gt;' argument given to 'delete', expected pointer src/_image.cpp: In member function 'Py::Object _image_module::readpng(const Py::Tuple&amp;)': src/_image.cpp:860: error: 'png_byte' was not declared in this scope src/_image.cpp:860: error: expected `;' before 'header' src/_image.cpp:866: error: 'header' was not declared in this scope src/_image.cpp:868: error: 'header' was not declared in this scope src/_image.cpp:868: error: 'png_sig_cmp' was not declared in this scope src/_image.cpp:873: error: 'png_structp' was not declared in this scope src/_image.cpp:873: error: expected `;' before 'png_ptr' src/_image.cpp:875: error: 'png_ptr' was not declared in this scope src/_image.cpp:878: error: 'png_infop' was not declared in this scope src/_image.cpp:878: error: expected `;' before 'info_ptr' src/_image.cpp:879: error: 'info_ptr' was not declared in this scope src/_image.cpp:882: error: 'png_ptr' was not declared in this scope src/_image.cpp:882: error: 'png_jmpbuf' was not declared in this scope src/_image.cpp:885: error: 'png_ptr' was not declared in this scope src/_image.cpp:885: error: 'png_init_io' was not declared in this scope src/_image.cpp:886: error: 'png_set_sig_bytes' was not declared in this scope src/_image.cpp:888: error: 'info_ptr' was not declared in this scope src/_image.cpp:888: error: 'png_read_info' was not declared in this scope src/_image.cpp:890: error: 'png_uint_32' was not declared in this scope src/_image.cpp:890: error: expected `;' before 'width' src/_image.cpp:891: error: expected `;' before 'height' src/_image.cpp:894: error: 'PNG_COLOR_TYPE_GRAY' was not declared in this scope src/_image.cpp:895: error: 'PNG_COLOR_TYPE_GRAY_ALPHA' was not declared in this scope src/_image.cpp:896: error: 'png_set_gray_to_rgb' was not declared in this scope src/_image.cpp:897: error: 'PNG_COLOR_TYPE_PALETTE' was not declared in this scope src/_image.cpp:898: error: 'png_set_palette_to_rgb' was not declared in this scope src/_image.cpp:902: error: 'png_set_strip_16' was not declared in this scope src/_image.cpp:905: error: 'png_set_interlace_handling' was not declared in this scope src/_image.cpp:906: error: 'png_read_update_info' was not declared in this scope src/_image.cpp:908: error: 'PNG_COLOR_TYPE_RGBA' was not declared in this scope src/_image.cpp:909: error: 'PNG_COLOR_TYPE_RGB' was not declared in this scope src/_image.cpp:915: error: 'png_jmpbuf' was not declared in this scope src/_image.cpp:918: error: 'png_bytep' was not declared in this scope src/_image.cpp:918: error: 'row_pointers' was not declared in this scope src/_image.cpp:918: error: expected type-specifier before 'png_bytep' src/_image.cpp:918: error: expected `;' before 'png_bytep' src/_image.cpp:919: error: expected `;' before 'row' src/_image.cpp:921: error: 'row' was not declared in this scope src/_image.cpp:921: error: 'height' was not declared in this scope src/_image.cpp:922: error: expected type-specifier before 'png_byte' src/_image.cpp:922: error: expected `;' before 'png_byte' src/_image.cpp:924: error: 'png_read_image' was not declared in this scope src/_image.cpp:929: error: 'height' was not declared in this scope src/_image.cpp:930: error: 'width' was not declared in this scope src/_image.cpp:936: error: expected `;' before 'y' src/_image.cpp:936: error: 'y' was not declared in this scope src/_image.cpp:938: error: expected `;' before 'x' src/_image.cpp:938: error: 'x' was not declared in this scope src/_image.cpp:940: error: 'ptr' was not declared in this scope src/_image.cpp:951: error: 'png_read_end' was not declared in this scope src/_image.cpp:952: error: 'png_infopp_NULL' was not declared in this scope src/_image.cpp:952: error: 'png_destroy_read_struct' was not declared in this scope src/_image.cpp:956: error: type '&lt;type error&gt;' argument given to 'delete', expected pointer error: command 'gcc' failed with exit status 1 </code></pre>
8
2009-10-15T05:45:29Z
1,570,506
<p>if you are apt-based try</p> <p><code>$ sudo apt-get build-dep matplotlib</code></p>
9
2009-10-15T05:51:06Z
[ "python", "installation", "matplotlib" ]
Please help install matplotlib. It won't work! (Python)
1,570,495
<p>I downloaded the source. Untarred it. "sudo python setup.py install". And below are the errors I get. Can someone help? By the way, Numpy is installed. Thanks a lot.</p> <pre><code>src/_image.cpp:5:17: error: png.h: No such file or directory src/_image.cpp: In member function 'Py::Object Image::write_png(const Py::Tuple&amp;)': src/_image.cpp:646: error: 'png_structp' was not declared in this scope src/_image.cpp:646: error: expected `;' before 'png_ptr' src/_image.cpp:647: error: 'png_infop' was not declared in this scope src/_image.cpp:647: error: expected `;' before 'info_ptr' src/_image.cpp:648: error: aggregate 'png_color_8_struct sig_bit' has incomplete type and cannot be defined src/_image.cpp:649: error: 'png_uint_32' was not declared in this scope src/_image.cpp:649: error: expected `;' before 'row' src/_image.cpp:652: error: 'png_bytep' was not declared in this scope src/_image.cpp:652: error: 'row_pointers' was not declared in this scope src/_image.cpp:652: error: expected type-specifier before 'png_bytep' src/_image.cpp:652: error: expected `;' before 'png_bytep' src/_image.cpp:654: error: 'row' was not declared in this scope src/_image.cpp:660: error: type '&lt;type error&gt;' argument given to 'delete', expected pointer src/_image.cpp:665: error: 'png_ptr' was not declared in this scope src/_image.cpp:665: error: 'PNG_LIBPNG_VER_STRING' was not declared in this scope src/_image.cpp:665: error: 'png_create_write_struct' was not declared in this scope src/_image.cpp:669: error: type '&lt;type error&gt;' argument given to 'delete', expected pointer src/_image.cpp:673: error: 'info_ptr' was not declared in this scope src/_image.cpp:673: error: 'png_create_info_struct' was not declared in this scope src/_image.cpp:677: error: 'png_destroy_write_struct' was not declared in this scope src/_image.cpp:678: error: type '&lt;type error&gt;' argument given to 'delete', expected pointer src/_image.cpp:685: error: 'png_destroy_write_struct' was not declared in this scope src/_image.cpp:686: error: type '&lt;type error&gt;' argument given to 'delete', expected pointer src/_image.cpp:690: error: 'png_init_io' was not declared in this scope src/_image.cpp:693: error: 'PNG_COLOR_TYPE_RGB_ALPHA' was not declared in this scope src/_image.cpp:693: error: 'PNG_INTERLACE_NONE' was not declared in this scope src/_image.cpp:694: error: 'PNG_COMPRESSION_TYPE_BASE' was not declared in this scope src/_image.cpp:694: error: 'PNG_FILTER_TYPE_BASE' was not declared in this scope src/_image.cpp:694: error: 'png_set_IHDR' was not declared in this scope src/_image.cpp:703: error: 'png_set_sBIT' was not declared in this scope src/_image.cpp:705: error: 'png_write_info' was not declared in this scope src/_image.cpp:706: error: 'png_write_image' was not declared in this scope src/_image.cpp:707: error: 'png_write_end' was not declared in this scope src/_image.cpp:708: error: 'png_destroy_write_struct' was not declared in this scope src/_image.cpp:711: error: type '&lt;type error&gt;' argument given to 'delete', expected pointer src/_image.cpp: In member function 'Py::Object _image_module::readpng(const Py::Tuple&amp;)': src/_image.cpp:860: error: 'png_byte' was not declared in this scope src/_image.cpp:860: error: expected `;' before 'header' src/_image.cpp:866: error: 'header' was not declared in this scope src/_image.cpp:868: error: 'header' was not declared in this scope src/_image.cpp:868: error: 'png_sig_cmp' was not declared in this scope src/_image.cpp:873: error: 'png_structp' was not declared in this scope src/_image.cpp:873: error: expected `;' before 'png_ptr' src/_image.cpp:875: error: 'png_ptr' was not declared in this scope src/_image.cpp:878: error: 'png_infop' was not declared in this scope src/_image.cpp:878: error: expected `;' before 'info_ptr' src/_image.cpp:879: error: 'info_ptr' was not declared in this scope src/_image.cpp:882: error: 'png_ptr' was not declared in this scope src/_image.cpp:882: error: 'png_jmpbuf' was not declared in this scope src/_image.cpp:885: error: 'png_ptr' was not declared in this scope src/_image.cpp:885: error: 'png_init_io' was not declared in this scope src/_image.cpp:886: error: 'png_set_sig_bytes' was not declared in this scope src/_image.cpp:888: error: 'info_ptr' was not declared in this scope src/_image.cpp:888: error: 'png_read_info' was not declared in this scope src/_image.cpp:890: error: 'png_uint_32' was not declared in this scope src/_image.cpp:890: error: expected `;' before 'width' src/_image.cpp:891: error: expected `;' before 'height' src/_image.cpp:894: error: 'PNG_COLOR_TYPE_GRAY' was not declared in this scope src/_image.cpp:895: error: 'PNG_COLOR_TYPE_GRAY_ALPHA' was not declared in this scope src/_image.cpp:896: error: 'png_set_gray_to_rgb' was not declared in this scope src/_image.cpp:897: error: 'PNG_COLOR_TYPE_PALETTE' was not declared in this scope src/_image.cpp:898: error: 'png_set_palette_to_rgb' was not declared in this scope src/_image.cpp:902: error: 'png_set_strip_16' was not declared in this scope src/_image.cpp:905: error: 'png_set_interlace_handling' was not declared in this scope src/_image.cpp:906: error: 'png_read_update_info' was not declared in this scope src/_image.cpp:908: error: 'PNG_COLOR_TYPE_RGBA' was not declared in this scope src/_image.cpp:909: error: 'PNG_COLOR_TYPE_RGB' was not declared in this scope src/_image.cpp:915: error: 'png_jmpbuf' was not declared in this scope src/_image.cpp:918: error: 'png_bytep' was not declared in this scope src/_image.cpp:918: error: 'row_pointers' was not declared in this scope src/_image.cpp:918: error: expected type-specifier before 'png_bytep' src/_image.cpp:918: error: expected `;' before 'png_bytep' src/_image.cpp:919: error: expected `;' before 'row' src/_image.cpp:921: error: 'row' was not declared in this scope src/_image.cpp:921: error: 'height' was not declared in this scope src/_image.cpp:922: error: expected type-specifier before 'png_byte' src/_image.cpp:922: error: expected `;' before 'png_byte' src/_image.cpp:924: error: 'png_read_image' was not declared in this scope src/_image.cpp:929: error: 'height' was not declared in this scope src/_image.cpp:930: error: 'width' was not declared in this scope src/_image.cpp:936: error: expected `;' before 'y' src/_image.cpp:936: error: 'y' was not declared in this scope src/_image.cpp:938: error: expected `;' before 'x' src/_image.cpp:938: error: 'x' was not declared in this scope src/_image.cpp:940: error: 'ptr' was not declared in this scope src/_image.cpp:951: error: 'png_read_end' was not declared in this scope src/_image.cpp:952: error: 'png_infopp_NULL' was not declared in this scope src/_image.cpp:952: error: 'png_destroy_read_struct' was not declared in this scope src/_image.cpp:956: error: type '&lt;type error&gt;' argument given to 'delete', expected pointer error: command 'gcc' failed with exit status 1 </code></pre>
8
2009-10-15T05:45:29Z
1,570,514
<p>You don't need to compile from source: <code> sudo apt-get install python-matplotlib </code></p> <p>The easy way out.</p>
4
2009-10-15T05:53:33Z
[ "python", "installation", "matplotlib" ]
Displaying the Length of Individual Sequences in File
1,570,873
<p>I have a file that contains two sequences. I have a program that could read all sequences, combine them together, and display the length of both sequences together. Now I want to display the length individually. The two sequences are separated by the symbol <code>&gt;</code>.</p> <p>Example:</p> <pre><code>SEQ1 &gt;ATGGGACTAGCAGT SEQ2 &gt;AGGATGATGAGTGA </code></pre> <p>Program:</p> <pre><code>#!usr/bin/python import re fh=open('clostp1.fa','r') count=0 content=fh.readlines() fh.close() seq='' patt=re.compile('&gt;(.*?)') for item in content: m=patt.match(item) if not m: s=item.replace('\n','') seq=seq+s seq=seq.replace('\s','') print seq print 'The length of the coding sequence of the bacillus' print len(seq) </code></pre>
0
2009-10-15T07:48:41Z
1,570,897
<pre><code>for line in open("clostp1.fa"): name, sequence = map(str.strip,line.split('&gt;')) print "The length of %s is %s"%(name, len(sequence)) </code></pre>
4
2009-10-15T07:55:41Z
[ "python" ]
Displaying the Length of Individual Sequences in File
1,570,873
<p>I have a file that contains two sequences. I have a program that could read all sequences, combine them together, and display the length of both sequences together. Now I want to display the length individually. The two sequences are separated by the symbol <code>&gt;</code>.</p> <p>Example:</p> <pre><code>SEQ1 &gt;ATGGGACTAGCAGT SEQ2 &gt;AGGATGATGAGTGA </code></pre> <p>Program:</p> <pre><code>#!usr/bin/python import re fh=open('clostp1.fa','r') count=0 content=fh.readlines() fh.close() seq='' patt=re.compile('&gt;(.*?)') for item in content: m=patt.match(item) if not m: s=item.replace('\n','') seq=seq+s seq=seq.replace('\s','') print seq print 'The length of the coding sequence of the bacillus' print len(seq) </code></pre>
0
2009-10-15T07:48:41Z
1,570,937
<p>If I understood correctly, you want to print out each individual sequence followed by its length, right? I believe you just have a function to return the sequences and later do what ever yuo want with them.</p> <pre><code>#!usr/bin/python import re def get_content(file): """ Returns a dict with the name of the seq and its value """ result = {} for current_line in open(file): name, value = line.strip().split("&gt;") result[name] = value return result </code></pre> <p>You get the dict and then print what ever you need to print.</p>
1
2009-10-15T08:05:28Z
[ "python" ]
Displaying the Length of Individual Sequences in File
1,570,873
<p>I have a file that contains two sequences. I have a program that could read all sequences, combine them together, and display the length of both sequences together. Now I want to display the length individually. The two sequences are separated by the symbol <code>&gt;</code>.</p> <p>Example:</p> <pre><code>SEQ1 &gt;ATGGGACTAGCAGT SEQ2 &gt;AGGATGATGAGTGA </code></pre> <p>Program:</p> <pre><code>#!usr/bin/python import re fh=open('clostp1.fa','r') count=0 content=fh.readlines() fh.close() seq='' patt=re.compile('&gt;(.*?)') for item in content: m=patt.match(item) if not m: s=item.replace('\n','') seq=seq+s seq=seq.replace('\s','') print seq print 'The length of the coding sequence of the bacillus' print len(seq) </code></pre>
0
2009-10-15T07:48:41Z
1,570,969
<pre><code>for line in open("clostp1.fa"): name, _, seq = line.partition('&gt;') name, seq = name.rstrip(), seq.rstrip() print("The length of {} is {}".format(name, len(seq))) </code></pre> <p><code>partition</code> is more appropriate here then <code>split</code>. you need to <code>rstrip</code> each individual part, and formatting syntax will work in py3.1, use</p> <pre><code>print("The length of {0} is {1}".format(name, len(seq))) </code></pre> <p>to make it work in py2.6.</p>
0
2009-10-15T08:14:41Z
[ "python" ]
Displaying the Length of Individual Sequences in File
1,570,873
<p>I have a file that contains two sequences. I have a program that could read all sequences, combine them together, and display the length of both sequences together. Now I want to display the length individually. The two sequences are separated by the symbol <code>&gt;</code>.</p> <p>Example:</p> <pre><code>SEQ1 &gt;ATGGGACTAGCAGT SEQ2 &gt;AGGATGATGAGTGA </code></pre> <p>Program:</p> <pre><code>#!usr/bin/python import re fh=open('clostp1.fa','r') count=0 content=fh.readlines() fh.close() seq='' patt=re.compile('&gt;(.*?)') for item in content: m=patt.match(item) if not m: s=item.replace('\n','') seq=seq+s seq=seq.replace('\s','') print seq print 'The length of the coding sequence of the bacillus' print len(seq) </code></pre>
0
2009-10-15T07:48:41Z
1,570,983
<pre><code>import re pattern = re.compile('(?P&lt;seqname&gt;\w*)\s*&gt;\s*(?P&lt;seqval&gt;\w*)') for item in open('clostp1.fa','r').readlines(): m = pattern.match(item) if m: print "sequence name: %s - %s length" % (m.groupdict()['seqname'],len(m.groupdict()['seqval'])) </code></pre>
0
2009-10-15T08:17:51Z
[ "python" ]
Vim, Python and curses
1,571,032
<p>I wrote a small python script for vim that uses the curses library. When I try to call the function curses complains about:</p> <pre><code>Traceback (most recent call last): File "&lt;string&gt;", line 9, in &lt;module&gt; File "/usr/lib/python2.6/curses/__init__.py", line 33, in initscr fd=_sys.__stdout__.fileno()) _curses.error: setupterm: could not find terminal </code></pre> <p>Don't know how to solve this</p> <p>Edit: GVIM complains Vim works fine</p>
0
2009-10-15T08:28:42Z
1,571,170
<p>I'm not very sure about the context, but "GVIM complains Vim works fine" is very insightful: curses are used in the console, gvim is run in a X window, thus there's no console.</p>
6
2009-10-15T09:06:42Z
[ "python", "vim", "curses" ]
Choose Python version for egg installation or install parallel versions of site-package
1,571,047
<p>Via <code>fink install</code> I put the following Python version on my Mac OS X computer:</p> <ul> <li><code>python2.3</code>,</li> <li><code>python2.4</code>,</li> <li><code>python2.5</code>,</li> <li><code>python2.6</code>.</li> </ul> <p>Further, <code>python</code> is alias for <code>python2.6</code> on my system.</p> <ol> <li><p>I want to install an <a href="http://mxm-mad-science.blogspot.com/2008/02/python-eggs-simple-introduction.html" rel="nofollow">egg</a>, e.g. <code>easy_install networkx-0.36-py2.5.egg</code>, where I have to use python 2.5 instead of version 2.6. Is this possible without changing the <code>python</code> alias?</p></li> <li><p>Can you tell me, whether and how I can install <code>networkx-0.36-py2.5</code> and <code>networkx-1.0rc1-py2.6</code> in parallel?</p></li> <li><p>How can I install a site-package in a way, that it is available for different Python versions?</p></li> </ol>
2
2009-10-15T08:30:26Z
1,571,104
<p><strong>Edit:</strong> Read <a href="http://stackoverflow.com/questions/1571047/choose-python-version-for-egg-installation-install-parallel-versions-of-site-pa/1571477#1571477">Ned Deily's answer</a> before you read this one</p> <p><hr /></p> <p><strong>1.</strong></p> <p>On my system I have different easy_install script for each python version:</p> <ul> <li>/usr/bin/easy_install-2.5</li> <li>/usr/bin/easy_install-2.6</li> </ul> <p>The contents of the 2.6 version looks like this:</p> <pre><code>#!/System/Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python import sys sys.argv[0] = sys.argv[0].replace('-2.6', '') # EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==0.6c9','console_scripts','easy_install' __requires__ = 'setuptools==0.6c9' import sys from pkg_resources import load_entry_point sys.exit( load_entry_point('setuptools==0.6c9', 'console_scripts', 'easy_install')() ) </code></pre> <p>Now, if you not already have those scripts on you machine, you could create those by using the above as template. Just change the first line so it points to the right python interpreter. Probably something like:</p> <pre><code>#!/sw/bin/python23 </code></pre> <p>And change the third line to match the current script name; meaning, if the script is called easy_install-2.3, then it should look like this:</p> <pre><code>sys.argv[0] = sys.argv[0].replace('-2.3', '') </code></pre> <p>And of course if you are not using setuptools version 0.6c9 than you will have to change this, too.</p> <p><hr /></p> <p>An alternative is to run the easy_install script as an argument of the right python version. Like this:</p> <pre><code>$ python23 /some/path/easy_install networkx-0.36-py2.5.egg </code></pre> <p><strong>2.</strong></p> <p>Each python version has a different site-lib, so they are independent from each other. You can install different modules and versions for different python versions</p> <p><strong>3.</strong></p> <p>You could make the env variable PYTHONPATH point to a common directory or add a common directory to <em>sys.path</em> in your scripts. But be aware that some modules work only with certain python versions and include C code that has to be compiled for each python version...</p>
2
2009-10-15T08:46:46Z
[ "python", "easy-install", "egg" ]
Choose Python version for egg installation or install parallel versions of site-package
1,571,047
<p>Via <code>fink install</code> I put the following Python version on my Mac OS X computer:</p> <ul> <li><code>python2.3</code>,</li> <li><code>python2.4</code>,</li> <li><code>python2.5</code>,</li> <li><code>python2.6</code>.</li> </ul> <p>Further, <code>python</code> is alias for <code>python2.6</code> on my system.</p> <ol> <li><p>I want to install an <a href="http://mxm-mad-science.blogspot.com/2008/02/python-eggs-simple-introduction.html" rel="nofollow">egg</a>, e.g. <code>easy_install networkx-0.36-py2.5.egg</code>, where I have to use python 2.5 instead of version 2.6. Is this possible without changing the <code>python</code> alias?</p></li> <li><p>Can you tell me, whether and how I can install <code>networkx-0.36-py2.5</code> and <code>networkx-1.0rc1-py2.6</code> in parallel?</p></li> <li><p>How can I install a site-package in a way, that it is available for different Python versions?</p></li> </ol>
2
2009-10-15T08:30:26Z
1,571,477
<p><code>easy_install</code> is part of the <code>setuptools</code> package. <code>Fink</code> has separate <code>setuptools</code> packages for python 2.5 and python 2.6:</p> <pre><code>fink install setuptools-py25 setuptools-py26 </code></pre> <p>You can then download and install <code>networkx</code> to both versions:</p> <pre><code>/sw/bin/easy_install-2.5 networkx /sw/bin/easy_install-2.6 networkx </code></pre> <p>If you need a particular version of the package:</p> <pre><code>/sw/bin/easy_install-2.5 networkx==0.36 /sw/bin/easy_install-2.6 networkx==0.36 </code></pre>
4
2009-10-15T10:18:46Z
[ "python", "easy-install", "egg" ]
Boost.Python - How to return by reference?
1,571,054
<p>I'm using Boost.Python to create Python modules from C++ classes. And I ran into a problem with references.</p> <p>Condider the following case where I have a class Foo with overloaded get methods that can either return by value or reference.</p> <p>Specifying that the return by value should be used was easy once I typedefed a signature. But I think it should be possible return a reference as well by using a <code>return_value_policy</code>. However, using what seemed appropriate (<a href="http://www.boost.org/doc/libs/1%5F40%5F0/libs/python/doc/v2/reference%5Fexisting%5Fobject.html">doc</a>); <code>return_value_policy&lt;reference_existing_object&gt;</code> did not seem to work. </p> <p>Have I misunderstood what it does?</p> <pre><code>struct Foo { Foo(float x) { _x = x; } float&amp; get() { return _x; } float get() const { return _x; } private: float _x; }; // Wrapper code BOOST_PYTHON_MODULE(my_module) { using namespace boost::python; typedef float (Foo::*get_by_value)() const; typedef float&amp; (Foo::*get_by_ref)(); class_&lt;Foo&gt;("Foo", init&lt;float&gt;()) .def("get", get_by_value(&amp;Foo::get)) .def("get_ref", get_by_ref(&amp;Foo::get), return_value_policy&lt;reference_existing_object&gt;())//Doesn't work ; } </code></pre> <p>Note: I know it could be dangerous to reference existing object without life-time managing.</p> <p><strong>Update:</strong><br /> It looks like it works for objects but not basic data types.<br /> Take this revised example:</p> <pre><code>struct Foo { Foo(float x) { _x = x; } float&amp; get() { return _x; } float get() const { return _x; } void set( float f ){ _x = f;} Foo&amp; self(){return *this;} private: float _x; }; // Wrapper code using namespace boost::python; BOOST_PYTHON_MODULE(my_module) { typedef float (Foo::*get_by_value)() const; class_&lt;Foo&gt;("Foo", init&lt;float&gt;()) .def("get", get_by_value(&amp;Foo::get)) .def("get_self", &amp;Foo::self, return_value_policy&lt;reference_existing_object&gt;()) .def("set", &amp;Foo::set); ; } </code></pre> <p>Which in a test gave the expected result:</p> <pre><code>&gt;&gt;&gt; foo1 = Foo(123) &gt;&gt;&gt; foo1.get() 123.0 &gt;&gt;&gt; foo2 = foo1.get_self() &gt;&gt;&gt; foo2.set(1) &gt;&gt;&gt; foo1.get() 1.0 &gt;&gt;&gt; id(foo1) == id(foo2) False </code></pre>
8
2009-10-15T08:31:54Z
1,571,163
<p>I don't know much about Boost.Python, so I may misunderstand the question, in which case this is completely unhelpful. But here goes:</p> <p>In Python you can't choose between returning by reference or by value, the distinction doesn't make sense in Python. I find it's easiest to think of it as everything being handled by reference. </p> <p>You just have objects, and you have names for those objects. So</p> <pre><code>foo = "ryiuy" </code></pre> <p>Creates the string object "ryiuy" and then lets you refer to that string object with the name "foo". So in Python, when you get passed something, you get passed that object. There is no "values" as such, so you can't pass the value. But then again, it's also a valid viewpoint that there aren't references either, just objects and their names.</p> <p>So the answer is, I guess, is that when you get a reference in C, you need to pass a reference to the object that reference references into Python. And when you get a value in C, you need to pass a reference to the object that you create from that value into Python.</p>
0
2009-10-15T09:04:48Z
[ "python", "boost", "boost-python" ]
Boost.Python - How to return by reference?
1,571,054
<p>I'm using Boost.Python to create Python modules from C++ classes. And I ran into a problem with references.</p> <p>Condider the following case where I have a class Foo with overloaded get methods that can either return by value or reference.</p> <p>Specifying that the return by value should be used was easy once I typedefed a signature. But I think it should be possible return a reference as well by using a <code>return_value_policy</code>. However, using what seemed appropriate (<a href="http://www.boost.org/doc/libs/1%5F40%5F0/libs/python/doc/v2/reference%5Fexisting%5Fobject.html">doc</a>); <code>return_value_policy&lt;reference_existing_object&gt;</code> did not seem to work. </p> <p>Have I misunderstood what it does?</p> <pre><code>struct Foo { Foo(float x) { _x = x; } float&amp; get() { return _x; } float get() const { return _x; } private: float _x; }; // Wrapper code BOOST_PYTHON_MODULE(my_module) { using namespace boost::python; typedef float (Foo::*get_by_value)() const; typedef float&amp; (Foo::*get_by_ref)(); class_&lt;Foo&gt;("Foo", init&lt;float&gt;()) .def("get", get_by_value(&amp;Foo::get)) .def("get_ref", get_by_ref(&amp;Foo::get), return_value_policy&lt;reference_existing_object&gt;())//Doesn't work ; } </code></pre> <p>Note: I know it could be dangerous to reference existing object without life-time managing.</p> <p><strong>Update:</strong><br /> It looks like it works for objects but not basic data types.<br /> Take this revised example:</p> <pre><code>struct Foo { Foo(float x) { _x = x; } float&amp; get() { return _x; } float get() const { return _x; } void set( float f ){ _x = f;} Foo&amp; self(){return *this;} private: float _x; }; // Wrapper code using namespace boost::python; BOOST_PYTHON_MODULE(my_module) { typedef float (Foo::*get_by_value)() const; class_&lt;Foo&gt;("Foo", init&lt;float&gt;()) .def("get", get_by_value(&amp;Foo::get)) .def("get_self", &amp;Foo::self, return_value_policy&lt;reference_existing_object&gt;()) .def("set", &amp;Foo::set); ; } </code></pre> <p>Which in a test gave the expected result:</p> <pre><code>&gt;&gt;&gt; foo1 = Foo(123) &gt;&gt;&gt; foo1.get() 123.0 &gt;&gt;&gt; foo2 = foo1.get_self() &gt;&gt;&gt; foo2.set(1) &gt;&gt;&gt; foo1.get() 1.0 &gt;&gt;&gt; id(foo1) == id(foo2) False </code></pre>
8
2009-10-15T08:31:54Z
1,571,421
<p>Are you sure that the c++ object is being copied? You will get a new python object each time but which references the same c++ object. How are you determining that the object has been copied?</p>
0
2009-10-15T10:07:14Z
[ "python", "boost", "boost-python" ]
Boost.Python - How to return by reference?
1,571,054
<p>I'm using Boost.Python to create Python modules from C++ classes. And I ran into a problem with references.</p> <p>Condider the following case where I have a class Foo with overloaded get methods that can either return by value or reference.</p> <p>Specifying that the return by value should be used was easy once I typedefed a signature. But I think it should be possible return a reference as well by using a <code>return_value_policy</code>. However, using what seemed appropriate (<a href="http://www.boost.org/doc/libs/1%5F40%5F0/libs/python/doc/v2/reference%5Fexisting%5Fobject.html">doc</a>); <code>return_value_policy&lt;reference_existing_object&gt;</code> did not seem to work. </p> <p>Have I misunderstood what it does?</p> <pre><code>struct Foo { Foo(float x) { _x = x; } float&amp; get() { return _x; } float get() const { return _x; } private: float _x; }; // Wrapper code BOOST_PYTHON_MODULE(my_module) { using namespace boost::python; typedef float (Foo::*get_by_value)() const; typedef float&amp; (Foo::*get_by_ref)(); class_&lt;Foo&gt;("Foo", init&lt;float&gt;()) .def("get", get_by_value(&amp;Foo::get)) .def("get_ref", get_by_ref(&amp;Foo::get), return_value_policy&lt;reference_existing_object&gt;())//Doesn't work ; } </code></pre> <p>Note: I know it could be dangerous to reference existing object without life-time managing.</p> <p><strong>Update:</strong><br /> It looks like it works for objects but not basic data types.<br /> Take this revised example:</p> <pre><code>struct Foo { Foo(float x) { _x = x; } float&amp; get() { return _x; } float get() const { return _x; } void set( float f ){ _x = f;} Foo&amp; self(){return *this;} private: float _x; }; // Wrapper code using namespace boost::python; BOOST_PYTHON_MODULE(my_module) { typedef float (Foo::*get_by_value)() const; class_&lt;Foo&gt;("Foo", init&lt;float&gt;()) .def("get", get_by_value(&amp;Foo::get)) .def("get_self", &amp;Foo::self, return_value_policy&lt;reference_existing_object&gt;()) .def("set", &amp;Foo::set); ; } </code></pre> <p>Which in a test gave the expected result:</p> <pre><code>&gt;&gt;&gt; foo1 = Foo(123) &gt;&gt;&gt; foo1.get() 123.0 &gt;&gt;&gt; foo2 = foo1.get_self() &gt;&gt;&gt; foo2.set(1) &gt;&gt;&gt; foo1.get() 1.0 &gt;&gt;&gt; id(foo1) == id(foo2) False </code></pre>
8
2009-10-15T08:31:54Z
2,009,000
<p>I think you want <a href="http://www.boost.org/doc/libs/1_38_0/libs/python/doc/v2/return_internal_reference.html" rel="nofollow">return internal reference</a> instead. I have used it before to do something similar.</p>
2
2010-01-05T20:49:08Z
[ "python", "boost", "boost-python" ]
Boost.Python - How to return by reference?
1,571,054
<p>I'm using Boost.Python to create Python modules from C++ classes. And I ran into a problem with references.</p> <p>Condider the following case where I have a class Foo with overloaded get methods that can either return by value or reference.</p> <p>Specifying that the return by value should be used was easy once I typedefed a signature. But I think it should be possible return a reference as well by using a <code>return_value_policy</code>. However, using what seemed appropriate (<a href="http://www.boost.org/doc/libs/1%5F40%5F0/libs/python/doc/v2/reference%5Fexisting%5Fobject.html">doc</a>); <code>return_value_policy&lt;reference_existing_object&gt;</code> did not seem to work. </p> <p>Have I misunderstood what it does?</p> <pre><code>struct Foo { Foo(float x) { _x = x; } float&amp; get() { return _x; } float get() const { return _x; } private: float _x; }; // Wrapper code BOOST_PYTHON_MODULE(my_module) { using namespace boost::python; typedef float (Foo::*get_by_value)() const; typedef float&amp; (Foo::*get_by_ref)(); class_&lt;Foo&gt;("Foo", init&lt;float&gt;()) .def("get", get_by_value(&amp;Foo::get)) .def("get_ref", get_by_ref(&amp;Foo::get), return_value_policy&lt;reference_existing_object&gt;())//Doesn't work ; } </code></pre> <p>Note: I know it could be dangerous to reference existing object without life-time managing.</p> <p><strong>Update:</strong><br /> It looks like it works for objects but not basic data types.<br /> Take this revised example:</p> <pre><code>struct Foo { Foo(float x) { _x = x; } float&amp; get() { return _x; } float get() const { return _x; } void set( float f ){ _x = f;} Foo&amp; self(){return *this;} private: float _x; }; // Wrapper code using namespace boost::python; BOOST_PYTHON_MODULE(my_module) { typedef float (Foo::*get_by_value)() const; class_&lt;Foo&gt;("Foo", init&lt;float&gt;()) .def("get", get_by_value(&amp;Foo::get)) .def("get_self", &amp;Foo::self, return_value_policy&lt;reference_existing_object&gt;()) .def("set", &amp;Foo::set); ; } </code></pre> <p>Which in a test gave the expected result:</p> <pre><code>&gt;&gt;&gt; foo1 = Foo(123) &gt;&gt;&gt; foo1.get() 123.0 &gt;&gt;&gt; foo2 = foo1.get_self() &gt;&gt;&gt; foo2.set(1) &gt;&gt;&gt; foo1.get() 1.0 &gt;&gt;&gt; id(foo1) == id(foo2) False </code></pre>
8
2009-10-15T08:31:54Z
2,119,543
<p>In Python, there's the concept of <em>immutable types</em>. An immutable types can't have its value changed. Examples of built-in immutable types are int, float and str.</p> <p>Having said that, you can't do what you want with <code>boost::python</code>, because Python itself does not allow you to change the value of the float returned by the function. </p> <p>Your second example shows one solution, another would be to create thin-wrappers and exposing that:</p> <pre><code>void Foo_set_x(Foo&amp; self, float value) { self.get() = value; } class_&lt;Foo&gt;("Foo", init&lt;float&gt;()) ... .def("set", &amp;Foo_set_x); ; </code></pre> <p>Which is a better solution than having to change the original C++ class.</p>
6
2010-01-22T18:33:31Z
[ "python", "boost", "boost-python" ]
ActiveMQ : Use Django Auth with Stomp
1,571,224
<p>I am working on <a href="http://blog.gridspy.co.nz/2009/09/introducing-the-nexus.html" rel="nofollow">power monitoring</a> and want to send live power data to authorised users only. Some users have opted to install power sensors in their houses, others are viewing those sensors. Each sensor sends samples to a <a href="http://twistedmatrix.com/" rel="nofollow">Twisted</a> backend - the goal is to have this backend forward the data to Javascript running in the browser.</p> <p>My current solution to forwarding the data is an <a href="http://orbited.org/" rel="nofollow">Orbited</a> server and an instance of <a href="http://www.morbidq.com/" rel="nofollow">MorbidQ</a> (MorbidQ is a Stomp server). Each building in my system (<a href="http://your.gridspy.co.nz/powertech/" rel="nofollow">example here</a>) has its own channel for updates. The twisted backend broadcasts the data through the MorbidQ channel to anyone watching, but anyone can watch. There is an entry on my blog about <a href="http://blog.gridspy.co.nz/2009/10/realtime-data-from-sensors-to-browsers.html" rel="nofollow">the data flow from sensor to site</a></p> <p><strong>For many buildings, I only want a couple of users to be able to see live data in a given building. I would like to use Django Auth if possible, or some sort of workaround if not.</strong></p> <p>What is the easiest way to secure these channels per user? Can I use Django Auth? Should I use RabbitMQ or ActiveMQ instead of MorbidQ? What measures can I take to keep this solution secure?</p> <p>For coding I am most confident in C++ and Python.</p> <p>Thanks!</p>
4
2009-10-15T09:22:49Z
1,575,334
<p>If you use the restq extensions for morbidq, you can have it send an http callback to your application every time the user attempts to connect. (See <a href="http://www.morbidq.com/trac/wiki/RestQ" rel="nofollow">http://www.morbidq.com/trac/wiki/RestQ</a> ). Your django app can then just return yes or no to the connect attempt (after it runs though some auth procedure.)</p>
1
2009-10-15T21:56:47Z
[ "python", "django", "stomp", "orbited" ]
ActiveMQ : Use Django Auth with Stomp
1,571,224
<p>I am working on <a href="http://blog.gridspy.co.nz/2009/09/introducing-the-nexus.html" rel="nofollow">power monitoring</a> and want to send live power data to authorised users only. Some users have opted to install power sensors in their houses, others are viewing those sensors. Each sensor sends samples to a <a href="http://twistedmatrix.com/" rel="nofollow">Twisted</a> backend - the goal is to have this backend forward the data to Javascript running in the browser.</p> <p>My current solution to forwarding the data is an <a href="http://orbited.org/" rel="nofollow">Orbited</a> server and an instance of <a href="http://www.morbidq.com/" rel="nofollow">MorbidQ</a> (MorbidQ is a Stomp server). Each building in my system (<a href="http://your.gridspy.co.nz/powertech/" rel="nofollow">example here</a>) has its own channel for updates. The twisted backend broadcasts the data through the MorbidQ channel to anyone watching, but anyone can watch. There is an entry on my blog about <a href="http://blog.gridspy.co.nz/2009/10/realtime-data-from-sensors-to-browsers.html" rel="nofollow">the data flow from sensor to site</a></p> <p><strong>For many buildings, I only want a couple of users to be able to see live data in a given building. I would like to use Django Auth if possible, or some sort of workaround if not.</strong></p> <p>What is the easiest way to secure these channels per user? Can I use Django Auth? Should I use RabbitMQ or ActiveMQ instead of MorbidQ? What measures can I take to keep this solution secure?</p> <p>For coding I am most confident in C++ and Python.</p> <p>Thanks!</p>
4
2009-10-15T09:22:49Z
8,414,003
<p>Reviving an old thread: MorbidQ is not meant for production use AFAIK. ActiveMQ is a much more robust beast and provides much better ways to handle user-based authentication. I wrote <a href="http://pythonware.blogspot.com/2011/12/user-based-authentication-using-orbited.html" rel="nofollow">this</a> back in 2010 which deals with static user authentication - but ActiveMQ allows you to pass a dynamic list of users for authentication, which can come from whichever backend the application has available. The post I mentioned above does not deal with it, but a little digging into the ActiveMQ authentication/security manual section (plus some Java knowledge) can enable a pretty nasty setup for such use. If LDAP is available, even better.</p>
1
2011-12-07T10:41:29Z
[ "python", "django", "stomp", "orbited" ]
converting strptime into 'X hours ago'
1,571,272
<p>I have a a date in strptime that I want to show as 'X hours ago'. I can happily convert hours into days and weeks etc. but I don't know how to do the initial sum. Here is how I'm converting the string into strptime:</p> <pre><code>time.strptime(obj.created_at, '%a %b %d %H:%M:%S +0000 %Y') </code></pre> <p>p.s. bonus points for figuring out why it won't take %z for '+0000' - am I completely wrong about what this is?</p>
1
2009-10-15T09:34:59Z
1,571,293
<p>It seems the <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#timesince" rel="nofollow"><code>timesince</code></a> in Django could help you out without you having to convert. The source for <code>timesince</code> is available <a href="http://code.djangoproject.com/browser/django/trunk/django/utils/timesince.py" rel="nofollow">here</a>.</p>
3
2009-10-15T09:38:51Z
[ "python", "timestamp", "strptime" ]
converting strptime into 'X hours ago'
1,571,272
<p>I have a a date in strptime that I want to show as 'X hours ago'. I can happily convert hours into days and weeks etc. but I don't know how to do the initial sum. Here is how I'm converting the string into strptime:</p> <pre><code>time.strptime(obj.created_at, '%a %b %d %H:%M:%S +0000 %Y') </code></pre> <p>p.s. bonus points for figuring out why it won't take %z for '+0000' - am I completely wrong about what this is?</p>
1
2009-10-15T09:34:59Z
1,571,391
<p>Can you use datetime instead? (Or convert whatever you have into datetime?)</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; created_at = datetime.datetime(2009,10,15, 13) &gt;&gt;&gt; now = datetime.datetime.now() &gt;&gt;&gt; delta = now - created_at &gt;&gt;&gt; hours_ago = '%d Hours Ago' % (delta.seconds/60/60) &gt;&gt;&gt; hours_ago '5 Hours Ago' </code></pre>
0
2009-10-15T10:01:02Z
[ "python", "timestamp", "strptime" ]
converting strptime into 'X hours ago'
1,571,272
<p>I have a a date in strptime that I want to show as 'X hours ago'. I can happily convert hours into days and weeks etc. but I don't know how to do the initial sum. Here is how I'm converting the string into strptime:</p> <pre><code>time.strptime(obj.created_at, '%a %b %d %H:%M:%S +0000 %Y') </code></pre> <p>p.s. bonus points for figuring out why it won't take %z for '+0000' - am I completely wrong about what this is?</p>
1
2009-10-15T09:34:59Z
1,572,956
<p>The <code>datetime</code> module is definitely easier to use, but, if you insist, you can do it with the <code>time</code> module instead. I.e.:</p> <pre><code>&gt;&gt;&gt; import time &gt;&gt;&gt; fmt = '%a %b %d %H:%M:%S +0000 %Y' &gt;&gt;&gt; time.strftime(fmt) 'Thu Oct 15 07:54:07 +0000 2009' &gt;&gt;&gt; createdat = 'Thu Oct 15 02:30:30 +0000 2009' &gt;&gt;&gt; createdtim = time.strptime(createdat, fmt) &gt;&gt;&gt; hoursago = (time.time() - time.mktime(createdtim)) / 3600 &gt;&gt;&gt; print hoursago 5.42057559947 </code></pre> <p>One reason the <code>time</code> module is so pesky to use is that it uses two different ways to represent time -- one is a 9-tuple (and that's what you get from <code>strptime</code>), and one is a float "seconds since the epoch" (and that's what you need to do differences); the <code>mktime</code> function translates the former to the latter. Difference in hours is clearly 1/3600 of the difference in seconds -- you'll have to decide how to display a typically-fractionary "number of hours ago", of course (hour and fraction with some digits, or, round to closest integer number of hours, or what else).</p> <p>The literal '+0000' in your format, for <code>strptime</code>, means you expect and ignore those literal characters at that spot in your "createdat" string (normally you'd have a timezone offset specifier there). If that's indeed what you want, then you have the right format string!</p>
2
2009-10-15T15:01:37Z
[ "python", "timestamp", "strptime" ]
Can a dictionary be passed to django models on create?
1,571,570
<p>Is is possible to do something similar to this with a list, dictionary or something else even?</p> <pre><code>data_dict = { 'title' : 'awesome title', 'body' : 'great body of text', } Model.objects.create(data_dict) </code></pre> <p>Even better if I can extend it</p> <pre><code>Model.objects.create(data_dict, extra='hello', extra2='world) </code></pre>
55
2009-10-15T10:41:29Z
1,571,593
<p>If <code>title</code> and <code>body</code> are fields in your model, then <a href="http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists">you can deliver the keyword arguments in your dictionary using the ** operator</a>.</p> <p>Assuming your model is called <code>MyModel</code>:</p> <pre><code># create instance of model m = MyModel(**data_dict) # don't forget to save to database! m.save() </code></pre> <p>As for your second question, the dictionary has to be the final argument. Again, <code>extra</code> and <code>extra2</code> should be fields in the model.</p> <pre><code>m2 =MyModel(extra='hello', extra2='world', **data_dict) m2.save() </code></pre>
110
2009-10-15T10:49:09Z
[ "python", "django", "django-models", "dictionary" ]
Can a dictionary be passed to django models on create?
1,571,570
<p>Is is possible to do something similar to this with a list, dictionary or something else even?</p> <pre><code>data_dict = { 'title' : 'awesome title', 'body' : 'great body of text', } Model.objects.create(data_dict) </code></pre> <p>Even better if I can extend it</p> <pre><code>Model.objects.create(data_dict, extra='hello', extra2='world) </code></pre>
55
2009-10-15T10:41:29Z
32,898,403
<p>Not directly an answer to the question, but I find this code helped me create the dicts that save nicely into the correct answer. The type conversions made are required if this data will be exported to json.</p> <p>I hope this helps:</p> <pre><code> #mod is a django database model instance def toDict( mod ): import datetime from decimal import Decimal import re #Go through the object, load in the objects we want obj = {} for key in mod.__dict__: if re.search('^_', key): continue #Copy my data if isinstance( mod.__dict__[key], datetime.datetime ): obj[key] = int(calendar.timegm( ts.utctimetuple(mod.__dict__[key]))) elif isinstance( mod.__dict__[key], Decimal ): obj[key] = float( mod.__dict__[key] ) else: obj[key] = mod.__dict__[key] return obj def toCsv( mod, fields, delim=',' ): import datetime from decimal import Decimal #Dump the items raw = [] for key in fields: if key not in mod.__dict__: continue #Copy my data if isinstance( mod.__dict__[key], datetime.datetime ): raw.append( str(calendar.timegm( ts.utctimetuple(mod.__dict__[key]))) ) elif isinstance( mod.__dict__[key], Decimal ): raw.append( str(float( mod.__dict__[key] ))) else: raw.append( str(mod.__dict__[key]) ) return delim.join( raw ) </code></pre>
1
2015-10-01T23:36:23Z
[ "python", "django", "django-models", "dictionary" ]
XML-RPC server with better error reporting
1,571,598
<p>Standard libraries (<code>xmlrpclib</code>+<code>SimpleXMLRPCServer</code> in Python 2 and <code>xmlrpc.server</code> in Python 3) report all errors (including usage errors) as python exceptions which is not suitable for public services: exception strings are often not easy understandable without python knowledge and might expose some sensitive information. It's not hard to fix this, but I prefer to avoid reinventing the wheel. Is there a third party library with better error reporting? I'm interested in good fault messages for all usage errors and hiding internals when reporting internal errors (this is better done with logging).</p> <p><code>xmlrpclib</code> already have the constants for such errors: <code>NOT_WELLFORMED_ERROR</code>, <code>UNSUPPORTED_ENCODING</code>, <code>INVALID_ENCODING_CHAR</code>, <code>INVALID_XMLRPC</code>, <code>METHOD_NOT_FOUND</code>, <code>INVALID_METHOD_PARAMS</code>, <code>INTERNAL_ERROR</code>.</p>
1
2009-10-15T10:50:52Z
1,608,160
<p>I don't think you have a library specific problem. When using any library or framework you typically want to trap all errors, log them somewhere, and throw up "Oops, we're having problems. You may want to contact us at x@x.com with error number 100 and tell us what you did." So wrap your failable entry points in try/catches, create a generic logger and off you go...</p>
1
2009-10-22T15:47:13Z
[ "python", "xml-rpc" ]
XML-RPC server with better error reporting
1,571,598
<p>Standard libraries (<code>xmlrpclib</code>+<code>SimpleXMLRPCServer</code> in Python 2 and <code>xmlrpc.server</code> in Python 3) report all errors (including usage errors) as python exceptions which is not suitable for public services: exception strings are often not easy understandable without python knowledge and might expose some sensitive information. It's not hard to fix this, but I prefer to avoid reinventing the wheel. Is there a third party library with better error reporting? I'm interested in good fault messages for all usage errors and hiding internals when reporting internal errors (this is better done with logging).</p> <p><code>xmlrpclib</code> already have the constants for such errors: <code>NOT_WELLFORMED_ERROR</code>, <code>UNSUPPORTED_ENCODING</code>, <code>INVALID_ENCODING_CHAR</code>, <code>INVALID_XMLRPC</code>, <code>METHOD_NOT_FOUND</code>, <code>INVALID_METHOD_PARAMS</code>, <code>INTERNAL_ERROR</code>.</p>
1
2009-10-15T10:50:52Z
1,608,496
<p>It look like there is no ready library with my requirements, so a ended up with own implementation:</p> <pre><code>class ApplicationError(Fault): def __init__(self, exc_info): Fault.__init__(self, xmlrpclib.APPLICATION_ERROR, u'Application internal error') class NotWellformedError(Fault): def __init__(self, exc): Fault.__init__(self, xmlrpclib.NOT_WELLFORMED_ERROR, str(exc)) class UnsupportedEncoding(Fault): def __init__(self, exc): Fault.__init__(self, xmlrpclib.UNSUPPORTED_ENCODING, str(exc)) # XXX INVALID_ENCODING_CHAR is masked by xmlrpclib, so the error code will be # INVALID_XMLRPC. class InvalidRequest(Fault): def __init__(self, message): ault.__init__(self, xmlrpclib.INVALID_XMLRPC, message) class MethodNotFound(Fault): def __init__(self, name): Fault.__init__(self, xmlrpclib.METHOD_NOT_FOUND, u'Method %r is not supported' % name) class WrongMethodUsage(Fault): def __init__(self, message): Fault.__init__(self, xmlrpclib.INVALID_METHOD_PARAMS, message) class WrongType(Fault): def __init__(self, arg_name, type_name): Fault.__init__(self, xmlrpclib.INVALID_METHOD_PARAMS, u'Parameter %s must be %s' % (arg_name, type_name)) class XMLRPCDispatcher(SimpleXMLRPCDispatcher, XMLRPCDocGenerator): server_name = server_title = 'Personalization center RPC interface' server_documentation = 'Available methods' def __init__(self, methods): SimpleXMLRPCDispatcher.__init__(self, allow_none=True, encoding=None) self.register_instance(methods) self.register_multicall_functions() #self.register_introspection_functions() def _dispatch(self, method_name, args): if self.funcs.has_key(method_name): method = self.funcs[method_name] else: method = self.instance._getMethod(method_name) arg_names, args_name, kwargs_name, defaults = \ inspect.getargspec(method) assert arg_names[0]=='self' arg_names = arg_names[1:] n_args = len(args) if not (args_name or defaults): if n_args!=len(arg_names): raise WrongMethodUsage( u'Method %s takes exactly %d parameters (%d given)' % \ (method_name, len(arg_names), n_args)) else: min_args = len(arg_names)-len(defaults) if len(args)&lt;min_args: raise WrongMethodUsage( u'Method %s requires at least %d parameters (%d given)' % \ (method_name, min_args, n_args)) if not args_name and n_args&gt;len(arg_names): raise WrongMethodUsage( u'Method %s requires at most %d parameters (%d given)' % \ (method_name, len(arg_names), n_args)) try: return method(*args) except Fault: raise except: logger.exception('Application internal error for %s%r', method_name, args) raise ApplicationError(sys.exc_info()) def dispatch(self, data): try: try: args, method_name = xmlrpclib.loads(data) except ExpatError, exc: raise NotWellformedError(exc) except LookupError, exc: raise UnsupportedEncoding(exc) except xmlrpclib.ResponseError: raise InvalidRequest('Request structure is invalid') method_name = method_name.encode('ascii', 'replace') result = self._dispatch(method_name, args) except Fault, exc: logger.warning('Fault %s: %s', exc.faultCode, exc.faultString) return xmlrpclib.dumps(exc) else: try: return xmlrpclib.dumps((result,), methodresponse=1) except: logger.exception('Application internal error when marshalling'\ ' result for %s%r', method_name, args) return xmlrpclib.dumps(ApplicationError(sys.exc_info())) class InterfaceMethods: def _getMethod(self, name): if name.startswith('_'): raise MethodNotFound(name) try: method = getattr(self, name) except AttributeError: raise MethodNotFound(name) if not inspect.ismethod(method): raise MethodNotFound(name) return method </code></pre>
1
2009-10-22T16:43:41Z
[ "python", "xml-rpc" ]
Iterating through a list in Python
1,571,651
<p>I am trying to iterate through a list and take each part of the list, encode it and join the result up when it is all done. As an example, I have a string which produces a list with each element being 16 characters in length.</p> <pre><code>message = (u'sixteen-letters.sixteen-letters.sixteen-letters.sixteen-letters.') result = split16(message, 16) msg = ';'.join(encode(result.pop(0)) for i in result) </code></pre> <p>The encode function takes a 16 byte string and returns the result. However with the way it is written, it only encodes half of the elements in the list.</p> <p>If I try comprehension:</p> <pre><code>result = [encode(split16(message, 16) for message in list_of_messages)] result = ''.join(result) </code></pre> <p>It results in the whole list being sent at once. What I need to do is send each element to the encode function separately, get the result then join them together.</p> <p>Is there an easy way of achieving this?</p>
0
2009-10-15T11:04:21Z
1,571,664
<p>Are you trying to do something like this?</p> <pre><code>';'.join(encode(i) for i in message.split('.')) </code></pre> <p>of course it could be just </p> <pre><code>';'.join(encode(i) for i in result) </code></pre> <p>if your <code>split16</code> function complicated enough.</p>
1
2009-10-15T11:06:53Z
[ "python", "list", "list-comprehension" ]
Iterating through a list in Python
1,571,651
<p>I am trying to iterate through a list and take each part of the list, encode it and join the result up when it is all done. As an example, I have a string which produces a list with each element being 16 characters in length.</p> <pre><code>message = (u'sixteen-letters.sixteen-letters.sixteen-letters.sixteen-letters.') result = split16(message, 16) msg = ';'.join(encode(result.pop(0)) for i in result) </code></pre> <p>The encode function takes a 16 byte string and returns the result. However with the way it is written, it only encodes half of the elements in the list.</p> <p>If I try comprehension:</p> <pre><code>result = [encode(split16(message, 16) for message in list_of_messages)] result = ''.join(result) </code></pre> <p>It results in the whole list being sent at once. What I need to do is send each element to the encode function separately, get the result then join them together.</p> <p>Is there an easy way of achieving this?</p>
0
2009-10-15T11:04:21Z
1,571,725
<p>I'm not quite clear what you are after, but</p> <pre><code>msg=";".join(map(encode,(message[i:i+16] for i in range(0,len(message),16)))) </code></pre>
0
2009-10-15T11:16:54Z
[ "python", "list", "list-comprehension" ]
Iterating through a list in Python
1,571,651
<p>I am trying to iterate through a list and take each part of the list, encode it and join the result up when it is all done. As an example, I have a string which produces a list with each element being 16 characters in length.</p> <pre><code>message = (u'sixteen-letters.sixteen-letters.sixteen-letters.sixteen-letters.') result = split16(message, 16) msg = ';'.join(encode(result.pop(0)) for i in result) </code></pre> <p>The encode function takes a 16 byte string and returns the result. However with the way it is written, it only encodes half of the elements in the list.</p> <p>If I try comprehension:</p> <pre><code>result = [encode(split16(message, 16) for message in list_of_messages)] result = ''.join(result) </code></pre> <p>It results in the whole list being sent at once. What I need to do is send each element to the encode function separately, get the result then join them together.</p> <p>Is there an easy way of achieving this?</p>
0
2009-10-15T11:04:21Z
1,571,729
<p>I am a bit confused about what you are exactly trying to do, which is compounded by a missing paren in the code you posted:</p> <pre><code>result = [encode(split16(message, 16) for message in list_of_messages] </code></pre> <p>Should that be:</p> <pre><code>result = [encode(split16(message, 16) for message in list_of_messages)] </code></pre> <p>or:</p> <pre><code>result = [encode(split16(message, 16)) for message in list_of_messages] </code></pre> <p>I think the second will do what you want.</p> <p>This code:</p> <pre><code>msg = ';'.join(encode(result.pop(0)) for i in result) </code></pre> <p>is failing because at every step you are iterating through <code>result</code>, but shortening it at every step with <code>pop</code>. It should just be:</p> <pre><code>msg = ';'.join(encode(i) for i in result) </code></pre>
1
2009-10-15T11:17:42Z
[ "python", "list", "list-comprehension" ]
Select specific child elements with BeautifulSoup
1,571,699
<p>I'm reading up on BeautifulSoup to screen-scrape some pretty heavy html pages. Going through the documentation of BeautifulSoup I can't seem to find a easy way to select child elements.</p> <p>Given the html:</p> <pre><code>&lt;div id="top"&gt; &lt;div&gt;Content&lt;/div&gt; &lt;div&gt; &lt;div&gt;Content I Want&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I want a easy way to to get the "Content I Want" given I have the object top. Coming to BeautifulSoup I thought it would be easy, and something like topobj.nodes[1].nodes[0].string. Instead I only see variables and functions that also return the elements together with text nodes, comments and so on. </p> <p>Am I missing something? Or do I really need to resort to a long form using .find() or even worse using list comphrensions on the .contents variable.</p> <p>The reason is that I don't trust the whitespace of the webpage to be the same so I want to ignore it and only traverse on elements.</p>
2
2009-10-15T11:12:42Z
1,571,813
<p>You are more flexible with <code>find</code>, and to get what you want you just need to run:</p> <pre><code>node = p.find('div', text="Content I Want") </code></pre> <p>But since it might not be <em>how</em> you want to get there, following options might suit you better:</p> <pre><code>xml = """&lt;div id="top"&gt;&lt;div&gt;Content&lt;/div&gt;&lt;div&gt;&lt;div&gt;Content I Want&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;""" from BeautifulSoup import BeautifulSoup p = BeautifulSoup(xml) # returns a list of texts print p.div.div.findNextSibling().div.contents # returns a list of texts print p.div.div.findNextSibling().div(text=True) # join (and strip) the values print ''.join(s.strip() for s in p.div.div.findNextSibling().div(text=True)) </code></pre>
2
2009-10-15T11:34:56Z
[ "python", "beautifulsoup", "html-parsing" ]
Python Vs C - Handling environment variable in Windows
1,572,153
<p>I see a variation in output between C and python code in Windows trying to get the same functionality. The c code ( similar to unix shell scripts ) shows the TEST1 environment variable in 'test.bat.output' with its value as empty string whereas the python code removes this environment variable. </p> <p>Is there a way to ask Python not to remove the environment variable from environ table when it is empty?</p> <h2>C</h2> <pre><code>#include &lt;windows.h&gt; main() { DWORD dwRet; char pszOldVal[1024] = "abc"; if(! SetEnvironmentVariable("TEST1", "")) puts("Error\n"); // _putenv("TEST1="); // GetEnvironmentVariable("TEST1", pszOldVal, dwRet); system("cmd /c test.bat &gt;test.bat.output"); } </code></pre> <h2>Python</h2> <pre><code>import os os.environ['TEST1'] = "" os.environ['TEST2'] = "karthik" os.system("cmd /c test.bat &gt; test.bat.output.python") </code></pre> <p>-Karthik</p>
2
2009-10-15T12:48:29Z
1,572,348
<p>Yes empty values are not being put into environ, but interesting thing is calling SetEnvironmentVariable from win32api or ctypes module has same affect as os.environ though win32api.SetEnvironmentVariable would be calling the same function as in C .</p> <p>So are you sure you get different result in C code?</p> <pre><code>import win32api import os win32api.SetEnvironmentVariable("TEST1", "") # or # import ctypes # ctypes.windll.kernel32.SetEnvironmentVariable("TEST1", "") os.system("echo %TEST1%") </code></pre>
0
2009-10-15T13:23:17Z
[ "python", "c", "environment-variables" ]
Python Vs C - Handling environment variable in Windows
1,572,153
<p>I see a variation in output between C and python code in Windows trying to get the same functionality. The c code ( similar to unix shell scripts ) shows the TEST1 environment variable in 'test.bat.output' with its value as empty string whereas the python code removes this environment variable. </p> <p>Is there a way to ask Python not to remove the environment variable from environ table when it is empty?</p> <h2>C</h2> <pre><code>#include &lt;windows.h&gt; main() { DWORD dwRet; char pszOldVal[1024] = "abc"; if(! SetEnvironmentVariable("TEST1", "")) puts("Error\n"); // _putenv("TEST1="); // GetEnvironmentVariable("TEST1", pszOldVal, dwRet); system("cmd /c test.bat &gt;test.bat.output"); } </code></pre> <h2>Python</h2> <pre><code>import os os.environ['TEST1'] = "" os.environ['TEST2'] = "karthik" os.system("cmd /c test.bat &gt; test.bat.output.python") </code></pre> <p>-Karthik</p>
2
2009-10-15T12:48:29Z
1,572,352
<p>This is a possible answer. I don't have a Windows system handy to test with, so I don't really know what this code will do, but what happens if you do this:</p> <pre><code>import os, subprocess myenv = {} myenv.update(os.environ) myenv['TEST1'] = "" myenv['TEST2'] = "karthik" subprocess.Popen(('cmd', '/c', 'test.bat'), stdout=file("test.bat.output.python", 'w'), env=myenv).wait() </code></pre> <p>In my opinion, you might be encountering a Python bug of some kind. Especially if the code I just gave works.</p> <p>Also, testing your code under Unix does work. The environment ends up with an empty environment variable in it.</p>
0
2009-10-15T13:24:17Z
[ "python", "c", "environment-variables" ]
Python Vs C - Handling environment variable in Windows
1,572,153
<p>I see a variation in output between C and python code in Windows trying to get the same functionality. The c code ( similar to unix shell scripts ) shows the TEST1 environment variable in 'test.bat.output' with its value as empty string whereas the python code removes this environment variable. </p> <p>Is there a way to ask Python not to remove the environment variable from environ table when it is empty?</p> <h2>C</h2> <pre><code>#include &lt;windows.h&gt; main() { DWORD dwRet; char pszOldVal[1024] = "abc"; if(! SetEnvironmentVariable("TEST1", "")) puts("Error\n"); // _putenv("TEST1="); // GetEnvironmentVariable("TEST1", pszOldVal, dwRet); system("cmd /c test.bat &gt;test.bat.output"); } </code></pre> <h2>Python</h2> <pre><code>import os os.environ['TEST1'] = "" os.environ['TEST2'] = "karthik" os.system("cmd /c test.bat &gt; test.bat.output.python") </code></pre> <p>-Karthik</p>
2
2009-10-15T12:48:29Z
1,572,698
<p>Cross-platform compatibility between Windows and "most everybody else" (operating systems derived or inspired from Unix) is often hard to get, especially in the innumerable corner cases that inevitably arise (e.g., as in this question, "does setting an environment variable to empty mean unsetting it"). Sometimes it's just easier to access Windows specific functionality directly rather than trying to stretch the "cross-platform" functionality.</p> <p>While the traditional way to access Windows-specific functionality from Python is the <a href="http://python.net/crew/skippy/win32/Downloads.html" rel="nofollow">win32all</a> extension package, in recent Python versions the <a href="http://docs.python.org/library/ctypes.html" rel="nofollow">ctypes</a> standard library module offers an alternative with the advantage of requiring no installation of C coded extensions. An interesting project is <a href="http://pypi.python.org/pypi/jaraco.windows/1.3" rel="nofollow">jaraco.windows</a>, a set of pure-Python code on top of <code>ctypes</code> to make Windows operations easier and smoother. For example, if you work with the environment and/or the registry, the <a href="https://svn.jaraco.com/jaraco/python/jaraco.windows/jaraco/windows/environ.py" rel="nofollow">environ.py</a> module offers a nice set of functions and classes with a more Pythonic feel to them than the bare win32 API as accessed by the underlying <code>ctypes</code> (e.g., get an exception with a readable error message in it in case of errors, rather than having to check return codes &amp;c).</p>
2
2009-10-15T14:25:07Z
[ "python", "c", "environment-variables" ]
script to find pagerank of domain
1,572,183
<p>how can I automate finding the pagerank of a domain? I came across <a href="http://blogmag.net/blog/read/91/Python%5Fcode%5Fto%5Fcheck%5Fyour%5FGoogle%5FPageRank" rel="nofollow">this Python script</a> but it no longer works. Seems Google doesn't like people automating this.</p> <p>So, is there an alternative provider of page rank scores? I do not need the exact same result as Google, but something comparable.</p>
5
2009-10-15T12:54:04Z
1,574,033
<p>Have you tried HalOtis Marketing's Page Rank script at <a href="http://www.halotis.com/2009/08/02/google-page-range-python-script/" rel="nofollow">http://www.halotis.com/2009/08/02/google-page-range-python-script/</a>? He generally writes good, simple Python code for exactly this kind of stuff.</p>
2
2009-10-15T17:56:03Z
[ "python", "api", "pagerank" ]
script to find pagerank of domain
1,572,183
<p>how can I automate finding the pagerank of a domain? I came across <a href="http://blogmag.net/blog/read/91/Python%5Fcode%5Fto%5Fcheck%5Fyour%5FGoogle%5FPageRank" rel="nofollow">this Python script</a> but it no longer works. Seems Google doesn't like people automating this.</p> <p>So, is there an alternative provider of page rank scores? I do not need the exact same result as Google, but something comparable.</p>
5
2009-10-15T12:54:04Z
1,574,836
<p>Here is a python script <a href="http://www.djangosnippets.org/snippets/221/" rel="nofollow">which does work</a>. I had to do exactly the same thing recently!</p>
4
2009-10-15T20:29:46Z
[ "python", "api", "pagerank" ]
Can I use Django's Generic Views with google-app-engine-django?
1,572,255
<p>Put simply, is there a way to get generic views to work?</p> <p>If I try the following in urls.py:</p> <pre><code>publisher_info = { 'queryset': Publisher.objects.all(), } urlpatterns = patterns('', (r'^publishers/$', list_detail.object_list, publisher_info) ) </code></pre> <p>I get the following error:</p> <blockquote> <p>AttributeError at /publishers 'Query'</p> <p>object has no attribute '_clone'</p> </blockquote> <p>Is this due to the fact that Django models aren't supported on App Engine and google-app-engine-django hasn't been able to port over all associated code? If so, would it be easy to fix myself?</p>
1
2009-10-15T13:07:18Z
1,572,277
<p>It looks like this project should provide that functionality as a core feature.</p> <p><a href="http://code.google.com/p/app-engine-patch/" rel="nofollow">http://code.google.com/p/app-engine-patch/</a></p>
1
2009-10-15T13:11:10Z
[ "python", "django", "google-app-engine", "django-models", "django-generic-views" ]
Can I use Django's Generic Views with google-app-engine-django?
1,572,255
<p>Put simply, is there a way to get generic views to work?</p> <p>If I try the following in urls.py:</p> <pre><code>publisher_info = { 'queryset': Publisher.objects.all(), } urlpatterns = patterns('', (r'^publishers/$', list_detail.object_list, publisher_info) ) </code></pre> <p>I get the following error:</p> <blockquote> <p>AttributeError at /publishers 'Query'</p> <p>object has no attribute '_clone'</p> </blockquote> <p>Is this due to the fact that Django models aren't supported on App Engine and google-app-engine-django hasn't been able to port over all associated code? If so, would it be easy to fix myself?</p>
1
2009-10-15T13:07:18Z
1,683,369
<p>The answer seems to be No.</p>
1
2009-11-05T20:28:47Z
[ "python", "django", "google-app-engine", "django-models", "django-generic-views" ]
How do I request data securely via Google OAuth?
1,572,450
<p>Until recently users of my site were able to import data from Google, via OAuth. However, recently they have received the warning below, in a yellow box, when authorising (although the import still works).</p> <p>I've also noticed this same warning on Facebook's GMail authenticator!</p> <p>What's changed / am I missing?</p> <blockquote> <p>This website is registered with Google to make authorization requests, but has not been configured to send requests securely.</p> <p>If you grant access but you did not initiate this request at www.foo.com, it may be possible for other users of www.foo.com to access your data. We recommend you deny access unless you are certain that you initiated this request directly with www.foo.com.</p> </blockquote> <p>(The site is written in Zope/Python, but the step/documentation I'm missing is more important)</p>
2
2009-10-15T13:40:14Z
1,572,588
<p>Did you try Googling the error message? Doing so took me to <a href="http://code.google.com/apis/accounts/docs/RegistrationForWebAppsAuto.html" rel="nofollow">this page</a>, which states:</p> <blockquote> <p>Registered with enhanced security: Registered applications <strong>with a security certificate on file</strong> can use secure tokens. The Access Request page removes cautions, displaying this message: " Google is not affiliated with , and we recommend that you grant access only if you trust the site."</p> </blockquote> <p>See their docs, step 4, "Upload a security certificate" for more details.</p>
1
2009-10-15T14:04:55Z
[ "python", "oauth" ]
How can I make Zenoss recognize skin changes?
1,572,661
<p>I'm writing a ZenPack for Zenoss which includes a new DataSource. The DataSource has a ToOne relationship with another persistent object and I'm trying to construct the user interface to allow a user to specify the value of this relationship. I've given the DataSource a factory_type_information attribute with an "immediate_view" key mapped to the name of a skin/template - "viewAgentScriptDataSource". In my ZenPack's skins directory, I created viewAgentScriptDataSource.pt. Zenoss seems to have liked this and now when I view an instance of the DataSource, I see a page based on viewAgentScriptDataSource.pt.</p> <p>However, after this first success, any edits I make to the skin/template file are ignored. I tried replacing the dummy content of the file with something more realistic and reloading the data source view. The dummy content still appears. I tried restarting Zenoss and reloading the view. The dummy content still appears. I tried deleting my ZenPack and re-installing it. The dummy content still appears.</p> <p>How do I get Zenoss to load the new contents of the skin file?</p>
0
2009-10-15T14:16:57Z
1,578,608
<p>The problem turned out to be that none of the template changes I made actually had any impact on the final page output. The changes were picked up, they just didn't matter.</p>
1
2009-10-16T14:59:24Z
[ "python", "zope", "zenoss" ]
Unexpected result in a simple example
1,572,676
<pre><code> def solve(numLegs, numHeads): for numSpiders in range(0, numHeads + 1): for numChicks in range(0, numHeads - numSpiders + 1): numPigs = numHeads - numChicks - numSpiders totLegs = 4*numPigs + 2*numChicks + 6*numSpiders if totLegs == numLegs: return [numPigs, numChicks, numSpiders] return [None, None, None] def barnYard(heads, legs): pigs, chickens, spiders = solve(legs, heads) if pigs == None: print "There is no solution." else: print 'Number of pigs: ', pigs print 'Number of Chickens: ', chickens print 'Number of Spider: ', spiders barnYard(20,56) # 8 pigs - 12 chickens barnYard(21,62) # 10 pig - 11 chickens </code></pre> <p>20 heads and 56 legs returns 8 pigs and 12 chickens, so I made it 21 and 62 to add a spider, but it still returns pigs and chickens, whats wrong in the code?</p> <p>Thanks!</p>
0
2009-10-15T14:21:44Z
1,572,713
<p>There is absolutely nothing wrong with your code. That's a completely valid result. With 10 pigs and 11 chickens, you get <code>10+11=21</code> heads, and <code>10*4 + 11*2</code> = 62 legs.</p> <p>So it returns a correct result.</p> <p>Now if you change that to 10 heads and 62 legs, and also change the code to have 8 legs for a spider as they tend to do, then you get the result 3 pigs, 1 chicken and 6 spiders.</p> <p>Your code simply tries spiders last, so you wont get any spiders unless it <em>has</em> to be spiders.</p>
2
2009-10-15T14:28:31Z
[ "python" ]
Unexpected result in a simple example
1,572,676
<pre><code> def solve(numLegs, numHeads): for numSpiders in range(0, numHeads + 1): for numChicks in range(0, numHeads - numSpiders + 1): numPigs = numHeads - numChicks - numSpiders totLegs = 4*numPigs + 2*numChicks + 6*numSpiders if totLegs == numLegs: return [numPigs, numChicks, numSpiders] return [None, None, None] def barnYard(heads, legs): pigs, chickens, spiders = solve(legs, heads) if pigs == None: print "There is no solution." else: print 'Number of pigs: ', pigs print 'Number of Chickens: ', chickens print 'Number of Spider: ', spiders barnYard(20,56) # 8 pigs - 12 chickens barnYard(21,62) # 10 pig - 11 chickens </code></pre> <p>20 heads and 56 legs returns 8 pigs and 12 chickens, so I made it 21 and 62 to add a spider, but it still returns pigs and chickens, whats wrong in the code?</p> <p>Thanks!</p>
0
2009-10-15T14:21:44Z
1,572,729
<p>A linear system with 2 equations and 3 variables is under-determined -- there may be multiple solutions for any given set of parameters; and this is indeed the case for the code you're showing. Nothing wrong with the code, if what you want is to get the solution (if any) with as few spiders as possible.</p> <p>If you want to get the solution (if any) with <em>as many</em> spiders as possible, try "many spiders" first, for example change the outer loop, which is now</p> <pre><code> for numSpiders in range(0, numHeads + 1): </code></pre> <p>i.e., first tries to get a solution with no spiders at all, then if that fails tries with one, and so forth, to be instead:</p> <pre><code> for numSpiders in reversed(range(0, numHeads + 1)): </code></pre> <p>which goes the other way round (that's what the <code>reversed</code> is for) and will try <code>numHeads</code> spiders first, then <code>numHeads-1</code>, and so forth.</p> <p>(Your equations are actually Diophantine ones, i.e., strictly integer-based, which has important implications when compared to ordinary linear equations which admit fractional solutions, but your issue here is not tied to Diophantine-equation problems, just to the bit about underdetermined linear systems).</p>
2
2009-10-15T14:30:48Z
[ "python" ]
Unexpected result in a simple example
1,572,676
<pre><code> def solve(numLegs, numHeads): for numSpiders in range(0, numHeads + 1): for numChicks in range(0, numHeads - numSpiders + 1): numPigs = numHeads - numChicks - numSpiders totLegs = 4*numPigs + 2*numChicks + 6*numSpiders if totLegs == numLegs: return [numPigs, numChicks, numSpiders] return [None, None, None] def barnYard(heads, legs): pigs, chickens, spiders = solve(legs, heads) if pigs == None: print "There is no solution." else: print 'Number of pigs: ', pigs print 'Number of Chickens: ', chickens print 'Number of Spider: ', spiders barnYard(20,56) # 8 pigs - 12 chickens barnYard(21,62) # 10 pig - 11 chickens </code></pre> <p>20 heads and 56 legs returns 8 pigs and 12 chickens, so I made it 21 and 62 to add a spider, but it still returns pigs and chickens, whats wrong in the code?</p> <p>Thanks!</p>
0
2009-10-15T14:21:44Z
1,572,737
<p>Your code is correct - in the first iteration of the outermost <code>for</code> loop, <code>numChicks</code> is <code>0</code>. Since <code>solve</code> returns as soon as it finds a valid match, another possible valid match won't be attempted.</p> <p>You could change the <code>return</code> statement into a <code>yield</code> statement and iterate over <code>solve</code>'s results to get all possible combinations.</p> <p>For instance:</p> <pre><code>def solve(numLegs, numHeads): for numBees in range(0, numHeads + 1): for numChicks in range(0, numHeads - numBees + 1): numPigs = numHeads - numChicks - numBees totLegs = 4*numPigs + 2*numChicks + 6*numBees if totLegs == numLegs: yield [numPigs, numChicks, numBees] def barnYard(heads, legs): for pigs, chickens, bees in solve(legs, heads): print 'Number of pigs: ', pigs print 'Number of chickens: ', chickens print 'Number of bees: ', bees barnYard(20,56) </code></pre> <p>will output:</p> <pre><code>Number of pigs: 8 Number of chickens: 12 Number of bees: 0 Number of pigs: 6 Number of chickens: 13 Number of bees: 1 Number of pigs: 4 Number of chickens: 14 Number of bees: 2 Number of pigs: 2 Number of chickens: 15 Number of bees: 3 Number of pigs: 0 Number of chickens: 16 Number of bees: 4 </code></pre>
5
2009-10-15T14:31:34Z
[ "python" ]
In Python, Python Image Library 1.1.6, how can I expand the canvas without resizing?
1,572,691
<p>I am probably looking for the wrong thing in the handbook, but I am looking to take an image object and expand it without resizing (stretching/squishing) the original image. </p> <p>Toy example: imagine a blue rectangle, 200 x 100, then I perform some operation and I have a new image object, 400 x 300, consisting of a white background upon which a 200 x 100 blue rectangle rests. Bonus if I can control in which direction this expands, or the new background color, etc.</p> <p>Essentially, I have an image to which I will be adding iteratively, and I do not know what size it will be at the outset. </p> <p>I suppose it would be possible for me to grab the original object, make a new, slightly larger object, paste the original on there, draw a little more, then repeat. It seems like it might be computationally expensive. However, I thought there would be a function for this, as I assume it is a common operation. Perhaps I assumed wrong.</p>
11
2009-10-15T14:23:55Z
1,572,966
<p>The ImageOps.expand function will expand the image, but it adds the same amount of pixels in each direction.</p> <p>The best way is simply to make a new image and paste:</p> <pre><code>newImage = Image.new(mode, (newWidth,newHeight)) newImage.paste(srcImage, (x1,y1,x1+oldWidth,y1+oldHeight)) </code></pre> <p>If performance is an issue, make your original image bigger than needed and crop it after the drawing is done.</p>
20
2009-10-15T15:03:47Z
[ "python", "python-imaging-library" ]
In Python, Python Image Library 1.1.6, how can I expand the canvas without resizing?
1,572,691
<p>I am probably looking for the wrong thing in the handbook, but I am looking to take an image object and expand it without resizing (stretching/squishing) the original image. </p> <p>Toy example: imagine a blue rectangle, 200 x 100, then I perform some operation and I have a new image object, 400 x 300, consisting of a white background upon which a 200 x 100 blue rectangle rests. Bonus if I can control in which direction this expands, or the new background color, etc.</p> <p>Essentially, I have an image to which I will be adding iteratively, and I do not know what size it will be at the outset. </p> <p>I suppose it would be possible for me to grab the original object, make a new, slightly larger object, paste the original on there, draw a little more, then repeat. It seems like it might be computationally expensive. However, I thought there would be a function for this, as I assume it is a common operation. Perhaps I assumed wrong.</p>
11
2009-10-15T14:23:55Z
1,573,679
<p>You might consider a rather different approach to your image... build it out of tiles of a fixed size. That way, as you need to expand, you just add new image tiles. When you have completed all of your computation, you can determine the final size of the image, create a blank image of that size, and paste the tiles into it. That should reduce the amount of copying you're looking at for completing the task.</p> <p>(You'd likely want to encapsulate such a tiled image into an object that hid the tiling aspects from the other layers of code, of course.)</p>
2
2009-10-15T16:55:26Z
[ "python", "python-imaging-library" ]
In Python, Python Image Library 1.1.6, how can I expand the canvas without resizing?
1,572,691
<p>I am probably looking for the wrong thing in the handbook, but I am looking to take an image object and expand it without resizing (stretching/squishing) the original image. </p> <p>Toy example: imagine a blue rectangle, 200 x 100, then I perform some operation and I have a new image object, 400 x 300, consisting of a white background upon which a 200 x 100 blue rectangle rests. Bonus if I can control in which direction this expands, or the new background color, etc.</p> <p>Essentially, I have an image to which I will be adding iteratively, and I do not know what size it will be at the outset. </p> <p>I suppose it would be possible for me to grab the original object, make a new, slightly larger object, paste the original on there, draw a little more, then repeat. It seems like it might be computationally expensive. However, I thought there would be a function for this, as I assume it is a common operation. Perhaps I assumed wrong.</p>
11
2009-10-15T14:23:55Z
27,784,150
<p>Based on interjays answer:</p> <pre><code>#!/usr/bin/env python from PIL import Image import math def resize_canvas(old_image_path="314.jpg", new_image_path="save.jpg", canvas_width=500, canvas_height=500): """Resize the canvas of old_image_path and store the new image in new_image_path. Center the image on the new canvas. """ im = Image.open(old_image_path) old_width, old_height = im.size # Center the image x1 = int(math.floor((canvas_width - old_width) / 2)) y1 = int(math.floor((canvas_height - old_height) / 2)) mode = im.mode if len(mode) == 1: # L, 1 new_background = (255) if len(mode) == 3: # RGB new_background = (255, 255, 255) if len(mode) == 4: # RGBA, CMYK new_background = (255, 255, 255, 255) newImage = Image.new(mode, (canvas_width, canvas_height), new_background) newImage.paste(im, (x1, y1, x1 + old_width, y1 + old_height)) newImage.save(new_image_path) resize_canvas() </code></pre>
2
2015-01-05T16:52:45Z
[ "python", "python-imaging-library" ]
Importing Python modules from a distant directory
1,572,967
<p>What's the shortest way to import a module from a distant, relative directory?</p> <p>We've been using this code which isn't too bad except your current working directory <em>has</em> to be the same as the directory as this code's or the relative path breaks, which can be error prone and confusing to users.</p> <pre><code>import sys sys.path.append('../../../Path/To/Shared/Code') </code></pre> <p>This code (I think) fixes that problem but is a lot more to type.</p> <pre><code>import os,sys sys.path.append(os.path.realpath(os.path.join(os.path.dirname(__file__), '../../../Path/To/Shared/Code'))) </code></pre> <p>Is there a shorter way to append the absolute path? The brevity matters because this is going to have to be typed/appear in a lot of our files. (We can't factor it out because then it would be in the shared code and we couldn't get to it. Chicken &amp; egg, bootstrapping, etc.)</p> <p>Plus it bothers me that we keep blindly appending to sys.path but that would be even more code. I sure wish something in the standard library could help with this.</p> <p>This will typically appear in script files which are run from the command line. We're running Python 2.6.2.</p> <p><strong>Edit:</strong> The reason we're using relative paths is that we typically have multiple, independent copies of the codebase on our computers. It's important that each copy of the codebase use its own copy of the shared code. So any solution which supports only a single code base (e.g., 'Put it in site-packages.') won't work for us.</p> <p>Any suggestions? Thank you!</p>
2
2009-10-15T15:04:08Z
1,572,979
<p>Any reason you wouldn't want to make your own shared-code dir under site-packages? Then you could just import import shared.code.module...</p>
1
2009-10-15T15:06:29Z
[ "python" ]
Importing Python modules from a distant directory
1,572,967
<p>What's the shortest way to import a module from a distant, relative directory?</p> <p>We've been using this code which isn't too bad except your current working directory <em>has</em> to be the same as the directory as this code's or the relative path breaks, which can be error prone and confusing to users.</p> <pre><code>import sys sys.path.append('../../../Path/To/Shared/Code') </code></pre> <p>This code (I think) fixes that problem but is a lot more to type.</p> <pre><code>import os,sys sys.path.append(os.path.realpath(os.path.join(os.path.dirname(__file__), '../../../Path/To/Shared/Code'))) </code></pre> <p>Is there a shorter way to append the absolute path? The brevity matters because this is going to have to be typed/appear in a lot of our files. (We can't factor it out because then it would be in the shared code and we couldn't get to it. Chicken &amp; egg, bootstrapping, etc.)</p> <p>Plus it bothers me that we keep blindly appending to sys.path but that would be even more code. I sure wish something in the standard library could help with this.</p> <p>This will typically appear in script files which are run from the command line. We're running Python 2.6.2.</p> <p><strong>Edit:</strong> The reason we're using relative paths is that we typically have multiple, independent copies of the codebase on our computers. It's important that each copy of the codebase use its own copy of the shared code. So any solution which supports only a single code base (e.g., 'Put it in site-packages.') won't work for us.</p> <p>Any suggestions? Thank you!</p>
2
2009-10-15T15:04:08Z
1,573,073
<p>You have several ways to handle imports, all documented in the Python language manual.</p> <p>See <a href="http://docs.python.org/library/site.html" rel="nofollow">http://docs.python.org/library/site.html</a> and <a href="http://docs.python.org/reference/simple%5Fstmts.html#the-import-statement" rel="nofollow">http://docs.python.org/reference/simple%5Fstmts.html#the-import-statement</a></p> <ol> <li><p>Put it in site-packages and have multiple Python installations. You select the installation using the ordinary <code>PATH</code> environment variable.</p></li> <li><p>Put the directory in your <code>PYTHONPATH</code> environment variable. This is a per-individual-person setting, so you can manage to have multiple versions of the codebase this way.</p></li> <li><p>Put the directory in <code>.pth</code> files in your site-packages. You select the installation using the ordinary <code>PATH</code> environment variable.</p></li> </ol>
-1
2009-10-15T15:19:11Z
[ "python" ]
Importing Python modules from a distant directory
1,572,967
<p>What's the shortest way to import a module from a distant, relative directory?</p> <p>We've been using this code which isn't too bad except your current working directory <em>has</em> to be the same as the directory as this code's or the relative path breaks, which can be error prone and confusing to users.</p> <pre><code>import sys sys.path.append('../../../Path/To/Shared/Code') </code></pre> <p>This code (I think) fixes that problem but is a lot more to type.</p> <pre><code>import os,sys sys.path.append(os.path.realpath(os.path.join(os.path.dirname(__file__), '../../../Path/To/Shared/Code'))) </code></pre> <p>Is there a shorter way to append the absolute path? The brevity matters because this is going to have to be typed/appear in a lot of our files. (We can't factor it out because then it would be in the shared code and we couldn't get to it. Chicken &amp; egg, bootstrapping, etc.)</p> <p>Plus it bothers me that we keep blindly appending to sys.path but that would be even more code. I sure wish something in the standard library could help with this.</p> <p>This will typically appear in script files which are run from the command line. We're running Python 2.6.2.</p> <p><strong>Edit:</strong> The reason we're using relative paths is that we typically have multiple, independent copies of the codebase on our computers. It's important that each copy of the codebase use its own copy of the shared code. So any solution which supports only a single code base (e.g., 'Put it in site-packages.') won't work for us.</p> <p>Any suggestions? Thank you!</p>
2
2009-10-15T15:04:08Z
1,573,088
<p>You've explained in a comment why you don't want to install "a single site-packages directory", but what about putting in <code>site-packages</code> a single, tiny <em>module</em>, say <code>jebootstrap.py</code>:</p> <pre><code>import os, sys def relative_dir(apath): return os.path.realpath( os.path.join(os.path.dirname(apath), '../../../Path/To/Shared/Code')) def addpack(apath): relative = relative_dir(apath) if relative not in sys.path: sys.path.append(relative) </code></pre> <p>Now everywhere in your code you can just have</p> <pre><code>import jebootstrap jebootsrap.addpack(__file__) </code></pre> <p>and all the rest of your shared codebase can remain independent per-installation.</p>
2
2009-10-15T15:21:44Z
[ "python" ]
Importing Python modules from a distant directory
1,572,967
<p>What's the shortest way to import a module from a distant, relative directory?</p> <p>We've been using this code which isn't too bad except your current working directory <em>has</em> to be the same as the directory as this code's or the relative path breaks, which can be error prone and confusing to users.</p> <pre><code>import sys sys.path.append('../../../Path/To/Shared/Code') </code></pre> <p>This code (I think) fixes that problem but is a lot more to type.</p> <pre><code>import os,sys sys.path.append(os.path.realpath(os.path.join(os.path.dirname(__file__), '../../../Path/To/Shared/Code'))) </code></pre> <p>Is there a shorter way to append the absolute path? The brevity matters because this is going to have to be typed/appear in a lot of our files. (We can't factor it out because then it would be in the shared code and we couldn't get to it. Chicken &amp; egg, bootstrapping, etc.)</p> <p>Plus it bothers me that we keep blindly appending to sys.path but that would be even more code. I sure wish something in the standard library could help with this.</p> <p>This will typically appear in script files which are run from the command line. We're running Python 2.6.2.</p> <p><strong>Edit:</strong> The reason we're using relative paths is that we typically have multiple, independent copies of the codebase on our computers. It's important that each copy of the codebase use its own copy of the shared code. So any solution which supports only a single code base (e.g., 'Put it in site-packages.') won't work for us.</p> <p>Any suggestions? Thank you!</p>
2
2009-10-15T15:04:08Z
1,573,105
<p>Since you don't want to install it in site-packages, you should use <a href="http://pypi.python.org/pypi/zc.buildout/" rel="nofollow">buildout</a> or <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">virtualenv</a> to create isolated development environments. That solves the problem, and means you don't have to fiddle with sys.path anymore (in fact, because Buildout does exactly that for you).</p>
4
2009-10-15T15:26:04Z
[ "python" ]
Modifying state of other objects in a constructor: design no-no?
1,573,054
<p>I'm refactoring some code and found this (simplified of course, but general idea):</p> <pre><code>class Variable: def __init__(self): self.__constraints = [] def addConstraint(self, c): self.__constraints.append(c) class Constraint: def __init__(self, variables): for v in variables: v.addConstraint(self) </code></pre> <p>The fact that the constructor of Constraint modifies other object's states instead of its own smells a little funky to me. What do other people think - is this OK, or is it a prime candidate for refactoring?</p> <p>Edit: My concern is not the parent/child relationship, but that it is linked up inside the constructor rather than in a separate method.</p>
2
2009-10-15T15:16:29Z
1,573,078
<p>I agree with you. That's backwards. There may be some good reason for why, but it's unclear programming and it likely to bite someone if the foot sooner or later.</p>
0
2009-10-15T15:20:29Z
[ "python", "oop", "refactoring", "constructor" ]
Modifying state of other objects in a constructor: design no-no?
1,573,054
<p>I'm refactoring some code and found this (simplified of course, but general idea):</p> <pre><code>class Variable: def __init__(self): self.__constraints = [] def addConstraint(self, c): self.__constraints.append(c) class Constraint: def __init__(self, variables): for v in variables: v.addConstraint(self) </code></pre> <p>The fact that the constructor of Constraint modifies other object's states instead of its own smells a little funky to me. What do other people think - is this OK, or is it a prime candidate for refactoring?</p> <p>Edit: My concern is not the parent/child relationship, but that it is linked up inside the constructor rather than in a separate method.</p>
2
2009-10-15T15:16:29Z
1,573,091
<p>I see it as a self registration pattern. "Hello I'm new here, please allow me to join." </p> <p>I might prefer to have a differently named method so that the purpose is more clear, but I do actually quite like the approach.</p>
4
2009-10-15T15:23:26Z
[ "python", "oop", "refactoring", "constructor" ]
Modifying state of other objects in a constructor: design no-no?
1,573,054
<p>I'm refactoring some code and found this (simplified of course, but general idea):</p> <pre><code>class Variable: def __init__(self): self.__constraints = [] def addConstraint(self, c): self.__constraints.append(c) class Constraint: def __init__(self, variables): for v in variables: v.addConstraint(self) </code></pre> <p>The fact that the constructor of Constraint modifies other object's states instead of its own smells a little funky to me. What do other people think - is this OK, or is it a prime candidate for refactoring?</p> <p>Edit: My concern is not the parent/child relationship, but that it is linked up inside the constructor rather than in a separate method.</p>
2
2009-10-15T15:16:29Z
1,573,096
<p>This is common usage when you have two objects that are closely related (i.e. where only one of them alone doesn't make sense). Most common case: Parent child relations. When you add a child to a parent (i.e. <code>parent.children.append(child)</code>), you often also update the <code>child.parent</code> pointer.</p>
0
2009-10-15T15:24:22Z
[ "python", "oop", "refactoring", "constructor" ]
Modifying state of other objects in a constructor: design no-no?
1,573,054
<p>I'm refactoring some code and found this (simplified of course, but general idea):</p> <pre><code>class Variable: def __init__(self): self.__constraints = [] def addConstraint(self, c): self.__constraints.append(c) class Constraint: def __init__(self, variables): for v in variables: v.addConstraint(self) </code></pre> <p>The fact that the constructor of Constraint modifies other object's states instead of its own smells a little funky to me. What do other people think - is this OK, or is it a prime candidate for refactoring?</p> <p>Edit: My concern is not the parent/child relationship, but that it is linked up inside the constructor rather than in a separate method.</p>
2
2009-10-15T15:16:29Z
1,573,143
<p>I personally am not necessarily opposed to this, but...</p> <p>I would choose one usage pattern, and stick with it. In your case, since Variable already has a clean addConstraint method, my preference would be to use it.</p> <p>Otherwise, you'll need to add good checking to prevent the user from constructing a Constraint, and then adding it to the Variable class (thereby adding it twice).</p> <p>That being said, with something like a Constraint, though, I would probably not do this. A Constraint seems like a conceptually independent entity from a Variable. I see no logical reason the same constraint couldn't be added to two separate variables. I would just make it so you construct your constraint, then add them manually, specifically for this reason.</p>
0
2009-10-15T15:32:28Z
[ "python", "oop", "refactoring", "constructor" ]
Modifying state of other objects in a constructor: design no-no?
1,573,054
<p>I'm refactoring some code and found this (simplified of course, but general idea):</p> <pre><code>class Variable: def __init__(self): self.__constraints = [] def addConstraint(self, c): self.__constraints.append(c) class Constraint: def __init__(self, variables): for v in variables: v.addConstraint(self) </code></pre> <p>The fact that the constructor of Constraint modifies other object's states instead of its own smells a little funky to me. What do other people think - is this OK, or is it a prime candidate for refactoring?</p> <p>Edit: My concern is not the parent/child relationship, but that it is linked up inside the constructor rather than in a separate method.</p>
2
2009-10-15T15:16:29Z
1,573,177
<p>I entirely concur with @djna's answer that the specific use case is perfectly legit -- here, it's an example of an object needing to en-register itself with a specified set of registries "at birth".</p> <p>A very sharp and extremely common subcase of that would be an observer object that exists strictly for the purpose of observing a given observable -- perfectly fine to pass the observable to the observer's initializer, and exactly the right way to ensure the class invariant "instances of this observer class are at all times connected to exactly one observable", which would be not established "at birth" if the registration was carried out only after the completion of initialization.</p> <p>Other similar cases include for example a widget object that must at all time exist within a container window: it would somewhat weird to implement it otherwise than having the widget take the parent as an initializer argument and tell the parent "hi, I'm your new child!".</p> <p>At least in those 1-many cases you could imagine forcing the parent or observable to have a method that both creates and enregisters the new object. In a many-many case like this one, the somewhat inside-out nature of that approach gets revealed -- since the constraint must be registered with multiple variables, it would be "against the grain" to ask any specific one of them to create the constraint. The code you supply on the other hand is perfectly natural.</p> <p>Only for cases that cannot reasonably be framed as the new object "enregistering itself" would I feel some doubt (there are a few other legit ones, such as objects creating and enregistering other auxiliary ones at birth, but they're nowhere near as common).</p>
2
2009-10-15T15:38:16Z
[ "python", "oop", "refactoring", "constructor" ]
convert exponential to decimal in python
1,573,080
<p>I have an array in python that contains a set of values, some of them are</p> <p>2.32313e+07</p> <p>2.1155e+07</p> <p>1.923e+07</p> <p>11856</p> <p>112.32</p> <p>How do I convert the exponential formats to the decimal format</p> <p>Additional: Is there a way I can convert the exponent directly to decimal when printing out in UNIX with awk?</p>
6
2009-10-15T15:20:33Z
1,573,115
<p>I imagine you have a list rather than an array, but here it doesn't make much of a difference; in 2.6 and earlier versions of Python, something like:</p> <pre><code>&gt;&gt;&gt; L = [2.32313e+07, 2.1155e+07, 1.923e+07, 11856, 112.32] &gt;&gt;&gt; for x in L: print '%f' % x ... 23231300.000000 21155000.000000 19230000.000000 11856.000000 112.320000 </code></pre> <p>and in 2.6 or later, the <code>.format</code> method. I imagine you are aware that the numbers per se, as numbers, aren't in any "format" -- it's the <em>strings</em> you obtain by formatting the numbers, e.g. for output, that are in some format. BTW, variants on that <code>%f</code> can let you control number of decimals, width, alignment, etc -- hard to suggest exactly what you may want without further specs from you.</p> <p>In awk, you can use <a href="http://www.math.utah.edu/docs/info/gawk%5F7.html#SEC60">printf</a>.</p>
5
2009-10-15T15:27:07Z
[ "python", "unix", "awk", "exponent" ]
convert exponential to decimal in python
1,573,080
<p>I have an array in python that contains a set of values, some of them are</p> <p>2.32313e+07</p> <p>2.1155e+07</p> <p>1.923e+07</p> <p>11856</p> <p>112.32</p> <p>How do I convert the exponential formats to the decimal format</p> <p>Additional: Is there a way I can convert the exponent directly to decimal when printing out in UNIX with awk?</p>
6
2009-10-15T15:20:33Z
1,573,146
<p>You can use locale.format() to format your numbers for output. This has the additional benefit of being consistent with any locale-specific conventions that might be expected in the presentation of the numbers. If you want complete control at the specific place where you do the output, you'd be better of with the <em>print "format" % vars...</em> <a href="http://stackoverflow.com/questions/1573080/convert-exponential-to-decimal-in-python/1573115#1573115">variant</a>.</p> <p>Example:</p> <pre><code>&gt;&gt;&gt; import locale &gt;&gt;&gt; locale.setlocale(locale.LC_ALL, "") 'C/UTF-8/C/C/C/C' &gt;&gt;&gt; locale.format("%f", 2.32313e+07, 1) '23231300.000000' </code></pre>
1
2009-10-15T15:33:13Z
[ "python", "unix", "awk", "exponent" ]
convert exponential to decimal in python
1,573,080
<p>I have an array in python that contains a set of values, some of them are</p> <p>2.32313e+07</p> <p>2.1155e+07</p> <p>1.923e+07</p> <p>11856</p> <p>112.32</p> <p>How do I convert the exponential formats to the decimal format</p> <p>Additional: Is there a way I can convert the exponent directly to decimal when printing out in UNIX with awk?</p>
6
2009-10-15T15:20:33Z
1,573,542
<p>In answer to the last part of your question, <code>awk</code> can use the same <code>printf</code> format:</p> <pre><code>awk '{printf "%f\n",$1}' exponential_file </code></pre> <p>Where exponential_file contains:</p> <pre><code>2.32313e+07 2.1155e+07 1.923e+07 11856 112.32 </code></pre> <p>You can do the conversion into a variable for use later. Here is a simplistic example:</p> <pre><code>awk '{n = sprintf("%f\n",$1); print n * 2}' exponential_file </code></pre>
0
2009-10-15T16:32:11Z
[ "python", "unix", "awk", "exponent" ]
What is the typical workflow for development of a Zenoss ZenPack?
1,573,166
<p>ZenPack development seems to involve the creation of a variety of persistent state. There are model classes which represent explicitly persistent state. There are skins which are associated with model objects. There are organizers and instances of persistent classes (data sources, graphs, etc).</p> <p>Considering that during development, many things are done wrong before they're done right, and considering that loading up a ZenPack that does things wrong has persistent consequences on the Zenoss instance it is loaded into and that these consequences are hard to undo, what is the usual approach for development of a ZenPack?</p>
2
2009-10-15T15:35:53Z
1,573,261
<p>I don't know anything about Zenoss specifically, but this situations are common for any syste that have persistent configuration in one form or another, like Zope and Plone for example.</p> <p>And the workflow is that you create a test environment that you can delete and replicate, but in parts and in whole. For a typical Plone site, for example, you have a <a href="http://pypi.python.org/pypi/zc.buildout/" rel="nofollow">buildout</a> that lets you replicate the development environment including all dependencies. Then in the extension module you develop you have a script/function that allows you to set up the persistent configuration as you want it.</p> <p>This results in you being able to easily recreate a desired state.</p> <p>You also have workflow "stages". Development, typically done on each developers local machine. Staging/testing, which is done on a test server. This is done by copying over the production machines persistent state to the staging machine, and then running any setup/upgrade scripts, and making sure everything works. Finally you the upgrade the production server.</p>
2
2009-10-15T15:49:53Z
[ "python", "database", "zenoss" ]
What is the typical workflow for development of a Zenoss ZenPack?
1,573,166
<p>ZenPack development seems to involve the creation of a variety of persistent state. There are model classes which represent explicitly persistent state. There are skins which are associated with model objects. There are organizers and instances of persistent classes (data sources, graphs, etc).</p> <p>Considering that during development, many things are done wrong before they're done right, and considering that loading up a ZenPack that does things wrong has persistent consequences on the Zenoss instance it is loaded into and that these consequences are hard to undo, what is the usual approach for development of a ZenPack?</p>
2
2009-10-15T15:35:53Z
7,033,005
<p>I am working on this very problem this week with Zenoss 3.1.</p> <p><strong>Caveat-</strong> If you make a bad zenpack - no wait - <strong>when</strong> you make a bad one, it can get stuck in Zope's db, and there is no way to get it out AFAIK. So-</p> <p><strong>First use the GUI to make a complete backup of a clean Zenoss site.</strong></p> <p>Later you will need to restore using zenrestore to clean up the mess.</p> <p>There are two answers, I think:</p> <p><strong>1) if its a portlet-</strong></p> <p>Portlets can only be installed using an egg. Normally Zenoss docs recommend you create eggs using the GUI interface, but that makes for a ridiculous development iteration. However there are explanations in the docs of other ways. If your code, possibly starting with a well-know community portlet like Show Graph or Google Maps, is correct for portlets as opposed to regular zenpacks, then </p> <ul> <li><p>you name the top directory of your code in the standard zenpack form, with versions. </p></li> <li><p>cd into that directory and run</p></li> </ul> <p><code>python setup.py bdist_egg</code></p> <p>which will create dist and build directories.</p> <ul> <li><p>The egg will be in the dist directory. </p></li> <li><p>Install the egg using the GUI.</p></li> <li><p>Notice its not fully installed... grrrrrr.</p></li> <li><p>Restart the daemons - <code>zopectl restart ; zenhub restart</code></p></li> <li><p>Test. </p></li> <li><p>Delete the portlet using the GUI. Repeat.</p></li> </ul> <p><strong>Gotchas:</strong> - You must have setup.py and maybe one or more of- INSTALL.txt MANIFEST.in README.txt in the top directory.</p> <ul> <li><p>Setup.py must match your directory names.</p></li> <li><p>If you are using old or copied <strong>init</strong>.py files with their <strong>init</strong>.pyc versions, then you may need to delete these pyc files to force the python script to re-create them.</p></li> <li><p>I like to run the script as follows just to be certain: <code>rm -f ./dist ./build ; python setup.py bdist_egg</code> </p></li> </ul> <p><strong>2) If it's a regular zenpack</strong></p> <p>The docs tell you how to do this.</p> <ul> <li><p>Get your zenpack installed from whatever source; often you will just start with the empty one created by the GUI.</p></li> <li><p>Copy the files from <code>/usr/local/zenoss/zenoss/Zenpacks/yourzenpack</code> into your code development area. </p></li> <li><p>Un-install the zenpack using the GUI.</p></li> <li><p>On the command line as zenoss user, run the zpack install --link command ( look up syntax) to install the zenpack thats actually in your code area.</p></li> <li><p>Test</p></li> <li><p>Update your code.</p></li> <li><p>On the command line as zenoss, run <code>zopectl restart ; zenhub restart</code></p></li> <li><p>Test.</p></li> <li><p>Repeat. Be Happy.</p></li> </ul>
2
2011-08-11T21:21:22Z
[ "python", "database", "zenoss" ]
How do you implement a web-based direct deposit/eCheck payment system?
1,573,383
<p>I'm trying to develop a site that will allow users to pay for services with eChecks that other users are offering.</p> <p>The purchaser would pay money that would go into my account via direct deposit. The service provider could later withdraw money up to the amount they accumulated to their bank account.</p> <p>Every time I ask payment gateway providers about this, they act like I'm speaking in a foreign language. Paypal told me that their API doesn't allow direct deposits or eChecks.</p> <p>What sort of merchant account / gateway combination do I need to do this? Can you direct me to any specific companies? I use Python/Django to develop applications, do you know of any libraries that might assist me with this endeavor?</p>
4
2009-10-15T16:08:35Z
1,573,504
<p>I'm certain that you would not be able to do facilitated ACH/EFT transfers directly from one user's account to another user's account. However, as long as there's a third party in between the two users, this should be possible. But I'm assuming you'd want to do that anyways, so that you can get paid. The trick is finding a provider that will do both withdrawals and deposits, since most providers only give you withdrawals. I'd recommend at least talking to <a href="http://www.braintreepaymentsolutions.com/" rel="nofollow">BrainTree</a>; they're by far my favorite payment provider. If they don't work out though, you might try <a href="http://www.allianceach.com/" rel="nofollow">Alliance</a>, however, I've never used them, so take that recommendation with a grain of salt.</p>
3
2009-10-15T16:24:42Z
[ "python", "django", "payment-gateway", "payment" ]
Python def function: How do you specify the end of the function?
1,573,548
<p>I'm just learning python and confused when a "def" of a function ends?</p> <p>I see code samples like:</p> <pre><code>def myfunc(a=4,b=6): sum = a + b return sum myfunc() </code></pre> <p>I know it doesn't end because of the return (because I've seen if statements... if FOO than return BAR, else return FOOBAR). How does Python know this isn't a recursive function that calls itself? When the function runs does it just keep going through the program until it finds a return? That'd lead to some interesting errors.</p> <p>Thanks</p>
17
2009-10-15T16:32:53Z
1,573,554
<p>white spaces matter. when block is finished, that's when the function definition is finished.</p> <p>when function runs, it keeps going until it finishes, or until <code>return</code> or <code>yield</code> statement is encountered. If function finishes without encountering <code>return</code> or <code>yield</code> statements <code>None</code> is returned implicitly.</p> <p>there is plenty more information in <a href="http://docs.python.org/tutorial/controlflow.html#defining-functions" rel="nofollow">the tutorial</a>.</p>
0
2009-10-15T16:34:38Z
[ "python", "syntax" ]
Python def function: How do you specify the end of the function?
1,573,548
<p>I'm just learning python and confused when a "def" of a function ends?</p> <p>I see code samples like:</p> <pre><code>def myfunc(a=4,b=6): sum = a + b return sum myfunc() </code></pre> <p>I know it doesn't end because of the return (because I've seen if statements... if FOO than return BAR, else return FOOBAR). How does Python know this isn't a recursive function that calls itself? When the function runs does it just keep going through the program until it finds a return? That'd lead to some interesting errors.</p> <p>Thanks</p>
17
2009-10-15T16:32:53Z
1,573,555
<p>In Python whitespace is significant. The function ends when the indentation becomes smaller (less).</p> <pre><code>def f(): pass # first line pass # second line pass # &lt;-- less indentation, not part of function f. </code></pre> <p>Note that one-line functions can be written without indentation, on one line:</p> <pre><code>def f(): pass </code></pre> <p>And, then there is the use of semi-colons, but this is <strong>not recommended</strong>:</p> <pre><code>def f(): pass; pass </code></pre> <p>The three forms above show how the end of a function is defined <em>syntactically</em>. As for the <em>semantics</em>, in Python there are three ways to exit a function:</p> <ul> <li><p>Using the <code>return</code> statement. This works the same as in any other imperative programming language you may know.</p></li> <li><p>Using the <code>yield</code> statement. This means that the function is a generator. Explaining its semantics is beyond the scope of this answer. Have a look at <a href="http://stackoverflow.com/questions/231767/can-somebody-explain-me-the-python-yield-statement"><em>Can somebody explain me the python yield statement?</em></a></p></li> <li><p>By simply executing the last statement. If there are no more statements and the last statement is not a <code>return</code> statement, then the function exists as if the last statement were <code>return None</code>. That is to say, without an explicit <code>return</code> statement a function returns <code>None</code>. This function returns <code>None</code>:</p> <pre><code>def f(): pass </code></pre> <p>And so does this one:</p> <pre><code>def f(): 42 </code></pre></li> </ul>
40
2009-10-15T16:34:42Z
[ "python", "syntax" ]
Python def function: How do you specify the end of the function?
1,573,548
<p>I'm just learning python and confused when a "def" of a function ends?</p> <p>I see code samples like:</p> <pre><code>def myfunc(a=4,b=6): sum = a + b return sum myfunc() </code></pre> <p>I know it doesn't end because of the return (because I've seen if statements... if FOO than return BAR, else return FOOBAR). How does Python know this isn't a recursive function that calls itself? When the function runs does it just keep going through the program until it finds a return? That'd lead to some interesting errors.</p> <p>Thanks</p>
17
2009-10-15T16:32:53Z
1,573,556
<p>Python is white-space sensitive in regard to the indentation. Once the indentation level falls back to the level at which the function is defined, the function has ended.</p>
20
2009-10-15T16:34:47Z
[ "python", "syntax" ]
Python def function: How do you specify the end of the function?
1,573,548
<p>I'm just learning python and confused when a "def" of a function ends?</p> <p>I see code samples like:</p> <pre><code>def myfunc(a=4,b=6): sum = a + b return sum myfunc() </code></pre> <p>I know it doesn't end because of the return (because I've seen if statements... if FOO than return BAR, else return FOOBAR). How does Python know this isn't a recursive function that calls itself? When the function runs does it just keep going through the program until it finds a return? That'd lead to some interesting errors.</p> <p>Thanks</p>
17
2009-10-15T16:32:53Z
1,573,564
<p>It uses indentation</p> <pre><code> def func(): funcbody if cond: ifbody outofif outof_func </code></pre>
1
2009-10-15T16:35:56Z
[ "python", "syntax" ]
Python def function: How do you specify the end of the function?
1,573,548
<p>I'm just learning python and confused when a "def" of a function ends?</p> <p>I see code samples like:</p> <pre><code>def myfunc(a=4,b=6): sum = a + b return sum myfunc() </code></pre> <p>I know it doesn't end because of the return (because I've seen if statements... if FOO than return BAR, else return FOOBAR). How does Python know this isn't a recursive function that calls itself? When the function runs does it just keep going through the program until it finds a return? That'd lead to some interesting errors.</p> <p>Thanks</p>
17
2009-10-15T16:32:53Z
1,573,666
<p>To be precise, a block ends when it encounter a non-empty line indented at most the same level with the start. This non empty line is not part of that block For example, the following print ends two blocks at the same time:</p> <pre><code>def foo(): if bar: print "bar" print "baz" # ends the if and foo at the same time </code></pre> <p>The indentation level is less-than-or-equal to both the def and the if, hence it ends them both.</p> <p>Lines with no statement, no matter the indentation, does not matter</p> <pre><code>def foo(): print "The line below has no indentation" print "Still part of foo" </code></pre> <p>But the statement that marks the end of the block must be indented at the same level as any existing indentation. The following, then, is an error:</p> <pre><code>def foo(): print "Still correct" print "Error because there is no block at this indentation" </code></pre> <p>Generally, if you're used to curly braces language, just indent the code like them and you'll be fine.</p> <p>BTW, the "standard" way of indenting is with spaces only, but of course tab only is possible, but please don't mix them both.</p>
6
2009-10-15T16:52:29Z
[ "python", "syntax" ]
Python def function: How do you specify the end of the function?
1,573,548
<p>I'm just learning python and confused when a "def" of a function ends?</p> <p>I see code samples like:</p> <pre><code>def myfunc(a=4,b=6): sum = a + b return sum myfunc() </code></pre> <p>I know it doesn't end because of the return (because I've seen if statements... if FOO than return BAR, else return FOOBAR). How does Python know this isn't a recursive function that calls itself? When the function runs does it just keep going through the program until it finds a return? That'd lead to some interesting errors.</p> <p>Thanks</p>
17
2009-10-15T16:32:53Z
1,574,034
<p>So its the indentation that matters. As other users here have pointed out to you, when the indentation level is at the same point as the def function declaration your function has ended. Keep in mind that you cannot mix tabs and spaces in Python. Most editors provide support for this.</p>
1
2009-10-15T17:56:30Z
[ "python", "syntax" ]
Python def function: How do you specify the end of the function?
1,573,548
<p>I'm just learning python and confused when a "def" of a function ends?</p> <p>I see code samples like:</p> <pre><code>def myfunc(a=4,b=6): sum = a + b return sum myfunc() </code></pre> <p>I know it doesn't end because of the return (because I've seen if statements... if FOO than return BAR, else return FOOBAR). How does Python know this isn't a recursive function that calls itself? When the function runs does it just keep going through the program until it finds a return? That'd lead to some interesting errors.</p> <p>Thanks</p>
17
2009-10-15T16:32:53Z
15,537,588
<p>Interestingly, if you're just typing at the python interactive interpreter, you have to follow a function with a blank line. This does not work:</p> <pre><code>def foo(x): return x+1 print "last" </code></pre> <p>although it is perfectly legal python syntax in a file. There are other syntactic differences when typing to the interpreter too, so beware.</p>
1
2013-03-21T00:54:48Z
[ "python", "syntax" ]
psycopg2 disconnects from server
1,573,579
<p>I've been tackling this for a while. I setup a completely new machine. I've installed a fresh copy of postgresql and all my other dependencies. Basically, I get these database disconnections at random times. I can perform identical requests and either it works or it doesn't. Very nondeterministic in outward appearance. Watching logs at Postgresql, it doesn't even get a connection. Now, I would expect that if it never connected I would get this problem when establishing the connection and getting the cursor, but I get it when trying to actually use the connection later. Given the traceback below, I would expect to see a connection made in the pg logs, and then disconnected for some reason later. I don't, so I wonder if there is some clue in that mismatch.</p> <pre><code>Traceback (most recent call last): File "/usr/local/lib/python2.6/dist-packages/Django-1.1-py2.6.egg/django/core/handlers/wsgi.py", line 242, in __call__ response = self.get_response(request) File "/usr/local/lib/python2.6/dist-packages/Django-1.1-py2.6.egg/django/core/handlers/base.py", line 73, in get_response response = middleware_method(request) File "/usr/local/lib/python2.6/dist-packages/Django-1.1-py2.6.egg/django/middleware/locale.py", line 16, in process_request language = translation.get_language_from_request(request) File "/usr/local/lib/python2.6/dist-packages/Django-1.1-py2.6.egg/django/utils/translation/__init__.py", line 97, in get_language_from_request return real_get_language_from_request(request) File "/usr/local/lib/python2.6/dist-packages/Django-1.1-py2.6.egg/django/utils/translation/trans_real.py", line 349, in get_language_from_request lang_code = request.session.get('django_language', None) File "/usr/local/lib/python2.6/dist-packages/Django-1.1-py2.6.egg/django/contrib/sessions/backends/base.py", line 63, in get return self._session.get(key, default) File "/usr/local/lib/python2.6/dist-packages/Django-1.1-py2.6.egg/django/contrib/sessions/backends/base.py", line 172, in _get_session self._session_cache = self.load() File "/usr/local/lib/python2.6/dist-packages/Django-1.1-py2.6.egg/django/contrib/sessions/backends/db.py", line 16, in load expire_date__gt=datetime.datetime.now() File "/usr/local/lib/python2.6/dist-packages/Django-1.1-py2.6.egg/django/db/models/manager.py", line 120, in get return self.get_query_set().get(*args, **kwargs) File "/usr/local/lib/python2.6/dist-packages/Django-1.1-py2.6.egg/django/db/models/query.py", line 300, in get num = len(clone) File "/usr/local/lib/python2.6/dist-packages/Django-1.1-py2.6.egg/django/db/models/query.py", line 81, in __len__ self._result_cache = list(self.iterator()) File "/usr/local/lib/python2.6/dist-packages/Django-1.1-py2.6.egg/django/db/models/query.py", line 238, in iterator for row in self.query.results_iter(): File "/usr/local/lib/python2.6/dist-packages/Django-1.1-py2.6.egg/django/db/models/sql/query.py", line 287, in results_iter for rows in self.execute_sql(MULTI): File "/usr/local/lib/python2.6/dist-packages/Django-1.1-py2.6.egg/django/db/models/sql/query.py", line 2369, in execute_sql cursor.execute(sql, params) File "/usr/local/lib/python2.6/dist-packages/Django-1.1-py2.6.egg/django/db/backends/util.py", line 19, in execute return self.cursor.execute(sql, params) OperationalError: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. </code></pre>
4
2009-10-15T16:38:27Z
1,573,673
<p>Do you <code>fork()</code> child processes (use preforked FastCGI or something similar)? This might be the reason that connection established in parent process doesn't work in child. If you use preforked method it's easy to switch to threading to see whether the problem has gone away. I saw exactly the same floating error in such case.</p>
2
2009-10-15T16:53:15Z
[ "python", "database", "django", "postgresql", "psycopg2" ]
psycopg2 disconnects from server
1,573,579
<p>I've been tackling this for a while. I setup a completely new machine. I've installed a fresh copy of postgresql and all my other dependencies. Basically, I get these database disconnections at random times. I can perform identical requests and either it works or it doesn't. Very nondeterministic in outward appearance. Watching logs at Postgresql, it doesn't even get a connection. Now, I would expect that if it never connected I would get this problem when establishing the connection and getting the cursor, but I get it when trying to actually use the connection later. Given the traceback below, I would expect to see a connection made in the pg logs, and then disconnected for some reason later. I don't, so I wonder if there is some clue in that mismatch.</p> <pre><code>Traceback (most recent call last): File "/usr/local/lib/python2.6/dist-packages/Django-1.1-py2.6.egg/django/core/handlers/wsgi.py", line 242, in __call__ response = self.get_response(request) File "/usr/local/lib/python2.6/dist-packages/Django-1.1-py2.6.egg/django/core/handlers/base.py", line 73, in get_response response = middleware_method(request) File "/usr/local/lib/python2.6/dist-packages/Django-1.1-py2.6.egg/django/middleware/locale.py", line 16, in process_request language = translation.get_language_from_request(request) File "/usr/local/lib/python2.6/dist-packages/Django-1.1-py2.6.egg/django/utils/translation/__init__.py", line 97, in get_language_from_request return real_get_language_from_request(request) File "/usr/local/lib/python2.6/dist-packages/Django-1.1-py2.6.egg/django/utils/translation/trans_real.py", line 349, in get_language_from_request lang_code = request.session.get('django_language', None) File "/usr/local/lib/python2.6/dist-packages/Django-1.1-py2.6.egg/django/contrib/sessions/backends/base.py", line 63, in get return self._session.get(key, default) File "/usr/local/lib/python2.6/dist-packages/Django-1.1-py2.6.egg/django/contrib/sessions/backends/base.py", line 172, in _get_session self._session_cache = self.load() File "/usr/local/lib/python2.6/dist-packages/Django-1.1-py2.6.egg/django/contrib/sessions/backends/db.py", line 16, in load expire_date__gt=datetime.datetime.now() File "/usr/local/lib/python2.6/dist-packages/Django-1.1-py2.6.egg/django/db/models/manager.py", line 120, in get return self.get_query_set().get(*args, **kwargs) File "/usr/local/lib/python2.6/dist-packages/Django-1.1-py2.6.egg/django/db/models/query.py", line 300, in get num = len(clone) File "/usr/local/lib/python2.6/dist-packages/Django-1.1-py2.6.egg/django/db/models/query.py", line 81, in __len__ self._result_cache = list(self.iterator()) File "/usr/local/lib/python2.6/dist-packages/Django-1.1-py2.6.egg/django/db/models/query.py", line 238, in iterator for row in self.query.results_iter(): File "/usr/local/lib/python2.6/dist-packages/Django-1.1-py2.6.egg/django/db/models/sql/query.py", line 287, in results_iter for rows in self.execute_sql(MULTI): File "/usr/local/lib/python2.6/dist-packages/Django-1.1-py2.6.egg/django/db/models/sql/query.py", line 2369, in execute_sql cursor.execute(sql, params) File "/usr/local/lib/python2.6/dist-packages/Django-1.1-py2.6.egg/django/db/backends/util.py", line 19, in execute return self.cursor.execute(sql, params) OperationalError: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. </code></pre>
4
2009-10-15T16:38:27Z
1,579,793
<p>This is a very similar question to the one posted here:</p> <p><a href="http://stackoverflow.com/questions/393637/django-fastcgi-randomly-raising-operationalerror">http://stackoverflow.com/questions/393637/django-fastcgi-randomly-raising-operationalerror</a></p> <p>I imagine the answer will be the same to both if and when someone eventually figured it out. This same problem has been bothering me for about a month now and I have no idea what could be causing it.</p>
3
2009-10-16T18:58:24Z
[ "python", "database", "django", "postgresql", "psycopg2" ]
Output in two rows for multiple columns in python
1,573,671
<p>I'm working with an output list that contains the following information: </p> <pre><code>[start position, stop position, chromosome, [('sample name', 'sample value'), ('sample name','sample value')...]] [[59000, 59500, chr1, [('cn_04', '1.362352462'), ('cn_01', '1.802001235')]], [100000, 110000, chr1, [('cn_03', '1.887268908'), ('cn_02', '1.990457407'), ('cn_01', '4.302275763')]], [63500, 64000, chr1, [('cn_03', '1.887268908'), ('cn_02', '1.990457407'), ('cn_01', '4.302275763')]] ...] </code></pre> <p>I want to write it to an excel file that will format it with the sample names as the titles of columns and then the values for the samples in columns. Some samples don't have values so these spaces would be blank or have no data notation. Something that looks Like this (sorry had to use >> to denote column separations):</p> <pre><code>cn_01 cn_02 cn_03 cn_04 cn_05 cn_06 start stop chromosome 1.802 "" "" 1.362 "" "" 59000 59500 chr1 4.302 1.990 1.887 "" "" "" 100000 110000 chr1 </code></pre> <p>Any help would be great. </p>
0
2009-10-15T16:53:09Z
1,573,752
<p>You can create a simple text file with "*.csv" extension. Separate each field (column) by a comma. Optionally, use quotation marks for text fields, especially if a field is expected to contain your delimiter (comma). You can even put excel formulas (preceded by '=') and excel will parse them correctly.</p> <p>Double click on any csv file will open it in excel (unless your computer has other settings).</p> <p>You can also use the <a href="http://docs.python.org/library/csv.html" rel="nofollow">csv module</a></p> <p>The <a href="http://rads.stackoverflow.com/amzn/click/0596158068" rel="nofollow">Learning Python book</a> contains examples with more complex control (formatting, spreadsheets) using Windows COM components</p> <p>EDIT: I have just seen <a href="http://www.python-excel.org/" rel="nofollow">this site</a>. The PDF tutorial seems to be very detailed. Never used this.</p>
0
2009-10-15T17:07:20Z
[ "python", "file", "format", "bioinformatics" ]
Output in two rows for multiple columns in python
1,573,671
<p>I'm working with an output list that contains the following information: </p> <pre><code>[start position, stop position, chromosome, [('sample name', 'sample value'), ('sample name','sample value')...]] [[59000, 59500, chr1, [('cn_04', '1.362352462'), ('cn_01', '1.802001235')]], [100000, 110000, chr1, [('cn_03', '1.887268908'), ('cn_02', '1.990457407'), ('cn_01', '4.302275763')]], [63500, 64000, chr1, [('cn_03', '1.887268908'), ('cn_02', '1.990457407'), ('cn_01', '4.302275763')]] ...] </code></pre> <p>I want to write it to an excel file that will format it with the sample names as the titles of columns and then the values for the samples in columns. Some samples don't have values so these spaces would be blank or have no data notation. Something that looks Like this (sorry had to use >> to denote column separations):</p> <pre><code>cn_01 cn_02 cn_03 cn_04 cn_05 cn_06 start stop chromosome 1.802 "" "" 1.362 "" "" 59000 59500 chr1 4.302 1.990 1.887 "" "" "" 100000 110000 chr1 </code></pre> <p>Any help would be great. </p>
0
2009-10-15T16:53:09Z
1,573,881
<p>Here's one approach. I made the simplifying assumption that there is a small finite limit to the possible number of observations, so I just loop from 1 to 6 explicitly. You can easily expand the upper limit of the loop, although if you go past 9 the logic in the get_obs function will need to change. You could also write something more complex to first scan through all the data and get all the possible observation names, but I didn't want to put in that effort if it's not necessary.</p> <p>This could be somewhat simplified if you used a dictionary instead of a list of tuples to hold the observation data for each row.</p> <pre><code>data = [[59000, 59500, 'chr1', [('cn_04', '1.362352462'), ('cn_01', '1.802001235')]], [100000, 110000, 'chr1', [('cn_03', '1.887268908'), ('cn_02', '1.990457407'), ('cn_01', '4.302275763')]], [63500, 64000, 'chr1', [('cn_03', '1.887268908'), ('cn_02', '1.990457407'), ('cn_01', '4.302275763')]] ] def get_obs( num, obslist ): keyval = 'cn_0' + str(num) for obs in obslist: if obs[0] == keyval: return obs[1] return "." for data_row in data: output_row = "" for obs in range(1,7): output_row += get_obs( obs, data_row[3] ) + '\t' output_row += str(data_row[0]) + '\t' output_row += str(data_row[1]) + '\t' output_row += str(data_row[2]) print output_row </code></pre>
0
2009-10-15T17:27:17Z
[ "python", "file", "format", "bioinformatics" ]
Output in two rows for multiple columns in python
1,573,671
<p>I'm working with an output list that contains the following information: </p> <pre><code>[start position, stop position, chromosome, [('sample name', 'sample value'), ('sample name','sample value')...]] [[59000, 59500, chr1, [('cn_04', '1.362352462'), ('cn_01', '1.802001235')]], [100000, 110000, chr1, [('cn_03', '1.887268908'), ('cn_02', '1.990457407'), ('cn_01', '4.302275763')]], [63500, 64000, chr1, [('cn_03', '1.887268908'), ('cn_02', '1.990457407'), ('cn_01', '4.302275763')]] ...] </code></pre> <p>I want to write it to an excel file that will format it with the sample names as the titles of columns and then the values for the samples in columns. Some samples don't have values so these spaces would be blank or have no data notation. Something that looks Like this (sorry had to use >> to denote column separations):</p> <pre><code>cn_01 cn_02 cn_03 cn_04 cn_05 cn_06 start stop chromosome 1.802 "" "" 1.362 "" "" 59000 59500 chr1 4.302 1.990 1.887 "" "" "" 100000 110000 chr1 </code></pre> <p>Any help would be great. </p>
0
2009-10-15T16:53:09Z
1,573,885
<p>Never do these types of nested lists/dictionary, they are not pythonic and are very likely to bring you to an error.</p> <p>Instead, either use a class:</p> <pre><code>&gt;&gt;&gt; class Gene: def __init__(self, start, end, chromosome, transcripts): self.start = start self.end = end self.chromosome = chromosome self.transcripts = transcripts &gt;&gt;&gt; gene1 = Gene(59000, 59500, 'chr1', [('cn_04', '1.362352462'), ('cn_01', '1.802001235')]) &gt;&gt;&gt; gene2 = Gene(100000, 110000, 'chr1', [('cn_03', '1.887268908'), ('cn_02', '1.990457407'), ('cn_01', '4.302275763')]) &gt;&gt;&gt; genes = [gene1, gene2, ...] &gt;&gt;&gt; gene1.start 59000 &gt;&gt;&gt; genes[1].start 59000 </code></pre> <p>or either use numpy's recordarrays and matrixes.</p> <p>To read and write CSV file you can use numpy's recarrays and functions.</p> <pre><code>&gt;&gt;&gt; from matplotlib.mlab import csv2rec, rec2csv &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; d = array([(0, 10, 'chr1', [1, 2]), (20, 30, 'chr2', [1,2])], dtype=[('start', int), ('end', int), ('chromosome', 'S8'), ('transcripts', list)]) # all values in the 'chromosome' column &gt;&gt;&gt; d['chromosome'] array(['chr1', 'chr2'], dtype='|S8') # records in which chromosome == 1 &gt;&gt;&gt; d[d['chromosome'] == 'chr1'] # print first record &gt;&gt;&gt; d[0] (0, 10, 'chr1', [1, 2]) # save it to a csv file: &gt;&gt;&gt; rec2csv(d, 'csvfile.txt', delimiter='\t') </code></pre>
-1
2009-10-15T17:27:30Z
[ "python", "file", "format", "bioinformatics" ]
Output in two rows for multiple columns in python
1,573,671
<p>I'm working with an output list that contains the following information: </p> <pre><code>[start position, stop position, chromosome, [('sample name', 'sample value'), ('sample name','sample value')...]] [[59000, 59500, chr1, [('cn_04', '1.362352462'), ('cn_01', '1.802001235')]], [100000, 110000, chr1, [('cn_03', '1.887268908'), ('cn_02', '1.990457407'), ('cn_01', '4.302275763')]], [63500, 64000, chr1, [('cn_03', '1.887268908'), ('cn_02', '1.990457407'), ('cn_01', '4.302275763')]] ...] </code></pre> <p>I want to write it to an excel file that will format it with the sample names as the titles of columns and then the values for the samples in columns. Some samples don't have values so these spaces would be blank or have no data notation. Something that looks Like this (sorry had to use >> to denote column separations):</p> <pre><code>cn_01 cn_02 cn_03 cn_04 cn_05 cn_06 start stop chromosome 1.802 "" "" 1.362 "" "" 59000 59500 chr1 4.302 1.990 1.887 "" "" "" 100000 110000 chr1 </code></pre> <p>Any help would be great. </p>
0
2009-10-15T16:53:09Z
1,574,384
<p>For sending data to Excel, I would use CSV instead of a fixed-length text format; that way, if it turns out (say) that you need more significant figures in your float values, the format of your output doesn't change. Also, you can just open CSV files in Excel; you don't have to import them. And the <code>csv.writer</code> deals with all of the data-type conversion issues for you.</p> <p>I'd also take advantage of the (apparent) fact that the 4th item in each observation appears to be a set of key/value pairs, which the <code>dict</code> function can turn into a dictionary. Assuming that you know what all of the keys are, you can specify the order that you want them to appear in your output simply by putting them in a list (called <code>keys</code> in the below code). Then it's simple to create an ordered list of values with a list comprehension. Thus:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; import csv &gt;&gt;&gt; keys = ['cn_01', 'cn_02', 'cn_03', 'cn_04', 'cn_05', 'cn_06'] &gt;&gt;&gt; data = [[59000, 59500, 'chr1', [('cn_04', '1.362352462'), ('cn_01', '1.802001235')]], [100000, 110000, 'chr1', [('cn_03', '1.887268908'), ('cn_02', '1.990457407'), ('cn_01', '4.302275763')]], [63500, 64000, 'chr1', [('cn_03', '1.887268908'), ('cn_02', '1.990457407'), ('cn_01', '4.302275763')]]] &gt;&gt;&gt; writer = csv.writer(sys.stdout) &gt;&gt;&gt; writer.writerow(keys + ['start', 'stop', 'chromosome']) cn_01,cn_02,cn_03,cn_04,cn_05,cn_06,start,stop,chromosome &gt;&gt;&gt;&gt;for obs in data: d = dict(obs[3]) row = [d.get(k, None) for k in keys] + obs[0:3] writer.writerow(row) 1.802001235,,,1.362352462,,,59000,59500,chr1 4.302275763,1.990457407,1.887268908,,,,100000,110000,chr1 4.302275763,1.990457407,1.887268908,,,,63500,64000,chr1 </code></pre> <p>The above writes the data to <code>sys.stdout</code>; to create a real CSV file you'd do something like:</p> <pre><code>with open('file.csv', 'w') as f: writer = csv.writer(f) # now use the writer to write out the data </code></pre>
3
2009-10-15T19:06:11Z
[ "python", "file", "format", "bioinformatics" ]
Output in two rows for multiple columns in python
1,573,671
<p>I'm working with an output list that contains the following information: </p> <pre><code>[start position, stop position, chromosome, [('sample name', 'sample value'), ('sample name','sample value')...]] [[59000, 59500, chr1, [('cn_04', '1.362352462'), ('cn_01', '1.802001235')]], [100000, 110000, chr1, [('cn_03', '1.887268908'), ('cn_02', '1.990457407'), ('cn_01', '4.302275763')]], [63500, 64000, chr1, [('cn_03', '1.887268908'), ('cn_02', '1.990457407'), ('cn_01', '4.302275763')]] ...] </code></pre> <p>I want to write it to an excel file that will format it with the sample names as the titles of columns and then the values for the samples in columns. Some samples don't have values so these spaces would be blank or have no data notation. Something that looks Like this (sorry had to use >> to denote column separations):</p> <pre><code>cn_01 cn_02 cn_03 cn_04 cn_05 cn_06 start stop chromosome 1.802 "" "" 1.362 "" "" 59000 59500 chr1 4.302 1.990 1.887 "" "" "" 100000 110000 chr1 </code></pre> <p>Any help would be great. </p>
0
2009-10-15T16:53:09Z
1,576,437
<p>You can also use <a href="http://pypi.python.org/pypi/xlwt" rel="nofollow">xlwt</a> to write .xls files directly, without touching Excel. <a href="http://panela.blog-city.com/pyexcelerator%5Fxlwt%5Fcheatsheet%5Fcreate%5Fnative%5Fexcel%5Ffrom%5Fpu.htm" rel="nofollow">More info</a>.</p> <p>Here is some sample code to get you started (far from perfect):</p> <pre><code>import xlwt as xl def list2xls(data, fn=None, col_names=None, row_names=None): wb = xl.Workbook() ws = wb.add_sheet('output') if col_names: _write_1d_list_horz(ws, 0, 1, col_names) if row_names: _write_1d_list_vert(ws, 1, 0, row_names) _write_matrix(ws, 1, 1, data) if not fn: fn = 'test.xls' wb.save(fn) def _write_matrix(ws, row_start, col_start, mat): for irow, row in enumerate(mat): _write_1d_list_horz(ws, irow + row_start, col_start, row) def _write_1d_list_horz(ws, row, col, list): for i, val in enumerate(list): ws.write(row, i + col, val) def _write_1d_list_vert(ws, row, col, list): for i, val in enumerate(list): ws.write(row + i, col, val) </code></pre> <p>Call list2xls, with data as a 2-d list, and optional column and row names as lists.</p>
0
2009-10-16T06:31:44Z
[ "python", "file", "format", "bioinformatics" ]