title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Downloading file using IE from python | 1,398,780 | <p>I'm trying to download file with Python using IE:</p>
<pre><code>from win32com.client import DispatchWithEvents
class EventHandler(object):
def OnDownloadBegin(self):
pass
ie = DispatchWithEvents("InternetExplorer.Application", EventHandler)
ie.Visible = 0
ie.Navigate('http://website/file.xml')
</code></pre>
<p>After this, I'm getting a window asking the user where to save the file. How can I save this file automatically from python?</p>
<p>I need to <strong>use some browser</strong>, not urllib or mechanize, because <strong>before downloading file I need to interact with some ajax functionality</strong>.</p>
| 7 | 2009-09-09T10:18:42Z | 4,571,068 | <p>One option could also be to embed your own browser.</p>
<p>Thats e.g. possible with Qt via <a href="http://www.riverbankcomputing.co.uk/software/pyqt/intro" rel="nofollow">PyQt</a> (GPL) or <a href="http://www.pyside.org/" rel="nofollow">PySide</a> (LGPL). There you could embed the WebKit engine. You could then either display the page in a <a href="http://doc.trolltech.com/latest/qwebview.html#details" rel="nofollow">QWebView</a> and let the user navigate to your download and filter that event or use a simple <a href="http://doc.trolltech.com/latest/qwebpage.html#details" rel="nofollow">QWebPage</a> where everything could be automated and nothing has to be shown at all.</p>
<p>And <a href="http://en.wikipedia.org/wiki/Webkit" rel="nofollow">WebKit</a> should be mighty enough to do anything you want.</p>
<p>Very basic example:</p>
<pre><code>import sys
from PySide import QtCore, QtGui, QtWebKit
url = 'http://developer.qt.nokia.com/wiki/PySideDownloads/'
class TestKit(QtCore.QObject):
def __init__(self, app):
self.page = QtWebKit.QWebPage()
self.page.loadFinished.connect(self.finished)
self.page.mainFrame().load(QtCore.QUrl(url))
self.app = app
def finished(self, evt):
# inspect DOM -> navigate to next page or download
print self.page.currentFrame().documentElement().toInnerXml().encode(
'utf-8')
# when everything is done
self.app.quit()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
t = TestKit(app)
sys.exit(app.exec_())
</code></pre>
| 1 | 2010-12-31T16:12:17Z | [
"python",
"internet-explorer",
"com"
] |
Downloading file using IE from python | 1,398,780 | <p>I'm trying to download file with Python using IE:</p>
<pre><code>from win32com.client import DispatchWithEvents
class EventHandler(object):
def OnDownloadBegin(self):
pass
ie = DispatchWithEvents("InternetExplorer.Application", EventHandler)
ie.Visible = 0
ie.Navigate('http://website/file.xml')
</code></pre>
<p>After this, I'm getting a window asking the user where to save the file. How can I save this file automatically from python?</p>
<p>I need to <strong>use some browser</strong>, not urllib or mechanize, because <strong>before downloading file I need to interact with some ajax functionality</strong>.</p>
| 7 | 2009-09-09T10:18:42Z | 4,573,966 | <p><a href="http://pamie.sourceforge.net/" rel="nofollow">pamie</a> perhaps</p>
<blockquote>
<p>P.A.M.I.E. - stands for Python
Automated Module For I.E.</p>
<p>Pamie's main use is for testing web
sites by which you automate the
Internet Explorer client using the
Pamie scripting language. PAMIE is
not a record playback engine!</p>
<p>Pamie allows you to automate I.E. by
manipulating I.E.'s Document Object
Model via COM. This Free tool is for
use by Quality Assurance Engineers
and Developers.</p>
</blockquote>
| 2 | 2011-01-01T11:54:16Z | [
"python",
"internet-explorer",
"com"
] |
Downloading file using IE from python | 1,398,780 | <p>I'm trying to download file with Python using IE:</p>
<pre><code>from win32com.client import DispatchWithEvents
class EventHandler(object):
def OnDownloadBegin(self):
pass
ie = DispatchWithEvents("InternetExplorer.Application", EventHandler)
ie.Visible = 0
ie.Navigate('http://website/file.xml')
</code></pre>
<p>After this, I'm getting a window asking the user where to save the file. How can I save this file automatically from python?</p>
<p>I need to <strong>use some browser</strong>, not urllib or mechanize, because <strong>before downloading file I need to interact with some ajax functionality</strong>.</p>
| 7 | 2009-09-09T10:18:42Z | 4,590,561 | <p>This works for me as long as the IE dialogs are in the foreground and the downloaded file does not already exist in the "Save As" directory:</p>
<pre><code>import time
import threading
import win32ui, win32gui, win32com, pythoncom, win32con
from win32com.client import Dispatch
class IeThread(threading.Thread):
def run(self):
pythoncom.CoInitialize()
ie = Dispatch("InternetExplorer.Application")
ie.Visible = 0
ie.Navigate('http://website/file.xml')
def PushButton(handle, label):
if win32gui.GetWindowText(handle) == label:
win32gui.SendMessage(handle, win32con.BM_CLICK, None, None)
return True
IeThread().start()
time.sleep(3) # wait until IE is started
wnd = win32ui.GetForegroundWindow()
if wnd.GetWindowText() == "File Download - Security Warning":
win32gui.EnumChildWindows(wnd.GetSafeHwnd(), PushButton, "&Save");
time.sleep(1)
wnd = win32ui.GetForegroundWindow()
if wnd.GetWindowText() == "Save As":
win32gui.EnumChildWindows(wnd.GetSafeHwnd(), PushButton, "&Save");
</code></pre>
| 7 | 2011-01-04T04:08:48Z | [
"python",
"internet-explorer",
"com"
] |
Downloading file using IE from python | 1,398,780 | <p>I'm trying to download file with Python using IE:</p>
<pre><code>from win32com.client import DispatchWithEvents
class EventHandler(object):
def OnDownloadBegin(self):
pass
ie = DispatchWithEvents("InternetExplorer.Application", EventHandler)
ie.Visible = 0
ie.Navigate('http://website/file.xml')
</code></pre>
<p>After this, I'm getting a window asking the user where to save the file. How can I save this file automatically from python?</p>
<p>I need to <strong>use some browser</strong>, not urllib or mechanize, because <strong>before downloading file I need to interact with some ajax functionality</strong>.</p>
| 7 | 2009-09-09T10:18:42Z | 17,243,096 | <p>This is definitely absolutely the last way I would normally do this but today I did have to resort to banging away to get something working. I have IE 10 so @cgohlke's answer won't work (no window text). All attempts to get a proper version of Client Authentication working were failing so had to fall back on this. Maybe it'll help someone else who's equally at the end of their tether.</p>
<pre><code>import IEC
import pywinauto
import win32.com
# Creates a new IE Window
ie = IEC.IEController(window_num=0)
# Register application as an app for pywinauto
shell = win32com.client.Dispatch("WScript.Shell")
pwa_app = pywinauto.application.Application()
w_handle = pywinauto.findwindows.find_windows(title=u'<Title of the site - find it using SWAPY>', class_name='IEFrame')[0]
window = pwa_app.window_(handle=w_handle)
window.SetFocus()
# Click on the download link
ie.ClickLink(<download link>)
# Get the handle of the Open Save Cancel dialog
ctrl = window['2']
# You may need to adjust the coords here to make sure you hit the button you want
ctrl.ClickInput(button='left', coords=(495, 55), double=False, wheel_dist=0)
</code></pre>
<p>But man, is it horrible!</p>
| 0 | 2013-06-21T19:40:35Z | [
"python",
"internet-explorer",
"com"
] |
The Assignment Problem, a numpy function? | 1,398,822 | <p>Since an <a href="http://en.wikipedia.org/wiki/Assignment%5Fproblem">assignment problem</a> can be posed in the form of a single matrix, I am wandering if numpy has a function to solve such a matrix. So far I have found none. Maybe one of you guys know if numpy/scipy has an assignment-problem-solve function?</p>
<p><strong>Edit:</strong> In the meanwhile I have found a python (not numpy/scipy) implementation at <a href="http://www.clapper.org/software/python/munkres/">http://www.clapper.org/software/python/munkres/</a>. Still I suppose a numpy/scipy implementation could be much faster, right?</p>
| 6 | 2009-09-09T10:28:36Z | 1,436,399 | <p>No, NumPy contains no such function. Combinatorial optimization is outside of NumPy's scope. It may be possible to do it with one of the optimizers in <code>scipy.optimize</code> but I have a feeling that the constraints may not be of the right form.</p>
<p><a href="http://networkx.lanl.gov/" rel="nofollow">NetworkX</a> probably also includes algorithms for assignment problems.</p>
| 3 | 2009-09-17T02:09:07Z | [
"python",
"numpy",
"scipy"
] |
The Assignment Problem, a numpy function? | 1,398,822 | <p>Since an <a href="http://en.wikipedia.org/wiki/Assignment%5Fproblem">assignment problem</a> can be posed in the form of a single matrix, I am wandering if numpy has a function to solve such a matrix. So far I have found none. Maybe one of you guys know if numpy/scipy has an assignment-problem-solve function?</p>
<p><strong>Edit:</strong> In the meanwhile I have found a python (not numpy/scipy) implementation at <a href="http://www.clapper.org/software/python/munkres/">http://www.clapper.org/software/python/munkres/</a>. Still I suppose a numpy/scipy implementation could be much faster, right?</p>
| 6 | 2009-09-09T10:28:36Z | 1,510,183 | <p>There is an implementation of the <a href="http://pypi.python.org/pypi/hungarian/0.2" rel="nofollow">Munkres' algorithm</a> as a python extension module which has numpy support. I've used it successfully on my old laptop. However, it does not work on my new machine - I assume there is a problem with "new" numpy versions (or 64bit arch).</p>
| 2 | 2009-10-02T15:16:38Z | [
"python",
"numpy",
"scipy"
] |
The Assignment Problem, a numpy function? | 1,398,822 | <p>Since an <a href="http://en.wikipedia.org/wiki/Assignment%5Fproblem">assignment problem</a> can be posed in the form of a single matrix, I am wandering if numpy has a function to solve such a matrix. So far I have found none. Maybe one of you guys know if numpy/scipy has an assignment-problem-solve function?</p>
<p><strong>Edit:</strong> In the meanwhile I have found a python (not numpy/scipy) implementation at <a href="http://www.clapper.org/software/python/munkres/">http://www.clapper.org/software/python/munkres/</a>. Still I suppose a numpy/scipy implementation could be much faster, right?</p>
| 6 | 2009-09-09T10:28:36Z | 22,773,632 | <p>There is now a numpy implementation of the munkres algorithm in scikit-learn under <a href="https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/linear_assignment_.py">sklearn/utils/linear_assignment_.py</a> its only dependency is numpy. I tried it with some approximately 20x20 matrices, and it seems to be about 4 times as fast as the one linked to in the question. cProfiler shows 2.517 seconds vs 9.821 seconds for 100 iterations.</p>
| 10 | 2014-03-31T22:44:35Z | [
"python",
"numpy",
"scipy"
] |
The Assignment Problem, a numpy function? | 1,398,822 | <p>Since an <a href="http://en.wikipedia.org/wiki/Assignment%5Fproblem">assignment problem</a> can be posed in the form of a single matrix, I am wandering if numpy has a function to solve such a matrix. So far I have found none. Maybe one of you guys know if numpy/scipy has an assignment-problem-solve function?</p>
<p><strong>Edit:</strong> In the meanwhile I have found a python (not numpy/scipy) implementation at <a href="http://www.clapper.org/software/python/munkres/">http://www.clapper.org/software/python/munkres/</a>. Still I suppose a numpy/scipy implementation could be much faster, right?</p>
| 6 | 2009-09-09T10:28:36Z | 36,044,076 | <p>I was hoping that the newer <code>scipy.optimize.linear_sum_assignment</code> would be fastest, but (perhaps not surprisingly) the <a href="https://github.com/jfrelinger/cython-munkres-wrapper" rel="nofollow">Cython library</a> (which does not have pip support) is significantly faster, at least for my use case:</p>
<pre><code>$ python -m timeit -s 'from scipy.optimize import linear_sum_assignment; import numpy as np; np.random.seed(0); c = np.random.rand(20,30)' 'a,b = linear_sum_assignment(c)'
100 loops, best of 3: 3.43 msec per loop
$ python -m timeit -s 'from munkres import munkres; import numpy as np; np.random.seed(0); c = np.random.rand(20,30)' 'a = munkres(c)'
10000 loops, best of 3: 139 usec per loop
$ python -m timeit -s 'from scipy.optimize import linear_sum_assignment; import numpy as np; np.random.seed(0);' 'c = np.random.rand(20,30); a,b = linear_sum_assignment(c)'
100 loops, best of 3: 3.01 msec per loop
$ python -m timeit -s 'from munkres import munkres; import numpy as np; np.random.seed(0)' 'c = np.random.rand(20,30); a = munkres(c)'
10000 loops, best of 3: 127 usec per loop
</code></pre>
<p>I saw similar results for sizes between 2x2 and 100x120 (10-40x faster).</p>
| 1 | 2016-03-16T18:29:58Z | [
"python",
"numpy",
"scipy"
] |
Is it possible to intercept attribute getting/setting in ActionScript 3? | 1,398,890 | <p>When developing in ActionScript 3, I often find myself looking for a way to achieve something similar to what is offered by python's <code>__getattr__</code> / <code>__setattr__</code> magic methods i.e. to be able to intercept attribute lookup on an instance, and do something custom. </p>
<p>Is there some acceptable way to achieve this in ActionScript 3? In AS3 attribute lookup behaves a little differently for normal (sealed) and dynamic classes -- ideally this would work in the same way for both cases. In python this works beautifully for all kinds of objects (of course!) even for subclasses of dict itself!</p>
| -1 | 2009-09-09T10:44:49Z | 1,399,375 | <p>Look a the <code>flash.utils.Proxy</code> object.</p>
<blockquote>
<p>The Proxy class lets you override the
default behavior of ActionScript
operations (such as retrieving and
modifying properties) on an object.</p>
</blockquote>
| 0 | 2009-09-09T12:22:50Z | [
"actionscript-3",
"python"
] |
Is it possible to intercept attribute getting/setting in ActionScript 3? | 1,398,890 | <p>When developing in ActionScript 3, I often find myself looking for a way to achieve something similar to what is offered by python's <code>__getattr__</code> / <code>__setattr__</code> magic methods i.e. to be able to intercept attribute lookup on an instance, and do something custom. </p>
<p>Is there some acceptable way to achieve this in ActionScript 3? In AS3 attribute lookup behaves a little differently for normal (sealed) and dynamic classes -- ideally this would work in the same way for both cases. In python this works beautifully for all kinds of objects (of course!) even for subclasses of dict itself!</p>
| -1 | 2009-09-09T10:44:49Z | 1,405,155 | <p>in as3 you can code explicit variables' accessors.
ex Class1:</p>
<p>private var __myvar:String;</p>
<p>public function get myvar():String { return __myvar; }
public function set myvar(value:String):void { __myvar = value; }</p>
<p>now as you create an instance of Class1 you can access __myvar through the accessor functions.
if you want to set bindable that var you have to put the [Bindable] keyword upon one of its accessors.
further,
you can also implement the getter or the setter only, so your var will be read or write only.
i hope it helps ;)</p>
<p>pigiuz</p>
| 0 | 2009-09-10T13:01:02Z | [
"actionscript-3",
"python"
] |
Django : import problem with python-twitter module | 1,399,478 | <p>When I try to import python-twitter module in my app, django tries to import django.templatetags.twitter instead of python-twitter module (in /usr/lib/python2.5/site-packages/twitter.py), but I don't know why. :s</p>
<p>For example:</p>
<pre><code>myproject/
myapp/
templatetags/
file.py
</code></pre>
<p>In <code>file.py</code>:</p>
<pre><code>import twitter # this imports django.templatetags.twitter
</code></pre>
<p>Any idea to fix it ?</p>
<p>Thank you very much :)</p>
<p>Edit: I've found the problem. My templatetags file was named "twitter.py". I've renamed it to "twitter_tags.py" and now this works. :)</p>
| 2 | 2009-09-09T12:47:15Z | 1,399,576 | <blockquote>
<p>The submodules often need to refer to each other. For example, the surround module might use the echo module. In fact, such references are so common that the import statement first looks in the containing package before looking in the standard module search path. <a href="http://docs.python.org/tutorial/modules.html#intra-package-references" rel="nofollow">source</a></p>
</blockquote>
<p>Therefore, you will need to use an absolute import.</p>
<pre><code>from some.other.pkg import twitter
</code></pre>
| 1 | 2009-09-09T13:04:54Z | [
"python",
"django",
"import",
"twitter"
] |
Store django forms.MultipleChoiceField in Models directly | 1,399,622 | <p>Say I have choices defined as follows:</p>
<pre><code>choices = (('1','a'),
('2','b'),
('3','c'))
</code></pre>
<p>And a form that renders and inputs these values in a MultipleChoiceField,</p>
<pre><code>class Form1(forms.Form):
field = forms.MultipleChoiceField(choices=choices)
</code></pre>
<p>What is the right way to store <code>field</code> in a model.</p>
<p>I can of course loop through the <code>forms.cleaned_data['field']</code> and obtain a value that fits in <code>models.CommaSeperatedIntegerField</code>.</p>
<p>Again, each time I retrieve these values, I will have to loop and convert into options.</p>
<p>I think there is a better way to do so, as in this way, I am in a way re-implementing the function that CommaSeperateIntegerField is supposed to do.</p>
| 1 | 2009-09-09T13:14:55Z | 1,400,531 | <p>The first thing I would consider is better normalization of your database schema; if a single instance of your model can have multiple values for this field, the field perhaps should be a linked model with a ForeignKey instead.</p>
<p>If you're using Postgres, you could also use an ARRAY field; Django now has <a href="https://docs.djangoproject.com/en/dev/ref/contrib/postgres/fields/#arrayfield" rel="nofollow">built-in support</a>.</p>
<p>If you can't do either of those, then you do basically need to reimplement a (better) version of CommaSeparatedIntegerField. The reason is that CommaSeparatedIntegerField is nothing but <a href="http://code.djangoproject.com/browser/django/trunk/django/db/models/fields/__init__.py#L436" rel="nofollow">a plain CharField whose default formfield representation is a regex-validated text input</a>. In other words, it doesn't do anything that's useful to you.</p>
<p>What you need to write is a custom ListField or MultipleValuesField that expects a Python list and returns a Python list, but internally converts that list to/from a comma-separated string for insertion in the database. Read the <a href="http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields" rel="nofollow">documentation on custom model fields</a>; I think in your case you'll want a subclass of CharField with two methods overridden: <a href="http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#to_python" rel="nofollow">to_python</a> (convert CSV string to Python list) and <a href="http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#get_db_prep_value" rel="nofollow">get_db_prep_value</a> (convert Python list to CSV string).</p>
| 8 | 2009-09-09T15:53:43Z | [
"python",
"django",
"django-models",
"django-forms"
] |
Store django forms.MultipleChoiceField in Models directly | 1,399,622 | <p>Say I have choices defined as follows:</p>
<pre><code>choices = (('1','a'),
('2','b'),
('3','c'))
</code></pre>
<p>And a form that renders and inputs these values in a MultipleChoiceField,</p>
<pre><code>class Form1(forms.Form):
field = forms.MultipleChoiceField(choices=choices)
</code></pre>
<p>What is the right way to store <code>field</code> in a model.</p>
<p>I can of course loop through the <code>forms.cleaned_data['field']</code> and obtain a value that fits in <code>models.CommaSeperatedIntegerField</code>.</p>
<p>Again, each time I retrieve these values, I will have to loop and convert into options.</p>
<p>I think there is a better way to do so, as in this way, I am in a way re-implementing the function that CommaSeperateIntegerField is supposed to do.</p>
| 1 | 2009-09-09T13:14:55Z | 7,157,811 | <p>I just had this same problem and the solution (to me) because as Carl Meyer put it. I don't want a normalized version of this "list of strings" is to just have a CharField in the model. This way your model will store the normalized list of items. In my case this is countries.</p>
<p>So the model declaration is just</p>
<pre><code>countries = CharField(max_lenght=XXX)
</code></pre>
<p>where XXX is a precalculated value of 2x my country list. Because it's simpler for us to apply a check to see if the current country is in this list rather than do it as a M2M to a Country table.</p>
| 1 | 2011-08-23T07:52:32Z | [
"python",
"django",
"django-models",
"django-forms"
] |
Python datatype suitable for my cache | 1,399,717 | <p>I'm searching for the a datatype for a cache, basically I need the functionality of a dict, i.e. random access based on a key, which has a limited number of entries so that when the limit is reached the oldest item gets automatically removed.
Furthermore I need to be able to store it via shelve or pickle and rely on Python 2.4.
Should I subclass dict and add a list to it? Any suggestions?</p>
<p><strong>Edit:</strong><br />
I have not mentioned the scale, I need to keep track of already read items which consist of a signature by which they are identified and I only want to keep track of about a few hundred of them.
collections.deque seem nice but that's a list and I need random access. So dict would seem suitable, however somehow I need to expire items if the limit is hit which means I need to keep track the order in which they have been added.</p>
| 1 | 2009-09-09T13:33:40Z | 1,399,804 | <p>I think you answered the question yourself. You need to subclass a dict. And you also of course needs to have a list of the keys, so when the list gets too long you can purge the oldest one.</p>
<p>I would however possibly look into memcached or similar.</p>
| 1 | 2009-09-09T13:50:22Z | [
"python"
] |
Python datatype suitable for my cache | 1,399,717 | <p>I'm searching for the a datatype for a cache, basically I need the functionality of a dict, i.e. random access based on a key, which has a limited number of entries so that when the limit is reached the oldest item gets automatically removed.
Furthermore I need to be able to store it via shelve or pickle and rely on Python 2.4.
Should I subclass dict and add a list to it? Any suggestions?</p>
<p><strong>Edit:</strong><br />
I have not mentioned the scale, I need to keep track of already read items which consist of a signature by which they are identified and I only want to keep track of about a few hundred of them.
collections.deque seem nice but that's a list and I need random access. So dict would seem suitable, however somehow I need to expire items if the limit is hit which means I need to keep track the order in which they have been added.</p>
| 1 | 2009-09-09T13:33:40Z | 1,400,249 | <p>You probably want an LRU cache (one where "oldest" is measured by "least recently accessed" as opposed to "least recently obtained") -- for most access patterns it performs MUCH better than a naive "oldest goes first" cache (an extremely popular item may easily be the oldest one obtained, but half the recent hits go to it -- how silly to evict it just because it was obtained a long time ago, when it's SO popular!-). Read up on caching in general at <a href="http://en.wikipedia.org/wiki/Cache%5Falgorithms" rel="nofollow">wikipedia</a>.</p>
<p>LRU is tricky to program in solid and well-performing ways; I recommend you download, install and reuse <a href="http://evan.prodromou.name/Software/Python/LRUCache" rel="nofollow">lrucache</a> instead. If it doesn't match all of your needs exactly, it's easier to tweak existing code than to start from scratch on a tricky subject. </p>
| 1 | 2009-09-09T14:56:10Z | [
"python"
] |
Python: convert free text to date | 1,399,727 | <p>Assuming the text is typed at the same time in the same (Israeli) timezone, The following free text lines are equivalent:</p>
<pre><code>Wed Sep 9 16:26:57 IDT 2009
2009-09-09 16:26:57
16:26:57
September 9th, 16:26:57
</code></pre>
<p>Is there a python module that would convert all these text-dates to an (identical) <code>datetime.datetime</code> instance?</p>
<p>I would like to use it in a command-line tool that would get a freetext date and time as an argument, and return the equivalent date and time in different time zones, e.g.:</p>
<pre><code>~$wdate 16:00 Israel
Israel: 16:00
San Francisco: 06:00
UTC: 13:00
</code></pre>
<p>or:</p>
<pre><code>~$wdate 18:00 SanFran
San Francisco 18:00:22
Israel: 01:00:22 (Day after)
UTC: 22:00:22
</code></pre>
<p>Any Ideas?</p>
<p>Thanks,</p>
<p>Udi</p>
| 4 | 2009-09-09T13:35:46Z | 1,399,760 | <p>The <a href="http://labix.org/python-dateutil">python-dateutil</a> package sounds like it would be helpful. Your examples only use simple HH:MM timestamps with a (magically shortened) city identifier, but it seems able to handle more complicated formats like those earlier in the question, too.</p>
| 6 | 2009-09-09T13:43:57Z | [
"python",
"time",
"parsing",
"freetext"
] |
Python: convert free text to date | 1,399,727 | <p>Assuming the text is typed at the same time in the same (Israeli) timezone, The following free text lines are equivalent:</p>
<pre><code>Wed Sep 9 16:26:57 IDT 2009
2009-09-09 16:26:57
16:26:57
September 9th, 16:26:57
</code></pre>
<p>Is there a python module that would convert all these text-dates to an (identical) <code>datetime.datetime</code> instance?</p>
<p>I would like to use it in a command-line tool that would get a freetext date and time as an argument, and return the equivalent date and time in different time zones, e.g.:</p>
<pre><code>~$wdate 16:00 Israel
Israel: 16:00
San Francisco: 06:00
UTC: 13:00
</code></pre>
<p>or:</p>
<pre><code>~$wdate 18:00 SanFran
San Francisco 18:00:22
Israel: 01:00:22 (Day after)
UTC: 22:00:22
</code></pre>
<p>Any Ideas?</p>
<p>Thanks,</p>
<p>Udi</p>
| 4 | 2009-09-09T13:35:46Z | 1,399,789 | <p>You could you <a href="http://docs.python.org/library/time.html#time.strptime" rel="nofollow"><code>time.strptime</code></a></p>
<p>Like this : </p>
<pre><code>time.strptime("2009-09-09 16:26:57", "%Y-%m-%d %H:%M:%S")
</code></pre>
<p>It will return a struct_time value (more info on the python doc page).</p>
| 0 | 2009-09-09T13:48:42Z | [
"python",
"time",
"parsing",
"freetext"
] |
Python: convert free text to date | 1,399,727 | <p>Assuming the text is typed at the same time in the same (Israeli) timezone, The following free text lines are equivalent:</p>
<pre><code>Wed Sep 9 16:26:57 IDT 2009
2009-09-09 16:26:57
16:26:57
September 9th, 16:26:57
</code></pre>
<p>Is there a python module that would convert all these text-dates to an (identical) <code>datetime.datetime</code> instance?</p>
<p>I would like to use it in a command-line tool that would get a freetext date and time as an argument, and return the equivalent date and time in different time zones, e.g.:</p>
<pre><code>~$wdate 16:00 Israel
Israel: 16:00
San Francisco: 06:00
UTC: 13:00
</code></pre>
<p>or:</p>
<pre><code>~$wdate 18:00 SanFran
San Francisco 18:00:22
Israel: 01:00:22 (Day after)
UTC: 22:00:22
</code></pre>
<p>Any Ideas?</p>
<p>Thanks,</p>
<p>Udi</p>
| 4 | 2009-09-09T13:35:46Z | 1,400,141 | <p><a href="http://code.google.com/p/parsedatetime/" rel="nofollow">parsedatetime</a> seems to be a very capable module for this specific task.</p>
| 3 | 2009-09-09T14:39:12Z | [
"python",
"time",
"parsing",
"freetext"
] |
Django and monkey patching issue | 1,399,746 | <p>I have recently started experimenting with Django for some web applications in my spare time. While designing the data model for one, I came across the dilemma of using inheritance to define a user of the website or using a technique known as monkey patching with the User class already supplied by the framework.</p>
<p>I tried to add a field by means of (after having defined all my models etc. without errors, according to <code>python manage.py validate</code>):</p>
<p><code>User.add_to_class('location', models.CharField(max_length=250,blank=True))</code></p>
<p>and executed the <code>syncdb</code> command. However, I keep getting this error</p>
<blockquote>
<p>OperationalError: no such column:
auth_user.location</p>
</blockquote>
<p>whether I am in the admin view of the site or the manage.py shell. There must be an extra step I'm missing, but there seems to be limited documentation on the whole monkey patching technique. So I'm asking you for assistance before I resort to inheritance. Any code, tips, or pointers to additional documentation are of course welcome.</p>
<p>Thanks in advance.</p>
<p>PS. I'm aware this technique is ugly, and probably ill-advised. ;)</p>
| 4 | 2009-09-09T13:40:39Z | 1,399,775 | <p>Djangos framework uses metaclasses to initialize the tables. That means you can't monkey-patch in new columns, unless you also re-initialize the class, which I'm not sure is even possible. (It may be).</p>
<p>See <a href="http://stackoverflow.com/questions/1251294/difference-between-returning-modified-class-and-using-type/">http://stackoverflow.com/questions/1251294/difference-between-returning-modified-class-and-using-type/</a> for some more info.</p>
| 0 | 2009-09-09T13:46:48Z | [
"python",
"django",
"monkeypatching"
] |
Django and monkey patching issue | 1,399,746 | <p>I have recently started experimenting with Django for some web applications in my spare time. While designing the data model for one, I came across the dilemma of using inheritance to define a user of the website or using a technique known as monkey patching with the User class already supplied by the framework.</p>
<p>I tried to add a field by means of (after having defined all my models etc. without errors, according to <code>python manage.py validate</code>):</p>
<p><code>User.add_to_class('location', models.CharField(max_length=250,blank=True))</code></p>
<p>and executed the <code>syncdb</code> command. However, I keep getting this error</p>
<blockquote>
<p>OperationalError: no such column:
auth_user.location</p>
</blockquote>
<p>whether I am in the admin view of the site or the manage.py shell. There must be an extra step I'm missing, but there seems to be limited documentation on the whole monkey patching technique. So I'm asking you for assistance before I resort to inheritance. Any code, tips, or pointers to additional documentation are of course welcome.</p>
<p>Thanks in advance.</p>
<p>PS. I'm aware this technique is ugly, and probably ill-advised. ;)</p>
| 4 | 2009-09-09T13:40:39Z | 1,399,777 | <p>I guess you might run into problems regarding where is your monkeypatch defined. I guess django syncdb creates databse tables only from the "pure" auth application, so your model will then be without "location", and then your site with the patch will look for the field.</p>
<p>Probably less painful way of adding additional info to user profiles is described <a href="http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users" rel="nofollow">in Django docs</a>.</p>
| 0 | 2009-09-09T13:47:22Z | [
"python",
"django",
"monkeypatching"
] |
Django and monkey patching issue | 1,399,746 | <p>I have recently started experimenting with Django for some web applications in my spare time. While designing the data model for one, I came across the dilemma of using inheritance to define a user of the website or using a technique known as monkey patching with the User class already supplied by the framework.</p>
<p>I tried to add a field by means of (after having defined all my models etc. without errors, according to <code>python manage.py validate</code>):</p>
<p><code>User.add_to_class('location', models.CharField(max_length=250,blank=True))</code></p>
<p>and executed the <code>syncdb</code> command. However, I keep getting this error</p>
<blockquote>
<p>OperationalError: no such column:
auth_user.location</p>
</blockquote>
<p>whether I am in the admin view of the site or the manage.py shell. There must be an extra step I'm missing, but there seems to be limited documentation on the whole monkey patching technique. So I'm asking you for assistance before I resort to inheritance. Any code, tips, or pointers to additional documentation are of course welcome.</p>
<p>Thanks in advance.</p>
<p>PS. I'm aware this technique is ugly, and probably ill-advised. ;)</p>
| 4 | 2009-09-09T13:40:39Z | 1,399,788 | <p>Here's a <a href="http://www.b-list.org/weblog/2006/jun/06/django-tips-extending-user-model/" rel="nofollow">(slightly older) way of extending the <code>User</code> model</a>.</p>
<p>Here's <a href="http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users" rel="nofollow">what the docs have to say</a>.</p>
<p>And here's a <a href="http://groups.google.com/group/django-users/browse%5Fthread/thread/bb6add7b1126fcfe/f9af6cd5b4c3dcd1?lnk=gst&q=User#f9af6cd5b4c3dcd1" rel="nofollow">recent conversation on django-users</a> about the topic.</p>
| 2 | 2009-09-09T13:48:40Z | [
"python",
"django",
"monkeypatching"
] |
Django and monkey patching issue | 1,399,746 | <p>I have recently started experimenting with Django for some web applications in my spare time. While designing the data model for one, I came across the dilemma of using inheritance to define a user of the website or using a technique known as monkey patching with the User class already supplied by the framework.</p>
<p>I tried to add a field by means of (after having defined all my models etc. without errors, according to <code>python manage.py validate</code>):</p>
<p><code>User.add_to_class('location', models.CharField(max_length=250,blank=True))</code></p>
<p>and executed the <code>syncdb</code> command. However, I keep getting this error</p>
<blockquote>
<p>OperationalError: no such column:
auth_user.location</p>
</blockquote>
<p>whether I am in the admin view of the site or the manage.py shell. There must be an extra step I'm missing, but there seems to be limited documentation on the whole monkey patching technique. So I'm asking you for assistance before I resort to inheritance. Any code, tips, or pointers to additional documentation are of course welcome.</p>
<p>Thanks in advance.</p>
<p>PS. I'm aware this technique is ugly, and probably ill-advised. ;)</p>
| 4 | 2009-09-09T13:40:39Z | 1,399,813 | <p>When you add a field to any model, even if you do it the 'official' way, you need to migrate the database - Django doesn't do it for you. Drop the table and run <code>./manage.py syncdb</code> again.</p>
<p>You might want to investigate one of the migrations frameworks, such as <code>south</code>, which will manage this sort of thing for you.</p>
| 7 | 2009-09-09T13:52:26Z | [
"python",
"django",
"monkeypatching"
] |
Django and monkey patching issue | 1,399,746 | <p>I have recently started experimenting with Django for some web applications in my spare time. While designing the data model for one, I came across the dilemma of using inheritance to define a user of the website or using a technique known as monkey patching with the User class already supplied by the framework.</p>
<p>I tried to add a field by means of (after having defined all my models etc. without errors, according to <code>python manage.py validate</code>):</p>
<p><code>User.add_to_class('location', models.CharField(max_length=250,blank=True))</code></p>
<p>and executed the <code>syncdb</code> command. However, I keep getting this error</p>
<blockquote>
<p>OperationalError: no such column:
auth_user.location</p>
</blockquote>
<p>whether I am in the admin view of the site or the manage.py shell. There must be an extra step I'm missing, but there seems to be limited documentation on the whole monkey patching technique. So I'm asking you for assistance before I resort to inheritance. Any code, tips, or pointers to additional documentation are of course welcome.</p>
<p>Thanks in advance.</p>
<p>PS. I'm aware this technique is ugly, and probably ill-advised. ;)</p>
| 4 | 2009-09-09T13:40:39Z | 1,399,843 | <p>There's an alternative to both approaches, which is to simply use <a href="http://www.b-list.org/weblog/2006/jun/06/django-tips-extending-user-model/">a related profile model</a>. This also happens to be a well-documented, highly recommended approach. Perhaps the reason that the add_to_class approach is not well-documented, as you noted, is because it's <a href="http://groups.google.com/group/django-users/browse%5Fthread/thread/a35d94ce1a7893b0">explicitly discouraged</a> (for good reason).</p>
| 13 | 2009-09-09T13:55:48Z | [
"python",
"django",
"monkeypatching"
] |
Import failed when the module is already in the sys.path | 1,399,896 | <p>It's weird to me that the import fails even when it's in the <code>sys.path</code>.</p>
<p>today, I set up a google app engine django environment on ubuntu in my lab's pc. And it works fine when I checked out the code and ran it in windows(same pc in the lab).</p>
<p>But when I went to the dorm, and checked out the code and start to run, it failed weirdly.</p>
<p>I print the <code>sys.path</code>, like this:</p>
<pre><code>['/home/tower/googlecode/mygae', '/home/tower/googlecode/mygae/.google_appengine', '/home/tower/googlecode/mygae/.google_appengine/lib/antlr3', ...]
</code></pre>
<p>and when I ran python complained </p>
<pre><code>from google.appengine.api import apiproxy_stub_map
ImportError: No module named appengine.api
</code></pre>
<p>it's easy to know the google module is in the <code>'/home/tower/googlecode/mygae/.google_appengine'</code>
directory, and the<code> __init__.py</code> for each module is present.</p>
<p>So what can be the reason for this weird thing? Or what I messed up probably? </p>
<p>thanks.</p>
| 0 | 2009-09-09T14:03:57Z | 1,399,918 | <p>Sometimes you can get an import error for a module when the error is something different, like a syntax error. Try putting </p>
<pre><code>import pdb;pdb.set_trace()
</code></pre>
<p>just before the import and then s(tep) into the import, and n(ext) thruogh the module in question to see of you get an error.</p>
| 0 | 2009-09-09T14:07:04Z | [
"python",
"django"
] |
Import failed when the module is already in the sys.path | 1,399,896 | <p>It's weird to me that the import fails even when it's in the <code>sys.path</code>.</p>
<p>today, I set up a google app engine django environment on ubuntu in my lab's pc. And it works fine when I checked out the code and ran it in windows(same pc in the lab).</p>
<p>But when I went to the dorm, and checked out the code and start to run, it failed weirdly.</p>
<p>I print the <code>sys.path</code>, like this:</p>
<pre><code>['/home/tower/googlecode/mygae', '/home/tower/googlecode/mygae/.google_appengine', '/home/tower/googlecode/mygae/.google_appengine/lib/antlr3', ...]
</code></pre>
<p>and when I ran python complained </p>
<pre><code>from google.appengine.api import apiproxy_stub_map
ImportError: No module named appengine.api
</code></pre>
<p>it's easy to know the google module is in the <code>'/home/tower/googlecode/mygae/.google_appengine'</code>
directory, and the<code> __init__.py</code> for each module is present.</p>
<p>So what can be the reason for this weird thing? Or what I messed up probably? </p>
<p>thanks.</p>
| 0 | 2009-09-09T14:03:57Z | 1,400,006 | <p>Can you import <code>google</code> and <code>google.appengine</code>?
Are you sure interpreter has read and traverse access rights to the module tree?</p>
| 2 | 2009-09-09T14:20:13Z | [
"python",
"django"
] |
Import failed when the module is already in the sys.path | 1,399,896 | <p>It's weird to me that the import fails even when it's in the <code>sys.path</code>.</p>
<p>today, I set up a google app engine django environment on ubuntu in my lab's pc. And it works fine when I checked out the code and ran it in windows(same pc in the lab).</p>
<p>But when I went to the dorm, and checked out the code and start to run, it failed weirdly.</p>
<p>I print the <code>sys.path</code>, like this:</p>
<pre><code>['/home/tower/googlecode/mygae', '/home/tower/googlecode/mygae/.google_appengine', '/home/tower/googlecode/mygae/.google_appengine/lib/antlr3', ...]
</code></pre>
<p>and when I ran python complained </p>
<pre><code>from google.appengine.api import apiproxy_stub_map
ImportError: No module named appengine.api
</code></pre>
<p>it's easy to know the google module is in the <code>'/home/tower/googlecode/mygae/.google_appengine'</code>
directory, and the<code> __init__.py</code> for each module is present.</p>
<p>So what can be the reason for this weird thing? Or what I messed up probably? </p>
<p>thanks.</p>
| 0 | 2009-09-09T14:03:57Z | 1,400,120 | <p>Looks like you're getting a module (or package) called 'google' from elsewhere -- perhaps <code>/home/tower/googlecode/mygae</code> -- and THAT google module has no <code>appengine</code> in it. To check, print <code>google.__file__</code> and if possible <code>google.__path__</code>; that should be informative.</p>
| 1 | 2009-09-09T14:35:42Z | [
"python",
"django"
] |
Import failed when the module is already in the sys.path | 1,399,896 | <p>It's weird to me that the import fails even when it's in the <code>sys.path</code>.</p>
<p>today, I set up a google app engine django environment on ubuntu in my lab's pc. And it works fine when I checked out the code and ran it in windows(same pc in the lab).</p>
<p>But when I went to the dorm, and checked out the code and start to run, it failed weirdly.</p>
<p>I print the <code>sys.path</code>, like this:</p>
<pre><code>['/home/tower/googlecode/mygae', '/home/tower/googlecode/mygae/.google_appengine', '/home/tower/googlecode/mygae/.google_appengine/lib/antlr3', ...]
</code></pre>
<p>and when I ran python complained </p>
<pre><code>from google.appengine.api import apiproxy_stub_map
ImportError: No module named appengine.api
</code></pre>
<p>it's easy to know the google module is in the <code>'/home/tower/googlecode/mygae/.google_appengine'</code>
directory, and the<code> __init__.py</code> for each module is present.</p>
<p>So what can be the reason for this weird thing? Or what I messed up probably? </p>
<p>thanks.</p>
| 0 | 2009-09-09T14:03:57Z | 14,343,216 | <p>I had the same problem on <strong>Ubuntu</strong> when I wanted to play with <strong>google.appengine</strong> in console. First I tried to fix it by removing the <code>/usr/lib/python2.7/dist-packages/google</code> package altogether but <strong>Ubuntu One</strong> complained. Finally I resolved it by merging the <strong>GAE SDK google package</strong> into the <strong>package that caused the collision</strong>.</p>
<p>The contents of the <code>/usr/lib/python2.7/dist-packages/google</code> dir now look like this:</p>
<pre><code>/google
/appengine
/net
/protobuf
/pyglib
/storage
/__init__.py
/__init__.pyc
</code></pre>
| 2 | 2013-01-15T17:21:52Z | [
"python",
"django"
] |
Endianness of integers in Python | 1,400,012 | <p>I'm working on a program where I store some data in an integer and process it bitwise. For example, I might receive the number 48, which I will process bit-by-bit. In general the endianness of integers depends on the machine representation of integers, but does Python do anything to guarantee that the ints will always be little-endian? Or do I need to check endianness like I would in C and then write separate code for the two cases?</p>
<p>I ask because my code runs on a Sun machine and, although the one it's running on now uses Intel processors, I might have to switch to a machine with Sun processors in the future, which I know is big-endian.</p>
| 12 | 2009-09-09T14:20:42Z | 1,400,026 | <p>Python's <code>int</code> has the same endianness as the processor it runs on. The <a href="http://docs.python.org/library/struct.html"><code>struct</code></a> module lets you convert byte blobs to ints (and viceversa, and some other data types too) in either native, little-endian, or big-endian ways, depending on the <a href="http://docs.python.org/library/struct.html#struct.calcsize">format string</a> you choose: start the format with <code>@</code> or no endianness character to use native endianness (and native sizes -- everything else uses standard sizes), '~' for native, '<' for little-endian, '>' or '!' for big-endian.</p>
<p>This is byte-by-byte, not bit-by-bit; not sure exactly what you mean by bit-by-bit processing in this context, but I assume it can be accomodated similarly.</p>
<p>For fast "bulk" processing in simple cases, consider also the <a href="http://docs.python.org/library/array.html">array</a> module -- the <code>fromstring</code> and <code>tostring</code> methods can operate on large number of bytes speedily, and the <code>byteswap</code> method can get you the "other" endianness (native to non-native or vice versa), again rapidly and for a large number of items (the whole array).</p>
| 15 | 2009-09-09T14:23:14Z | [
"python",
"integer",
"endianness"
] |
Endianness of integers in Python | 1,400,012 | <p>I'm working on a program where I store some data in an integer and process it bitwise. For example, I might receive the number 48, which I will process bit-by-bit. In general the endianness of integers depends on the machine representation of integers, but does Python do anything to guarantee that the ints will always be little-endian? Or do I need to check endianness like I would in C and then write separate code for the two cases?</p>
<p>I ask because my code runs on a Sun machine and, although the one it's running on now uses Intel processors, I might have to switch to a machine with Sun processors in the future, which I know is big-endian.</p>
| 12 | 2009-09-09T14:20:42Z | 1,400,069 | <p>If you need to process your data 'bitwise' then the <a href="http://code.google.com/p/python-bitstring/"><code>bitstring</code></a> module might be of help to you. It can also deal with endianness between platforms (on the latest trunk build at least - to be released in the next few days). </p>
<p>The <a href="http://docs.python.org/library/struct.html"><code>struct</code> module</a> is the best standard method of dealing with endianness between platforms. For example this packs and unpack the integers 1, 2, 3 into two 'shorts' and one 'long' (2 and 4 bytes on most platforms) using native endianness:</p>
<pre><code>>>> from struct import *
>>> pack('hhl', 1, 2, 3)
'\x00\x01\x00\x02\x00\x00\x00\x03'
>>> unpack('hhl', '\x00\x01\x00\x02\x00\x00\x00\x03')
(1, 2, 3)
</code></pre>
<p>To check the endianness of the platform programmatically you can use</p>
<pre><code>>>> import sys
>>> sys.byteorder
</code></pre>
<p>which will either return <code>"big"</code> or <code>"little"</code>.</p>
| 13 | 2009-09-09T14:27:59Z | [
"python",
"integer",
"endianness"
] |
Endianness of integers in Python | 1,400,012 | <p>I'm working on a program where I store some data in an integer and process it bitwise. For example, I might receive the number 48, which I will process bit-by-bit. In general the endianness of integers depends on the machine representation of integers, but does Python do anything to guarantee that the ints will always be little-endian? Or do I need to check endianness like I would in C and then write separate code for the two cases?</p>
<p>I ask because my code runs on a Sun machine and, although the one it's running on now uses Intel processors, I might have to switch to a machine with Sun processors in the future, which I know is big-endian.</p>
| 12 | 2009-09-09T14:20:42Z | 1,400,075 | <p>Check when?</p>
<p>When doing bitwise operations, the int in will have the same endianess as the ints you put in. You don't need to check that. You only need to care about this when converting to/from sequences of bytes, in both languages, afaik.</p>
<p>In Python you use the struct module for this, most commonly struct.pack() and struct.unpack(). </p>
| 2 | 2009-09-09T14:28:26Z | [
"python",
"integer",
"endianness"
] |
Endianness of integers in Python | 1,400,012 | <p>I'm working on a program where I store some data in an integer and process it bitwise. For example, I might receive the number 48, which I will process bit-by-bit. In general the endianness of integers depends on the machine representation of integers, but does Python do anything to guarantee that the ints will always be little-endian? Or do I need to check endianness like I would in C and then write separate code for the two cases?</p>
<p>I ask because my code runs on a Sun machine and, although the one it's running on now uses Intel processors, I might have to switch to a machine with Sun processors in the future, which I know is big-endian.</p>
| 12 | 2009-09-09T14:20:42Z | 20,535,615 | <p>The following snippet will tell you if your system default is little endian (otherwise it is big-endian)</p>
<pre><code>import struct
little_endian = (struct.unpack('<I', struct.pack('=I', 1))[0] == 1)
</code></pre>
<p>Note, however, this will not affect the behavior of bitwise operators: <code>1<<1</code> is equal to <code>2</code> regardless of the default endianness of your system.</p>
| 1 | 2013-12-12T05:18:00Z | [
"python",
"integer",
"endianness"
] |
Multi-line Pattern and tag search | 1,400,136 | <p>I'm trying to make a pattern for tags, but the sub method just replaces the first char and 3 at the end of the line, im trying to replace all tags on the line and with multiline</p>
<pre><code>p=re.compile('<img=([^}]*)>([^}]*)</img>', re.S)
p.sub(r'[img=\1]\2[/img]','<img="test">dsad</img> <img="test2">dsad2</img>')
output:
'**[**img="test">dsad</img> <img="test2"]dsad2**[/img]**'
</code></pre>
| 0 | 2009-09-09T14:38:31Z | 1,400,202 | <p>You're using towards the start of your re's pattern:</p>
<pre><code><img=([^}]*)>
</code></pre>
<p>this will gobble up (as group 1) all characters after the leading <code><img=</code>, <strong>including other tags!!!</strong>, up to the last <code>></code> it can possibly gobble; <code>*</code> is GREEDY -- it gobbles up as much as it possibly can. Not sure why you're specifically excluding closed-braces <code>}</code>? Maybe you meant to exclude closed angular brackets instead (<code>></code>).</p>
<p>For NON-greedy matching, instead of <code>*</code>, you need <code>*?</code>; with that, you'll be gobbling up as little as you can, instead of as much as you can. So, I think you mean:</p>
<pre><code>p = re.compile(r'<img=([^>]*?)>(.*?)</img>', re.S)
</code></pre>
<p>this matches one <code>img</code> tag (and all tags inside it), and appears to be performing exactly the substitutions you mean.</p>
| 1 | 2009-09-09T14:48:59Z | [
"python",
"regex",
"multiline"
] |
How do I scroll a wxPython wx.html.HtmlWindow back down to where it was when the user clicked a link? | 1,400,179 | <p>I am using a wxPython wx.html.HtmlWindow to display part of my interface. The user can scroll down a list of links in a window smaller than the list. When they click on a link, I need to repaint the web page, but I want to return the page position back to where they clicked it. </p>
<p>I've tried MouseEvent.GetLogicalPosition() on the event, but it wants a DC and the best I've been able to do is get the same information as GetPosition(), so I must not be feeding it the right one.</p>
<p>I also tried HtmlWindow.CalcScrolledPosition(), but apparently that isn't available in HtmlWindow because I get a NotImplementedError...</p>
<p>What I would like is a scroll position that can be derived from the MouseEvent, or the OnLinkClicked information.</p>
<p>I know about HtmlWindow.ScrollToAnchor(), but it's flaky and unaesthetic -- I would prefer to bypass it if possible so that I can scroll back <em>exactly</em> to where the user clicked.</p>
<p>Thanks!</p>
| 2 | 2009-09-09T14:45:57Z | 1,401,438 | <p>how about having a look at the <a href="http://svn.wxwidgets.org/viewvc/wx/wxWidgets/trunk/src/html/htmlwin.cpp?annotate=61772" rel="nofollow">source of wxHtmlWindow</a> for inspiration? for example at <a href="http://svn.wxwidgets.org/viewvc/wx/wxWidgets/trunk/src/html/htmlwin.cpp?annotate=61772#l487" rel="nofollow"><code>wxHtmlWindow::LoadPage()</code></a>: it</p>
<pre><code>// store[s the current] scroll position into history item:
int x, y;
GetViewStart(&x, &y);
(*m_History)[m_HistoryPos].SetPos(y);
</code></pre>
<p>this saved scroll position is used in <a href="http://svn.wxwidgets.org/viewvc/wx/wxWidgets/trunk/src/html/htmlwin.cpp?annotate=61772#l768" rel="nofollow"><code>wxHtmlWindow::HistoryBack()</code></a>:</p>
<pre><code>Scroll(0, (*m_History)[m_HistoryPos].GetPos());
Refresh();
</code></pre>
<p>to go back to the saved position.</p>
<p>i would assume that this built-in "go-to-the-last-position-in-window" handling isn't the most "flaky and unaesthetic". could something similar work for you, too?</p>
| 2 | 2009-09-09T18:55:35Z | [
"python",
"wxpython"
] |
How do I scroll a wxPython wx.html.HtmlWindow back down to where it was when the user clicked a link? | 1,400,179 | <p>I am using a wxPython wx.html.HtmlWindow to display part of my interface. The user can scroll down a list of links in a window smaller than the list. When they click on a link, I need to repaint the web page, but I want to return the page position back to where they clicked it. </p>
<p>I've tried MouseEvent.GetLogicalPosition() on the event, but it wants a DC and the best I've been able to do is get the same information as GetPosition(), so I must not be feeding it the right one.</p>
<p>I also tried HtmlWindow.CalcScrolledPosition(), but apparently that isn't available in HtmlWindow because I get a NotImplementedError...</p>
<p>What I would like is a scroll position that can be derived from the MouseEvent, or the OnLinkClicked information.</p>
<p>I know about HtmlWindow.ScrollToAnchor(), but it's flaky and unaesthetic -- I would prefer to bypass it if possible so that I can scroll back <em>exactly</em> to where the user clicked.</p>
<p>Thanks!</p>
| 2 | 2009-09-09T14:45:57Z | 1,579,014 | <p>Usually, click events are trigged by MouseUp events. If you track the mouse position by capturing any MouseDown events, you will know where the last click (MouseUp) happened, and that should allow you to reconstruct things.</p>
<p>For this particular problem, you might have to do a bit more work in MouseDown like checking if they are within the wxHtmlWindow control and if so, then saving something like a line number.</p>
| 0 | 2009-10-16T16:17:26Z | [
"python",
"wxpython"
] |
How do I scroll a wxPython wx.html.HtmlWindow back down to where it was when the user clicked a link? | 1,400,179 | <p>I am using a wxPython wx.html.HtmlWindow to display part of my interface. The user can scroll down a list of links in a window smaller than the list. When they click on a link, I need to repaint the web page, but I want to return the page position back to where they clicked it. </p>
<p>I've tried MouseEvent.GetLogicalPosition() on the event, but it wants a DC and the best I've been able to do is get the same information as GetPosition(), so I must not be feeding it the right one.</p>
<p>I also tried HtmlWindow.CalcScrolledPosition(), but apparently that isn't available in HtmlWindow because I get a NotImplementedError...</p>
<p>What I would like is a scroll position that can be derived from the MouseEvent, or the OnLinkClicked information.</p>
<p>I know about HtmlWindow.ScrollToAnchor(), but it's flaky and unaesthetic -- I would prefer to bypass it if possible so that I can scroll back <em>exactly</em> to where the user clicked.</p>
<p>Thanks!</p>
| 2 | 2009-09-09T14:45:57Z | 2,850,055 | <p>Maybe a bit late, but with some tips from ax, and some hints from <a href="http://stackoverflow.com/questions/1871405/how-do-i-keep-a-wx-html-htmlwindow-at-the-same-position-during-resize-without-fl">here</a>, I think that calling:</p>
<pre><code>scrollpos = wx.html.HtmlWindow.GetViewStart()[1]
</code></pre>
<p>and storing that, and then later doing a call to:</p>
<pre><code>wx.html.HtmlWindow.Scroll(0, scrollpos)
</code></pre>
<p>works for me. Of course, you do need to change wx.html.HtmlWindow to an actual reference to an instance.</p>
| 1 | 2010-05-17T14:53:00Z | [
"python",
"wxpython"
] |
How do I scroll a wxPython wx.html.HtmlWindow back down to where it was when the user clicked a link? | 1,400,179 | <p>I am using a wxPython wx.html.HtmlWindow to display part of my interface. The user can scroll down a list of links in a window smaller than the list. When they click on a link, I need to repaint the web page, but I want to return the page position back to where they clicked it. </p>
<p>I've tried MouseEvent.GetLogicalPosition() on the event, but it wants a DC and the best I've been able to do is get the same information as GetPosition(), so I must not be feeding it the right one.</p>
<p>I also tried HtmlWindow.CalcScrolledPosition(), but apparently that isn't available in HtmlWindow because I get a NotImplementedError...</p>
<p>What I would like is a scroll position that can be derived from the MouseEvent, or the OnLinkClicked information.</p>
<p>I know about HtmlWindow.ScrollToAnchor(), but it's flaky and unaesthetic -- I would prefer to bypass it if possible so that I can scroll back <em>exactly</em> to where the user clicked.</p>
<p>Thanks!</p>
| 2 | 2009-09-09T14:45:57Z | 8,591,447 | <p>Here is what I am doing to scroll page to previous position.
I do this to avoid blinking.</p>
<pre><code> pos = self.GetViewStart()[1]
self.Freeze()
self.SetPage(src)
if save_scroll_pos:
self.Scroll(0, pos)
self.Thaw()
</code></pre>
| 1 | 2011-12-21T14:31:01Z | [
"python",
"wxpython"
] |
Python class for pickle- and copy-persistent object? | 1,400,295 | <p>I'm trying to write a class for a read-only object which will not be really copied with the <code>copy</code> module, and when it will be pickled to be transferred between processes each process will maintain no more than one copy of it, no matter how many times it will be passed around as a "new" object. Is there already something like that?</p>
| 4 | 2009-09-09T15:05:31Z | 1,400,366 | <p>I don't know of any such functionality already implemented. The interesting problem is as follows, and needs precise specs as to what's to happen in this case...:</p>
<ul>
<li>process A makes the obj and sends it to B which unpickles it, so far so good</li>
<li>A makes change X to the obj, meanwhile B makes change Y to ITS copy of the obj</li>
<li>now either process sends its obj to the other, which unpickles it: <em>what changes
to the object need to be visible at this time in each process</em>? does it matter
whether A's sending to B or vice versa, i.e. does A "own" the object? or what?</li>
</ul>
<p>If you don't care, say because only A OWNS the obj -- only A is ever allowed to make changes and send the obj to others, others can't and won't change -- then the problems boil down to identifying obj uniquely -- a GUID will do. The class can maintain a class attribute dict mapping GUIDs to existing instances (probably as a weak-value dict to avoid keeping instances needlessly alive, but that's a side issue) and ensure the existing instance is returned when appropriate.</p>
<p>But if changes need to be synchronized to any finer granularity, then suddenly it's a REALLY difficult problem of distributed computing and the specs of what happens in what cases really need to be nailed down with the utmost care (and more paranoia than is present in most of us -- distributed programming is VERY tricky unless a few simple and provably correct patterns and idioms are followed fanatically!-).</p>
<p>If you can nail down the specs for us, I can offer a sketch of how I would go about trying to meet them. But I won't presume to guess the specs on your behalf;-).</p>
<p><strong>Edit</strong>: the OP has clarified, and it seems all he needs is a better understanding of how to control <code>__new__</code>. That's easy: see <a href="http://docs.python.org/library/pickle.html?#object.%5F%5Fgetnewargs%5F%5F" rel="nofollow"><code>__getnewargs__</code></a> -- you'll need a new-style class and pickling with protocol 2 or better (but those are advisable anyway for other reasons!-), then <code>__getnewargs__</code> in an existing object can simply return the object's GUID (which <code>__new__</code> must receive as an optional parameter). So <code>__new__</code> can check if the GUID is present in the class's <code>memo</code> [[weakvalue;-)]]dict (and if so return the corresponding object value) -- if not (or if the GUID is not passed, implying it's not an unpickling, so a fresh GUID must be generated), then make a truly-new object (setting its GUID;-) and also record it in the class-level <code>memo</code>.</p>
<p>BTW, to make GUIDs, consider using the <a href="http://docs.python.org/library/uuid.html" rel="nofollow">uuid</a> module in the standard library.</p>
| 1 | 2009-09-09T15:20:17Z | [
"python",
"persistence",
"pickle"
] |
Python class for pickle- and copy-persistent object? | 1,400,295 | <p>I'm trying to write a class for a read-only object which will not be really copied with the <code>copy</code> module, and when it will be pickled to be transferred between processes each process will maintain no more than one copy of it, no matter how many times it will be passed around as a "new" object. Is there already something like that?</p>
| 4 | 2009-09-09T15:05:31Z | 1,401,887 | <p>you could use simply a dictionnary with the key and the values the same in the receiver. And to avoid a memory leak use a WeakKeyDictionary. </p>
| 0 | 2009-09-09T20:25:42Z | [
"python",
"persistence",
"pickle"
] |
Python class for pickle- and copy-persistent object? | 1,400,295 | <p>I'm trying to write a class for a read-only object which will not be really copied with the <code>copy</code> module, and when it will be pickled to be transferred between processes each process will maintain no more than one copy of it, no matter how many times it will be passed around as a "new" object. Is there already something like that?</p>
| 4 | 2009-09-09T15:05:31Z | 1,445,790 | <p>I made an attempt to implement this. @Alex Martelli and anyone else, please give me comments/improvements. I think this will eventually end up on GitHub.</p>
<pre><code>"""
todo: need to lock library to avoid thread trouble?
todo: need to raise an exception if we're getting pickled with
an old protocol?
todo: make it polite to other classes that use __new__. Therefore, should
probably work not only when there is only one item in the *args passed to new.
"""
import uuid
import weakref
library = weakref.WeakValueDictionary()
class UuidToken(object):
def __init__(self, uuid):
self.uuid = uuid
class PersistentReadOnlyObject(object):
def __new__(cls, *args, **kwargs):
if len(args)==1 and len(kwargs)==0 and isinstance(args[0], UuidToken):
received_uuid = args[0].uuid
else:
received_uuid = None
if received_uuid:
# This section is for when we are called at unpickling time
thing = library.pop(received_uuid, None)
if thing:
thing._PersistentReadOnlyObject__skip_setstate = True
return thing
else: # This object does not exist in our library yet; Let's add it
new_args = args[1:]
thing = super(PersistentReadOnlyObject, cls).__new__(cls,
*new_args,
**kwargs)
thing._PersistentReadOnlyObject__uuid = received_uuid
library[received_uuid] = thing
return thing
else:
# This section is for when we are called at normal creation time
thing = super(PersistentReadOnlyObject, cls).__new__(cls, *args,
**kwargs)
new_uuid = uuid.uuid4()
thing._PersistentReadOnlyObject__uuid = new_uuid
library[new_uuid] = thing
return thing
def __getstate__(self):
my_dict = dict(self.__dict__)
del my_dict["_PersistentReadOnlyObject__uuid"]
return my_dict
def __getnewargs__(self):
return (UuidToken(self._PersistentReadOnlyObject__uuid),)
def __setstate__(self, state):
if self.__dict__.pop("_PersistentReadOnlyObject__skip_setstate", None):
return
else:
self.__dict__.update(state)
def __deepcopy__(self, memo):
return self
def __copy__(self):
return self
# --------------------------------------------------------------
"""
From here on it's just testing stuff; will be moved to another file.
"""
def play_around(queue, thing):
import copy
queue.put((thing, copy.deepcopy(thing),))
class Booboo(PersistentReadOnlyObject):
def __init__(self):
self.number = random.random()
if __name__ == "__main__":
import multiprocessing
import random
import copy
def same(a, b):
return (a is b) and (a == b) and (id(a) == id(b)) and \
(a.number == b.number)
a = Booboo()
b = copy.copy(a)
c = copy.deepcopy(a)
assert same(a, b) and same(b, c)
my_queue = multiprocessing.Queue()
process = multiprocessing.Process(target = play_around,
args=(my_queue, a,))
process.start()
process.join()
things = my_queue.get()
for thing in things:
assert same(thing, a) and same(thing, b) and same(thing, c)
print("all cool!")
</code></pre>
| 2 | 2009-09-18T17:10:58Z | [
"python",
"persistence",
"pickle"
] |
Dictionary of tags in declarative SQLAlchemy? | 1,400,537 | <p>I am working on a quite large code base that has been implemented using <code>sqlalchemy.ext.declarative</code>, and I need to add a dict-like property to one of the classes. What I need is the same as in <a href="http://stackoverflow.com/questions/780774/sqlalchemy-dictionary-of-tags">this question</a>, but in a declarative fashion. Can anyone with more knowledge in SQLAlchemy give me an example?
Thanks in advance...</p>
| 6 | 2009-09-09T15:54:37Z | 1,400,881 | <p>Declarative is just another way of defining things. Virtually you end up with the exact same environment than if you used separated mapping.</p>
<p>Since I answered the other question, I'll try this one as well. Hope it gives more upvotes ;)</p>
<p>Well, first we define the classes</p>
<pre><code>from sqlalchemy import Column, Integer, String, Table, create_engine
from sqlalchemy import orm, MetaData, Column, ForeignKey
from sqlalchemy.orm import relation, mapper, sessionmaker
from sqlalchemy.orm.collections import column_mapped_collection
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite:///:memory:', echo=True)
Base = declarative_base(bind=engine)
class Note(Base):
__tablename__ = 'notes'
id_item = Column(Integer, ForeignKey('items.id'), primary_key=True)
name = Column(String(20), primary_key=True)
value = Column(String(100))
def __init__(self, name, value):
self.name = name
self.value = value
class Item(Base):
__tablename__ = 'items'
id = Column(Integer, primary_key=True)
name = Column(String(20))
description = Column(String(100))
_notesdict = relation(Note,
collection_class=column_mapped_collection(Note.name))
notes = association_proxy('_notesdict', 'value', creator=Note)
def __init__(self, name, description=''):
self.name = name
self.description = description
Base.metadata.create_all()
</code></pre>
<p>Now let's make a test:</p>
<pre><code>Session = sessionmaker(bind=engine)
s = Session()
i = Item('ball', 'A round full ball')
i.notes['color'] = 'orange'
i.notes['size'] = 'big'
i.notes['data'] = 'none'
s.add(i)
s.commit()
print i.notes
</code></pre>
<p>I get:</p>
<pre><code>{u'color': u'orange', u'data': u'none', u'size': u'big'}
</code></pre>
<p>Now let's check the notes table...</p>
<pre><code>for note in s.query(Note):
print note.id_item, note.name, note.value
</code></pre>
<p>I get:</p>
<pre><code>1 color orange
1 data none
1 size big
</code></pre>
<p>It works!! :D</p>
| 13 | 2009-09-09T17:04:33Z | [
"python",
"sqlalchemy",
"declarative"
] |
How to empty a list in Python? | 1,400,608 | <p>It seems so "dirty" emptying a list in this way:</p>
<pre><code>while len(alist) > 0 : alist.pop()
</code></pre>
<p>Does a clear way exist to do that?</p>
| 215 | 2009-09-09T16:08:21Z | 1,400,614 | <pre><code>list = []
</code></pre>
<p>will reset <code>list</code> to an empty list.</p>
<p>Note that you generally should not shadow reserved function names, such as <code>list</code>, which is the constructor for a list object -- you could use <code>lst</code> or <code>list_</code> instead, for instance.</p>
| -1 | 2009-09-09T16:09:46Z | [
"python",
"list"
] |
How to empty a list in Python? | 1,400,608 | <p>It seems so "dirty" emptying a list in this way:</p>
<pre><code>while len(alist) > 0 : alist.pop()
</code></pre>
<p>Does a clear way exist to do that?</p>
| 215 | 2009-09-09T16:08:21Z | 1,400,622 | <p>This actually removes the contents from the list, not replaces the old label with a new empty list</p>
<pre><code>del lst[:]
</code></pre>
<p>example:</p>
<pre><code>lst1 = [1, 2, 3]
lst2 = lst1
del lst1[:]
print(lst2)
</code></pre>
<p>For the sake of completeness, slice assignment achieves the same effect:</p>
<pre><code>lst[:] = []
</code></pre>
<p>and can be used to shrink a part of the list while replacing a part at the same time (but is out of scope of the question).</p>
<p>Note that doing <code>lst = []</code> does not empty the list, just creates a new object and binds it to the variable <code>lst</code>, but the old list will still have the same elements, and effect will be apparent if it had other variable bindings.</p>
| 366 | 2009-09-09T16:10:40Z | [
"python",
"list"
] |
How to empty a list in Python? | 1,400,608 | <p>It seems so "dirty" emptying a list in this way:</p>
<pre><code>while len(alist) > 0 : alist.pop()
</code></pre>
<p>Does a clear way exist to do that?</p>
| 215 | 2009-09-09T16:08:21Z | 1,400,624 | <p>You could try:</p>
<pre><code>alist[:] = []
</code></pre>
<p>Which means: Splice in the list <code>[]</code> (0 elements) at the location <code>[:]</code> (all indexes from start to finish)</p>
<p>The [:] is the slice operator. See <a href="http://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation">this question</a> for more information.</p>
| 37 | 2009-09-09T16:10:52Z | [
"python",
"list"
] |
How to empty a list in Python? | 1,400,608 | <p>It seems so "dirty" emptying a list in this way:</p>
<pre><code>while len(alist) > 0 : alist.pop()
</code></pre>
<p>Does a clear way exist to do that?</p>
| 215 | 2009-09-09T16:08:21Z | 8,239,837 | <p>it turns out that with python 2.5.2, <code>del l[:]</code> is slightly slower than <code>l[:] = []</code> by 1.1 usec.</p>
<pre><code>$ python -mtimeit "l=list(range(1000))" "b=l[:];del b[:]"
10000 loops, best of 3: 29.8 usec per loop
$ python -mtimeit "l=list(range(1000))" "b=l[:];b[:] = []"
10000 loops, best of 3: 28.7 usec per loop
$ python -V
Python 2.5.2
</code></pre>
| 23 | 2011-11-23T09:30:17Z | [
"python",
"list"
] |
How to empty a list in Python? | 1,400,608 | <p>It seems so "dirty" emptying a list in this way:</p>
<pre><code>while len(alist) > 0 : alist.pop()
</code></pre>
<p>Does a clear way exist to do that?</p>
| 215 | 2009-09-09T16:08:21Z | 25,275,196 | <p>Another simple code you could use (depending on your situation) is:</p>
<pre><code>index=len(list)-1
while index>=0:
del list[index]
index-=1
</code></pre>
<p>You have to start index at the length of the list and go backwards versus index at 0, forwards because that would end you up with index equal to the length of the list with it only being cut in half.</p>
<p>Also, be sure that the while line has a "greater than or equal to" sign. Omitting it will leave you with list[0] remaining.</p>
| 1 | 2014-08-12T22:34:31Z | [
"python",
"list"
] |
How to empty a list in Python? | 1,400,608 | <p>It seems so "dirty" emptying a list in this way:</p>
<pre><code>while len(alist) > 0 : alist.pop()
</code></pre>
<p>Does a clear way exist to do that?</p>
| 215 | 2009-09-09T16:08:21Z | 30,087,221 | <p>If you have Python 3.3 or better, you could use the <a href="https://docs.python.org/dev/library/stdtypes.html#typesseq-mutable"><code>clear()</code></a> method of <code>list</code>:</p>
<pre><code>alist.clear() # removes all items from alist (equivalent to del alist[:])
</code></pre>
<p>As per the linked page, the same can also be achieved with <code>alist *= 0</code>.</p>
| 15 | 2015-05-06T20:46:24Z | [
"python",
"list"
] |
How to create QString in PyQt4? | 1,400,858 | <pre><code>str = QtCore.QString('Hello')
AttributeError: 'module' object has no attribute 'QString'
QtCore.QString._init_(self)
AttributeError: 'module' object has no attribute 'QString'
</code></pre>
<p>Yes, I'm read <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qstring.html" rel="nofollow">QString Class Reference</a> </p>
<p>if you can, answer with code sample. Thanks</p>
| 9 | 2009-09-09T17:00:03Z | 1,400,885 | <pre><code>In [1]: from PyQt4 import QtCore
In [2]: s = QtCore.QString('foo')
In [3]: s
Out[3]: PyQt4.QtCore.QString(u'foo')
</code></pre>
| 6 | 2009-09-09T17:06:04Z | [
"python",
"user-interface",
"pyqt"
] |
How to create QString in PyQt4? | 1,400,858 | <pre><code>str = QtCore.QString('Hello')
AttributeError: 'module' object has no attribute 'QString'
QtCore.QString._init_(self)
AttributeError: 'module' object has no attribute 'QString'
</code></pre>
<p>Yes, I'm read <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qstring.html" rel="nofollow">QString Class Reference</a> </p>
<p>if you can, answer with code sample. Thanks</p>
| 9 | 2009-09-09T17:00:03Z | 1,485,652 | <p>It depends on your import statement.</p>
<p>If you write</p>
<pre><code>from PyQt4 import QtGui, QtCore
</code></pre>
<p>you must call QString with</p>
<pre><code>yourstr = QtCore.QString('foo')
</code></pre>
<p>I think you've written this :</p>
<pre><code>from PyQt4.QtGui import *
from PyQt4.QtCore import *
</code></pre>
<p>It's not really recommended, but you should call String with :</p>
<pre><code>yourstr = QString('foo')
</code></pre>
| 1 | 2009-09-28T06:12:06Z | [
"python",
"user-interface",
"pyqt"
] |
How to create QString in PyQt4? | 1,400,858 | <pre><code>str = QtCore.QString('Hello')
AttributeError: 'module' object has no attribute 'QString'
QtCore.QString._init_(self)
AttributeError: 'module' object has no attribute 'QString'
</code></pre>
<p>Yes, I'm read <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qstring.html" rel="nofollow">QString Class Reference</a> </p>
<p>if you can, answer with code sample. Thanks</p>
| 9 | 2009-09-09T17:00:03Z | 2,595,514 | <p>In Python 3, QString is automatically mapped to the native Python string by default:</p>
<blockquote>
<p>The QString class is implemented as a mapped type that is automatically converted to and from a Python string. In addition a None is converted to a null QString. However, a null QString is converted to an empty Python string (and not None). (This is because Qt often returns a null QString when it should probably return an empty QString.)</p>
<p>The QChar and QStringRef classes are implemented as mapped types that are automatically converted to and from Python strings.</p>
<p>The QStringList class is implemented as a mapped type that is automatically converted to and from Python lists of strings.</p>
<p>The QLatin1Char, QLatin1String and QStringMatcher classes are not implemented.</p>
</blockquote>
<p><a href="http://pyqt.sourceforge.net/Docs/PyQt4/qstring.html" rel="nofollow">http://pyqt.sourceforge.net/Docs/PyQt4/qstring.html</a></p>
| 14 | 2010-04-07T20:04:01Z | [
"python",
"user-interface",
"pyqt"
] |
How to create QString in PyQt4? | 1,400,858 | <pre><code>str = QtCore.QString('Hello')
AttributeError: 'module' object has no attribute 'QString'
QtCore.QString._init_(self)
AttributeError: 'module' object has no attribute 'QString'
</code></pre>
<p>Yes, I'm read <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qstring.html" rel="nofollow">QString Class Reference</a> </p>
<p>if you can, answer with code sample. Thanks</p>
| 9 | 2009-09-09T17:00:03Z | 3,982,776 | <p>From PyQt4 4.6+ in Python3 QString doesn't exist and you are supposed to use ordinary Python3 unicode objects (string literals). To do this so that your code will work in both Python 2.x AND Python 3.x you can do following:</p>
<pre><code>try:
from PyQt4.QtCore import QString
except ImportError:
# we are using Python3 so QString is not defined
QString = type("")
</code></pre>
<p>Depending on your use case you might get away with this simple hack.</p>
| 9 | 2010-10-20T22:14:36Z | [
"python",
"user-interface",
"pyqt"
] |
How to get Django admin.TabularInline to NOT require some items | 1,400,981 | <pre><code>class LineItemInline(admin.TabularInline):
model = LineItem
extra = 10
class InvoiceAdmin(admin.ModelAdmin):
model = Invoice
inlines = (LineItemInline,)
</code></pre>
<p>and</p>
<pre><code>class LineItem(models.Model):
invoice = models.ForeignKey(Invoice)
item_product_code = models.CharField(max_length=32)
item_description = models.CharField(max_length=64)
item_commodity_code = models.ForeignKey(CommodityCode)
item_unit_cost = models.IntegerField()
item_unit_of_measure = models.ForeignKey(UnitOfMeasure, default=0)
item_quantity = models.IntegerField()
item_total_cost = models.IntegerField()
item_vat_amount = models.IntegerField(default=0)
item_vat_rate = models.IntegerField(default=0)
</code></pre>
<p>When I have it setup like this, the admin interface is requiring me to add data to all ten LineItems. The LineItems have required fields, but I expected it to not require whole line items if there was no data entered.</p>
| 0 | 2009-09-09T17:27:57Z | 1,401,171 | <p>That's strange, it's supposed not to do that - it shouldn't require any data in a row if you haven't entered anything.</p>
<p>I wonder if the <code>default</code> options are causing it to get confused. Again, Django should cope with this, but try removing those and see what happens.</p>
<p>Also note that this:</p>
<pre><code>item_unit_of_measure = models.ForeignKey(UnitOfMeasure, default=0)
</code></pre>
<p>is not valid, since 0 can not be the ID of a UnitOfMeasure object. If you want FKs to not be required, use <code>null=True, blank=True</code> in the field declaration.</p>
| 1 | 2009-09-09T18:08:18Z | [
"python",
"django"
] |
How to get Django admin.TabularInline to NOT require some items | 1,400,981 | <pre><code>class LineItemInline(admin.TabularInline):
model = LineItem
extra = 10
class InvoiceAdmin(admin.ModelAdmin):
model = Invoice
inlines = (LineItemInline,)
</code></pre>
<p>and</p>
<pre><code>class LineItem(models.Model):
invoice = models.ForeignKey(Invoice)
item_product_code = models.CharField(max_length=32)
item_description = models.CharField(max_length=64)
item_commodity_code = models.ForeignKey(CommodityCode)
item_unit_cost = models.IntegerField()
item_unit_of_measure = models.ForeignKey(UnitOfMeasure, default=0)
item_quantity = models.IntegerField()
item_total_cost = models.IntegerField()
item_vat_amount = models.IntegerField(default=0)
item_vat_rate = models.IntegerField(default=0)
</code></pre>
<p>When I have it setup like this, the admin interface is requiring me to add data to all ten LineItems. The LineItems have required fields, but I expected it to not require whole line items if there was no data entered.</p>
| 0 | 2009-09-09T17:27:57Z | 1,402,180 | <p>Turns out the problem is default values. The one pointed out above about UnitOfMeasure isn't the actual problem though, any field with a default= causes it to require the rest of the data to be present. This to me seems like a bug since a default value should be subtracted out when determining if there is anything in the record that needs saving, but when I remove all the default values, it works.</p>
<p>In this code,
item_unit_of_measure = models.ForeignKey(UnitOfMeasure, default=0)
it was a sneaky way of letting the 0th entry in the database be the default value. That doesn't work unfortunately as he pointed out though.</p>
| 0 | 2009-09-09T21:23:07Z | [
"python",
"django"
] |
Python with matplotlib - drawing multiple figures in parallel | 1,401,102 | <p>I have functions that contribute to small parts of a figure generation. I'm trying to use these functions to generate multiple figures? So something like this:</p>
<ol>
<li>work with Figure 1</li>
<li>do something else</li>
<li>work with Figure 2</li>
<li>do something else</li>
<li>work with Figure 1</li>
<li>do something else</li>
<li>work with Figure 2</li>
</ol>
<p>If anyone could help, that'd be great!</p>
| 29 | 2009-09-09T17:57:12Z | 1,401,191 | <p>There are several ways to do this, and the simplest is to use the figure numbers. The code below makes two figures, #0 and #1, each with two lines. #0 has the points 1,2,3,4,5,6, and #2 has the points 10,20,30,40,50,60.</p>
<pre><code>from pylab import *
figure(0)
plot([1,2,3])
figure(1)
plot([10, 20, 30])
figure(0)
plot([4, 5, 6])
figure(1)
plot([40, 50, 60])
show()
</code></pre>
| 33 | 2009-09-09T18:11:15Z | [
"python",
"matplotlib",
"figures"
] |
Python with matplotlib - drawing multiple figures in parallel | 1,401,102 | <p>I have functions that contribute to small parts of a figure generation. I'm trying to use these functions to generate multiple figures? So something like this:</p>
<ol>
<li>work with Figure 1</li>
<li>do something else</li>
<li>work with Figure 2</li>
<li>do something else</li>
<li>work with Figure 1</li>
<li>do something else</li>
<li>work with Figure 2</li>
</ol>
<p>If anyone could help, that'd be great!</p>
| 29 | 2009-09-09T17:57:12Z | 1,401,686 | <p>For a more general answer to this question and to questions you may soon have, I would recommend the <a href="http://matplotlib.sourceforge.net/users/artists.html">official tutorial</a>.</p>
| 6 | 2009-09-09T19:44:20Z | [
"python",
"matplotlib",
"figures"
] |
Python with matplotlib - drawing multiple figures in parallel | 1,401,102 | <p>I have functions that contribute to small parts of a figure generation. I'm trying to use these functions to generate multiple figures? So something like this:</p>
<ol>
<li>work with Figure 1</li>
<li>do something else</li>
<li>work with Figure 2</li>
<li>do something else</li>
<li>work with Figure 1</li>
<li>do something else</li>
<li>work with Figure 2</li>
</ol>
<p>If anyone could help, that'd be great!</p>
| 29 | 2009-09-09T17:57:12Z | 14,591,411 | <p>The best way to show multiple figures is use matplotlib or pylab. (for windows)
with matplotlib you can prepare the figures and then when you finish the process with them you can show with the comand "matplotlib.show()" and all figures should be shown.</p>
<p>(on linux) you don´t have problems adding changes to figures because the interactive mode is enable (on windows the interactive mode don't work OK). </p>
| 0 | 2013-01-29T20:13:49Z | [
"python",
"matplotlib",
"figures"
] |
CRC32 to make short URL for web | 1,401,218 | <p>I am trying to understand crc32 to generate the unique url for web page.</p>
<p>If we use the crc32, what is the maximum number of urls can be used so that we can avoid duplicates?</p>
<p>What could be the approximative string length to keep the checksum to be 2^32?</p>
<p>When I tried UUID for an url and convert the uuid bytes to base 64, I could reduce to 22 chars long. I wonder I can reduce still further.</p>
<p>Mostly I want to convert the url (maximum 1024 chars) to shorted id.</p>
| 4 | 2009-09-09T18:16:32Z | 1,401,231 | <p>There is no such number as the "maximum number of urls can be used so that we can avoid duplicates" for CRC32.</p>
<p>The problem is that CRC32 can produce duplicates, and it's not a function of how many values you throw at it, it's a function of what those values look like.</p>
<p>So you might have a collision on the second url, if you're unlucky.</p>
<p>You should not base your algorithm on producing a unique hash, instead produce a unique value for each url manually.</p>
| 6 | 2009-09-09T18:18:45Z | [
"c#",
"python",
"url",
"crc32",
"short-url"
] |
CRC32 to make short URL for web | 1,401,218 | <p>I am trying to understand crc32 to generate the unique url for web page.</p>
<p>If we use the crc32, what is the maximum number of urls can be used so that we can avoid duplicates?</p>
<p>What could be the approximative string length to keep the checksum to be 2^32?</p>
<p>When I tried UUID for an url and convert the uuid bytes to base 64, I could reduce to 22 chars long. I wonder I can reduce still further.</p>
<p>Mostly I want to convert the url (maximum 1024 chars) to shorted id.</p>
| 4 | 2009-09-09T18:16:32Z | 1,401,237 | <p>If you're already storing the full URL in a database table, an integer ID is pretty short, and can be made shorter by converting it to base 16, 64, or 85. If you can use a UUID, you can use an integer, and you may as well, since it's shorter and I don't see what benefit a UUID would provide in your lookup table.</p>
| 4 | 2009-09-09T18:19:55Z | [
"c#",
"python",
"url",
"crc32",
"short-url"
] |
CRC32 to make short URL for web | 1,401,218 | <p>I am trying to understand crc32 to generate the unique url for web page.</p>
<p>If we use the crc32, what is the maximum number of urls can be used so that we can avoid duplicates?</p>
<p>What could be the approximative string length to keep the checksum to be 2^32?</p>
<p>When I tried UUID for an url and convert the uuid bytes to base 64, I could reduce to 22 chars long. I wonder I can reduce still further.</p>
<p>Mostly I want to convert the url (maximum 1024 chars) to shorted id.</p>
| 4 | 2009-09-09T18:16:32Z | 1,401,243 | <p>CRC32 means <em>cyclic redundancy check</em> with 32 bits where any arbitrary amount of bits is summed up to a 32 bit check sum. And check sum functions are surjective, that means multiple input values have the same output value. So you cannot inverse the function.</p>
| 1 | 2009-09-09T18:20:37Z | [
"c#",
"python",
"url",
"crc32",
"short-url"
] |
CRC32 to make short URL for web | 1,401,218 | <p>I am trying to understand crc32 to generate the unique url for web page.</p>
<p>If we use the crc32, what is the maximum number of urls can be used so that we can avoid duplicates?</p>
<p>What could be the approximative string length to keep the checksum to be 2^32?</p>
<p>When I tried UUID for an url and convert the uuid bytes to base 64, I could reduce to 22 chars long. I wonder I can reduce still further.</p>
<p>Mostly I want to convert the url (maximum 1024 chars) to shorted id.</p>
| 4 | 2009-09-09T18:16:32Z | 1,401,286 | <p>No, even you use md5, or any other check sum, the URL CAN BE duplicate, it all depends on your luck.</p>
<p>So don't make an unique url base on those check sum</p>
| 0 | 2009-09-09T18:27:37Z | [
"c#",
"python",
"url",
"crc32",
"short-url"
] |
CRC32 to make short URL for web | 1,401,218 | <p>I am trying to understand crc32 to generate the unique url for web page.</p>
<p>If we use the crc32, what is the maximum number of urls can be used so that we can avoid duplicates?</p>
<p>What could be the approximative string length to keep the checksum to be 2^32?</p>
<p>When I tried UUID for an url and convert the uuid bytes to base 64, I could reduce to 22 chars long. I wonder I can reduce still further.</p>
<p>Mostly I want to convert the url (maximum 1024 chars) to shorted id.</p>
| 4 | 2009-09-09T18:16:32Z | 1,401,331 | <p>The right way to make a short URL is to store the full one in the database and publish something that maps to the row index. A compact way is to use the Base64 of the row ID, for example. Or you could use a UID for the primary key and show that.</p>
<p>Do not use a checksum, because it's too small and very likely to conflict. A cryptographic hash is larger and less likely, but it's still not the right way to go.</p>
| 1 | 2009-09-09T18:36:24Z | [
"c#",
"python",
"url",
"crc32",
"short-url"
] |
CRC32 to make short URL for web | 1,401,218 | <p>I am trying to understand crc32 to generate the unique url for web page.</p>
<p>If we use the crc32, what is the maximum number of urls can be used so that we can avoid duplicates?</p>
<p>What could be the approximative string length to keep the checksum to be 2^32?</p>
<p>When I tried UUID for an url and convert the uuid bytes to base 64, I could reduce to 22 chars long. I wonder I can reduce still further.</p>
<p>Mostly I want to convert the url (maximum 1024 chars) to shorted id.</p>
| 4 | 2009-09-09T18:16:32Z | 1,401,384 | <p>The quickest (and perhaps best!) way to solve things may be to simply use a hash of the local path and query of a given URI, as follows:</p>
<pre><code>using System;
namespace HashSample
{
class Program
{
static void Main(string[] args)
{
Uri uri = new Uri(
"http://host.com/folder/file.jpg?code=ABC123");
string hash = GetPathAndQueryHash(uri);
Console.WriteLine(hash);
}
public static string GetPathAndQueryHash(Uri uri)
{
return uri.PathAndQuery.GetHashCode().ToString();
}
}
}
</code></pre>
<p>The above presumes that the URI scheme and host remain the same. If not GetHashCode will work with any string.</p>
<p>For a great discussion on CRC32 Hash Collision visit: <a href="http://episteme.arstechnica.com/eve/forums/a/tpc/f/6330927813/m/821008399831" rel="nofollow">http://episteme.arstechnica.com/eve/forums/a/tpc/f/6330927813/m/821008399831</a></p>
| -1 | 2009-09-09T18:45:42Z | [
"c#",
"python",
"url",
"crc32",
"short-url"
] |
Return the number of affected rows from a MERGE with cx_oracle | 1,401,328 | <p>How can you get the number of affected rows from executing a "MERGE INTO..." sql command within CX_Oracle?<br />
When ever I execute the MERGE SQL on cx_oracle, I get a cursor.rowcount of -1. Is there a way to get the number of rows affected by the merge?</p>
| 3 | 2009-09-09T18:36:10Z | 1,401,442 | <p>Since cx_oracle follows the python DBAPI specification (I presume), this is expected 'behaviour'. The exact same problem was discussed <a href="http://stackoverflow.com/questions/839069/cursor-rowcount-always-1-in-sqlite3-in-python3k">here on stackoverflow</a> before.</p>
<p>Some more links with possible solutions:</p>
<ul>
<li><a href="http://www.oracle-developer.net/display.php?id=220" rel="nofollow">http://www.oracle-developer.net/display.php?id=220</a></li>
<li><a href="http://asktom.oracle.com/pls/asktom/f?p=100%3A11%3A0%3A%3A%3A%3AP11%5FQUESTION%5FID%3A122741200346595110" rel="nofollow">http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:122741200346595110</a></li>
</ul>
| 1 | 2009-09-09T18:56:30Z | [
"python",
"oracle",
"cx-oracle"
] |
Performance lost when open a db multiple times in BerkeleyDB | 1,401,497 | <p>I'm using BerkeleyDB to develop a small app. And I have a question about opening a database multiple time in BDB.</p>
<p>I have a large set of text ( corpus ), and I want to load a part of it to do the calculation. I have two pseudo-code (mix with python) here</p>
<p>@1</p>
<pre><code>def getCorpus(token):
DB.open()
DB.get(token)
DB.close()
</code></pre>
<p>@2</p>
<pre><code>#open and wait
def openCorpus():
DB.open()
#close database
def closeCorpus():
DB.close()
def getCorpus(token):
DB.get(token)
</code></pre>
<p>In the second example, I'll open the db before the calculation, load token for each loop and then close the db. </p>
<p>In the first example, each time the loop ask for the token, I'll open, get and then close the db.</p>
<p>Is there any performance lost ?</p>
<p>I also note that I'm using a DBEnv to manage the database</p>
| 0 | 2009-09-09T19:09:06Z | 1,401,546 | <p>If you aren't caching the opened file you will always get performance lost because:</p>
<ul>
<li>you call open() and close() multiple times which are quite expensive,</li>
<li>you lose all potential buffers (both system buffers and bdb internal buffers).</li>
</ul>
<p>But I wouldn't care too much about the performance before the code is written.</p>
| 3 | 2009-09-09T19:19:15Z | [
"python",
"database",
"performance",
"berkeley-db"
] |
How do I programmatically check whether an image (PNG, JPEG, or GIF) is corrupted? | 1,401,527 | <p>Okay. So I have about 250,000 high resolution images. What I want to do is go through all of them and find ones that are corrupted. If you know what 4scrape is, then you know the nature of the images I.</p>
<p>Corrupted, to me, is the image is loaded into Firefox and it says</p>
<blockquote>
<p><code>The image âsuch and such imageâ cannot be displayed, because it contains errors.</code></p>
</blockquote>
<p>Now, I could select all of my 250,000 images (~150gb) and drag-n-drop them into Firefox. That would be bad though, because I don't think Mozilla designed Firefox to open 250,000 tabs. No, I need a way to programmatically check whether an image is corrupted.</p>
<p>Does anyone know a PHP or Python library which can do something along these lines? Or an existing piece of software for Windows?</p>
<p>I have already removed obviously corrupted images (such as ones that are 0 bytes) but I'm about 99.9% sure that there are more diseased images floating around in my throng of a collection.</p>
| 14 | 2009-09-09T19:15:41Z | 1,401,544 | <p>i suggest you check out imagemagick for this: <a href="http://www.imagemagick.org/">http://www.imagemagick.org/</a></p>
<p>there you have a tool called identify which you can either use in combination with a script/stdout or you can use the programming interface provided</p>
| 6 | 2009-09-09T19:18:41Z | [
"php",
"python",
"image"
] |
How do I programmatically check whether an image (PNG, JPEG, or GIF) is corrupted? | 1,401,527 | <p>Okay. So I have about 250,000 high resolution images. What I want to do is go through all of them and find ones that are corrupted. If you know what 4scrape is, then you know the nature of the images I.</p>
<p>Corrupted, to me, is the image is loaded into Firefox and it says</p>
<blockquote>
<p><code>The image âsuch and such imageâ cannot be displayed, because it contains errors.</code></p>
</blockquote>
<p>Now, I could select all of my 250,000 images (~150gb) and drag-n-drop them into Firefox. That would be bad though, because I don't think Mozilla designed Firefox to open 250,000 tabs. No, I need a way to programmatically check whether an image is corrupted.</p>
<p>Does anyone know a PHP or Python library which can do something along these lines? Or an existing piece of software for Windows?</p>
<p>I have already removed obviously corrupted images (such as ones that are 0 bytes) but I'm about 99.9% sure that there are more diseased images floating around in my throng of a collection.</p>
| 14 | 2009-09-09T19:15:41Z | 1,401,565 | <p>An easy way would be to try loading and verifying the files with PIL (Python Imaging Library).</p>
<pre><code>from PIL import Image
v_image = Image.open(file)
v_image.verify()
</code></pre>
<p>Catch the exceptions...</p>
<p>From <a href="http://effbot.org/imagingbook/image.htm">the documentation</a>:</p>
<p><strong>im.verify()</strong></p>
<p><em>Attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. This method only works on a newly opened image; if the image has already been loaded, the result is undefined. Also, if you need to load the image after using this method, you must reopen the image file.</em></p>
| 20 | 2009-09-09T19:24:10Z | [
"php",
"python",
"image"
] |
How do I programmatically check whether an image (PNG, JPEG, or GIF) is corrupted? | 1,401,527 | <p>Okay. So I have about 250,000 high resolution images. What I want to do is go through all of them and find ones that are corrupted. If you know what 4scrape is, then you know the nature of the images I.</p>
<p>Corrupted, to me, is the image is loaded into Firefox and it says</p>
<blockquote>
<p><code>The image âsuch and such imageâ cannot be displayed, because it contains errors.</code></p>
</blockquote>
<p>Now, I could select all of my 250,000 images (~150gb) and drag-n-drop them into Firefox. That would be bad though, because I don't think Mozilla designed Firefox to open 250,000 tabs. No, I need a way to programmatically check whether an image is corrupted.</p>
<p>Does anyone know a PHP or Python library which can do something along these lines? Or an existing piece of software for Windows?</p>
<p>I have already removed obviously corrupted images (such as ones that are 0 bytes) but I'm about 99.9% sure that there are more diseased images floating around in my throng of a collection.</p>
| 14 | 2009-09-09T19:15:41Z | 1,401,566 | <p>If your exact requirements are that it show correctly <em>in FireFox</em> you may have a difficult time - the only way to be sure would be to link to the exact same image loading source code as FireFox.</p>
<p>Basic image corruption (file is incomplete) can be detected simply by trying to open the file using any number of image libraries.</p>
<p>However many images can fail to display simply because they stretch a part of the file format that the particular viewer you are using can't handle (GIF in particular has a lot of these edge cases, but you can find JPEG and the rare PNG file that can only be displayed in specific viewers). There are also some ugly JPEG edge cases where the file <em>appears</em> to be uncorrupted in viewer X, but in reality the file has been cut short and is only displaying correctly because very little information has been lost (FireFox can show some cut off JPEGs correctly [you get a grey bottom], but others result in FireFox seeming the load them half way and then display the error message instead of the partial image)</p>
| 3 | 2009-09-09T19:24:44Z | [
"php",
"python",
"image"
] |
How do I programmatically check whether an image (PNG, JPEG, or GIF) is corrupted? | 1,401,527 | <p>Okay. So I have about 250,000 high resolution images. What I want to do is go through all of them and find ones that are corrupted. If you know what 4scrape is, then you know the nature of the images I.</p>
<p>Corrupted, to me, is the image is loaded into Firefox and it says</p>
<blockquote>
<p><code>The image âsuch and such imageâ cannot be displayed, because it contains errors.</code></p>
</blockquote>
<p>Now, I could select all of my 250,000 images (~150gb) and drag-n-drop them into Firefox. That would be bad though, because I don't think Mozilla designed Firefox to open 250,000 tabs. No, I need a way to programmatically check whether an image is corrupted.</p>
<p>Does anyone know a PHP or Python library which can do something along these lines? Or an existing piece of software for Windows?</p>
<p>I have already removed obviously corrupted images (such as ones that are 0 bytes) but I'm about 99.9% sure that there are more diseased images floating around in my throng of a collection.</p>
| 14 | 2009-09-09T19:15:41Z | 1,402,740 | <p>In PHP, with <a href="http://php.net/manual/en/function.exif-imagetype.php" rel="nofollow">exif_imagetype()</a>:</p>
<pre><code>if (exif_imagetype($filename) === false)
{
unlink($filename); // image is corrupted
}
</code></pre>
<p><strong>EDIT</strong>: Or you can try to fully load the image with <a href="http://php.net/manual/en/function.imagecreatefromstring.php" rel="nofollow">ImageCreateFromString()</a>:</p>
<pre><code>if (ImageCreateFromString(file_get_contents($filename)) === false)
{
unlink($filename); // image is corrupted
}
</code></pre>
<blockquote>
<p>An image resource will be returned on
success. <strong>FALSE is returned if</strong> the
image type is unsupported, the data is
not in a recognized format, or <strong>the
image is corrupt</strong> and cannot be loaded.</p>
</blockquote>
| 4 | 2009-09-09T23:50:44Z | [
"php",
"python",
"image"
] |
How do I programmatically check whether an image (PNG, JPEG, or GIF) is corrupted? | 1,401,527 | <p>Okay. So I have about 250,000 high resolution images. What I want to do is go through all of them and find ones that are corrupted. If you know what 4scrape is, then you know the nature of the images I.</p>
<p>Corrupted, to me, is the image is loaded into Firefox and it says</p>
<blockquote>
<p><code>The image âsuch and such imageâ cannot be displayed, because it contains errors.</code></p>
</blockquote>
<p>Now, I could select all of my 250,000 images (~150gb) and drag-n-drop them into Firefox. That would be bad though, because I don't think Mozilla designed Firefox to open 250,000 tabs. No, I need a way to programmatically check whether an image is corrupted.</p>
<p>Does anyone know a PHP or Python library which can do something along these lines? Or an existing piece of software for Windows?</p>
<p>I have already removed obviously corrupted images (such as ones that are 0 bytes) but I'm about 99.9% sure that there are more diseased images floating around in my throng of a collection.</p>
| 14 | 2009-09-09T19:15:41Z | 2,335,797 | <p>You could use imagemagick if it is available:</p>
<p>if you want to do a whole folder</p>
<pre><code>identify "./myfolder/*" >log.txt 2>&1
</code></pre>
<p>if you want to just check a file:</p>
<pre><code>identify myfile.jpg
</code></pre>
| 0 | 2010-02-25T16:45:55Z | [
"php",
"python",
"image"
] |
Python: copy.deepcopy produces an error | 1,401,610 | <p>I have been using this copy method for quite a while, in lots of classes that needed it.</p>
<pre><code>class population (list):
def __init__ (self):
pass
def copy(self):
return copy.deepcopy(self)
</code></pre>
<p>It has suddenly started producing this error:</p>
<pre><code> File "C:\Python26\lib\copy.py", line 338, in _reconstruct
state = deepcopy(state, memo)
File "C:\Python26\lib\copy.py", line 162, in deepcopy
y = copier(x, memo)
File "C:\Python26\lib\copy.py", line 255, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File "C:\Python26\lib\copy.py", line 189, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "C:\Python26\lib\copy.py", line 323, in _reconstruct
y = callable(*args)
File "C:\Python26\lib\copy_reg.py", line 93, in __newobj__
return cls.__new__(cls, *args)
TypeError: object.__new__(generator) is not safe, use generator.__new__()
>>>
</code></pre>
<p>the lines which include the references to lines 338, 162, 255, 189 were repeated quite a few times before the 'line 338' that I copied here.</p>
| 2 | 2009-09-09T19:32:40Z | 1,401,640 | <p>Are you cloning a generator? <a href="https://mail.python.org/pipermail/python-list/2009-March/539759.html" rel="nofollow">Generators can't be cloned.</a></p>
<p>Copying answer by Gabriel Genellina here:</p>
<hr>
<p>There is no way of "cloning" a generator:</p>
<pre><code>py> g = (i for i in [1,2,3])
py> type(g)()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot create 'generator' instances
py> g.gi_code = code
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: readonly attribute
py> import copy
py> copy.copy(g)
Traceback (most recent call last):
...
TypeError: object.__new__(generator) is not safe, use generator.__new__()
py> type(g).__new__
<built-in method __new__ of type object at 0x1E1CA560>
</code></pre>
<p>You can do that with a generator function because it acts as a "generator<br>
factory", building a new generator when called. Even using the Python C<br>
API, to create a generator one needs a frame object -- and there is no way<br>
to create a frame object "on the fly" that I know of :(</p>
<pre><code>py> import ctypes
py> PyGen_New = ctypes.pythonapi.PyGen_New
py> PyGen_New.argtypes = [ctypes.py_object]
py> PyGen_New.restype = ctypes.py_object
py> g = (i for i in [1,2,3])
py> g2 = PyGen_New(g.gi_frame)
py> g2.gi_code is g.gi_code
True
py> g2.gi_frame is g.gi_frame
True
py> g.next()
1
py> g2.next()
2
</code></pre>
<p>g and g2 share the same execution frame, so they're not independent. There<br>
is no easy way to create a new frame in Python:</p>
<pre><code>py> type(g.gi_frame)()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot create 'frame' instances
</code></pre>
<p>One could try using PyFrame_New -- but that's way too magic for my taste...</p>
| 9 | 2009-09-09T19:38:33Z | [
"python",
"generator"
] |
Problem with list of strings in python | 1,401,650 | <p>Why on Earth doesn't the interpreter raise SyntaxError everytime I do this:</p>
<pre><code>my_abc = ['a',
'b',
'c'
'd',]
</code></pre>
<p>I just wanted to add 'c' to the list of strings, and forgot to append the comma. I would expect this to cause some kind of error, as it's cleary incorrect. </p>
<p>Instead, what I got:</p>
<pre><code>>>> my_abc
['a', 'b', 'cd']
</code></pre>
<p>And this is <strong>never</strong> what I want. </p>
<p>Why is it automatically concatenated? I can hardly count how many times I got bitten by this behavior.
Is there anything I can do with it?</p>
<p><strong>Just to clarify*</strong>: I don't actually mind auto-concatenation, my problem has to do ONLY with lists of strings, because they often do much more than just carry text, they're used to control flow, to pass field names and many other things. </p>
| 5 | 2009-09-09T19:40:07Z | 1,401,670 | <p>It's by design. It allows, for example, writing long string literals in several lines without using +.</p>
| 6 | 2009-09-09T19:42:38Z | [
"python",
"list"
] |
Problem with list of strings in python | 1,401,650 | <p>Why on Earth doesn't the interpreter raise SyntaxError everytime I do this:</p>
<pre><code>my_abc = ['a',
'b',
'c'
'd',]
</code></pre>
<p>I just wanted to add 'c' to the list of strings, and forgot to append the comma. I would expect this to cause some kind of error, as it's cleary incorrect. </p>
<p>Instead, what I got:</p>
<pre><code>>>> my_abc
['a', 'b', 'cd']
</code></pre>
<p>And this is <strong>never</strong> what I want. </p>
<p>Why is it automatically concatenated? I can hardly count how many times I got bitten by this behavior.
Is there anything I can do with it?</p>
<p><strong>Just to clarify*</strong>: I don't actually mind auto-concatenation, my problem has to do ONLY with lists of strings, because they often do much more than just carry text, they're used to control flow, to pass field names and many other things. </p>
| 5 | 2009-09-09T19:40:07Z | 1,401,677 | <p>Because two string literals side-by-side, delimited by whitespace, are concatenated. Since the strings are within a list, they are 'side-by-side'.</p>
<p>See: <a href="http://docs.python.org/reference/lexical%5Fanalysis.html#string-literal-concatenation" rel="nofollow">http://docs.python.org/reference/lexical%5Fanalysis.html#string-literal-concatenation</a></p>
| 3 | 2009-09-09T19:43:21Z | [
"python",
"list"
] |
Problem with list of strings in python | 1,401,650 | <p>Why on Earth doesn't the interpreter raise SyntaxError everytime I do this:</p>
<pre><code>my_abc = ['a',
'b',
'c'
'd',]
</code></pre>
<p>I just wanted to add 'c' to the list of strings, and forgot to append the comma. I would expect this to cause some kind of error, as it's cleary incorrect. </p>
<p>Instead, what I got:</p>
<pre><code>>>> my_abc
['a', 'b', 'cd']
</code></pre>
<p>And this is <strong>never</strong> what I want. </p>
<p>Why is it automatically concatenated? I can hardly count how many times I got bitten by this behavior.
Is there anything I can do with it?</p>
<p><strong>Just to clarify*</strong>: I don't actually mind auto-concatenation, my problem has to do ONLY with lists of strings, because they often do much more than just carry text, they're used to control flow, to pass field names and many other things. </p>
| 5 | 2009-09-09T19:40:07Z | 1,401,685 | <p>Because often people want to do something like this:</p>
<pre><code>line = ("Here's a very long line, with no line breaks,"
" which should be displayed to the user (perhaps"
" as an error message or question box).")
</code></pre>
<p>It's easier to write this without having to manually concatenate strings. C, C++, and (I believe) Java and C# also have this behavior.</p>
| 2 | 2009-09-09T19:44:20Z | [
"python",
"list"
] |
Problem with list of strings in python | 1,401,650 | <p>Why on Earth doesn't the interpreter raise SyntaxError everytime I do this:</p>
<pre><code>my_abc = ['a',
'b',
'c'
'd',]
</code></pre>
<p>I just wanted to add 'c' to the list of strings, and forgot to append the comma. I would expect this to cause some kind of error, as it's cleary incorrect. </p>
<p>Instead, what I got:</p>
<pre><code>>>> my_abc
['a', 'b', 'cd']
</code></pre>
<p>And this is <strong>never</strong> what I want. </p>
<p>Why is it automatically concatenated? I can hardly count how many times I got bitten by this behavior.
Is there anything I can do with it?</p>
<p><strong>Just to clarify*</strong>: I don't actually mind auto-concatenation, my problem has to do ONLY with lists of strings, because they often do much more than just carry text, they're used to control flow, to pass field names and many other things. </p>
| 5 | 2009-09-09T19:40:07Z | 1,401,691 | <p>Is called "Implicit String Concatenation" and a PEP that proposed its removal was rejected: <a href="http://www.python.org/dev/peps/pep-3126/">http://www.python.org/dev/peps/pep-3126/</a></p>
| 12 | 2009-09-09T19:45:15Z | [
"python",
"list"
] |
Problem with list of strings in python | 1,401,650 | <p>Why on Earth doesn't the interpreter raise SyntaxError everytime I do this:</p>
<pre><code>my_abc = ['a',
'b',
'c'
'd',]
</code></pre>
<p>I just wanted to add 'c' to the list of strings, and forgot to append the comma. I would expect this to cause some kind of error, as it's cleary incorrect. </p>
<p>Instead, what I got:</p>
<pre><code>>>> my_abc
['a', 'b', 'cd']
</code></pre>
<p>And this is <strong>never</strong> what I want. </p>
<p>Why is it automatically concatenated? I can hardly count how many times I got bitten by this behavior.
Is there anything I can do with it?</p>
<p><strong>Just to clarify*</strong>: I don't actually mind auto-concatenation, my problem has to do ONLY with lists of strings, because they often do much more than just carry text, they're used to control flow, to pass field names and many other things. </p>
| 5 | 2009-09-09T19:40:07Z | 1,402,033 | <p>As others said, it's by design.</p>
<p>Why is it so ? Mostly for historical reasons : C also does it.</p>
<p>In some cases it's handy because it reduce syntaxic noise and avoid adding unwanted spaces (inline SQL queries, complexes regexpes, etc).</p>
<p>What you can do about it ? Not much, but if it really happens often for you, try one of the following tricks.</p>
<ul>
<li>indent your list with coma at the beginning of the line. It's weird, but if you do so the missing comas become obvious.</li>
<li>assign strings to variables and use variables list whenever you can (and it's often a good idea for other reasons, like avoiding duplicate strings).</li>
<li><p>split your list: for list of words you can put the whole list inside only one string and split it like below. For more than 5 elements it's also shorter.</p>
<p>'a b c d e'.split(' ').</p></li>
</ul>
| 2 | 2009-09-09T20:54:48Z | [
"python",
"list"
] |
Python: List all base classes in a hierarchy of given class | 1,401,661 | <p>Given a class <code>Foo</code> (whether it is a <a href="http://docs.python.org/reference/datamodel.html#new-style-and-classic-classes">new-style</a> class or not), how do you generate <strong>all</strong> the base classes - anywhere in the inheritance hierarchy - it <a href="http://docs.python.org/library/functions.html?highlight=issubclass#issubclass"><code>issubclass</code></a> of?</p>
| 65 | 2009-09-09T19:41:52Z | 1,401,706 | <p>you can use the <code>__bases__</code> tuple of the class object:</p>
<pre><code>class A(object, B, C):
def __init__(self):
pass
print A.__bases__
</code></pre>
<p>The tuple returned by <code>__bases__</code> has all its base classes.</p>
<p>Hope it helps!</p>
| 12 | 2009-09-09T19:47:49Z | [
"python",
"class",
"inheritance",
"oop",
"introspection"
] |
Python: List all base classes in a hierarchy of given class | 1,401,661 | <p>Given a class <code>Foo</code> (whether it is a <a href="http://docs.python.org/reference/datamodel.html#new-style-and-classic-classes">new-style</a> class or not), how do you generate <strong>all</strong> the base classes - anywhere in the inheritance hierarchy - it <a href="http://docs.python.org/library/functions.html?highlight=issubclass#issubclass"><code>issubclass</code></a> of?</p>
| 65 | 2009-09-09T19:41:52Z | 1,401,707 | <p><code>inspect.getclasstree()</code> will create a nested list of classes and their bases.
Usage:</p>
<pre><code>inspect.getclasstree(inspect.getmro(IOError)) # Insert your Class instead of IOError.
</code></pre>
| 19 | 2009-09-09T19:47:54Z | [
"python",
"class",
"inheritance",
"oop",
"introspection"
] |
Python: List all base classes in a hierarchy of given class | 1,401,661 | <p>Given a class <code>Foo</code> (whether it is a <a href="http://docs.python.org/reference/datamodel.html#new-style-and-classic-classes">new-style</a> class or not), how do you generate <strong>all</strong> the base classes - anywhere in the inheritance hierarchy - it <a href="http://docs.python.org/library/functions.html?highlight=issubclass#issubclass"><code>issubclass</code></a> of?</p>
| 65 | 2009-09-09T19:41:52Z | 1,401,708 | <p>See the <a href="http://docs.python.org/library/stdtypes.html#special-attributes"><code>__bases__</code> property</a> available on a python <code>class</code>, which contains a tuple of the bases classes:</p>
<pre><code>>>> def classlookup(cls):
... c = list(cls.__bases__)
... for base in c:
... c.extend(classlookup(base))
... return c
...
>>> class A: pass
...
>>> class B(A): pass
...
>>> class C(object, B): pass
...
>>> classlookup(C)
[<type 'object'>, <class __main__.B at 0x00AB7300>, <class __main__.A at 0x00A6D630>]
</code></pre>
| 23 | 2009-09-09T19:48:12Z | [
"python",
"class",
"inheritance",
"oop",
"introspection"
] |
Python: List all base classes in a hierarchy of given class | 1,401,661 | <p>Given a class <code>Foo</code> (whether it is a <a href="http://docs.python.org/reference/datamodel.html#new-style-and-classic-classes">new-style</a> class or not), how do you generate <strong>all</strong> the base classes - anywhere in the inheritance hierarchy - it <a href="http://docs.python.org/library/functions.html?highlight=issubclass#issubclass"><code>issubclass</code></a> of?</p>
| 65 | 2009-09-09T19:41:52Z | 1,401,900 | <p><code>inspect.getmro(cls)</code> works for both new and old style classes and returns the same as <code>NewClass.mro()</code>: a list of the class and all its base classes.</p>
<pre><code>>>> class A(object):
>>> pass
>>>
>>> class B(A):
>>> pass
>>>
>>> import inspect
>>> inspect.getmro(B)
(<class '__main__.B'>, <class '__main__.A'>, <type 'object'>)
</code></pre>
| 102 | 2009-09-09T20:28:21Z | [
"python",
"class",
"inheritance",
"oop",
"introspection"
] |
How can the euclidean distance be calculated with numpy? | 1,401,712 | <p>I have two points in 3D:</p>
<pre><code>(xa, ya, za)
(xb, yb, zb)
</code></pre>
<p>And I want to calculate the distance:</p>
<pre><code>dist = sqrt((xa-xb)^2 + (ya-yb)^2 + (za-zb)^2)
</code></pre>
<p>What's the best way to do this with Numpy, or with Python in general? I have:</p>
<pre><code>a = numpy.array((xa ,ya, za))
b = numpy.array((xb, yb, zb))
</code></pre>
| 150 | 2009-09-09T19:48:49Z | 1,401,755 | <p>Another instance of <a href="http://stackoverflow.com/questions/13289/can-you-share-your-secrets-or-best-practices-for-problem-solving/13336#13336">this problem solving method</a>. As soon as I submitted the question I got it:</p>
<pre><code>def dist(x,y):
return numpy.sqrt(numpy.sum((x-y)**2))
a = numpy.array((xa,ya,za))
b = numpy.array((xb,yb,zb))
dist_a_b = dist(a,b)
</code></pre>
| 16 | 2009-09-09T19:56:36Z | [
"python",
"numpy",
"euclidean-distance"
] |
How can the euclidean distance be calculated with numpy? | 1,401,712 | <p>I have two points in 3D:</p>
<pre><code>(xa, ya, za)
(xb, yb, zb)
</code></pre>
<p>And I want to calculate the distance:</p>
<pre><code>dist = sqrt((xa-xb)^2 + (ya-yb)^2 + (za-zb)^2)
</code></pre>
<p>What's the best way to do this with Numpy, or with Python in general? I have:</p>
<pre><code>a = numpy.array((xa ,ya, za))
b = numpy.array((xb, yb, zb))
</code></pre>
| 150 | 2009-09-09T19:48:49Z | 1,401,828 | <p>Use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.norm.html"><code>numpy.linalg.norm</code></a>:</p>
<pre><code>dist = numpy.linalg.norm(a-b)
</code></pre>
| 265 | 2009-09-09T20:12:50Z | [
"python",
"numpy",
"euclidean-distance"
] |
How can the euclidean distance be calculated with numpy? | 1,401,712 | <p>I have two points in 3D:</p>
<pre><code>(xa, ya, za)
(xb, yb, zb)
</code></pre>
<p>And I want to calculate the distance:</p>
<pre><code>dist = sqrt((xa-xb)^2 + (ya-yb)^2 + (za-zb)^2)
</code></pre>
<p>What's the best way to do this with Numpy, or with Python in general? I have:</p>
<pre><code>a = numpy.array((xa ,ya, za))
b = numpy.array((xb, yb, zb))
</code></pre>
| 150 | 2009-09-09T19:48:49Z | 4,169,284 | <pre><code>dist = numpy.linalg.norm(a-b)
</code></pre>
<p>Is a nice one line answer. However, if speed is a concern I would recommend experimenting on your machine. I found that using the <code>math</code> library's <code>sqrt</code> with the <code>**</code> operator for the square is much faster on my machine than the one line, numpy solution. </p>
<p>I ran my tests using this simple program:</p>
<pre><code>#!/usr/bin/python
import math
import numpy
from random import uniform
def fastest_calc_dist(p1,p2):
return math.sqrt((p2[0] - p1[0]) ** 2 +
(p2[1] - p1[1]) ** 2 +
(p2[2] - p1[2]) ** 2)
def math_calc_dist(p1,p2):
return math.sqrt(math.pow((p2[0] - p1[0]), 2) +
math.pow((p2[1] - p1[1]), 2) +
math.pow((p2[2] - p1[2]), 2))
def numpy_calc_dist(p1,p2):
return numpy.linalg.norm(numpy.array(p1)-numpy.array(p2))
TOTAL_LOCATIONS = 1000
p1 = dict()
p2 = dict()
for i in range(0, TOTAL_LOCATIONS):
p1[i] = (uniform(0,1000),uniform(0,1000),uniform(0,1000))
p2[i] = (uniform(0,1000),uniform(0,1000),uniform(0,1000))
total_dist = 0
for i in range(0, TOTAL_LOCATIONS):
for j in range(0, TOTAL_LOCATIONS):
dist = fastest_calc_dist(p1[i], p2[j]) #change this line for testing
total_dist += dist
print total_dist
</code></pre>
<p>On my machine, <code>math_calc_dist</code> runs much faster than <code>numpy_calc_dist</code>: <strong>1.5 seconds</strong> versus <strong>23.5 seconds</strong>.</p>
<p>To get a measurable difference between <code>fastest_calc_dist</code> and <code>math_calc_dist</code> I had to up <code>TOTAL_LOCATIONS</code> to 6000. Then <code>fastest_calc_dist</code> takes <strong>~50 seconds</strong> while <code>math_calc_dist</code> takes <strong>~60 seconds</strong>.</p>
<p>You can also experiment with <code>numpy.sqrt</code> and <code>numpy.square</code> though both were slower than the <code>math</code> alternatives on my machine.</p>
<p>My tests were run with Python 2.6.6.</p>
| 3 | 2010-11-12T21:40:53Z | [
"python",
"numpy",
"euclidean-distance"
] |
How can the euclidean distance be calculated with numpy? | 1,401,712 | <p>I have two points in 3D:</p>
<pre><code>(xa, ya, za)
(xb, yb, zb)
</code></pre>
<p>And I want to calculate the distance:</p>
<pre><code>dist = sqrt((xa-xb)^2 + (ya-yb)^2 + (za-zb)^2)
</code></pre>
<p>What's the best way to do this with Numpy, or with Python in general? I have:</p>
<pre><code>a = numpy.array((xa ,ya, za))
b = numpy.array((xb, yb, zb))
</code></pre>
| 150 | 2009-09-09T19:48:49Z | 7,373,947 | <p>You can just substract the vectors and then innerproduct.</p>
<p>Following your example</p>
<pre><code>a = numpy.array((xa,ya,za))
b = numpy.array((xb,yb,zb))
tmp = a - b
sum_squared = numpy.dot(tmp.T , tmp)
result sqrt(sum_squared)
</code></pre>
<p>Simple Code an easy to understand.</p>
| 2 | 2011-09-10T19:08:12Z | [
"python",
"numpy",
"euclidean-distance"
] |
How can the euclidean distance be calculated with numpy? | 1,401,712 | <p>I have two points in 3D:</p>
<pre><code>(xa, ya, za)
(xb, yb, zb)
</code></pre>
<p>And I want to calculate the distance:</p>
<pre><code>dist = sqrt((xa-xb)^2 + (ya-yb)^2 + (za-zb)^2)
</code></pre>
<p>What's the best way to do this with Numpy, or with Python in general? I have:</p>
<pre><code>a = numpy.array((xa ,ya, za))
b = numpy.array((xb, yb, zb))
</code></pre>
| 150 | 2009-09-09T19:48:49Z | 13,155,932 | <p>Can be done like this, don't know how fast it is but its no numpy.</p>
<pre><code>from math import sqrt
a = (1,2,3) #data point 1
b = (4,5,6) #data point 2
print sqrt(sum( (a - b)**2 for a, b in zip(a, b)))
</code></pre>
| 6 | 2012-10-31T10:33:48Z | [
"python",
"numpy",
"euclidean-distance"
] |
How can the euclidean distance be calculated with numpy? | 1,401,712 | <p>I have two points in 3D:</p>
<pre><code>(xa, ya, za)
(xb, yb, zb)
</code></pre>
<p>And I want to calculate the distance:</p>
<pre><code>dist = sqrt((xa-xb)^2 + (ya-yb)^2 + (za-zb)^2)
</code></pre>
<p>What's the best way to do this with Numpy, or with Python in general? I have:</p>
<pre><code>a = numpy.array((xa ,ya, za))
b = numpy.array((xb, yb, zb))
</code></pre>
| 150 | 2009-09-09T19:48:49Z | 20,943,162 | <p>I find a 'dist' function in matplotlib.mlab, but i don't think it's handy enough. I'm posting it here just for reference.</p>
<pre><code>import numpy as np
import matplotlib as plt
a = np.array([1,2,3])
b = np.array([2,3,4])
# distance between a and b
dis = plt.mlab.dist(a,b)
</code></pre>
| 5 | 2014-01-06T04:46:53Z | [
"python",
"numpy",
"euclidean-distance"
] |
How can the euclidean distance be calculated with numpy? | 1,401,712 | <p>I have two points in 3D:</p>
<pre><code>(xa, ya, za)
(xb, yb, zb)
</code></pre>
<p>And I want to calculate the distance:</p>
<pre><code>dist = sqrt((xa-xb)^2 + (ya-yb)^2 + (za-zb)^2)
</code></pre>
<p>What's the best way to do this with Numpy, or with Python in general? I have:</p>
<pre><code>a = numpy.array((xa ,ya, za))
b = numpy.array((xb, yb, zb))
</code></pre>
| 150 | 2009-09-09T19:48:49Z | 21,986,532 | <p>There's a function for that in SciPy, it's called <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.euclidean.html#scipy.spatial.distance.euclidean">Euclidean</a></p>
<p>example:</p>
<pre><code>from scipy.spatial import distance
a = (1,2,3)
b = (4,5,6)
dst = distance.euclidean(a,b)
</code></pre>
| 41 | 2014-02-24T11:32:29Z | [
"python",
"numpy",
"euclidean-distance"
] |
How can the euclidean distance be calculated with numpy? | 1,401,712 | <p>I have two points in 3D:</p>
<pre><code>(xa, ya, za)
(xb, yb, zb)
</code></pre>
<p>And I want to calculate the distance:</p>
<pre><code>dist = sqrt((xa-xb)^2 + (ya-yb)^2 + (za-zb)^2)
</code></pre>
<p>What's the best way to do this with Numpy, or with Python in general? I have:</p>
<pre><code>a = numpy.array((xa ,ya, za))
b = numpy.array((xb, yb, zb))
</code></pre>
| 150 | 2009-09-09T19:48:49Z | 37,283,639 | <p>Here's some concise code for Euclidean distance in Python given two points represented as lists in Python.</p>
<pre><code>def distance(v1,v2):
return sum([(x-y)**2 for (x,y) in zip(v1,v2)])**(0.5)
</code></pre>
| 1 | 2016-05-17T18:22:33Z | [
"python",
"numpy",
"euclidean-distance"
] |
How can the euclidean distance be calculated with numpy? | 1,401,712 | <p>I have two points in 3D:</p>
<pre><code>(xa, ya, za)
(xb, yb, zb)
</code></pre>
<p>And I want to calculate the distance:</p>
<pre><code>dist = sqrt((xa-xb)^2 + (ya-yb)^2 + (za-zb)^2)
</code></pre>
<p>What's the best way to do this with Numpy, or with Python in general? I have:</p>
<pre><code>a = numpy.array((xa ,ya, za))
b = numpy.array((xb, yb, zb))
</code></pre>
| 150 | 2009-09-09T19:48:49Z | 39,301,337 | <p>I like np.dot (dot product): </p>
<pre><code>a = numpy.array((xa,ya,za))
b = numpy.array((xb,yb,zb))
distance = (np.dot(a-b,a-b))**.5
</code></pre>
| 1 | 2016-09-02T22:14:11Z | [
"python",
"numpy",
"euclidean-distance"
] |
Convert list of objects to a list of integers and a lookup table | 1,401,721 | <p>To illustrate what I mean by this, here is an example</p>
<pre><code>messages = [
('Ricky', 'Steve', 'SMS'),
('Steve', 'Karl', 'SMS'),
('Karl', 'Nora', 'Email')
]
</code></pre>
<p>I want to convert this list and a definition of groups to a list of integers and a lookup dictionary so that each element in the group gets a unique id. That id should map to the element in the lookup table like this</p>
<pre><code>messages_int, lookup_table = create_lookup_list(
messages, ('person', 'person', 'medium'))
print messages_int
[ (0, 1, 0),
(1, 2, 0),
(2, 3, 1) ]
print lookup_table
{ 'person': ['Ricky', 'Steve', 'Karl', 'Nora'],
'medium': ['SMS', 'Email']
}
</code></pre>
<p>I wonder if there is an elegant and pythonic solution to this problem. </p>
<p>I am also open to better terminology than <code>create_lookup_list</code> etc</p>
| 4 | 2009-09-09T19:50:22Z | 1,401,738 | <p>Here is my own solution - I doubt it's the best</p>
<pre><code>def create_lookup_list(input_list, groups):
# use a dictionary for the indices so that the index lookup
# is fast (not necessarily a requirement)
indices = dict((group, {}) for group in groups)
output = []
# assign indices by iterating through the list
for row in input_list:
newrow = []
for group, element in zip(groups, row):
if element in indices[group]:
index = indices[group][element]
else:
index = indices[group][element] = len(indices[group])
newrow.append(index)
output.append(newrow)
# create the lookup table
lookup_dict = {}
for group in indices:
lookup_dict[group] = sorted(indices[group].keys(),
lambda e1, e2: indices[group][e1]-indices[group][e2])
return output, lookup_dict
</code></pre>
| 1 | 2009-09-09T19:53:48Z | [
"python",
"lookup"
] |
Convert list of objects to a list of integers and a lookup table | 1,401,721 | <p>To illustrate what I mean by this, here is an example</p>
<pre><code>messages = [
('Ricky', 'Steve', 'SMS'),
('Steve', 'Karl', 'SMS'),
('Karl', 'Nora', 'Email')
]
</code></pre>
<p>I want to convert this list and a definition of groups to a list of integers and a lookup dictionary so that each element in the group gets a unique id. That id should map to the element in the lookup table like this</p>
<pre><code>messages_int, lookup_table = create_lookup_list(
messages, ('person', 'person', 'medium'))
print messages_int
[ (0, 1, 0),
(1, 2, 0),
(2, 3, 1) ]
print lookup_table
{ 'person': ['Ricky', 'Steve', 'Karl', 'Nora'],
'medium': ['SMS', 'Email']
}
</code></pre>
<p>I wonder if there is an elegant and pythonic solution to this problem. </p>
<p>I am also open to better terminology than <code>create_lookup_list</code> etc</p>
| 4 | 2009-09-09T19:50:22Z | 1,401,852 | <p>Mine's about the same length and complexity:</p>
<pre><code>import collections
def create_lookup_list(messages, labels):
# Collect all the values
lookup = collections.defaultdict(set)
for msg in messages:
for l, v in zip(labels, msg):
lookup[l].add(v)
# Make the value sets lists
for k, v in lookup.items():
lookup[k] = list(v)
# Make the lookup_list
lookup_list = []
for msg in messages:
lookup_list.append([lookup[l].index(v) for l, v in zip(labels, msg)])
return lookup_list, lookup
</code></pre>
| 2 | 2009-09-09T20:17:44Z | [
"python",
"lookup"
] |
Convert list of objects to a list of integers and a lookup table | 1,401,721 | <p>To illustrate what I mean by this, here is an example</p>
<pre><code>messages = [
('Ricky', 'Steve', 'SMS'),
('Steve', 'Karl', 'SMS'),
('Karl', 'Nora', 'Email')
]
</code></pre>
<p>I want to convert this list and a definition of groups to a list of integers and a lookup dictionary so that each element in the group gets a unique id. That id should map to the element in the lookup table like this</p>
<pre><code>messages_int, lookup_table = create_lookup_list(
messages, ('person', 'person', 'medium'))
print messages_int
[ (0, 1, 0),
(1, 2, 0),
(2, 3, 1) ]
print lookup_table
{ 'person': ['Ricky', 'Steve', 'Karl', 'Nora'],
'medium': ['SMS', 'Email']
}
</code></pre>
<p>I wonder if there is an elegant and pythonic solution to this problem. </p>
<p>I am also open to better terminology than <code>create_lookup_list</code> etc</p>
| 4 | 2009-09-09T19:50:22Z | 1,401,862 | <p>Here is my solution, it's not better - it's just different :)</p>
<pre><code>def create_lookup_list(data, keys):
encoded = []
table = dict([(key, []) for key in keys])
for record in data:
msg_int = []
for key, value in zip(keys, record):
if value not in table[key]:
table[key].append(value)
msg_int.append(table[key].index(value))
encoded.append(tuple(msg_int))
return encoded, table
</code></pre>
| 0 | 2009-09-09T20:20:25Z | [
"python",
"lookup"
] |
Convert list of objects to a list of integers and a lookup table | 1,401,721 | <p>To illustrate what I mean by this, here is an example</p>
<pre><code>messages = [
('Ricky', 'Steve', 'SMS'),
('Steve', 'Karl', 'SMS'),
('Karl', 'Nora', 'Email')
]
</code></pre>
<p>I want to convert this list and a definition of groups to a list of integers and a lookup dictionary so that each element in the group gets a unique id. That id should map to the element in the lookup table like this</p>
<pre><code>messages_int, lookup_table = create_lookup_list(
messages, ('person', 'person', 'medium'))
print messages_int
[ (0, 1, 0),
(1, 2, 0),
(2, 3, 1) ]
print lookup_table
{ 'person': ['Ricky', 'Steve', 'Karl', 'Nora'],
'medium': ['SMS', 'Email']
}
</code></pre>
<p>I wonder if there is an elegant and pythonic solution to this problem. </p>
<p>I am also open to better terminology than <code>create_lookup_list</code> etc</p>
| 4 | 2009-09-09T19:50:22Z | 1,401,890 | <p>This is a bit simpler, and more direct.</p>
<pre><code>from collections import defaultdict
def create_lookup_list( messages, schema ):
def mapped_rows( messages ):
for row in messages:
newRow= []
for col, value in zip(schema,row):
if value not in lookups[col]:
lookups[col].append(value)
code= lookups[col].index(value)
newRow.append(code)
yield newRow
lookups = defaultdict(list)
return list( mapped_rows(messages) ), dict(lookups)
</code></pre>
<p>If the lookups were proper dictionaries, not lists, this could be simplified further.<br />
Make your "lookup table" have the following structure</p>
<pre><code>{ 'person': {'Ricky':0, 'Steve':1, 'Karl':2, 'Nora':3},
'medium': {'SMS':0, 'Email':1}
}
</code></pre>
<p>And it can be further reduced in complexity. </p>
<p>You can turn this working copy of the lookups into it's inverse as follows:</p>
<pre><code>>>> lookups = { 'person': {'Ricky':0, 'Steve':1, 'Karl':2, 'Nora':3},
'medium': {'SMS':0, 'Email':1}
}
>>> dict( ( d, dict( (v,k) for k,v in lookups[d].items() ) ) for d in lookups )
{'person': {0: 'Ricky', 1: 'Steve', 2: 'Karl', 3: 'Nora'}, 'medium': {0: 'SMS', 1: 'Email'}}
</code></pre>
| 1 | 2009-09-09T20:26:21Z | [
"python",
"lookup"
] |
Convert list of objects to a list of integers and a lookup table | 1,401,721 | <p>To illustrate what I mean by this, here is an example</p>
<pre><code>messages = [
('Ricky', 'Steve', 'SMS'),
('Steve', 'Karl', 'SMS'),
('Karl', 'Nora', 'Email')
]
</code></pre>
<p>I want to convert this list and a definition of groups to a list of integers and a lookup dictionary so that each element in the group gets a unique id. That id should map to the element in the lookup table like this</p>
<pre><code>messages_int, lookup_table = create_lookup_list(
messages, ('person', 'person', 'medium'))
print messages_int
[ (0, 1, 0),
(1, 2, 0),
(2, 3, 1) ]
print lookup_table
{ 'person': ['Ricky', 'Steve', 'Karl', 'Nora'],
'medium': ['SMS', 'Email']
}
</code></pre>
<p>I wonder if there is an elegant and pythonic solution to this problem. </p>
<p>I am also open to better terminology than <code>create_lookup_list</code> etc</p>
| 4 | 2009-09-09T19:50:22Z | 1,402,043 | <p>Here is mine, the inner function lets me write the index-tuple as a generator.</p>
<pre><code>def create_lookup_list( data, format):
table = {}
indices = []
def get_index( item, form ):
row = table.setdefault( form, [] )
try:
return row.index( item )
except ValueError:
n = len( row )
row.append( item )
return n
for row in data:
indices.append( tuple( get_index( item, form ) for item, form in zip( row, format ) ))
return table, indices
</code></pre>
| 0 | 2009-09-09T20:55:53Z | [
"python",
"lookup"
] |
Convert list of objects to a list of integers and a lookup table | 1,401,721 | <p>To illustrate what I mean by this, here is an example</p>
<pre><code>messages = [
('Ricky', 'Steve', 'SMS'),
('Steve', 'Karl', 'SMS'),
('Karl', 'Nora', 'Email')
]
</code></pre>
<p>I want to convert this list and a definition of groups to a list of integers and a lookup dictionary so that each element in the group gets a unique id. That id should map to the element in the lookup table like this</p>
<pre><code>messages_int, lookup_table = create_lookup_list(
messages, ('person', 'person', 'medium'))
print messages_int
[ (0, 1, 0),
(1, 2, 0),
(2, 3, 1) ]
print lookup_table
{ 'person': ['Ricky', 'Steve', 'Karl', 'Nora'],
'medium': ['SMS', 'Email']
}
</code></pre>
<p>I wonder if there is an elegant and pythonic solution to this problem. </p>
<p>I am also open to better terminology than <code>create_lookup_list</code> etc</p>
| 4 | 2009-09-09T19:50:22Z | 1,402,079 | <p>In Otto's answer (or anyone else's with string->id dicts), I'd replace (if obsessing over speed is your thing):</p>
<pre><code># create the lookup table
lookup_dict = {}
for group in indices:
lookup_dict[group] = sorted(indices[group].keys(),
lambda e1, e2: indices[group][e1]-indices[group][e2])
</code></pre>
<p>by</p>
<pre><code># k2i must map keys to consecutive ints [0,len(k2i)-1)
def inverse_indices(k2i):
inv=[0]*len(k2i)
for k,i in k2i.iteritems():
inv[i]=k
return inv
lookup_table = dict((g,inverse_indices(gi)) for g,gi in indices.iteritems())
</code></pre>
<p>This is better because direct assignment to each item in the inverse array directly is faster than sorting.</p>
| 2 | 2009-09-09T21:01:32Z | [
"python",
"lookup"
] |
Convert list of objects to a list of integers and a lookup table | 1,401,721 | <p>To illustrate what I mean by this, here is an example</p>
<pre><code>messages = [
('Ricky', 'Steve', 'SMS'),
('Steve', 'Karl', 'SMS'),
('Karl', 'Nora', 'Email')
]
</code></pre>
<p>I want to convert this list and a definition of groups to a list of integers and a lookup dictionary so that each element in the group gets a unique id. That id should map to the element in the lookup table like this</p>
<pre><code>messages_int, lookup_table = create_lookup_list(
messages, ('person', 'person', 'medium'))
print messages_int
[ (0, 1, 0),
(1, 2, 0),
(2, 3, 1) ]
print lookup_table
{ 'person': ['Ricky', 'Steve', 'Karl', 'Nora'],
'medium': ['SMS', 'Email']
}
</code></pre>
<p>I wonder if there is an elegant and pythonic solution to this problem. </p>
<p>I am also open to better terminology than <code>create_lookup_list</code> etc</p>
| 4 | 2009-09-09T19:50:22Z | 1,402,381 | <p><code>defaultdict</code> combined with the <code>itertools.count().next</code> method is a good way to assign identifiers to unique items. Here's an example of how to apply this in your case:</p>
<pre><code>from itertools import count
from collections import defaultdict
def create_lookup_list(data, domains):
domain_keys = defaultdict(lambda:defaultdict(count().next))
out = []
for row in data:
out.append(tuple(domain_keys[dom][val] for val, dom in zip(row, domains)))
lookup_table = dict((k, sorted(d, key=d.get)) for k, d in domain_keys.items())
return out, lookup_table
</code></pre>
<p>Edit: note that <code>count().next</code> becomes <code>count().__next__</code> or <code>lambda: next(count())</code> in Python 3.</p>
| 3 | 2009-09-09T22:04:41Z | [
"python",
"lookup"
] |
Why is there no list.clear() method in python? | 1,401,933 | <p>Inspired by <a href="http://stackoverflow.com/questions/1400608/how-to-empty-a-list-in-python">this question.</a></p>
<p>Why is there no list.clear() method in python? I've found several questions here that say the correct way to do it is one of the following, but no one has said why there isn't just a method for it.</p>
<pre><code>del lst[:]
lst[:] = []
</code></pre>
<p>While it may go against the "zen of python" to have more than one way of doing something, it certainly seems more obvious to me to have a "list.clear()" method. It would also fall in line with dicts and sets, both of which have .clear().</p>
<p>I came across a few posts to the python-dev and python-ideas concerning this and didn't come to a definitive answer (see <a href="http://mail.python.org/pipermail/python-list/2006-April/549512.html">here</a> (2006) and <a href="http://mail.python.org/pipermail/python-ideas/2009-April/003897.html">here</a> (2009)). Has Guido weighed in on it? Is it just a point of contention that hasn't been resolved yet over the last 4-5 years?</p>
<p><strong>Update:</strong> list.clear() was added to python in 3.3 - <a href="http://bugs.python.org/issue10516">see here</a></p>
| 36 | 2009-09-09T20:34:42Z | 1,402,256 | <p>In the threads you linked <a href="https://mail.python.org/pipermail/python-list/2006-April/384992.html" rel="nofollow">Raymond Hettinger pretty much sums up the pros and cons</a> of adding that method. When it comes to language design, it's really important to be conservative. See for example the <a href="http://blogs.msdn.com/ericgu/archive/2004/01/12/57985.aspx" rel="nofollow">"every feature starts with -100 points"</a> principle the C# team has. You don't get something as clean as Python by adding features willy-nilly. Just take a look at some of the more cruftier popular scripting languages to see where it takes you.</p>
<p>I guess the <code>.clear()</code> method just never did cross the implicit -100 points rule to become something worth adding to the core language. Although given that the methodname is already used for an equivalent purpose and the alternative can be hard to find, it probably isn't all that far from it.</p>
| 18 | 2009-09-09T21:40:04Z | [
"python",
"list",
"clear"
] |
Why is there no list.clear() method in python? | 1,401,933 | <p>Inspired by <a href="http://stackoverflow.com/questions/1400608/how-to-empty-a-list-in-python">this question.</a></p>
<p>Why is there no list.clear() method in python? I've found several questions here that say the correct way to do it is one of the following, but no one has said why there isn't just a method for it.</p>
<pre><code>del lst[:]
lst[:] = []
</code></pre>
<p>While it may go against the "zen of python" to have more than one way of doing something, it certainly seems more obvious to me to have a "list.clear()" method. It would also fall in line with dicts and sets, both of which have .clear().</p>
<p>I came across a few posts to the python-dev and python-ideas concerning this and didn't come to a definitive answer (see <a href="http://mail.python.org/pipermail/python-list/2006-April/549512.html">here</a> (2006) and <a href="http://mail.python.org/pipermail/python-ideas/2009-April/003897.html">here</a> (2009)). Has Guido weighed in on it? Is it just a point of contention that hasn't been resolved yet over the last 4-5 years?</p>
<p><strong>Update:</strong> list.clear() was added to python in 3.3 - <a href="http://bugs.python.org/issue10516">see here</a></p>
| 36 | 2009-09-09T20:34:42Z | 1,402,334 | <p>I can't answer to the why; but there absolutely should be one, so different types of objects can be cleared with the same interface.</p>
<p>An obvious, simple example:</p>
<pre><code>def process_and_clear_requests(reqs):
for r in reqs:
do_req(r)
reqs.clear()
</code></pre>
<p>This only requires that the object support iteration, and that it support clear(). If lists had a clear() method, this could accept a list or set equally. Instead, since sets and lists have a different API for deleting their contents, that doesn't work; you end up with an unnecessarily ugly hack, like:</p>
<pre><code>def process_and_clear_requests(reqs):
for r in reqs:
do_req(r)
if getattr(reqs, "clear"):
reqs.clear()
else:
del reqs[:]
</code></pre>
<p>As far as I'm concerned, using del obj[:] or obj[:] = [] are just unpleasant, unintuitive hacks to work around the fact that list is missing clear().</p>
<p>This is taking "reducing redundancy" to a fault, where it damages the <em>consistency</em> of the language, which is even more important.</p>
<p>As to which you should use, I'd recommend del obj[:]. I think it's easier to implement for non-list-like objects.</p>
| 6 | 2009-09-09T21:51:57Z | [
"python",
"list",
"clear"
] |
Why is there no list.clear() method in python? | 1,401,933 | <p>Inspired by <a href="http://stackoverflow.com/questions/1400608/how-to-empty-a-list-in-python">this question.</a></p>
<p>Why is there no list.clear() method in python? I've found several questions here that say the correct way to do it is one of the following, but no one has said why there isn't just a method for it.</p>
<pre><code>del lst[:]
lst[:] = []
</code></pre>
<p>While it may go against the "zen of python" to have more than one way of doing something, it certainly seems more obvious to me to have a "list.clear()" method. It would also fall in line with dicts and sets, both of which have .clear().</p>
<p>I came across a few posts to the python-dev and python-ideas concerning this and didn't come to a definitive answer (see <a href="http://mail.python.org/pipermail/python-list/2006-April/549512.html">here</a> (2006) and <a href="http://mail.python.org/pipermail/python-ideas/2009-April/003897.html">here</a> (2009)). Has Guido weighed in on it? Is it just a point of contention that hasn't been resolved yet over the last 4-5 years?</p>
<p><strong>Update:</strong> list.clear() was added to python in 3.3 - <a href="http://bugs.python.org/issue10516">see here</a></p>
| 36 | 2009-09-09T20:34:42Z | 6,675,045 | <p>While there was no <code>list.clear()</code> when this question was asked, 3.3 now has one (as requested in <a href="http://bugs.python.org/issue10516">http://bugs.python.org/issue10516</a>). Additionally, <code>clear()</code> methods have been added to <a href="http://docs.python.org/dev/library/functions.html#bytearray"><code>bytearray</code></a> and <a href="http://docs.python.org/dev/library/collections.abc.html#collections.abc.MutableSequence"><code>MutableSequence</code></a> to ease switching between lists and other collections (set, dict etc).</p>
<p>Full details of the change can be found <a href="http://docs.python.org/dev/whatsnew/3.3.html#other-language-changes">here</a>.</p>
| 13 | 2011-07-13T06:43:22Z | [
"python",
"list",
"clear"
] |
Why is there no list.clear() method in python? | 1,401,933 | <p>Inspired by <a href="http://stackoverflow.com/questions/1400608/how-to-empty-a-list-in-python">this question.</a></p>
<p>Why is there no list.clear() method in python? I've found several questions here that say the correct way to do it is one of the following, but no one has said why there isn't just a method for it.</p>
<pre><code>del lst[:]
lst[:] = []
</code></pre>
<p>While it may go against the "zen of python" to have more than one way of doing something, it certainly seems more obvious to me to have a "list.clear()" method. It would also fall in line with dicts and sets, both of which have .clear().</p>
<p>I came across a few posts to the python-dev and python-ideas concerning this and didn't come to a definitive answer (see <a href="http://mail.python.org/pipermail/python-list/2006-April/549512.html">here</a> (2006) and <a href="http://mail.python.org/pipermail/python-ideas/2009-April/003897.html">here</a> (2009)). Has Guido weighed in on it? Is it just a point of contention that hasn't been resolved yet over the last 4-5 years?</p>
<p><strong>Update:</strong> list.clear() was added to python in 3.3 - <a href="http://bugs.python.org/issue10516">see here</a></p>
| 36 | 2009-09-09T20:34:42Z | 13,714,092 | <p>The question should be why <code>clear</code> was deemed necessary in the first place. The following works to clear any Python collection that I can think of.</p>
<pre><code>def clear(x):
return type(x)()
>>> s = {1, 2, 3}
>>> s
set([1, 2, 3])
>>> s = clear(s)
>>> s
set([])
>>> l = [1, 2, 3]
>>> l
[1, 2, 3]
>>> l = clear(l)
>>> l
[]
</code></pre>
| -6 | 2012-12-04T23:54:39Z | [
"python",
"list",
"clear"
] |
Why is there no list.clear() method in python? | 1,401,933 | <p>Inspired by <a href="http://stackoverflow.com/questions/1400608/how-to-empty-a-list-in-python">this question.</a></p>
<p>Why is there no list.clear() method in python? I've found several questions here that say the correct way to do it is one of the following, but no one has said why there isn't just a method for it.</p>
<pre><code>del lst[:]
lst[:] = []
</code></pre>
<p>While it may go against the "zen of python" to have more than one way of doing something, it certainly seems more obvious to me to have a "list.clear()" method. It would also fall in line with dicts and sets, both of which have .clear().</p>
<p>I came across a few posts to the python-dev and python-ideas concerning this and didn't come to a definitive answer (see <a href="http://mail.python.org/pipermail/python-list/2006-April/549512.html">here</a> (2006) and <a href="http://mail.python.org/pipermail/python-ideas/2009-April/003897.html">here</a> (2009)). Has Guido weighed in on it? Is it just a point of contention that hasn't been resolved yet over the last 4-5 years?</p>
<p><strong>Update:</strong> list.clear() was added to python in 3.3 - <a href="http://bugs.python.org/issue10516">see here</a></p>
| 36 | 2009-09-09T20:34:42Z | 27,305,592 | <p>When testing, it is often useful to setup the data forming the domain of the tests in global variables, so that tests can build on one another if necessary/simpler.
In such cases, having a method to clear the list would allow you to do it without the need to declare those variables as global within a function (i.e. the tests).
I know, the tests should not depend on one another...</p>
| 0 | 2014-12-04T22:43:18Z | [
"python",
"list",
"clear"
] |
Script to connect to a web page | 1,401,941 | <p>Looking for a python script that would simply connect to a web page (maybe some querystring parameters).</p>
<p>I am going to run this script as a batch job in unix.</p>
| 1 | 2009-09-09T20:35:44Z | 1,401,954 | <p><a href="http://docs.python.org/library/urllib2.html">urllib2</a> will do what you want and it's pretty simple to use.</p>
<pre><code>import urllib
import urllib2
params = {'param1': 'value1'}
req = urllib2.Request("http://someurl", urllib.urlencode(params))
res = urllib2.urlopen(req)
data = res.read()
</code></pre>
<p>It's also nice because it's easy to modify the above code to do all sorts of other things like POST requests, Basic Authentication, etc.</p>
| 9 | 2009-09-09T20:39:36Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.