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
list |
|---|---|---|---|---|---|---|---|---|---|
Iterate over a python sequence in multiples of n?
| 760,753
|
<p>How do I process the elements of a sequence in batches, idiomatically?</p>
<p>For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:</p>
<pre><code>for x, y in "abcdef":
print "%s%s\n" % (x, y)
ab
cd
ef
</code></pre>
<p>Of course, this doesn't work because it is expecting a single element from the list which itself contains 2 elements.</p>
<p>What is a nice, short, clean, pythonic way to process the next n elements of a list in a batch, or sub-strings of length n from a larger string (two similar problems)?</p>
| 17
|
2009-04-17T15:01:35Z
| 1,398,649
|
<pre><code>
s = 'abcdefgh'
for e in (s[i:i+2] for i in range(0,len(s),2)):
print(e)
</code></pre>
| 1
|
2009-09-09T09:52:09Z
|
[
"iteration",
"python"
] |
Iterate over a python sequence in multiples of n?
| 760,753
|
<p>How do I process the elements of a sequence in batches, idiomatically?</p>
<p>For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:</p>
<pre><code>for x, y in "abcdef":
print "%s%s\n" % (x, y)
ab
cd
ef
</code></pre>
<p>Of course, this doesn't work because it is expecting a single element from the list which itself contains 2 elements.</p>
<p>What is a nice, short, clean, pythonic way to process the next n elements of a list in a batch, or sub-strings of length n from a larger string (two similar problems)?</p>
| 17
|
2009-04-17T15:01:35Z
| 24,007,145
|
<p>The <a href="https://docs.python.org/2/library/itertools.html" rel="nofollow">itertools doc</a> has a recipe for this:</p>
<pre><code>from itertools import izip_longest
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
</code></pre>
<p>Usage:</p>
<pre><code>>>> l = [1,2,3,4,5,6,7,8,9]
>>> [z for z in grouper(l, 3)]
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
</code></pre>
| 0
|
2014-06-03T04:28:50Z
|
[
"iteration",
"python"
] |
Iterate over a python sequence in multiples of n?
| 760,753
|
<p>How do I process the elements of a sequence in batches, idiomatically?</p>
<p>For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:</p>
<pre><code>for x, y in "abcdef":
print "%s%s\n" % (x, y)
ab
cd
ef
</code></pre>
<p>Of course, this doesn't work because it is expecting a single element from the list which itself contains 2 elements.</p>
<p>What is a nice, short, clean, pythonic way to process the next n elements of a list in a batch, or sub-strings of length n from a larger string (two similar problems)?</p>
| 17
|
2009-04-17T15:01:35Z
| 32,863,281
|
<p>Except for two answers I saw a lot of premature materialization on the batches, and subscripting (which does not work for all iterators). Hence I came up with this alternative:</p>
<pre class="lang-py prettyprint-override"><code>def iter_x_and_n(iterable, x, n):
yield x
try:
for _ in range(n):
yield next(iterable)
except StopIteration:
pass
def batched(iterable, n):
if n<1: raise ValueError("Can not create batches of size %d, number must be strictly positive" % n)
iterable = iter(iterable)
try:
for x in iterable:
yield iter_x_and_n(iterable, x, n-1)
except StopIteration:
pass
</code></pre>
<p>It beats me that there is no one-liner or few-liner solution for this (to the best of my knowleged). The key issue is that both the outer generator and the inner generator need to handle the StopIteration correctly. The outer generator should only yield something if there is at least one element left. The intuitive way to check this, is to execute a next(...) and catch a StopIteration.</p>
| 0
|
2015-09-30T10:03:23Z
|
[
"iteration",
"python"
] |
Iterate over a python sequence in multiples of n?
| 760,753
|
<p>How do I process the elements of a sequence in batches, idiomatically?</p>
<p>For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:</p>
<pre><code>for x, y in "abcdef":
print "%s%s\n" % (x, y)
ab
cd
ef
</code></pre>
<p>Of course, this doesn't work because it is expecting a single element from the list which itself contains 2 elements.</p>
<p>What is a nice, short, clean, pythonic way to process the next n elements of a list in a batch, or sub-strings of length n from a larger string (two similar problems)?</p>
| 17
|
2009-04-17T15:01:35Z
| 34,114,803
|
<p>From the docs of more_itertools:</p>
<pre><code>more_itertools.chunked(iterable, n)
</code></pre>
<p>Break an iterable into lists of a given length:</p>
<pre><code>>>> list(chunked([1, 2, 3, 4, 5, 6, 7], 3))
[[1, 2, 3], [4, 5, 6], [7]]
</code></pre>
<p>If the length of iterable is not evenly divisible by n, the last returned list will be shorter.</p>
| 0
|
2015-12-06T06:38:02Z
|
[
"iteration",
"python"
] |
Is there a fini routine for a python module written in C?
| 760,937
|
<p>I have a python module written in C, and I would like to add a function that is called when the module is unloaded. I obviously have an <code>initfoo</code> function to initialize the module -- is there a way to tell python to call a <code>finifoo</code> function when it's uninitializing the module?</p>
<p>Is <code>atexit</code> my only option?</p>
| 3
|
2009-04-17T15:40:25Z
| 760,981
|
<p>Not in Python 2, but <a href="http://www.python.org/dev/peps/pep-3121/" rel="nofollow">Python 3 seems to</a>. If you need to manage some resource, I would advise putting it in a module-level object -- I'm pretty sure those will be garbage-collected when the module is unloaded.</p>
<p><hr /></p>
<p>From the link:</p>
<blockquote>
<p>Currently, extension modules are
initialized usually once and then
"live" forever. The only exception is
when Py_Finalize() is called: then the
initialization routine is invoked a
second time.</p>
</blockquote>
<p>This suggests that you could set a static boolean in your initializer that gets flipped on every call. Check it status to see whether or not the module is being finalized.</p>
| 4
|
2009-04-17T15:52:00Z
|
[
"python",
"c",
"python-module"
] |
Long-running ssh commands in python paramiko module (and how to end them)
| 760,978
|
<p>I want to run a <code>tail -f logfile</code> command on a remote machine using python's paramiko module. I've been attempting it so far in the following fashion:</p>
<pre><code>interface = paramiko.SSHClient()
#snip the connection setup portion
stdin, stdout, stderr = interface.exec_command("tail -f logfile")
#snip into threaded loop
print stdout.readline()
</code></pre>
<p>I'd like the command to run as long as necessary, but I have 2 problems:</p>
<ol>
<li>How do I stop this cleanly? I thought of making a Channel and then using the <code>shutdown()</code> command on the channel when I'm through with it- but that seems messy. Is it possible to do something like sent <code>Ctrl-C</code> to the channel's stdin?</li>
<li><code>readline()</code> blocks, and I could avoid threads if I had a non-blocking method of getting output- any thoughts?</li>
</ol>
| 17
|
2009-04-17T15:51:20Z
| 762,686
|
<p>To close the process simply run:</p>
<pre><code>interface.close()
</code></pre>
<p>In terms of nonblocking, you can't get a non-blocking read. The best you would be able to to would be to parse over it one "block" at a time, "stdout.read(1)" will only block when there are no characters left in the buffer. </p>
| 0
|
2009-04-18T00:58:10Z
|
[
"python",
"ssh",
"paramiko"
] |
Long-running ssh commands in python paramiko module (and how to end them)
| 760,978
|
<p>I want to run a <code>tail -f logfile</code> command on a remote machine using python's paramiko module. I've been attempting it so far in the following fashion:</p>
<pre><code>interface = paramiko.SSHClient()
#snip the connection setup portion
stdin, stdout, stderr = interface.exec_command("tail -f logfile")
#snip into threaded loop
print stdout.readline()
</code></pre>
<p>I'd like the command to run as long as necessary, but I have 2 problems:</p>
<ol>
<li>How do I stop this cleanly? I thought of making a Channel and then using the <code>shutdown()</code> command on the channel when I'm through with it- but that seems messy. Is it possible to do something like sent <code>Ctrl-C</code> to the channel's stdin?</li>
<li><code>readline()</code> blocks, and I could avoid threads if I had a non-blocking method of getting output- any thoughts?</li>
</ol>
| 17
|
2009-04-17T15:51:20Z
| 766,255
|
<p>Instead of calling exec_command on the client, get hold of the transport and generate your own channel. The <a href="http://www.lag.net/paramiko/docs/paramiko.Channel-class.html" rel="nofollow">channel</a> can be used to execute a command, and you can use it in a select statement to find out when data can be read:</p>
<pre><code>#!/usr/bin/env python
import paramiko
import select
client = paramiko.SSHClient()
client.load_system_host_keys()
client.connect('host.example.com')
transport = client.get_transport()
channel = transport.open_session()
channel.exec_command("tail -f /var/log/everything/current")
while True:
rl, wl, xl = select.select([channel],[],[],0.0)
if len(rl) > 0:
# Must be stdout
print channel.recv(1024)
</code></pre>
<p>The channel object can be read from and written to, connecting with stdout and stdin of the remote command. You can get at stderr by calling <code>channel.makefile_stderr(...)</code>.</p>
<p>I've set the timeout to <code>0.0</code> seconds because a non-blocking solution was requested. Depending on your needs, you might want to block with a non-zero timeout.</p>
| 20
|
2009-04-19T22:27:05Z
|
[
"python",
"ssh",
"paramiko"
] |
Long-running ssh commands in python paramiko module (and how to end them)
| 760,978
|
<p>I want to run a <code>tail -f logfile</code> command on a remote machine using python's paramiko module. I've been attempting it so far in the following fashion:</p>
<pre><code>interface = paramiko.SSHClient()
#snip the connection setup portion
stdin, stdout, stderr = interface.exec_command("tail -f logfile")
#snip into threaded loop
print stdout.readline()
</code></pre>
<p>I'd like the command to run as long as necessary, but I have 2 problems:</p>
<ol>
<li>How do I stop this cleanly? I thought of making a Channel and then using the <code>shutdown()</code> command on the channel when I'm through with it- but that seems messy. Is it possible to do something like sent <code>Ctrl-C</code> to the channel's stdin?</li>
<li><code>readline()</code> blocks, and I could avoid threads if I had a non-blocking method of getting output- any thoughts?</li>
</ol>
| 17
|
2009-04-17T15:51:20Z
| 836,069
|
<p>1) You can just close the client if you wish. The server on the other end will kill the tail process. </p>
<p>2) If you need to do this in a non-blocking way, you will have to use the channel object directly. You can then watch for both stdout and stderr with channel.recv_ready() and channel.recv_stderr_ready(), or use select.select.</p>
| 12
|
2009-05-07T17:43:22Z
|
[
"python",
"ssh",
"paramiko"
] |
Long-running ssh commands in python paramiko module (and how to end them)
| 760,978
|
<p>I want to run a <code>tail -f logfile</code> command on a remote machine using python's paramiko module. I've been attempting it so far in the following fashion:</p>
<pre><code>interface = paramiko.SSHClient()
#snip the connection setup portion
stdin, stdout, stderr = interface.exec_command("tail -f logfile")
#snip into threaded loop
print stdout.readline()
</code></pre>
<p>I'd like the command to run as long as necessary, but I have 2 problems:</p>
<ol>
<li>How do I stop this cleanly? I thought of making a Channel and then using the <code>shutdown()</code> command on the channel when I'm through with it- but that seems messy. Is it possible to do something like sent <code>Ctrl-C</code> to the channel's stdin?</li>
<li><code>readline()</code> blocks, and I could avoid threads if I had a non-blocking method of getting output- any thoughts?</li>
</ol>
| 17
|
2009-04-17T15:51:20Z
| 11,190,794
|
<p>Just for information, there is a solution to do this using channel.get_pty(). Fore more details have a look at: <a href="http://stackoverflow.com/a/11190727/1480181">http://stackoverflow.com/a/11190727/1480181</a></p>
| 0
|
2012-06-25T14:02:15Z
|
[
"python",
"ssh",
"paramiko"
] |
Long-running ssh commands in python paramiko module (and how to end them)
| 760,978
|
<p>I want to run a <code>tail -f logfile</code> command on a remote machine using python's paramiko module. I've been attempting it so far in the following fashion:</p>
<pre><code>interface = paramiko.SSHClient()
#snip the connection setup portion
stdin, stdout, stderr = interface.exec_command("tail -f logfile")
#snip into threaded loop
print stdout.readline()
</code></pre>
<p>I'd like the command to run as long as necessary, but I have 2 problems:</p>
<ol>
<li>How do I stop this cleanly? I thought of making a Channel and then using the <code>shutdown()</code> command on the channel when I'm through with it- but that seems messy. Is it possible to do something like sent <code>Ctrl-C</code> to the channel's stdin?</li>
<li><code>readline()</code> blocks, and I could avoid threads if I had a non-blocking method of getting output- any thoughts?</li>
</ol>
| 17
|
2009-04-17T15:51:20Z
| 14,888,341
|
<p>Just a small update to the solution by Andrew Aylett. The following code actually breaks the loop and quits when the external process finishes:</p>
<pre><code>import paramiko
import select
client = paramiko.SSHClient()
client.load_system_host_keys()
client.connect('host.example.com')
channel = client.get_transport().open_session()
channel.exec_command("tail -f /var/log/everything/current")
while True:
if channel.exit_status_ready():
break
rl, wl, xl = select.select([channel], [], [], 0.0)
if len(rl) > 0:
print channel.recv(1024)
</code></pre>
| 6
|
2013-02-15T04:40:38Z
|
[
"python",
"ssh",
"paramiko"
] |
pyQT QNetworkManager and ProgressBars
| 761,286
|
<p>I'm trying to code something that downloads a file from a webserver and saves it, showing the download progress in a QProgressBar.
Now, there are ways to do this in regular Python and it's easy. Problem is that it locks the refresh of the progressBar. Solution is to use PyQT's QNetworkManager class. I can download stuff just fine with it, I just can't get the setup to show the progress on the progressBar. Here´s an example:</p>
<pre><code>class Form(QDialog):
def __init__(self,parent=None):
super(Form,self).__init__(parent)
self.progressBar = QProgressBar()
self.reply = None
layout = QHBoxLayout()
layout.addWidget(self.progressBar)
self.setLayout(layout)
self.manager = QNetworkAccessManager(self)
self.connect(self.manager,SIGNAL("finished(QNetworkReply*)"),self.replyFinished)
self.Down()
def Down(self):
address = QUrl("http://stackoverflow.com") #URL from the remote file.
self.manager.get(QNetworkRequest(address))
def replyFinished(self, reply):
self.connect(reply,SIGNAL("downloadProgress(int,int)"),self.progressBar, SLOT("setValue(int)"))
self.reply = reply
self.progressBar.setMaximum(reply.size())
alltext = self.reply.readAll()
#print alltext
#print alltext
def updateBar(self, read,total):
print "read", read
print "total",total
#self.progressBar.setMinimum(0)
#self.progressBar.setMask(total)
#self.progressBar.setValue(read)
</code></pre>
<p><hr /></p>
<p>In this case, my method "updateBar" is never called... any ideas?</p>
| 1
|
2009-04-17T17:03:51Z
| 762,680
|
<p>Well you haven't connected any of the signals to your updateBar() method.</p>
<p>change</p>
<pre><code>def replyFinished(self, reply):
self.connect(reply,SIGNAL("downloadProgress(int,int)"),self.progressBar, SLOT("setValue(int)"))
</code></pre>
<p>to </p>
<pre><code>def replyFinished(self, reply):
self.connect(reply,SIGNAL("downloadProgress(int,int)"),self.updateBar)
</code></pre>
<p>Note that in Python you don't have to explicitly use the SLOT() syntax; you can just pass the reference to your method or function.</p>
<p>Update:</p>
<p>I just wanted to point out that if you want to use a Progress bar in any situation where your GUI locks up during processing, one solution is to run your processing code in another thread so your GUI receives repaint events. Consider reading about the QThread class, in case you come across another reason for a progress bar that does not have a pre-built solution for you.</p>
| 4
|
2009-04-18T00:53:34Z
|
[
"python",
"pyqt"
] |
Suppress the u'prefix indicating unicode' in python strings
| 761,361
|
<p>Is there a way to globally suppress the unicode string indicator in python? I'm working exclusively with unicode in an application, and do a lot of interactive stuff. Having the u'prefix' show up in all of my debug output is unnecessary and obnoxious. Can it be turned off?</p>
| 30
|
2009-04-17T17:22:04Z
| 761,459
|
<p>You could use Python 3.0.. The default string type is unicode, so the <code>u''</code> prefix is no longer required..</p>
<p>In short, no. You cannot turn this off.</p>
<p>The <code>u</code> comes from the <code>unicode.__repr__</code> method, which is used to display stuff in REPL:</p>
<pre><code>>>> print repr(unicode('a'))
u'a'
>>> unicode('a')
u'a'
</code></pre>
<p>If I'm not mistaken, you cannot override this without recompiling Python.</p>
<p>The simplest way around this is to simply print the string..</p>
<pre><code>>>> print unicode('a')
a
</code></pre>
<p>If you use the <code>unicode()</code> builtin to construct all your strings, you could do something like..</p>
<pre><code>>>> class unicode(unicode):
... def __repr__(self):
... return __builtins__.unicode.__repr__(self).lstrip("u")
...
>>> unicode('a')
a
</code></pre>
<p>..but don't do that, it's horrible</p>
| 30
|
2009-04-17T17:42:38Z
|
[
"python",
"string",
"unicode",
"printing"
] |
Suppress the u'prefix indicating unicode' in python strings
| 761,361
|
<p>Is there a way to globally suppress the unicode string indicator in python? I'm working exclusively with unicode in an application, and do a lot of interactive stuff. Having the u'prefix' show up in all of my debug output is unnecessary and obnoxious. Can it be turned off?</p>
| 30
|
2009-04-17T17:22:04Z
| 1,146,258
|
<p>I know this isn't a global option, but you can also suppress the Unicode u by placing the string in a str() function.</p>
<p>So a Unicode derived list that would look like:</p>
<pre><code>>>> myList=[unicode('a'),unicode('b'),unicode('c')]
>>> myList
[u'a', u'b', u'c']
</code></pre>
<p>would become this:</p>
<pre><code>>>> myList=[str(unicode('a')),str(unicode('b')),str(unicode('c'))]
>>> myList
['a', 'b', 'c']
</code></pre>
<p>It's a bit cumbersome, but might be useful to some one</p>
| 4
|
2009-07-18T00:19:01Z
|
[
"python",
"string",
"unicode",
"printing"
] |
Suppress the u'prefix indicating unicode' in python strings
| 761,361
|
<p>Is there a way to globally suppress the unicode string indicator in python? I'm working exclusively with unicode in an application, and do a lot of interactive stuff. Having the u'prefix' show up in all of my debug output is unnecessary and obnoxious. Can it be turned off?</p>
| 30
|
2009-04-17T17:22:04Z
| 5,822,478
|
<p>Try the following</p>
<blockquote>
<p>print str(result.url)</p>
</blockquote>
<p>It could be that your default encoding has been changed.</p>
<p>You can check your default encoding with the following:-</p>
<pre><code>> import sys
> print sys.getdefaultencoding()
> ascii
</code></pre>
<p>The default should be ascii which means u'string' should be printed as 'string' but yours may have been modified.</p>
| 1
|
2011-04-28T17:14:03Z
|
[
"python",
"string",
"unicode",
"printing"
] |
Suppress the u'prefix indicating unicode' in python strings
| 761,361
|
<p>Is there a way to globally suppress the unicode string indicator in python? I'm working exclusively with unicode in an application, and do a lot of interactive stuff. Having the u'prefix' show up in all of my debug output is unnecessary and obnoxious. Can it be turned off?</p>
| 30
|
2009-04-17T17:22:04Z
| 5,822,501
|
<p>Not sure with unicode, but generally you can call <code>str.encode()</code> to convert it to a more suitable form. For instance, subprocess output captured in Python 3.0+ captures it as a byte stream (prefix 'b'), and encode() fixes to a regular string form.</p>
| 3
|
2011-04-28T17:16:02Z
|
[
"python",
"string",
"unicode",
"printing"
] |
Suppress the u'prefix indicating unicode' in python strings
| 761,361
|
<p>Is there a way to globally suppress the unicode string indicator in python? I'm working exclusively with unicode in an application, and do a lot of interactive stuff. Having the u'prefix' show up in all of my debug output is unnecessary and obnoxious. Can it be turned off?</p>
| 30
|
2009-04-17T17:22:04Z
| 5,839,420
|
<p>You have to use <code>print str(your_Variable)</code></p>
| 1
|
2011-04-30T04:06:41Z
|
[
"python",
"string",
"unicode",
"printing"
] |
Suppress the u'prefix indicating unicode' in python strings
| 761,361
|
<p>Is there a way to globally suppress the unicode string indicator in python? I'm working exclusively with unicode in an application, and do a lot of interactive stuff. Having the u'prefix' show up in all of my debug output is unnecessary and obnoxious. Can it be turned off?</p>
| 30
|
2009-04-17T17:22:04Z
| 5,839,729
|
<p>using <code>str( text )</code> is a somewhat bad idea in fact whenever you cannot be 100% sure about both your python's default encoding and the exact content of the string---the latter would be typical for a text fetched from the internet. also, depending on what you want to do, using <code>print text.encode( 'utf-8' )</code> or <code>print repr( text.encode( 'utf-8' ) )</code> may yield disappointing results, as you might get a rendering full of unreadable codepoints like <code>\x3a</code>.</p>
<p>i think the optimum is really to avail yourself of a unicode-capable command line (difficult under windows, easy under linux) and switch from python 2.x to python 3.x. the ease and clarity of text vs bytes handling afforded by the new python 3 series is really one of the big gains you can expect. it does mean you'll have to spend a little time learning the distinction between 'bytes' and 'text' and grasp the concept of character encodings, but then that time is much better spent in a python 3 environment as python's new approch to these vexing problems is much clearer and much less error-prone than what python 2 had to offer. i'd go so far as to call python 2's approach to unicode problematic in retrospect, although i used to think of it as superior---when i compared it to the <a href="http://php.net/manual/en/function.utf8-encode.php">way this issue is handled in php</a>.</p>
<p><strong>edit</strong> i just stopped by <a href="http://stackoverflow.com/questions/571694/what-factors-make-php-unicode-incompatible">a related discussion</a> here on SO and found this comment on the way that php these days appears to tackle unicode / encoding issues:</p>
<blockquote>
<p>It's like a mouse trying to eat an
elephant. By framing Unicode as an
extension of ASCII (we have normal
strings and we have mb_strings) it
gets things the wrong way around, and
gets hung up on what special cases are
required to deal with characters with
funny squiggles that need more than
one byte. If you treat Unicode as
providing an abstract space for any
character you need, ASCII is
accommodated in that without any need
to treat it as a special case.</p>
</blockquote>
<p>i quote this here because in my experience 90% of all SO python+unicode topics seem to come from people who used to be fine with ascii or maybe latin-1, got bitten by the occasional character that was not supported in their usual settings, and then basically just want to get rid of it. what you do when switching to python 3 is exactly what the commenter above suggests to do: instead of viewing unicode as a vexing extension of ascii, you start to view ascii (and almost any other encoding you'll ever meet) as subset(s) of unicode. </p>
<p>to be true, unicode v6 is certainly not the last word in encodings, but it is as close to being universal as you can get in 2011. get used to it.</p>
| 6
|
2011-04-30T05:15:38Z
|
[
"python",
"string",
"unicode",
"printing"
] |
Suppress the u'prefix indicating unicode' in python strings
| 761,361
|
<p>Is there a way to globally suppress the unicode string indicator in python? I'm working exclusively with unicode in an application, and do a lot of interactive stuff. Having the u'prefix' show up in all of my debug output is unnecessary and obnoxious. Can it be turned off?</p>
| 30
|
2009-04-17T17:22:04Z
| 8,627,204
|
<p>In the case that you do not want to update to Python 3, you could make use of substrings.
For example, say the original output was (u'mystring',). Let us assume for the sake of the example that the variable row contains the "mystring" string without the unicode prefix. Then you would want to do something like this:</p>
<pre><code>temp = str(row); #str is not necessary, but probably good practice
temp = temp[:-3];
print = temp[3:];
</code></pre>
| 1
|
2011-12-24T22:29:10Z
|
[
"python",
"string",
"unicode",
"printing"
] |
Suppress the u'prefix indicating unicode' in python strings
| 761,361
|
<p>Is there a way to globally suppress the unicode string indicator in python? I'm working exclusively with unicode in an application, and do a lot of interactive stuff. Having the u'prefix' show up in all of my debug output is unnecessary and obnoxious. Can it be turned off?</p>
| 30
|
2009-04-17T17:22:04Z
| 13,246,056
|
<p>I had a case where I needed drop the u prefix because I was setting up some javascript with python as part of an html template. A simple output left the u prefix in for the dict keys e.g.</p>
<pre><code>var turns = [{u'armies':2...];
</code></pre>
<p>which breaks javascript.</p>
<p>In order to get the output javascript needed, I used the json python module to encode the string for me:</p>
<pre><code>turns = json.dumps(turns)
</code></pre>
<p>This does the trick in my particular case and as the keys are all ascii there is no worry about the encoding. You could probably use this trick for your debug output.</p>
| 13
|
2012-11-06T07:05:49Z
|
[
"python",
"string",
"unicode",
"printing"
] |
Suppress the u'prefix indicating unicode' in python strings
| 761,361
|
<p>Is there a way to globally suppress the unicode string indicator in python? I'm working exclusively with unicode in an application, and do a lot of interactive stuff. Having the u'prefix' show up in all of my debug output is unnecessary and obnoxious. Can it be turned off?</p>
| 30
|
2009-04-17T17:22:04Z
| 30,167,034
|
<pre><code>from __future__ import unicode_literals
</code></pre>
<p>is available since Python 2.6 (released on October 1, 2008). It is default in Python 3.</p>
<p>It allows to omit <code>u''</code> prefix in the source code though it does not change <code>repr(unicode_string)</code> that would be misleading.</p>
<p>You could override <code>sys.displayhook()</code> in a Python REPL, to display objects however your like. You could also override <code>__repr__</code> for your own custom objects.</p>
| 2
|
2015-05-11T11:54:37Z
|
[
"python",
"string",
"unicode",
"printing"
] |
Suppress the u'prefix indicating unicode' in python strings
| 761,361
|
<p>Is there a way to globally suppress the unicode string indicator in python? I'm working exclusively with unicode in an application, and do a lot of interactive stuff. Having the u'prefix' show up in all of my debug output is unnecessary and obnoxious. Can it be turned off?</p>
| 30
|
2009-04-17T17:22:04Z
| 35,850,273
|
<p>Just in case you are getting something like this <code>u['hello']</code> then you must be printing an array. print <code>str(arr[0])</code> and you are good to go. </p>
| 1
|
2016-03-07T17:37:57Z
|
[
"python",
"string",
"unicode",
"printing"
] |
Suppress the u'prefix indicating unicode' in python strings
| 761,361
|
<p>Is there a way to globally suppress the unicode string indicator in python? I'm working exclusively with unicode in an application, and do a lot of interactive stuff. Having the u'prefix' show up in all of my debug output is unnecessary and obnoxious. Can it be turned off?</p>
| 30
|
2009-04-17T17:22:04Z
| 38,702,735
|
<p>What seems to be working for me:</p>
<pre><code>import ast
import json
j = json.loads('{"one" : "two"}')
j
dd = {u'one': u'two'}
dd
# to get double quotes
json.dumps(j, encoding='ascii')
json.dumps(dd, encoding='ascii')
# to get single quotes
str(ast.literal_eval(json.dumps(j, encoding='ascii')))
str(ast.literal_eval(json.dumps(dd, encoding='ascii')))
</code></pre>
<p>Output:</p>
<pre><code>>>> {u'one': u'two'}
>>> {u'one': u'two'}
>>> '{"one": "two"}'
>>> '{"one": "two"}'
>>> "{'one': 'two'}"
>>> "{'one': 'two'}"
</code></pre>
<p>Above works for dictionaries and JSON objects, as self-evident.</p>
<p>For just a string, wrapping in str() seems to work for me.</p>
<pre><code>s=u'test string'
s
str(s)
</code></pre>
<p>Output:</p>
<pre><code>>>> u'test string'
>>> 'test string'
</code></pre>
<p>Python version: 2.7.12</p>
| 0
|
2016-08-01T15:31:56Z
|
[
"python",
"string",
"unicode",
"printing"
] |
Why csv.reader is not pythonic?
| 761,430
|
<p>I started to use the <a href="https://docs.python.org/2/library/csv.html#csv.reader" rel="nofollow">csv.reader</a> in Python 2.6 but you can't use <code>len</code> on it, or slice it, etc. What's the reason behind this? It certainly feels very limiting.</p>
<p>Or is this just an abandoned module in later versions?</p>
| 7
|
2009-04-17T17:35:38Z
| 761,449
|
<p>I'm pretty sure you can't use len or slice because it is an iterator. Try this instead.</p>
<pre><code>import csv
r = csv.reader(...)
lines = [line for line in r]
print len(lines) #number of lines
for odd in lines[1::2]: print odd # print odd lines
</code></pre>
| 14
|
2009-04-17T17:40:42Z
|
[
"python",
"csv"
] |
Is it ok to use dashes in Python files when trying to import them?
| 761,519
|
<p>Basically when I have a python file like:</p>
<pre><code>python-code.py
</code></pre>
<p>and use:</p>
<pre><code>import (python-code)
</code></pre>
<p>the interpreter gives me syntax error.</p>
<p>Any ideas on how to fix it? Are dashes illegal in python file names?</p>
| 65
|
2009-04-17T17:58:59Z
| 761,529
|
<p>The problem is that <code>python-code</code> is not an identifier. The parser sees this as <code>python</code> minus <code>code</code>. Of course this won't do what you're asking. You will need to use a filename that is also a valid python identifier. Try replacing the <code>-</code> with an underscore.</p>
| 19
|
2009-04-17T18:01:05Z
|
[
"python",
"naming"
] |
Is it ok to use dashes in Python files when trying to import them?
| 761,519
|
<p>Basically when I have a python file like:</p>
<pre><code>python-code.py
</code></pre>
<p>and use:</p>
<pre><code>import (python-code)
</code></pre>
<p>the interpreter gives me syntax error.</p>
<p>Any ideas on how to fix it? Are dashes illegal in python file names?</p>
| 65
|
2009-04-17T17:58:59Z
| 761,531
|
<p>You should check out <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a>, the Style Guide for Python Code:</p>
<blockquote>
<p>Package and Module Names Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.</p>
<p>Since module names are mapped to file names, and some file systems are case insensitive and truncate long names, it is important that module names be chosen to be fairly short -- this won't be a problem on Unix, but it may be a problem when the code is transported to older Mac or Windows versions, or DOS.</p>
</blockquote>
<p>In other words: rename your file :)</p>
| 84
|
2009-04-17T18:01:46Z
|
[
"python",
"naming"
] |
Is it ok to use dashes in Python files when trying to import them?
| 761,519
|
<p>Basically when I have a python file like:</p>
<pre><code>python-code.py
</code></pre>
<p>and use:</p>
<pre><code>import (python-code)
</code></pre>
<p>the interpreter gives me syntax error.</p>
<p>Any ideas on how to fix it? Are dashes illegal in python file names?</p>
| 65
|
2009-04-17T17:58:59Z
| 761,534
|
<p>You could probably import it through some <code>__import__</code> hack, but if you don't already know how, you shouldn't. Python module names should be valid variable names ("identifiers") -- that means if you have a module <code>foo_bar</code>, you can use it from within Python (<code>print foo_bar</code>). You wouldn't be able to do so with a weird name (<code>print foo-bar</code> -> syntax error).</p>
| 3
|
2009-04-17T18:03:29Z
|
[
"python",
"naming"
] |
Is it ok to use dashes in Python files when trying to import them?
| 761,519
|
<p>Basically when I have a python file like:</p>
<pre><code>python-code.py
</code></pre>
<p>and use:</p>
<pre><code>import (python-code)
</code></pre>
<p>the interpreter gives me syntax error.</p>
<p>Any ideas on how to fix it? Are dashes illegal in python file names?</p>
| 65
|
2009-04-17T17:58:59Z
| 762,693
|
<p>One other thing to note in your code is that import is not a function. So <code>import(python-code)</code> should be <code>import python-code</code> which, as some have already mentioned, is interpreted as "import python minus code", not what you intended. If you really need to import a file with a dash in its name, you can do the following::</p>
<pre><code>python_code = __import__('python-code')
</code></pre>
<p>But, as also mentioned above, this is not really recommended. You should change the filename if it's something you control.</p>
| 74
|
2009-04-18T01:06:18Z
|
[
"python",
"naming"
] |
Is it ok to use dashes in Python files when trying to import them?
| 761,519
|
<p>Basically when I have a python file like:</p>
<pre><code>python-code.py
</code></pre>
<p>and use:</p>
<pre><code>import (python-code)
</code></pre>
<p>the interpreter gives me syntax error.</p>
<p>Any ideas on how to fix it? Are dashes illegal in python file names?</p>
| 65
|
2009-04-17T17:58:59Z
| 37,831,973
|
<p>Dashes are <em>not</em> illegal but you should not use them for 3 reasons:</p>
<ol>
<li>You need special syntax to import files with dashes</li>
<li>Nobody expects a module name with a dash</li>
<li>It's against the recommendations of the <a href="https://www.python.org/dev/peps/pep-0008/#id38" rel="nofollow">Python Style Guide</a></li>
</ol>
<p>If you definitely need to import a file name with a dash the special syntax is this:</p>
<pre><code>module_name = __import__('module-name')
</code></pre>
<p>If you're curious, the reason for the special syntax is that when you write <code>import somename</code> you're creating a module object with identifier <code>somename</code> (so you can later use it with e.g. somename.funcname). Of course <code>module-name</code> is not a valid identifier and hence the special syntax that gives a valid one.</p>
<hr>
<p>Note: nothing original in my answer except including what I considered to be the most relevant bits of information from all other answers in one place</p>
| 4
|
2016-06-15T09:52:47Z
|
[
"python",
"naming"
] |
Overriding 'to boolean' operator in python?
| 761,586
|
<p>I'm using a class that is inherited from list as a data structure:</p>
<pre><code>class CItem( list ) :
pass
oItem = CItem()
oItem.m_something = 10
oItem += [ 1, 2, 3 ]
</code></pre>
<p>All is perfect, but if I use my object of my class inside of an 'if', python evaluates it to False if underlying the list has no elements. Since my class is not just list, I really want it to evaluate False only if it's None, and evaluate to True otherwise:</p>
<pre><code>a = None
if a :
print "this is not called, as expected"
a = CItem()
if a :
print "and this is not called too, since CItem is empty list. How to fix it?"
</code></pre>
| 19
|
2009-04-17T18:15:27Z
| 761,605
|
<p>In 2.x: override <a href="https://docs.python.org/2/reference/datamodel.html#object.__nonzero__"><code>__nonzero__()</code></a>. In 3.x, override <a href="https://docs.python.org/3/reference/datamodel.html?highlight=__bool__#object.__bool__"><code>__bool__()</code></a>.</p>
| 33
|
2009-04-17T18:21:14Z
|
[
"python"
] |
If you were to clone Monopoly Tycoon in Python, what libraries would you use?
| 761,652
|
<p>Ever played the game Monopoly Tycoon? I think it's great.
I would love to remake it. Unfortunately, I have no experience when it comes to 3D programming. I imagine there's a relatively steep learning curve when it comes to openGL stuff, figuring out what is being clicked on and so on...</p>
<p>If you were to undertake this task, what libraries would you need?</p>
| 3
|
2009-04-17T18:30:52Z
| 761,668
|
<p><a href="http://www.pygame.org/news.html" rel="nofollow">pyGame</a> seems quite mature and builds on top of the proven SDL library. </p>
| 6
|
2009-04-17T18:36:22Z
|
[
"python",
"opengl"
] |
If you were to clone Monopoly Tycoon in Python, what libraries would you use?
| 761,652
|
<p>Ever played the game Monopoly Tycoon? I think it's great.
I would love to remake it. Unfortunately, I have no experience when it comes to 3D programming. I imagine there's a relatively steep learning curve when it comes to openGL stuff, figuring out what is being clicked on and so on...</p>
<p>If you were to undertake this task, what libraries would you need?</p>
| 3
|
2009-04-17T18:30:52Z
| 763,147
|
<p>I'd use pyglet. It's all opengl from the start, doesn't build on top of ugly SDL library and has better interfaces than what I've seen on other python's multimedia libraries.</p>
<pre><code>import pyglet
from pyglet.gl import *
class Application(object):
def __init__(self):
self.window = window = pyglet.window.Window()
window.push_handlers(self)
def on_draw(self):
self.window.clear()
glBegin(GL_TRIANGLES)
glVertex2f(0,0)
glVertex2f(200,0)
glVertex2f(200,200)
glEnd()
if __name__=='__main__':
app = Application()
pyglet.app.run()
</code></pre>
<p>I wrote this from scratch to show you a reference. You can pretty much start from that. </p>
<p>There's couple of useful things in the library like vertex lists, textures, scheduling, unicode fonts, a little bit of UI components, event dispatching, audio. The library itself is messy inside and I didn't like it too much. But then this is my opinion from every library that has widespread and that I've looked into.</p>
<p>Myself I'm dissatisfied to the opengl namespacing. It'd be better with non-C namespace in the front. This'd leave you in some flexibility:</p>
<pre><code>from pyglet.gl import Begin, Vertex2f, TRIANGLES, End
...
Begin(TRIANGLES)
Vertex2f(0,0)
Vertex2f(200,0)
Vertex2f(200,200)
End()
</code></pre>
| 4
|
2009-04-18T08:40:11Z
|
[
"python",
"opengl"
] |
How to get the label of a choice in a Django forms ChoiceField?
| 761,698
|
<p>I have a ChoiceField, now how do I get the "label" when I need it?</p>
<pre><code>class ContactForm(forms.Form):
reason = forms.ChoiceField(choices=[("feature", "A feature"),
("order", "An order")],
widget=forms.RadioSelect)
</code></pre>
<p><code>form.cleaned_data["reason"]</code> would only give me "feature" or "order" or so.</p>
| 41
|
2009-04-17T18:43:52Z
| 762,002
|
<p>Here is a way I came up with. There may be an easier way. I tested it using <code>python manage.py shell</code>:</p>
<pre><code>>>> cf = ContactForm({'reason': 'feature'})
>>> cf.is_valid()
True
>>> cf.fields['reason'].choices
[('feature', 'A feature')]
>>> for val in cf.fields['reason'].choices:
... if val[0] == cf.cleaned_data['reason']:
... print val[1]
... break
...
A feature
</code></pre>
<p>Note: This probably isn't very Pythonic, but it demonstrates where the data you need can be found.</p>
| 3
|
2009-04-17T20:06:40Z
|
[
"python",
"django",
"choicefield"
] |
How to get the label of a choice in a Django forms ChoiceField?
| 761,698
|
<p>I have a ChoiceField, now how do I get the "label" when I need it?</p>
<pre><code>class ContactForm(forms.Form):
reason = forms.ChoiceField(choices=[("feature", "A feature"),
("order", "An order")],
widget=forms.RadioSelect)
</code></pre>
<p><code>form.cleaned_data["reason"]</code> would only give me "feature" or "order" or so.</p>
| 41
|
2009-04-17T18:43:52Z
| 762,830
|
<p>See the docs on <a href="http://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.get%5FFOO%5Fdisplay">Model.get_FOO_display()</a>. So, should be something like :</p>
<pre><code>ContactForm.get_reason_display()
</code></pre>
<p>In a template, use like this:</p>
<pre><code>{{ OBJNAME.get_FIELDNAME_display }}
</code></pre>
| 90
|
2009-04-18T03:28:26Z
|
[
"python",
"django",
"choicefield"
] |
How to get the label of a choice in a Django forms ChoiceField?
| 761,698
|
<p>I have a ChoiceField, now how do I get the "label" when I need it?</p>
<pre><code>class ContactForm(forms.Form):
reason = forms.ChoiceField(choices=[("feature", "A feature"),
("order", "An order")],
widget=forms.RadioSelect)
</code></pre>
<p><code>form.cleaned_data["reason"]</code> would only give me "feature" or "order" or so.</p>
| 41
|
2009-04-17T18:43:52Z
| 4,019,532
|
<p>I think maybe @webjunkie is right.</p>
<p>If you're reading from the form from a POST then you would do </p>
<pre><code>def contact_view(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
contact = form.save()
contact.reason = form.cleaned_data['reason']
contact.save()
</code></pre>
| 0
|
2010-10-25T22:57:07Z
|
[
"python",
"django",
"choicefield"
] |
How to get the label of a choice in a Django forms ChoiceField?
| 761,698
|
<p>I have a ChoiceField, now how do I get the "label" when I need it?</p>
<pre><code>class ContactForm(forms.Form):
reason = forms.ChoiceField(choices=[("feature", "A feature"),
("order", "An order")],
widget=forms.RadioSelect)
</code></pre>
<p><code>form.cleaned_data["reason"]</code> would only give me "feature" or "order" or so.</p>
| 41
|
2009-04-17T18:43:52Z
| 7,600,927
|
<p>This may help:</p>
<pre><code>reason = form.cleaned_data['reason']
reason = dict(form.fields['reason'].choices)[reason]
</code></pre>
| 51
|
2011-09-29T17:14:51Z
|
[
"python",
"django",
"choicefield"
] |
How to get the label of a choice in a Django forms ChoiceField?
| 761,698
|
<p>I have a ChoiceField, now how do I get the "label" when I need it?</p>
<pre><code>class ContactForm(forms.Form):
reason = forms.ChoiceField(choices=[("feature", "A feature"),
("order", "An order")],
widget=forms.RadioSelect)
</code></pre>
<p><code>form.cleaned_data["reason"]</code> would only give me "feature" or "order" or so.</p>
| 41
|
2009-04-17T18:43:52Z
| 9,574,425
|
<p>This the easiest way to do this: <a href="https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.get_FOO_display">Model instance reference: Model.get_FOO_display()</a></p>
<p>You can use this function which will return the display name: <code>ObjectName.get_FieldName_display()</code></p>
<p>Replace <code>ObjectName</code> with your class name and <code>FieldName</code> with the field of which you need to fetch the display name of.</p>
| 11
|
2012-03-05T21:40:16Z
|
[
"python",
"django",
"choicefield"
] |
How to get the label of a choice in a Django forms ChoiceField?
| 761,698
|
<p>I have a ChoiceField, now how do I get the "label" when I need it?</p>
<pre><code>class ContactForm(forms.Form):
reason = forms.ChoiceField(choices=[("feature", "A feature"),
("order", "An order")],
widget=forms.RadioSelect)
</code></pre>
<p><code>form.cleaned_data["reason"]</code> would only give me "feature" or "order" or so.</p>
| 41
|
2009-04-17T18:43:52Z
| 10,051,191
|
<p>If the form instance is bound, you can use</p>
<pre><code>chosen_label = form.instance.get_FOO_display()
</code></pre>
| 5
|
2012-04-07T02:18:21Z
|
[
"python",
"django",
"choicefield"
] |
How to get the label of a choice in a Django forms ChoiceField?
| 761,698
|
<p>I have a ChoiceField, now how do I get the "label" when I need it?</p>
<pre><code>class ContactForm(forms.Form):
reason = forms.ChoiceField(choices=[("feature", "A feature"),
("order", "An order")],
widget=forms.RadioSelect)
</code></pre>
<p><code>form.cleaned_data["reason"]</code> would only give me "feature" or "order" or so.</p>
| 41
|
2009-04-17T18:43:52Z
| 10,515,057
|
<p>You can have your form like this:</p>
<pre><code>#forms.py
CHOICES = [('feature', "A feature"), (order", "An order")]
class ContactForm(forms.Form):
reason = forms.ChoiceField(choices=CHOICES,
widget=forms.RadioSelect)
</code></pre>
<p>Then this would give you what you want:</p>
<pre><code>reason = dict(CHOICES)[form.cleaned_data["reason"]]
</code></pre>
| 2
|
2012-05-09T11:20:24Z
|
[
"python",
"django",
"choicefield"
] |
Trimming a string in Python
| 761,804
|
<p>How do I remove leading and trailing whitespace from a string in Python?</p>
<p>For example:</p>
<pre><code>" Hello " --> "Hello"
" Hello" --> "Hello"
"Hello " --> "Hello"
"Bob has a cat" --> "Bob has a cat"
</code></pre>
| 610
|
2009-04-17T19:16:06Z
| 761,816
|
<pre><code>myString.strip()
</code></pre>
| 33
|
2009-04-17T19:19:12Z
|
[
"python",
"string",
"trim"
] |
Trimming a string in Python
| 761,804
|
<p>How do I remove leading and trailing whitespace from a string in Python?</p>
<p>For example:</p>
<pre><code>" Hello " --> "Hello"
" Hello" --> "Hello"
"Hello " --> "Hello"
"Bob has a cat" --> "Bob has a cat"
</code></pre>
| 610
|
2009-04-17T19:16:06Z
| 761,822
|
<p>You want strip():</p>
<pre><code>myphrases = [ " Hello ", " Hello", "Hello ", "Bob has a cat" ]
for phrase in myphrases:
print phrase.strip()
</code></pre>
| 18
|
2009-04-17T19:21:14Z
|
[
"python",
"string",
"trim"
] |
Trimming a string in Python
| 761,804
|
<p>How do I remove leading and trailing whitespace from a string in Python?</p>
<p>For example:</p>
<pre><code>" Hello " --> "Hello"
" Hello" --> "Hello"
"Hello " --> "Hello"
"Bob has a cat" --> "Bob has a cat"
</code></pre>
| 610
|
2009-04-17T19:16:06Z
| 761,825
|
<p>Just one space, or all such spaces? If the second, then strings already have a <code>.strip()</code> method:</p>
<pre><code>>>> ' Hello '.strip()
'Hello'
>>> ' Hello'.strip()
'Hello'
>>> 'Bob has a cat'.strip()
'Bob has a cat'
>>> ' Hello '.strip() # ALL spaces at ends removed
'Hello'
</code></pre>
<p>If you need only to remove one space however, you could do it with:</p>
<pre><code>def strip_one_space(s):
if s.endswith(" "): s = s[:-1]
if s.startswith(" "): s = s[1:]
return s
>>> strip_one_space(" Hello ")
' Hello'
</code></pre>
<p>Also, note that <code>str.strip()</code> removes other whitespace characters as well (e.g. tabs and newlines). To remove only spaces, you can specify the character to remove as an argument to <code>strip</code>, i.e.:</p>
<pre><code>>>> " Hello\n".strip(" ")
'Hello\n'
</code></pre>
| 932
|
2009-04-17T19:21:29Z
|
[
"python",
"string",
"trim"
] |
Trimming a string in Python
| 761,804
|
<p>How do I remove leading and trailing whitespace from a string in Python?</p>
<p>For example:</p>
<pre><code>" Hello " --> "Hello"
" Hello" --> "Hello"
"Hello " --> "Hello"
"Bob has a cat" --> "Bob has a cat"
</code></pre>
| 610
|
2009-04-17T19:16:06Z
| 6,039,813
|
<p>As pointed out in answers above </p>
<pre><code>myString.strip()
</code></pre>
<p>will remove all the leading and trailing whitespace characters such as \n, \r, \t, \f, space.</p>
<p>For more flexibility use the following</p>
<ul>
<li>Removes only <strong>leading</strong> whitespace chars: <code>myString.lstrip()</code></li>
<li>Removes only <strong>trailing</strong> whitespace chars: <code>myString.rstrip()</code></li>
<li>Removes <strong>specific</strong> whitespace chars: <code>myString.strip('\n')</code> or <code>myString.lstrip('\n\r')</code> or <code>myString.rstrip('\n\t')</code> and so on.</li>
</ul>
<p>More details are available in the <a href="http://docs.python.org/release/2.3/lib/module-string.html">docs</a></p>
| 163
|
2011-05-18T04:16:47Z
|
[
"python",
"string",
"trim"
] |
Trimming a string in Python
| 761,804
|
<p>How do I remove leading and trailing whitespace from a string in Python?</p>
<p>For example:</p>
<pre><code>" Hello " --> "Hello"
" Hello" --> "Hello"
"Hello " --> "Hello"
"Bob has a cat" --> "Bob has a cat"
</code></pre>
| 610
|
2009-04-17T19:16:06Z
| 10,192,113
|
<p><code>strip</code> is not limited to whitespace characters either:</p>
<pre><code># remove all leading/trailing commas, periods and hyphens
title = title.strip(',.-')
</code></pre>
| 68
|
2012-04-17T13:22:23Z
|
[
"python",
"string",
"trim"
] |
Active Directory - Django/Rails
| 761,820
|
<p>I'm thinking about re-writing a web app in Django or Rails and wondering about authenticating against AD. Is one ecosystem better suited for this (libraries, etc) or is it a toss-up?</p>
<p>(The app will be hosted on Linux)</p>
<p>I have lots of reasons for the re-write, one them is to make myself more marketable. Anyone care to comment on the which of these frameworks has better long-term outlook for a new programmer? (I've read the StackOverflow threads already, but ask just in case something new has come up).</p>
<p>Thanks in advance.</p>
| 3
|
2009-04-17T19:20:28Z
| 761,857
|
<p>A quick google to give you some pointers on using Active Directory in these environments.</p>
<ul>
<li><a href="http://www.djangosnippets.org/snippets/501/" rel="nofollow">http://www.djangosnippets.org/snippets/501/</a></li>
<li><a href="http://www.zorched.net/2007/06/04/active-directory-authentication-for-ruby-on-rails/" rel="nofollow">http://www.zorched.net/2007/06/04/active-directory-authentication-for-ruby-on-rails/</a></li>
</ul>
| 3
|
2009-04-17T19:32:41Z
|
[
"python",
"ruby-on-rails",
"ruby",
"django",
"active-directory"
] |
Active Directory - Django/Rails
| 761,820
|
<p>I'm thinking about re-writing a web app in Django or Rails and wondering about authenticating against AD. Is one ecosystem better suited for this (libraries, etc) or is it a toss-up?</p>
<p>(The app will be hosted on Linux)</p>
<p>I have lots of reasons for the re-write, one them is to make myself more marketable. Anyone care to comment on the which of these frameworks has better long-term outlook for a new programmer? (I've read the StackOverflow threads already, but ask just in case something new has come up).</p>
<p>Thanks in advance.</p>
| 3
|
2009-04-17T19:20:28Z
| 763,921
|
<p>I did Active Directory auth in Rails about a year ago. I did it similarly to the article Daniel linked to. It felt hacky, but it was an internal app, so it was acceptable.</p>
<p>Since then <a href="http://www.modrails.org/" rel="nofollow">Passenger</a> (<code>mod_rails</code>) has come out which could be a better alternative than FastCGI. </p>
| 0
|
2009-04-18T18:33:31Z
|
[
"python",
"ruby-on-rails",
"ruby",
"django",
"active-directory"
] |
Python : How to convert markdown formatted text to text
| 761,824
|
<p>I need to convert markdown text to plain text format to display summary in my website. I want the code in python. </p>
| 16
|
2009-04-17T19:21:18Z
| 761,847
|
<p>This module will help do what you describe:</p>
<p><a href="http://www.freewisdom.org/projects/python-markdown/Using%5Fas%5Fa%5FModule">http://www.freewisdom.org/projects/python-markdown/Using_as_a_Module</a></p>
<p>Once you have converted the markdown to HTML, you can use a HTML parser to strip out the plain text.</p>
<p>Your code might look something like this:</p>
<pre><code>from BeautifulSoup import BeautifulSoup
from markdown import markdown
html = markdown(some_html_string)
text = ''.join(BeautifulSoup(html).findAll(text=True))
</code></pre>
| 25
|
2009-04-17T19:27:32Z
|
[
"python",
"parsing",
"markdown"
] |
Python : How to convert markdown formatted text to text
| 761,824
|
<p>I need to convert markdown text to plain text format to display summary in my website. I want the code in python. </p>
| 16
|
2009-04-17T19:21:18Z
| 761,901
|
<p>Commented and removed it because I finally think I see the rub here: It may be easier to convert your markdown text to HTML and remove HTML from the text. I'm not aware of anything to remove markdown from text effectively but there are many HTML to plain text solutions.</p>
| 1
|
2009-04-17T19:42:56Z
|
[
"python",
"parsing",
"markdown"
] |
Importing In Python
| 762,111
|
<p>Is it possible to import modules based on location? </p>
<p>(eg. do all modules i import have to be in /usr/lib64/python2.5/ or a similar dir?)</p>
<p>I'd like to import a module that's local to the current script.</p>
| 3
|
2009-04-17T20:37:07Z
| 762,120
|
<p>You can edit your <a href="http://docs.python.org/tutorial/modules.html#the-module-search-path" rel="nofollow">PYTHONPATH</a> to add or remove locations that python will search whenever you attempt an import.</p>
| 3
|
2009-04-17T20:39:58Z
|
[
"python",
"import"
] |
Importing In Python
| 762,111
|
<p>Is it possible to import modules based on location? </p>
<p>(eg. do all modules i import have to be in /usr/lib64/python2.5/ or a similar dir?)</p>
<p>I'd like to import a module that's local to the current script.</p>
| 3
|
2009-04-17T20:37:07Z
| 762,122
|
<ul>
<li><p>python will import from the current directory by default.</p></li>
<li><p><strong>sys.path</strong> is the variable that controls where python searches for imports.</p></li>
</ul>
| 3
|
2009-04-17T20:40:13Z
|
[
"python",
"import"
] |
Importing In Python
| 762,111
|
<p>Is it possible to import modules based on location? </p>
<p>(eg. do all modules i import have to be in /usr/lib64/python2.5/ or a similar dir?)</p>
<p>I'd like to import a module that's local to the current script.</p>
| 3
|
2009-04-17T20:37:07Z
| 762,125
|
<p>You can extend the path at runtime like this:</p>
<pre><code>sys.path.extend(map(os.path.abspath, ['other1/', 'other2/', 'yourlib/']))
</code></pre>
| 9
|
2009-04-17T20:41:04Z
|
[
"python",
"import"
] |
Importing In Python
| 762,111
|
<p>Is it possible to import modules based on location? </p>
<p>(eg. do all modules i import have to be in /usr/lib64/python2.5/ or a similar dir?)</p>
<p>I'd like to import a module that's local to the current script.</p>
| 3
|
2009-04-17T20:37:07Z
| 762,135
|
<p>You can import module that are in the same path the module you are importing to. For example:</p>
<p>Directory contains: <code>mod1.py, mod2.py</code></p>
<pre><code>mod2.py
--------
import mod1
</code></pre>
<p>Or you can add any directory to your PYTHON_PATH variable:</p>
<pre><code>import sys
sys.path.extend('/user/some/other/directory')
import mod1
</code></pre>
| 0
|
2009-04-17T20:43:14Z
|
[
"python",
"import"
] |
Importing In Python
| 762,111
|
<p>Is it possible to import modules based on location? </p>
<p>(eg. do all modules i import have to be in /usr/lib64/python2.5/ or a similar dir?)</p>
<p>I'd like to import a module that's local to the current script.</p>
| 3
|
2009-04-17T20:37:07Z
| 762,142
|
<p>It searches in ./lib by default.</p>
| 0
|
2009-04-17T20:46:45Z
|
[
"python",
"import"
] |
Importing In Python
| 762,111
|
<p>Is it possible to import modules based on location? </p>
<p>(eg. do all modules i import have to be in /usr/lib64/python2.5/ or a similar dir?)</p>
<p>I'd like to import a module that's local to the current script.</p>
| 3
|
2009-04-17T20:37:07Z
| 762,709
|
<p>For low-level control over the import process, the <a href="http://docs.python.org/library/imp.html" rel="nofollow">imp</a> module lets you import modules from arbitrary open files under arbitrary names.</p>
<p>For example, if this is <code>foo.py</code>:</p>
<pre><code>def x():
print 'hello, world'
</code></pre>
<p>Then this code:</p>
<pre><code>import imp
with open('foo.py', 'r') as module_file:
imp.load_module('module_name', module_file, '', ('', 'r', imp.PY_SOURCE))
import module_name
module_name.x()
</code></pre>
<p>prints "hello, world".</p>
| 0
|
2009-04-18T01:27:44Z
|
[
"python",
"import"
] |
Importing In Python
| 762,111
|
<p>Is it possible to import modules based on location? </p>
<p>(eg. do all modules i import have to be in /usr/lib64/python2.5/ or a similar dir?)</p>
<p>I'd like to import a module that's local to the current script.</p>
| 3
|
2009-04-17T20:37:07Z
| 763,809
|
<h2>Use <strong>init</strong>.py</h2>
<p>The only problem with doing dynamic modification of sys.path is that you need to repeat it in every script and hard-code the pathnames. That gets messy and non DRY if you have even two or three files. </p>
<p>Instead, if your file structure looks like this: </p>
<pre><code>~/foo/__init__.py
~/foo/foo.py
~/foo/bar/__init__.py
~/foo/bar/baz.py
</code></pre>
<p>Here the <strong>init</strong>.py's are blank files created with touch, while foo.py and baz.py are actual python scripts. Then you can do something like this: </p>
<pre><code>import sys
try:
from foo import foo
from foo.bar import baz
except ImportError:
"%s is not in %s. Add to your PYTHONPATH in ~/.bashrc" % \
(os.path.expanduser("~/foo"),sys.path)
</code></pre>
<p>Structuring your stuff as a package from the beginning is a <em>little</em> more work but makes it much easier to scale the project later and to see where imports are coming from. Moreover, if you move stuff around, you can use a single symlink rather than doing a find/replace through your codebase. E.g. if you moved '~/foo' to '~/downloads/foo', just do this: </p>
<pre><code>cd ~
ln -s ~/downloads/foo foo
</code></pre>
<p>And all your imports will still work. </p>
| 0
|
2009-04-18T17:34:48Z
|
[
"python",
"import"
] |
Django Template: Comparing Dictionary Length in IF Statement
| 762,118
|
<p>I am trying to compare the length of a dictionary inside a django template</p>
<p>For example, I would like to know the correct syntax to do the following:</p>
<pre><code> {% if error_messages %}
<div class="error">
{% if length(error_messages) > 1 %}
Please fix the following errors:
<div class="erroritem">
{% for key, value in error_messages.items %}
<br>{{ value }}
{% endfor %}
</div>
{% else %}
{% for key, value in error_messages.items %}
{{ value }}
{% endfor %}
{% endif %}
</div>
{% endif %}
</code></pre>
| 1
|
2009-04-17T20:38:44Z
| 762,134
|
<p>You could do this, using the <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#length">length</a> filter and the <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#ifequal">ifequal</a> tag:</p>
<pre><code>{% if error_messages %}
<div class="error">
{% ifequal error_messages|length 1 %}
error_messages[0]
{% else %}
Please fix the following errors:
<div class="erroritem">
{% for key, value in error_messages.items %}
<br>{{ value }}
{% endfor %}
</div>
{% endifequal %}
</div>
{% endif %}
</code></pre>
<p>Anything else will have to go down the path of <a href="http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags">custom tags and filters</a>.</p>
| 8
|
2009-04-17T20:42:35Z
|
[
"python",
"django"
] |
Django Template: Comparing Dictionary Length in IF Statement
| 762,118
|
<p>I am trying to compare the length of a dictionary inside a django template</p>
<p>For example, I would like to know the correct syntax to do the following:</p>
<pre><code> {% if error_messages %}
<div class="error">
{% if length(error_messages) > 1 %}
Please fix the following errors:
<div class="erroritem">
{% for key, value in error_messages.items %}
<br>{{ value }}
{% endfor %}
</div>
{% else %}
{% for key, value in error_messages.items %}
{{ value }}
{% endfor %}
{% endif %}
</div>
{% endif %}
</code></pre>
| 1
|
2009-04-17T20:38:44Z
| 2,194,667
|
<p>use the smart_if template tag: </p>
<p><a href="http://www.djangosnippets.org/snippets/1350/" rel="nofollow">http://www.djangosnippets.org/snippets/1350/</a></p>
<p>its super cool :)</p>
<p>can do all the obvious stuff like: </p>
<p>{% if articles|length >= 5 %}...{% endif %}</p>
<p>{% if "ifnotequal tag" != "beautiful" %}...{% endif %}</p>
| 1
|
2010-02-03T19:06:38Z
|
[
"python",
"django"
] |
Django Template: Comparing Dictionary Length in IF Statement
| 762,118
|
<p>I am trying to compare the length of a dictionary inside a django template</p>
<p>For example, I would like to know the correct syntax to do the following:</p>
<pre><code> {% if error_messages %}
<div class="error">
{% if length(error_messages) > 1 %}
Please fix the following errors:
<div class="erroritem">
{% for key, value in error_messages.items %}
<br>{{ value }}
{% endfor %}
</div>
{% else %}
{% for key, value in error_messages.items %}
{{ value }}
{% endfor %}
{% endif %}
</div>
{% endif %}
</code></pre>
| 1
|
2009-04-17T20:38:44Z
| 29,987,079
|
<p>You can actually use both the <code>if</code> tag and the <code>length</code> filter</p>
<pre><code>{% if page_detail.page_content|length > 2 %}
<strong><a class="see-more" href="#" data-prevent-default="">
Learn More</a></strong>{% endif %}
</code></pre>
<p><strong>NB</strong>
Ensure no spaces between the dictionary/object and the <code>length</code> filter when used in the <code>if</code> tag so as not to throw an exception.</p>
| 2
|
2015-05-01T12:44:52Z
|
[
"python",
"django"
] |
Overriding class member variables in Python (Django/Satchmo)
| 762,165
|
<p>I'm using Satchmo and Django and am trying to extend Satchmo's Product model. I'd like to make one of the fields in Satchmo's Product model have a default value in the admin without changing Satchmo's source code. Here is an abbreviated version of Satchmo's Product model:</p>
<pre><code>class Product(models.Model):
site = models.ForeignKey(Site, verbose_name='Site')
</code></pre>
<p>This is what I attempted to do to extend it...</p>
<pre><code>class MyProduct(Product):
Product.site = models.ForeignKey(Site, verbose_name='Site', editable=False, default=1)
</code></pre>
<p>This does not work, any ideas on why?</p>
| 1
|
2009-04-17T20:54:10Z
| 762,352
|
<p>For two reasons, firstly the way you are trying to override a class variable just isn't how it works in Python. You just define it in the class as normal, the same way that <code>def __init__(self):</code> is overriding the super-class initializer. But, Django model inheritance simply doesn't support this. If you want to add constraints, you could do so in the save() method.</p>
| 1
|
2009-04-17T21:55:30Z
|
[
"python",
"django",
"satchmo"
] |
Overriding class member variables in Python (Django/Satchmo)
| 762,165
|
<p>I'm using Satchmo and Django and am trying to extend Satchmo's Product model. I'd like to make one of the fields in Satchmo's Product model have a default value in the admin without changing Satchmo's source code. Here is an abbreviated version of Satchmo's Product model:</p>
<pre><code>class Product(models.Model):
site = models.ForeignKey(Site, verbose_name='Site')
</code></pre>
<p>This is what I attempted to do to extend it...</p>
<pre><code>class MyProduct(Product):
Product.site = models.ForeignKey(Site, verbose_name='Site', editable=False, default=1)
</code></pre>
<p>This does not work, any ideas on why?</p>
| 1
|
2009-04-17T20:54:10Z
| 762,579
|
<p>You can't change the superclass from a subclass. </p>
<p>You have the source. Use subversion. Make the change. When Satchmo is updated merge the updates around your change. </p>
| -2
|
2009-04-17T23:43:16Z
|
[
"python",
"django",
"satchmo"
] |
Overriding class member variables in Python (Django/Satchmo)
| 762,165
|
<p>I'm using Satchmo and Django and am trying to extend Satchmo's Product model. I'd like to make one of the fields in Satchmo's Product model have a default value in the admin without changing Satchmo's source code. Here is an abbreviated version of Satchmo's Product model:</p>
<pre><code>class Product(models.Model):
site = models.ForeignKey(Site, verbose_name='Site')
</code></pre>
<p>This is what I attempted to do to extend it...</p>
<pre><code>class MyProduct(Product):
Product.site = models.ForeignKey(Site, verbose_name='Site', editable=False, default=1)
</code></pre>
<p>This does not work, any ideas on why?</p>
| 1
|
2009-04-17T20:54:10Z
| 768,882
|
<p>You could probably monkeypatch it if you really wanted to:</p>
<pre><code>site_field = Product._meta.get_field('site')
site_field.editable = False
site_field.default = 1
</code></pre>
<p>But this is a nasty habit and could cause problems; arguably less maintainable than just patching Satchmo's source directly.</p>
| 1
|
2009-04-20T15:52:20Z
|
[
"python",
"django",
"satchmo"
] |
Matplotlib Build Problem: Error C1083: Cannot open include file: 'ft2build.h'
| 762,292
|
<p><strong>ft2build.h</strong> is located here:</p>
<p><strong>C:\Program Files\GnuWin32\include</strong></p>
<p>Initially, I made the same mistake as here:</p>
<p><a href="http://stackoverflow.com/questions/160938/fatal-error-c1083-cannot-open-include-file-tiffio-h-no-such-file-or-director">http://stackoverflow.com/questions/160938/fatal-error-c1083-cannot-open-include-file-tiffio-h-no-such-file-or-director</a></p>
<p>but since then, I've corrected that particular error (I've added the above directory to the "include" list, rather than the "executables" list), but I still get an error. The complete output is this:</p>
<pre><code>BUILDING MATPLOTLIB
matplotlib: 0.98.5.2
python: 2.6.2 Stackless 3.1b3 060516 (release26-maint, Apr
14 2009, 21:19:36) [MSC v.1500 32 bit (Intel)]
platform: win32
Windows version: (5, 1, 2600, 2, 'Service Pack 3')
REQUIRED DEPENDENCIES
numpy: 1.3.0
freetype2: found, but unknown version (no pkg-config)
* WARNING: Could not find 'freetype2' headers in any
* of '.', '.\freetype2'.
OPTIONAL BACKEND DEPENDENCIES
libpng: found, but unknown version (no pkg-config)
* Could not find 'libpng' headers in any of '.'
Tkinter: no
* No tk/win32 support for this python version yet
wxPython: 2.8.9.2
* WxAgg extension not required for wxPython >= 2.8
Gtk+: no
* Building for Gtk+ requires pygtk; you must be able
* to "import gtk" in your build/install environment
Mac OS X native: no
Qt: no
Qt4: no
Cairo: no
OPTIONAL DATE/TIMEZONE DEPENDENCIES
datetime: present, version unknown
dateutil: matplotlib will provide
pytz: matplotlib will provide
OPTIONAL USETEX DEPENDENCIES
dvipng: no
ghostscript: no
latex: no
pdftops: no
[Edit setup.cfg to suppress the above messages]
============================================================================
pymods ['pylab']
packages ['matplotlib', 'matplotlib.backends', 'matplotlib.projections', 'mpl_to
olkits', 'matplotlib.numerix', 'matplotlib.numerix.mlab', 'matplotlib.numerix.ma
', 'matplotlib.numerix.npyma', 'matplotlib.numerix.linear_algebra', 'matplotlib.
numerix.random_array', 'matplotlib.numerix.fft', 'matplotlib.delaunay', 'pytz',
'dateutil', 'dateutil/zoneinfo']
running build
running build_py
copying lib\matplotlib\mpl-data\matplotlibrc -> build\lib.win32-2.6\matplotlib\m
pl-data
copying lib\matplotlib\mpl-data\matplotlib.conf -> build\lib.win32-2.6\matplotli
b\mpl-data
running build_ext
building 'matplotlib.ft2font' extension
C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.exe /c /nologo /Ox /MD /W
3 /GS- /DNDEBUG -IC:\Python26\lib\site-packages\numpy\core\include -I. -IC:\Pyth
on26\lib\site-packages\numpy\core\include\freetype2 -I.\freetype2 -IC:\Python26\
include -IC:\Python26\include\Stackless -IC:\Python26\PC /Tpsrc/ft2font.cpp /Fob
uild\temp.win32-2.6\Release\src/ft2font.obj
ft2font.cpp
C:\Program Files\Microsoft Visual Studio 9.0\VC\INCLUDE\xlocale(342) : warning C
4530: C++ exception handler used, but unwind semantics are not enabled. Specify
/EHsc
c:\python26\lib\site-packages\matplotlib-0.98.5.2\src\ft2font.h(13) : fatal erro
r C1083: Cannot open include file: 'ft2build.h': No such file or directory
error: command '"C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.exe"' fa
iled with exit status 2
</code></pre>
<p>I should mention that this is Python 2.6</p>
| 23
|
2009-04-17T21:36:22Z
| 762,957
|
<p>Have you installed freetype properly? If you have, there should be a file named <code>ft2build.h</code> somewhere under the installation directory, and the directory where that file is found is the one that you should specify with <code>-I</code>. The string "GnuWin32" does not appear anywhere in the output of your build command, so it looks like you have not placed that directory in the correct include list.</p>
| 13
|
2009-04-18T05:27:41Z
|
[
"python",
"build",
"matplotlib",
"freetype"
] |
Matplotlib Build Problem: Error C1083: Cannot open include file: 'ft2build.h'
| 762,292
|
<p><strong>ft2build.h</strong> is located here:</p>
<p><strong>C:\Program Files\GnuWin32\include</strong></p>
<p>Initially, I made the same mistake as here:</p>
<p><a href="http://stackoverflow.com/questions/160938/fatal-error-c1083-cannot-open-include-file-tiffio-h-no-such-file-or-director">http://stackoverflow.com/questions/160938/fatal-error-c1083-cannot-open-include-file-tiffio-h-no-such-file-or-director</a></p>
<p>but since then, I've corrected that particular error (I've added the above directory to the "include" list, rather than the "executables" list), but I still get an error. The complete output is this:</p>
<pre><code>BUILDING MATPLOTLIB
matplotlib: 0.98.5.2
python: 2.6.2 Stackless 3.1b3 060516 (release26-maint, Apr
14 2009, 21:19:36) [MSC v.1500 32 bit (Intel)]
platform: win32
Windows version: (5, 1, 2600, 2, 'Service Pack 3')
REQUIRED DEPENDENCIES
numpy: 1.3.0
freetype2: found, but unknown version (no pkg-config)
* WARNING: Could not find 'freetype2' headers in any
* of '.', '.\freetype2'.
OPTIONAL BACKEND DEPENDENCIES
libpng: found, but unknown version (no pkg-config)
* Could not find 'libpng' headers in any of '.'
Tkinter: no
* No tk/win32 support for this python version yet
wxPython: 2.8.9.2
* WxAgg extension not required for wxPython >= 2.8
Gtk+: no
* Building for Gtk+ requires pygtk; you must be able
* to "import gtk" in your build/install environment
Mac OS X native: no
Qt: no
Qt4: no
Cairo: no
OPTIONAL DATE/TIMEZONE DEPENDENCIES
datetime: present, version unknown
dateutil: matplotlib will provide
pytz: matplotlib will provide
OPTIONAL USETEX DEPENDENCIES
dvipng: no
ghostscript: no
latex: no
pdftops: no
[Edit setup.cfg to suppress the above messages]
============================================================================
pymods ['pylab']
packages ['matplotlib', 'matplotlib.backends', 'matplotlib.projections', 'mpl_to
olkits', 'matplotlib.numerix', 'matplotlib.numerix.mlab', 'matplotlib.numerix.ma
', 'matplotlib.numerix.npyma', 'matplotlib.numerix.linear_algebra', 'matplotlib.
numerix.random_array', 'matplotlib.numerix.fft', 'matplotlib.delaunay', 'pytz',
'dateutil', 'dateutil/zoneinfo']
running build
running build_py
copying lib\matplotlib\mpl-data\matplotlibrc -> build\lib.win32-2.6\matplotlib\m
pl-data
copying lib\matplotlib\mpl-data\matplotlib.conf -> build\lib.win32-2.6\matplotli
b\mpl-data
running build_ext
building 'matplotlib.ft2font' extension
C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.exe /c /nologo /Ox /MD /W
3 /GS- /DNDEBUG -IC:\Python26\lib\site-packages\numpy\core\include -I. -IC:\Pyth
on26\lib\site-packages\numpy\core\include\freetype2 -I.\freetype2 -IC:\Python26\
include -IC:\Python26\include\Stackless -IC:\Python26\PC /Tpsrc/ft2font.cpp /Fob
uild\temp.win32-2.6\Release\src/ft2font.obj
ft2font.cpp
C:\Program Files\Microsoft Visual Studio 9.0\VC\INCLUDE\xlocale(342) : warning C
4530: C++ exception handler used, but unwind semantics are not enabled. Specify
/EHsc
c:\python26\lib\site-packages\matplotlib-0.98.5.2\src\ft2font.h(13) : fatal erro
r C1083: Cannot open include file: 'ft2build.h': No such file or directory
error: command '"C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.exe"' fa
iled with exit status 2
</code></pre>
<p>I should mention that this is Python 2.6</p>
| 23
|
2009-04-17T21:36:22Z
| 4,767,910
|
<p>For those who might have the same issue but on a Mac OS 10.6 (snow leopard) and Python 2.7. , the easiest solution I found was to get a make file which downloads Numpy, scipy and matplotlib and compile them for you. You can customize the make file to get you matplotlib only. Here is the <a href="http://stefan.sofa-rockers.org/2010/11/17/building-numpy-scipy-matplotlib-python-27-snow-leo/" rel="nofollow">link</a> to the solution.</p>
| 3
|
2011-01-22T12:55:35Z
|
[
"python",
"build",
"matplotlib",
"freetype"
] |
Matplotlib Build Problem: Error C1083: Cannot open include file: 'ft2build.h'
| 762,292
|
<p><strong>ft2build.h</strong> is located here:</p>
<p><strong>C:\Program Files\GnuWin32\include</strong></p>
<p>Initially, I made the same mistake as here:</p>
<p><a href="http://stackoverflow.com/questions/160938/fatal-error-c1083-cannot-open-include-file-tiffio-h-no-such-file-or-director">http://stackoverflow.com/questions/160938/fatal-error-c1083-cannot-open-include-file-tiffio-h-no-such-file-or-director</a></p>
<p>but since then, I've corrected that particular error (I've added the above directory to the "include" list, rather than the "executables" list), but I still get an error. The complete output is this:</p>
<pre><code>BUILDING MATPLOTLIB
matplotlib: 0.98.5.2
python: 2.6.2 Stackless 3.1b3 060516 (release26-maint, Apr
14 2009, 21:19:36) [MSC v.1500 32 bit (Intel)]
platform: win32
Windows version: (5, 1, 2600, 2, 'Service Pack 3')
REQUIRED DEPENDENCIES
numpy: 1.3.0
freetype2: found, but unknown version (no pkg-config)
* WARNING: Could not find 'freetype2' headers in any
* of '.', '.\freetype2'.
OPTIONAL BACKEND DEPENDENCIES
libpng: found, but unknown version (no pkg-config)
* Could not find 'libpng' headers in any of '.'
Tkinter: no
* No tk/win32 support for this python version yet
wxPython: 2.8.9.2
* WxAgg extension not required for wxPython >= 2.8
Gtk+: no
* Building for Gtk+ requires pygtk; you must be able
* to "import gtk" in your build/install environment
Mac OS X native: no
Qt: no
Qt4: no
Cairo: no
OPTIONAL DATE/TIMEZONE DEPENDENCIES
datetime: present, version unknown
dateutil: matplotlib will provide
pytz: matplotlib will provide
OPTIONAL USETEX DEPENDENCIES
dvipng: no
ghostscript: no
latex: no
pdftops: no
[Edit setup.cfg to suppress the above messages]
============================================================================
pymods ['pylab']
packages ['matplotlib', 'matplotlib.backends', 'matplotlib.projections', 'mpl_to
olkits', 'matplotlib.numerix', 'matplotlib.numerix.mlab', 'matplotlib.numerix.ma
', 'matplotlib.numerix.npyma', 'matplotlib.numerix.linear_algebra', 'matplotlib.
numerix.random_array', 'matplotlib.numerix.fft', 'matplotlib.delaunay', 'pytz',
'dateutil', 'dateutil/zoneinfo']
running build
running build_py
copying lib\matplotlib\mpl-data\matplotlibrc -> build\lib.win32-2.6\matplotlib\m
pl-data
copying lib\matplotlib\mpl-data\matplotlib.conf -> build\lib.win32-2.6\matplotli
b\mpl-data
running build_ext
building 'matplotlib.ft2font' extension
C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.exe /c /nologo /Ox /MD /W
3 /GS- /DNDEBUG -IC:\Python26\lib\site-packages\numpy\core\include -I. -IC:\Pyth
on26\lib\site-packages\numpy\core\include\freetype2 -I.\freetype2 -IC:\Python26\
include -IC:\Python26\include\Stackless -IC:\Python26\PC /Tpsrc/ft2font.cpp /Fob
uild\temp.win32-2.6\Release\src/ft2font.obj
ft2font.cpp
C:\Program Files\Microsoft Visual Studio 9.0\VC\INCLUDE\xlocale(342) : warning C
4530: C++ exception handler used, but unwind semantics are not enabled. Specify
/EHsc
c:\python26\lib\site-packages\matplotlib-0.98.5.2\src\ft2font.h(13) : fatal erro
r C1083: Cannot open include file: 'ft2build.h': No such file or directory
error: command '"C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.exe"' fa
iled with exit status 2
</code></pre>
<p>I should mention that this is Python 2.6</p>
| 23
|
2009-04-17T21:36:22Z
| 5,206,094
|
<p>This error comes about when building matplotlib on Ubuntu 10.10 also. The solution is to do:</p>
<pre><code>sudo apt-get install python-dev libfreetype6-dev
</code></pre>
| 57
|
2011-03-05T19:02:47Z
|
[
"python",
"build",
"matplotlib",
"freetype"
] |
Matplotlib Build Problem: Error C1083: Cannot open include file: 'ft2build.h'
| 762,292
|
<p><strong>ft2build.h</strong> is located here:</p>
<p><strong>C:\Program Files\GnuWin32\include</strong></p>
<p>Initially, I made the same mistake as here:</p>
<p><a href="http://stackoverflow.com/questions/160938/fatal-error-c1083-cannot-open-include-file-tiffio-h-no-such-file-or-director">http://stackoverflow.com/questions/160938/fatal-error-c1083-cannot-open-include-file-tiffio-h-no-such-file-or-director</a></p>
<p>but since then, I've corrected that particular error (I've added the above directory to the "include" list, rather than the "executables" list), but I still get an error. The complete output is this:</p>
<pre><code>BUILDING MATPLOTLIB
matplotlib: 0.98.5.2
python: 2.6.2 Stackless 3.1b3 060516 (release26-maint, Apr
14 2009, 21:19:36) [MSC v.1500 32 bit (Intel)]
platform: win32
Windows version: (5, 1, 2600, 2, 'Service Pack 3')
REQUIRED DEPENDENCIES
numpy: 1.3.0
freetype2: found, but unknown version (no pkg-config)
* WARNING: Could not find 'freetype2' headers in any
* of '.', '.\freetype2'.
OPTIONAL BACKEND DEPENDENCIES
libpng: found, but unknown version (no pkg-config)
* Could not find 'libpng' headers in any of '.'
Tkinter: no
* No tk/win32 support for this python version yet
wxPython: 2.8.9.2
* WxAgg extension not required for wxPython >= 2.8
Gtk+: no
* Building for Gtk+ requires pygtk; you must be able
* to "import gtk" in your build/install environment
Mac OS X native: no
Qt: no
Qt4: no
Cairo: no
OPTIONAL DATE/TIMEZONE DEPENDENCIES
datetime: present, version unknown
dateutil: matplotlib will provide
pytz: matplotlib will provide
OPTIONAL USETEX DEPENDENCIES
dvipng: no
ghostscript: no
latex: no
pdftops: no
[Edit setup.cfg to suppress the above messages]
============================================================================
pymods ['pylab']
packages ['matplotlib', 'matplotlib.backends', 'matplotlib.projections', 'mpl_to
olkits', 'matplotlib.numerix', 'matplotlib.numerix.mlab', 'matplotlib.numerix.ma
', 'matplotlib.numerix.npyma', 'matplotlib.numerix.linear_algebra', 'matplotlib.
numerix.random_array', 'matplotlib.numerix.fft', 'matplotlib.delaunay', 'pytz',
'dateutil', 'dateutil/zoneinfo']
running build
running build_py
copying lib\matplotlib\mpl-data\matplotlibrc -> build\lib.win32-2.6\matplotlib\m
pl-data
copying lib\matplotlib\mpl-data\matplotlib.conf -> build\lib.win32-2.6\matplotli
b\mpl-data
running build_ext
building 'matplotlib.ft2font' extension
C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.exe /c /nologo /Ox /MD /W
3 /GS- /DNDEBUG -IC:\Python26\lib\site-packages\numpy\core\include -I. -IC:\Pyth
on26\lib\site-packages\numpy\core\include\freetype2 -I.\freetype2 -IC:\Python26\
include -IC:\Python26\include\Stackless -IC:\Python26\PC /Tpsrc/ft2font.cpp /Fob
uild\temp.win32-2.6\Release\src/ft2font.obj
ft2font.cpp
C:\Program Files\Microsoft Visual Studio 9.0\VC\INCLUDE\xlocale(342) : warning C
4530: C++ exception handler used, but unwind semantics are not enabled. Specify
/EHsc
c:\python26\lib\site-packages\matplotlib-0.98.5.2\src\ft2font.h(13) : fatal erro
r C1083: Cannot open include file: 'ft2build.h': No such file or directory
error: command '"C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.exe"' fa
iled with exit status 2
</code></pre>
<p>I should mention that this is Python 2.6</p>
| 23
|
2009-04-17T21:36:22Z
| 12,326,339
|
<p>I had the same error in red hat 6. Turns out that I needed to install <code>freetype-devel</code>, not <code>freetype</code> (using <code>sudo yum install freetype-devel</code>)</p>
| 3
|
2012-09-07T22:42:44Z
|
[
"python",
"build",
"matplotlib",
"freetype"
] |
Matplotlib Build Problem: Error C1083: Cannot open include file: 'ft2build.h'
| 762,292
|
<p><strong>ft2build.h</strong> is located here:</p>
<p><strong>C:\Program Files\GnuWin32\include</strong></p>
<p>Initially, I made the same mistake as here:</p>
<p><a href="http://stackoverflow.com/questions/160938/fatal-error-c1083-cannot-open-include-file-tiffio-h-no-such-file-or-director">http://stackoverflow.com/questions/160938/fatal-error-c1083-cannot-open-include-file-tiffio-h-no-such-file-or-director</a></p>
<p>but since then, I've corrected that particular error (I've added the above directory to the "include" list, rather than the "executables" list), but I still get an error. The complete output is this:</p>
<pre><code>BUILDING MATPLOTLIB
matplotlib: 0.98.5.2
python: 2.6.2 Stackless 3.1b3 060516 (release26-maint, Apr
14 2009, 21:19:36) [MSC v.1500 32 bit (Intel)]
platform: win32
Windows version: (5, 1, 2600, 2, 'Service Pack 3')
REQUIRED DEPENDENCIES
numpy: 1.3.0
freetype2: found, but unknown version (no pkg-config)
* WARNING: Could not find 'freetype2' headers in any
* of '.', '.\freetype2'.
OPTIONAL BACKEND DEPENDENCIES
libpng: found, but unknown version (no pkg-config)
* Could not find 'libpng' headers in any of '.'
Tkinter: no
* No tk/win32 support for this python version yet
wxPython: 2.8.9.2
* WxAgg extension not required for wxPython >= 2.8
Gtk+: no
* Building for Gtk+ requires pygtk; you must be able
* to "import gtk" in your build/install environment
Mac OS X native: no
Qt: no
Qt4: no
Cairo: no
OPTIONAL DATE/TIMEZONE DEPENDENCIES
datetime: present, version unknown
dateutil: matplotlib will provide
pytz: matplotlib will provide
OPTIONAL USETEX DEPENDENCIES
dvipng: no
ghostscript: no
latex: no
pdftops: no
[Edit setup.cfg to suppress the above messages]
============================================================================
pymods ['pylab']
packages ['matplotlib', 'matplotlib.backends', 'matplotlib.projections', 'mpl_to
olkits', 'matplotlib.numerix', 'matplotlib.numerix.mlab', 'matplotlib.numerix.ma
', 'matplotlib.numerix.npyma', 'matplotlib.numerix.linear_algebra', 'matplotlib.
numerix.random_array', 'matplotlib.numerix.fft', 'matplotlib.delaunay', 'pytz',
'dateutil', 'dateutil/zoneinfo']
running build
running build_py
copying lib\matplotlib\mpl-data\matplotlibrc -> build\lib.win32-2.6\matplotlib\m
pl-data
copying lib\matplotlib\mpl-data\matplotlib.conf -> build\lib.win32-2.6\matplotli
b\mpl-data
running build_ext
building 'matplotlib.ft2font' extension
C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.exe /c /nologo /Ox /MD /W
3 /GS- /DNDEBUG -IC:\Python26\lib\site-packages\numpy\core\include -I. -IC:\Pyth
on26\lib\site-packages\numpy\core\include\freetype2 -I.\freetype2 -IC:\Python26\
include -IC:\Python26\include\Stackless -IC:\Python26\PC /Tpsrc/ft2font.cpp /Fob
uild\temp.win32-2.6\Release\src/ft2font.obj
ft2font.cpp
C:\Program Files\Microsoft Visual Studio 9.0\VC\INCLUDE\xlocale(342) : warning C
4530: C++ exception handler used, but unwind semantics are not enabled. Specify
/EHsc
c:\python26\lib\site-packages\matplotlib-0.98.5.2\src\ft2font.h(13) : fatal erro
r C1083: Cannot open include file: 'ft2build.h': No such file or directory
error: command '"C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.exe"' fa
iled with exit status 2
</code></pre>
<p>I should mention that this is Python 2.6</p>
| 23
|
2009-04-17T21:36:22Z
| 13,188,340
|
<p>Another solution for Mac OS X is to install Freetype with Homebrew.</p>
<pre><code>brew install freetype
</code></pre>
| 6
|
2012-11-02T02:13:29Z
|
[
"python",
"build",
"matplotlib",
"freetype"
] |
Matplotlib Build Problem: Error C1083: Cannot open include file: 'ft2build.h'
| 762,292
|
<p><strong>ft2build.h</strong> is located here:</p>
<p><strong>C:\Program Files\GnuWin32\include</strong></p>
<p>Initially, I made the same mistake as here:</p>
<p><a href="http://stackoverflow.com/questions/160938/fatal-error-c1083-cannot-open-include-file-tiffio-h-no-such-file-or-director">http://stackoverflow.com/questions/160938/fatal-error-c1083-cannot-open-include-file-tiffio-h-no-such-file-or-director</a></p>
<p>but since then, I've corrected that particular error (I've added the above directory to the "include" list, rather than the "executables" list), but I still get an error. The complete output is this:</p>
<pre><code>BUILDING MATPLOTLIB
matplotlib: 0.98.5.2
python: 2.6.2 Stackless 3.1b3 060516 (release26-maint, Apr
14 2009, 21:19:36) [MSC v.1500 32 bit (Intel)]
platform: win32
Windows version: (5, 1, 2600, 2, 'Service Pack 3')
REQUIRED DEPENDENCIES
numpy: 1.3.0
freetype2: found, but unknown version (no pkg-config)
* WARNING: Could not find 'freetype2' headers in any
* of '.', '.\freetype2'.
OPTIONAL BACKEND DEPENDENCIES
libpng: found, but unknown version (no pkg-config)
* Could not find 'libpng' headers in any of '.'
Tkinter: no
* No tk/win32 support for this python version yet
wxPython: 2.8.9.2
* WxAgg extension not required for wxPython >= 2.8
Gtk+: no
* Building for Gtk+ requires pygtk; you must be able
* to "import gtk" in your build/install environment
Mac OS X native: no
Qt: no
Qt4: no
Cairo: no
OPTIONAL DATE/TIMEZONE DEPENDENCIES
datetime: present, version unknown
dateutil: matplotlib will provide
pytz: matplotlib will provide
OPTIONAL USETEX DEPENDENCIES
dvipng: no
ghostscript: no
latex: no
pdftops: no
[Edit setup.cfg to suppress the above messages]
============================================================================
pymods ['pylab']
packages ['matplotlib', 'matplotlib.backends', 'matplotlib.projections', 'mpl_to
olkits', 'matplotlib.numerix', 'matplotlib.numerix.mlab', 'matplotlib.numerix.ma
', 'matplotlib.numerix.npyma', 'matplotlib.numerix.linear_algebra', 'matplotlib.
numerix.random_array', 'matplotlib.numerix.fft', 'matplotlib.delaunay', 'pytz',
'dateutil', 'dateutil/zoneinfo']
running build
running build_py
copying lib\matplotlib\mpl-data\matplotlibrc -> build\lib.win32-2.6\matplotlib\m
pl-data
copying lib\matplotlib\mpl-data\matplotlib.conf -> build\lib.win32-2.6\matplotli
b\mpl-data
running build_ext
building 'matplotlib.ft2font' extension
C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.exe /c /nologo /Ox /MD /W
3 /GS- /DNDEBUG -IC:\Python26\lib\site-packages\numpy\core\include -I. -IC:\Pyth
on26\lib\site-packages\numpy\core\include\freetype2 -I.\freetype2 -IC:\Python26\
include -IC:\Python26\include\Stackless -IC:\Python26\PC /Tpsrc/ft2font.cpp /Fob
uild\temp.win32-2.6\Release\src/ft2font.obj
ft2font.cpp
C:\Program Files\Microsoft Visual Studio 9.0\VC\INCLUDE\xlocale(342) : warning C
4530: C++ exception handler used, but unwind semantics are not enabled. Specify
/EHsc
c:\python26\lib\site-packages\matplotlib-0.98.5.2\src\ft2font.h(13) : fatal erro
r C1083: Cannot open include file: 'ft2build.h': No such file or directory
error: command '"C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.exe"' fa
iled with exit status 2
</code></pre>
<p>I should mention that this is Python 2.6</p>
| 23
|
2009-04-17T21:36:22Z
| 18,308,136
|
<p>I also fixed this problem by installing freetype using homebrew on Mac OS X. However, that was not sufficient, as the libraries were not linked properly under Mac OS X 10.7. So I had to manually add them to <code>pip</code> command as follows:</p>
<pre><code>brew install freetype
brew install libpng
LDFLAGS="-L/usr/local/opt/freetype/lib -L/usr/local/opt/libpng/lib" CPPFLAGS="-I/usr/local/opt/freetype/include -I/usr/local/opt/libpng/include -I/usr/local/opt/freetype/include/freetype2" pip install matplotlib
</code></pre>
<p>Note that you also have to add the folder <code>/usr/local/opt/freetype/include/freetype2</code>, which is not included by default on the homebrew notification, but will result in not finding <code>ft2build.h</code>.</p>
| 2
|
2013-08-19T07:04:16Z
|
[
"python",
"build",
"matplotlib",
"freetype"
] |
Matplotlib Build Problem: Error C1083: Cannot open include file: 'ft2build.h'
| 762,292
|
<p><strong>ft2build.h</strong> is located here:</p>
<p><strong>C:\Program Files\GnuWin32\include</strong></p>
<p>Initially, I made the same mistake as here:</p>
<p><a href="http://stackoverflow.com/questions/160938/fatal-error-c1083-cannot-open-include-file-tiffio-h-no-such-file-or-director">http://stackoverflow.com/questions/160938/fatal-error-c1083-cannot-open-include-file-tiffio-h-no-such-file-or-director</a></p>
<p>but since then, I've corrected that particular error (I've added the above directory to the "include" list, rather than the "executables" list), but I still get an error. The complete output is this:</p>
<pre><code>BUILDING MATPLOTLIB
matplotlib: 0.98.5.2
python: 2.6.2 Stackless 3.1b3 060516 (release26-maint, Apr
14 2009, 21:19:36) [MSC v.1500 32 bit (Intel)]
platform: win32
Windows version: (5, 1, 2600, 2, 'Service Pack 3')
REQUIRED DEPENDENCIES
numpy: 1.3.0
freetype2: found, but unknown version (no pkg-config)
* WARNING: Could not find 'freetype2' headers in any
* of '.', '.\freetype2'.
OPTIONAL BACKEND DEPENDENCIES
libpng: found, but unknown version (no pkg-config)
* Could not find 'libpng' headers in any of '.'
Tkinter: no
* No tk/win32 support for this python version yet
wxPython: 2.8.9.2
* WxAgg extension not required for wxPython >= 2.8
Gtk+: no
* Building for Gtk+ requires pygtk; you must be able
* to "import gtk" in your build/install environment
Mac OS X native: no
Qt: no
Qt4: no
Cairo: no
OPTIONAL DATE/TIMEZONE DEPENDENCIES
datetime: present, version unknown
dateutil: matplotlib will provide
pytz: matplotlib will provide
OPTIONAL USETEX DEPENDENCIES
dvipng: no
ghostscript: no
latex: no
pdftops: no
[Edit setup.cfg to suppress the above messages]
============================================================================
pymods ['pylab']
packages ['matplotlib', 'matplotlib.backends', 'matplotlib.projections', 'mpl_to
olkits', 'matplotlib.numerix', 'matplotlib.numerix.mlab', 'matplotlib.numerix.ma
', 'matplotlib.numerix.npyma', 'matplotlib.numerix.linear_algebra', 'matplotlib.
numerix.random_array', 'matplotlib.numerix.fft', 'matplotlib.delaunay', 'pytz',
'dateutil', 'dateutil/zoneinfo']
running build
running build_py
copying lib\matplotlib\mpl-data\matplotlibrc -> build\lib.win32-2.6\matplotlib\m
pl-data
copying lib\matplotlib\mpl-data\matplotlib.conf -> build\lib.win32-2.6\matplotli
b\mpl-data
running build_ext
building 'matplotlib.ft2font' extension
C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.exe /c /nologo /Ox /MD /W
3 /GS- /DNDEBUG -IC:\Python26\lib\site-packages\numpy\core\include -I. -IC:\Pyth
on26\lib\site-packages\numpy\core\include\freetype2 -I.\freetype2 -IC:\Python26\
include -IC:\Python26\include\Stackless -IC:\Python26\PC /Tpsrc/ft2font.cpp /Fob
uild\temp.win32-2.6\Release\src/ft2font.obj
ft2font.cpp
C:\Program Files\Microsoft Visual Studio 9.0\VC\INCLUDE\xlocale(342) : warning C
4530: C++ exception handler used, but unwind semantics are not enabled. Specify
/EHsc
c:\python26\lib\site-packages\matplotlib-0.98.5.2\src\ft2font.h(13) : fatal erro
r C1083: Cannot open include file: 'ft2build.h': No such file or directory
error: command '"C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.exe"' fa
iled with exit status 2
</code></pre>
<p>I should mention that this is Python 2.6</p>
| 23
|
2009-04-17T21:36:22Z
| 24,534,246
|
<p>I was able to solve this on Windows by doing the following:</p>
<pre><code> set INCLUDE=%INCLUDE%;C:\tmp\msvcr90-x32
set LIB=%LIB%;C:\tmp\msvcr90-x32
pip.exe install matplotlib
</code></pre>
<p>The link libraries for Freetype on windows can be found here: <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#matplotlib" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/#matplotlib</a> (from meawoppl's comment)</p>
<p>Just download the "matplotlibâ1.xâwindowsâlinkâlibraries.zip", and open the README from the zip.</p>
| 1
|
2014-07-02T14:48:43Z
|
[
"python",
"build",
"matplotlib",
"freetype"
] |
Is this Python code thread safe?
| 762,448
|
<pre><code>import time
import threading
class test(threading.Thread):
def __init__ (self):
threading.Thread.__init__(self)
self.doSkip = False
self.count = 0
def run(self):
while self.count<9:
self.work()
def skip(self):
self.doSkip = True
def work(self):
self.count+=1
time.sleep(1)
if(self.doSkip):
print "skipped"
self.doSkip = False
return
print self.count
t = test()
t.start()
while t.count<9:
time.sleep(2)
t.skip()
</code></pre>
| 2
|
2009-04-17T22:33:40Z
| 762,463
|
<p>Thread-safe in which way? I don't see any part you might want to protect here.</p>
<p>skip may reset the <code>doSkip</code> at any time, so there's not much point in locking it. You don't have any resources that are accessed at the same time - so IMHO nothing can be corrupted / unsafe in this code.</p>
<p>The only part that might run differently depending on locking / counting is how many "skip"s do you expect on every call to <code>.skip()</code>. If you want to ensure that every skip results in a skipped call to <code>.work()</code>, you should change <code>doSkip</code> into a counter that is protected by a lock on both increment and compare/decrement. Currently one thread might turn <code>doSkip</code> on after the check, but before the <code>doSkip</code> reset. It doesn't matter in this example, but in some real situation (with more code) it might make a difference.</p>
| 2
|
2009-04-17T22:42:54Z
|
[
"python",
"multithreading"
] |
Is this Python code thread safe?
| 762,448
|
<pre><code>import time
import threading
class test(threading.Thread):
def __init__ (self):
threading.Thread.__init__(self)
self.doSkip = False
self.count = 0
def run(self):
while self.count<9:
self.work()
def skip(self):
self.doSkip = True
def work(self):
self.count+=1
time.sleep(1)
if(self.doSkip):
print "skipped"
self.doSkip = False
return
print self.count
t = test()
t.start()
while t.count<9:
time.sleep(2)
t.skip()
</code></pre>
| 2
|
2009-04-17T22:33:40Z
| 762,470
|
<p>Apparently there isn't any critical resource, so I'd say it's thread-safe.</p>
<p>But as usual you can't predict in which order the two threads will be blocked/run by the scheduler.</p>
| 0
|
2009-04-17T22:44:50Z
|
[
"python",
"multithreading"
] |
Is this Python code thread safe?
| 762,448
|
<pre><code>import time
import threading
class test(threading.Thread):
def __init__ (self):
threading.Thread.__init__(self)
self.doSkip = False
self.count = 0
def run(self):
while self.count<9:
self.work()
def skip(self):
self.doSkip = True
def work(self):
self.count+=1
time.sleep(1)
if(self.doSkip):
print "skipped"
self.doSkip = False
return
print self.count
t = test()
t.start()
while t.count<9:
time.sleep(2)
t.skip()
</code></pre>
| 2
|
2009-04-17T22:33:40Z
| 762,481
|
<p>This is and will thread safe as long as you don't share data between threads.</p>
<p>If an other thread needs to read/write data to your thread class, then this won't be thread safe unless you protect data with some synchronization mechanism (like locks).</p>
| 0
|
2009-04-17T22:46:59Z
|
[
"python",
"multithreading"
] |
Is this Python code thread safe?
| 762,448
|
<pre><code>import time
import threading
class test(threading.Thread):
def __init__ (self):
threading.Thread.__init__(self)
self.doSkip = False
self.count = 0
def run(self):
while self.count<9:
self.work()
def skip(self):
self.doSkip = True
def work(self):
self.count+=1
time.sleep(1)
if(self.doSkip):
print "skipped"
self.doSkip = False
return
print self.count
t = test()
t.start()
while t.count<9:
time.sleep(2)
t.skip()
</code></pre>
| 2
|
2009-04-17T22:33:40Z
| 764,584
|
<p>Whenever the test of a mutex boolean ( e.g. if(self.doSkip) ) is separate from the set of the mutex boolean you will probably have threading problems.</p>
<p>The rule is that your thread will get swapped out at the most inconvenient time. That is, after the test and before the set. Moving them closer together reduces the window for screw-ups but does not eliminate them. You almost always need a specially created mechanism from the language or kernel to fully close that window.</p>
<p>The threading library has Semaphores that can be used to synchronize threads and/or create critical sections of code.</p>
| 1
|
2009-04-19T00:53:39Z
|
[
"python",
"multithreading"
] |
Is this Python code thread safe?
| 762,448
|
<pre><code>import time
import threading
class test(threading.Thread):
def __init__ (self):
threading.Thread.__init__(self)
self.doSkip = False
self.count = 0
def run(self):
while self.count<9:
self.work()
def skip(self):
self.doSkip = True
def work(self):
self.count+=1
time.sleep(1)
if(self.doSkip):
print "skipped"
self.doSkip = False
return
print self.count
t = test()
t.start()
while t.count<9:
time.sleep(2)
t.skip()
</code></pre>
| 2
|
2009-04-17T22:33:40Z
| 766,280
|
<p>To elaborate on DanM's answer, conceivably this could happen:</p>
<ol>
<li>Thread 1: <code>t.skip()</code></li>
<li>Thread 2: <code>if self.doSkip: print 'skipped'</code></li>
<li>Thread 1: <code>t.skip()</code></li>
<li>Thread 2: <code>self.doSkip = False</code></li>
<li>etc.</li>
</ol>
<p>In other words, while you might expect to see one "skipped" for every call to <code>t.skip()</code>, this sequence of events would violate that.</p>
<p>However, because of your <code>sleep()</code> calls, I think this sequence of events is actually impossible.</p>
<p>(unless your computer is running <em>really</em> slowly)</p>
| 0
|
2009-04-19T22:40:55Z
|
[
"python",
"multithreading"
] |
Python Regexp problem
| 762,482
|
<p>I'm trying to regexp a line from a webpage. The line is as follows:</p>
<pre><code><tr><td width=60 bgcolor='#ffffcc'><b>random Value</b></td><td align=center width=80>
</code></pre>
<p>This is what I tried, but it doesn't seem to work, can anyone help me out? 'htmlbody' contains the html page and no, I did not forget to import 're'.</p>
<pre><code>reg = re.compile("<tr><td width=60 bgcolor='#ffffcc'><b>([^<]*)</b></td><td align=center width=80>")
value = reg.search(htmlbody)
print 'Value is', value
</code></pre>
| 0
|
2009-04-17T22:47:53Z
| 762,496
|
<p>This</p>
<pre><code>import re
htmlbody = "<tr><td width=60 bgcolor='#ffffcc'><b>random Value</b></td><td align=center width=80>"
reg = re.compile("<tr><td width=60 bgcolor='#ffffcc'><b>([^<]*)</b></td><td align=center width=80>")
value = reg.search(htmlbody).group(1)
print 'Value is', value
</code></pre>
<p>prints out</p>
<pre><code>Value is random Value
</code></pre>
<p>Is this what you want?</p>
| 1
|
2009-04-17T22:56:45Z
|
[
"python",
"html",
"regex"
] |
Python Regexp problem
| 762,482
|
<p>I'm trying to regexp a line from a webpage. The line is as follows:</p>
<pre><code><tr><td width=60 bgcolor='#ffffcc'><b>random Value</b></td><td align=center width=80>
</code></pre>
<p>This is what I tried, but it doesn't seem to work, can anyone help me out? 'htmlbody' contains the html page and no, I did not forget to import 're'.</p>
<pre><code>reg = re.compile("<tr><td width=60 bgcolor='#ffffcc'><b>([^<]*)</b></td><td align=center width=80>")
value = reg.search(htmlbody)
print 'Value is', value
</code></pre>
| 0
|
2009-04-17T22:47:53Z
| 762,556
|
<p>There is no surefire way to do this with a regex. See <a href="http://stackoverflow.com/questions/701166">Can you provide some examples of why it is hard to parse XML and HTML with a regex?</a> for why. What you need is an HTML parser like <a href="http://docs.python.org/library/htmlparser.html" rel="nofollow">HTMLParser</a>:</p>
<pre><code>#!/usr/bin/python
from HTMLParser import HTMLParser
class FindTDs(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.level = 0
def handle_starttag(self, tag, attrs):
if tag == 'td':
self.level = self.level + 1
def handle_endtag(self, tag):
if tag == 'td':
self.level = self.level - 1
def handle_data(self, data):
if self.level > 0:
print data
find = FindTDs()
html = "<table>\n"
for i in range(3):
html += "\t<tr>"
for j in range(5):
html += "<td>%s.%s</td>" % (i, j)
html += "</tr>\n"
html += "</table>"
find.feed(html)
</code></pre>
| 4
|
2009-04-17T23:22:47Z
|
[
"python",
"html",
"regex"
] |
Python Regexp problem
| 762,482
|
<p>I'm trying to regexp a line from a webpage. The line is as follows:</p>
<pre><code><tr><td width=60 bgcolor='#ffffcc'><b>random Value</b></td><td align=center width=80>
</code></pre>
<p>This is what I tried, but it doesn't seem to work, can anyone help me out? 'htmlbody' contains the html page and no, I did not forget to import 're'.</p>
<pre><code>reg = re.compile("<tr><td width=60 bgcolor='#ffffcc'><b>([^<]*)</b></td><td align=center width=80>")
value = reg.search(htmlbody)
print 'Value is', value
</code></pre>
| 0
|
2009-04-17T22:47:53Z
| 762,559
|
<p>It sounds like you may want to use <code>findall</code> rather than <code>search</code>:</p>
<pre><code>reg = re.compile("<tr><td width=60 bgcolor='#ffffcc'><b>([^<]*)</b></td><td align=center width=80>")
value = reg.findall(htmlbody)
print 'Found %i match(es)' % len(value)
</code></pre>
<p>I have to caution you, though, that regular expressions are notoriously poor at handling HTML. You're better off using a proper parser using the <a href="http://docs.python.org/library/htmlparser.html" rel="nofollow">HTMLParser module built in to Python</a>.</p>
| 1
|
2009-04-17T23:26:50Z
|
[
"python",
"html",
"regex"
] |
Defining a table with sqlalchemy with a mysql unix timestamp
| 762,750
|
<p>Background, there are several ways to store dates in MySQ.</p>
<ol>
<li>As a string e.g. "09/09/2009".</li>
<li>As integer using the function UNIX_TIMESTAMP() this is supposedly the traditional unix time representation (you know seconds since the epoch plus/minus leap seconds).</li>
<li>As a MySQL TIMESTAMP, a mysql specific data type not the same than unix timestamps.</li>
<li><p>As a MySQL Date field, another mysql specific data type.</p>
<p>It's very important not to confuse case 2 with case 3 (or case 4).
I have an existing table with an integer date field (case 2) how can I define it in sqlalchemy in a way I don't have to access mysql's "FROM_UNIXTIME" function?</p>
<p>For the record, just using sqlalchemy.types.DateTime and hoping it does the right thing when it detects an integer column doesn't work, it works for timestamp fields and date fields.</p></li>
</ol>
| 3
|
2009-04-18T02:22:58Z
| 763,195
|
<p>So yeah, this approach works. And I ended up answering my own question :/, hope somebody finds this useful.</p>
<pre><code>import datetime, time
from sqlalchemy.types import TypeDecorator, DateTime
class IntegerDateTime(TypeDecorator):
"""a type that decorates DateTime, converts to unix time on
the way in and to datetime.datetime objects on the way out."""
impl = DateTime
def process_bind_param(self, value, engine):
"""Assumes a datetime.datetime"""
assert isinstance(value, datetime.datetime)
return int(time.mktime(value.timetuple()))
def process_result_value(self, value, engine):
return datetime.datetime.fromtimestamp(float(value))
def copy(self):
return IntegerDateTime(timezone=self.timezone)
</code></pre>
| 2
|
2009-04-18T09:19:18Z
|
[
"python",
"mysql",
"sqlalchemy"
] |
Defining a table with sqlalchemy with a mysql unix timestamp
| 762,750
|
<p>Background, there are several ways to store dates in MySQ.</p>
<ol>
<li>As a string e.g. "09/09/2009".</li>
<li>As integer using the function UNIX_TIMESTAMP() this is supposedly the traditional unix time representation (you know seconds since the epoch plus/minus leap seconds).</li>
<li>As a MySQL TIMESTAMP, a mysql specific data type not the same than unix timestamps.</li>
<li><p>As a MySQL Date field, another mysql specific data type.</p>
<p>It's very important not to confuse case 2 with case 3 (or case 4).
I have an existing table with an integer date field (case 2) how can I define it in sqlalchemy in a way I don't have to access mysql's "FROM_UNIXTIME" function?</p>
<p>For the record, just using sqlalchemy.types.DateTime and hoping it does the right thing when it detects an integer column doesn't work, it works for timestamp fields and date fields.</p></li>
</ol>
| 3
|
2009-04-18T02:22:58Z
| 866,566
|
<p>I think there is a couple of issues with the type decorator you showed.</p>
<ol>
<li><code>impl</code> should be <code>sqlalchemy.types.Integer</code> instead of <code>DateTime</code>.</li>
<li>The decorator should allow nullable columns.</li>
</ol>
<p>Here's the what I have in mind:</p>
<pre><code>
import datetime, time
from sqlalchemy.types import TypeDecorator, DateTime, Integer
class IntegerDateTime(TypeDecorator):
"""a type that decorates DateTime, converts to unix time on
the way in and to datetime.datetime objects on the way out."""
impl = Integer # In schema, you want these datetimes to
# be stored as integers.
def process_bind_param(self, value, _):
"""Assumes a datetime.datetime"""
if value is None:
return None # support nullability
elif isinstance(value, datetime.datetime):
return int(time.mktime(value.timetuple()))
raise ValueError("Can operate only on datetime values. "
"Offending value type: {0}".format(type(value).__name__))
def process_result_value(self, value, _):
if value is not None: # support nullability
return datetime.datetime.fromtimestamp(float(value))
</code></pre>
| 5
|
2009-05-15T00:44:41Z
|
[
"python",
"mysql",
"sqlalchemy"
] |
How do you store an app engine Image object in the db?
| 762,764
|
<p>I'm a bit stuck with my code:</p>
<pre><code>def setVenueImage(img):
img = images.Image(img.read())
x, y = photo_utils.getIdealResolution(img.width, img.height)
img.resize(x, y)
img.execute_transforms()
venue_obj = getVenueSingletonObject()
if venue_obj is None:
venue_obj = Venue(images = [img])
else:
venue_obj.images.append(img)
db.put(venue_obj)
</code></pre>
<p>I'm using django with app engine - so img.read() works fine.</p>
<p>In fact all of this code works fine up until I try to store img into the database. My model expects a Blob, so when I put in the image as img, then it throws a fit, and I get:</p>
<blockquote>
<p>BadValueError at /admin/venue/
Items in the images list must all be Blob instances</p>
</blockquote>
<p>Ok, so an Image must not be a Blob, but then how do I make it a blob? Blobs take in a byte string, but how do I make my image a byte string?</p>
<p>I haven't seen in the docs anywhere where they <em>actually</em> use image objects, so I'm not sure how this is all supposed to work, but I do want to use image objects to resize my image (I know you can do it in PIL, but I'd like to know how to do it with google's Image class).</p>
<p>Thanks for any pointers :)</p>
| 1
|
2009-04-18T02:36:47Z
| 762,777
|
<p><a href="http://code.google.com/appengine/docs/python/images/usingimages.html" rel="nofollow">http://code.google.com/appengine/docs/python/images/usingimages.html</a></p>
<p>I think that link should help. Good luck.</p>
| 0
|
2009-04-18T02:45:09Z
|
[
"python",
"google-app-engine",
"image"
] |
How do you store an app engine Image object in the db?
| 762,764
|
<p>I'm a bit stuck with my code:</p>
<pre><code>def setVenueImage(img):
img = images.Image(img.read())
x, y = photo_utils.getIdealResolution(img.width, img.height)
img.resize(x, y)
img.execute_transforms()
venue_obj = getVenueSingletonObject()
if venue_obj is None:
venue_obj = Venue(images = [img])
else:
venue_obj.images.append(img)
db.put(venue_obj)
</code></pre>
<p>I'm using django with app engine - so img.read() works fine.</p>
<p>In fact all of this code works fine up until I try to store img into the database. My model expects a Blob, so when I put in the image as img, then it throws a fit, and I get:</p>
<blockquote>
<p>BadValueError at /admin/venue/
Items in the images list must all be Blob instances</p>
</blockquote>
<p>Ok, so an Image must not be a Blob, but then how do I make it a blob? Blobs take in a byte string, but how do I make my image a byte string?</p>
<p>I haven't seen in the docs anywhere where they <em>actually</em> use image objects, so I'm not sure how this is all supposed to work, but I do want to use image objects to resize my image (I know you can do it in PIL, but I'd like to know how to do it with google's Image class).</p>
<p>Thanks for any pointers :)</p>
| 1
|
2009-04-18T02:36:47Z
| 762,860
|
<p>I'm not happy with this solution as it doesn't convert an Image object to a blob, but it will do for the time being:</p>
<pre><code>def setVenueImage(img):
original = img.read()
img = images.Image(original)
x, y = photo_utils.getIdealResolution(img.width, img.height)
img = images.resize(original, x, y)
venue_obj = getVenueSingletonObject()
if venue_obj is None:
venue_obj = Venue(images = [db.Blob(img)])
else:
venue_obj.images.append(db.Blob(img))
db.put(venue_obj)
</code></pre>
| 2
|
2009-04-18T04:09:34Z
|
[
"python",
"google-app-engine",
"image"
] |
How do you store an app engine Image object in the db?
| 762,764
|
<p>I'm a bit stuck with my code:</p>
<pre><code>def setVenueImage(img):
img = images.Image(img.read())
x, y = photo_utils.getIdealResolution(img.width, img.height)
img.resize(x, y)
img.execute_transforms()
venue_obj = getVenueSingletonObject()
if venue_obj is None:
venue_obj = Venue(images = [img])
else:
venue_obj.images.append(img)
db.put(venue_obj)
</code></pre>
<p>I'm using django with app engine - so img.read() works fine.</p>
<p>In fact all of this code works fine up until I try to store img into the database. My model expects a Blob, so when I put in the image as img, then it throws a fit, and I get:</p>
<blockquote>
<p>BadValueError at /admin/venue/
Items in the images list must all be Blob instances</p>
</blockquote>
<p>Ok, so an Image must not be a Blob, but then how do I make it a blob? Blobs take in a byte string, but how do I make my image a byte string?</p>
<p>I haven't seen in the docs anywhere where they <em>actually</em> use image objects, so I'm not sure how this is all supposed to work, but I do want to use image objects to resize my image (I know you can do it in PIL, but I'd like to know how to do it with google's Image class).</p>
<p>Thanks for any pointers :)</p>
| 1
|
2009-04-18T02:36:47Z
| 773,127
|
<p><a href="http://aralbalkan.com/1333" rel="nofollow">http://aralbalkan.com/1333</a></p>
<p>try this link, it is about a GAW SWF project and sources are inclued.</p>
| 0
|
2009-04-21T15:20:44Z
|
[
"python",
"google-app-engine",
"image"
] |
How do you store an app engine Image object in the db?
| 762,764
|
<p>I'm a bit stuck with my code:</p>
<pre><code>def setVenueImage(img):
img = images.Image(img.read())
x, y = photo_utils.getIdealResolution(img.width, img.height)
img.resize(x, y)
img.execute_transforms()
venue_obj = getVenueSingletonObject()
if venue_obj is None:
venue_obj = Venue(images = [img])
else:
venue_obj.images.append(img)
db.put(venue_obj)
</code></pre>
<p>I'm using django with app engine - so img.read() works fine.</p>
<p>In fact all of this code works fine up until I try to store img into the database. My model expects a Blob, so when I put in the image as img, then it throws a fit, and I get:</p>
<blockquote>
<p>BadValueError at /admin/venue/
Items in the images list must all be Blob instances</p>
</blockquote>
<p>Ok, so an Image must not be a Blob, but then how do I make it a blob? Blobs take in a byte string, but how do I make my image a byte string?</p>
<p>I haven't seen in the docs anywhere where they <em>actually</em> use image objects, so I'm not sure how this is all supposed to work, but I do want to use image objects to resize my image (I know you can do it in PIL, but I'd like to know how to do it with google's Image class).</p>
<p>Thanks for any pointers :)</p>
| 1
|
2009-04-18T02:36:47Z
| 899,950
|
<p>This will probably work:</p>
<pre><code>def setVenueImage(img):
img = images.Image(img.read())
x, y = photo_utils.getIdealResolution(img.width, img.height)
img.resize(x, y)
img_bytes = img.execute_transforms() # Converts to PNG
venue_obj = getVenueSingletonObject()
if venue_obj is None:
venue_obj = Venue(images = [img_bytes])
else:
venue_obj.images.append(img_bytes)
db.put(venue_obj)
</code></pre>
<p>I'm assuming that Venue.images is a ListProperty(db.Blob), correct? This is probably the wrong thing to do. Define a VenueImage model with a simple blob property and store its key into the Venue. If you put the images in there directly you'll hit the 1MB row limit on the datastore.</p>
| 2
|
2009-05-22T20:54:28Z
|
[
"python",
"google-app-engine",
"image"
] |
How do i convert WMD markdown syntax to HTML on my site?
| 763,087
|
<p>Am using django and am implementing WMD on my site, am just wondering how do i convert the markdown syntax to HTML for display purposes, is there some sort of function i should call to do this conversion?</p>
<p>What is the best way to handle markdown ie. do i save the markdown as is to the database then parse it when displaying it or should i save the converted HTML then convert it to markup during editing?</p>
| 3
|
2009-04-18T07:21:39Z
| 763,102
|
<p>Check out the <a href="http://docs.djangoproject.com/en/1.0/ref/contrib/#markup" rel="nofollow">markup</a> add-on which comes with Django. That is what you are looking for.</p>
<blockquote>
<p>To activate these filters, add 'django.contrib.markup' to your INSTALLED_APPS setting. Once youâve done that, use {% load markup %} in a template, and youâll have access to these filters. For more documentation, read the source code in django/contrib/markup/templatetags/markup.py.</p>
</blockquote>
<p>Also check out <a href="http://www.freewisdom.org/projects/python-markdown/Django" rel="nofollow">this article</a> for some more details if you're still stuck.</p>
| 7
|
2009-04-18T07:47:21Z
|
[
"python",
"html",
"django",
"markdown",
"wmd"
] |
Auto GET to argument of view
| 763,103
|
<pre><code>some_view?param1=10&param2=20
def some_view(request, param1, param2):
</code></pre>
<p>Is such possible in Django?</p>
| 0
|
2009-04-18T07:48:08Z
| 763,107
|
<p>I'm not sure it's possible to get it to pass them as <em>arguments</em> to the view function, but why can't you access the <code>GET </code> variables from <code>request.GET</code>? Given that URL, Django would have <code>request.GET['param1']</code> be 10 and <code>request.GET['param2']</code> be 20. Otherwise, you'd have to come up with some kind of weird regular expression to try and do what you want.</p>
| 1
|
2009-04-18T07:54:09Z
|
[
"python",
"django",
"django-urls",
"django-views"
] |
Auto GET to argument of view
| 763,103
|
<pre><code>some_view?param1=10&param2=20
def some_view(request, param1, param2):
</code></pre>
<p>Is such possible in Django?</p>
| 0
|
2009-04-18T07:48:08Z
| 763,133
|
<p>I agree with Paolo... the stuff after the '?' are GET parameters and should probably be treated as such. That said, if you really want to keep the definition of some_view() as you've stated in the question, you could do something like:</p>
<pre><code>from django.http import Http404
def some_view_proxy(request):
if 'param1' in request.GET and 'param2' in request.GET:
return some_view(request, request.GET['param1'],
request.GET['param2'])
raise Http404
</code></pre>
<p>Or you could just define some_view() like this and use the GET params. Just curious, why do you want that?</p>
| 1
|
2009-04-18T08:27:15Z
|
[
"python",
"django",
"django-urls",
"django-views"
] |
Auto GET to argument of view
| 763,103
|
<pre><code>some_view?param1=10&param2=20
def some_view(request, param1, param2):
</code></pre>
<p>Is such possible in Django?</p>
| 0
|
2009-04-18T07:48:08Z
| 763,357
|
<p>Instead of fighting Django, why not just request some_view/10/20 and then set up urls.py to extract the arguments?</p>
| 1
|
2009-04-18T12:26:15Z
|
[
"python",
"django",
"django-urls",
"django-views"
] |
Auto GET to argument of view
| 763,103
|
<pre><code>some_view?param1=10&param2=20
def some_view(request, param1, param2):
</code></pre>
<p>Is such possible in Django?</p>
| 0
|
2009-04-18T07:48:08Z
| 763,387
|
<p>You could always write a decorator. Eg. something like (untested):</p>
<pre><code>def map_params(func):
def decorated(request):
return func(request, **request.GET)
return decorated
@map_params
def some_view(request, param1, param2):
...
</code></pre>
| 3
|
2009-04-18T12:47:22Z
|
[
"python",
"django",
"django-urls",
"django-views"
] |
How to interact through vim?
| 763,372
|
<p>I am writing an editor which has lot of parameters that could be easily interacted with through text. I find it inconvenient to implement a separate text-editor or lots of UI code for every little parameter. Usual buttons, boxes and gadgets would be burdensome and clumsy. I'd much rather let user interact with those parameters through vim.</p>
<p>The preferable way for me would be to get editor open vim with my text buffer. Then, when one would save the text buffer in vim, my editor would get notified from that and update it's view.</p>
| 1
|
2009-04-18T12:34:43Z
| 763,381
|
<p>Check out <a href="https://addons.mozilla.org/en-US/firefox/addon/4125" rel="nofollow">It's All Text!</a>. It's a Firefox add-in that does something similar for <code>textarea</code>s on web pages, except the editor in question is configurable.</p>
| 2
|
2009-04-18T12:43:28Z
|
[
"python",
"linux",
"vim"
] |
How to interact through vim?
| 763,372
|
<p>I am writing an editor which has lot of parameters that could be easily interacted with through text. I find it inconvenient to implement a separate text-editor or lots of UI code for every little parameter. Usual buttons, boxes and gadgets would be burdensome and clumsy. I'd much rather let user interact with those parameters through vim.</p>
<p>The preferable way for me would be to get editor open vim with my text buffer. Then, when one would save the text buffer in vim, my editor would get notified from that and update it's view.</p>
| 1
|
2009-04-18T12:34:43Z
| 763,426
|
<p>Write your intermediate results (what you want the user to edit) to a temp file. Then use the <code>$EDITOR</code> environment variable in a system call to make the user edit the temp file, and read the results when the process finishes.</p>
<p>This lets users configure which editor they want to use in a pseudo-standard fashion.</p>
| 6
|
2009-04-18T13:19:31Z
|
[
"python",
"linux",
"vim"
] |
How to interact through vim?
| 763,372
|
<p>I am writing an editor which has lot of parameters that could be easily interacted with through text. I find it inconvenient to implement a separate text-editor or lots of UI code for every little parameter. Usual buttons, boxes and gadgets would be burdensome and clumsy. I'd much rather let user interact with those parameters through vim.</p>
<p>The preferable way for me would be to get editor open vim with my text buffer. Then, when one would save the text buffer in vim, my editor would get notified from that and update it's view.</p>
| 1
|
2009-04-18T12:34:43Z
| 763,983
|
<p>You can also think about integrating VIM in to your app. <a href="http://pida.co.uk/" rel="nofollow">Pida</a> does this</p>
| 1
|
2009-04-18T19:14:10Z
|
[
"python",
"linux",
"vim"
] |
Python Beginner: How to Prevent 'finally' from executing?
| 763,480
|
<p>The function code:</p>
<pre><code># Connect to the DB
try:
dbi = MySQLdb.connect(host='localhost', \
user='user', \
passwd='pass', \
db='dbname', \
port=3309)
print "Connected to DB ..."
except MySQLdb.Error, e:
apiErr = 2
apiErrMsg = "Error %d: %s" % (e.args[0], e.args[1])
return
# To prevent try..finally bug in python2.4,
# one has to nest the "try: except:" part.
try:
try:
sql = dbi.cursor()
sql.execute("""
SELECT *
FROM table
WHERE idClient = %s
""", (key, ))
access = sql.fetchall()
# [some more code here]
except MySQLdb.Error, e:
apiErr = 2
apiErrMsg = "Error %d: %s" % (e.args[0], e.args[1])
return
finally:
sql.close()
dbi.close()
</code></pre>
<p>I understand that in a try .. except .. finally, the finally block will always execute.
In the above code, I don't want the finally in the second try block to execute if there is an exception in the first try block. What am I doing wrong?</p>
<p>(Note: Using python 2.4)</p>
<p>Clarification: I am not aware if MySQLdb closes connections automatically when an error occurs. The problem I am facing with the above code is, when there is an error in establishing a connection (the first try block of the code), calling dbi.close() in the finally block raises "AttributeError: 'NoneType' object has no attribute 'close'" with reference to dbi ... </p>
<p><strong>Solution</strong>:
This worked as desired -</p>
<pre><code># define at the start
dbi = None
sql = None
</code></pre>
<p>In the finally block, </p>
<pre><code>if sql is not None:
sql.close()
if dbi is not None:
dbi.close()
</code></pre>
<p>Thanks to those who replied. I learned something new from all of you. (I'll try to phrase my questions more clearly the next time :).</p>
| 3
|
2009-04-18T14:01:21Z
| 763,484
|
<p>Don't use finally. If you don't want the code to always be executed then you should find another flow control structure that meets your needs.</p>
<p>One way to accomplish this behavior is to move the statements in your 'finally' block to the bottom of your 'try' block. That way they won't get executed when an exception is thrown but will get executed, after all other statements, otherwise.</p>
<p><strong>EDIT:</strong></p>
<p>After further discussion it appears that in your case you do actually want to use 'finally'. What I recommend is checking to see if your connection has already been closed before you attempt to close it.</p>
| 4
|
2009-04-18T14:05:34Z
|
[
"python"
] |
Python Beginner: How to Prevent 'finally' from executing?
| 763,480
|
<p>The function code:</p>
<pre><code># Connect to the DB
try:
dbi = MySQLdb.connect(host='localhost', \
user='user', \
passwd='pass', \
db='dbname', \
port=3309)
print "Connected to DB ..."
except MySQLdb.Error, e:
apiErr = 2
apiErrMsg = "Error %d: %s" % (e.args[0], e.args[1])
return
# To prevent try..finally bug in python2.4,
# one has to nest the "try: except:" part.
try:
try:
sql = dbi.cursor()
sql.execute("""
SELECT *
FROM table
WHERE idClient = %s
""", (key, ))
access = sql.fetchall()
# [some more code here]
except MySQLdb.Error, e:
apiErr = 2
apiErrMsg = "Error %d: %s" % (e.args[0], e.args[1])
return
finally:
sql.close()
dbi.close()
</code></pre>
<p>I understand that in a try .. except .. finally, the finally block will always execute.
In the above code, I don't want the finally in the second try block to execute if there is an exception in the first try block. What am I doing wrong?</p>
<p>(Note: Using python 2.4)</p>
<p>Clarification: I am not aware if MySQLdb closes connections automatically when an error occurs. The problem I am facing with the above code is, when there is an error in establishing a connection (the first try block of the code), calling dbi.close() in the finally block raises "AttributeError: 'NoneType' object has no attribute 'close'" with reference to dbi ... </p>
<p><strong>Solution</strong>:
This worked as desired -</p>
<pre><code># define at the start
dbi = None
sql = None
</code></pre>
<p>In the finally block, </p>
<pre><code>if sql is not None:
sql.close()
if dbi is not None:
dbi.close()
</code></pre>
<p>Thanks to those who replied. I learned something new from all of you. (I'll try to phrase my questions more clearly the next time :).</p>
| 3
|
2009-04-18T14:01:21Z
| 763,499
|
<p>I think in this case you do want to use finally, because you want to close those connections. </p>
<p>I disagree with the notion that you should have two try blocks in the same method.</p>
<p>I think the flaw in the design is acquiring the connection and performing the query in the same method. I would recommend separating the two. A service class or method knows about the unit of work. It should acquire the connection, pass it to another class that performs the query, and closes the connection when it's done. That way the query method can throw any exception it encounters and leave the cleanup to the class or method that's responsible for the connection.</p>
| 5
|
2009-04-18T14:14:58Z
|
[
"python"
] |
Python Beginner: How to Prevent 'finally' from executing?
| 763,480
|
<p>The function code:</p>
<pre><code># Connect to the DB
try:
dbi = MySQLdb.connect(host='localhost', \
user='user', \
passwd='pass', \
db='dbname', \
port=3309)
print "Connected to DB ..."
except MySQLdb.Error, e:
apiErr = 2
apiErrMsg = "Error %d: %s" % (e.args[0], e.args[1])
return
# To prevent try..finally bug in python2.4,
# one has to nest the "try: except:" part.
try:
try:
sql = dbi.cursor()
sql.execute("""
SELECT *
FROM table
WHERE idClient = %s
""", (key, ))
access = sql.fetchall()
# [some more code here]
except MySQLdb.Error, e:
apiErr = 2
apiErrMsg = "Error %d: %s" % (e.args[0], e.args[1])
return
finally:
sql.close()
dbi.close()
</code></pre>
<p>I understand that in a try .. except .. finally, the finally block will always execute.
In the above code, I don't want the finally in the second try block to execute if there is an exception in the first try block. What am I doing wrong?</p>
<p>(Note: Using python 2.4)</p>
<p>Clarification: I am not aware if MySQLdb closes connections automatically when an error occurs. The problem I am facing with the above code is, when there is an error in establishing a connection (the first try block of the code), calling dbi.close() in the finally block raises "AttributeError: 'NoneType' object has no attribute 'close'" with reference to dbi ... </p>
<p><strong>Solution</strong>:
This worked as desired -</p>
<pre><code># define at the start
dbi = None
sql = None
</code></pre>
<p>In the finally block, </p>
<pre><code>if sql is not None:
sql.close()
if dbi is not None:
dbi.close()
</code></pre>
<p>Thanks to those who replied. I learned something new from all of you. (I'll try to phrase my questions more clearly the next time :).</p>
| 3
|
2009-04-18T14:01:21Z
| 763,550
|
<p>Use <code>else:</code> instead of <code>finally:</code>. See the <a href="http://docs.python.org/tutorial/errors.html#handling-exceptions">Exception Handling</a> part of the docs:</p>
<blockquote>
<p>The <code>try ... except</code> statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception.</p>
</blockquote>
<pre><code>for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print 'cannot open', arg
else:
print arg, 'has', len(f.readlines()), 'lines'
f.close()
</code></pre>
<p>..basically:</p>
<pre><code>try:
[code that might error]
except IOError:
[This code is only ran when IOError is raised]
else:
[This code is only ran when NO exception is raised]
finally:
[This code is always run, both if an exception is raised or not]
</code></pre>
| 6
|
2009-04-18T14:47:59Z
|
[
"python"
] |
Priority issue in Sitemaps
| 763,485
|
<p>I am trying to use Django sitemaps. </p>
<pre><code>class BlogSiteMap(Sitemap):
"""A simple class to get sitemaps for blog"""
changefreq = 'hourly'
priority = 0.5
def items(self):
return Blog.objects.order_by('-pubDate')
def lastmod(self, obj):
return obj.pubDate
</code></pre>
<p>My problem is..I wanted to set the priority of first 3 blog object as 1.0 and rest of them
as 0.5 priority.</p>
<p>I read the <a href="http://docs.djangoproject.com/en/dev/ref/contrib/sitemaps/#ref-contrib-sitemaps" rel="nofollow">documentation</a> but couldn't any way out of it.</p>
<p>Any help would be appreciable. Thanks in advance.</p>
| 1
|
2009-04-18T14:05:41Z
| 763,571
|
<p>I think you can alter each object with its priority. Like that for example:</p>
<pre><code>def items(self):
for i, obj in enumerate(Blog.objects.order_by('-pubDate')):
obj.priority = i < 3 and 1 or 0.5
yield obj
def priority(self, obj):
return obj.priority
</code></pre>
| 1
|
2009-04-18T15:02:47Z
|
[
"python",
"django",
"sitemap"
] |
Priority issue in Sitemaps
| 763,485
|
<p>I am trying to use Django sitemaps. </p>
<pre><code>class BlogSiteMap(Sitemap):
"""A simple class to get sitemaps for blog"""
changefreq = 'hourly'
priority = 0.5
def items(self):
return Blog.objects.order_by('-pubDate')
def lastmod(self, obj):
return obj.pubDate
</code></pre>
<p>My problem is..I wanted to set the priority of first 3 blog object as 1.0 and rest of them
as 0.5 priority.</p>
<p>I read the <a href="http://docs.djangoproject.com/en/dev/ref/contrib/sitemaps/#ref-contrib-sitemaps" rel="nofollow">documentation</a> but couldn't any way out of it.</p>
<p>Any help would be appreciable. Thanks in advance.</p>
| 1
|
2009-04-18T14:05:41Z
| 898,447
|
<p>Something like that might work:</p>
<pre><code>def priority(self, obj):
if obj.id in list(Blog.objects.all()[:3].values_list('id'))
return 1.0
else:
return 0.5
</code></pre>
| 0
|
2009-05-22T15:23:40Z
|
[
"python",
"django",
"sitemap"
] |
How do I store a string with a `"` in it?
| 763,654
|
<p>I want to have a JSON object with the value of an attribute as a string with the character <code>"</code>.
For example:</p>
<pre><code>{
"Dimensions" : " 12.0" x 9.6" "
}
</code></pre>
<p>Obviously this is not possible. How do I do this?
With Python.</p>
| 1
|
2009-04-18T15:57:00Z
| 763,660
|
<p>JSON.stringify, if using Javascript, will escape it for you.<br />
If not, you can escape them like \" (put a \ in front)<br />
Edit: in Python, try <a href="http://ayaz.wordpress.com/2007/04/22/reescape-pythons-equivalent-of-phps-addslashes/" rel="nofollow">re.escape()</a> or just replace all " with \":</p>
<pre><code>"json string".replace("\"","\\\"");
</code></pre>
| 1
|
2009-04-18T15:59:25Z
|
[
"python",
"json"
] |
How do I store a string with a `"` in it?
| 763,654
|
<p>I want to have a JSON object with the value of an attribute as a string with the character <code>"</code>.
For example:</p>
<pre><code>{
"Dimensions" : " 12.0" x 9.6" "
}
</code></pre>
<p>Obviously this is not possible. How do I do this?
With Python.</p>
| 1
|
2009-04-18T15:57:00Z
| 763,688
|
<p>Isaac is correct.</p>
<p>As for how to do it in python, you need to provide a more detailed explanation of how you are building your <code>JSON</code> object. For example, let's say you're using no external libraries and are doing it manually (ridiculous, I know), you would do this:</p>
<pre><code>>>> string = "{ \"Dimensions\" : \" 12.0\\\" x 9.6\\\" \" }"
>>> print string
{ "Dimensions" : " 12.0\" x 9.6\" " }
</code></pre>
<p>Obviously this is kind of silly. If you are using the standard python json module, try this:</p>
<pre><code>from json import JSONEncoder
encoder = JSONEncoder()
string = encoder.encode({ "Dimensions":" 12.0\" x 9.6\" " })
>>> print string
{"Dimensions": " 12.0\" x 9.6\" "}
</code></pre>
<p>which is the desired result. </p>
| 7
|
2009-04-18T16:12:10Z
|
[
"python",
"json"
] |
How do I store a string with a `"` in it?
| 763,654
|
<p>I want to have a JSON object with the value of an attribute as a string with the character <code>"</code>.
For example:</p>
<pre><code>{
"Dimensions" : " 12.0" x 9.6" "
}
</code></pre>
<p>Obviously this is not possible. How do I do this?
With Python.</p>
| 1
|
2009-04-18T15:57:00Z
| 765,258
|
<p>Python has two symbols you can use to specify string literals, the single quote and the double quote. </p>
<p>For example:
my_string = "I'm home!"</p>
<p>Or, more relevant to you, </p>
<pre><code>>>> string = '{ "Dimensions" : " 12.0\\\" x 9.6\\\" " }'
>>> print string
{ "Dimensions" : " 12.0\" x 9.6\" " }
</code></pre>
<p>You can also prefix the string with 'r' to specify it is a raw string, so backslash escaped sequences are not processed, making it cleaner.</p>
<pre><code>>>> string = r'{ "Dimensions" : " 12.0\" x 9.6\" " }'
>>> print string
{ "Dimensions" : " 12.0\" x 9.6\" " }
</code></pre>
| 3
|
2009-04-19T11:29:19Z
|
[
"python",
"json"
] |
python, "a in b" keyword, how about multiple a's?
| 763,944
|
<p>My adventures in Python continue and my favorite books are silent again. Python offers a built-in way to test if a variable is inside an iterable object, using the 'in' keyword:</p>
<pre><code>if "a" in "abrakadabra" :
print "it is definitely here"
</code></pre>
<p>But is it possible to test if more than one item is in the list (any one)?
Currently, I'm using the syntax below, but it is kinda long:</p>
<pre><code>if "// @in " in sTxt or "// @out " in sTxt or "// @ret " in sTxt or <10 more>
print "found."
</code></pre>
<p>Of course regexes can help, but using regexes will take lots of verbose of code and will
not be as clear as "a in b". Are there any other Pythonic ways?</p>
| 15
|
2009-04-18T18:53:11Z
| 763,947
|
<p><code>any(snippet in text_body for snippet in ("hi", "foo", "bar", "spam"))</code></p>
| 7
|
2009-04-18T18:57:12Z
|
[
"python"
] |
python, "a in b" keyword, how about multiple a's?
| 763,944
|
<p>My adventures in Python continue and my favorite books are silent again. Python offers a built-in way to test if a variable is inside an iterable object, using the 'in' keyword:</p>
<pre><code>if "a" in "abrakadabra" :
print "it is definitely here"
</code></pre>
<p>But is it possible to test if more than one item is in the list (any one)?
Currently, I'm using the syntax below, but it is kinda long:</p>
<pre><code>if "// @in " in sTxt or "// @out " in sTxt or "// @ret " in sTxt or <10 more>
print "found."
</code></pre>
<p>Of course regexes can help, but using regexes will take lots of verbose of code and will
not be as clear as "a in b". Are there any other Pythonic ways?</p>
| 15
|
2009-04-18T18:53:11Z
| 763,951
|
<pre><code>alternatives = ("// @in ", "// @out ", "// @ret ")
if any(a in sTxT for a in alternatives):
print "found"
if all(a in sTxT for a in alternatives):
print "found all"
</code></pre>
<p><a href="http://docs.python.org/library/functions.html#any"><code>any()</code></a> and <a href="http://docs.python.org/library/functions.html#all"><code>all()</code></a> takes an iterable and checks if any/all of them evaluate to a true value. Combine that with a generator expressions, and you can check multiple items.</p>
| 45
|
2009-04-18T18:58:14Z
|
[
"python"
] |
python, "a in b" keyword, how about multiple a's?
| 763,944
|
<p>My adventures in Python continue and my favorite books are silent again. Python offers a built-in way to test if a variable is inside an iterable object, using the 'in' keyword:</p>
<pre><code>if "a" in "abrakadabra" :
print "it is definitely here"
</code></pre>
<p>But is it possible to test if more than one item is in the list (any one)?
Currently, I'm using the syntax below, but it is kinda long:</p>
<pre><code>if "// @in " in sTxt or "// @out " in sTxt or "// @ret " in sTxt or <10 more>
print "found."
</code></pre>
<p>Of course regexes can help, but using regexes will take lots of verbose of code and will
not be as clear as "a in b". Are there any other Pythonic ways?</p>
| 15
|
2009-04-18T18:53:11Z
| 763,957
|
<p>There's no built in way in the syntax to do it. However you can use the 'any' function to make it easier as @MizardX and @Benjamin Peterson showed.</p>
| 0
|
2009-04-18T19:00:01Z
|
[
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.