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 |
|---|---|---|---|---|---|---|---|---|---|
Python: List Sorting with Multiple Attributes and Mixed Order | 1,516,249 | <p>I have to sort a python list, with multiple attributes. I can do that in ascending order for ALL attributes easily with</p>
<pre><code>L.sort(key=operator.attrgetter(attribute))....
</code></pre>
<p>but the problem is, that I have use mixed configurations for ascending/descending... I have to "imitate" a bit the SQL Order By where you can do something like "name ASC, year DESC".
Is there a way to do this easily in python without having to implement a custom compare function?</p>
| 12 | 2009-10-04T12:10:07Z | 1,516,449 | <p>If your attributes are numeric, you have this.</p>
<pre><code>def mixed_order( a ):
return ( a.attribute1, -a.attribute2 )
someList.sort( key=mixed_order )
</code></pre>
<p>If your attributes includes strings or other more complex objects, you have some choices.</p>
<p>The <code>.sort()</code> method is stable: you can do multiple passes. This is perhaps the simplest. It's also remarkably fast.</p>
<pre><code>def key1( a ): return a.attribute1
def key2( a ): return a.attribute2
someList.sort( key=key2, reverse=True )
someList.sort( key=key1 )
</code></pre>
<p>If this is the only sort, you can define your own special-purpose comparison operators. Minimally, you need <code>__eq__</code> and <code>__lt__</code>. The other four can be derived from these two by simple logic.</p>
| 22 | 2009-10-04T13:48:13Z | [
"python",
"list",
"sorting"
] |
How to remove "similar" but not identical content in a MySQL database | 1,516,263 | <p>Suppose I have this table:</p>
<pre><code>ID | description
-------------------
5 | The bird flew over the tree.
2 | The birds, flew over the tree
</code></pre>
<p>These two rows have "similar" content. How would I remove #2? </p>
<ol>
<li>What algorithm should I use for "similar" text?</li>
<li>How would I do this with Python?</li>
</ol>
<p>Thanks!</p>
| 3 | 2009-10-04T12:16:49Z | 1,516,291 | <p>Typically, for each value, you'd create a 'simplified' value (remove whatever wasn't essential ... in your example, the punctuation and pluralization), and then compare the simplified values for equality.</p>
| 3 | 2009-10-04T12:28:06Z | [
"python",
"mysql",
"algorithm",
"string"
] |
How to remove "similar" but not identical content in a MySQL database | 1,516,263 | <p>Suppose I have this table:</p>
<pre><code>ID | description
-------------------
5 | The bird flew over the tree.
2 | The birds, flew over the tree
</code></pre>
<p>These two rows have "similar" content. How would I remove #2? </p>
<ol>
<li>What algorithm should I use for "similar" text?</li>
<li>How would I do this with Python?</li>
</ol>
<p>Thanks!</p>
| 3 | 2009-10-04T12:16:49Z | 1,516,499 | <p>You could use the <a href="http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html#operator%5Flike" rel="nofollow">LIKE operator</a>.</p>
<pre><code>DELETE FROM myTable WHERE description LIKE 'The bird%flew over the tree%';
</code></pre>
| 0 | 2009-10-04T14:08:46Z | [
"python",
"mysql",
"algorithm",
"string"
] |
How to remove "similar" but not identical content in a MySQL database | 1,516,263 | <p>Suppose I have this table:</p>
<pre><code>ID | description
-------------------
5 | The bird flew over the tree.
2 | The birds, flew over the tree
</code></pre>
<p>These two rows have "similar" content. How would I remove #2? </p>
<ol>
<li>What algorithm should I use for "similar" text?</li>
<li>How would I do this with Python?</li>
</ol>
<p>Thanks!</p>
| 3 | 2009-10-04T12:16:49Z | 1,516,516 | <p>What you could try is stripping necessary punctuation and running each sentence through a <a href="http://en.wikipedia.org/wiki/Stemming" rel="nofollow">stemmer</a> (e.g. a <a href="http://tartarus.org/~martin/PorterStemmer/" rel="nofollow">Porter Stemmer</a>). </p>
<p>Once you have a stemmed version of the sentence you could store that in another column for comparison. However, you may find it more space efficient to hash the stemmed sentence if the sentences are long (e.g. over 40 chars on average).</p>
<p>Any rows which share the same stemmed sentence or hash will be highly likely to be equivalent - you could automate their removal, or create a UI to enable a human to rapidly approve each one.</p>
<p>Here's a <a href="http://tartarus.org/~martin/PorterStemmer/python.txt" rel="nofollow">Python implementation of the Porter stemmer</a>.</p>
| 5 | 2009-10-04T14:17:25Z | [
"python",
"mysql",
"algorithm",
"string"
] |
How to remove "similar" but not identical content in a MySQL database | 1,516,263 | <p>Suppose I have this table:</p>
<pre><code>ID | description
-------------------
5 | The bird flew over the tree.
2 | The birds, flew over the tree
</code></pre>
<p>These two rows have "similar" content. How would I remove #2? </p>
<ol>
<li>What algorithm should I use for "similar" text?</li>
<li>How would I do this with Python?</li>
</ol>
<p>Thanks!</p>
| 3 | 2009-10-04T12:16:49Z | 10,457,601 | <p>You can define the difference between two strings to be the edit distance, which is the number of operations needed to change one string to another. The set of operations can be anything you want, but if the two strings are of different size in the comparison, you must have an insertion and deletion operation.</p>
<p><a href="http://en.wikipedia.org/wiki/Edit_distance" rel="nofollow">http://en.wikipedia.org/wiki/Edit_distance</a></p>
<p>I would recommend </p>
<p><a href="http://en.wikipedia.org/wiki/Levenshtein_distance" rel="nofollow">http://en.wikipedia.org/wiki/Levenshtein_distance</a></p>
<p>or</p>
<p><a href="http://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance" rel="nofollow">http://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance</a></p>
<p>You would then set a threshold of edit distance that indicates the two strings are similar, e.g. 2 edits or 3 edits. </p>
<p>This may not be a good idea if your database is large, though.</p>
<p>In pseudocode, you would basically say</p>
<pre><code>if editDist(stringA, stringB) > editThreshold
remove stringA %or stringB
end
</code></pre>
| 0 | 2012-05-05T00:02:59Z | [
"python",
"mysql",
"algorithm",
"string"
] |
python varargs before function name? | 1,516,467 | <p>I'm doing some Python coding in a clients code base and I stumbled on a line of code that looks something like this (the variable names have been changed to protect the innocent):</p>
<pre><code>reply = function1(a=foo, **function2(bar, b=baz))
</code></pre>
<p>Normally ** in the argument list collects remaining keyword arguments but what do they do in front of the function name?</p>
| 2 | 2009-10-04T13:56:21Z | 1,516,477 | <p>I'd say that this is just calling a function that returns a dict-like object and therefor the asterisks just convert the returned dict into the keyword arguments for function1, just as usual.</p>
| 11 | 2009-10-04T13:59:53Z | [
"python",
"varargs"
] |
sqlite3 in Python | 1,516,508 | <p>How do I check if the database file already exists or not?
And, if the it exists, how do I check if it already has a specific table or not? </p>
| 6 | 2009-10-04T14:13:24Z | 1,516,527 | <p>To see if a database exists, you can <a href="http://docs.python.org/library/sqlite3.html#sqlite3.connect"><code>sqlite3.connect</code></a> to the file that you think contains the database, and try running a query on it. If it is <em>not</em> a database, you will get this error:</p>
<pre><code>>>> c.execute("SELECT * FROM tbl")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
sqlite3.DatabaseError: file is encrypted or is not a database
</code></pre>
<p><code>sqlite3.connect</code> <em>will</em> create the database if it doesn't exist; as @johnp points out in the comments, <a href="http://docs.python.org/library/os.path.html#os.path.exists"><code>os.path.exists</code></a> will tell you whether the file exists.</p>
<p>To check for existing tables, you <a href="http://www.sqlite.org/faq.html#q7">query against sqlite_master</a>. For example:</p>
<pre><code>>>> def foo(name):
... for row in c.execute("SELECT name FROM sqlite_master WHERE type='table'"):
... if row == (name,):
... return True
... return False
...
>>> foo("tz_data")
True
>>> foo("asdf")
False
</code></pre>
| 9 | 2009-10-04T14:22:18Z | [
"python",
"sqlite3"
] |
Displaying integers in a wxpython listctrl | 1,516,742 | <p>I have a wxPython ListCtrl with five columns. Four of these hold strings, the last one has integer values. I have been storing these as strings (i.e. '4', '17', etc.). However, now that I have added a ColumnSorterMixin to let me sort specific columns in the list, I'm finding, of course, that the integer column is being sorted lexically rather than numerically.</p>
<p>Is there a simple way of fixing this?</p>
| 2 | 2009-10-04T15:58:18Z | 1,516,874 | <p>I think that the most robust way of doing custom sort is to use <a href="http://docs.wxwidgets.org/stable/wx%5Fwxlistctrl.html#wxlistctrlsortitems" rel="nofollow">SortItems()</a> function in wx.ListCtrl. Note that you have to provide item data for each item (using <code>SetItemData()</code>) </p>
<p>Just provide your own callback, say:</p>
<pre><code>def sortColumn(item1, item2):
try:
i1 = int(item1)
i2 = int(item2)
except ValueError:
return cmp(item1, item2)
else:
return cmp(i1, i2)
</code></pre>
<p>Didn't check it, but something along these lines should work for all columns, unless you have a column where some values are strings representing integers and some are not. </p>
| 2 | 2009-10-04T17:01:12Z | [
"python",
"wxpython",
"listctrl"
] |
In Django, how do I filter based on all entities in a many-to-many relation instead of any? | 1,516,795 | <p>I have a model like this:</p>
<pre><code>class Task(models.model):
TASK_STATUS_CHOICES = (
(u"P", u'Pending'),
(u"A", u'Assigned'),
(u"C", u'Complete'),
(u"F", u'Failed')
)
status = models.CharField(max_length=2, choices=TASK_STATUS_CHOICES)
prerequisites = models.ManyToManyField('self', symmetrical=False, related_name="dependents")
</code></pre>
<p>I want to find all tasks whose prerequisites are <em>all</em> complete. I have tried:</p>
<pre><code>Task.objects.filter(prerequisites__status=u"C")
</code></pre>
<p>This gets all tasks for which <em>any</em> prerequisite is complete. I thought maybe I need to use an annotation, but I can't see how to apply a filter on the prerequisite tasks before doing an aggregation. For example, I can find the number of prerequisites of each task like this:</p>
<pre><code>Task.objects.annotate(prereq_count=Count('prerequisites'))
</code></pre>
<p>But how do I annotate tasks with the number of their prerequisites that have a status not equal to "C"?</p>
| 4 | 2009-10-04T16:27:27Z | 1,517,516 | <p>For your first question -- 'all tasks whose prerequisites are all complete':</p>
<pre><code>>>> Task.objects.exclude(prerequisites__status__in=['A','P','F'])
</code></pre>
<p>This will also include tasks with no prerequisites (as they have no incomplete prerequisites). As a doctest (using your model definition), the following passes:</p>
<pre><code>>>> a = Task.objects.create(status='C')
>>> b = Task.objects.create(status='A')
>>> b.prerequisites.add(a)
>>> c = Task.objects.create(status='P')
>>> c.prerequisites.add(b)
>>> prerequisites_complete = Task.objects.exclude(prerequisites__status__in=['A','P','F'])
>>> set([t.id for t in prerequisites_complete]) == set([a.id, b.id])
True
</code></pre>
<p>This doesn't answer how many incomplete prerequisites each task has -- which you might need for display, optimization, etc. </p>
| 4 | 2009-10-04T22:10:01Z | [
"python",
"django",
"orm"
] |
Python insert not getting desired results? | 1,516,889 | <p>#!/usr/bin/python</p>
<pre><code>numbers = [1, 2, 3, 5, 6, 7]
clean = numbers.insert(3, 'four')
print clean
# desire results [1, 2, 3, 'four', 5, 6, 7]
</code></pre>
<p>I am getting "None". What am I doing wrong?</p>
| 3 | 2009-10-04T17:07:30Z | 1,516,896 | <p>Mutating-methods on lists tend to return <code>None</code>, <strong>not</strong> the modified list as you expect -- such metods perform their effect by altering the list in-place, not by building and returning a new one. So, <code>print numbers</code> instead of <code>print clean</code> will show you the altered list.</p>
<p>If you need to keep <code>numbers</code> intact, first you make a copy, then you alter the copy:</p>
<pre><code>clean = list(numbers)
clean.insert(3, 'four')
</code></pre>
<p>this has the overall effect you appear to desire: <code>numbers</code> is unchanged, <code>clean</code> is the changed list.</p>
| 12 | 2009-10-04T17:11:18Z | [
"python"
] |
Python insert not getting desired results? | 1,516,889 | <p>#!/usr/bin/python</p>
<pre><code>numbers = [1, 2, 3, 5, 6, 7]
clean = numbers.insert(3, 'four')
print clean
# desire results [1, 2, 3, 'four', 5, 6, 7]
</code></pre>
<p>I am getting "None". What am I doing wrong?</p>
| 3 | 2009-10-04T17:07:30Z | 1,516,899 | <p>The insert method modifies the list in place and does not return a new reference. Try:</p>
<pre><code>>>> numbers = [1, 2, 3, 5, 6, 7]
>>> numbers.insert(3, 'four')
>>> print numbers
[1, 2, 3, 'four', 5, 6, 7]
</code></pre>
| 6 | 2009-10-04T17:11:33Z | [
"python"
] |
Python insert not getting desired results? | 1,516,889 | <p>#!/usr/bin/python</p>
<pre><code>numbers = [1, 2, 3, 5, 6, 7]
clean = numbers.insert(3, 'four')
print clean
# desire results [1, 2, 3, 'four', 5, 6, 7]
</code></pre>
<p>I am getting "None". What am I doing wrong?</p>
| 3 | 2009-10-04T17:07:30Z | 1,516,902 | <p>insert will insert the item into the given list. Print numbers instead and you'll see your results. insert does not return the new list.</p>
| 1 | 2009-10-04T17:12:05Z | [
"python"
] |
Python insert not getting desired results? | 1,516,889 | <p>#!/usr/bin/python</p>
<pre><code>numbers = [1, 2, 3, 5, 6, 7]
clean = numbers.insert(3, 'four')
print clean
# desire results [1, 2, 3, 'four', 5, 6, 7]
</code></pre>
<p>I am getting "None". What am I doing wrong?</p>
| 3 | 2009-10-04T17:07:30Z | 1,516,903 | <p>The list.insert() operator doesn't return anything, what you probably want is:</p>
<pre><code>print numbers
</code></pre>
| 1 | 2009-10-04T17:12:09Z | [
"python"
] |
monitor service for "failure" | 1,516,943 | <p>I'm developing a script which monitors a service for failure and launches another a different action depending on if failure is present or not. </p>
<p>I require a python script to monitor the output from a python program "monitor-services" and parsing the output search for an occurance of the word "failure". If present, the script should return with a true value, and run for a maxiumum of 30 seconds returning false if no occurance of "failure" occurs.</p>
<p>Sample output returned from "monitor-services":</p>
<pre>
{Device} [/device/xxx] Networks = dbus.Array([dbus.ObjectPath('/device/xxx/xxx'), dbus.ObjectPath('/device/00242b2e41b6/hidden')], signature=dbus.Signature('o'), variant_level=1)
{Service} [/profile/default/wifi_xxx_managed_wep] State = association
{Profile} [/profile/default] Services = dbus.Array([dbus.ObjectPath('/profile/default/wifi_xxx_managed_wep'), dbus.ObjectPath('/profile/default/wifi_xxx_managed_rsn')], signature=dbus.Signature('o'), variant_level=1)
{Manager} [/] Services = dbus.Array([dbus.ObjectPath('/profile/default/wifi_xxx_managed_wep'), dbus.ObjectPath('/profile/default/wifi_xxx_managed_rsn')], signature=dbus.Signature('o'), variant_level=1)
{Service} [/profile/default/wifi_xxx_managed_wep] **failure**
{Service} [/profile/default/wifi_xxx_managed_wep] State = idle
</pre>
<p>Any help would be appreciated.</p>
<p>[edit] A failure is likely to occur with 30 seconds or so of the action triggering the script, hence the script is required to terminate after 30 seconds. [/edit]</p>
| 0 | 2009-10-04T17:33:49Z | 1,517,148 | <pre><code>#!/usr/bin/python
from subprocess import Popen, PIPE
import sys
data = Popen(["monitor-services"], stdout=PIPE).communicate()[0]
sys.exit("failure" in data)
</code></pre>
<p>This does everything you want, except for the 30s wait (which I don't understand). Notice that it returns 0 if failure is not found, 1 if it is found, according to the shell conventions (i.e. 0 is success, non-zero is failure).</p>
| 1 | 2009-10-04T19:09:08Z | [
"python",
"scripting"
] |
python refresh/reload | 1,517,038 | <p>This is a very basic question - but I haven't been able to find an answer by searching online.</p>
<p>I am using python to control ArcGIS, and I have a simple python script, that calls some pre-written code.</p>
<p>However, when I make a change to the pre-written code, it does not appear to result in any change. I import this module, and have tried refreshing it, but nothing happens.</p>
<p>I've even moved the file it calls to another location, and the script still works fine. One thing I did yesterday was I added the folder where all my python files are to the sys path (using sys.append('path') ), and I wonder if that made a difference.</p>
<p>Thanks in advance, and sorry for the sloppy terminology. </p>
| 21 | 2009-10-04T18:23:26Z | 1,517,072 | <p>One way to do this is to call <a href="http://docs.python.org/library/functions.html#reload"><code>reload</code></a>.</p>
<p>Example: Here is the contents of <code>foo.py</code>:</p>
<pre><code>def bar():
return 1
</code></pre>
<p>In an interactive session, I can do:</p>
<pre><code>>>> import foo
>>> foo.bar()
1
</code></pre>
<p>Then in another window, I can change <code>foo.py</code> to:</p>
<pre><code>def bar():
return "Hello"
</code></pre>
<p>Back in the interactive session, calling <code>foo.bar()</code> still returns 1, until I do:</p>
<pre><code>>>> reload(foo)
<module 'foo' from 'foo.py'>
>>> foo.bar()
'Hello'
</code></pre>
<p>Calling <code>reload</code> is <em>one</em> way to ensure that your module is up-to-date even if the file on disk has changed. It's not necessarily the most efficient (you might be better off checking the last modification time on the file or using something like <a href="http://pyinotify.sourceforge.net/">pyinotify</a> before you <code>reload</code>), but it's certainly quick to implement.</p>
<p>One reason that Python doesn't read from the source module every time is that loading a module is (relatively) expensive -- what if you had a 300kb module and you were just using a single constant from the file? Python loads a module once and keeps it in memory, until you <code>reload</code> it.</p>
| 17 | 2009-10-04T18:40:08Z | [
"python",
"refresh",
"reload"
] |
python refresh/reload | 1,517,038 | <p>This is a very basic question - but I haven't been able to find an answer by searching online.</p>
<p>I am using python to control ArcGIS, and I have a simple python script, that calls some pre-written code.</p>
<p>However, when I make a change to the pre-written code, it does not appear to result in any change. I import this module, and have tried refreshing it, but nothing happens.</p>
<p>I've even moved the file it calls to another location, and the script still works fine. One thing I did yesterday was I added the folder where all my python files are to the sys path (using sys.append('path') ), and I wonder if that made a difference.</p>
<p>Thanks in advance, and sorry for the sloppy terminology. </p>
| 21 | 2009-10-04T18:23:26Z | 1,517,073 | <p>I'm not really sure that is what you mean, so don't hesitate to correct me. You are importing a module - let's call it mymodule.py - in your program, but when you change its contents, you don't see the difference?</p>
<p>Python will not look for changes in mymodule.py each time it is used, it will load it a first time, compile it to bytecode and keep it internally. It will normally also save the compiled bytecode (mymodule.pyc). The next time you will start your program, it will check if mymodule.py is more recent than mymodule.pyc, and recompile it if necessary.</p>
<p>If you need to, you can reload the module explicitly:</p>
<pre><code>import mymodule
[... some code ...]
if userAskedForRefresh:
reload(mymodule)
</code></pre>
<p>Of course, it is more complicated than that and you may have side-effects depending on what you do with your program regarding the other module, for example if variables depends on classes defined in mymodule.</p>
<p>Alternatively, you could use the <code>execfile</code> function (or <code>exec()</code>, <code>eval()</code>, <code>compile()</code>)</p>
| 1 | 2009-10-04T18:40:27Z | [
"python",
"refresh",
"reload"
] |
python refresh/reload | 1,517,038 | <p>This is a very basic question - but I haven't been able to find an answer by searching online.</p>
<p>I am using python to control ArcGIS, and I have a simple python script, that calls some pre-written code.</p>
<p>However, when I make a change to the pre-written code, it does not appear to result in any change. I import this module, and have tried refreshing it, but nothing happens.</p>
<p>I've even moved the file it calls to another location, and the script still works fine. One thing I did yesterday was I added the folder where all my python files are to the sys path (using sys.append('path') ), and I wonder if that made a difference.</p>
<p>Thanks in advance, and sorry for the sloppy terminology. </p>
| 21 | 2009-10-04T18:23:26Z | 1,517,087 | <p>It's unclear what you mean with "refresh", but the normal behavior of Python is that you need to restart the software for it to take a new look on a Python module and reread it.</p>
<p>If your changes isn't taken care of even after restart, then this is due to one of two errors:</p>
<ol>
<li>The timestamp on the pyc-file is incorrect and some time in the future.</li>
<li>You are actually editing the wrong file.</li>
</ol>
<p>You can with reload re-read a file even without restarting the software with the reload() command. Note that any variable pointing to anything in the module will need to get reimported after the reload. Something like this:</p>
<pre><code>import themodule
from themodule import AClass
reload(themodule)
from themodule import AClass
</code></pre>
| 24 | 2009-10-04T18:46:24Z | [
"python",
"refresh",
"reload"
] |
python refresh/reload | 1,517,038 | <p>This is a very basic question - but I haven't been able to find an answer by searching online.</p>
<p>I am using python to control ArcGIS, and I have a simple python script, that calls some pre-written code.</p>
<p>However, when I make a change to the pre-written code, it does not appear to result in any change. I import this module, and have tried refreshing it, but nothing happens.</p>
<p>I've even moved the file it calls to another location, and the script still works fine. One thing I did yesterday was I added the folder where all my python files are to the sys path (using sys.append('path') ), and I wonder if that made a difference.</p>
<p>Thanks in advance, and sorry for the sloppy terminology. </p>
| 21 | 2009-10-04T18:23:26Z | 7,479,862 | <p>I used the following when importing all objects from within a module to ensure web2py was using my current code:</p>
<pre><code>import buttons
import table
reload(buttons)
reload(table)
from buttons import *
from table import *
</code></pre>
| 0 | 2011-09-20T03:39:59Z | [
"python",
"refresh",
"reload"
] |
python refresh/reload | 1,517,038 | <p>This is a very basic question - but I haven't been able to find an answer by searching online.</p>
<p>I am using python to control ArcGIS, and I have a simple python script, that calls some pre-written code.</p>
<p>However, when I make a change to the pre-written code, it does not appear to result in any change. I import this module, and have tried refreshing it, but nothing happens.</p>
<p>I've even moved the file it calls to another location, and the script still works fine. One thing I did yesterday was I added the folder where all my python files are to the sys path (using sys.append('path') ), and I wonder if that made a difference.</p>
<p>Thanks in advance, and sorry for the sloppy terminology. </p>
| 21 | 2009-10-04T18:23:26Z | 27,299,101 | <p>I had the exact same issue creating a geoprocessing script for ArcGIS 10.2. I had a python toolbox script, a tool script and then a common script. I have a parameter for Dev/Test/Prod in the tool that would control which version of the code was run. Dev would run the code in the dev folder, test from test folder and prod from prod folder. Changes to the common dev script would not run when the tool was run from ArcCatalog. Closing ArcCatalog made no difference. Even though I selected Dev or Test it would always run from the prod folder.</p>
<p>Adding reload(myCommonModule) to the tool script resolved this issue.</p>
| 0 | 2014-12-04T16:31:15Z | [
"python",
"refresh",
"reload"
] |
python refresh/reload | 1,517,038 | <p>This is a very basic question - but I haven't been able to find an answer by searching online.</p>
<p>I am using python to control ArcGIS, and I have a simple python script, that calls some pre-written code.</p>
<p>However, when I make a change to the pre-written code, it does not appear to result in any change. I import this module, and have tried refreshing it, but nothing happens.</p>
<p>I've even moved the file it calls to another location, and the script still works fine. One thing I did yesterday was I added the folder where all my python files are to the sys path (using sys.append('path') ), and I wonder if that made a difference.</p>
<p>Thanks in advance, and sorry for the sloppy terminology. </p>
| 21 | 2009-10-04T18:23:26Z | 35,972,411 | <p>I found a bypass online. Magic commands exist. It works like a charm for me. The Reload option didn't work for me. Got it from <a href="https://support.enthought.com/hc/en-us/articles/204469240-Jupyter-IPython-After-editing-a-module-changes-are-not-effective-without-kernel-restart?page=1#comment_203342093" rel="nofollow">here</a> and point 3 of this link.</p>
<p>Basically all you have to do is the following: and changes you make are reflected automatically after you save.</p>
<pre><code>In [1]: %load_ext autoreload
In [2]: %autoreload 2
In [3]: Import MODULE
In [4]: my_class = Module.class()
my_class.printham()
Out[4]: ham
In [5]: #make changes to printham and save
In [6]: my_class.printham()
Out[6]: hamlet
</code></pre>
| 0 | 2016-03-13T15:57:10Z | [
"python",
"refresh",
"reload"
] |
How do I install SciPy on 64 bit Windows? | 1,517,129 | <p>How do I install SciPy on my system?</p>
<p>For the NumPy part (that SciPy depends on) there is actually an installer for 64 bit Windows: <a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0/numpy-1.3.0.win-amd64-py2.6.msi">numpy-1.3.0.win-amd64-py2.6.msi</a> (is direct download URL, 2310144 bytes).</p>
<p>Running the SciPy superpack installer results in this
message in a dialog box:</p>
<blockquote>
<p>Cannot install. Python version 2.6 required, which was not found in the registry.</p>
</blockquote>
<p>I already have Python 2.6.2 installed (and a working Django installation
in it), but I don't know about any Registry story.</p>
<p>The registry entries seem to already exist:</p>
<pre><code>REGEDIT4
[HKEY_LOCAL_MACHINE\SOFTWARE\Python]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Help]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Help\Main Python Documentation]
@="D:\\Python262\\Doc\\python262.chm"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\InstallPath]
@="D:\\Python262\\"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\InstallPath\InstallGroup]
@="Python 2.6"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Modules]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\PythonPath]
@="D:\\Python262\\Lib;D:\\Python262\\DLLs;D:\\Python262\\Lib\\lib-tk"
</code></pre>
<hr>
<p>What I have done so far:</p>
<p><strong>Step 1</strong></p>
<p>Downloaded the NumPy superpack installer
numpy-1.3.0rc2-win32-superpack-python2.6.exe
(<a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0rc2/numpy-1.3.0rc2-win32-superpack-python2.6.exe">direct download URL</a>, 4782592 bytes). Running this installer
resulted in the same message, "Cannot install. Python
version 2.6 required, which was not found in the registry.".
<strong>Update</strong>: there is actually an installer for NumPy that works - see beginning of the question.</p>
<p><strong>Step 2</strong></p>
<p>Tried to install NumPy in another way. Downloaded the zip
package numpy-1.3.0rc2.zip (<a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0rc2/numpy-1.3.0rc2.zip">direct download URL</a>, 2404011 bytes),
extracted the zip file in a normal way to a temporary
directory, D:\temp7\numpy-1.3.0rc2 (where setup.py and
README.txt is). I then opened a command line window and:</p>
<pre><code>d:
cd D:\temp7\numpy-1.3.0rc2
setup.py install
</code></pre>
<p>This ran for a long time and also included use of cl.exe
(part of Visual Studio). Here is a nearly 5000 lines long
<a href="http://www.pil.sdu.dk/1/until2039-12-31/SO/numpyBuildTranscript_2009-10-03.html">transcript</a> (230 KB).</p>
<p>This seemed to work. I can now do this in Python:</p>
<pre><code>import numpy as np
np.random.random(10)
</code></pre>
<p>with this result:</p>
<pre><code>array([ 0.35667511, 0.56099423, 0.38423629, 0.09733172, 0.81560421,
0.18813222, 0.10566666, 0.84968066, 0.79472597, 0.30997724])
</code></pre>
<p><strong>Step 3</strong></p>
<p>Downloaded the SciPy superpack installer, scipy-0.7.1rc3-
win32-superpack-python2.6.exe (<a href="http://dfn.dl.sourceforge.net/project/scipy/scipy/0.7.1rc3/scipy-0.7.1rc3-win32-superpack-python2.6.exe">direct download URL</a>, 45597175
bytes). Running this installer resulted in the message
listed in the beginning</p>
<p><strong>Step 4</strong></p>
<p>Tried to install SciPy in another way. Downloaded the zip
package scipy-0.7.1rc3.zip (<a href="http://dfn.dl.sourceforge.net/project/scipy/scipy/0.7.1rc3/scipy-0.7.1rc3.zip">direct download URL</a>, 5506562
bytes), extracted the zip file in a normal way to a
temporary directory, D:\temp7\scipy-0.7.1 (where setup.py
and README.txt is). I then opened a command line window and:</p>
<pre><code>d:
cd D:\temp7\scipy-0.7.1
setup.py install
</code></pre>
<p>This did not achieve much - here is a <a href="http://www.pil.sdu.dk/1/until2039-12-31/SO/scipyBuildTranscript2.html">transcript</a> (about 95
lines).</p>
<p>And it fails:</p>
<pre><code>>>> import scipy as sp2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named scipy
</code></pre>
<hr>
<p>Platform: Python 2.6.2 installed in directory D:\Python262,
Windows XP 64 bit SP2, 8 GB RAM, Visual Studio 2008
Professional Edition installed.</p>
<p>The startup screen of the installed Python is:</p>
<pre><code>Python 2.6.2 (r262:71605, Apr 14 2009, 22:46:50) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
</code></pre>
<p>Value of PATH, result from SET in a command line window:</p>
<pre><code>Path=D:\Perl64\site\bin;D:\Perl64\bin;C:\Program Files (x86)\PC Connectivity Solution\;D:\Perl\site\bin;D:\Perl\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;d:\Program Files (x86)\WinSCP\;D:\MassLynx\;D:\Program Files (x86)\Analyst\bin;d:\Python262;d:\Python262\Scripts;D:\Program Files (x86)\TortoiseSVN\bin;D:\Program Files\TortoiseSVN\bin;C:\WINDOWS\system32\WindowsPowerShell\v1.0;D:\Program Files (x86)\IDM Computer Solutions\UltraEdit\
</code></pre>
| 54 | 2009-10-04T19:01:43Z | 1,517,139 | <p>Try to install Python 2.6.3 over your 2.6.2 (this should also add correct Registry entry), or to register your existing installation <a href="http://effbot.org/zone/python-register.htm" rel="nofollow">using this script</a>. Installer should work after that.</p>
<p>Building SciPy requires a Fortran compiler and libraries - <a href="http://www.netlib.org/blas/" rel="nofollow">BLAS</a> and <a href="http://www.netlib.org/lapack/index.html" rel="nofollow">LAPACK</a>.</p>
| 1 | 2009-10-04T19:05:48Z | [
"python",
"windows",
"64bit",
"numpy",
"scipy"
] |
How do I install SciPy on 64 bit Windows? | 1,517,129 | <p>How do I install SciPy on my system?</p>
<p>For the NumPy part (that SciPy depends on) there is actually an installer for 64 bit Windows: <a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0/numpy-1.3.0.win-amd64-py2.6.msi">numpy-1.3.0.win-amd64-py2.6.msi</a> (is direct download URL, 2310144 bytes).</p>
<p>Running the SciPy superpack installer results in this
message in a dialog box:</p>
<blockquote>
<p>Cannot install. Python version 2.6 required, which was not found in the registry.</p>
</blockquote>
<p>I already have Python 2.6.2 installed (and a working Django installation
in it), but I don't know about any Registry story.</p>
<p>The registry entries seem to already exist:</p>
<pre><code>REGEDIT4
[HKEY_LOCAL_MACHINE\SOFTWARE\Python]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Help]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Help\Main Python Documentation]
@="D:\\Python262\\Doc\\python262.chm"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\InstallPath]
@="D:\\Python262\\"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\InstallPath\InstallGroup]
@="Python 2.6"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Modules]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\PythonPath]
@="D:\\Python262\\Lib;D:\\Python262\\DLLs;D:\\Python262\\Lib\\lib-tk"
</code></pre>
<hr>
<p>What I have done so far:</p>
<p><strong>Step 1</strong></p>
<p>Downloaded the NumPy superpack installer
numpy-1.3.0rc2-win32-superpack-python2.6.exe
(<a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0rc2/numpy-1.3.0rc2-win32-superpack-python2.6.exe">direct download URL</a>, 4782592 bytes). Running this installer
resulted in the same message, "Cannot install. Python
version 2.6 required, which was not found in the registry.".
<strong>Update</strong>: there is actually an installer for NumPy that works - see beginning of the question.</p>
<p><strong>Step 2</strong></p>
<p>Tried to install NumPy in another way. Downloaded the zip
package numpy-1.3.0rc2.zip (<a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0rc2/numpy-1.3.0rc2.zip">direct download URL</a>, 2404011 bytes),
extracted the zip file in a normal way to a temporary
directory, D:\temp7\numpy-1.3.0rc2 (where setup.py and
README.txt is). I then opened a command line window and:</p>
<pre><code>d:
cd D:\temp7\numpy-1.3.0rc2
setup.py install
</code></pre>
<p>This ran for a long time and also included use of cl.exe
(part of Visual Studio). Here is a nearly 5000 lines long
<a href="http://www.pil.sdu.dk/1/until2039-12-31/SO/numpyBuildTranscript_2009-10-03.html">transcript</a> (230 KB).</p>
<p>This seemed to work. I can now do this in Python:</p>
<pre><code>import numpy as np
np.random.random(10)
</code></pre>
<p>with this result:</p>
<pre><code>array([ 0.35667511, 0.56099423, 0.38423629, 0.09733172, 0.81560421,
0.18813222, 0.10566666, 0.84968066, 0.79472597, 0.30997724])
</code></pre>
<p><strong>Step 3</strong></p>
<p>Downloaded the SciPy superpack installer, scipy-0.7.1rc3-
win32-superpack-python2.6.exe (<a href="http://dfn.dl.sourceforge.net/project/scipy/scipy/0.7.1rc3/scipy-0.7.1rc3-win32-superpack-python2.6.exe">direct download URL</a>, 45597175
bytes). Running this installer resulted in the message
listed in the beginning</p>
<p><strong>Step 4</strong></p>
<p>Tried to install SciPy in another way. Downloaded the zip
package scipy-0.7.1rc3.zip (<a href="http://dfn.dl.sourceforge.net/project/scipy/scipy/0.7.1rc3/scipy-0.7.1rc3.zip">direct download URL</a>, 5506562
bytes), extracted the zip file in a normal way to a
temporary directory, D:\temp7\scipy-0.7.1 (where setup.py
and README.txt is). I then opened a command line window and:</p>
<pre><code>d:
cd D:\temp7\scipy-0.7.1
setup.py install
</code></pre>
<p>This did not achieve much - here is a <a href="http://www.pil.sdu.dk/1/until2039-12-31/SO/scipyBuildTranscript2.html">transcript</a> (about 95
lines).</p>
<p>And it fails:</p>
<pre><code>>>> import scipy as sp2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named scipy
</code></pre>
<hr>
<p>Platform: Python 2.6.2 installed in directory D:\Python262,
Windows XP 64 bit SP2, 8 GB RAM, Visual Studio 2008
Professional Edition installed.</p>
<p>The startup screen of the installed Python is:</p>
<pre><code>Python 2.6.2 (r262:71605, Apr 14 2009, 22:46:50) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
</code></pre>
<p>Value of PATH, result from SET in a command line window:</p>
<pre><code>Path=D:\Perl64\site\bin;D:\Perl64\bin;C:\Program Files (x86)\PC Connectivity Solution\;D:\Perl\site\bin;D:\Perl\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;d:\Program Files (x86)\WinSCP\;D:\MassLynx\;D:\Program Files (x86)\Analyst\bin;d:\Python262;d:\Python262\Scripts;D:\Program Files (x86)\TortoiseSVN\bin;D:\Program Files\TortoiseSVN\bin;C:\WINDOWS\system32\WindowsPowerShell\v1.0;D:\Program Files (x86)\IDM Computer Solutions\UltraEdit\
</code></pre>
| 54 | 2009-10-04T19:01:43Z | 1,517,333 | <p>As the transcript for SciPy told you, SciPy isn't really supposed to work on Win64:</p>
<pre><code>Warning: Windows 64 bits support is experimental, and only available for
testing. You are advised not to use it for production.
</code></pre>
<p>So I would suggest to install the 32-bit version of Python, and stop attempting to build SciPy yourself. If you still want to try anyway, you first need to compile BLAS and LAPACK, as PiotrLegnica says. See the transcript for the places where it was looking for compiled versions of these libraries.</p>
| 5 | 2009-10-04T20:44:04Z | [
"python",
"windows",
"64bit",
"numpy",
"scipy"
] |
How do I install SciPy on 64 bit Windows? | 1,517,129 | <p>How do I install SciPy on my system?</p>
<p>For the NumPy part (that SciPy depends on) there is actually an installer for 64 bit Windows: <a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0/numpy-1.3.0.win-amd64-py2.6.msi">numpy-1.3.0.win-amd64-py2.6.msi</a> (is direct download URL, 2310144 bytes).</p>
<p>Running the SciPy superpack installer results in this
message in a dialog box:</p>
<blockquote>
<p>Cannot install. Python version 2.6 required, which was not found in the registry.</p>
</blockquote>
<p>I already have Python 2.6.2 installed (and a working Django installation
in it), but I don't know about any Registry story.</p>
<p>The registry entries seem to already exist:</p>
<pre><code>REGEDIT4
[HKEY_LOCAL_MACHINE\SOFTWARE\Python]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Help]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Help\Main Python Documentation]
@="D:\\Python262\\Doc\\python262.chm"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\InstallPath]
@="D:\\Python262\\"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\InstallPath\InstallGroup]
@="Python 2.6"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Modules]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\PythonPath]
@="D:\\Python262\\Lib;D:\\Python262\\DLLs;D:\\Python262\\Lib\\lib-tk"
</code></pre>
<hr>
<p>What I have done so far:</p>
<p><strong>Step 1</strong></p>
<p>Downloaded the NumPy superpack installer
numpy-1.3.0rc2-win32-superpack-python2.6.exe
(<a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0rc2/numpy-1.3.0rc2-win32-superpack-python2.6.exe">direct download URL</a>, 4782592 bytes). Running this installer
resulted in the same message, "Cannot install. Python
version 2.6 required, which was not found in the registry.".
<strong>Update</strong>: there is actually an installer for NumPy that works - see beginning of the question.</p>
<p><strong>Step 2</strong></p>
<p>Tried to install NumPy in another way. Downloaded the zip
package numpy-1.3.0rc2.zip (<a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0rc2/numpy-1.3.0rc2.zip">direct download URL</a>, 2404011 bytes),
extracted the zip file in a normal way to a temporary
directory, D:\temp7\numpy-1.3.0rc2 (where setup.py and
README.txt is). I then opened a command line window and:</p>
<pre><code>d:
cd D:\temp7\numpy-1.3.0rc2
setup.py install
</code></pre>
<p>This ran for a long time and also included use of cl.exe
(part of Visual Studio). Here is a nearly 5000 lines long
<a href="http://www.pil.sdu.dk/1/until2039-12-31/SO/numpyBuildTranscript_2009-10-03.html">transcript</a> (230 KB).</p>
<p>This seemed to work. I can now do this in Python:</p>
<pre><code>import numpy as np
np.random.random(10)
</code></pre>
<p>with this result:</p>
<pre><code>array([ 0.35667511, 0.56099423, 0.38423629, 0.09733172, 0.81560421,
0.18813222, 0.10566666, 0.84968066, 0.79472597, 0.30997724])
</code></pre>
<p><strong>Step 3</strong></p>
<p>Downloaded the SciPy superpack installer, scipy-0.7.1rc3-
win32-superpack-python2.6.exe (<a href="http://dfn.dl.sourceforge.net/project/scipy/scipy/0.7.1rc3/scipy-0.7.1rc3-win32-superpack-python2.6.exe">direct download URL</a>, 45597175
bytes). Running this installer resulted in the message
listed in the beginning</p>
<p><strong>Step 4</strong></p>
<p>Tried to install SciPy in another way. Downloaded the zip
package scipy-0.7.1rc3.zip (<a href="http://dfn.dl.sourceforge.net/project/scipy/scipy/0.7.1rc3/scipy-0.7.1rc3.zip">direct download URL</a>, 5506562
bytes), extracted the zip file in a normal way to a
temporary directory, D:\temp7\scipy-0.7.1 (where setup.py
and README.txt is). I then opened a command line window and:</p>
<pre><code>d:
cd D:\temp7\scipy-0.7.1
setup.py install
</code></pre>
<p>This did not achieve much - here is a <a href="http://www.pil.sdu.dk/1/until2039-12-31/SO/scipyBuildTranscript2.html">transcript</a> (about 95
lines).</p>
<p>And it fails:</p>
<pre><code>>>> import scipy as sp2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named scipy
</code></pre>
<hr>
<p>Platform: Python 2.6.2 installed in directory D:\Python262,
Windows XP 64 bit SP2, 8 GB RAM, Visual Studio 2008
Professional Edition installed.</p>
<p>The startup screen of the installed Python is:</p>
<pre><code>Python 2.6.2 (r262:71605, Apr 14 2009, 22:46:50) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
</code></pre>
<p>Value of PATH, result from SET in a command line window:</p>
<pre><code>Path=D:\Perl64\site\bin;D:\Perl64\bin;C:\Program Files (x86)\PC Connectivity Solution\;D:\Perl\site\bin;D:\Perl\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;d:\Program Files (x86)\WinSCP\;D:\MassLynx\;D:\Program Files (x86)\Analyst\bin;d:\Python262;d:\Python262\Scripts;D:\Program Files (x86)\TortoiseSVN\bin;D:\Program Files\TortoiseSVN\bin;C:\WINDOWS\system32\WindowsPowerShell\v1.0;D:\Program Files (x86)\IDM Computer Solutions\UltraEdit\
</code></pre>
| 54 | 2009-10-04T19:01:43Z | 1,517,680 | <p>I haven't tried it, but you may want to download <a href="http://www.portablepython.com/wiki/PortablePython1.1Py2.5.4" rel="nofollow">this version</a> of <a href="http://www.portablepython.com/" rel="nofollow">Portable Python</a>. It comes with Scipy-0.7.0b1 running on Python 2.5.4. </p>
| 3 | 2009-10-04T23:13:37Z | [
"python",
"windows",
"64bit",
"numpy",
"scipy"
] |
How do I install SciPy on 64 bit Windows? | 1,517,129 | <p>How do I install SciPy on my system?</p>
<p>For the NumPy part (that SciPy depends on) there is actually an installer for 64 bit Windows: <a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0/numpy-1.3.0.win-amd64-py2.6.msi">numpy-1.3.0.win-amd64-py2.6.msi</a> (is direct download URL, 2310144 bytes).</p>
<p>Running the SciPy superpack installer results in this
message in a dialog box:</p>
<blockquote>
<p>Cannot install. Python version 2.6 required, which was not found in the registry.</p>
</blockquote>
<p>I already have Python 2.6.2 installed (and a working Django installation
in it), but I don't know about any Registry story.</p>
<p>The registry entries seem to already exist:</p>
<pre><code>REGEDIT4
[HKEY_LOCAL_MACHINE\SOFTWARE\Python]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Help]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Help\Main Python Documentation]
@="D:\\Python262\\Doc\\python262.chm"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\InstallPath]
@="D:\\Python262\\"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\InstallPath\InstallGroup]
@="Python 2.6"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Modules]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\PythonPath]
@="D:\\Python262\\Lib;D:\\Python262\\DLLs;D:\\Python262\\Lib\\lib-tk"
</code></pre>
<hr>
<p>What I have done so far:</p>
<p><strong>Step 1</strong></p>
<p>Downloaded the NumPy superpack installer
numpy-1.3.0rc2-win32-superpack-python2.6.exe
(<a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0rc2/numpy-1.3.0rc2-win32-superpack-python2.6.exe">direct download URL</a>, 4782592 bytes). Running this installer
resulted in the same message, "Cannot install. Python
version 2.6 required, which was not found in the registry.".
<strong>Update</strong>: there is actually an installer for NumPy that works - see beginning of the question.</p>
<p><strong>Step 2</strong></p>
<p>Tried to install NumPy in another way. Downloaded the zip
package numpy-1.3.0rc2.zip (<a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0rc2/numpy-1.3.0rc2.zip">direct download URL</a>, 2404011 bytes),
extracted the zip file in a normal way to a temporary
directory, D:\temp7\numpy-1.3.0rc2 (where setup.py and
README.txt is). I then opened a command line window and:</p>
<pre><code>d:
cd D:\temp7\numpy-1.3.0rc2
setup.py install
</code></pre>
<p>This ran for a long time and also included use of cl.exe
(part of Visual Studio). Here is a nearly 5000 lines long
<a href="http://www.pil.sdu.dk/1/until2039-12-31/SO/numpyBuildTranscript_2009-10-03.html">transcript</a> (230 KB).</p>
<p>This seemed to work. I can now do this in Python:</p>
<pre><code>import numpy as np
np.random.random(10)
</code></pre>
<p>with this result:</p>
<pre><code>array([ 0.35667511, 0.56099423, 0.38423629, 0.09733172, 0.81560421,
0.18813222, 0.10566666, 0.84968066, 0.79472597, 0.30997724])
</code></pre>
<p><strong>Step 3</strong></p>
<p>Downloaded the SciPy superpack installer, scipy-0.7.1rc3-
win32-superpack-python2.6.exe (<a href="http://dfn.dl.sourceforge.net/project/scipy/scipy/0.7.1rc3/scipy-0.7.1rc3-win32-superpack-python2.6.exe">direct download URL</a>, 45597175
bytes). Running this installer resulted in the message
listed in the beginning</p>
<p><strong>Step 4</strong></p>
<p>Tried to install SciPy in another way. Downloaded the zip
package scipy-0.7.1rc3.zip (<a href="http://dfn.dl.sourceforge.net/project/scipy/scipy/0.7.1rc3/scipy-0.7.1rc3.zip">direct download URL</a>, 5506562
bytes), extracted the zip file in a normal way to a
temporary directory, D:\temp7\scipy-0.7.1 (where setup.py
and README.txt is). I then opened a command line window and:</p>
<pre><code>d:
cd D:\temp7\scipy-0.7.1
setup.py install
</code></pre>
<p>This did not achieve much - here is a <a href="http://www.pil.sdu.dk/1/until2039-12-31/SO/scipyBuildTranscript2.html">transcript</a> (about 95
lines).</p>
<p>And it fails:</p>
<pre><code>>>> import scipy as sp2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named scipy
</code></pre>
<hr>
<p>Platform: Python 2.6.2 installed in directory D:\Python262,
Windows XP 64 bit SP2, 8 GB RAM, Visual Studio 2008
Professional Edition installed.</p>
<p>The startup screen of the installed Python is:</p>
<pre><code>Python 2.6.2 (r262:71605, Apr 14 2009, 22:46:50) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
</code></pre>
<p>Value of PATH, result from SET in a command line window:</p>
<pre><code>Path=D:\Perl64\site\bin;D:\Perl64\bin;C:\Program Files (x86)\PC Connectivity Solution\;D:\Perl\site\bin;D:\Perl\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;d:\Program Files (x86)\WinSCP\;D:\MassLynx\;D:\Program Files (x86)\Analyst\bin;d:\Python262;d:\Python262\Scripts;D:\Program Files (x86)\TortoiseSVN\bin;D:\Program Files\TortoiseSVN\bin;C:\WINDOWS\system32\WindowsPowerShell\v1.0;D:\Program Files (x86)\IDM Computer Solutions\UltraEdit\
</code></pre>
| 54 | 2009-10-04T19:01:43Z | 1,523,358 | <p>Short answer: windows 64 support is still work in progress at this time. The superpack will certainly not work on a 64 bits python (but it should work fine on a 32 bits python, even on windows 64).</p>
<p>The main issue with windows 64 is that building with mingw-w64 is not stable at this point: it may be our's (numpy devs) fault, python's fault or mingw-w64. Most likely a combination of all those :). So you have to use proprietary compilers: anything other than MS compiler crashes numpy randomly; for the fortran compiler, ifort is the one to use. As of today, both numpy and scipy source code can be compiled with VS 2008 and ifort (all tests passing), but building it is still quite a pain, and not well supported by numpy build infrastructure.</p>
| 29 | 2009-10-06T02:47:52Z | [
"python",
"windows",
"64bit",
"numpy",
"scipy"
] |
How do I install SciPy on 64 bit Windows? | 1,517,129 | <p>How do I install SciPy on my system?</p>
<p>For the NumPy part (that SciPy depends on) there is actually an installer for 64 bit Windows: <a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0/numpy-1.3.0.win-amd64-py2.6.msi">numpy-1.3.0.win-amd64-py2.6.msi</a> (is direct download URL, 2310144 bytes).</p>
<p>Running the SciPy superpack installer results in this
message in a dialog box:</p>
<blockquote>
<p>Cannot install. Python version 2.6 required, which was not found in the registry.</p>
</blockquote>
<p>I already have Python 2.6.2 installed (and a working Django installation
in it), but I don't know about any Registry story.</p>
<p>The registry entries seem to already exist:</p>
<pre><code>REGEDIT4
[HKEY_LOCAL_MACHINE\SOFTWARE\Python]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Help]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Help\Main Python Documentation]
@="D:\\Python262\\Doc\\python262.chm"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\InstallPath]
@="D:\\Python262\\"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\InstallPath\InstallGroup]
@="Python 2.6"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Modules]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\PythonPath]
@="D:\\Python262\\Lib;D:\\Python262\\DLLs;D:\\Python262\\Lib\\lib-tk"
</code></pre>
<hr>
<p>What I have done so far:</p>
<p><strong>Step 1</strong></p>
<p>Downloaded the NumPy superpack installer
numpy-1.3.0rc2-win32-superpack-python2.6.exe
(<a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0rc2/numpy-1.3.0rc2-win32-superpack-python2.6.exe">direct download URL</a>, 4782592 bytes). Running this installer
resulted in the same message, "Cannot install. Python
version 2.6 required, which was not found in the registry.".
<strong>Update</strong>: there is actually an installer for NumPy that works - see beginning of the question.</p>
<p><strong>Step 2</strong></p>
<p>Tried to install NumPy in another way. Downloaded the zip
package numpy-1.3.0rc2.zip (<a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0rc2/numpy-1.3.0rc2.zip">direct download URL</a>, 2404011 bytes),
extracted the zip file in a normal way to a temporary
directory, D:\temp7\numpy-1.3.0rc2 (where setup.py and
README.txt is). I then opened a command line window and:</p>
<pre><code>d:
cd D:\temp7\numpy-1.3.0rc2
setup.py install
</code></pre>
<p>This ran for a long time and also included use of cl.exe
(part of Visual Studio). Here is a nearly 5000 lines long
<a href="http://www.pil.sdu.dk/1/until2039-12-31/SO/numpyBuildTranscript_2009-10-03.html">transcript</a> (230 KB).</p>
<p>This seemed to work. I can now do this in Python:</p>
<pre><code>import numpy as np
np.random.random(10)
</code></pre>
<p>with this result:</p>
<pre><code>array([ 0.35667511, 0.56099423, 0.38423629, 0.09733172, 0.81560421,
0.18813222, 0.10566666, 0.84968066, 0.79472597, 0.30997724])
</code></pre>
<p><strong>Step 3</strong></p>
<p>Downloaded the SciPy superpack installer, scipy-0.7.1rc3-
win32-superpack-python2.6.exe (<a href="http://dfn.dl.sourceforge.net/project/scipy/scipy/0.7.1rc3/scipy-0.7.1rc3-win32-superpack-python2.6.exe">direct download URL</a>, 45597175
bytes). Running this installer resulted in the message
listed in the beginning</p>
<p><strong>Step 4</strong></p>
<p>Tried to install SciPy in another way. Downloaded the zip
package scipy-0.7.1rc3.zip (<a href="http://dfn.dl.sourceforge.net/project/scipy/scipy/0.7.1rc3/scipy-0.7.1rc3.zip">direct download URL</a>, 5506562
bytes), extracted the zip file in a normal way to a
temporary directory, D:\temp7\scipy-0.7.1 (where setup.py
and README.txt is). I then opened a command line window and:</p>
<pre><code>d:
cd D:\temp7\scipy-0.7.1
setup.py install
</code></pre>
<p>This did not achieve much - here is a <a href="http://www.pil.sdu.dk/1/until2039-12-31/SO/scipyBuildTranscript2.html">transcript</a> (about 95
lines).</p>
<p>And it fails:</p>
<pre><code>>>> import scipy as sp2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named scipy
</code></pre>
<hr>
<p>Platform: Python 2.6.2 installed in directory D:\Python262,
Windows XP 64 bit SP2, 8 GB RAM, Visual Studio 2008
Professional Edition installed.</p>
<p>The startup screen of the installed Python is:</p>
<pre><code>Python 2.6.2 (r262:71605, Apr 14 2009, 22:46:50) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
</code></pre>
<p>Value of PATH, result from SET in a command line window:</p>
<pre><code>Path=D:\Perl64\site\bin;D:\Perl64\bin;C:\Program Files (x86)\PC Connectivity Solution\;D:\Perl\site\bin;D:\Perl\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;d:\Program Files (x86)\WinSCP\;D:\MassLynx\;D:\Program Files (x86)\Analyst\bin;d:\Python262;d:\Python262\Scripts;D:\Program Files (x86)\TortoiseSVN\bin;D:\Program Files\TortoiseSVN\bin;C:\WINDOWS\system32\WindowsPowerShell\v1.0;D:\Program Files (x86)\IDM Computer Solutions\UltraEdit\
</code></pre>
| 54 | 2009-10-04T19:01:43Z | 2,114,531 | <p>Unofficial 64-bit installers for <a href="http://en.wikipedia.org/wiki/NumPy">NumPy</a> and <a href="http://en.wikipedia.org/wiki/SciPy">SciPy</a> are available at <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/">http://www.lfd.uci.edu/~gohlke/pythonlibs/</a></p>
| 52 | 2010-01-22T02:18:23Z | [
"python",
"windows",
"64bit",
"numpy",
"scipy"
] |
How do I install SciPy on 64 bit Windows? | 1,517,129 | <p>How do I install SciPy on my system?</p>
<p>For the NumPy part (that SciPy depends on) there is actually an installer for 64 bit Windows: <a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0/numpy-1.3.0.win-amd64-py2.6.msi">numpy-1.3.0.win-amd64-py2.6.msi</a> (is direct download URL, 2310144 bytes).</p>
<p>Running the SciPy superpack installer results in this
message in a dialog box:</p>
<blockquote>
<p>Cannot install. Python version 2.6 required, which was not found in the registry.</p>
</blockquote>
<p>I already have Python 2.6.2 installed (and a working Django installation
in it), but I don't know about any Registry story.</p>
<p>The registry entries seem to already exist:</p>
<pre><code>REGEDIT4
[HKEY_LOCAL_MACHINE\SOFTWARE\Python]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Help]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Help\Main Python Documentation]
@="D:\\Python262\\Doc\\python262.chm"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\InstallPath]
@="D:\\Python262\\"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\InstallPath\InstallGroup]
@="Python 2.6"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Modules]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\PythonPath]
@="D:\\Python262\\Lib;D:\\Python262\\DLLs;D:\\Python262\\Lib\\lib-tk"
</code></pre>
<hr>
<p>What I have done so far:</p>
<p><strong>Step 1</strong></p>
<p>Downloaded the NumPy superpack installer
numpy-1.3.0rc2-win32-superpack-python2.6.exe
(<a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0rc2/numpy-1.3.0rc2-win32-superpack-python2.6.exe">direct download URL</a>, 4782592 bytes). Running this installer
resulted in the same message, "Cannot install. Python
version 2.6 required, which was not found in the registry.".
<strong>Update</strong>: there is actually an installer for NumPy that works - see beginning of the question.</p>
<p><strong>Step 2</strong></p>
<p>Tried to install NumPy in another way. Downloaded the zip
package numpy-1.3.0rc2.zip (<a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0rc2/numpy-1.3.0rc2.zip">direct download URL</a>, 2404011 bytes),
extracted the zip file in a normal way to a temporary
directory, D:\temp7\numpy-1.3.0rc2 (where setup.py and
README.txt is). I then opened a command line window and:</p>
<pre><code>d:
cd D:\temp7\numpy-1.3.0rc2
setup.py install
</code></pre>
<p>This ran for a long time and also included use of cl.exe
(part of Visual Studio). Here is a nearly 5000 lines long
<a href="http://www.pil.sdu.dk/1/until2039-12-31/SO/numpyBuildTranscript_2009-10-03.html">transcript</a> (230 KB).</p>
<p>This seemed to work. I can now do this in Python:</p>
<pre><code>import numpy as np
np.random.random(10)
</code></pre>
<p>with this result:</p>
<pre><code>array([ 0.35667511, 0.56099423, 0.38423629, 0.09733172, 0.81560421,
0.18813222, 0.10566666, 0.84968066, 0.79472597, 0.30997724])
</code></pre>
<p><strong>Step 3</strong></p>
<p>Downloaded the SciPy superpack installer, scipy-0.7.1rc3-
win32-superpack-python2.6.exe (<a href="http://dfn.dl.sourceforge.net/project/scipy/scipy/0.7.1rc3/scipy-0.7.1rc3-win32-superpack-python2.6.exe">direct download URL</a>, 45597175
bytes). Running this installer resulted in the message
listed in the beginning</p>
<p><strong>Step 4</strong></p>
<p>Tried to install SciPy in another way. Downloaded the zip
package scipy-0.7.1rc3.zip (<a href="http://dfn.dl.sourceforge.net/project/scipy/scipy/0.7.1rc3/scipy-0.7.1rc3.zip">direct download URL</a>, 5506562
bytes), extracted the zip file in a normal way to a
temporary directory, D:\temp7\scipy-0.7.1 (where setup.py
and README.txt is). I then opened a command line window and:</p>
<pre><code>d:
cd D:\temp7\scipy-0.7.1
setup.py install
</code></pre>
<p>This did not achieve much - here is a <a href="http://www.pil.sdu.dk/1/until2039-12-31/SO/scipyBuildTranscript2.html">transcript</a> (about 95
lines).</p>
<p>And it fails:</p>
<pre><code>>>> import scipy as sp2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named scipy
</code></pre>
<hr>
<p>Platform: Python 2.6.2 installed in directory D:\Python262,
Windows XP 64 bit SP2, 8 GB RAM, Visual Studio 2008
Professional Edition installed.</p>
<p>The startup screen of the installed Python is:</p>
<pre><code>Python 2.6.2 (r262:71605, Apr 14 2009, 22:46:50) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
</code></pre>
<p>Value of PATH, result from SET in a command line window:</p>
<pre><code>Path=D:\Perl64\site\bin;D:\Perl64\bin;C:\Program Files (x86)\PC Connectivity Solution\;D:\Perl\site\bin;D:\Perl\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;d:\Program Files (x86)\WinSCP\;D:\MassLynx\;D:\Program Files (x86)\Analyst\bin;d:\Python262;d:\Python262\Scripts;D:\Program Files (x86)\TortoiseSVN\bin;D:\Program Files\TortoiseSVN\bin;C:\WINDOWS\system32\WindowsPowerShell\v1.0;D:\Program Files (x86)\IDM Computer Solutions\UltraEdit\
</code></pre>
| 54 | 2009-10-04T19:01:43Z | 2,114,577 | <p>For completeness: <a href="http://www.enthought.com/" rel="nofollow">Enthought</a> has a Python distribution which includes SciPy; however, it's not free. Caveat: I've never used it.</p>
| 2 | 2010-01-22T02:30:32Z | [
"python",
"windows",
"64bit",
"numpy",
"scipy"
] |
How do I install SciPy on 64 bit Windows? | 1,517,129 | <p>How do I install SciPy on my system?</p>
<p>For the NumPy part (that SciPy depends on) there is actually an installer for 64 bit Windows: <a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0/numpy-1.3.0.win-amd64-py2.6.msi">numpy-1.3.0.win-amd64-py2.6.msi</a> (is direct download URL, 2310144 bytes).</p>
<p>Running the SciPy superpack installer results in this
message in a dialog box:</p>
<blockquote>
<p>Cannot install. Python version 2.6 required, which was not found in the registry.</p>
</blockquote>
<p>I already have Python 2.6.2 installed (and a working Django installation
in it), but I don't know about any Registry story.</p>
<p>The registry entries seem to already exist:</p>
<pre><code>REGEDIT4
[HKEY_LOCAL_MACHINE\SOFTWARE\Python]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Help]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Help\Main Python Documentation]
@="D:\\Python262\\Doc\\python262.chm"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\InstallPath]
@="D:\\Python262\\"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\InstallPath\InstallGroup]
@="Python 2.6"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Modules]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\PythonPath]
@="D:\\Python262\\Lib;D:\\Python262\\DLLs;D:\\Python262\\Lib\\lib-tk"
</code></pre>
<hr>
<p>What I have done so far:</p>
<p><strong>Step 1</strong></p>
<p>Downloaded the NumPy superpack installer
numpy-1.3.0rc2-win32-superpack-python2.6.exe
(<a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0rc2/numpy-1.3.0rc2-win32-superpack-python2.6.exe">direct download URL</a>, 4782592 bytes). Running this installer
resulted in the same message, "Cannot install. Python
version 2.6 required, which was not found in the registry.".
<strong>Update</strong>: there is actually an installer for NumPy that works - see beginning of the question.</p>
<p><strong>Step 2</strong></p>
<p>Tried to install NumPy in another way. Downloaded the zip
package numpy-1.3.0rc2.zip (<a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0rc2/numpy-1.3.0rc2.zip">direct download URL</a>, 2404011 bytes),
extracted the zip file in a normal way to a temporary
directory, D:\temp7\numpy-1.3.0rc2 (where setup.py and
README.txt is). I then opened a command line window and:</p>
<pre><code>d:
cd D:\temp7\numpy-1.3.0rc2
setup.py install
</code></pre>
<p>This ran for a long time and also included use of cl.exe
(part of Visual Studio). Here is a nearly 5000 lines long
<a href="http://www.pil.sdu.dk/1/until2039-12-31/SO/numpyBuildTranscript_2009-10-03.html">transcript</a> (230 KB).</p>
<p>This seemed to work. I can now do this in Python:</p>
<pre><code>import numpy as np
np.random.random(10)
</code></pre>
<p>with this result:</p>
<pre><code>array([ 0.35667511, 0.56099423, 0.38423629, 0.09733172, 0.81560421,
0.18813222, 0.10566666, 0.84968066, 0.79472597, 0.30997724])
</code></pre>
<p><strong>Step 3</strong></p>
<p>Downloaded the SciPy superpack installer, scipy-0.7.1rc3-
win32-superpack-python2.6.exe (<a href="http://dfn.dl.sourceforge.net/project/scipy/scipy/0.7.1rc3/scipy-0.7.1rc3-win32-superpack-python2.6.exe">direct download URL</a>, 45597175
bytes). Running this installer resulted in the message
listed in the beginning</p>
<p><strong>Step 4</strong></p>
<p>Tried to install SciPy in another way. Downloaded the zip
package scipy-0.7.1rc3.zip (<a href="http://dfn.dl.sourceforge.net/project/scipy/scipy/0.7.1rc3/scipy-0.7.1rc3.zip">direct download URL</a>, 5506562
bytes), extracted the zip file in a normal way to a
temporary directory, D:\temp7\scipy-0.7.1 (where setup.py
and README.txt is). I then opened a command line window and:</p>
<pre><code>d:
cd D:\temp7\scipy-0.7.1
setup.py install
</code></pre>
<p>This did not achieve much - here is a <a href="http://www.pil.sdu.dk/1/until2039-12-31/SO/scipyBuildTranscript2.html">transcript</a> (about 95
lines).</p>
<p>And it fails:</p>
<pre><code>>>> import scipy as sp2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named scipy
</code></pre>
<hr>
<p>Platform: Python 2.6.2 installed in directory D:\Python262,
Windows XP 64 bit SP2, 8 GB RAM, Visual Studio 2008
Professional Edition installed.</p>
<p>The startup screen of the installed Python is:</p>
<pre><code>Python 2.6.2 (r262:71605, Apr 14 2009, 22:46:50) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
</code></pre>
<p>Value of PATH, result from SET in a command line window:</p>
<pre><code>Path=D:\Perl64\site\bin;D:\Perl64\bin;C:\Program Files (x86)\PC Connectivity Solution\;D:\Perl\site\bin;D:\Perl\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;d:\Program Files (x86)\WinSCP\;D:\MassLynx\;D:\Program Files (x86)\Analyst\bin;d:\Python262;d:\Python262\Scripts;D:\Program Files (x86)\TortoiseSVN\bin;D:\Program Files\TortoiseSVN\bin;C:\WINDOWS\system32\WindowsPowerShell\v1.0;D:\Program Files (x86)\IDM Computer Solutions\UltraEdit\
</code></pre>
| 54 | 2009-10-04T19:01:43Z | 2,459,784 | <p>Another alternative: <a href="http://www.pythonxy.com/" rel="nofollow">http://www.pythonxy.com/</a></p>
<p>Free and includes lots of stuff meant to work together smoothly.</p>
<p><a href="http://permalink.gmane.org/gmane.comp.python.xy.devel/109" rel="nofollow">This person</a> says </p>
<blockquote>
<p>Did you try linux.pythonxy ? ( <a href="http://linux.pythonxy.com" rel="nofollow">http://linux.pythonxy.com</a> ).</p>
<p>It's 64 bit ready ...</p>
</blockquote>
<p>Though I'm not quite sure what that means.</p>
| 2 | 2010-03-17T03:45:20Z | [
"python",
"windows",
"64bit",
"numpy",
"scipy"
] |
How do I install SciPy on 64 bit Windows? | 1,517,129 | <p>How do I install SciPy on my system?</p>
<p>For the NumPy part (that SciPy depends on) there is actually an installer for 64 bit Windows: <a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0/numpy-1.3.0.win-amd64-py2.6.msi">numpy-1.3.0.win-amd64-py2.6.msi</a> (is direct download URL, 2310144 bytes).</p>
<p>Running the SciPy superpack installer results in this
message in a dialog box:</p>
<blockquote>
<p>Cannot install. Python version 2.6 required, which was not found in the registry.</p>
</blockquote>
<p>I already have Python 2.6.2 installed (and a working Django installation
in it), but I don't know about any Registry story.</p>
<p>The registry entries seem to already exist:</p>
<pre><code>REGEDIT4
[HKEY_LOCAL_MACHINE\SOFTWARE\Python]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Help]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Help\Main Python Documentation]
@="D:\\Python262\\Doc\\python262.chm"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\InstallPath]
@="D:\\Python262\\"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\InstallPath\InstallGroup]
@="Python 2.6"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Modules]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\PythonPath]
@="D:\\Python262\\Lib;D:\\Python262\\DLLs;D:\\Python262\\Lib\\lib-tk"
</code></pre>
<hr>
<p>What I have done so far:</p>
<p><strong>Step 1</strong></p>
<p>Downloaded the NumPy superpack installer
numpy-1.3.0rc2-win32-superpack-python2.6.exe
(<a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0rc2/numpy-1.3.0rc2-win32-superpack-python2.6.exe">direct download URL</a>, 4782592 bytes). Running this installer
resulted in the same message, "Cannot install. Python
version 2.6 required, which was not found in the registry.".
<strong>Update</strong>: there is actually an installer for NumPy that works - see beginning of the question.</p>
<p><strong>Step 2</strong></p>
<p>Tried to install NumPy in another way. Downloaded the zip
package numpy-1.3.0rc2.zip (<a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0rc2/numpy-1.3.0rc2.zip">direct download URL</a>, 2404011 bytes),
extracted the zip file in a normal way to a temporary
directory, D:\temp7\numpy-1.3.0rc2 (where setup.py and
README.txt is). I then opened a command line window and:</p>
<pre><code>d:
cd D:\temp7\numpy-1.3.0rc2
setup.py install
</code></pre>
<p>This ran for a long time and also included use of cl.exe
(part of Visual Studio). Here is a nearly 5000 lines long
<a href="http://www.pil.sdu.dk/1/until2039-12-31/SO/numpyBuildTranscript_2009-10-03.html">transcript</a> (230 KB).</p>
<p>This seemed to work. I can now do this in Python:</p>
<pre><code>import numpy as np
np.random.random(10)
</code></pre>
<p>with this result:</p>
<pre><code>array([ 0.35667511, 0.56099423, 0.38423629, 0.09733172, 0.81560421,
0.18813222, 0.10566666, 0.84968066, 0.79472597, 0.30997724])
</code></pre>
<p><strong>Step 3</strong></p>
<p>Downloaded the SciPy superpack installer, scipy-0.7.1rc3-
win32-superpack-python2.6.exe (<a href="http://dfn.dl.sourceforge.net/project/scipy/scipy/0.7.1rc3/scipy-0.7.1rc3-win32-superpack-python2.6.exe">direct download URL</a>, 45597175
bytes). Running this installer resulted in the message
listed in the beginning</p>
<p><strong>Step 4</strong></p>
<p>Tried to install SciPy in another way. Downloaded the zip
package scipy-0.7.1rc3.zip (<a href="http://dfn.dl.sourceforge.net/project/scipy/scipy/0.7.1rc3/scipy-0.7.1rc3.zip">direct download URL</a>, 5506562
bytes), extracted the zip file in a normal way to a
temporary directory, D:\temp7\scipy-0.7.1 (where setup.py
and README.txt is). I then opened a command line window and:</p>
<pre><code>d:
cd D:\temp7\scipy-0.7.1
setup.py install
</code></pre>
<p>This did not achieve much - here is a <a href="http://www.pil.sdu.dk/1/until2039-12-31/SO/scipyBuildTranscript2.html">transcript</a> (about 95
lines).</p>
<p>And it fails:</p>
<pre><code>>>> import scipy as sp2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named scipy
</code></pre>
<hr>
<p>Platform: Python 2.6.2 installed in directory D:\Python262,
Windows XP 64 bit SP2, 8 GB RAM, Visual Studio 2008
Professional Edition installed.</p>
<p>The startup screen of the installed Python is:</p>
<pre><code>Python 2.6.2 (r262:71605, Apr 14 2009, 22:46:50) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
</code></pre>
<p>Value of PATH, result from SET in a command line window:</p>
<pre><code>Path=D:\Perl64\site\bin;D:\Perl64\bin;C:\Program Files (x86)\PC Connectivity Solution\;D:\Perl\site\bin;D:\Perl\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;d:\Program Files (x86)\WinSCP\;D:\MassLynx\;D:\Program Files (x86)\Analyst\bin;d:\Python262;d:\Python262\Scripts;D:\Program Files (x86)\TortoiseSVN\bin;D:\Program Files\TortoiseSVN\bin;C:\WINDOWS\system32\WindowsPowerShell\v1.0;D:\Program Files (x86)\IDM Computer Solutions\UltraEdit\
</code></pre>
| 54 | 2009-10-04T19:01:43Z | 2,760,359 | <p>I was getting this same error on a 32-bit machine. I fixed it by registering my Python installation, using the script at:</p>
<p><a href="http://effbot.org/zone/python-register.htm" rel="nofollow">http://effbot.org/zone/python-register.htm</a> </p>
<p>It's possible that the script would also make the 64-bit superpack installers work.</p>
| 0 | 2010-05-03T18:41:43Z | [
"python",
"windows",
"64bit",
"numpy",
"scipy"
] |
How do I install SciPy on 64 bit Windows? | 1,517,129 | <p>How do I install SciPy on my system?</p>
<p>For the NumPy part (that SciPy depends on) there is actually an installer for 64 bit Windows: <a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0/numpy-1.3.0.win-amd64-py2.6.msi">numpy-1.3.0.win-amd64-py2.6.msi</a> (is direct download URL, 2310144 bytes).</p>
<p>Running the SciPy superpack installer results in this
message in a dialog box:</p>
<blockquote>
<p>Cannot install. Python version 2.6 required, which was not found in the registry.</p>
</blockquote>
<p>I already have Python 2.6.2 installed (and a working Django installation
in it), but I don't know about any Registry story.</p>
<p>The registry entries seem to already exist:</p>
<pre><code>REGEDIT4
[HKEY_LOCAL_MACHINE\SOFTWARE\Python]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Help]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Help\Main Python Documentation]
@="D:\\Python262\\Doc\\python262.chm"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\InstallPath]
@="D:\\Python262\\"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\InstallPath\InstallGroup]
@="Python 2.6"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Modules]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\PythonPath]
@="D:\\Python262\\Lib;D:\\Python262\\DLLs;D:\\Python262\\Lib\\lib-tk"
</code></pre>
<hr>
<p>What I have done so far:</p>
<p><strong>Step 1</strong></p>
<p>Downloaded the NumPy superpack installer
numpy-1.3.0rc2-win32-superpack-python2.6.exe
(<a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0rc2/numpy-1.3.0rc2-win32-superpack-python2.6.exe">direct download URL</a>, 4782592 bytes). Running this installer
resulted in the same message, "Cannot install. Python
version 2.6 required, which was not found in the registry.".
<strong>Update</strong>: there is actually an installer for NumPy that works - see beginning of the question.</p>
<p><strong>Step 2</strong></p>
<p>Tried to install NumPy in another way. Downloaded the zip
package numpy-1.3.0rc2.zip (<a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0rc2/numpy-1.3.0rc2.zip">direct download URL</a>, 2404011 bytes),
extracted the zip file in a normal way to a temporary
directory, D:\temp7\numpy-1.3.0rc2 (where setup.py and
README.txt is). I then opened a command line window and:</p>
<pre><code>d:
cd D:\temp7\numpy-1.3.0rc2
setup.py install
</code></pre>
<p>This ran for a long time and also included use of cl.exe
(part of Visual Studio). Here is a nearly 5000 lines long
<a href="http://www.pil.sdu.dk/1/until2039-12-31/SO/numpyBuildTranscript_2009-10-03.html">transcript</a> (230 KB).</p>
<p>This seemed to work. I can now do this in Python:</p>
<pre><code>import numpy as np
np.random.random(10)
</code></pre>
<p>with this result:</p>
<pre><code>array([ 0.35667511, 0.56099423, 0.38423629, 0.09733172, 0.81560421,
0.18813222, 0.10566666, 0.84968066, 0.79472597, 0.30997724])
</code></pre>
<p><strong>Step 3</strong></p>
<p>Downloaded the SciPy superpack installer, scipy-0.7.1rc3-
win32-superpack-python2.6.exe (<a href="http://dfn.dl.sourceforge.net/project/scipy/scipy/0.7.1rc3/scipy-0.7.1rc3-win32-superpack-python2.6.exe">direct download URL</a>, 45597175
bytes). Running this installer resulted in the message
listed in the beginning</p>
<p><strong>Step 4</strong></p>
<p>Tried to install SciPy in another way. Downloaded the zip
package scipy-0.7.1rc3.zip (<a href="http://dfn.dl.sourceforge.net/project/scipy/scipy/0.7.1rc3/scipy-0.7.1rc3.zip">direct download URL</a>, 5506562
bytes), extracted the zip file in a normal way to a
temporary directory, D:\temp7\scipy-0.7.1 (where setup.py
and README.txt is). I then opened a command line window and:</p>
<pre><code>d:
cd D:\temp7\scipy-0.7.1
setup.py install
</code></pre>
<p>This did not achieve much - here is a <a href="http://www.pil.sdu.dk/1/until2039-12-31/SO/scipyBuildTranscript2.html">transcript</a> (about 95
lines).</p>
<p>And it fails:</p>
<pre><code>>>> import scipy as sp2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named scipy
</code></pre>
<hr>
<p>Platform: Python 2.6.2 installed in directory D:\Python262,
Windows XP 64 bit SP2, 8 GB RAM, Visual Studio 2008
Professional Edition installed.</p>
<p>The startup screen of the installed Python is:</p>
<pre><code>Python 2.6.2 (r262:71605, Apr 14 2009, 22:46:50) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
</code></pre>
<p>Value of PATH, result from SET in a command line window:</p>
<pre><code>Path=D:\Perl64\site\bin;D:\Perl64\bin;C:\Program Files (x86)\PC Connectivity Solution\;D:\Perl\site\bin;D:\Perl\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;d:\Program Files (x86)\WinSCP\;D:\MassLynx\;D:\Program Files (x86)\Analyst\bin;d:\Python262;d:\Python262\Scripts;D:\Program Files (x86)\TortoiseSVN\bin;D:\Program Files\TortoiseSVN\bin;C:\WINDOWS\system32\WindowsPowerShell\v1.0;D:\Program Files (x86)\IDM Computer Solutions\UltraEdit\
</code></pre>
| 54 | 2009-10-04T19:01:43Z | 16,299,104 | <p>Install Python distribution <a href="http://www.python.org/download/" rel="nofollow">http://www.python.org/download/</a>.</p>
<p>Download and Install Anaconda Python Distribution.</p>
<p>Make Anaconda Python distribution link to py3.3, if you want Numpy, Scipy or Matplotlib to work in py3.3 or just use it like that to have only py2.7 and older functionality.</p>
<p>The link below provides more detail about Anaconda:
<a href="http://infodatatech.blogspot.com/2013/04/anaconda-python-distribution-python-33.html" rel="nofollow">http://infodatatech.blogspot.com/2013/04/anaconda-python-distribution-python-33.html</a>.</p>
| 0 | 2013-04-30T11:45:40Z | [
"python",
"windows",
"64bit",
"numpy",
"scipy"
] |
How do I install SciPy on 64 bit Windows? | 1,517,129 | <p>How do I install SciPy on my system?</p>
<p>For the NumPy part (that SciPy depends on) there is actually an installer for 64 bit Windows: <a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0/numpy-1.3.0.win-amd64-py2.6.msi">numpy-1.3.0.win-amd64-py2.6.msi</a> (is direct download URL, 2310144 bytes).</p>
<p>Running the SciPy superpack installer results in this
message in a dialog box:</p>
<blockquote>
<p>Cannot install. Python version 2.6 required, which was not found in the registry.</p>
</blockquote>
<p>I already have Python 2.6.2 installed (and a working Django installation
in it), but I don't know about any Registry story.</p>
<p>The registry entries seem to already exist:</p>
<pre><code>REGEDIT4
[HKEY_LOCAL_MACHINE\SOFTWARE\Python]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Help]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Help\Main Python Documentation]
@="D:\\Python262\\Doc\\python262.chm"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\InstallPath]
@="D:\\Python262\\"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\InstallPath\InstallGroup]
@="Python 2.6"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Modules]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\PythonPath]
@="D:\\Python262\\Lib;D:\\Python262\\DLLs;D:\\Python262\\Lib\\lib-tk"
</code></pre>
<hr>
<p>What I have done so far:</p>
<p><strong>Step 1</strong></p>
<p>Downloaded the NumPy superpack installer
numpy-1.3.0rc2-win32-superpack-python2.6.exe
(<a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0rc2/numpy-1.3.0rc2-win32-superpack-python2.6.exe">direct download URL</a>, 4782592 bytes). Running this installer
resulted in the same message, "Cannot install. Python
version 2.6 required, which was not found in the registry.".
<strong>Update</strong>: there is actually an installer for NumPy that works - see beginning of the question.</p>
<p><strong>Step 2</strong></p>
<p>Tried to install NumPy in another way. Downloaded the zip
package numpy-1.3.0rc2.zip (<a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0rc2/numpy-1.3.0rc2.zip">direct download URL</a>, 2404011 bytes),
extracted the zip file in a normal way to a temporary
directory, D:\temp7\numpy-1.3.0rc2 (where setup.py and
README.txt is). I then opened a command line window and:</p>
<pre><code>d:
cd D:\temp7\numpy-1.3.0rc2
setup.py install
</code></pre>
<p>This ran for a long time and also included use of cl.exe
(part of Visual Studio). Here is a nearly 5000 lines long
<a href="http://www.pil.sdu.dk/1/until2039-12-31/SO/numpyBuildTranscript_2009-10-03.html">transcript</a> (230 KB).</p>
<p>This seemed to work. I can now do this in Python:</p>
<pre><code>import numpy as np
np.random.random(10)
</code></pre>
<p>with this result:</p>
<pre><code>array([ 0.35667511, 0.56099423, 0.38423629, 0.09733172, 0.81560421,
0.18813222, 0.10566666, 0.84968066, 0.79472597, 0.30997724])
</code></pre>
<p><strong>Step 3</strong></p>
<p>Downloaded the SciPy superpack installer, scipy-0.7.1rc3-
win32-superpack-python2.6.exe (<a href="http://dfn.dl.sourceforge.net/project/scipy/scipy/0.7.1rc3/scipy-0.7.1rc3-win32-superpack-python2.6.exe">direct download URL</a>, 45597175
bytes). Running this installer resulted in the message
listed in the beginning</p>
<p><strong>Step 4</strong></p>
<p>Tried to install SciPy in another way. Downloaded the zip
package scipy-0.7.1rc3.zip (<a href="http://dfn.dl.sourceforge.net/project/scipy/scipy/0.7.1rc3/scipy-0.7.1rc3.zip">direct download URL</a>, 5506562
bytes), extracted the zip file in a normal way to a
temporary directory, D:\temp7\scipy-0.7.1 (where setup.py
and README.txt is). I then opened a command line window and:</p>
<pre><code>d:
cd D:\temp7\scipy-0.7.1
setup.py install
</code></pre>
<p>This did not achieve much - here is a <a href="http://www.pil.sdu.dk/1/until2039-12-31/SO/scipyBuildTranscript2.html">transcript</a> (about 95
lines).</p>
<p>And it fails:</p>
<pre><code>>>> import scipy as sp2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named scipy
</code></pre>
<hr>
<p>Platform: Python 2.6.2 installed in directory D:\Python262,
Windows XP 64 bit SP2, 8 GB RAM, Visual Studio 2008
Professional Edition installed.</p>
<p>The startup screen of the installed Python is:</p>
<pre><code>Python 2.6.2 (r262:71605, Apr 14 2009, 22:46:50) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
</code></pre>
<p>Value of PATH, result from SET in a command line window:</p>
<pre><code>Path=D:\Perl64\site\bin;D:\Perl64\bin;C:\Program Files (x86)\PC Connectivity Solution\;D:\Perl\site\bin;D:\Perl\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;d:\Program Files (x86)\WinSCP\;D:\MassLynx\;D:\Program Files (x86)\Analyst\bin;d:\Python262;d:\Python262\Scripts;D:\Program Files (x86)\TortoiseSVN\bin;D:\Program Files\TortoiseSVN\bin;C:\WINDOWS\system32\WindowsPowerShell\v1.0;D:\Program Files (x86)\IDM Computer Solutions\UltraEdit\
</code></pre>
| 54 | 2009-10-04T19:01:43Z | 16,300,038 | <p><a href="http://code.google.com/p/winpython/" rel="nofollow">WinPython</a> is an open-source distribution that has 64-bit numpy and scipy.</p>
| 4 | 2013-04-30T12:34:15Z | [
"python",
"windows",
"64bit",
"numpy",
"scipy"
] |
How do I install SciPy on 64 bit Windows? | 1,517,129 | <p>How do I install SciPy on my system?</p>
<p>For the NumPy part (that SciPy depends on) there is actually an installer for 64 bit Windows: <a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0/numpy-1.3.0.win-amd64-py2.6.msi">numpy-1.3.0.win-amd64-py2.6.msi</a> (is direct download URL, 2310144 bytes).</p>
<p>Running the SciPy superpack installer results in this
message in a dialog box:</p>
<blockquote>
<p>Cannot install. Python version 2.6 required, which was not found in the registry.</p>
</blockquote>
<p>I already have Python 2.6.2 installed (and a working Django installation
in it), but I don't know about any Registry story.</p>
<p>The registry entries seem to already exist:</p>
<pre><code>REGEDIT4
[HKEY_LOCAL_MACHINE\SOFTWARE\Python]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Help]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Help\Main Python Documentation]
@="D:\\Python262\\Doc\\python262.chm"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\InstallPath]
@="D:\\Python262\\"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\InstallPath\InstallGroup]
@="Python 2.6"
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\Modules]
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\PythonPath]
@="D:\\Python262\\Lib;D:\\Python262\\DLLs;D:\\Python262\\Lib\\lib-tk"
</code></pre>
<hr>
<p>What I have done so far:</p>
<p><strong>Step 1</strong></p>
<p>Downloaded the NumPy superpack installer
numpy-1.3.0rc2-win32-superpack-python2.6.exe
(<a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0rc2/numpy-1.3.0rc2-win32-superpack-python2.6.exe">direct download URL</a>, 4782592 bytes). Running this installer
resulted in the same message, "Cannot install. Python
version 2.6 required, which was not found in the registry.".
<strong>Update</strong>: there is actually an installer for NumPy that works - see beginning of the question.</p>
<p><strong>Step 2</strong></p>
<p>Tried to install NumPy in another way. Downloaded the zip
package numpy-1.3.0rc2.zip (<a href="http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0rc2/numpy-1.3.0rc2.zip">direct download URL</a>, 2404011 bytes),
extracted the zip file in a normal way to a temporary
directory, D:\temp7\numpy-1.3.0rc2 (where setup.py and
README.txt is). I then opened a command line window and:</p>
<pre><code>d:
cd D:\temp7\numpy-1.3.0rc2
setup.py install
</code></pre>
<p>This ran for a long time and also included use of cl.exe
(part of Visual Studio). Here is a nearly 5000 lines long
<a href="http://www.pil.sdu.dk/1/until2039-12-31/SO/numpyBuildTranscript_2009-10-03.html">transcript</a> (230 KB).</p>
<p>This seemed to work. I can now do this in Python:</p>
<pre><code>import numpy as np
np.random.random(10)
</code></pre>
<p>with this result:</p>
<pre><code>array([ 0.35667511, 0.56099423, 0.38423629, 0.09733172, 0.81560421,
0.18813222, 0.10566666, 0.84968066, 0.79472597, 0.30997724])
</code></pre>
<p><strong>Step 3</strong></p>
<p>Downloaded the SciPy superpack installer, scipy-0.7.1rc3-
win32-superpack-python2.6.exe (<a href="http://dfn.dl.sourceforge.net/project/scipy/scipy/0.7.1rc3/scipy-0.7.1rc3-win32-superpack-python2.6.exe">direct download URL</a>, 45597175
bytes). Running this installer resulted in the message
listed in the beginning</p>
<p><strong>Step 4</strong></p>
<p>Tried to install SciPy in another way. Downloaded the zip
package scipy-0.7.1rc3.zip (<a href="http://dfn.dl.sourceforge.net/project/scipy/scipy/0.7.1rc3/scipy-0.7.1rc3.zip">direct download URL</a>, 5506562
bytes), extracted the zip file in a normal way to a
temporary directory, D:\temp7\scipy-0.7.1 (where setup.py
and README.txt is). I then opened a command line window and:</p>
<pre><code>d:
cd D:\temp7\scipy-0.7.1
setup.py install
</code></pre>
<p>This did not achieve much - here is a <a href="http://www.pil.sdu.dk/1/until2039-12-31/SO/scipyBuildTranscript2.html">transcript</a> (about 95
lines).</p>
<p>And it fails:</p>
<pre><code>>>> import scipy as sp2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named scipy
</code></pre>
<hr>
<p>Platform: Python 2.6.2 installed in directory D:\Python262,
Windows XP 64 bit SP2, 8 GB RAM, Visual Studio 2008
Professional Edition installed.</p>
<p>The startup screen of the installed Python is:</p>
<pre><code>Python 2.6.2 (r262:71605, Apr 14 2009, 22:46:50) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
</code></pre>
<p>Value of PATH, result from SET in a command line window:</p>
<pre><code>Path=D:\Perl64\site\bin;D:\Perl64\bin;C:\Program Files (x86)\PC Connectivity Solution\;D:\Perl\site\bin;D:\Perl\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;d:\Program Files (x86)\WinSCP\;D:\MassLynx\;D:\Program Files (x86)\Analyst\bin;d:\Python262;d:\Python262\Scripts;D:\Program Files (x86)\TortoiseSVN\bin;D:\Program Files\TortoiseSVN\bin;C:\WINDOWS\system32\WindowsPowerShell\v1.0;D:\Program Files (x86)\IDM Computer Solutions\UltraEdit\
</code></pre>
| 54 | 2009-10-04T19:01:43Z | 36,177,359 | <p>It is terrible to install such Python data science packages independently on Windows. Try <a href="https://www.continuum.io/downloads#_windows" rel="nofollow">Anaconda</a> (one installer, 400 more Python packages, py2 & py3 support). Anaconda really helps me a lot!</p>
| 1 | 2016-03-23T11:47:57Z | [
"python",
"windows",
"64bit",
"numpy",
"scipy"
] |
What's a good library to do computational geometry (like CGAL) in a garbage-collected language? | 1,517,192 | <p>I need a library to handle computational geometry in a project, especially boolean operations, but just about every feature is useful. The best library I can find for this is <a href="http://www.cgal.org/">CGAL</a>, but this is the sort of project I would hesitate to make without garbage collection.</p>
<p>What language/library pairs can you recommend? So far my best bet is importing CGAL into D. There is also a project for making Python bindings for CGAL, but it's very incomplete.</p>
| 7 | 2009-10-04T19:33:16Z | 1,517,213 | <p>I would still recommend to proceed with Python and the existing Python binding. When you find it's incomplete, you'll also find that it is fairly easy to extend - Python's C API is designed so that integrating with external libraries is fairly easy (for experienced C programmers).</p>
| 4 | 2009-10-04T19:45:51Z | [
"python",
"binding",
"garbage-collection",
"computational-geometry",
"cgal"
] |
What's a good library to do computational geometry (like CGAL) in a garbage-collected language? | 1,517,192 | <p>I need a library to handle computational geometry in a project, especially boolean operations, but just about every feature is useful. The best library I can find for this is <a href="http://www.cgal.org/">CGAL</a>, but this is the sort of project I would hesitate to make without garbage collection.</p>
<p>What language/library pairs can you recommend? So far my best bet is importing CGAL into D. There is also a project for making Python bindings for CGAL, but it's very incomplete.</p>
| 7 | 2009-10-04T19:33:16Z | 2,227,063 | <p>Perhaps you can look at Shapely for python</p>
<p><a href="http://pypi.python.org/pypi/Shapely/" rel="nofollow">http://pypi.python.org/pypi/Shapely/</a></p>
<p>For Java I would use JTS</p>
<p>For .NET I would use SharpMap or .NETTopologySuite</p>
| 3 | 2010-02-09T05:50:09Z | [
"python",
"binding",
"garbage-collection",
"computational-geometry",
"cgal"
] |
What's a good library to do computational geometry (like CGAL) in a garbage-collected language? | 1,517,192 | <p>I need a library to handle computational geometry in a project, especially boolean operations, but just about every feature is useful. The best library I can find for this is <a href="http://www.cgal.org/">CGAL</a>, but this is the sort of project I would hesitate to make without garbage collection.</p>
<p>What language/library pairs can you recommend? So far my best bet is importing CGAL into D. There is also a project for making Python bindings for CGAL, but it's very incomplete.</p>
| 7 | 2009-10-04T19:33:16Z | 2,489,751 | <p>JTS is also available in .NET via IKVM.</p>
| 0 | 2010-03-22T02:46:28Z | [
"python",
"binding",
"garbage-collection",
"computational-geometry",
"cgal"
] |
What's a good library to do computational geometry (like CGAL) in a garbage-collected language? | 1,517,192 | <p>I need a library to handle computational geometry in a project, especially boolean operations, but just about every feature is useful. The best library I can find for this is <a href="http://www.cgal.org/">CGAL</a>, but this is the sort of project I would hesitate to make without garbage collection.</p>
<p>What language/library pairs can you recommend? So far my best bet is importing CGAL into D. There is also a project for making Python bindings for CGAL, but it's very incomplete.</p>
| 7 | 2009-10-04T19:33:16Z | 16,423,563 | <p>I've just found this and it seems very promising even if it seems a young project: <a href="https://pyrr.readthedocs.org/en/latest/index.html#" rel="nofollow">https://pyrr.readthedocs.org/en/latest/index.html#</a></p>
<blockquote>
<p>Pyrr is a Python mathematical library.</p>
</blockquote>
<p>and it is based on numpy!</p>
| 0 | 2013-05-07T16:00:32Z | [
"python",
"binding",
"garbage-collection",
"computational-geometry",
"cgal"
] |
What's a good library to do computational geometry (like CGAL) in a garbage-collected language? | 1,517,192 | <p>I need a library to handle computational geometry in a project, especially boolean operations, but just about every feature is useful. The best library I can find for this is <a href="http://www.cgal.org/">CGAL</a>, but this is the sort of project I would hesitate to make without garbage collection.</p>
<p>What language/library pairs can you recommend? So far my best bet is importing CGAL into D. There is also a project for making Python bindings for CGAL, but it's very incomplete.</p>
| 7 | 2009-10-04T19:33:16Z | 20,856,338 | <p>The <a href="http://code.google.com/p/cgal-bindings/" rel="nofollow">CGAL-bindings</a> project provides bindings for CGAL using SWIG. The targeted languages, so far, are Java and Python. The CGAL-bindings project is open source, and supported/founded by two french companies.</p>
| 1 | 2013-12-31T11:05:09Z | [
"python",
"binding",
"garbage-collection",
"computational-geometry",
"cgal"
] |
Cutting text from IPython shell using Ctrl-X is broken | 1,517,259 | <p>I use IPython very frequently and happily. Somehow, cutting text from the shell using the keyboard shortcut, <kbd>Ctrl</kbd> + <kbd>X</kbd>, is broken. Actually, I have a few different installations of IPython. In some of the installations, the shortcut works; in the others, it doesn't work.</p>
<p>What might be the reason for this? Where should I look into?</p>
| 0 | 2009-10-04T20:08:08Z | 1,517,291 | <p>You say you have multiple instances installed -- are these all on different machines? What operating system(s) are they running? If you access them remotely, what operating system are <em>you</em> running?</p>
<p>Do you get to them using ssh? Do you run something like screen, either locally or remotely, or both? There are lots of things that can interfere with your terminal settings, especially when you're working remotely.</p>
<p>I'm almost certain that iPython doesn't have anything to do with it -- though you might want to check the version numbers, to see if working and non-working environments are running different versions.</p>
<p>More likely, it is something in the terminal emulation layer, but you'll likely have to do some detective work of your own to find out what piece is causing it.</p>
<p>Take it one step at a time -- try to cut from a local shell, to make sure that works. Then connect to a remote machine, and cut from <em>that</em> shell. Start screen, if that's your normal way of doing things, and test from <em>that</em> shell. Then start ipython. If it stops there, then see if you can find another application on the same machine that's linked against gnu readline, and try that. You may find that none of the console apps cut proplerly on that machine, or you may find that they work, but not under screen. Or you may find that something in the terminal settings stops everything from working as soon as you ssh in.</p>
<p>You may also have some luck. if you can find out what terminal the remote machine thinks you are using ( echo $TERM ) by copying the termcap file from a working machine to one that doesn't. That's a bit more involved for these forums, though -- I'd repost at that point on serverfault.com or superuser.com</p>
<p>I hope that at least gives you a starting place -- terminals are finicky, and difficult to get right. Most people seem to not bother, as long as everything <em>mostly</em> works.</p>
| 2 | 2009-10-04T20:26:22Z | [
"python",
"keyboard-shortcuts",
"ipython"
] |
Basic cocoa application using dock in Python, but not Xcode and all that extras | 1,517,342 | <p>It seems that if I want to create a very basic Cocoa application with a dock icon and the like, I would <a href="http://developer.apple.com/cocoa/pyobjc.html" rel="nofollow">have to use</a> Xcode and the GUI builder (w/ <strong>PyObjC</strong>).</p>
<p>The application I am intending to write is largely concerned with algorithms and basic IO - and thus, not mostly related to Apple specific stuff.</p>
<p>Basically the application is supposed to run periodically (say, every 3 minutes) .. pull some information via AppleScript and write HTML files to a particular directory. I would like to add a Dock icon for this application .. mainly to showing the "status" of the process (for example, if there is an error .. the dock icon would have a red flag on it). Another advantage of the dock icon is that I can make it run on startup.</p>
<p>Additional bonus for defining the dock right-click menu in a simple way (eg: using Python lists of callables).</p>
<p>Can I achieve this without using Xcode or GUI builders but simply using Emacs and Python?</p>
| 2 | 2009-10-04T20:46:22Z | 1,517,377 | <p><a href="http://pyobjc.sourceforge.net/" rel="nofollow">PyObjC</a>, which is included with Mac OS X 10.5 and 10.6, is pretty close to what you're looking for.</p>
| 2 | 2009-10-04T21:01:12Z | [
"python",
"cocoa",
"pyobjc",
"dock"
] |
Basic cocoa application using dock in Python, but not Xcode and all that extras | 1,517,342 | <p>It seems that if I want to create a very basic Cocoa application with a dock icon and the like, I would <a href="http://developer.apple.com/cocoa/pyobjc.html" rel="nofollow">have to use</a> Xcode and the GUI builder (w/ <strong>PyObjC</strong>).</p>
<p>The application I am intending to write is largely concerned with algorithms and basic IO - and thus, not mostly related to Apple specific stuff.</p>
<p>Basically the application is supposed to run periodically (say, every 3 minutes) .. pull some information via AppleScript and write HTML files to a particular directory. I would like to add a Dock icon for this application .. mainly to showing the "status" of the process (for example, if there is an error .. the dock icon would have a red flag on it). Another advantage of the dock icon is that I can make it run on startup.</p>
<p>Additional bonus for defining the dock right-click menu in a simple way (eg: using Python lists of callables).</p>
<p>Can I achieve this without using Xcode or GUI builders but simply using Emacs and Python?</p>
| 2 | 2009-10-04T20:46:22Z | 1,517,639 | <p>Chuck is correct about PyObjC.</p>
<p>You should then read about this NSApplication method to change your icon. </p>
<p><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ApplicationKit/Classes/NSApplication%5FClass/Reference/Reference.html#//apple%5Fref/occ/instm/NSApplication/setApplicationIconImage%3A" rel="nofollow">-(void)setApplicationIconImage:(NSImage *)anImage;</a></p>
<p>For the dock menu, implement the following in an application delegate. You can build an NSMenu programmatically to avoid using InterfaceBuilder.</p>
<p><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/NSApplicationDelegate%5FProtocol/Reference/Reference.html#//apple%5Fref/occ/intfm/NSApplicationDelegate/applicationDockMenu%3A" rel="nofollow">-(NSMenu *)applicationDockMenu:(NSApplication *)sender;</a></p>
| 0 | 2009-10-04T23:01:10Z | [
"python",
"cocoa",
"pyobjc",
"dock"
] |
Basic cocoa application using dock in Python, but not Xcode and all that extras | 1,517,342 | <p>It seems that if I want to create a very basic Cocoa application with a dock icon and the like, I would <a href="http://developer.apple.com/cocoa/pyobjc.html" rel="nofollow">have to use</a> Xcode and the GUI builder (w/ <strong>PyObjC</strong>).</p>
<p>The application I am intending to write is largely concerned with algorithms and basic IO - and thus, not mostly related to Apple specific stuff.</p>
<p>Basically the application is supposed to run periodically (say, every 3 minutes) .. pull some information via AppleScript and write HTML files to a particular directory. I would like to add a Dock icon for this application .. mainly to showing the "status" of the process (for example, if there is an error .. the dock icon would have a red flag on it). Another advantage of the dock icon is that I can make it run on startup.</p>
<p>Additional bonus for defining the dock right-click menu in a simple way (eg: using Python lists of callables).</p>
<p>Can I achieve this without using Xcode or GUI builders but simply using Emacs and Python?</p>
| 2 | 2009-10-04T20:46:22Z | 1,517,691 | <p>Install the latest <a href="http://svn.pythonmac.org/py2app/py2app/trunk/doc/index.html">py2app</a>, then make a new directory -- cd to it -- in it make a <code>HelloWorld.py</code> file such as:</p>
<pre><code># generic Python imports
import datetime
import os
import sched
import sys
import tempfile
import threading
import time
# need PyObjC on sys.path...:
for d in sys.path:
if 'Extras' in d:
sys.path.append(d + '/PyObjC')
break
# objc-related imports
import objc
from Foundation import *
from AppKit import *
from PyObjCTools import AppHelper
# all stuff related to the repeating-action
thesched = sched.scheduler(time.time, time.sleep)
def tick(n, writer):
writer(n)
thesched.enter(20.0, 10, tick, (n+1, writer))
fd, name = tempfile.mkstemp('.txt', 'hello', '/tmp');
print 'writing %r' % name
f = os.fdopen(fd, 'w')
f.write(datetime.datetime.now().isoformat())
f.write('\n')
f.close()
def schedule(writer):
pool = NSAutoreleasePool.alloc().init()
thesched.enter(0.0, 10, tick, (1, writer))
thesched.run()
# normally you'd want pool.drain() here, but since this function never
# ends until end of program (thesched.run never returns since each tick
# schedules a new one) that pool.drain would never execute here;-).
# objc-related stuff
class TheDelegate(NSObject):
statusbar = None
state = 'idle'
def applicationDidFinishLaunching_(self, notification):
statusbar = NSStatusBar.systemStatusBar()
self.statusitem = statusbar.statusItemWithLength_(
NSVariableStatusItemLength)
self.statusitem.setHighlightMode_(1)
self.statusitem.setToolTip_('Example')
self.statusitem.setTitle_('Example')
self.menu = NSMenu.alloc().init()
menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
'Quit', 'terminate:', '')
self.menu.addItem_(menuitem)
self.statusitem.setMenu_(self.menu)
def writer(self, s):
self.badge.setBadgeLabel_(str(s))
if __name__ == "__main__":
# prepare and set our delegate
app = NSApplication.sharedApplication()
delegate = TheDelegate.alloc().init()
app.setDelegate_(delegate)
delegate.badge = app.dockTile()
delegate.writer(0)
# on a separate thread, run the scheduler
t = threading.Thread(target=schedule, args=(delegate.writer,))
t.setDaemon(1)
t.start()
# let her rip!-)
AppHelper.runEventLoop()
</code></pre>
<p>Of course, in your real code, you'll be performing your own periodic actions every 3 minutes (rather than writing a temp file every 20 seconds as I'm doing here), doing your own status updates (rather than just showing a counter of the number of files written so far), etc, etc, but I hope this example shows you a viable starting point.</p>
<p>Then in Terminal.App cd to the directory containing this source file, <code>py2applet --make-setup HelloWorld.py</code>, <code>python setup.py py2app -A -p PyObjC</code>.</p>
<p>You now have in subdirectory <code>dist</code> a directory <code>HelloWorld.app</code>; <code>open dist</code> and drag the icon to the Dock, and you're all set (on your own machine -- distributing to other machines may not work due to the <code>-A</code> flag, but I had trouble building without it, probably due to mis-installed egg files laying around this machine;-). No doubt you'll want to customize your icon &c.</p>
<p>This doesn't do the "extra credit" thingy you asked for -- it's already a lot of code and I decided to stop here (the extra credit thingy may warrant a new question). Also, I'm not quite sure that <em>all</em> the incantations I'm performing here are actually necessary or useful; the docs are pretty latitant for making a pyobjc .app without Xcode, as you require, so I hacked this together from bits and pieces of example code found on the net plus a substantial amount of trial and error. Still, I hope it helps!-)</p>
| 8 | 2009-10-04T23:18:09Z | [
"python",
"cocoa",
"pyobjc",
"dock"
] |
About Python's built in sort() method | 1,517,347 | <p>What algorithm is the built in <code>sort()</code> method in Python using? Is it possible to have a look at the code for that method?</p>
| 43 | 2009-10-04T20:48:00Z | 1,517,357 | <p>In early python-versions, the sort function implemented a modified version of quicksort.
However, it was deemed unstable and as of 2.3 they switched to using an adaptive mergesort algorithm.</p>
| 6 | 2009-10-04T20:52:09Z | [
"python",
"algorithm",
"sorting",
"python-internals"
] |
About Python's built in sort() method | 1,517,347 | <p>What algorithm is the built in <code>sort()</code> method in Python using? Is it possible to have a look at the code for that method?</p>
| 43 | 2009-10-04T20:48:00Z | 1,517,363 | <p>Sure! The code's <a href="http://svn.python.org/view/python/trunk/Objects/listobject.c?revision=69227&view=markup">here</a>, starting with function <code>islt</code> and proceeding for QUITE a while;-). As Chris's comment suggests, it's C code. You'll also want to read <a href="http://svn.python.org/view/python/trunk/Objects/listsort.txt?revision=69846&view=markup">this</a> text file for a textual explanation, results, etc etc.</p>
<p>If you prefer reading Java code than C code, you could look at Joshua Bloch's implementation of timsort in and for Java (Joshua's also the guy who implemented, in 1997, the modified mergesort that's still used in Java, and one can hope that Java will eventually switch to his recent port of timsort).</p>
<p>Some explanation of the Java port of timsort is <a href="http://bugs.sun.com/bugdatabase/view%5Fbug.do?bug%5Fid=6804124">here</a>, the diff is <a href="http://hg.openjdk.java.net/jdk7/tl/jdk/rev/bfd7abda8f79">here</a> (with pointers to all needed files), the key file is <a href="http://hg.openjdk.java.net/jdk7/tl/jdk/file/bfd7abda8f79/src/share/classes/java/util/TimSort.java">here</a> -- FWIW, while I'm a better C programmer than Java programmer, in this case I find Joshua's Java code more readable overall than Tim's C code;-).</p>
| 60 | 2009-10-04T20:53:10Z | [
"python",
"algorithm",
"sorting",
"python-internals"
] |
About Python's built in sort() method | 1,517,347 | <p>What algorithm is the built in <code>sort()</code> method in Python using? Is it possible to have a look at the code for that method?</p>
| 43 | 2009-10-04T20:48:00Z | 1,517,648 | <p>I just wanted to supply a very helpful link that I missed in Alex's otherwise comprehensive answer: <a href="http://corte.si/posts/code/timsort/index.html">A high-level explanation of Python's timsort</a> (with graph visualizations!).</p>
<p>(Yes, the algorithm is basically known as <a href="http://en.wikipedia.org/wiki/Timsort">Timsort</a> now)</p>
| 19 | 2009-10-04T23:03:41Z | [
"python",
"algorithm",
"sorting",
"python-internals"
] |
How can I interact with the android scripting environment from an android app? | 1,517,372 | <p>I'd like to use python scripts as plugins for an app I'm developing. This seems to be possible by interacting with android-scripting-environment (ASE), as is done by Locale, but I haven't found any documentation about this. How you execute ASE scripts from your own app?</p>
| 2 | 2009-10-04T20:59:23Z | 1,519,428 | <p>It looks like the Locale "plugin" is just recieving a broadcasted <code>Intent</code> to <code>com.twofortyfouram.locale.intent.action.FIRE_SETTING</code> which includs the script as an <code>Extra</code> with the name <code>com.google.ase.extra.SCRIPT_NAME</code>.</p>
<p>The relevant bits are in <a href="http://code.google.com/p/android-scripting/source/browse/android/AndroidScriptingEnvironment/src/com/google/ase/locale/LocaleReceiver.java" rel="nofollow">com.google.ase.locale.LocaleReceiver</a>.</p>
| 0 | 2009-10-05T11:03:43Z | [
"python",
"android",
"ase",
"android-scripting"
] |
Closing sockets in python | 1,517,418 | <p>I'm modifying Python code that have this form:</p>
<pre><code>def foo(self):
try:
connect socket
except Exception, e:
some error reporting stuff
return an error
use the socket
do some other stuff
if some condition:
return
do some more stuff
socket.close()
return normally
</code></pre>
<p>Coming from Java I would like to have a try - finally around the whole thing to make sure that the socket is closed. Should this code also have that or is it some kind of Pythonic magic happening in the background that makes it so that you don't have to?</p>
<p>I read in the python docs that sockets are closed when they are garbage collected. But relying on the garbage collector to close your sockets doesn't feel so good.</p>
| 3 | 2009-10-04T21:24:44Z | 1,517,433 | <p>You seem to be wanting the finally block added to try/except in 2.5</p>
<p><a href="http://docs.python.org/whatsnew/2.5.html#pep-341-unified-try-except-finally" rel="nofollow">http://docs.python.org/whatsnew/2.5.html#pep-341-unified-try-except-finally</a></p>
<p>You are correct that relying on the autoclose when garbage collected is a bad practice, it's best to close them when you are done with them. A try/finally is a good way to do it.</p>
<p>Don't forget to call shutdown() before close().</p>
| 1 | 2009-10-04T21:31:22Z | [
"python",
"sockets",
"try-catch"
] |
Closing sockets in python | 1,517,418 | <p>I'm modifying Python code that have this form:</p>
<pre><code>def foo(self):
try:
connect socket
except Exception, e:
some error reporting stuff
return an error
use the socket
do some other stuff
if some condition:
return
do some more stuff
socket.close()
return normally
</code></pre>
<p>Coming from Java I would like to have a try - finally around the whole thing to make sure that the socket is closed. Should this code also have that or is it some kind of Pythonic magic happening in the background that makes it so that you don't have to?</p>
<p>I read in the python docs that sockets are closed when they are garbage collected. But relying on the garbage collector to close your sockets doesn't feel so good.</p>
| 3 | 2009-10-04T21:24:44Z | 1,517,457 | <p>You can use a <code>try-finally</code> block, which was added in Python 2.5:</p>
<pre><code>try:
open socket
do stuff with socket
finally:
close socket
</code></pre>
<p>Or you can use the <code>with</code> statement, which was added in Python 2.6 (and can be used in 2.5 with a <code>from __future__ import with_statement</code> declaration):</p>
<pre><code>with open_the_socket() as s:
use s
</code></pre>
<p>This will automatically close the socket when the inner block is exited, whether it's exited normally or via an exception, provided that the socket class closes in its <code>__exit__()</code> method.</p>
<p>As of Python 2.7.2 the <code>__exit__()</code> method is not implemented on the socket class.</p>
| 11 | 2009-10-04T21:44:33Z | [
"python",
"sockets",
"try-catch"
] |
Closing sockets in python | 1,517,418 | <p>I'm modifying Python code that have this form:</p>
<pre><code>def foo(self):
try:
connect socket
except Exception, e:
some error reporting stuff
return an error
use the socket
do some other stuff
if some condition:
return
do some more stuff
socket.close()
return normally
</code></pre>
<p>Coming from Java I would like to have a try - finally around the whole thing to make sure that the socket is closed. Should this code also have that or is it some kind of Pythonic magic happening in the background that makes it so that you don't have to?</p>
<p>I read in the python docs that sockets are closed when they are garbage collected. But relying on the garbage collector to close your sockets doesn't feel so good.</p>
| 3 | 2009-10-04T21:24:44Z | 1,517,522 | <p>In addition to the try/finally block, consider setting a socket default timeout that will automatically close the socket(s) after your specified time. </p>
<p><a href="http://docs.python.org/library/socket.html?highlight=setdefaulttimeout#socket.setdefaulttimeout" rel="nofollow">http://docs.python.org/library/socket.html?highlight=setdefaulttimeout#socket.setdefaulttimeout</a></p>
| 0 | 2009-10-04T22:12:05Z | [
"python",
"sockets",
"try-catch"
] |
How to space a write file | 1,517,456 | <p>Hello everyone I'm currently new to python, and I'm trying to write a program where the user can input a message and the output will show the numeric code of the message, but at the same time I need to write the numeric code to an additional file.</p>
<p>So for example the user inputs the word "Hello"
The user will see the output "72 101 108 108 111"</p>
<p>Now that output should also be copied into an external document labeled as my "EncryptedMessage.txt" </p>
<p>The numbers are written to the folder however there is no space between them so when I put it in the decoder it will not decode, is there anyway for me to get a space between them?</p>
<p>Example of my coding.</p>
<pre><code>def main():
outfile = open("EncryptedMessage.txt", "w")
messgage = " "
message = raw_input("Enter a message: ")
for ch in message:
ascii = ord(ch)
outfile.write(str(ascii) )
print ascii,
outfile.close()
</code></pre>
<p>Sorry I'm not really good with programming terms.</p>
| 0 | 2009-10-04T21:44:12Z | 1,517,463 | <p>just manually add a space:</p>
<pre><code>outfile.write(str(ascii) + " ")
</code></pre>
| 2 | 2009-10-04T21:45:43Z | [
"python",
"file",
"spacing"
] |
How to space a write file | 1,517,456 | <p>Hello everyone I'm currently new to python, and I'm trying to write a program where the user can input a message and the output will show the numeric code of the message, but at the same time I need to write the numeric code to an additional file.</p>
<p>So for example the user inputs the word "Hello"
The user will see the output "72 101 108 108 111"</p>
<p>Now that output should also be copied into an external document labeled as my "EncryptedMessage.txt" </p>
<p>The numbers are written to the folder however there is no space between them so when I put it in the decoder it will not decode, is there anyway for me to get a space between them?</p>
<p>Example of my coding.</p>
<pre><code>def main():
outfile = open("EncryptedMessage.txt", "w")
messgage = " "
message = raw_input("Enter a message: ")
for ch in message:
ascii = ord(ch)
outfile.write(str(ascii) )
print ascii,
outfile.close()
</code></pre>
<p>Sorry I'm not really good with programming terms.</p>
| 0 | 2009-10-04T21:44:12Z | 1,517,478 | <p>Bear in mind that cobbal's answer will add an extra space to the end of the file. You can strip it off using:</p>
<pre><code>s.rstrip(str(ascii))
</code></pre>
| 0 | 2009-10-04T21:53:45Z | [
"python",
"file",
"spacing"
] |
How to space a write file | 1,517,456 | <p>Hello everyone I'm currently new to python, and I'm trying to write a program where the user can input a message and the output will show the numeric code of the message, but at the same time I need to write the numeric code to an additional file.</p>
<p>So for example the user inputs the word "Hello"
The user will see the output "72 101 108 108 111"</p>
<p>Now that output should also be copied into an external document labeled as my "EncryptedMessage.txt" </p>
<p>The numbers are written to the folder however there is no space between them so when I put it in the decoder it will not decode, is there anyway for me to get a space between them?</p>
<p>Example of my coding.</p>
<pre><code>def main():
outfile = open("EncryptedMessage.txt", "w")
messgage = " "
message = raw_input("Enter a message: ")
for ch in message:
ascii = ord(ch)
outfile.write(str(ascii) )
print ascii,
outfile.close()
</code></pre>
<p>Sorry I'm not really good with programming terms.</p>
| 0 | 2009-10-04T21:44:12Z | 1,517,519 | <p>You can do this without the loop using Python list comprehension and the join method to add the spaces between the ascii values.</p>
<pre><code>" ".join([str(ord(c)) for c in message])
</code></pre>
<p>This will evaluate to a string of ascii values separated by spaces.</p>
| 5 | 2009-10-04T22:10:23Z | [
"python",
"file",
"spacing"
] |
Linux packaging abstraction layer written in Python? | 1,517,495 | <p>I'm looking for a way to generate .deb and .rpm packages from my build scripts, containing the resulting products. Since everything is written in Python, I'm wondering if anyone knows of an abstraction layer that would allow me to drive both RPM and Deb construction from the same code?</p>
| 2 | 2009-10-04T22:01:41Z | 1,517,593 | <p>Distutils in python's standard library has a <a href="http://docs.python.org/distutils/builtdist.html#creating-rpm-packages" rel="nofollow">bdist_rpm</a> command to build rpms and the third-paty <a href="http://github.com/astraw/stdeb" rel="nofollow">stdeb</a> module adds a command for producing debs.</p>
| 2 | 2009-10-04T22:40:38Z | [
"python",
"packaging",
"rpm",
"deb"
] |
Stream large binary files with urllib2 to file | 1,517,616 | <p>I use the following code to stream large files from the Internet into a local file:</p>
<pre><code>fp = open(file, 'wb')
req = urllib2.urlopen(url)
for line in req:
fp.write(line)
fp.close()
</code></pre>
<p>This works but it downloads quite slowly. Is there a faster way? (The files are large so I don't want to keep them in memory.)</p>
| 44 | 2009-10-04T22:50:47Z | 1,517,659 | <p>I used to use <code>mechanize</code> module and its Browser.retrieve() method. In the past it took 100% CPU and downloaded things very slowly, but some recent release fixed this bug and works very quickly.</p>
<p>Example:</p>
<pre><code>import mechanize
browser = mechanize.Browser()
browser.retrieve('http://www.kernel.org/pub/linux/kernel/v2.6/testing/linux-2.6.32-rc1.tar.bz2', 'Downloads/my-new-kernel.tar.bz2')
</code></pre>
<p>Mechanize is based on urllib2, so urllib2 can also have similar method... but I can't find any now.</p>
| 6 | 2009-10-04T23:07:49Z | [
"python",
"file",
"streaming",
"urllib2"
] |
Stream large binary files with urllib2 to file | 1,517,616 | <p>I use the following code to stream large files from the Internet into a local file:</p>
<pre><code>fp = open(file, 'wb')
req = urllib2.urlopen(url)
for line in req:
fp.write(line)
fp.close()
</code></pre>
<p>This works but it downloads quite slowly. Is there a faster way? (The files are large so I don't want to keep them in memory.)</p>
| 44 | 2009-10-04T22:50:47Z | 1,517,728 | <p>No reason to work line by line (small chunks AND requires Python to find the line ends for you!-), just chunk it up in bigger chunks, e.g.:</p>
<pre><code>from urllib2 import urlopen # Python 2
# from urllib.request import urlopen # Python 3
response = urlopen(url)
CHUNK = 16 * 1024
with open(file, 'wb') as f:
while True:
chunk = response.read(CHUNK)
if not chunk: break
f.write(chunk)
</code></pre>
<p>Experiment a bit with various CHUNK sizes to find the "sweet spot" for your requirements.</p>
| 79 | 2009-10-04T23:42:58Z | [
"python",
"file",
"streaming",
"urllib2"
] |
Stream large binary files with urllib2 to file | 1,517,616 | <p>I use the following code to stream large files from the Internet into a local file:</p>
<pre><code>fp = open(file, 'wb')
req = urllib2.urlopen(url)
for line in req:
fp.write(line)
fp.close()
</code></pre>
<p>This works but it downloads quite slowly. Is there a faster way? (The files are large so I don't want to keep them in memory.)</p>
| 44 | 2009-10-04T22:50:47Z | 5,397,438 | <p>You can also use <a href="http://docs.python.org/library/shutil.html" rel="nofollow">shutil</a>:</p>
<pre><code>import shutil
from urllib2 import urlopen # Python 2
# from urllib.request import urlopen # Python 3
req = urlopen(url)
with open(file, 'wb') as fp:
shutil.copyfileobj(req, fp)
</code></pre>
| 56 | 2011-03-22T20:28:18Z | [
"python",
"file",
"streaming",
"urllib2"
] |
Stream large binary files with urllib2 to file | 1,517,616 | <p>I use the following code to stream large files from the Internet into a local file:</p>
<pre><code>fp = open(file, 'wb')
req = urllib2.urlopen(url)
for line in req:
fp.write(line)
fp.close()
</code></pre>
<p>This works but it downloads quite slowly. Is there a faster way? (The files are large so I don't want to keep them in memory.)</p>
| 44 | 2009-10-04T22:50:47Z | 25,532,537 | <p>You can use urllib.retrieve() to download files:</p>
<p>Example:</p>
<pre><code>from urllib import urlretrieve # Python 2
# from urllib.request import urlretrieve # Python 3
url = "http://www.examplesite.com/myfile"
urlretreive(url,"./local_file")
</code></pre>
| 2 | 2014-08-27T16:34:35Z | [
"python",
"file",
"streaming",
"urllib2"
] |
Django: How to modify a text field before showing it in admin | 1,517,626 | <p>I have a Django Model with a text field. I would like to modify the content of the text field before it's presented to the user in Django Admin.</p>
<p>I was expecting to see signal equivalent of <strong>post_load</strong> but it doesn't seem to exist.</p>
<p><strong>To be more specific:</strong></p>
<p>I have a text field that takes user input. In this text field there is a read more separator. Text before the separator is going to go into introtext field, everything after goes into fulltext field.</p>
<p>At the same time, I only want to show the user 1 text field when they're editing the article.</p>
<p>My plan was to on_load read the data from introtext and fulltext field and combine them into fulltext textarea. On pre_save, I would split the text using the read more separator and store intro in introtext and remainder in fulltext.</p>
<p>So, before the form is displayed, I need to populate the fulltext field with</p>
<pre><code>introtext + '<!--readmore-->' + fulltext
</code></pre>
<p>and I need to be able to do this for existing items.</p>
| 1 | 2009-10-04T22:56:21Z | 1,517,707 | <p>Have a look into <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form" rel="nofollow">Providing your own form</a> for the admin pages. </p>
<p>Once you have your own form, you can use the default param in the form to provide the initial value you want. See the docs on the <a href="http://docs.djangoproject.com/en/dev/ref/forms/fields/#initial" rel="nofollow">Initial param</a> for the form field. As this link will show you, it is possible to use a callable or a constant as your initial value.</p>
| 2 | 2009-10-04T23:26:04Z | [
"python",
"django",
"django-models",
"django-signals"
] |
Django: How to modify a text field before showing it in admin | 1,517,626 | <p>I have a Django Model with a text field. I would like to modify the content of the text field before it's presented to the user in Django Admin.</p>
<p>I was expecting to see signal equivalent of <strong>post_load</strong> but it doesn't seem to exist.</p>
<p><strong>To be more specific:</strong></p>
<p>I have a text field that takes user input. In this text field there is a read more separator. Text before the separator is going to go into introtext field, everything after goes into fulltext field.</p>
<p>At the same time, I only want to show the user 1 text field when they're editing the article.</p>
<p>My plan was to on_load read the data from introtext and fulltext field and combine them into fulltext textarea. On pre_save, I would split the text using the read more separator and store intro in introtext and remainder in fulltext.</p>
<p>So, before the form is displayed, I need to populate the fulltext field with</p>
<pre><code>introtext + '<!--readmore-->' + fulltext
</code></pre>
<p>and I need to be able to do this for existing items.</p>
| 1 | 2009-10-04T22:56:21Z | 1,518,289 | <p>There is no post_load because there is no load function.</p>
<p>Loading of the instance is done in <strong>init</strong> function, therefore the right answer is to use post_init signal.</p>
| 1 | 2009-10-05T04:43:52Z | [
"python",
"django",
"django-models",
"django-signals"
] |
Is it possible to save a list of values into a SQLite column? | 1,517,771 | <p>I want 3 columns to have 9 different values, like a list in Python.
Is it possible? If not in SQLite, then on another database engine?</p>
| 4 | 2009-10-05T00:26:26Z | 1,517,795 | <p>Generally, you do this by stringifying the list (with repr()), and then saving the string. On reading the string from the database, use eval() to re-create the list. Be careful, though that you are certain no user-generated data can get into the column, or the eval() is a security risk.</p>
| 5 | 2009-10-05T00:40:24Z | [
"python",
"sqlite"
] |
Is it possible to save a list of values into a SQLite column? | 1,517,771 | <p>I want 3 columns to have 9 different values, like a list in Python.
Is it possible? If not in SQLite, then on another database engine?</p>
| 4 | 2009-10-05T00:26:26Z | 1,518,067 | <p>You must serialize the list (or other Python object) into a string of bytes, aka "BLOB";-), through your favorite means (<code>marshal</code> is good for lists of elementary values such as numbers or strings &c, <code>cPickle</code> if you want a very general solution, etc), and deserialize it when you fetch it back. Of course, that basically carries the list (or other Python object) as a passive "payload" -- can't meaningfully use it in <code>WHERE</code> clauses, <code>ORDER BY</code>, etc. </p>
<p>Relational databases just don't deal all that well with non-atomic values and would prefer other, normalized alternatives (store the list's items in a different table which includes a "listID" column, put the "listID" in your main table, etc). NON-relational databases, while they typically have limitations wrt relational ones (e.g., no joins), may offer more direct support for your requirement.</p>
<p>Some relational DBs do have non-relational extensions. For example, PostGreSQL supports an <a href="http://www.postgresql.org/docs/8.4/static/arrays.html">array</a> data type (not quite as general as Python's lists -- PgSQL's arrays are intrinsically homogeneous).</p>
| 8 | 2009-10-05T02:45:13Z | [
"python",
"sqlite"
] |
Is it possible to save a list of values into a SQLite column? | 1,517,771 | <p>I want 3 columns to have 9 different values, like a list in Python.
Is it possible? If not in SQLite, then on another database engine?</p>
| 4 | 2009-10-05T00:26:26Z | 1,518,649 | <p>Your question is difficult to understand. Here it is again:</p>
<p>I want 3 columns to have 9 different values, like a list in Python. Is it possible? If not in SQLite, then on another database engine?</p>
<p>Here is what I believe you are asking: is it possible to take a Python list of 9 different values, and save the values under a particular column in a database?</p>
<p>The answer to this question is "yes". I suggest using a Python ORM library instead of trying to write the SQL code yourself. This example code uses <a href="http://autumn-orm.org/" rel="nofollow">Autumn</a>:</p>
<pre><code>import autumn
import autumn.util
from autumn.util import create_table
# get a database connection object
my_test_db = autumn.util.AutoConn("my_test.db")
# code to create the database table
_create_sql = """\
DROP TABLE IF EXISTS mytest;
CREATE TABLE mytest (
id INTEGER PRIMARY KEY AUTOINCREMENT,
value INTEGER NOT NULL,
UNIQUE(value)
);"""
# create the table, dropping any previous table of same name
create_table(my_test_db, _create_sql)
# create ORM class; Autumn introspects the database to find out columns
class MyTest(autumn.model.Model):
db = my_test_db
lst = [3, 6, 9, 2, 4, 8, 1, 5, 7] # list of 9 unique values
for n in lst:
row = MyTest(value=n) # create MyTest() row instance with value initialized
row.save() # write the data to the database
</code></pre>
<p>Run this code, then exit Python and run <code>sqlite3 my_test.db</code>. Then run this SQL command inside SQLite: <code>select * from mytest;</code> Here is the result:</p>
<pre><code>1|3
2|6
3|9
4|2
5|4
6|8
7|1
8|5
9|7
</code></pre>
<p>This example pulls values from one list, and uses the values to populate one column from the database. It could be trivially extended to add additional columns and populate them as well.</p>
<p>If this is not the answer you are looking for, please rephrase your request to clarify.</p>
<p>P.S. This example uses <code>autumn.util</code>. The <code>setup.py</code> included with the current release of Autumn does not install <code>util.py</code> in the correct place; you will need to finish the setup of Autumn by hand.</p>
<p>You could use a more mature ORM such as SQLAlchemy or the ORM from Django. However, I really do like Autumn, especially for SQLite.</p>
| 3 | 2009-10-05T07:19:11Z | [
"python",
"sqlite"
] |
Python Image Library ellipse with wide outline | 1,517,778 | <p>When creating an ellipse with PIL, is it possible to have a thicker/wider outline? Currently, I'm trying to do <code>canvas.ellipse(box, outline=colour, fill=None)</code>, but would like to be able to give the <code>outline</code> parameter a width.</p>
| 2 | 2009-10-05T00:29:11Z | 1,518,075 | <p>You could use the <a href="http://effbot.org/zone/aggdraw-index.htm" rel="nofollow">aggdraw</a> advanced-graphics add-on module to PIL -- with it, the method to draw an ellipse, like others, takes a <code>pen</code> object which you can make with your favorite width (as well as color and opacity).</p>
| 1 | 2009-10-05T02:48:59Z | [
"python",
"image",
"python-imaging-library"
] |
Using lookahead with generators | 1,517,862 | <p>I have implemented a generator-based scanner in Python that tokenizes a string into tuples of the form <em>(token type, token value)</em>:</p>
<pre><code>for token in scan("a(b)"):
print token
</code></pre>
<p>would print</p>
<pre><code>("literal", "a")
("l_paren", "(")
...
</code></pre>
<p>The next task implies parsing the token stream and for that, I need be able to look one item ahead from the current one without moving the pointer ahead as well. The fact that iterators and generators do not provide the complete sequence of items at once but each item as needed makes lookaheads a bit trickier compared to lists, since the next item is not known unless <code>__next__()</code> is called.</p>
<p>What could a straightforward implementation of a generator-based lookahead look like? Currently I'm using a workaround which implies making a list out of the generator:</p>
<pre><code>token_list = [token for token in scan(string)]
</code></pre>
<p>The lookahead then is easily implemented by something like that:</p>
<pre><code>try:
next_token = token_list[index + 1]
except: IndexError:
next_token = None
</code></pre>
<p>Of course this just works fine. But thinking that over, my second question arises: Is there really a point of making <code>scan()</code> a generator in the first place?</p>
| 16 | 2009-10-05T01:10:55Z | 1,517,887 | <p>It's not pretty, but this may do what you want:</p>
<pre><code>def paired_iter(it):
token = it.next()
for lookahead in it:
yield (token, lookahead)
token = lookahead
yield (token, None)
def scan(s):
for c in s:
yield c
for this_token, next_token in paired_iter(scan("ABCDEF")):
print "this:%s next:%s" % (this_token, next_token)
</code></pre>
<p>Prints:</p>
<pre><code>this:A next:B
this:B next:C
this:C next:D
this:D next:E
this:E next:F
this:F next:None
</code></pre>
| 6 | 2009-10-05T01:23:56Z | [
"python",
"generator",
"lookahead"
] |
Using lookahead with generators | 1,517,862 | <p>I have implemented a generator-based scanner in Python that tokenizes a string into tuples of the form <em>(token type, token value)</em>:</p>
<pre><code>for token in scan("a(b)"):
print token
</code></pre>
<p>would print</p>
<pre><code>("literal", "a")
("l_paren", "(")
...
</code></pre>
<p>The next task implies parsing the token stream and for that, I need be able to look one item ahead from the current one without moving the pointer ahead as well. The fact that iterators and generators do not provide the complete sequence of items at once but each item as needed makes lookaheads a bit trickier compared to lists, since the next item is not known unless <code>__next__()</code> is called.</p>
<p>What could a straightforward implementation of a generator-based lookahead look like? Currently I'm using a workaround which implies making a list out of the generator:</p>
<pre><code>token_list = [token for token in scan(string)]
</code></pre>
<p>The lookahead then is easily implemented by something like that:</p>
<pre><code>try:
next_token = token_list[index + 1]
except: IndexError:
next_token = None
</code></pre>
<p>Of course this just works fine. But thinking that over, my second question arises: Is there really a point of making <code>scan()</code> a generator in the first place?</p>
| 16 | 2009-10-05T01:10:55Z | 1,517,965 | <p>You can write a wrapper that buffers some number of items from the generator, and provides a lookahead() function to peek at those buffered items:</p>
<pre><code>class Lookahead:
def __init__(self, iter):
self.iter = iter
self.buffer = []
def __iter__(self):
return self
def next(self):
if self.buffer:
return self.buffer.pop(0)
else:
return self.iter.next()
def lookahead(self, n):
"""Return an item n entries ahead in the iteration."""
while n >= len(self.buffer):
try:
self.buffer.append(self.iter.next())
except StopIteration:
return None
return self.buffer[n]
</code></pre>
| 13 | 2009-10-05T02:03:46Z | [
"python",
"generator",
"lookahead"
] |
Using lookahead with generators | 1,517,862 | <p>I have implemented a generator-based scanner in Python that tokenizes a string into tuples of the form <em>(token type, token value)</em>:</p>
<pre><code>for token in scan("a(b)"):
print token
</code></pre>
<p>would print</p>
<pre><code>("literal", "a")
("l_paren", "(")
...
</code></pre>
<p>The next task implies parsing the token stream and for that, I need be able to look one item ahead from the current one without moving the pointer ahead as well. The fact that iterators and generators do not provide the complete sequence of items at once but each item as needed makes lookaheads a bit trickier compared to lists, since the next item is not known unless <code>__next__()</code> is called.</p>
<p>What could a straightforward implementation of a generator-based lookahead look like? Currently I'm using a workaround which implies making a list out of the generator:</p>
<pre><code>token_list = [token for token in scan(string)]
</code></pre>
<p>The lookahead then is easily implemented by something like that:</p>
<pre><code>try:
next_token = token_list[index + 1]
except: IndexError:
next_token = None
</code></pre>
<p>Of course this just works fine. But thinking that over, my second question arises: Is there really a point of making <code>scan()</code> a generator in the first place?</p>
| 16 | 2009-10-05T01:10:55Z | 1,517,967 | <p>Paul's is a good answer. A class based approach with arbitrary lookahead might look something like:</p>
<pre><code>class lookahead(object):
def __init__(self, generator, lookahead_count=1):
self.gen = iter(generator)
self.look_count = lookahead_count
def __iter__(self):
self.lookahead = []
self.stopped = False
try:
for i in range(self.look_count):
self.lookahead.append(self.gen.next())
except StopIteration:
self.stopped = True
return self
def next(self):
if not self.stopped:
try:
self.lookahead.append(self.gen.next())
except StopIteration:
self.stopped = True
if self.lookahead != []:
return self.lookahead.pop(0)
else:
raise StopIteration
x = lookahead("abcdef", 3)
for i in x:
print i, x.lookahead
</code></pre>
| 0 | 2009-10-05T02:04:01Z | [
"python",
"generator",
"lookahead"
] |
Using lookahead with generators | 1,517,862 | <p>I have implemented a generator-based scanner in Python that tokenizes a string into tuples of the form <em>(token type, token value)</em>:</p>
<pre><code>for token in scan("a(b)"):
print token
</code></pre>
<p>would print</p>
<pre><code>("literal", "a")
("l_paren", "(")
...
</code></pre>
<p>The next task implies parsing the token stream and for that, I need be able to look one item ahead from the current one without moving the pointer ahead as well. The fact that iterators and generators do not provide the complete sequence of items at once but each item as needed makes lookaheads a bit trickier compared to lists, since the next item is not known unless <code>__next__()</code> is called.</p>
<p>What could a straightforward implementation of a generator-based lookahead look like? Currently I'm using a workaround which implies making a list out of the generator:</p>
<pre><code>token_list = [token for token in scan(string)]
</code></pre>
<p>The lookahead then is easily implemented by something like that:</p>
<pre><code>try:
next_token = token_list[index + 1]
except: IndexError:
next_token = None
</code></pre>
<p>Of course this just works fine. But thinking that over, my second question arises: Is there really a point of making <code>scan()</code> a generator in the first place?</p>
| 16 | 2009-10-05T01:10:55Z | 1,517,982 | <p>Here is an example that allows a single item to be sent back to the generator</p>
<pre><code>def gen():
for i in range(100):
v=yield i # when you call next(), v will be set to None
if v:
yield None # this yields None to send() call
v=yield v # so this yield is for the first next() after send()
g=gen()
x=g.next()
print 0,x
x=g.next()
print 1,x
x=g.next()
print 2,x # oops push it back
x=g.send(x)
x=g.next()
print 3,x # x should be 2 again
x=g.next()
print 4,x
</code></pre>
| 2 | 2009-10-05T02:10:48Z | [
"python",
"generator",
"lookahead"
] |
Using lookahead with generators | 1,517,862 | <p>I have implemented a generator-based scanner in Python that tokenizes a string into tuples of the form <em>(token type, token value)</em>:</p>
<pre><code>for token in scan("a(b)"):
print token
</code></pre>
<p>would print</p>
<pre><code>("literal", "a")
("l_paren", "(")
...
</code></pre>
<p>The next task implies parsing the token stream and for that, I need be able to look one item ahead from the current one without moving the pointer ahead as well. The fact that iterators and generators do not provide the complete sequence of items at once but each item as needed makes lookaheads a bit trickier compared to lists, since the next item is not known unless <code>__next__()</code> is called.</p>
<p>What could a straightforward implementation of a generator-based lookahead look like? Currently I'm using a workaround which implies making a list out of the generator:</p>
<pre><code>token_list = [token for token in scan(string)]
</code></pre>
<p>The lookahead then is easily implemented by something like that:</p>
<pre><code>try:
next_token = token_list[index + 1]
except: IndexError:
next_token = None
</code></pre>
<p>Of course this just works fine. But thinking that over, my second question arises: Is there really a point of making <code>scan()</code> a generator in the first place?</p>
| 16 | 2009-10-05T01:10:55Z | 1,518,097 | <p>Pretty good answers there, but my favorite approach would be to use <code>itertools.tee</code> -- given an iterator, it returns two (or more if requested) that can be advanced independently. It buffers in memory just as much as needed (i.e., not much, if the iterators don't get very "out of step" from each other). E.g.:</p>
<pre><code>import itertools
import collections
class IteratorWithLookahead(collections.Iterator):
def __init__(self, it):
self.it, self.nextit = itertools.tee(iter(it))
self._advance()
def _advance(self):
self.lookahead = next(self.nextit, None)
def __next__(self):
self._advance()
return next(self.it)
</code></pre>
<p>You can wrap any iterator with this class, and then use the <code>.lookahead</code> attribute of the wrapper to know what the next item to be returned in the future will be. I like to leave all the real logic to itertools.tee and just provide this thin glue!-)</p>
| 18 | 2009-10-05T03:00:18Z | [
"python",
"generator",
"lookahead"
] |
Using lookahead with generators | 1,517,862 | <p>I have implemented a generator-based scanner in Python that tokenizes a string into tuples of the form <em>(token type, token value)</em>:</p>
<pre><code>for token in scan("a(b)"):
print token
</code></pre>
<p>would print</p>
<pre><code>("literal", "a")
("l_paren", "(")
...
</code></pre>
<p>The next task implies parsing the token stream and for that, I need be able to look one item ahead from the current one without moving the pointer ahead as well. The fact that iterators and generators do not provide the complete sequence of items at once but each item as needed makes lookaheads a bit trickier compared to lists, since the next item is not known unless <code>__next__()</code> is called.</p>
<p>What could a straightforward implementation of a generator-based lookahead look like? Currently I'm using a workaround which implies making a list out of the generator:</p>
<pre><code>token_list = [token for token in scan(string)]
</code></pre>
<p>The lookahead then is easily implemented by something like that:</p>
<pre><code>try:
next_token = token_list[index + 1]
except: IndexError:
next_token = None
</code></pre>
<p>Of course this just works fine. But thinking that over, my second question arises: Is there really a point of making <code>scan()</code> a generator in the first place?</p>
| 16 | 2009-10-05T01:10:55Z | 1,518,260 | <p>Since you say you are tokenizing a string and not a general iterable, I suggest the simplest solution of just expanding your tokenizer to return a 3-tuple:
<code>(token_type, token_value, token_index)</code>, where <code>token_index</code> is the index of the token in the string. Then you can look forward, backward, or anywhere else in the string. Just don't go past the end. Simplest and most flexible solution I think.</p>
<p>Also, you needn't use a list comprehension to create a list from a generator. Just call the list() constructor on it:</p>
<pre><code> token_list = list(scan(string))
</code></pre>
| 1 | 2009-10-05T04:25:33Z | [
"python",
"generator",
"lookahead"
] |
Using lookahead with generators | 1,517,862 | <p>I have implemented a generator-based scanner in Python that tokenizes a string into tuples of the form <em>(token type, token value)</em>:</p>
<pre><code>for token in scan("a(b)"):
print token
</code></pre>
<p>would print</p>
<pre><code>("literal", "a")
("l_paren", "(")
...
</code></pre>
<p>The next task implies parsing the token stream and for that, I need be able to look one item ahead from the current one without moving the pointer ahead as well. The fact that iterators and generators do not provide the complete sequence of items at once but each item as needed makes lookaheads a bit trickier compared to lists, since the next item is not known unless <code>__next__()</code> is called.</p>
<p>What could a straightforward implementation of a generator-based lookahead look like? Currently I'm using a workaround which implies making a list out of the generator:</p>
<pre><code>token_list = [token for token in scan(string)]
</code></pre>
<p>The lookahead then is easily implemented by something like that:</p>
<pre><code>try:
next_token = token_list[index + 1]
except: IndexError:
next_token = None
</code></pre>
<p>Of course this just works fine. But thinking that over, my second question arises: Is there really a point of making <code>scan()</code> a generator in the first place?</p>
| 16 | 2009-10-05T01:10:55Z | 6,449,237 | <p>How I would write it concisely, if I just needed 1 element's worth of lookahead:</p>
<pre><code>SEQUENCE_END = object()
def lookahead(iterable):
iter = iter(iterable)
current = next(iter)
for ahead in iter:
yield current,ahead
current = ahead
yield current,SEQUENCE_END
</code></pre>
<p>Example:</p>
<pre><code>>>> for x,ahead in lookahead(range(3)):
>>> print(x,ahead)
0, 1
1, 2
2, <object SEQUENCE_END>
</code></pre>
| 0 | 2011-06-23T04:10:21Z | [
"python",
"generator",
"lookahead"
] |
Using lookahead with generators | 1,517,862 | <p>I have implemented a generator-based scanner in Python that tokenizes a string into tuples of the form <em>(token type, token value)</em>:</p>
<pre><code>for token in scan("a(b)"):
print token
</code></pre>
<p>would print</p>
<pre><code>("literal", "a")
("l_paren", "(")
...
</code></pre>
<p>The next task implies parsing the token stream and for that, I need be able to look one item ahead from the current one without moving the pointer ahead as well. The fact that iterators and generators do not provide the complete sequence of items at once but each item as needed makes lookaheads a bit trickier compared to lists, since the next item is not known unless <code>__next__()</code> is called.</p>
<p>What could a straightforward implementation of a generator-based lookahead look like? Currently I'm using a workaround which implies making a list out of the generator:</p>
<pre><code>token_list = [token for token in scan(string)]
</code></pre>
<p>The lookahead then is easily implemented by something like that:</p>
<pre><code>try:
next_token = token_list[index + 1]
except: IndexError:
next_token = None
</code></pre>
<p>Of course this just works fine. But thinking that over, my second question arises: Is there really a point of making <code>scan()</code> a generator in the first place?</p>
| 16 | 2009-10-05T01:10:55Z | 15,726,344 | <p>Construct a simple lookahead wrapper using <a href="http://docs.python.org/2.7/library/itertools.html#itertools.tee" rel="nofollow"><em>itertools.tee</em></a>:</p>
<pre><code>from itertools import tee, islice
class LookAhead:
'Wrap an iterator with lookahead indexing'
def __init__(self, iterator):
self.t = tee(iterator, 1)[0]
def __iter__(self):
return self
def next(self):
return next(self.t)
def __getitem__(self, i):
for value in islice(self.t.__copy__(), i, None):
return value
raise IndexError(i)
</code></pre>
<p>Use the class to wrap an existing iterable or iterator. You can then either iterate normally using <em>next</em> or you can lookahead with indexed lookups.</p>
<pre><code>>>> it = LookAhead([10, 20, 30, 40, 50])
>>> next(it)
10
>>> it[0]
20
>>> next(it)
20
>>> it[0]
30
>>> list(it)
[30, 40, 50]
</code></pre>
<p>To run this code under Python 3, simply change the <em>next</em> method to <em>__next__</em>.</p>
| 2 | 2013-03-31T04:28:58Z | [
"python",
"generator",
"lookahead"
] |
What's the best way to read python documentation for all installed packages? | 1,517,885 | <p>I use python.org a lot for reading python documentation. I also use ipython help function, but I would prefer a GUI app that I could run on my machine that would show documentation for all installed packages.</p>
<p>Do you know if anything like this exists?</p>
<p>Do you have any suggestions?</p>
| 5 | 2009-10-05T01:20:07Z | 1,517,890 | <p>The <code>pydoc</code> command has a built-in HTTP server, which you can start with:</p>
<pre><code>pydoc -p 8080
</code></pre>
<p>Then head to <a href="http://localhost:8080/">http://localhost:8080/</a> in your browser. It will have documentation for all modules installed on its search path, which includes anything in <code>site-packages</code>.</p>
| 9 | 2009-10-05T01:25:04Z | [
"python",
"documentation"
] |
Python Image Uploading with AjaxUpload | 1,517,959 | <p>I'm trying to use AjaxUpload with Python:
<a href="http://valums.com/ajax-upload/" rel="nofollow">http://valums.com/ajax-upload/</a></p>
<p>I would like to know how to access the uploaded file with Python. On the web site, it says:</p>
<pre><code>* PHP: $_FILES['userfile']
* Rails: params[:userfile]
</code></pre>
<p>What is the Syntax for Python?</p>
<p>request.params['userfile'] doesn't seem to work.</p>
<p>Thanks in advance! Here is my current code (using PIL imported as Image)</p>
<pre><code>im = Image.open(request.params['myFile'].file)
</code></pre>
| 4 | 2009-10-05T02:00:14Z | 1,518,170 | <p>in django, you can use:</p>
<pre><code>request.FILES['file']
</code></pre>
<p>instead of:</p>
<pre><code>request.POST['file']
</code></pre>
<p>i did not know how to do in pylons...maybe it is the same concept..</p>
| 0 | 2009-10-05T03:37:07Z | [
"python",
"pylons",
"python-imaging-library",
"image-uploading",
"ajax-upload"
] |
Python Image Uploading with AjaxUpload | 1,517,959 | <p>I'm trying to use AjaxUpload with Python:
<a href="http://valums.com/ajax-upload/" rel="nofollow">http://valums.com/ajax-upload/</a></p>
<p>I would like to know how to access the uploaded file with Python. On the web site, it says:</p>
<pre><code>* PHP: $_FILES['userfile']
* Rails: params[:userfile]
</code></pre>
<p>What is the Syntax for Python?</p>
<p>request.params['userfile'] doesn't seem to work.</p>
<p>Thanks in advance! Here is my current code (using PIL imported as Image)</p>
<pre><code>im = Image.open(request.params['myFile'].file)
</code></pre>
| 4 | 2009-10-05T02:00:14Z | 1,698,974 | <pre><code>import cgi
#This will give you the data of the file,
# but won't give you the filename, unfortunately.
# For that you have to do some other trick.
file_data = cgi.FieldStorage.getfirst('file')
#<IGNORE if you're not using mod_python>
#(If you're using mod_python you can also get the Request object
# by passing 'req' to the relevant function in 'index.py', like "def func(req):"
# Then you access it with req.form.getfirst('file') instead. NOTE that the
# first method will work even when using mod_python, but the first FieldStorage
# object called is the only one with relevant data, so if you pass 'req' to the
# function you have to use the method that uses 'req'.)
#</IGNORE>
#Then you can write it to a file like so...
file = open('example_filename.wtvr','w')#'w' is for 'write'
file.write(file_data)
file.close()
#Then access it like so...
file = open('example_filename.wtvr','r')#'r' is for 'read'
#And use file.read() or whatever else to do what you want.
</code></pre>
| 1 | 2009-11-09T03:39:50Z | [
"python",
"pylons",
"python-imaging-library",
"image-uploading",
"ajax-upload"
] |
Python Image Uploading with AjaxUpload | 1,517,959 | <p>I'm trying to use AjaxUpload with Python:
<a href="http://valums.com/ajax-upload/" rel="nofollow">http://valums.com/ajax-upload/</a></p>
<p>I would like to know how to access the uploaded file with Python. On the web site, it says:</p>
<pre><code>* PHP: $_FILES['userfile']
* Rails: params[:userfile]
</code></pre>
<p>What is the Syntax for Python?</p>
<p>request.params['userfile'] doesn't seem to work.</p>
<p>Thanks in advance! Here is my current code (using PIL imported as Image)</p>
<pre><code>im = Image.open(request.params['myFile'].file)
</code></pre>
| 4 | 2009-10-05T02:00:14Z | 4,769,662 | <p>I'm working with Pyramid, and I was trying to do the same thing. After some time I came up with this solution.</p>
<pre><code>from cStringIO import StringIO
from cgi import FieldStorage
fs = FieldStorage(fp=request['wsgi.input'], environ=request)
f = StringIO(fs.value)
im = Image.open(f)
</code></pre>
<p>I'm not sure if it's the "right" one, but it seems to work.</p>
| 1 | 2011-01-22T18:22:49Z | [
"python",
"pylons",
"python-imaging-library",
"image-uploading",
"ajax-upload"
] |
banshee: How would I set the rating for a specific track on Banshee through DBus? | 1,517,984 | <p>I'd like to set the 'rating' of a specific track (i.e. not only the one currently playing) on Banshee through the DBus interface?</p>
| 1 | 2009-10-05T02:11:39Z | 1,560,744 | <p>Banshee does not expose rating functions via DBus.</p>
<p>You can quickly view all functions that it exposes, using applications like d-feet[1]. Make sure that an instance of the application you are interested in (like Banshee in this case) is running.</p>
<p>There is a bug report already requesting to add rating functionality[2] to DBus interface. You might want to subscribe to it.</p>
<ol>
<li><a href="https://fedorahosted.org/d-feet/" rel="nofollow">https://fedorahosted.org/d-feet/</a></li>
<li><a href="https://bugzilla.gnome.org/show%5Fbug.cgi?id=579754" rel="nofollow">https://bugzilla.gnome.org/show%5Fbug.cgi?id=579754</a></li>
</ol>
| 2 | 2009-10-13T14:54:18Z | [
"python",
"linux",
"dbus",
"banshee"
] |
banshee: How would I set the rating for a specific track on Banshee through DBus? | 1,517,984 | <p>I'd like to set the 'rating' of a specific track (i.e. not only the one currently playing) on Banshee through the DBus interface?</p>
| 1 | 2009-10-05T02:11:39Z | 7,144,007 | <p>Banshee does support rating via commandline since last year.</p>
<pre><code>banshee --set-rating={1;2;3;4;5}
</code></pre>
<p>See the bug report for more options:
<a href="https://bugzilla.gnome.org/show_bug.cgi?id=579754" rel="nofollow">Add item rating to DBus interface</a></p>
| 2 | 2011-08-22T06:52:13Z | [
"python",
"linux",
"dbus",
"banshee"
] |
banshee: How would I set the rating for a specific track on Banshee through DBus? | 1,517,984 | <p>I'd like to set the 'rating' of a specific track (i.e. not only the one currently playing) on Banshee through the DBus interface?</p>
| 1 | 2009-10-05T02:11:39Z | 11,862,540 | <p>Sadly the developer have not implemented a GET method, so there is no common way to execute "rate current track 1 star up/down"-command, much less than a specific track.
Does anyone has written a script which provide this feature?
Yet, I haven't found any solution to modify the D-Bus Property via command line.
Finally here is my Workaround for rate the current played Track.</p>
<pre><code>#!/bin/bash
#read current TrackRating
R=$(qdbus org.mpris.MediaPlayer2.banshee /org/mpris/MediaPlayer2 org.freedesktop.DBus.Properties.Get org.mpris.MediaPlayer2.Player Metadata | grep 'userRating' | tr -d '/xesam:userRating: ')
case $R in
'' ) R=0 ;;
'0.2' ) R=1 ;;
'0.4' ) R=2 ;;
'0.6' ) R=3 ;;
'0.8' ) R=4 ;;
'1' ) R=5 ;;
esac
case $1 in
'inc' ) [ $R -lt 5 ]
banshee --set-rating=$(($R+1)) ;;
'dec' ) [ $R -gt 0 ]
banshee --set-rating=$(($R-1)) ;;
'res' ) banshee --set-rating=3 ;;
'min' ) banshee --set-rating=0 ;;
'max' ) banshee --set-rating=5 ;;
esac
</code></pre>
<p>Options:</p>
<ul>
<li>inc -> increase rating by one if possible</li>
<li>dec -> decrease rating by one if possible</li>
<li>res -> reset rating to three stars</li>
<li>min -> set rating to zero stars</li>
<li>max -> set rating to five stars</li>
</ul>
<p>As far Banshee will not provide manipulating data of a specific Track this is my best bet.</p>
| 1 | 2012-08-08T10:26:46Z | [
"python",
"linux",
"dbus",
"banshee"
] |
How to keep query parameters during pagination with webhelpers.paginate | 1,518,068 | <p>I look an example of paginating from <a href="http://rapidprototype.ch/bg2docs/tg2pagination.html" rel="nofollow">http://rapidprototype.ch/bg2docs/tg2pagination.html</a> for my Turbogears 2 project and it works great but, I have a problem regarding my query parameters when I change the page I'm looking.</p>
<p>This is what I have in my controller when listing.</p>
<pre><code>def list(self, page=1, **kw):
q = ""
if kw.has_key('q'):
log.debug("searching %s" % kw)
q = kw['q']
if kw.has_key('all'):
q = ""
products = DBSession.query(model.Product).filter(
or_(model.Product.name.like('%%%s%%' % q),
model.Product.description.like('%%%s%%' % q),
model.Product.model.like('%%%s%%' % q),
model.Product.code.like('%%%s%%' % q))).all()
def get_link(product):
return Markup("""<a href="form?id=%s">%s</a>""" % (product.id, product.id))
product_fields = [
(Markup("""<a href="?s=id">Id</a>"""), get_link),
(u'Name', 'name'),
(u'Model', 'model'),
(u'Code', 'code'),
(u'Description', 'description')]
product_grid = MyDataGrid(fields = product_fields)
currentPage = paginate.Page(products, page, items_per_page=50)
return dict(currentPage=currentPage,
title=u'Products List', item=u'product', items=u'products',
data=currentPage.items,
grid=product_grid,
page=u'Search %s results' % q,
q=q,
hits=len(products))
</code></pre>
<p>This is the html template fragment</p>
<pre><code><h1>List of ${items}</h1>
<form action="list" method="get">
<input name="q" type="text" value="${value_of('q', default='')}"/>
<input type="submit" value="Search"/> <input type="submit" name="all" value="All"/>
</form>
${hits} ${items} found
<p class="pagelist">${currentPage.pager(format='$link_first ~3~ $link_last')}</p>
<div>
${grid(data)}
</div>
<p><a href="${tg.url('form')}">Add a ${item}</a></p>
</code></pre>
<p>The searches works fine resulting in links like this '<em>/list?q=cable</em>' but when I click some of the paginating pages "1,2...8,9" turns to '<em>/list?page=2</em>'</p>
<p>How do I add my previous query parameter or any other parameters to the link?</p>
| 2 | 2009-10-05T02:45:19Z | 1,518,293 | <p>After experimenting on the shell for a while I think I found a solution.</p>
<p>There's a kwargs dictionary defined in currentPage (after being assigned from paginate.Page), so I made some experiments sending parameters and it worked. This is how.</p>
<pre><code>currentPage = paginate.Page(products, page, items_per_page=50)
currentPage.kwargs['q'] = q
return dict(currentPage=currentPage,
title=u'Products List', item=u'product', items=u'products',
data=currentPage.items,
grid=product_grid,
page=u'Search %s results' % q,
q=q,
hits=len(products))
</code></pre>
<p>now I get this kind of links: '<em>/list?q=cable&page=2</em>' still wondering if it is the best solution or the <em>best practice</em></p>
| 1 | 2009-10-05T04:45:13Z | [
"python",
"pagination",
"pylons",
"genshi",
"turbogears2"
] |
How to keep query parameters during pagination with webhelpers.paginate | 1,518,068 | <p>I look an example of paginating from <a href="http://rapidprototype.ch/bg2docs/tg2pagination.html" rel="nofollow">http://rapidprototype.ch/bg2docs/tg2pagination.html</a> for my Turbogears 2 project and it works great but, I have a problem regarding my query parameters when I change the page I'm looking.</p>
<p>This is what I have in my controller when listing.</p>
<pre><code>def list(self, page=1, **kw):
q = ""
if kw.has_key('q'):
log.debug("searching %s" % kw)
q = kw['q']
if kw.has_key('all'):
q = ""
products = DBSession.query(model.Product).filter(
or_(model.Product.name.like('%%%s%%' % q),
model.Product.description.like('%%%s%%' % q),
model.Product.model.like('%%%s%%' % q),
model.Product.code.like('%%%s%%' % q))).all()
def get_link(product):
return Markup("""<a href="form?id=%s">%s</a>""" % (product.id, product.id))
product_fields = [
(Markup("""<a href="?s=id">Id</a>"""), get_link),
(u'Name', 'name'),
(u'Model', 'model'),
(u'Code', 'code'),
(u'Description', 'description')]
product_grid = MyDataGrid(fields = product_fields)
currentPage = paginate.Page(products, page, items_per_page=50)
return dict(currentPage=currentPage,
title=u'Products List', item=u'product', items=u'products',
data=currentPage.items,
grid=product_grid,
page=u'Search %s results' % q,
q=q,
hits=len(products))
</code></pre>
<p>This is the html template fragment</p>
<pre><code><h1>List of ${items}</h1>
<form action="list" method="get">
<input name="q" type="text" value="${value_of('q', default='')}"/>
<input type="submit" value="Search"/> <input type="submit" name="all" value="All"/>
</form>
${hits} ${items} found
<p class="pagelist">${currentPage.pager(format='$link_first ~3~ $link_last')}</p>
<div>
${grid(data)}
</div>
<p><a href="${tg.url('form')}">Add a ${item}</a></p>
</code></pre>
<p>The searches works fine resulting in links like this '<em>/list?q=cable</em>' but when I click some of the paginating pages "1,2...8,9" turns to '<em>/list?page=2</em>'</p>
<p>How do I add my previous query parameter or any other parameters to the link?</p>
| 2 | 2009-10-05T02:45:19Z | 1,587,593 | <p>you should use syntax like:</p>
<pre><code>currentPage.kwargs['q'] = q
currentPage = paginate.Page(
products,
page,
items_per_page=50,
q = q
)
</code></pre>
| 1 | 2009-10-19T08:48:11Z | [
"python",
"pagination",
"pylons",
"genshi",
"turbogears2"
] |
How to keep query parameters during pagination with webhelpers.paginate | 1,518,068 | <p>I look an example of paginating from <a href="http://rapidprototype.ch/bg2docs/tg2pagination.html" rel="nofollow">http://rapidprototype.ch/bg2docs/tg2pagination.html</a> for my Turbogears 2 project and it works great but, I have a problem regarding my query parameters when I change the page I'm looking.</p>
<p>This is what I have in my controller when listing.</p>
<pre><code>def list(self, page=1, **kw):
q = ""
if kw.has_key('q'):
log.debug("searching %s" % kw)
q = kw['q']
if kw.has_key('all'):
q = ""
products = DBSession.query(model.Product).filter(
or_(model.Product.name.like('%%%s%%' % q),
model.Product.description.like('%%%s%%' % q),
model.Product.model.like('%%%s%%' % q),
model.Product.code.like('%%%s%%' % q))).all()
def get_link(product):
return Markup("""<a href="form?id=%s">%s</a>""" % (product.id, product.id))
product_fields = [
(Markup("""<a href="?s=id">Id</a>"""), get_link),
(u'Name', 'name'),
(u'Model', 'model'),
(u'Code', 'code'),
(u'Description', 'description')]
product_grid = MyDataGrid(fields = product_fields)
currentPage = paginate.Page(products, page, items_per_page=50)
return dict(currentPage=currentPage,
title=u'Products List', item=u'product', items=u'products',
data=currentPage.items,
grid=product_grid,
page=u'Search %s results' % q,
q=q,
hits=len(products))
</code></pre>
<p>This is the html template fragment</p>
<pre><code><h1>List of ${items}</h1>
<form action="list" method="get">
<input name="q" type="text" value="${value_of('q', default='')}"/>
<input type="submit" value="Search"/> <input type="submit" name="all" value="All"/>
</form>
${hits} ${items} found
<p class="pagelist">${currentPage.pager(format='$link_first ~3~ $link_last')}</p>
<div>
${grid(data)}
</div>
<p><a href="${tg.url('form')}">Add a ${item}</a></p>
</code></pre>
<p>The searches works fine resulting in links like this '<em>/list?q=cable</em>' but when I click some of the paginating pages "1,2...8,9" turns to '<em>/list?page=2</em>'</p>
<p>How do I add my previous query parameter or any other parameters to the link?</p>
| 2 | 2009-10-05T02:45:19Z | 10,733,016 | <p>you can update request params, like this snippets.</p>
<pre><code>def paginate(self, items, items_per_page=20):
"""https://bitbucket.org/bbangert/webhelpers/src/acfb17881c1c/webhelpers/paginate.py"""
current_page = self.request.GET.get('page') or 1
def page_url(page):
params = self.request.params.copy()
params['page'] = page
return self.request.current_route_url(_query=params)
return Page(collection=items, page=current_page, items_per_page=items_per_page, url=page_url)
</code></pre>
| 0 | 2012-05-24T07:28:15Z | [
"python",
"pagination",
"pylons",
"genshi",
"turbogears2"
] |
Django - use reverse url mapping in settings | 1,518,286 | <p>A few of the options in the django settings file are urls, for example <code>LOGIN_URL</code> and <code>LOGIN_REDIRECT_URL</code>. Is it possible to avoid hardcoding these urls, and instead use reverse url mapping? At the moment this is really the only place where I find myself writing the same urls in multiple places.</p>
| 28 | 2009-10-05T04:40:49Z | 1,519,675 | <h1>Django 1.5 and later</h1>
<p>As of Django 1.5, <code>LOGIN_URL</code> and <code>LOGIN_REDIRECT_URL</code> accept named URL patterns. That means you don't need to hardcode any urls in your settings.</p>
<pre><code>LOGIN_URL = 'login' # name of url pattern
</code></pre>
<p>For Django 1.5 - 1.9, you can also use the view function name, but this is deprecated in Django 1.10 so it's not recommended.</p>
<pre><code>LOGIN_URL = 'django.contrib.auth.views.login' # path to view function
</code></pre>
<h1>Django 1.4</h1>
<p>For Django 1.4, you can could use <a href="https://docs.djangoproject.com/en/1.6/ref/urlresolvers/#reverse-lazy"><code>reverse_lazy</code></a></p>
<pre><code>LOGIN_URL = reverse_lazy('login')
</code></pre>
<h1>Django 1.3 and earlier</h1>
<p>This is the original answer, which worked before <code>reverse_lazy</code> was added to Django</p>
<p>In urls.py, import settings:</p>
<pre><code>from django.conf import settings
</code></pre>
<p>Then add the url pattern</p>
<pre><code>urlpatterns=('',
...
url('^%s$' %settings.LOGIN_URL[1:], 'django.contrib.auth.views.login',
name="login")
...
)
</code></pre>
<p>Note that you need to slice <code>LOGIN_URL</code> to remove the leading forward slash.</p>
<p>In the shell:</p>
<pre><code>>>>from django.core.urlresolvers import reverse
>>>reverse('login')
'/accounts/login/'
</code></pre>
| 39 | 2009-10-05T12:03:31Z | [
"python",
"django",
"url",
"dry"
] |
Django - use reverse url mapping in settings | 1,518,286 | <p>A few of the options in the django settings file are urls, for example <code>LOGIN_URL</code> and <code>LOGIN_REDIRECT_URL</code>. Is it possible to avoid hardcoding these urls, and instead use reverse url mapping? At the moment this is really the only place where I find myself writing the same urls in multiple places.</p>
| 28 | 2009-10-05T04:40:49Z | 8,790,991 | <p>In django development version reverse_lazy() becomes an option:
<a href="https://docs.djangoproject.com/en/dev/ref/urlresolvers/#reverse-lazy" rel="nofollow">https://docs.djangoproject.com/en/dev/ref/urlresolvers/#reverse-lazy</a></p>
| 11 | 2012-01-09T15:42:51Z | [
"python",
"django",
"url",
"dry"
] |
Using Embedded Dictionary for iterative charater replacement | 1,518,358 | <p>I'm trying to understand an iterative function that that takes a string "12345" and returns all the possible misspellings based upon a dictionary of keys close to each character in the string.</p>
<pre><code>outerDic = {}
Dict1 = {'1':'2','2':'q'}
outerDic['1'] = Dict1
Dict1 = {'1':'1','2':'q','3':'w','4':'3'}
outerDic['2'] = Dict1
Dict1 = {'1':'2','2':'w','3':'e','4':'4'}
outerDic['3'] = Dict1
Dict1 = {'1':'3','2':'e','3':'r','4':'5' }
outerDic['4'] = Dict1
Dict1 = {'1':'4','2':'r','3':'t','4':'6' }
outerDic['5'] = Dict1
outerDic
</code></pre>
<p>The output should return a list of strings</p>
<pre><code>12345
22345
q2345
11345
1q345
13345
12245
12e45
12445
</code></pre>
<p>and so on...</p>
<p>I've set the function up as follows:</p>
<pre><code>def split_line(text):
words = text.split()
for current_word in words:
getWordsIterations()
</code></pre>
<p>I'd like to understand how to set up the getWordsIterations () function to go through the dictionary and systematically replace the characters. </p>
<p>Thanks in advance, kind of new to pythong.</p>
| 0 | 2009-10-05T05:14:09Z | 1,518,387 | <p>I'm not sure what the inner dicts, all with keys '1', '2', etc, signify -- are they basically just stand-ins for lists presenting possible typos? But then some (but not all) would also include the "right" character... a non-typo...?! Sorry, but you're really being extremely confusing in this presentation -- the example doesn't help much (why is there never a "w" in the second position, which is supposed to be a possible typo there if I understand your weird data structure...? etc, etc).</p>
<p>So, while awaiting clarification, let me assume that all you want is to represent for each input character all possible single-character typos for it -- lists would be fine but strings are more compact in this case, and essentially equivalent:</p>
<pre><code>possible_typos = {
'1': '2q',
'2': '1qw3',
'3': '2we4',
'4': '3er5',
'5': '4rt6',
}
</code></pre>
<p>now if you only care about cases with exactly 1 mis-spelling:</p>
<pre><code>def one_typo(word):
L = list(word)
for i, c in enumerate(L):
for x in possible_typos[c]:
L[i] = x
yield ''.join(L)
L[i] = c
</code></pre>
<p>so for example, <code>for w in one_typo("12345"): print w</code> emits:</p>
<pre><code>22345
q2345
11345
1q345
1w345
13345
12245
12w45
12e45
12445
12335
123e5
123r5
12355
12344
1234r
1234t
12346
</code></pre>
<p>"Any number of typos" would produce an <em>enormous</em> list -- is that what you want? Or "0 to 2 typos"? Or what else exactly...?</p>
| 1 | 2009-10-05T05:28:54Z | [
"python",
"function",
"iteration"
] |
Python - Google App Engine | 1,518,383 | <p>I'm just starting learning google app engine.</p>
<p>When I enter the following code below, all I got is "Hello world!"
I think the desired result is "Hello, webapp World!"</p>
<p>What am I missing? I even try copying the google framework folder to live in the same folder as my app.</p>
<p>Thanks.</p>
<pre><code>from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
class MainPage(webapp.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write('Hello, webapp World!')
application = webapp.WSGIApplication(
[('/', MainPage)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
</code></pre>
| 0 | 2009-10-05T05:27:43Z | 1,518,392 | <p>Running exactly this code DOES give me the desired output. I suspect you must be erroneously running some <em>other</em> code, since there's absolutely <strong>no</strong> way this code as given could possibly emit what you observe.</p>
| 5 | 2009-10-05T05:30:50Z | [
"python"
] |
How to parse Youtube search results? | 1,518,481 | <p>When a user submits a query, I would like to append this to search results in Youtube and download this "page" on the backend of my code (Python-Django).</p>
<p>What is the best way to do this?
Do you suggest that I do this manually? And create a custom parser? Scanning each line for a certain pattern...</p>
<p>Or is there an easier way, such as using their API?</p>
<p>By the way, I am familiar with crawling. I just want to know the method for YOUTUBE. I understand how to download/parse pages. (I will be using urllib2.)</p>
| 0 | 2009-10-05T06:13:49Z | 1,518,526 | <p>The preferred way is probably with the <a href="http://code.google.com/apis/youtube/getting%5Fstarted.html#data%5Fapi" rel="nofollow">YouTube API</a></p>
| 5 | 2009-10-05T06:36:59Z | [
"python"
] |
Stripping code for production | 1,518,484 | <p>So I want to physically get rid of debugging code before deploying it to appengine.
What I'm doing right now is a simple check:</p>
<pre><code>settings.py:
DEBUG = os.environ['HTTP_HOST'] == 'localhost'
from settings import DEBUG
if DEBUG:
#ensure I haven't screwed smth up during refactoring
</code></pre>
<p>But this check will be consuming CPU cycles during each call, right?
In Java, there's a pattern that would strip debugging code at compile time:</p>
<pre><code>public static final boolean DEBUG = true; // change to false before going production
if(DEBUG){
//debug logging
}
</code></pre>
<p>Is there a clean way to achieve the same effect in Python or should I wrap the code to be stripped with smth like <code>#%STRIP_ME%</code> and then run a custom script against it?</p>
| 0 | 2009-10-05T06:14:55Z | 1,518,489 | <p>No, there isn't clean way. </p>
<p><a href="http://stackoverflow.com/questions/560040/conditional-compilation-in-python">http://stackoverflow.com/questions/560040/conditional-compilation-in-python</a></p>
<p>Differrent question, similar goals.</p>
| 3 | 2009-10-05T06:18:55Z | [
"python",
"google-app-engine"
] |
Stripping code for production | 1,518,484 | <p>So I want to physically get rid of debugging code before deploying it to appengine.
What I'm doing right now is a simple check:</p>
<pre><code>settings.py:
DEBUG = os.environ['HTTP_HOST'] == 'localhost'
from settings import DEBUG
if DEBUG:
#ensure I haven't screwed smth up during refactoring
</code></pre>
<p>But this check will be consuming CPU cycles during each call, right?
In Java, there's a pattern that would strip debugging code at compile time:</p>
<pre><code>public static final boolean DEBUG = true; // change to false before going production
if(DEBUG){
//debug logging
}
</code></pre>
<p>Is there a clean way to achieve the same effect in Python or should I wrap the code to be stripped with smth like <code>#%STRIP_ME%</code> and then run a custom script against it?</p>
| 0 | 2009-10-05T06:14:55Z | 1,518,512 | <p>If you are worried about the code and able to do this, you could use a decorator approach to inject the debugs, and then for production code, redefine the decorator functions to be no-ops. </p>
<p>Honestly, I wouldn't worry about it though since the if statement should correspond to a jump statement in assembly, or maybe a couple more than that.</p>
| 2 | 2009-10-05T06:32:56Z | [
"python",
"google-app-engine"
] |
Stripping code for production | 1,518,484 | <p>So I want to physically get rid of debugging code before deploying it to appengine.
What I'm doing right now is a simple check:</p>
<pre><code>settings.py:
DEBUG = os.environ['HTTP_HOST'] == 'localhost'
from settings import DEBUG
if DEBUG:
#ensure I haven't screwed smth up during refactoring
</code></pre>
<p>But this check will be consuming CPU cycles during each call, right?
In Java, there's a pattern that would strip debugging code at compile time:</p>
<pre><code>public static final boolean DEBUG = true; // change to false before going production
if(DEBUG){
//debug logging
}
</code></pre>
<p>Is there a clean way to achieve the same effect in Python or should I wrap the code to be stripped with smth like <code>#%STRIP_ME%</code> and then run a custom script against it?</p>
| 0 | 2009-10-05T06:14:55Z | 1,519,061 | <p>First, I'd suggest making your check "os.environ['SERVER_SOFTWARE'].startswith('Dev')". This will work even if you access the dev server on another host.</p>
<p>Also, your 'DEBUG' statement will only be evaluated the first time the config module is imported on each App server instance. This is fine, since the debug status won't change from request to request, and it also saves a few CPU cycles. I wouldn't worry about the CPU cycles consumed checking if you're in debug mode later, though - there is much, much lower hanging fruit, and I doubt you can even <em>measure</em> the performance degradation of a simple if statement.</p>
| 2 | 2009-10-05T09:34:06Z | [
"python",
"google-app-engine"
] |
Stripping code for production | 1,518,484 | <p>So I want to physically get rid of debugging code before deploying it to appengine.
What I'm doing right now is a simple check:</p>
<pre><code>settings.py:
DEBUG = os.environ['HTTP_HOST'] == 'localhost'
from settings import DEBUG
if DEBUG:
#ensure I haven't screwed smth up during refactoring
</code></pre>
<p>But this check will be consuming CPU cycles during each call, right?
In Java, there's a pattern that would strip debugging code at compile time:</p>
<pre><code>public static final boolean DEBUG = true; // change to false before going production
if(DEBUG){
//debug logging
}
</code></pre>
<p>Is there a clean way to achieve the same effect in Python or should I wrap the code to be stripped with smth like <code>#%STRIP_ME%</code> and then run a custom script against it?</p>
| 0 | 2009-10-05T06:14:55Z | 1,519,143 | <p>You would most likely benefit from using the <a href="http://docs.python.org/library/logging.html" rel="nofollow">logging module</a> and importance levels.</p>
<p>Code wouldn't need to be removed before publishing, you can granularly configure the importance level should you ever need to debug in production and it becomes easy to search your code for where notices originate from.</p>
| 1 | 2009-10-05T09:55:19Z | [
"python",
"google-app-engine"
] |
Python most common element in a list | 1,518,522 | <p>What is an efficient way to find the most common element in a Python list?</p>
<p>My list items may not be hashable so can't use a dictionary.
Also in case of draws the item with the lowest index should be returned. Example:</p>
<pre><code>>>> most_common(['duck', 'duck', 'goose'])
'duck'
>>> most_common(['goose', 'duck', 'duck', 'goose'])
'goose'
</code></pre>
| 63 | 2009-10-05T06:35:44Z | 1,518,531 | <p>If they are not hashable, you can sort them and do a single loop over the result counting the items (identical items will be next to each other). But it might be faster to make them hashable and use a dict.</p>
<pre><code>def most_common(lst):
cur_length = 0
max_length = 0
cur_i = 0
max_i = 0
cur_item = None
max_item = None
for i, item in sorted(enumerate(lst), key=lambda x: x[1]):
if cur_item is None or cur_item != item:
if cur_length > max_length or (cur_length == max_length and cur_i < max_i):
max_length = cur_length
max_i = cur_i
max_item = cur_item
cur_length = 1
cur_i = i
cur_item = item
else:
cur_length += 1
if cur_length > max_length or (cur_length == max_length and cur_i < max_i):
return cur_item
return max_item
</code></pre>
| 8 | 2009-10-05T06:39:56Z | [
"python",
"list"
] |
Python most common element in a list | 1,518,522 | <p>What is an efficient way to find the most common element in a Python list?</p>
<p>My list items may not be hashable so can't use a dictionary.
Also in case of draws the item with the lowest index should be returned. Example:</p>
<pre><code>>>> most_common(['duck', 'duck', 'goose'])
'duck'
>>> most_common(['goose', 'duck', 'duck', 'goose'])
'goose'
</code></pre>
| 63 | 2009-10-05T06:35:44Z | 1,518,533 | <p>Sort a copy of the list and find the longest run. You can decorate the list before sorting it with the index of each element, and then choose the run that starts with the lowest index in the case of a tie.</p>
| 5 | 2009-10-05T06:40:21Z | [
"python",
"list"
] |
Python most common element in a list | 1,518,522 | <p>What is an efficient way to find the most common element in a Python list?</p>
<p>My list items may not be hashable so can't use a dictionary.
Also in case of draws the item with the lowest index should be returned. Example:</p>
<pre><code>>>> most_common(['duck', 'duck', 'goose'])
'duck'
>>> most_common(['goose', 'duck', 'duck', 'goose'])
'goose'
</code></pre>
| 63 | 2009-10-05T06:35:44Z | 1,518,542 | <p>This is the obvious slow solution (O(n^2)) if neither sorting nor hashing is feasible, but equality comparison (<code>==</code>) is available:</p>
<pre><code>def most_common(items):
if not items:
raise ValueError
fitems = []
best_idx = 0
for item in items:
item_missing = True
i = 0
for fitem in fitems:
if fitem[0] == item:
fitem[1] += 1
d = fitem[1] - fitems[best_idx][1]
if d > 0 or (d == 0 and fitems[best_idx][2] > fitem[2]):
best_idx = i
item_missing = False
break
i += 1
if item_missing:
fitems.append([item, 1, i])
return items[best_idx]
</code></pre>
<p>But making your items hashable or sortable (as recommended by other answers) would almost always make finding the most common element faster if the length of your list (n) is large. O(n) on average with hashing, and O(n*log(n)) at worst for sorting.</p>
| 1 | 2009-10-05T06:46:53Z | [
"python",
"list"
] |
Python most common element in a list | 1,518,522 | <p>What is an efficient way to find the most common element in a Python list?</p>
<p>My list items may not be hashable so can't use a dictionary.
Also in case of draws the item with the lowest index should be returned. Example:</p>
<pre><code>>>> most_common(['duck', 'duck', 'goose'])
'duck'
>>> most_common(['goose', 'duck', 'duck', 'goose'])
'goose'
</code></pre>
| 63 | 2009-10-05T06:35:44Z | 1,518,563 | <p>Here:</p>
<pre><code>def most_common(l):
max = 0
maxitem = None
for x in set(l):
count = l.count(x)
if count > max:
max = count
maxitem = x
return maxitem
</code></pre>
<p>I have a vague feeling there is a method somewhere in the standard library that will give you the count of each element, but I can't find it.</p>
| 0 | 2009-10-05T06:56:18Z | [
"python",
"list"
] |
Python most common element in a list | 1,518,522 | <p>What is an efficient way to find the most common element in a Python list?</p>
<p>My list items may not be hashable so can't use a dictionary.
Also in case of draws the item with the lowest index should be returned. Example:</p>
<pre><code>>>> most_common(['duck', 'duck', 'goose'])
'duck'
>>> most_common(['goose', 'duck', 'duck', 'goose'])
'goose'
</code></pre>
| 63 | 2009-10-05T06:35:44Z | 1,518,564 | <pre><code>>>> li = ['goose', 'duck', 'duck']
>>> def foo(li):
st = set(li)
mx = -1
for each in st:
temp = li.count(each):
if mx < temp:
mx = temp
h = each
return h
>>> foo(li)
'duck'
</code></pre>
| 0 | 2009-10-05T06:56:50Z | [
"python",
"list"
] |
Python most common element in a list | 1,518,522 | <p>What is an efficient way to find the most common element in a Python list?</p>
<p>My list items may not be hashable so can't use a dictionary.
Also in case of draws the item with the lowest index should be returned. Example:</p>
<pre><code>>>> most_common(['duck', 'duck', 'goose'])
'duck'
>>> most_common(['goose', 'duck', 'duck', 'goose'])
'goose'
</code></pre>
| 63 | 2009-10-05T06:35:44Z | 1,518,588 | <p>A one-liner:</p>
<pre><code>def most_common (lst):
return max(((item, lst.count(item)) for item in set(lst)), key=lambda a: a[1])[0]</code></pre>
| 2 | 2009-10-05T07:04:24Z | [
"python",
"list"
] |
Python most common element in a list | 1,518,522 | <p>What is an efficient way to find the most common element in a Python list?</p>
<p>My list items may not be hashable so can't use a dictionary.
Also in case of draws the item with the lowest index should be returned. Example:</p>
<pre><code>>>> most_common(['duck', 'duck', 'goose'])
'duck'
>>> most_common(['goose', 'duck', 'duck', 'goose'])
'goose'
</code></pre>
| 63 | 2009-10-05T06:35:44Z | 1,518,632 | <p>A simpler one-liner:</p>
<pre><code>def most_common(lst):
return max(set(lst), key=lst.count)
</code></pre>
| 253 | 2009-10-05T07:14:52Z | [
"python",
"list"
] |
Python most common element in a list | 1,518,522 | <p>What is an efficient way to find the most common element in a Python list?</p>
<p>My list items may not be hashable so can't use a dictionary.
Also in case of draws the item with the lowest index should be returned. Example:</p>
<pre><code>>>> most_common(['duck', 'duck', 'goose'])
'duck'
>>> most_common(['goose', 'duck', 'duck', 'goose'])
'goose'
</code></pre>
| 63 | 2009-10-05T06:35:44Z | 1,518,754 | <pre><code># use Decorate, Sort, Undecorate to solve the problem
def most_common(iterable):
# Make a list with tuples: (item, index)
# The index will be used later to break ties for most common item.
lst = [(x, i) for i, x in enumerate(iterable)]
lst.sort()
# lst_final will also be a list of tuples: (count, index, item)
# Sorting on this list will find us the most common item, and the index
# will break ties so the one listed first wins. Count is negative so
# largest count will have lowest value and sort first.
lst_final = []
# Get an iterator for our new list...
itr = iter(lst)
# ...and pop the first tuple off. Setup current state vars for loop.
count = 1
tup = next(itr)
x_cur, i_cur = tup
# Loop over sorted list of tuples, counting occurrences of item.
for tup in itr:
# Same item again?
if x_cur == tup[0]:
# Yes, same item; increment count
count += 1
else:
# No, new item, so write previous current item to lst_final...
t = (-count, i_cur, x_cur)
lst_final.append(t)
# ...and reset current state vars for loop.
x_cur, i_cur = tup
count = 1
# Write final item after loop ends
t = (-count, i_cur, x_cur)
lst_final.append(t)
lst_final.sort()
answer = lst_final[0][2]
return answer
print most_common(['x', 'e', 'a', 'e', 'a', 'e', 'e']) # prints 'e'
print most_common(['goose', 'duck', 'duck', 'goose']) # prints 'goose'
</code></pre>
| 2 | 2009-10-05T08:02:50Z | [
"python",
"list"
] |
Python most common element in a list | 1,518,522 | <p>What is an efficient way to find the most common element in a Python list?</p>
<p>My list items may not be hashable so can't use a dictionary.
Also in case of draws the item with the lowest index should be returned. Example:</p>
<pre><code>>>> most_common(['duck', 'duck', 'goose'])
'duck'
>>> most_common(['goose', 'duck', 'duck', 'goose'])
'goose'
</code></pre>
| 63 | 2009-10-05T06:35:44Z | 1,519,293 | <p>This is an O(n) solution.</p>
<pre><code>mydict = {}
cnt, itm = 0, ''
for item in reversed(lst):
mydict[item] = mydict.get(item, 0) + 1
if mydict[item] >= cnt :
cnt, itm = mydict[item], item
print itm
</code></pre>
<p>(reversed is used to make sure that it returns the lowest index item)</p>
| 4 | 2009-10-05T10:29:02Z | [
"python",
"list"
] |
Python most common element in a list | 1,518,522 | <p>What is an efficient way to find the most common element in a Python list?</p>
<p>My list items may not be hashable so can't use a dictionary.
Also in case of draws the item with the lowest index should be returned. Example:</p>
<pre><code>>>> most_common(['duck', 'duck', 'goose'])
'duck'
>>> most_common(['goose', 'duck', 'duck', 'goose'])
'goose'
</code></pre>
| 63 | 2009-10-05T06:35:44Z | 1,520,716 | <p>With so many solutions proposed, I'm amazed nobody's proposed what I'd consider an obvious one (for non-hashable but comparable elements) -- [<code>itertools.groupby</code>][1]. <code>itertools</code> offers fast, reusable functionality, and lets you delegate some tricky logic to well-tested standard library components. Consider for example:</p>
<pre><code>import itertools
import operator
def most_common(L):
# get an iterable of (item, iterable) pairs
SL = sorted((x, i) for i, x in enumerate(L))
# print 'SL:', SL
groups = itertools.groupby(SL, key=operator.itemgetter(0))
# auxiliary function to get "quality" for an item
def _auxfun(g):
item, iterable = g
count = 0
min_index = len(L)
for _, where in iterable:
count += 1
min_index = min(min_index, where)
# print 'item %r, count %r, minind %r' % (item, count, min_index)
return count, -min_index
# pick the highest-count/earliest item
return max(groups, key=_auxfun)[0]
</code></pre>
<p>This could be written more concisely, of course, but I'm aiming for maximal clarity. The two <code>print</code> statements can be uncommented to better see the machinery in action; for example, <em>with</em> prints uncommented:</p>
<pre><code>print most_common(['goose', 'duck', 'duck', 'goose'])
</code></pre>
<p>emits:</p>
<pre><code>SL: [('duck', 1), ('duck', 2), ('goose', 0), ('goose', 3)]
item 'duck', count 2, minind 1
item 'goose', count 2, minind 0
goose
</code></pre>
<p>As you see, <code>SL</code> is a list of pairs, each pair an item followed by the item's index in the original list (to implement the key condition that, if the "most common" items with the same highest count are > 1, the result must be the earliest-occurring one).</p>
<p><code>groupby</code> groups by the item only (via <code>operator.itemgetter</code>). The auxiliary function, called once per grouping during the <code>max</code> computation, receives and internally unpacks a group - a tuple with two items <code>(item, iterable)</code> where the iterable's items are also two-item tuples, <code>(item, original index)</code> [[the items of <code>SL</code>]].</p>
<p>Then the auxiliary function uses a loop to determine both the count of entries in the group's iterable, <em>and</em> the minimum original index; it returns those as combined "quality key", with the min index sign-changed so the <code>max</code> operation will consider "better" those items that occurred earlier in the original list.</p>
<p>This code could be much simpler if it worried a <em>little</em> less about big-O issues in time and space, e.g....:</p>
<pre><code>def most_common(L):
groups = itertools.groupby(sorted(L))
def _auxfun((item, iterable)):
return len(list(iterable)), -L.index(item)
return max(groups, key=_auxfun)[0]
</code></pre>
<p>same basic idea, just expressed more simply and compactly... but, alas, an extra O(N) auxiliary space (to embody the groups' iterables to lists) and O(N squared) time (to get the <code>L.index</code> of every item). While premature optimization is the root of all evil in programming, deliberately picking an O(N squared) approach when an O(N log N) one is available just goes too much against the grain of scalability!-)</p>
<p>Finally, for those who prefer "oneliners" to clarity and performance, a bonus 1-liner version with suitably mangled names:-).</p>
<pre><code>from itertools import groupby as g
def most_common_oneliner(L):
return max(g(sorted(L)), key=lambda(x, v):(len(list(v)),-L.index(x)))[0]
</code></pre>
| 49 | 2009-10-05T15:16:29Z | [
"python",
"list"
] |
Python most common element in a list | 1,518,522 | <p>What is an efficient way to find the most common element in a Python list?</p>
<p>My list items may not be hashable so can't use a dictionary.
Also in case of draws the item with the lowest index should be returned. Example:</p>
<pre><code>>>> most_common(['duck', 'duck', 'goose'])
'duck'
>>> most_common(['goose', 'duck', 'duck', 'goose'])
'goose'
</code></pre>
| 63 | 2009-10-05T06:35:44Z | 2,634,155 | <p>You probably don't need this anymore, but this is what I did for a similar problem. (It looks longer than it is because of the comments.)</p>
<pre><code>itemList = ['hi', 'hi', 'hello', 'bye']
counter = {}
maxItemCount = 0
for item in itemList:
try:
# Referencing this will cause a KeyError exception
# if it doesn't already exist
counter[item]
# ... meaning if we get this far it didn't happen so
# we'll increment
counter[item] += 1
except KeyError:
# If we got a KeyError we need to create the
# dictionary key
counter[item] = 1
# Keep overwriting maxItemCount with the latest number,
# if it's higher than the existing itemCount
if counter[item] > maxItemCount:
maxItemCount = counter[item]
mostPopularItem = item
print mostPopularItem
</code></pre>
| 3 | 2010-04-14T00:35:16Z | [
"python",
"list"
] |
Python most common element in a list | 1,518,522 | <p>What is an efficient way to find the most common element in a Python list?</p>
<p>My list items may not be hashable so can't use a dictionary.
Also in case of draws the item with the lowest index should be returned. Example:</p>
<pre><code>>>> most_common(['duck', 'duck', 'goose'])
'duck'
>>> most_common(['goose', 'duck', 'duck', 'goose'])
'goose'
</code></pre>
| 63 | 2009-10-05T06:35:44Z | 19,600,390 | <pre><code>def mostCommon(lst):
# Finds the element of highest value & occurrence
table = {}
# Counts the number of occurences for each number
for ele in lst:
if ele in table:
table[ele] = table[ele] + 1
else:
table.update( {ele : 1} )
# Inverts the keys & values
invert = lambda mydict: {v:k for k, v in mydict.items()}
table = invert(table) # Inverting is necessary to access values
# Returns highest value in dictionary
return table[ max(table.keys()) ]
</code></pre>
| 0 | 2013-10-25T22:30:07Z | [
"python",
"list"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.