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
Can Python's list comprehensions (ideally) do the equivalent of 'count(*)...group by...' in SQL?
2,148,480
4
2010-01-27T16:18:18Z
2,148,531
10
2010-01-27T16:25:17Z
[ "python", "list", "count", "python-2.6" ]
I think list comprehensions may give me this, but I'm not sure: any elegant solutions in Python (2.6) in general for selecting unique objects in a list and providing a count? (I've defined an `__eq__` to define uniqueness on my object definition). So in RDBMS-land, something like this: ``` CREATE TABLE x(n NUMBER(1)...
[Lennart Regebro provided a nice one-liner](http://stackoverflow.com/questions/2134416/pyparsing-where-order-of-tokens-in-unpredictable/2134640#2134640) that does what you want: ``` >>> values = [1,1,1,2] >>> print [(x,values.count(x)) for x in set(values)] [(1, 3), (2, 1)] ``` [As S.Lott mentions](http://stackoverfl...
Can Python's list comprehensions (ideally) do the equivalent of 'count(*)...group by...' in SQL?
2,148,480
4
2010-01-27T16:18:18Z
2,148,555
11
2010-01-27T16:28:14Z
[ "python", "list", "count", "python-2.6" ]
I think list comprehensions may give me this, but I'm not sure: any elegant solutions in Python (2.6) in general for selecting unique objects in a list and providing a count? (I've defined an `__eq__` to define uniqueness on my object definition). So in RDBMS-land, something like this: ``` CREATE TABLE x(n NUMBER(1)...
``` >>> from collections import Counter >>> Counter([1,1,1,2]) Counter({1: 3, 2: 1}) ``` [Counter](http://docs.python.org/3.1/library/collections.html#collections.Counter) only available in py3.1, inherits from the `dict`.
scrape html generated by javascript with python
2,148,493
16
2010-01-27T16:20:22Z
5,272,521
10
2011-03-11T11:49:34Z
[ "javascript", "python", "browser", "screen-scraping" ]
I need to scrape a site with python. I obtain the source html code with the urlib module, but I need to scrape also some html code that is generated by a javascript function (which is included in the html source). What this functions does "in" the site is that when you press a button it outputs some html code. How can ...
In Python, I think [Selenium 1.0](http://seleniumhq.org/projects/remote-control/) is the way to go. It’s a library that allows you to control a real web browser from your language of choice. You need to have the web browser in question installed on the machine your script runs on, but it looks like the most reliable...
How to write a confusion matrix in Python?
2,148,543
11
2010-01-27T16:27:19Z
14,271,799
10
2013-01-11T04:41:36Z
[ "python", "machine-learning" ]
I wrote a confusion matrix calculation code in Python: ``` def conf_mat(prob_arr, input_arr): # confusion matrix conf_arr = [[0, 0], [0, 0]] for i in range(len(prob_arr)): if int(input_arr[i]) == 1: if float(prob_arr[i]) < 0.5: ...
[Scikit-learn](http://scikit-learn.org/stable/) (which I recommend using anyways) has it included in the `metrics` module: ``` >>> from sklearn.metrics import confusion_matrix >>> y_true = [0, 1, 2, 0, 1, 2, 0, 1, 2] >>> y_pred = [0, 0, 0, 0, 1, 1, 0, 2, 2] >>> confusion_matrix(y_true, y_pred) array([[3, 0, 0], ...
How to write a confusion matrix in Python?
2,148,543
11
2010-01-27T16:27:19Z
29,877,565
21
2015-04-26T12:22:11Z
[ "python", "machine-learning" ]
I wrote a confusion matrix calculation code in Python: ``` def conf_mat(prob_arr, input_arr): # confusion matrix conf_arr = [[0, 0], [0, 0]] for i in range(len(prob_arr)): if int(input_arr[i]) == 1: if float(prob_arr[i]) < 0.5: ...
Scikit-Learn provide a `confusion_matrix` function ``` from sklearn.metrics import confusion_matrix y_actu = [2, 0, 2, 2, 0, 1, 1, 2, 2, 0, 1, 2] y_pred = [0, 0, 2, 1, 0, 2, 1, 0, 2, 0, 2, 2] confusion_matrix(y_actu, y_pred) ``` which output a Numpy array ``` array([[3, 0, 2], [0, 1, 1], [0, 2, 3]]) ``...
How do I find the shortest overlapping match using regular expressions?
2,148,700
12
2010-01-27T16:49:34Z
7,554,619
9
2011-09-26T11:49:10Z
[ "python", "regex" ]
I'm still relatively new to regex. I'm trying to find the shortest string of text that matches a particular pattern, but am having trouble if the shortest pattern is a substring of a larger match. For example: ``` import re string = "A|B|A|B|C|D|E|F|G" my_pattern = 'a.*?b.*?c' my_regex = re.compile(my_pattern, re.DOT...
Contrary to most other answers here, this *can* be done in a single regex using a [positive lookahead assertion](http://www.regular-expressions.info/lookaround.html) with a [capturing group](http://www.regular-expressions.info/brackets.html): ``` >>> my_pattern = '(?=(a.*?b.*?c))' >>> my_regex = re.compile(my_pattern,...
Python - Trap all signals
2,148,888
16
2010-01-27T17:16:29Z
2,148,925
18
2010-01-27T17:24:03Z
[ "python", "linux", "signal-handling" ]
In python 2.6 under Linux, I can use the following to handle a TERM signal: ``` import signal def handleSigTERM(): shutdown() signal.signal(signal.SIGTERM, handleSigTERM) ``` Is there any way to setup a handler for all signals received by the process, other than just setting them up one-at-a-time?
You could just loop through the signals in the signal module and set them up. ``` for i in [x for x in dir(signal) if x.startswith("SIG")]: try: signum = getattr(signal,i) signal.signal(signum,sighandler) except RuntimeError,m: print "Skipping %s"%i ```
Python - Trap all signals
2,148,888
16
2010-01-27T17:16:29Z
5,669,030
9
2011-04-14T20:06:35Z
[ "python", "linux", "signal-handling" ]
In python 2.6 under Linux, I can use the following to handle a TERM signal: ``` import signal def handleSigTERM(): shutdown() signal.signal(signal.SIGTERM, handleSigTERM) ``` Is there any way to setup a handler for all signals received by the process, other than just setting them up one-at-a-time?
If you want to get rid of the try, just ignore signals that cannot be caught. ``` def receive_signal(signum, stack): if signum in [1,2,3,15]: print 'Caught signal %s, exiting.' %(str(signum)) sys.exit() else: print 'Caught signal %s, ignoring.' %(str(signum)) def main(): uncatchabl...
When running a python script in IDLE, is there a way to pass in command line arguments (args)?
2,148,994
28
2010-01-27T17:33:20Z
2,149,029
23
2010-01-27T17:37:14Z
[ "python", "command-line-arguments", "python-idle" ]
I'm testing some python code that parses command line input. Is there a way to pass this input in through IDLE? Currently I'm saving in the IDLE editor and running from a command prompt. I'm running Windows.
It doesn't seem like IDLE provides a way to do this through the GUI, but you could do something like: ``` idle.py -r scriptname.py arg1 arg2 arg3 ``` You can also set `sys.argv` manually, like: ``` try: __file__ except: sys.argv = [sys.argv[0], 'argument1', 'argument2', 'argument2'] ``` (Credit <http://wayn...
Python asyncore & dbus
2,149,358
5
2010-01-27T18:27:49Z
2,149,387
7
2010-01-27T18:32:13Z
[ "python", "dbus", "asyncore" ]
Is it possible to integrate `asyncore` with `dbus` through the same `main loop`? Usually, DBus integration is done through `glib` main loop: is it possible to have either `asyncore` integrate this main loop *or* have dbus use `asyncore`'s ?
`asyncore` sucks. `glib` already provides async stuff, so just use `glib`'s mainloop to do everything.
Customary To Inherit Metaclasses From type?
2,149,846
21
2010-01-27T19:55:12Z
2,150,336
33
2010-01-27T21:21:58Z
[ "python", "metaclass" ]
I have been trying to understand python metaclasses, and so have been going through some sample code. As far as I understand it, a Python metaclass can be any callable. So, I can have my metaclass like ``` def metacls(clsName, bases, atts): .... return type(clsName, bases, atts) ``` However, I have seen a lot...
There are subtle differences, mostly relating to inheritance. When using a function as a metaclass, the resulting class is really an instance of `type`, and can be inherited from without restriction; however, the metaclass function will never be called for such subclasses. When using a subclass of `type` as a metaclass...
Finding Signed Angle Between Vectors
2,150,050
23
2010-01-27T20:34:51Z
2,150,111
27
2010-01-27T20:44:34Z
[ "java", "python", "math", "trigonometry", "angle" ]
How would you find the signed angle theta from vector a to b? And yes, I know that theta = arccos((a.b)/(|a||b|)). However, this does not contain a sign (i.e. it doesn't distinguish between a clockwise or counterclockwise rotation). I need something that can tell me the minimum angle to rotate from a to b. A positiv...
If you have an atan2() function in your math library of choice: ``` signed_angle = atan2(b.y,b.x) - atan2(a.y,a.x) ```
Finding Signed Angle Between Vectors
2,150,050
23
2010-01-27T20:34:51Z
2,150,475
44
2010-01-27T21:44:38Z
[ "java", "python", "math", "trigonometry", "angle" ]
How would you find the signed angle theta from vector a to b? And yes, I know that theta = arccos((a.b)/(|a||b|)). However, this does not contain a sign (i.e. it doesn't distinguish between a clockwise or counterclockwise rotation). I need something that can tell me the minimum angle to rotate from a to b. A positiv...
What you want to use is often called the “perp dot product”, that is, find the vector perpendicular to one of the vectors, and then find the dot product with the other vector. ``` if(a.x*b.y - a.y*b.x < 0) angle = -angle; ``` You can also do this: ``` angle = atan2( a.x*b.y - a.y*b.x, a.x*b.x + a.y*b.y ); ``...
Efficient way to shift a list in python
2,150,108
122
2010-01-27T20:44:07Z
2,150,125
123
2010-01-27T20:46:27Z
[ "python", "list" ]
What is the most efficient way to shift a list in python? Right now I have something like this: ``` >>> def shift(l, n): ... return l[n:] + l[:n] ... >>> l = [1,2,3,4] >>> shift(l,1) [2, 3, 4, 1] >>> shift(l,2) [3, 4, 1, 2] >>> shift(l,0) [1, 2, 3, 4] >>> shift(l,-1) [4, 1, 2, 3] ``` Is there a better way?
A [`collections.deque`](http://docs.python.org/library/collections.html#deque-objects) is optimized for pulling and pushing on both ends. They even have a dedicated `rotate()` method. ``` from collections import deque items = deque([1, 2]) items.append(3) # deque == [1, 2, 3] items.rotate(1) # The deque is now: [3, 1,...
Efficient way to shift a list in python
2,150,108
122
2010-01-27T20:44:07Z
2,150,512
21
2010-01-27T21:48:40Z
[ "python", "list" ]
What is the most efficient way to shift a list in python? Right now I have something like this: ``` >>> def shift(l, n): ... return l[n:] + l[:n] ... >>> l = [1,2,3,4] >>> shift(l,1) [2, 3, 4, 1] >>> shift(l,2) [3, 4, 1, 2] >>> shift(l,0) [1, 2, 3, 4] >>> shift(l,-1) [4, 1, 2, 3] ``` Is there a better way?
It depends on what you want to have happen when you do this: ``` >>> shift([1,2,3], 14) ``` You might want to change your: ``` def shift(seq, n): return seq[n:]+seq[:n] ``` to: ``` def shift(seq, n): n = n % len(seq) return seq[n:] + seq[:n] ```
Efficient way to shift a list in python
2,150,108
122
2010-01-27T20:44:07Z
2,151,035
9
2010-01-27T23:10:59Z
[ "python", "list" ]
What is the most efficient way to shift a list in python? Right now I have something like this: ``` >>> def shift(l, n): ... return l[n:] + l[:n] ... >>> l = [1,2,3,4] >>> shift(l,1) [2, 3, 4, 1] >>> shift(l,2) [3, 4, 1, 2] >>> shift(l,0) [1, 2, 3, 4] >>> shift(l,-1) [4, 1, 2, 3] ``` Is there a better way?
This also depends on if you want to shift the list in place (mutating it), or if you want the function to return a new list. Because, according to my tests, something like this is at least twenty times faster than your implementation that adds two lists: ``` def shiftInPlace(l, n): n = n % len(l) head = l[:n] ...
Efficient way to shift a list in python
2,150,108
122
2010-01-27T20:44:07Z
8,391,327
47
2011-12-05T20:20:52Z
[ "python", "list" ]
What is the most efficient way to shift a list in python? Right now I have something like this: ``` >>> def shift(l, n): ... return l[n:] + l[:n] ... >>> l = [1,2,3,4] >>> shift(l,1) [2, 3, 4, 1] >>> shift(l,2) [3, 4, 1, 2] >>> shift(l,0) [1, 2, 3, 4] >>> shift(l,-1) [4, 1, 2, 3] ``` Is there a better way?
What about just using [`pop(0)`](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists)? > `list.pop([i])` > > Remove the item at the given position in the list, and return it. If > no index is specified, `a.pop()` removes and returns the last item in > the list. (The square brackets around the `i` in t...
Efficient way to shift a list in python
2,150,108
122
2010-01-27T20:44:07Z
12,872,433
15
2012-10-13T10:57:20Z
[ "python", "list" ]
What is the most efficient way to shift a list in python? Right now I have something like this: ``` >>> def shift(l, n): ... return l[n:] + l[:n] ... >>> l = [1,2,3,4] >>> shift(l,1) [2, 3, 4, 1] >>> shift(l,2) [3, 4, 1, 2] >>> shift(l,0) [1, 2, 3, 4] >>> shift(l,-1) [4, 1, 2, 3] ``` Is there a better way?
Numpy can do this using the [`roll`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.roll.html#numpy.roll) command: ``` >>> import numpy >>> a=numpy.arange(1,10) #Generate some data >>> numpy.roll(a,1) array([9, 1, 2, 3, 4, 5, 6, 7, 8]) >>> numpy.roll(a,-1) array([2, 3, 4, 5, 6, 7, 8, 9, 1]) >>> numpy.roll(a...
Efficient way to shift a list in python
2,150,108
122
2010-01-27T20:44:07Z
13,124,747
9
2012-10-29T15:34:10Z
[ "python", "list" ]
What is the most efficient way to shift a list in python? Right now I have something like this: ``` >>> def shift(l, n): ... return l[n:] + l[:n] ... >>> l = [1,2,3,4] >>> shift(l,1) [2, 3, 4, 1] >>> shift(l,2) [3, 4, 1, 2] >>> shift(l,0) [1, 2, 3, 4] >>> shift(l,-1) [4, 1, 2, 3] ``` Is there a better way?
If you just want to iterate over these sets of elements rather than construct a separate data structure, consider using iterators to construct a generator expression: ``` def shift(l,n): return itertools.islice(itertools.cycle(l),n,n+len(l)) >>> list(shift([1,2,3],1)) [2, 3, 1] ```
Is python a serious option for concurrent programming
2,150,144
4
2010-01-27T20:49:54Z
2,150,166
11
2010-01-27T20:54:11Z
[ "python", "multithreading" ]
just considering starting to learning python but I have one concern before I invest more time. Let me phrase this as a statement followed by a concern for others to comment on as perhaps the assumptions in the statement are invalid: I have read about GIL and the consensus seems to be if you require concurrent solution...
[`multiprocessing`](http://docs.python.org/library/multiprocessing.html) can get around the GIL, but it introduces its own issues such as communication between the processes.
Is python a serious option for concurrent programming
2,150,144
4
2010-01-27T20:49:54Z
2,150,315
7
2010-01-27T21:18:12Z
[ "python", "multithreading" ]
just considering starting to learning python but I have one concern before I invest more time. Let me phrase this as a statement followed by a concern for others to comment on as perhaps the assumptions in the statement are invalid: I have read about GIL and the consensus seems to be if you require concurrent solution...
Python is not very good for CPU-bound concurrent programming. The GIL will (in many cases) make your program run as if it was running on a single core - or even worse. Even Unladen Swallow will (probably) not solve that problem (quote from their [project plan](http://code.google.com/p/unladen-swallow/wiki/ProjectPlan):...
Can somebody explain a money regex that just checks if the value matches some pattern?
2,150,205
2
2010-01-27T21:00:30Z
2,150,465
8
2010-01-27T21:43:10Z
[ "python", "regex", "money" ]
**There are multiple posts on here that capture value**, but I'm just looking to check to see if the value is something. More vaguely put; I'm looking to understand the difference between checking a value, and "capturing" a value. In the current case the value would be the following acceptable money formats: [Here is ...
Assuming you want to allow `$5.` but not `5.`, the following will accept your language: ``` money = re.compile('|'.join([ r'^\$?(\d*\.\d{1,2})$', # e.g., $.50, .50, $1.50, $.5, .5 r'^\$?(\d+)$', # e.g., $500, $5, 500, 5 r'^\$(\d+\.?)$', # e.g., $5. ])) ``` Important pieces to understand: * `...
ISO Time (ISO 8601) in Python?
2,150,739
58
2010-01-27T22:22:36Z
2,151,151
9
2010-01-27T23:31:08Z
[ "python", "datetime", "iso8601" ]
I have a file. In Python, I would like to take its creation time, and convert it to an [ISO time (ISO 8601) string](http://en.wikipedia.org/wiki/ISO_8601) **while preserving the fact that it was created in the Eastern Time Zone**. How do I take the file's ctime and convert it to an ISO time string, that indicates the ...
You'll need to use `os.stat` to get the file creation time and a combination of `time.strftime` and `time.timezone` for formatting: ``` >>> import time >>> import os >>> t = os.stat('C:/Path/To/File.txt').st_ctime >>> t = time.localtime(t) >>> formatted = time.strftime('%Y-%m-%d %H:%M:%S', t) >>> tz = str.format('{0:+...
ISO Time (ISO 8601) in Python?
2,150,739
58
2010-01-27T22:22:36Z
4,462,893
25
2010-12-16T16:20:25Z
[ "python", "datetime", "iso8601" ]
I have a file. In Python, I would like to take its creation time, and convert it to an [ISO time (ISO 8601) string](http://en.wikipedia.org/wiki/ISO_8601) **while preserving the fact that it was created in the Eastern Time Zone**. How do I take the file's ctime and convert it to an ISO time string, that indicates the ...
**ISO 8601 Time Representation** The international standard ISO 8601 describes a string representation for dates and times. Two simple examples of this format are ``` 2010-12-16 17:22:15 20101216T172215 ``` (which both stand for the 16 of December 2010) but the format also allows for sub-second resolution times and ...
ISO Time (ISO 8601) in Python?
2,150,739
58
2010-01-27T22:22:36Z
15,142,736
36
2013-02-28T18:19:18Z
[ "python", "datetime", "iso8601" ]
I have a file. In Python, I would like to take its creation time, and convert it to an [ISO time (ISO 8601) string](http://en.wikipedia.org/wiki/ISO_8601) **while preserving the fact that it was created in the Eastern Time Zone**. How do I take the file's ctime and convert it to an ISO time string, that indicates the ...
I found the datetime.isoformat in the [doc](http://docs.python.org/2/library/datetime.html); seems to do what you want : ``` datetime.isoformat([sep]) Return a string representing the date and time in ISO 8601 format, YYYY-MM-DDTHH:MM:SS.mmmmmm or, if microsecond is 0, YYYY-MM-DDTHH:MM:SS If utcoffset() does not ret...
ISO Time (ISO 8601) in Python?
2,150,739
58
2010-01-27T22:22:36Z
28,147,286
59
2015-01-26T09:14:36Z
[ "python", "datetime", "iso8601" ]
I have a file. In Python, I would like to take its creation time, and convert it to an [ISO time (ISO 8601) string](http://en.wikipedia.org/wiki/ISO_8601) **while preserving the fact that it was created in the Eastern Time Zone**. How do I take the file's ctime and convert it to an ISO time string, that indicates the ...
Local to ISO-8601: ``` import datetime datetime.datetime.now().isoformat() ``` UTC to ISO-8601: ``` import datetime datetime.datetime.utcnow().isoformat() ```
ISO Time (ISO 8601) in Python?
2,150,739
58
2010-01-27T22:22:36Z
33,970,813
8
2015-11-28T11:31:31Z
[ "python", "datetime", "iso8601" ]
I have a file. In Python, I would like to take its creation time, and convert it to an [ISO time (ISO 8601) string](http://en.wikipedia.org/wiki/ISO_8601) **while preserving the fact that it was created in the Eastern Time Zone**. How do I take the file's ctime and convert it to an ISO time string, that indicates the ...
[ISO8601 time format](http://tools.ietf.org/html/rfc3339#page-12) does not store a time zone name, only the corresponding utc offset is preserved. To convert a file ctime to an ISO 8601 time string while preserving the utc offset in Python 3: ``` >>> import os >>> from datetime import datetime, timezone >>> ts = os.p...
replacing node text using lxml.objectify while preserving attributes
2,150,838
4
2010-01-27T22:37:21Z
2,151,303
8
2010-01-27T23:55:10Z
[ "python", "xml", "lxml" ]
Using `lxml.objectify` like so: ``` from lxml import objectify o = objectify.fromstring("<a><b atr='someatr'>oldtext</b></a>") o.b = 'newtext' ``` results in `<a><b>newtext</b></a>`, losing the node attribute. It seems to be directly replacing the element with a newly created one, rather than simply replacing the t...
``` >>> type(o.b) <type 'lxml.objectify.StringElement'> ``` You are replacing an element with a plain string. You need to replace it with a new string element. ``` >>> o.b = objectify.E.b('newtext', atr='someatr') ``` For some reason you can't just do: ``` >>> o.b.text = 'newtext' ``` However, this seems to work: ...
How can I use BeautifulSoup to find all the links in a page pointing to a specific domain?
2,151,365
4
2010-01-28T00:10:46Z
2,151,427
7
2010-01-28T00:23:30Z
[ "python", "beautifulsoup" ]
How can I use BeautifulSoup to find all the links in a page pointing to a specific domain?
Use SoupStrainer, ``` from BeautifulSoup import BeautifulSoup, SoupStrainer import re # Find all links links = SoupStrainer('a') [tag for tag in BeautifulSoup(doc, parseOnlyThese=links)] linkstodomain = SoupStrainer('a', href=re.compile('example.com/')) ``` Edit: Modified example from official doc.
Pythonic Way to Create Union of All Values Contained in Multiple Lists
2,151,517
23
2010-01-28T00:44:41Z
2,151,553
44
2010-01-28T00:54:10Z
[ "python", "xml", "list" ]
Doing some XML processing in python. (Edit: I'm forced to use Python 2.4 for this project, boo!) I want to know what is the most Pythonic way to do this (create union of all values in multiple lists): ``` def getUniqueAttributeValues(xml_attribute_nodes): # split attribute values by whitespace into lists resul...
[`set.union`](http://docs.python.org/library/stdtypes.html#set.union) does what you want: ``` >>> results_list = [[1,2,3], [1,2,4]] >>> results_union = set().union(*results_list) >>> print results_union set([1, 2, 3, 4]) ``` You can also do this with more than two lists.
Pythonic Way to Create Union of All Values Contained in Multiple Lists
2,151,517
23
2010-01-28T00:44:41Z
2,152,138
8
2010-01-28T03:38:01Z
[ "python", "xml", "list" ]
Doing some XML processing in python. (Edit: I'm forced to use Python 2.4 for this project, boo!) I want to know what is the most Pythonic way to do this (create union of all values in multiple lists): ``` def getUniqueAttributeValues(xml_attribute_nodes): # split attribute values by whitespace into lists resul...
Since you seem to be using Python 2.5 (it **would** be nice to mention in your Q if you need an A for versions != 2.6, the current production one, by the way;-) and want a list rather than a set as the result, I recommend: ``` import itertools ... return list(set(itertools.chain(*result_list))) ``` [iterto...
Conditionally Require Only One Field In Django Model Form
2,151,966
7
2010-01-28T02:52:50Z
2,151,974
7
2010-01-28T02:54:32Z
[ "python", "django", "forms", "validation", "model" ]
Anyway to make a field conditionally required based on whether or not another field in the same form has been filled out? ``` If field1 has no data, but field2 does form is valid. ``` --- ``` If field1 has no data and field2 has no data form is invalid ``` Not looking for any javascript solutions. I feel as...
Override .clean(self) method, check for self.cleaned\_data and raise ValidationError <https://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other>
Can I get my instance of mechanize.Browser to stay on the same page after calling b.form.submit()?
2,152,098
3
2010-01-28T03:24:46Z
2,167,177
7
2010-01-30T07:21:49Z
[ "python", "screen-scraping", "mechanize" ]
In Python's mechanize.Browser module, when you submit a form the browser instance goes to that page. For this one request, I don't want that; I want it just to stay on the page it's currently on and give me the response in another object (for looping purposes). Anyone know a quick to do this? EDIT: Hmm, so I have this...
The answer to my immediate question in the headline is yes, with `mechanize.Browser.open_novisit()`. It works just like `open()`, but it doesn't change the state of the Browser instance -- that is, it will retrieve the page, and your Browser object will stay where it was.
how to find time at particular timezone from anywhere
2,152,471
5
2010-01-28T05:19:13Z
2,152,557
8
2010-01-28T05:46:39Z
[ "python", "linux", "datetime", "timezone" ]
I need to know the current time at CDT when my Python script is run. However this script will be run in multiple different timezones so a simple offset won't work. I only need a solution for Linux, but a cross platform solution would be ideal.
[pytz](http://pypi.python.org/pypi/pytz) or [dateutil.tz](http://pypi.python.org/pypi/python-dateutil/) is the trick here. Basically it's something like this: ``` >>> from pytz import timezone >>> mytz = timezone('Europe/Paris') >>> yourtz = timezone('US/Eastern') >>> from datetime import datetime >>> now = datetime....
Python looping: idiomatically comparing successive items in a list
2,152,640
6
2010-01-28T06:09:10Z
2,152,948
12
2010-01-28T07:29:57Z
[ "loops", "iterator", "python" ]
I need to loop over a list of objects, comparing them like this: 0 vs. 1, 1 vs. 2, 2 vs. 3, etc. (I'm using pysvn to extract a list of diffs.) I wound up just looping over an index, but I keep wondering if there's some way to do it which is more closely idiomatic. It's Python; shouldn't I be using iterators in some cle...
This is called a sliding window. There's an [example in the `itertools` documentation](http://www.python.org/doc/2.3.5/lib/itertools-example.html) that does it. Here's the code: ``` from itertools import islice def window(seq, n=2): "Returns a sliding window (of width n) over data from the iterable" " s -> ...
Filtering a list of strings based on contents
2,152,898
25
2010-01-28T07:17:41Z
2,152,904
9
2010-01-28T07:19:13Z
[ "python", "list" ]
Given the list `['a','ab','abc','bac']`, I want to compute a list with strings that have `'ab'` in them. I.e. the result is `['ab','abc']`. How can this be done in Python?
``` [x for x in L if 'ab' in x] ```
Filtering a list of strings based on contents
2,152,898
25
2010-01-28T07:17:41Z
2,152,908
36
2010-01-28T07:20:01Z
[ "python", "list" ]
Given the list `['a','ab','abc','bac']`, I want to compute a list with strings that have `'ab'` in them. I.e. the result is `['ab','abc']`. How can this be done in Python?
This simple filtering can be achieved in many ways with Python. The best approach is to use "list comprehensions" as follows: ``` >>> lst = ['a', 'ab', 'abc', 'bac'] >>> res = [k for k in lst if 'ab' in k] >>> res ['ab', 'abc'] >>> ``` Another way is to use the `filter` function: ``` >>> filter(lambda k: 'ab' in k, ...
Python example of Joe's Erlang websocket example
2,153,294
9
2010-01-28T08:58:50Z
2,153,880
10
2010-01-28T10:48:54Z
[ "python", "websocket" ]
I've just been working through the erlang websockets example from [Joe Armstrong's blog](http://armstrongonsoftware.blogspot.com/2009/12/comet-is-dead-long-live-websockets.html) I'm still quite new to erlang so I decided to write a simple server in python that would help teach me about websockets (and hopefully some er...
For those who are interested this was the solution ``` import threading import socket def start_server(): tick = 0 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('localhost', 1234)) sock.listen(100) while True: print 'listening...' csock, address = sock.accept(...
Python object conversion
2,153,295
21
2010-01-28T08:59:13Z
2,154,790
15
2010-01-28T13:30:47Z
[ "python" ]
Assume that we have a an object `k` of type `class A`. We defined a second `class B(A)`. What is the best practice to "convert" object `k` to `class B` and preserve all data in `k`?
This does the "class conversion" but it is subject to collateral damage. Creating another object and replacing its `__dict__` as BrainCore posted would be safer - but this code does what you asked, with no new object being created. ``` class A(object): pass class B(A): def __add__(self, other): return...
Python: Finding average of a nested list
2,153,444
10
2010-01-28T09:27:29Z
2,153,459
10
2010-01-28T09:30:23Z
[ "python" ]
I have a list ``` a = [[1,2,3],[4,5,6],[7,8,9]] ``` Now I want to find the average of these inner list so that ``` a = [(1+4+7)/3,(2+5+8)/3,(3+6+9)/3] ``` 'a' should not be a nested list in the end. Kindly provide an answer for the generic case
``` a = [sum(x)/len(x) for x in zip(*a)] # a is now [4, 5, 6] for your example ``` In Python 2.x, if you don't want integer division, replace `sum(x)/len(x)` by `1.0*sum(x)/len(x)` above. [Documentation for zip](http://docs.python.org/library/functions.html#zip).
Returning the first N characters of a unicode string
2,153,920
9
2010-01-28T10:56:23Z
2,154,536
7
2010-01-28T12:44:50Z
[ "python", "unicode", "python-2.x" ]
I have a string in unicode and I need to return the first N characters. I am doing this: ``` result = unistring[:5] ``` but of course the length of unicode strings != length of characters. Any ideas? The only solution is using re? Edit: More info ``` unistring = "Μεταλλικα" #Metallica written in Greek lett...
When you say: ``` unistring = "Μεταλλικα" #Metallica written in Greek letters ``` You *do not have* a unicode string. You have a bytestring in (presumably) UTF-8. That is not the same thing. A unicode string is a separate datatype in Python. You get unicode by decoding bytestrings using the right encoding: ...
Identify groups of continuous numbers in a list
2,154,249
42
2010-01-28T11:57:15Z
2,154,409
7
2010-01-28T12:21:30Z
[ "python", "list", "range", "continuous" ]
I'd like to identify groups of continuous numbers in a list, so that: ``` myfunc([2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20]) ``` Returns: ``` [(2,5), (12,17), 20] ``` And was wondering what the best way to do this was (particularly if there's something inbuilt into Python). Edit: Note I originally forgot to mention ...
Assuming your list is sorted: ``` >>> from itertools import groupby >>> def ranges(lst): pos = (j - i for i, j in enumerate(lst)) t = 0 for i, els in groupby(pos): l = len(list(els)) el = lst[t] t += l yield range(el, el+l) >>> lst = [2, 3, 4, 5, 12, 13, 14, 15, 16, 17] >>...
Identify groups of continuous numbers in a list
2,154,249
42
2010-01-28T11:57:15Z
2,154,437
71
2010-01-28T12:26:12Z
[ "python", "list", "range", "continuous" ]
I'd like to identify groups of continuous numbers in a list, so that: ``` myfunc([2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20]) ``` Returns: ``` [(2,5), (12,17), 20] ``` And was wondering what the best way to do this was (particularly if there's something inbuilt into Python). Edit: Note I originally forgot to mention ...
**EDIT 2: To answer the OP new requirement** ``` ranges = [] for key, group in groupby(enumerate(data), lambda (index, item): index - item): group = map(itemgetter(1), group) if len(group) > 1: ranges.append(xrange(group[0], group[-1])) else: ranges.append(group[0]) ``` Output: ``` [xrang...
Identify groups of continuous numbers in a list
2,154,249
42
2010-01-28T11:57:15Z
2,154,741
10
2010-01-28T13:21:51Z
[ "python", "list", "range", "continuous" ]
I'd like to identify groups of continuous numbers in a list, so that: ``` myfunc([2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20]) ``` Returns: ``` [(2,5), (12,17), 20] ``` And was wondering what the best way to do this was (particularly if there's something inbuilt into Python). Edit: Note I originally forgot to mention ...
The "naive" solution which I find somewhat readable atleast. ``` x = [2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 22, 25, 26, 28, 51, 52, 57] def group(L): first = last = L[0] for n in L[1:]: if n - 1 == last: # Part of the group, bump the end last = n else: # Not part of the group, yield ...
Python linked list O(1) insert/remove
2,154,946
4
2010-01-28T13:55:37Z
2,154,958
9
2010-01-28T13:58:23Z
[ "python", "algorithm", "list", "linked-list" ]
I am looking for a linked list and related algorithms implementation for Python. Everyone I ask just recommends using built in Python lists, but performance measurements indicate that list insertion and removal is a bottleneck for our application. It's trivial to implement a simple linked list, but I wonder if there is...
Here's a [blog post](http://www.algorithm.co.il/blogs/index.php/programming/python/lru-cache-solution-a-case-for-linked-lists-in-python/) sharing your pain. It includes an implementation of a linked list and a performance comparison. --- Perhaps `blist` would be better, though (from [here](http://pypi.python.org/pypi...
Python linked list O(1) insert/remove
2,154,946
4
2010-01-28T13:55:37Z
2,155,794
7
2010-01-28T15:51:09Z
[ "python", "algorithm", "list", "linked-list" ]
I am looking for a linked list and related algorithms implementation for Python. Everyone I ask just recommends using built in Python lists, but performance measurements indicate that list insertion and removal is a bottleneck for our application. It's trivial to implement a simple linked list, but I wonder if there is...
Python lists are [O(1) for operations at the end of the list](http://wiki.python.org/moin/TimeComplexity). If you'll be doing all your inserting in a semi-sequential fashion--by analogy to C, only keeping a single pointer into the middle of the list as a "cursor" of sorts--you could save yourself a lot of effort by jus...
Is AMQP production ready?
2,155,759
10
2010-01-28T15:46:06Z
2,155,805
12
2010-01-28T15:53:13Z
[ ".net", "python", "rabbitmq", "amqp" ]
I'd like to use AMQP to join two services one written in C# and other written in python. I'm expecting quite large volume of messages per second. * Is there any AMQP Broker that is production ready? * Are the python & .net bindings good enough?
Yes: [RabbitMQ](http://www.rabbitmq.com/)
Python: How can I increment a char?
2,156,892
50
2010-01-28T18:28:20Z
2,156,898
98
2010-01-28T18:28:50Z
[ "python", "char", "increment" ]
I'm new to Python, coming from Java and C. How can I increment a char? In Java or C, chars and ints are practically interchangeable, and in certain loops, it's very useful to me to be able to do increment chars, and index arrays by chars. How can I do this in Python? It's bad enough not having a traditional for(;;) lo...
In Python 2.x, just use the `ord` and `chr` functions: ``` >>> ord('c') 99 >>> ord('c') + 1 100 >>> chr(ord('c') + 1) 'd' >>> ``` Python 3.x makes this more organized and interesting, due to its clear distinction between bytes and unicode. By default, a "string" is unicode, so the above works (`ord` receives Unicode ...
Python: How can I increment a char?
2,156,892
50
2010-01-28T18:28:20Z
2,156,970
11
2010-01-28T18:38:50Z
[ "python", "char", "increment" ]
I'm new to Python, coming from Java and C. How can I increment a char? In Java or C, chars and ints are practically interchangeable, and in certain loops, it's very useful to me to be able to do increment chars, and index arrays by chars. How can I do this in Python? It's bad enough not having a traditional for(;;) lo...
"bad enough not having a traditional for(;;) looper"?? What? Are you trying to do ``` import string for c in string.lowercase: ...do something with c... ``` Or perhaps you're using `string.uppercase` or `string.letters`? Python doesn't have `for(;;)` because there are often better ways to do it. It also doesn't...
Python: Accessing an attribute using a variable
2,157,035
21
2010-01-28T18:47:40Z
2,157,049
38
2010-01-28T18:49:38Z
[ "python" ]
How do I reference `this_prize.left` or `this_prize.right` using a variable? ``` from collections import namedtuple import random Prize = namedtuple("Prize", ["left", "right"]) this_prize = Prize("FirstPrize", "SecondPrize") if random.random() > .5: choice = "left" else: choice = "right" #retrieve the v...
``` getattr(this_prize,choice) ``` <http://docs.python.org/library/functions.html#getattr>
Python: Accessing an attribute using a variable
2,157,035
21
2010-01-28T18:47:40Z
2,157,125
35
2010-01-28T19:01:14Z
[ "python" ]
How do I reference `this_prize.left` or `this_prize.right` using a variable? ``` from collections import namedtuple import random Prize = namedtuple("Prize", ["left", "right"]) this_prize = Prize("FirstPrize", "SecondPrize") if random.random() > .5: choice = "left" else: choice = "right" #retrieve the v...
The expression `this_prize.choice` is telling the interpreter that you want to access an attribute of this\_prize with the name "choice". But this attribute does not exist in this\_prize. What you actually want is to return the attribute of this\_prize identified by the ***value*** of choice. So you just need to chang...
Python: Using namedtuple._replace with a variable as a fieldname
2,157,561
7
2010-01-28T20:02:00Z
2,157,742
14
2010-01-28T20:32:48Z
[ "python", "namedtuple" ]
Can I reference a namedtuple fieldame using a variable? ``` from collections import namedtuple import random Prize = namedtuple("Prize", ["left", "right"]) this_prize = Prize("FirstPrize", "SecondPrize") if random.random() > .5: choice = "left" else: choice = "right" #retrieve the value of "left" or "rig...
Tuples are immutable, and so are NamedTuples. They are not supposed to be changed! `this_prize._replace(choice = "Yay")` calls `_replace` with the keyword argument `"choice"`. It doesn't use `choice` as a variable and tries to replace a field by the name of `choice`. `this_prize._replace(**{choice : "Yay"} )` would u...
drop into python interpreter while executing function
2,158,097
51
2010-01-28T21:27:44Z
2,158,119
30
2010-01-28T21:30:17Z
[ "python" ]
i have a python module with a function: ``` def do_stuff(param1 = 'a'): if type(param1) == int: # enter python interpreter here do_something() else: do_something_else() ``` is there a way to drop into the command line interpreter where i have the comment? so that if i run the following...
Inserting ``` import pdb; pdb.set_trace() ``` will enter the python debugger at that point See here: <http://docs.python.org/library/pdb.html>
drop into python interpreter while executing function
2,158,097
51
2010-01-28T21:27:44Z
2,158,266
90
2010-01-28T21:53:57Z
[ "python" ]
i have a python module with a function: ``` def do_stuff(param1 = 'a'): if type(param1) == int: # enter python interpreter here do_something() else: do_something_else() ``` is there a way to drop into the command line interpreter where i have the comment? so that if i run the following...
If you want a standard interactive prompt (instead of the debugger, as shown by prestomation), you can do this: ``` import code code.interact(local=locals()) ``` See: the [code module](http://docs.python.org/library/code.html#code.interact). If you have IPython installed, and want an IPython shell instead, you can d...
drop into python interpreter while executing function
2,158,097
51
2010-01-28T21:27:44Z
32,960,430
11
2015-10-06T01:43:55Z
[ "python" ]
i have a python module with a function: ``` def do_stuff(param1 = 'a'): if type(param1) == int: # enter python interpreter here do_something() else: do_something_else() ``` is there a way to drop into the command line interpreter where i have the comment? so that if i run the following...
If you want a default Python interpreter, you can do ``` import code code.interact(local=dict(globals(), **locals())) ``` This will allow access to both locals and globals. If you want to drop into an IPython interpreter, the `IPShellEmbed` solution is **outdated**. Currently what works is: ``` from IPython import ...
How do I turn a python datetime into a string, with readable format date?
2,158,347
65
2010-01-28T22:08:27Z
2,158,454
87
2010-01-28T22:23:44Z
[ "python", "datetime", "string-formatting" ]
``` t = e['updated_parsed'] dt = datetime.datetime(t[0],t[1],t[2],t[3],t[4],t[5],t[6] print dt >>>2010-01-28 08:39:49.000003 ``` How do I turn that into a string?: ``` "January 28, 2010" ```
The datetime class has a method strftime. [strftime() Behavior](https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior) in the Python docs documents the different formats it accepts. For this specific example, it would look something like: ``` my_datetime.strftime("%B %d, %Y") ```
How do I turn a python datetime into a string, with readable format date?
2,158,347
65
2010-01-28T22:08:27Z
22,842,734
52
2014-04-03T15:49:16Z
[ "python", "datetime", "string-formatting" ]
``` t = e['updated_parsed'] dt = datetime.datetime(t[0],t[1],t[2],t[3],t[4],t[5],t[6] print dt >>>2010-01-28 08:39:49.000003 ``` How do I turn that into a string?: ``` "January 28, 2010" ```
Here is how you can accomplish the same using python's general formatting function... ``` >>>from datetime import datetime >>>"{:%B %d, %Y}".format(datetime.now()) ``` The formatting characters used here are the same as those used by [strftime](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-beh...
Flatten (an irregular) list of lists in Python
2,158,395
256
2010-01-28T22:15:42Z
2,158,522
28
2010-01-28T22:34:45Z
[ "python", "list", "optimization", "flatten" ]
Yes, I know this subject has been covered before ([here](http://stackoverflow.com/questions/120886), [here](http://stackoverflow.com/questions/406121), [here](http://stackoverflow.com/questions/457215), [here](http://stackoverflow.com/questions/952914)), but as far as I know, all solutions, except for one, fail on a li...
My solution: ``` def flatten(x): if isinstance(x, collections.Iterable): return [a for i in x for a in flatten(i)] else: return [x] ``` A little more concise, but pretty much the same.
Flatten (an irregular) list of lists in Python
2,158,395
256
2010-01-28T22:15:42Z
2,158,532
221
2010-01-28T22:35:51Z
[ "python", "list", "optimization", "flatten" ]
Yes, I know this subject has been covered before ([here](http://stackoverflow.com/questions/120886), [here](http://stackoverflow.com/questions/406121), [here](http://stackoverflow.com/questions/457215), [here](http://stackoverflow.com/questions/952914)), but as far as I know, all solutions, except for one, fail on a li...
Using generator functions can make your example a little easier to read and probably boost the performance. ## Python 2 ``` def flatten(l): for el in l: if isinstance(el, collections.Iterable) and not isinstance(el, basestring): for sub in flatten(el): yield sub else: ...
Flatten (an irregular) list of lists in Python
2,158,395
256
2010-01-28T22:15:42Z
2,158,562
17
2010-01-28T22:42:07Z
[ "python", "list", "optimization", "flatten" ]
Yes, I know this subject has been covered before ([here](http://stackoverflow.com/questions/120886), [here](http://stackoverflow.com/questions/406121), [here](http://stackoverflow.com/questions/457215), [here](http://stackoverflow.com/questions/952914)), but as far as I know, all solutions, except for one, fail on a li...
This version of `flatten` avoids python's recursion limit (and thus works with arbitrarily deep, nested iterables). It is a generator which can handle strings and arbitrary iterables (even infinite ones). ``` import itertools as IT import collections def flatten(iterable, ltypes=collections.Iterable): remainder =...
Flatten (an irregular) list of lists in Python
2,158,395
256
2010-01-28T22:15:42Z
2,159,079
29
2010-01-29T00:27:22Z
[ "python", "list", "optimization", "flatten" ]
Yes, I know this subject has been covered before ([here](http://stackoverflow.com/questions/120886), [here](http://stackoverflow.com/questions/406121), [here](http://stackoverflow.com/questions/457215), [here](http://stackoverflow.com/questions/952914)), but as far as I know, all solutions, except for one, fail on a li...
Generator version of @unutbu's non-recursive solution, as requested by @Andrew in a comment: ``` def genflat(l, ltypes=collections.Sequence): l = list(l) i = 0 while i < len(l): while isinstance(l[i], ltypes): if not l[i]: l.pop(i) i -= 1 ...
Flatten (an irregular) list of lists in Python
2,158,395
256
2010-01-28T22:15:42Z
4,590,652
8
2011-01-04T04:29:07Z
[ "python", "list", "optimization", "flatten" ]
Yes, I know this subject has been covered before ([here](http://stackoverflow.com/questions/120886), [here](http://stackoverflow.com/questions/406121), [here](http://stackoverflow.com/questions/457215), [here](http://stackoverflow.com/questions/952914)), but as far as I know, all solutions, except for one, fail on a li...
``` def flatten(xs): res = [] def loop(ys): for i in ys: if isinstance(i, list): loop(i) else: res.append(i) loop(xs) return res ```
Flatten (an irregular) list of lists in Python
2,158,395
256
2010-01-28T22:15:42Z
4,694,575
10
2011-01-14T18:31:33Z
[ "python", "list", "optimization", "flatten" ]
Yes, I know this subject has been covered before ([here](http://stackoverflow.com/questions/120886), [here](http://stackoverflow.com/questions/406121), [here](http://stackoverflow.com/questions/457215), [here](http://stackoverflow.com/questions/952914)), but as far as I know, all solutions, except for one, fail on a li...
Here's another answer that is even more interesting... ``` import re def Flatten(TheList): a = str(TheList) b,crap = re.subn(r'[\[,\]]', ' ', a) c = b.split() d = [int(x) for x in c] return(d) ``` Basically, it converts the nested list to a string, uses a regex to strip out the nested syntax, an...
Flatten (an irregular) list of lists in Python
2,158,395
256
2010-01-28T22:15:42Z
5,409,395
16
2011-03-23T17:42:24Z
[ "python", "list", "optimization", "flatten" ]
Yes, I know this subject has been covered before ([here](http://stackoverflow.com/questions/120886), [here](http://stackoverflow.com/questions/406121), [here](http://stackoverflow.com/questions/457215), [here](http://stackoverflow.com/questions/952914)), but as far as I know, all solutions, except for one, fail on a li...
Here is my functional version of recursive flatten which handles both tuples and lists, and lets you throw in any mix of positional arguments. Returns a generator which produces the entire sequence in order, arg by arg: ``` flatten = lambda *n: (e for a in n for e in (flatten(*a) if isinstance(a, (tuple, list)) el...
Flatten (an irregular) list of lists in Python
2,158,395
256
2010-01-28T22:15:42Z
14,491,059
19
2013-01-23T23:04:43Z
[ "python", "list", "optimization", "flatten" ]
Yes, I know this subject has been covered before ([here](http://stackoverflow.com/questions/120886), [here](http://stackoverflow.com/questions/406121), [here](http://stackoverflow.com/questions/457215), [here](http://stackoverflow.com/questions/952914)), but as far as I know, all solutions, except for one, fail on a li...
Generator using recursion and duck typing (updated for Python 3): ``` def flatten(L): for item in L: try: yield from flatten(item) except TypeError: yield item list(flatten([[[1, 2, 3], [4, 5]], 6])) >>>[1, 2, 3, 4, 5, 6] ```
Flatten (an irregular) list of lists in Python
2,158,395
256
2010-01-28T22:15:42Z
14,781,252
56
2013-02-08T20:59:02Z
[ "python", "list", "optimization", "flatten" ]
Yes, I know this subject has been covered before ([here](http://stackoverflow.com/questions/120886), [here](http://stackoverflow.com/questions/406121), [here](http://stackoverflow.com/questions/457215), [here](http://stackoverflow.com/questions/952914)), but as far as I know, all solutions, except for one, fail on a li...
You could simply use the flatten function in the [`compiler.ast`](http://docs.python.org/2/library/compiler.html#module-compiler.ast) module. ``` >>> from compiler.ast import flatten >>> flatten([0, [1, 2], [3, 4, [5, 6]], 7]) [0, 1, 2, 3, 4, 5, 6, 7] ```
Strange Python set and hash behaviour - how does this work?
2,159,232
4
2010-01-29T01:02:43Z
2,159,241
13
2010-01-29T01:06:43Z
[ "python", "hash", "set" ]
I have a class called `GraphEdge` which I would like to be uniquely defined within a set (the built-in `set` type) by its `tail` and `head` members, which are set via `__init__`. If I do not define `__hash__`, I see the following behaviour: ``` >>> E = GraphEdge('A', 'B') >>> H = GraphEdge('A', 'B') >>> hash(E) 13973...
You have a hash collision. On hash collision, the set uses the == operator to check on whether or not they are truly equal to each other.
Strange Python set and hash behaviour - how does this work?
2,159,232
4
2010-01-29T01:02:43Z
2,159,257
7
2010-01-29T01:12:05Z
[ "python", "hash", "set" ]
I have a class called `GraphEdge` which I would like to be uniquely defined within a set (the built-in `set` type) by its `tail` and `head` members, which are set via `__init__`. If I do not define `__hash__`, I see the following behaviour: ``` >>> E = GraphEdge('A', 'B') >>> H = GraphEdge('A', 'B') >>> hash(E) 13973...
It's important to understand how hash and == work together, because both are used by sets. For two values x and y, the important rule is that: ``` x == y ==> hash(x) == hash(y) ``` (x equals y implies that x and y's hashes are equal). But, the inverse is not true: two unequal values can have the same hash. Sets (and...
installing mechanize with easy_install
2,159,733
6
2010-01-29T03:36:06Z
9,389,250
10
2012-02-22T04:50:36Z
[ "python", "mechanize", "easy-install" ]
I just got easy\_install downloaded but i'm having problems installing mechanize, should I be addressing site-packages at any point. In the first try below, i got an error. in the second try below, i got command not found which is wierd since I know for sure that it downloaded. ``` names-computer:~ names$ cd /Users/na...
``` apt-get install python-setuptools ``` This command will install `easy_install` on ubuntu.
Access request in django custom template tags
2,160,261
57
2010-01-29T06:21:16Z
2,160,298
128
2010-01-29T06:30:35Z
[ "python", "django", "django-templates", "django-custom-tags" ]
My code in myapp\_extras.py: ``` from django import template register = template.Library() @register.inclusion_tag('new/userinfo.html') def address(): address = request.session['address'] return {'address':address} ``` in 'settings.py': ``` TEMPLATE_CONTEXT_PROCESSORS =( "django.core.context_processors...
`request` is not a variable in that scope. You will have to get it from the context first. [Pass `takes_context` to the decorator and add `context` to the tag arguments](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags). Like this: ``` @register.inclusion_tag('new/userinfo.html', takes_...
Access request in django custom template tags
2,160,261
57
2010-01-29T06:21:16Z
2,943,973
11
2010-05-31T13:54:22Z
[ "python", "django", "django-templates", "django-custom-tags" ]
My code in myapp\_extras.py: ``` from django import template register = template.Library() @register.inclusion_tag('new/userinfo.html') def address(): address = request.session['address'] return {'address':address} ``` in 'settings.py': ``` TEMPLATE_CONTEXT_PROCESSORS =( "django.core.context_processors...
I've tried solution from above (from Ignacio Vazquez-Abrams) and it actually didn't work until I've found out that context processors works only with `RequestContext` wrapper class. So in main view method you should add the following line: ``` from django.template import RequestContext return render_to_respon...
Access request in django custom template tags
2,160,261
57
2010-01-29T06:21:16Z
8,669,417
7
2011-12-29T15:01:33Z
[ "python", "django", "django-templates", "django-custom-tags" ]
My code in myapp\_extras.py: ``` from django import template register = template.Library() @register.inclusion_tag('new/userinfo.html') def address(): address = request.session['address'] return {'address':address} ``` in 'settings.py': ``` TEMPLATE_CONTEXT_PROCESSORS =( "django.core.context_processors...
I've done this way: ``` from django import template register = template.Library() def do_test_request(parser,token): try: tag_name = token.split_contents() # Not really useful except ValueError: raise template.TemplateSyntaxError("%r error" % token.contents.split()[0]) return RequestTestNo...
Convert C++ to Python (For Loop multiple assignment)
2,160,616
2
2010-01-29T08:02:05Z
2,160,632
8
2010-01-29T08:06:16Z
[ "c++", "python", "for-loop" ]
Convert to python: ``` #include <iostream> using namespace std; int main(int argc, char** argv) { for (int i = 0, j = i + 3; i < 100; ++i, j= i+3) cout << i << " j: " << j << endl; getchar(); return 0; } ``` I try: ``` for i in range(99): j = i + 3 print i, " j: ", j ``` How to make it...
Just change 99 to 100 ``` for i in range(100): j = i + 3 print i, " j: ", j ``` Or ``` for i,j in [(i, i+3) for i in range(100)]: ```
Sweave for python
2,161,152
24
2010-01-29T10:03:56Z
2,162,068
16
2010-01-29T13:06:34Z
[ "python", "sweave", "literate-programming" ]
I've recently started using [Sweave](http://www.stat.uni-muenchen.de/~leisch/Sweave/)\* for creating reports of analyses run with R, and am now looking to do the same with my python scripts. I've found references to [embedding python in Sweave](http://romainfrancois.blog.free.fr/index.php?post/2009/01/21/Python-and-Sw...
I don't believe that there's a direct equivalent, so Romain Francois's suggestion (in your link) is probably the best. You might also want to consider the following: 1. Have a look at [PyLit](http://pylit.berlios.de/) and [PyReport](http://gael-varoquaux.info/computers/pyreport/) which are intended for literate progra...
Sweave for python
2,161,152
24
2010-01-29T10:03:56Z
2,368,659
20
2010-03-03T04:01:04Z
[ "python", "sweave", "literate-programming" ]
I've recently started using [Sweave](http://www.stat.uni-muenchen.de/~leisch/Sweave/)\* for creating reports of analyses run with R, and am now looking to do the same with my python scripts. I've found references to [embedding python in Sweave](http://romainfrancois.blog.free.fr/index.php?post/2009/01/21/Python-and-Sw...
I have written a Python implementation of Sweave called Pweave that implements basic functionality and some options of Sweave for Python code embedded in reST or Latex document. You can get it here: <http://mpastell.com/pweave> and see the original blog post here: <http://mpastell.com/2010/03/03/pweave-sweave-for-pytho...
Sweave for python
2,161,152
24
2010-01-29T10:03:56Z
8,069,844
14
2011-11-09T18:39:44Z
[ "python", "sweave", "literate-programming" ]
I've recently started using [Sweave](http://www.stat.uni-muenchen.de/~leisch/Sweave/)\* for creating reports of analyses run with R, and am now looking to do the same with my python scripts. I've found references to [embedding python in Sweave](http://romainfrancois.blog.free.fr/index.php?post/2009/01/21/Python-and-Sw...
[Dexy](http://www.dexy.it/) is a very similar product to Sweave. One advantage of Dexy is that it is not exclusive to one single language. You could create a Dexy document that included R code, Python code, or about anything else.
Sweave for python
2,161,152
24
2010-01-29T10:03:56Z
14,471,700
7
2013-01-23T02:55:58Z
[ "python", "sweave", "literate-programming" ]
I've recently started using [Sweave](http://www.stat.uni-muenchen.de/~leisch/Sweave/)\* for creating reports of analyses run with R, and am now looking to do the same with my python scripts. I've found references to [embedding python in Sweave](http://romainfrancois.blog.free.fr/index.php?post/2009/01/21/Python-and-Sw...
This is a bit late, but for future reference you might consider my [PythonTeX](https://github.com/gpoore/pythontex) package for LaTeX. PythonTeX allows you enter Python code in a LaTeX document, run it, and bring back the output. But unlike Sweave, the document you actually edit is a valid .tex document (not .Snw or .R...
Regex to separate Numeric from Alpha
2,161,519
4
2010-01-29T11:21:52Z
2,161,531
8
2010-01-29T11:24:19Z
[ "python", "regex" ]
I have a bunch of strings: ``` "10people" "5cars" .. ``` How would I split this to? ``` ['10','people'] ['5','cars'] ``` It can be any amount of numbers and text. I'm thinking about writing some sort of regex - however I'm sure there's an easy way to do it in Python.
Use the regex `(\d+)([a-zA-Z]+)`. ``` import re a = ["10people", "5cars"] [re.match('^(\\d+)([a-zA-Z]+)$', x).groups() for x in a] ``` Result: ``` [('10', 'people'), ('5', 'cars')] ```
Regex to separate Numeric from Alpha
2,161,519
4
2010-01-29T11:21:52Z
2,161,547
8
2010-01-29T11:27:07Z
[ "python", "regex" ]
I have a bunch of strings: ``` "10people" "5cars" .. ``` How would I split this to? ``` ['10','people'] ['5','cars'] ``` It can be any amount of numbers and text. I'm thinking about writing some sort of regex - however I'm sure there's an easy way to do it in Python.
``` >>> re.findall('(\d+|[a-zA-Z]+)', '12fgsdfg234jhfq35rjg') ['12', 'fgsdfg', '234', 'jhfq', '35', 'rjg'] ```
How to count the frequency of the elements in a list?
2,161,752
77
2010-01-29T12:08:20Z
2,161,791
31
2010-01-29T12:16:03Z
[ "python", "counter", "frequency", "counting" ]
I'm a python newbie, so please bear with me. I need to find the frequency of elements in a list ``` a = [1,1,1,1,2,2,2,2,3,3,4,5,5] ``` output-> ``` b = [4,4,2,1,2] ``` Also I want to remove the duplicates from a ``` a = [1,2,3,4,5] ```
To count the number of appearances: ``` from collections import defaultdict appearances = defaultdict(int) for curr in a: appearances[curr] += 1 ``` To remove duplicates: ``` a = set(a) ```
How to count the frequency of the elements in a list?
2,161,752
77
2010-01-29T12:08:20Z
2,161,792
13
2010-01-29T12:16:19Z
[ "python", "counter", "frequency", "counting" ]
I'm a python newbie, so please bear with me. I need to find the frequency of elements in a list ``` a = [1,1,1,1,2,2,2,2,3,3,4,5,5] ``` output-> ``` b = [4,4,2,1,2] ``` Also I want to remove the duplicates from a ``` a = [1,2,3,4,5] ```
Counting the frequency of elements is probably best done with a dictionary: ``` b = {} for item in a: b[item] = b.get(item, 0) + 1 ``` To remove the duplicates, use a set: ``` a = list(set(a)) ```
How to count the frequency of the elements in a list?
2,161,752
77
2010-01-29T12:08:20Z
2,161,801
47
2010-01-29T12:18:39Z
[ "python", "counter", "frequency", "counting" ]
I'm a python newbie, so please bear with me. I need to find the frequency of elements in a list ``` a = [1,1,1,1,2,2,2,2,3,3,4,5,5] ``` output-> ``` b = [4,4,2,1,2] ``` Also I want to remove the duplicates from a ``` a = [1,2,3,4,5] ```
Since the list is ordered you can do this: ``` a = [1,1,1,1,2,2,2,2,3,3,4,5,5] from itertools import groupby [len(list(group)) for key, group in groupby(a)] ``` Output: ``` [4, 4, 2, 1, 2] ```
How to count the frequency of the elements in a list?
2,161,752
77
2010-01-29T12:08:20Z
2,162,035
9
2010-01-29T13:00:53Z
[ "python", "counter", "frequency", "counting" ]
I'm a python newbie, so please bear with me. I need to find the frequency of elements in a list ``` a = [1,1,1,1,2,2,2,2,3,3,4,5,5] ``` output-> ``` b = [4,4,2,1,2] ``` Also I want to remove the duplicates from a ``` a = [1,2,3,4,5] ```
In Python 2.7+, you could use [collections.Counter](http://docs.python.org/3.1/whatsnew/2.7.html#new-improved-and-deprecated-modules) to count items ``` >>> a = [1,1,1,1,2,2,2,2,3,3,4,5,5] >>> >>> from collections import Counter >>> c=Counter(a) >>> >>> c.values() [4, 4, 2, 1, 2] >>> >>> c.keys() [1, 2, 3, 4, 5] ```
How to count the frequency of the elements in a list?
2,161,752
77
2010-01-29T12:08:20Z
2,162,045
216
2010-01-29T13:02:41Z
[ "python", "counter", "frequency", "counting" ]
I'm a python newbie, so please bear with me. I need to find the frequency of elements in a list ``` a = [1,1,1,1,2,2,2,2,3,3,4,5,5] ``` output-> ``` b = [4,4,2,1,2] ``` Also I want to remove the duplicates from a ``` a = [1,2,3,4,5] ```
In Python 2.7, you can use [`collections.Counter`](https://docs.python.org/2/library/collections.html#collections.Counter): ``` import collections a = [1,1,1,1,2,2,2,2,3,3,4,5,5] counter=collections.Counter(a) print(counter) # Counter({1: 4, 2: 4, 3: 2, 5: 2, 4: 1}) print(counter.values()) # [4, 4, 2, 1, 2] print(coun...
How to count the frequency of the elements in a list?
2,161,752
77
2010-01-29T12:08:20Z
9,744,274
54
2012-03-16T20:44:01Z
[ "python", "counter", "frequency", "counting" ]
I'm a python newbie, so please bear with me. I need to find the frequency of elements in a list ``` a = [1,1,1,1,2,2,2,2,3,3,4,5,5] ``` output-> ``` b = [4,4,2,1,2] ``` Also I want to remove the duplicates from a ``` a = [1,2,3,4,5] ```
Python 2.7+ introduces Dictionary Comprehension. Building the dictionary from the list will get you the count as well as get rid of duplicates. ``` >>> a = [1,1,1,1,2,2,2,2,3,3,4,5,5] >>> d = {x:a.count(x) for x in a} >>> d {1: 4, 2: 4, 3: 2, 4: 1, 5: 2} >>> a, b = d.keys(), d.values() >>> a [1, 2, 3, 4, 5] >>> b [4, ...
Calling gnuplot from python
2,161,932
14
2010-01-29T12:44:00Z
2,161,965
19
2010-01-29T12:48:52Z
[ "python", "gnuplot" ]
I've a python script that after some computing will generate two data files formatted as gnuplot input. How do I 'call' gnuplot from python ? I want to send the following python string as input to gnuplot: ``` "plot '%s' with lines, '%s' with points;" % (eout,nout) ``` where '*eout*' and '*nout*' are the two filena...
The [`subprocess`](http://docs.python.org/library/subprocess.html) module lets you call other programs: ``` import subprocess plot = subprocess.Popen(['gnuplot'], stdin=subprocess.PIPE) plot.communicate("plot '%s' with lines, '%s' with points;" % (eout,nout)) ```
Calling gnuplot from python
2,161,932
14
2010-01-29T12:44:00Z
5,002,645
11
2011-02-15T10:43:21Z
[ "python", "gnuplot" ]
I've a python script that after some computing will generate two data files formatted as gnuplot input. How do I 'call' gnuplot from python ? I want to send the following python string as input to gnuplot: ``` "plot '%s' with lines, '%s' with points;" % (eout,nout) ``` where '*eout*' and '*nout*' are the two filena...
Subprocess is explained very clearly on Doug Hellemann's [Python Module of the Week](http://www.doughellmann.com/PyMOTW/subprocess/) This works well: ``` import subprocess proc = subprocess.Popen(['gnuplot','-p'], shell=True, stdin=subprocess.PIPE, ...
How to set timeout for urlfetch in Google App Engine?
2,162,115
14
2010-01-29T13:14:15Z
2,162,160
20
2010-01-29T13:22:56Z
[ "python", "django", "google-app-engine", "timeout" ]
I'm trying to have Django (on top of GAE) fetch data from another web service. I'm often hit with error like this: > ApplicationError: 2 timed out Request > > Method: GET > > Request URL:http://localhost:8080/ > > Exception Type: DownloadError > > Exception Value: ApplicationError: 2 timed out > > Exception Location: ...
You can set it using the `deadline` argument of the [fetch function](http://code.google.com/appengine/docs/python/urlfetch/fetchfunction.html). From [the docs](http://code.google.com/appengine/docs/python/urlfetch/overview.html): > The deadline can be up to a maximum of 60 seconds for request handlers and 10 minutes f...
How to set timeout for urlfetch in Google App Engine?
2,162,115
14
2010-01-29T13:14:15Z
12,980,842
24
2012-10-19T19:06:54Z
[ "python", "django", "google-app-engine", "timeout" ]
I'm trying to have Django (on top of GAE) fetch data from another web service. I'm often hit with error like this: > ApplicationError: 2 timed out Request > > Method: GET > > Request URL:http://localhost:8080/ > > Exception Type: DownloadError > > Exception Value: ApplicationError: 2 timed out > > Exception Location: ...
Seeing as this is a `Python` question, I thought I'd provide a Python answer for anyone who comes across this problem. Just import `urlfetch` and then define a deadline before doing anything else in your code: ``` from google.appengine.api import urlfetch urlfetch.set_default_fetch_deadline(60) ```
Why do I have to press Ctrl+D twice to close stdin?
2,162,914
13
2010-01-29T15:27:55Z
2,164,353
11
2010-01-29T18:52:52Z
[ "python", "bash", "stdin" ]
I have the following Python script that reads numbers and outputs an error if the input is not a number. ``` import fileinput import sys for line in (txt.strip() for txt in fileinput.input()): if not line.isdigit(): sys.stderr.write("ERROR: not a number: %s\n" % line) ``` If I get the input from stdin, I ...
In Python 3, this was due to [a bug in Python's standard I/O library](http://bugs.python.org/issue5505). The bug was fixed in Python 3.3. --- In a Unix terminal, typing Ctrl+D doesn't actually close the process's stdin. But typing either Enter or Ctrl+D does cause the OS `read` system call to return right away. So: ...
Why do I have to press Ctrl+D twice to close stdin?
2,162,914
13
2010-01-29T15:27:55Z
2,171,030
9
2010-01-31T08:25:11Z
[ "python", "bash", "stdin" ]
I have the following Python script that reads numbers and outputs an error if the input is not a number. ``` import fileinput import sys for line in (txt.strip() for txt in fileinput.input()): if not line.isdigit(): sys.stderr.write("ERROR: not a number: %s\n" % line) ``` If I get the input from stdin, I ...
Most likely this has to do with Python the following Python issues: * [5505](http://bugs.python.org/issue5505): `sys.stdin.read()` doesn't return after first EOF on Windows, and * [1633941](http://bugs.python.org/issue1633941): `for line in sys.stdin:` doesn't notice EOF the first time.
Python order of execution
2,162,975
2
2010-01-29T15:36:28Z
2,163,073
10
2010-01-29T15:49:24Z
[ "python", "order", "execution" ]
I was wondering if Python has similar issues as C regarding the order of execution of certain elements of code. For example, I know in C there are times say when it's not guaranteed that some variable is initialized before another. Or just because one line of code is above another it's not guaranteed that it is implem...
The only thing I can think of that may surprise some people is: ``` def test(): try: return True finally: return False print test() ``` Output: ``` False ``` `finally` clauses really are executed last, even if a `return` statement precedes them. However, this is not specific to Python.
Best way to make Django's login_required the default
2,164,069
73
2010-01-29T18:08:37Z
2,164,224
76
2010-01-29T18:33:20Z
[ "python", "django" ]
I'm working on a large Django app, the vast majority of which requires a login to access. This means that all throughout our app we've sprinkled: ``` @login_required def view(...): ``` That's fine, and it works great *as long as we remember to add it everywhere*! Sadly sometimes we forget, and the failure often isn't...
Middleware may be your best bet. I've used this piece of code in the past, modified from a snippet found elsewhere: ``` import re from django.conf import settings from django.contrib.auth.decorators import login_required class RequireLoginMiddleware(object): """ Middleware component that wraps the login_req...
Best way to make Django's login_required the default
2,164,069
73
2010-01-29T18:08:37Z
2,165,855
24
2010-01-29T23:07:47Z
[ "python", "django" ]
I'm working on a large Django app, the vast majority of which requires a login to access. This means that all throughout our app we've sprinkled: ``` @login_required def view(...): ``` That's fine, and it works great *as long as we remember to add it everywhere*! Sadly sometimes we forget, and the failure often isn't...
There is an alternative to putting a decorator on each view function. You can also put the `login_required()` decorator in the `urls.py` file. While this is still a manual task, at least you have it all in one place, which makes it easier to audit. e.g., ``` from my_views import home_view urlpatterns = patte...
In python django how do you print out an object's inrospection? The list of all public methods of that object (variable and/or functions)?
2,164,767
14
2010-01-29T19:56:53Z
2,164,802
27
2010-01-29T20:06:01Z
[ "python", "django" ]
In python django how do you print out an object's inrospection? The list of all public methods of that object (variable and/or functions)? e.g.: ``` def Factotum(models.Model): id_ref = models.IntegerField() def calculateSeniorityFactor(): return (1000 - id_ref) * 1000 ``` I want to be able to run a command...
Well, things you can introspect are many, not just one. Good things to start with are: ``` >>> help(object) >>> dir(object) >>> object.__dict__ ``` Also take a look at the inspect module in the standard library. That should make 99% of all the bases belong to you.
Replacing one character of a string in python
2,165,172
7
2010-01-29T21:09:33Z
2,165,206
12
2010-01-29T21:14:51Z
[ "python" ]
In python, are strings mutable? The line `someString[3] = "a"` throws the error > TypeError: 'str' object does not > support item assignment I can see why (as I could have written someString[3] = "test" and that would obviously be illegal) but is there a method to do this in python?
Python strings are immutable, and so they do not support item or slice assigment. You'll have to build a new string using i.e. `someString[:3] + 'a' + someString[4:]` or some other suitable approach.
Replacing one character of a string in python
2,165,172
7
2010-01-29T21:09:33Z
2,165,236
7
2010-01-29T21:20:02Z
[ "python" ]
In python, are strings mutable? The line `someString[3] = "a"` throws the error > TypeError: 'str' object does not > support item assignment I can see why (as I could have written someString[3] = "test" and that would obviously be illegal) but is there a method to do this in python?
Instead of storing your value as a string, you could use a list of characters: ``` >>> l = list('foobar') >>> l[3] = 'f' >>> l[5] = 'n' ``` Then if you want to convert it back to a string to display it, use this: ``` >>> ''.join(l) 'foofan' ``` If you are changing a lot of characters one at a time, this method will...
Multiplying a subset of a list of integers together in python
2,165,449
3
2010-01-29T21:57:24Z
2,165,481
9
2010-01-29T22:03:09Z
[ "python" ]
Let's say I have a list of 10 integers and I want the result of multiplying the first 5 together. Is there a pythonic way of doing this? Python seems to be great with lists :)
``` import operator l = [1, 2, 3, 4, 5, 6, 7, 8, 9] print reduce(operator.mul, [v for (k, v,) in enumerate(l) if k < 5]) >> 120 ``` Edit: Better way to do it ``` print reduce(operator.mul, l[:5]) >> 120 ```
Removing html tags from a text using Regular Expression in python
2,165,943
6
2010-01-29T23:22:10Z
2,166,133
13
2010-01-30T00:01:34Z
[ "python", "html", "regex", "tags" ]
I'm trying to look at a html file and remove all the tags from it so that only the text is left but I'm having a problem with my regex. This is what I have so far. ``` import urllib.request, re def test(url): html = str(urllib.request.urlopen(url).read()) print(re.findall('<[\w\/\.\w]*>',html)) ``` The html is a simp...
Use [BeautifulSoup](http://stackoverflow.com/questions/tagged/beautifulsoup). Use [lxml](http://stackoverflow.com/questions/tagged/lxml). Do not use [regular expressions](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) to parse HTML. --- Edit 2010-01-...
Python: namedtuple._replace() doesn't work as descrbed in the documentation
2,166,147
19
2010-01-30T00:03:53Z
2,166,158
8
2010-01-30T00:07:17Z
[ "python", "namedtuple" ]
I was having trouble implementing `namedtuple._replace()`, so I copied the code right off of the documentation: ``` Point = namedtuple('Point', 'x,y') p = Point(x=11, y=22) p._replace(x=33) print p ``` and I got: ``` Point(x=11, y=22) ``` instead of: ``` Point(x=33, y=22) ``` as is shown in the doc. I'm using...
[`namedtuple._replace()`](http://docs.python.org/library/collections.html#collections.somenamedtuple._replace) returns a new tuple; the original is unchanged.