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 |
|---|---|---|---|---|---|---|---|---|---|
How to get started with Sessions in Google App Engine / Django? | 1,271,892 | <p>I'm new to Python / GAE / Django. I get that with GAE there are no in-memory sessions per se... but I think I want something equivalent. I <a href="http://docs.djangoproject.com/en/dev/topics/http/sessions/" rel="nofollow">read</a> that Django sessions <a href="http://code.google.com/appengine/articles/appengine%5Fhelper%5Ffor%5Fdjango.html" rel="nofollow">can be backed</a> by BigTable or MemCache, but I never got them working. I guess what I'm asking is "Should I..."</p>
<ol>
<li>Persist with getting Django sessions working?</li>
<li>Look at some other webapp framework for sessions in particular, or the site in general?</li>
<li>Roll my own?</li>
</ol>
<p>It seems to me that sessions are not supported out-of-the-box and are somehow not first class citizens. What do you do?!</p>
<p>Thanks.</p>
| 5 | 2009-08-13T13:17:31Z | 3,899,191 | <p>I am using gaeutilities session now. However, the problem is that these created sessions are accessible only within the server-side codes. When I try to access them in django template tag, I could retrieve them out. Am I missing something?</p>
<p>Example: Client side (Django template tags)</p>
<pre><code> {% if request.session["email"]%}
<p><a href="/logout/"id="menu">Logout</a></p>
<p class="subtext">GoodBye!</p>
{% else %}
<p><a href="/login/"id="menu">Login</a></p>
<p class="subtext">Welcome!</p>
{% endif %}
</code></pre>
<p>Server side is just a simple self.session['email'] and can be access by all server side files.</p>
<p>Any ideas on how to access them on the client side apart from rendering the session value to the page? I need all client side pages to access the session value.</p>
| 1 | 2010-10-10T05:54:13Z | [
"python",
"django",
"google-app-engine"
] |
How to get started with Sessions in Google App Engine / Django? | 1,271,892 | <p>I'm new to Python / GAE / Django. I get that with GAE there are no in-memory sessions per se... but I think I want something equivalent. I <a href="http://docs.djangoproject.com/en/dev/topics/http/sessions/" rel="nofollow">read</a> that Django sessions <a href="http://code.google.com/appengine/articles/appengine%5Fhelper%5Ffor%5Fdjango.html" rel="nofollow">can be backed</a> by BigTable or MemCache, but I never got them working. I guess what I'm asking is "Should I..."</p>
<ol>
<li>Persist with getting Django sessions working?</li>
<li>Look at some other webapp framework for sessions in particular, or the site in general?</li>
<li>Roll my own?</li>
</ol>
<p>It seems to me that sessions are not supported out-of-the-box and are somehow not first class citizens. What do you do?!</p>
<p>Thanks.</p>
| 5 | 2009-08-13T13:17:31Z | 4,368,517 | <p>gaeuitlities includes a django middleware, however I haven't done django development in a while and can't 100% guarantee it's been kept up to date with django. I'm sure it won't take me long to fix if it there is an issue.</p>
<p><a href="https://github.com/joerussbowman/gaeutilities/blob/master/appengine_utilities/django-middleware/middleware.py" rel="nofollow">https://github.com/joerussbowman/gaeutilities/blob/master/appengine_utilities/django-middleware/middleware.py</a></p>
<p>If you use that middleware for you sessions, it should work as you expect including in templates. Please file any issues on github if you encounter problems.</p>
<p><a href="https://github.com/joerussbowman/gaeutilities" rel="nofollow">https://github.com/joerussbowman/gaeutilities</a></p>
| 0 | 2010-12-06T16:19:48Z | [
"python",
"django",
"google-app-engine"
] |
accessing remote url's in Google App Engine | 1,271,908 | <p>I don't know the correct terminology to do a google search.
What I want is to make a POST http request to other url, for example
twitter, from within mi app in google app engine.</p>
<p>If the question is unclear please comment.
Thanks!</p>
<p>Manuel</p>
| 0 | 2009-08-13T13:22:04Z | 1,271,933 | <p>Google provides <a href="http://code.google.com/intl/de-DE/appengine/docs/python/urlfetch/" rel="nofollow">urlfetch</a> for this.</p>
| 3 | 2009-08-13T13:26:37Z | [
"python",
"google-app-engine",
"twitter",
"httprequest"
] |
BaseException.message deprecated in Python 2.6 | 1,272,138 | <p>I get a warning that BaseException.message is deprecated in Python 2.6 when I use the following user-defined exception:</p>
<pre><code>class MyException(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return repr(self.message)
</code></pre>
<p>This is the warning:</p>
<pre><code>DeprecationWarning: BaseException.message has been deprecated as of Python 2.6
self.message = message
</code></pre>
<p>What's wrong with this? What do I have to change to get rid of the deprecation warning?</p>
| 121 | 2009-08-13T13:59:21Z | 1,272,176 | <p>Yes, it's deprecated in Python 2.6 because it's going away in Python 3.0</p>
<p>BaseException class does not provide a way to store error message anymore. You'll have to implement it yourself. You can do this with a subclass that uses a property for storing the message.</p>
<pre><code>class MyException(Exception):
def _get_message(self):
return self._message
def _set_message(self, message):
self._message = message
message = property(_get_message, _set_message)
</code></pre>
<p>Hope this helps</p>
| 26 | 2009-08-13T14:06:51Z | [
"python",
"exception",
"deprecated"
] |
BaseException.message deprecated in Python 2.6 | 1,272,138 | <p>I get a warning that BaseException.message is deprecated in Python 2.6 when I use the following user-defined exception:</p>
<pre><code>class MyException(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return repr(self.message)
</code></pre>
<p>This is the warning:</p>
<pre><code>DeprecationWarning: BaseException.message has been deprecated as of Python 2.6
self.message = message
</code></pre>
<p>What's wrong with this? What do I have to change to get rid of the deprecation warning?</p>
| 121 | 2009-08-13T13:59:21Z | 1,272,197 | <pre><code>class MyException(Exception):
def __str__(self):
return repr(self.args[0])
e = MyException('asdf')
print e
</code></pre>
<p>This is your class in Python2.6 style. The new exception takes an arbitrary number of arguments.</p>
| 8 | 2009-08-13T14:09:43Z | [
"python",
"exception",
"deprecated"
] |
BaseException.message deprecated in Python 2.6 | 1,272,138 | <p>I get a warning that BaseException.message is deprecated in Python 2.6 when I use the following user-defined exception:</p>
<pre><code>class MyException(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return repr(self.message)
</code></pre>
<p>This is the warning:</p>
<pre><code>DeprecationWarning: BaseException.message has been deprecated as of Python 2.6
self.message = message
</code></pre>
<p>What's wrong with this? What do I have to change to get rid of the deprecation warning?</p>
| 121 | 2009-08-13T13:59:21Z | 3,928,752 | <p>As far as I can tell, simply using a different name for the message attribute avoids the conflict with the base class, and thus stops the deprecation warning:</p>
<pre><code>class MyException(Exception):
def __init__(self, message):
self.msg = message
def __str__(self):
return repr(self.msg)
</code></pre>
<p>Seems like a hack to me.</p>
<p>Maybe someone can explain why the warning is issued even when the subclass defines a message attribute explicitly. If the base class no longer has this attribute, there shouldn't be a problem.</p>
| 3 | 2010-10-13T23:00:36Z | [
"python",
"exception",
"deprecated"
] |
BaseException.message deprecated in Python 2.6 | 1,272,138 | <p>I get a warning that BaseException.message is deprecated in Python 2.6 when I use the following user-defined exception:</p>
<pre><code>class MyException(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return repr(self.message)
</code></pre>
<p>This is the warning:</p>
<pre><code>DeprecationWarning: BaseException.message has been deprecated as of Python 2.6
self.message = message
</code></pre>
<p>What's wrong with this? What do I have to change to get rid of the deprecation warning?</p>
| 121 | 2009-08-13T13:59:21Z | 6,029,838 | <h2>Solution - almost no coding needed</h2>
<ol>
<li>Just inherit your exception class from <code>Exception</code></li>
<li>and pass the message as the first parameter to the constructor</li>
</ol>
<p>Example:</p>
<pre><code>class MyException(Exception):
"""My documentation"""
try:
raise MyException('my detailed description')
except MyException as my:
print my # outputs 'my detailed description'
</code></pre>
<p>You can use <code>str(my)</code> or (less elegant) <code>my.args[0]</code> to access the custom message.</p>
<h2>Background</h2>
<p>In the newer versions of Python (from 2.6) we are supposed to inherit our custom exception classes from Exception which (<a href="http://docs.python.org/library/exceptions.html#exceptions.Exception">starting from Python 2.5</a>) inherits from BaseException. The background is described in detail in <a href="http://www.python.org/dev/peps/pep-0352/">PEP352</a>.</p>
<pre><code>class BaseException(object):
"""Superclass representing the base of the exception hierarchy.
Provides an 'args' attribute that contains all arguments passed
to the constructor. Suggested practice, though, is that only a
single string argument be passed to the constructor."""
</code></pre>
<p><code>__str__</code> and <code>__repr__</code> are already implemented in a meaningful way,
especially for the case of only one arg (that can be used as message).</p>
<p>You do not need to repeat <code>__str__</code> or <code>__init__</code> implementation or create <code>_get_message</code> as suggested by others.</p>
| 107 | 2011-05-17T10:58:34Z | [
"python",
"exception",
"deprecated"
] |
BaseException.message deprecated in Python 2.6 | 1,272,138 | <p>I get a warning that BaseException.message is deprecated in Python 2.6 when I use the following user-defined exception:</p>
<pre><code>class MyException(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return repr(self.message)
</code></pre>
<p>This is the warning:</p>
<pre><code>DeprecationWarning: BaseException.message has been deprecated as of Python 2.6
self.message = message
</code></pre>
<p>What's wrong with this? What do I have to change to get rid of the deprecation warning?</p>
| 121 | 2009-08-13T13:59:21Z | 28,226,376 | <h1>How to replicate the warning</h1>
<p>Let me clarify the problem, as one cannot replicate this with the question's sample code, this will replicate the warning:</p>
<pre><code>>>> error = Exception('foobarbaz')
>>> error.message
__main__:1: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6
'foobarbaz'
</code></pre>
<h1>Eliminating the warning while still using <code>.message</code></h1>
<p>And the way you get <em>rid</em> of the <code>DeprecationWarning</code> is to subclass a builtin exception as the Python designers intended (and we'll leave out the <code>__str__</code> since the builtin <code>__repr__</code> is just fine):</p>
<pre><code>class MyException(Exception):
def __init__(self, message, *args):
self.message = message
# delegate the rest of initialization to parent
super(MyException, self).__init__(message, *args)
>>> myexception = MyException('my message')
>>> myexception.message
'my message'
>>> str(myexception)
'my message'
>>> repr(myexception)
"MyException('my message',)"
</code></pre>
<h1>Alternatively, avoid the <code>.message</code> attribute</h1>
<p>However, it is probably preferable to avoid the message attribute to begin with and just take the <code>str</code> of the error. Just subclass <code>Exception</code>:</p>
<pre><code>class MyException(Exception):
'''demo straight subclass'''
</code></pre>
<p>And usage:</p>
<pre><code>>>> myexception = MyException('my message')
>>> str(myexception)
'my message'
</code></pre>
<p>See also this answer:</p>
<p><a href="http://stackoverflow.com/questions/1319615/proper-way-to-declare-custom-exceptions-in-modern-python/26938914#26938914">Proper way to declare custom exceptions in modern Python?</a></p>
| 1 | 2015-01-29T23:06:04Z | [
"python",
"exception",
"deprecated"
] |
BaseException.message deprecated in Python 2.6 | 1,272,138 | <p>I get a warning that BaseException.message is deprecated in Python 2.6 when I use the following user-defined exception:</p>
<pre><code>class MyException(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return repr(self.message)
</code></pre>
<p>This is the warning:</p>
<pre><code>DeprecationWarning: BaseException.message has been deprecated as of Python 2.6
self.message = message
</code></pre>
<p>What's wrong with this? What do I have to change to get rid of the deprecation warning?</p>
| 121 | 2009-08-13T13:59:21Z | 29,503,053 | <p>The advice to use str(myexception) leads to unicode problems in python 2.7, e.g.:</p>
<pre><code>str(Exception(u'δÏÏÏδÏ'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128)
</code></pre>
<p>:(</p>
<pre><code>unicode(Exception(u'δÏÏÏδÏ'))
</code></pre>
<p>works as expected, and is preferred in cases where some of the content of the error string includes user input</p>
| 0 | 2015-04-07T23:14:44Z | [
"python",
"exception",
"deprecated"
] |
BaseException.message deprecated in Python 2.6 | 1,272,138 | <p>I get a warning that BaseException.message is deprecated in Python 2.6 when I use the following user-defined exception:</p>
<pre><code>class MyException(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return repr(self.message)
</code></pre>
<p>This is the warning:</p>
<pre><code>DeprecationWarning: BaseException.message has been deprecated as of Python 2.6
self.message = message
</code></pre>
<p>What's wrong with this? What do I have to change to get rid of the deprecation warning?</p>
| 121 | 2009-08-13T13:59:21Z | 30,881,390 | <p>Continuing on from <a href="http://stackoverflow.com/a/6029838/1101109">geekQ's answer</a>, the preferred option is usually:</p>
<pre><code>str(my)
</code></pre>
<p>Because sometimes exceptions have more than one argument, so <code>my.args[0]</code> is not guaranteed to provide all the relevant information.</p>
<p>For instance:</p>
<pre><code># Python 2.7
try:
u'\u12345'.encode('utf-8').encode('utf-8')
except UnicodeDecodeError as e:
print e.args[0]
print e.args
print str(e)
</code></pre>
<p>Prints as output:</p>
<pre><code>ascii
('ascii', '\xe1\x88\xb45', 0, 1, 'ordinal not in range(128)')
'ascii' codec can't decode byte 0xe1 in position 0: ordinal not in range(128)
</code></pre>
<p>However it's a context sensitive trade off, because for instance:</p>
<pre><code># Python 2.7
>>> str(SyntaxError())
'None'
# 'None' compares True which might not be expected
</code></pre>
| 0 | 2015-06-17T02:32:20Z | [
"python",
"exception",
"deprecated"
] |
BaseException.message deprecated in Python 2.6 | 1,272,138 | <p>I get a warning that BaseException.message is deprecated in Python 2.6 when I use the following user-defined exception:</p>
<pre><code>class MyException(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return repr(self.message)
</code></pre>
<p>This is the warning:</p>
<pre><code>DeprecationWarning: BaseException.message has been deprecated as of Python 2.6
self.message = message
</code></pre>
<p>What's wrong with this? What do I have to change to get rid of the deprecation warning?</p>
| 121 | 2009-08-13T13:59:21Z | 34,137,629 | <p>pzrq's post says to use:</p>
<pre><code>str(e)
</code></pre>
<p>This was exactly what I needed.</p>
<p>(If you are in a unicode environment, it appears that:</p>
<pre><code>unicode(e)
</code></pre>
<p>will work, and it appears to work fine in a non-unicode environment)</p>
<p>Pzrq said a lot of other good stuff, but I almost missed their answer due to all the good stuff. Since I don't have 50 points I cannot comment on their answer to attempt to draw attention to the simple solution that works, and since I don't have 15 I cannot vote that answer up, but I can post (feels backward, but oh well) - so here I am posting - probably lose points for that...</p>
<p>Since my point is to draw attention to pzrq's answer, please don't glaze over and miss it in all the below. the first few lines of this post are the most important.</p>
<p>My story:</p>
<p>The problem I came here for was if you want to catch an exception from a class that you have no control over - what then??? I'm certainly not going to subclass all possible classes my code uses in an attempt to be able to get a message out of all possible exceptions!</p>
<p>I was using:</p>
<pre><code>except Exception as e:
print '%s (%s)' % (e.message,type(e))
</code></pre>
<p>which, as we all now know, gives the warning OP asked about (which brought me here), and this, which pzrq gives as a way to do it:</p>
<pre><code>except Exception as e:
print '%s (%s)' % (str(e),type(e))
</code></pre>
<p>did not. </p>
<p>I'm not in a unicode environment, but jjc's answer made me wonder, so I had to try it. In this context this becomes:</p>
<pre><code>except Exception as e:
print '%s (%s)' % (unicode(e),type(e))
</code></pre>
<p>which, to my surprise, worked exactly like str(e) - so now that's what I'm using.</p>
<p>Don't know if 'str(e)/unicode(e)' is the 'approved Python way', and I'll probably find out why that's not good when I get to 3.0, but one hopes that the ability to handle an unexpected exception (*) without dying and still get some information from it won't ever go away...</p>
<p>(*) Hmm. "unexpected exception" - I think I just stuttered!</p>
| 0 | 2015-12-07T15:47:57Z | [
"python",
"exception",
"deprecated"
] |
Is it possible to add a network drive to %PATH% environment variable | 1,272,242 | <p>I have a python script calling an exe file. The exe file can be in the same folder as that of the python script or in a network drive. Is it possible to call the exe if it is in a remote drive/computer? Can this be done by setting the %PATH% variable</p>
| 0 | 2009-08-13T14:17:01Z | 1,272,313 | <p>Yes you can put a UNC path in your <code>%PATH%</code> env variable, and it will work if you have access to that path with your current session. </p>
| 1 | 2009-08-13T14:28:15Z | [
"python",
"windows",
"sysinternals"
] |
Is it possible to add a network drive to %PATH% environment variable | 1,272,242 | <p>I have a python script calling an exe file. The exe file can be in the same folder as that of the python script or in a network drive. Is it possible to call the exe if it is in a remote drive/computer? Can this be done by setting the %PATH% variable</p>
| 0 | 2009-08-13T14:17:01Z | 16,741,926 | <p>Although use of a UNC will often work in the %PATH% variable this is unsupported by Microsoft as it can cause problems such as service failures. This issue continues through Windows 7 / Server 2008R2.</p>
<p>Please reference <a href="http://support.microsoft.com/kb/978856" rel="nofollow">Microsoft KB Article ID: 978856</a></p>
<p>*cheers</p>
| 2 | 2013-05-24T19:02:04Z | [
"python",
"windows",
"sysinternals"
] |
Batch output redirection when using start command for GUI app | 1,272,309 | <p>This is the scenario:</p>
<p>We have a Python script that starts a Windows batch file and redirects its output to a file. Afterwards it reads the file and then tries to delete it:</p>
<pre><code>os.system(C:\batch.bat >C:\temp.txt 2>&1)
os.remove(C:\temp.txt)
</code></pre>
<p>In the batch.bat we start a Windows GUI programm like this:</p>
<pre><code>start c:\the_programm.exe
</code></pre>
<p>Thats all in the batch fÃle.</p>
<p>Now the os.remove() fails with "Permission denied" because the temp.txt is still locked by the system. It seems this is caused by the still runing the_programm.exe (whos output also seems to be redirected to the temp.txt). </p>
<p>Any idea how to start the_programm.exe without having the temp.txt locked while it is still running? The Python part is hardly changeable as this is a tool (<a href="http://busyb.sourceforge.net/" rel="nofollow">BusyB</a>).</p>
<p>In fact I do not need the output of the_programm.exe, so the essence of the question is: <strong>How do I decouple the_programm.exe from locking temp.txt for its output?</strong>
Or: <strong>How do I use START or another Windows command to start a program without inheriting the batch output redirection?</strong></p>
| 0 | 2009-08-13T14:27:10Z | 1,272,393 | <p>I don't think Windows will let you delete an open file. Sounds like you're wanting to throw away the program's output; would redirecting to 'nul' instead do what you need?</p>
| 0 | 2009-08-13T14:41:45Z | [
"python",
"windows",
"batch-file",
"output-redirect"
] |
Batch output redirection when using start command for GUI app | 1,272,309 | <p>This is the scenario:</p>
<p>We have a Python script that starts a Windows batch file and redirects its output to a file. Afterwards it reads the file and then tries to delete it:</p>
<pre><code>os.system(C:\batch.bat >C:\temp.txt 2>&1)
os.remove(C:\temp.txt)
</code></pre>
<p>In the batch.bat we start a Windows GUI programm like this:</p>
<pre><code>start c:\the_programm.exe
</code></pre>
<p>Thats all in the batch fÃle.</p>
<p>Now the os.remove() fails with "Permission denied" because the temp.txt is still locked by the system. It seems this is caused by the still runing the_programm.exe (whos output also seems to be redirected to the temp.txt). </p>
<p>Any idea how to start the_programm.exe without having the temp.txt locked while it is still running? The Python part is hardly changeable as this is a tool (<a href="http://busyb.sourceforge.net/" rel="nofollow">BusyB</a>).</p>
<p>In fact I do not need the output of the_programm.exe, so the essence of the question is: <strong>How do I decouple the_programm.exe from locking temp.txt for its output?</strong>
Or: <strong>How do I use START or another Windows command to start a program without inheriting the batch output redirection?</strong></p>
| 0 | 2009-08-13T14:27:10Z | 1,272,480 | <p>As I understand it, this is the issue, and what he wants to do:</p>
<ol>
<li>Make <em>no</em> changes to the python code.</li>
<li><p>The Python code is written assuming that "temp.txt" is no longer being used when this function returns:</p>
<p>os.system(C:\batch.bat >C:\temp.txt 2>&1)</p></li>
<li><p>This is in fact not the case because "batch.bat" spawns an interactive GUI program using the "start" command.</p></li>
</ol>
<p>How about changing your "batch.bat" file to contain:</p>
<pre><code>start c:\the_programm.exe
pause
</code></pre>
<p>This will keep the "batch.bat" file running until you hit a key on that window. Once you hit a key, the "os.system" python command will return, and then python will call "os.remove".</p>
| 0 | 2009-08-13T14:53:37Z | [
"python",
"windows",
"batch-file",
"output-redirect"
] |
Batch output redirection when using start command for GUI app | 1,272,309 | <p>This is the scenario:</p>
<p>We have a Python script that starts a Windows batch file and redirects its output to a file. Afterwards it reads the file and then tries to delete it:</p>
<pre><code>os.system(C:\batch.bat >C:\temp.txt 2>&1)
os.remove(C:\temp.txt)
</code></pre>
<p>In the batch.bat we start a Windows GUI programm like this:</p>
<pre><code>start c:\the_programm.exe
</code></pre>
<p>Thats all in the batch fÃle.</p>
<p>Now the os.remove() fails with "Permission denied" because the temp.txt is still locked by the system. It seems this is caused by the still runing the_programm.exe (whos output also seems to be redirected to the temp.txt). </p>
<p>Any idea how to start the_programm.exe without having the temp.txt locked while it is still running? The Python part is hardly changeable as this is a tool (<a href="http://busyb.sourceforge.net/" rel="nofollow">BusyB</a>).</p>
<p>In fact I do not need the output of the_programm.exe, so the essence of the question is: <strong>How do I decouple the_programm.exe from locking temp.txt for its output?</strong>
Or: <strong>How do I use START or another Windows command to start a program without inheriting the batch output redirection?</strong></p>
| 0 | 2009-08-13T14:27:10Z | 1,272,848 | <p>Are you closing the file after you're done reading it? The following works at my end:</p>
<pre><code>import os
os.system('runbat.bat > runbat.log 2>&1')
f = open('runbat.log')
print f.read()
f.close()
os.remove('runbat.log')
</code></pre>
<p>but fails if I remove the <code>f.close()</code> line.</p>
| 0 | 2009-08-13T15:50:55Z | [
"python",
"windows",
"batch-file",
"output-redirect"
] |
Batch output redirection when using start command for GUI app | 1,272,309 | <p>This is the scenario:</p>
<p>We have a Python script that starts a Windows batch file and redirects its output to a file. Afterwards it reads the file and then tries to delete it:</p>
<pre><code>os.system(C:\batch.bat >C:\temp.txt 2>&1)
os.remove(C:\temp.txt)
</code></pre>
<p>In the batch.bat we start a Windows GUI programm like this:</p>
<pre><code>start c:\the_programm.exe
</code></pre>
<p>Thats all in the batch fÃle.</p>
<p>Now the os.remove() fails with "Permission denied" because the temp.txt is still locked by the system. It seems this is caused by the still runing the_programm.exe (whos output also seems to be redirected to the temp.txt). </p>
<p>Any idea how to start the_programm.exe without having the temp.txt locked while it is still running? The Python part is hardly changeable as this is a tool (<a href="http://busyb.sourceforge.net/" rel="nofollow">BusyB</a>).</p>
<p>In fact I do not need the output of the_programm.exe, so the essence of the question is: <strong>How do I decouple the_programm.exe from locking temp.txt for its output?</strong>
Or: <strong>How do I use START or another Windows command to start a program without inheriting the batch output redirection?</strong></p>
| 0 | 2009-08-13T14:27:10Z | 1,273,144 | <p>Why capture to a file if you're just deleting it immediately?</p>
<p>How about this:</p>
<pre><code>os.system(C:\batch.bat >nul 2>&1)
</code></pre>
<p>EDIT: Oops, I missed your comment about reading the file, I only noticed the code.</p>
| 0 | 2009-08-13T16:36:43Z | [
"python",
"windows",
"batch-file",
"output-redirect"
] |
Batch output redirection when using start command for GUI app | 1,272,309 | <p>This is the scenario:</p>
<p>We have a Python script that starts a Windows batch file and redirects its output to a file. Afterwards it reads the file and then tries to delete it:</p>
<pre><code>os.system(C:\batch.bat >C:\temp.txt 2>&1)
os.remove(C:\temp.txt)
</code></pre>
<p>In the batch.bat we start a Windows GUI programm like this:</p>
<pre><code>start c:\the_programm.exe
</code></pre>
<p>Thats all in the batch fÃle.</p>
<p>Now the os.remove() fails with "Permission denied" because the temp.txt is still locked by the system. It seems this is caused by the still runing the_programm.exe (whos output also seems to be redirected to the temp.txt). </p>
<p>Any idea how to start the_programm.exe without having the temp.txt locked while it is still running? The Python part is hardly changeable as this is a tool (<a href="http://busyb.sourceforge.net/" rel="nofollow">BusyB</a>).</p>
<p>In fact I do not need the output of the_programm.exe, so the essence of the question is: <strong>How do I decouple the_programm.exe from locking temp.txt for its output?</strong>
Or: <strong>How do I use START or another Windows command to start a program without inheriting the batch output redirection?</strong></p>
| 0 | 2009-08-13T14:27:10Z | 1,273,817 | <p>This is a bit hacky, but you could try it. It uses the <code>AT</code> command to run <code>the_programm.exe</code> up to a minute in the future (which it computes using the <code>%TIME%</code> environment variable and <code>SET</code> arithmetic).</p>
<p>batch.bat:</p>
<pre><code>@echo off
setlocal
:: store the current time so it does not change while parsing
set t=%time%
:: parse hour, minute, second
set h=%t:~0,2%
set m=%t:~3,2%
set s=%t:~6,2%
:: reduce strings to simple integers
if "%h:~0,1%"==" " set h=%h:~1%
if "%m:~0,1%"=="0" set m=%m:~1%
if "%s:~0,1%"=="0" set s=%s:~1%
:: choose number of seconds in the future; granularity for AT is one
:: minute, plus we need a few extra seconds for this script to run
set x=70
:: calculate hour and minute to run the program
set /a x=s + x
set /a s="x %% 60"
set /a x=m + x / 60
set /a m="x %% 60"
set /a h=h + x / 60
set /a h="h %% 24"
:: schedule the program to run
at %h%:%m% c:\the_programm.exe
</code></pre>
<p>You can look at the <code>AT /?</code> and <code>SET /?</code> to see what each of these is doing. I left off the <code>/interactive</code> parameter of <code>AT</code> since you commented that "no user interaction is allowed".</p>
<p>Caveats:</p>
<ul>
<li>It appears that <code>%TIME%</code> is always 24-hour time, regardless of locale settings in the control panel, but I don't have any proof of this.</li>
<li>If your system is loaded down and batch.bat takes more than 10 seconds to run, the <code>AT</code> command will be scheduled to run 1 day later. You can recover this manually, using <code>AT {job} /delete</code>, and increase the <code>x=70</code> to something more acceptable.</li>
</ul>
<p>The <code>START</code> command, unfortunately, even when given <code>/i</code> to ignore the current environment, seems to pass along the open file descriptors of the parent <code>cmd.exe</code> process. These file descriptors appear to be handed off to subprocesses, even if the subprocesses are redirected to NUL, and are kept open even if intermediate shell processes terminate. You can see this in <a href="http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx" rel="nofollow">Process Explorer</a> if you have a batch file which <code>START</code>s another batch file which <code>START</code>s another batch file (etc.) which <code>START</code>s a GUI Windows app. Once the intermediate batch files have terminated, the GUI app will own the file handles, even if it (and the intermediate batch files) were all redirected to <code>NUL</code>.</p>
| 2 | 2009-08-13T18:39:18Z | [
"python",
"windows",
"batch-file",
"output-redirect"
] |
Batch output redirection when using start command for GUI app | 1,272,309 | <p>This is the scenario:</p>
<p>We have a Python script that starts a Windows batch file and redirects its output to a file. Afterwards it reads the file and then tries to delete it:</p>
<pre><code>os.system(C:\batch.bat >C:\temp.txt 2>&1)
os.remove(C:\temp.txt)
</code></pre>
<p>In the batch.bat we start a Windows GUI programm like this:</p>
<pre><code>start c:\the_programm.exe
</code></pre>
<p>Thats all in the batch fÃle.</p>
<p>Now the os.remove() fails with "Permission denied" because the temp.txt is still locked by the system. It seems this is caused by the still runing the_programm.exe (whos output also seems to be redirected to the temp.txt). </p>
<p>Any idea how to start the_programm.exe without having the temp.txt locked while it is still running? The Python part is hardly changeable as this is a tool (<a href="http://busyb.sourceforge.net/" rel="nofollow">BusyB</a>).</p>
<p>In fact I do not need the output of the_programm.exe, so the essence of the question is: <strong>How do I decouple the_programm.exe from locking temp.txt for its output?</strong>
Or: <strong>How do I use START or another Windows command to start a program without inheriting the batch output redirection?</strong></p>
| 0 | 2009-08-13T14:27:10Z | 1,276,896 | <p>Finally I could find a proper solution:</p>
<p>I am not using a batch file anymore for starting the_programm.exe, but a Python script:</p>
<pre><code>from subprocess import Popen
if __name__ == '__main__':
Popen('C:/the_programm.exe', close_fds=True)
</code></pre>
<p>The close_fds parameter decouples the file handles from the .exe process! That's it!</p>
| 0 | 2009-08-14T09:23:00Z | [
"python",
"windows",
"batch-file",
"output-redirect"
] |
parsing CSV files backwards | 1,272,315 | <p>I have csv files with the following format:</p>
<pre><code>CSV FILE
"a" , "b" , "c" , "d"
hello, world , 1 , 2 , 3
1,2,3,4,5,6,7 , 2 , 456 , 87
h,1231232,3 , 3 , 45 , 44
</code></pre>
<p>The problem is that the first field has commas "," in it. I have no control over file generation, as that's the format I receive them in. Is there a way to read a CSV file backwards, from the end of line to the beginning? </p>
<p>I don't mind writing a little python script to do so, if Iâm guided in the right direction.</p>
| 2 | 2009-08-13T14:28:26Z | 1,272,327 | <p>You could always do something with regex's, like (perl regex)</p>
<pre><code>#!/usr/bin/perl
use IO::File;
if (my $file = new IO::File("test.csv"))
{
foreach my $line (<$file>) {
$line =~ m/^(.*),(.*?),(.*?),(.*?)$/;
print "[$1][$2][$3][$4]\n";
}
} else {
print "Unable to open test.csv\n";
}
</code></pre>
<p>(The first is a greedy search, the last 3 are not)
<strong>Edit</strong>: posted full code instead of just the regex</p>
| 1 | 2009-08-13T14:30:56Z | [
"python",
"parsing",
"csv",
"readline"
] |
parsing CSV files backwards | 1,272,315 | <p>I have csv files with the following format:</p>
<pre><code>CSV FILE
"a" , "b" , "c" , "d"
hello, world , 1 , 2 , 3
1,2,3,4,5,6,7 , 2 , 456 , 87
h,1231232,3 , 3 , 45 , 44
</code></pre>
<p>The problem is that the first field has commas "," in it. I have no control over file generation, as that's the format I receive them in. Is there a way to read a CSV file backwards, from the end of line to the beginning? </p>
<p>I don't mind writing a little python script to do so, if Iâm guided in the right direction.</p>
| 2 | 2009-08-13T14:28:26Z | 1,272,329 | <p>Reverse the string first and then process it. </p>
<p>tmp = tmp[::-1]</p>
| 1 | 2009-08-13T14:31:05Z | [
"python",
"parsing",
"csv",
"readline"
] |
parsing CSV files backwards | 1,272,315 | <p>I have csv files with the following format:</p>
<pre><code>CSV FILE
"a" , "b" , "c" , "d"
hello, world , 1 , 2 , 3
1,2,3,4,5,6,7 , 2 , 456 , 87
h,1231232,3 , 3 , 45 , 44
</code></pre>
<p>The problem is that the first field has commas "," in it. I have no control over file generation, as that's the format I receive them in. Is there a way to read a CSV file backwards, from the end of line to the beginning? </p>
<p>I don't mind writing a little python script to do so, if Iâm guided in the right direction.</p>
| 2 | 2009-08-13T14:28:26Z | 1,272,338 | <p>The <code>rsplit</code> string method splits a string starting from the right instead of the left, and so it's probably what you're looking for (it takes an argument specifying the max number of times to split):</p>
<pre><code>line = "hello, world , 1 , 2 , 3"
parts = line.rsplit(",", 3)
print parts # prints ['hello, world ', ' 1 ', ' 2 ', ' 3']
</code></pre>
<p>If you want to strip the whitespace from the beginning and end of each item in your splitted list, then you can just use the <code>strip</code> method with a list comprehension</p>
<pre><code>parts = [s.strip() for s in parts]
print parts # prints ['hello, world', '1', '2', '3']
</code></pre>
| 14 | 2009-08-13T14:32:41Z | [
"python",
"parsing",
"csv",
"readline"
] |
parsing CSV files backwards | 1,272,315 | <p>I have csv files with the following format:</p>
<pre><code>CSV FILE
"a" , "b" , "c" , "d"
hello, world , 1 , 2 , 3
1,2,3,4,5,6,7 , 2 , 456 , 87
h,1231232,3 , 3 , 45 , 44
</code></pre>
<p>The problem is that the first field has commas "," in it. I have no control over file generation, as that's the format I receive them in. Is there a way to read a CSV file backwards, from the end of line to the beginning? </p>
<p>I don't mind writing a little python script to do so, if Iâm guided in the right direction.</p>
| 2 | 2009-08-13T14:28:26Z | 1,272,344 | <p>From the sample You have provided, it looks like "columns" are fixed size. First (the one with commas) is 16 characters long, so why don't You try reading the file line by line, then for each line reading the first 16 characters (as a value of first column), and the rest accordingly? After You have each value, You can go and parse it further (trim whitespaces, and so on...).</p>
| 1 | 2009-08-13T14:33:15Z | [
"python",
"parsing",
"csv",
"readline"
] |
parsing CSV files backwards | 1,272,315 | <p>I have csv files with the following format:</p>
<pre><code>CSV FILE
"a" , "b" , "c" , "d"
hello, world , 1 , 2 , 3
1,2,3,4,5,6,7 , 2 , 456 , 87
h,1231232,3 , 3 , 45 , 44
</code></pre>
<p>The problem is that the first field has commas "," in it. I have no control over file generation, as that's the format I receive them in. Is there a way to read a CSV file backwards, from the end of line to the beginning? </p>
<p>I don't mind writing a little python script to do so, if Iâm guided in the right direction.</p>
| 2 | 2009-08-13T14:28:26Z | 1,272,356 | <p>That's not then a CSV file, comma separated means just that.</p>
<p>How can you be certain that is not:</p>
<pre><code>CSV FILE
"a" , "b" , "c" , "d"
hello , world , 1 , 2 , 3
1 , 2 , 3 , 4 , 5,6,7,2,456,87
h , 1231232 , 3 , 3 , 45,44
</code></pre>
<p>If the file is as you indicate then the first group should be surrounded by quotes, looks as though the field names are so odd that fields containing commas are not.</p>
<p>I'm not a fan of fixing errors away from their source, I'd push back to the data generator to deliver proper CSV if that's what they are claiming it is.</p>
| 1 | 2009-08-13T14:35:21Z | [
"python",
"parsing",
"csv",
"readline"
] |
parsing CSV files backwards | 1,272,315 | <p>I have csv files with the following format:</p>
<pre><code>CSV FILE
"a" , "b" , "c" , "d"
hello, world , 1 , 2 , 3
1,2,3,4,5,6,7 , 2 , 456 , 87
h,1231232,3 , 3 , 45 , 44
</code></pre>
<p>The problem is that the first field has commas "," in it. I have no control over file generation, as that's the format I receive them in. Is there a way to read a CSV file backwards, from the end of line to the beginning? </p>
<p>I don't mind writing a little python script to do so, if Iâm guided in the right direction.</p>
| 2 | 2009-08-13T14:28:26Z | 1,272,359 | <p>If you always expect the same number of columns, and only the first column can contain commas, just read anything and concatenate excess columns at the beginning.</p>
<p>The problem is that the interface is ambiguous, and you can try to circumvent this, but the better solution is to try to get the interface fixed (which is often harder than creating several patches...).</p>
| 0 | 2009-08-13T14:36:01Z | [
"python",
"parsing",
"csv",
"readline"
] |
parsing CSV files backwards | 1,272,315 | <p>I have csv files with the following format:</p>
<pre><code>CSV FILE
"a" , "b" , "c" , "d"
hello, world , 1 , 2 , 3
1,2,3,4,5,6,7 , 2 , 456 , 87
h,1231232,3 , 3 , 45 , 44
</code></pre>
<p>The problem is that the first field has commas "," in it. I have no control over file generation, as that's the format I receive them in. Is there a way to read a CSV file backwards, from the end of line to the beginning? </p>
<p>I don't mind writing a little python script to do so, if Iâm guided in the right direction.</p>
| 2 | 2009-08-13T14:28:26Z | 1,272,361 | <p>I agree with mr beer. That is a badly formed csv file. Your best bet is to find other delimiters or stop overloading the commas or quote/escape the non field separating commas</p>
| 0 | 2009-08-13T14:36:03Z | [
"python",
"parsing",
"csv",
"readline"
] |
parsing CSV files backwards | 1,272,315 | <p>I have csv files with the following format:</p>
<pre><code>CSV FILE
"a" , "b" , "c" , "d"
hello, world , 1 , 2 , 3
1,2,3,4,5,6,7 , 2 , 456 , 87
h,1231232,3 , 3 , 45 , 44
</code></pre>
<p>The problem is that the first field has commas "," in it. I have no control over file generation, as that's the format I receive them in. Is there a way to read a CSV file backwards, from the end of line to the beginning? </p>
<p>I don't mind writing a little python script to do so, if Iâm guided in the right direction.</p>
| 2 | 2009-08-13T14:28:26Z | 1,272,364 | <p>I don't fully understand why you want to read each line in reverse, but you could do this:</p>
<pre><code>import csv
file = open("mycsvfile.csv")
reversedLines = [line[::-1] for line in file]
file.close()
reader = csv.reader(reversedLines)
for backwardRow in reader:
lastField = backwardRow[0][::-1]
secondField = backwardRow[1][::-1]
</code></pre>
| 3 | 2009-08-13T14:36:26Z | [
"python",
"parsing",
"csv",
"readline"
] |
Alternatives to mod_python's CGI handler | 1,272,325 | <p>I'm looking for the simplest way of using python and SQLAlchemy to produce some XML for a jQuery based HTTP client. Right now I'm using mod_python's CGI handler but I'm unhappy with the fact that I can't persist stuff like the SQLAlchemy session.</p>
<p>The mod_python publisher handler that is apparently capable of persisting stuff does not allow requests with XML content type (as used by jQuery's ajax stuff) so I can't use it.</p>
<p>What other options are there?</p>
| 2 | 2009-08-13T14:29:51Z | 1,272,579 | <p>You could always write your own handler, which is the way mod_python is normally intended to be used. You would have to set some HTTP headers (and you could have a look at the publisher handler's source code for inspiration on that), but otherwise I don't think it's much more complicated than what you've been trying to do.</p>
<p>Though as long as you're at it, I would suggest trying mod_wsgi instead of mod_python, which is probably eventually going to supersede mod_python. WSGI is a Python standard for writing web applications.</p>
| 2 | 2009-08-13T15:08:43Z | [
"python",
"cgi",
"mod-python"
] |
Python looping to read and parse all in a directory | 1,272,405 | <pre><code>class __init__:
path = "articles/"
files = os.listdir(path)
files.reverse()
def iterate(Files, Path):
def handleXml(content):
months = ['', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
parse = re.compile('<(.*?)>(.*?)<(.*?)>').findall(content)
day = parse[1][1]
month = months[int(parse[2][1])]
dayN = parse[3][1]
year = parse[4][1]
hour = parse[5][1]
min = parse[6][1]
amPM = parse[7][1]
title = parse[9][1]
author = parse[10][1]
article = parse[11][1]
category = parse[12][1]
if len(Files) > 5:
del Files[5:]
for file in Files:
file = "%s%s" % (Path, file)
f = open(file, 'r')
handleXml(f.read())
f.close()
iterate(files, path)
</code></pre>
<p>It runs on start, and if I check the files array it contains all the file names.
But when I loop through them they just do not work, only displays the first one.
If I return file I only get the first two, and if I return parse even on duplicate files it is not identical.
None of this makes any sense.</p>
<p>I am trying to make a simple blog using Python, and because my server has a very old version of Python I cannot use modules like glob, everything needs to be as basic as possible.</p>
<p>The files array contains all the files in the directory, which is good enough for me. I do not need to go through other directories inside the articles directory.</p>
<p>But when I try to output parse, even on duplicate files I get different results.</p>
<p>Thanks,</p>
<ul>
<li>Tom</li>
</ul>
| 1 | 2009-08-13T14:43:53Z | 1,272,505 | <p>Could it be because of:</p>
<pre><code>del Files[5:]
</code></pre>
<p>It deletes the last 5 entries from the original list as well. Instead of using <code>del</code>, you can try:</p>
<pre><code>for file in Files[:5]:
#...
</code></pre>
| 1 | 2009-08-13T14:56:29Z | [
"python",
"xml",
"file-io",
"blogs"
] |
Python looping to read and parse all in a directory | 1,272,405 | <pre><code>class __init__:
path = "articles/"
files = os.listdir(path)
files.reverse()
def iterate(Files, Path):
def handleXml(content):
months = ['', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
parse = re.compile('<(.*?)>(.*?)<(.*?)>').findall(content)
day = parse[1][1]
month = months[int(parse[2][1])]
dayN = parse[3][1]
year = parse[4][1]
hour = parse[5][1]
min = parse[6][1]
amPM = parse[7][1]
title = parse[9][1]
author = parse[10][1]
article = parse[11][1]
category = parse[12][1]
if len(Files) > 5:
del Files[5:]
for file in Files:
file = "%s%s" % (Path, file)
f = open(file, 'r')
handleXml(f.read())
f.close()
iterate(files, path)
</code></pre>
<p>It runs on start, and if I check the files array it contains all the file names.
But when I loop through them they just do not work, only displays the first one.
If I return file I only get the first two, and if I return parse even on duplicate files it is not identical.
None of this makes any sense.</p>
<p>I am trying to make a simple blog using Python, and because my server has a very old version of Python I cannot use modules like glob, everything needs to be as basic as possible.</p>
<p>The files array contains all the files in the directory, which is good enough for me. I do not need to go through other directories inside the articles directory.</p>
<p>But when I try to output parse, even on duplicate files I get different results.</p>
<p>Thanks,</p>
<ul>
<li>Tom</li>
</ul>
| 1 | 2009-08-13T14:43:53Z | 1,274,818 | <p>As stated in the comments, the actual recursion is missing.<br />
Even if it is there in some other place of the code, the recursion call is the typical place where the things are wrong, and for this reason I would suggest you to double check it.</p>
<p>However, why don't you use <a href="http://docs.python.org/library/os.html#os.walk" rel="nofollow">os.walk</a>? It iterates through all the path, without the need of reinventing the (recursive) wheel. It has been introduced in 2.3, though, and I do not know how old your python is.</p>
| 0 | 2009-08-13T21:51:55Z | [
"python",
"xml",
"file-io",
"blogs"
] |
Using Python (Bash?) to get OS-level system information (CPU Speed) | 1,272,903 | <p>I want to repeat <a href="http://stackoverflow.com/questions/25552/using-java-to-get-os-level-system-information">this question</a> using python. Reason is I have access to 10 nodes in a cluster and each node is not identical. They range in performance and I want to find which is the best computer to use remotely based on memory and cpu-speed/cores available.</p>
<p>EDIT: Heck, even just a command line interface would be useful. Any quick and dirty solutions?</p>
| 1 | 2009-08-13T15:59:16Z | 1,272,945 | <p>Take a look at the <a href="http://support.hyperic.com/display/SIGAR/Home" rel="nofollow">SIGAR</a> library which has an extensive API for collecting system data cross-platform. It also has libraries available in many languages (Python, Java, Erlang, Ruby, etc).</p>
| 1 | 2009-08-13T16:06:09Z | [
"python",
"performance",
"cpu-speed"
] |
How can I implement matlabs ``ismember()`` command in Python? | 1,273,041 | <p>here is my problem: I would like to create a boolean matrix B that contains <code>True</code> everywhere that matrix A has a value contained in vector v. One inconvenient solution would be:</p>
<pre><code>import numpy as np
>>> A = np.array([[0,1,2], [1,2,3], [2,3,4]])
array([[0, 1, 2],
[1, 2, 3],
[2, 3, 4]])
>>> v = [1,2]
>>> B = (A==v[0]) + (A==v[1]) # matlab: ``B = ismember(A,v)``
array([[False, True, True],
[ True, True, False],
[ True, False, False]], dtype=bool)
</code></pre>
<p>Is there maybe a solution that would be more convenient if A and v would have more values?</p>
<p>Cheers!</p>
| 3 | 2009-08-13T16:19:09Z | 1,273,138 | <p>Here's a naive one-liner:</p>
<pre><code>[any (value in item for value in v) for item in A]
</code></pre>
<p>Sample output:</p>
<pre><code>>>> A = ( [0,1,2], [1,2,3], [2,3,4] )
>>> v = [1,2]
>>> [any (value in item for value in v) for item in A]
[True, True, True]
>>> v = [1]
>>> [any (value in item for value in v) for item in A]
[True, True, False]
</code></pre>
<p>It's a very Pythonic approach, but I'm certain it won't scale well on large arrays or vectors because Python's <code>in</code> operator is a linear search (on lists/tuples, at least).</p>
<p>As Brooks Moses pointed out in the below comment, the output should be a 3x3 matrix. That's why you give sample output in your questions. (Thanks Brooks)</p>
<pre><code>>>> v=[1,2]
>>> [ [item in v for item in row] for row in A]
[[False, True, True], [True, True, False], [True, False, False]]
>>> v=[1]
>>> [ [item in v for item in row] for row in A]
[[False, True, False], [True, False, False], [False, False, False]]
</code></pre>
| 1 | 2009-08-13T16:35:48Z | [
"python",
"arrays",
"matrix"
] |
How can I implement matlabs ``ismember()`` command in Python? | 1,273,041 | <p>here is my problem: I would like to create a boolean matrix B that contains <code>True</code> everywhere that matrix A has a value contained in vector v. One inconvenient solution would be:</p>
<pre><code>import numpy as np
>>> A = np.array([[0,1,2], [1,2,3], [2,3,4]])
array([[0, 1, 2],
[1, 2, 3],
[2, 3, 4]])
>>> v = [1,2]
>>> B = (A==v[0]) + (A==v[1]) # matlab: ``B = ismember(A,v)``
array([[False, True, True],
[ True, True, False],
[ True, False, False]], dtype=bool)
</code></pre>
<p>Is there maybe a solution that would be more convenient if A and v would have more values?</p>
<p>Cheers!</p>
| 3 | 2009-08-13T16:19:09Z | 1,273,151 | <p>I don't know much numpy, be here's a raw python one:</p>
<pre><code>>>> A = [[0,1,2], [1,2,3], [2,3,4]]
>>> v = [1,2]
>>> B = [map(lambda val: val in v, a) for a in A]
>>>
>>> B
[[False, True, True], [True, True, False], [True, False, False]]
</code></pre>
<p><strong>Edit</strong>: As Brooks Moses notes and some simple timing seems to show, this one is probably be better:</p>
<pre><code>>>> B = [ [val in v for val in a] for a in A]
</code></pre>
| 4 | 2009-08-13T16:37:57Z | [
"python",
"arrays",
"matrix"
] |
How can I implement matlabs ``ismember()`` command in Python? | 1,273,041 | <p>here is my problem: I would like to create a boolean matrix B that contains <code>True</code> everywhere that matrix A has a value contained in vector v. One inconvenient solution would be:</p>
<pre><code>import numpy as np
>>> A = np.array([[0,1,2], [1,2,3], [2,3,4]])
array([[0, 1, 2],
[1, 2, 3],
[2, 3, 4]])
>>> v = [1,2]
>>> B = (A==v[0]) + (A==v[1]) # matlab: ``B = ismember(A,v)``
array([[False, True, True],
[ True, True, False],
[ True, False, False]], dtype=bool)
</code></pre>
<p>Is there maybe a solution that would be more convenient if A and v would have more values?</p>
<p>Cheers!</p>
| 3 | 2009-08-13T16:19:09Z | 1,273,185 | <p>Using numpy primitives:</p>
<pre><code>>>> import numpy as np
>>> A = np.array([[0,1,2], [1,2,3], [2,3,4]])
>>> v = [1,2]
>>> print np.vectorize(lambda x: x in v)(A)
[[False True True]
[ True True False]
[ True False False]]
</code></pre>
<p>For non-tiny inputs convert v to a set first for a large speedup.</p>
<p>To use numpy.setmember1d:</p>
<pre><code>Auniq, Ainv = np.unique1d(A, return_inverse=True)
result = np.take(np.setmember1d(Auniq, np.unique1d(v)), Ainv).reshape(A.shape)
</code></pre>
| 3 | 2009-08-13T16:44:12Z | [
"python",
"arrays",
"matrix"
] |
How can I implement matlabs ``ismember()`` command in Python? | 1,273,041 | <p>here is my problem: I would like to create a boolean matrix B that contains <code>True</code> everywhere that matrix A has a value contained in vector v. One inconvenient solution would be:</p>
<pre><code>import numpy as np
>>> A = np.array([[0,1,2], [1,2,3], [2,3,4]])
array([[0, 1, 2],
[1, 2, 3],
[2, 3, 4]])
>>> v = [1,2]
>>> B = (A==v[0]) + (A==v[1]) # matlab: ``B = ismember(A,v)``
array([[False, True, True],
[ True, True, False],
[ True, False, False]], dtype=bool)
</code></pre>
<p>Is there maybe a solution that would be more convenient if A and v would have more values?</p>
<p>Cheers!</p>
| 3 | 2009-08-13T16:19:09Z | 1,273,194 | <p>I think the closest you'll get is <code>numpy.ismember1d</code>, but it won't work well with your example. I think your solution (<code>B = (A==v[0]) + (A==v[1])</code>) may actually be the best one.</p>
| 1 | 2009-08-13T16:45:24Z | [
"python",
"arrays",
"matrix"
] |
How can I implement matlabs ``ismember()`` command in Python? | 1,273,041 | <p>here is my problem: I would like to create a boolean matrix B that contains <code>True</code> everywhere that matrix A has a value contained in vector v. One inconvenient solution would be:</p>
<pre><code>import numpy as np
>>> A = np.array([[0,1,2], [1,2,3], [2,3,4]])
array([[0, 1, 2],
[1, 2, 3],
[2, 3, 4]])
>>> v = [1,2]
>>> B = (A==v[0]) + (A==v[1]) # matlab: ``B = ismember(A,v)``
array([[False, True, True],
[ True, True, False],
[ True, False, False]], dtype=bool)
</code></pre>
<p>Is there maybe a solution that would be more convenient if A and v would have more values?</p>
<p>Cheers!</p>
| 3 | 2009-08-13T16:19:09Z | 1,273,815 | <p>Alas, <code>setmember1d</code> as it exists in numpy is broken when either array has duplicated elements (as A does here). Download <a href="http://projects.scipy.org/numpy/raw-attachment/ticket/872/setmember.py" rel="nofollow">this</a> version, call it e.g sem.py somewhere on your sys.path, add to it a first line <code>import numpy as nm</code>, and THEN this finally works:</p>
<pre><code>>>> import sem
>>> print sem.setmember1d(A.reshape(A.size), v).reshape(A.shape)
[[False True True]
[True True False]
[True False False]]
</code></pre>
<p>Note the difference wrt @Aants' similar answer: this version has the second row of the resulting bool array correct, while his version (using the <code>setmember1d</code> that comes as part of numpy) incorrectly has the second row as all <code>True</code>s.</p>
| 3 | 2009-08-13T18:39:09Z | [
"python",
"arrays",
"matrix"
] |
How can I implement matlabs ``ismember()`` command in Python? | 1,273,041 | <p>here is my problem: I would like to create a boolean matrix B that contains <code>True</code> everywhere that matrix A has a value contained in vector v. One inconvenient solution would be:</p>
<pre><code>import numpy as np
>>> A = np.array([[0,1,2], [1,2,3], [2,3,4]])
array([[0, 1, 2],
[1, 2, 3],
[2, 3, 4]])
>>> v = [1,2]
>>> B = (A==v[0]) + (A==v[1]) # matlab: ``B = ismember(A,v)``
array([[False, True, True],
[ True, True, False],
[ True, False, False]], dtype=bool)
</code></pre>
<p>Is there maybe a solution that would be more convenient if A and v would have more values?</p>
<p>Cheers!</p>
| 3 | 2009-08-13T16:19:09Z | 6,101,855 | <p>Since Numpy version 1.4 there's a new function, in1d() that's the equivalent of ismember() in matlab: <a href="http://docs.scipy.org/doc/numpy-1.6.0/reference/generated/numpy.in1d.html" rel="nofollow">http://docs.scipy.org/doc/numpy-1.6.0/reference/generated/numpy.in1d.html</a>. But as ars points out, it only returns a 1d array.</p>
| 1 | 2011-05-23T19:20:24Z | [
"python",
"arrays",
"matrix"
] |
Can't import Numpy in Python | 1,273,203 | <p>I'm trying to write some code that uses Numpy. However, I can't import it:</p>
<pre><code>Python 2.6.2 (r262, May 15 2009, 10:22:27)
[GCC 3.4.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named numpy
</code></pre>
<p>I tried the suggestions in <a href="http://stackoverflow.com/questions/233320/cannot-import-sqlite-with-python-2-6" title="Cannot import sqlite with Python 2.6">this question</a>:</p>
<pre><code>>>> import sys
>>> print sys.path
['', '/usr/intel/pkgs/python/2.6.2/lib/python26.zip', '/usr/intel/pkgs/python/2.6.2/lib/python2.6', '/usr/intel/pkgs/python/2.6.2/lib/python2.6/plat-linux2', '/usr/intel/pkgs/python/2.6.2/lib/python2.6/lib-tk', '/usr/intel/pkgs/python/2.6.2/lib/python2.6/lib-old', '/usr/intel/pkgs/python/2.6.2/lib/python2.6/lib-dynload', '/usr/intel/pkgs/python/2.6.2/lib/python2.6/site-packages']
</code></pre>
<p>and I searched for files named <code>numpy</code> in that path:</p>
<pre><code>$ find /usr/intel/pkgs/python/2.6.2/bin/python -iname numpy\*
</code></pre>
<p>But nothing came up.</p>
<p>So...</p>
<ul>
<li>Are there any other places in which Python modules are commonly installed?</li>
<li>How can I install numpy locally in my account, if it turns out that it isn't installed in the central areas?</li>
</ul>
| 16 | 2009-08-13T16:48:29Z | 1,273,217 | <p>Have you installed it?</p>
<p>On debian/ubuntu:</p>
<pre><code>aptitude install python-numpy
</code></pre>
<p>On windows:</p>
<p><a href="http://sourceforge.net/projects/numpy/files/NumPy/"><code>http://sourceforge.net/projects/numpy/files/NumPy/</code></a></p>
<p>On other systems:</p>
<p><a href="http://sourceforge.net/projects/numpy/files/NumPy/"><code>http://sourceforge.net/projects/numpy/files/NumPy/</code></a></p>
<pre><code>$ tar xfz numpy-n.m.tar.gz
$ cd numpy-n.m
$ python setup.py install
</code></pre>
| 19 | 2009-08-13T16:50:53Z | [
"python",
"import",
"numpy"
] |
Can't import Numpy in Python | 1,273,203 | <p>I'm trying to write some code that uses Numpy. However, I can't import it:</p>
<pre><code>Python 2.6.2 (r262, May 15 2009, 10:22:27)
[GCC 3.4.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named numpy
</code></pre>
<p>I tried the suggestions in <a href="http://stackoverflow.com/questions/233320/cannot-import-sqlite-with-python-2-6" title="Cannot import sqlite with Python 2.6">this question</a>:</p>
<pre><code>>>> import sys
>>> print sys.path
['', '/usr/intel/pkgs/python/2.6.2/lib/python26.zip', '/usr/intel/pkgs/python/2.6.2/lib/python2.6', '/usr/intel/pkgs/python/2.6.2/lib/python2.6/plat-linux2', '/usr/intel/pkgs/python/2.6.2/lib/python2.6/lib-tk', '/usr/intel/pkgs/python/2.6.2/lib/python2.6/lib-old', '/usr/intel/pkgs/python/2.6.2/lib/python2.6/lib-dynload', '/usr/intel/pkgs/python/2.6.2/lib/python2.6/site-packages']
</code></pre>
<p>and I searched for files named <code>numpy</code> in that path:</p>
<pre><code>$ find /usr/intel/pkgs/python/2.6.2/bin/python -iname numpy\*
</code></pre>
<p>But nothing came up.</p>
<p>So...</p>
<ul>
<li>Are there any other places in which Python modules are commonly installed?</li>
<li>How can I install numpy locally in my account, if it turns out that it isn't installed in the central areas?</li>
</ul>
| 16 | 2009-08-13T16:48:29Z | 1,273,280 | <p>Your sys.path is kind of unusual, as each entry is prefixed with /usr/intel. I guess numpy is installed in the usual non-prefixed place, e.g. it. /usr/share/pyshared/numpy on my Ubuntu system.</p>
<p>Try <code>find / -iname '*numpy*'</code></p>
| 4 | 2009-08-13T16:59:40Z | [
"python",
"import",
"numpy"
] |
Can't import Numpy in Python | 1,273,203 | <p>I'm trying to write some code that uses Numpy. However, I can't import it:</p>
<pre><code>Python 2.6.2 (r262, May 15 2009, 10:22:27)
[GCC 3.4.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named numpy
</code></pre>
<p>I tried the suggestions in <a href="http://stackoverflow.com/questions/233320/cannot-import-sqlite-with-python-2-6" title="Cannot import sqlite with Python 2.6">this question</a>:</p>
<pre><code>>>> import sys
>>> print sys.path
['', '/usr/intel/pkgs/python/2.6.2/lib/python26.zip', '/usr/intel/pkgs/python/2.6.2/lib/python2.6', '/usr/intel/pkgs/python/2.6.2/lib/python2.6/plat-linux2', '/usr/intel/pkgs/python/2.6.2/lib/python2.6/lib-tk', '/usr/intel/pkgs/python/2.6.2/lib/python2.6/lib-old', '/usr/intel/pkgs/python/2.6.2/lib/python2.6/lib-dynload', '/usr/intel/pkgs/python/2.6.2/lib/python2.6/site-packages']
</code></pre>
<p>and I searched for files named <code>numpy</code> in that path:</p>
<pre><code>$ find /usr/intel/pkgs/python/2.6.2/bin/python -iname numpy\*
</code></pre>
<p>But nothing came up.</p>
<p>So...</p>
<ul>
<li>Are there any other places in which Python modules are commonly installed?</li>
<li>How can I install numpy locally in my account, if it turns out that it isn't installed in the central areas?</li>
</ul>
| 16 | 2009-08-13T16:48:29Z | 7,300,628 | <p>I was trying to import numpy in python 3.2.1 on windows 7. </p>
<p>Followed suggestions in above answer for numpy-1.6.1.zip as below after unzipping it</p>
<pre><code>cd numpy-1.6
python setup.py install
</code></pre>
<p>but got an error with a statement as below</p>
<pre><code>unable to find vcvarsall.bat
</code></pre>
<p>For this error I found a related question <a href="http://stackoverflow.com/questions/2817869/error-unable-to-find-vcvarsall-bat">here</a> which suggested installing mingW. MingW was taking some time to install. </p>
<p>In the meanwhile tried to install numpy 1.6 again using the direct windows installer available at this <a href="http://sourceforge.net/projects/numpy/files/NumPy/1.6.1/" rel="nofollow">link</a>
the file name is "numpy-1.6.1-win32-superpack-python3.2.exe"</p>
<p>Installation went smoothly and now I am able to import numpy without using mingW.</p>
<p>Long story short try using windows installer for numpy, if one is available.</p>
| 0 | 2011-09-04T16:38:19Z | [
"python",
"import",
"numpy"
] |
Can't import Numpy in Python | 1,273,203 | <p>I'm trying to write some code that uses Numpy. However, I can't import it:</p>
<pre><code>Python 2.6.2 (r262, May 15 2009, 10:22:27)
[GCC 3.4.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named numpy
</code></pre>
<p>I tried the suggestions in <a href="http://stackoverflow.com/questions/233320/cannot-import-sqlite-with-python-2-6" title="Cannot import sqlite with Python 2.6">this question</a>:</p>
<pre><code>>>> import sys
>>> print sys.path
['', '/usr/intel/pkgs/python/2.6.2/lib/python26.zip', '/usr/intel/pkgs/python/2.6.2/lib/python2.6', '/usr/intel/pkgs/python/2.6.2/lib/python2.6/plat-linux2', '/usr/intel/pkgs/python/2.6.2/lib/python2.6/lib-tk', '/usr/intel/pkgs/python/2.6.2/lib/python2.6/lib-old', '/usr/intel/pkgs/python/2.6.2/lib/python2.6/lib-dynload', '/usr/intel/pkgs/python/2.6.2/lib/python2.6/site-packages']
</code></pre>
<p>and I searched for files named <code>numpy</code> in that path:</p>
<pre><code>$ find /usr/intel/pkgs/python/2.6.2/bin/python -iname numpy\*
</code></pre>
<p>But nothing came up.</p>
<p>So...</p>
<ul>
<li>Are there any other places in which Python modules are commonly installed?</li>
<li>How can I install numpy locally in my account, if it turns out that it isn't installed in the central areas?</li>
</ul>
| 16 | 2009-08-13T16:48:29Z | 30,621,853 | <p><strong>To install it on Debian/Ubuntu:</strong></p>
<pre><code>sudo apt-get install python-numpy
</code></pre>
| 2 | 2015-06-03T13:40:35Z | [
"python",
"import",
"numpy"
] |
Disable assertions in Python | 1,273,211 | <p>How do I disable assertions in Python?</p>
<p>That is, if an assertion fails, I don't want it to throw an <code>AssertionError</code>, but to keep going.</p>
| 37 | 2009-08-13T16:49:37Z | 1,273,224 | <p>Running in optimized mode should do it.</p>
<pre><code>python -OO module.py
</code></pre>
| 3 | 2009-08-13T16:52:09Z | [
"python",
"debugging",
"assert"
] |
Disable assertions in Python | 1,273,211 | <p>How do I disable assertions in Python?</p>
<p>That is, if an assertion fails, I don't want it to throw an <code>AssertionError</code>, but to keep going.</p>
| 37 | 2009-08-13T16:49:37Z | 1,273,225 | <p>Use <code>python -O</code>:</p>
<pre><code>$ python -O
>>> assert False
>>>
</code></pre>
| 7 | 2009-08-13T16:52:12Z | [
"python",
"debugging",
"assert"
] |
Disable assertions in Python | 1,273,211 | <p>How do I disable assertions in Python?</p>
<p>That is, if an assertion fails, I don't want it to throw an <code>AssertionError</code>, but to keep going.</p>
| 37 | 2009-08-13T16:49:37Z | 1,273,233 | <p>Call Python with the -O flag:</p>
<p>test.py:</p>
<pre><code>assert(False)
print 'Done'
</code></pre>
<p>Output:</p>
<pre><code>C:\temp\py>C:\Python26\python.exe test.py
Traceback (most recent call last):
File "test.py", line 1, in <module>
assert(False)
AssertionError
C:\temp\py>C:\Python26\python.exe -O test.py
Done
</code></pre>
| 46 | 2009-08-13T16:53:41Z | [
"python",
"debugging",
"assert"
] |
Disable assertions in Python | 1,273,211 | <p>How do I disable assertions in Python?</p>
<p>That is, if an assertion fails, I don't want it to throw an <code>AssertionError</code>, but to keep going.</p>
| 37 | 2009-08-13T16:49:37Z | 21,325,317 | <p>Both of the two answers already given are valid (call Python with either <code>-O</code> or <code>-OO</code> on the command line).</p>
<p>Here is the difference between them:</p>
<ul>
<li><p><code>-O</code> Turn on basic optimizations. This changes the filename extension
for compiled (bytecode) files from .pyc to .pyo.</p></li>
<li><p><code>-OO</code> Discard docstrings <em>in addition</em> to the <code>-O</code> optimizations.</p></li>
</ul>
<p>(From the <a href="http://docs.python.org/3.3/using/cmdline.html" rel="nofollow">Python documentation</a>)</p>
| 9 | 2014-01-24T05:45:49Z | [
"python",
"debugging",
"assert"
] |
Disable assertions in Python | 1,273,211 | <p>How do I disable assertions in Python?</p>
<p>That is, if an assertion fails, I don't want it to throw an <code>AssertionError</code>, but to keep going.</p>
| 37 | 2009-08-13T16:49:37Z | 29,741,912 | <p>You should <em>NOT</em> disable (most) assertions. In safety-critical software, they can save lives (or the mission, if it is unmanned). They also save a lot of developer time, and catch untested errors during deployment.</p>
<p>Instead, guard some (few) expensive assertion checks by something like:</p>
<pre><code>import logging
logger = logging.getLogger(__name__)
if logger.getEffectiveLevel() < logging.DEBUG:
ok = check_expensive_property()
assert ok, 'Run !'
</code></pre>
| 0 | 2015-04-20T07:41:51Z | [
"python",
"debugging",
"assert"
] |
django problem uploading and saving documents | 1,273,285 | <p>I am working on a django app. One part would involve uploading files (e.g. spreadsheet or whatever). I am getting this error:</p>
<pre><code>IOError at /fileupload/
[Errno 13] Permission denied: 'fyi.xml'
</code></pre>
<p>Where 'fileupload' was the django app name and 'fyi.xml' was the test document I was uploading.</p>
<p>So, I used chmod and chown to make the [project directory]/static/documents/ folder writable to apache. Actually I even tried just making it chmod 777, still no luck.</p>
<p>So, in my settings.py I just changed where my MEDIA_ROOT was:</p>
<pre><code>MEDIA_ROOT = '/var/www/static/'
</code></pre>
<p>Then, in case it was an SELinux thing, I created the new documents directory in /var/www/static'...</p>
<pre><code>drwxr-xr-x 2 apache root 4096 Aug 13 11:20 documents
</code></pre>
<p>Then I did these commands to try to change the context so apache would be allowed to write here. I'm not too familiar with this distro, it's the flavor of Red Hat we're given, so I've never had to go beyond chmod and/or chown to fix a permissions problem.</p>
<pre><code>sudo chcon -h system_u:object_r:httpd_sys_content_t /var/www/static
sudo chcon -R -h root:object_r:httpd_sys_content_t /var/www/static
sudo chcon -R -h root:object_r:httpd_sys_content_t /var/www/static/*
</code></pre>
<p>None of this made any difference. To be honest, I'm not positive that I even have SELinux here but since normal unix permissions didn't seem to work I thought I'd try it.</p>
<p>So, does anyone have an idea on what to look at next? Not sure how much code I should post here, but in case it would be helpful here's what's in my views.py:</p>
<pre><code>views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from forms import UploadFileForm
from fyi.models import Materials
def handle_uploaded_file(f):
destination = open('fyi.xml', 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['document'])
form.save()
template = 'upload_success.html'
else:
form = UploadFileForm()
template = 'fileupload.html'
return render_to_response( template, {'form': form})
</code></pre>
<p>...any help would be appreciated.</p>
| 1 | 2009-08-13T17:00:26Z | 1,273,533 | <p>Maybe try changing:</p>
<pre><code>destination = open('fyi.xml', 'wb+')
</code></pre>
<p>to something like:</p>
<pre><code>upload_dir = settings.MEDIA_ROOT # or wherever
destination = open(os.path.join(upload_dir, 'fyi.xml'), 'wb+')
</code></pre>
<p>If it is an SELinux issue, perhaps this page would help:</p>
<ul>
<li><a href="http://blog.chrisramsay.co.uk/2009/05/22/writing-files-with-django-under-selinux/" rel="nofollow">http://blog.chrisramsay.co.uk/2009/05/22/writing-files-with-django-under-selinux/</a></li>
</ul>
| 0 | 2009-08-13T17:46:04Z | [
"python",
"django",
"file",
"permissions"
] |
Python Twisted: restricting access by IP address | 1,273,297 | <p>What would be the best method to restrict access to my XMLRPC server by IP address? I see the class CGIScript in web/twcgi.py has a render method that is accessing the request... but I am not sure how to gain access to this request in my server. I saw an example where someone patched twcgi.py to set environment variables and then in the server access the environment variables... but I figure there has to be a better solution.</p>
<p>Thanks.</p>
| 2 | 2009-08-13T17:03:13Z | 1,273,455 | <p>I'd use a firewall on windows, or <code>iptables</code> on linux.</p>
| 0 | 2009-08-13T17:30:25Z | [
"python",
"twisted"
] |
Python Twisted: restricting access by IP address | 1,273,297 | <p>What would be the best method to restrict access to my XMLRPC server by IP address? I see the class CGIScript in web/twcgi.py has a render method that is accessing the request... but I am not sure how to gain access to this request in my server. I saw an example where someone patched twcgi.py to set environment variables and then in the server access the environment variables... but I figure there has to be a better solution.</p>
<p>Thanks.</p>
| 2 | 2009-08-13T17:03:13Z | 1,305,810 | <p>Okay, another answer is to get the ip address from the transport, inside any protocol:</p>
<p><code>d = </code> <a href="http://twistedmatrix.com/documents/current/api/twisted.internet.interfaces.ITCPTransport.html#getHost" rel="nofollow"><code>self.transport.getHost</code></a> <code>() ; print d.type, d.host, d.port</code></p>
<p>Then use the value to filter it in any way you want.</p>
| 2 | 2009-08-20T12:21:16Z | [
"python",
"twisted"
] |
Python Twisted: restricting access by IP address | 1,273,297 | <p>What would be the best method to restrict access to my XMLRPC server by IP address? I see the class CGIScript in web/twcgi.py has a render method that is accessing the request... but I am not sure how to gain access to this request in my server. I saw an example where someone patched twcgi.py to set environment variables and then in the server access the environment variables... but I figure there has to be a better solution.</p>
<p>Thanks.</p>
| 2 | 2009-08-13T17:03:13Z | 1,308,789 | <p>When a connection is established, a factory's buildProtocol is called to create a new protocol instance to handle that connection. buildProtocol is passed the address of the peer which established the connection and buildProtocol may return None to have the connection closed immediately.</p>
<p>So, for example, you can write a factory like this:</p>
<pre><code>from twisted.internet.protocol import ServerFactory
class LocalOnlyFactory(ServerFactory):
def buildProtocol(self, addr):
if addr.host == "127.0.0.1":
return ServerFactory.buildProtocol(self, addr)
return None
</code></pre>
<p>And only local connections will be handled (but all connections will still be accepted initially since you must accept them to learn what the peer address is).</p>
<p>You can apply this to the factory you're using to serve XML-RPC resources. Just subclass that factory and add logic like this (or you can do a wrapper instead of a subclass).</p>
<p>iptables or some other platform firewall is also a good idea for some cases, though. With that approach, your process never even has to see the connection attempt.</p>
| 5 | 2009-08-20T21:02:34Z | [
"python",
"twisted"
] |
How to skip empty dates (weekends) in a financial Matplotlib Python graph? | 1,273,472 | <pre><code>ax.plot_date((dates, dates), (highs, lows), '-')
</code></pre>
<p>I'm currently using this command to plot financial highs and lows using <a href="http://en.wikipedia.org/wiki/Matplotlib">Matplotlib</a>. It works great, but how do I remove the blank spaces in the x-axis left by days without market data, such as weekends and holidays?</p>
<p>I have lists of dates, highs, lows, closes and opens. I can't find any examples of creating a graph with an x-axis that show dates but doesn't enforce a constant scale. </p>
| 9 | 2009-08-13T17:33:29Z | 1,273,603 | <p>I think you need to "artificially synthesize" the exact form of plot you want by using <code>xticks</code> to set the tick labels to the strings representing the dates (of course placing the ticks at equispaced intervals even though the dates you're representing aren't equispaced) and then using a plain <code>plot</code>.</p>
| 3 | 2009-08-13T17:56:33Z | [
"python",
"graph",
"matplotlib",
"financial"
] |
How to skip empty dates (weekends) in a financial Matplotlib Python graph? | 1,273,472 | <pre><code>ax.plot_date((dates, dates), (highs, lows), '-')
</code></pre>
<p>I'm currently using this command to plot financial highs and lows using <a href="http://en.wikipedia.org/wiki/Matplotlib">Matplotlib</a>. It works great, but how do I remove the blank spaces in the x-axis left by days without market data, such as weekends and holidays?</p>
<p>I have lists of dates, highs, lows, closes and opens. I can't find any examples of creating a graph with an x-axis that show dates but doesn't enforce a constant scale. </p>
| 9 | 2009-08-13T17:33:29Z | 1,273,671 | <p>One of the advertised features of <a href="http://pytseries.sourceforge.net/" rel="nofollow">scikits.timeseries</a> is "Create time series plots with intelligently spaced axis labels". </p>
<p>You can see some example plots <a href="http://pytseries.sourceforge.net/lib.plotting.examples.html" rel="nofollow">here</a>. In the first example (shown below) the 'business' frequency is used for the data, which automatically excludes holidays and weekends and the like. It also masks missing data points, which you see as gaps in this plot, rather than linearly interpolating them.</p>
<p><img src="http://pytseries.sourceforge.net/_images/yahoo.png" alt="alt text"></p>
| 4 | 2009-08-13T18:10:05Z | [
"python",
"graph",
"matplotlib",
"financial"
] |
How to skip empty dates (weekends) in a financial Matplotlib Python graph? | 1,273,472 | <pre><code>ax.plot_date((dates, dates), (highs, lows), '-')
</code></pre>
<p>I'm currently using this command to plot financial highs and lows using <a href="http://en.wikipedia.org/wiki/Matplotlib">Matplotlib</a>. It works great, but how do I remove the blank spaces in the x-axis left by days without market data, such as weekends and holidays?</p>
<p>I have lists of dates, highs, lows, closes and opens. I can't find any examples of creating a graph with an x-axis that show dates but doesn't enforce a constant scale. </p>
| 9 | 2009-08-13T17:33:29Z | 1,275,389 | <p>I will typically use <a href="http://en.wikipedia.org/wiki/NumPy" rel="nofollow">NumPy</a>'s NaN (not a number) for values that are invalid or not present. They are represented by Matplotlib as gaps in the plot and NumPy is part of pylab/Matplotlib.</p>
<pre><code>>>> import pylab
>>> xs = pylab.arange(10.) + 733632. # valid date range
>>> ys = [1,2,3,2,pylab.nan,2,3,2,5,2.4] # some data (one undefined)
>>> pylab.plot_date(xs, ys, ydate=False, linestyle='-', marker='')
[<matplotlib.lines.Line2D instance at 0x0378D418>]
>>> pylab.show()
</code></pre>
| 6 | 2009-08-14T00:18:51Z | [
"python",
"graph",
"matplotlib",
"financial"
] |
How to skip empty dates (weekends) in a financial Matplotlib Python graph? | 1,273,472 | <pre><code>ax.plot_date((dates, dates), (highs, lows), '-')
</code></pre>
<p>I'm currently using this command to plot financial highs and lows using <a href="http://en.wikipedia.org/wiki/Matplotlib">Matplotlib</a>. It works great, but how do I remove the blank spaces in the x-axis left by days without market data, such as weekends and holidays?</p>
<p>I have lists of dates, highs, lows, closes and opens. I can't find any examples of creating a graph with an x-axis that show dates but doesn't enforce a constant scale. </p>
| 9 | 2009-08-13T17:33:29Z | 2,335,781 | <p>There's an example of how to do this on the Matplotlib site:</p>
<p><a href="http://matplotlib.sourceforge.net/examples/api/date_index_formatter.html">http://matplotlib.sourceforge.net/examples/api/date_index_formatter.html</a></p>
| 6 | 2010-02-25T16:44:17Z | [
"python",
"graph",
"matplotlib",
"financial"
] |
Porting a Python app that uses Psyco to Mac | 1,273,546 | <p>I'm trying to port my Python app from Windows to Mac. My app uses Psyco. How exactly do I install Psyco on Mac?</p>
<p>Keep in mind I'm a Mac newbie.</p>
| 0 | 2009-08-13T17:48:27Z | 1,273,631 | <p>The <a href="http://psyco.sourceforge.net/" rel="nofollow">News</a> page shows that a Mac port is still being written. Learn how to install from source code using Make. Apply that patch, compile, and install.</p>
| -1 | 2009-08-13T18:03:25Z | [
"python",
"osx",
"psyco"
] |
Porting a Python app that uses Psyco to Mac | 1,273,546 | <p>I'm trying to port my Python app from Windows to Mac. My app uses Psyco. How exactly do I install Psyco on Mac?</p>
<p>Keep in mind I'm a Mac newbie.</p>
| 0 | 2009-08-13T17:48:27Z | 1,273,646 | <p>First, you need Apple's XCode installed (well, specifically you only need the gcc compiler that comes with it, but installing the whole thing is simpler;-). If you want the latest and greatest, sign up for <a href="http://developer.apple.com/" rel="nofollow">ADC</a> at the lowest (free!-) level and download from there; otherwise it should be in your OSX DVD (or, depending on OSX level and how you installed the OS, the installer might already be on your hard disk).</p>
<p>To verify XCode's properly installed, at a Terminal.app enter <code>gcc</code> and you should see a message such as <code>i686-apple-darwin9-gcc-4.0.1: no input files</code>.</p>
<p>Once that works, download psyco's sources from <a href="http://sourceforge.net/projects/psyco/files/psyco/1.6/psyco-1.6-src.tar.gz/download" rel="nofollow">here</a>, unpack them (you probably can get it done during the download, worst case use <code>tar xzf psyco-1.6-src.tar.gz</code> in Terminal.app after cd'ing to the directory you've downloaded that tar.gz to), cd into the new psyco-1.6 directory.</p>
<p>Then do <code>python setup.py install</code> at the Terminal.app shell prompt. Depending on how exactly you installed things, you may need to use <code>sudo python setup.py install</code> and give your password to enable writing into the system directories.</p>
| 2 | 2009-08-13T18:06:07Z | [
"python",
"osx",
"psyco"
] |
Exporting keyframes in blender python | 1,273,588 | <p>I'm trying to export animation from blender, here's what I've done so far:<br />
--- This is just to give you an idea of what I'm doing and I've left out a lot to keep it short.<br />
--- If it's too confusing or if it's needed I could post the whole source.</p>
<pre><code># Get the armature
arm = ob.getData()
# Start at the root bone
for bone in bones:
if not bone.parent:
traceBone(bone)
def traceBone(bone):
# Get the channel for this bone
channel=action.getChannelIpo(bone.name);
# Get the loc x, y, z channels
c_locx=channel[Ipo.OB_LOCX].bezierPoints
frameCount=len(c_locx)
# Write each location frame
for frameIndex in range(frameCount):
frame_x=c_locx[frameIndex].pt
frameTime=int(frame_x[0]-1)
# Write the time of the frame
writeInt(frameTime)
# Write the x, y and z coordinates
writeFloats(frame_x[1], frame_z[1], frame_y[1])
# Iv'e done the same for rotation
c_quatx=channel[Ipo.PO_QUATX].bezierPoints
# Write the quaternion w, x, y and z values
writeFloats(frame_w[1], frame_x[1], frame_z[1], frame_y[1])
# Go through the children
for child in bone.children:
traceBone(child)
</code></pre>
<p>As far as I can tell this all works fine, the problem is that these values are offsets,
representing change, but what I need is absolute values representing the location and rotation values of the bone relative to it's parent.</p>
<p>How do I get the position and rotation relative to it's parent?</p>
| 2 | 2009-08-13T17:54:31Z | 1,676,436 | <p>The channel data should be applied on top of the bind pose matrix.</p>
<p>The complete formula is the following:</p>
<p><strong>Mr = Ms * B0*P0 * B1*P1 <em>...</em> Bn*Pn</strong></p>
<p>where:</p>
<p><strong>Mr</strong> = result matrix for a bone 'n'</p>
<p><strong>Ms</strong> = skeleton->world matrix</p>
<p><strong>Bi</strong> = bind pose matrix for bone 'i'</p>
<p><strong>Pi</strong> = pose actual matrix constructed from stored channels (that you are exporting)</p>
<p>'n-1' is a parent bone for 'n', 'n-2' is parent of 'n-1', ... , '0' is a parent of '1'</p>
| 2 | 2009-11-04T20:37:17Z | [
"python",
"3d",
"blender"
] |
parsing month year pairs into datetime | 1,273,811 | <p>Let's say i have 2 strings 'Jan-2010' and 'Mar-2010' and i want to parse it such that it returns 2 datetime objects: 1-Jan-2010 and 31-Mar-2010 (i.e. the last day). </p>
<p>What would be the best strategy in python? Should i just split the string into tokens or use regular expressions and then use the calendar functions to get say the last day of the month for 'Mar-2010' (getting the first day is trivial, its always 1 in this case unless i wanted the first working day of the month).</p>
<p>Any suggestions? Thanks in advance.</p>
| 4 | 2009-08-13T18:38:56Z | 1,273,950 | <pre><code>from datetime import datetime, timedelta
def first_day(some_date):
return some_date.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
def next_month(some_date):
return first_day(first_day(some_date) + timedelta(days=31))
def last_day(some_date):
return next_month(some_date) - timedelta(days=1)
# testing:
months = [('Jan-2010', 'Mar-2010'), # your example
('Apr-2009', 'Apr-2009'), # same month, 30 days
('Jan-2008', 'Dec-2008'), # whole year
('Jan-2007', 'Feb-2007')] # february involved
for date1, date2 in months:
print first_day(datetime.strptime(date1, '%b-%Y')),
print '-',
print last_day(datetime.strptime(date2, '%b-%Y'))
</code></pre>
<p>That prints:</p>
<pre><code>2010-01-01 00:00:00 - 2010-03-31 00:00:00
2009-04-01 00:00:00 - 2009-04-30 00:00:00
2008-01-01 00:00:00 - 2008-12-31 00:00:00
2007-01-01 00:00:00 - 2007-02-28 00:00:00
</code></pre>
| 2 | 2009-08-13T19:02:00Z | [
"python",
"datetime"
] |
parsing month year pairs into datetime | 1,273,811 | <p>Let's say i have 2 strings 'Jan-2010' and 'Mar-2010' and i want to parse it such that it returns 2 datetime objects: 1-Jan-2010 and 31-Mar-2010 (i.e. the last day). </p>
<p>What would be the best strategy in python? Should i just split the string into tokens or use regular expressions and then use the calendar functions to get say the last day of the month for 'Mar-2010' (getting the first day is trivial, its always 1 in this case unless i wanted the first working day of the month).</p>
<p>Any suggestions? Thanks in advance.</p>
| 4 | 2009-08-13T18:38:56Z | 1,273,953 | <p><code>strptime</code> does the string parsing into dates on your behalf:</p>
<pre><code>def firstofmonth(MmmYyyy):
return datetime.datetime.strptime(MmmYyyy, '%b-%Y').date()
</code></pre>
<p>much better than messing around with tokenization, regexp, &c!-).</p>
<p>To get the date of the last day of the month, you can indeed use the calendar module:</p>
<pre><code>def lastofmonth(MmmYyyy):
first = firstofmonth(MmmYyyy)
_, lastday = calendar.monthrange(first.year, first.month)
return datetime.date(first.year, first.month, lastday)
</code></pre>
<p>You could ALMOST do it neatly with datetime alone, e.g., an ALMOST working approach:</p>
<pre><code>def lastofmonth(MmmYyyy):
first = firstofmonth(MmmYyyy)
return first.replace(month=first.month+1, day=1
) - datetime.timedelta(days=1)
</code></pre>
<p>but, alas!, this breaks for December, and the code needed to specialcase December makes the overall approach goofier than calendar affords;-).</p>
| 5 | 2009-08-13T19:02:52Z | [
"python",
"datetime"
] |
parsing month year pairs into datetime | 1,273,811 | <p>Let's say i have 2 strings 'Jan-2010' and 'Mar-2010' and i want to parse it such that it returns 2 datetime objects: 1-Jan-2010 and 31-Mar-2010 (i.e. the last day). </p>
<p>What would be the best strategy in python? Should i just split the string into tokens or use regular expressions and then use the calendar functions to get say the last day of the month for 'Mar-2010' (getting the first day is trivial, its always 1 in this case unless i wanted the first working day of the month).</p>
<p>Any suggestions? Thanks in advance.</p>
| 4 | 2009-08-13T18:38:56Z | 1,274,043 | <p>Riffing on Alex Martelli's:</p>
<pre><code>import datetime
def lastofmonthHelper(MmmYyyy): # Takes a date
return MmmYyyy.replace(year=MmmYyyy.year+(MmmYyyy.month==12), month=MmmYyyy.month%12 + 1, day=1) - datetime.timedelta(days=1)
>>> for month in range(1,13):
... t = datetime.date(2009,month,1)
... print t, lastofmonthHelper(t)
...
2009-01-01 2009-01-31
2009-02-01 2009-02-28
2009-03-01 2009-03-31
2009-04-01 2009-04-30
2009-05-01 2009-05-31
2009-06-01 2009-06-30
2009-07-01 2009-07-31
2009-08-01 2009-08-31
2009-09-01 2009-09-30
2009-10-01 2009-10-31
2009-11-01 2009-11-30
2009-12-01 2009-12-31
</code></pre>
<p>You don't have to use the first day of the month, BTW. I would have put this in a comment but we all know how the formatting would have turned out. Feel free to upvote Alex.</p>
<p>If you call with the result of a firstofmonth() call, you get the desired result:</p>
<pre><code>>>> lastofmonthHelper(firstofmonth('Apr-2009'))
datetime.date(2009, 4, 30)
</code></pre>
| 0 | 2009-08-13T19:20:46Z | [
"python",
"datetime"
] |
parsing month year pairs into datetime | 1,273,811 | <p>Let's say i have 2 strings 'Jan-2010' and 'Mar-2010' and i want to parse it such that it returns 2 datetime objects: 1-Jan-2010 and 31-Mar-2010 (i.e. the last day). </p>
<p>What would be the best strategy in python? Should i just split the string into tokens or use regular expressions and then use the calendar functions to get say the last day of the month for 'Mar-2010' (getting the first day is trivial, its always 1 in this case unless i wanted the first working day of the month).</p>
<p>Any suggestions? Thanks in advance.</p>
| 4 | 2009-08-13T18:38:56Z | 1,274,102 | <p>I highly recommend using the python timeseries module, which you can download and read about here: </p>
<p><a href="http://pytseries.sourceforge.net/" rel="nofollow">http://pytseries.sourceforge.net/</a> </p>
<p>You should also use the dateutil package for parsing the date string, which you can find here: </p>
<p><a href="http://labix.org/python-dateutil" rel="nofollow">http://labix.org/python-dateutil</a></p>
<p>Then you can do something like this</p>
<pre><code>import datetime
import dateutil.parser
import scikits.timeseries as TS
m1 = TS.Date('M', datetime=dateutil.parser.parse('Jan-2010'))
m2 = TS.Date('M', datetime=dateutil.parser.parse('Mar-2010'))
d1 = m1.asfreq('D', relation='START') # returns a TS.Date object
d2 = m2.asfreq('D', relation='END')
firstDay = d1.datetime
lastDay = d2.datetime
</code></pre>
<p>This solution is dependent out outside modules, but they're very powerful and well written.</p>
| 3 | 2009-08-13T19:30:57Z | [
"python",
"datetime"
] |
parsing month year pairs into datetime | 1,273,811 | <p>Let's say i have 2 strings 'Jan-2010' and 'Mar-2010' and i want to parse it such that it returns 2 datetime objects: 1-Jan-2010 and 31-Mar-2010 (i.e. the last day). </p>
<p>What would be the best strategy in python? Should i just split the string into tokens or use regular expressions and then use the calendar functions to get say the last day of the month for 'Mar-2010' (getting the first day is trivial, its always 1 in this case unless i wanted the first working day of the month).</p>
<p>Any suggestions? Thanks in advance.</p>
| 4 | 2009-08-13T18:38:56Z | 11,325,538 | <p>i know it's long time gone, but if someone needs:</p>
<pre><code>from dateutil import rrule
from dateutil import parser
from datetime import datetime
first_day = parser.parse('Jan-2010',default=datetime(1,1,1))
last_day = rrule.rrule(rrule.MONTHLY,count=1,bymonthday=-1, bysetpos=1,dtstart=parser.parse('Mar-2010'))
</code></pre>
| 1 | 2012-07-04T08:46:43Z | [
"python",
"datetime"
] |
What is the correct way to generate a json from file in GoogleAppEngine? | 1,274,035 | <p>I'm quite new to python and GAE, can anyone please provide some help/sample code for doing the following simple task? I managed to read a simple file and output it as a webpage but I need some slightly more complicated logic. Here is the pseudo code:</p>
<pre><code> open file;
for each line in file {
store first line as album title;
for each song read {
store first line as song title;
store second line as song URL;
}
}
Output the read in data as a json;
</code></pre>
<p>The file format will be something like this </p>
<p><em>Album title1<br> song1 title<br> song1 url<br> song2 title<br> song2 url<br> <br> Album title2<br> song1 title<br> song1 url<br> song2 title<br> song2 url<br> ..</em></p>
| 1 | 2009-08-13T19:19:05Z | 1,274,374 | <p>Here's a generator-based solution with a few nice features:</p>
<ul>
<li>Tolerates multiple blank lines between albums in text file </li>
<li>Tolerates leading/trailing blank lines in text file </li>
<li>Uses only an album's worth of memory at a time </li>
<li>Demonstrates a lot of neato things you can do with Python :) </li>
</ul>
<p><strong>albums.txt</strong></p>
<pre><code>Album title1
song1 title
song1 url
song2 title
song2 url
Album title2
song1 title
song1 url
song2 title
song2 url
</code></pre>
<p><strong>Code</strong></p>
<pre><code>from django.utils import simplejson
def gen_groups(lines):
""" Returns contiguous groups of lines in a file """
group = []
for line in lines:
line = line.strip()
if not line and group:
yield group
group = []
elif line:
group.append(line)
def gen_albums(groups):
""" Given groups of lines in an album file, returns albums """
for group in groups:
title = group.pop(0)
songinfo = zip(*[iter(group)]*2)
songs = [dict(title=title,url=url) for title,url in songinfo]
album = dict(title=title, songs=songs)
yield album
input = open('albums.txt')
groups = gen_groups(input)
albums = gen_albums(groups)
print simplejson.dumps(list(albums))
</code></pre>
<p><strong>Output</strong></p>
<pre><code>[{"songs": [{"url": "song1 url", "title": "song1 title"}, {"url": "song2 url", "title": "song2 title"}], "title": "song2
title"},
{"songs": [{"url": "song1 url", "title": "song1 title"}, {"url": "song2 url", "title": "song2 title"}], "title": "song2
title"}]
</code></pre>
<p>Album information could then be accessed in Javascript like so:</p>
<pre><code>var url = albums[1].songs[0].url;
</code></pre>
<p>Lastly, here's a note about that <a href="http://docs.python.org/library/functions.html#zip" rel="nofollow">tricky zip line</a>.</p>
| 3 | 2009-08-13T20:26:52Z | [
"python",
"google-app-engine",
"file-io"
] |
What is the correct way to generate a json from file in GoogleAppEngine? | 1,274,035 | <p>I'm quite new to python and GAE, can anyone please provide some help/sample code for doing the following simple task? I managed to read a simple file and output it as a webpage but I need some slightly more complicated logic. Here is the pseudo code:</p>
<pre><code> open file;
for each line in file {
store first line as album title;
for each song read {
store first line as song title;
store second line as song URL;
}
}
Output the read in data as a json;
</code></pre>
<p>The file format will be something like this </p>
<p><em>Album title1<br> song1 title<br> song1 url<br> song2 title<br> song2 url<br> <br> Album title2<br> song1 title<br> song1 url<br> song2 title<br> song2 url<br> ..</em></p>
| 1 | 2009-08-13T19:19:05Z | 1,274,429 | <pre><code>from django.utils import simplejson
def albums(f):
"" yields lists of strings which are the
stripped lines for an album (blocks of
nonblank lines separated by blocks of
blank ones.
"""
while True:
# skip leading blank lines if any
for line in f:
if not line: return
line = line.strip()
if line: break
result = [line]
# read up to next blank line or EOF
for line in f:
if not line:
yield result
return
line = line.strip()
if not line: break
result.append(line)
yield result
def songs(album):
""" yields lists of 2 lines, one list per song.
"""
for i in xrange(1, len(album), 2):
yield (album[i:i+2] + ['??'])[:2]
result = dict()
f = open('thefile.txt')
for albumlines in albums(f):
current = result[albumlines[0]] = []
for songlines in songs(albumlines):
current.append( {
'songtitle': songlines[0],
'songurl': songlines[1]
} )
response.out.write(simplejson.dumps(result))
</code></pre>
| 1 | 2009-08-13T20:37:32Z | [
"python",
"google-app-engine",
"file-io"
] |
Why isn't assertRaises catching my Attribute Error using python unittest? | 1,274,047 | <p>I'm trying to run this test: <code>self.assertRaises(AttributeError, branch[0].childrennodes)</code>, and <code>branch[0</code>] does not have an attribute <code>childrennodes</code>, so it should be throwing an <code>AttributeError</code>, which the <code>assertRaises</code> should catch, but when I run the test, the test fails because it is throwing an <code>AttributeError</code>.</p>
<pre><code>Traceback (most recent call last):
File "/home/tttt/../tttt/tests.py", line 504, in test_get_categories_branch
self.assertRaises(AttributeError, branch[0].children_nodes)
AttributeError: 'Category' object has no attribute 'children_nodes'
</code></pre>
<p>Any ideas?</p>
| 18 | 2009-08-13T19:21:28Z | 1,274,141 | <p>I think its because assert raises only accepts a callable. It evalutes to see if the callable raises an exception, not if the statement itself does.</p>
<pre><code>self.assertRaises(AttributeError, getattr, branch[0], "childrennodes")
</code></pre>
<p>should work.</p>
<p>EDIT:</p>
<p>As THC4k correctly says it gathers the statements at collection time and will error then, not at testing time.</p>
<p>Also this is a reason why I like nose, it has a decorator (raises) that is useful and clearer for these kind of tests.</p>
<pre><code>@raises(AttributeError)
def test_1(self)
branch[0].childrennodes
</code></pre>
| 19 | 2009-08-13T19:38:39Z | [
"python",
"django",
"unit-testing"
] |
Why isn't assertRaises catching my Attribute Error using python unittest? | 1,274,047 | <p>I'm trying to run this test: <code>self.assertRaises(AttributeError, branch[0].childrennodes)</code>, and <code>branch[0</code>] does not have an attribute <code>childrennodes</code>, so it should be throwing an <code>AttributeError</code>, which the <code>assertRaises</code> should catch, but when I run the test, the test fails because it is throwing an <code>AttributeError</code>.</p>
<pre><code>Traceback (most recent call last):
File "/home/tttt/../tttt/tests.py", line 504, in test_get_categories_branch
self.assertRaises(AttributeError, branch[0].children_nodes)
AttributeError: 'Category' object has no attribute 'children_nodes'
</code></pre>
<p>Any ideas?</p>
| 18 | 2009-08-13T19:21:28Z | 2,267,788 | <p>When the test is running, before calling self.assertRaises, Python needs to find the value of all the method's arguments. In doing so, it evaluates <code>branch[0].children_nodes</code>, which raises an AttributeError. Since we haven't invoked assertRaises yet, this exception is not caught, causing the test to fail.</p>
<p>The solution is to wrap <code>branch[0].children_nodes</code> in a function or a lambda:</p>
<pre><code>self.assertRaises(AttributeError, lambda: branch[0].children_nodes)
</code></pre>
<p>assertRaises can also be used as a context manager (Since Python 2.7, or in PyPI package 'unittest2'):</p>
<pre><code>with self.assertRaises(AttributeError):
branch[0].children_nodes
# etc
</code></pre>
<p>This is nice because it can be used on arbitrary blocks of code in the middle of a test, rather than having to create a new function just to define the block of code to which it applies.</p>
<p>It can give you access to the raised exception for further processing, if needed:</p>
<pre><code>with self.assertRaises(AttributeError) as cm:
branch[0].children_nodes
self.assertEquals(cm.exception.special_attribute, 123)
</code></pre>
| 47 | 2010-02-15T17:41:07Z | [
"python",
"django",
"unit-testing"
] |
Why isn't assertRaises catching my Attribute Error using python unittest? | 1,274,047 | <p>I'm trying to run this test: <code>self.assertRaises(AttributeError, branch[0].childrennodes)</code>, and <code>branch[0</code>] does not have an attribute <code>childrennodes</code>, so it should be throwing an <code>AttributeError</code>, which the <code>assertRaises</code> should catch, but when I run the test, the test fails because it is throwing an <code>AttributeError</code>.</p>
<pre><code>Traceback (most recent call last):
File "/home/tttt/../tttt/tests.py", line 504, in test_get_categories_branch
self.assertRaises(AttributeError, branch[0].children_nodes)
AttributeError: 'Category' object has no attribute 'children_nodes'
</code></pre>
<p>Any ideas?</p>
| 18 | 2009-08-13T19:21:28Z | 38,149,257 | <p>pytest also has a similar decorator:</p>
<pre><code>from pytest import raises
def test_raising():
with raises(AttributeError):
branch[0].childrennodes
</code></pre>
| 1 | 2016-07-01T15:38:41Z | [
"python",
"django",
"unit-testing"
] |
How can I write 'n <<= 1' (Python) in PHP? | 1,274,493 | <p>I have the Python expression <code>n <<= 1</code> </p>
<p>How do you express this in PHP?</p>
| 1 | 2009-08-13T20:50:16Z | 1,274,505 | <p>It's the same operator in php. <code>$n <<= 1;</code></p>
| 5 | 2009-08-13T20:52:23Z | [
"php",
"python",
"operators",
"bitwise-operators"
] |
How can I write 'n <<= 1' (Python) in PHP? | 1,274,493 | <p>I have the Python expression <code>n <<= 1</code> </p>
<p>How do you express this in PHP?</p>
| 1 | 2009-08-13T20:50:16Z | 1,274,508 | <p><code>$n <<= 1;</code> is valid php</p>
| 2 | 2009-08-13T20:52:52Z | [
"php",
"python",
"operators",
"bitwise-operators"
] |
How can I write 'n <<= 1' (Python) in PHP? | 1,274,493 | <p>I have the Python expression <code>n <<= 1</code> </p>
<p>How do you express this in PHP?</p>
| 1 | 2009-08-13T20:50:16Z | 1,274,556 | <p>That statement is short for</p>
<pre><code>n = n << 1;
</code></pre>
<p>the << operator is means a bitwise shift left, by n positions. Its counterpart is >>, which means shift right by n. To visualize, say you have the value 5, and you want to shift it left by 2 positions. In binary:</p>
<pre><code>0000 0101 -> 5
shift left by 2:
0001 0100 -> 20
</code></pre>
<p>Basically, you shift all bits in the given direction, and pad with zeroes. More or less equivalent, if you don't have a bitwise shift operator (which is common in most, if not all languages), is multiplying by 2^n for shift left, and dividing by 2^n for shift right.</p>
<p>In the example, you can see that: 5 * 2^2 = 5 * 4 = 20.</p>
| 6 | 2009-08-13T21:02:51Z | [
"php",
"python",
"operators",
"bitwise-operators"
] |
How can I create a list of files in the current directory and its subdirectories with a given extension? | 1,274,506 | <p>I'm trying to generate a text file that has a list of all files in the current directory and all of its sub-directories with the extension <code>".asp"</code>. What would be the best way to do this?</p>
| 5 | 2009-08-13T20:52:27Z | 1,274,528 | <p>You'll want to use os.walk which will make that trivial.</p>
<pre><code>import os
asps = []
for root, dirs, files in os.walk(r'C:\web'):
for file in files:
if file.endswith('.asp'):
asps.append(file)
</code></pre>
| 11 | 2009-08-13T20:57:08Z | [
"python"
] |
How can I create a list of files in the current directory and its subdirectories with a given extension? | 1,274,506 | <p>I'm trying to generate a text file that has a list of all files in the current directory and all of its sub-directories with the extension <code>".asp"</code>. What would be the best way to do this?</p>
| 5 | 2009-08-13T20:52:27Z | 1,274,530 | <p>walk the tree with <a href="http://docs.python.org/library/os.html#os.walk" rel="nofollow"><code>os.walk</code></a> and filter content with <a href="http://docs.python.org/library/glob.html" rel="nofollow"><code>glob</code></a>:</p>
<pre><code>import os
import glob
asps = []
for root, dirs, files in os.walk('/path/to/dir'):
asps += glob.glob(os.path.join(root, '*.asp'))
</code></pre>
<p>or with <a href="http://docs.python.org/library/fnmatch.html#fnmatch.filter" rel="nofollow"><code>fnmatch.filter</code></a>:</p>
<pre><code>import fnmatch
for root, dirs, files in os.walk('/path/to/dir'):
asps += fnmatch.filter(files, '*.asp')
</code></pre>
| 3 | 2009-08-13T20:57:42Z | [
"python"
] |
I'm trying to figure out how to use dbus with pidgin | 1,274,869 | <p>My problem is I'm not sure how to interface them. Do I need to have pidgin installed in a particular way in order for dbus to interface with it? and if not does the pidgin gui have to be running in order for dbus to utilize it?</p>
| 4 | 2009-08-13T22:01:29Z | 1,274,904 | <p>As per <a href="http://forums.devshed.com/python-programming-11/dbus-with-pidgin-help-with-changing-messages-from-pointer-518436.html">this</a> source you could do the following :</p>
<pre><code>#!/usr/bin/env python
def cb_func(account, rec, message):
#change message here somehow?
print message
import dbus, gobject
from dbus.mainloop.glib import DBusGMainLoop
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
bus = dbus.SessionBus()
bus.add_signal_receiver(cb_func,
dbus_interface="im.pidgin.purple.PurpleInterface",
signal_name="SendingImMsg")
loop = gobject.MainLoop()
loop.run()
</code></pre>
<p>Probably you can get started with this lead.</p>
| 5 | 2009-08-13T22:12:43Z | [
"python",
"dbus"
] |
I'm trying to figure out how to use dbus with pidgin | 1,274,869 | <p>My problem is I'm not sure how to interface them. Do I need to have pidgin installed in a particular way in order for dbus to interface with it? and if not does the pidgin gui have to be running in order for dbus to utilize it?</p>
| 4 | 2009-08-13T22:01:29Z | 1,283,474 | <pre><code>import dbus
from dbus.mainloop.glib import DBusGMainLoop
main_loop = DBusGMainLoop()
session_bus = dbus.SessionBus(mainloop = main_loop)
obj = session_bus.get_object("im.pidgin.purple.PurpleService", "/im/pidgin/purple/PurpleObject")
purple = dbus.Interface(obj, "im.pidgin.purple.PurpleInterface")
</code></pre>
<p>Then you can use the purple object to call some methods like this:</p>
<pre><code>status = purple.PurpleSavedstatusNew("", current)
purple.PurpleSavedstatusSetMessage(status, message)
purple.PurpleSavedstatusActivate(status)
</code></pre>
| 4 | 2009-08-16T04:57:29Z | [
"python",
"dbus"
] |
I'm trying to figure out how to use dbus with pidgin | 1,274,869 | <p>My problem is I'm not sure how to interface them. Do I need to have pidgin installed in a particular way in order for dbus to interface with it? and if not does the pidgin gui have to be running in order for dbus to utilize it?</p>
| 4 | 2009-08-13T22:01:29Z | 1,587,278 | <p>A really useful tool to use when getting started with using DBUS to interface with Pidgin is <a href="https://fedorahosted.org/d-feet/" rel="nofollow">D-Feet</a>. You can see all the available methods you can call and even execute them directly from the GUI.</p>
| 2 | 2009-10-19T06:49:00Z | [
"python",
"dbus"
] |
I'm trying to figure out how to use dbus with pidgin | 1,274,869 | <p>My problem is I'm not sure how to interface them. Do I need to have pidgin installed in a particular way in order for dbus to interface with it? and if not does the pidgin gui have to be running in order for dbus to utilize it?</p>
| 4 | 2009-08-13T22:01:29Z | 1,589,096 | <p>You do not need to do any special configuration of Pidgin to use D-Bus, however it must be running if you want to use it. You can check the script I'm using to control Pidgin status from the NetworkManager-dispatcher (<a href="http://github.com/abbot/shredder/blob/master/pidgin-netstatus.py" rel="nofollow">part 1</a>, <a href="http://github.com/abbot/shredder/blob/master/98-pidgin.sh" rel="nofollow">part 2</a>) as a sample how to interface Pidgin via D-Bus from python.</p>
| 0 | 2009-10-19T14:45:52Z | [
"python",
"dbus"
] |
I'm trying to figure out how to use dbus with pidgin | 1,274,869 | <p>My problem is I'm not sure how to interface them. Do I need to have pidgin installed in a particular way in order for dbus to interface with it? and if not does the pidgin gui have to be running in order for dbus to utilize it?</p>
| 4 | 2009-08-13T22:01:29Z | 21,430,579 | <p>The code below has an example of showing the buddy list when it is hidden and another example of starting an IM conversation with a specific contact.</p>
<pre><code>import dbus
BUS_ARGS = ('im.pidgin.purple.PurpleService', '/im/pidgin/purple/PurpleObject')
obj = dbus.SessionBus().get_object(*BUS_ARGS)
purple = dbus.Interface(obj, 'im.pidgin.purple.PurpleInterface')
# show buddy list if it is hidden
purple.PurpleBlistSetVisible(1)
# start IM conversation with specific contact
account = purple.PurpleAccountsFindConnected('', '')
conversation = purple.PurpleConversationNew(1, account, 'alice@example.com')
</code></pre>
<p>I can recommend a number of useful resources relating to using dbus with pidgin:</p>
<ul>
<li><a href="http://arstechnica.com/information-technology/2007/05/pidgin-2-0/4/" rel="nofollow">Riding the D-Bus with Pidgin</a> - Has three separate python dbus examples.</li>
<li><a href="http://manpages.ubuntu.com/manpages/precise/man1/purple-remote.1.html" rel="nofollow">purple-remote</a> - It's a python script that was installed on my ubuntu machine when I installed pidgin. Its a single file and pretty easy to read through. </li>
<li><a href="http://dbus.freedesktop.org/doc/dbus-monitor.1.html" rel="nofollow">dbus-monitor</a> - Great program to monitor dbus calls. It can help you discover what calls are being used by programs you use when you can't find them documented.</li>
<li><a href="http://doc.qt.digia.com/4.6/qdbusviewer.html" rel="nofollow">qdbusviewer</a> - Great graphical tool that can list pidgins dbus methods. You can also call them from the tool itself.</li>
</ul>
<p><img src="http://i.stack.imgur.com/71mkm.png" alt="qdbusviewer"></p>
| 2 | 2014-01-29T12:03:22Z | [
"python",
"dbus"
] |
Returning None or a tuple and unpacking | 1,274,875 | <p>I am always annoyed by this fact:</p>
<pre><code>$ cat foo.py
def foo(flag):
if flag:
return (1,2)
else:
return None
first, second = foo(True)
first, second = foo(False)
$ python foo.py
Traceback (most recent call last):
File "foo.py", line 8, in <module>
first, second = foo(False)
TypeError: 'NoneType' object is not iterable
</code></pre>
<p>The fact is that in order to correctly unpack without troubles I have either to catch the TypeError or to have something like</p>
<pre><code>values = foo(False)
if values is not None:
first, second = values
</code></pre>
<p>Which is kind of annoying. Is there a trick to improve this situation (e.g. to so set both first and second to None without having foo returning (None, None)) or a suggestion about the best design strategy for cases like the one I present ? *variables maybe ?</p>
| 13 | 2009-08-13T22:03:19Z | 1,274,887 | <p>Well, you could do...</p>
<pre><code>first,second = foo(True) or (None,None)
first,second = foo(False) or (None,None)
</code></pre>
<p>but as far as I know there's no simpler way to expand None to fill in the entirety of a tuple.</p>
| 14 | 2009-08-13T22:06:25Z | [
"python",
"design",
"return-value"
] |
Returning None or a tuple and unpacking | 1,274,875 | <p>I am always annoyed by this fact:</p>
<pre><code>$ cat foo.py
def foo(flag):
if flag:
return (1,2)
else:
return None
first, second = foo(True)
first, second = foo(False)
$ python foo.py
Traceback (most recent call last):
File "foo.py", line 8, in <module>
first, second = foo(False)
TypeError: 'NoneType' object is not iterable
</code></pre>
<p>The fact is that in order to correctly unpack without troubles I have either to catch the TypeError or to have something like</p>
<pre><code>values = foo(False)
if values is not None:
first, second = values
</code></pre>
<p>Which is kind of annoying. Is there a trick to improve this situation (e.g. to so set both first and second to None without having foo returning (None, None)) or a suggestion about the best design strategy for cases like the one I present ? *variables maybe ?</p>
| 13 | 2009-08-13T22:03:19Z | 1,274,888 | <p>I don't think there's a trick. You can simplify your calling code to:</p>
<pre><code>values = foo(False)
if values:
first, second = values
</code></pre>
<p>or even:</p>
<pre><code>values = foo(False)
first, second = values or (first_default, second_default)
</code></pre>
<p>where first_default and second_default are values you'd give to first and second as defaults.</p>
| 7 | 2009-08-13T22:07:16Z | [
"python",
"design",
"return-value"
] |
Returning None or a tuple and unpacking | 1,274,875 | <p>I am always annoyed by this fact:</p>
<pre><code>$ cat foo.py
def foo(flag):
if flag:
return (1,2)
else:
return None
first, second = foo(True)
first, second = foo(False)
$ python foo.py
Traceback (most recent call last):
File "foo.py", line 8, in <module>
first, second = foo(False)
TypeError: 'NoneType' object is not iterable
</code></pre>
<p>The fact is that in order to correctly unpack without troubles I have either to catch the TypeError or to have something like</p>
<pre><code>values = foo(False)
if values is not None:
first, second = values
</code></pre>
<p>Which is kind of annoying. Is there a trick to improve this situation (e.g. to so set both first and second to None without having foo returning (None, None)) or a suggestion about the best design strategy for cases like the one I present ? *variables maybe ?</p>
| 13 | 2009-08-13T22:03:19Z | 1,274,908 | <p>I don't see what is wrong with returning (None,None). It is much cleaner than the solutions suggested here which involve far more changes in your code. </p>
<p>It also doesn't make sense that you want None to automagically be split into 2 variables.</p>
| 16 | 2009-08-13T22:14:14Z | [
"python",
"design",
"return-value"
] |
Returning None or a tuple and unpacking | 1,274,875 | <p>I am always annoyed by this fact:</p>
<pre><code>$ cat foo.py
def foo(flag):
if flag:
return (1,2)
else:
return None
first, second = foo(True)
first, second = foo(False)
$ python foo.py
Traceback (most recent call last):
File "foo.py", line 8, in <module>
first, second = foo(False)
TypeError: 'NoneType' object is not iterable
</code></pre>
<p>The fact is that in order to correctly unpack without troubles I have either to catch the TypeError or to have something like</p>
<pre><code>values = foo(False)
if values is not None:
first, second = values
</code></pre>
<p>Which is kind of annoying. Is there a trick to improve this situation (e.g. to so set both first and second to None without having foo returning (None, None)) or a suggestion about the best design strategy for cases like the one I present ? *variables maybe ?</p>
| 13 | 2009-08-13T22:03:19Z | 1,274,932 | <p>You should be careful with the <code>x or y</code> style of solution. They work, but they're a bit broader than your original specification. Essentially, what if <code>foo(True)</code> returns an empty tuple <code>()</code>? As long as you know that it's OK to treat that as <code>(None, None)</code>, you're good with the solutions provided.</p>
<p>If this were a common scenario, I'd probably write a utility function like:</p>
<pre><code># needs a better name! :)
def to_tup(t):
return t if t is not None else (None, None)
first, second = to_tup(foo(True))
first, second = to_tup(foo(False))
</code></pre>
| 2 | 2009-08-13T22:19:29Z | [
"python",
"design",
"return-value"
] |
Returning None or a tuple and unpacking | 1,274,875 | <p>I am always annoyed by this fact:</p>
<pre><code>$ cat foo.py
def foo(flag):
if flag:
return (1,2)
else:
return None
first, second = foo(True)
first, second = foo(False)
$ python foo.py
Traceback (most recent call last):
File "foo.py", line 8, in <module>
first, second = foo(False)
TypeError: 'NoneType' object is not iterable
</code></pre>
<p>The fact is that in order to correctly unpack without troubles I have either to catch the TypeError or to have something like</p>
<pre><code>values = foo(False)
if values is not None:
first, second = values
</code></pre>
<p>Which is kind of annoying. Is there a trick to improve this situation (e.g. to so set both first and second to None without having foo returning (None, None)) or a suggestion about the best design strategy for cases like the one I present ? *variables maybe ?</p>
| 13 | 2009-08-13T22:03:19Z | 1,274,945 | <pre><code>def foo(flag):
return ((1,2) if flag else (None, None))
</code></pre>
| 1 | 2009-08-13T22:22:15Z | [
"python",
"design",
"return-value"
] |
Returning None or a tuple and unpacking | 1,274,875 | <p>I am always annoyed by this fact:</p>
<pre><code>$ cat foo.py
def foo(flag):
if flag:
return (1,2)
else:
return None
first, second = foo(True)
first, second = foo(False)
$ python foo.py
Traceback (most recent call last):
File "foo.py", line 8, in <module>
first, second = foo(False)
TypeError: 'NoneType' object is not iterable
</code></pre>
<p>The fact is that in order to correctly unpack without troubles I have either to catch the TypeError or to have something like</p>
<pre><code>values = foo(False)
if values is not None:
first, second = values
</code></pre>
<p>Which is kind of annoying. Is there a trick to improve this situation (e.g. to so set both first and second to None without having foo returning (None, None)) or a suggestion about the best design strategy for cases like the one I present ? *variables maybe ?</p>
| 13 | 2009-08-13T22:03:19Z | 1,275,055 | <p>I think there is a problem of <strong>abstraction</strong>. </p>
<p>A function should maintain some level of abstraction, that helps in reducing complexity of the code.<br />
In this case, either the function is not maintaining the right abstraction, either the caller is not respecting it.</p>
<p>The function could have been something like <code>get_point2d()</code>; in this case, the level of the abstraction is on the tuple, and therefore returning None would be a good way to signal some particular case (e.g. non-existing entity). The error in this case would be to expect two items, while actually the only thing you know is that the function returns one object (with information related to a 2d point). </p>
<p>But it could also have been something like <code>get_two_values_from_db()</code>; in this case the abstraction would be broken by returning None, because the function (as the name suggest) <em>should return two values and not one</em>!</p>
<p>Either way, the main goal of using a function - reducing complexity - is, at least partially, lost. </p>
<p>Note that this issue would not appear clearly with the original name; that's also why it is always important to give good names to function and methods.</p>
| 11 | 2009-08-13T22:45:50Z | [
"python",
"design",
"return-value"
] |
Returning None or a tuple and unpacking | 1,274,875 | <p>I am always annoyed by this fact:</p>
<pre><code>$ cat foo.py
def foo(flag):
if flag:
return (1,2)
else:
return None
first, second = foo(True)
first, second = foo(False)
$ python foo.py
Traceback (most recent call last):
File "foo.py", line 8, in <module>
first, second = foo(False)
TypeError: 'NoneType' object is not iterable
</code></pre>
<p>The fact is that in order to correctly unpack without troubles I have either to catch the TypeError or to have something like</p>
<pre><code>values = foo(False)
if values is not None:
first, second = values
</code></pre>
<p>Which is kind of annoying. Is there a trick to improve this situation (e.g. to so set both first and second to None without having foo returning (None, None)) or a suggestion about the best design strategy for cases like the one I present ? *variables maybe ?</p>
| 13 | 2009-08-13T22:03:19Z | 1,275,323 | <p>How about this:</p>
<pre><code>$ cat foo.py
def foo(flag):
if flag:
return (1,2)
else:
return (None,)*2
first, second = foo(True)
first, second = foo(False)
</code></pre>
<p><strong>Edit:</strong> Just to be clear, the only change is to replace <code>return None</code> with <code>return (None,)*2</code>. I am extremely surprised that no one else has thought of this. (Or if they have, I would like to know why they didn't use it.)</p>
| 1 | 2009-08-13T23:54:49Z | [
"python",
"design",
"return-value"
] |
Returning None or a tuple and unpacking | 1,274,875 | <p>I am always annoyed by this fact:</p>
<pre><code>$ cat foo.py
def foo(flag):
if flag:
return (1,2)
else:
return None
first, second = foo(True)
first, second = foo(False)
$ python foo.py
Traceback (most recent call last):
File "foo.py", line 8, in <module>
first, second = foo(False)
TypeError: 'NoneType' object is not iterable
</code></pre>
<p>The fact is that in order to correctly unpack without troubles I have either to catch the TypeError or to have something like</p>
<pre><code>values = foo(False)
if values is not None:
first, second = values
</code></pre>
<p>Which is kind of annoying. Is there a trick to improve this situation (e.g. to so set both first and second to None without having foo returning (None, None)) or a suggestion about the best design strategy for cases like the one I present ? *variables maybe ?</p>
| 13 | 2009-08-13T22:03:19Z | 1,275,693 | <p>OK, I would just return (None, None), but as long as we are in whacko-land (heh), here is a way using a subclass of tuple. In the else case, you don't return None, but instead return an empty container, which seems to be in the spirit of things. The container's "iterator" unpacks None values when empty. Demonstrates the iterator protocol anyway...</p>
<p>Tested using v2.5.2:</p>
<pre><code>class Tuple(tuple):
def __iter__(self):
if self:
# If Tuple has contents, return normal tuple iterator...
return super(Tuple, self).__iter__()
else:
# Else return a bogus iterator that returns None twice...
class Nonerizer(object):
def __init__(self):
self.x=0
def __iter__(self):
return self
def next(self):
if self.x < 2:
self.x += 1
return None
else:
raise StopIteration
return Nonerizer()
def foo(flag):
if flag:
return Tuple((1,2))
else:
return Tuple() # It's not None, but it's an empty container.
first, second = foo(True)
print first, second
first, second = foo(False)
print first, second
</code></pre>
<p>Output is the desired:</p>
<pre><code>1 2
None None
</code></pre>
| 1 | 2009-08-14T02:07:09Z | [
"python",
"design",
"return-value"
] |
collapsing whitespace in a string | 1,274,906 | <p>I have a string that kind of looks like this:</p>
<pre><code>"stuff . // : /// more-stuff .. .. ...$%$% stuff -> DD"
</code></pre>
<p>and I want to strip off all punctuation, make everything uppercase and collapse all whitespace so that it looks like this:</p>
<pre><code>"STUFF MORE STUFF STUFF DD"
</code></pre>
<p>Is this possible with one regex or do I need to combine more than two? This is what I have so far:</p>
<pre><code>def normalize(string):
import re
string = string.upper()
rex = re.compile(r'\W')
rex_s = re.compile(r'\s{2,}')
result = rex.sub(' ', string) # this produces a string with tons of whitespace padding
result = rex.sub('', result) # this reduces all those spaces
return result
</code></pre>
<p>The only thing that doesn't work is the whitespace collapsing. Any ideas?</p>
| 3 | 2009-08-13T22:13:50Z | 1,274,913 | <pre><code>result = rex.sub(' ', string) # this produces a string with tons of whitespace padding
result = rex.sub('', result) # this reduces all those spaces
</code></pre>
<p>Because you typo'd and forgot to use rex_s for the second call instead. Also, you need to substitute at least one space back in or you'll end up with any multiple-space gap becoming no gap at all, instead of a single-space gap.</p>
<pre><code>result = rex.sub(' ', string) # this produces a string with tons of whitespace padding
result = rex_s.sub(' ', result) # this reduces all those spaces
</code></pre>
| 3 | 2009-08-13T22:15:08Z | [
"python",
"regex"
] |
collapsing whitespace in a string | 1,274,906 | <p>I have a string that kind of looks like this:</p>
<pre><code>"stuff . // : /// more-stuff .. .. ...$%$% stuff -> DD"
</code></pre>
<p>and I want to strip off all punctuation, make everything uppercase and collapse all whitespace so that it looks like this:</p>
<pre><code>"STUFF MORE STUFF STUFF DD"
</code></pre>
<p>Is this possible with one regex or do I need to combine more than two? This is what I have so far:</p>
<pre><code>def normalize(string):
import re
string = string.upper()
rex = re.compile(r'\W')
rex_s = re.compile(r'\s{2,}')
result = rex.sub(' ', string) # this produces a string with tons of whitespace padding
result = rex.sub('', result) # this reduces all those spaces
return result
</code></pre>
<p>The only thing that doesn't work is the whitespace collapsing. Any ideas?</p>
| 3 | 2009-08-13T22:13:50Z | 1,274,918 | <p>Here's a single-step approach (but the uppercasing actually uses a string method -- much simpler!-):</p>
<pre><code>rex = re.compile(r'\W+')
result = rex.sub(' ', strarg).upper()
</code></pre>
<p>where <code>strarg</code> is the string argument (<em>don't</em> use names that shadow builtins or standard library modules, <em>please</em> ... pretty please?-)</p>
| 14 | 2009-08-13T22:15:59Z | [
"python",
"regex"
] |
collapsing whitespace in a string | 1,274,906 | <p>I have a string that kind of looks like this:</p>
<pre><code>"stuff . // : /// more-stuff .. .. ...$%$% stuff -> DD"
</code></pre>
<p>and I want to strip off all punctuation, make everything uppercase and collapse all whitespace so that it looks like this:</p>
<pre><code>"STUFF MORE STUFF STUFF DD"
</code></pre>
<p>Is this possible with one regex or do I need to combine more than two? This is what I have so far:</p>
<pre><code>def normalize(string):
import re
string = string.upper()
rex = re.compile(r'\W')
rex_s = re.compile(r'\s{2,}')
result = rex.sub(' ', string) # this produces a string with tons of whitespace padding
result = rex.sub('', result) # this reduces all those spaces
return result
</code></pre>
<p>The only thing that doesn't work is the whitespace collapsing. Any ideas?</p>
| 3 | 2009-08-13T22:13:50Z | 1,275,019 | <p>Do you have to use regular expressions? Do you feel you must do it in one line?</p>
<pre><code>>>> import string
>>> s = "stuff . // : /// more-stuff .. .. ...$%$% stuff -> DD"
>>> s2 = ''.join(c for c in s if c in string.letters + ' ')
>>> ' '.join(s2.split())
'stuff morestuff stuff DD'
</code></pre>
| 1 | 2009-08-13T22:38:39Z | [
"python",
"regex"
] |
collapsing whitespace in a string | 1,274,906 | <p>I have a string that kind of looks like this:</p>
<pre><code>"stuff . // : /// more-stuff .. .. ...$%$% stuff -> DD"
</code></pre>
<p>and I want to strip off all punctuation, make everything uppercase and collapse all whitespace so that it looks like this:</p>
<pre><code>"STUFF MORE STUFF STUFF DD"
</code></pre>
<p>Is this possible with one regex or do I need to combine more than two? This is what I have so far:</p>
<pre><code>def normalize(string):
import re
string = string.upper()
rex = re.compile(r'\W')
rex_s = re.compile(r'\s{2,}')
result = rex.sub(' ', string) # this produces a string with tons of whitespace padding
result = rex.sub('', result) # this reduces all those spaces
return result
</code></pre>
<p>The only thing that doesn't work is the whitespace collapsing. Any ideas?</p>
| 3 | 2009-08-13T22:13:50Z | 1,275,406 | <pre><code>s = "$$$aa1bb2 cc-dd ee_ff ggg."
re.sub(r'\W+', ' ', s).upper()
# ' AA1BB2 CC DD EE_FF GGG '
</code></pre>
<p>Is _ punctuation?</p>
<pre><code>re.sub(r'[_\W]+', ' ', s).upper()
# ' AA1BB2 CC DD EE FF GGG '
</code></pre>
<p>Don't want the leading and trailing space?</p>
<pre><code>re.sub(r'[_\W]+', ' ', s).strip().upper()
# 'AA1BB2 CC DD EE FF GGG'
</code></pre>
| 3 | 2009-08-14T00:23:59Z | [
"python",
"regex"
] |
collapsing whitespace in a string | 1,274,906 | <p>I have a string that kind of looks like this:</p>
<pre><code>"stuff . // : /// more-stuff .. .. ...$%$% stuff -> DD"
</code></pre>
<p>and I want to strip off all punctuation, make everything uppercase and collapse all whitespace so that it looks like this:</p>
<pre><code>"STUFF MORE STUFF STUFF DD"
</code></pre>
<p>Is this possible with one regex or do I need to combine more than two? This is what I have so far:</p>
<pre><code>def normalize(string):
import re
string = string.upper()
rex = re.compile(r'\W')
rex_s = re.compile(r'\s{2,}')
result = rex.sub(' ', string) # this produces a string with tons of whitespace padding
result = rex.sub('', result) # this reduces all those spaces
return result
</code></pre>
<p>The only thing that doesn't work is the whitespace collapsing. Any ideas?</p>
| 3 | 2009-08-13T22:13:50Z | 22,213,412 | <p>works in python3 this will retain the same whitespace character you collapsed. So if you have a tab and a space next to each other they wont collapse into a single character.</p>
<pre><code>def collapse_whitespace_characters(raw_text):
ret = ''
if len(raw_text) > 1:
prev_char = raw_text[0]
ret += prev_char
for cur_char in raw_text[1:]:
if not cur_char.isspace() or cur_char != prev_char:
ret += cur_char
prev_char = cur_char
else:
ret = raw_text
return ret
</code></pre>
<p>this one will collapse whitespace sets into the first whitespace character it sees</p>
<pre><code>def collapse_whitespace(raw_text):
ret = ''
if len(raw_text) > 1:
prev_char = raw_text[0]
ret += prev_char
for cur_char in raw_text[1:]:
if not cur_char.isspace() or \
(cur_char.isspace() and not prev_char.isspace()):
ret += cur_char
prev_char = cur_char
else:
ret = raw_text
return ret
</code></pre>
<p>>>> collapse_whitespace_characters('we like spaces and\t\t TABS AND WHATEVER\xa0\xa0IS')<br/>
'we like spaces and\t TABS\tAND WHATEVER\xa0IS'
<br/><br/>
>>> collapse_whitespace('we like spaces and\t\t TABS AND WHATEVER\xa0\xa0IS')
<br/>
'we like spaces and\tTABS\tAND WHATEVER\xa0IS'</p>
<p>for punctuation</p>
<pre><code>def collapse_punctuation(raw_text):
ret = ''
if len(raw_text) > 1:
prev_char = raw_text[0]
ret += prev_char
for cur_char in raw_text[1:]:
if cur_char.isalnum() or cur_char != prev_char:
ret += cur_char
prev_char = cur_char
else:
ret = raw_text
return ret
</code></pre>
<p>to actually answer the question</p>
<pre><code>orig = 'stuff . // : /// more-stuff .. .. ...$%$% stuff -> DD'
collapse_whitespace(''.join([(c.upper() if c.isalnum() else ' ') for c in orig]))
</code></pre>
<p>as said, the regexp would be something like</p>
<pre><code>re.sub('\W+', ' ', orig).upper()
</code></pre>
| 1 | 2014-03-06T02:05:22Z | [
"python",
"regex"
] |
Eliminate part of a file in python | 1,274,941 | <p>In the below file I have 3 occurrences of '.1'. I want to eliminate the last one and write the rest of file to a new file. Kindly suggest some way to do it in PYTHON and thank you all.</p>
<blockquote>
<p>d1dlwa_ a.1.1.1 (A:) Protozoan/bacterial hemoglobin {Ciliate (Paramecium caudatum) [TaxId: 5885]}
slfeqlggqaavqavtaqfyaniqadatvatffngidmpnqtnktaaflcaalggpnawt</p>
</blockquote>
| 1 | 2009-08-13T22:21:00Z | 1,274,958 | <p>If the file's not too horrendously huge, by far the simplest approach is:</p>
<pre><code>f = open('oldfile', 'r')
data = f.read()
f.close()
data = data.replace('.1.1.1', '.1.1')
f = open('newfile', 'w')
f.write(data)
f.close()
</code></pre>
<p>If the file IS horrendously huge, you'll need to read it and write it by pieces. For example, if each <em>line</em> ISN'T too horrendously huge:</p>
<pre><code>inf = open('oldfile', 'r')
ouf = open('newfile', 'w')
for line in inf:
line = line.replace('.1.1.1', '.1.1')
ouf.write(line)
ouf.close()
inf.close()
</code></pre>
| 7 | 2009-08-13T22:24:35Z | [
"python",
"file"
] |
Eliminate part of a file in python | 1,274,941 | <p>In the below file I have 3 occurrences of '.1'. I want to eliminate the last one and write the rest of file to a new file. Kindly suggest some way to do it in PYTHON and thank you all.</p>
<blockquote>
<p>d1dlwa_ a.1.1.1 (A:) Protozoan/bacterial hemoglobin {Ciliate (Paramecium caudatum) [TaxId: 5885]}
slfeqlggqaavqavtaqfyaniqadatvatffngidmpnqtnktaaflcaalggpnawt</p>
</blockquote>
| 1 | 2009-08-13T22:21:00Z | 1,274,960 | <p>You can have something like this :</p>
<pre><code>
line = line.split(" ")
line[0] = line[0][0:line[0].rindex(".")]
print " ".join(line)
</code></pre>
<p>Not the prettiest code, but from my console tests, it works.</p>
| 0 | 2009-08-13T22:24:51Z | [
"python",
"file"
] |
Eliminate part of a file in python | 1,274,941 | <p>In the below file I have 3 occurrences of '.1'. I want to eliminate the last one and write the rest of file to a new file. Kindly suggest some way to do it in PYTHON and thank you all.</p>
<blockquote>
<p>d1dlwa_ a.1.1.1 (A:) Protozoan/bacterial hemoglobin {Ciliate (Paramecium caudatum) [TaxId: 5885]}
slfeqlggqaavqavtaqfyaniqadatvatffngidmpnqtnktaaflcaalggpnawt</p>
</blockquote>
| 1 | 2009-08-13T22:21:00Z | 1,274,969 | <p>Works with any size file:</p>
<pre><code>open('newfile', 'w').writelines(line.replace('.1.1.1', '.1.1')
for line in open('oldfile'))
</code></pre>
| 4 | 2009-08-13T22:28:23Z | [
"python",
"file"
] |
Does django's Form class maintain state? | 1,275,009 | <p>I'm building my first form with django, and I'm seeing some behavior that I really did not expect at all. I defined a form class:</p>
<pre><code>class AssignmentFilterForm(forms.Form):
filters = []
filter = forms.ChoiceField()
def __init__(self, *args, **kwargs):
super(forms.Form, self).__init__(*args, **kwargs)
self.filters.append(PatientFilter('All'))
self.filters.append(PatientFilter('Assigned', 'service__isnull', False))
self.filters.append(PatientFilter('Unassigned', 'service__isnull', True))
for i, f in enumerate(self.filters):
self.fields["filter"].choices.append((i, f.name))
</code></pre>
<p>When I output this form to a template using:</p>
<pre><code>{{ form.as_p }}
</code></pre>
<p>I see the correct choices. However, after refreshing the page, I see the list three times in the select box. Hitting refresh again results in the list showing 10 times in the select box! </p>
<p>Here is my view:</p>
<pre><code>@login_required
def assign_test(request):
pg = PhysicianGroup.objects.get(pk=physician_group)
if request.method == 'POST':
form = AssignmentFilterForm(request.POST)
if form.is_valid():
yes = False
else:
form = AssignmentFilterForm()
patients = pg.allPatients().order_by('bed__room__unit', 'bed__room__order', 'bed__order' )
return render_to_response('hospitalists/assign_test.html', RequestContext(request, {'patients': patients, 'form': form,}))
</code></pre>
<p>What am I doing wrong?</p>
<p>Thanks, Pete</p>
| 0 | 2009-08-13T22:35:35Z | 1,275,057 | <p>You're appending to the PER-CLASS variable self.filters. Make it into a PER-INSTANCE variable instead, by doing <code>self.filters = []</code> at the start of <code>__init__</code>.</p>
| 1 | 2009-08-13T22:46:18Z | [
"python",
"django"
] |
Does django's Form class maintain state? | 1,275,009 | <p>I'm building my first form with django, and I'm seeing some behavior that I really did not expect at all. I defined a form class:</p>
<pre><code>class AssignmentFilterForm(forms.Form):
filters = []
filter = forms.ChoiceField()
def __init__(self, *args, **kwargs):
super(forms.Form, self).__init__(*args, **kwargs)
self.filters.append(PatientFilter('All'))
self.filters.append(PatientFilter('Assigned', 'service__isnull', False))
self.filters.append(PatientFilter('Unassigned', 'service__isnull', True))
for i, f in enumerate(self.filters):
self.fields["filter"].choices.append((i, f.name))
</code></pre>
<p>When I output this form to a template using:</p>
<pre><code>{{ form.as_p }}
</code></pre>
<p>I see the correct choices. However, after refreshing the page, I see the list three times in the select box. Hitting refresh again results in the list showing 10 times in the select box! </p>
<p>Here is my view:</p>
<pre><code>@login_required
def assign_test(request):
pg = PhysicianGroup.objects.get(pk=physician_group)
if request.method == 'POST':
form = AssignmentFilterForm(request.POST)
if form.is_valid():
yes = False
else:
form = AssignmentFilterForm()
patients = pg.allPatients().order_by('bed__room__unit', 'bed__room__order', 'bed__order' )
return render_to_response('hospitalists/assign_test.html', RequestContext(request, {'patients': patients, 'form': form,}))
</code></pre>
<p>What am I doing wrong?</p>
<p>Thanks, Pete</p>
| 0 | 2009-08-13T22:35:35Z | 1,275,174 | <p>This is actually a feature of Python that catches a lot of people.</p>
<p>When you define variables on the class as you have with <code>filters = []</code> the right half of the expression is evaluated when the class is initially defined. So when your code is first run it will create a new list in memory and return a reference to this list. As a result, each <code>AssignmentFilterForm</code> instance will have its own filters variable, but they will all point to this same list in memory. To solve this just move the initialization of <code>self.filters</code> into your <code>__init__</code> method.</p>
<p>Most of the time you don't run into this issue because the types you are using aren't stored as a reference. Numbers, booleans, etc are stored as their value. Strings are stored by reference, but strings are immutable meaning a new string must be created in memory every time it is changed and a new reference returned.</p>
<p>Pointers don't present themselves often in scripting language, so it's often confusing at first when they do.</p>
<p>Here's a simple IDLE session example to show what's happening</p>
<pre><code>>>> class Test():
myList = []
def __init__( self ):
self.myList.append( "a" )
>>> Test.myList
[]
>>> test1 = Test()
>>> Test.myList
['a']
>>> test1.myList
['a']
>>> test2 = Test()
>>> test2.myList
['a', 'a']
>>> test1.myList
['a', 'a']
>>> Test.myList
['a', 'a']
</code></pre>
| 7 | 2009-08-13T23:12:50Z | [
"python",
"django"
] |
Does django's Form class maintain state? | 1,275,009 | <p>I'm building my first form with django, and I'm seeing some behavior that I really did not expect at all. I defined a form class:</p>
<pre><code>class AssignmentFilterForm(forms.Form):
filters = []
filter = forms.ChoiceField()
def __init__(self, *args, **kwargs):
super(forms.Form, self).__init__(*args, **kwargs)
self.filters.append(PatientFilter('All'))
self.filters.append(PatientFilter('Assigned', 'service__isnull', False))
self.filters.append(PatientFilter('Unassigned', 'service__isnull', True))
for i, f in enumerate(self.filters):
self.fields["filter"].choices.append((i, f.name))
</code></pre>
<p>When I output this form to a template using:</p>
<pre><code>{{ form.as_p }}
</code></pre>
<p>I see the correct choices. However, after refreshing the page, I see the list three times in the select box. Hitting refresh again results in the list showing 10 times in the select box! </p>
<p>Here is my view:</p>
<pre><code>@login_required
def assign_test(request):
pg = PhysicianGroup.objects.get(pk=physician_group)
if request.method == 'POST':
form = AssignmentFilterForm(request.POST)
if form.is_valid():
yes = False
else:
form = AssignmentFilterForm()
patients = pg.allPatients().order_by('bed__room__unit', 'bed__room__order', 'bed__order' )
return render_to_response('hospitalists/assign_test.html', RequestContext(request, {'patients': patients, 'form': form,}))
</code></pre>
<p>What am I doing wrong?</p>
<p>Thanks, Pete</p>
| 0 | 2009-08-13T22:35:35Z | 1,275,451 | <p>As answered above, you need to initialize filters as an instance variable:</p>
<pre><code>def __init__(...):
self.filters = []
self.filters.append(...)
# ...
</code></pre>
<p>If you want to know more about how the Form class works, you should read this page in the Django wiki:</p>
<ul>
<li><a href="http://code.djangoproject.com/wiki/DevModelCreation" rel="nofollow">Model Creation and Initialization</a></li>
</ul>
<p>It talks about the internals of the Model class, but you'll find the general setup of fields is somewhat similar to the Form (minus the database stuff). It's a bit dated (2006), but I think the basic principles still apply. The metaclass stuff can be a bit confusing if you're new though.</p>
| 0 | 2009-08-14T00:37:13Z | [
"python",
"django"
] |
Does django's Form class maintain state? | 1,275,009 | <p>I'm building my first form with django, and I'm seeing some behavior that I really did not expect at all. I defined a form class:</p>
<pre><code>class AssignmentFilterForm(forms.Form):
filters = []
filter = forms.ChoiceField()
def __init__(self, *args, **kwargs):
super(forms.Form, self).__init__(*args, **kwargs)
self.filters.append(PatientFilter('All'))
self.filters.append(PatientFilter('Assigned', 'service__isnull', False))
self.filters.append(PatientFilter('Unassigned', 'service__isnull', True))
for i, f in enumerate(self.filters):
self.fields["filter"].choices.append((i, f.name))
</code></pre>
<p>When I output this form to a template using:</p>
<pre><code>{{ form.as_p }}
</code></pre>
<p>I see the correct choices. However, after refreshing the page, I see the list three times in the select box. Hitting refresh again results in the list showing 10 times in the select box! </p>
<p>Here is my view:</p>
<pre><code>@login_required
def assign_test(request):
pg = PhysicianGroup.objects.get(pk=physician_group)
if request.method == 'POST':
form = AssignmentFilterForm(request.POST)
if form.is_valid():
yes = False
else:
form = AssignmentFilterForm()
patients = pg.allPatients().order_by('bed__room__unit', 'bed__room__order', 'bed__order' )
return render_to_response('hospitalists/assign_test.html', RequestContext(request, {'patients': patients, 'form': form,}))
</code></pre>
<p>What am I doing wrong?</p>
<p>Thanks, Pete</p>
| 0 | 2009-08-13T22:35:35Z | 1,276,608 | <p>To clarify from some of the other answers:</p>
<p>The fields are, and must be, class variables. They get all sorts of things done to them by the metaclass, and this is the correct way to define them.</p>
<p>However, your <code>filters</code> variable does not need to be a class var. It can quite easily be an instance var - just remove the definition from the class and put it in <code>__init__</code>. Or, perhaps even better, don't make it a property at all - just a local var within <code>__init__</code>. Then, instead of appending to <code>filters.choices</code>, just reassign it.</p>
<pre><code>def __init__(self, *args, **kwargs):
super(forms.Form, self).__init__(*args, **kwargs)
filters = []
filters.append(PatientFilter('All'))
filters.append(PatientFilter('Assigned', 'service__isnull', False))
filters.append(PatientFilter('Unassigned', 'service__isnull', True))
self.fields["filter"].choices = [(i, f.name) for i, f in enumerate(filters)]
</code></pre>
| 0 | 2009-08-14T08:05:47Z | [
"python",
"django"
] |
Does django's Form class maintain state? | 1,275,009 | <p>I'm building my first form with django, and I'm seeing some behavior that I really did not expect at all. I defined a form class:</p>
<pre><code>class AssignmentFilterForm(forms.Form):
filters = []
filter = forms.ChoiceField()
def __init__(self, *args, **kwargs):
super(forms.Form, self).__init__(*args, **kwargs)
self.filters.append(PatientFilter('All'))
self.filters.append(PatientFilter('Assigned', 'service__isnull', False))
self.filters.append(PatientFilter('Unassigned', 'service__isnull', True))
for i, f in enumerate(self.filters):
self.fields["filter"].choices.append((i, f.name))
</code></pre>
<p>When I output this form to a template using:</p>
<pre><code>{{ form.as_p }}
</code></pre>
<p>I see the correct choices. However, after refreshing the page, I see the list three times in the select box. Hitting refresh again results in the list showing 10 times in the select box! </p>
<p>Here is my view:</p>
<pre><code>@login_required
def assign_test(request):
pg = PhysicianGroup.objects.get(pk=physician_group)
if request.method == 'POST':
form = AssignmentFilterForm(request.POST)
if form.is_valid():
yes = False
else:
form = AssignmentFilterForm()
patients = pg.allPatients().order_by('bed__room__unit', 'bed__room__order', 'bed__order' )
return render_to_response('hospitalists/assign_test.html', RequestContext(request, {'patients': patients, 'form': form,}))
</code></pre>
<p>What am I doing wrong?</p>
<p>Thanks, Pete</p>
| 0 | 2009-08-13T22:35:35Z | 1,284,510 | <p>I picked up the book Pro Django which answers this question. It's a great book by the way, and I highly recommend it!</p>
<p>The solution is to make BOTH the choice field and my helper var both instance variables:</p>
<pre><code>class AssignmentFilterForm(forms.Form):
def __init__(self, pg, request = None):
super(forms.Form, self).__init__(request)
self.filters = []
self.filters.append(PatientFilter('All'))
self.filters.append(PatientFilter('Assigned', 'service__isnull', False))
self.filters.append(PatientFilter('Unassigned', 'service__isnull', True))
self.addPhysicians(pg)
self.fields['filter'] = forms.ChoiceField()
for i, f in enumerate(self.filters):
self.fields['filter'].choices.append((i, f.name))
</code></pre>
<p>Clearing out the choices works but would surely result in threading issues. </p>
| 1 | 2009-08-16T15:15:13Z | [
"python",
"django"
] |
How to use Staticgenerator with Django + Apache + mod_python | 1,275,270 | <p>I have currently an enviroment with Django + Apache via mod_python. How can I use <a href="http://superjared.com/projects/static-generator/" rel="nofollow" title="Staticgenerator">Staticgenerator</a> without nginx, just with Apache and mod_python? Thank you.</p>
| 2 | 2009-08-13T23:35:37Z | 1,275,299 | <p>Perhaps this page from the webfaction forum will help:</p>
<ul>
<li><a href="http://forum.webfaction.com/viewtopic.php?id=1945" rel="nofollow">http://forum.webfaction.com/viewtopic.php?id=1945</a></li>
</ul>
| 0 | 2009-08-13T23:48:10Z | [
"python",
"django",
"apache",
"mod-python"
] |
How to use Staticgenerator with Django + Apache + mod_python | 1,275,270 | <p>I have currently an enviroment with Django + Apache via mod_python. How can I use <a href="http://superjared.com/projects/static-generator/" rel="nofollow" title="Staticgenerator">Staticgenerator</a> without nginx, just with Apache and mod_python? Thank you.</p>
| 2 | 2009-08-13T23:35:37Z | 2,000,049 | <p><a href="http://superjared.com/projects/static-generator/" rel="nofollow">Staticgenerator</a> is designed to be used with a front-end http server. The example configuration as shown on the <a href="http://github.com/JaredKuolt/staticgenerator" rel="nofollow">Github Staticgenerator</a> page is using <a href="http://nginx.org/" rel="nofollow">Nginx</a> as the front-end http server and <a href="http://httpd.apache.org/" rel="nofollow">Apache</a> as the back-end http server.</p>
<p>If you want a static website generator that isn't specifically designed to be used with a front-end http server, you might want to look at <a href="http://github.com/lakshmivyas/hyde" rel="nofollow">Hyde</a>. <a href="http://github.com/lakshmivyas/hyde" rel="nofollow">Hyde</a> is Django powered and statically generates the webpages, which are then placed in a deploy directory. <a href="http://github.com/lakshmivyas/hyde" rel="nofollow">Hyde</a> came out of the developer, <a href="http://github.com/lakshmivyas/" rel="nofollow">Lakshmi Vyas</a>, wanting a Django based <a href="http://github.com/mojombo/jekyll" rel="nofollow">Jekyll</a>, which is a static website generator written in Ruby. Lakshmi Vyas did look into <a href="http://superjared.com/projects/static-generator/" rel="nofollow">Staticgenerator</a> prior to developing <a href="http://github.com/lakshmivyas/hyde" rel="nofollow">Hyde</a> but decided to roll his own.</p>
| 0 | 2010-01-04T15:01:10Z | [
"python",
"django",
"apache",
"mod-python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.