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 |
|---|---|---|---|---|---|---|---|---|---|
Concatenating Dictionaries | 1,232,904 | <p>I have three lists, the first is a list of names, the second is a list of dictionaries, and the third is a list of data. Each position in a list corresponds with the same positions in the other lists. List_1[0] has corresponding data in List_2[0] and List_3[0], etc. I would like to turn these three lists into a dictionary inside a dictionary, with the values in List_1 being the primary keys. How do I do this while keeping everything in order?</p>
| 6 | 2009-08-05T12:22:03Z | 1,232,942 | <p>Python 3:</p>
<pre><code>combined = {name:dict(data1=List_2[i], data2=List_3[i]) for i, name in enumerate(List_1)}
</code></pre>
<p>Python 2.5:</p>
<pre><code>combined = {}
for i, name in enumerate(List_1):
combined[name] = dict(data1=List_2[i], data2=List_3[i])
</code></pre>
| 1 | 2009-08-05T12:28:07Z | [
"python",
"dictionary",
"merge",
"key"
] |
Concatenating Dictionaries | 1,232,904 | <p>I have three lists, the first is a list of names, the second is a list of dictionaries, and the third is a list of data. Each position in a list corresponds with the same positions in the other lists. List_1[0] has corresponding data in List_2[0] and List_3[0], etc. I would like to turn these three lists into a dictionary inside a dictionary, with the values in List_1 being the primary keys. How do I do this while keeping everything in order?</p>
| 6 | 2009-08-05T12:22:03Z | 1,234,352 | <p>if the order of these things matters, you should not use a dictionary. by definition, they are unordered. you can use one of the <a href="http://www.python.org/dev/peps/pep-0372/#reference-implementation" rel="nofollow">many ordered_dictionary implementations</a> floating around, or wait for python 2.7 or 3.1 which will include an ordered dictionary implementation in the collections module.</p>
| 0 | 2009-08-05T16:33:25Z | [
"python",
"dictionary",
"merge",
"key"
] |
Python multiprocessing easy way to implement a simple counter? | 1,233,222 | <p>Hey everyone, I am using multiprocessing in python now. and I am just wondering whether there exists some sort of simple counter variable that each process when they are done processing some task could just increment ( kind of like how much work done in total).</p>
<p>I looked up the API for Value, don't think it's mutable.</p>
| 7 | 2009-08-05T13:19:56Z | 1,233,363 | <p><code>Value</code> is indeed mutable; you specify the datatype you want from the <code>ctypes</code> module and then it can be mutated. Here's a complete, working script that demonstrates this:</p>
<pre><code>from time import sleep
from ctypes import c_int
from multiprocessing import Value, Lock, Process
counter = Value(c_int) # defaults to 0
counter_lock = Lock()
def increment():
with counter_lock:
counter.value += 1
def do_something():
print("I'm a separate process!")
increment()
Process(target=do_something).start()
sleep(1)
print counter.value # prints 1, because Value is shared and mutable
</code></pre>
<p>EDIT: Luper correctly points out in a comment below that <code>Value</code> values are locked by default. This is correct in the sense that even if an assignment consists of multiple operations (such as assigning a string which might be many characters) then this assignment is atomic. However, when incrementing a counter you'll still need an external lock as provided in my example, because incrementing loads the current value and then increments it and then assigns the result back to the <code>Value</code>.</p>
<p>So without an external lock, you might run into the following circumstance:</p>
<ul>
<li>Process 1 reads (atomically) the current value of the counter, then increments it</li>
<li>before Process 1 can assign the incremented counter back to the <code>Value</code>, a context switch occurrs</li>
<li>Process 2 reads (atomically) the current (unincremented) value of the counter, increments it, and assigns the incremented result (atomically) back to <code>Value</code></li>
<li>Process 1 assigns its incremented value (atomically), blowing away the increment performed by Process 2</li>
</ul>
| 20 | 2009-08-05T13:46:06Z | [
"python",
"multiprocessing"
] |
Hit a URL on other server from google app engine | 1,233,284 | <p>I want to hit a URL from python in google app engine. Can any one please tell me how can i hit the URL using python in google app engine. </p>
| 1 | 2009-08-05T13:32:05Z | 1,233,295 | <p>You can use the <a href="http://code.google.com/appengine/docs/python/urlfetch/overview.html" rel="nofollow">URLFetch API</a></p>
<pre><code>from google.appengine.api import urlfetch
url = "http://www.google.com/"
result = urlfetch.fetch(url)
if result.status_code == 200:
doSomethingWithResult(result.content)
</code></pre>
| 6 | 2009-08-05T13:34:23Z | [
"python",
"google-app-engine",
"url"
] |
Hit a URL on other server from google app engine | 1,233,284 | <p>I want to hit a URL from python in google app engine. Can any one please tell me how can i hit the URL using python in google app engine. </p>
| 1 | 2009-08-05T13:32:05Z | 1,258,042 | <p>It always depends on post or get. urllib can post to a form somewhere else, if we want the rather tricky thing validate between different hashes (sha and md5)</p>
<pre><code>import urllib
data = urllib.urlencode({"id" : str(d), "password" : self.request.POST['passwd'], "edit" : "edit"})
result = urlfetch.fetch(url="http://www..../Login.do",
payload=data,
method=urlfetch.POST,
headers={'Content-Type': 'application/x-www-form-urlencoded'})
if result.content.find('loggedInOrYourInfo') > 0:
self.response.out.write("clear")
else:
self.response.out.write("wrong password ")
</code></pre>
| 0 | 2009-08-11T01:20:52Z | [
"python",
"google-app-engine",
"url"
] |
Could not import Django settings into Google App Engine | 1,233,326 | <p>Hello all you Google App Engine experts, </p>
<p>I have used Django a little before but am new to Google App Engine and
am trying to use it's development web server with Django for the first time. </p>
<p>I don't know if this is relevent but I previously had Django 1.1 and
Python 2.6 on my Windows XP and even though I have uninstalled Python
2.6 there is still a folder and entries in the registry.</p>
<p>I have followed the instructions from Google but when I browse to the GAE developemnt web server it cannot find my settings
(details below). </p>
<p>Any hints gratefully received.</p>
<p>Regards</p>
<p>Geoff </p>
<pre><code>C:\Documents and Settings\GeoffK\My Documents\ing\ingsite>echo %PATH%
C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS
\system32\WindowsPowerShell\v1.0;;C:\Python25;C:\Python25\Lib\site-
packages\django\bin;C:\Documents and Settings\GeoffK\My Documents\ing
\ingsite;C:\Program Files\Google\google_appengine\
C:\Documents and Settings\GeoffK\My Documents\ing\ingsite>echo
%PYTHONPATH%
C:\Documents and Settings\GeoffK\My Documents\ing\ingsite
C:\Documents and Settings\GeoffK\My Documents\ing\ingsite>C:\Documents
and Settings\GeoffK\My Documents\ing\ingsite>dev_appserver.py --
debug_imports ingiliz\
INFO 2009-08-04 07:29:45,328 appengine_rpc.py:157] Server:
appengine.google.
com
INFO 2009-08-04 07:29:45,358 appcfg.py:322] Checking for updates
to the SDK.
INFO 2009-08-04 07:29:45,578 appcfg.py:336] The SDK is up to date.
WARNING 2009-08-04 07:29:45,578 datastore_file_stub.py:404] Could not
read data
store data from c:\docume~1\geoffk\locals~1\temp
\dev_appserver.datastore
WARNING 2009-08-04 07:29:45,578 datastore_file_stub.py:404] Could not
read data
store data from c:\docume~1\geoffk\locals~1\temp
\dev_appserver.datastore.history
WARNING 2009-08-04 07:29:45,608 dev_appserver.py:3296] Could not
initialize ima
ges API; you are likely missing the Python "PIL" module. ImportError:
No module
named _imaging
INFO 2009-08-04 07:29:45,625 dev_appserver_main.py:465] Running
application
ingiliz on port 8080: http://localhost:8080
</code></pre>
<p>.....
Now attempting to browse
if need more detail here I can post
..... </p>
<pre><code> if not settings.DATABASE_ENGINE:
File "C:\Python25\lib\site-packages\django\conf\__init__.py", line
28, in __ge
tattr__
self._import_settings()
File "C:\Python25\lib\site-packages\django\conf\__init__.py", line
59, in _imp
ort_settings
self._target = Settings(settings_module)
File "C:\Python25\lib\site-packages\django\conf\__init__.py", line
94, in __in
it__
raise ImportError, "Could not import settings '%s' (Is it on
sys.path? Does
it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'settings' (Is it on sys.path?
Does it ha
ve syntax errors?): No module named settings
INFO 2009-08-04 07:31:02,187 dev_appserver.py:2982] "GET / HTTP/
1.1" 500 -
</code></pre>
| 0 | 2009-08-05T13:40:06Z | 1,424,757 | <p>I had a similar problem and I put an empty settings.py file in my root directory and it worked.</p>
<p>Good Luck</p>
| 2 | 2009-09-15T01:59:06Z | [
"python",
"django",
"google-app-engine"
] |
Could not import Django settings into Google App Engine | 1,233,326 | <p>Hello all you Google App Engine experts, </p>
<p>I have used Django a little before but am new to Google App Engine and
am trying to use it's development web server with Django for the first time. </p>
<p>I don't know if this is relevent but I previously had Django 1.1 and
Python 2.6 on my Windows XP and even though I have uninstalled Python
2.6 there is still a folder and entries in the registry.</p>
<p>I have followed the instructions from Google but when I browse to the GAE developemnt web server it cannot find my settings
(details below). </p>
<p>Any hints gratefully received.</p>
<p>Regards</p>
<p>Geoff </p>
<pre><code>C:\Documents and Settings\GeoffK\My Documents\ing\ingsite>echo %PATH%
C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS
\system32\WindowsPowerShell\v1.0;;C:\Python25;C:\Python25\Lib\site-
packages\django\bin;C:\Documents and Settings\GeoffK\My Documents\ing
\ingsite;C:\Program Files\Google\google_appengine\
C:\Documents and Settings\GeoffK\My Documents\ing\ingsite>echo
%PYTHONPATH%
C:\Documents and Settings\GeoffK\My Documents\ing\ingsite
C:\Documents and Settings\GeoffK\My Documents\ing\ingsite>C:\Documents
and Settings\GeoffK\My Documents\ing\ingsite>dev_appserver.py --
debug_imports ingiliz\
INFO 2009-08-04 07:29:45,328 appengine_rpc.py:157] Server:
appengine.google.
com
INFO 2009-08-04 07:29:45,358 appcfg.py:322] Checking for updates
to the SDK.
INFO 2009-08-04 07:29:45,578 appcfg.py:336] The SDK is up to date.
WARNING 2009-08-04 07:29:45,578 datastore_file_stub.py:404] Could not
read data
store data from c:\docume~1\geoffk\locals~1\temp
\dev_appserver.datastore
WARNING 2009-08-04 07:29:45,578 datastore_file_stub.py:404] Could not
read data
store data from c:\docume~1\geoffk\locals~1\temp
\dev_appserver.datastore.history
WARNING 2009-08-04 07:29:45,608 dev_appserver.py:3296] Could not
initialize ima
ges API; you are likely missing the Python "PIL" module. ImportError:
No module
named _imaging
INFO 2009-08-04 07:29:45,625 dev_appserver_main.py:465] Running
application
ingiliz on port 8080: http://localhost:8080
</code></pre>
<p>.....
Now attempting to browse
if need more detail here I can post
..... </p>
<pre><code> if not settings.DATABASE_ENGINE:
File "C:\Python25\lib\site-packages\django\conf\__init__.py", line
28, in __ge
tattr__
self._import_settings()
File "C:\Python25\lib\site-packages\django\conf\__init__.py", line
59, in _imp
ort_settings
self._target = Settings(settings_module)
File "C:\Python25\lib\site-packages\django\conf\__init__.py", line
94, in __in
it__
raise ImportError, "Could not import settings '%s' (Is it on
sys.path? Does
it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'settings' (Is it on sys.path?
Does it ha
ve syntax errors?): No module named settings
INFO 2009-08-04 07:31:02,187 dev_appserver.py:2982] "GET / HTTP/
1.1" 500 -
</code></pre>
| 0 | 2009-08-05T13:40:06Z | 1,648,228 | <p>for local testing add these at the start of your main.py</p>
<pre><code>import os, sys
os.environ["DJANGO_SETTINGS_MODULE"] = "appid.settings"
sys.path.append("/app/folder")
</code></pre>
| 1 | 2009-10-30T05:57:53Z | [
"python",
"django",
"google-app-engine"
] |
Could not import Django settings into Google App Engine | 1,233,326 | <p>Hello all you Google App Engine experts, </p>
<p>I have used Django a little before but am new to Google App Engine and
am trying to use it's development web server with Django for the first time. </p>
<p>I don't know if this is relevent but I previously had Django 1.1 and
Python 2.6 on my Windows XP and even though I have uninstalled Python
2.6 there is still a folder and entries in the registry.</p>
<p>I have followed the instructions from Google but when I browse to the GAE developemnt web server it cannot find my settings
(details below). </p>
<p>Any hints gratefully received.</p>
<p>Regards</p>
<p>Geoff </p>
<pre><code>C:\Documents and Settings\GeoffK\My Documents\ing\ingsite>echo %PATH%
C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS
\system32\WindowsPowerShell\v1.0;;C:\Python25;C:\Python25\Lib\site-
packages\django\bin;C:\Documents and Settings\GeoffK\My Documents\ing
\ingsite;C:\Program Files\Google\google_appengine\
C:\Documents and Settings\GeoffK\My Documents\ing\ingsite>echo
%PYTHONPATH%
C:\Documents and Settings\GeoffK\My Documents\ing\ingsite
C:\Documents and Settings\GeoffK\My Documents\ing\ingsite>C:\Documents
and Settings\GeoffK\My Documents\ing\ingsite>dev_appserver.py --
debug_imports ingiliz\
INFO 2009-08-04 07:29:45,328 appengine_rpc.py:157] Server:
appengine.google.
com
INFO 2009-08-04 07:29:45,358 appcfg.py:322] Checking for updates
to the SDK.
INFO 2009-08-04 07:29:45,578 appcfg.py:336] The SDK is up to date.
WARNING 2009-08-04 07:29:45,578 datastore_file_stub.py:404] Could not
read data
store data from c:\docume~1\geoffk\locals~1\temp
\dev_appserver.datastore
WARNING 2009-08-04 07:29:45,578 datastore_file_stub.py:404] Could not
read data
store data from c:\docume~1\geoffk\locals~1\temp
\dev_appserver.datastore.history
WARNING 2009-08-04 07:29:45,608 dev_appserver.py:3296] Could not
initialize ima
ges API; you are likely missing the Python "PIL" module. ImportError:
No module
named _imaging
INFO 2009-08-04 07:29:45,625 dev_appserver_main.py:465] Running
application
ingiliz on port 8080: http://localhost:8080
</code></pre>
<p>.....
Now attempting to browse
if need more detail here I can post
..... </p>
<pre><code> if not settings.DATABASE_ENGINE:
File "C:\Python25\lib\site-packages\django\conf\__init__.py", line
28, in __ge
tattr__
self._import_settings()
File "C:\Python25\lib\site-packages\django\conf\__init__.py", line
59, in _imp
ort_settings
self._target = Settings(settings_module)
File "C:\Python25\lib\site-packages\django\conf\__init__.py", line
94, in __in
it__
raise ImportError, "Could not import settings '%s' (Is it on
sys.path? Does
it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'settings' (Is it on sys.path?
Does it ha
ve syntax errors?): No module named settings
INFO 2009-08-04 07:31:02,187 dev_appserver.py:2982] "GET / HTTP/
1.1" 500 -
</code></pre>
| 0 | 2009-08-05T13:40:06Z | 3,184,944 | <p>How are you developing the application using Django and google application engine? </p>
<p>If you are using Django, settings.py should already be there. </p>
<p>Tyr <a href="http://code.google.com/p/app-engine-patch/" rel="nofollow">App engine patch</a></p>
<p>it provides a good starting point to develop the applications using Google app and Django.</p>
| 0 | 2010-07-06T09:15:02Z | [
"python",
"django",
"google-app-engine"
] |
Could not import Django settings into Google App Engine | 1,233,326 | <p>Hello all you Google App Engine experts, </p>
<p>I have used Django a little before but am new to Google App Engine and
am trying to use it's development web server with Django for the first time. </p>
<p>I don't know if this is relevent but I previously had Django 1.1 and
Python 2.6 on my Windows XP and even though I have uninstalled Python
2.6 there is still a folder and entries in the registry.</p>
<p>I have followed the instructions from Google but when I browse to the GAE developemnt web server it cannot find my settings
(details below). </p>
<p>Any hints gratefully received.</p>
<p>Regards</p>
<p>Geoff </p>
<pre><code>C:\Documents and Settings\GeoffK\My Documents\ing\ingsite>echo %PATH%
C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS
\system32\WindowsPowerShell\v1.0;;C:\Python25;C:\Python25\Lib\site-
packages\django\bin;C:\Documents and Settings\GeoffK\My Documents\ing
\ingsite;C:\Program Files\Google\google_appengine\
C:\Documents and Settings\GeoffK\My Documents\ing\ingsite>echo
%PYTHONPATH%
C:\Documents and Settings\GeoffK\My Documents\ing\ingsite
C:\Documents and Settings\GeoffK\My Documents\ing\ingsite>C:\Documents
and Settings\GeoffK\My Documents\ing\ingsite>dev_appserver.py --
debug_imports ingiliz\
INFO 2009-08-04 07:29:45,328 appengine_rpc.py:157] Server:
appengine.google.
com
INFO 2009-08-04 07:29:45,358 appcfg.py:322] Checking for updates
to the SDK.
INFO 2009-08-04 07:29:45,578 appcfg.py:336] The SDK is up to date.
WARNING 2009-08-04 07:29:45,578 datastore_file_stub.py:404] Could not
read data
store data from c:\docume~1\geoffk\locals~1\temp
\dev_appserver.datastore
WARNING 2009-08-04 07:29:45,578 datastore_file_stub.py:404] Could not
read data
store data from c:\docume~1\geoffk\locals~1\temp
\dev_appserver.datastore.history
WARNING 2009-08-04 07:29:45,608 dev_appserver.py:3296] Could not
initialize ima
ges API; you are likely missing the Python "PIL" module. ImportError:
No module
named _imaging
INFO 2009-08-04 07:29:45,625 dev_appserver_main.py:465] Running
application
ingiliz on port 8080: http://localhost:8080
</code></pre>
<p>.....
Now attempting to browse
if need more detail here I can post
..... </p>
<pre><code> if not settings.DATABASE_ENGINE:
File "C:\Python25\lib\site-packages\django\conf\__init__.py", line
28, in __ge
tattr__
self._import_settings()
File "C:\Python25\lib\site-packages\django\conf\__init__.py", line
59, in _imp
ort_settings
self._target = Settings(settings_module)
File "C:\Python25\lib\site-packages\django\conf\__init__.py", line
94, in __in
it__
raise ImportError, "Could not import settings '%s' (Is it on
sys.path? Does
it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'settings' (Is it on sys.path?
Does it ha
ve syntax errors?): No module named settings
INFO 2009-08-04 07:31:02,187 dev_appserver.py:2982] "GET / HTTP/
1.1" 500 -
</code></pre>
| 0 | 2009-08-05T13:40:06Z | 4,800,327 | <p>I started getting these problems after adding appengine_config.py to my project. On the file I had incorrect path for settings (just settings, even though I should have had myproj.settings)</p>
<pre><code>os.environ['DJANGO_SETTINGS_MODULE'] = 'myproj.settings'
</code></pre>
<p>"Interesting" twist was that when everything went well, this did not cause any trouble. Only after hitting some errors I started getting complaints about not being able to import settings.</p>
| 0 | 2011-01-26T00:20:02Z | [
"python",
"django",
"google-app-engine"
] |
No Multiline Lambda in Python: Why not? | 1,233,448 | <p>I've heard it said that multiline lambdas can't be added in Python because they would clash syntactically with the other syntax constructs in Python. I was thinking about this on the bus today and realized I couldn't think of a single Python construct that multiline lambdas clash with. Given that I know the language pretty well, this surprised me.</p>
<p>Now, I'm sure Guido had a reason for not including multiline lambdas in the language, but out of curiosity: what's a situation where including a multiline lambda would be ambiguous? Is what I've heard true, or is there some other reason that Python doesn't allow multiline lambdas?</p>
| 129 | 2009-08-05T14:00:30Z | 1,233,509 | <p>Look at the following:</p>
<pre><code>map(multilambda x:
y=x+1
return y
, [1,2,3])
</code></pre>
<p>Is this a lambda returning <code>(y, [1,2,3])</code> (thus map only gets one parameter, resulting in an error)? Or does it return <code>y</code>? Or is it a syntax error, because the comma on the new line is misplaced? How would Python know what you want?</p>
<p>Within the parens, indentation doesn't matter to python, so you can't unambiguously work with multilines.</p>
<p>This is just a simple one, there's probably more examples.</p>
| 75 | 2009-08-05T14:10:30Z | [
"python",
"syntax",
"lambda"
] |
No Multiline Lambda in Python: Why not? | 1,233,448 | <p>I've heard it said that multiline lambdas can't be added in Python because they would clash syntactically with the other syntax constructs in Python. I was thinking about this on the bus today and realized I couldn't think of a single Python construct that multiline lambdas clash with. Given that I know the language pretty well, this surprised me.</p>
<p>Now, I'm sure Guido had a reason for not including multiline lambdas in the language, but out of curiosity: what's a situation where including a multiline lambda would be ambiguous? Is what I've heard true, or is there some other reason that Python doesn't allow multiline lambdas?</p>
| 129 | 2009-08-05T14:00:30Z | 1,233,520 | <p>Guido van Rossum (the inventor of Python) answers this exact question himself in <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=147358">an old blog post</a>.<br>
Basically, he admits that it's theoretically possible, but that any proposed solution would be un-Pythonic:</p>
<blockquote>
<p>"But the complexity of any proposed solution for this puzzle is immense, to me: it requires the parser (or more precisely, the lexer) to be able to switch back and forth between indent-sensitive and indent-insensitive modes, keeping a stack of previous modes and indentation level. Technically that can all be solved (there's already a stack of indentation levels that could be generalized). But none of that takes away my gut feeling that it is all an elaborate <a href="http://en.wikipedia.org/wiki/Rube_Goldberg_Machine">Rube Goldberg contraption</a>."</p>
</blockquote>
| 300 | 2009-08-05T14:12:30Z | [
"python",
"syntax",
"lambda"
] |
No Multiline Lambda in Python: Why not? | 1,233,448 | <p>I've heard it said that multiline lambdas can't be added in Python because they would clash syntactically with the other syntax constructs in Python. I was thinking about this on the bus today and realized I couldn't think of a single Python construct that multiline lambdas clash with. Given that I know the language pretty well, this surprised me.</p>
<p>Now, I'm sure Guido had a reason for not including multiline lambdas in the language, but out of curiosity: what's a situation where including a multiline lambda would be ambiguous? Is what I've heard true, or is there some other reason that Python doesn't allow multiline lambdas?</p>
| 129 | 2009-08-05T14:00:30Z | 1,233,611 | <p>A couple of relevant links:</p>
<p>For a while, I was following the development of Reia, which was initially going to have Python's indentation based syntax with Ruby blocks too, all on top of Erlang. But, the designer wound up giving up on indentation sensitivity, and this post he wrote about that decision includes a discussion about problems he ran into with indentation + multi-line blocks, and an increased appreciation he gained for Guido's design issues/decisions:</p>
<p><a href="http://www.unlimitednovelty.com/2009/03/indentation-sensitivity-post-mortem.html">http://www.unlimitednovelty.com/2009/03/indentation-sensitivity-post-mortem.html</a></p>
<p>Also, here's an interesting proposal for Ruby-style blocks in Python I ran across where Guido posts a response w/o actually shooting it down (not sure whether there has been any subsequent shoot down, though):</p>
<p><a href="http://tav.espians.com/ruby-style-blocks-in-python.html">http://tav.espians.com/ruby-style-blocks-in-python.html</a></p>
| 12 | 2009-08-05T14:27:04Z | [
"python",
"syntax",
"lambda"
] |
No Multiline Lambda in Python: Why not? | 1,233,448 | <p>I've heard it said that multiline lambdas can't be added in Python because they would clash syntactically with the other syntax constructs in Python. I was thinking about this on the bus today and realized I couldn't think of a single Python construct that multiline lambdas clash with. Given that I know the language pretty well, this surprised me.</p>
<p>Now, I'm sure Guido had a reason for not including multiline lambdas in the language, but out of curiosity: what's a situation where including a multiline lambda would be ambiguous? Is what I've heard true, or is there some other reason that Python doesn't allow multiline lambdas?</p>
| 129 | 2009-08-05T14:00:30Z | 13,672,943 | <p>This is generally very ugly (but sometimes the alternatives are even more ugly), so a workaround is to make a braces expression:</p>
<pre><code>lambda: (
doFoo('abc'),
doBar(123),
doBaz())
</code></pre>
<p>It won't accept any assignments though, so you'll have to prepare data beforehand.
The place I found this useful is the PySide wrapper, where you sometimes have short callbacks. Writing additional member functions would be even more ugly. Normally you won't need this.</p>
<p>Example:</p>
<pre><code>pushButtonShowDialog.clicked.connect(
lambda: (
field1.clear(),
spinBox1.setValue(0),
diag.show())
</code></pre>
| 14 | 2012-12-02T19:32:22Z | [
"python",
"syntax",
"lambda"
] |
No Multiline Lambda in Python: Why not? | 1,233,448 | <p>I've heard it said that multiline lambdas can't be added in Python because they would clash syntactically with the other syntax constructs in Python. I was thinking about this on the bus today and realized I couldn't think of a single Python construct that multiline lambdas clash with. Given that I know the language pretty well, this surprised me.</p>
<p>Now, I'm sure Guido had a reason for not including multiline lambdas in the language, but out of curiosity: what's a situation where including a multiline lambda would be ambiguous? Is what I've heard true, or is there some other reason that Python doesn't allow multiline lambdas?</p>
| 129 | 2009-08-05T14:00:30Z | 18,996,338 | <p>Let me try to tackle @balpha parsing problem. I would use parentheses around the multiline lamda. If there is no parentheses, the lambda definition is greedy. So the lambda in </p>
<pre><code>map(lambda x:
y = x+1
z = x-1
y*z,
[1,2,3]))
</code></pre>
<p>returns a function that returns <code>(y*z, [1,2,3])</code></p>
<p>But</p>
<pre><code>map((lambda x:
y = x+1
z = x-1
y*z)
,[1,2,3]))
</code></pre>
<p>means</p>
<pre><code>map(func, [1,2,3])
</code></pre>
<p>where func is the multiline lambda that return y*z. Does that work?</p>
| 5 | 2013-09-25T04:39:24Z | [
"python",
"syntax",
"lambda"
] |
No Multiline Lambda in Python: Why not? | 1,233,448 | <p>I've heard it said that multiline lambdas can't be added in Python because they would clash syntactically with the other syntax constructs in Python. I was thinking about this on the bus today and realized I couldn't think of a single Python construct that multiline lambdas clash with. Given that I know the language pretty well, this surprised me.</p>
<p>Now, I'm sure Guido had a reason for not including multiline lambdas in the language, but out of curiosity: what's a situation where including a multiline lambda would be ambiguous? Is what I've heard true, or is there some other reason that Python doesn't allow multiline lambdas?</p>
| 129 | 2009-08-05T14:00:30Z | 26,210,269 | <p>A workaround to get multiline lambda functions (an extension to skriticos's answer):</p>
<pre><code>(lambda n: (exec('global x; x=4; x=x+n'), x-2)[-1])(0)
</code></pre>
<p><strong>What it does:</strong></p>
<ul>
<li><p>Python simplifies (executes) every component of a tuple before
reading the delimiters.</p></li>
<li><p>e.g., <code>lambda x: (functionA(), functionB(), functionC(), 0)[-1]</code>
would execute all three functions even though the only information
that's used is the last item in the list (0).</p></li>
<li><p>Normally you can't assign to or declare variables within lists or tuples in python, however using the <code>exec</code> function you can (note that it always returns: <code>None</code>).</p></li>
<li><p>Note that unless you declare a variable as <code>global</code> it won't exist outside of that <code>exec</code> function call (this is only true for <code>exec</code> functions within <code>lambda</code> statements).</p></li>
<li><p>e.g., <code>(lambda: exec('x=5;print(x)'))()</code> works fine without <code>global</code> declaration. However, <code>(lambda: (exec('x=5'), exec('print(x)')))()</code> or <code>(lambda: (exec('x=5'), x)()</code> do not.</p></li>
<li><p><strike>Note that all <code>global</code> variables are stored in the global namespace and will continue to exist after the function call is complete. For this reason, this is not a good solution and should be avoided if at all possible.</strike> <code>global</code> variables declared from the <code>exec</code> function inside a lambda function are kept separate from the <code>global</code> namespace. (tested in Python 3.3.3)</p></li>
<li><p>The <code>[-1]</code> at the end of the tuple gets the last index. For example <code>[1,2,3,4][-1]</code> is <code>4</code>. This is done so only the desired output value(s) is returned rather than an entire tuple containing <code>None</code> from <code>exec</code> functions and other extraneous values.</p></li>
</ul>
<p>Equivalent multi-line function:</p>
<pre><code>def function(n):
x = 4
x = x+n
return x-2
function(0)
</code></pre>
<p><strong>Ways to avoid needing a multi-line lambda:</strong></p>
<p>Recursion:</p>
<pre><code>f = lambda i: 1 if i==0 or i==1 else f(i-1)+f(i-2)
</code></pre>
<p>Booleans are Integers:</p>
<pre><code>lambda a, b: [(0, 9), (2, 3)][a<4][b>3]
</code></pre>
<p>Iterators:</p>
<pre><code>lambda x: [n**2 for n in x] #Assuming x is a list or tuple in this case
</code></pre>
| 2 | 2014-10-06T05:03:37Z | [
"python",
"syntax",
"lambda"
] |
No Multiline Lambda in Python: Why not? | 1,233,448 | <p>I've heard it said that multiline lambdas can't be added in Python because they would clash syntactically with the other syntax constructs in Python. I was thinking about this on the bus today and realized I couldn't think of a single Python construct that multiline lambdas clash with. Given that I know the language pretty well, this surprised me.</p>
<p>Now, I'm sure Guido had a reason for not including multiline lambdas in the language, but out of curiosity: what's a situation where including a multiline lambda would be ambiguous? Is what I've heard true, or is there some other reason that Python doesn't allow multiline lambdas?</p>
| 129 | 2009-08-05T14:00:30Z | 34,741,858 | <p>(For anyone still interested in the topic.)</p>
<p>Consider this (includes even usage of statements' return values in further statements within the "multiline" lambda, although it's ugly to the point of vomiting ;-)</p>
<pre><code>>>> def foo(arg):
... result = arg * 2;
... print "foo(" + str(arg) + ") called: " + str(result);
... return result;
...
>>> f = lambda a, b, state=[]: [
... state.append(foo(a)),
... state.append(foo(b)),
... state.append(foo(state[0] + state[1])),
... state[-1]
... ][-1];
>>> f(1, 2);
foo(1) called: 2
foo(2) called: 4
foo(6) called: 12
12
</code></pre>
| 2 | 2016-01-12T10:59:50Z | [
"python",
"syntax",
"lambda"
] |
Python Dictionary to URL Parameters | 1,233,539 | <p>I am trying to convert a Python dictionary to a string for use as URL parameters. I am sure that there is a better, more <a href="http://en.wikipedia.org/wiki/Pythonic">Pythonic</a> way of doing this. What is it?</p>
<pre><code>x = ""
for key, val in {'a':'A', 'b':'B'}.items():
x += "%s=%s&" %(key,val)
x = x[:-1]
</code></pre>
| 64 | 2009-08-05T14:14:06Z | 1,233,551 | <p>Use <a href="http://docs.python.org/library/urllib.html#urllib.urlencode"><code>urllib.urlencode()</code></a>. It takes a dictionary of key-value pairs, and converts it into a form suitable for a URL (e.g., <code>key1=val1&key2=val2</code>).</p>
<p>If you are using Python3, use <a href="https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlencode"><code>urllib.parse.urlencode()</code></a></p>
<p>If you want to make a URL with repetitive params such as: <code>p=1&p=2&p=3</code> you have two options:</p>
<pre><code>>>> import urllib
>>> a = (('p',1),('p',2), ('p', 3))
>>> urllib.urlencode(a)
'p=1&p=2&p=3'
</code></pre>
<p>or if you want to make a url with repetitive params:</p>
<pre><code>>>> urllib.urlencode({'p': [1, 2, 3]}, doseq=True)
'p=1&p=2&p=3'
</code></pre>
| 128 | 2009-08-05T14:16:28Z | [
"python",
"dictionary",
"url-parameters"
] |
PYTHON: Converting list of tuples into a dictionary | 1,233,546 | <p>I'm looking for a way to convert <strong>list of tuples</strong> which looks like this:</p>
<pre><code>[(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)]
</code></pre>
<p>into <strong>a dictionary</strong>, where key:value pair looks like this:</p>
<pre><code>{4:[1,2,3] ,15:[4,5,9,11,12], 23:[6,7,8,10]}
</code></pre>
<p>Second element from a tuple becomes a dictionary key.
First tuple element is assigned to that key.</p>
<p>Can you show me how that can be done?</p>
| 30 | 2009-08-05T14:15:49Z | 1,233,573 | <pre><code>l = [(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)]
d = {}
for v, k in l:
d.setdefault(k, []).append(v)
</code></pre>
| 2 | 2009-08-05T14:19:43Z | [
"python",
"list",
"dictionary"
] |
PYTHON: Converting list of tuples into a dictionary | 1,233,546 | <p>I'm looking for a way to convert <strong>list of tuples</strong> which looks like this:</p>
<pre><code>[(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)]
</code></pre>
<p>into <strong>a dictionary</strong>, where key:value pair looks like this:</p>
<pre><code>{4:[1,2,3] ,15:[4,5,9,11,12], 23:[6,7,8,10]}
</code></pre>
<p>Second element from a tuple becomes a dictionary key.
First tuple element is assigned to that key.</p>
<p>Can you show me how that can be done?</p>
| 30 | 2009-08-05T14:15:49Z | 1,233,587 | <pre><code>tuples = [(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)]
dicts = {}
for elem in tuples:
try:
dicts[elem[1]].append(elem[0])
except KeyError:
dicts[elem[1]] = [elem[0],]
</code></pre>
| 2 | 2009-08-05T14:22:25Z | [
"python",
"list",
"dictionary"
] |
PYTHON: Converting list of tuples into a dictionary | 1,233,546 | <p>I'm looking for a way to convert <strong>list of tuples</strong> which looks like this:</p>
<pre><code>[(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)]
</code></pre>
<p>into <strong>a dictionary</strong>, where key:value pair looks like this:</p>
<pre><code>{4:[1,2,3] ,15:[4,5,9,11,12], 23:[6,7,8,10]}
</code></pre>
<p>Second element from a tuple becomes a dictionary key.
First tuple element is assigned to that key.</p>
<p>Can you show me how that can be done?</p>
| 30 | 2009-08-05T14:15:49Z | 1,233,588 | <pre><code>>>> a = [(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)]
>>> b = {}
>>> for i, j in a:
... b.setdefault(j, []).append(i)
...
>>> b
{23: [6, 7, 8, 10], 4: [1, 2, 3], 15: [4, 5, 9, 11, 12]}
>>>
</code></pre>
| 12 | 2009-08-05T14:22:30Z | [
"python",
"list",
"dictionary"
] |
PYTHON: Converting list of tuples into a dictionary | 1,233,546 | <p>I'm looking for a way to convert <strong>list of tuples</strong> which looks like this:</p>
<pre><code>[(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)]
</code></pre>
<p>into <strong>a dictionary</strong>, where key:value pair looks like this:</p>
<pre><code>{4:[1,2,3] ,15:[4,5,9,11,12], 23:[6,7,8,10]}
</code></pre>
<p>Second element from a tuple becomes a dictionary key.
First tuple element is assigned to that key.</p>
<p>Can you show me how that can be done?</p>
| 30 | 2009-08-05T14:15:49Z | 1,233,617 | <p>This will do:</p>
<pre><code>from collections import defaultdict
def to_list_of_dicts(list_of_tuples):
d = defaultdict(list)
for x, y in list_of_tuples:
d[y].append(x)
return sorted([{x: y} for (x, y) in d.items()])
</code></pre>
| 2 | 2009-08-05T14:27:40Z | [
"python",
"list",
"dictionary"
] |
PYTHON: Converting list of tuples into a dictionary | 1,233,546 | <p>I'm looking for a way to convert <strong>list of tuples</strong> which looks like this:</p>
<pre><code>[(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)]
</code></pre>
<p>into <strong>a dictionary</strong>, where key:value pair looks like this:</p>
<pre><code>{4:[1,2,3] ,15:[4,5,9,11,12], 23:[6,7,8,10]}
</code></pre>
<p>Second element from a tuple becomes a dictionary key.
First tuple element is assigned to that key.</p>
<p>Can you show me how that can be done?</p>
| 30 | 2009-08-05T14:15:49Z | 1,233,628 | <pre><code>>>> from collections import defaultdict
>>> l= [(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)]
>>> d= defaultdict( list )
>>> for v, k in l:
... d[k].append(v)
...
>>> d
defaultdict(<type 'list'>, {23: [6, 7, 8, 10], 4: [1, 2, 3], 15: [4, 5, 9, 11, 12]})
>>> [ {k:d[k]} for k in sorted(d) ]
[{4: [1, 2, 3]}, {15: [4, 5, 9, 11, 12]}, {23: [6, 7, 8, 10]}]
</code></pre>
| 41 | 2009-08-05T14:29:46Z | [
"python",
"list",
"dictionary"
] |
PYTHON: Converting list of tuples into a dictionary | 1,233,546 | <p>I'm looking for a way to convert <strong>list of tuples</strong> which looks like this:</p>
<pre><code>[(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)]
</code></pre>
<p>into <strong>a dictionary</strong>, where key:value pair looks like this:</p>
<pre><code>{4:[1,2,3] ,15:[4,5,9,11,12], 23:[6,7,8,10]}
</code></pre>
<p>Second element from a tuple becomes a dictionary key.
First tuple element is assigned to that key.</p>
<p>Can you show me how that can be done?</p>
| 30 | 2009-08-05T14:15:49Z | 3,632,691 | <p>It's not fancy but it is simple</p>
<pre><code>l = [(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)]
d = dict((k, [i[0] for i in l if i[1] == k]) for k in frozenset(j[1] for j in l))
</code></pre>
<p>Huzzah!</p>
| 2 | 2010-09-03T02:24:46Z | [
"python",
"list",
"dictionary"
] |
k-means clustering implementation in python, running out of memory | 1,233,593 | <h3>Â Note: updates/solutions at the bottom of this question</h3>
<p>As part of a product recommendation engine, I'm trying to segment my users based on their product preferences starting with using the k-means clustering algorithm.</p>
<p>My data is a dictionary of the form:</p>
<pre><code>prefs = {
'user_id_1': { 1L: 3.0f, 2L: 1.0f, },
'user_id_2': { 4L: 1.0f, 8L: 1.5f, },
}
</code></pre>
<p>where the product ids are the longs, and ratings are floats. the data is sparse. I currently have about 60,000 users, most of whom have only rated a handful of products. The dictionary of values for each user is implemented using a defaultdict(float) to simplify the code.</p>
<p>My implementation of k-means clustering is as follows:</p>
<pre><code>def kcluster(prefs,sim_func=pearson,k=100,max_iterations=100):
from collections import defaultdict
users = prefs.keys()
centroids = [prefs[random.choice(users)] for i in range(k)]
lastmatches = None
for t in range(max_iterations):
print 'Iteration %d' % t
bestmatches = [[] for i in range(k)]
# Find which centroid is closest for each row
for j in users:
row = prefs[j]
bestmatch=(0,0)
for i in range(k):
d = simple_pearson(row,centroids[i])
if d < bestmatch[1]: bestmatch = (i,d)
bestmatches[bestmatch[0]].append(j)
# If the results are the same as last time, this is complete
if bestmatches == lastmatches: break
lastmatches=bestmatches
centroids = [defaultdict(float) for i in range(k)]
# Move the centroids to the average of their members
for i in range(k):
len_best = len(bestmatches[i])
if len_best > 0:
items = set.union(*[set(prefs[u].keys()) for u in bestmatches[i]])
for user_id in bestmatches[i]:
row = prefs[user_id]
for m in items:
if row[m] > 0.0: centroids[i][m]+=(row[m]/len_best)
return bestmatches
</code></pre>
<p>As far as I can tell, the algorithm is handling the first part (assigning each user to its nearest centroid) fine.</p>
<p>The problem is when doing the next part, taking the average rating for each product in each cluster and using these average ratings as the centroids for the next pass.</p>
<p>Basically, before it's even managed to do the calculations for the first cluster (i=0), the algorithm bombs out with a MemoryError at this line:</p>
<pre><code>if row[m] > 0.0: centroids[i][m]+=(row[m]/len_best)
</code></pre>
<p>Originally the division step was in a seperate loop, but fared no better.</p>
<p>This is the exception I get:</p>
<pre><code>malloc: *** mmap(size=16777216) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
</code></pre>
<p>Any help would be greatly appreciated.</p>
<p><hr /></p>
<h3>Update: Final algorithms</h3>
<p>Thanks to the help recieved here, this is my fixed algorithm. If you spot anything blatantly wrong please add a comment.</p>
<p>First, the simple_pearson implementation</p>
<pre><code>def simple_pearson(v1,v2):
si = [val for val in v1 if val in v2]
n = len(si)
if n==0: return 0.0
sum1 = 0.0
sum2 = 0.0
sum1_sq = 0.0
sum2_sq = 0.0
p_sum = 0.0
for v in si:
sum1+=v1[v]
sum2+=v2[v]
sum1_sq+=pow(v1[v],2)
sum2_sq+=pow(v2[v],2)
p_sum+=(v1[v]*v2[v])
# Calculate Pearson score
num = p_sum-(sum1*sum2/n)
temp = (sum1_sq-pow(sum1,2)/n) * (sum2_sq-pow(sum2,2)/n)
if temp < 0.0:
temp = -temp
den = sqrt(temp)
if den==0: return 1.0
r = num/den
return r
</code></pre>
<p>A simple method to turn simple_pearson into a distance value:</p>
<pre><code>def distance(v1,v2):
return 1.0-simple_pearson(v1,v2)
</code></pre>
<p>And finally, the k-means clustering implementation:</p>
<pre><code>def kcluster(prefs,k=21,max_iterations=50):
from collections import defaultdict
users = prefs.keys()
centroids = [prefs[u] for u in random.sample(users, k)]
lastmatches = None
for t in range(max_iterations):
print 'Iteration %d' % t
bestmatches = [[] for i in range(k)]
# Find which centroid is closest for each row
for j in users:
row = prefs[j]
bestmatch=(0,2.0)
for i in range(k):
d = distance(row,centroids[i])
if d <= bestmatch[1]: bestmatch = (i,d)
bestmatches[bestmatch[0]].append(j)
# If the results are the same as last time, this is complete
if bestmatches == lastmatches: break
lastmatches=bestmatches
centroids = [defaultdict(float) for i in range(k)]
# Move the centroids to the average of their members
for i in range(k):
len_best = len(bestmatches[i])
if len_best > 0:
for user_id in bestmatches[i]:
row = prefs[user_id]
for m in row:
centroids[i][m]+=row[m]
for key in centroids[i].keys():
centroids[i][key]/=len_best
# We may have made the centroids quite dense which significantly
# slows down subsequent iterations, so we delete values below a
# threshold to speed things up
if centroids[i][key] < 0.001:
del centroids[i][key]
return centroids, bestmatches
</code></pre>
| 6 | 2009-08-05T14:24:04Z | 1,234,525 | <p>Your <code>centroids</code> does not need to be an actual list.</p>
<p>You never appear to reference anything other than <code>centroids[i][m]</code>. If you only want <code>centroids[i]</code>, then perhaps it doesn't need to be a list; a simple dictionary would probably do.</p>
<pre><code> centroids = defaultdict(float)
# Move the centroids to the average of their members
for i in range(k):
len_best = len(bestmatches[i])
if len_best > 0:
items = set.union(*[set(prefs[u].keys()) for u in bestmatches[i]])
for user_id in bestmatches[i]:
row = prefs[user_id]
for m in items:
if row[m] > 0.0: centroids[m]+=(row[m]/len_best)
</code></pre>
<p>May work better.</p>
| 0 | 2009-08-05T17:05:27Z | [
"python"
] |
k-means clustering implementation in python, running out of memory | 1,233,593 | <h3>Â Note: updates/solutions at the bottom of this question</h3>
<p>As part of a product recommendation engine, I'm trying to segment my users based on their product preferences starting with using the k-means clustering algorithm.</p>
<p>My data is a dictionary of the form:</p>
<pre><code>prefs = {
'user_id_1': { 1L: 3.0f, 2L: 1.0f, },
'user_id_2': { 4L: 1.0f, 8L: 1.5f, },
}
</code></pre>
<p>where the product ids are the longs, and ratings are floats. the data is sparse. I currently have about 60,000 users, most of whom have only rated a handful of products. The dictionary of values for each user is implemented using a defaultdict(float) to simplify the code.</p>
<p>My implementation of k-means clustering is as follows:</p>
<pre><code>def kcluster(prefs,sim_func=pearson,k=100,max_iterations=100):
from collections import defaultdict
users = prefs.keys()
centroids = [prefs[random.choice(users)] for i in range(k)]
lastmatches = None
for t in range(max_iterations):
print 'Iteration %d' % t
bestmatches = [[] for i in range(k)]
# Find which centroid is closest for each row
for j in users:
row = prefs[j]
bestmatch=(0,0)
for i in range(k):
d = simple_pearson(row,centroids[i])
if d < bestmatch[1]: bestmatch = (i,d)
bestmatches[bestmatch[0]].append(j)
# If the results are the same as last time, this is complete
if bestmatches == lastmatches: break
lastmatches=bestmatches
centroids = [defaultdict(float) for i in range(k)]
# Move the centroids to the average of their members
for i in range(k):
len_best = len(bestmatches[i])
if len_best > 0:
items = set.union(*[set(prefs[u].keys()) for u in bestmatches[i]])
for user_id in bestmatches[i]:
row = prefs[user_id]
for m in items:
if row[m] > 0.0: centroids[i][m]+=(row[m]/len_best)
return bestmatches
</code></pre>
<p>As far as I can tell, the algorithm is handling the first part (assigning each user to its nearest centroid) fine.</p>
<p>The problem is when doing the next part, taking the average rating for each product in each cluster and using these average ratings as the centroids for the next pass.</p>
<p>Basically, before it's even managed to do the calculations for the first cluster (i=0), the algorithm bombs out with a MemoryError at this line:</p>
<pre><code>if row[m] > 0.0: centroids[i][m]+=(row[m]/len_best)
</code></pre>
<p>Originally the division step was in a seperate loop, but fared no better.</p>
<p>This is the exception I get:</p>
<pre><code>malloc: *** mmap(size=16777216) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
</code></pre>
<p>Any help would be greatly appreciated.</p>
<p><hr /></p>
<h3>Update: Final algorithms</h3>
<p>Thanks to the help recieved here, this is my fixed algorithm. If you spot anything blatantly wrong please add a comment.</p>
<p>First, the simple_pearson implementation</p>
<pre><code>def simple_pearson(v1,v2):
si = [val for val in v1 if val in v2]
n = len(si)
if n==0: return 0.0
sum1 = 0.0
sum2 = 0.0
sum1_sq = 0.0
sum2_sq = 0.0
p_sum = 0.0
for v in si:
sum1+=v1[v]
sum2+=v2[v]
sum1_sq+=pow(v1[v],2)
sum2_sq+=pow(v2[v],2)
p_sum+=(v1[v]*v2[v])
# Calculate Pearson score
num = p_sum-(sum1*sum2/n)
temp = (sum1_sq-pow(sum1,2)/n) * (sum2_sq-pow(sum2,2)/n)
if temp < 0.0:
temp = -temp
den = sqrt(temp)
if den==0: return 1.0
r = num/den
return r
</code></pre>
<p>A simple method to turn simple_pearson into a distance value:</p>
<pre><code>def distance(v1,v2):
return 1.0-simple_pearson(v1,v2)
</code></pre>
<p>And finally, the k-means clustering implementation:</p>
<pre><code>def kcluster(prefs,k=21,max_iterations=50):
from collections import defaultdict
users = prefs.keys()
centroids = [prefs[u] for u in random.sample(users, k)]
lastmatches = None
for t in range(max_iterations):
print 'Iteration %d' % t
bestmatches = [[] for i in range(k)]
# Find which centroid is closest for each row
for j in users:
row = prefs[j]
bestmatch=(0,2.0)
for i in range(k):
d = distance(row,centroids[i])
if d <= bestmatch[1]: bestmatch = (i,d)
bestmatches[bestmatch[0]].append(j)
# If the results are the same as last time, this is complete
if bestmatches == lastmatches: break
lastmatches=bestmatches
centroids = [defaultdict(float) for i in range(k)]
# Move the centroids to the average of their members
for i in range(k):
len_best = len(bestmatches[i])
if len_best > 0:
for user_id in bestmatches[i]:
row = prefs[user_id]
for m in row:
centroids[i][m]+=row[m]
for key in centroids[i].keys():
centroids[i][key]/=len_best
# We may have made the centroids quite dense which significantly
# slows down subsequent iterations, so we delete values below a
# threshold to speed things up
if centroids[i][key] < 0.001:
del centroids[i][key]
return centroids, bestmatches
</code></pre>
| 6 | 2009-08-05T14:24:04Z | 1,234,620 | <p>Not all these observations are directly relevant to your issues as expressed, but..:</p>
<p>a. why are the key in prefs, as shown, longs? unless you have billions of users, simple ints will be fine and save you a little memory.</p>
<p>b. your code:</p>
<pre><code>centroids = [prefs[random.choice(users)] for i in range(k)]
</code></pre>
<p>can give you repeats (two identical centroids), which in turn would not make the K-means algorithm happy. Just use the faster and more solid</p>
<pre><code>centroids = [prefs[u] for random.sample(users, k)]
</code></pre>
<p>c. in your code as posted you're calling a function <code>simple_pearson</code> which you never define anywhere; I assume you mean to call <code>sim_func</code>, but it's really hard to help on different issues while at the same time having to guess how the code you posted differs from any code that might actually be working</p>
<p>d. one more indication that this posted code may be different from anything that might actually work: you set <code>bestmatch=(0,0)</code> but then test with <code>if d < bestmatch[1]:</code> -- how is the test ever going to succeed? is the distance function returning negative values?</p>
<p>e. the point of a defaultdict is that just accessing <code>row[m]</code> magically adds an item to <code>row</code> at index <code>m</code> (with the value obtained by calling the defaultdict's factory, here 0.0). That item will then take up memory forevermore. You absolutely DON'T need this behavior, and therefore your code:</p>
<pre><code> row = prefs[user_id]
for m in items:
if row[m] > 0.0: centroids[i][m]+=(row[m]/len_best)
</code></pre>
<p>is wasting huge amount of memory, making <code>prefs</code> into a dense matrix (mostly full of 0.0 values) from the sparse one it used to be. If you code instead</p>
<pre><code> row = prefs[user_id]
for m in row:
centroids[i][m]+=(row[m]/len_best)
</code></pre>
<p>there will be no growth in <code>row</code> and therefore in <code>prefs</code> because you're looping over the keys that <code>row</code> already has.</p>
<p>There may be many other such issues, major like the last one or minor ones -- as an example of the latter, </p>
<p>f. don't divide a bazillion times by <code>len_best</code>: compute its inverse one outside the loop and multiply by that inverse -- also you don't need to do that multiplication inside the loop, you can do it at the end in a separate since it's the same value that's multiplying every item -- this saves no memory but avoids wantonly wasting CPU time;-). OK, these are <em>two</em> minor issues, I guess, not just one;-).</p>
<p>As I mentioned there may be many others, but with the density of issues already shown by these six (or seven), plus the separate suggestion already advanced by S.Lott (which I think would not fix your main out-of-memory problem, since his code still addressing the <code>row</code> defaultdict by too many keys it doesn't contain), I think it wouldn't be very productive to keep looking for even more -- maybe start by fixing these ones and if problems persist post a separate question about those...?</p>
| 6 | 2009-08-05T17:23:39Z | [
"python"
] |
What is the simplest way to SSH using Python? | 1,233,655 | <p>How can I simply SSH to a remote server from a local Python (3.0) script, supply a login/password, execute a command and print the output to the Python console?</p>
<p>I would rather not use any large external library or install anything on the remote server.</p>
| 73 | 2009-08-05T14:34:25Z | 1,233,729 | <p>Your definition of "simplest" is important here - simple code means using a module (though "large external library" is an exaggeration).</p>
<p>I believe the most up-to-date (actively developed) module is <a href="http://www.lag.net/paramiko/">paramiko</a>. It comes with demo scripts in the download, and has detailed online API documentation. You could also try <a href="http://pexpect.sourceforge.net/pxssh.html">PxSSH</a>, which is contained in <a href="http://sourceforge.net/projects/pexpect/">pexpect</a>. There's a short sample along with the documentation at the first link. </p>
<p>Again with respect to simplicity, note that good error-detection is always going to make your code look more complex, but you should be able to reuse a lot of code from the sample scripts then forget about it.</p>
| 8 | 2009-08-05T14:44:49Z | [
"python",
"linux",
"unix",
"ssh"
] |
What is the simplest way to SSH using Python? | 1,233,655 | <p>How can I simply SSH to a remote server from a local Python (3.0) script, supply a login/password, execute a command and print the output to the Python console?</p>
<p>I would rather not use any large external library or install anything on the remote server.</p>
| 73 | 2009-08-05T14:34:25Z | 1,233,763 | <p>I haven't tried it, but this <a href="http://pypi.python.org/pypi/pysftp/" rel="nofollow">pysftp</a> module might help, which in turn uses paramiko. I believe everything is client-side.</p>
<p>The interesting command is probably <code>.execute()</code> which executes an arbitrary command on the remote machine. (The module also features <code>.get()</code> and <code>.put</code> methods which allude more to its FTP character).</p>
<p>UPDATE:</p>
<p>I've re-written the answer after the blog post I originally linked to is not available anymore. Some of the comments that refer to the old version of this answer will now look weird.</p>
| 37 | 2009-08-05T14:49:05Z | [
"python",
"linux",
"unix",
"ssh"
] |
What is the simplest way to SSH using Python? | 1,233,655 | <p>How can I simply SSH to a remote server from a local Python (3.0) script, supply a login/password, execute a command and print the output to the Python console?</p>
<p>I would rather not use any large external library or install anything on the remote server.</p>
| 73 | 2009-08-05T14:34:25Z | 1,233,845 | <p>You can code it yourself using Paramiko, as suggested above. Alternatively, you can look into Fabric, a python application for doing all the things you asked about:</p>
<blockquote>
<p>Fabric is a Python library and
command-line tool designed to
streamline deploying applications or
performing system administration tasks
via the SSH protocol. It provides
tools for running arbitrary shell
commands (either as a normal login
user, or via sudo), uploading and
downloading files, and so forth.</p>
</blockquote>
<p>I think this fits your needs. It is also not a large library and requires no server installation, although it does have dependencies on paramiko and pycrypt that require installation on the client.</p>
<p>The app used to be <a href="http://www.nongnu.org/fab/">here</a>. It can now be found <a href="http://docs.fabfile.org/0.9/">here</a>.</p>
<pre><code>* The official, canonical repository is git.fabfile.org
* The official Github mirror is GitHub/bitprophet/fabric
</code></pre>
<p>There are several good articles on it, though you should be careful because it has changed in the last six months:</p>
<p><a href="http://lethain.com/entry/2008/nov/04/deploying-django-with-fabric/">Deploying Django with Fabric</a></p>
<p><a href="http://www.clemesha.org/blog/modern-python-hacker-tools-virtualenv-fabric-pip/">Tools of the Modern Python Hacker: Virtualenv, Fabric and Pip</a></p>
<p><a href="http://lincolnloop.com/blog/2008/dec/07/simple-easy-deployment-fabric-and-virtualenv/">Simple & Easy Deployment with Fabric and Virtualenv</a></p>
<hr>
<p>Later: Fabric no longer requires paramiko to install:</p>
<pre><code>$ pip install fabric
Downloading/unpacking fabric
Downloading Fabric-1.4.2.tar.gz (182Kb): 182Kb downloaded
Running setup.py egg_info for package fabric
warning: no previously-included files matching '*' found under directory 'docs/_build'
warning: no files found matching 'fabfile.py'
Downloading/unpacking ssh>=1.7.14 (from fabric)
Downloading ssh-1.7.14.tar.gz (794Kb): 794Kb downloaded
Running setup.py egg_info for package ssh
Downloading/unpacking pycrypto>=2.1,!=2.4 (from ssh>=1.7.14->fabric)
Downloading pycrypto-2.6.tar.gz (443Kb): 443Kb downloaded
Running setup.py egg_info for package pycrypto
Installing collected packages: fabric, ssh, pycrypto
Running setup.py install for fabric
warning: no previously-included files matching '*' found under directory 'docs/_build'
warning: no files found matching 'fabfile.py'
Installing fab script to /home/hbrown/.virtualenvs/fabric-test/bin
Running setup.py install for ssh
Running setup.py install for pycrypto
...
Successfully installed fabric ssh pycrypto
Cleaning up...
</code></pre>
<p>This is mostly cosmetic, however: ssh is a fork of paramiko, the maintainer for both libraries is the same (Jeff Forcier, also the author of Fabric), and <a href="http://bitprophet.org/blog/2012/09/29/paramiko-and-ssh/">the maintainer has plans to reunite paramiko and ssh under the name paramiko</a>. (This correction via <a href="http://stackoverflow.com/users/687980/pbanka">pbanka</a>.)</p>
| 59 | 2009-08-05T15:00:29Z | [
"python",
"linux",
"unix",
"ssh"
] |
What is the simplest way to SSH using Python? | 1,233,655 | <p>How can I simply SSH to a remote server from a local Python (3.0) script, supply a login/password, execute a command and print the output to the Python console?</p>
<p>I would rather not use any large external library or install anything on the remote server.</p>
| 73 | 2009-08-05T14:34:25Z | 1,233,872 | <p>If you want to avoid any extra modules, you can use the subprocess module to run</p>
<pre><code>ssh [host] [command]
</code></pre>
<p>and capture the output. </p>
<p>Try something like:</p>
<pre><code>process = subprocess.Popen("ssh example.com ls", shell=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output,stderr = process.communicate()
status = process.poll()
print output
</code></pre>
<p>To deal with usernames and passwords, you can use subprocess to interact with the ssh process, or you could install a public key on the server to avoid the password prompt.</p>
| 21 | 2009-08-05T15:05:39Z | [
"python",
"linux",
"unix",
"ssh"
] |
What is the simplest way to SSH using Python? | 1,233,655 | <p>How can I simply SSH to a remote server from a local Python (3.0) script, supply a login/password, execute a command and print the output to the Python console?</p>
<p>I would rather not use any large external library or install anything on the remote server.</p>
| 73 | 2009-08-05T14:34:25Z | 1,238,024 | <p>Like hughdbrown, I like Fabric. Please notice that while it implement its own declarative scripting (for making deploys and the such) it can also be imported as a Python module and used on your programs without having to write a Fabric script.</p>
<p>Fabric has a new maintainer and is in the process of being rewriten; that means that most tutorials you'll (currently) find on the web will not work with the current version. Also, Google still shows the old Fabric page as the first result. </p>
<p>For up to date documentation you can check: <a href="http://docs.fabfile.org">http://docs.fabfile.org</a></p>
| 6 | 2009-08-06T10:08:26Z | [
"python",
"linux",
"unix",
"ssh"
] |
What is the simplest way to SSH using Python? | 1,233,655 | <p>How can I simply SSH to a remote server from a local Python (3.0) script, supply a login/password, execute a command and print the output to the Python console?</p>
<p>I would rather not use any large external library or install anything on the remote server.</p>
| 73 | 2009-08-05T14:34:25Z | 5,142,224 | <p>I have written <a href="http://www.no-ack.org/2010/11/python-bindings-for-libssh2.html">Python bindings for libssh2</a>. Libssh2 is a client-side library implementing the SSH2 protocol.</p>
<pre><code>import socket
import libssh2
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('exmaple.com', 22))
session = libssh2.Session()
session.startup(sock)
session.userauth_password('john', '******')
channel = session.channel()
channel.execute('ls -l')
print channel.read(1024)
</code></pre>
| 15 | 2011-02-28T12:51:11Z | [
"python",
"linux",
"unix",
"ssh"
] |
What is the simplest way to SSH using Python? | 1,233,655 | <p>How can I simply SSH to a remote server from a local Python (3.0) script, supply a login/password, execute a command and print the output to the Python console?</p>
<p>I would rather not use any large external library or install anything on the remote server.</p>
| 73 | 2009-08-05T14:34:25Z | 14,267,862 | <p>I found paramiko to be a bit too low-level, and Fabric not especially well-suited to being used as a library, so I put together my own library called <a href="http://pypi.python.org/pypi/spur">spur</a> that uses paramiko to implement a slightly nicer interface:</p>
<pre><code>import spur
shell = spur.SshShell(hostname="localhost", username="bob", password="password1")
result = shell.run(["echo", "-n", "hello"])
print result.output # prints hello
</code></pre>
<p>You can also choose to print the output of the program as it's running, which is useful if you want to see the output of long-running commands before it exits:</p>
<pre><code>result = shell.run(["echo", "-n", "hello"], stdout=sys.stdout)
</code></pre>
| 6 | 2013-01-10T21:47:55Z | [
"python",
"linux",
"unix",
"ssh"
] |
What is the simplest way to SSH using Python? | 1,233,655 | <p>How can I simply SSH to a remote server from a local Python (3.0) script, supply a login/password, execute a command and print the output to the Python console?</p>
<p>I would rather not use any large external library or install anything on the remote server.</p>
| 73 | 2009-08-05T14:34:25Z | 34,411,796 | <p>This worked for me</p>
<pre><code>import subprocess
import sys
HOST="IP"
COMMAND="ifconfig"
def passwordless_ssh(HOST):
ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND],
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
result = ssh.stdout.readlines()
if result == []:
error = ssh.stderr.readlines()
print >>sys.stderr, "ERROR: %s" % error
return "error"
else:
return result
</code></pre>
| 1 | 2015-12-22T08:51:39Z | [
"python",
"linux",
"unix",
"ssh"
] |
Installing Pinax on Windows | 1,233,670 | <p>Can I install <a href="http://pinaxproject.com/" rel="nofollow">Pinax</a> on Windows Environment?
Is there a easy way?
Which environment do you recommend?</p>
| 4 | 2009-08-05T14:36:04Z | 1,233,982 | <p>Provided you have Python and Django installed, Pinax should install fine. According to the documentation there is one step that you have to do specifically on Windows however (Under the "Note To Windows Users" heading):</p>
<p><a href="http://pinaxproject.com/docs/0.5.1/install.html" rel="nofollow">http://pinaxproject.com/docs/0.5.1/install.html</a></p>
| 0 | 2009-08-05T15:24:48Z | [
"python",
"django",
"web-applications",
"pinax"
] |
Installing Pinax on Windows | 1,233,670 | <p>Can I install <a href="http://pinaxproject.com/" rel="nofollow">Pinax</a> on Windows Environment?
Is there a easy way?
Which environment do you recommend?</p>
| 4 | 2009-08-05T14:36:04Z | 1,234,266 | <p>I spent a while trying to get the .7 beta working in Windows and ran into a lot of trouble. However, it looks like the 3rd beta release of .7 (the latest beta release) focuses on Windows support. So try that, instead of the 'stable' version - it's close to being released as stable anyway, and is recommended now for use.</p>
<p>In the end though, I switched to Ubuntu and haven't been happier. Python development is much nicer in Linux. It's easier to install many Python packages, I run into fewer configuration issues, and there's better support and documentation available.</p>
| 0 | 2009-08-05T16:17:05Z | [
"python",
"django",
"web-applications",
"pinax"
] |
Installing Pinax on Windows | 1,233,670 | <p>Can I install <a href="http://pinaxproject.com/" rel="nofollow">Pinax</a> on Windows Environment?
Is there a easy way?
Which environment do you recommend?</p>
| 4 | 2009-08-05T14:36:04Z | 1,416,015 | <p>I have pinax 0.7rc1 installed and working on windows 7, with no problems.</p>
<p>Check out this video for a great example on how to do this. He uses pinax 0.7beta3 on windows XP.</p>
<p><a href="http://www.vimeo.com/6098872" rel="nofollow">http://www.vimeo.com/6098872</a></p>
<p>Here are the steps I followed.</p>
<ol>
<li>download and install python</li>
<li>download and install python image library</li>
<li>download pinax at <a href="http://pinaxproject.com" rel="nofollow">http://pinaxproject.com</a></li>
<li>extract the download to some working directory <code><pinax-directory></code> (maybe c:\pinax ?)</li>
<li>make sure you have python in your path (c:\pythonXX)</li>
<li>make sure you have the python scripts folder in your path (c:\pythonXX\scripts)</li>
<li>open a command prompt</li>
<li><code>cd</code> to <code><pinax-directory>\scripts</code> folder</li>
<li>run <code>python pinax-boot.py <pinax-env></code> (I used "../pinax-env")</li>
<li>wait for pinax-boot process to finish</li>
</ol>
<p>-- technically pinax is installed and ready to use, but the next steps will get you up and running with pinax social app (any other app will also work fine)</p>
<ol>
<li>cd to your <code><pinax-env>\scripts</code> directory</li>
<li>execute the <code>activate.bat</code> script</li>
<li>execute <code>python clone_project social <pinax-env>\social</code></li>
<li>cd to <code><pinax-env>\social</code></li>
<li>execute <code>python manage.py syncdb</code></li>
<li><p>execute <code>python manage.py runserver</code></p></li>
<li><p>open your browser to the server and you should see your new pinax site</p></li>
</ol>
<p>Voila!! Pinax on Windows.</p>
| 7 | 2009-09-12T20:13:08Z | [
"python",
"django",
"web-applications",
"pinax"
] |
Django ManyToMany Template Questions | 1,233,709 | <p>Good Morning All,</p>
<p>I've been a PHP programmer for quite some time, but I've felt the need to move more towards the Python direction and what's better than playing around with Django.</p>
<p>While in the process, I'm come to a stopping point where I know there is an easy solution, but I'm just missing it - How do I display manytomany relationships in a Django Template?</p>
<p>My Django Model: (most of the fields have been removed)</p>
<pre><code>class Category(models.Model):
name = models.CharField(max_length=125)
slug = models.SlugField()
categories = models.ManyToManyField(Category, blank=True, null=True)
class Recipe(models.Model):
title = models.CharField('Title', max_length=250)
slug = models.SlugField()
class Photo(models.Model):
recipe = models.ForeignKey(Recipe)
image = models.ImageField(upload_to="images/recipes", blank=True)
</code></pre>
<p>So, there is the basic models I'm using in my application called "recipes."<br />
With that said, there are two questions I'm looking for answers on:</p>
<ol>
<li>How would I go about displaying the categories for a recipe on it's details page?</li>
<li>How would I go about displaying the image for the recipe on it's details page?</li>
</ol>
<p>If I go into the Python shell, and input the following, I do get a result:</p>
<pre><code>>>> photos = Photo.objects.filter(recipe=1)
>>> photos
[<Photo: Awesome Pasta>]
>>> for photo in photos:
... print "Photo: %s" % photo.logo
...
Photo: images/recipes/2550298482_46729d51af__.jpg
</code></pre>
<p>But when I try something like the following in my template, I get an error saying "Invalid block tag: 'photo.image'."</p>
<pre><code>{% for photo in photos %}
{% photo.image %}
{% endfor %}
</code></pre>
<p>Although, even if that did work, the ID is still hard coded into the view, how would you go about having this dynamic for each recipe?</p>
<p>Details Page View.py snippet:</p>
<pre><code>def details(request, slug='0'):
p = get_object_or_404(Recipe, slug=slug)
photos = Photo.objects.filter(recipe=1)
return render_to_response('recipes/recipes_detail.html', {'p': p, 'photos': photos})
</code></pre>
<p>Thanks in advance for the help and understanding for what is probably a very simple question to all of you!</p>
<p><strong>UPDATE: When removing the additional fields in the models, I forgot the categories field for the Recipes model.</strong> </p>
| 3 | 2009-08-05T14:42:13Z | 1,233,737 | <p>From what I can see, I think you've got a small syntax error:</p>
<pre><code>{% photo.image %}
</code></pre>
<p>should instead be:</p>
<pre><code>{{ photo.image }}
</code></pre>
<p>The <code>{% %}</code> notation is used for django template tags. Variables, on the other hand, are expressed with the <code>{{ }}</code> notation.</p>
<p>To make it dynamic, you can take advantage of the fact that your <code>Photo</code> model has a foreign key to <code>Recipe</code>. This means that there will be a reverse relation from the <code>Recipe</code> instance you've loaded using the slug back to the set of photos:</p>
<pre><code>def details(request, slug='0'):
p = get_object_or_404(Recipe, slug=slug)
photos = p.photo_set.all()
</code></pre>
<p>Hopefully that will work for you. Glad to see you're enjoying working with Django!</p>
| 3 | 2009-08-05T14:45:43Z | [
"python",
"django",
"templates",
"django-templates",
"many-to-many"
] |
PyQt : why adding a dummy class definition in my file make the application crash? | 1,233,711 | <p>Consider the code below:</p>
<pre><code> #!/usr/bin/env python
from PyQt4 import QtCore, QtGui
import os,sys
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.listWidget = QtGui.QListWidget(None)
self.setCentralWidget(self.listWidget)
if __name__ == '__main__':
app = QtGui.QApplication (sys.argv)
mainWin = MainWindow ()
mainWin.show ()
sys.exit (app.exec_())
</code></pre>
<p>Works ok.
Now if I add a dummy class (that inherits from a QtGui module's class) in the global scope ...</p>
<pre><code>class MainWindow(QtGui.QMainWindow):
... # unchanged
class MyWidget(QtGui.QWidget):
def __init__(self):
super(MyWidget, self).__init__()
if __name__ == '__main__':
... # unchanged
</code></pre>
<p>... when i launch the script i get the error:</p>
<blockquote>
<p>TypeError: argument 1 of
QMainWindow.setCentralWidget() has an
invalid type</p>
</blockquote>
<p>This error message is cryptic for me as i can't connect it to the modification done.
Do you have an idea what could be the source of this error?</p>
| 0 | 2009-08-05T14:42:39Z | 1,233,760 | <p>I have not worked with PyQt before, but didn't you forget to call the constructor of the superclass here? </p>
<pre><code>class MyWidget(QtGui.QWidget):
def __init__(self):
# Where is the call to QtGui.QWidget's init ?
pass
</code></pre>
| 0 | 2009-08-05T14:48:47Z | [
"python",
"pyqt4"
] |
PyQt : why adding a dummy class definition in my file make the application crash? | 1,233,711 | <p>Consider the code below:</p>
<pre><code> #!/usr/bin/env python
from PyQt4 import QtCore, QtGui
import os,sys
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.listWidget = QtGui.QListWidget(None)
self.setCentralWidget(self.listWidget)
if __name__ == '__main__':
app = QtGui.QApplication (sys.argv)
mainWin = MainWindow ()
mainWin.show ()
sys.exit (app.exec_())
</code></pre>
<p>Works ok.
Now if I add a dummy class (that inherits from a QtGui module's class) in the global scope ...</p>
<pre><code>class MainWindow(QtGui.QMainWindow):
... # unchanged
class MyWidget(QtGui.QWidget):
def __init__(self):
super(MyWidget, self).__init__()
if __name__ == '__main__':
... # unchanged
</code></pre>
<p>... when i launch the script i get the error:</p>
<blockquote>
<p>TypeError: argument 1 of
QMainWindow.setCentralWidget() has an
invalid type</p>
</blockquote>
<p>This error message is cryptic for me as i can't connect it to the modification done.
Do you have an idea what could be the source of this error?</p>
| 0 | 2009-08-05T14:42:39Z | 1,234,122 | <p>Can't reproduce the problem as reported: the following exact code</p>
<pre><code>from PyQt4 import QtCore, QtGui
import os, sys
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.listWidget = QtGui.QListWidget(None)
self.setCentralWidget(self.listWidget)
class MyWidget(QtGui.QWidget):
def __init__(self):
super(MyWidget, self).__init__()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
mainWin = MainWindow()
mainWin.show()
sys.exit(app.exec_())
</code></pre>
<p>runs just fine for me (showing an empty window of course). So I guess it's down to versions details! I'm using system-supplied Python 2.5.1 on Mac OS X 10.5.7 and adding a</p>
<pre><code>print QtCore.PYQT_VERSION_STR
</code></pre>
<p>shows I'm on version 4.5.1 of PyQt. What about you?</p>
| 1 | 2009-08-05T15:49:39Z | [
"python",
"pyqt4"
] |
python sub-process | 1,233,728 | <p>I usually execute a Fortran file in Linux (manually) as:</p>
<ol>
<li>Connect to the server</li>
<li>Go to the specific folder</li>
<li><code>ifort xxx.for -o xxx && ./xxx</code> (where 'xxx.for' is my Fortran file and 'xxx' is Fortran executable file)</li>
</ol>
<p>But I need to call my fortran file (xxx.for) from python (I'm a beginner), so I used <code>subprocess</code> with the following command:</p>
<pre><code>cmd = ["ssh", sshConnect, "cd %s;"%(workDir), Fortrancmd %s jobname "%s -o %s" exeFilename "%s && %s ./ %s%s"%(exeFilename)]
</code></pre>
<p>But I get an error, and I'm not sure what's wrong. Here's the full code:</p>
<pre><code>import string
import subprocess as subProc
from subprocess import Popen as ProcOpen
from subprocess import PIPE
import numpy
import subprocess
userID = "pear"
serverName = "say4"
workDir = "/home/pear/2/W/fortran/"
Fortrancmd = "ifort"
jobname = "rad.for"
exeFilename = "rad"
sshConnect=userID+"@"+servername
cmd=["ssh", sshConnect, "cd %s;"%(workDir), Fortrancmd %s jobname "%s -o %s" exeFilename "%s && %s ./ %s%s"%(exeFilename)]
**#command to execute fortran files in Linux
**#ifort <filename>.for -o <filename> && ./<filename> (press enter)
**#example:ifort xxx.for -o xxx && ./xxx (press enter)
print cmd
</code></pre>
<p>How can I write a python program that performs all 3 steps described above and avoids the error I'm getting?</p>
| 5 | 2009-08-05T14:44:40Z | 1,233,801 | <p>do you have to use python?</p>
<p>ssh user@host "command"</p>
| 0 | 2009-08-05T14:54:11Z | [
"python",
"ssh",
"subprocess"
] |
python sub-process | 1,233,728 | <p>I usually execute a Fortran file in Linux (manually) as:</p>
<ol>
<li>Connect to the server</li>
<li>Go to the specific folder</li>
<li><code>ifort xxx.for -o xxx && ./xxx</code> (where 'xxx.for' is my Fortran file and 'xxx' is Fortran executable file)</li>
</ol>
<p>But I need to call my fortran file (xxx.for) from python (I'm a beginner), so I used <code>subprocess</code> with the following command:</p>
<pre><code>cmd = ["ssh", sshConnect, "cd %s;"%(workDir), Fortrancmd %s jobname "%s -o %s" exeFilename "%s && %s ./ %s%s"%(exeFilename)]
</code></pre>
<p>But I get an error, and I'm not sure what's wrong. Here's the full code:</p>
<pre><code>import string
import subprocess as subProc
from subprocess import Popen as ProcOpen
from subprocess import PIPE
import numpy
import subprocess
userID = "pear"
serverName = "say4"
workDir = "/home/pear/2/W/fortran/"
Fortrancmd = "ifort"
jobname = "rad.for"
exeFilename = "rad"
sshConnect=userID+"@"+servername
cmd=["ssh", sshConnect, "cd %s;"%(workDir), Fortrancmd %s jobname "%s -o %s" exeFilename "%s && %s ./ %s%s"%(exeFilename)]
**#command to execute fortran files in Linux
**#ifort <filename>.for -o <filename> && ./<filename> (press enter)
**#example:ifort xxx.for -o xxx && ./xxx (press enter)
print cmd
</code></pre>
<p>How can I write a python program that performs all 3 steps described above and avoids the error I'm getting?</p>
| 5 | 2009-08-05T14:44:40Z | 1,233,808 | <p>For the manual part you may want to look into <a href="http://pexpect.sourceforge.net/pexpect.html" rel="nofollow">pexpect</a> or for windows <a href="http://sage.math.washington.edu/home/goreckc/sage/wexpect/" rel="nofollow">wexpect</a>. These allow you to perform subprocesses and pass input under interactive conditions. </p>
<p>However most of what you're doing sounds like it would work well in a shell script. For simplicity, you could make a shell script on the server side for your server side operations, and then plug in the path in the ssh statement:</p>
<pre><code>ssh user@host "/path/to/script.sh"
</code></pre>
| 2 | 2009-08-05T14:55:28Z | [
"python",
"ssh",
"subprocess"
] |
python sub-process | 1,233,728 | <p>I usually execute a Fortran file in Linux (manually) as:</p>
<ol>
<li>Connect to the server</li>
<li>Go to the specific folder</li>
<li><code>ifort xxx.for -o xxx && ./xxx</code> (where 'xxx.for' is my Fortran file and 'xxx' is Fortran executable file)</li>
</ol>
<p>But I need to call my fortran file (xxx.for) from python (I'm a beginner), so I used <code>subprocess</code> with the following command:</p>
<pre><code>cmd = ["ssh", sshConnect, "cd %s;"%(workDir), Fortrancmd %s jobname "%s -o %s" exeFilename "%s && %s ./ %s%s"%(exeFilename)]
</code></pre>
<p>But I get an error, and I'm not sure what's wrong. Here's the full code:</p>
<pre><code>import string
import subprocess as subProc
from subprocess import Popen as ProcOpen
from subprocess import PIPE
import numpy
import subprocess
userID = "pear"
serverName = "say4"
workDir = "/home/pear/2/W/fortran/"
Fortrancmd = "ifort"
jobname = "rad.for"
exeFilename = "rad"
sshConnect=userID+"@"+servername
cmd=["ssh", sshConnect, "cd %s;"%(workDir), Fortrancmd %s jobname "%s -o %s" exeFilename "%s && %s ./ %s%s"%(exeFilename)]
**#command to execute fortran files in Linux
**#ifort <filename>.for -o <filename> && ./<filename> (press enter)
**#example:ifort xxx.for -o xxx && ./xxx (press enter)
print cmd
</code></pre>
<p>How can I write a python program that performs all 3 steps described above and avoids the error I'm getting?</p>
| 5 | 2009-08-05T14:44:40Z | 1,233,847 | <p>one error:<br>
you have an unquoted %s in your list of args, so your string formatting will fail.</p>
| 1 | 2009-08-05T15:01:13Z | [
"python",
"ssh",
"subprocess"
] |
python sub-process | 1,233,728 | <p>I usually execute a Fortran file in Linux (manually) as:</p>
<ol>
<li>Connect to the server</li>
<li>Go to the specific folder</li>
<li><code>ifort xxx.for -o xxx && ./xxx</code> (where 'xxx.for' is my Fortran file and 'xxx' is Fortran executable file)</li>
</ol>
<p>But I need to call my fortran file (xxx.for) from python (I'm a beginner), so I used <code>subprocess</code> with the following command:</p>
<pre><code>cmd = ["ssh", sshConnect, "cd %s;"%(workDir), Fortrancmd %s jobname "%s -o %s" exeFilename "%s && %s ./ %s%s"%(exeFilename)]
</code></pre>
<p>But I get an error, and I'm not sure what's wrong. Here's the full code:</p>
<pre><code>import string
import subprocess as subProc
from subprocess import Popen as ProcOpen
from subprocess import PIPE
import numpy
import subprocess
userID = "pear"
serverName = "say4"
workDir = "/home/pear/2/W/fortran/"
Fortrancmd = "ifort"
jobname = "rad.for"
exeFilename = "rad"
sshConnect=userID+"@"+servername
cmd=["ssh", sshConnect, "cd %s;"%(workDir), Fortrancmd %s jobname "%s -o %s" exeFilename "%s && %s ./ %s%s"%(exeFilename)]
**#command to execute fortran files in Linux
**#ifort <filename>.for -o <filename> && ./<filename> (press enter)
**#example:ifort xxx.for -o xxx && ./xxx (press enter)
print cmd
</code></pre>
<p>How can I write a python program that performs all 3 steps described above and avoids the error I'm getting?</p>
| 5 | 2009-08-05T14:44:40Z | 1,233,854 | <p>there are some syntax errors...</p>
<p>original:</p>
<pre><code>cmd=["ssh", sshConnect, "cd %s;"%(workDir), Fortrancmd %s jobname "%s -o %s" exeFilename "%s && %s ./ %s%s"%(exeFilename)]
</code></pre>
<p>I think you mean:</p>
<pre><code>cmd = [
"ssh",
sshConnect,
"cd %s;" % (workDir,),
"%s %s -o %s && ./%s" % (Fortrancmd, jobname, exeFilename, exeFilename)
]
</code></pre>
<p>A few notes:</p>
<ul>
<li>a tuple with one element requires a comma at the end of the first argument see (workDir,) to be interpreted as a tuple (vs. simple order-of-operations parens)</li>
<li>it is probably easier to contruct your fortan command with a single string format operation</li>
</ul>
<p>PS - For readability it is often a good idea to break long lists into multiple lines :)</p>
<h2>my advice</h2>
<p>I would recommend looking at <a href="http://stackoverflow.com/questions/1233655/what-is-the-simplest-way-to-ssh-using-python">this stackoverflow thread for ssh</a> instead of using subprocess</p>
| 3 | 2009-08-05T15:03:35Z | [
"python",
"ssh",
"subprocess"
] |
python sub-process | 1,233,728 | <p>I usually execute a Fortran file in Linux (manually) as:</p>
<ol>
<li>Connect to the server</li>
<li>Go to the specific folder</li>
<li><code>ifort xxx.for -o xxx && ./xxx</code> (where 'xxx.for' is my Fortran file and 'xxx' is Fortran executable file)</li>
</ol>
<p>But I need to call my fortran file (xxx.for) from python (I'm a beginner), so I used <code>subprocess</code> with the following command:</p>
<pre><code>cmd = ["ssh", sshConnect, "cd %s;"%(workDir), Fortrancmd %s jobname "%s -o %s" exeFilename "%s && %s ./ %s%s"%(exeFilename)]
</code></pre>
<p>But I get an error, and I'm not sure what's wrong. Here's the full code:</p>
<pre><code>import string
import subprocess as subProc
from subprocess import Popen as ProcOpen
from subprocess import PIPE
import numpy
import subprocess
userID = "pear"
serverName = "say4"
workDir = "/home/pear/2/W/fortran/"
Fortrancmd = "ifort"
jobname = "rad.for"
exeFilename = "rad"
sshConnect=userID+"@"+servername
cmd=["ssh", sshConnect, "cd %s;"%(workDir), Fortrancmd %s jobname "%s -o %s" exeFilename "%s && %s ./ %s%s"%(exeFilename)]
**#command to execute fortran files in Linux
**#ifort <filename>.for -o <filename> && ./<filename> (press enter)
**#example:ifort xxx.for -o xxx && ./xxx (press enter)
print cmd
</code></pre>
<p>How can I write a python program that performs all 3 steps described above and avoids the error I'm getting?</p>
| 5 | 2009-08-05T14:44:40Z | 1,800,837 | <p>Here is a complete example of using the subprocess module to run a remote command via ssh (a simple echo in this case) and grab the results, hope it helps:</p>
<pre><code>>>> import subprocess
>>> proc = subprocess.Popen(("ssh", "remoteuser@host", "echo", "1"), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> stdout, stderr = proc.communicate()
</code></pre>
<p>Which in this case returns: ('1\n', '')</p>
<p>Note that to get this to work without requiring a password you will likely have to add your local user's public key to ~remoteuser/.ssh/authorized_keys on the remote machine.</p>
| 1 | 2009-11-26T00:10:40Z | [
"python",
"ssh",
"subprocess"
] |
python sub-process | 1,233,728 | <p>I usually execute a Fortran file in Linux (manually) as:</p>
<ol>
<li>Connect to the server</li>
<li>Go to the specific folder</li>
<li><code>ifort xxx.for -o xxx && ./xxx</code> (where 'xxx.for' is my Fortran file and 'xxx' is Fortran executable file)</li>
</ol>
<p>But I need to call my fortran file (xxx.for) from python (I'm a beginner), so I used <code>subprocess</code> with the following command:</p>
<pre><code>cmd = ["ssh", sshConnect, "cd %s;"%(workDir), Fortrancmd %s jobname "%s -o %s" exeFilename "%s && %s ./ %s%s"%(exeFilename)]
</code></pre>
<p>But I get an error, and I'm not sure what's wrong. Here's the full code:</p>
<pre><code>import string
import subprocess as subProc
from subprocess import Popen as ProcOpen
from subprocess import PIPE
import numpy
import subprocess
userID = "pear"
serverName = "say4"
workDir = "/home/pear/2/W/fortran/"
Fortrancmd = "ifort"
jobname = "rad.for"
exeFilename = "rad"
sshConnect=userID+"@"+servername
cmd=["ssh", sshConnect, "cd %s;"%(workDir), Fortrancmd %s jobname "%s -o %s" exeFilename "%s && %s ./ %s%s"%(exeFilename)]
**#command to execute fortran files in Linux
**#ifort <filename>.for -o <filename> && ./<filename> (press enter)
**#example:ifort xxx.for -o xxx && ./xxx (press enter)
print cmd
</code></pre>
<p>How can I write a python program that performs all 3 steps described above and avoids the error I'm getting?</p>
| 5 | 2009-08-05T14:44:40Z | 10,364,583 | <p>You could use <a href="http://docs.fabfile.org" rel="nofollow">fabric</a> for steps 1 and 2.
This is the basic idea:</p>
<pre><code>from fabric.api import *
env.hosts = ['host']
dir = '/home/...'
def compile(file):
with cd(dir):
run("ifort %s.for -o %s" % file)
run("./%s > stdout.txt" % file)
</code></pre>
<ul>
<li>Create fabfile.py</li>
<li>And you run <code>fab compile:filename</code></li>
</ul>
| 1 | 2012-04-28T14:49:18Z | [
"python",
"ssh",
"subprocess"
] |
PIL does not save transparency | 1,233,772 | <pre><code>from PIL import Image
img = Image.open('1.png')
img.save('2.png')
</code></pre>
<p>The first image has a transparent background, but when I save it, the transparency is gone (background is white)</p>
<p>What am I doing wrong?</p>
| 9 | 2009-08-05T14:50:26Z | 1,233,807 | <p>Probably the image is indexed (mode "P" in PIL), so the transparency is not set in PNG alpha channel, but in metadata info.</p>
<p>You can get transparent background palette index with the following code:</p>
<pre><code>from PIL import Image
img = Image.open('1.png')
png_info = img.info
img.save('2.png', **png_info)
</code></pre>
<p>image info is a dictionary, so you can inspect it to see the info that it has:</p>
<p>eg: If you print it you will get an output like the following:</p>
<pre><code>{'transparency': 7, 'gamma': 0.45454, 'dpi': (72, 72)}
</code></pre>
<p>The information saved there will vary depending on the tool that created the original PNG, but what is important for you here is the "transparency" key. In the example it says that palette index "7" must be treated as transparent.</p>
| 28 | 2009-08-05T14:55:20Z | [
"python",
"png",
"python-imaging-library"
] |
PIL does not save transparency | 1,233,772 | <pre><code>from PIL import Image
img = Image.open('1.png')
img.save('2.png')
</code></pre>
<p>The first image has a transparent background, but when I save it, the transparency is gone (background is white)</p>
<p>What am I doing wrong?</p>
| 9 | 2009-08-05T14:50:26Z | 1,234,048 | <p>You can always force the the type to "RGBA",</p>
<pre><code>img = Image.open('1.png')
img.convert('RGBA')
img.save('2.png')
</code></pre>
| 2 | 2009-08-05T15:38:30Z | [
"python",
"png",
"python-imaging-library"
] |
How long do zipimported module imports remain cached in memory when using appengine / python and is there a way to keep them in memory? | 1,233,826 | <p>I've recently uploaded an app that uses django appengine patch and currently have a cron job that runs every two minutes. On each invocation of the worker url it consumes quite a bit of resources </p>
<pre><code>/worker_url 200 7633ms 34275cpu_ms 28116api_ms
</code></pre>
<p>That is because on each invocation it does a cold zipimport of all the libraries django etc.</p>
<ul>
<li>How long do the imported modules stay in memory?</li>
<li>Is there a way to keep these modules in memory so even if subsequent calls are not within the timeframe that these modules stay in memory they still don't invoke the overhead?</li>
</ul>
| 1 | 2009-08-05T14:58:29Z | 1,233,996 | <p>app engine keeps everything in memory according to normal Python semantics as long as it's serving one or more requests in the same process in the same node; if and when it needs those resources, the process goes away (so nothing stays in memory that it used to have), and new processes may be started (on the same node or different nodes) any time to serve requests (whether other processes serving other requests are still running, or not). This is much like the fast-CGI model: you're assured of normal semantics within a single request but apart from that anything between 0 and N (no upper limit) different nodes may be running your code, each serving sequentially anything between 0 and K (no upper limit) different requests.</p>
<p>There is nothing you can do to "stay in memory" (for zipimported modules or anything else).</p>
<p>For completeness let me mention memcache, which is an explicit hint/request to the app engine runtime to keep something in a special form of memory, a distributed hash table that's shared among all processes running your code -- that's hard though not impossible to use for imported modules (you'd need pretty sophisticated import hooks) and I recommend against the effort needed to develop such hooks because even in presence of such explicit hints the app engine runtime can still at any time choose to eject anything you've stashed away in the cache, anyway.</p>
<p>Rather -- I'm not sure why a cron job in particular would need all of django nor of why you're zipimporting it rather than just using the 1.0.2 that now comes with app engine, per <a href="http://code.google.com/appengine/docs/python/tools/libraries.html#Django" rel="nofollow">the docs</a> -- care to elaborate? This might be a useful issue for you to optimize.</p>
| 1 | 2009-08-05T15:27:31Z | [
"python",
"django",
"google-app-engine",
"import"
] |
In GTK, how do I get the actual size of a widget on screen? | 1,234,223 | <p>First I looked at the <code>get_size_request</code> method. The docs there end with:</p>
<blockquote>
<p>To get the size a widget will actually use, call the <code>size_request()</code> instead of this method.</p>
</blockquote>
<p>I look at <code>size_request()</code>, and it ends with </p>
<blockquote>
<p>Also remember that the size request is not necessarily the size a widget will actually be allocated.</p>
</blockquote>
<p>So, is there any function in GTK to get what size a widget actually is? This is a widget that is on-screen and actually being displayed, so GTK definitely has this information somewhere.</p>
| 5 | 2009-08-05T16:09:08Z | 1,234,294 | <p>This should be it (took some time to find):</p>
<blockquote>
<p>The get_allocation() method returns a gtk.gdk.Rectangle containing the bounds of the widget's allocation.</p>
</blockquote>
<p>From <a href="http://library.gnome.org/devel/pygtk/stable/class-gtkwidget.html#method-gtkwidget--get-allocation">here</a>.</p>
| 9 | 2009-08-05T16:23:46Z | [
"python",
"api",
"user-interface",
"gtk",
"pygtk"
] |
In Twisted Python - Make sure a protocol instance would be completely deallocated | 1,234,292 | <p>I have a pretty intensive chat socket server written in Twisted Python, I start it using internet.TCPServer with a factory and that factory references to a protocol object that handles all communications with the client.</p>
<p>How should I make sure a protocol instance completely destroys itself once a client has disconnected?</p>
<p>I've got a function named connectionLost that is fired up once a client disconnects and I try stopping all activity right there but I suspect some reactor stuff (like twisted.words instances) keep running for obsolete protocol instances.</p>
<p>What would be the best approach to handle this?</p>
<p>Thanks!</p>
| 4 | 2009-08-05T16:23:16Z | 1,236,382 | <p>ok, for sorting out this issue I have set a <code>__del__</code> method in the protocol class and I am now logging protocol instances that have not been garbage collected within 1 minute from the time the client has disconnected. </p>
<p>If anybody has any better solution I'll still be glad to hear about it but so far I have already fixed a few potential memory leaks using this log.</p>
<p>Thanks!</p>
| -1 | 2009-08-06T00:14:22Z | [
"python",
"sockets",
"twisted",
"twisted.words"
] |
Introspecting a given function's nested (local) functions in Python | 1,234,672 | <p>Given the function</p>
<pre><code>def f():
x, y = 1, 2
def get():
print 'get'
def post():
print 'post'
</code></pre>
<p>is there a way for me to access its local get() and post() functions in a way that I can call them? I'm looking for a function that will work like so with the function f() defined above:</p>
<pre><code>>>> get, post = get_local_functions(f)
>>> get()
'get'
</code></pre>
<p>I can access the code objects for those local functions like so</p>
<pre><code>import inspect
for c in f.func_code.co_consts:
if inspect.iscode(c):
print c.co_name, c
</code></pre>
<p>which results in</p>
<pre><code>get <code object get at 0x26e78 ...>
post <code object post at 0x269f8 ...>
</code></pre>
<p>but I can't figure out how to get the actual callable function objects. Is that even possible?</p>
<p>Thanks for your help,</p>
<p>Will.</p>
| 5 | 2009-08-05T17:36:15Z | 1,234,689 | <p>You can return functions just like any other object in Python:</p>
<pre><code>def f():
x, y = 1, 2
def get():
print 'get'
def post():
print 'post'
return (get, post)
get, post = f()
</code></pre>
<p>Hope this helps!</p>
<p>Note, though, that if you want to use your 'x' and 'y' variables in get() or post(), you should make them a list.</p>
<p>If you do something like this:</p>
<pre><code>def f():
x = [1]
def get():
print 'get', x[0]
x[0] -= 1
def post():
print 'post', x[0]
x[0] += 1
return (get, post)
get1, post1 = f()
get2, post2 = f()
</code></pre>
<p>get1 and post1 will reference a different 'x' list than get2 and post2.</p>
| 2 | 2009-08-05T17:43:38Z | [
"python",
"function",
"introspection",
"inspect"
] |
Introspecting a given function's nested (local) functions in Python | 1,234,672 | <p>Given the function</p>
<pre><code>def f():
x, y = 1, 2
def get():
print 'get'
def post():
print 'post'
</code></pre>
<p>is there a way for me to access its local get() and post() functions in a way that I can call them? I'm looking for a function that will work like so with the function f() defined above:</p>
<pre><code>>>> get, post = get_local_functions(f)
>>> get()
'get'
</code></pre>
<p>I can access the code objects for those local functions like so</p>
<pre><code>import inspect
for c in f.func_code.co_consts:
if inspect.iscode(c):
print c.co_name, c
</code></pre>
<p>which results in</p>
<pre><code>get <code object get at 0x26e78 ...>
post <code object post at 0x269f8 ...>
</code></pre>
<p>but I can't figure out how to get the actual callable function objects. Is that even possible?</p>
<p>Thanks for your help,</p>
<p>Will.</p>
| 5 | 2009-08-05T17:36:15Z | 1,234,756 | <p>You could use exec to run the code objects. For example, if you had f defined as above, then</p>
<pre><code>exec(f.func_code.co_consts[3])
</code></pre>
<p>would give </p>
<pre><code>get
</code></pre>
<p>as output. </p>
| 2 | 2009-08-05T17:57:21Z | [
"python",
"function",
"introspection",
"inspect"
] |
Introspecting a given function's nested (local) functions in Python | 1,234,672 | <p>Given the function</p>
<pre><code>def f():
x, y = 1, 2
def get():
print 'get'
def post():
print 'post'
</code></pre>
<p>is there a way for me to access its local get() and post() functions in a way that I can call them? I'm looking for a function that will work like so with the function f() defined above:</p>
<pre><code>>>> get, post = get_local_functions(f)
>>> get()
'get'
</code></pre>
<p>I can access the code objects for those local functions like so</p>
<pre><code>import inspect
for c in f.func_code.co_consts:
if inspect.iscode(c):
print c.co_name, c
</code></pre>
<p>which results in</p>
<pre><code>get <code object get at 0x26e78 ...>
post <code object post at 0x269f8 ...>
</code></pre>
<p>but I can't figure out how to get the actual callable function objects. Is that even possible?</p>
<p>Thanks for your help,</p>
<p>Will.</p>
| 5 | 2009-08-05T17:36:15Z | 1,235,642 | <p>The inner function objects don't exist before the function f() is executed. If you want to get them you'll have to construct them yourself. That is definitely non-trivial because they might be closures that capture variables from the scope of the function and will anyway require poking around in objects that should probably be regarded as implementation details of the interpreter.</p>
<p>If you want to collect the functions with less repetition I recommend one of the following approaches:</p>
<p>a) Just put the functions in a class definition and return a reference to that class. A collection of related functions that are accessed by name smells awfully like a class.</p>
<p>b) Create a dict subclass that has a method for registering functions and use that as a decorator.</p>
<p>The code for this would look something like this:</p>
<pre><code>class FunctionCollector(dict):
def register(self, func):
self[func.__name__] = func
def f():
funcs = FunctionCollector()
@funcs.register
def get():
return 'get'
@funcs.register
def put():
return 'put'
return funcs
</code></pre>
<p>c) Poke around in locals() and filter out the function with inspect.isfunction. (usually not a good idea)</p>
| 1 | 2009-08-05T20:45:10Z | [
"python",
"function",
"introspection",
"inspect"
] |
Introspecting a given function's nested (local) functions in Python | 1,234,672 | <p>Given the function</p>
<pre><code>def f():
x, y = 1, 2
def get():
print 'get'
def post():
print 'post'
</code></pre>
<p>is there a way for me to access its local get() and post() functions in a way that I can call them? I'm looking for a function that will work like so with the function f() defined above:</p>
<pre><code>>>> get, post = get_local_functions(f)
>>> get()
'get'
</code></pre>
<p>I can access the code objects for those local functions like so</p>
<pre><code>import inspect
for c in f.func_code.co_consts:
if inspect.iscode(c):
print c.co_name, c
</code></pre>
<p>which results in</p>
<pre><code>get <code object get at 0x26e78 ...>
post <code object post at 0x269f8 ...>
</code></pre>
<p>but I can't figure out how to get the actual callable function objects. Is that even possible?</p>
<p>Thanks for your help,</p>
<p>Will.</p>
| 5 | 2009-08-05T17:36:15Z | 1,235,801 | <p>You are pretty close of doing that - just missing <code>new</code> module:</p>
<pre><code>import inspect
import new
def f():
x, y = 1, 2
def get():
print 'get'
def post():
print 'post'
for c in f.func_code.co_consts:
if inspect.iscode(c):
f = new.function(c, globals())
print f # Here you have your function :].
</code></pre>
<p>But why the heck bother? Isn't it easier to use class? Instantiation looks like a function call anyway.</p>
| 4 | 2009-08-05T21:15:39Z | [
"python",
"function",
"introspection",
"inspect"
] |
How to roll my own pypi? | 1,235,331 | <p>I would like to run my own internal pypi server, for egg distribution within my organization.</p>
<p>I have found a few projects, such as: </p>
<ul>
<li><a href="http://pypi.python.org/pypi/EggBasket/">http://pypi.python.org/pypi/EggBasket/</a></li>
<li><a href="http://plone.org/products/plonesoftwarecenter">http://plone.org/products/plonesoftwarecenter</a></li>
</ul>
<p>As I understand it, pypi.python.org uses software called Cheese Shop. </p>
<p>My questions: </p>
<ol>
<li>Why can't I use cheeseshop itself? (I can't find it, not sure it exists)</li>
<li>How do other people solve this problem? (Currently we use <em>blush</em> svn to distribute eggs)</li>
</ol>
<p>*edit: This seems canonical <a href="http://wiki.python.org/moin/PyPiImplementations">http://wiki.python.org/moin/PyPiImplementations</a>. Still, I'm interested in feedback.</p>
| 36 | 2009-08-05T19:43:35Z | 1,236,347 | <p>The source to Cheese Shop can be downloaded from <a href="https://bitbucket.org/pypa/pypi/src" rel="nofollow">https://bitbucket.org/pypa/pypi/src</a>. There is also an example, from the page you linked to, of using Apache as a "dumb" Python package repository:</p>
<pre><code># Mount pypi repositories into URI space
Alias /pypi /var/pypi
# /pypi/dev: Redirect for unknown packages (fallback to pypi)
RewriteCond /var/pypi/dev/$1 !-d
RewriteCond /var/pypi/dev/$1 !-f
RewriteRule ^/pypi/dev/([^/]+)/?$ http://pypi.python.org/pypi/$1/ [R,L]
RewriteCond /var/pypi/dev/$1/$2 !-f
RewriteRule ^/pypi/dev/([^/]+)/([^/]+)$ http://pypi.python.org/pypi/$1/$2 [R,L]
# /pypi/stable: Redirect for unknown packages (fallback to pypi)
RewriteCond /var/pypi/stable/$1 !-d
RewriteCond /var/pypi/stable/$1 !-f
RewriteRule ^/pypi/stable/([^/]+)/?$ http://pypi.python.org/pypi/$1/ [R,L]
RewriteCond /var/pypi/stable/$1/$2 !-f
RewriteRule ^/pypi/stable/([^/]+)/([^/]+)$ http://pypi.python.org/pypi/$1/$2 [R,L]
</code></pre>
| 12 | 2009-08-06T00:00:39Z | [
"python",
"pypi"
] |
How to roll my own pypi? | 1,235,331 | <p>I would like to run my own internal pypi server, for egg distribution within my organization.</p>
<p>I have found a few projects, such as: </p>
<ul>
<li><a href="http://pypi.python.org/pypi/EggBasket/">http://pypi.python.org/pypi/EggBasket/</a></li>
<li><a href="http://plone.org/products/plonesoftwarecenter">http://plone.org/products/plonesoftwarecenter</a></li>
</ul>
<p>As I understand it, pypi.python.org uses software called Cheese Shop. </p>
<p>My questions: </p>
<ol>
<li>Why can't I use cheeseshop itself? (I can't find it, not sure it exists)</li>
<li>How do other people solve this problem? (Currently we use <em>blush</em> svn to distribute eggs)</li>
</ol>
<p>*edit: This seems canonical <a href="http://wiki.python.org/moin/PyPiImplementations">http://wiki.python.org/moin/PyPiImplementations</a>. Still, I'm interested in feedback.</p>
| 36 | 2009-08-05T19:43:35Z | 1,468,293 | <p>If you would like a lighter solution then deploying an entire pypi server, you could try using a server index generated by <a href="http://pypi.python.org/pypi/basketweaver" rel="nofollow">basketweaver</a>.</p>
| 2 | 2009-09-23T20:14:59Z | [
"python",
"pypi"
] |
How to roll my own pypi? | 1,235,331 | <p>I would like to run my own internal pypi server, for egg distribution within my organization.</p>
<p>I have found a few projects, such as: </p>
<ul>
<li><a href="http://pypi.python.org/pypi/EggBasket/">http://pypi.python.org/pypi/EggBasket/</a></li>
<li><a href="http://plone.org/products/plonesoftwarecenter">http://plone.org/products/plonesoftwarecenter</a></li>
</ul>
<p>As I understand it, pypi.python.org uses software called Cheese Shop. </p>
<p>My questions: </p>
<ol>
<li>Why can't I use cheeseshop itself? (I can't find it, not sure it exists)</li>
<li>How do other people solve this problem? (Currently we use <em>blush</em> svn to distribute eggs)</li>
</ol>
<p>*edit: This seems canonical <a href="http://wiki.python.org/moin/PyPiImplementations">http://wiki.python.org/moin/PyPiImplementations</a>. Still, I'm interested in feedback.</p>
| 36 | 2009-08-05T19:43:35Z | 12,632,065 | <p>Updated: crate.io has shut down and the domain is now something else entirely.</p>
<p>One project that hasn't been mentioned is <a href="https://crate.io/" rel="nofollow">https://crate.io/</a>, which seems very active. It claims to be a "Next Generation Python Packaging Index", but they have their repositories split nicely into pieces that seem to welcome customization and remixing to your purposes.</p>
| 3 | 2012-09-28T00:40:53Z | [
"python",
"pypi"
] |
How to roll my own pypi? | 1,235,331 | <p>I would like to run my own internal pypi server, for egg distribution within my organization.</p>
<p>I have found a few projects, such as: </p>
<ul>
<li><a href="http://pypi.python.org/pypi/EggBasket/">http://pypi.python.org/pypi/EggBasket/</a></li>
<li><a href="http://plone.org/products/plonesoftwarecenter">http://plone.org/products/plonesoftwarecenter</a></li>
</ul>
<p>As I understand it, pypi.python.org uses software called Cheese Shop. </p>
<p>My questions: </p>
<ol>
<li>Why can't I use cheeseshop itself? (I can't find it, not sure it exists)</li>
<li>How do other people solve this problem? (Currently we use <em>blush</em> svn to distribute eggs)</li>
</ol>
<p>*edit: This seems canonical <a href="http://wiki.python.org/moin/PyPiImplementations">http://wiki.python.org/moin/PyPiImplementations</a>. Still, I'm interested in feedback.</p>
| 36 | 2009-08-05T19:43:35Z | 12,874,682 | <p>For light-weight solution, use <a href="http://pypi.python.org/pypi/pypiserver">pypiserver</a>. </p>
| 12 | 2012-10-13T15:46:42Z | [
"python",
"pypi"
] |
How to roll my own pypi? | 1,235,331 | <p>I would like to run my own internal pypi server, for egg distribution within my organization.</p>
<p>I have found a few projects, such as: </p>
<ul>
<li><a href="http://pypi.python.org/pypi/EggBasket/">http://pypi.python.org/pypi/EggBasket/</a></li>
<li><a href="http://plone.org/products/plonesoftwarecenter">http://plone.org/products/plonesoftwarecenter</a></li>
</ul>
<p>As I understand it, pypi.python.org uses software called Cheese Shop. </p>
<p>My questions: </p>
<ol>
<li>Why can't I use cheeseshop itself? (I can't find it, not sure it exists)</li>
<li>How do other people solve this problem? (Currently we use <em>blush</em> svn to distribute eggs)</li>
</ol>
<p>*edit: This seems canonical <a href="http://wiki.python.org/moin/PyPiImplementations">http://wiki.python.org/moin/PyPiImplementations</a>. Still, I'm interested in feedback.</p>
| 36 | 2009-08-05T19:43:35Z | 14,475,708 | <p>Another missing from this (oldish) list: </p>
<h2><a href="https://github.com/benliles/djangopypi" rel="nofollow">djangopypi</a></h2>
<p>Django based, which might be a slight overkill, but I love django and it makes it extremely simple to modify it to your need should it not be satisfying.</p>
| 0 | 2013-01-23T08:57:02Z | [
"python",
"pypi"
] |
How to roll my own pypi? | 1,235,331 | <p>I would like to run my own internal pypi server, for egg distribution within my organization.</p>
<p>I have found a few projects, such as: </p>
<ul>
<li><a href="http://pypi.python.org/pypi/EggBasket/">http://pypi.python.org/pypi/EggBasket/</a></li>
<li><a href="http://plone.org/products/plonesoftwarecenter">http://plone.org/products/plonesoftwarecenter</a></li>
</ul>
<p>As I understand it, pypi.python.org uses software called Cheese Shop. </p>
<p>My questions: </p>
<ol>
<li>Why can't I use cheeseshop itself? (I can't find it, not sure it exists)</li>
<li>How do other people solve this problem? (Currently we use <em>blush</em> svn to distribute eggs)</li>
</ol>
<p>*edit: This seems canonical <a href="http://wiki.python.org/moin/PyPiImplementations">http://wiki.python.org/moin/PyPiImplementations</a>. Still, I'm interested in feedback.</p>
| 36 | 2009-08-05T19:43:35Z | 14,475,827 | <p>And crate source code is available, though documentation is, least that can be said, not-existent:</p>
<p><strong><a href="https://github.com/crateio/crate.web" rel="nofollow">Crate.Web</a></strong></p>
<p>It's a Django Application providing a Python Package Index. Uses a couple other packages from <a href="https://github.com/crateio" rel="nofollow">https://github.com/crateio</a> so you might be able to roll out your own version without django.</p>
<p>I'm specifically thinking about a static one, I always thought there should be a very easy way to go explore directly some [pre-configured] repositories and shop cheese directly from my github/bitbucket public and private repos, with just a simple (gunicorn) process running.</p>
| 0 | 2013-01-23T09:04:00Z | [
"python",
"pypi"
] |
How to roll my own pypi? | 1,235,331 | <p>I would like to run my own internal pypi server, for egg distribution within my organization.</p>
<p>I have found a few projects, such as: </p>
<ul>
<li><a href="http://pypi.python.org/pypi/EggBasket/">http://pypi.python.org/pypi/EggBasket/</a></li>
<li><a href="http://plone.org/products/plonesoftwarecenter">http://plone.org/products/plonesoftwarecenter</a></li>
</ul>
<p>As I understand it, pypi.python.org uses software called Cheese Shop. </p>
<p>My questions: </p>
<ol>
<li>Why can't I use cheeseshop itself? (I can't find it, not sure it exists)</li>
<li>How do other people solve this problem? (Currently we use <em>blush</em> svn to distribute eggs)</li>
</ol>
<p>*edit: This seems canonical <a href="http://wiki.python.org/moin/PyPiImplementations">http://wiki.python.org/moin/PyPiImplementations</a>. Still, I'm interested in feedback.</p>
| 36 | 2009-08-05T19:43:35Z | 19,236,106 | <p>There is a fork of djangopypi named djangopypi2 you can get it from <a href="https://github.com/popen2/djangopypi2/" rel="nofollow">https://github.com/popen2/djangopypi2/</a>, I installed it and works for me, this option is what I had choose from a list of about 24 alternatives that I have found in a recently search, you can see the list here: <a href="http://uyeya.blogspot.com/2013/10/list-of-local-alternatives-of-pypi.html" rel="nofollow">http://uyeya.blogspot.com/2013/10/list-of-local-alternatives-of-pypi.html</a></p>
| 3 | 2013-10-07T22:46:04Z | [
"python",
"pypi"
] |
How to roll my own pypi? | 1,235,331 | <p>I would like to run my own internal pypi server, for egg distribution within my organization.</p>
<p>I have found a few projects, such as: </p>
<ul>
<li><a href="http://pypi.python.org/pypi/EggBasket/">http://pypi.python.org/pypi/EggBasket/</a></li>
<li><a href="http://plone.org/products/plonesoftwarecenter">http://plone.org/products/plonesoftwarecenter</a></li>
</ul>
<p>As I understand it, pypi.python.org uses software called Cheese Shop. </p>
<p>My questions: </p>
<ol>
<li>Why can't I use cheeseshop itself? (I can't find it, not sure it exists)</li>
<li>How do other people solve this problem? (Currently we use <em>blush</em> svn to distribute eggs)</li>
</ol>
<p>*edit: This seems canonical <a href="http://wiki.python.org/moin/PyPiImplementations">http://wiki.python.org/moin/PyPiImplementations</a>. Still, I'm interested in feedback.</p>
| 36 | 2009-08-05T19:43:35Z | 21,519,926 | <p>I ran into the same problem, and <a href="https://pypi.python.org/pypi/ClueReleaseManager" rel="nofollow">ClueReleaseManager</a> solved the problem of hosting an internal PyPI server/custom Python repository for me. </p>
<p>That answers question two, and I guess you already have the answer to question one.</p>
| 0 | 2014-02-03T04:53:45Z | [
"python",
"pypi"
] |
Python: how can I handle any unhandled exception in an alternative way? | 1,235,349 | <p>Normally unhandled exceptions go to the stdout (or stderr?), I am building an app where I want to pass this info to the GUI before shutting down and display it to the user and, at the same time I want to write it to a log file. So, I need an str with the full text of the exception.</p>
<p>How can I do this?</p>
| 6 | 2009-08-05T19:46:05Z | 1,235,378 | <pre><code>try:
# blah blah The Main Loop, function, whatever...
except e:
do_something_with(str(e))
</code></pre>
| 0 | 2009-08-05T19:52:24Z | [
"python",
"exception"
] |
Python: how can I handle any unhandled exception in an alternative way? | 1,235,349 | <p>Normally unhandled exceptions go to the stdout (or stderr?), I am building an app where I want to pass this info to the GUI before shutting down and display it to the user and, at the same time I want to write it to a log file. So, I need an str with the full text of the exception.</p>
<p>How can I do this?</p>
| 6 | 2009-08-05T19:46:05Z | 1,235,428 | <pre><code>import sys, logging
logging.basicConfig(filename='/path/to/log/file', filemode='w')
...
try:
your_code_here()
except:
logging.exception("My code failed") # logs exception to file
# you define display_exception_in_ui as "def display_exception_in_ui(exc, tb):"
display_exception_in_ui(*sys.exc_info()[1:]) # passes exception instance, traceback
</code></pre>
| 2 | 2009-08-05T20:00:55Z | [
"python",
"exception"
] |
Python: how can I handle any unhandled exception in an alternative way? | 1,235,349 | <p>Normally unhandled exceptions go to the stdout (or stderr?), I am building an app where I want to pass this info to the GUI before shutting down and display it to the user and, at the same time I want to write it to a log file. So, I need an str with the full text of the exception.</p>
<p>How can I do this?</p>
| 6 | 2009-08-05T19:46:05Z | 1,235,434 | <p>Use sys.excepthook to replace the base exception handler. You can do something like:</p>
<pre><code>import sys
from PyQt4 import QtGui
import os.path
import traceback
def handle_exception(exc_type, exc_value, exc_traceback):
""" handle all exceptions """
## KeyboardInterrupt is a special case.
## We don't raise the error dialog when it occurs.
if issubclass(exc_type, KeyboardInterrupt):
if QtGui.qApp:
QtGui.qApp.quit()
return
filename, line, dummy, dummy = traceback.extract_tb( exc_traceback ).pop()
filename = os.path.basename( filename )
error = "%s: %s" % ( exc_type.__name__, exc_value )
QtGui.QMessageBox.critical(None,"Error",
"<html>A critical error has occured.<br/> "
+ "<b>%s</b><br/><br/>" % error
+ "It occurred at <b>line %d</b> of file <b>%s</b>.<br/>" % (line, filename)
+ "</html>")
print "Closed due to an error. This is the full error report:"
print
print "".join(traceback.format_exception(exc_type, exc_value, exc_traceback))
sys.exit(1)
# install handler for exceptions
sys.excepthook = handle_exception
</code></pre>
<p>This catches all unhandled exceptions, so you don't need a try...except block at the top level of your code.</p>
| 13 | 2009-08-05T20:02:35Z | [
"python",
"exception"
] |
Python: how can I handle any unhandled exception in an alternative way? | 1,235,349 | <p>Normally unhandled exceptions go to the stdout (or stderr?), I am building an app where I want to pass this info to the GUI before shutting down and display it to the user and, at the same time I want to write it to a log file. So, I need an str with the full text of the exception.</p>
<p>How can I do this?</p>
| 6 | 2009-08-05T19:46:05Z | 1,236,614 | <p>You already got excellent answers, I just wanted to add one more tip that's served me well over the years in a variety of language for the specific problem "how to cleanly diagnose, log, etc, <code>out of memory</code> errors?". Problem is, if your code gets control before enough objects have been destroyed and their memory recycled, memory might be too tight to do propert logging, gui work, etc, etc -- how do we ensure this doesn't happen?</p>
<p>Answer: build an emergency stash so you know you can spend it in such emergencies:</p>
<pre><code>rainydayfund = [[] for x in xrange(16*1024)] # or however much you need
def handle_exception(e):
global rainydayfund
del rainydayfund
... etc, etc ...
</code></pre>
| 8 | 2009-08-06T02:01:42Z | [
"python",
"exception"
] |
Python: how can I handle any unhandled exception in an alternative way? | 1,235,349 | <p>Normally unhandled exceptions go to the stdout (or stderr?), I am building an app where I want to pass this info to the GUI before shutting down and display it to the user and, at the same time I want to write it to a log file. So, I need an str with the full text of the exception.</p>
<p>How can I do this?</p>
| 6 | 2009-08-05T19:46:05Z | 32,189,605 | <p>I tried using <a href="http://stackoverflow.com/a/1235434/4794">Neil's answer</a>, but it doesn't work with a Tkinter GUI. For that, I had to <a href="http://stackoverflow.com/a/4771200/4794">override <code>report_callback_exception()</code></a>.</p>
<pre><code>import Tkinter as tk
import tkMessageBox
import traceback
class MyApp(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
parent.report_callback_exception = self.report_callback_exception
self.parent = parent
self.button_frame = tk.Frame(self)
self.button_frame.pack(side='top')
self.button_run = tk.Button(
self.button_frame, text="Run", command=self.run
)
self.button_run.grid(row=0, column=1, sticky='W')
def run(self):
tkMessageBox.showinfo('Info', 'The process is running.')
raise RuntimeError('Tripped.')
def report_callback_exception(self, exc_type, exc_value, exc_traceback):
message = ''.join(traceback.format_exception(exc_type,
exc_value,
exc_traceback))
tkMessageBox.showerror('Error', message)
def main():
root = tk.Tk() # parent widget
MyApp(root).pack(fill='both', expand=True)
root.mainloop() # enter Tk event loop
if __name__ == '__main__':
main()
</code></pre>
| 0 | 2015-08-24T18:51:55Z | [
"python",
"exception"
] |
In GTK, how do I make a window unable to be closed? | 1,235,417 | <p>For example, graying out the "X" on windows systems.</p>
| 4 | 2009-08-05T19:59:22Z | 1,235,424 | <p>Just call the <code>set_deletable</code> with <code>False</code> on the window in question. It will work as long as GTK can convince the window manager to make the window unclosable. </p>
| 3 | 2009-08-05T20:00:25Z | [
"python",
"windows",
"gtk",
"pygtk"
] |
In GTK, how do I make a window unable to be closed? | 1,235,417 | <p>For example, graying out the "X" on windows systems.</p>
| 4 | 2009-08-05T19:59:22Z | 1,283,500 | <p>If Gtk can't convince the window manager you can always connect the "delete-event" signal and return True from the callback. Doing this Gtk assumes that the callback handle that signal and does nothing.</p>
<pre><code>import gtk
window = gtk.Window()
window.connect('delete-event',lambda widget, event: True)
</code></pre>
| 5 | 2009-08-16T05:19:23Z | [
"python",
"windows",
"gtk",
"pygtk"
] |
Searching a Unicode file using Python | 1,235,588 | <h1>Setup</h1>
<p>I'm writing a script to process and annotate build logs from Visual Studio. The build logs are HTML, and from what I can tell, Unicode (UTF-16?) as well. Here's a snippet from one of the files:</p>
<blockquote>
<p>c:\anonyfolder\anonyfile.c(17169) : warning C4701: potentially uninitialized local variable 'object_adrs2' used<br />
c:\anonyfolder\anonyfile.c(17409) : warning C4701: potentially uninitialized local variable 'pclcrd_ptr' used<br />
c:\anonyfolder\anonyfile.c(17440) : warning C4701: potentially uninitialized local variable 'object_adrs2' used </p>
</blockquote>
<p>The first 16 bytes of the file look like this:</p>
<blockquote>
<p>feff 003c 0068 0074 006d 006c 003e 000d</p>
</blockquote>
<p>The rest of the file is littered with null bytes as well.</p>
<p>I'd like to be able to perform string and regular expression searches/matches on these files. However, when I try the following code I get an error message.</p>
<pre><code>buildLog = open(sys.argv[1]).readlines()
for line in buildLog:
match = u'warning'
if line.find(match) >= 0:
print line
</code></pre>
<p>The error message:</p>
<blockquote>
<p>Traceback (most recent call last):<br />
File "proclogs.py", line 60, in <br />
if line.find(match) >= 0:<br />
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)</p>
</blockquote>
<p>Apparently it's choking on the <code>0xff</code> byte in <code>0xfeff</code> at the beginning of the file. If I skip the first line, I get no matches:</p>
<pre><code>buildLog = open(sys.argv[1]).readlines()
for line in buildLog[1:]: # Skip the first line.
match = u'warning'
if line.find(match) >= 0:
print line
</code></pre>
<p>Likewise, using the non-Unicode <code>match = 'warning'</code> produces no results.</p>
<h1>Question</h1>
<p>How can I portably search a Unicode file using strings and regular expressions in Python? Additionally, how can I do so such that I can reconstruct the original file? (The goal is to be able to write annotations on the warning lines without mangling the file.)</p>
| 1 | 2009-08-05T20:35:59Z | 1,235,625 | <p>Try using the codecs package:</p>
<pre><code>import codecs
buildLog = codecs.open(sys.argv[1], "r", "utf-16").readlines()
</code></pre>
<p>Also you may run into trouble with your print statement as it may try to convert the strings to your console encoding. If you're printing for your review you could use,</p>
<pre><code>print repr(line)
</code></pre>
| 7 | 2009-08-05T20:42:51Z | [
"python",
"unicode",
"encoding"
] |
Searching a Unicode file using Python | 1,235,588 | <h1>Setup</h1>
<p>I'm writing a script to process and annotate build logs from Visual Studio. The build logs are HTML, and from what I can tell, Unicode (UTF-16?) as well. Here's a snippet from one of the files:</p>
<blockquote>
<p>c:\anonyfolder\anonyfile.c(17169) : warning C4701: potentially uninitialized local variable 'object_adrs2' used<br />
c:\anonyfolder\anonyfile.c(17409) : warning C4701: potentially uninitialized local variable 'pclcrd_ptr' used<br />
c:\anonyfolder\anonyfile.c(17440) : warning C4701: potentially uninitialized local variable 'object_adrs2' used </p>
</blockquote>
<p>The first 16 bytes of the file look like this:</p>
<blockquote>
<p>feff 003c 0068 0074 006d 006c 003e 000d</p>
</blockquote>
<p>The rest of the file is littered with null bytes as well.</p>
<p>I'd like to be able to perform string and regular expression searches/matches on these files. However, when I try the following code I get an error message.</p>
<pre><code>buildLog = open(sys.argv[1]).readlines()
for line in buildLog:
match = u'warning'
if line.find(match) >= 0:
print line
</code></pre>
<p>The error message:</p>
<blockquote>
<p>Traceback (most recent call last):<br />
File "proclogs.py", line 60, in <br />
if line.find(match) >= 0:<br />
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)</p>
</blockquote>
<p>Apparently it's choking on the <code>0xff</code> byte in <code>0xfeff</code> at the beginning of the file. If I skip the first line, I get no matches:</p>
<pre><code>buildLog = open(sys.argv[1]).readlines()
for line in buildLog[1:]: # Skip the first line.
match = u'warning'
if line.find(match) >= 0:
print line
</code></pre>
<p>Likewise, using the non-Unicode <code>match = 'warning'</code> produces no results.</p>
<h1>Question</h1>
<p>How can I portably search a Unicode file using strings and regular expressions in Python? Additionally, how can I do so such that I can reconstruct the original file? (The goal is to be able to write annotations on the warning lines without mangling the file.)</p>
| 1 | 2009-08-05T20:35:59Z | 1,235,698 | <p>Tried this? When saving a parsing script with non-ascii characters, I had the interpreter suggest an alternate encoding to the front of the file.</p>
<pre><code>Non-ASCII found, yet no encoding declared. Add a line like:
# -*- coding: cp1252 -*-
</code></pre>
<p>Adding that as the first line of the script fixed the problem for me. Not sure if this is what's causing your error, though.</p>
| 0 | 2009-08-05T20:55:11Z | [
"python",
"unicode",
"encoding"
] |
Comparing persistent storage solutions in python | 1,235,594 | <p>I'm starting on a new scientific project which has a lot of data (millions of entries) I'd like to store in an easily and quickly accessible format. I've come across a number of different potential options, but I'm not sure how to pick amongst them. My data can probably just be stored as a dictionary, or potentially a dictionary of dictionaries. Some potential considerations:</p>
<ul>
<li>Speed. I can't load all the data off disk every time I start a new script, and I'd like as quick access to random entries as possible.</li>
<li>Ease-of-use. This is python. The storage should feel like python.</li>
<li>Stability/maturity. I'd like something that's currently supported, although something that works well but is still in development would be fine. </li>
<li>Ease of installation. My sysadmin should be able to get this running on our cluster.</li>
</ul>
<p>I don't really care that much about the size of the storage, but it could be a consideration if an option is really terrible on this front. Also, if it matters, I'll most likely be creating the database once, and thereafter only reading from it.</p>
<p>Some potential options that I've started looking at (see <a href="http://stackoverflow.com/questions/195626/how-to-avoid-computation-every-time-a-python-module-is-reloaded">this</a> post):</p>
<ul>
<li><a href="http://www.pytables.org/">pyTables</a></li>
<li><a href="http://www.zope.org/">ZopeDB</a></li>
<li><a href="http://pypi.python.org/pypi/shove">shove</a></li>
<li><a href="http://docs.python.org/library/shelve.html">shelve</a></li>
<li><a href="http://streamhacker.com/2009/05/20/building-a-nltk-freqdist-on-redis/">redis</a></li>
<li><a href="http://www.mems-exchange.org/software/durus/">durus</a></li>
</ul>
<p>Any suggestions on which of these might be better for my purposes? Any better ideas? Some of these have a back-end; any suggestions on which file-system back-end would be best?</p>
| 10 | 2009-08-05T20:37:18Z | 1,235,620 | <p>A RDBMS.</p>
<p>Nothing is more realiable than using tables on a well known RDBMS. <a href="http://www.postgresql.org/" rel="nofollow">Postgresql</a> comes to mind.</p>
<p>That automatically gives you some choices for the future like clustering. Also you automatically have a lot of tools to administer your database, and you can use it from other software written in virtually any language.</p>
<p>It is really fast.</p>
<p>In the "feel like python" point, I might add that you can use an ORM. A strong name is <a href="http://www.sqlalchemy.org/" rel="nofollow">sqlalchemy</a>. Maybe with the <a href="http://elixir.ematia.de" rel="nofollow">elixir</a> "<em>extension</em>".</p>
<p>Using sqlalchemy you can leave your user/sysadmin choose which database backend he wants to use. Maybe they already have <a href="http://www.mysql.com/" rel="nofollow">MySql</a> installed - no problem.</p>
<p>RDBMSs are still the best choice for data storage.</p>
| 8 | 2009-08-05T20:41:50Z | [
"python",
"orm",
"persistence"
] |
Comparing persistent storage solutions in python | 1,235,594 | <p>I'm starting on a new scientific project which has a lot of data (millions of entries) I'd like to store in an easily and quickly accessible format. I've come across a number of different potential options, but I'm not sure how to pick amongst them. My data can probably just be stored as a dictionary, or potentially a dictionary of dictionaries. Some potential considerations:</p>
<ul>
<li>Speed. I can't load all the data off disk every time I start a new script, and I'd like as quick access to random entries as possible.</li>
<li>Ease-of-use. This is python. The storage should feel like python.</li>
<li>Stability/maturity. I'd like something that's currently supported, although something that works well but is still in development would be fine. </li>
<li>Ease of installation. My sysadmin should be able to get this running on our cluster.</li>
</ul>
<p>I don't really care that much about the size of the storage, but it could be a consideration if an option is really terrible on this front. Also, if it matters, I'll most likely be creating the database once, and thereafter only reading from it.</p>
<p>Some potential options that I've started looking at (see <a href="http://stackoverflow.com/questions/195626/how-to-avoid-computation-every-time-a-python-module-is-reloaded">this</a> post):</p>
<ul>
<li><a href="http://www.pytables.org/">pyTables</a></li>
<li><a href="http://www.zope.org/">ZopeDB</a></li>
<li><a href="http://pypi.python.org/pypi/shove">shove</a></li>
<li><a href="http://docs.python.org/library/shelve.html">shelve</a></li>
<li><a href="http://streamhacker.com/2009/05/20/building-a-nltk-freqdist-on-redis/">redis</a></li>
<li><a href="http://www.mems-exchange.org/software/durus/">durus</a></li>
</ul>
<p>Any suggestions on which of these might be better for my purposes? Any better ideas? Some of these have a back-end; any suggestions on which file-system back-end would be best?</p>
| 10 | 2009-08-05T20:37:18Z | 1,235,683 | <p>Sqlite -- it comes with python, fast, widely availible and easy to maintain</p>
| 3 | 2009-08-05T20:52:11Z | [
"python",
"orm",
"persistence"
] |
Comparing persistent storage solutions in python | 1,235,594 | <p>I'm starting on a new scientific project which has a lot of data (millions of entries) I'd like to store in an easily and quickly accessible format. I've come across a number of different potential options, but I'm not sure how to pick amongst them. My data can probably just be stored as a dictionary, or potentially a dictionary of dictionaries. Some potential considerations:</p>
<ul>
<li>Speed. I can't load all the data off disk every time I start a new script, and I'd like as quick access to random entries as possible.</li>
<li>Ease-of-use. This is python. The storage should feel like python.</li>
<li>Stability/maturity. I'd like something that's currently supported, although something that works well but is still in development would be fine. </li>
<li>Ease of installation. My sysadmin should be able to get this running on our cluster.</li>
</ul>
<p>I don't really care that much about the size of the storage, but it could be a consideration if an option is really terrible on this front. Also, if it matters, I'll most likely be creating the database once, and thereafter only reading from it.</p>
<p>Some potential options that I've started looking at (see <a href="http://stackoverflow.com/questions/195626/how-to-avoid-computation-every-time-a-python-module-is-reloaded">this</a> post):</p>
<ul>
<li><a href="http://www.pytables.org/">pyTables</a></li>
<li><a href="http://www.zope.org/">ZopeDB</a></li>
<li><a href="http://pypi.python.org/pypi/shove">shove</a></li>
<li><a href="http://docs.python.org/library/shelve.html">shelve</a></li>
<li><a href="http://streamhacker.com/2009/05/20/building-a-nltk-freqdist-on-redis/">redis</a></li>
<li><a href="http://www.mems-exchange.org/software/durus/">durus</a></li>
</ul>
<p>Any suggestions on which of these might be better for my purposes? Any better ideas? Some of these have a back-end; any suggestions on which file-system back-end would be best?</p>
| 10 | 2009-08-05T20:37:18Z | 1,235,761 | <p>If you only need simple (dict like) access mechanisms and need efficiency for processing a lot of data, then <a href="http://h5py.alfven.org/" rel="nofollow">HDF5</a> might be a good option. If you are going to be using numpy then it is really worth considering.</p>
| 2 | 2009-08-05T21:06:54Z | [
"python",
"orm",
"persistence"
] |
Comparing persistent storage solutions in python | 1,235,594 | <p>I'm starting on a new scientific project which has a lot of data (millions of entries) I'd like to store in an easily and quickly accessible format. I've come across a number of different potential options, but I'm not sure how to pick amongst them. My data can probably just be stored as a dictionary, or potentially a dictionary of dictionaries. Some potential considerations:</p>
<ul>
<li>Speed. I can't load all the data off disk every time I start a new script, and I'd like as quick access to random entries as possible.</li>
<li>Ease-of-use. This is python. The storage should feel like python.</li>
<li>Stability/maturity. I'd like something that's currently supported, although something that works well but is still in development would be fine. </li>
<li>Ease of installation. My sysadmin should be able to get this running on our cluster.</li>
</ul>
<p>I don't really care that much about the size of the storage, but it could be a consideration if an option is really terrible on this front. Also, if it matters, I'll most likely be creating the database once, and thereafter only reading from it.</p>
<p>Some potential options that I've started looking at (see <a href="http://stackoverflow.com/questions/195626/how-to-avoid-computation-every-time-a-python-module-is-reloaded">this</a> post):</p>
<ul>
<li><a href="http://www.pytables.org/">pyTables</a></li>
<li><a href="http://www.zope.org/">ZopeDB</a></li>
<li><a href="http://pypi.python.org/pypi/shove">shove</a></li>
<li><a href="http://docs.python.org/library/shelve.html">shelve</a></li>
<li><a href="http://streamhacker.com/2009/05/20/building-a-nltk-freqdist-on-redis/">redis</a></li>
<li><a href="http://www.mems-exchange.org/software/durus/">durus</a></li>
</ul>
<p>Any suggestions on which of these might be better for my purposes? Any better ideas? Some of these have a back-end; any suggestions on which file-system back-end would be best?</p>
| 10 | 2009-08-05T20:37:18Z | 1,235,922 | <p>Go with a RDBMS is reliable scalable and fast.</p>
<p>If you need a more scalabre solution and don't need the features of RDBMS, you can go with a key-value store like couchdb that has a good python api.</p>
| 1 | 2009-08-05T21:43:36Z | [
"python",
"orm",
"persistence"
] |
Comparing persistent storage solutions in python | 1,235,594 | <p>I'm starting on a new scientific project which has a lot of data (millions of entries) I'd like to store in an easily and quickly accessible format. I've come across a number of different potential options, but I'm not sure how to pick amongst them. My data can probably just be stored as a dictionary, or potentially a dictionary of dictionaries. Some potential considerations:</p>
<ul>
<li>Speed. I can't load all the data off disk every time I start a new script, and I'd like as quick access to random entries as possible.</li>
<li>Ease-of-use. This is python. The storage should feel like python.</li>
<li>Stability/maturity. I'd like something that's currently supported, although something that works well but is still in development would be fine. </li>
<li>Ease of installation. My sysadmin should be able to get this running on our cluster.</li>
</ul>
<p>I don't really care that much about the size of the storage, but it could be a consideration if an option is really terrible on this front. Also, if it matters, I'll most likely be creating the database once, and thereafter only reading from it.</p>
<p>Some potential options that I've started looking at (see <a href="http://stackoverflow.com/questions/195626/how-to-avoid-computation-every-time-a-python-module-is-reloaded">this</a> post):</p>
<ul>
<li><a href="http://www.pytables.org/">pyTables</a></li>
<li><a href="http://www.zope.org/">ZopeDB</a></li>
<li><a href="http://pypi.python.org/pypi/shove">shove</a></li>
<li><a href="http://docs.python.org/library/shelve.html">shelve</a></li>
<li><a href="http://streamhacker.com/2009/05/20/building-a-nltk-freqdist-on-redis/">redis</a></li>
<li><a href="http://www.mems-exchange.org/software/durus/">durus</a></li>
</ul>
<p>Any suggestions on which of these might be better for my purposes? Any better ideas? Some of these have a back-end; any suggestions on which file-system back-end would be best?</p>
| 10 | 2009-08-05T20:37:18Z | 1,235,947 | <p>Might want to give <a href="http://www.mongodb.org/">mongodb</a> a shot - the PyMongo library works with dictionaries and supports most Python types. Easy to install, very performant + scalable. MongoDB (and PyMongo) is also used <a href="http://www.mongodb.org/display/DOCS/Production+Deployments">in production</a> at some big names.</p>
| 13 | 2009-08-05T21:49:31Z | [
"python",
"orm",
"persistence"
] |
Comparing persistent storage solutions in python | 1,235,594 | <p>I'm starting on a new scientific project which has a lot of data (millions of entries) I'd like to store in an easily and quickly accessible format. I've come across a number of different potential options, but I'm not sure how to pick amongst them. My data can probably just be stored as a dictionary, or potentially a dictionary of dictionaries. Some potential considerations:</p>
<ul>
<li>Speed. I can't load all the data off disk every time I start a new script, and I'd like as quick access to random entries as possible.</li>
<li>Ease-of-use. This is python. The storage should feel like python.</li>
<li>Stability/maturity. I'd like something that's currently supported, although something that works well but is still in development would be fine. </li>
<li>Ease of installation. My sysadmin should be able to get this running on our cluster.</li>
</ul>
<p>I don't really care that much about the size of the storage, but it could be a consideration if an option is really terrible on this front. Also, if it matters, I'll most likely be creating the database once, and thereafter only reading from it.</p>
<p>Some potential options that I've started looking at (see <a href="http://stackoverflow.com/questions/195626/how-to-avoid-computation-every-time-a-python-module-is-reloaded">this</a> post):</p>
<ul>
<li><a href="http://www.pytables.org/">pyTables</a></li>
<li><a href="http://www.zope.org/">ZopeDB</a></li>
<li><a href="http://pypi.python.org/pypi/shove">shove</a></li>
<li><a href="http://docs.python.org/library/shelve.html">shelve</a></li>
<li><a href="http://streamhacker.com/2009/05/20/building-a-nltk-freqdist-on-redis/">redis</a></li>
<li><a href="http://www.mems-exchange.org/software/durus/">durus</a></li>
</ul>
<p>Any suggestions on which of these might be better for my purposes? Any better ideas? Some of these have a back-end; any suggestions on which file-system back-end would be best?</p>
| 10 | 2009-08-05T20:37:18Z | 1,237,699 | <p>I'm working on such a project and I'm using <a href="http://www.sqlite.org">SQLite</a>.</p>
<p>SQLite stores everything in one file and is part of <a href="http://docs.python.org/library/sqlite3.html">Python's standard library</a>. Hence, installation and configuration is virtually for free (ease of installation).</p>
<p>You can easily manage the database file with small Python scripts or via various tools. There is also a <a href="https://addons.mozilla.org/en-US/firefox/addon/5817">Firefox plugin</a> (ease of installation / ease-of-use).</p>
<p>I find it very convenient to use SQL to filter/sort/manipulate/... the data. Although, I'm not an SQL expert. (ease-of-use)</p>
<p>I'm not sure if SQLite is the fastes DB system for this work and it lacks some features you might need e.g. stored procedures.</p>
<p>Anyway, SQLite works for me.</p>
| 5 | 2009-08-06T08:48:28Z | [
"python",
"orm",
"persistence"
] |
Comparing persistent storage solutions in python | 1,235,594 | <p>I'm starting on a new scientific project which has a lot of data (millions of entries) I'd like to store in an easily and quickly accessible format. I've come across a number of different potential options, but I'm not sure how to pick amongst them. My data can probably just be stored as a dictionary, or potentially a dictionary of dictionaries. Some potential considerations:</p>
<ul>
<li>Speed. I can't load all the data off disk every time I start a new script, and I'd like as quick access to random entries as possible.</li>
<li>Ease-of-use. This is python. The storage should feel like python.</li>
<li>Stability/maturity. I'd like something that's currently supported, although something that works well but is still in development would be fine. </li>
<li>Ease of installation. My sysadmin should be able to get this running on our cluster.</li>
</ul>
<p>I don't really care that much about the size of the storage, but it could be a consideration if an option is really terrible on this front. Also, if it matters, I'll most likely be creating the database once, and thereafter only reading from it.</p>
<p>Some potential options that I've started looking at (see <a href="http://stackoverflow.com/questions/195626/how-to-avoid-computation-every-time-a-python-module-is-reloaded">this</a> post):</p>
<ul>
<li><a href="http://www.pytables.org/">pyTables</a></li>
<li><a href="http://www.zope.org/">ZopeDB</a></li>
<li><a href="http://pypi.python.org/pypi/shove">shove</a></li>
<li><a href="http://docs.python.org/library/shelve.html">shelve</a></li>
<li><a href="http://streamhacker.com/2009/05/20/building-a-nltk-freqdist-on-redis/">redis</a></li>
<li><a href="http://www.mems-exchange.org/software/durus/">durus</a></li>
</ul>
<p>Any suggestions on which of these might be better for my purposes? Any better ideas? Some of these have a back-end; any suggestions on which file-system back-end would be best?</p>
| 10 | 2009-08-05T20:37:18Z | 1,237,760 | <p>The NEMO collaboration (building a cosmic neutrino detector underwater) had much of the same problems, and they used mysql and postgresql without major problems.</p>
| 1 | 2009-08-06T09:03:37Z | [
"python",
"orm",
"persistence"
] |
Comparing persistent storage solutions in python | 1,235,594 | <p>I'm starting on a new scientific project which has a lot of data (millions of entries) I'd like to store in an easily and quickly accessible format. I've come across a number of different potential options, but I'm not sure how to pick amongst them. My data can probably just be stored as a dictionary, or potentially a dictionary of dictionaries. Some potential considerations:</p>
<ul>
<li>Speed. I can't load all the data off disk every time I start a new script, and I'd like as quick access to random entries as possible.</li>
<li>Ease-of-use. This is python. The storage should feel like python.</li>
<li>Stability/maturity. I'd like something that's currently supported, although something that works well but is still in development would be fine. </li>
<li>Ease of installation. My sysadmin should be able to get this running on our cluster.</li>
</ul>
<p>I don't really care that much about the size of the storage, but it could be a consideration if an option is really terrible on this front. Also, if it matters, I'll most likely be creating the database once, and thereafter only reading from it.</p>
<p>Some potential options that I've started looking at (see <a href="http://stackoverflow.com/questions/195626/how-to-avoid-computation-every-time-a-python-module-is-reloaded">this</a> post):</p>
<ul>
<li><a href="http://www.pytables.org/">pyTables</a></li>
<li><a href="http://www.zope.org/">ZopeDB</a></li>
<li><a href="http://pypi.python.org/pypi/shove">shove</a></li>
<li><a href="http://docs.python.org/library/shelve.html">shelve</a></li>
<li><a href="http://streamhacker.com/2009/05/20/building-a-nltk-freqdist-on-redis/">redis</a></li>
<li><a href="http://www.mems-exchange.org/software/durus/">durus</a></li>
</ul>
<p>Any suggestions on which of these might be better for my purposes? Any better ideas? Some of these have a back-end; any suggestions on which file-system back-end would be best?</p>
| 10 | 2009-08-05T20:37:18Z | 1,247,644 | <p>if you really just need dictionary-like storage, some of the new key/value or column stores like Cassandra or MongoDB might provide a lot more speed than you'd get with a relational database. Of course if you decide to go with RDBMS, SQLAlchemy is the way to go (disclaimer: I am its creator), but your desired featurelist seems to lean in the direction of "I just want a dictionary that feels like Python" - if you aren't interested in relational queries or strong ACIDity, those facets of RDBMS will probably feel cumbersome.</p>
| 4 | 2009-08-08T00:56:55Z | [
"python",
"orm",
"persistence"
] |
Comparing persistent storage solutions in python | 1,235,594 | <p>I'm starting on a new scientific project which has a lot of data (millions of entries) I'd like to store in an easily and quickly accessible format. I've come across a number of different potential options, but I'm not sure how to pick amongst them. My data can probably just be stored as a dictionary, or potentially a dictionary of dictionaries. Some potential considerations:</p>
<ul>
<li>Speed. I can't load all the data off disk every time I start a new script, and I'd like as quick access to random entries as possible.</li>
<li>Ease-of-use. This is python. The storage should feel like python.</li>
<li>Stability/maturity. I'd like something that's currently supported, although something that works well but is still in development would be fine. </li>
<li>Ease of installation. My sysadmin should be able to get this running on our cluster.</li>
</ul>
<p>I don't really care that much about the size of the storage, but it could be a consideration if an option is really terrible on this front. Also, if it matters, I'll most likely be creating the database once, and thereafter only reading from it.</p>
<p>Some potential options that I've started looking at (see <a href="http://stackoverflow.com/questions/195626/how-to-avoid-computation-every-time-a-python-module-is-reloaded">this</a> post):</p>
<ul>
<li><a href="http://www.pytables.org/">pyTables</a></li>
<li><a href="http://www.zope.org/">ZopeDB</a></li>
<li><a href="http://pypi.python.org/pypi/shove">shove</a></li>
<li><a href="http://docs.python.org/library/shelve.html">shelve</a></li>
<li><a href="http://streamhacker.com/2009/05/20/building-a-nltk-freqdist-on-redis/">redis</a></li>
<li><a href="http://www.mems-exchange.org/software/durus/">durus</a></li>
</ul>
<p>Any suggestions on which of these might be better for my purposes? Any better ideas? Some of these have a back-end; any suggestions on which file-system back-end would be best?</p>
| 10 | 2009-08-05T20:37:18Z | 1,249,880 | <p>It really depends on what you're trying to do. An RDBMS is designed for <em>relational data</em>, so if your data is relational, then use one of the various SQL options. But it sounds like your data is more oriented towards a key-value store with very fast random GET operations. If that's the case, compare the benchmarks of the various key-stores, focusing on the GET speed. The ideal key-value store will keep or cache requests in memory, and be able to handle many GET requests concurrently. You may actually want to create your own benchmark suite so you can effectively compare random concurrent GET operations.</p>
<p>Why do you need a cluster? Is the size of each value very large? If not, you shouldn't need a cluster to handle storage of a million entries. But if you're storing large blobs of data, that matters, and you may need something easily supports <em>read slaves</em> and/or transparent partitioning. Some of the key-value stores are <em>document oriented</em> and/or optimized for storing larger values. Redis is technically more <em>storage efficient</em> for larger values due to the indexing overhead required for fast GETs, but that doesn't necessarily mean it's slower. In fact, the extra indexing makes lookups faster.</p>
<p>You're the only one that can truly answer this question, and I strongly recommend putting together a custom benchmark suite to test available options with actual usage scenarios. The data you get from that will give you more insight than anything else.</p>
| 1 | 2009-08-08T20:57:18Z | [
"python",
"orm",
"persistence"
] |
Python: remove dictionary from list | 1,235,618 | <p>If I have a list of dictionaries, say:</p>
<pre><code>[{'id': 1, 'name': 'paul'},
{'id': 2, 'name': 'john'}]
</code></pre>
<p>and I would like to remove the dictionary with <code>id</code> of 2 (or name john), what is the most efficient way to go about this programmatically (that is to say, I don't know the index of the entry in the list so it can't simply be popped).</p>
| 19 | 2009-08-05T20:41:13Z | 1,235,628 | <p>list.pop() is a good choice:</p>
<pre><code>>>> a = [{'id': 1, 'name': 'paul'},
... {'id': 2, 'name': 'john'}]
>>> a.pop(1)
{'id': 2, 'name': 'john'}
>>> a
[{'id': 1, 'name': 'paul'}]
</code></pre>
<p>You can develop other ways of tracking done <em>which</em> dictionary you want to eliminate, so long as it resolves to an integer. Here is one of those ways:</p>
<pre><code>>>> a = [{'id': 1, 'name': 'paul'},
... {'id': 2, 'name': 'john'}]
>>> for i in reversed(range(len(a))):
... if a[i].get('id') == 2:
... a.pop(i)
...
{'id': 2, 'name': 'john'}
>>> a
[{'id': 1, 'name': 'paul'}]
</code></pre>
<p>Another possibility is to use del:</p>
<pre><code>[{'id': 1, 'name': 'paul'}]
>>> a = [{'id': 1, 'name': 'paul'},
... {'id': 2, 'name': 'john'}]
>>> a
[{'id': 1, 'name': 'paul'}, {'id': 2, 'name': 'john'}]
>>> del a[1]
>>> a
[{'id': 1, 'name': 'paul'}]
</code></pre>
| 1 | 2009-08-05T20:43:04Z | [
"python",
"list",
"dictionary"
] |
Python: remove dictionary from list | 1,235,618 | <p>If I have a list of dictionaries, say:</p>
<pre><code>[{'id': 1, 'name': 'paul'},
{'id': 2, 'name': 'john'}]
</code></pre>
<p>and I would like to remove the dictionary with <code>id</code> of 2 (or name john), what is the most efficient way to go about this programmatically (that is to say, I don't know the index of the entry in the list so it can't simply be popped).</p>
| 19 | 2009-08-05T20:41:13Z | 1,235,631 | <pre><code>thelist[:] = [d for d in thelist if d.get('id') != 2]
</code></pre>
<p><strong>Edit</strong>: as some doubts have been expressed in a comment about the performance of this code (some based on misunderstanding Python's performance characteristics, some on assuming beyond the given specs that there is exactly one dict in the list with a value of 2 for key 'id'), I wish to offer reassurance on this point.</p>
<p>On an old Linux box, measuring this code:</p>
<pre><code>$ python -mtimeit -s"lod=[{'id':i, 'name':'nam%s'%i} for i in range(99)]; import random" "thelist=list(lod); random.shuffle(thelist); thelist[:] = [d for d in thelist if d.get('id') != 2]"
10000 loops, best of 3: 82.3 usec per loop
</code></pre>
<p>of which about 57 microseconds for the random.shuffle (needed to ensure that the element to remove is not ALWAYS at the same spot;-) and 0.65 microseconds for the initial copy (whoever worries about performance impact of shallow copies of Python lists is most obviously out to lunch;-), needed to avoid altering the original list in the loop (so each leg of the loop does have something to delete;-).</p>
<p>When it is known that there is exactly one item to remove, it's possible to locate and remove it even more expeditiously:</p>
<pre><code>$ python -mtimeit -s"lod=[{'id':i, 'name':'nam%s'%i} for i in range(99)]; import random" "thelist=list(lod); random.shuffle(thelist); where=(i for i,d in enumerate(thelist) if d.get('id')==2).next(); del thelist[where]"
10000 loops, best of 3: 72.8 usec per loop
</code></pre>
<p>(use the <code>next</code> builtin rather than the <code>.next</code> method if you're on Python 2.6 or better, of course) -- but this code breaks down if the number of dicts that satisfy the removal condition is not exactly one. Generalizing this, we have:</p>
<pre><code>$ python -mtimeit -s"lod=[{'id':i, 'name':'nam%s'%i} for i in range(33)]*3; import random" "thelist=list(lod); where=[i for i,d in enumerate(thelist) if d.get('id')==2]; where.reverse()" "for i in where: del thelist[i]"
10000 loops, best of 3: 23.7 usec per loop
</code></pre>
<p>where the shuffling can be removed because there are already three equispaced dicts to remove, as we know. And the listcomp, unchanged, fares well:</p>
<pre><code>$ python -mtimeit -s"lod=[{'id':i, 'name':'nam%s'%i} for i in range(33)]*3; import random" "thelist=list(lod); thelist[:] = [d for d in thelist if d.get('id') != 2]"
10000 loops, best of 3: 23.8 usec per loop
</code></pre>
<p>totally neck and neck, with even just 3 elements of 99 to be removed. With longer lists and more repetitions, this holds even more of course:</p>
<pre><code>$ python -mtimeit -s"lod=[{'id':i, 'name':'nam%s'%i} for i in range(33)]*133; import random" "thelist=list(lod); where=[i for i,d in enumerate(thelist) if d.get('id')==2]; where.reverse()" "for i in where: del thelist[i]"
1000 loops, best of 3: 1.11 msec per loop
$ python -mtimeit -s"lod=[{'id':i, 'name':'nam%s'%i} for i in range(33)]*133; import random" "thelist=list(lod); thelist[:] = [d for d in thelist if d.get('id') != 2]"
1000 loops, best of 3: 998 usec per loop
</code></pre>
<p>All in all, it's obviously not worth deploying the subtlety of making and reversing the list of indices to remove, vs the perfectly simple and obvious list comprehension, to possibly gain 100 nanoseconds in one small case -- and lose 113 microseconds in a larger one;-). Avoiding or criticizing simple, straightforward, and perfectly performance-adequate solutions (like list comprehensions for this general class of "remove some items from a list" problems) is a particularly nasty example of Knuth's and Hoare's well-known thesis that "premature optimization is the root of all evil in programming"!-)</p>
| 40 | 2009-08-05T20:43:26Z | [
"python",
"list",
"dictionary"
] |
Python: remove dictionary from list | 1,235,618 | <p>If I have a list of dictionaries, say:</p>
<pre><code>[{'id': 1, 'name': 'paul'},
{'id': 2, 'name': 'john'}]
</code></pre>
<p>and I would like to remove the dictionary with <code>id</code> of 2 (or name john), what is the most efficient way to go about this programmatically (that is to say, I don't know the index of the entry in the list so it can't simply be popped).</p>
| 19 | 2009-08-05T20:41:13Z | 1,235,647 | <p>You can try the following: </p>
<pre><code>a = [{'id': 1, 'name': 'paul'},
{'id': 2, 'name': 'john'}]
for e in range(len(a) - 1, -1, -1):
if a[e]['id'] == 2:
a.pop(e)
</code></pre>
<p>If You can't pop from the beginning - pop from the end, it won't ruin the for loop.</p>
| 0 | 2009-08-05T20:46:13Z | [
"python",
"list",
"dictionary"
] |
Python: remove dictionary from list | 1,235,618 | <p>If I have a list of dictionaries, say:</p>
<pre><code>[{'id': 1, 'name': 'paul'},
{'id': 2, 'name': 'john'}]
</code></pre>
<p>and I would like to remove the dictionary with <code>id</code> of 2 (or name john), what is the most efficient way to go about this programmatically (that is to say, I don't know the index of the entry in the list so it can't simply be popped).</p>
| 19 | 2009-08-05T20:41:13Z | 1,235,655 | <p>Here's a way to do it with a list comprehension (assuming you name your list 'foo'):</p>
<pre><code>[x for x in foo if not (2 == x.get('id'))]
</code></pre>
<p>Substitute <code>'john' == x.get('name')</code> or whatever as appropriate.</p>
<p><code>filter</code> also works:</p>
<p><code>foo.filter(lambda x: x.get('id')!=2, foo)</code></p>
<p>And if you want a generator you can use itertools:</p>
<p><code>itertools.ifilter(lambda x: x.get('id')!=2, foo)</code></p>
<p>However, as of Python 3, <code>filter</code> will return an iterator anyway, so the list comprehension is really the best choice, as Alex suggested.</p>
| 3 | 2009-08-05T20:46:48Z | [
"python",
"list",
"dictionary"
] |
Python: remove dictionary from list | 1,235,618 | <p>If I have a list of dictionaries, say:</p>
<pre><code>[{'id': 1, 'name': 'paul'},
{'id': 2, 'name': 'john'}]
</code></pre>
<p>and I would like to remove the dictionary with <code>id</code> of 2 (or name john), what is the most efficient way to go about this programmatically (that is to say, I don't know the index of the entry in the list so it can't simply be popped).</p>
| 19 | 2009-08-05T20:41:13Z | 1,235,677 | <p>You could try something along the following lines:</p>
<pre><code>def destructively_remove_if(predicate, list):
for k in xrange(len(list)):
if predicate(list[k]):
del list[k]
break
return list
list = [
{ 'id': 1, 'name': 'John' },
{ 'id': 2, 'name': 'Karl' },
{ 'id': 3, 'name': 'Desdemona' }
]
print "Before:", list
destructively_remove_if(lambda p: p["id"] == 2, list)
print "After:", list
</code></pre>
<p>Unless you build something akin to an index over your data, I
don't think that you can do better than doing a brute-force "table
scan" over the entire list. If your data is sorted by the key you
are using, you might be able to employ the <em>bisect</em> module to
find the object you are looking for somewhat faster.</p>
| 0 | 2009-08-05T20:51:38Z | [
"python",
"list",
"dictionary"
] |
Python: remove dictionary from list | 1,235,618 | <p>If I have a list of dictionaries, say:</p>
<pre><code>[{'id': 1, 'name': 'paul'},
{'id': 2, 'name': 'john'}]
</code></pre>
<p>and I would like to remove the dictionary with <code>id</code> of 2 (or name john), what is the most efficient way to go about this programmatically (that is to say, I don't know the index of the entry in the list so it can't simply be popped).</p>
| 19 | 2009-08-05T20:41:13Z | 1,235,684 | <p>This is not properly an anwser (as I think you already have some quite good of them), but... have you considered of having a dictionary of <code><id>:<name></code> instead of a list of dictionaries?</p>
| 4 | 2009-08-05T20:52:17Z | [
"python",
"list",
"dictionary"
] |
Python: remove dictionary from list | 1,235,618 | <p>If I have a list of dictionaries, say:</p>
<pre><code>[{'id': 1, 'name': 'paul'},
{'id': 2, 'name': 'john'}]
</code></pre>
<p>and I would like to remove the dictionary with <code>id</code> of 2 (or name john), what is the most efficient way to go about this programmatically (that is to say, I don't know the index of the entry in the list so it can't simply be popped).</p>
| 19 | 2009-08-05T20:41:13Z | 1,235,710 | <pre><code># assume ls contains your list
for i in range(len(ls)):
if ls[i]['id'] == 2:
del ls[i]
break
</code></pre>
<p>Will probably be faster than the list comprehension methods on average because it doesn't traverse the whole list if it finds the item in question early on.</p>
| 0 | 2009-08-05T20:58:06Z | [
"python",
"list",
"dictionary"
] |
Execute python code inside browser without Jython | 1,235,629 | <p>Is there a way to execute python code in a browser, other than using Jython and an applet?</p>
<p>The execution does not have to deal with anything related to graphics. For example, just sum all the digits of a binary 1Gb file (chosen by the browser user) and then return the result to the server.</p>
<p>I am aware that <a href="http://pyro.sourceforge.net/">python can be executed remotely</a> outside a browser, but my requirement is to be done inside a browser.</p>
<p>For sure, I take for granted the user will keep the right to execute or not, and will be asked to do so, and all this security stuff... but that is not my question.</p>
| 17 | 2009-08-05T20:43:04Z | 1,235,671 | <p>No, you can't.</p>
<p>Modern browsers only run javascript or plugins. You can develop your own python plugin and convince people to download and run it, but I guess that falls to the "not inside the browser" category.</p>
| 3 | 2009-08-05T20:50:02Z | [
"python",
"browser",
"remote-execution"
] |
Execute python code inside browser without Jython | 1,235,629 | <p>Is there a way to execute python code in a browser, other than using Jython and an applet?</p>
<p>The execution does not have to deal with anything related to graphics. For example, just sum all the digits of a binary 1Gb file (chosen by the browser user) and then return the result to the server.</p>
<p>I am aware that <a href="http://pyro.sourceforge.net/">python can be executed remotely</a> outside a browser, but my requirement is to be done inside a browser.</p>
<p>For sure, I take for granted the user will keep the right to execute or not, and will be asked to do so, and all this security stuff... but that is not my question.</p>
| 17 | 2009-08-05T20:43:04Z | 1,235,672 | <p>You mean client-side?</p>
<p><a href="http://books.google.com/books?id=fzUCGtyg0MMC&pg=PA437&lpg=PA437&dq=python+client+side+script+internet+explorer&source=bl&ots=Y221r-y9yw&sig=GZtEidkb3N5KypJBvyaBOKOvsHE&hl=en&ei=pvB5SpSqH5-Ntgfag92WCQ&sa=X&oi=book%5Fresult&ct=result&resnum=3#v=onepage&q=python%20client%20side%20script%20internet%20explorer&f=false" rel="nofollow" title="Python programming on Win32 By Mark Hammond, Andy Robinson">Sure you can</a>! But you need to have python installed on the client first.</p>
<p>The linked book describes that in order to use client-side Active Scripting, you can test it with the a simple <code>html</code> file.</p>
<pre><code><html><body>
<script language='Python'>alert("Hello, Python!")</script>
</body></html>
</code></pre>
<p>In the old version refered in that book (Python programming on Win32
By Mark Hammond, Andy Robinson)
it says that you need to install the <a href="http://python.net/crew/mhammond/win32/Downloads.html" rel="nofollow">Python Win32 extensions</a>, and it will automatically register Python Active Scripting. Should you do it manually, you have to run the script <code>python\win32comext\axscript\client\pyscript.py</code>.</p>
| 3 | 2009-08-05T20:50:08Z | [
"python",
"browser",
"remote-execution"
] |
Execute python code inside browser without Jython | 1,235,629 | <p>Is there a way to execute python code in a browser, other than using Jython and an applet?</p>
<p>The execution does not have to deal with anything related to graphics. For example, just sum all the digits of a binary 1Gb file (chosen by the browser user) and then return the result to the server.</p>
<p>I am aware that <a href="http://pyro.sourceforge.net/">python can be executed remotely</a> outside a browser, but my requirement is to be done inside a browser.</p>
<p>For sure, I take for granted the user will keep the right to execute or not, and will be asked to do so, and all this security stuff... but that is not my question.</p>
| 17 | 2009-08-05T20:43:04Z | 1,235,689 | <p>By accident I was listening to <a href="http://www.hanselminutes.com/default.aspx?ShowID=191" rel="nofollow"> Hanselminutes </a> where he mentioned about Gestalt project. This is a solution to integrate a languages as IronRuby and IronPython in browser via Silverlight.</p>
<p>So I think the answer is no if you don't have any special plugins.</p>
| 2 | 2009-08-05T20:53:28Z | [
"python",
"browser",
"remote-execution"
] |
Execute python code inside browser without Jython | 1,235,629 | <p>Is there a way to execute python code in a browser, other than using Jython and an applet?</p>
<p>The execution does not have to deal with anything related to graphics. For example, just sum all the digits of a binary 1Gb file (chosen by the browser user) and then return the result to the server.</p>
<p>I am aware that <a href="http://pyro.sourceforge.net/">python can be executed remotely</a> outside a browser, but my requirement is to be done inside a browser.</p>
<p>For sure, I take for granted the user will keep the right to execute or not, and will be asked to do so, and all this security stuff... but that is not my question.</p>
| 17 | 2009-08-05T20:43:04Z | 1,235,778 | <p>The <a href="http://pyjs.org/">Pyjamas</a> project has a compiler called pyjs which turns Python code into Javascript.</p>
| 9 | 2009-08-05T21:10:38Z | [
"python",
"browser",
"remote-execution"
] |
Execute python code inside browser without Jython | 1,235,629 | <p>Is there a way to execute python code in a browser, other than using Jython and an applet?</p>
<p>The execution does not have to deal with anything related to graphics. For example, just sum all the digits of a binary 1Gb file (chosen by the browser user) and then return the result to the server.</p>
<p>I am aware that <a href="http://pyro.sourceforge.net/">python can be executed remotely</a> outside a browser, but my requirement is to be done inside a browser.</p>
<p>For sure, I take for granted the user will keep the right to execute or not, and will be asked to do so, and all this security stuff... but that is not my question.</p>
| 17 | 2009-08-05T20:43:04Z | 3,009,499 | <p>nosklo's answer is wrong: pyxpcomext for firefox adds language="python" support to script tags. yes it's a whopping 10mb plugin, but that's life. i think it's best if you refer to <a href="http://wiki.python.org/moin/WebBrowserProgramming">http://wiki.python.org/moin/WebBrowserProgramming</a> because that is where all known documented links between python and web browser technology are recorded: you can take your pick, there.</p>
| 6 | 2010-06-09T20:07:20Z | [
"python",
"browser",
"remote-execution"
] |
Execute python code inside browser without Jython | 1,235,629 | <p>Is there a way to execute python code in a browser, other than using Jython and an applet?</p>
<p>The execution does not have to deal with anything related to graphics. For example, just sum all the digits of a binary 1Gb file (chosen by the browser user) and then return the result to the server.</p>
<p>I am aware that <a href="http://pyro.sourceforge.net/">python can be executed remotely</a> outside a browser, but my requirement is to be done inside a browser.</p>
<p>For sure, I take for granted the user will keep the right to execute or not, and will be asked to do so, and all this security stuff... but that is not my question.</p>
| 17 | 2009-08-05T20:43:04Z | 10,701,304 | <p><a href="http://repl.it/" rel="nofollow">http://repl.it/</a> - Python interpreter in JavaScript running on client side. There are many other languages too. Source is available under MIT license, which is awesome.</p>
| 3 | 2012-05-22T11:40:13Z | [
"python",
"browser",
"remote-execution"
] |
Execute python code inside browser without Jython | 1,235,629 | <p>Is there a way to execute python code in a browser, other than using Jython and an applet?</p>
<p>The execution does not have to deal with anything related to graphics. For example, just sum all the digits of a binary 1Gb file (chosen by the browser user) and then return the result to the server.</p>
<p>I am aware that <a href="http://pyro.sourceforge.net/">python can be executed remotely</a> outside a browser, but my requirement is to be done inside a browser.</p>
<p>For sure, I take for granted the user will keep the right to execute or not, and will be asked to do so, and all this security stuff... but that is not my question.</p>
| 17 | 2009-08-05T20:43:04Z | 15,921,657 | <p>On my travels, I came across <a href="http://www.skulpt.org/" rel="nofollow">Skulpt</a>, a project which seems to offer Python directly in the browser without plugins. It's licensed under MIT.</p>
<p><a href="http://www.skulpt.org/" rel="nofollow">Skulpt Homepage</a></p>
<p><a href="https://github.com/bnmnetp/skulpt" rel="nofollow">Skulpt @ Github</a></p>
| 4 | 2013-04-10T09:14:05Z | [
"python",
"browser",
"remote-execution"
] |
Execute python code inside browser without Jython | 1,235,629 | <p>Is there a way to execute python code in a browser, other than using Jython and an applet?</p>
<p>The execution does not have to deal with anything related to graphics. For example, just sum all the digits of a binary 1Gb file (chosen by the browser user) and then return the result to the server.</p>
<p>I am aware that <a href="http://pyro.sourceforge.net/">python can be executed remotely</a> outside a browser, but my requirement is to be done inside a browser.</p>
<p>For sure, I take for granted the user will keep the right to execute or not, and will be asked to do so, and all this security stuff... but that is not my question.</p>
| 17 | 2009-08-05T20:43:04Z | 17,888,934 | <p>I put together a table comparing many Python-In-Browser technologies not long ago:
<a href="http://stromberg.dnsalias.org/~strombrg/pybrowser/python-browser.html">http://stromberg.dnsalias.org/~strombrg/pybrowser/python-browser.html</a></p>
| 5 | 2013-07-26T18:56:09Z | [
"python",
"browser",
"remote-execution"
] |
Execute python code inside browser without Jython | 1,235,629 | <p>Is there a way to execute python code in a browser, other than using Jython and an applet?</p>
<p>The execution does not have to deal with anything related to graphics. For example, just sum all the digits of a binary 1Gb file (chosen by the browser user) and then return the result to the server.</p>
<p>I am aware that <a href="http://pyro.sourceforge.net/">python can be executed remotely</a> outside a browser, but my requirement is to be done inside a browser.</p>
<p>For sure, I take for granted the user will keep the right to execute or not, and will be asked to do so, and all this security stuff... but that is not my question.</p>
| 17 | 2009-08-05T20:43:04Z | 20,455,523 | <p>Brython - "A Python 3 implementation for client-side web programming"</p>
<ul>
<li><a href="http://www.brython.info/" rel="nofollow">http://www.brython.info/</a></li>
<li><a href="https://bitbucket.org/olemis/brython/src" rel="nofollow">https://bitbucket.org/olemis/brython/src</a></li>
</ul>
| 2 | 2013-12-08T16:08:01Z | [
"python",
"browser",
"remote-execution"
] |
Execute python code inside browser without Jython | 1,235,629 | <p>Is there a way to execute python code in a browser, other than using Jython and an applet?</p>
<p>The execution does not have to deal with anything related to graphics. For example, just sum all the digits of a binary 1Gb file (chosen by the browser user) and then return the result to the server.</p>
<p>I am aware that <a href="http://pyro.sourceforge.net/">python can be executed remotely</a> outside a browser, but my requirement is to be done inside a browser.</p>
<p>For sure, I take for granted the user will keep the right to execute or not, and will be asked to do so, and all this security stuff... but that is not my question.</p>
| 17 | 2009-08-05T20:43:04Z | 39,829,630 | <p>You can now (2016) also use:</p>
<p><a href="http://www.transcrypt.org" rel="nofollow">http://www.transcrypt.org</a></p>
<p>It compiles a large subset of Python 3.5 (incl. multiple inheritance, operator overloading, all types of comprehensions, generators & iterators) to lean and fast JS, supports source level debugging with sourcemaps and optional static typechecking using mypy.</p>
<p>Disclaimer: I am the originator of the project.</p>
| 0 | 2016-10-03T10:37:17Z | [
"python",
"browser",
"remote-execution"
] |
new django app's from 1.1 causing 500 error | 1,235,777 | <p>i'm running on wsgi on centos 5... </p>
<p>i've recently updated locally from 1.0 to 1.1</p>
<p>I updated the server using svn update </p>
<p>now when I apply a new app developed locally to the server it returns with a 500 error.</p>
<p>all i'm doing is python manage.py startapp appname</p>
<p>adding the app into installed_apps in the settings file and uploading</p>
<p>this then causes a 500 error... anything that would be causing this?</p>
| 0 | 2009-08-05T21:10:37Z | 1,248,150 | <p>Check also the list at <a href="http://code.djangoproject.com/wiki/BackwardsIncompatibleChanges" rel="nofollow">http://code.djangoproject.com/wiki/BackwardsIncompatibleChanges</a>.</p>
| 1 | 2009-08-08T06:34:40Z | [
"python",
"django",
"centos"
] |
new django app's from 1.1 causing 500 error | 1,235,777 | <p>i'm running on wsgi on centos 5... </p>
<p>i've recently updated locally from 1.0 to 1.1</p>
<p>I updated the server using svn update </p>
<p>now when I apply a new app developed locally to the server it returns with a 500 error.</p>
<p>all i'm doing is python manage.py startapp appname</p>
<p>adding the app into installed_apps in the settings file and uploading</p>
<p>this then causes a 500 error... anything that would be causing this?</p>
| 0 | 2009-08-05T21:10:37Z | 1,252,372 | <p>Didn't we solve this for you in IRC the other day? If not, there was someone with the same OS and vague problem description.</p>
<p>Turned out to be a third-party app causing the problem, not the newly added one (which a review of the trackback proved if read carefully)</p>
| 1 | 2009-08-09T21:44:30Z | [
"python",
"django",
"centos"
] |
Using localflavor Django form fields on Google's App Engine | 1,235,851 | <p>Is it possible to use the form fields from </p>
<pre><code>django.contrib.localflavor.us.forms
</code></pre>
<p>on the Google App Engine? Can I simply use those form fields, or do I need a form field under </p>
<pre><code>google.appengine.ext.db.djangoforms
</code></pre>
| 1 | 2009-08-05T21:26:49Z | 5,959,177 | <p>You would need to grab the folder under <code>django.contrib.localflavour</code> and import it into your app.</p>
| 1 | 2011-05-11T04:16:00Z | [
"python",
"django",
"google-app-engine",
"django-forms"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.