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
sequence |
---|---|---|---|---|---|---|---|---|---|
Why does Ruby have Rails while Python has no central framework? | 406,907 | <p>This is a(n) historical question, not a comparison-between-languages question:</p>
<p><a href="http://tomayko.com/writings/no-rails-for-python">This article from 2005</a> talks about the lack of a single, central framework for Python. For Ruby, this framework is clearly Rails. <strong>Why, historically speaking, did this happen for Ruby but not for Python?</strong> (or did it happen, and that framework is Django?)</p>
<p>Also, the hypothetical questions: <strong>would Python be more popular if it had one, good framework? Would Ruby be less popular if it had no central framework?</strong></p>
<p><strong>[Please avoid discussions of whether Ruby or Python is better, which is just too open-ended to answer.]</strong></p>
<p><strong>Edit:</strong> Though I thought this is obvious, I'm not saying that other frameworks do not exist for Ruby, but rather that the big one <strong>in terms of popularity</strong> is Rails. Also, I should mention that I'm not saying that frameworks for Python are not as good (or better than) Rails. Every framework has its pros and cons, but Rails seems to, as Ben Blank says in the one of the comments below, have surpassed Ruby in terms of popularity. There are no examples of that on the Python side. WHY? That's the question.</p>
| 8 | 2009-01-02T14:26:57Z | 407,000 | <p>Python is not a one-trick pony. Therefore, there's no single "central framework" for it. Many people first heard of Python as "another nice OO language" or through one of the many uses to which it has been put.</p>
<p>To be fair, Ruby is not a one-trick pony either. It's just that many people regarded Rails as the "killer app" that got them to look at a previously-not-well-known language. I suspect many people never heard of Ruby before Rails, but that's by no means the only thing Ruby can do.</p>
| 1 | 2009-01-02T15:02:40Z | [
"python",
"ruby-on-rails",
"ruby",
"frameworks",
"history"
] |
Why does Ruby have Rails while Python has no central framework? | 406,907 | <p>This is a(n) historical question, not a comparison-between-languages question:</p>
<p><a href="http://tomayko.com/writings/no-rails-for-python">This article from 2005</a> talks about the lack of a single, central framework for Python. For Ruby, this framework is clearly Rails. <strong>Why, historically speaking, did this happen for Ruby but not for Python?</strong> (or did it happen, and that framework is Django?)</p>
<p>Also, the hypothetical questions: <strong>would Python be more popular if it had one, good framework? Would Ruby be less popular if it had no central framework?</strong></p>
<p><strong>[Please avoid discussions of whether Ruby or Python is better, which is just too open-ended to answer.]</strong></p>
<p><strong>Edit:</strong> Though I thought this is obvious, I'm not saying that other frameworks do not exist for Ruby, but rather that the big one <strong>in terms of popularity</strong> is Rails. Also, I should mention that I'm not saying that frameworks for Python are not as good (or better than) Rails. Every framework has its pros and cons, but Rails seems to, as Ben Blank says in the one of the comments below, have surpassed Ruby in terms of popularity. There are no examples of that on the Python side. WHY? That's the question.</p>
| 8 | 2009-01-02T14:26:57Z | 407,003 | <p>As I see it, Rails put Ruby on the map. The simple fact is that before Rails, Ruby was a minor esoteric language, with very little adoption. Ruby owes its success to Rails. As such, Rails has a central place in the Ruby ecosystem. As slim points out, there are other web frameworks, but it's going to be very difficult to overtake Rails as the leader.</p>
<p>Python on the other hand, had a very different adoption curve. Before Rails, Python was much more widely used than Ruby, and so had a number of competing web frameworks, each slowly building their constituencies. Django has done a good job consolidating support, and becoming the leader in the Python web framework world, but it will never be the One True Framework simply because of the way the community developed.</p>
| 35 | 2009-01-02T15:03:40Z | [
"python",
"ruby-on-rails",
"ruby",
"frameworks",
"history"
] |
Why does Ruby have Rails while Python has no central framework? | 406,907 | <p>This is a(n) historical question, not a comparison-between-languages question:</p>
<p><a href="http://tomayko.com/writings/no-rails-for-python">This article from 2005</a> talks about the lack of a single, central framework for Python. For Ruby, this framework is clearly Rails. <strong>Why, historically speaking, did this happen for Ruby but not for Python?</strong> (or did it happen, and that framework is Django?)</p>
<p>Also, the hypothetical questions: <strong>would Python be more popular if it had one, good framework? Would Ruby be less popular if it had no central framework?</strong></p>
<p><strong>[Please avoid discussions of whether Ruby or Python is better, which is just too open-ended to answer.]</strong></p>
<p><strong>Edit:</strong> Though I thought this is obvious, I'm not saying that other frameworks do not exist for Ruby, but rather that the big one <strong>in terms of popularity</strong> is Rails. Also, I should mention that I'm not saying that frameworks for Python are not as good (or better than) Rails. Every framework has its pros and cons, but Rails seems to, as Ben Blank says in the one of the comments below, have surpassed Ruby in terms of popularity. There are no examples of that on the Python side. WHY? That's the question.</p>
| 8 | 2009-01-02T14:26:57Z | 407,260 | <p>I agree with Ned. I'd bet that more than 90% of Ruby installations are for no other purpose than running Rails. Rails dominates Ruby - there is no single application that dominates Python, mainly because the Python community is somewhat bigger than the Ruby community. </p>
| 5 | 2009-01-02T16:07:34Z | [
"python",
"ruby-on-rails",
"ruby",
"frameworks",
"history"
] |
Why does Ruby have Rails while Python has no central framework? | 406,907 | <p>This is a(n) historical question, not a comparison-between-languages question:</p>
<p><a href="http://tomayko.com/writings/no-rails-for-python">This article from 2005</a> talks about the lack of a single, central framework for Python. For Ruby, this framework is clearly Rails. <strong>Why, historically speaking, did this happen for Ruby but not for Python?</strong> (or did it happen, and that framework is Django?)</p>
<p>Also, the hypothetical questions: <strong>would Python be more popular if it had one, good framework? Would Ruby be less popular if it had no central framework?</strong></p>
<p><strong>[Please avoid discussions of whether Ruby or Python is better, which is just too open-ended to answer.]</strong></p>
<p><strong>Edit:</strong> Though I thought this is obvious, I'm not saying that other frameworks do not exist for Ruby, but rather that the big one <strong>in terms of popularity</strong> is Rails. Also, I should mention that I'm not saying that frameworks for Python are not as good (or better than) Rails. Every framework has its pros and cons, but Rails seems to, as Ben Blank says in the one of the comments below, have surpassed Ruby in terms of popularity. There are no examples of that on the Python side. WHY? That's the question.</p>
| 8 | 2009-01-02T14:26:57Z | 407,543 | <p>Would ruby be less popular without Rails? absolutely.</p>
<p>Would Python be more popular with one true framework? You mean as opposed to several? May be, who knows. In any case most agree Django is a very good framework.</p>
<p>Why, historically, did it happen to Ruby? Because DHH chose Ruby after doing his own research. </p>
<p>To add to the answer regarding Rails having made a breakthrough because of 'convention over configuration' there is also another reason and that is that Rails has been using the meta-programming abilities of Ruby superbly. A lot of the magic of Rails which has contributed to removing a lot of the pain of developing web apps came through this clever use of ruby meta-programming.</p>
| 2 | 2009-01-02T17:51:17Z | [
"python",
"ruby-on-rails",
"ruby",
"frameworks",
"history"
] |
Why does Ruby have Rails while Python has no central framework? | 406,907 | <p>This is a(n) historical question, not a comparison-between-languages question:</p>
<p><a href="http://tomayko.com/writings/no-rails-for-python">This article from 2005</a> talks about the lack of a single, central framework for Python. For Ruby, this framework is clearly Rails. <strong>Why, historically speaking, did this happen for Ruby but not for Python?</strong> (or did it happen, and that framework is Django?)</p>
<p>Also, the hypothetical questions: <strong>would Python be more popular if it had one, good framework? Would Ruby be less popular if it had no central framework?</strong></p>
<p><strong>[Please avoid discussions of whether Ruby or Python is better, which is just too open-ended to answer.]</strong></p>
<p><strong>Edit:</strong> Though I thought this is obvious, I'm not saying that other frameworks do not exist for Ruby, but rather that the big one <strong>in terms of popularity</strong> is Rails. Also, I should mention that I'm not saying that frameworks for Python are not as good (or better than) Rails. Every framework has its pros and cons, but Rails seems to, as Ben Blank says in the one of the comments below, have surpassed Ruby in terms of popularity. There are no examples of that on the Python side. WHY? That's the question.</p>
| 8 | 2009-01-02T14:26:57Z | 408,146 | <p>The real technical answer is that there are three major approaches to web-development in Python: one is CGI-based, where the application is built just like an old one-off Perl application to run through CGI or FastCGI, e.g. <a href="http://trac.edgewall.org/" rel="nofollow">Trac</a>; then there is <a href="http://zope.org/" rel="nofollow">Zope</a>, which is a bizarro overengineered framework with its own DB concept, a strange misguided through-the-web software development concept, etc. (but <a href="http://plone.org" rel="nofollow">Plone</a> is still quite popular); and then there is Django (and <a href="http://turbogears.org/" rel="nofollow">Turbogears</a>, etc.), which is guided by the same just-the-tools-needed philosophy as Rails (it can be argued who got there first or who did it better). A lot of people would probably agree that the Django/Rails/<a href="http://cakephp.org" rel="nofollow">CakePHP</a> approach is better than the older approaches, but as the older language Python has a lot more legacy frameworks that are still trying to evolve and stay relevant. These frameworks will hang on because there is already developer buy-in for them. For example, in hindsight many people would probably say that Zope (especially ZODB) was a terrible mistake, but Zope 3 is much better than Zope 2, and there are already whole companies built around Zope technologies.</p>
| 7 | 2009-01-02T22:08:20Z | [
"python",
"ruby-on-rails",
"ruby",
"frameworks",
"history"
] |
Why does Ruby have Rails while Python has no central framework? | 406,907 | <p>This is a(n) historical question, not a comparison-between-languages question:</p>
<p><a href="http://tomayko.com/writings/no-rails-for-python">This article from 2005</a> talks about the lack of a single, central framework for Python. For Ruby, this framework is clearly Rails. <strong>Why, historically speaking, did this happen for Ruby but not for Python?</strong> (or did it happen, and that framework is Django?)</p>
<p>Also, the hypothetical questions: <strong>would Python be more popular if it had one, good framework? Would Ruby be less popular if it had no central framework?</strong></p>
<p><strong>[Please avoid discussions of whether Ruby or Python is better, which is just too open-ended to answer.]</strong></p>
<p><strong>Edit:</strong> Though I thought this is obvious, I'm not saying that other frameworks do not exist for Ruby, but rather that the big one <strong>in terms of popularity</strong> is Rails. Also, I should mention that I'm not saying that frameworks for Python are not as good (or better than) Rails. Every framework has its pros and cons, but Rails seems to, as Ben Blank says in the one of the comments below, have surpassed Ruby in terms of popularity. There are no examples of that on the Python side. WHY? That's the question.</p>
| 8 | 2009-01-02T14:26:57Z | 408,756 | <p>I'd have to agree that Django is basically the "Rails for Python" equivalent. Why did it take so long? The simple answer is too many options.</p>
<p>In Python, there are many request/response systems, url rewriters, ORMs, templating languages, etc. that you could build a web stack in dozens of different configurations. In fact, this is exactly what Pylons and TurboGears do is provide a reliable, predictable stack to build MVC web apps.</p>
<p>What Django did differently was they encapsulated everything. Rather than go the components route, they built one contiguous system. They built their own ORM, their own template language, their own middleware system, etc. Their reasoning was that there was no unified system like this for Python.</p>
| 2 | 2009-01-03T07:33:13Z | [
"python",
"ruby-on-rails",
"ruby",
"frameworks",
"history"
] |
Why does Ruby have Rails while Python has no central framework? | 406,907 | <p>This is a(n) historical question, not a comparison-between-languages question:</p>
<p><a href="http://tomayko.com/writings/no-rails-for-python">This article from 2005</a> talks about the lack of a single, central framework for Python. For Ruby, this framework is clearly Rails. <strong>Why, historically speaking, did this happen for Ruby but not for Python?</strong> (or did it happen, and that framework is Django?)</p>
<p>Also, the hypothetical questions: <strong>would Python be more popular if it had one, good framework? Would Ruby be less popular if it had no central framework?</strong></p>
<p><strong>[Please avoid discussions of whether Ruby or Python is better, which is just too open-ended to answer.]</strong></p>
<p><strong>Edit:</strong> Though I thought this is obvious, I'm not saying that other frameworks do not exist for Ruby, but rather that the big one <strong>in terms of popularity</strong> is Rails. Also, I should mention that I'm not saying that frameworks for Python are not as good (or better than) Rails. Every framework has its pros and cons, but Rails seems to, as Ben Blank says in the one of the comments below, have surpassed Ruby in terms of popularity. There are no examples of that on the Python side. WHY? That's the question.</p>
| 8 | 2009-01-02T14:26:57Z | 412,947 | <p>If you followed the news, you have read that Merb and Rails will merge. This is a good move IMHO. I think it's because of the common goal that the developers have: They want a simple framework for webdev, which comes with a OR mapper, routing, template language, etc which fits for most tasks..</p>
| 0 | 2009-01-05T12:19:03Z | [
"python",
"ruby-on-rails",
"ruby",
"frameworks",
"history"
] |
Why does Ruby have Rails while Python has no central framework? | 406,907 | <p>This is a(n) historical question, not a comparison-between-languages question:</p>
<p><a href="http://tomayko.com/writings/no-rails-for-python">This article from 2005</a> talks about the lack of a single, central framework for Python. For Ruby, this framework is clearly Rails. <strong>Why, historically speaking, did this happen for Ruby but not for Python?</strong> (or did it happen, and that framework is Django?)</p>
<p>Also, the hypothetical questions: <strong>would Python be more popular if it had one, good framework? Would Ruby be less popular if it had no central framework?</strong></p>
<p><strong>[Please avoid discussions of whether Ruby or Python is better, which is just too open-ended to answer.]</strong></p>
<p><strong>Edit:</strong> Though I thought this is obvious, I'm not saying that other frameworks do not exist for Ruby, but rather that the big one <strong>in terms of popularity</strong> is Rails. Also, I should mention that I'm not saying that frameworks for Python are not as good (or better than) Rails. Every framework has its pros and cons, but Rails seems to, as Ben Blank says in the one of the comments below, have surpassed Ruby in terms of popularity. There are no examples of that on the Python side. WHY? That's the question.</p>
| 8 | 2009-01-02T14:26:57Z | 2,864,532 | <p>Check out this article on <a href="http://blog.ianbicking.org/what-really-makes-rails-work.html" rel="nofollow">why we'll never see Python-on-Rails</a>. The author gives some of the basic reasons why Python has never had <strong>and will never have</strong> a central framework. I might add, myself, that Java doesn't have one either, and for the same reasons.</p>
<p>According to the author, Rails is strictly tied to its "implementation," which is Ruby. Rails was adopted by many developers and Ruby was just part of it. Rails works perfectly on Ruby (or Ruby wanna-bes like Groovy), but more importantly, as many other answers say, Rails led the way to Ruby adoption.</p>
<blockquote>
<p>This is why Rails-for-Python won't
work, or at least what people have
been focusing on with Rails isn't
correct. It's not about the
implementation or the quality of the
framework, it's about the pattern of
adoption. It's about putting the
framework up front, and the
implementation in the back -- even if
this wasn't the Rails developers
intentions (though maybe they are
clever and this was their intention).</p>
</blockquote>
<p>Basically, you can't get a bunch of language-loving folk to gather around a single framework. On the Java side, while Spring is well-loved, it's no Rails in terms of popularity in the Java community. In a mature community developers have their own ideas about what metaphors work and don't work in a framework. <strong>This</strong> is why Rails leads to Ruby and not the other way around (typically, mostly, not in all cases).</p>
| 0 | 2010-05-19T10:09:31Z | [
"python",
"ruby-on-rails",
"ruby",
"frameworks",
"history"
] |
How to intercept special (alt / ctrl) key press? | 406,933 | <p>How can I catch key combinations like <kbd>ALT</kbd>+<kbd>K</kbd> or <kbd>CTRL</kbd>+<kbd>ALT</kbd>+<kbd>H</kbd> in python <code>curses</code>?</p>
| 8 | 2009-01-02T14:34:45Z | 407,022 | <p>A terminal converts the control key in combination with a letter key to a normal ASCII code. This can be read from the <a href="http://www.opengroup.org/onlinepubs/007908799/xcurses/wgetch.html">getch</a>() function like any other key press.</p>
<pre><code>CTRL-A: getch() returns 1
CTRL-B: getch() returns 2
...
CTRL-Z: getch() returns 26
</code></pre>
<p>Also, the <a href="http://www.mkssoftware.com/docs/man3/curs_inopts.3.asp">keypad</a>() function must be called to enable other special function keys (e.g. left arrow, F1, home, etc).</p>
<p>I don't believe there is a portable way to receive meta-keys (e.g. ALT-H) through a terminal. Some send an escape (0x1B) followed by the modified key while others set the high-bit and only send one byte.</p>
| 10 | 2009-01-02T15:09:56Z | [
"python",
"curses"
] |
PyQt: getting widgets to resize automatically in a QDialog | 406,939 | <p>I'm having difficulty getting widgets in a QDialog resized automatically when the dialog itself is resized.</p>
<p>In the following program, the textarea resizes automatically if you resize the main window. However, the textarea within the dialog stays the same size when the dialog is resized.</p>
<p>Is there any way of making the textarea in the dialog resize automatically? I've tried using <code>setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)</code> on the dialog itself and the two widgets within, but that seems to have no effect.</p>
<p>I'm using Qt version 3.3.7 and PyQt version 3.5.5-29 on openSuSE 10.2, if that's relevant.</p>
<pre><code>import sys
from qt import *
# The numbers 1 to 1000 as a string.
NUMBERS = ("%d " * 1000) % (tuple(range(1,1001)))
# Add a textarea containing the numbers 1 to 1000 to the given
# QWidget.
def addTextArea(parent, size):
textbox = QTextEdit(parent)
textbox.setReadOnly(True)
textbox.setMinimumSize(QSize(size, size*0.75))
textbox.setText(NUMBERS)
class TestDialog(QDialog):
def __init__(self,parent=None):
QDialog.__init__(self,parent)
self.setCaption("Dialog")
everything = QVBox(self)
addTextArea(everything, 400)
everything.resize(everything.sizeHint())
class TestMainWindow(QMainWindow):
def __init__(self,parent=None):
QMainWindow.__init__(self,parent)
self.setCaption("Main Window")
everything = QVBox(self)
addTextArea(everything, 800)
button = QPushButton("Open dialog", everything)
self.connect(button, SIGNAL('clicked()'), self.openDialog)
self.setCentralWidget(everything)
self.resize(self.sizeHint())
self.dialog = TestDialog(self)
def openDialog(self):
self.dialog.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
mainwin = TestMainWindow(None)
app.setMainWidget(mainwin)
mainwin.show()
app.exec_loop()
</code></pre>
| 7 | 2009-01-02T14:39:30Z | 406,982 | <p>QMainWindow has special behavior for the central widget that a QDialog does not. To achieve the desired behavior you need to create a <a href="http://doc.trolltech.com/3.3/layout.html" rel="nofollow">layout</a>, add the text area to the layout and assign the layout to the dialog.</p>
| 3 | 2009-01-02T14:56:35Z | [
"python",
"qt",
"pyqt",
"qdialog"
] |
PyQt: getting widgets to resize automatically in a QDialog | 406,939 | <p>I'm having difficulty getting widgets in a QDialog resized automatically when the dialog itself is resized.</p>
<p>In the following program, the textarea resizes automatically if you resize the main window. However, the textarea within the dialog stays the same size when the dialog is resized.</p>
<p>Is there any way of making the textarea in the dialog resize automatically? I've tried using <code>setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)</code> on the dialog itself and the two widgets within, but that seems to have no effect.</p>
<p>I'm using Qt version 3.3.7 and PyQt version 3.5.5-29 on openSuSE 10.2, if that's relevant.</p>
<pre><code>import sys
from qt import *
# The numbers 1 to 1000 as a string.
NUMBERS = ("%d " * 1000) % (tuple(range(1,1001)))
# Add a textarea containing the numbers 1 to 1000 to the given
# QWidget.
def addTextArea(parent, size):
textbox = QTextEdit(parent)
textbox.setReadOnly(True)
textbox.setMinimumSize(QSize(size, size*0.75))
textbox.setText(NUMBERS)
class TestDialog(QDialog):
def __init__(self,parent=None):
QDialog.__init__(self,parent)
self.setCaption("Dialog")
everything = QVBox(self)
addTextArea(everything, 400)
everything.resize(everything.sizeHint())
class TestMainWindow(QMainWindow):
def __init__(self,parent=None):
QMainWindow.__init__(self,parent)
self.setCaption("Main Window")
everything = QVBox(self)
addTextArea(everything, 800)
button = QPushButton("Open dialog", everything)
self.connect(button, SIGNAL('clicked()'), self.openDialog)
self.setCentralWidget(everything)
self.resize(self.sizeHint())
self.dialog = TestDialog(self)
def openDialog(self):
self.dialog.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
mainwin = TestMainWindow(None)
app.setMainWidget(mainwin)
mainwin.show()
app.exec_loop()
</code></pre>
| 7 | 2009-01-02T14:39:30Z | 407,309 | <p>I had looked at using a QLayout before but had no luck. I was trying to do something like</p>
<pre><code>dialog.setLayout(some_layout)
</code></pre>
<p>but I couldn't get that approach to work so I gave up.</p>
<p>My mistake was that I was trying to pass the layout to the dialog when I should have been passing the dialog to the layout.</p>
<p>Adding the lines</p>
<pre><code>layout = QVBoxLayout(self)
layout.add(everything)
</code></pre>
<p>to the end of <code>TestDialog.__init__</code> fixes the problem.</p>
<p>Thanks to Monjardin for prompting me to reconsider layouts.</p>
| 2 | 2009-01-02T16:21:56Z | [
"python",
"qt",
"pyqt",
"qdialog"
] |
PyQt: getting widgets to resize automatically in a QDialog | 406,939 | <p>I'm having difficulty getting widgets in a QDialog resized automatically when the dialog itself is resized.</p>
<p>In the following program, the textarea resizes automatically if you resize the main window. However, the textarea within the dialog stays the same size when the dialog is resized.</p>
<p>Is there any way of making the textarea in the dialog resize automatically? I've tried using <code>setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)</code> on the dialog itself and the two widgets within, but that seems to have no effect.</p>
<p>I'm using Qt version 3.3.7 and PyQt version 3.5.5-29 on openSuSE 10.2, if that's relevant.</p>
<pre><code>import sys
from qt import *
# The numbers 1 to 1000 as a string.
NUMBERS = ("%d " * 1000) % (tuple(range(1,1001)))
# Add a textarea containing the numbers 1 to 1000 to the given
# QWidget.
def addTextArea(parent, size):
textbox = QTextEdit(parent)
textbox.setReadOnly(True)
textbox.setMinimumSize(QSize(size, size*0.75))
textbox.setText(NUMBERS)
class TestDialog(QDialog):
def __init__(self,parent=None):
QDialog.__init__(self,parent)
self.setCaption("Dialog")
everything = QVBox(self)
addTextArea(everything, 400)
everything.resize(everything.sizeHint())
class TestMainWindow(QMainWindow):
def __init__(self,parent=None):
QMainWindow.__init__(self,parent)
self.setCaption("Main Window")
everything = QVBox(self)
addTextArea(everything, 800)
button = QPushButton("Open dialog", everything)
self.connect(button, SIGNAL('clicked()'), self.openDialog)
self.setCentralWidget(everything)
self.resize(self.sizeHint())
self.dialog = TestDialog(self)
def openDialog(self):
self.dialog.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
mainwin = TestMainWindow(None)
app.setMainWidget(mainwin)
mainwin.show()
app.exec_loop()
</code></pre>
| 7 | 2009-01-02T14:39:30Z | 4,453,751 | <p>Check out <a href="https://sourceforge.net/projects/pyqtresize/" rel="nofollow">Python QT Automatic Widget Resizer</a> It's suppose to work well.</p>
| 1 | 2010-12-15T19:01:07Z | [
"python",
"qt",
"pyqt",
"qdialog"
] |
PyQt: getting widgets to resize automatically in a QDialog | 406,939 | <p>I'm having difficulty getting widgets in a QDialog resized automatically when the dialog itself is resized.</p>
<p>In the following program, the textarea resizes automatically if you resize the main window. However, the textarea within the dialog stays the same size when the dialog is resized.</p>
<p>Is there any way of making the textarea in the dialog resize automatically? I've tried using <code>setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)</code> on the dialog itself and the two widgets within, but that seems to have no effect.</p>
<p>I'm using Qt version 3.3.7 and PyQt version 3.5.5-29 on openSuSE 10.2, if that's relevant.</p>
<pre><code>import sys
from qt import *
# The numbers 1 to 1000 as a string.
NUMBERS = ("%d " * 1000) % (tuple(range(1,1001)))
# Add a textarea containing the numbers 1 to 1000 to the given
# QWidget.
def addTextArea(parent, size):
textbox = QTextEdit(parent)
textbox.setReadOnly(True)
textbox.setMinimumSize(QSize(size, size*0.75))
textbox.setText(NUMBERS)
class TestDialog(QDialog):
def __init__(self,parent=None):
QDialog.__init__(self,parent)
self.setCaption("Dialog")
everything = QVBox(self)
addTextArea(everything, 400)
everything.resize(everything.sizeHint())
class TestMainWindow(QMainWindow):
def __init__(self,parent=None):
QMainWindow.__init__(self,parent)
self.setCaption("Main Window")
everything = QVBox(self)
addTextArea(everything, 800)
button = QPushButton("Open dialog", everything)
self.connect(button, SIGNAL('clicked()'), self.openDialog)
self.setCentralWidget(everything)
self.resize(self.sizeHint())
self.dialog = TestDialog(self)
def openDialog(self):
self.dialog.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
mainwin = TestMainWindow(None)
app.setMainWidget(mainwin)
mainwin.show()
app.exec_loop()
</code></pre>
| 7 | 2009-01-02T14:39:30Z | 13,209,797 | <p>Just to add a little note about this - I was trying to have a child window spawned from an application, which is a <code>QDialog</code>, containing a single <code>QTextEdit</code> as a child/content - and I wanted the <code>QTextEdit</code> to resize automatically whenever the <code>QDialog</code> window size changes. This seems to have done the trick for me with <code>PyQt4</code>:</p>
<pre><code>def showTextWindow(self):
#QVBox, QHBox # don't exist in Qt4
dialog = QDialog(self)
#dialog.setGeometry(QRect(100, 100, 400, 200))
dialog.setWindowTitle("Title")
dialog.setAttribute(QtCore.Qt.WA_DeleteOnClose)
textbox = QTextEdit(dialog)
textbox.setReadOnly(True)
textbox.setMinimumSize(QSize(400, 400*0.75))
textbox.setText("AHAAA!")
# this seems enough to have the QTextEdit
# autoresize to window size changes of dialog!
layout = QHBoxLayout(dialog)
layout.addWidget(textbox)
dialog.setLayout(layout)
dialog.exec_()
</code></pre>
| 1 | 2012-11-03T13:52:18Z | [
"python",
"qt",
"pyqt",
"qdialog"
] |
How to synchronize the same object on client and server side in client-server application? Is small messages framework good for this job? | 407,464 | <p>I'm making a game engine in c++ and python. I'm using OGRE for 3D rendering, OpenAL for sound, ODE for physics, OIS for input, HawkNL for networking and boost.python for embedded python interpreter. Every subsystem (library) is wrapped by a class - manager and every manager is singleton. Now, I have a class - Object - this could be every visible object in game world. This is some kind of mix, object has graphics representation (entity) and representation in physics simulator (solid). These two are most important here. Class Object is just pure abstract base class - interface. I've decided to implement Object on client side as ObjectClientSide - this implementation has the entity, and on server side as ObjectServerSide - this implementation has the solid. Physics simulator runs only on server, and rendering is done only on client of course. The object can exist only when both implementations are working together. Every object has unique id and both instances of the same object on client and server side have the same id.</p>
<p>So, after this short background, my first question is: is this design good? How can I make it better? And the main question: how should I synchronize these objects?</p>
<p>Next, both implementations have the same interface, but part of it is implemented on server side and part on client side. So, for example, if player wants to move forward his character he should send a request to object on server. The server then makes changes to simulation and sends updated position to client. For that reason, I've created small messages framework. There is a Message class, Router, Rule and rules inherited from Rule. When message arrives, Router checks it against the rules and sends it to destination. So, when I call myObjectInstanceOnClientSide->setPosition(x,y,z) this object creates Message, its content is function and parameters and destination is object with the same id on server. When object with the same id on server side gets this message it calls this function with given arguments. So, when a function can't be implemented on one side it creates a message and sends it to object on the other side. I think this can be very useful in scripts. Scripts can be very clean, if script needs for example turn on animation on clients, I only need to call this function on server's local object - the rest is in background.</p>
<p>So, is this ok? Am I wrong about this? It this common solution?</p>
| 1 | 2009-01-02T17:22:29Z | 407,478 | <p>It sounds like you would be sending a lot of tiny messages. The UDP and IP headers will add 28 bytes of overhead (20 bytes for the IPv4 header or 40 for IPv6 plus 8 bytes for the UDP header). So, <strong>I would suggest combining multiple messages to be dispatched together at a perioidic rate.</strong></p>
<p>You may also want to read these other questions and answers:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/42515/dealing-with-latency-in-networked-games">Dealing with Latency in Networked Games</a></li>
<li><a href="http://stackoverflow.com/questions/390067/real-time-multiplayer-game-concept-question#390078">Real-time multiplayer game (concept question)</a></li>
</ul>
<p>I added a <a href="http://www.devmaster.net/wiki/Networking_links" rel="nofollow">bunch of useful links</a> to the <a href="http://www.devmaster.net/" rel="nofollow">DevMaster.net</a> <a href="http://www.devmaster.net/wiki/Main_Page" rel="nofollow">Wiki</a> years ago that are still relavent:</p>
<ul>
<li><a href="http://www.gamedev.net/reference/articles/article1138.asp" rel="nofollow">Networking for Games 101 FAQ</a></li>
<li><a href="http://www.gamedev.net/community/forums/showfaq.asp?forum_id=15" rel="nofollow">Multiplayer and Network Programming</a></li>
<li><a href="http://trac.bookofhook.com/bookofhook/trac.cgi/wiki/IntroductionToMultiplayerGameProgramming" rel="nofollow">Introduction to Multiplayer Game</a></li>
<li><a href="http://trac.bookofhook.com/bookofhook/trac.cgi/wiki/Quake3Networking" rel="nofollow">Programming The Quake3 Networking Model</a></li>
<li><a href="http://unreal.epicgames.com/Network.htm" rel="nofollow">Unreal Networking Architecture</a></li>
<li><a href="http://gafferongames.wordpress.com/game-physics/networked-physics/" rel="nofollow">Networked Physics</a></li>
<li><a href="http://beej.us/guide/bgnet/" rel="nofollow">Beej's Network Guide</a></li>
</ul>
<p>I'd suggest starting to read <a href="http://gafferongames.wordpress.com/" rel="nofollow">Glenn Fiedler's blog</a>. He's done some incredibly work with networked physics including the recent <a href="http://www.pandemicstudios.com/mercenaries/index.php" rel="nofollow">Mercenaries 2</a> release. He started a series of articles called <a href="http://gafferongames.wordpress.com/networking-for-game-programmers/" rel="nofollow">Networking for Game Programmers</a>.</p>
| 7 | 2009-01-02T17:27:09Z | [
"c++",
"python",
"oop"
] |
Python urllib2 file upload problems | 407,468 | <p>I'm currently trying to initiate a file upload with urllib2 and the <a href="http://fabien.seisen.org/python/urllib2_multipart.html" rel="nofollow">urllib2_file</a> library. Here's my code:</p>
<pre><code>import sys
import urllib2_file
import urllib2
URL='http://aquate.us/upload.php'
d = [('uploaded', open(sys.argv[1:]))]
req = urllib2.Request(URL, d)
u = urllib2.urlopen(req)
print u.read()
</code></pre>
<p>I've placed this .py file in my My Documents directory and placed a shortcut to it in my Send To folder (the shortcut URL is ).</p>
<p>When I right click a file, choose Send To, and select Aquate (my python), it opens a command prompt for a split second and then closes it. Nothing gets uploaded.</p>
<p>I knew there was probably an error going on so I typed the code into CL python, line by line.
When I ran the <code>u=urllib2.urlopen(req)</code> line, I didn't get an error;
<img src="http://www.aquate.us/u/55245858877937182052.jpg" alt="alt text"></p>
<p>instead, the cursor simply started blinking on a new line beneath that line. I waited a couple of minutes to see if something would happen but it just stayed like that. To get it to stop, I had to press ctrl+break.</p>
<p>What's up with this script?</p>
<p>Thanks in advance!</p>
<p>[Edit]
Forgot to mention -- when I ran the script without the request data (the file) it ran like a charm. Is it a problem with urllib2_file?</p>
<p>[edit 2]:</p>
<pre><code>import MultipartPostHandler, urllib2, cookielib,sys
import win32clipboard as w
cookies = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies),MultipartPostHandler.MultipartPostHandler)
params = {"uploaded" : open("c:/cfoot.js") }
a=opener.open("http://www.aquate.us/upload.php", params)
text = a.read()
w.OpenClipboard()
w.EmptyClipboard()
w.SetClipboardText(text)
w.CloseClipboard()
</code></pre>
<p>That code works like a charm if you run it through the command line.</p>
| 6 | 2009-01-02T17:23:55Z | 407,545 | <p>If you're using Python 2.5 or newer, <code>urllib2_file</code> is both unnecessary and unsupported, so check which version you're using (and perhaps upgrade).</p>
<p>If you're using Python 2.3 or 2.4 (the only versions supported by <code>urllib2_file</code>), try running <a href="http://fabien.seisen.org/python/test.py" rel="nofollow">the sample code</a> and see if you have the same problem. If so, there is likely something wrong either with your Python or <code>urllib2_file</code> installation.</p>
<p><strong>EDIT:</strong></p>
<p>Also, you don't seem to be using either of <code>urllib2_file</code>'s two supported formats for POST data. Try using <strong>one</strong> of the following two lines instead:</p>
<pre><code>d = ['uploaded', open(sys.argv[1:])]
## --OR-- ##
d = {'uploaded': open(sys.argv[1:])}
</code></pre>
| 2 | 2009-01-02T17:52:22Z | [
"python",
"post",
"upload",
"urllib2"
] |
Python urllib2 file upload problems | 407,468 | <p>I'm currently trying to initiate a file upload with urllib2 and the <a href="http://fabien.seisen.org/python/urllib2_multipart.html" rel="nofollow">urllib2_file</a> library. Here's my code:</p>
<pre><code>import sys
import urllib2_file
import urllib2
URL='http://aquate.us/upload.php'
d = [('uploaded', open(sys.argv[1:]))]
req = urllib2.Request(URL, d)
u = urllib2.urlopen(req)
print u.read()
</code></pre>
<p>I've placed this .py file in my My Documents directory and placed a shortcut to it in my Send To folder (the shortcut URL is ).</p>
<p>When I right click a file, choose Send To, and select Aquate (my python), it opens a command prompt for a split second and then closes it. Nothing gets uploaded.</p>
<p>I knew there was probably an error going on so I typed the code into CL python, line by line.
When I ran the <code>u=urllib2.urlopen(req)</code> line, I didn't get an error;
<img src="http://www.aquate.us/u/55245858877937182052.jpg" alt="alt text"></p>
<p>instead, the cursor simply started blinking on a new line beneath that line. I waited a couple of minutes to see if something would happen but it just stayed like that. To get it to stop, I had to press ctrl+break.</p>
<p>What's up with this script?</p>
<p>Thanks in advance!</p>
<p>[Edit]
Forgot to mention -- when I ran the script without the request data (the file) it ran like a charm. Is it a problem with urllib2_file?</p>
<p>[edit 2]:</p>
<pre><code>import MultipartPostHandler, urllib2, cookielib,sys
import win32clipboard as w
cookies = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies),MultipartPostHandler.MultipartPostHandler)
params = {"uploaded" : open("c:/cfoot.js") }
a=opener.open("http://www.aquate.us/upload.php", params)
text = a.read()
w.OpenClipboard()
w.EmptyClipboard()
w.SetClipboardText(text)
w.CloseClipboard()
</code></pre>
<p>That code works like a charm if you run it through the command line.</p>
| 6 | 2009-01-02T17:23:55Z | 407,557 | <p>First, there's a third way to run Python programs.</p>
<p>From cmd.exe, type <code>python myprogram.py</code>. You get a nice log. You don't have to type stuff one line at a time.</p>
<p>Second, check the <a href="http://www.python.org/doc/2.5.2/lib/module-urllib2.html" rel="nofollow">urrlib2</a> documentation. You'll need to look at <a href="http://www.python.org/doc/2.5.2/lib/module-urllib.html" rel="nofollow">urllib</a>, also.</p>
<p>A Request requires a URL and a urlencoded encoded buffer of data.</p>
<blockquote>
<p>data should be a buffer in the
standard
application/x-www-form-urlencoded
format. The urllib.urlencode()
function takes a mapping or sequence
of 2-tuples and returns a string in
this format.</p>
</blockquote>
<p>You need to encode your data.</p>
| 0 | 2009-01-02T17:56:42Z | [
"python",
"post",
"upload",
"urllib2"
] |
Python urllib2 file upload problems | 407,468 | <p>I'm currently trying to initiate a file upload with urllib2 and the <a href="http://fabien.seisen.org/python/urllib2_multipart.html" rel="nofollow">urllib2_file</a> library. Here's my code:</p>
<pre><code>import sys
import urllib2_file
import urllib2
URL='http://aquate.us/upload.php'
d = [('uploaded', open(sys.argv[1:]))]
req = urllib2.Request(URL, d)
u = urllib2.urlopen(req)
print u.read()
</code></pre>
<p>I've placed this .py file in my My Documents directory and placed a shortcut to it in my Send To folder (the shortcut URL is ).</p>
<p>When I right click a file, choose Send To, and select Aquate (my python), it opens a command prompt for a split second and then closes it. Nothing gets uploaded.</p>
<p>I knew there was probably an error going on so I typed the code into CL python, line by line.
When I ran the <code>u=urllib2.urlopen(req)</code> line, I didn't get an error;
<img src="http://www.aquate.us/u/55245858877937182052.jpg" alt="alt text"></p>
<p>instead, the cursor simply started blinking on a new line beneath that line. I waited a couple of minutes to see if something would happen but it just stayed like that. To get it to stop, I had to press ctrl+break.</p>
<p>What's up with this script?</p>
<p>Thanks in advance!</p>
<p>[Edit]
Forgot to mention -- when I ran the script without the request data (the file) it ran like a charm. Is it a problem with urllib2_file?</p>
<p>[edit 2]:</p>
<pre><code>import MultipartPostHandler, urllib2, cookielib,sys
import win32clipboard as w
cookies = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies),MultipartPostHandler.MultipartPostHandler)
params = {"uploaded" : open("c:/cfoot.js") }
a=opener.open("http://www.aquate.us/upload.php", params)
text = a.read()
w.OpenClipboard()
w.EmptyClipboard()
w.SetClipboardText(text)
w.CloseClipboard()
</code></pre>
<p>That code works like a charm if you run it through the command line.</p>
| 6 | 2009-01-02T17:23:55Z | 4,019,389 | <p>If you're still on Python2.5, what worked for me was to download the code here:</p>
<p><a href="http://peerit.blogspot.com/2007/07/multipartposthandler-doesnt-work-for.html" rel="nofollow">http://peerit.blogspot.com/2007/07/multipartposthandler-doesnt-work-for.html</a></p>
<p>and save it as MultipartPostHandler.py</p>
<p>then use:</p>
<pre><code>import urllib2, MultipartPostHandler
opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler())
opener.open(url, {"file":open(...)})
</code></pre>
<p>or if you need cookies:</p>
<pre><code>import urllib2, MultipartPostHandler, cookielib
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj), MultipartPostHandler.MultipartPostHandler())
opener.open(url, {"file":open(...)})
</code></pre>
| 0 | 2010-10-25T22:29:34Z | [
"python",
"post",
"upload",
"urllib2"
] |
Python: Set Bits Count (popcount) | 407,587 | <p>Few blob's have been duplicated in my database(oracle 11g), performed XOR operations on the blob using UTL_RAW.BIT_XOR. After that i wanted to count the number of set bits in the binary string, so wrote the code above.</p>
<p>During a small experiment, i wanted to see what is the hex and the integer value produced and wrote this procedure..</p>
<pre><code>SQL> declare
2
3 vblob1 blob;
4
5 BEGIN
6
7 select leftiriscode INTO vblob1 FROM irisdata WHERE irisid=1;
8
9 dbms_output.put_line(rawtohex(vblob1));
10
11
12 dbms_output.put_line(UTL_RAW.CAST_TO_binary_integer(vblob1));
13
14
15 END;
16 /
</code></pre>
<p>OUTPUT: HEXVALUE:</p>
<pre><code>0F0008020003030D030C1D1C3C383C330A3311373724764C54496C0A6B029B84840547A341BBA83D
BB5FB9DE4CDE5EFE96E1FC6169438344D604681D409F9F9F3BC07EE0C4E0C033A23B37791F59F84F
F94E4F664E3072B0229DA09D9F0F1FC600C2E380D6988C198B39517D157E7D66FE675237673D3D28
3A016C01411003343C76740F710F0F4F8FE976E1E882C186D316A63C0C7D7D7D7D397F016101B043
0176C37E767C7E0C7D010C8302C2D3E4F2ACE42F8D3F3F367A46F54285434ABB61BDB53CBF6C7CC0
F4C1C3F349B3F7BEB30E4A0CFE1C85180DC338C2C1C6E7A5CE3104303178724CCC5F451F573F3B24
7F24052000202003291F130F1B0E070C0E0D0F0E0F0B0B07070F1E1B330F27073F3F272E2F2F6F7B
2F2E1F2E4F7EFF7EDF3EBF253F3D2F39BF3D7F7FFED72FF39FE7773DBE9DBFBB3FE7A76E777DF55C
5F5F7ADF7FBD7F6AFE7B7D1FBE7F7F7DD7F63FBFBF2D3B7F7F5F2F7F3D7F7D3B3F3B7FFF4D676F7F
5D9FAD7DD17F7F6F6F0B6F7F3F767F1779364737370F7D3F5F377F2F3D3F7F1F2FE7709FB7BCB77B
0B77CF1DF5BF1F7F3D3E4E7F197F571F7D7E3F7F7F7D7F6F4F75FF6F7ECE2FFF793EFFEDB7BDDD1F
FF3BCE3F7F3FBF3D6C7FFF7F7F4FAF7F6FFFFF8D7777BF3AE30FAEEEEBCF5FEEFEE75FFEACFFDF0F
DFFFF77FFF677F4FFF7F7F1B5F1F5F146F1F1E1B3B1F3F273303170F370E250B
INTEGER VALUE: 15
</code></pre>
<p>There was a variance between the hex code and the integer value produced, so used the following python code to check the actual integer value.</p>
<pre><code>print int("0F0008020003030D030C1D1C3C383C330A3311373724764C54496C0A6B029B84840547A341BBA83D
BB5FB9DE4CDE5EFE96E1FC6169438344D604681D409F9F9F3BC07EE0C4E0C033A23B37791F59F84F
F94E4F664E3072B0229DA09D9F0F1FC600C2E380D6988C198B39517D157E7D66FE675237673D3D28
3A016C01411003343C76740F710F0F4F8FE976E1E882C186D316A63C0C7D7D7D7D397F016101B043
0176C37E767C7E0C7D010C8302C2D3E4F2ACE42F8D3F3F367A46F54285434ABB61BDB53CBF6C7CC0
F4C1C3F349B3F7BEB30E4A0CFE1C85180DC338C2C1C6E7A5CE3104303178724CCC5F451F573F3B24
7F24052000202003291F130F1B0E070C0E0D0F0E0F0B0B07070F1E1B330F27073F3F272E2F2F6F7B
2F2E1F2E4F7EFF7EDF3EBF253F3D2F39BF3D7F7FFED72FF39FE7773DBE9DBFBB3FE7A76E777DF55C
5F5F7ADF7FBD7F6AFE7B7D1FBE7F7F7DD7F63FBFBF2D3B7F7F5F2F7F3D7F7D3B3F3B7FFF4D676F7F
5D9FAD7DD17F7F6F6F0B6F7F3F767F1779364737370F7D3F5F377F2F3D3F7F1F2FE7709FB7BCB77B
0B77CF1DF5BF1F7F3D3E4E7F197F571F7D7E3F7F7F7D7F6F4F75FF6F7ECE2FFF793EFFEDB7BDDD1F
FF3BCE3F7F3FBF3D6C7FFF7F7F4FAF7F6FFFFF8D7777BF3AE30FAEEEEBCF5FEEFEE75FFEACFFDF0F
DFFFF77FFF677F4FFF7F7F1B5F1F5F146F1F1E1B3B1F3F273303170F370E250B",16)
</code></pre>
<p>Answer:</p>
<pre><code>611951595100708231079693644541095422704525056339295086455197024065285448917042457
942011979060274412229909425184116963447100932992139876977824261789243946528467423
887840013630358158845039770703659333212332565531927875442166643379024991542726916
563271158141698128396823655639931773363878078933197184072343959630467756337300811
165816534945075483141582643531294791665590339000206551162697220540050652439977992
246472159627917169957822698172925680112854091876671868161705785698942483896808137
210721991100755736178634253569843464062494863175653771387230991126430841565373390
924951878267929443498220727531299945275045612499928105876210478958806304156695438
684335624641395635997624911334453040399012259638042898470872203581555352191122920
004010193837249388365999010692555403377045768493630826307316376698443166439386014
145858084176544890282148970436631175577000673079418699845203671050174181808397880
048734270748095682582556024378558289251964544327507321930196203199459115159756564
507340111030285226951393012863778670390172056906403480159339130447254293412506482
027099835944315172972281427649277354815211185293109925602315480350955479477144523
387689192243720928249121486221114300503766209279369960344185651810101969585926336
07333771272398091
</code></pre>
<p>To get the set-bit count I have written the following code in C:</p>
<pre><code>int bitsoncount(unsigned x)
{
unsigned int b=0;
if(x > 1)
b=1;
while(x &= (x - 1))
b++;
return b;
}
</code></pre>
<p>When I tried the same code in python it did not work. I am new to python through curiosity I'm experimenting, excuse me if am wrong.</p>
<pre><code>def bitsoncount(x):
b=0;
if(x>1):
b=1;
while(x &= (x-1)):
</code></pre>
<p>I get an error at the last line, need some help in resolving this and implementing the logic in python :-)</p>
<p>I was interested in checking out the set bits version in python after what i have seen!</p>
<p>Thank You,
Chaitanya</p>
<p>Related question: <a href="http://stackoverflow.com/questions/109023/best-algorithm-to-count-the-number-of-set-bits-in-a-32-bit-integer">Best algorithm to count the number of set bits in a 32-bit integer?</a></p>
| 13 | 2009-01-02T18:09:07Z | 407,619 | <p>What version of Python are you using?
First off, Python uses white space not semicolon's, so to start it should look something like this...</p>
<pre><code> def bitsoncount(x):
b=0
while(x > 0):
x &= x - 1
b+=1
return b
</code></pre>
| 4 | 2009-01-02T18:18:54Z | [
"python",
"bit-manipulation"
] |
Python: Set Bits Count (popcount) | 407,587 | <p>Few blob's have been duplicated in my database(oracle 11g), performed XOR operations on the blob using UTL_RAW.BIT_XOR. After that i wanted to count the number of set bits in the binary string, so wrote the code above.</p>
<p>During a small experiment, i wanted to see what is the hex and the integer value produced and wrote this procedure..</p>
<pre><code>SQL> declare
2
3 vblob1 blob;
4
5 BEGIN
6
7 select leftiriscode INTO vblob1 FROM irisdata WHERE irisid=1;
8
9 dbms_output.put_line(rawtohex(vblob1));
10
11
12 dbms_output.put_line(UTL_RAW.CAST_TO_binary_integer(vblob1));
13
14
15 END;
16 /
</code></pre>
<p>OUTPUT: HEXVALUE:</p>
<pre><code>0F0008020003030D030C1D1C3C383C330A3311373724764C54496C0A6B029B84840547A341BBA83D
BB5FB9DE4CDE5EFE96E1FC6169438344D604681D409F9F9F3BC07EE0C4E0C033A23B37791F59F84F
F94E4F664E3072B0229DA09D9F0F1FC600C2E380D6988C198B39517D157E7D66FE675237673D3D28
3A016C01411003343C76740F710F0F4F8FE976E1E882C186D316A63C0C7D7D7D7D397F016101B043
0176C37E767C7E0C7D010C8302C2D3E4F2ACE42F8D3F3F367A46F54285434ABB61BDB53CBF6C7CC0
F4C1C3F349B3F7BEB30E4A0CFE1C85180DC338C2C1C6E7A5CE3104303178724CCC5F451F573F3B24
7F24052000202003291F130F1B0E070C0E0D0F0E0F0B0B07070F1E1B330F27073F3F272E2F2F6F7B
2F2E1F2E4F7EFF7EDF3EBF253F3D2F39BF3D7F7FFED72FF39FE7773DBE9DBFBB3FE7A76E777DF55C
5F5F7ADF7FBD7F6AFE7B7D1FBE7F7F7DD7F63FBFBF2D3B7F7F5F2F7F3D7F7D3B3F3B7FFF4D676F7F
5D9FAD7DD17F7F6F6F0B6F7F3F767F1779364737370F7D3F5F377F2F3D3F7F1F2FE7709FB7BCB77B
0B77CF1DF5BF1F7F3D3E4E7F197F571F7D7E3F7F7F7D7F6F4F75FF6F7ECE2FFF793EFFEDB7BDDD1F
FF3BCE3F7F3FBF3D6C7FFF7F7F4FAF7F6FFFFF8D7777BF3AE30FAEEEEBCF5FEEFEE75FFEACFFDF0F
DFFFF77FFF677F4FFF7F7F1B5F1F5F146F1F1E1B3B1F3F273303170F370E250B
INTEGER VALUE: 15
</code></pre>
<p>There was a variance between the hex code and the integer value produced, so used the following python code to check the actual integer value.</p>
<pre><code>print int("0F0008020003030D030C1D1C3C383C330A3311373724764C54496C0A6B029B84840547A341BBA83D
BB5FB9DE4CDE5EFE96E1FC6169438344D604681D409F9F9F3BC07EE0C4E0C033A23B37791F59F84F
F94E4F664E3072B0229DA09D9F0F1FC600C2E380D6988C198B39517D157E7D66FE675237673D3D28
3A016C01411003343C76740F710F0F4F8FE976E1E882C186D316A63C0C7D7D7D7D397F016101B043
0176C37E767C7E0C7D010C8302C2D3E4F2ACE42F8D3F3F367A46F54285434ABB61BDB53CBF6C7CC0
F4C1C3F349B3F7BEB30E4A0CFE1C85180DC338C2C1C6E7A5CE3104303178724CCC5F451F573F3B24
7F24052000202003291F130F1B0E070C0E0D0F0E0F0B0B07070F1E1B330F27073F3F272E2F2F6F7B
2F2E1F2E4F7EFF7EDF3EBF253F3D2F39BF3D7F7FFED72FF39FE7773DBE9DBFBB3FE7A76E777DF55C
5F5F7ADF7FBD7F6AFE7B7D1FBE7F7F7DD7F63FBFBF2D3B7F7F5F2F7F3D7F7D3B3F3B7FFF4D676F7F
5D9FAD7DD17F7F6F6F0B6F7F3F767F1779364737370F7D3F5F377F2F3D3F7F1F2FE7709FB7BCB77B
0B77CF1DF5BF1F7F3D3E4E7F197F571F7D7E3F7F7F7D7F6F4F75FF6F7ECE2FFF793EFFEDB7BDDD1F
FF3BCE3F7F3FBF3D6C7FFF7F7F4FAF7F6FFFFF8D7777BF3AE30FAEEEEBCF5FEEFEE75FFEACFFDF0F
DFFFF77FFF677F4FFF7F7F1B5F1F5F146F1F1E1B3B1F3F273303170F370E250B",16)
</code></pre>
<p>Answer:</p>
<pre><code>611951595100708231079693644541095422704525056339295086455197024065285448917042457
942011979060274412229909425184116963447100932992139876977824261789243946528467423
887840013630358158845039770703659333212332565531927875442166643379024991542726916
563271158141698128396823655639931773363878078933197184072343959630467756337300811
165816534945075483141582643531294791665590339000206551162697220540050652439977992
246472159627917169957822698172925680112854091876671868161705785698942483896808137
210721991100755736178634253569843464062494863175653771387230991126430841565373390
924951878267929443498220727531299945275045612499928105876210478958806304156695438
684335624641395635997624911334453040399012259638042898470872203581555352191122920
004010193837249388365999010692555403377045768493630826307316376698443166439386014
145858084176544890282148970436631175577000673079418699845203671050174181808397880
048734270748095682582556024378558289251964544327507321930196203199459115159756564
507340111030285226951393012863778670390172056906403480159339130447254293412506482
027099835944315172972281427649277354815211185293109925602315480350955479477144523
387689192243720928249121486221114300503766209279369960344185651810101969585926336
07333771272398091
</code></pre>
<p>To get the set-bit count I have written the following code in C:</p>
<pre><code>int bitsoncount(unsigned x)
{
unsigned int b=0;
if(x > 1)
b=1;
while(x &= (x - 1))
b++;
return b;
}
</code></pre>
<p>When I tried the same code in python it did not work. I am new to python through curiosity I'm experimenting, excuse me if am wrong.</p>
<pre><code>def bitsoncount(x):
b=0;
if(x>1):
b=1;
while(x &= (x-1)):
</code></pre>
<p>I get an error at the last line, need some help in resolving this and implementing the logic in python :-)</p>
<p>I was interested in checking out the set bits version in python after what i have seen!</p>
<p>Thank You,
Chaitanya</p>
<p>Related question: <a href="http://stackoverflow.com/questions/109023/best-algorithm-to-count-the-number-of-set-bits-in-a-32-bit-integer">Best algorithm to count the number of set bits in a 32-bit integer?</a></p>
| 13 | 2009-01-02T18:09:07Z | 407,650 | <p>The direct translation of your C algorithm is as follows:</p>
<pre><code>def bitsoncount(x):
b = 0
while x > 0:
x &= x - 1
b += 1
return b
</code></pre>
| 3 | 2009-01-02T18:31:19Z | [
"python",
"bit-manipulation"
] |
Python: Set Bits Count (popcount) | 407,587 | <p>Few blob's have been duplicated in my database(oracle 11g), performed XOR operations on the blob using UTL_RAW.BIT_XOR. After that i wanted to count the number of set bits in the binary string, so wrote the code above.</p>
<p>During a small experiment, i wanted to see what is the hex and the integer value produced and wrote this procedure..</p>
<pre><code>SQL> declare
2
3 vblob1 blob;
4
5 BEGIN
6
7 select leftiriscode INTO vblob1 FROM irisdata WHERE irisid=1;
8
9 dbms_output.put_line(rawtohex(vblob1));
10
11
12 dbms_output.put_line(UTL_RAW.CAST_TO_binary_integer(vblob1));
13
14
15 END;
16 /
</code></pre>
<p>OUTPUT: HEXVALUE:</p>
<pre><code>0F0008020003030D030C1D1C3C383C330A3311373724764C54496C0A6B029B84840547A341BBA83D
BB5FB9DE4CDE5EFE96E1FC6169438344D604681D409F9F9F3BC07EE0C4E0C033A23B37791F59F84F
F94E4F664E3072B0229DA09D9F0F1FC600C2E380D6988C198B39517D157E7D66FE675237673D3D28
3A016C01411003343C76740F710F0F4F8FE976E1E882C186D316A63C0C7D7D7D7D397F016101B043
0176C37E767C7E0C7D010C8302C2D3E4F2ACE42F8D3F3F367A46F54285434ABB61BDB53CBF6C7CC0
F4C1C3F349B3F7BEB30E4A0CFE1C85180DC338C2C1C6E7A5CE3104303178724CCC5F451F573F3B24
7F24052000202003291F130F1B0E070C0E0D0F0E0F0B0B07070F1E1B330F27073F3F272E2F2F6F7B
2F2E1F2E4F7EFF7EDF3EBF253F3D2F39BF3D7F7FFED72FF39FE7773DBE9DBFBB3FE7A76E777DF55C
5F5F7ADF7FBD7F6AFE7B7D1FBE7F7F7DD7F63FBFBF2D3B7F7F5F2F7F3D7F7D3B3F3B7FFF4D676F7F
5D9FAD7DD17F7F6F6F0B6F7F3F767F1779364737370F7D3F5F377F2F3D3F7F1F2FE7709FB7BCB77B
0B77CF1DF5BF1F7F3D3E4E7F197F571F7D7E3F7F7F7D7F6F4F75FF6F7ECE2FFF793EFFEDB7BDDD1F
FF3BCE3F7F3FBF3D6C7FFF7F7F4FAF7F6FFFFF8D7777BF3AE30FAEEEEBCF5FEEFEE75FFEACFFDF0F
DFFFF77FFF677F4FFF7F7F1B5F1F5F146F1F1E1B3B1F3F273303170F370E250B
INTEGER VALUE: 15
</code></pre>
<p>There was a variance between the hex code and the integer value produced, so used the following python code to check the actual integer value.</p>
<pre><code>print int("0F0008020003030D030C1D1C3C383C330A3311373724764C54496C0A6B029B84840547A341BBA83D
BB5FB9DE4CDE5EFE96E1FC6169438344D604681D409F9F9F3BC07EE0C4E0C033A23B37791F59F84F
F94E4F664E3072B0229DA09D9F0F1FC600C2E380D6988C198B39517D157E7D66FE675237673D3D28
3A016C01411003343C76740F710F0F4F8FE976E1E882C186D316A63C0C7D7D7D7D397F016101B043
0176C37E767C7E0C7D010C8302C2D3E4F2ACE42F8D3F3F367A46F54285434ABB61BDB53CBF6C7CC0
F4C1C3F349B3F7BEB30E4A0CFE1C85180DC338C2C1C6E7A5CE3104303178724CCC5F451F573F3B24
7F24052000202003291F130F1B0E070C0E0D0F0E0F0B0B07070F1E1B330F27073F3F272E2F2F6F7B
2F2E1F2E4F7EFF7EDF3EBF253F3D2F39BF3D7F7FFED72FF39FE7773DBE9DBFBB3FE7A76E777DF55C
5F5F7ADF7FBD7F6AFE7B7D1FBE7F7F7DD7F63FBFBF2D3B7F7F5F2F7F3D7F7D3B3F3B7FFF4D676F7F
5D9FAD7DD17F7F6F6F0B6F7F3F767F1779364737370F7D3F5F377F2F3D3F7F1F2FE7709FB7BCB77B
0B77CF1DF5BF1F7F3D3E4E7F197F571F7D7E3F7F7F7D7F6F4F75FF6F7ECE2FFF793EFFEDB7BDDD1F
FF3BCE3F7F3FBF3D6C7FFF7F7F4FAF7F6FFFFF8D7777BF3AE30FAEEEEBCF5FEEFEE75FFEACFFDF0F
DFFFF77FFF677F4FFF7F7F1B5F1F5F146F1F1E1B3B1F3F273303170F370E250B",16)
</code></pre>
<p>Answer:</p>
<pre><code>611951595100708231079693644541095422704525056339295086455197024065285448917042457
942011979060274412229909425184116963447100932992139876977824261789243946528467423
887840013630358158845039770703659333212332565531927875442166643379024991542726916
563271158141698128396823655639931773363878078933197184072343959630467756337300811
165816534945075483141582643531294791665590339000206551162697220540050652439977992
246472159627917169957822698172925680112854091876671868161705785698942483896808137
210721991100755736178634253569843464062494863175653771387230991126430841565373390
924951878267929443498220727531299945275045612499928105876210478958806304156695438
684335624641395635997624911334453040399012259638042898470872203581555352191122920
004010193837249388365999010692555403377045768493630826307316376698443166439386014
145858084176544890282148970436631175577000673079418699845203671050174181808397880
048734270748095682582556024378558289251964544327507321930196203199459115159756564
507340111030285226951393012863778670390172056906403480159339130447254293412506482
027099835944315172972281427649277354815211185293109925602315480350955479477144523
387689192243720928249121486221114300503766209279369960344185651810101969585926336
07333771272398091
</code></pre>
<p>To get the set-bit count I have written the following code in C:</p>
<pre><code>int bitsoncount(unsigned x)
{
unsigned int b=0;
if(x > 1)
b=1;
while(x &= (x - 1))
b++;
return b;
}
</code></pre>
<p>When I tried the same code in python it did not work. I am new to python through curiosity I'm experimenting, excuse me if am wrong.</p>
<pre><code>def bitsoncount(x):
b=0;
if(x>1):
b=1;
while(x &= (x-1)):
</code></pre>
<p>I get an error at the last line, need some help in resolving this and implementing the logic in python :-)</p>
<p>I was interested in checking out the set bits version in python after what i have seen!</p>
<p>Thank You,
Chaitanya</p>
<p>Related question: <a href="http://stackoverflow.com/questions/109023/best-algorithm-to-count-the-number-of-set-bits-in-a-32-bit-integer">Best algorithm to count the number of set bits in a 32-bit integer?</a></p>
| 13 | 2009-01-02T18:09:07Z | 407,672 | <p>Maybe this is what you mean?</p>
<pre><code>def bits_on_count(x):
b = 0
while x != 0:
if x & 1: # Last bit is a 1
b += 1
x >>= 1 # Shift the bits of x right
return b
</code></pre>
<p>There's also a way to do it simply in Python 3.0:</p>
<pre><code>def bits_on_count(x):
return sum(c=='1' for c in bin(x))
</code></pre>
<p>This uses the fact that bin(x) gives a binary representation of x.</p>
| 2 | 2009-01-02T18:40:29Z | [
"python",
"bit-manipulation"
] |
Python: Set Bits Count (popcount) | 407,587 | <p>Few blob's have been duplicated in my database(oracle 11g), performed XOR operations on the blob using UTL_RAW.BIT_XOR. After that i wanted to count the number of set bits in the binary string, so wrote the code above.</p>
<p>During a small experiment, i wanted to see what is the hex and the integer value produced and wrote this procedure..</p>
<pre><code>SQL> declare
2
3 vblob1 blob;
4
5 BEGIN
6
7 select leftiriscode INTO vblob1 FROM irisdata WHERE irisid=1;
8
9 dbms_output.put_line(rawtohex(vblob1));
10
11
12 dbms_output.put_line(UTL_RAW.CAST_TO_binary_integer(vblob1));
13
14
15 END;
16 /
</code></pre>
<p>OUTPUT: HEXVALUE:</p>
<pre><code>0F0008020003030D030C1D1C3C383C330A3311373724764C54496C0A6B029B84840547A341BBA83D
BB5FB9DE4CDE5EFE96E1FC6169438344D604681D409F9F9F3BC07EE0C4E0C033A23B37791F59F84F
F94E4F664E3072B0229DA09D9F0F1FC600C2E380D6988C198B39517D157E7D66FE675237673D3D28
3A016C01411003343C76740F710F0F4F8FE976E1E882C186D316A63C0C7D7D7D7D397F016101B043
0176C37E767C7E0C7D010C8302C2D3E4F2ACE42F8D3F3F367A46F54285434ABB61BDB53CBF6C7CC0
F4C1C3F349B3F7BEB30E4A0CFE1C85180DC338C2C1C6E7A5CE3104303178724CCC5F451F573F3B24
7F24052000202003291F130F1B0E070C0E0D0F0E0F0B0B07070F1E1B330F27073F3F272E2F2F6F7B
2F2E1F2E4F7EFF7EDF3EBF253F3D2F39BF3D7F7FFED72FF39FE7773DBE9DBFBB3FE7A76E777DF55C
5F5F7ADF7FBD7F6AFE7B7D1FBE7F7F7DD7F63FBFBF2D3B7F7F5F2F7F3D7F7D3B3F3B7FFF4D676F7F
5D9FAD7DD17F7F6F6F0B6F7F3F767F1779364737370F7D3F5F377F2F3D3F7F1F2FE7709FB7BCB77B
0B77CF1DF5BF1F7F3D3E4E7F197F571F7D7E3F7F7F7D7F6F4F75FF6F7ECE2FFF793EFFEDB7BDDD1F
FF3BCE3F7F3FBF3D6C7FFF7F7F4FAF7F6FFFFF8D7777BF3AE30FAEEEEBCF5FEEFEE75FFEACFFDF0F
DFFFF77FFF677F4FFF7F7F1B5F1F5F146F1F1E1B3B1F3F273303170F370E250B
INTEGER VALUE: 15
</code></pre>
<p>There was a variance between the hex code and the integer value produced, so used the following python code to check the actual integer value.</p>
<pre><code>print int("0F0008020003030D030C1D1C3C383C330A3311373724764C54496C0A6B029B84840547A341BBA83D
BB5FB9DE4CDE5EFE96E1FC6169438344D604681D409F9F9F3BC07EE0C4E0C033A23B37791F59F84F
F94E4F664E3072B0229DA09D9F0F1FC600C2E380D6988C198B39517D157E7D66FE675237673D3D28
3A016C01411003343C76740F710F0F4F8FE976E1E882C186D316A63C0C7D7D7D7D397F016101B043
0176C37E767C7E0C7D010C8302C2D3E4F2ACE42F8D3F3F367A46F54285434ABB61BDB53CBF6C7CC0
F4C1C3F349B3F7BEB30E4A0CFE1C85180DC338C2C1C6E7A5CE3104303178724CCC5F451F573F3B24
7F24052000202003291F130F1B0E070C0E0D0F0E0F0B0B07070F1E1B330F27073F3F272E2F2F6F7B
2F2E1F2E4F7EFF7EDF3EBF253F3D2F39BF3D7F7FFED72FF39FE7773DBE9DBFBB3FE7A76E777DF55C
5F5F7ADF7FBD7F6AFE7B7D1FBE7F7F7DD7F63FBFBF2D3B7F7F5F2F7F3D7F7D3B3F3B7FFF4D676F7F
5D9FAD7DD17F7F6F6F0B6F7F3F767F1779364737370F7D3F5F377F2F3D3F7F1F2FE7709FB7BCB77B
0B77CF1DF5BF1F7F3D3E4E7F197F571F7D7E3F7F7F7D7F6F4F75FF6F7ECE2FFF793EFFEDB7BDDD1F
FF3BCE3F7F3FBF3D6C7FFF7F7F4FAF7F6FFFFF8D7777BF3AE30FAEEEEBCF5FEEFEE75FFEACFFDF0F
DFFFF77FFF677F4FFF7F7F1B5F1F5F146F1F1E1B3B1F3F273303170F370E250B",16)
</code></pre>
<p>Answer:</p>
<pre><code>611951595100708231079693644541095422704525056339295086455197024065285448917042457
942011979060274412229909425184116963447100932992139876977824261789243946528467423
887840013630358158845039770703659333212332565531927875442166643379024991542726916
563271158141698128396823655639931773363878078933197184072343959630467756337300811
165816534945075483141582643531294791665590339000206551162697220540050652439977992
246472159627917169957822698172925680112854091876671868161705785698942483896808137
210721991100755736178634253569843464062494863175653771387230991126430841565373390
924951878267929443498220727531299945275045612499928105876210478958806304156695438
684335624641395635997624911334453040399012259638042898470872203581555352191122920
004010193837249388365999010692555403377045768493630826307316376698443166439386014
145858084176544890282148970436631175577000673079418699845203671050174181808397880
048734270748095682582556024378558289251964544327507321930196203199459115159756564
507340111030285226951393012863778670390172056906403480159339130447254293412506482
027099835944315172972281427649277354815211185293109925602315480350955479477144523
387689192243720928249121486221114300503766209279369960344185651810101969585926336
07333771272398091
</code></pre>
<p>To get the set-bit count I have written the following code in C:</p>
<pre><code>int bitsoncount(unsigned x)
{
unsigned int b=0;
if(x > 1)
b=1;
while(x &= (x - 1))
b++;
return b;
}
</code></pre>
<p>When I tried the same code in python it did not work. I am new to python through curiosity I'm experimenting, excuse me if am wrong.</p>
<pre><code>def bitsoncount(x):
b=0;
if(x>1):
b=1;
while(x &= (x-1)):
</code></pre>
<p>I get an error at the last line, need some help in resolving this and implementing the logic in python :-)</p>
<p>I was interested in checking out the set bits version in python after what i have seen!</p>
<p>Thank You,
Chaitanya</p>
<p>Related question: <a href="http://stackoverflow.com/questions/109023/best-algorithm-to-count-the-number-of-set-bits-in-a-32-bit-integer">Best algorithm to count the number of set bits in a 32-bit integer?</a></p>
| 13 | 2009-01-02T18:09:07Z | 407,674 | <p>what you're looking for is called the <a href="http://en.wikipedia.org/wiki/Hamming_weight">Hamming Weight</a>.</p>
<p>in python 2.6/3.0 it can be found rather easily with:</p>
<pre><code>bits = sum( b == '1' for b in bin(x)[2:] )
</code></pre>
| 8 | 2009-01-02T18:42:26Z | [
"python",
"bit-manipulation"
] |
Python: Set Bits Count (popcount) | 407,587 | <p>Few blob's have been duplicated in my database(oracle 11g), performed XOR operations on the blob using UTL_RAW.BIT_XOR. After that i wanted to count the number of set bits in the binary string, so wrote the code above.</p>
<p>During a small experiment, i wanted to see what is the hex and the integer value produced and wrote this procedure..</p>
<pre><code>SQL> declare
2
3 vblob1 blob;
4
5 BEGIN
6
7 select leftiriscode INTO vblob1 FROM irisdata WHERE irisid=1;
8
9 dbms_output.put_line(rawtohex(vblob1));
10
11
12 dbms_output.put_line(UTL_RAW.CAST_TO_binary_integer(vblob1));
13
14
15 END;
16 /
</code></pre>
<p>OUTPUT: HEXVALUE:</p>
<pre><code>0F0008020003030D030C1D1C3C383C330A3311373724764C54496C0A6B029B84840547A341BBA83D
BB5FB9DE4CDE5EFE96E1FC6169438344D604681D409F9F9F3BC07EE0C4E0C033A23B37791F59F84F
F94E4F664E3072B0229DA09D9F0F1FC600C2E380D6988C198B39517D157E7D66FE675237673D3D28
3A016C01411003343C76740F710F0F4F8FE976E1E882C186D316A63C0C7D7D7D7D397F016101B043
0176C37E767C7E0C7D010C8302C2D3E4F2ACE42F8D3F3F367A46F54285434ABB61BDB53CBF6C7CC0
F4C1C3F349B3F7BEB30E4A0CFE1C85180DC338C2C1C6E7A5CE3104303178724CCC5F451F573F3B24
7F24052000202003291F130F1B0E070C0E0D0F0E0F0B0B07070F1E1B330F27073F3F272E2F2F6F7B
2F2E1F2E4F7EFF7EDF3EBF253F3D2F39BF3D7F7FFED72FF39FE7773DBE9DBFBB3FE7A76E777DF55C
5F5F7ADF7FBD7F6AFE7B7D1FBE7F7F7DD7F63FBFBF2D3B7F7F5F2F7F3D7F7D3B3F3B7FFF4D676F7F
5D9FAD7DD17F7F6F6F0B6F7F3F767F1779364737370F7D3F5F377F2F3D3F7F1F2FE7709FB7BCB77B
0B77CF1DF5BF1F7F3D3E4E7F197F571F7D7E3F7F7F7D7F6F4F75FF6F7ECE2FFF793EFFEDB7BDDD1F
FF3BCE3F7F3FBF3D6C7FFF7F7F4FAF7F6FFFFF8D7777BF3AE30FAEEEEBCF5FEEFEE75FFEACFFDF0F
DFFFF77FFF677F4FFF7F7F1B5F1F5F146F1F1E1B3B1F3F273303170F370E250B
INTEGER VALUE: 15
</code></pre>
<p>There was a variance between the hex code and the integer value produced, so used the following python code to check the actual integer value.</p>
<pre><code>print int("0F0008020003030D030C1D1C3C383C330A3311373724764C54496C0A6B029B84840547A341BBA83D
BB5FB9DE4CDE5EFE96E1FC6169438344D604681D409F9F9F3BC07EE0C4E0C033A23B37791F59F84F
F94E4F664E3072B0229DA09D9F0F1FC600C2E380D6988C198B39517D157E7D66FE675237673D3D28
3A016C01411003343C76740F710F0F4F8FE976E1E882C186D316A63C0C7D7D7D7D397F016101B043
0176C37E767C7E0C7D010C8302C2D3E4F2ACE42F8D3F3F367A46F54285434ABB61BDB53CBF6C7CC0
F4C1C3F349B3F7BEB30E4A0CFE1C85180DC338C2C1C6E7A5CE3104303178724CCC5F451F573F3B24
7F24052000202003291F130F1B0E070C0E0D0F0E0F0B0B07070F1E1B330F27073F3F272E2F2F6F7B
2F2E1F2E4F7EFF7EDF3EBF253F3D2F39BF3D7F7FFED72FF39FE7773DBE9DBFBB3FE7A76E777DF55C
5F5F7ADF7FBD7F6AFE7B7D1FBE7F7F7DD7F63FBFBF2D3B7F7F5F2F7F3D7F7D3B3F3B7FFF4D676F7F
5D9FAD7DD17F7F6F6F0B6F7F3F767F1779364737370F7D3F5F377F2F3D3F7F1F2FE7709FB7BCB77B
0B77CF1DF5BF1F7F3D3E4E7F197F571F7D7E3F7F7F7D7F6F4F75FF6F7ECE2FFF793EFFEDB7BDDD1F
FF3BCE3F7F3FBF3D6C7FFF7F7F4FAF7F6FFFFF8D7777BF3AE30FAEEEEBCF5FEEFEE75FFEACFFDF0F
DFFFF77FFF677F4FFF7F7F1B5F1F5F146F1F1E1B3B1F3F273303170F370E250B",16)
</code></pre>
<p>Answer:</p>
<pre><code>611951595100708231079693644541095422704525056339295086455197024065285448917042457
942011979060274412229909425184116963447100932992139876977824261789243946528467423
887840013630358158845039770703659333212332565531927875442166643379024991542726916
563271158141698128396823655639931773363878078933197184072343959630467756337300811
165816534945075483141582643531294791665590339000206551162697220540050652439977992
246472159627917169957822698172925680112854091876671868161705785698942483896808137
210721991100755736178634253569843464062494863175653771387230991126430841565373390
924951878267929443498220727531299945275045612499928105876210478958806304156695438
684335624641395635997624911334453040399012259638042898470872203581555352191122920
004010193837249388365999010692555403377045768493630826307316376698443166439386014
145858084176544890282148970436631175577000673079418699845203671050174181808397880
048734270748095682582556024378558289251964544327507321930196203199459115159756564
507340111030285226951393012863778670390172056906403480159339130447254293412506482
027099835944315172972281427649277354815211185293109925602315480350955479477144523
387689192243720928249121486221114300503766209279369960344185651810101969585926336
07333771272398091
</code></pre>
<p>To get the set-bit count I have written the following code in C:</p>
<pre><code>int bitsoncount(unsigned x)
{
unsigned int b=0;
if(x > 1)
b=1;
while(x &= (x - 1))
b++;
return b;
}
</code></pre>
<p>When I tried the same code in python it did not work. I am new to python through curiosity I'm experimenting, excuse me if am wrong.</p>
<pre><code>def bitsoncount(x):
b=0;
if(x>1):
b=1;
while(x &= (x-1)):
</code></pre>
<p>I get an error at the last line, need some help in resolving this and implementing the logic in python :-)</p>
<p>I was interested in checking out the set bits version in python after what i have seen!</p>
<p>Thank You,
Chaitanya</p>
<p>Related question: <a href="http://stackoverflow.com/questions/109023/best-algorithm-to-count-the-number-of-set-bits-in-a-32-bit-integer">Best algorithm to count the number of set bits in a 32-bit integer?</a></p>
| 13 | 2009-01-02T18:09:07Z | 407,736 | <p>Try this module:</p>
<pre><code>import sys
if sys.maxint < 2**32:
msb2= 2**30
else:
msb2= 2**62
BITS=[-msb2*2] # not converted into long
while msb2:
BITS.append(msb2)
msb2 >>= 1
def bitcount(n):
return sum(1 for b in BITS if b&n)
</code></pre>
<p>This should work for machine integers (depending on your OS and the Python version). It won't work for any <code>long</code>.</p>
| 0 | 2009-01-02T19:06:26Z | [
"python",
"bit-manipulation"
] |
Python: Set Bits Count (popcount) | 407,587 | <p>Few blob's have been duplicated in my database(oracle 11g), performed XOR operations on the blob using UTL_RAW.BIT_XOR. After that i wanted to count the number of set bits in the binary string, so wrote the code above.</p>
<p>During a small experiment, i wanted to see what is the hex and the integer value produced and wrote this procedure..</p>
<pre><code>SQL> declare
2
3 vblob1 blob;
4
5 BEGIN
6
7 select leftiriscode INTO vblob1 FROM irisdata WHERE irisid=1;
8
9 dbms_output.put_line(rawtohex(vblob1));
10
11
12 dbms_output.put_line(UTL_RAW.CAST_TO_binary_integer(vblob1));
13
14
15 END;
16 /
</code></pre>
<p>OUTPUT: HEXVALUE:</p>
<pre><code>0F0008020003030D030C1D1C3C383C330A3311373724764C54496C0A6B029B84840547A341BBA83D
BB5FB9DE4CDE5EFE96E1FC6169438344D604681D409F9F9F3BC07EE0C4E0C033A23B37791F59F84F
F94E4F664E3072B0229DA09D9F0F1FC600C2E380D6988C198B39517D157E7D66FE675237673D3D28
3A016C01411003343C76740F710F0F4F8FE976E1E882C186D316A63C0C7D7D7D7D397F016101B043
0176C37E767C7E0C7D010C8302C2D3E4F2ACE42F8D3F3F367A46F54285434ABB61BDB53CBF6C7CC0
F4C1C3F349B3F7BEB30E4A0CFE1C85180DC338C2C1C6E7A5CE3104303178724CCC5F451F573F3B24
7F24052000202003291F130F1B0E070C0E0D0F0E0F0B0B07070F1E1B330F27073F3F272E2F2F6F7B
2F2E1F2E4F7EFF7EDF3EBF253F3D2F39BF3D7F7FFED72FF39FE7773DBE9DBFBB3FE7A76E777DF55C
5F5F7ADF7FBD7F6AFE7B7D1FBE7F7F7DD7F63FBFBF2D3B7F7F5F2F7F3D7F7D3B3F3B7FFF4D676F7F
5D9FAD7DD17F7F6F6F0B6F7F3F767F1779364737370F7D3F5F377F2F3D3F7F1F2FE7709FB7BCB77B
0B77CF1DF5BF1F7F3D3E4E7F197F571F7D7E3F7F7F7D7F6F4F75FF6F7ECE2FFF793EFFEDB7BDDD1F
FF3BCE3F7F3FBF3D6C7FFF7F7F4FAF7F6FFFFF8D7777BF3AE30FAEEEEBCF5FEEFEE75FFEACFFDF0F
DFFFF77FFF677F4FFF7F7F1B5F1F5F146F1F1E1B3B1F3F273303170F370E250B
INTEGER VALUE: 15
</code></pre>
<p>There was a variance between the hex code and the integer value produced, so used the following python code to check the actual integer value.</p>
<pre><code>print int("0F0008020003030D030C1D1C3C383C330A3311373724764C54496C0A6B029B84840547A341BBA83D
BB5FB9DE4CDE5EFE96E1FC6169438344D604681D409F9F9F3BC07EE0C4E0C033A23B37791F59F84F
F94E4F664E3072B0229DA09D9F0F1FC600C2E380D6988C198B39517D157E7D66FE675237673D3D28
3A016C01411003343C76740F710F0F4F8FE976E1E882C186D316A63C0C7D7D7D7D397F016101B043
0176C37E767C7E0C7D010C8302C2D3E4F2ACE42F8D3F3F367A46F54285434ABB61BDB53CBF6C7CC0
F4C1C3F349B3F7BEB30E4A0CFE1C85180DC338C2C1C6E7A5CE3104303178724CCC5F451F573F3B24
7F24052000202003291F130F1B0E070C0E0D0F0E0F0B0B07070F1E1B330F27073F3F272E2F2F6F7B
2F2E1F2E4F7EFF7EDF3EBF253F3D2F39BF3D7F7FFED72FF39FE7773DBE9DBFBB3FE7A76E777DF55C
5F5F7ADF7FBD7F6AFE7B7D1FBE7F7F7DD7F63FBFBF2D3B7F7F5F2F7F3D7F7D3B3F3B7FFF4D676F7F
5D9FAD7DD17F7F6F6F0B6F7F3F767F1779364737370F7D3F5F377F2F3D3F7F1F2FE7709FB7BCB77B
0B77CF1DF5BF1F7F3D3E4E7F197F571F7D7E3F7F7F7D7F6F4F75FF6F7ECE2FFF793EFFEDB7BDDD1F
FF3BCE3F7F3FBF3D6C7FFF7F7F4FAF7F6FFFFF8D7777BF3AE30FAEEEEBCF5FEEFEE75FFEACFFDF0F
DFFFF77FFF677F4FFF7F7F1B5F1F5F146F1F1E1B3B1F3F273303170F370E250B",16)
</code></pre>
<p>Answer:</p>
<pre><code>611951595100708231079693644541095422704525056339295086455197024065285448917042457
942011979060274412229909425184116963447100932992139876977824261789243946528467423
887840013630358158845039770703659333212332565531927875442166643379024991542726916
563271158141698128396823655639931773363878078933197184072343959630467756337300811
165816534945075483141582643531294791665590339000206551162697220540050652439977992
246472159627917169957822698172925680112854091876671868161705785698942483896808137
210721991100755736178634253569843464062494863175653771387230991126430841565373390
924951878267929443498220727531299945275045612499928105876210478958806304156695438
684335624641395635997624911334453040399012259638042898470872203581555352191122920
004010193837249388365999010692555403377045768493630826307316376698443166439386014
145858084176544890282148970436631175577000673079418699845203671050174181808397880
048734270748095682582556024378558289251964544327507321930196203199459115159756564
507340111030285226951393012863778670390172056906403480159339130447254293412506482
027099835944315172972281427649277354815211185293109925602315480350955479477144523
387689192243720928249121486221114300503766209279369960344185651810101969585926336
07333771272398091
</code></pre>
<p>To get the set-bit count I have written the following code in C:</p>
<pre><code>int bitsoncount(unsigned x)
{
unsigned int b=0;
if(x > 1)
b=1;
while(x &= (x - 1))
b++;
return b;
}
</code></pre>
<p>When I tried the same code in python it did not work. I am new to python through curiosity I'm experimenting, excuse me if am wrong.</p>
<pre><code>def bitsoncount(x):
b=0;
if(x>1):
b=1;
while(x &= (x-1)):
</code></pre>
<p>I get an error at the last line, need some help in resolving this and implementing the logic in python :-)</p>
<p>I was interested in checking out the set bits version in python after what i have seen!</p>
<p>Thank You,
Chaitanya</p>
<p>Related question: <a href="http://stackoverflow.com/questions/109023/best-algorithm-to-count-the-number-of-set-bits-in-a-32-bit-integer">Best algorithm to count the number of set bits in a 32-bit integer?</a></p>
| 13 | 2009-01-02T18:09:07Z | 407,758 | <p>Python 2.6 or 3.0:</p>
<pre><code>def bitsoncount(x):
return bin(x).count('1')
</code></pre>
<p>Example:</p>
<pre><code>>>> x = 123
>>> bin(x)
'0b1111011'
>>> bitsoncount(x)
6
</code></pre>
<p>Or </p>
<p><a href="http://stackoverflow.com/questions/109023/best-algorithm-to-count-the-number-of-set-bits-in-a-32-bit-integer#109025">Matt Howells's answer</a> in Python:</p>
<pre><code>def bitsoncount(i):
assert 0 <= i < 0x100000000
i = i - ((i >> 1) & 0x55555555)
i = (i & 0x33333333) + ((i >> 2) & 0x33333333)
return (((i + (i >> 4) & 0xF0F0F0F) * 0x1010101) & 0xffffffff) >> 24
</code></pre>
| 29 | 2009-01-02T19:12:55Z | [
"python",
"bit-manipulation"
] |
Python: Set Bits Count (popcount) | 407,587 | <p>Few blob's have been duplicated in my database(oracle 11g), performed XOR operations on the blob using UTL_RAW.BIT_XOR. After that i wanted to count the number of set bits in the binary string, so wrote the code above.</p>
<p>During a small experiment, i wanted to see what is the hex and the integer value produced and wrote this procedure..</p>
<pre><code>SQL> declare
2
3 vblob1 blob;
4
5 BEGIN
6
7 select leftiriscode INTO vblob1 FROM irisdata WHERE irisid=1;
8
9 dbms_output.put_line(rawtohex(vblob1));
10
11
12 dbms_output.put_line(UTL_RAW.CAST_TO_binary_integer(vblob1));
13
14
15 END;
16 /
</code></pre>
<p>OUTPUT: HEXVALUE:</p>
<pre><code>0F0008020003030D030C1D1C3C383C330A3311373724764C54496C0A6B029B84840547A341BBA83D
BB5FB9DE4CDE5EFE96E1FC6169438344D604681D409F9F9F3BC07EE0C4E0C033A23B37791F59F84F
F94E4F664E3072B0229DA09D9F0F1FC600C2E380D6988C198B39517D157E7D66FE675237673D3D28
3A016C01411003343C76740F710F0F4F8FE976E1E882C186D316A63C0C7D7D7D7D397F016101B043
0176C37E767C7E0C7D010C8302C2D3E4F2ACE42F8D3F3F367A46F54285434ABB61BDB53CBF6C7CC0
F4C1C3F349B3F7BEB30E4A0CFE1C85180DC338C2C1C6E7A5CE3104303178724CCC5F451F573F3B24
7F24052000202003291F130F1B0E070C0E0D0F0E0F0B0B07070F1E1B330F27073F3F272E2F2F6F7B
2F2E1F2E4F7EFF7EDF3EBF253F3D2F39BF3D7F7FFED72FF39FE7773DBE9DBFBB3FE7A76E777DF55C
5F5F7ADF7FBD7F6AFE7B7D1FBE7F7F7DD7F63FBFBF2D3B7F7F5F2F7F3D7F7D3B3F3B7FFF4D676F7F
5D9FAD7DD17F7F6F6F0B6F7F3F767F1779364737370F7D3F5F377F2F3D3F7F1F2FE7709FB7BCB77B
0B77CF1DF5BF1F7F3D3E4E7F197F571F7D7E3F7F7F7D7F6F4F75FF6F7ECE2FFF793EFFEDB7BDDD1F
FF3BCE3F7F3FBF3D6C7FFF7F7F4FAF7F6FFFFF8D7777BF3AE30FAEEEEBCF5FEEFEE75FFEACFFDF0F
DFFFF77FFF677F4FFF7F7F1B5F1F5F146F1F1E1B3B1F3F273303170F370E250B
INTEGER VALUE: 15
</code></pre>
<p>There was a variance between the hex code and the integer value produced, so used the following python code to check the actual integer value.</p>
<pre><code>print int("0F0008020003030D030C1D1C3C383C330A3311373724764C54496C0A6B029B84840547A341BBA83D
BB5FB9DE4CDE5EFE96E1FC6169438344D604681D409F9F9F3BC07EE0C4E0C033A23B37791F59F84F
F94E4F664E3072B0229DA09D9F0F1FC600C2E380D6988C198B39517D157E7D66FE675237673D3D28
3A016C01411003343C76740F710F0F4F8FE976E1E882C186D316A63C0C7D7D7D7D397F016101B043
0176C37E767C7E0C7D010C8302C2D3E4F2ACE42F8D3F3F367A46F54285434ABB61BDB53CBF6C7CC0
F4C1C3F349B3F7BEB30E4A0CFE1C85180DC338C2C1C6E7A5CE3104303178724CCC5F451F573F3B24
7F24052000202003291F130F1B0E070C0E0D0F0E0F0B0B07070F1E1B330F27073F3F272E2F2F6F7B
2F2E1F2E4F7EFF7EDF3EBF253F3D2F39BF3D7F7FFED72FF39FE7773DBE9DBFBB3FE7A76E777DF55C
5F5F7ADF7FBD7F6AFE7B7D1FBE7F7F7DD7F63FBFBF2D3B7F7F5F2F7F3D7F7D3B3F3B7FFF4D676F7F
5D9FAD7DD17F7F6F6F0B6F7F3F767F1779364737370F7D3F5F377F2F3D3F7F1F2FE7709FB7BCB77B
0B77CF1DF5BF1F7F3D3E4E7F197F571F7D7E3F7F7F7D7F6F4F75FF6F7ECE2FFF793EFFEDB7BDDD1F
FF3BCE3F7F3FBF3D6C7FFF7F7F4FAF7F6FFFFF8D7777BF3AE30FAEEEEBCF5FEEFEE75FFEACFFDF0F
DFFFF77FFF677F4FFF7F7F1B5F1F5F146F1F1E1B3B1F3F273303170F370E250B",16)
</code></pre>
<p>Answer:</p>
<pre><code>611951595100708231079693644541095422704525056339295086455197024065285448917042457
942011979060274412229909425184116963447100932992139876977824261789243946528467423
887840013630358158845039770703659333212332565531927875442166643379024991542726916
563271158141698128396823655639931773363878078933197184072343959630467756337300811
165816534945075483141582643531294791665590339000206551162697220540050652439977992
246472159627917169957822698172925680112854091876671868161705785698942483896808137
210721991100755736178634253569843464062494863175653771387230991126430841565373390
924951878267929443498220727531299945275045612499928105876210478958806304156695438
684335624641395635997624911334453040399012259638042898470872203581555352191122920
004010193837249388365999010692555403377045768493630826307316376698443166439386014
145858084176544890282148970436631175577000673079418699845203671050174181808397880
048734270748095682582556024378558289251964544327507321930196203199459115159756564
507340111030285226951393012863778670390172056906403480159339130447254293412506482
027099835944315172972281427649277354815211185293109925602315480350955479477144523
387689192243720928249121486221114300503766209279369960344185651810101969585926336
07333771272398091
</code></pre>
<p>To get the set-bit count I have written the following code in C:</p>
<pre><code>int bitsoncount(unsigned x)
{
unsigned int b=0;
if(x > 1)
b=1;
while(x &= (x - 1))
b++;
return b;
}
</code></pre>
<p>When I tried the same code in python it did not work. I am new to python through curiosity I'm experimenting, excuse me if am wrong.</p>
<pre><code>def bitsoncount(x):
b=0;
if(x>1):
b=1;
while(x &= (x-1)):
</code></pre>
<p>I get an error at the last line, need some help in resolving this and implementing the logic in python :-)</p>
<p>I was interested in checking out the set bits version in python after what i have seen!</p>
<p>Thank You,
Chaitanya</p>
<p>Related question: <a href="http://stackoverflow.com/questions/109023/best-algorithm-to-count-the-number-of-set-bits-in-a-32-bit-integer">Best algorithm to count the number of set bits in a 32-bit integer?</a></p>
| 13 | 2009-01-02T18:09:07Z | 1,040,157 | <p>How do you like this one:</p>
<pre><code>def bitsoncount(x):
b = 0
bit = 1
while bit <= x:
b += int(x & bit > 0)
bit = bit << 1
return b
</code></pre>
<p>Basically, you use a test bit that starts right and gets shifted all the way through up to the bit length of your in parameter. For each position the bit & x yields a single bit which is on, or none. Check > 0 and turn the resulting True|False into 1|0 with int(), and add this to the accumulator. Seems to work nicely for longs :-) .</p>
| 0 | 2009-06-24T18:41:03Z | [
"python",
"bit-manipulation"
] |
A generic priority queue for Python | 407,734 | <p>I need to use a priority queue in my Python code. Looking around for something efficient, I came upon <a href="http://docs.python.org/library/heapq.html">heapq</a>. It looks good, but seems to be specified only for integers. I suppose it works with any objects that have comparison operators, but it doesn't specify what comparison operators it needs. </p>
<p>Besides, <code>heapq</code> seems to be implemented in Python, so it's not fast.</p>
<p>Are you aware of any fast implementations for priority queues in Python ? Optimally, I'd like the queue to be generic (i.e. work well for any object with a specified comparison operator).</p>
<p>Thanks in advance</p>
<p><strong>Update:</strong></p>
<p>Re comparison in <code>heapq</code>, I can either use a <code>(priority, object)</code> as Charlie Martin suggests, or just implement <code>__cmp__</code> for my object. </p>
<p>I'm still looking for something faster than <code>heapq</code>.</p>
| 33 | 2009-01-02T19:05:54Z | 407,755 | <p>Um, <a href="http://docs.python.org/library/queue.html#Queue.PriorityQueue">Queue.PriorityQueue</a> ? Recall that Python isn't strongly typed, so you can save anything you like: just make a tuple of (priority,thing) and you're set.</p>
| 31 | 2009-01-02T19:11:31Z | [
"python",
"queue"
] |
A generic priority queue for Python | 407,734 | <p>I need to use a priority queue in my Python code. Looking around for something efficient, I came upon <a href="http://docs.python.org/library/heapq.html">heapq</a>. It looks good, but seems to be specified only for integers. I suppose it works with any objects that have comparison operators, but it doesn't specify what comparison operators it needs. </p>
<p>Besides, <code>heapq</code> seems to be implemented in Python, so it's not fast.</p>
<p>Are you aware of any fast implementations for priority queues in Python ? Optimally, I'd like the queue to be generic (i.e. work well for any object with a specified comparison operator).</p>
<p>Thanks in advance</p>
<p><strong>Update:</strong></p>
<p>Re comparison in <code>heapq</code>, I can either use a <code>(priority, object)</code> as Charlie Martin suggests, or just implement <code>__cmp__</code> for my object. </p>
<p>I'm still looking for something faster than <code>heapq</code>.</p>
| 33 | 2009-01-02T19:05:54Z | 407,759 | <p>Did you look at the <a href="http://docs.python.org/_sources/library/heapq.txt" rel="nofollow">"Show Source" link</a> on the heapq page? There's an example a little less than halfway down of using a heap with a list of (int, char) tuples as a priority queue.</p>
| 7 | 2009-01-02T19:13:33Z | [
"python",
"queue"
] |
A generic priority queue for Python | 407,734 | <p>I need to use a priority queue in my Python code. Looking around for something efficient, I came upon <a href="http://docs.python.org/library/heapq.html">heapq</a>. It looks good, but seems to be specified only for integers. I suppose it works with any objects that have comparison operators, but it doesn't specify what comparison operators it needs. </p>
<p>Besides, <code>heapq</code> seems to be implemented in Python, so it's not fast.</p>
<p>Are you aware of any fast implementations for priority queues in Python ? Optimally, I'd like the queue to be generic (i.e. work well for any object with a specified comparison operator).</p>
<p>Thanks in advance</p>
<p><strong>Update:</strong></p>
<p>Re comparison in <code>heapq</code>, I can either use a <code>(priority, object)</code> as Charlie Martin suggests, or just implement <code>__cmp__</code> for my object. </p>
<p>I'm still looking for something faster than <code>heapq</code>.</p>
| 33 | 2009-01-02T19:05:54Z | 407,868 | <p>I've not used it, but you could try <a href="http://hkn.eecs.berkeley.edu/~dyoo/python/">PyHeap</a>. It's written in C so hopefully it is fast enough for you. </p>
<p>Are you positive heapq/PriorityQueue won't be fast enough? It might be worth going with one of them to start, and then profiling to see if it really is your performance bottlneck.</p>
| 6 | 2009-01-02T19:57:30Z | [
"python",
"queue"
] |
A generic priority queue for Python | 407,734 | <p>I need to use a priority queue in my Python code. Looking around for something efficient, I came upon <a href="http://docs.python.org/library/heapq.html">heapq</a>. It looks good, but seems to be specified only for integers. I suppose it works with any objects that have comparison operators, but it doesn't specify what comparison operators it needs. </p>
<p>Besides, <code>heapq</code> seems to be implemented in Python, so it's not fast.</p>
<p>Are you aware of any fast implementations for priority queues in Python ? Optimally, I'd like the queue to be generic (i.e. work well for any object with a specified comparison operator).</p>
<p>Thanks in advance</p>
<p><strong>Update:</strong></p>
<p>Re comparison in <code>heapq</code>, I can either use a <code>(priority, object)</code> as Charlie Martin suggests, or just implement <code>__cmp__</code> for my object. </p>
<p>I'm still looking for something faster than <code>heapq</code>.</p>
| 33 | 2009-01-02T19:05:54Z | 407,922 | <p>I ended up implementing a wrapper for <code>heapq</code>, adding a dict for maintaining the queue's elements unique. The result should be quite efficient for all operators:</p>
<pre><code>class PriorityQueueSet(object):
"""
Combined priority queue and set data structure.
Acts like a priority queue, except that its items are guaranteed to be
unique. Provides O(1) membership test, O(log N) insertion and O(log N)
removal of the smallest item.
Important: the items of this data structure must be both comparable and
hashable (i.e. must implement __cmp__ and __hash__). This is true of
Python's built-in objects, but you should implement those methods if you
want to use the data structure for custom objects.
"""
def __init__(self, items=[]):
"""
Create a new PriorityQueueSet.
Arguments:
items (list): An initial item list - it can be unsorted and
non-unique. The data structure will be created in O(N).
"""
self.set = dict((item, True) for item in items)
self.heap = self.set.keys()
heapq.heapify(self.heap)
def has_item(self, item):
"""Check if ``item`` exists in the queue."""
return item in self.set
def pop_smallest(self):
"""Remove and return the smallest item from the queue."""
smallest = heapq.heappop(self.heap)
del self.set[smallest]
return smallest
def add(self, item):
"""Add ``item`` to the queue if doesn't already exist."""
if item not in self.set:
self.set[item] = True
heapq.heappush(self.heap, item)
</code></pre>
| 16 | 2009-01-02T20:19:36Z | [
"python",
"queue"
] |
A generic priority queue for Python | 407,734 | <p>I need to use a priority queue in my Python code. Looking around for something efficient, I came upon <a href="http://docs.python.org/library/heapq.html">heapq</a>. It looks good, but seems to be specified only for integers. I suppose it works with any objects that have comparison operators, but it doesn't specify what comparison operators it needs. </p>
<p>Besides, <code>heapq</code> seems to be implemented in Python, so it's not fast.</p>
<p>Are you aware of any fast implementations for priority queues in Python ? Optimally, I'd like the queue to be generic (i.e. work well for any object with a specified comparison operator).</p>
<p>Thanks in advance</p>
<p><strong>Update:</strong></p>
<p>Re comparison in <code>heapq</code>, I can either use a <code>(priority, object)</code> as Charlie Martin suggests, or just implement <code>__cmp__</code> for my object. </p>
<p>I'm still looking for something faster than <code>heapq</code>.</p>
| 33 | 2009-01-02T19:05:54Z | 7,736,473 | <p>You can use heapq for non-integer elements (tuples)</p>
<pre><code>from heapq import *
heap = []
data = [(10,"ten"), (3,"three"), (5,"five"), (7,"seven"), (9, "nine"), (2,"two")]
for item in data:
heappush(heap, item)
sorted = []
while heap:
sorted.append(heappop(heap))
print sorted
data.sort()
print data == sorted
</code></pre>
| 5 | 2011-10-12T07:11:32Z | [
"python",
"queue"
] |
A generic priority queue for Python | 407,734 | <p>I need to use a priority queue in my Python code. Looking around for something efficient, I came upon <a href="http://docs.python.org/library/heapq.html">heapq</a>. It looks good, but seems to be specified only for integers. I suppose it works with any objects that have comparison operators, but it doesn't specify what comparison operators it needs. </p>
<p>Besides, <code>heapq</code> seems to be implemented in Python, so it's not fast.</p>
<p>Are you aware of any fast implementations for priority queues in Python ? Optimally, I'd like the queue to be generic (i.e. work well for any object with a specified comparison operator).</p>
<p>Thanks in advance</p>
<p><strong>Update:</strong></p>
<p>Re comparison in <code>heapq</code>, I can either use a <code>(priority, object)</code> as Charlie Martin suggests, or just implement <code>__cmp__</code> for my object. </p>
<p>I'm still looking for something faster than <code>heapq</code>.</p>
| 33 | 2009-01-02T19:05:54Z | 9,967,786 | <p>This is efficient and works for strings or any type input as well -:)</p>
<pre><code>pq = [] # list of entries arranged in a heap
entry_finder = {} # mapping of tasks to entries
REMOVED = '<removed-task>' # placeholder for a removed task
counter = itertools.count() # unique sequence count
def add_task(task, priority=0):
'Add a new task or update the priority of an existing task'
if task in entry_finder:
remove_task(task)
count = next(counter)
entry = [priority, count, task]
entry_finder[task] = entry
heappush(pq, entry)
def remove_task(task):
'Mark an existing task as REMOVED. Raise KeyError if not found.'
entry = entry_finder.pop(task)
entry[-1] = REMOVED
def pop_task():
'Remove and return the lowest priority task. Raise KeyError if empty.'
while pq:
priority, count, task = heappop(pq)
if task is not REMOVED:
del entry_finder[task]
return task
raise KeyError('pop from an empty priority queue')
</code></pre>
<p><strong>Reference:</strong>
<a href="http://docs.python.org/library/heapq.html" rel="nofollow">http://docs.python.org/library/heapq.html</a></p>
| 1 | 2012-04-01T19:57:11Z | [
"python",
"queue"
] |
A generic priority queue for Python | 407,734 | <p>I need to use a priority queue in my Python code. Looking around for something efficient, I came upon <a href="http://docs.python.org/library/heapq.html">heapq</a>. It looks good, but seems to be specified only for integers. I suppose it works with any objects that have comparison operators, but it doesn't specify what comparison operators it needs. </p>
<p>Besides, <code>heapq</code> seems to be implemented in Python, so it's not fast.</p>
<p>Are you aware of any fast implementations for priority queues in Python ? Optimally, I'd like the queue to be generic (i.e. work well for any object with a specified comparison operator).</p>
<p>Thanks in advance</p>
<p><strong>Update:</strong></p>
<p>Re comparison in <code>heapq</code>, I can either use a <code>(priority, object)</code> as Charlie Martin suggests, or just implement <code>__cmp__</code> for my object. </p>
<p>I'm still looking for something faster than <code>heapq</code>.</p>
| 33 | 2009-01-02T19:05:54Z | 26,786,269 | <p>I've got a priority queue / fibonacci heap at <a href="https://pypi.python.org/pypi/fibonacci-heap-mod" rel="nofollow">https://pypi.python.org/pypi/fibonacci-heap-mod</a></p>
<p>It's not fast (large constant c on delete-min, which is O(c*logn)). But find-min, insert, decrease-key and merge are all O(1) - IOW, it's lazy.</p>
<p>If it's too slow on CPython, you might try Pypy, Nuitka or even CPython+Numba :)</p>
| 1 | 2014-11-06T18:01:32Z | [
"python",
"queue"
] |
A generic priority queue for Python | 407,734 | <p>I need to use a priority queue in my Python code. Looking around for something efficient, I came upon <a href="http://docs.python.org/library/heapq.html">heapq</a>. It looks good, but seems to be specified only for integers. I suppose it works with any objects that have comparison operators, but it doesn't specify what comparison operators it needs. </p>
<p>Besides, <code>heapq</code> seems to be implemented in Python, so it's not fast.</p>
<p>Are you aware of any fast implementations for priority queues in Python ? Optimally, I'd like the queue to be generic (i.e. work well for any object with a specified comparison operator).</p>
<p>Thanks in advance</p>
<p><strong>Update:</strong></p>
<p>Re comparison in <code>heapq</code>, I can either use a <code>(priority, object)</code> as Charlie Martin suggests, or just implement <code>__cmp__</code> for my object. </p>
<p>I'm still looking for something faster than <code>heapq</code>.</p>
| 33 | 2009-01-02T19:05:54Z | 34,863,948 | <blockquote>
<p>I can either use a <code>(priority, object)</code> as Charlie Martin suggests, or just implement <code>__cmp__</code> for my object.</p>
</blockquote>
<p>If you want inserted objects to be prioritized by a specific rule, I found it very helpful to write a simple subclass of <code>PriorityQueue</code> which accepts a key-function. You won't have to insert <code>(priority, object)</code> tuples manually and the handling feels more natural.</p>
<p><strong>Demo of the desired behavior</strong>:</p>
<pre><code>>>> h = KeyHeap(sum)
>>> h.put([-1,1])
>>> h.put((-1,-2,-3))
>>> h.put({100})
>>> h.put([1,2,3])
>>> h.get()
(-1, -2, -3)
>>> h.get()
[-1, 1]
>>> h.get()
[1, 2, 3]
>>> h.get()
set([100])
>>> h.empty()
True
>>>
>>> k = KeyHeap(len)
>>> k.put('hello')
>>> k.put('stackoverflow')
>>> k.put('!')
>>> k.get()
'!'
>>> k.get()
'hello'
>>> k.get()
'stackoverflow'
</code></pre>
<p><strong>Python 2 code</strong></p>
<pre><code>from Queue import PriorityQueue
class KeyHeap(PriorityQueue):
def __init__(self, key, maxsize=0):
PriorityQueue.__init__(self, maxsize)
self.key = key
def put(self, x):
PriorityQueue.put(self, (self.key(x), x))
def get(self):
return PriorityQueue.get(self)[1]
</code></pre>
<p><strong>Python 3 code</strong></p>
<pre><code>from queue import PriorityQueue
class KeyHeap(PriorityQueue):
def __init__(self, key, maxsize=0):
super().__init__(maxsize)
self.key = key
def put(self, x):
super().put((self.key(x), x))
def get(self):
return super().get()[1]
</code></pre>
<p>Obviously, calling <code>put</code> will (and should!) raise an error if you try to insert an object which your key-function cannot process.</p>
| 0 | 2016-01-18T20:57:50Z | [
"python",
"queue"
] |
A generic priority queue for Python | 407,734 | <p>I need to use a priority queue in my Python code. Looking around for something efficient, I came upon <a href="http://docs.python.org/library/heapq.html">heapq</a>. It looks good, but seems to be specified only for integers. I suppose it works with any objects that have comparison operators, but it doesn't specify what comparison operators it needs. </p>
<p>Besides, <code>heapq</code> seems to be implemented in Python, so it's not fast.</p>
<p>Are you aware of any fast implementations for priority queues in Python ? Optimally, I'd like the queue to be generic (i.e. work well for any object with a specified comparison operator).</p>
<p>Thanks in advance</p>
<p><strong>Update:</strong></p>
<p>Re comparison in <code>heapq</code>, I can either use a <code>(priority, object)</code> as Charlie Martin suggests, or just implement <code>__cmp__</code> for my object. </p>
<p>I'm still looking for something faster than <code>heapq</code>.</p>
| 33 | 2009-01-02T19:05:54Z | 37,008,050 | <p>Another option for a priority queue which also supports decrease-key operation is <a href="https://github.com/DanielStutzbach/heapdict" rel="nofollow">this</a> implementation by Daniel Stutzbach worked perfectly for me with Python 3.5.</p>
<pre><code>from heapdict import heapdict
hd = heapdict()
hd["two"] = 2
hd["one"] = 1
obj = hd.popitem()
print("object:",obj[0])
print("priority:",obj[1])
# object: one
# priority: 1
</code></pre>
| -1 | 2016-05-03T15:18:23Z | [
"python",
"queue"
] |
Prevent Python subprocess from passing fds on Windows? | 408,039 | <p>Python's subprocess module by default passes all open file descriptors to any child processes it spawns. This means that if the parent process is listening on a port, and is killed, it cannot restart and begin listening again (even using SO_REUSEADDR) because the child is still in possession of that descriptor. I have no control over the child process.</p>
<p>The subprocess POpen constructor does accept a close_fds argument, which would close descriptors on the child, just as I want. However, there is a restriction, only on Windows, that prevents it from being used if stdin/stdout are also overridden, which I need to do.</p>
<p>Does anyone know of a work-around for this on Windows?</p>
| 1 | 2009-01-02T21:08:42Z | 408,049 | <p>I don't have a windows box around, so this is untested, but I'd be tempted to try the os.dup and os.dup2 methods; duplicate the file descriptors and use those instead of the parent ones.</p>
| -2 | 2009-01-02T21:15:14Z | [
"python",
"windows",
"subprocess",
"popen"
] |
Prevent Python subprocess from passing fds on Windows? | 408,039 | <p>Python's subprocess module by default passes all open file descriptors to any child processes it spawns. This means that if the parent process is listening on a port, and is killed, it cannot restart and begin listening again (even using SO_REUSEADDR) because the child is still in possession of that descriptor. I have no control over the child process.</p>
<p>The subprocess POpen constructor does accept a close_fds argument, which would close descriptors on the child, just as I want. However, there is a restriction, only on Windows, that prevents it from being used if stdin/stdout are also overridden, which I need to do.</p>
<p>Does anyone know of a work-around for this on Windows?</p>
| 1 | 2009-01-02T21:08:42Z | 408,270 | <p>What seems to be the most relevant information that I can find: <a href="http://msdn.microsoft.com/en-us/library/ms724935%28VS.85%29.aspx" rel="nofollow">SetHandleInformation</a>, referenced in <a href="http://msdn.microsoft.com/en-us/library/ms682499%28VS.85%29.aspx" rel="nofollow">this</a> article, should give you pointers.</p>
<p>You'll probably need to use pywin32 and/or ctypes to accomplish what you want.</p>
| 2 | 2009-01-02T23:11:48Z | [
"python",
"windows",
"subprocess",
"popen"
] |
Python Outlook 2007 COM primer | 408,046 | <p>I've been inspired by <a href="http://stackoverflow.com/questions/405724/modifying-microsoft-outlook-contacts-from-python">Modifying Microsoft Outlook contacts from Python</a> -- I'm looking to try scripting some of my more annoying Outlook uses with the <code>win32com</code> package. I'm a Linux user trapped in a Windows users' cubicle, so I don't know much about COM.</p>
<p>I'm looking for information on whether COM allows for reflection via <code>win32com</code> or whether there's documentation on the Outlook 2007 COM objects. Any other pointers that you think will be helpful are welcome!</p>
<p>I've found <a href="http://wiki.exchange4linux.org/e4lwiki/n-h.support.wiki/uploads/programming_outlook_with_python.pdf">Programming Outlook With Python</a>, but I'm using Outlook 2007 so I'd like some more information on how much of the Outlook 2000 information is still applicable.</p>
<p>TIA!</p>
| 8 | 2009-01-02T21:12:50Z | 408,073 | <p>To answer your question about documentation. Here are two links that I regularly visit when developing Outlook macros. While the sites are primarily focused on development with MS technologies most of the code can be pretty easily translated to python once you understand how to use COM.</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/bb176619.aspx">http://msdn.microsoft.com/en-us/library/bb176619.aspx</a>][1]</li>
<li><a href="http://www.outlookcode.com/">http://www.outlookcode.com/</a></li>
<li>Deal Outlook Security <a href="http://www.outlookcode.com/article.aspx?ID=52">http://www.outlookcode.com/article.aspx?ID=52</a></li>
<li>Redemption <a href="http://www.dimastr.com/redemption/">http://www.dimastr.com/redemption/</a></li>
</ul>
| 6 | 2009-01-02T21:26:31Z | [
"python",
"com",
"outlook",
"outlook-2007"
] |
Python Outlook 2007 COM primer | 408,046 | <p>I've been inspired by <a href="http://stackoverflow.com/questions/405724/modifying-microsoft-outlook-contacts-from-python">Modifying Microsoft Outlook contacts from Python</a> -- I'm looking to try scripting some of my more annoying Outlook uses with the <code>win32com</code> package. I'm a Linux user trapped in a Windows users' cubicle, so I don't know much about COM.</p>
<p>I'm looking for information on whether COM allows for reflection via <code>win32com</code> or whether there's documentation on the Outlook 2007 COM objects. Any other pointers that you think will be helpful are welcome!</p>
<p>I've found <a href="http://wiki.exchange4linux.org/e4lwiki/n-h.support.wiki/uploads/programming_outlook_with_python.pdf">Programming Outlook With Python</a>, but I'm using Outlook 2007 so I'd like some more information on how much of the Outlook 2000 information is still applicable.</p>
<p>TIA!</p>
| 8 | 2009-01-02T21:12:50Z | 408,117 | <p>In general, older references to the object model are probably still valid given the attention Microsoft pays to backwards-compatability.</p>
<p>As for whether or not you will be able to use win32com in python for Outlook, yes, you should be able to use that to make late-bound calls to the Outlook object model. Here is a page that describes how to do it with Excel:</p>
<p><a href="http://oreilly.com/catalog/pythonwin32/chapter/ch12.html">http://oreilly.com/catalog/pythonwin32/chapter/ch12.html</a></p>
<p>A problem that you should be made aware of is the fact that Outlook has a security dialog that is thrown up when external programs try to access the object model and perform operations in outlook. You are <em>not</em> going to be able to suppress this dialog.</p>
<p>If you want to avoid the dialog, you are better off creating macros in VBA for Outlook that are loaded in a session, and put buttons on a new CommandBar to execute them.</p>
| 6 | 2009-01-02T21:50:56Z | [
"python",
"com",
"outlook",
"outlook-2007"
] |
Python Outlook 2007 COM primer | 408,046 | <p>I've been inspired by <a href="http://stackoverflow.com/questions/405724/modifying-microsoft-outlook-contacts-from-python">Modifying Microsoft Outlook contacts from Python</a> -- I'm looking to try scripting some of my more annoying Outlook uses with the <code>win32com</code> package. I'm a Linux user trapped in a Windows users' cubicle, so I don't know much about COM.</p>
<p>I'm looking for information on whether COM allows for reflection via <code>win32com</code> or whether there's documentation on the Outlook 2007 COM objects. Any other pointers that you think will be helpful are welcome!</p>
<p>I've found <a href="http://wiki.exchange4linux.org/e4lwiki/n-h.support.wiki/uploads/programming_outlook_with_python.pdf">Programming Outlook With Python</a>, but I'm using Outlook 2007 so I'd like some more information on how much of the Outlook 2000 information is still applicable.</p>
<p>TIA!</p>
| 8 | 2009-01-02T21:12:50Z | 9,816,622 | <p>This was my implementation from a couple years ago. I used it to automate the receiving and sending of email. Not sure if this will work with 2010. It depends on Redemption as well.</p>
<pre><code>import win32com.client,os,re
from utils.autoencode import autoencode
generated='2D5E2D34-BED5-4B9F-9793-A31E26E6806Ex0x4x7.py'
mapi_utils=win32com.client.Dispatch('Redemption.MAPIUtils')
olFolderDeletedItems=3
olFolderOutbox=4
olFolderSentItems=5
olFolderInbox=6
olFolderCalendar=9
olFolderContacts=10
olFolderJournal=11
olFolderNotes=12
olFolderTasks=13
class Attachment:
def __init__(self,CreationTime,attachement):
self.CreationTime=CreationTime
self.attachement=attachement
self.FileName=attachement.FileName
self.FileSize=attachement.FileSize
self.text=self.attachement.AsText
def Save(self,folder,filename=None,group=True):
if group:
folderGroup=re.sub('\\W','',str(self.CreationTime))
subfolder=os.path.join(folder,folderGroup)
if not os.path.isdir(subfolder):
os.mkdir(subfolder)
else:
folderGroup=''
if filename:
path=os.path.join(folder,folderGroup,filename)
else:
path=os.path.join(folder,folderGroup,self.FileName)
if os.path.isdir(folder):
self.attachement.SaveAsFile(path.replace('/','\\'))
return path
class Attachments:
def __init__(self,CreationTime,Attachments):
self.CreationTime=CreationTime
self.Attachments=Attachments
def __iter__(self):
return self.next()
def next(self):
for idx in range(self.Attachments.Count):
idx+=1
yield Attachment(self.CreationTime,self.Attachments.Item(idx))
class Message:
def __init__(self,store,folder,msg):
self.store=store
self.folder=folder
self.msg=msg
self.Attachments=Attachments(self.msg.CreationTime,msg.Attachments)
self.body=msg.Body
self.body_format=msg.BodyFormat
self.html=msg.HTMLBody
self.subject=msg.Subject
self.unread=msg.UnRead
self.id=msg.EntryID
def __str__(self):
return str('%s-%s-%s'%(self.store.Name,self.folder, self.msg))
def read(self,bool=True):
status=bool==False
self.msg.UnRead=status
class Inbox:
def __init__(self,session,store,folder,wantedFolder=None):
self.session=session
self.store=store
self.folder=folder
self.wantedFolder=wantedFolder
self.Name=folder.Name
def __getitem__(self,name):
self.wantedFolder=name
return self.next()
def __str__(self):
return '%s-%s'%(self.store.Name,self.Name)
def __iter__(self):
return self.next()
def subFolder(self,name):
self.wantedFolder=name
return self.next()
def next(self):
if self.wantedFolder:
subFolders=self.folder.Folders
for idx in range(subFolders.Count):
idx+=1
subfolder=subFolders.Item(idx)
if subfolder.Name==self.wantedFolder:
for msg in subfolder.Items:
yield Message(self.store,self.folder,msg)
else:
for msg in self.folder.Items:
yield Message(self.store,self.folder,msg)
class Store:
def __init__(self,session,store):
self.session=session
self.store=store
self.Name=store.Name
self.Inbox=Inbox(self.session,self.store,self.session.GetDefaultFolder(olFolderInbox))
def __str__(self):
return self.Name
def __iter__(self):
return self.next()
def next(self,folder=None):
pass
class rdo:
def __init__(self):
'''Outlook Redemption RDO wrapper'''
self.session = win32com.client.gencache.EnsureDispatch("Redemption.RDOSession")
self.session.Logon()
self.stores={}
for store in self.session.Stores:
self.stores[store.Name]=Store(self.session,store)
self.default_store=self.session.Stores.DefaultStore.Name
def __getitem__(self,name):
if self.stores.has_key(name):
return self.stores[name]
def __iter__(self):
return self.next()
def next(self):
stores=self.stores.keys()
yield self.stores[stores.pop(stores.index(self.default_store))]
for store in stores:
yield self.stores[store]
def getStore(self,name):
if self.stores.has_key(name):
return self.stores[name]
else:
return False
def getSharedMailbox(self,name):
try:
return Store(self.session,self.session.GetSharedMailbox(name))
except Exception,e:
if 'Could not resolve in GAL' in e.args[2][2]:
raise Exception('Mailbox could not be found')
else:
raise Exception ('Unknown error: %s'%e.args[2][2])
if __name__=='__main__':
r=rdo()
inbox = r.getStore('Mailbox - Foo').Inbox
for msg in inbox.subFolder('test'):
print msg.subject,msg.id
</code></pre>
| 1 | 2012-03-22T04:52:47Z | [
"python",
"com",
"outlook",
"outlook-2007"
] |
In Windows, how can I enumerate and get text from another window's controls? | 408,334 | <p>More particularly - I have a window handle of another running application. This application contains a <code>TListControl.UnicodeClass</code> control somewhere (I know this from Winspector). How can I, using the Windows API and that window handle, go through all the items in that list control and get the text from all of the items?</p>
<p>You can assume the language is C/C++, though I'll actually be using win32all for python. References to the appropriate API calls would be great.</p>
| 1 | 2009-01-02T23:49:34Z | 408,386 | <p>You want EnumWindows and EnumChildWindows for the enumeration. See <a href="http://support.microsoft.com/kb/183009" rel="nofollow">here</a> for examples and usage info/warnings.</p>
<p>For window text, once you have the appropriate HWND, you want <a href="http://msdn.microsoft.com/en-us/library/ms633520(VS.85).aspx" rel="nofollow">GetWindowText</a> in general, and control-specific API's if the text is stored in a different place (eg: list controls). For the specific control, you will need to know the specific API, and it may not be available though just Windows API calls (for example, controls with owner-draw items can store their text in the app, not accessible to Windows).</p>
| 4 | 2009-01-03T00:27:24Z | [
"python",
"windows",
"winapi",
"controls"
] |
In Windows, how can I enumerate and get text from another window's controls? | 408,334 | <p>More particularly - I have a window handle of another running application. This application contains a <code>TListControl.UnicodeClass</code> control somewhere (I know this from Winspector). How can I, using the Windows API and that window handle, go through all the items in that list control and get the text from all of the items?</p>
<p>You can assume the language is C/C++, though I'll actually be using win32all for python. References to the appropriate API calls would be great.</p>
| 1 | 2009-01-02T23:49:34Z | 409,110 | <p>Above answers are completely wrong and don't even know what is a PAS.
This has been answered hundreds of times for 20 years on Usenet.
You must use IPC of course (RPM)</p>
<p>ask on news://comp.os.ms-windows.programmer.win32 for code.</p>
| 2 | 2009-01-03T14:37:35Z | [
"python",
"windows",
"winapi",
"controls"
] |
How to produce a 303 Http Response in Django? | 408,541 | <p>Last couple of days we were discussing at <a href="http://stackoverflow.com/questions/401191/how-to-return-random-items-restfully">another question</a> the best to manage randomness in a RESTful way; today I went to play a little bit with some ideas in Django only to find that there is no easy standard way of returning a 303 response (nor a 300 one, btw), that is, there doesn't seem to exist an HttpResponseSeeOther inside django.HTTP or in another place. </p>
<p>Do you know any means for achieving this?</p>
| 17 | 2009-01-03T03:20:07Z | 408,549 | <p>You could just override HttpResponse, like the other Responses do:</p>
<pre><code>class HttpResponseSeeOther(HttpResponseRedirect):
status_code = 303
return HttpResponseSeeOther('/other-url/')
</code></pre>
| 23 | 2009-01-03T03:25:12Z | [
"python",
"django",
"http",
"rest"
] |
How to produce a 303 Http Response in Django? | 408,541 | <p>Last couple of days we were discussing at <a href="http://stackoverflow.com/questions/401191/how-to-return-random-items-restfully">another question</a> the best to manage randomness in a RESTful way; today I went to play a little bit with some ideas in Django only to find that there is no easy standard way of returning a 303 response (nor a 300 one, btw), that is, there doesn't seem to exist an HttpResponseSeeOther inside django.HTTP or in another place. </p>
<p>Do you know any means for achieving this?</p>
| 17 | 2009-01-03T03:20:07Z | 408,572 | <p>The generic HttpResponse object lets you specify any status code you want:</p>
<pre><code>response = HttpResponse(content="", status=303)
response["Location"] = "http://example.com/redirect/here/"
</code></pre>
<p>If you need something re-usable then Gerald's answer is definitely valid; simply create your own HttpResponseSeeOther class. Django only provides these specific classes for a few of the most common status codes.</p>
| 19 | 2009-01-03T03:54:35Z | [
"python",
"django",
"http",
"rest"
] |
Convert CVS/SVN to a Programming Snippets Site | 408,621 | <p>I use cvs to maintain all my python snippets, notes, c, c++ code. As the hosting provider provides a public web- server also, I was thinking that I should convert the cvs automatically to a programming snippets website. </p>
<ol>
<li><a href="http://www.freebsd.org/projects/cvsweb.html" rel="nofollow">cvsweb</a> is not what I mean.</li>
<li><a href="http://www.doxygen.org" rel="nofollow">doxygen</a> is for a complete project and to browse the self-referencing codes online.I think doxygen is more like web based ctags.</li>
</ol>
<p>I tried with <a href="http://www.voidspace.org.uk/python/rest2web/" rel="nofollow">rest2web</a>, it is requires that I write /restweb headers and files to be .txt files and it will interfere with the programming language syntax.</p>
<p>An approach I have thought is:
1) run source-hightlight and create .html pages for all the scripts.
2) now write a script to index those script .htmls and create webpage.
3) Create the website of those pages.</p>
<p>before proceeding, I thought I shall discuss here, if the members have any suggestion.
What do do, when you want to maintain your snippets and notes in cvs and also auto generate it into a good website. I like rest2web for converting notes to html.</p>
| 2 | 2009-01-03T04:53:31Z | 408,644 | <p>Run <a href="http://trac.edgewall.org/" rel="nofollow">Trac</a> on the server linked to the (svn) repository. The Trac wiki can conveniently refer to files and changesets. You get TODO tickets, too.</p>
| 3 | 2009-01-03T05:14:15Z | [
"python",
"svn",
"web-applications",
"rest",
"cvs"
] |
Convert CVS/SVN to a Programming Snippets Site | 408,621 | <p>I use cvs to maintain all my python snippets, notes, c, c++ code. As the hosting provider provides a public web- server also, I was thinking that I should convert the cvs automatically to a programming snippets website. </p>
<ol>
<li><a href="http://www.freebsd.org/projects/cvsweb.html" rel="nofollow">cvsweb</a> is not what I mean.</li>
<li><a href="http://www.doxygen.org" rel="nofollow">doxygen</a> is for a complete project and to browse the self-referencing codes online.I think doxygen is more like web based ctags.</li>
</ol>
<p>I tried with <a href="http://www.voidspace.org.uk/python/rest2web/" rel="nofollow">rest2web</a>, it is requires that I write /restweb headers and files to be .txt files and it will interfere with the programming language syntax.</p>
<p>An approach I have thought is:
1) run source-hightlight and create .html pages for all the scripts.
2) now write a script to index those script .htmls and create webpage.
3) Create the website of those pages.</p>
<p>before proceeding, I thought I shall discuss here, if the members have any suggestion.
What do do, when you want to maintain your snippets and notes in cvs and also auto generate it into a good website. I like rest2web for converting notes to html.</p>
| 2 | 2009-01-03T04:53:31Z | 408,662 | <p>enscript or pygmentize (part of pygments) can be used to convert code to HTML. You can use a custom header or footer to link to the actual code for download.</p>
| 1 | 2009-01-03T05:32:58Z | [
"python",
"svn",
"web-applications",
"rest",
"cvs"
] |
Convert CVS/SVN to a Programming Snippets Site | 408,621 | <p>I use cvs to maintain all my python snippets, notes, c, c++ code. As the hosting provider provides a public web- server also, I was thinking that I should convert the cvs automatically to a programming snippets website. </p>
<ol>
<li><a href="http://www.freebsd.org/projects/cvsweb.html" rel="nofollow">cvsweb</a> is not what I mean.</li>
<li><a href="http://www.doxygen.org" rel="nofollow">doxygen</a> is for a complete project and to browse the self-referencing codes online.I think doxygen is more like web based ctags.</li>
</ol>
<p>I tried with <a href="http://www.voidspace.org.uk/python/rest2web/" rel="nofollow">rest2web</a>, it is requires that I write /restweb headers and files to be .txt files and it will interfere with the programming language syntax.</p>
<p>An approach I have thought is:
1) run source-hightlight and create .html pages for all the scripts.
2) now write a script to index those script .htmls and create webpage.
3) Create the website of those pages.</p>
<p>before proceeding, I thought I shall discuss here, if the members have any suggestion.
What do do, when you want to maintain your snippets and notes in cvs and also auto generate it into a good website. I like rest2web for converting notes to html.</p>
| 2 | 2009-01-03T04:53:31Z | 430,829 | <p>I finally settled for <a href="http://www.voidspace.org.uk/python/rest2web/" rel="nofollow">rest2web</a>. I had to do the following. </p>
<ol>
<li>Use a separate python script to recursively copy the files in the CVS to a separate directory.</li>
<li>Added extra files index.txt and template.txt to all the directories which I wanted to be in the webpage.</li>
<li>The <strong>best thing</strong> about rest2web is that it supports python scripting within the template.txt, so I just ran a loop of the contents and indexed them in the page.</li>
<li>There is still lot more to go to automate the entire process. For eg. Inline viewing of programs and colorization, which I think can be done with some more trials.</li>
</ol>
<p>I have the completed website here, It is called <a href="http://uthcode.sarovar.org" rel="nofollow">uthcode</a>.</p>
| 0 | 2009-01-10T10:22:30Z | [
"python",
"svn",
"web-applications",
"rest",
"cvs"
] |
Catch MainLoop exceptions and displaying them in MessageDialogs | 408,810 | <p>I have a wxPython application that relies on an external config file. I want provide friendly message dialogs that show up if there are any config errors. I've tried to make this work by wrapping my app.MainLoop() call in a try/except statement.</p>
<p>The code below works for the init code in my MainWindow frame class, but doesn't catch any exceptions that occur within the MainLoop. How can I catch these exceptions as well?</p>
<pre><code>if __name__ == '__main__':
app = MyApp(0)
try:
MainWindow(None, -1, 'My Cool App')
app.MainLoop()
except ConfigParser.Error, error_message:
messagebox = wx.MessageDialog(None, error_message, 'Configuration Error', wx.OK | wx.ICON_ERROR)
messagebox.ShowModal()
</code></pre>
<p>I've read some mention of an OnExceptionInMainLoop method that can be overridden in the wx.App class, but the source I read must be out of date (2004) since wx.App no longer seems to have a method by that name.</p>
<p><strong>EDIT:</strong></p>
<p>I need to be able to catch unhandled exceptions during my mainloop so that I can further handle them and display them in error dialogs, not pass silently, and not terminate the app.</p>
<p>The sys.excepthook solution is too low level and doesn't play nice with the wxPython mainloop thread. While the link to the other answer does the same try/except wrapping around the mainloop which doesn't work due, once again, to wxPython spawning a different thread for the app/ui.</p>
| 1 | 2009-01-03T09:22:50Z | 409,266 | <p>Don't know if this will work for a wxPython application, but in the sys module you can overwrite the excepthook attribute, which is a function called with 3 arguments, <code>(type, value, traceback)</code>, when an uncaugth exception is caught. You can install your own function in there that handles only the exceptions you want, and call the original function for all the others.</p>
<p>Consult: <a href="http://docs.python.org/library/sys.html#sys.excepthook" rel="nofollow" title="sys module">http://docs.python.org/library/sys.html#sys.excepthook</a></p>
| 2 | 2009-01-03T16:04:33Z | [
"python",
"exception-handling",
"wxpython",
"wxwidgets"
] |
Catch MainLoop exceptions and displaying them in MessageDialogs | 408,810 | <p>I have a wxPython application that relies on an external config file. I want provide friendly message dialogs that show up if there are any config errors. I've tried to make this work by wrapping my app.MainLoop() call in a try/except statement.</p>
<p>The code below works for the init code in my MainWindow frame class, but doesn't catch any exceptions that occur within the MainLoop. How can I catch these exceptions as well?</p>
<pre><code>if __name__ == '__main__':
app = MyApp(0)
try:
MainWindow(None, -1, 'My Cool App')
app.MainLoop()
except ConfigParser.Error, error_message:
messagebox = wx.MessageDialog(None, error_message, 'Configuration Error', wx.OK | wx.ICON_ERROR)
messagebox.ShowModal()
</code></pre>
<p>I've read some mention of an OnExceptionInMainLoop method that can be overridden in the wx.App class, but the source I read must be out of date (2004) since wx.App no longer seems to have a method by that name.</p>
<p><strong>EDIT:</strong></p>
<p>I need to be able to catch unhandled exceptions during my mainloop so that I can further handle them and display them in error dialogs, not pass silently, and not terminate the app.</p>
<p>The sys.excepthook solution is too low level and doesn't play nice with the wxPython mainloop thread. While the link to the other answer does the same try/except wrapping around the mainloop which doesn't work due, once again, to wxPython spawning a different thread for the app/ui.</p>
| 1 | 2009-01-03T09:22:50Z | 409,537 | <p>Perhaps <a href="http://stackoverflow.com/questions/166198/how-can-i-capture-all-exceptions-from-a-wxpython-application">this</a> question might be of some use, it tries to capture all exceptions.</p>
| 0 | 2009-01-03T18:24:54Z | [
"python",
"exception-handling",
"wxpython",
"wxwidgets"
] |
Catch MainLoop exceptions and displaying them in MessageDialogs | 408,810 | <p>I have a wxPython application that relies on an external config file. I want provide friendly message dialogs that show up if there are any config errors. I've tried to make this work by wrapping my app.MainLoop() call in a try/except statement.</p>
<p>The code below works for the init code in my MainWindow frame class, but doesn't catch any exceptions that occur within the MainLoop. How can I catch these exceptions as well?</p>
<pre><code>if __name__ == '__main__':
app = MyApp(0)
try:
MainWindow(None, -1, 'My Cool App')
app.MainLoop()
except ConfigParser.Error, error_message:
messagebox = wx.MessageDialog(None, error_message, 'Configuration Error', wx.OK | wx.ICON_ERROR)
messagebox.ShowModal()
</code></pre>
<p>I've read some mention of an OnExceptionInMainLoop method that can be overridden in the wx.App class, but the source I read must be out of date (2004) since wx.App no longer seems to have a method by that name.</p>
<p><strong>EDIT:</strong></p>
<p>I need to be able to catch unhandled exceptions during my mainloop so that I can further handle them and display them in error dialogs, not pass silently, and not terminate the app.</p>
<p>The sys.excepthook solution is too low level and doesn't play nice with the wxPython mainloop thread. While the link to the other answer does the same try/except wrapping around the mainloop which doesn't work due, once again, to wxPython spawning a different thread for the app/ui.</p>
| 1 | 2009-01-03T09:22:50Z | 517,555 | <p>I coded something like this for <a href="http://chandlerproject.org/" rel="nofollow">Chandler</a>, where any unhandled exceptions pop up a window with the stack and other info, and users can put in additional comments (what did they do when it happened etc.) and submit it for Chandler developers. A bit like the <a href="https://wiki.mozilla.org/QA/Talkback" rel="nofollow">Mozilla Talkback</a> (<a href="https://developer.mozilla.org/en/Crash_reporting" rel="nofollow">nowadays</a> they use Breakpad I believe) feature if you will.</p>
<p>To do this in wxPython, you need to provide redirect parameter to wx.App. This will pop up <a href="http://www.wxpython.org/docs/api/wx.PyOnDemandOutputWindow-class.html" rel="nofollow">wx.PyOnDemandOutputWindow</a> (you will probably want to override it to provide a nicer looking implementation).</p>
<p>The relevant source files in Chandler are here:</p>
<ul>
<li><a href="http://svn.osafoundation.org/chandler/trunk/chandler/Chandler.py" rel="nofollow">Chandler.py</a> starts the application and sets the redirect attribute, as well as tries to catch and display error dialogs in case normal application startup fails</li>
<li><a href="http://svn.osafoundation.org/chandler/trunk/chandler/application/Application.py" rel="nofollow">Application.py</a> customizes the application object, including setting up our customized wx.PyOnDemandOutputWindow </li>
<li><a href="http://svn.osafoundation.org/chandler/trunk/chandler/application/feedback.py" rel="nofollow">feedback.py</a> has the implementation for the customized wx.PyOnDemandOutputWindow; it will additionally need feedback.xrc and feedback_xrc.py</li>
</ul>
| 1 | 2009-02-05T19:36:01Z | [
"python",
"exception-handling",
"wxpython",
"wxwidgets"
] |
Catch MainLoop exceptions and displaying them in MessageDialogs | 408,810 | <p>I have a wxPython application that relies on an external config file. I want provide friendly message dialogs that show up if there are any config errors. I've tried to make this work by wrapping my app.MainLoop() call in a try/except statement.</p>
<p>The code below works for the init code in my MainWindow frame class, but doesn't catch any exceptions that occur within the MainLoop. How can I catch these exceptions as well?</p>
<pre><code>if __name__ == '__main__':
app = MyApp(0)
try:
MainWindow(None, -1, 'My Cool App')
app.MainLoop()
except ConfigParser.Error, error_message:
messagebox = wx.MessageDialog(None, error_message, 'Configuration Error', wx.OK | wx.ICON_ERROR)
messagebox.ShowModal()
</code></pre>
<p>I've read some mention of an OnExceptionInMainLoop method that can be overridden in the wx.App class, but the source I read must be out of date (2004) since wx.App no longer seems to have a method by that name.</p>
<p><strong>EDIT:</strong></p>
<p>I need to be able to catch unhandled exceptions during my mainloop so that I can further handle them and display them in error dialogs, not pass silently, and not terminate the app.</p>
<p>The sys.excepthook solution is too low level and doesn't play nice with the wxPython mainloop thread. While the link to the other answer does the same try/except wrapping around the mainloop which doesn't work due, once again, to wxPython spawning a different thread for the app/ui.</p>
| 1 | 2009-01-03T09:22:50Z | 12,109,646 | <p>Posting the solution that worked for me with a very similar problem.</p>
<pre><code>import wx
import sys
import traceback
class Frame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None)
panel = wx.Panel(self)
m_close = wx.Button(panel, -1, "Error")
m_close.Bind(wx.EVT_BUTTON, self.OnErr)
def OnErr(self, event):
1/0
def handleGUIException(exc_type, exc_value, exc_traceback):
err_msg = ''.join(traceback.format_exception(exc_type, exc_value, exc_traceback))
err_msg += '\n Your App will now terminate'
# Here collecting traceback and some log files to be sent for debugging.
# But also possible to handle the error and continue working.
dlg = wx.MessageDialog(None, err_msg, 'Termination dialog', wx.OK | wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
sys.exit()
sys.excepthook = handleGUIException
if __name__ == '__main__':
app = wx.App(redirect=False)
top = Frame()
top.Show()
app.MainLoop()
</code></pre>
| 0 | 2012-08-24T12:44:48Z | [
"python",
"exception-handling",
"wxpython",
"wxwidgets"
] |
How to compare and search list of integers efficiently? | 408,855 | <p>I have a database populated with 1 million objects. Each object has a 'tags' field - set of integers.</p>
<p>For example:</p>
<pre><code>object1: tags(1,3,4)
object2: tags(2)
object3: tags(3,4)
object4: tags(5)
</code></pre>
<p>and so on.</p>
<p>Query parameter is a set on integers, lets try q(3,4,5)</p>
<pre><code>object1 does not match ('1' not in '3,4,5')
object2 does not match ('2' not in '3,4,5')
object3 matches ('3 and 4' in '3,4,5' )
object4 matches ('5' in '3,4,5' )
</code></pre>
<p>How to select matched objects efficiently?</p>
| 4 | 2009-01-03T10:23:46Z | 408,864 | <p>You haven't stated weather you'd like to use SQL or if your reading the data into an application before doing so. From sounds of things your looking for a code based solution?</p>
<p>In .NET you would make a class implement the ICompare interface and write your own method to to compare two values that would either return a 0 or 1.</p>
| 0 | 2009-01-03T10:30:03Z | [
"python",
"postgresql"
] |
How to compare and search list of integers efficiently? | 408,855 | <p>I have a database populated with 1 million objects. Each object has a 'tags' field - set of integers.</p>
<p>For example:</p>
<pre><code>object1: tags(1,3,4)
object2: tags(2)
object3: tags(3,4)
object4: tags(5)
</code></pre>
<p>and so on.</p>
<p>Query parameter is a set on integers, lets try q(3,4,5)</p>
<pre><code>object1 does not match ('1' not in '3,4,5')
object2 does not match ('2' not in '3,4,5')
object3 matches ('3 and 4' in '3,4,5' )
object4 matches ('5' in '3,4,5' )
</code></pre>
<p>How to select matched objects efficiently?</p>
| 4 | 2009-01-03T10:23:46Z | 408,875 | <p>This is basic set theory. Intersect the two sets and if the result is the same as the original then the result is "match". Otherwise its not.</p>
<p>You can apply this principle using many languages. Most have libraries for doing things with sets. You can even do this using SQL.</p>
| 0 | 2009-01-03T10:44:04Z | [
"python",
"postgresql"
] |
How to compare and search list of integers efficiently? | 408,855 | <p>I have a database populated with 1 million objects. Each object has a 'tags' field - set of integers.</p>
<p>For example:</p>
<pre><code>object1: tags(1,3,4)
object2: tags(2)
object3: tags(3,4)
object4: tags(5)
</code></pre>
<p>and so on.</p>
<p>Query parameter is a set on integers, lets try q(3,4,5)</p>
<pre><code>object1 does not match ('1' not in '3,4,5')
object2 does not match ('2' not in '3,4,5')
object3 matches ('3 and 4' in '3,4,5' )
object4 matches ('5' in '3,4,5' )
</code></pre>
<p>How to select matched objects efficiently?</p>
| 4 | 2009-01-03T10:23:46Z | 408,893 | <p>Given that you are using PostgreSQL, you could use its <a href="http://www.postgresql.org/docs/8.2/static/functions-array.html" rel="nofollow">array</a> datatype and its contains/overlaps operators.</p>
<p>Of course this would tie your app to PostgreSQL tightly, which may not be desired. On the other hand, it may save you coding for when it's really needed (ie, when you finally have to port it to another database)</p>
<p>Although, given that in Python you have the <a href="http://docs.python.org/library/sets.html" rel="nofollow">set datatype</a> for that exact group of operations, using PostgreSQL might be overkill (depending on the performance requirements)</p>
<pre><code>>>> a = set([1,2,3])
>>> a
set([1, 2, 3])
>>> 1 in a
True
>>> set([1,2]) in a
False
>>> set([2,3]) & a
set([2, 3])
>>> set([8,9]) & a
set([])
>>> set([1,3]) & a
set([1, 3])
>>>
</code></pre>
| 3 | 2009-01-03T10:54:49Z | [
"python",
"postgresql"
] |
How to compare and search list of integers efficiently? | 408,855 | <p>I have a database populated with 1 million objects. Each object has a 'tags' field - set of integers.</p>
<p>For example:</p>
<pre><code>object1: tags(1,3,4)
object2: tags(2)
object3: tags(3,4)
object4: tags(5)
</code></pre>
<p>and so on.</p>
<p>Query parameter is a set on integers, lets try q(3,4,5)</p>
<pre><code>object1 does not match ('1' not in '3,4,5')
object2 does not match ('2' not in '3,4,5')
object3 matches ('3 and 4' in '3,4,5' )
object4 matches ('5' in '3,4,5' )
</code></pre>
<p>How to select matched objects efficiently?</p>
| 4 | 2009-01-03T10:23:46Z | 408,944 | <p>If I understood it right, its something like a:</p>
<p><code>Post-> posttags <-tags</code></p>
<p>kindof schema.</p>
<p>I wonder why are you doing it this way? </p>
<p>Is it a problem you have reached because you are using an ORM which retrieves data in objects and other lazy loaded associated objects.</p>
<p>Like a Post and Tag class in SQLAlchemy, with Post mapper having a property called 'tags' which can load set of Tag objects for given Post object.</p>
<p>If that's so, those kind of operations are usually very costly in ORM's and should be done with the SQL Statement support of ORM's or using the direct dbapi's like psycopg2.
Again, if the number of objects loaded from a query is huge (keeping in mind your 1Million) you need machine with lot of resources (or maybe None at all - <em>pure</em> ORM not recommended).</p>
<p>If its not an ORM and still your tags are stored like (sets) then I think there is something wrong with the schema.</p>
<p><code>posttags</code> is a many-to-many relationship as i see it and its a different table by itself (which is easily queriable), not a 'set' in posts table.</p>
| 1 | 2009-01-03T11:32:13Z | [
"python",
"postgresql"
] |
How to compare and search list of integers efficiently? | 408,855 | <p>I have a database populated with 1 million objects. Each object has a 'tags' field - set of integers.</p>
<p>For example:</p>
<pre><code>object1: tags(1,3,4)
object2: tags(2)
object3: tags(3,4)
object4: tags(5)
</code></pre>
<p>and so on.</p>
<p>Query parameter is a set on integers, lets try q(3,4,5)</p>
<pre><code>object1 does not match ('1' not in '3,4,5')
object2 does not match ('2' not in '3,4,5')
object3 matches ('3 and 4' in '3,4,5' )
object4 matches ('5' in '3,4,5' )
</code></pre>
<p>How to select matched objects efficiently?</p>
| 4 | 2009-01-03T10:23:46Z | 408,971 | <p>Looks to me like the <code>issubset()</code> method of <a href="http://docs.python.org/library/sets.html" rel="nofollow">sets</a> is what you are looking for:</p>
<pre><code>tags(1, 2, 3).issubset(q(1, 2, 3, 4))
</code></pre>
<p>If both <code>tags</code> and <code>q</code> are subclasses of the <code>set</code> class.
But I agree with the other answers that solving this in the database would be a better solution.</p>
| 0 | 2009-01-03T12:13:02Z | [
"python",
"postgresql"
] |
How to compare and search list of integers efficiently? | 408,855 | <p>I have a database populated with 1 million objects. Each object has a 'tags' field - set of integers.</p>
<p>For example:</p>
<pre><code>object1: tags(1,3,4)
object2: tags(2)
object3: tags(3,4)
object4: tags(5)
</code></pre>
<p>and so on.</p>
<p>Query parameter is a set on integers, lets try q(3,4,5)</p>
<pre><code>object1 does not match ('1' not in '3,4,5')
object2 does not match ('2' not in '3,4,5')
object3 matches ('3 and 4' in '3,4,5' )
object4 matches ('5' in '3,4,5' )
</code></pre>
<p>How to select matched objects efficiently?</p>
| 4 | 2009-01-03T10:23:46Z | 409,607 | <p>You're making a common mistake in database design, by storing a comma-separated list of tag id's. It's not a surprise that performing efficient queries against this is a blocker for you.</p>
<p>What you need is to model the mapping between objects and tags in a separate table.</p>
<pre><code>CREATE TABLE Tagged (
object_id INT NOT NULL,
tag_id INT NOT NULL,
PRIMARY KEY (object_id, tag_id),
FOREIGN KEY (object_id) REFERENCES Objects(object_id),
FOREIGN KEY (tag_id) REFERENCES Tags(tag_id)
);
</code></pre>
<p>Insert one row for each object/tag pairing. Of course, this means you have several rows for each <code>object_id</code>, but that's okay.</p>
<p>You can query for all objects that have tags 3,4,5:</p>
<pre><code>SELECT DISTINCT object_id
FROM Tagged
WHERE tag_id IN (3, 4, 5);
</code></pre>
<p>But this matches object1, which you don't want. You want to exclude objects that have other tags not in 3,4,5.</p>
<pre><code>SELECT DISTINCT t1.object_id
FROM Tagged t1
LEFT OUTER JOIN Tagged t2
ON (t1.object_id = t2.object_id AND t2.tag_id NOT IN (3, 4, 5))
WHERE t1.tag_id IN (3, 4, 5)
AND t2.object_id IS NULL;
</code></pre>
| 3 | 2009-01-03T19:09:27Z | [
"python",
"postgresql"
] |
How to compare and search list of integers efficiently? | 408,855 | <p>I have a database populated with 1 million objects. Each object has a 'tags' field - set of integers.</p>
<p>For example:</p>
<pre><code>object1: tags(1,3,4)
object2: tags(2)
object3: tags(3,4)
object4: tags(5)
</code></pre>
<p>and so on.</p>
<p>Query parameter is a set on integers, lets try q(3,4,5)</p>
<pre><code>object1 does not match ('1' not in '3,4,5')
object2 does not match ('2' not in '3,4,5')
object3 matches ('3 and 4' in '3,4,5' )
object4 matches ('5' in '3,4,5' )
</code></pre>
<p>How to select matched objects efficiently?</p>
| 4 | 2009-01-03T10:23:46Z | 410,803 | <p>I'm sorry. Looks like it was hard to me to explain the problem well :)</p>
<p>The 'postgresql' tag here os lot more meaningful than 'python'.
Self joined TAG table with IS NULL condition is what I really need.</p>
<p>SQLalchemy is also good advise.</p>
<p>Thank you all.</p>
| 0 | 2009-01-04T10:35:55Z | [
"python",
"postgresql"
] |
Python human readable object serialization | 408,866 | <p>i need to store Python structures made of lists / dictionaries, tuples into a human readable format. The idea is like using something similar to <a href="http://docs.python.org/library/pickle.html">pickle</a>, but pickle is not human-friendly. Other options that come to my mind are <a href="http://en.wikipedia.org/wiki/Yaml">YAML</a> (through <a href="http://pyyaml.org/">PyYAML</a> and <a href="http://www.json.org/">JSON</a> (through <a href="http://pypi.python.org/pypi/simplejson/">simplejson</a>) serializers.</p>
<p>Any other option that comes to your mind?</p>
<p>Thanks in advance.</p>
| 15 | 2009-01-03T10:30:40Z | 408,889 | <p>For simple cases pprint() and eval() come to mind.</p>
<p>Using your example:</p>
<pre><code>>>> d = {'age': 27,
... 'name': 'Joe',
... 'numbers': [1,
... 2,
... 3,
... 4,
... 5],
... 'subdict': {
... 'first': 1,
... 'second': 2,
... 'third': 3
... }
... }
>>>
>>> from pprint import pprint
>>> pprint(d)
{'age': 27,
'name': 'Joe',
'numbers': [1, 2, 3, 4, 5],
'subdict': {'first': 1, 'second': 2, 'third': 3}}
>>>
</code></pre>
<p>I would think twice about fixing two requirements with the same tool. Have you considered using pickle for the serializing and then pprint() (or a more fancy object viewer) for humans looking at the objects?</p>
| 11 | 2009-01-03T10:52:05Z | [
"python",
"json",
"yaml",
"serialization",
"pickle"
] |
Python human readable object serialization | 408,866 | <p>i need to store Python structures made of lists / dictionaries, tuples into a human readable format. The idea is like using something similar to <a href="http://docs.python.org/library/pickle.html">pickle</a>, but pickle is not human-friendly. Other options that come to my mind are <a href="http://en.wikipedia.org/wiki/Yaml">YAML</a> (through <a href="http://pyyaml.org/">PyYAML</a> and <a href="http://www.json.org/">JSON</a> (through <a href="http://pypi.python.org/pypi/simplejson/">simplejson</a>) serializers.</p>
<p>Any other option that comes to your mind?</p>
<p>Thanks in advance.</p>
| 15 | 2009-01-03T10:30:40Z | 408,912 | <p>If its <strong>just</strong> Python list, dictionary and tuple object. - <strong>JSON</strong> is the way to go. Its human readable, very easy to handle and language independent too. </p>
<p>Caution: Tuples will be converted to lists in simplejson.</p>
<pre><code>In [109]: simplejson.loads(simplejson.dumps({'d':(12,3,4,4,5)}))
Out[109]: {u'd': [12, 3, 4, 4, 5]}
</code></pre>
| 12 | 2009-01-03T11:04:55Z | [
"python",
"json",
"yaml",
"serialization",
"pickle"
] |
Python human readable object serialization | 408,866 | <p>i need to store Python structures made of lists / dictionaries, tuples into a human readable format. The idea is like using something similar to <a href="http://docs.python.org/library/pickle.html">pickle</a>, but pickle is not human-friendly. Other options that come to my mind are <a href="http://en.wikipedia.org/wiki/Yaml">YAML</a> (through <a href="http://pyyaml.org/">PyYAML</a> and <a href="http://www.json.org/">JSON</a> (through <a href="http://pypi.python.org/pypi/simplejson/">simplejson</a>) serializers.</p>
<p>Any other option that comes to your mind?</p>
<p>Thanks in advance.</p>
| 15 | 2009-01-03T10:30:40Z | 408,915 | <p>To use simplejson first <strong>easy_install simplejson</strong>:</p>
<pre><code>import simplejson
my_structure = {"name":"Joe", "age":27, "numbers":[1,2,3,4,5], "subdict":{"first":1, "second":2, "third": 3}}
json = simplejson.dumps(my_structure)
</code></pre>
<p>results in json being:</p>
<pre><code>{"age": 27, "subdict": {"second": 2, "third": 3, "first": 1}, "name": "Joe", "numbers": [1, 2, 3, 4, 5]}
</code></pre>
<p>Notice that its hardly changed the format of the dictionary at all, but you should run it through this step to ensure valid JSON data.</p>
<p>You can further pretty print the result:</p>
<pre><code>import pprint
pprint.pprint(my_structure)
</code></pre>
<p>results in:</p>
<pre><code>{'age': 27,
'name': 'Joe',
'numbers': [1, 2, 3, 4, 5],
'subdict': {'first': 1, 'second': 2, 'third': 3}}
</code></pre>
| 2 | 2009-01-03T11:05:32Z | [
"python",
"json",
"yaml",
"serialization",
"pickle"
] |
Python human readable object serialization | 408,866 | <p>i need to store Python structures made of lists / dictionaries, tuples into a human readable format. The idea is like using something similar to <a href="http://docs.python.org/library/pickle.html">pickle</a>, but pickle is not human-friendly. Other options that come to my mind are <a href="http://en.wikipedia.org/wiki/Yaml">YAML</a> (through <a href="http://pyyaml.org/">PyYAML</a> and <a href="http://www.json.org/">JSON</a> (through <a href="http://pypi.python.org/pypi/simplejson/">simplejson</a>) serializers.</p>
<p>Any other option that comes to your mind?</p>
<p>Thanks in advance.</p>
| 15 | 2009-01-03T10:30:40Z | 415,152 | <p>If you're after more representations than are covered by JSON, I highly recommend checking out <a href="http://code.google.com/p/pyon/wiki/GettingStarted" rel="nofollow">PyON</a> (Python Object Notation)...although I believe it's restricted to 2.6/3.0 and above, as it relies on the <strong>ast</strong> module. It handles custom class instances and recursive data types, amongst other features, which is more than is provided by JSON.</p>
| 2 | 2009-01-06T01:50:05Z | [
"python",
"json",
"yaml",
"serialization",
"pickle"
] |
Python human readable object serialization | 408,866 | <p>i need to store Python structures made of lists / dictionaries, tuples into a human readable format. The idea is like using something similar to <a href="http://docs.python.org/library/pickle.html">pickle</a>, but pickle is not human-friendly. Other options that come to my mind are <a href="http://en.wikipedia.org/wiki/Yaml">YAML</a> (through <a href="http://pyyaml.org/">PyYAML</a> and <a href="http://www.json.org/">JSON</a> (through <a href="http://pypi.python.org/pypi/simplejson/">simplejson</a>) serializers.</p>
<p>Any other option that comes to your mind?</p>
<p>Thanks in advance.</p>
| 15 | 2009-01-03T10:30:40Z | 2,350,046 | <p>You should check out jsonpickle (http://code.google.com/p/jsonpickle/). It will write out any python object into a json file. You can then read that file back into a python object. The nice thing is the inbetween file is very readable because it's json.</p>
| 1 | 2010-02-28T04:05:10Z | [
"python",
"json",
"yaml",
"serialization",
"pickle"
] |
Python human readable object serialization | 408,866 | <p>i need to store Python structures made of lists / dictionaries, tuples into a human readable format. The idea is like using something similar to <a href="http://docs.python.org/library/pickle.html">pickle</a>, but pickle is not human-friendly. Other options that come to my mind are <a href="http://en.wikipedia.org/wiki/Yaml">YAML</a> (through <a href="http://pyyaml.org/">PyYAML</a> and <a href="http://www.json.org/">JSON</a> (through <a href="http://pypi.python.org/pypi/simplejson/">simplejson</a>) serializers.</p>
<p>Any other option that comes to your mind?</p>
<p>Thanks in advance.</p>
| 15 | 2009-01-03T10:30:40Z | 29,450,743 | <p>There is <a href="http://intellimath.bitbucket.org/axon" rel="nofollow">AXON</a> (textual) format that combine the <strong>best</strong> of JSON, XML and YAML.
AXON format is quite readable and relatively compact.</p>
<p>The python (2.7/3.3/3.4) module <a href="https://pypi.python.org/pypi/pyaxon" rel="nofollow">pyaxon</a> supports <code>load(s)</code>/<code>dump(s)</code> functionality, including iterative <code>loading</code>/<code>dumping</code>. It's sufficiently fast in order to be useful.</p>
<p>Consider simple example:</p>
<pre><code>>>> d = {
'age': 27, 'name': 'Joe',
'numbers': [1, 2, 3, 4, 5],
'subdict': {'first': 1, 'second': 2, 'third': 3}
}
# pretty form
>>> axon.dumps(d, pretty=1)
{ age: 27
name: "Joe"
numbers: [1 2 3 4 5]
subdict: {
first: 1
second: 2
third: 3}}
# compact form
>>> axon.dumps(d)
{age:27 name:"Joe" numbers:[1 2 3 4 5] subdict:{first:1 second:2 third:3}}
</code></pre>
<p>It also can handle multiple objects in the message:</p>
<pre><code>>>> msg = axon.dumps([{'a':1, 'b':2, 'c':3}, {'a':2, 'b':3, 'c':4}])
>>> print(msg)
{a:1 b:2 c:3}
{a:2 b:3 c:4}
{a:3 b:4 c:5}
</code></pre>
<p>and then load them iteratively:</p>
<pre><code>for d in axon.iloads(msg):
print(d)
</code></pre>
| -1 | 2015-04-04T19:46:32Z | [
"python",
"json",
"yaml",
"serialization",
"pickle"
] |
Python human readable object serialization | 408,866 | <p>i need to store Python structures made of lists / dictionaries, tuples into a human readable format. The idea is like using something similar to <a href="http://docs.python.org/library/pickle.html">pickle</a>, but pickle is not human-friendly. Other options that come to my mind are <a href="http://en.wikipedia.org/wiki/Yaml">YAML</a> (through <a href="http://pyyaml.org/">PyYAML</a> and <a href="http://www.json.org/">JSON</a> (through <a href="http://pypi.python.org/pypi/simplejson/">simplejson</a>) serializers.</p>
<p>Any other option that comes to your mind?</p>
<p>Thanks in advance.</p>
| 15 | 2009-01-03T10:30:40Z | 29,450,916 | <p>What do you mean this is not human-readable??? ;)</p>
<pre><code>>>> d = {'age': 27,
... 'name': 'Joe',
... 'numbers': [1,2,3,4,5],
... 'subdict': {'first':1, 'second':2, 'third':3}
... }
>>>
>>> import pickle
>>> p = pickle.dumps(d)
>>> p
"(dp0\nS'age'\np1\nI27\nsS'subdict'\np2\n(dp3\nS'second'\np4\nI2\nsS'third'\np5\nI3\nsS'first'\np6\nI1\nssS'name'\np7\nS'Joe'\np8\nsS'numbers'\np9\n(lp10\nI1\naI2\naI3\naI4\naI5\nas."
</code></pre>
<p>Ok, well, maybe it just takes some practice⦠or you could cheat...</p>
<pre><code>>>> import pickletools
>>> pickletools.dis(p)
0: ( MARK
1: d DICT (MARK at 0)
2: p PUT 0
5: S STRING 'age'
12: p PUT 1
15: I INT 27
19: s SETITEM
20: S STRING 'subdict'
31: p PUT 2
34: ( MARK
35: d DICT (MARK at 34)
36: p PUT 3
39: S STRING 'second'
49: p PUT 4
52: I INT 2
55: s SETITEM
56: S STRING 'third'
65: p PUT 5
68: I INT 3
71: s SETITEM
72: S STRING 'first'
81: p PUT 6
84: I INT 1
87: s SETITEM
88: s SETITEM
89: S STRING 'name'
97: p PUT 7
100: S STRING 'Joe'
107: p PUT 8
110: s SETITEM
111: S STRING 'numbers'
122: p PUT 9
125: ( MARK
126: l LIST (MARK at 125)
127: p PUT 10
131: I INT 1
134: a APPEND
135: I INT 2
138: a APPEND
139: I INT 3
142: a APPEND
143: I INT 4
146: a APPEND
147: I INT 5
150: a APPEND
151: s SETITEM
152: . STOP
highest protocol among opcodes = 0
>>>
</code></pre>
<p>You'd still have to read the pickled object from a file, however you wouldn't need to <code>load</code> it. So, if it's a "dangerous" object, you still might be able to figure that out before doing the <code>load</code>. If you are stuck with a <code>pickle</code>, it might be a good option for deciphering what you have.</p>
| 1 | 2015-04-04T20:06:59Z | [
"python",
"json",
"yaml",
"serialization",
"pickle"
] |
Python mailbox encoding errors | 409,217 | <p>First, let me say that I'm a complete beginner at Python. I've never learned the language, I just thought "how hard can it be" when Google turned up nothing but Python snippets to solve my problem. :)</p>
<p>I have a bunch of mailboxes in Maildir format (a backup from the mail server on my old web host), and I need to extract the emails from these.
So far, the simplest way I've found has been to convert them to the mbox format, which Thunderbird supports, and it seems Python has a few classes for reading/writing both formats. Seems perfect.</p>
<p>The Python docs even have this little code snippet doing exactly what I need:</p>
<pre><code>src = mailbox.Maildir('maildir', factory=None)
dest = mailbox.mbox('/tmp/mbox')
for msg in src: #1
dest.add(msg) #2
</code></pre>
<p><em>Except</em> it doesn't work. And here's where my complete lack of knowledge about Python sets in.
On a few messages, I get a UnicodeDecodeError during the iteration (that is, when it's trying to read <code>msg</code> from <code>src</code>, on line <code>#1</code>). On others, I get a UnicodeEncodeError when trying to add <code>msg</code> to <code>dest</code> (line <code>#2</code>).</p>
<p>Clearly it makes some wrong assumptions about the encoding used. But I have no clue how to specify an encoding on the mailbox (For that matter, I don't know what the encoding should be either, but I can probably figure that out once I find a way to actually specify an encoding). </p>
<p>I get stack traces similar to the following:</p>
<pre><code> File "E:\Python30\lib\mailbox.py", line 102, in itervalues
value = self[key]
File "E:\Python30\lib\mailbox.py", line 74, in __getitem__
return self.get_message(key)
File "E:\Python30\lib\mailbox.py", line 317, in get_message
msg = MaildirMessage(f)
File "E:\Python30\lib\mailbox.py", line 1373, in __init__
Message.__init__(self, message)
File "E:\Python30\lib\mailbox.py", line 1345, in __init__
self._become_message(email.message_from_file(message))
File "E:\Python30\lib\email\__init__.py", line 46, in message_from_file
return Parser(*args, **kws).parse(fp)
File "E:\Python30\lib\email\parser.py", line 68, in parse
data = fp.read(8192)
File "E:\Python30\lib\io.py", line 1733, in read
eof = not self._read_chunk()
File "E:\Python30\lib\io.py", line 1562, in _read_chunk
self._set_decoded_chars(self._decoder.decode(input_chunk, eof))
File "E:\Python30\lib\io.py", line 1295, in decode
output = self.decoder.decode(input, final=final)
File "E:\Python30\lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 37: character maps to <undefined>
</code></pre>
<p>And on the UnicodeEncodeErrors:</p>
<pre><code> File "E:\Python30\lib\email\message.py", line 121, in __str__
return self.as_string()
File "E:\Python30\lib\email\message.py", line 136, in as_string
g.flatten(self, unixfrom=unixfrom)
File "E:\Python30\lib\email\generator.py", line 76, in flatten
self._write(msg)
File "E:\Python30\lib\email\generator.py", line 108, in _write
self._write_headers(msg)
File "E:\Python30\lib\email\generator.py", line 141, in _write_headers
header_name=h, continuation_ws='\t')
File "E:\Python30\lib\email\header.py", line 189, in __init__
self.append(s, charset, errors)
File "E:\Python30\lib\email\header.py", line 262, in append
input_bytes = s.encode(input_charset, errors)
UnicodeEncodeError: 'ascii' codec can't encode character '\xe5' in position 16:
ordinal not in range(128)
</code></pre>
<p>Anyone able to help me out here? (Suggestions for completely different solutions not involving Python are obviously welcome too. I just need a way to access get import the mails from these Maildir files.</p>
<p><em>Updates:</em></p>
<p>sys.getdefaultencoding returns 'utf-8'</p>
<p>I uploaded sample messages which cause both errors.
<a href="http://jalf.dk/python_problem/1187691008.H199308P14265.c1p.hostingzoom.com_2,S" rel="nofollow">This one</a> throws UnicodeEncodeError, and <a href="http://jalf.dk/python_problem/1219438193.H364790P13554.c1p.hostingzoom.com_2,S" rel="nofollow">this</a> throws UnicodeDecodeError</p>
<p>I tried running the same script in Python2.6, and got TypeErrors instead:</p>
<pre><code> File "c:\python26\lib\mailbox.py", line 529, in add
self._toc[self._next_key] = self._append_message(message)
File "c:\python26\lib\mailbox.py", line 665, in _append_message
offsets = self._install_message(message)
File "c:\python26\lib\mailbox.py", line 724, in _install_message
self._dump_message(message, self._file, self._mangle_from_)
File "c:\python26\lib\mailbox.py", line 220, in _dump_message
raise TypeError('Invalid message type: %s' % type(message))
TypeError: Invalid message type: <type 'instance'>
</code></pre>
| 6 | 2009-01-03T15:32:56Z | 409,431 | <p>Try it in Python 2.5 or 2.6 instead of 3.0. 3.0 has completely different Unicode handling and this module may not have been updated for 3.0. </p>
| 4 | 2009-01-03T17:32:09Z | [
"python",
"encoding",
"email-formats"
] |
Python mailbox encoding errors | 409,217 | <p>First, let me say that I'm a complete beginner at Python. I've never learned the language, I just thought "how hard can it be" when Google turned up nothing but Python snippets to solve my problem. :)</p>
<p>I have a bunch of mailboxes in Maildir format (a backup from the mail server on my old web host), and I need to extract the emails from these.
So far, the simplest way I've found has been to convert them to the mbox format, which Thunderbird supports, and it seems Python has a few classes for reading/writing both formats. Seems perfect.</p>
<p>The Python docs even have this little code snippet doing exactly what I need:</p>
<pre><code>src = mailbox.Maildir('maildir', factory=None)
dest = mailbox.mbox('/tmp/mbox')
for msg in src: #1
dest.add(msg) #2
</code></pre>
<p><em>Except</em> it doesn't work. And here's where my complete lack of knowledge about Python sets in.
On a few messages, I get a UnicodeDecodeError during the iteration (that is, when it's trying to read <code>msg</code> from <code>src</code>, on line <code>#1</code>). On others, I get a UnicodeEncodeError when trying to add <code>msg</code> to <code>dest</code> (line <code>#2</code>).</p>
<p>Clearly it makes some wrong assumptions about the encoding used. But I have no clue how to specify an encoding on the mailbox (For that matter, I don't know what the encoding should be either, but I can probably figure that out once I find a way to actually specify an encoding). </p>
<p>I get stack traces similar to the following:</p>
<pre><code> File "E:\Python30\lib\mailbox.py", line 102, in itervalues
value = self[key]
File "E:\Python30\lib\mailbox.py", line 74, in __getitem__
return self.get_message(key)
File "E:\Python30\lib\mailbox.py", line 317, in get_message
msg = MaildirMessage(f)
File "E:\Python30\lib\mailbox.py", line 1373, in __init__
Message.__init__(self, message)
File "E:\Python30\lib\mailbox.py", line 1345, in __init__
self._become_message(email.message_from_file(message))
File "E:\Python30\lib\email\__init__.py", line 46, in message_from_file
return Parser(*args, **kws).parse(fp)
File "E:\Python30\lib\email\parser.py", line 68, in parse
data = fp.read(8192)
File "E:\Python30\lib\io.py", line 1733, in read
eof = not self._read_chunk()
File "E:\Python30\lib\io.py", line 1562, in _read_chunk
self._set_decoded_chars(self._decoder.decode(input_chunk, eof))
File "E:\Python30\lib\io.py", line 1295, in decode
output = self.decoder.decode(input, final=final)
File "E:\Python30\lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 37: character maps to <undefined>
</code></pre>
<p>And on the UnicodeEncodeErrors:</p>
<pre><code> File "E:\Python30\lib\email\message.py", line 121, in __str__
return self.as_string()
File "E:\Python30\lib\email\message.py", line 136, in as_string
g.flatten(self, unixfrom=unixfrom)
File "E:\Python30\lib\email\generator.py", line 76, in flatten
self._write(msg)
File "E:\Python30\lib\email\generator.py", line 108, in _write
self._write_headers(msg)
File "E:\Python30\lib\email\generator.py", line 141, in _write_headers
header_name=h, continuation_ws='\t')
File "E:\Python30\lib\email\header.py", line 189, in __init__
self.append(s, charset, errors)
File "E:\Python30\lib\email\header.py", line 262, in append
input_bytes = s.encode(input_charset, errors)
UnicodeEncodeError: 'ascii' codec can't encode character '\xe5' in position 16:
ordinal not in range(128)
</code></pre>
<p>Anyone able to help me out here? (Suggestions for completely different solutions not involving Python are obviously welcome too. I just need a way to access get import the mails from these Maildir files.</p>
<p><em>Updates:</em></p>
<p>sys.getdefaultencoding returns 'utf-8'</p>
<p>I uploaded sample messages which cause both errors.
<a href="http://jalf.dk/python_problem/1187691008.H199308P14265.c1p.hostingzoom.com_2,S" rel="nofollow">This one</a> throws UnicodeEncodeError, and <a href="http://jalf.dk/python_problem/1219438193.H364790P13554.c1p.hostingzoom.com_2,S" rel="nofollow">this</a> throws UnicodeDecodeError</p>
<p>I tried running the same script in Python2.6, and got TypeErrors instead:</p>
<pre><code> File "c:\python26\lib\mailbox.py", line 529, in add
self._toc[self._next_key] = self._append_message(message)
File "c:\python26\lib\mailbox.py", line 665, in _append_message
offsets = self._install_message(message)
File "c:\python26\lib\mailbox.py", line 724, in _install_message
self._dump_message(message, self._file, self._mangle_from_)
File "c:\python26\lib\mailbox.py", line 220, in _dump_message
raise TypeError('Invalid message type: %s' % type(message))
TypeError: Invalid message type: <type 'instance'>
</code></pre>
| 6 | 2009-01-03T15:32:56Z | 409,486 | <p>Note </p>
<ol>
<li><p>@Jimmy2Times could be very True in saying that this module may not be updated for 3.0.</p></li>
<li><p>This is not an answer particularly rather a probable explanation of what is going on, why, how to reproduce it, other people can benefit from this. I am trying further to complete this answer.</p></li>
</ol>
<p>I have put up whatever I could find as <strong>Edit</strong> below</p>
<p>=====</p>
<p>I think this is what is happening</p>
<p>Among many other characters in your data, you have the two chars - <code>\x9d</code> and <code>\xe5</code> and these are encoded in some encoding format say <code>iso-8859-1</code>.</p>
<p>when Python 3.0 finds the encoded string it first tries to guess the encoding of the string and then decode it into unicode using the guessed encoding (the way it keeps encoded unicode strings - <a href="http://docs.python.org/3.0/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit" rel="nofollow">Link</a>). </p>
<p>I think its the guessing part is where it is going wrong. </p>
<p>To show what's most likely going on - </p>
<p>Let's say the encoding was <code>iso-8859-1</code> and the wrong guess was <code>cp1252</code> (as from the first traceback).</p>
<p>The decode for <code>\x9d</code> fails.</p>
<pre><code>In [290]: unicode(u'\x9d'.encode('iso-8859-1'), 'cp1252')
---------------------------------------------------------------------------
<type 'exceptions.UnicodeDecodeError'> Traceback (most recent call last)
/home/jv/<ipython console> in <module>()
/usr/lib/python2.5/encodings/cp1252.py in decode(self, input, errors)
13
14 def decode(self,input,errors='strict'):
---> 15 return codecs.charmap_decode(input,errors,decoding_table)
16
17 class IncrementalEncoder(codecs.IncrementalEncoder):
<type 'exceptions.UnicodeDecodeError'>: 'charmap' codec can't decode byte 0x9d in position 0: character maps to <undefined>
</code></pre>
<p>The decode for <code>\xe5</code> passes but then, when the message is retrieved from Python somewhere it is trying to encode it in <code>ascii</code> which fails</p>
<pre><code>In [291]: unicode(u'\xe5'.encode('iso-8859-1'), 'cp1252').encode('ascii')
---------------------------------------------------------------------------
<type 'exceptions.UnicodeEncodeError'> Traceback (most recent call last)
/home/jv/<ipython console> in <module>()
<type 'exceptions.UnicodeEncodeError'>: 'ascii' codec can't encode character u'\xe5' in position 0: ordinal not in range(128)
</code></pre>
<p>============</p>
<p><strong>EDIT</strong>:</p>
<p>Both your problems are in line #2. Where it first decodes into unicode and then encodes into ascii</p>
<p>First do <strong>easy_install chardet</strong></p>
<p>The decode error:</p>
<pre><code>In [75]: decd=open('jalf_decode_err','r').read()
In [76]: chardet.detect(decd)
Out[76]: {'confidence': 0.98999999999999999, 'encoding': 'utf-8'}
##this is what is tried at the back - my guess :)
In [77]: unicode(decd, 'cp1252')
---------------------------------------------------------------------------
<type 'exceptions.UnicodeDecodeError'> Traceback (most recent call last)
/home/jv/<ipython console> in <module>()
/usr/lib/python2.5/encodings/cp1252.py in decode(self, input, errors)
13
14 def decode(self,input,errors='strict'):
---> 15 return codecs.charmap_decode(input,errors,decoding_table)
16
17 class IncrementalEncoder(codecs.IncrementalEncoder):
<type 'exceptions.UnicodeDecodeError'>: 'charmap' codec can't decode byte 0x9d in position 2812: character maps to <undefined>'
##this is a FIX- this way all your messages r accepted
In [78]: unicode(decd, chardet.detect(decd)['encoding'])
Out[78]: u'Return-path: <[email protected]>\nEnvelope-to: [email protected]\nDelivery-date: Fri, 22 Aug 2008 16:49:53 -0400\nReceived: from [77.232.66.102] (helo=apps2.servage.net)\n\tby c1p.hostingzoom.com with esmtp (Exim 4.69)\n\t(envelope-from <[email protected]>)\n\tid 1KWdZu-0003VX-HP\n\tfor [email protected]; Fri, 22 Aug 2008 16:49:52 -0400\nReceived: from apps2.servage.net (apps2.servage.net [127.0.0.1])\n\tby apps2.servage.net (Postfix) with ESMTP id 4A87F980026\n\tfor <[email protected]>; Fri, 22 Aug 2008 21:49:46 +0100 (BST)\nReceived: (from root@localhost)\n\tby apps2.servage.net (8.13.8/8.13.8/Submit) id m7MKnkrB006225;\n\tFri, 22 Aug 2008 21:49:46 +0100\nDate: Fri, 22 Aug 2008 21:49:46 +0100\nMessage-Id: <[email protected]>\nTo: [email protected]\nSubject: =?UTF-8?B?WW5ncmVzYWdlbnMgTnloZWRzYnJldiAyMi44LjA4?=\nFrom: Nyhedsbrev fra Yngresagen <[email protected]>\nReply-To: [email protected]\nContent-type: text/plain; charset=UTF-8\nX-Abuse: Servage.net Listid 16329\nMime-Version: 1.0\nX-mailer: Servage Maillist System\nX-Spam-Status: No, score=0.1\nX-Spam-Score: 1\nX-Spam-Bar: /\nX-Spam-Flag: NO\nX-ClamAntiVirus-Scanner: This mail is clean\n\n\nK\xe6re medlem\n\nH\xe5ber du har en god sommer og er klar p\xe5 at l\xe6se seneste nyt i Yngresagen. God forn\xf8jelse!\n\n\n::. KOM TIL YS-CAF\xc8 .::\nFlere og billigere ungdomsboliger, afskaf 24-\xe5rs-reglen eller hvad synes du? Yngresagen indbyder dig til en \xe5ben debat over kaffe og snacks. Yngresagens Kristian Lauta, Mette Marb\xe6k, og formand Steffen M\xf8ller fort\xe6ller om tidligere projekter og vil gerne diskutere, hvad Yngresagen skal bruge sin tid p\xe5 fremover. \nVil du diskutere et emne, du br\xe6nder for, eller vil du bare v\xe6re med p\xe5 en lytter?\nS\xe5 kom torsdag d. 28/8 kl. 17-19, Kulturhuset 44, 2200 KBH N \n \n::. VIND GAVEKORT & BLIV H\xd8RT .:: \nYngresagen har lavet et sp\xf8rgeskema, s\xe5 du har direkte mulighed for at sige din mening, og v\xe6re med til at forme Yngresagens arbejde. Brug 5 min. p\xe5 at dele dine holdninger om f.eks. uddannelse, arbejde og unges vilk\xe5r - og vind et gavekort til en musikbutik. Vi tr\xe6kker lod blandt alle svarene og finder tre heldige vindere. Sp\xf8rgeskemaet er her: www.yngresagen.dk\n\n::. YS SPARKER NORDJYLLAND I GANG .::\nNordjylland bliver Yngresagens sunde region. Her er regionsansvarlig Andreas M\xf8ller Stehr ved at starte tre projekter op: 1) L\xf8beklub, 2) F\xf8rstehj\xe6lpskursus, 3) Mad til unge-program.\nVi har brug for flere frivillige til at sparke projekterne i gang. Vi tilbyder gratis fede aktiviteter, gratis t-shirts og ture til K\xf8benhavn, hvor du kan m\xf8de andre unge i YS. Har det fanget din interesse, s\xe5 t\xf8v ikke med at kontakte os: [email protected] tlf. 21935185. \n\n::. YNGRESAGEN I PRESSEN .::\nL\xe6s her et udsnit af sidste nyt om Yngresagen i medierne. L\xe6s og lyt mere p\xe5 hjemmesiden under \u201dYS i pressen\u201d.\n\n:: Radionyhederne: Unge skal informeres bedre om l\xe5n \nUnge ved for lidt om at l\xe5ne penge. Det udnytter banker og rejseselskaber til at give dem l\xe5n med t\xe5rnh\xf8je renter. S\xe5dan lyder det fra formand Steffen M\xf8ller fra landsforeningen Yngresagen. \n\n:: Danmarks Radio P1: Dansk Folkeparti - de \xe6ldres parti? \nHvorfor er det kun fattige \xe6ldre og ikke alle fattige, der kan s\xf8ge om at f\xe5 nedsat medielicens?\nDansk Folkepartis ungeordf\xf8rer, Karin N\xf8dgaard, og Yngresagens formand Steffen M\xf8ller debatterer medielicens, \xe6ldrecheck og indflydelse til unge \n\n:: Frederiksborg Amts Avis: Turen til Roskilde koster en holdning!\nFor at skabe et m\xf8de mellem politikere og unge fragter Yngresagen unge gratis til \xe5rets Roskilde Festival. Det sker med den s\xe5kaldte Yngrebussen, der kan l\xe6ses mere om p\xe5 www.yngrebussen.dk\n\n \n \nMed venlig hilsen \nYngresagen\n\nLandsforeningen Yngresagen\nKulturhuset Kapelvej 44\n2200 K\xf8benhavn N\n\ntlf. 29644960\[email protected]\nwww.yngresagen.dk\n\n\n-------------------------------------------------------\nUnsubscribe Link: \nhttp://apps.corecluster.net/apps/ml/r.php?l=16329&e=public%40jalf.dk%0D%0A&id=40830383\n-------------------------------------------------------\n\n'
</code></pre>
<p>Now its in unicode so it shouldn't give you any problem.</p>
<p>Now the encode problem: It is a problem</p>
<pre><code>In [129]: encd=open('jalf_encode_err','r').read()
In [130]: chardet.detect(encd)
Out[130]: {'confidence': 0.78187650822865284, 'encoding': 'ISO-8859-2'}
#even after the unicode conversion the encoding to ascii fails - because the criteris is strict by default
In [131]: unicode(encd, chardet.detect(encd)['encoding']).encode('ascii')
---------------------------------------------------------------------------
<type 'exceptions.UnicodeEncodeError'> Traceback (most recent call last)
/home/jv/<ipython console> in <module>()
<type 'exceptions.UnicodeEncodeError'>: 'ascii' codec can't encode character u'\u0159' in position 557: ordinal not in range(128)'
##changing the criteria to ignore
In [132]: unicode(encd, chardet.detect(encd)['encoding']).encode('ascii', 'ignore')
Out[132]: 'Return-path: <[email protected]>\nEnvelope-to: [email protected]\nDelivery-date: Tue, 21 Aug 2007 06:10:08 -0400\nReceived: from pfepc.post.tele.dk ([195.41.46.237]:52065)\n\tby c1p.hostingzoom.com with esmtp (Exim 4.66)\n\t(envelope-from <[email protected]>)\n\tid 1INQgX-0003fI-Un\n\tfor [email protected]; Tue, 21 Aug 2007 06:10:08 -0400\nReceived: from local.com (ns2.datadan.dk [195.41.7.21])\n\tby pfepc.post.tele.dk (Postfix) with SMTP id ADF4C8A0086\n\tfor <[email protected]>; Tue, 21 Aug 2007 12:10:04 +0200 (CEST)\nFrom: "Kollegiernes Kontor I Kbenhavn" <[email protected]>\nTo: "Jesper Alf Dam" <[email protected]>\nSubject: Fornyelse af profil\nDate: Tue, 21 Aug 2007 12:10:03 +0200\nX-Mailer: Dundas Mailer Control 1.0\nMIME-Version: 1.0\nContent-Type: Multipart/Alternative;\n\tboundary="Gark=_20078211010346yhSD0hUCo"\nMessage-Id: <[email protected]>\nX-Spam-Status: No, score=0.0\nX-Spam-Score: 0\nX-Spam-Bar: /\nX-Spam-Flag: NO\nX-ClamAntiVirus-Scanner: This mail is clean\n\n\n\n--Gark=_20078211010346yhSD0hUCo\nContent-Type: text/plain; charset=ISO-8859-1\nContent-Transfer-Encoding: Quoted-Printable\n\nHej Jesper Alf Dam=0D=0A=0D=0AHusk at forny din profil hos KKIK inden 28.=\n august 2007=0D=0ALog ind p=E5 din profil og benyt ikonet "forny".=0D=0A=0D=\n=0AVenlig hilsen=0D=0AKollegiernes Kontor i K=F8benhavn=0D=0A=0D=0Ahttp:/=\n/www.kollegierneskontor.dk/=0D=0A=0D=0A\n\n--Gark=_20078211010346yhSD0hUCo\nContent-Type: text/html; charset=ISO-8859-1\nContent-Transfer-Encoding: Quoted-Printable\n\n<html>=0D=0A<head>=0D=0A=0D=0A<style>=0D=0ABODY, TD {=0D=0Afont-family: v=\nerdana, arial, helvetica; font-size: 12px; color: #666666;=0D=0A}=0D=0A</=\nstyle>=0D=0A=0D=0A<title></title>=0D=0A=0D=0A</head>=0D=0A<body bgcolor=3D=\n#FFFFFF>=0D=0A<hr size=3D1 noshade>=0D=0A<table cellpadding=3D0 cellspaci=\nng=3D0 border=3D0 width=3D100%>=0D=0A<tr><td >=0D=0AHej Jesper Alf Dam<br=\n><br>Husk at forny din profil inden 28. august 2007<br>=0D=0ALog ind p=E5=\n din profil og benyt ikonet "forny".=0D=0A<br><br>=0D=0A<a href=3D"http:/=\n/www.kollegierneskontor.dk/">Klik her</a> for at logge ind.<br><br>Venlig=\n hilsen<br>Kollegiernes Kontor i K=F8benhavn=0D=0A</td></tr>=0D=0A</table=\n>=0D=0A<hr size=3D1 noshade>=0D=0A</body>=0D=0A</html>=0D=0A\n\n--Gark=_20078211010346yhSD0hUCo--\n\n'
In [133]: len(encd)
Out[133]: 2303
In [134]: len(unicode(encd, chardet.detect(encd)['encoding']).encode('ascii', 'ignore'))
Out[134]: 2302
</code></pre>
<p>CAUTION: as you can see there could be minor to moderate loss of data in this procedure. So its upto the user to use it or not.</p>
<p>so the code should look like </p>
<pre><code>import chardet
for msg in src:
msg=unicode(msg, chardet.detect(msg)['encoding']).encode('ascii', 'ignore')
dest.add(msg)
</code></pre>
| 4 | 2009-01-03T18:01:10Z | [
"python",
"encoding",
"email-formats"
] |
Cocoa client/server application | 409,354 | <p>Is there a way in Cocoa that is currently considered best practice for creating a multi-tier or client server application?</p>
<p>I'm an experienced web developer and I really love Python. I'm new to Cocoa though. The application I'm toying with writing is a patient management system for a large hospital. The system is expected to store huge amounts of data over time but the data transferred during a single session is very light (mostly just text). The communication is assumed to occur over a local network (wired or wireless). It has to be highly secure, of course.</p>
<p>The best I could come up with is to write a Python REST web service and connect to it through the Cocoa app. Maybe I'll even use Python to code the Cocoa app itself.</p>
<p>Looking at Cocoa, I see really great technologies in Cocoa like CoreData but I couldn't find anything similar for client server development. I just want to make sure that I'm not missing anything.</p>
<p>What do you think?</p>
<p>Real world examples will be greatly appreciated.</p>
<p>Thanks in advance.</p>
| 10 | 2009-01-03T16:57:11Z | 409,446 | <p>Generally, the ideas of all other client/server frameworks are applicable.</p>
<p>Take a look at this link: <a href="http://developer.apple.com/internet/webservices/webservicescoreandcfnetwork.html" rel="nofollow">http://developer.apple.com/internet/webservices/webservicescoreandcfnetwork.html</a></p>
| 1 | 2009-01-03T17:39:43Z | [
"python",
"cocoa",
"web-services",
"client-server",
"pyobjc"
] |
Cocoa client/server application | 409,354 | <p>Is there a way in Cocoa that is currently considered best practice for creating a multi-tier or client server application?</p>
<p>I'm an experienced web developer and I really love Python. I'm new to Cocoa though. The application I'm toying with writing is a patient management system for a large hospital. The system is expected to store huge amounts of data over time but the data transferred during a single session is very light (mostly just text). The communication is assumed to occur over a local network (wired or wireless). It has to be highly secure, of course.</p>
<p>The best I could come up with is to write a Python REST web service and connect to it through the Cocoa app. Maybe I'll even use Python to code the Cocoa app itself.</p>
<p>Looking at Cocoa, I see really great technologies in Cocoa like CoreData but I couldn't find anything similar for client server development. I just want to make sure that I'm not missing anything.</p>
<p>What do you think?</p>
<p>Real world examples will be greatly appreciated.</p>
<p>Thanks in advance.</p>
| 10 | 2009-01-03T16:57:11Z | 409,451 | <p>Look at the api's for <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html" rel="nofollow">NSConnection</a> and <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSURLDownload_Class/Reference/Reference.html" rel="nofollow">NSDownload</a> to handle the network connection. The <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html" rel="nofollow">NSString</a> class also has methods like <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/clm/NSString/stringWithContentsOfURL:encoding:error:" rel="nofollow">+ stringWithContentsOfURL:encoding:error:</a> that may be useful.</p>
<p>Then there is <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSXMLParser_Class/Reference/Reference.html" rel="nofollow">NSXMLParser</a> and <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSXMLDocument_Class/Reference/Reference.html" rel="nofollow">NSXMLDocument</a> for reading xml data.</p>
| -1 | 2009-01-03T17:45:45Z | [
"python",
"cocoa",
"web-services",
"client-server",
"pyobjc"
] |
Cocoa client/server application | 409,354 | <p>Is there a way in Cocoa that is currently considered best practice for creating a multi-tier or client server application?</p>
<p>I'm an experienced web developer and I really love Python. I'm new to Cocoa though. The application I'm toying with writing is a patient management system for a large hospital. The system is expected to store huge amounts of data over time but the data transferred during a single session is very light (mostly just text). The communication is assumed to occur over a local network (wired or wireless). It has to be highly secure, of course.</p>
<p>The best I could come up with is to write a Python REST web service and connect to it through the Cocoa app. Maybe I'll even use Python to code the Cocoa app itself.</p>
<p>Looking at Cocoa, I see really great technologies in Cocoa like CoreData but I couldn't find anything similar for client server development. I just want to make sure that I'm not missing anything.</p>
<p>What do you think?</p>
<p>Real world examples will be greatly appreciated.</p>
<p>Thanks in advance.</p>
| 10 | 2009-01-03T16:57:11Z | 409,806 | <p>Cocoa has <a href="http://en.wikipedia.org/wiki/Portable_Distributed_Objects" rel="nofollow">Portable Distributed Objects</a>, which let you build a client / server application in pure Objective-C and Cocoa which can communicate across processes or across a network. </p>
<p>Unfortunately it's one of the harder things to learn in Cocoa. Distributed objects haven't been updated to keep up with new technologies like bindings, there's not a lot of examples or documentation (and many of the tutorials are old, some even pre-dating OS X). There's also a lot of "gotchas," even for experienced Cocoa programmers, in the way objects are transmitted across the wire either as a copy or a proxy object. For example, you can transmit an NSURL from a server and it will seem fine if you convert it to a string or look at it in the debugger, but your client will crash if you try to use it in an NSURLConnection.</p>
<p>Depending on your experience it may be easier and quicker to use a web service, but it's still worth looking in to if you'd like to keep the entire project in Cocoa. Here's a <a href="http://cocoadevcentral.com/articles/000062.php" rel="nofollow">tutorial</a> if you'd like to see an example.</p>
| 2 | 2009-01-03T20:48:13Z | [
"python",
"cocoa",
"web-services",
"client-server",
"pyobjc"
] |
Cocoa client/server application | 409,354 | <p>Is there a way in Cocoa that is currently considered best practice for creating a multi-tier or client server application?</p>
<p>I'm an experienced web developer and I really love Python. I'm new to Cocoa though. The application I'm toying with writing is a patient management system for a large hospital. The system is expected to store huge amounts of data over time but the data transferred during a single session is very light (mostly just text). The communication is assumed to occur over a local network (wired or wireless). It has to be highly secure, of course.</p>
<p>The best I could come up with is to write a Python REST web service and connect to it through the Cocoa app. Maybe I'll even use Python to code the Cocoa app itself.</p>
<p>Looking at Cocoa, I see really great technologies in Cocoa like CoreData but I couldn't find anything similar for client server development. I just want to make sure that I'm not missing anything.</p>
<p>What do you think?</p>
<p>Real world examples will be greatly appreciated.</p>
<p>Thanks in advance.</p>
| 10 | 2009-01-03T16:57:11Z | 409,925 | <p>If you have control of both the client and server, and you can limit the client to OS X only, I second Marc's answer. Cocoa's distributed objects are an amazing technology and make RPC-style client-server apps very easy.</p>
<p>If the requirements above are too restrictive for you, you still have many options available to you in the Cocoa world:</p>
<ol>
<li><p>You can code the entire client app in Python using PyObjC. With this approach, you can use the standard network code that you're familiar with from the Python standard library. <a href="http://twistedmatrix.com" rel="nofollow">Twisted also integrates nicely with the Cocoa run loop (examples in the PyObjC example code) and I've had a lot of success using Twisted for network communication from with in a Cocoa app. If you choose to go this route, you may want to code the client app in Objective-C and load the python code as a plugin (using NSBundle). PyObjC's <code>py2app</code> can compile loadable bundles from python code.</p></li>
<li><p>You can use NSURLConnection for high-level access to an HTTP-based server.</p></li>
<li><p>Dropping down a level of abstraction, you can use Cocoa's NSStream to implement your network protocol. The class documentation is http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSStream_Class/Reference/Reference.html">here</a>, with links to example code demonstrating HTTP and SOAP protocols.</p></li>
<li><p>You can drop a further level down and use the CFNetwork classes. NSStream is based on CFNetwork, but you have lower-level control over the line using CFNetwork.</p></li>
</ol>
<p>Finally, the Apple technology for client-server architectures is the <a href="http://developer.apple.com/tools/webobjects/" rel="nofollow">WebObjects</a> framework.</p>
| 5 | 2009-01-03T21:51:49Z | [
"python",
"cocoa",
"web-services",
"client-server",
"pyobjc"
] |
Cocoa client/server application | 409,354 | <p>Is there a way in Cocoa that is currently considered best practice for creating a multi-tier or client server application?</p>
<p>I'm an experienced web developer and I really love Python. I'm new to Cocoa though. The application I'm toying with writing is a patient management system for a large hospital. The system is expected to store huge amounts of data over time but the data transferred during a single session is very light (mostly just text). The communication is assumed to occur over a local network (wired or wireless). It has to be highly secure, of course.</p>
<p>The best I could come up with is to write a Python REST web service and connect to it through the Cocoa app. Maybe I'll even use Python to code the Cocoa app itself.</p>
<p>Looking at Cocoa, I see really great technologies in Cocoa like CoreData but I couldn't find anything similar for client server development. I just want to make sure that I'm not missing anything.</p>
<p>What do you think?</p>
<p>Real world examples will be greatly appreciated.</p>
<p>Thanks in advance.</p>
| 10 | 2009-01-03T16:57:11Z | 829,539 | <p>I have written a server and a client class for use in Cocoa.
Using these classes makes it very easy to produce a server or client application without the knowledge about sockets and that C-stuff
Just have a look at <a href="http://www.1-more-thing.de/code/simpleserver" rel="nofollow">my website</a> or at the <a href="http://sourceforge.net/projects/simpleserver" rel="nofollow">sourceforge.net project site</a>.</p>
| 0 | 2009-05-06T13:25:52Z | [
"python",
"cocoa",
"web-services",
"client-server",
"pyobjc"
] |
Sorting and Grouping Nested Lists in Python | 409,370 | <p>I have the following data structure (a list of lists)</p>
<pre><code>[
['4', '21', '1', '14', '2008-10-24 15:42:58'],
['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['5', '21', '3', '19', '2008-10-24 15:45:45'],
['6', '21', '1', '1somename', '2008-10-24 15:45:49'],
['7', '22', '3', '2somename', '2008-10-24 15:45:51']
]
</code></pre>
<p>I would like to be able to</p>
<ol>
<li><p>Use a function to reorder the list so that I can group by each item in the list. For example I'd like to be able to group by the second column (so that all the 21's are together) </p></li>
<li><p>Use a function to only display certain values from each inner list. For example i'd like to reduce this list to only contain the 4th field value of '2somename' </p></li>
</ol>
<p>so the list would look like this </p>
<pre><code>[
['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['7', '22', '3', '2somename', '2008-10-24 15:45:51']
]
</code></pre>
| 23 | 2009-01-03T17:05:30Z | 409,394 | <p>If I understand your question correctly, the following code should do the job:</p>
<pre><code>l = [
['4', '21', '1', '14', '2008-10-24 15:42:58'],
['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['5', '21', '3', '19', '2008-10-24 15:45:45'],
['6', '21', '1', '1somename', '2008-10-24 15:45:49'],
['7', '22', '3', '2somename', '2008-10-24 15:45:51']
]
def compareField(field):
def c(l1,l2):
return cmp(l1[field], l2[field])
return c
# Use compareField(1) as the ordering criterion, i.e. sort only with
# respect to the 2nd field
l.sort(compareField(1))
for row in l: print row
print
# Select only those sublists for which 4th field=='2somename'
l2somename = [row for row in l if row[3]=='2somename']
for row in l2somename: print row
</code></pre>
<p>Output:</p>
<pre><code>['4', '21', '1', '14', '2008-10-24 15:42:58']
['5', '21', '3', '19', '2008-10-24 15:45:45']
['6', '21', '1', '1somename', '2008-10-24 15:45:49']
['3', '22', '4', '2somename', '2008-10-24 15:22:03']
['7', '22', '3', '2somename', '2008-10-24 15:45:51']
['3', '22', '4', '2somename', '2008-10-24 15:22:03']
['7', '22', '3', '2somename', '2008-10-24 15:45:51']
</code></pre>
| 3 | 2009-01-03T17:17:32Z | [
"python"
] |
Sorting and Grouping Nested Lists in Python | 409,370 | <p>I have the following data structure (a list of lists)</p>
<pre><code>[
['4', '21', '1', '14', '2008-10-24 15:42:58'],
['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['5', '21', '3', '19', '2008-10-24 15:45:45'],
['6', '21', '1', '1somename', '2008-10-24 15:45:49'],
['7', '22', '3', '2somename', '2008-10-24 15:45:51']
]
</code></pre>
<p>I would like to be able to</p>
<ol>
<li><p>Use a function to reorder the list so that I can group by each item in the list. For example I'd like to be able to group by the second column (so that all the 21's are together) </p></li>
<li><p>Use a function to only display certain values from each inner list. For example i'd like to reduce this list to only contain the 4th field value of '2somename' </p></li>
</ol>
<p>so the list would look like this </p>
<pre><code>[
['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['7', '22', '3', '2somename', '2008-10-24 15:45:51']
]
</code></pre>
| 23 | 2009-01-03T17:05:30Z | 409,416 | <p>If you assigned it to var "a"...</p>
<p>#1: </p>
<pre><code>a.sort(lambda x,y: cmp(x[1], y[1]))
</code></pre>
<p>#2: </p>
<pre><code>filter(lambda x: x[3]=="2somename", a)
</code></pre>
| 5 | 2009-01-03T17:26:37Z | [
"python"
] |
Sorting and Grouping Nested Lists in Python | 409,370 | <p>I have the following data structure (a list of lists)</p>
<pre><code>[
['4', '21', '1', '14', '2008-10-24 15:42:58'],
['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['5', '21', '3', '19', '2008-10-24 15:45:45'],
['6', '21', '1', '1somename', '2008-10-24 15:45:49'],
['7', '22', '3', '2somename', '2008-10-24 15:45:51']
]
</code></pre>
<p>I would like to be able to</p>
<ol>
<li><p>Use a function to reorder the list so that I can group by each item in the list. For example I'd like to be able to group by the second column (so that all the 21's are together) </p></li>
<li><p>Use a function to only display certain values from each inner list. For example i'd like to reduce this list to only contain the 4th field value of '2somename' </p></li>
</ol>
<p>so the list would look like this </p>
<pre><code>[
['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['7', '22', '3', '2somename', '2008-10-24 15:45:51']
]
</code></pre>
| 23 | 2009-01-03T17:05:30Z | 409,420 | <blockquote>
<p>Use a function to reorder the list so that I can group by each item in the list. For example I'd like to be able to group by the second column (so that all the 21's are together)</p>
</blockquote>
<p>Lists have a built in sort method and you can provide a function that extracts the sort key.</p>
<pre><code>>>> import pprint
>>> l.sort(key = lambda ll: ll[1])
>>> pprint.pprint(l)
[['4', '21', '1', '14', '2008-10-24 15:42:58'],
['5', '21', '3', '19', '2008-10-24 15:45:45'],
['6', '21', '1', '1somename', '2008-10-24 15:45:49'],
['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['7', '22', '3', '2somename', '2008-10-24 15:45:51']]
</code></pre>
<blockquote>
<p>Use a function to only display certain values from each inner list. For example i'd like to reduce this list to only contain the 4th field value of '2somename'</p>
</blockquote>
<p>This looks like a job for <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehensions</a></p>
<pre><code>>>> [ll[3] for ll in l]
['14', '2somename', '19', '1somename', '2somename']
</code></pre>
| 1 | 2009-01-03T17:27:29Z | [
"python"
] |
Sorting and Grouping Nested Lists in Python | 409,370 | <p>I have the following data structure (a list of lists)</p>
<pre><code>[
['4', '21', '1', '14', '2008-10-24 15:42:58'],
['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['5', '21', '3', '19', '2008-10-24 15:45:45'],
['6', '21', '1', '1somename', '2008-10-24 15:45:49'],
['7', '22', '3', '2somename', '2008-10-24 15:45:51']
]
</code></pre>
<p>I would like to be able to</p>
<ol>
<li><p>Use a function to reorder the list so that I can group by each item in the list. For example I'd like to be able to group by the second column (so that all the 21's are together) </p></li>
<li><p>Use a function to only display certain values from each inner list. For example i'd like to reduce this list to only contain the 4th field value of '2somename' </p></li>
</ol>
<p>so the list would look like this </p>
<pre><code>[
['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['7', '22', '3', '2somename', '2008-10-24 15:45:51']
]
</code></pre>
| 23 | 2009-01-03T17:05:30Z | 409,423 | <p>For the first question, the first thing you should do is sort the list by the second field:</p>
<pre><code>x = [
['4', '21', '1', '14', '2008-10-24 15:42:58'],
['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['5', '21', '3', '19', '2008-10-24 15:45:45'],
['6', '21', '1', '1somename', '2008-10-24 15:45:49'],
['7', '22', '3', '2somename', '2008-10-24 15:45:51']
]
from operator import itemgetter
x.sort(key=itemgetter(1))
</code></pre>
<p>Then you can use itertools' groupby function:</p>
<pre><code>from itertools import groupby
y = groupby(x, itemgetter(1))
</code></pre>
<p>Now y is an iterator containing tuples of (element, item iterator). It's more confusing to explain these tuples than it is to show code:</p>
<pre><code>for elt, items in groupby(x, itemgetter(1)):
print(elt, items)
for i in items:
print(i)
</code></pre>
<p>Which prints:</p>
<pre><code>21 <itertools._grouper object at 0x511a0>
['4', '21', '1', '14', '2008-10-24 15:42:58']
['5', '21', '3', '19', '2008-10-24 15:45:45']
['6', '21', '1', '1somename', '2008-10-24 15:45:49']
22 <itertools._grouper object at 0x51170>
['3', '22', '4', '2somename', '2008-10-24 15:22:03']
['7', '22', '3', '2somename', '2008-10-24 15:45:51']
</code></pre>
<p>For the second part, you should use list comprehensions as mentioned already here:</p>
<pre><code>from pprint import pprint as pp
pp([y for y in x if y[3] == '2somename'])
</code></pre>
<p>Which prints:</p>
<pre><code>[['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['7', '22', '3', '2somename', '2008-10-24 15:45:51']]
</code></pre>
| 37 | 2009-01-03T17:29:07Z | [
"python"
] |
Sorting and Grouping Nested Lists in Python | 409,370 | <p>I have the following data structure (a list of lists)</p>
<pre><code>[
['4', '21', '1', '14', '2008-10-24 15:42:58'],
['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['5', '21', '3', '19', '2008-10-24 15:45:45'],
['6', '21', '1', '1somename', '2008-10-24 15:45:49'],
['7', '22', '3', '2somename', '2008-10-24 15:45:51']
]
</code></pre>
<p>I would like to be able to</p>
<ol>
<li><p>Use a function to reorder the list so that I can group by each item in the list. For example I'd like to be able to group by the second column (so that all the 21's are together) </p></li>
<li><p>Use a function to only display certain values from each inner list. For example i'd like to reduce this list to only contain the 4th field value of '2somename' </p></li>
</ol>
<p>so the list would look like this </p>
<pre><code>[
['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['7', '22', '3', '2somename', '2008-10-24 15:45:51']
]
</code></pre>
| 23 | 2009-01-03T17:05:30Z | 409,442 | <p>If you'll be doing a lot of sorting and filtering, you may like some helper functions.</p>
<pre><code>m = [
['4', '21', '1', '14', '2008-10-24 15:42:58'],
['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['5', '21', '3', '19', '2008-10-24 15:45:45'],
['6', '21', '1', '1somename', '2008-10-24 15:45:49'],
['7', '22', '3', '2somename', '2008-10-24 15:45:51']
]
# Sort and filter helpers.
sort_on = lambda pos: lambda x: x[pos]
filter_on = lambda pos,val: lambda l: l[pos] == val
# Sort by second column
m = sorted(m, key=sort_on(1))
# Filter on 4th column, where value = '2somename'
m = filter(filter_on(3,'2somename'),m)
</code></pre>
| 1 | 2009-01-03T17:37:59Z | [
"python"
] |
Sorting and Grouping Nested Lists in Python | 409,370 | <p>I have the following data structure (a list of lists)</p>
<pre><code>[
['4', '21', '1', '14', '2008-10-24 15:42:58'],
['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['5', '21', '3', '19', '2008-10-24 15:45:45'],
['6', '21', '1', '1somename', '2008-10-24 15:45:49'],
['7', '22', '3', '2somename', '2008-10-24 15:45:51']
]
</code></pre>
<p>I would like to be able to</p>
<ol>
<li><p>Use a function to reorder the list so that I can group by each item in the list. For example I'd like to be able to group by the second column (so that all the 21's are together) </p></li>
<li><p>Use a function to only display certain values from each inner list. For example i'd like to reduce this list to only contain the 4th field value of '2somename' </p></li>
</ol>
<p>so the list would look like this </p>
<pre><code>[
['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['7', '22', '3', '2somename', '2008-10-24 15:45:51']
]
</code></pre>
| 23 | 2009-01-03T17:05:30Z | 409,478 | <p>It looks a lot like you're trying to use a list as a database.</p>
<p>Nowadays Python includes sqlite bindings in the core distribution. If you don't need persistence, it's really easy to create an in-memory sqlite database (see <a href="http://stackoverflow.com/questions/304393/how-do-i-create-a-sqllite3-in-memory-database">http://stackoverflow.com/questions/304393/how-do-i-create-a-sqllite3-in-memory-database</a>). </p>
<p>Then you can use SQL statements to do all this sorting and filtering without having to reinvent the wheel.</p>
| 1 | 2009-01-03T17:56:59Z | [
"python"
] |
Sorting and Grouping Nested Lists in Python | 409,370 | <p>I have the following data structure (a list of lists)</p>
<pre><code>[
['4', '21', '1', '14', '2008-10-24 15:42:58'],
['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['5', '21', '3', '19', '2008-10-24 15:45:45'],
['6', '21', '1', '1somename', '2008-10-24 15:45:49'],
['7', '22', '3', '2somename', '2008-10-24 15:45:51']
]
</code></pre>
<p>I would like to be able to</p>
<ol>
<li><p>Use a function to reorder the list so that I can group by each item in the list. For example I'd like to be able to group by the second column (so that all the 21's are together) </p></li>
<li><p>Use a function to only display certain values from each inner list. For example i'd like to reduce this list to only contain the 4th field value of '2somename' </p></li>
</ol>
<p>so the list would look like this </p>
<pre><code>[
['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['7', '22', '3', '2somename', '2008-10-24 15:45:51']
]
</code></pre>
| 23 | 2009-01-03T17:05:30Z | 409,514 | <p>For part (2), with x being your array, I think you want,</p>
<pre><code>[y for y in x if y[3] == '2somename']
</code></pre>
<p>Which will return a list of just your data lists that have a fourth value being '2somename'... Although it seems Kamil is giving you the best advice with going for SQL...</p>
| 2 | 2009-01-03T18:15:03Z | [
"python"
] |
Sorting and Grouping Nested Lists in Python | 409,370 | <p>I have the following data structure (a list of lists)</p>
<pre><code>[
['4', '21', '1', '14', '2008-10-24 15:42:58'],
['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['5', '21', '3', '19', '2008-10-24 15:45:45'],
['6', '21', '1', '1somename', '2008-10-24 15:45:49'],
['7', '22', '3', '2somename', '2008-10-24 15:45:51']
]
</code></pre>
<p>I would like to be able to</p>
<ol>
<li><p>Use a function to reorder the list so that I can group by each item in the list. For example I'd like to be able to group by the second column (so that all the 21's are together) </p></li>
<li><p>Use a function to only display certain values from each inner list. For example i'd like to reduce this list to only contain the 4th field value of '2somename' </p></li>
</ol>
<p>so the list would look like this </p>
<pre><code>[
['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['7', '22', '3', '2somename', '2008-10-24 15:45:51']
]
</code></pre>
| 23 | 2009-01-03T17:05:30Z | 409,684 | <p>You're simply creating indexes on your structure, right?</p>
<pre><code>>>> from collections import defaultdict
>>> def indexOn( things, pos ):
... inx= defaultdict(list)
... for t in things:
... inx[t[pos]].append(t)
... return inx
...
>>> a=[
... ['4', '21', '1', '14', '2008-10-24 15:42:58'],
... ['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
... ['5', '21', '3', '19', '2008-10-24 15:45:45'],
... ['6', '21', '1', '1somename', '2008-10-24 15:45:49'],
... ['7', '22', '3', '2somename', '2008-10-24 15:45:51']
... ]
</code></pre>
<p>Here's your first request, grouped by position 1.</p>
<pre><code>>>> import pprint
>>> pprint.pprint( dict(indexOn(a,1)) )
{'21': [['4', '21', '1', '14', '2008-10-24 15:42:58'],
['5', '21', '3', '19', '2008-10-24 15:45:45'],
['6', '21', '1', '1somename', '2008-10-24 15:45:49']],
'22': [['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['7', '22', '3', '2somename', '2008-10-24 15:45:51']]}
</code></pre>
<p>Here's your second request, grouped by position 3.</p>
<pre><code>>>> dict(indexOn(a,3))
{'19': [['5', '21', '3', '19', '2008-10-24 15:45:45']], '14': [['4', '21', '1', '14', '2008-10-24 15:42:58']], '2somename': [['3', '22', '4', '2somename', '2008-10-24 15:22:03'], ['7', '22', '3', '2somename', '2008-10-24 15:45:51']], '1somename': [['6', '21', '1', '1somename', '2008-10-24 15:45:49']]}
>>> pprint.pprint(_)
{'14': [['4', '21', '1', '14', '2008-10-24 15:42:58']],
'19': [['5', '21', '3', '19', '2008-10-24 15:45:45']],
'1somename': [['6', '21', '1', '1somename', '2008-10-24 15:45:49']],
'2somename': [['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['7', '22', '3', '2somename', '2008-10-24 15:45:51']]}
</code></pre>
| 1 | 2009-01-03T19:39:45Z | [
"python"
] |
Loop function parameters for sanity check | 409,449 | <p>I have a Python function in which I am doing some sanitisation of the input parameters:</p>
<pre><code>def func(param1, param2, param3):
param1 = param1 or ''
param2 = param2 or ''
param3 = param3 or ''
</code></pre>
<p>This caters for the arguments being passed as <em>None</em> rather than empty strings. Is there an easier/more concise way to loop round the function parameters to apply such an expression to all of them. My actual function has nine parameters.</p>
| 3 | 2009-01-03T17:41:09Z | 409,467 | <pre><code>def func(x='', y='', z='hooray!'):
print x, y, z
In [2]: f('test')
test hooray!
In [3]: f('test', 'and')
test and hooray!
In [4]: f('test', 'and', 'done!')
test and done!
</code></pre>
| -2 | 2009-01-03T17:51:38Z | [
"python",
"function",
"parameters",
"arguments",
"sanitization"
] |
Loop function parameters for sanity check | 409,449 | <p>I have a Python function in which I am doing some sanitisation of the input parameters:</p>
<pre><code>def func(param1, param2, param3):
param1 = param1 or ''
param2 = param2 or ''
param3 = param3 or ''
</code></pre>
<p>This caters for the arguments being passed as <em>None</em> rather than empty strings. Is there an easier/more concise way to loop round the function parameters to apply such an expression to all of them. My actual function has nine parameters.</p>
| 3 | 2009-01-03T17:41:09Z | 409,527 | <p>You could do some list manipulation:</p>
<pre><code>def func(param1, param2, param3):
param1, param2, param3 = map(lambda x: x or '', (param1, param2, param3))
</code></pre>
<p>but I'm not sure that's better than just writing out the nine lines, since once you get to nine parameters, that's a heinously long line.</p>
<p>You could change the declaration of the function:</p>
<pre><code>def func(*args):
param1, param2, param3 = map(lambda x: x or '', args)
</code></pre>
<p>but then you lose the documentation that comes from having real parameter names, as well as the possibility of changing the defaults, etc. And you still have a pretty fugly line there to unpack them.</p>
<p>I say write out the nine lines, or change the function to have fewer parameters: nine is kind of a lot anyway!</p>
| 2 | 2009-01-03T18:19:10Z | [
"python",
"function",
"parameters",
"arguments",
"sanitization"
] |
Loop function parameters for sanity check | 409,449 | <p>I have a Python function in which I am doing some sanitisation of the input parameters:</p>
<pre><code>def func(param1, param2, param3):
param1 = param1 or ''
param2 = param2 or ''
param3 = param3 or ''
</code></pre>
<p>This caters for the arguments being passed as <em>None</em> rather than empty strings. Is there an easier/more concise way to loop round the function parameters to apply such an expression to all of them. My actual function has nine parameters.</p>
| 3 | 2009-01-03T17:41:09Z | 409,564 | <p>This looks like a good job for a decorator. How about this:</p>
<pre><code>def sanitized(func):
def sfunc(*args, **kwds):
return func(*[arg or '' for arg in args],
**dict((k, v or '') for k,v in kwds.iteritems()))
sfunc.func_name = func.func_name
sfunc.func_doc = func.func_doc
return sfunc
</code></pre>
<p>You would use this on your function like so:</p>
<pre><code>@sanitized
def func(param1, param2, param3):
print param1, param2, param3
</code></pre>
<p>Then the parameters will be replaced by the empty string if they are false:</p>
<pre><code>>>> func('foo', None, 'spam')
foo spam
</code></pre>
<p>(Note that this will still mess up the function signature as Ned Batchelder points out in his answer. To fix that you could use <a href="http://pypi.python.org/pypi/decorator">Michele Simionato's decorator module</a>-- I think you'd just need to add a <code>@decorator</code> before the definition of <code>sanitized</code>)</p>
| 7 | 2009-01-03T18:43:01Z | [
"python",
"function",
"parameters",
"arguments",
"sanitization"
] |
Avoid exceptions? | 409,529 | <p>This particular example relates to Django in Python, but should apply to any language supporting exceptions:</p>
<pre><code>try:
object = ModelClass.objects.get(search=value)
except DoesNotExist:
pass
if object:
# do stuff
</code></pre>
<p>The Django model class provides a simple method <em>get</em> which allows me to search for <em>one and only one</em> object from the database, if it finds more or less it raises an exception. If can find zero or more with an alternative <em>filter</em> method, which returns a list:</p>
<pre><code>objects = ModelClass.objects.filter(search=value)
if len(objects) == 1:
object = objects[0]
# do stuff
</code></pre>
<p><strong>Am I overly averse to exceptions?</strong> To me the exception seems a little wasteful, at a guess, a quarter-to-a-half of the time will be 'exceptional'. I'd much prefer a function that returns <em>None</em> on failure. Would I be better to use Django's <em>filter</em> method and process the list myself?</p>
| 8 | 2009-01-03T18:19:50Z | 409,538 | <p>The clue is in the name - exceptions should be exceptional.</p>
<p>If you always expect the item will exist then use <code>get</code>, but if you expect it not to exist a reasonable proportion of the time (i.e. it not existing is an expected result rather than an exceptional result) then I'd suggest using <code>filter</code>.</p>
<p>So, seeing as you indicated that between 1 in 2 and 1 in 4 are expected not to exist, I'd definitely write a wrapper around <code>filter</code>, as that's definitely not an exceptional case.</p>
| 5 | 2009-01-03T18:25:14Z | [
"python",
"django",
"exception"
] |
Avoid exceptions? | 409,529 | <p>This particular example relates to Django in Python, but should apply to any language supporting exceptions:</p>
<pre><code>try:
object = ModelClass.objects.get(search=value)
except DoesNotExist:
pass
if object:
# do stuff
</code></pre>
<p>The Django model class provides a simple method <em>get</em> which allows me to search for <em>one and only one</em> object from the database, if it finds more or less it raises an exception. If can find zero or more with an alternative <em>filter</em> method, which returns a list:</p>
<pre><code>objects = ModelClass.objects.filter(search=value)
if len(objects) == 1:
object = objects[0]
# do stuff
</code></pre>
<p><strong>Am I overly averse to exceptions?</strong> To me the exception seems a little wasteful, at a guess, a quarter-to-a-half of the time will be 'exceptional'. I'd much prefer a function that returns <em>None</em> on failure. Would I be better to use Django's <em>filter</em> method and process the list myself?</p>
| 8 | 2009-01-03T18:19:50Z | 409,542 | <p>The answer will depend on the intent of the code. (I'm not sure what your code sample was meant to do, the pass in the exceptional case is confusing, what will the rest of the code do with <code>object</code> variable to work with?)</p>
<p>Whether to use exceptions or to use a method which treat the case as non-exceptional is a matter of taste in many cases. Certainly if the real code in the except clause is as complicated as the filter method you'd have to use to avoid the exception, then use the filter method. Simpler code is better code.</p>
| 2 | 2009-01-03T18:26:10Z | [
"python",
"django",
"exception"
] |
Avoid exceptions? | 409,529 | <p>This particular example relates to Django in Python, but should apply to any language supporting exceptions:</p>
<pre><code>try:
object = ModelClass.objects.get(search=value)
except DoesNotExist:
pass
if object:
# do stuff
</code></pre>
<p>The Django model class provides a simple method <em>get</em> which allows me to search for <em>one and only one</em> object from the database, if it finds more or less it raises an exception. If can find zero or more with an alternative <em>filter</em> method, which returns a list:</p>
<pre><code>objects = ModelClass.objects.filter(search=value)
if len(objects) == 1:
object = objects[0]
# do stuff
</code></pre>
<p><strong>Am I overly averse to exceptions?</strong> To me the exception seems a little wasteful, at a guess, a quarter-to-a-half of the time will be 'exceptional'. I'd much prefer a function that returns <em>None</em> on failure. Would I be better to use Django's <em>filter</em> method and process the list myself?</p>
| 8 | 2009-01-03T18:19:50Z | 409,545 | <p>I agree with the other answer but I wanted to add that exception passing like this is going to give you a very noticeable performance hit. Highly recommended that you check to see if the result exists (if that's what filter does) instead of passing on exceptions.</p>
<p><hr /></p>
<p>Edit:</p>
<p>In response to request for numbers on this, I ran this simple test...</p>
<pre><code>import time
def timethis(func, list, num):
st=time.time()
for i in xrange(0,1000000):
try:
func(list,num)
except:
pass
et = time.time()
print "Took %gs" % (et-st)
def check(list, num):
if num < len(list):
return list[num]
else:
return None
a=[1]
timethis(check, a, 1)
timethis(lambda x,y:x[y], a, 1)
</code></pre>
<p>And the output was..</p>
<pre><code>Took 0.772558s
Took 3.4512s
</code></pre>
<p>HTH.</p>
| 3 | 2009-01-03T18:27:19Z | [
"python",
"django",
"exception"
] |
Avoid exceptions? | 409,529 | <p>This particular example relates to Django in Python, but should apply to any language supporting exceptions:</p>
<pre><code>try:
object = ModelClass.objects.get(search=value)
except DoesNotExist:
pass
if object:
# do stuff
</code></pre>
<p>The Django model class provides a simple method <em>get</em> which allows me to search for <em>one and only one</em> object from the database, if it finds more or less it raises an exception. If can find zero or more with an alternative <em>filter</em> method, which returns a list:</p>
<pre><code>objects = ModelClass.objects.filter(search=value)
if len(objects) == 1:
object = objects[0]
# do stuff
</code></pre>
<p><strong>Am I overly averse to exceptions?</strong> To me the exception seems a little wasteful, at a guess, a quarter-to-a-half of the time will be 'exceptional'. I'd much prefer a function that returns <em>None</em> on failure. Would I be better to use Django's <em>filter</em> method and process the list myself?</p>
| 8 | 2009-01-03T18:19:50Z | 409,586 | <p>Aversion to excpetions is a matter of opinion - however, if there's reason to believe that a function or method is going to be called many times or called rapidly, exceptions will cause a significant slowdown. I learned this from my <a href="http://stackoverflow.com/questions/395599/java-graphic-library-for-multicoloured-text">previous question</a>, where I was previously relying on a thrown exception to return a default value rather than doing parameter checking to return that default.</p>
<p>Of course, exceptions can still exist for any reason, and you shouldn't be afraid to use or throw one if necessary - especially ones that could potentially break the normal flow of the calling function.</p>
| 2 | 2009-01-03T18:57:31Z | [
"python",
"django",
"exception"
] |
Avoid exceptions? | 409,529 | <p>This particular example relates to Django in Python, but should apply to any language supporting exceptions:</p>
<pre><code>try:
object = ModelClass.objects.get(search=value)
except DoesNotExist:
pass
if object:
# do stuff
</code></pre>
<p>The Django model class provides a simple method <em>get</em> which allows me to search for <em>one and only one</em> object from the database, if it finds more or less it raises an exception. If can find zero or more with an alternative <em>filter</em> method, which returns a list:</p>
<pre><code>objects = ModelClass.objects.filter(search=value)
if len(objects) == 1:
object = objects[0]
# do stuff
</code></pre>
<p><strong>Am I overly averse to exceptions?</strong> To me the exception seems a little wasteful, at a guess, a quarter-to-a-half of the time will be 'exceptional'. I'd much prefer a function that returns <em>None</em> on failure. Would I be better to use Django's <em>filter</em> method and process the list myself?</p>
| 8 | 2009-01-03T18:19:50Z | 409,704 | <p>There's a big schism in programming languages around the use of exceptions.</p>
<ul>
<li><p>The majority view is that <strong>exceptions should be exceptional</strong>. In most languages with exceptions, transfer of control by exception is considerably more expensive than by procedure return, for example.</p></li>
<li><p>There is a strong minority view that exceptions are just another control-flow construct, and they should be cheap. The <a href="http://www.smlnj.org/">Standard ML of New Jersey</a> and <a href="http://caml.inria.fr/">Objective Caml</a> compilers subscribe to that view. If you have cheap exceptions you can code some fancy backtracking algorithms in ways that are more difficult to code cleanly using other mechanisms.</p></li>
</ul>
<p>I've seen this debate repeated many times for new language designs, and almost always, the winner decides that exceptions should be expensive and rare. When you care about performanced, you'd be wise to program with this in mind.</p>
| 7 | 2009-01-03T19:52:37Z | [
"python",
"django",
"exception"
] |
Avoid exceptions? | 409,529 | <p>This particular example relates to Django in Python, but should apply to any language supporting exceptions:</p>
<pre><code>try:
object = ModelClass.objects.get(search=value)
except DoesNotExist:
pass
if object:
# do stuff
</code></pre>
<p>The Django model class provides a simple method <em>get</em> which allows me to search for <em>one and only one</em> object from the database, if it finds more or less it raises an exception. If can find zero or more with an alternative <em>filter</em> method, which returns a list:</p>
<pre><code>objects = ModelClass.objects.filter(search=value)
if len(objects) == 1:
object = objects[0]
# do stuff
</code></pre>
<p><strong>Am I overly averse to exceptions?</strong> To me the exception seems a little wasteful, at a guess, a quarter-to-a-half of the time will be 'exceptional'. I'd much prefer a function that returns <em>None</em> on failure. Would I be better to use Django's <em>filter</em> method and process the list myself?</p>
| 8 | 2009-01-03T18:19:50Z | 410,115 | <p>Believe it or not, this actually is an issue that is a bit different in each language. In Python, exceptions are regularly thrown for events that aren't exceptional by the language itself. Thus I think that the "you should only throw exceptions under exceptional circumstances" rule doesn't quite apply. I think the results you'll get on this forum will be slanted towards that point of view though, considering the high number of .Net programmers (see <a href="http://stackoverflow.com/questions/351400/why-are-net-programmers-so-afraid-of-exceptions">this question</a>) for more info on that).</p>
<p>At a very minimum, I'd better not catch anyone who sticks to that rule ever using a generator or a for loop in Python (both of which involve throwing exceptions for non-exceptional circumstances).</p>
| 8 | 2009-01-03T23:57:18Z | [
"python",
"django",
"exception"
] |
Avoid exceptions? | 409,529 | <p>This particular example relates to Django in Python, but should apply to any language supporting exceptions:</p>
<pre><code>try:
object = ModelClass.objects.get(search=value)
except DoesNotExist:
pass
if object:
# do stuff
</code></pre>
<p>The Django model class provides a simple method <em>get</em> which allows me to search for <em>one and only one</em> object from the database, if it finds more or less it raises an exception. If can find zero or more with an alternative <em>filter</em> method, which returns a list:</p>
<pre><code>objects = ModelClass.objects.filter(search=value)
if len(objects) == 1:
object = objects[0]
# do stuff
</code></pre>
<p><strong>Am I overly averse to exceptions?</strong> To me the exception seems a little wasteful, at a guess, a quarter-to-a-half of the time will be 'exceptional'. I'd much prefer a function that returns <em>None</em> on failure. Would I be better to use Django's <em>filter</em> method and process the list myself?</p>
| 8 | 2009-01-03T18:19:50Z | 411,070 | <p>I disagree with the above comments that an exception is inefficient in this instance, especially since it's being used in an I/O bound operation.</p>
<p>Here's a more realistic example using Django with an in-memory sqlite database. Each of a 100 different queries was run, then averaged for each of a 100 runs. Although I doubt if it would matter, I also changed the order of execution.</p>
<pre><code>With ObjectDoesNotExist... 0.102783939838
Without exception ........ 0.105322141647
With ObjectDoesNotExist... 0.102762134075
Without exception ........ 0.101523952484
With ObjectDoesNotExist... 0.100004930496
Without exception ........ 0.107946784496
</code></pre>
<p>You can instrument this in your own Django environment, but I doubt if your time is well spent avoiding this exception.</p>
| 2 | 2009-01-04T14:35:42Z | [
"python",
"django",
"exception"
] |
What versions of Python and wxPython correspond to each version of OSX? | 409,677 | <p>I'd like to know what versions of Python and wxPython correspond to each version of OSX. I'm interested to know exactly how far back some of my apps will remain compatible on a mac before having to install newer versions of Python and wxPython.</p>
| 0 | 2009-01-03T19:37:41Z | 409,702 | <p>Tiger shipped with Python 2.3.5 and wxPython 2.5.3, Leopard ships with python 2.5.1 and wxPython 2.8.4.</p>
<p>wxPython was not shipped with previous versions.</p>
<hr>
<p>OSX Lion has 2.7.1</p>
| 3 | 2009-01-03T19:49:20Z | [
"python",
"osx",
"wxpython",
"compatibility"
] |
Python: Alter elements of a list | 409,732 | <p>I have a list of booleans where occasionally I reset them all to false. After first writing the reset as:</p>
<pre><code>for b in bool_list:
b = False
</code></pre>
<p>I found it doesn't work. I spent a moment scratching my head, then remembered that of course it won't work since I'm only changing a reference to the bool, not its value. So I rewrote as:</p>
<pre><code>for i in xrange(len(bool_list)):
bool_list[i] = False
</code></pre>
<p>and everything works fine. But I found myself asking, "Is that really the most pythonic way to alter all elements of a list?" Are there other ways that manage to be either more efficient or clearer?</p>
| 15 | 2009-01-03T20:07:28Z | 409,744 | <p>If you only have one reference to the list, the following may be easier:</p>
<pre><code>bool_list = [False] * len(bool_list)
</code></pre>
<p>This creates a new list populated with <code>False</code> elements.</p>
<p>See my answer to <a href="http://stackoverflow.com/questions/369898/python-dictionary-clear#369925">Python dictionary clear</a> for a similar example.</p>
| 13 | 2009-01-03T20:13:14Z | [
"python",
"coding-style"
] |
Python: Alter elements of a list | 409,732 | <p>I have a list of booleans where occasionally I reset them all to false. After first writing the reset as:</p>
<pre><code>for b in bool_list:
b = False
</code></pre>
<p>I found it doesn't work. I spent a moment scratching my head, then remembered that of course it won't work since I'm only changing a reference to the bool, not its value. So I rewrote as:</p>
<pre><code>for i in xrange(len(bool_list)):
bool_list[i] = False
</code></pre>
<p>and everything works fine. But I found myself asking, "Is that really the most pythonic way to alter all elements of a list?" Are there other ways that manage to be either more efficient or clearer?</p>
| 15 | 2009-01-03T20:07:28Z | 409,745 | <p>I wouldn't use the range and len. It's a lot cleaner to use enumerate()</p>
<pre><code>for i, v in enumerate(bool_list): #i, v = index and value
bool_list[i] = False
</code></pre>
<p>It's left with an unused variable in this case, but it still looks cleaner in my opinion. There's no noticeable change in performance either.</p>
| 3 | 2009-01-03T20:13:52Z | [
"python",
"coding-style"
] |
Python: Alter elements of a list | 409,732 | <p>I have a list of booleans where occasionally I reset them all to false. After first writing the reset as:</p>
<pre><code>for b in bool_list:
b = False
</code></pre>
<p>I found it doesn't work. I spent a moment scratching my head, then remembered that of course it won't work since I'm only changing a reference to the bool, not its value. So I rewrote as:</p>
<pre><code>for i in xrange(len(bool_list)):
bool_list[i] = False
</code></pre>
<p>and everything works fine. But I found myself asking, "Is that really the most pythonic way to alter all elements of a list?" Are there other ways that manage to be either more efficient or clearer?</p>
| 15 | 2009-01-03T20:07:28Z | 409,746 | <p>For value types such as int, bool and string, your 2nd example is about as pretty as its going to get. Your first example will work on any reference types like classes, dicts, or other lists.</p>
| 0 | 2009-01-03T20:14:17Z | [
"python",
"coding-style"
] |
Python: Alter elements of a list | 409,732 | <p>I have a list of booleans where occasionally I reset them all to false. After first writing the reset as:</p>
<pre><code>for b in bool_list:
b = False
</code></pre>
<p>I found it doesn't work. I spent a moment scratching my head, then remembered that of course it won't work since I'm only changing a reference to the bool, not its value. So I rewrote as:</p>
<pre><code>for i in xrange(len(bool_list)):
bool_list[i] = False
</code></pre>
<p>and everything works fine. But I found myself asking, "Is that really the most pythonic way to alter all elements of a list?" Are there other ways that manage to be either more efficient or clearer?</p>
| 15 | 2009-01-03T20:07:28Z | 409,759 | <p>If you're willing to use <a href="http://numpy.scipy.org/" rel="nofollow">numpy</a> arrays, it's actually really easy to do things like this using array slices.</p>
<pre><code>import numpy
bool_list = numpy.zeros((100,), dtype=numpy.bool)
# do something interesting with bool_list as if it were a normal list
bool_list[:] = False
# all elements have been reset to False now
</code></pre>
| 4 | 2009-01-03T20:26:03Z | [
"python",
"coding-style"
] |
Python: Alter elements of a list | 409,732 | <p>I have a list of booleans where occasionally I reset them all to false. After first writing the reset as:</p>
<pre><code>for b in bool_list:
b = False
</code></pre>
<p>I found it doesn't work. I spent a moment scratching my head, then remembered that of course it won't work since I'm only changing a reference to the bool, not its value. So I rewrote as:</p>
<pre><code>for i in xrange(len(bool_list)):
bool_list[i] = False
</code></pre>
<p>and everything works fine. But I found myself asking, "Is that really the most pythonic way to alter all elements of a list?" Are there other ways that manage to be either more efficient or clearer?</p>
| 15 | 2009-01-03T20:07:28Z | 409,764 | <p>Here's another version:</p>
<pre><code>bool_list = [False for item in bool_list]
</code></pre>
| 13 | 2009-01-03T20:30:42Z | [
"python",
"coding-style"
] |
Python: Alter elements of a list | 409,732 | <p>I have a list of booleans where occasionally I reset them all to false. After first writing the reset as:</p>
<pre><code>for b in bool_list:
b = False
</code></pre>
<p>I found it doesn't work. I spent a moment scratching my head, then remembered that of course it won't work since I'm only changing a reference to the bool, not its value. So I rewrote as:</p>
<pre><code>for i in xrange(len(bool_list)):
bool_list[i] = False
</code></pre>
<p>and everything works fine. But I found myself asking, "Is that really the most pythonic way to alter all elements of a list?" Are there other ways that manage to be either more efficient or clearer?</p>
| 15 | 2009-01-03T20:07:28Z | 410,017 | <p>I think </p>
<pre><code>bool_list = [False for element in bool_list]
</code></pre>
<p>is as pythonic as it gets. Using lists like this should generaly be faster then a for loop in python too.</p>
| 0 | 2009-01-03T22:39:19Z | [
"python",
"coding-style"
] |
Python: Alter elements of a list | 409,732 | <p>I have a list of booleans where occasionally I reset them all to false. After first writing the reset as:</p>
<pre><code>for b in bool_list:
b = False
</code></pre>
<p>I found it doesn't work. I spent a moment scratching my head, then remembered that of course it won't work since I'm only changing a reference to the bool, not its value. So I rewrote as:</p>
<pre><code>for i in xrange(len(bool_list)):
bool_list[i] = False
</code></pre>
<p>and everything works fine. But I found myself asking, "Is that really the most pythonic way to alter all elements of a list?" Are there other ways that manage to be either more efficient or clearer?</p>
| 15 | 2009-01-03T20:07:28Z | 410,067 | <pre><code>bool_list[:] = [False] * len(bool_list)
</code></pre>
<p>or</p>
<pre><code>bool_list[:] = [False for item in bool_list]
</code></pre>
| 11 | 2009-01-03T23:11:59Z | [
"python",
"coding-style"
] |
Python: Alter elements of a list | 409,732 | <p>I have a list of booleans where occasionally I reset them all to false. After first writing the reset as:</p>
<pre><code>for b in bool_list:
b = False
</code></pre>
<p>I found it doesn't work. I spent a moment scratching my head, then remembered that of course it won't work since I'm only changing a reference to the bool, not its value. So I rewrote as:</p>
<pre><code>for i in xrange(len(bool_list)):
bool_list[i] = False
</code></pre>
<p>and everything works fine. But I found myself asking, "Is that really the most pythonic way to alter all elements of a list?" Are there other ways that manage to be either more efficient or clearer?</p>
| 15 | 2009-01-03T20:07:28Z | 410,213 | <p><strong>Summary</strong>
Performance-wise, numpy or a list multiplication are clear winners, as they are 10-20x faster than other approaches.</p>
<p>I did some performance testing on the various options proposed. I used Python 2.5.2, on Linux (Ubuntu 8.10), with a 1.5 Ghz Pentium M.</p>
<p><strong>Original:</strong></p>
<pre><code>python timeit.py -s 'bool_list = [True] * 1000' 'for x in xrange(len(bool_list)): bool_list[x] = False'
</code></pre>
<p>1000 loops, best of 3: 280 usec per loop</p>
<p><strong>Slice-based replacement with a list comprehension:</strong></p>
<pre><code>python timeit.py -s 'bool_list = [True] * 1000' 'bool_list[:] = [False for element in bool_list]'
</code></pre>
<p>1000 loops, best of 3: 215 usec per loop</p>
<p><strong>Slice-based replacement with a generator comprehension:</strong></p>
<pre><code>python timeit.py -s 'bool_list = [True] * 1000' 'bool_list[:] = (False for element in bool_list)'
</code></pre>
<p>1000 loops, best of 3: 265 usec per loop</p>
<p><strong>Enumerate</strong>:</p>
<pre><code>python timeit.py -s 'bool_list = [True] * 1000' 'for i, v in enumerate(bool_list): bool_list[i] = False'
</code></pre>
<p>1000 loops, best of 3: 385 usec per loop</p>
<p><strong>Numpy</strong>:</p>
<pre><code>python timeit.py -s 'import numpy' -s 'bool_list = numpy.zeros((1000,), dtype=numpy.bool)' 'bool_list[:] = False'
</code></pre>
<p>10000 loops, best of 3: 15.9 usec per loop</p>
<p><strong>Slice-based replacement with list multiplication:</strong></p>
<pre><code>python timeit.py -s 'bool_list = [True] * 1000' 'bool_list[:] = [False] * len(bool_list)'
</code></pre>
<p>10000 loops, best of 3: 23.3 usec per loop</p>
<p><strong>Reference replacement with list multiplication</strong></p>
<pre><code> python timeit.py -s 'bool_list = [True] * 1000' 'bool_list = [False] * len(bool_list)'
</code></pre>
<p>10000 loops, best of 3: 11.3 usec per loop</p>
| 12 | 2009-01-04T01:09:25Z | [
"python",
"coding-style"
] |
Parsing fixed-format data embedded in HTML in python | 409,769 | <p>I am using google's appengine api</p>
<pre><code>from google.appengine.api import urlfetch
</code></pre>
<p>to fetch a webpage. The result of</p>
<pre><code>result = urlfetch.fetch("http://www.example.com/index.html")
</code></pre>
<p>is a string of the html content (in result.content). The problem is the data that I want to parse is not really in HTML form, so I don't think using a python HTML parser will work for me. I need to parse all of the plain text in the body of the html document. The only problem is that urlfetch returns a single string of the entire HTML document, removing all newlines and extra spaces.</p>
<p><strong>EDIT:</strong>
Okay, I tried fetching a different URL and apparently urlfetch does not strip the newlines, it was the original webpage I was trying to parse that served the HTML file that way...
<strong>END EDIT</strong></p>
<p>If the document is something like this:</p>
<pre><code><html><head></head><body>
AAA 123 888 2008-10-30 ABC
BBB 987 332 2009-01-02 JSE
...
A4A 288 AAA
</body></html>
</code></pre>
<p>result.content will be this, after urlfetch fetches it:</p>
<pre><code>'<html><head></head><body>AAA 123 888 2008-10-30 ABCBBB 987 2009-01-02 JSE...A4A 288 AAA</body></html>'
</code></pre>
<p>Using an HTML parser will not help me with the data between the body tags, so I was going to use regular expresions to parse my data, but as you can see the last part of one line gets combined with the first part of the next line, and I don't know how to split it. I tried</p>
<pre><code>result.content.split('\n')
</code></pre>
<p>and</p>
<pre><code>result.content.split('\r')
</code></pre>
<p>but the resulting list was all just 1 element. I don't see any options in google's urlfetch function to not remove newlines.</p>
<p>Any ideas how I can parse this data? Maybe I need to fetch it differently?</p>
<p>Thanks in advance!</p>
| 0 | 2009-01-03T20:32:20Z | 409,780 | <p>Only suggestion I can think of is to parse it as if it has fixed width columns. Newlines are not taken into consideration for HTML. </p>
<p>If you have control of the source data, put it into a text file rather than HTML.</p>
| 2 | 2009-01-03T20:36:30Z | [
"python",
"html",
"google-app-engine",
"parsing",
"html-content-extraction"
] |
Parsing fixed-format data embedded in HTML in python | 409,769 | <p>I am using google's appengine api</p>
<pre><code>from google.appengine.api import urlfetch
</code></pre>
<p>to fetch a webpage. The result of</p>
<pre><code>result = urlfetch.fetch("http://www.example.com/index.html")
</code></pre>
<p>is a string of the html content (in result.content). The problem is the data that I want to parse is not really in HTML form, so I don't think using a python HTML parser will work for me. I need to parse all of the plain text in the body of the html document. The only problem is that urlfetch returns a single string of the entire HTML document, removing all newlines and extra spaces.</p>
<p><strong>EDIT:</strong>
Okay, I tried fetching a different URL and apparently urlfetch does not strip the newlines, it was the original webpage I was trying to parse that served the HTML file that way...
<strong>END EDIT</strong></p>
<p>If the document is something like this:</p>
<pre><code><html><head></head><body>
AAA 123 888 2008-10-30 ABC
BBB 987 332 2009-01-02 JSE
...
A4A 288 AAA
</body></html>
</code></pre>
<p>result.content will be this, after urlfetch fetches it:</p>
<pre><code>'<html><head></head><body>AAA 123 888 2008-10-30 ABCBBB 987 2009-01-02 JSE...A4A 288 AAA</body></html>'
</code></pre>
<p>Using an HTML parser will not help me with the data between the body tags, so I was going to use regular expresions to parse my data, but as you can see the last part of one line gets combined with the first part of the next line, and I don't know how to split it. I tried</p>
<pre><code>result.content.split('\n')
</code></pre>
<p>and</p>
<pre><code>result.content.split('\r')
</code></pre>
<p>but the resulting list was all just 1 element. I don't see any options in google's urlfetch function to not remove newlines.</p>
<p>Any ideas how I can parse this data? Maybe I need to fetch it differently?</p>
<p>Thanks in advance!</p>
| 0 | 2009-01-03T20:32:20Z | 409,844 | <p>I understand that the format of the document is the one you have posted. In that case, I agree that a parser like <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a> may not be a good solution.</p>
<p>I assume that you are already getting the interesting data (between the BODY tags) with a regular expression like</p>
<pre><code>import re
data = re.findall('<body>([^\<]*)</body>', result)[0]
</code></pre>
<p>then, it should be as easy as:</p>
<pre><code>start = 0
end = 5
while (end<len(data)):
print data[start:end]
start = end+1
end = end+5
print data[start:]
</code></pre>
<p>(note: I did not check this code against boundary cases, and I do expect it to fail. It is only here to show the generic idea)</p>
| 2 | 2009-01-03T21:13:07Z | [
"python",
"html",
"google-app-engine",
"parsing",
"html-content-extraction"
] |
Parsing fixed-format data embedded in HTML in python | 409,769 | <p>I am using google's appengine api</p>
<pre><code>from google.appengine.api import urlfetch
</code></pre>
<p>to fetch a webpage. The result of</p>
<pre><code>result = urlfetch.fetch("http://www.example.com/index.html")
</code></pre>
<p>is a string of the html content (in result.content). The problem is the data that I want to parse is not really in HTML form, so I don't think using a python HTML parser will work for me. I need to parse all of the plain text in the body of the html document. The only problem is that urlfetch returns a single string of the entire HTML document, removing all newlines and extra spaces.</p>
<p><strong>EDIT:</strong>
Okay, I tried fetching a different URL and apparently urlfetch does not strip the newlines, it was the original webpage I was trying to parse that served the HTML file that way...
<strong>END EDIT</strong></p>
<p>If the document is something like this:</p>
<pre><code><html><head></head><body>
AAA 123 888 2008-10-30 ABC
BBB 987 332 2009-01-02 JSE
...
A4A 288 AAA
</body></html>
</code></pre>
<p>result.content will be this, after urlfetch fetches it:</p>
<pre><code>'<html><head></head><body>AAA 123 888 2008-10-30 ABCBBB 987 2009-01-02 JSE...A4A 288 AAA</body></html>'
</code></pre>
<p>Using an HTML parser will not help me with the data between the body tags, so I was going to use regular expresions to parse my data, but as you can see the last part of one line gets combined with the first part of the next line, and I don't know how to split it. I tried</p>
<pre><code>result.content.split('\n')
</code></pre>
<p>and</p>
<pre><code>result.content.split('\r')
</code></pre>
<p>but the resulting list was all just 1 element. I don't see any options in google's urlfetch function to not remove newlines.</p>
<p>Any ideas how I can parse this data? Maybe I need to fetch it differently?</p>
<p>Thanks in advance!</p>
| 0 | 2009-01-03T20:32:20Z | 410,142 | <p>Once you have the body text as a single, long string, you can break it up as follows.
This presumes that each record is 26 characters.</p>
<pre><code>body= "AAA 123 888 2008-10-30 ABCBBB 987 2009-01-02 JSE...A4A 288 AAA"
for i in range(0,len(body),26):
line= body[i:i+26]
# parse the line
</code></pre>
| 1 | 2009-01-04T00:18:04Z | [
"python",
"html",
"google-app-engine",
"parsing",
"html-content-extraction"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.