title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
split a generator/iterable every n items in python (splitEvery)
1,915,170
16
2009-12-16T14:58:28Z
22,919,323
11
2014-04-07T17:36:55Z
[ "python", "iterator", "split" ]
I'm trying to write the Haskel function 'splitEvery' in Python. Here is it's definition: ``` splitEvery :: Int -> [e] -> [[e]] @'splitEvery' n@ splits a list into length-n pieces. The last piece will be shorter if @n@ does not evenly divide the length of the list. ``` The basic version of this works fine...
Here's a quick one-liner version. Like Haskell's, it is lazy. ``` from itertools import islice, takewhile, count split_every = (lambda n, it: takewhile(bool, (list(islice(it, n)) for _ in count(0)))) ``` This requires that you use `iter` **before** calling `split_every`, because it doesn't keep any internal state...
Is python's sorted() function guaranteed to be stable?
1,915,376
40
2009-12-16T15:30:01Z
1,915,418
47
2009-12-16T15:36:08Z
[ "python", "sorted", "stable-sort" ]
The [documentation](http://docs.python.org/library/functions.html#sorted) doesn't guarantee that. Is there any other place that it is documented? I'm guessing it might be stable since the sort method on lists is [guaranteed to be stable](http://docs.python.org/library/stdtypes.html#mutable-sequence-types) (Notes 9th p...
Yes, the intention of the manual is indeed to guarantee that `sorted` is stable and indeed that it uses exactly the same algorithm as the `sort` method. I do realize that the docs aren't 100% clear about this identity; doc patches are always happily accepted!
Is python's sorted() function guaranteed to be stable?
1,915,376
40
2009-12-16T15:30:01Z
1,971,943
16
2009-12-28T22:42:14Z
[ "python", "sorted", "stable-sort" ]
The [documentation](http://docs.python.org/library/functions.html#sorted) doesn't guarantee that. Is there any other place that it is documented? I'm guessing it might be stable since the sort method on lists is [guaranteed to be stable](http://docs.python.org/library/stdtypes.html#mutable-sequence-types) (Notes 9th p...
They are [stable](http://wiki.python.org/moin/HowTo/Sorting/). Although you don't need to know if sort and sorted are stable, because you don't need to sort in two steps when having multiple keys. For example, if you want to sort objects based on their `last_name`, `first_name` attributes, you can: ``` sorted_list= s...
python, convert a dictionary to a sorted list by value instead of key
1,915,564
13
2009-12-16T15:54:15Z
1,915,602
37
2009-12-16T15:58:48Z
[ "python", "sorting" ]
I have a collections.defaultdict(int) that I'm building to keep count of how many times a key shows up in a set of data. I later want to be able to sort it (obviously by turning it into a list first) in a descending fashion, ordered with the highest values first. I created my dictionary like the following: ``` adict =...
To get the dictionary sorted: ``` from operator import itemgetter sorted(adict.iteritems(), key=itemgetter(1), reverse=True) ```
python, convert a dictionary to a sorted list by value instead of key
1,915,564
13
2009-12-16T15:54:15Z
1,915,631
32
2009-12-16T16:02:48Z
[ "python", "sorting" ]
I have a collections.defaultdict(int) that I'm building to keep count of how many times a key shows up in a set of data. I later want to be able to sort it (obviously by turning it into a list first) in a descending fashion, ordered with the highest values first. I created my dictionary like the following: ``` adict =...
A dict's keys, reverse-sorted by the corresponding values, can best be gotten as ``` sorted(adict, key=adict.get, reverse=True) ``` since you want key/value pairs, you could work on the items as all other answers suggest, or (to use the nifty `adict.get` bound method instead of itemgetters or weird lambdas;-), ``` [...
python descriptors sharing values across classes
1,915,643
3
2009-12-16T16:03:50Z
1,915,712
7
2009-12-16T16:11:00Z
[ "python", "descriptor" ]
A python descriptor that I'm working with is sharing its value across all instances of its owner class. How can I make each instance's descriptor contain its own internal values? ``` class Desc(object): def __init__(self, initval=None,name='val'): self.val = initval self.name = name def __get_...
There is only one descriptor object, stored on the class object, so `self` is always the same. If you want to store data per-object and access it through the descriptor, you either have to store the data on each object (probably the better idea) or in some data-structure keyed by each object (an idea I don't like as mu...
with statement - backport for Python 2.5
1,915,927
4
2009-12-16T16:37:52Z
1,915,956
7
2009-12-16T16:41:35Z
[ "python", "with-statement", "backport" ]
I'd like to use `with` statement in Python 2.5 in some production code. It was backported, should I expect any problems (e.g. with availability/compatibility on other machines/etc)? Is this code ``` from __future__ import with_statement ``` compatible with Python 2.6?
Yes, that statement is a no-operation in Python 2.6, so you can freely use it to make `with` a keyword in your 2.5 code as well, without affecting your code's operation in 2.6. This is in fact the general design intention of "importing from the future" in Python!
Simplest way to publish over Zeroconf/Bonjour?
1,916,017
10
2009-12-16T16:51:17Z
1,916,772
9
2009-12-16T18:44:52Z
[ "python", "bonjour", "zeroconf" ]
I've got some apps I would like to make visible with zeroconf. 1. Is there an easy scriptable way to do this? 2. Is there anything that needs to be done by my network admin to enable this? Python or sh would be preferrable. OS-specific suggestions welcome for Linux and OS X.
I'd recommend [pybonjour](http://code.google.com/p/pybonjour/).
In Python, how can I test if I'm in Google App Engine SDK?
1,916,579
32
2009-12-16T18:14:30Z
1,916,594
52
2009-12-16T18:17:22Z
[ "python", "google-app-engine" ]
Whilst developing I want to handle some things slight differently than I will when I eventually upload to the Google servers. Is there a quick test that I can do to find out if I'm in the SDK or live?
See: [https://cloud.google.com/appengine/docs/python/how-requests-are-handled#Python\_The\_environment](http://code.google.com/appengine/docs/python/runtime.html#The_Environment) > The following environment variables are part of the CGI standard, with special behavior in App Engine: > `SERVER_SOFTWARE`: > > In the **d...
Programmatic Python Browser with JavaScript
1,916,711
12
2009-12-16T18:37:08Z
1,916,748
11
2009-12-16T18:42:13Z
[ "javascript", "python", "browser", "screen-scraping", "mechanize" ]
I want to screen-scrape a web-site that uses JavaScript. There is [mechanize](http://wwwsearch.sourceforge.net/mechanize/), the programmatic web browser for Python. However, it (understandably) doesn't interpret javascript. Is there any programmatic browser for Python which does? If not, is there any JavaScript implem...
You might be better off using a tool like [Selenium](http://seleniumhq.org/) to automate the scraping using a web browser, so the JS executes and the page renders just like it would for a real user.
Programmatic Python Browser with JavaScript
1,916,711
12
2009-12-16T18:37:08Z
1,917,551
7
2009-12-16T20:43:00Z
[ "javascript", "python", "browser", "screen-scraping", "mechanize" ]
I want to screen-scrape a web-site that uses JavaScript. There is [mechanize](http://wwwsearch.sourceforge.net/mechanize/), the programmatic web browser for Python. However, it (understandably) doesn't interpret javascript. Is there any programmatic browser for Python which does? If not, is there any JavaScript implem...
The [PyV8](http://code.google.com/p/pyv8/) package nicely wraps [Google's V8 Javascript engine](http://code.google.com/apis/v8/) for Python. It's particularly nice because not only can you call from Python to Javascript code, but you can call back from Javascript to Python code. This makes it quite straightforward to i...
Filter zipcodes by proximity in Django with the Spherical Law of Cosines
1,916,953
10
2009-12-16T19:12:28Z
1,917,068
8
2009-12-16T19:30:08Z
[ "python", "django", "zipcode", "proximity" ]
I'm trying to handle proximity search for a basic store locater in Django. Rather than haul PostGIS around with my app just so I can use GeoDjango's distance filter, I'd like to use the Spherical Law of Cosines distance formula in a model query. I'd like all of the calculations to be done in the database in one query, ...
It's possible the execute [raw SQL queries in Django](http://docs.djangoproject.com/en/dev/topics/db/sql/ "raw SQL queries in Django"). My suggestion is, write the query to pull a list of IDs (which it looks like you're doing now), then use the IDs to pull the associated models (in a regular, non-raw-SQL Django query)...
Filter zipcodes by proximity in Django with the Spherical Law of Cosines
1,916,953
10
2009-12-16T19:12:28Z
3,034,230
8
2010-06-13T23:02:33Z
[ "python", "django", "zipcode", "proximity" ]
I'm trying to handle proximity search for a basic store locater in Django. Rather than haul PostGIS around with my app just so I can use GeoDjango's distance filter, I'd like to use the Spherical Law of Cosines distance formula in a model query. I'd like all of the calculations to be done in the database in one query, ...
To follow up on Tom's answer, it won't work in SQLite by default because of SQLite's lack of math functions by default. No problem, it's pretty simple to add: ``` class LocationManager(models.Manager): def nearby_locations(self, latitude, longitude, radius, max_results=100, use_miles=True): if use_miles: ...
How to launch a Python/Tkinter dialog box that self-destructs?
1,917,198
4
2009-12-16T19:50:51Z
1,917,389
9
2009-12-16T20:19:26Z
[ "python", "tkinter" ]
Ok, I would like to put together a Python/Tkinter dialog box that displays a simple message and self-destructs after N seconds. Is there a simple way to do this?
You can use the `after` function to call a function after a delay elapsed and the `destroy` to close the window. Here is an example ``` from Tkinter import Label, Tk root = Tk() prompt = 'hello' label1 = Label(root, text=prompt, width=len(prompt)) label1.pack() def close_after_2s(): root.destroy() root.after(20...
Relational/Logic Programming in Python?
1,917,607
26
2009-12-16T20:50:21Z
1,917,894
9
2009-12-16T21:32:33Z
[ "python", "prolog", "logic-programming" ]
I'm a longtime python developer and recently have been introduced to Prolog. I love the concept of using relationship rules for certain kinds of tasks, and would like to add this to my repertoire. Are there any good libraries for logic programming in Python? I've done some searching on Google but only found the follow...
Perhaps you should google "Logic Programming in Python". [Pyke](http://pyke.sourceforge.net/) looks promising: > Pyke introduces a form of Logic Programming (inspired by Prolog) to > the Python community by providing a knowledge-based inference engine > (expert system) written in 100% Python. > > Unlike Prolog, Pyke i...
Relational/Logic Programming in Python?
1,917,607
26
2009-12-16T20:50:21Z
11,334,962
9
2012-07-04T20:11:51Z
[ "python", "prolog", "logic-programming" ]
I'm a longtime python developer and recently have been introduced to Prolog. I love the concept of using relationship rules for certain kinds of tasks, and would like to add this to my repertoire. Are there any good libraries for logic programming in Python? I've done some searching on Google but only found the follow...
You may want to use [pyDatalog](https://sites.google.com/site/pydatalog/), a logic programming library that I developed for Python implementing [Datalog](http://en.wikipedia.org/wiki/Datalog). It also works with SQLAlchemy to query relational databases using logic clauses.
Perl within Python?
1,917,656
6
2009-12-16T20:55:18Z
1,917,758
11
2009-12-16T21:09:16Z
[ "python", "perl", "text-mining" ]
There is a Perl library I would like to access from within Python. How can I use it? FYI, the software is [NCleaner](http://webascorpus.sourceforge.net/PHITE.php?sitesig=FILES&page=FILES%5F10%5FSoftware). I would like to use it from within Python to transform an HTML string into text. (Yes, I know about aaronsw's Pyth...
[pyperl](http://search.cpan.org/~gaas/pyperl-1.0/perlmodule.pod) provides perl embedding for python, but honestly it's not the way I'd go. I second Roboto's suggestion -- write a script that runs NCleaner (either processing from stdin to stdout, or working on temporary files, whichever one is more appropriate), and run...
Python import mechanics
1,917,958
10
2009-12-16T21:41:59Z
1,918,211
11
2009-12-16T22:20:10Z
[ "python", "coding-style", "import", "module", "conventions" ]
I have two related Python 'import' questions. They are easily testable, but I want answers that are language-defined and not implementation-specific, and I'm also interested in style/convention, so I'm asking here instead. 1) If module A imports module B, and module B imports module C, can code in module A reference ...
The first thing you should know is that the Python language is NOT an ISO standard. This is rather different from C/C++, and it means that there's no "proper" way to define a language behaviour - CPython might do something just because it was coded that way, and Jython might do the other way round. about your question...
Python import mechanics
1,917,958
10
2009-12-16T21:41:59Z
1,918,234
7
2009-12-16T22:24:23Z
[ "python", "coding-style", "import", "module", "conventions" ]
I have two related Python 'import' questions. They are easily testable, but I want answers that are language-defined and not implementation-specific, and I'm also interested in style/convention, so I'm asking here instead. 1) If module A imports module B, and module B imports module C, can code in module A reference ...
Alan's given a great answer, but I wanted to add that for your question 1 it depends on what you mean by 'imports'. If you use the `from C import x` syntax, then `x` becomes available in the namespace of `B`. If in `A` you then do `import B`, you *will* have access to `x` from `A` as `B.x`. It's not so much bad pract...
Making python/tkinter label widget update?
1,918,005
13
2009-12-16T21:47:52Z
1,918,054
14
2009-12-16T21:54:29Z
[ "python", "tkinter" ]
I'm working on getting a python/tkinter label widget to update its contents. Per an earlier thread today, I followed instructions on how to put together the widgets. At runtime, however, the label widget does NOT change contents, but simply retains its original content. As far as I can tell, decrement\_widget() is neve...
You'll want to set the label's `textvariable` with a [`StringVar`](http://epydoc.sourceforge.net/stdlib/Tkinter.StringVar-class.html); when the `StringVar` changes (by you calling `myStringVar.set("text here")`), then the label's text also gets updated. And yes, I agree, this is a strange way to do things. See [the Tk...
Python lists append return value
1,918,270
3
2009-12-16T22:29:35Z
1,918,296
13
2009-12-16T22:34:28Z
[ "python", "list" ]
I wanted to create a simple binary tree as followed by this image: ![http://imgur.com/QCVSW.png](http://i.stack.imgur.com/hpG9u.png) basically empty , but the last values so I created the root list : ``` root = [list(),list()] ``` and made a recursive function to populate it all : ``` def TF(nodeT,nodeF , i): ...
To solve your exact question, you can do this: ``` def list_append(lst, item): lst.append(item) return lst ``` and then `list_append(lst, item)` will append `item` to the `lst` and then return the `lst`.
Python lists append return value
1,918,270
3
2009-12-16T22:29:35Z
16,938,091
7
2013-06-05T10:56:20Z
[ "python", "list" ]
I wanted to create a simple binary tree as followed by this image: ![http://imgur.com/QCVSW.png](http://i.stack.imgur.com/hpG9u.png) basically empty , but the last values so I created the root list : ``` root = [list(),list()] ``` and made a recursive function to populate it all : ``` def TF(nodeT,nodeF , i): ...
In python you can use the "+" operator to contatenate two lists leaving the originals untouched. I guess that's what you want to do according to your question title. Thus ``` [1, 2] + [3] ``` will return ``` [1, 2, 3] ``` so you can use it more in a "functional fashion". Just in case you need it ``` [1, 2].__add__...
Can anyone explain python's relative imports?
1,918,539
86
2009-12-16T23:27:05Z
1,918,581
84
2009-12-16T23:37:54Z
[ "python" ]
I can't for the life of me get python's relative imports to work. I have created a simple example of where it does not function: The directory structure is: ``` /__init__.py /start.py /parent.py /sub/__init__.py /sub/relative.py ``` `/start.py` contains just: `import sub.relative` `/sub/relative.py` contains just `...
You are importing from package "sub". `start.py` is not itself in a package even if there is a `__init__.py` present. You would need to start your program from one directory over `parent.py`: ``` ./start.py ./pkg/__init__.py ./pkg/parent.py ./pkg/sub/__init__.py ./pkg/sub/relative.py ``` With `start.py`: ``` impor...
Reading a file via open().read() vs storing it in a variable
1,918,965
2
2009-12-17T01:41:19Z
1,918,988
10
2009-12-17T01:47:29Z
[ "python" ]
I've written this small app in Python that will generate paragraphs of dummy text, kind of like [this site](http://www.lipsum.com/), except it'll work offline. Right now you're supposed to provide a reasonably long text file (I'm currently using books from Project Gutenberg), which it will call open() and then read() o...
There's a few problems: * Your program becomes really hard to read. * You run the risk of """ appearing in the text and blowing everything up * You break the whole concept of content existing in the format in which it belongs. The book in question is a text file, it should live in a text file and if Python needs it, i...
Is there a better way to iterate over two lists, getting one element from each list for each iteration?
1,919,044
67
2009-12-17T02:00:55Z
1,919,055
126
2009-12-17T02:03:39Z
[ "python", "list", "iteration" ]
I have a list of Latitudes and one of Longitudes and need to iterate over the latitude and longitude pairs. Do you think it's be better to: A) (assume that equal lengths is already checked) ``` for i in range(len(Latitudes): Lat,Long=(Latitudes[i],Longitudes[i]) ``` \*\*\* EDIT .... or, B) ``` for Lat,Long in [(...
This is as pythonic as you can get: ``` for lat, long in zip(Latitudes, Longitudes): print lat, long ```
Is there a better way to iterate over two lists, getting one element from each list for each iteration?
1,919,044
67
2009-12-17T02:00:55Z
1,919,075
15
2009-12-17T02:10:49Z
[ "python", "list", "iteration" ]
I have a list of Latitudes and one of Longitudes and need to iterate over the latitude and longitude pairs. Do you think it's be better to: A) (assume that equal lengths is already checked) ``` for i in range(len(Latitudes): Lat,Long=(Latitudes[i],Longitudes[i]) ``` \*\*\* EDIT .... or, B) ``` for Lat,Long in [(...
Good to see lots of love for `zip` in the answers here. However it should be noted that if you are using a python version before 3.0, the `itertools` module in the standard library contains an `izip` function which returns an iterable, which is more appropriate in this case (especially if your list of latt/longs is qu...
Is there a better way to iterate over two lists, getting one element from each list for each iteration?
1,919,044
67
2009-12-17T02:00:55Z
1,919,402
28
2009-12-17T04:10:06Z
[ "python", "list", "iteration" ]
I have a list of Latitudes and one of Longitudes and need to iterate over the latitude and longitude pairs. Do you think it's be better to: A) (assume that equal lengths is already checked) ``` for i in range(len(Latitudes): Lat,Long=(Latitudes[i],Longitudes[i]) ``` \*\*\* EDIT .... or, B) ``` for Lat,Long in [(...
Another way to do this would be to by using `map`. ``` >>> a [1, 2, 3] >>> b [4, 5, 6] >>> for i,j in map(None,a,b): ... print i,j ... 1 4 2 5 3 6 ``` One difference in using map compared to zip is, with zip the length of new list is same as the length of shortest list. For example: ``` >>> a [1, 2, 3, 9...
Is there a better way to iterate over two lists, getting one element from each list for each iteration?
1,919,044
67
2009-12-17T02:00:55Z
1,919,544
12
2009-12-17T04:54:35Z
[ "python", "list", "iteration" ]
I have a list of Latitudes and one of Longitudes and need to iterate over the latitude and longitude pairs. Do you think it's be better to: A) (assume that equal lengths is already checked) ``` for i in range(len(Latitudes): Lat,Long=(Latitudes[i],Longitudes[i]) ``` \*\*\* EDIT .... or, B) ``` for Lat,Long in [(...
in case your Latitude and Longitude lists are large and lazily loaded: ``` from itertools import izip for lat, lon in izip(latitudes, longitudes): process(lat, lon) ``` or if you want to avoid the for-loop ``` from itertools import izip, imap out = imap(process, izip(latitudes, longitudes)) ```
Mass string replace in python?
1,919,096
37
2009-12-17T02:17:38Z
1,919,112
24
2009-12-17T02:24:03Z
[ "python", "regex", "string", "performance", "replace" ]
Say I have a string that looks like this: ``` str = "The &yquick &cbrown &bfox &Yjumps over the &ulazy dog" ``` You'll notice a lot of locations in the string where there is an ampersand, followed by a character (such as "&y" and "&c"). I need to replace these characters with an appropriate value that I have in a dic...
``` mydict = {"&y":"\033[0;30m", "&c":"\033[0;31m", "&b":"\033[0;32m", "&Y":"\033[0;33m", "&u":"\033[0;34m"} mystr = "The &yquick &cbrown &bfox &Yjumps over the &ulazy dog" for k, v in mydict.iteritems(): mystr = mystr.replace(k, v) print mystr The ←[0;30mquick ←[0;31mb...
Mass string replace in python?
1,919,096
37
2009-12-17T02:17:38Z
1,919,121
7
2009-12-17T02:27:00Z
[ "python", "regex", "string", "performance", "replace" ]
Say I have a string that looks like this: ``` str = "The &yquick &cbrown &bfox &Yjumps over the &ulazy dog" ``` You'll notice a lot of locations in the string where there is an ampersand, followed by a character (such as "&y" and "&c"). I need to replace these characters with an appropriate value that I have in a dic...
If you really want to dig into the topic take a look at this: <http://en.wikipedia.org/wiki/Aho-Corasick%5Falgorithm> The obvious solution by iterating over the dictionary and replacing each element in the string takes `O(n*m)` time, where n is the size of the dictionary, m is the length of the string. Whereas the Ah...
Mass string replace in python?
1,919,096
37
2009-12-17T02:17:38Z
1,919,124
13
2009-12-17T02:27:43Z
[ "python", "regex", "string", "performance", "replace" ]
Say I have a string that looks like this: ``` str = "The &yquick &cbrown &bfox &Yjumps over the &ulazy dog" ``` You'll notice a lot of locations in the string where there is an ampersand, followed by a character (such as "&y" and "&c"). I need to replace these characters with an appropriate value that I have in a dic...
Try this, making use of regular expression substitution, and standard string formatting: ``` # using your stated values for str and dict: >>> import re >>> str = re.sub(r'(&[a-zA-Z])', r'%(\1)s', str) >>> str % dict 'The \x1b[0;30mquick \x1b[0;31mbrown \x1b[0;32mfox \x1b[0;33mjumps over the \x1b[0;34mlazy dog' ``` Th...
What is so bad with threadlocals
1,920,053
21
2009-12-17T07:29:08Z
1,921,176
17
2009-12-17T11:39:39Z
[ "python", "django", "thread-local" ]
Everybody in Django world seems to hate threadlocals(<http://code.djangoproject.com/ticket/4280>, <http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser>). I read Armin's essay on this(<http://lucumr.pocoo.org/2006/7/10/why-i-cant-stand-threadlocal-and-others>), but most of it hinges on threadlocals is bad bec...
I don't think there is anything wrong with threadlocals - yes, it is a global variable, but besides that it's a normal tool. We use it just for this purpose (storing subdomain model in the context global to the current request from middleware) and it works perfectly. So I say, use the right tool for the job, in this c...
What is so bad with threadlocals
1,920,053
21
2009-12-17T07:29:08Z
1,924,524
21
2009-12-17T20:53:51Z
[ "python", "django", "thread-local" ]
Everybody in Django world seems to hate threadlocals(<http://code.djangoproject.com/ticket/4280>, <http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser>). I read Armin's essay on this(<http://lucumr.pocoo.org/2006/7/10/why-i-cant-stand-threadlocal-and-others>), but most of it hinges on threadlocals is bad bec...
I avoid this sort of usage of threadlocals, because it introduces an implicit non-local coupling. I frequently use models in all kinds of non-HTTP-oriented ways (local management commands, data import/export, etc). If I access some threadlocals data in models.py, now I have to find some way to ensure that it is always ...
How to find duplicate elements in array using for loop in Python?
1,920,145
17
2009-12-17T08:01:33Z
1,920,179
23
2009-12-17T08:11:01Z
[ "python", "duplicates" ]
I have a list with duplicate elements: ``` list_a=[1,2,3,5,6,7,5,2] tmp=[] for i in list_a: if tmp.__contains__(i): print i else: tmp.append(i) ``` I have used the above code to find the duplicate elements in the `list_a`. I don't want to remove the elements from list. But I want to ...
Use the `in` operator instead of calling `__contains__` directly. What you have almost works (but is O(n\*\*2)): ``` for i in xrange(len(list_a)): for j in xrange(i + 1, len(list_a)): if list_a[i] == list_a[j]: print "duplicate:", list_a[i] ``` But it's far easier to use a set (roughly O(n) due to the ha...
How to find duplicate elements in array using for loop in Python?
1,920,145
17
2009-12-17T08:01:33Z
1,920,196
14
2009-12-17T08:14:26Z
[ "python", "duplicates" ]
I have a list with duplicate elements: ``` list_a=[1,2,3,5,6,7,5,2] tmp=[] for i in list_a: if tmp.__contains__(i): print i else: tmp.append(i) ``` I have used the above code to find the duplicate elements in the `list_a`. I don't want to remove the elements from list. But I want to ...
You could always use a list comprehension: ``` dups = [x for x in list_a if list_a.count(x) > 1] ```
How to find duplicate elements in array using for loop in Python?
1,920,145
17
2009-12-17T08:01:33Z
1,920,254
50
2009-12-17T08:36:46Z
[ "python", "duplicates" ]
I have a list with duplicate elements: ``` list_a=[1,2,3,5,6,7,5,2] tmp=[] for i in list_a: if tmp.__contains__(i): print i else: tmp.append(i) ``` I have used the above code to find the duplicate elements in the `list_a`. I don't want to remove the elements from list. But I want to ...
Just for information, In python 2.7+, we can use Counter ``` import collections x=[1, 2, 3, 5, 6, 7, 5, 2] >>> x [1, 2, 3, 5, 6, 7, 5, 2] >>> y=collections.Counter(x) >>> y Counter({2: 2, 5: 2, 1: 1, 3: 1, 6: 1, 7: 1}) ``` Unique List ``` >>> list(y) [1, 2, 3, 5, 6, 7] ``` Items found more than 1 time ``` >>> [...
How to find duplicate elements in array using for loop in Python?
1,920,145
17
2009-12-17T08:01:33Z
1,920,395
7
2009-12-17T09:10:26Z
[ "python", "duplicates" ]
I have a list with duplicate elements: ``` list_a=[1,2,3,5,6,7,5,2] tmp=[] for i in list_a: if tmp.__contains__(i): print i else: tmp.append(i) ``` I have used the above code to find the duplicate elements in the `list_a`. I don't want to remove the elements from list. But I want to ...
Before Python 2.3, use dict() : ``` >>> lst = [1, 2, 3, 5, 6, 7, 5, 2] >>> stats = {} >>> for x in lst : # count occurrences of each letter: ... stats[x] = stats.get(x, 0) + 1 >>> print stats {1: 1, 2: 2, 3: 1, 5: 2, 6: 1, 7: 1} # filter letters appearing more than once: >>> duplicates = [dup for (dup, i) in stat...
Python, Ruby, Haskell - Do they provide true multithreading?
1,920,805
16
2009-12-17T10:33:03Z
1,920,818
7
2009-12-17T10:35:12Z
[ "python", "ruby", "concurrency", "haskell", "multithreading" ]
We are planning to write a highly concurrent application in any of the Very-High Level programming languages. 1) Do Python, Ruby, or Haskell support true multithreading? 2) If a program contains threads, will a Virtual Machine automatically assign work to multiple cores (or to physical CPUs if there is more than 1 CP...
The current version of Ruby 1.9(YARV- C based version) has native threads but has the problem of GIL. As I know Python also has the problem of GIL. However both Jython and JRuby(mature Java implementations of both Ruby and Python) provide native multithreading, no green threads and no GIL. Don't know about Haskell.
Python, Ruby, Haskell - Do they provide true multithreading?
1,920,805
16
2009-12-17T10:33:03Z
1,920,979
16
2009-12-17T11:00:29Z
[ "python", "ruby", "concurrency", "haskell", "multithreading" ]
We are planning to write a highly concurrent application in any of the Very-High Level programming languages. 1) Do Python, Ruby, or Haskell support true multithreading? 2) If a program contains threads, will a Virtual Machine automatically assign work to multiple cores (or to physical CPUs if there is more than 1 CP...
The GHC compiler will run your program on multiple OS threads (and thus multiple cores) if you compile with the `-threaded` option and then pass `+RTS -N<x> -RTS` at runtime, where `<x>` = the number of OS threads you want.
Python, Ruby, Haskell - Do they provide true multithreading?
1,920,805
16
2009-12-17T10:33:03Z
1,921,825
32
2009-12-17T13:35:17Z
[ "python", "ruby", "concurrency", "haskell", "multithreading" ]
We are planning to write a highly concurrent application in any of the Very-High Level programming languages. 1) Do Python, Ruby, or Haskell support true multithreading? 2) If a program contains threads, will a Virtual Machine automatically assign work to multiple cores (or to physical CPUs if there is more than 1 CP...
> 1) Do Python, Ruby, or Haskell support true multithreading? This has nothing to do with the language. It is a question of the hardware (if the machine only has 1 CPU, it is simply physically impossible to execute two instructions at the same time), the Operating System (again, if the OS doesn't support true multithr...
Python, Ruby, Haskell - Do they provide true multithreading?
1,920,805
16
2009-12-17T10:33:03Z
1,925,211
22
2009-12-17T23:04:44Z
[ "python", "ruby", "concurrency", "haskell", "multithreading" ]
We are planning to write a highly concurrent application in any of the Very-High Level programming languages. 1) Do Python, Ruby, or Haskell support true multithreading? 2) If a program contains threads, will a Virtual Machine automatically assign work to multiple cores (or to physical CPUs if there is more than 1 CP...
The Haskell implementation, GHC, supports multiple mechanisms for parallel execution on shared memory multicore. These mechanisms are described in "[Runtime Support for Multicore Haskell](http://www.haskell.org/~simonmar/bib/multicore-ghc-09_abstract.html)". Concretely, the Haskell runtime divides work be N OS threads...
Python many-to-one mapping (creating equivalence classes)
1,921,027
9
2009-12-17T11:08:36Z
1,921,146
9
2009-12-17T11:32:48Z
[ "python", "many-to-one", "equivalence-classes" ]
I have a project of converting one database to another. One of the original database columns defines the row's category. This column should be mapped to a new category in the new database. For example, let's assume the original categories are:`parrot, spam, cheese_shop, Cleese, Gilliam, Palin` Now that's a little ver...
It seems to me that you have two concerns. First, how do you express your mapping originally, that is, how do you type the mapping into your new\_mapping.py file. Second, how does the mapping work during the re-mapping process. There's no reason for these two representations to be the same. Start with the mapping you ...
Python - Should one start a new project directly in Python 3.x?
1,921,742
5
2009-12-17T13:20:06Z
17,330,887
8
2013-06-26T21:36:18Z
[ "python" ]
What Python version can you please recommend for a long-term (years) project? Should one use 2.6+ or 3.x is already stable? (only standard libraries are required) UPDATE: according to the answers below, Python 3.x still has critical bugs. Please also see [Python's list of bugs](http://bugs.python.org/).
**This is why you should use Python 3.x:** Python 2.x: ``` >>>True = False >>>True False ``` Python 3.x: ``` >>> True = False File "<stdin>", line 1 SyntaxError: assignment to keyword ``` Source: [Strangest language feature](http://stackoverflow.com/a/2021553/562769) *Prejudice: But so many packages are not Pyt...
Grep and Python
1,921,894
33
2009-12-17T13:45:00Z
1,921,932
46
2009-12-17T13:51:26Z
[ "python", "grep" ]
I need a way of searching a file using grep via a regular expression 'RE' from the unix command line. For example when i type in the command line: > python pythonfile.py 'RE' > 'file-to-be-searched' I need the regualr expression 'RE' to be searched in the file and print out the lines that contain the RE. Ok so heres...
The natural question is why not just use grep?! But assuming you can't ... ``` import re import sys file = open(sys.argv[2], "r") for line in file: if re.search(sys.argv[1], line): print line, ``` Things to note: * `search` instead of `match` to find anywhere in string * comma `,` after `...
Parsing HTML in python - lxml or BeautifulSoup? Which of these is better for what kinds of purposes?
1,922,032
44
2009-12-17T14:08:59Z
1,922,064
23
2009-12-17T14:13:22Z
[ "python", "beautifulsoup", "html-parsing", "lxml" ]
From what I can make out, the two main HTML parsing libraries in Python are lxml and BeautifulSoup. I've chosen BeautifulSoup for a project I'm working on, but I chose it for no particular reason other than finding the syntax a bit easier to learn and understand. But I see a lot of people seem to favour lxml and I've h...
~~For starters, BeautifulSoup is no longer actively maintained, and [the author even recommends alternatives](http://www.crummy.com/software/BeautifulSoup/3.1-problems.html) such as lxml.~~ Quoting from the linked page: > Version 3.1.0 of Beautiful Soup does > significantly worse on real-world HTML > than version 3.0...
Parsing HTML in python - lxml or BeautifulSoup? Which of these is better for what kinds of purposes?
1,922,032
44
2009-12-17T14:08:59Z
1,922,130
10
2009-12-17T14:24:12Z
[ "python", "beautifulsoup", "html-parsing", "lxml" ]
From what I can make out, the two main HTML parsing libraries in Python are lxml and BeautifulSoup. I've chosen BeautifulSoup for a project I'm working on, but I chose it for no particular reason other than finding the syntax a bit easier to learn and understand. But I see a lot of people seem to favour lxml and I've h...
Don't use BeautifulSoup, use [lxml.soupparser](http://lxml.de/elementsoup.html) then you're sitting on top of the power of lxml and can use the good bits of BeautifulSoup which is to deal with really broken and crappy HTML.
Parsing HTML in python - lxml or BeautifulSoup? Which of these is better for what kinds of purposes?
1,922,032
44
2009-12-17T14:08:59Z
1,923,767
25
2009-12-17T18:48:09Z
[ "python", "beautifulsoup", "html-parsing", "lxml" ]
From what I can make out, the two main HTML parsing libraries in Python are lxml and BeautifulSoup. I've chosen BeautifulSoup for a project I'm working on, but I chose it for no particular reason other than finding the syntax a bit easier to learn and understand. But I see a lot of people seem to favour lxml and I've h...
`Pyquery` provides the jQuery selector interface to Python (using lxml under the hood). <http://pypi.python.org/pypi/pyquery> It's really awesome, I don't use anything else anymore.
Parsing HTML in python - lxml or BeautifulSoup? Which of these is better for what kinds of purposes?
1,922,032
44
2009-12-17T14:08:59Z
19,549,530
9
2013-10-23T18:25:30Z
[ "python", "beautifulsoup", "html-parsing", "lxml" ]
From what I can make out, the two main HTML parsing libraries in Python are lxml and BeautifulSoup. I've chosen BeautifulSoup for a project I'm working on, but I chose it for no particular reason other than finding the syntax a bit easier to learn and understand. But I see a lot of people seem to favour lxml and I've h...
In summary, `lxml` is positioned as a lightning-fast production-quality html and xml parser that, by the way, also includes a `soupparser` module to fall back on BeautifulSoup's functionality. `BeautifulSoup` is a one-person project, designed to save you time to quickly extract data out of poorly-formed html or xml. [...
Python: when to use pty.fork() versus os.fork()
1,922,254
13
2009-12-17T14:47:41Z
1,923,358
10
2009-12-17T17:36:24Z
[ "python", "linux", "fork", "kill", "pty" ]
I'm uncertain whether to use `pty.fork()` or `os.fork()` when spawning external background processes from my app. (Such as chess engines) I want the spawned processes to die if the parent is killed, as with spawning apps in a terminal. What are the ups and downs between the two forks?
The child process created with `os.fork()` inherits stdin/stdout/stderr from parent process, while the child created with `pty.fork()` is connected to new pseudo terminal. You need the later when you write a program like xterm: `pty.fork()` in parent process returns a descriptor to control terminal of child process, so...
Python: obtain & manipulate (as integers) bit patterns of floats
1,922,771
7
2009-12-17T16:02:13Z
1,922,829
8
2009-12-17T16:11:20Z
[ "python", "floating-point", "bit-manipulation" ]
In Python V.2.5.4, I have a float, and I'd like to obtain and manipulate (as an integer) the bit pattern of that float. For example, suppose I have ``` x = 173.3125 ``` In IEEE 754 format, x's bit pattern (in hexadecimal) is `432D5000` . How can I obtain & manipulate (e.g., perform bitwise operations) on that bit p...
The problem is that a Python float object might not be a IEEE 754, because it is an object (in fact they are, but internally they could hold whichever representation is more convenient)... As leo said, you can do a type cast with ctypes, so you are enforcing a particular representation (in this case, single precision)...
Python: obtain & manipulate (as integers) bit patterns of floats
1,922,771
7
2009-12-17T16:02:13Z
1,922,871
11
2009-12-17T16:17:41Z
[ "python", "floating-point", "bit-manipulation" ]
In Python V.2.5.4, I have a float, and I'd like to obtain and manipulate (as an integer) the bit pattern of that float. For example, suppose I have ``` x = 173.3125 ``` In IEEE 754 format, x's bit pattern (in hexadecimal) is `432D5000` . How can I obtain & manipulate (e.g., perform bitwise operations) on that bit p...
You can get the string you want (apparently implying a big-endian, 32-bit representation; Python internally uses the native endianity and 64-bits for floats) with the `struct` module: ``` >>> import struct >>> x = 173.125 >>> s = struct.pack('>f', x) >>> ''.join('%2.2x' % ord(c) for c in s) '432d2000' ``` this doesn'...
Convert string / character to integer in python
1,923,054
7
2009-12-17T16:46:29Z
1,923,076
13
2009-12-17T16:49:06Z
[ "python", "string", "encryption", "integer" ]
I want to convert a single character of a string into an integer, add 2 to it, and then convert it back to a string. Hence, A becomes C, K becomes M, etc.
This is done through the chr and ord functions. Eg; `chr(ord(ch)+2)` does what you want. These are fully described [here](http://docs.python.org/library/functions.html).
Convert string / character to integer in python
1,923,054
7
2009-12-17T16:46:29Z
1,923,085
11
2009-12-17T16:50:56Z
[ "python", "string", "encryption", "integer" ]
I want to convert a single character of a string into an integer, add 2 to it, and then convert it back to a string. Hence, A becomes C, K becomes M, etc.
This sounds a lot like homework, so I'll give you a couple of pieces and let you fill in the rest. To access a single character of string s, its s[x] where x is an integer index. Indices start at 0. To get the integer value of a character it is ord(c) where c is the character. To cast an integer back to a character i...
monolithic inheritance vs modular member based OOP design
1,923,101
3
2009-12-17T16:52:56Z
1,923,175
7
2009-12-17T17:05:59Z
[ "python", "oop" ]
I'm having a hard time making a design decision I have a class in python, that processing form data, this data is very similar to other form data, and so I'm refactoring it into it's own object so it can be reused by the other classes. The delima is weather to make this formprocessor a member of the classes or a pare...
Definitely go for the modular approach. Some of the advantages of taking the modular approach are: * It makes your code more readable, i.e. it's more clear what the PageHandler and FormProcessor do * It makes it easier and more effective to write [unit tests](http://en.wikipedia.org/wiki/Unit%5Ftesting) on both of you...
Multiprocessing launching too many instances of Python VM
1,923,706
12
2009-12-17T18:37:24Z
1,924,559
19
2009-12-17T21:00:01Z
[ "python", "windows", "multiprocessing" ]
I am writing some multiprocessing code (Python 2.6.4, WinXP) that spawns processes to run background tasks. In playing around with some trivial examples, I am running into an issue where my code just continuously spawns new processes, even though I only tell it to spawn a fixed number. The program itself runs fine, bu...
It looks like you didn't carefully follow the guidelines in the documentation, specifically [this section](http://docs.python.org/library/multiprocessing.html#windows) where it talks about "Safe importing of main module". You need to protect your launch code with an `if __name__ == '__main__':` block or you'll get wha...
Python lambdas and scoping
1,924,214
6
2009-12-17T20:02:49Z
1,924,275
7
2009-12-17T20:12:57Z
[ "python", "lambda" ]
Given this snippet of code: ``` funcs = [] for x in range(3): funcs.append(lambda: x) print [f() for f in funcs] ``` I would expect it to print `[0, 1, 2]`, but instead it prints `[2, 2, 2]`. Is there something fundamental I'm missing about how lambdas work with scope?
This is a frequent question in Python. Basically the scoping is such that when `f()` is called, it will use the current value of `x`, not the value of `x` at the time the lambda is formed. There is a standard workaround: ``` funcs = [] for x in range(10): funcs.append(lambda x=x: x) print [f() for f in funcs] ``` The...
Use <optgroup> with form.fields.queryset?
1,924,704
5
2009-12-17T21:25:27Z
1,925,072
10
2009-12-17T22:33:59Z
[ "python", "django", "django-forms", "django-queryset" ]
Is it possible to set a form's ForeignKey field's queryset so that it will take separate queryset's and output them in `<optgroup>`'s? Here is what I have: views.py ``` form = TemplateFormBasic(initial={'template': digest.template.id}) form.fields['template'].queryset = Template.objects.filter(Q(default=1) | Q(user=...
I was able to figure it out using the example given on [this blog](http://dealingit.wordpress.com/2009/10/26/django-tip-showing-optgroup-in-a-modelform/) views.py ``` form.fields['template'].choices = templates_as_choices(request) def templates_as_choices(request): templates = [] default = [] user = [] ...
PyQt: Always on top
1,925,015
15
2009-12-17T22:22:15Z
1,925,061
22
2009-12-17T22:32:19Z
[ "python", "pyqt" ]
This is on PyQt4, Linux and Python 2.5 Can I make PyQt set my window "always on top" over other applications? For example, in GTK i use the property: Modal. Now, in PyQt I am using a QWidget, but, I can't find a way to do that. Any ideas??
Pass the QMainWindow the `WindowStaysOnTopHint` [window flag](http://doc.qt.io/qt-5/qt.html#WindowType-enum) (or use setWindowFlags). As in the name, this is a hint to the windowing manager (not a hard guarantee). Simplest possible example: ``` import sys from PyQt4 import QtGui, QtCore class mymainwindow(QtGui.QMa...
httplib CannotSendRequest error in WSGI
1,925,639
13
2009-12-18T00:58:42Z
1,927,317
22
2009-12-18T10:00:26Z
[ "python", "twitter", "oauth", "wsgi", "httplib" ]
I've used two different python oauth libraries with Django to authenticate with twitter. The setup is on apache with WSGI. When I restart the server everything works great for about 10 minutes and then the httplib seems to lock up (see the following error). I'm running only 1 process and 1 thread of WSGI but that seem...
This exception is raised when you reuse `httplib.HTTP` object for new request while you havn't called its `getresponse()` method for previous request. Probably there was some other error before this one that left connection in broken state. The simplest reliable way to fix the problem is creating new connection for eac...
Eclipse (with Pydev) keeps throwing SyntaxError
1,925,852
13
2009-12-18T02:07:04Z
1,925,868
34
2009-12-18T02:12:43Z
[ "python", "eclipse", "syntax", "pydev" ]
My code: `print "Hello World!"` I even tried adding a semicolon behind, but everytime I save and run (as Python run) it says: > File "E:\Software\Eclipse\Workspace\Python1\src\main.py", line 1 > print "Hello World!"; > > SyntaxError: invalid syntax I have no idea why.
What version of Python are you using? Python 2.X has `print` as a keyword, but Python 3.X only has `print()` as a function - you'd need to use `print("Hello, World!")` instead.
Django Unhandled Exception
1,925,898
9
2009-12-18T02:24:23Z
4,585,251
9
2011-01-03T14:27:28Z
[ "python", "django" ]
It is running under DEBUG = True mode. Sometimes it can throw out an error message with traceback information when encounter an error but sometimes it just display the following lines: ``` Unhandled Exception An unhandled exception was thrown by the application. ``` I have to switch to development server to see deta...
Just connect to the got\_request\_exception signal and log the exception: ``` from django.core.signals import got_request_exception import logging def log(*args, **kwargs): logging.exception('error') got_request_exception.connect(log) ``` This will log the whole trace. In the dev server, it logs in the cons...
what is blocking and non-blocking web server, what difference between both?
1,926,602
19
2009-12-18T06:07:58Z
1,926,631
28
2009-12-18T06:16:05Z
[ "python", "webserver" ]
i have seen many web framework provide non-blocking web server, i just want to know what it mean.
Using a **blocking** socket, execution will wait (ie. "block") until the full socket operation has taken place. So, you can process any results/responses in your code immediately after. These are also called *synchronous* sockets. A **non-blocking** socket operation will allow execution to resume immediately and you c...
what is blocking and non-blocking web server, what difference between both?
1,926,602
19
2009-12-18T06:07:58Z
5,670,665
49
2011-04-14T22:58:00Z
[ "python", "webserver" ]
i have seen many web framework provide non-blocking web server, i just want to know what it mean.
a blocking web-server is similar to a phone call. you need to wait on-line to get a response and continue; where as a non-blocking web-server is like a sms service. you sms your request,do your things and react when you receive an sms back!
"For" loop first iteration
1,927,544
33
2009-12-18T11:03:26Z
1,927,564
41
2009-12-18T11:07:38Z
[ "python", "algorithm", "iteration" ]
Greetings pyc-sires and py-ladies, I would like to inquire if there is an elegant pythonic way of executing some function on the first loop iteration. The only possibility I can think of is: ``` first = True for member in something.get(): if first: root.copy(member) first = False else: ...
Something like this should work. ``` for i, member in enumerate(something.get()): if i == 0: # Do thing # Code for everything ``` However, I would strongly recommend thinking about your code to see if you really have to do it this way, because it's sort of "dirty". Better would be to fetch the elemen...
"For" loop first iteration
1,927,544
33
2009-12-18T11:03:26Z
1,927,575
22
2009-12-18T11:09:46Z
[ "python", "algorithm", "iteration" ]
Greetings pyc-sires and py-ladies, I would like to inquire if there is an elegant pythonic way of executing some function on the first loop iteration. The only possibility I can think of is: ``` first = True for member in something.get(): if first: root.copy(member) first = False else: ...
You have several choices for the **Head-Tail** design pattern. ``` seq= something.get() root.copy( seq[0] ) foo( seq[0] ) for member in seq[1:]: somewhereElse.copy(member) foo( member ) ``` Or this ``` seq_iter= iter( something.get() ) head = seq_iter.next() root.copy( head ) foo( head ) for member in seq_it...
"For" loop first iteration
1,927,544
33
2009-12-18T11:03:26Z
1,935,799
7
2009-12-20T13:06:22Z
[ "python", "algorithm", "iteration" ]
Greetings pyc-sires and py-ladies, I would like to inquire if there is an elegant pythonic way of executing some function on the first loop iteration. The only possibility I can think of is: ``` first = True for member in something.get(): if first: root.copy(member) first = False else: ...
how about: ``` my_array = something.get() for member in my_array: if my_array.index(member) == 0: root.copy(member) else: somewhereElse.copy(member) foo(member) ``` or maybe: ``` for index, member in enumerate(something.get()): if index == 0: root.copy(member) else: ...
Compare two images the python/linux way
1,927,660
31
2009-12-18T11:27:38Z
1,927,681
22
2009-12-18T11:32:36Z
[ "python", "linux", "image" ]
Trying to solve a problem of preventing duplicate images to be uploaded. I have two JPGs. Looking at them I can see that they are in fact identical. But for some reason they have different file size (one is pulled from a backup, the other is another upload) and so they have a different md5 checksum. How can I efficie...
There is a OSS project that uses WebDriver to take screen shots and then compares the images to see if there are any issues ([http://code.google.com/p/fighting-layout-bugs/)](http://code.google.com/p/fighting-layout-bugs/)). It does it by openning the file into a stream and then comparing every bit. You may be able to...
Compare two images the python/linux way
1,927,660
31
2009-12-18T11:27:38Z
1,927,689
11
2009-12-18T11:34:01Z
[ "python", "linux", "image" ]
Trying to solve a problem of preventing duplicate images to be uploaded. I have two JPGs. Looking at them I can see that they are in fact identical. But for some reason they have different file size (one is pulled from a backup, the other is another upload) and so they have a different md5 checksum. How can I efficie...
I guess you should decode the images and do a pixel by pixel comparison to see if they're reasonably similar. With PIL and Numpy you can do it quite easily: ``` import Image import numpy import sys def main(): img1 = Image.open(sys.argv[1]) img2 = Image.open(sys.argv[2]) if img1.size != img2.size or img...
Compare two images the python/linux way
1,927,660
31
2009-12-18T11:27:38Z
6,204,954
14
2011-06-01T17:01:50Z
[ "python", "linux", "image" ]
Trying to solve a problem of preventing duplicate images to be uploaded. I have two JPGs. Looking at them I can see that they are in fact identical. But for some reason they have different file size (one is pulled from a backup, the other is another upload) and so they have a different md5 checksum. How can I efficie...
From [here](http://effbot.org/zone/pil-comparing-images.htm) The quickest way to determine if two images have exactly the same contents is to get the difference between the two images, and then calculate the bounding box of the non-zero regions in this image. If the images are identical, all pixels in the difference i...
Compare two images the python/linux way
1,927,660
31
2009-12-18T11:27:38Z
9,698,890
10
2012-03-14T09:16:09Z
[ "python", "linux", "image" ]
Trying to solve a problem of preventing duplicate images to be uploaded. I have two JPGs. Looking at them I can see that they are in fact identical. But for some reason they have different file size (one is pulled from a backup, the other is another upload) and so they have a different md5 checksum. How can I efficie...
Using ImageMagick, you can simply use in your shell [or call via the OS library from within a program] ``` compare image1 image2 output ``` This will create an output image with the differences marked ``` compare -metric AE -fuzz 5% image1 image2 output ``` Will give you a fuzziness factor of 5% to ignore minor pix...
Nested dot lookups in Django templates
1,929,109
5
2009-12-18T16:07:35Z
1,929,161
8
2009-12-18T16:14:25Z
[ "python", "django", "django-templates" ]
According to [The Django Book](http://www.djangobook.com/en/beta/chapter04/), Django's templating system supports nested dot lookups: > Dot lookups can be nested multiple levels deep. For instance, the following example uses {{ person.name.upper }}, which translates into a dictionary lookup (person['name']), then a me...
I think the problem is that you are expecting `ndx` to be evaluated when that simply never happens. Have you tried this: ``` {{ test.0.bar }} ``` I think that will do what you're looking for. > Are there goblins with this approach...? Sort of, but they aren't the ones you're talking about, and I don't think it's be...
In Python, use "dict" with keywords or anonymous dictionaries?
1,929,274
5
2009-12-18T16:26:56Z
1,929,304
13
2009-12-18T16:32:09Z
[ "python" ]
Say you want to pass a dictionary of values to a function, or otherwise want to work with a short-lived dictionary that won't be reused. There are two easy ways to do this: Use the `dict()` function to create a dictionary: ``` foo.update(dict(bar=42, baz='qux')) ``` Use an anonymous dictionary: ``` foo.update({'bar...
I prefer the anonymous dict option. I don't like the `dict()` option for the same reason I don't like: ``` i = int("1") ``` With the `dict()` option you're needlessly calling a function which is adding overhead you don't need: ``` >>> from timeit import Timer >>> Timer("mydict = {'a' : 1, 'b' : 2, 'c' : 'three'}")...
Django Admin: not seeing any app (permission problem?)
1,929,707
5
2009-12-18T17:45:02Z
1,930,130
11
2009-12-18T19:10:00Z
[ "python", "django", "permissions", "django-admin" ]
I have a site with Django running some custom apps. I was not using the Django ORM, just the view and templates but now I need to store some info so I created some models in one app and enabled the Admin. The problem is when I log in the Admin it just says "You don't have permission to edit anything", not even the Aut...
It sounds like you haven't registered any apps with the admin (step 5 in [this overview](http://docs.djangoproject.com/en/dev/ref/contrib/admin/#overview)). Try adding the line `admin.autodiscover()` to your main urls.py, making sure to do `from django.contrib import admin` first. For example: ``` # Other imports......
Django Admin: not seeing any app (permission problem?)
1,929,707
5
2009-12-18T17:45:02Z
7,021,995
18
2011-08-11T06:58:21Z
[ "python", "django", "permissions", "django-admin" ]
I have a site with Django running some custom apps. I was not using the Django ORM, just the view and templates but now I need to store some info so I created some models in one app and enabled the Admin. The problem is when I log in the Admin it just says "You don't have permission to edit anything", not even the Aut...
Hopefully this helps someone, but we had this same problem because someone added a different authentication backend to settings.py and did not keep the default ModelBackend. Changing the setting to: ``` AUTHENTICATION_BACKENDS = ( 'auth.authentication.EmailBackend', 'django.contrib.auth.backends.ModelBackend',...
PyTables problem - different results when iterating over subset of table
1,929,973
3
2009-12-18T18:38:36Z
1,931,993
7
2009-12-19T04:46:40Z
[ "python", "numpy", "pytables" ]
I am new to PyTables, and am looking at using it to process data generated from an agent-based modeling simulation and stored in HDF5. I'm working with a 39 MB test file, and am experiencing some strangeness. Here's the layout of the table: ``` /example/agt_coords (Table(2000000,)) '' description := { "agent":...
This is a very common point of confusion when iterating over `Table` object, When you iterate over a `Table` the type of item you get is not the data at the item, but an accessor to the table at the current row. So with ``` [x for x in coords if x['agent'] == 1] ``` you create a list of row accessors that all point ...
Is there a clever way to get the previous/next item using the Django ORM?
1,931,008
20
2009-12-18T22:18:49Z
1,931,065
31
2009-12-18T22:30:38Z
[ "python", "django", "django-models" ]
Say I have a list of photos ordered by creation date, as follows: ``` class Photo(models.Model): title = models.Char() image = models.Image() created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-created',) ``` I have an arbitrary Photo object photo\_x. Is there an easy ...
You're in luck! Django creates `get_next_by_foo` and `get_previous_by_foo` methods by default for `DateField` & `DateTimeField` as long as they do not have `null=True`. For example: ``` >>> from foo.models import Request >>> r = Request.objects.get(id=1) >>> r.get_next_by_created() <Request: xyz246> ``` And if you r...
How to parse somewhat wrong JSON with Python?
1,931,454
15
2009-12-19T00:25:08Z
1,931,531
19
2009-12-19T00:48:21Z
[ "python", "json", "google-app-engine" ]
I have a following JSON string coming from external input source: ``` {value: "82363549923gnyh49c9djl239pjm01223", id: 17893} ``` This is wrong-formatted JSON string ("id" and "value" must be in quotes), but I need to parse it anyway. I have tried simplejson and json-py and seems they could not be set up to parse suc...
since YAML (>=1.2) is a superset of JSON, you can do: ``` >>> import yaml >>> s = '{value: "82363549923gnyh49c9djl239pjm01223", id: 17893}' >>> yaml.load(s) {'id': 17893, 'value': '82363549923gnyh49c9djl239pjm01223'} ```
Python Datatype for a fixed-length FIFO
1,931,589
14
2009-12-19T01:14:10Z
1,931,603
26
2009-12-19T01:20:54Z
[ "python" ]
I would like to know if there is a native datatype in Python that acts like a fixed-length FIFO buffer. For example, I want do create a length-5 FIFO buffer that is initialized with all zeros. Then, it might look like this: [0,0,0,0,0] Then, when I call the put function on the object, it will shift off the last zero ...
``` x = collections.deque(5*[0], 5) ``` See [the docs](http://docs.python.org/library/collections.html?highlight=collections.deque#collections.deque) for more about `collections.deque`; the method you call `push` is actually called `appendleft` in that type. The second parameter (`maxlen`, giving the maximum lengths)...
Can't get MySQL source query to work using Python mysqldb module
1,932,298
5
2009-12-19T07:52:15Z
1,932,332
7
2009-12-19T08:07:37Z
[ "python", "mysql", "scripting" ]
I have the following lines of code: ``` sql = "source C:\\My Dropbox\\workspace\\projects\\hosted_inv\\create_site_db.sql" cursor.execute (sql) ``` When I execute my program, I get the following error: > Error 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version ...
The `source` command is one of the [built-in commands](http://dev.mysql.com/doc/refman/5.1/en/mysql-commands.html) recognized only by the mysql command-line client. It is not supported as a statement you can execute via any API. Some people think you can simply split an SQL script file on the "`;`" statement terminato...
Can't get MySQL source query to work using Python mysqldb module
1,932,298
5
2009-12-19T07:52:15Z
1,932,358
9
2009-12-19T08:27:17Z
[ "python", "mysql", "scripting" ]
I have the following lines of code: ``` sql = "source C:\\My Dropbox\\workspace\\projects\\hosted_inv\\create_site_db.sql" cursor.execute (sql) ``` When I execute my program, I get the following error: > Error 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version ...
As others said, you cannot use the command `source` in MySQLdb Python API So, instead of running that, load the file and execute it Lets say your .sql file has ``` create database test; ``` Read the content like ``` sql=open("test.sql").read() ``` And then execute it ``` cursor.execute(sql); ``` You will get ne...
remove numbers from a list without changing total sum
1,932,657
7
2009-12-19T11:22:00Z
1,932,687
11
2009-12-19T11:36:01Z
[ "python", "math", "sum", "combinations", "mathematical-optimization" ]
I have a list of numbers (example: `[-1, 1, -4, 5]`) and I have to remove numbers from the list without changing the total sum of the list. I want to remove the numbers with biggest absolute value possible, without changing the total, in the example removing `[-1, -4, 5]` will leave `[1]` so the sum doesn't change. I ...
if you redefine the problem as finding a subset whose sum equals the value of the complete set, you will realize that this is a NP-Hard problem, ([subset sum](http://en.wikipedia.org/wiki/Subset%5Fsum%5Fproblem)) so there is no polynomial complexity solution for this problem .
How do you listen to notifications from iTunes on a Mac (Using the NSDistributedNotificationCenter)
1,933,107
4
2009-12-19T14:59:38Z
1,936,674
10
2009-12-20T19:16:47Z
[ "python", "osx", "notifications", "pyobjc" ]
Looking for help/tutorials/sample code of using python to listen to [distributed notifications](http://developer.apple.com/mac/library/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSDistributedNotificationCenter%5FClass/Reference/Reference.html#//apple%5Fref/doc/uid/20000396-2831) from applications on a mac. I know...
If anyone comes by to this question, i figured out how to listen, the code below works. However accessing attributes do not seem to work like standard python attribute access. Update: you do not access attributes as you would in python i.e (.x), the code has been updated below, it now generates a dict called song\_det...
make python replace un-encodable chars with a string by default
1,933,184
6
2009-12-19T15:28:16Z
1,933,219
11
2009-12-19T15:39:20Z
[ "python", "replace", "encode" ]
I want to make python ignore chars it can't encode, by simply replacing them with the string `"<could not encode>"`. E.g, assuming the default encoding is ascii, the command ``` '%s is the word'%'ébác' ``` would yield ``` '<could not encode>b<could not encode>c is the word' ``` Is there any way to make this the ...
The [`str.encode`](http://docs.python.org/library/stdtypes.html#str.encode) function takes an optional argument defining the error handling: ``` str.encode([encoding[, errors]]) ``` From the docs: > Return an encoded version of the string. Default encoding is the current default string encoding. errors may be given ...
Python - specify which function in file to use on command line
1,933,400
2
2009-12-19T16:45:29Z
1,933,407
10
2009-12-19T16:47:32Z
[ "python", "command-line", "function" ]
Assume you have a programme with multiple functions defined. Each function is called in a separate for loop. Is it possible to specify which function should be called via the command line? Example: ``` python prog.py -x <<<filname>>> ``` Where -x tells python to go to a particular for loop and then execute the funct...
The Python idiom for the main entry point: ``` if __name__ == '__main__': main() ``` Replace `main()` by whatever function should go first ... (more on `if name ...`: <http://effbot.org/pyfaq/tutor-what-is-if-name-main-for.htm>) If you want to specify the function to run via command line argument, just check the...
Why should exec() and eval() be avoided?
1,933,451
18
2009-12-19T16:58:08Z
1,933,481
14
2009-12-19T17:04:00Z
[ "python" ]
I've seen this multiple times in multiple places, but never have found a satisfying explanation as to why this should be the case. So, hopefully, one will be presented here. Why should we (at least, generally) not use `exec()` and `eval()`? EDIT: I see that people are assuming that this question pertains to web serve...
There are often clearer, more direct ways to get the same effect. If you build a complex string and pass it to exec, the code is difficult to follow, and difficult to test. Example: I wrote code that read in string keys and values and set corresponding fields in an object. It looked like this: ``` for key, val in val...
Why should exec() and eval() be avoided?
1,933,451
18
2009-12-19T16:58:08Z
1,933,525
8
2009-12-19T17:14:30Z
[ "python" ]
I've seen this multiple times in multiple places, but never have found a satisfying explanation as to why this should be the case. So, hopefully, one will be presented here. Why should we (at least, generally) not use `exec()` and `eval()`? EDIT: I see that people are assuming that this question pertains to web serve...
Security aside, `eval` and `exec` are often marked as undesirable because of the complexity they induce. When you see a `eval` call you often don't know what's really going on behind it, because it acts on data that's usually in a variable. This makes code harder to read. Invoking the full power of the interpreter is ...
Why should exec() and eval() be avoided?
1,933,451
18
2009-12-19T16:58:08Z
1,933,555
7
2009-12-19T17:22:19Z
[ "python" ]
I've seen this multiple times in multiple places, but never have found a satisfying explanation as to why this should be the case. So, hopefully, one will be presented here. Why should we (at least, generally) not use `exec()` and `eval()`? EDIT: I see that people are assuming that this question pertains to web serve...
eval() and exec() can promote lazy programming. More importantly it indicates the code being executed may not have been written at design time therefore not tested. In other words, how do you test dynamically generated code? Especially across browsers.
Why should exec() and eval() be avoided?
1,933,451
18
2009-12-19T16:58:08Z
1,933,723
7
2009-12-19T18:20:30Z
[ "python" ]
I've seen this multiple times in multiple places, but never have found a satisfying explanation as to why this should be the case. So, hopefully, one will be presented here. Why should we (at least, generally) not use `exec()` and `eval()`? EDIT: I see that people are assuming that this question pertains to web serve...
When you need exec and eval, yeah, you really do need them. But, the majority of the in-the-wild usage of these functions (and the similar constructs in other scripting languages) is totally inappropriate and could be replaced with other simpler constructs that are faster, more secure and have fewer bugs. You *can*, ...
Why should exec() and eval() be avoided?
1,933,451
18
2009-12-19T16:58:08Z
1,934,554
7
2009-12-20T00:22:00Z
[ "python" ]
I've seen this multiple times in multiple places, but never have found a satisfying explanation as to why this should be the case. So, hopefully, one will be presented here. Why should we (at least, generally) not use `exec()` and `eval()`? EDIT: I see that people are assuming that this question pertains to web serve...
In contrast to what most answers are saying here, exec is actually part of the recipe for building super-complete decorators in Python, as you can duplicate everything about the decorated function exactly, producing the same signature for the purposes of documentation and such. It's key to the functionality of the wide...
How do you clone a class in Python?
1,933,784
6
2009-12-19T18:45:46Z
1,933,811
13
2009-12-19T18:52:37Z
[ "python" ]
I have a class A and i want a class B with exactly the same capabilities. I cannot or do not want to inherit from B, such as doing class B(A):pass Still i want B to be identical to A, yet have a different i: id(A) != id(B) Watch out, i am not talking about instances but classes to be cloned.
I'm pretty sure whatever you are trying to do can be solved in a better way, but here is something that gives you a clone of the class with a new id: ``` def c(): class Clone(object): pass return Clone c1 = c() c2 = c() print id(c1) print id(c2) ``` gives: ``` 4303713312 4303831072 ```
A pythonic way how to find if a value is between two values in a list
1,933,919
7
2009-12-19T19:33:03Z
1,933,932
20
2009-12-19T19:36:56Z
[ "list", "grid", "range", "python", "snapping" ]
Having a sorted list and some random value, I would like to find in which range the value is. List goes like this: [0, 5, 10, 15, 20] And value is, say 8. The standard way would be to either go from start until we hit value that is bigger than ours (like in the example below), or to perform [binary search](http://en....
``` >>> import bisect >>> grid = [0, 5, 10, 15, 20] >>> value = 8 >>> bisect.bisect(grid, value) 2 ``` Edit: [bisect — Array bisection algorithm](http://docs.python.org/library/bisect.html)
Rotating Proxies for web scraping
1,934,088
8
2009-12-19T20:46:21Z
8,612,054
11
2011-12-23T03:46:07Z
[ "python", "proxy", "screen-scraping", "web-crawler", "squid" ]
I've got a python web crawler and I want to distribute the download requests among many different proxy servers, probably running squid (though I'm open to alternatives). For example, it could work in a round-robin fashion, where request1 goes to proxy1, request2 to proxy2, and eventually looping back around. Any idea ...
I've setted up rotating proxies using HAProxy + DeleGate + Multiple Tor Instances. With Tor you don't have good control of bandwidth and latency but it's useful for web scraping. I've just published an article on the subject: [Running Your Own Anonymous Rotating Proxies](http://blog.databigbang.com/running-your-own-ano...
Item assignment on bytes object in Python
1,934,624
2
2009-12-20T01:16:16Z
1,934,649
10
2009-12-20T01:39:59Z
[ "python", "python-3.x" ]
GAHH, code not working is bad code indeed! > in RemoveRETNs > toOutput[currentLoc - 0x00400000] = b'\xCC' TypeError: 'bytes' object does not support item assignment How can I fix this: ``` inputFile = 'original.exe' outputFile = 'output.txt' patchedFile = 'original_patched.exe' def GetFileContents(filename): f ...
Change the `return` statement of `GetFileContents` into ``` return bytearray(fileContents) ``` and the rest should work. You need to use `bytearray` rather than `bytes` simply because the former is read/write, the latter (which is what you're using now) is read-only.
How to execute Python scripts in Windows?
1,934,675
70
2009-12-20T02:09:25Z
1,934,695
20
2009-12-20T02:32:28Z
[ "python", "windows", "scripting", "command-line", "file-association" ]
I have a simple script blah.py (using Python 2): ``` import sys print sys.argv[1] ``` If I execute my script by: ``` python c:/..../blah.py argument ``` It prints argument but if I execute script by: ``` blah.py argument ``` error occurs: > IndexError... So arguments do not pass to script. python.exe in PATH. ...
you should make the default application to handle python files be python.exe. right click a \*.py file, select "Open With" dialog. In there select "python.exe" and check "always use this program for this file type" (something like that). then your python files will always be run using python.exe
How to execute Python scripts in Windows?
1,934,675
70
2009-12-20T02:09:25Z
1,936,078
113
2009-12-20T15:05:41Z
[ "python", "windows", "scripting", "command-line", "file-association" ]
I have a simple script blah.py (using Python 2): ``` import sys print sys.argv[1] ``` If I execute my script by: ``` python c:/..../blah.py argument ``` It prints argument but if I execute script by: ``` blah.py argument ``` error occurs: > IndexError... So arguments do not pass to script. python.exe in PATH. ...
When you execute a script without typing "python" in front, you need to know two things about how Windows invokes the program. First is to find out what kind of file Windows thinks it is: ``` C:\>assoc .py .py=Python.File ``` Next, you need to know how Windows is executing things with that extension. It's ass...
How to execute Python scripts in Windows?
1,934,675
70
2009-12-20T02:09:25Z
13,023,969
10
2012-10-23T05:15:37Z
[ "python", "windows", "scripting", "command-line", "file-association" ]
I have a simple script blah.py (using Python 2): ``` import sys print sys.argv[1] ``` If I execute my script by: ``` python c:/..../blah.py argument ``` It prints argument but if I execute script by: ``` blah.py argument ``` error occurs: > IndexError... So arguments do not pass to script. python.exe in PATH. ...
Additionally, if you want to be able to run your python scripts without typing the `.py` (or `.pyw`) on the end of the file name, you need to add `.PY` (or `.PY;.PYW`) to the list of extensions in the PATHEXT environment variable. In Windows 7: right-click on Computer left-click Properties left-click Advanced sys...
Why use Django on Google App Engine?
1,934,914
78
2009-12-20T05:03:45Z
1,934,925
48
2009-12-20T05:17:02Z
[ "python", "django", "google-app-engine" ]
When researching Google App Engine (GAE), it's clear that using Django is wildly popular for developing in Python on GAE. I've been scouring the web to find information on the costs and benefits of using Django, to find out *why* it's so popular. While I've been able to find a wide variety of sources on *how* to run Dj...
Django probably isn't the right choice for you, if you're sure that GAE is right for you. The strengths of the two technologies don't align very well - you completely lose a lot of Django's wonderful orm on GAE, and if you do use it, you write code that isn't really directly suitable to bigtable and the way GAE works. ...
Why use Django on Google App Engine?
1,934,914
78
2009-12-20T05:03:45Z
1,934,951
15
2009-12-20T05:31:57Z
[ "python", "django", "google-app-engine" ]
When researching Google App Engine (GAE), it's clear that using Django is wildly popular for developing in Python on GAE. I've been scouring the web to find information on the costs and benefits of using Django, to find out *why* it's so popular. While I've been able to find a wide variety of sources on *how* to run Dj...
I've done lots of projects on GAE. Some in django, some in their normal framework. For small things, I usually use their normal framework for simplicity and quickness. Like <http://stdicon.com>, <http://yaml-online-parser.appspot.com/>, or <http://text-twist.appspot.com/>. For large things, I go with django to take a...
Why use Django on Google App Engine?
1,934,914
78
2009-12-20T05:03:45Z
1,935,686
18
2009-12-20T12:26:29Z
[ "python", "django", "google-app-engine" ]
When researching Google App Engine (GAE), it's clear that using Django is wildly popular for developing in Python on GAE. I've been scouring the web to find information on the costs and benefits of using Django, to find out *why* it's so popular. While I've been able to find a wide variety of sources on *how* to run Dj...
We use django on our appengine instances mostly when we have to serve actual websites to the user. It has a great template engine, url routing and all the request/response/error handling built in. So even while we can't use the magic orm/admin stuff it has a lot going for it. For api services we built something very s...
Why use Django on Google App Engine?
1,934,914
78
2009-12-20T05:03:45Z
28,627,569
8
2015-02-20T11:10:12Z
[ "python", "django", "google-app-engine" ]
When researching Google App Engine (GAE), it's clear that using Django is wildly popular for developing in Python on GAE. I've been scouring the web to find information on the costs and benefits of using Django, to find out *why* it's so popular. While I've been able to find a wide variety of sources on *how* to run Dj...
I think all this answers are a bit obsolete. Now you can use `Google Cloud SQL` > Django is a popular third-party Python web framework. **When coupled > with Google Cloud SQL, all of its functionality can be *fully* supported > by applications running on App Engine**. Support for using Google Cloud > SQL with Django ...