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
Numpy `logical_or` for more than two arguments
20,528,328
10
2013-12-11T19:33:29Z
20,528,566
50
2013-12-11T19:48:25Z
[ "python", "numpy", "logical" ]
Numpy's `logical_or` function takes no more than two arrays to compare. How can I find the union of more than two arrays? (The same question could be asked with regard to Numpy's `logical_and` and obtaining the intersection of more than two arrays.)
If you're asking about [`numpy.logical_or`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.logical_or.html), then no, as the docs explicitly say, the only parameters are `x1, x2`, and optionally `out`: > `numpy.`**`logical_or`**(*`x1, x2[, out]`*) = *`<ufunc 'logical_or'>`* --- You can of course chain tog...
Syntax error on the definition of a function in python which seems valid
20,528,815
5
2013-12-11T20:02:11Z
20,528,881
13
2013-12-11T20:05:27Z
[ "python", "sh" ]
When I define a function in this code: ``` def is_palindrome(seq): s=seq[::-1] if s==seq: return True else: return False myfile=open('palindrome.txt','r') for line in myfile: if is_palindrome(line.srtrip()): print(line,end='') myfile.close() ``` It returns this error message...
You're executing your script as a \*sh script. You should do `python palindrome.py` Indeed, the error message you get is typically an error of \*sh script... When you're calling the script via `./palindrome.py`, it executes it with the first interpreter which matches. It seems to be a \*sh interpretor here, from your ...
What is the best way to save image metadata alongside a tif with Python?
20,529,187
8
2013-12-11T20:22:40Z
20,529,932
7
2013-12-11T21:07:20Z
[ "python", "python-imaging-library", "tiff" ]
In my work as a grad student, I capture microscope images and use python to save them as raw tif's. I would like to add metadata such as the name of the microscope I am using, the magnification level, and the imaging laser wavelength. These details are all important for how I post-process the images. I should be able ...
> I should be able to do this with a tif, right? Since it has a header? No. First, your premise is wrong, but that's a red herring. TIFF does have a header, but it doesn't allow you to store arbitrary metadata in it. But TIFF is a tagged file format, a series of chunks of different types, so the header isn't importa...
How to select/reduce a list of dictionaries in Flask/Jinja
20,529,234
11
2013-12-11T20:26:28Z
24,187,114
13
2014-06-12T14:34:44Z
[ "python", "flask", "jinja" ]
I have a Jinja template with a list of dictionaries. Order matters. I'd like to reduce the list or lookup values based on the keys/values of the dictionaries. Here's an example: ``` {% set ordered_dicts = [ { 'id': 'foo', 'name': 'My name is Foo' }, { 'id...
I've just backported `equalto` like this: ``` app.jinja_env.tests['equalto'] = lambda value, other : value == other ``` After that [this example from 2.8 docs](http://jinja.pocoo.org/docs/templates/#equalto) works: ``` {{ users|selectattr("email", "equalto", "[email protected]") }} ``` *Update*: Flask has a decorator...
writing a pytest function to check outputting to a file in python?
20,531,072
5
2013-12-11T22:15:35Z
20,545,394
7
2013-12-12T13:52:34Z
[ "python", "function", "file-io", "py.test" ]
I asked [this](http://stackoverflow.com/questions/20507601/writing-a-pytest-function-for-checking-the-output-on-console-stdout-in-python) question about how to write a pytest to check output in `stdout` and got a solution. Now I need to write a `test case`, to check if the contents are written to the file and that the ...
There is the [tmpdir fixture](http://pytest.org/latest/tmpdir.html) which will create you a per-test temporary directory. So a test would look something like this: ``` def writetoafile(fname): with open(fname, 'w') as fp: fp.write('Hello\n') def test_writetofile(tmpdir): file = tmpdir.join('output.txt...
Python sort array by another positions array
20,531,883
2
2013-12-11T23:10:10Z
20,531,913
7
2013-12-11T23:12:28Z
[ "python", "arrays", "sorting" ]
Assume I have two arrays, the first one containing int data, the second one containing positions `a = [11, 22, 44, 55]` `b = [0, 1, 10, 11]` i.e. I want `a[i]` to be be moved to position `b[i]` `for all i`. If I haven't specified a position, then insert a `-1` i.e ``` sorted_a = [11, 22,-1,-1,-1,-1,-1,-1,-1,-1, 44...
Something like this: ``` res = [-1]*(max(b)+1) # create a list of required size with only -1's for i, v in zip(b, a): res[i] = v ``` The idea behind the algorithm: 1. Create the resulting list with a size capable of holding up to the largest index in `b` 2. Populate this list with `-1` 3. Iterate through `b` ...
Multiple lines of x tick labels in matplotlib
20,532,614
6
2013-12-12T00:14:05Z
20,546,657
7
2013-12-12T14:50:18Z
[ "python", "python-3.x", "matplotlib" ]
I'm trying to make a plot similar to this excel example: ![example](http://i.stack.imgur.com/8iyCF.png) I would like to know if there is anyways to have a second layer on the x tick labels (e.g. "5 Year Statistical Summary"). I know I can make multi-line tick labels using `\n` but I want to be able to shift the two l...
this gets close: ![xtick](http://i.stack.imgur.com/nGlO9.png) ``` fig = plt.figure( figsize=(8, 4 ) ) ax = fig.add_axes( [.05, .1, .9, .85 ] ) ax.set_yticks( np.linspace(0, 200, 11 ) ) xticks = [ 2, 3, 4, 6, 8, 10 ] xticks_minor = [ 1, 5, 7, 9, 11 ] xlbls = [ 'background', '5 year statistical summary', 'future build...
Ubuntu running `pip install` gives error 'The following required packages can not be built: * freetype'
20,533,426
118
2013-12-12T01:35:07Z
20,533,455
176
2013-12-12T01:38:04Z
[ "python", "ubuntu", "python-2.7", "matplotlib", "pip" ]
When performing `pip install -r requirements.txt`, I get the following error during the stage where it is installing `matplotlib`: ``` REQUIRED DEPENDENCIES AND EXTENSIONS numpy: yes [not found. pip may install it below.] dateutil: yes [dateutil was not found. It is required for date ...
No. `pip` will not install system-level dependencies. This means `pip` will not install RPM(s) (*Redhat based systems*) or DEB(s) (*Debian based systems*). To install system dependencies you will need to use one of the following methods depending on your system. **Ubuntu/Debian:** ``` apt-get install libfreetype6-de...
Ubuntu running `pip install` gives error 'The following required packages can not be built: * freetype'
20,533,426
118
2013-12-12T01:35:07Z
24,465,830
112
2014-06-28T10:21:27Z
[ "python", "ubuntu", "python-2.7", "matplotlib", "pip" ]
When performing `pip install -r requirements.txt`, I get the following error during the stage where it is installing `matplotlib`: ``` REQUIRED DEPENDENCIES AND EXTENSIONS numpy: yes [not found. pip may install it below.] dateutil: yes [dateutil was not found. It is required for date ...
I had to install libxft-dev in order to enable matplotlib on ubuntu server 14.04. ``` sudo apt-get install libfreetype6-dev libxft-dev ``` And then I could use ``` sudo easy_install matplotlib ```
Ubuntu running `pip install` gives error 'The following required packages can not be built: * freetype'
20,533,426
118
2013-12-12T01:35:07Z
27,773,719
26
2015-01-05T05:06:02Z
[ "python", "ubuntu", "python-2.7", "matplotlib", "pip" ]
When performing `pip install -r requirements.txt`, I get the following error during the stage where it is installing `matplotlib`: ``` REQUIRED DEPENDENCIES AND EXTENSIONS numpy: yes [not found. pip may install it below.] dateutil: yes [dateutil was not found. It is required for date ...
A workaround is to do `sudo apt-get install pkg-config` which I found [in this github issue](https://github.com/matplotlib/matplotlib/issues/3029/).
How to build a utf8 string in python
20,533,828
2
2013-12-12T02:19:48Z
20,533,833
7
2013-12-12T02:20:22Z
[ "python", "string", "utf-8" ]
I know how to build a string with variables by doing something like this ``` 'this is a {!s} {!}'.format('simple','example') ``` But I couldn't get this to work if one of the variables has a utf8 character. It tells me that 'ascii' codec can't encode character . . .
``` u'this is a {} {}'.format(u'привет', u'мир') ``` As an alternative for Python2.7 you may import `unicode_literals` from `__future__` to mark all strings as unicode by default. In this case to mark some string as ASCII you need to prefix it with `b`: ``` >>> from __future__ import unicode_literals >>> 'th...
Lazy evaluation python
20,535,342
22
2013-12-12T04:55:22Z
20,535,379
27
2013-12-12T04:58:23Z
[ "python", "python-3.x", "lazy-evaluation" ]
what is lazy evaluation in python? one website said : In Python 3.x the range() function returns a special range object which computes elements of the list on demand (lazy or deferred evaluation): ``` >>> r = range(10) >>> print(r) range(0, 10) >>> print(r[3]) 3 ``` what is meant by this ?
The object returned by `range()` (or `xrange()` in Python2.x) is known as a [generator](https://wiki.python.org/moin/Generators). Instead of storing the entire range, `[0,1,2,..,9]`, in memory, the generator stores a definition for `(i=0; i<10; i+=1)` and computes the next value only when needed (AKA lazy-evaluation)....
Opencv python. WaitKey don't respond?
20,539,497
6
2013-12-12T09:24:53Z
28,322,925
7
2015-02-04T13:43:14Z
[ "python", "opencv", "ubuntu-12.04" ]
I'm using opencv 2.4.7 on ubuntu 12.04. I'm programming with python and I have a problem when i run this script: ``` import cv2 img = cv2.imread('347620923614738322_233985812.jpg') cv2.namedWindow("window") cv2.imshow("window", img) cv2.waitKey(0) ``` The problem is that the script doesn't stop when I close the imag...
I found that it works if i press the key whilst the window is in focus. If the command line is in focus then nothing happens
How to find outliers in a series, vectorized?
20,539,777
10
2013-12-12T09:39:01Z
20,603,021
7
2013-12-16T03:33:51Z
[ "python", "numpy", "pandas", "vectorization" ]
I have a pandas.Series of positive numbers. I need to find the indexes of "outliers", whose values depart by `3` or more from the previous "norm". How to vectorize this function: ``` def baseline(s): values = [] indexes = [] last_valid = s.iloc[0] for idx, val in s.iteritems(): if abs(val - la...
Here's my original "vectorized" solution: You can get the `last_valid` using [shift](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.shift.html) and numpy's [where](http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html): ``` In [1]: s = pd.Series([10, 10, 10, 14, 10, 10, 10, 14, 100...
Python Tuple to Dict, with additional list of keys
20,540,871
4
2013-12-12T10:25:52Z
20,540,948
12
2013-12-12T10:29:09Z
[ "python", "list-comprehension", "django-1.5" ]
So I have this array of tuples: ``` [(u'030944', u'20091123', 10, 30, 0), (u'030944', u'20100226', 10, 15, 0)] ``` And I have this list of field names: ``` ['id', 'date', 'hour', 'minute', 'interval'] ``` I would like to, in one fell swoop if possible, to convert the list of tuples to a dict: ``` [{ 'id': u'03...
``` data = [(u'030944', u'20091123', 10, 30, 0), (u'030944', u'20100226', 10, 15, 0)] fields = ['id', 'date', 'hour', 'minute', 'interval'] dicts = [dict(zip(fields, d)) for d in data] ``` To explain, `zip` takes one or more sequences, and returns a sequence of tuples, with the first element of each input sequence, th...
how can i tell if a string contains ONLY digits and spaces in python using regex
20,544,148
4
2013-12-12T12:53:38Z
20,544,177
7
2013-12-12T12:54:48Z
[ "python", "regex", "numbers", "spaces", "digits" ]
I'm trying to write some script in python (using regex) and I have the following problem: I need to make sure that a string contains ONLY digits and spaces but it could contain any number of numbers. Meaning it should match to the strings: "213" (one number), "123 432" (two numbers), and even "123 432 543 3 235 34 56...
This code will check if the string only contains numbers and space character. ``` if re.match("^[0-9 ]+$", myString): print "Only numbers and Spaces" ```
Truncate a decimal value in Python
20,544,714
10
2013-12-12T13:21:32Z
20,544,831
7
2013-12-12T13:27:00Z
[ "python", "formatting", "decimal", "truncate" ]
I am trying to truncate a decimal value in Python. I don't want to round it, but instead just display the decimal values upto the specified accuracy. I tried the following: ``` d = 0.989434 '{:.{prec}f}'.format(d, prec=2) ``` This rounds it to 0.99. But I actually want the output to be 0.98. Obviously, `round()` is n...
I am not aware of all your requirements, but this will be fairly robust. ``` >> before_dec, after_dec = str(d).split('.') >> float('.'.join((before_dec, after_dec[0:2]))) 0.98 ```
Shuffle columns of an array with Numpy
20,546,419
8
2013-12-12T14:40:25Z
20,546,443
10
2013-12-12T14:41:32Z
[ "python", "arrays", "numpy" ]
Let's say I have an array `r` of dimension `(n, m)`. I would like to shuffle the columns of that array. If I use `numpy.random.shuffle(r)` it shuffles the lines. How can I only shuffle the columns? So that the first column become the second one and the third the first, etc, randomly. **Example:** input: ``` array([...
While asking I thought about maybe I could shuffle the transposed array: ``` np.random.shuffle(np.transpose(r)) ``` It looks like it does the job. I'd appreciate comments to know if it's a good way of achieving this.
._GLOBAL_DEFAULT_TIMEOUT occurs on simple urlopen
20,546,491
2
2013-12-12T14:43:42Z
20,546,731
12
2013-12-12T14:53:37Z
[ "python", "sockets", "python-2.7", "error-handling", "timeout" ]
I've got a problem which is this: ``` Sorry Traceback (most recent call last): File "testconn.py", line 2, in <module> import httplib File "C:\Python27\lib\httplib.py", line 680, in <module> class HTTPConnection: File "C:\Python27\lib\httplib.py", line 692, in HTTPConnection timeout=socket._GLOBAL_DEFAULT_TIMEOUT, sou...
Check if you have your own `socket.py` file. That shadows import of standard library `socket` module. Find it, rename(or remove) it. You should also rename(or remove) `socket.pyc`. --- BTW, the following line has a typo ( header **s** ) ``` req = urllib2.Request("http://google.com/", headers = header) # ...
Explode multiple slices of pie together in matplotlib
20,549,016
7
2013-12-12T16:35:39Z
20,556,088
7
2013-12-12T23:04:43Z
[ "python", "matplotlib", "pie-chart" ]
I really like the "explode" option on matplotlib pie charts. I was hoping to be able to "explode in groups". I'm plotting lots of little slices that fall into 3 or 4 categories. I'd like to explode all the little slices together, as groups. I figure that's not entirely clear, so I have called upon my sorely lacking ab...
I'm not aware of any direct way to specify grouped exploded pies, but it is quite simple to use patches to redraw a pie with groups like ``` # original part (left) import numpy as np import matplotlib.pyplot as plt f,ax = plt.subplots(1,2) ax[0].set_aspect('equal') data=np.abs(np.random.randn(7)) wedges, texts = ax[0...
Django Rest Framework - Could not resolve URL for hyperlinked relationship using view name "user-detail"
20,550,598
34
2013-12-12T17:49:04Z
20,553,926
36
2013-12-12T20:48:21Z
[ "python", "django", "user", "django-rest-framework" ]
I am building a project in Django Rest Framework where users can login to view their wine cellar. My ModelViewSets were working just fine and all of a sudden I get this frustrating error: > Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related mode...
Because it's a `HyperlinkedModelSerializer` your serializer is trying to resolve the URL for the related `User` on your `Bottle`. As you don't have the user detail view it can't do this. Hence the exception. 1. Would not just registering the `UserViewSet` with the router solve your issue? 2. You could define the use...
Django Rest Framework - Could not resolve URL for hyperlinked relationship using view name "user-detail"
20,550,598
34
2013-12-12T17:49:04Z
37,178,456
8
2016-05-12T06:02:13Z
[ "python", "django", "user", "django-rest-framework" ]
I am building a project in Django Rest Framework where users can login to view their wine cellar. My ModelViewSets were working just fine and all of a sudden I get this frustrating error: > Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related mode...
I came across this error too and solved it as follows: The reason is I forgot giving "\*\*-detail" (view\_name, e.g.: user-detail) a namespace. So, Django Rest Framework could not find that view. There is one app in my project, suppose that my project name is `myproject`, and the app name is `myapp`. There is two ur...
What's the difference between __iter__ and __getitem__?
20,551,042
9
2013-12-12T18:12:37Z
20,551,346
11
2013-12-12T18:28:30Z
[ "python", "python-2.7", "python-3.x" ]
This happens in Python 2.7.6 and 3.3.3 for me. When I define a class like this ``` class foo: def __getitem__(self, *args): print(*args) ``` And then try to iterate (and what I thought would call iter) on an instance, ``` bar = foo() for i in bar: print(i) ``` it just counts up by one for the args a...
Yes, this is an intended design. It is documented, well-tested, and relied upon by sequence types such as *str*. The \_\_getitem\_\_ version is a legacy before Python had modern iterators. The idea was that any sequence (something that is indexable and has a length) would be automatically iterable using the series s[0...
Changing line properties in matplotlib pie chart
20,551,477
6
2013-12-12T18:35:06Z
20,551,981
10
2013-12-12T19:01:13Z
[ "python", "matplotlib", "pie-chart" ]
I'm trying to make the lines on my matplotlib pie chart much lighter. Because I have so many slices, the lines are way too thick, as shown here: ![enter image description here](http://i.stack.imgur.com/uwQUn.png) I read [this example](http://stackoverflow.com/questions/1915871/matplotlib-controlling-pie-chart-font-co...
try this: ``` ax = plt.subplot(111) wedges, texts = ax.pie(np.abs(np.random.randn(5))) for w in wedges: w.set_linewidth(2) w.set_edgecolor('cyan') ``` ![pie](http://i.stack.imgur.com/qvC4g.png) Additionally, if you only have an `axes` object and don't have direct access to the pie's wedges you can retrieve...
How do I get PyLint to recognize numpy members?
20,553,551
73
2013-12-12T20:27:12Z
25,566,156
16
2014-08-29T10:11:55Z
[ "python", "numpy", "pylint" ]
I am running PyLint on a Python project. PyLint makes many complaints about being unable to find numpy members. How can I avoid this while avoiding skipping membership checks. From the code: ``` import numpy as np print np.zeros([1, 4]) ``` Which, when ran, I get the expected: > [[ 0. 0. 0. 0.]] However, pylint g...
Since this is the top result in google and it gave me the impression that you have to ignore those warnings in all files: The problem has actually been fixed in the sources of pylint/astroid last month <https://bitbucket.org/logilab/astroid/commits/83d78af4866be5818f193360c78185e1008fd29e> but are not yet in the Ubunt...
How do I get PyLint to recognize numpy members?
20,553,551
73
2013-12-12T20:27:12Z
27,943,375
30
2015-01-14T12:50:17Z
[ "python", "numpy", "pylint" ]
I am running PyLint on a Python project. PyLint makes many complaints about being unable to find numpy members. How can I avoid this while avoiding skipping membership checks. From the code: ``` import numpy as np print np.zeros([1, 4]) ``` Which, when ran, I get the expected: > [[ 0. 0. 0. 0.]] However, pylint g...
I had the same issue here, even with the latest versions of all related packages (`astroid 1.3.2`, `logilab_common 0.63.2`, `pylon 1.4.0`). The following solution worked like a charm: I added `numpy` to the list of ignored modules by modifying my `pylintrc` file, in the `[TYPECHECK]` section: ``` [TYPECHECK] ignored...
How do I get PyLint to recognize numpy members?
20,553,551
73
2013-12-12T20:27:12Z
31,465,070
13
2015-07-16T21:45:39Z
[ "python", "numpy", "pylint" ]
I am running PyLint on a Python project. PyLint makes many complaints about being unable to find numpy members. How can I avoid this while avoiding skipping membership checks. From the code: ``` import numpy as np print np.zeros([1, 4]) ``` Which, when ran, I get the expected: > [[ 0. 0. 0. 0.]] However, pylint g...
In recent versions of pylint you can add `--extension-pkg-whitelist=numpy` to your pylint command. They had fixed this problem in an earlier version in an unsafe way. Now if you want them to look more carefully at a package outside of the standard library, you must explicitly whitelist it. [See here.](https://bitbucket...
How do I get PyLint to recognize numpy members?
20,553,551
73
2013-12-12T20:27:12Z
35,259,944
10
2016-02-07T22:29:19Z
[ "python", "numpy", "pylint" ]
I am running PyLint on a Python project. PyLint makes many complaints about being unable to find numpy members. How can I avoid this while avoiding skipping membership checks. From the code: ``` import numpy as np print np.zeros([1, 4]) ``` Which, when ran, I get the expected: > [[ 0. 0. 0. 0.]] However, pylint g...
I was getting the same error for a small numpy project I was working on and decided that ignoring the numpy modules would do just fine. I created a `.pylintrc` file with: `$ pylint --generate-rcfile > ~/.pylintrc` and following paduwan's and j\_houg's advice I modified the following sectors: ``` [MASTER] # A comma-...
Moving between underscore separated words in PyCharm with Alt + ←/→
20,553,964
6
2013-12-12T20:50:10Z
20,553,965
10
2013-12-12T20:50:10Z
[ "python", "pycharm", "shortcuts" ]
In PyCharm when I move between words with the `Alt + ←/→` shortcut it moves the cursor between whitespace separated words. How can I make it move the cursor between `underscore_seperated_words`?
The option is not obvious but if I tick `Editor -> Smart Keys -> Use "CamelHumps" words` then when moving between words with `Alt + ←/→` I can step between underscore separated words rather than just space separated "words". *The same works for camelCase words obviously.*
Is Python 3.3 better than 2.7 for Decoding and Re-Encoding Scraped Web Text to UTF-8?? Like, a lot better?
20,555,142
6
2013-12-12T21:59:24Z
20,555,504
9
2013-12-12T22:22:54Z
[ "python", "python-2.7", "python-3.x", "unicode", "encoding" ]
There are seemingly a million questions involving Python Unicode Errors where the `...ordinal [is] not in range(128)`. Seemingly, the vast majority involve Python 2.x. I know about these errors because I am currently in encoding, decoding hell. For a side-project, I scrape web pages and attempt to normalize that text ...
I'll speak from the point of view of a Python 2.7 user. It's true that Python 3 introduces some big changes on the `Unicode` field. I won't say it is easier to work with `encodings` in Python 3, but it's indeed more reasonable for doing i18n stuff. Like I said, I use Python 2.7 and so far I've been able to handle eve...
Generate equation with the result value closest to the requested one, have speed problems
20,555,559
15
2013-12-12T22:26:07Z
20,598,709
9
2013-12-15T19:23:46Z
[ "python", "performance", "algorithm", "permutation", "np" ]
I am writing some quiz game and need computer to solve 1 game in the quiz if players fail to solve it. Given data : 1. List of 6 numbers to use, for example 4, 8, 6, 2, 15, 50. 2. Targeted value, where 0 < value < 1000, for example 590. 3. Available operations are division, addition, multiplication and division. 4. P...
You can build all the possible expression trees with the given numbers and evalate them. You don't need to keep them all in memory, just print them when the target number is found: First we need a class to hold the expression. It is better to design it to be immutable, so its value can be precomputed. Something like t...
`pip install pandas` gives UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 41: ordinal not in range(128)
20,555,761
16
2013-12-12T22:40:00Z
20,557,179
8
2013-12-13T00:44:49Z
[ "python", "ubuntu", "pip", "python-2.x", "digital-ocean" ]
When performing `pip install pandas` on a Digital Ocean 512MB droplet, I get the error `UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 41: ordinal not in range(128)`. Any ideas what may have caused it? I'm running Ubuntu 12.04 64bit. [[Full Error]](https://gist.github.com/anonymous/7936900)
It looks like gcc being killed due to insufficient memory (see [@Blender's comment)](http://stackoverflow.com/questions/20555761/pip-install-pandas-gives-unicodedecodeerror-ascii-codec-cant-decode-byte-0#comment30742213_20555761) exposed a bug in pip. It mixes bytestrings and Unicode while logging that leads to: ``` >...
Queue Class, dequeue and enqueue ? python
20,557,440
2
2013-12-13T01:15:34Z
20,557,495
8
2013-12-13T01:22:24Z
[ "python", "class", "methods", "queue" ]
So I have this question and it says create a class queue and make the method dequeue and enqueue Here's what I have so far, could someone direct me on the right track? ``` class queue: def __init__(self,queue): self.queue = [] def dequeue(self): if len(queue) > 0: ...
There are a few problems here. * `queue` by itself refers to your *class*, not to the instance's attribute with the same name, which is `self.queue`. You have to use the `self.` all the time. And it would really help to give the class and its attribute different names, to avoid this confusion. (It would also help to u...
Opening Local File Works with urllib but not with urllib2
20,558,587
13
2013-12-13T03:29:30Z
20,558,624
16
2013-12-13T03:33:06Z
[ "python", "urllib2", "urllib" ]
I'm trying to open a local file using urllib2. How can I go about doing this? When I try the following line with urllib: ``` resp = urllib.urlopen(url) ``` it works correctly, but when I switch it to: ``` resp = urllib2.urlopen(url) ``` I get: ``` ValueError: unknown url type: /path/to/file ``` where that file de...
Just put `"file://"` in front of the path ``` >>> import urllib2 >>> urllib2.urlopen("file:///etc/debian_version").read() 'wheezy/sid\n' ```
Python: How RECURSIVELY remove None values from a NESTED data structure (lists and dictionaries)?
20,558,699
7
2013-12-13T03:42:54Z
20,558,778
9
2013-12-13T03:53:13Z
[ "python", "list", "python-2.7", "dictionary", "recursion" ]
Here is some nested data, that includes lists, tuples, and dictionaries: ``` data1 = ( 501, (None, 999), None, (None), 504 ) data2 = { 1:601, 2:None, None:603, 'four':'sixty' } data3 = OrderedDict( [(None, 401), (12, 402), (13, None), (14, data2)] ) data = [ [None, 22, tuple([None]), (None,None), None], ( (None, 202),...
If you can assume that the `__init__` methods of the various subclasses have the same signature as the typical base class: ``` def remove_none(obj): if isinstance(obj, (list, tuple, set)): return type(obj)(remove_none(x) for x in obj if x is not None) elif isinstance(obj, dict): return type(obj)((remove_no...
Python: How RECURSIVELY remove None values from a NESTED data structure (lists and dictionaries)?
20,558,699
7
2013-12-13T03:42:54Z
35,262,767
8
2016-02-08T05:17:42Z
[ "python", "list", "python-2.7", "dictionary", "recursion" ]
Here is some nested data, that includes lists, tuples, and dictionaries: ``` data1 = ( 501, (None, 999), None, (None), 504 ) data2 = { 1:601, 2:None, None:603, 'four':'sixty' } data3 = OrderedDict( [(None, 401), (12, 402), (13, None), (14, data2)] ) data = [ [None, 22, tuple([None]), (None,None), None], ( (None, 202),...
If you want a full-featured, yet succinct approach to handling real-world nested data structures like these, and even handle cycles, I recommend looking at [the remap utility from the boltons utility package](http://boltons.readthedocs.org/en/latest/iterutils.html#nested). After `pip install boltons` or copying [iteru...
How to deploy structured Flask app on AWS elastic beanstalk
20,558,747
4
2013-12-13T03:49:31Z
20,574,036
7
2013-12-13T19:01:50Z
[ "python", "amazon-web-services", "flask", "elastic-beanstalk" ]
After successfully deploying a test app using the steps outlined here: <http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_Python_flask.html> I tried to deploy my actual flask application which has the following structure: ``` myApp/ runServer.py requirements.txt myApp/ __init__.py ...
Add the following to `.ebextensions/<env-name>.config`: ``` option_settings: "aws:elasticbeanstalk:container:python": WSGIPath: myApp/handlers/views.py ``` **Update:** If you don't have .ebextensions directory, please create one for the project. You can find more information of what can be done regarding the c...
python no module named serial
20,559,457
3
2013-12-13T05:06:03Z
20,560,497
10
2013-12-13T06:34:38Z
[ "python", "database", "sqlite" ]
I am having a problem with my python program. I wrote the program to get the data(temperature) from arduino to my raspberry pi sqlite database. but it gives me an error at line4(import serial) saying "ImportError: No module named serial". I use python3 and have already updated the pyserial. i am new in python so i am m...
Here's a question about [How to install pip with Python 3?](http://stackoverflow.com/questions/6587507/how-to-install-pip-with-python-3). After that, you could use `pip` to install `pyserial` compatible with python-3.x, like the following: ``` $ sudo pip3 install pyserial ``` Here is a [doc](http://pyserial.sourcefor...
Find all text files not containing some text string
20,560,795
7
2013-12-13T06:58:00Z
20,592,257
12
2013-12-15T07:27:21Z
[ "python", "list", "python-2.7" ]
I'm on **Python 2.7.1** and I'm trying to identify all text files that **don't** contain some text string. The program seemed to be working at first but whenever I add the text string to a file, it keeps coming up as if it doesn't contain it (false positive). When I check the contents of the text file, the string is c...
Modifying element while iterating the list cause unexpected results: For example: ``` >>> lst = [1,2,4,6,3,8,0,5] >>> for n in lst: ... if n % 2 == 0: ... lst.remove(n) ... >>> lst [1, 4, 3, 0, 5] ``` **Workaround** iterate over copy ``` >>> lst = [1,2,4,6,3,8,0,5] >>> for n in lst[:]: ... if n % 2 ...
Use StringIO as stdin with Popen
20,568,107
9
2013-12-13T13:48:50Z
20,568,726
8
2013-12-13T14:19:42Z
[ "python", "subprocess" ]
I have the following shell script that I would like to write in Python (of course `grep .` is actually a much more complex command): ``` #!/bin/bash (cat somefile 2>/dev/null || (echo 'somefile not found'; cat logfile)) \ | grep . ``` I tried this (which lacks an equivalent to `cat logfile` anyway): ``` #!/usr/bin/...
``` p = subprocess.Popen(['grep', '...'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) output, output_err = p.communicate(myfile.read()) ```
Python handling socket.error: [Errno 104] Connection reset by peer
20,568,216
31
2013-12-13T13:53:47Z
20,568,874
62
2013-12-13T14:27:16Z
[ "python", "ubuntu", "python-2.7", "urllib2" ]
When using Python 2.7 with `urllib2` to retrieve data from an API, I get the error `[Errno 104] Connection reset by peer`. Whats causing the error, and how should the error be handled so that the script does not crash? **ticker.py** ``` def urlopen(url): response = None request = urllib2.Request(url=url) ...
> "Connection reset by peer" is the TCP/IP equivalent of slamming the phone back on the hook. It's more polite than merely not replying, leaving one hanging. But it's not the FIN-ACK expected of the truly polite TCP/IP converseur. ([From other SO answer](http://stackoverflow.com/a/1434506/816449)) So you can't do anyt...
"if variable not in list" not working returning true all the time
20,568,336
2
2013-12-13T13:59:13Z
20,568,384
12
2013-12-13T14:01:41Z
[ "python", "if-statement", "return" ]
Why is this line of code always returning true? ``` def GetPlayersMove(self): self.move = input("Enter Rock, Paper or Scissors: ") if self.move.lower() not in ["rock" "paper", "scissors"]: print("Error") ```
The code is missing `,`. ``` ["rock" "paper", "scissors"] # ^ ``` `"rock" "paper"` is equivalent to `"rockpaper"`: ``` >>> ["rock" "paper", "scissors"] ['rockpaper', 'scissors'] >>> ``` See [String literal concatenation](http://docs.python.org/2/reference/lexical_analysis.html#string-literal-concatenation)
is there any way to prevent side effects in python?
20,569,142
7
2013-12-13T14:42:04Z
20,569,793
7
2013-12-13T15:14:17Z
[ "python", "functional-programming", "side-effects" ]
Is there any way to prevent side effects in python? For example, the following function has a side effect, is there any keyword or any other way to have the python complain about it? ``` def func_with_side_affect(a): a.append('foo') ```
Python is really not set up to enforce prevention of side-effects. As some others have mentioned, you can try to `deepcopy` the data or use immutable types, but these still have corner cases that are tricky to catch, and it's just a ton more effort than it's worth. Using a functional style in Python normally involves ...
Python decorator for class
20,569,451
3
2013-12-13T14:57:58Z
20,570,066
7
2013-12-13T15:27:00Z
[ "python", "decorator" ]
I try do this: ``` import unittest def decorator(cls): class Decorator(cls): def __init__(self, *args, **kwargs): super(Decorator, self).__init__(*args, **kwargs) return Decorator @decorator class myClass(unittest.TestCase): def __init__(self, *args, **kwargs): super(myClass,...
You cannot use `super(myClass, self)` within a decorated class in this way. `myClass` is looked up as a global, and the global `myClass` is *rebound* to `Decorator`, so you are telling Python to look in the class MRO for `__init__` starting from `Decorator` which is `myClass`, which calls `super(myClass, self).__init_...
Importing flask.ext.wtf
20,569,699
7
2013-12-13T15:10:24Z
20,578,797
13
2013-12-14T01:49:07Z
[ "python", "flask", "packages", "flask-wtforms", "python-venv" ]
I am using venv, and I develop using eclipse . I want to add a contact page . I did : ``` $ . bin/activate $ pip install flask-wtf ``` And I import some modules in the forms.py : I used this : ``` from flask.ext.wtf import Form, TextField, TextAreaField, SubmitField ``` and then this : ``` from flask.ext.wtf imp...
What version of flask-wtf did you install? Since version 9 you do all of the field imports from WTForms not from Flask-WTF. So your imports will be (note that according to [`docs`](https://flask-wtf.readthedocs.org/en/latest/quickstart.html) import statement was changed): ``` from flask_wtf import Form from wtforms i...
Selecting a column on a multi-index pandas DataFrame
20,570,626
6
2013-12-13T15:55:45Z
20,571,963
10
2013-12-13T16:59:30Z
[ "python", "matplotlib", "pandas", "multi-index" ]
Given this DataFrame: ``` from pandas import DataFrame arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo'], ['one', 'two', 'one', 'two', 'one', 'two']] tuples = zip(*arrays) index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second']) df = DataFrame(randn(3, 6), index=[1, 2, 3], columns=index) ``` ...
Start with dataframe of form ``` >>> df first bar baz foo second one two one two one two 1 0.085930 -0.848468 0.911572 -0.705026 -1.284458 -0.602760 2 0.385054 2.539314 0.589164 0.765126 0.210199 -0.481789 3 -0.352475 -0.9...
Constructing a co-occurrence matrix in python pandas
20,574,257
14
2013-12-13T19:15:32Z
20,574,460
15
2013-12-13T19:28:57Z
[ "python", "pandas", "statistics" ]
I know you how to do this in [R](http://stackoverflow.com/questions/10622730/constructing-a-co-occurrence-matrix-from-dummycoded-observations-in-r). But, is there any functions in pandas that transforms a dataframe to an nxn co-occurrence matrix containing the counts of two aspects co-occurring. For example an matrix ...
It's a simple linear algebra, you multiply matrix with its transpose (your example contains strings, don't forget to convert them to integer): ``` >>> df_asint = df.astype(int) >>> coocc = df_asint.T.dot(df_asint) >>> coocc Dop Snack Trans Dop 4 2 3 Snack 2 3 2 Trans 3 2 ...
multiprocessing - reading big input data - program hangs
20,574,810
7
2013-12-13T19:50:34Z
20,575,275
8
2013-12-13T20:19:09Z
[ "python", "multiprocessing", "generator", "embarrassingly-parallel" ]
I want to run parallel computation on some input data which is loaded from a file. (The file can be really big, so I use a generator for this.) On a certain number of items, my code runs OK but above this threshold the program hangs (some of the worker processes do not end). Any suggestions? (I am running this with p...
This is because nothing in your code takes anything *off* `result_queue`. The behavior then depends on internal queue buffering details: if "not a lot" of data is waiting, everything appears fine, but if "a lot" of data is waiting, everything freezes. Not much more can be said, because it involves layers of internal ma...
Pandas datetime column to ordinal
20,576,618
4
2013-12-13T21:49:55Z
20,576,734
7
2013-12-13T21:57:40Z
[ "python", "datetime", "pandas" ]
I'm trying to create a new Pandas dataframe column with ordinal day from a datetime column: ``` import pandas as pd from datetime import datetime print df.ix[0:5] date file gom3_197801.nc 2011-02-16 00:00:00 gom3_197802.nc 2011-02-16 00:00:00 gom3_197803.nc ...
Use apply: ``` df['date'].apply(lambda x: x.toordinal()) ```
python dictionary sorting in descending order based on values
20,577,840
10
2013-12-13T23:38:24Z
20,577,876
24
2013-12-13T23:41:56Z
[ "python", "dictionary" ]
I want to sort this dictionary d based on value of sub key key3 in descending order. See below: ``` d = { '123': { 'key1': 3, 'key2': 11, 'key3': 3 }, '124': { 'key1': 6, 'key2': 56, 'key3': 6 }, '125': { 'key1': 7, 'key2': 44, 'key3': 9 }, } ``` So final dictionary would look like this. ``` d = { '1...
[Dictionaries do not have any inherent order](http://docs.python.org/3/library/stdtypes.html#dictionary-view-objects). Or, rather, their inherent order is "arbitrary but not random", so it doesn't do you any good. In different terms, your `d` and your `e` would be exactly equivalent dictionaries. What you can do here...
Python: What's the "Pythonic" way to process two lists?
20,578,102
3
2013-12-14T00:09:05Z
20,578,134
8
2013-12-14T00:12:04Z
[ "python", "list", "list-comprehension" ]
Say I have this code in Python. I'm a Perl programmer, as you may be able to tell. ``` # Both list1 and list2 are a list of strings for x in list1: for y in list2: if y in x: return True return False ``` What's a more Pythonic way to handle this? I assume a list comprehension could do it well, but I can't...
To convert two nested loops into a nested comprehension, you just do this: ``` [<expression> for x in list1 for y in list2] ``` If you've never thought through how list comprehensions work, the tutorial [explains it](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions): > A list comprehension c...
Python: requests module throws exception with Gevent
20,580,252
5
2013-12-14T06:07:05Z
20,580,706
7
2013-12-14T07:13:45Z
[ "python", "http", "exception", "python-requests", "gevent" ]
The following code: ``` import gevent import gevent.monkey gevent.monkey.patch_socket() import requests import json base_url = 'https://api.getclever.com' section_url = base_url + '/v1.1/sections' #get all sections sections = requests.get(section_url, auth=('DEMO_KEY', '')).json() urls = [base_url+data['uri']+'/stu...
Here's a similar question: [[Errno 2] \_ssl.c:504: The operation did not complete (read)](https://github.com/kennethreitz/requests/issues/1480#issuecomment-22604424). When you comment out ``` gevent.monkey.patch_socket() ``` or use ``` gevent.monkey.patch_all() ``` or use ``` gevent.monkey.patch_socket() gevent.m...
Python & URLLIB2 - Request webpage but don't wait for response
20,580,896
4
2013-12-14T07:41:46Z
20,580,957
7
2013-12-14T07:49:52Z
[ "python", "urllib2" ]
In python, how would I go about making a http request but not waiting for a response. I don't care about getting any data back, I just need to server to register a page request. Right now I use this code: ``` urllib2.urlopen("COOL WEBSITE") ``` But obviously this pauses the script until a a response is returned, I j...
What you want here is called **Threading** or **Asynchronous**. **Threading**: * Wrap the call to `urllib2.urlopen()` in a `threading.Thread()` Example: ``` from threading import Thread def open_website(url): return urllib2.urlopen(url) Thread(target=open_website, args=["http://google.com"]).start() ``` **As...
Boost.Python: How to expose std::unique_ptr
20,581,679
16
2013-12-14T09:34:10Z
20,738,438
10
2013-12-23T06:56:42Z
[ "python", "c++", "c++11", "unique-ptr", "boost-python" ]
I am fairly new to boost.python and trying to expose the return value of a function to python. The function signature looks like this: ``` std::unique_ptr<Message> someFunc(const std::string &str) const; ``` When calling the function in python, I get the following error: ``` TypeError: No to_python (by-value) conv...
In short, Boost.Python does not support move-semantics, and therefore does not support `std::unique_ptr`. Boost.Python's [news/change log](http://www.boost.org/doc/libs/1_55_0/libs/python/doc/news.html) has no indication that it has been updated for C++11 move-semantics. Additionally, this [feature request](https://svn...
ImportError: No module named backend_tkagg
20,582,384
6
2013-12-14T10:55:40Z
22,898,493
7
2014-04-06T18:58:30Z
[ "python", "numpy", "module", "pycharm", "python-module" ]
I have such imports and code: ``` import pandas as pd import numpy as np import statsmodels.formula.api as sm import matplotlib.pyplot as plt #Read the data from pydatasets repo using Pandas url = './file.csv' white_side = pd.read_csv(url) #Fitting the model model = sm.ols(formula='budget ~ article_size'...
I use openSuse 13.1 and had the same error "ImportError: No module named backend\_tkagg". I solved it by using this suggestion: <http://forums.opensuse.org/showthread.php/416182-Python-matplolib>. I've installed the python-matplotlib-tk package, and now it is working just fine. E.g. you can use: `zypper install pyth...
python.h not fond when trying to install gevent-socketio
20,582,707
7
2013-12-14T11:28:00Z
20,582,718
12
2013-12-14T11:29:18Z
[ "python", "django", "gevent-socketio" ]
here is my error when I try to install gevent-socketio > Installing collected packages: gevent, greenlet > Running setup.py install for gevent > building 'gevent.core' extension > gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes >-fPIC -DLIBEV\_EMBED=1 -DEV\_COMMON= -DEV\_CHECK\_ENAB...
Install the **Development Package(s)**: **CentOS/RHEL**:: ``` yum install python-devel ``` **Debian/Ubuntu:** ``` apt-get install python-dev ```
Why is print so slow in Python 3.3 and how can I fix it?
20,584,047
14
2013-12-14T13:44:16Z
20,584,219
12
2013-12-14T14:00:29Z
[ "python", "performance", "unicode", "python-3.3" ]
I just tried to run this script with Python 3.3. Unfortunately it's about twice as slow than with Python 2.7. ``` #!/usr/bin/env python from sys import stdin def main(): for line in stdin: try: fields = line.split('"', 6) print(fields[5]) except: pass if __nam...
Python 3 decodes data read from `stdin` and encodes again to `stdout`; it is not so much the `print()` function that is slower here as the unicode-to-bytes conversion and vice-versa. In your case you probably want to bypass this and deal with bytes only; you can access the underlying `BufferedIOBase` implementation th...
How do I create a Python CLR procedure in SQL Server?
20,584,374
2
2013-12-13T20:34:59Z
20,584,375
7
2013-12-14T01:19:17Z
[ "sql-server", "python" ]
We want to call some python from tsql on sql server 2008. The python script is fully developed and works great. We cannot trigger anything from the client app because it is closed source and cannot be modified. So we have full access to SQL Server (2005 and 2008), and can see that "trigger" record get inserted... and...
**[EDIT] Per Paul White's comment, IronPython (and anything else that relies on dynamically-generated code) cannot be used inside a SQLCLR object.** Which makes the following statement incorrect. I will leave it here for future visitors. > In order to use Python to program SQL CLR objects, you will need to use IronPy...
Python precision in string formatting with float numbers
20,586,011
5
2013-12-14T17:16:53Z
20,586,479
11
2013-12-14T18:00:38Z
[ "python", "string", "floating-point" ]
I don't understand why, by formatting a string containing a float value, the precision of this last one is not respected. Ie: ``` '%f' % 38.2551994324 ``` returns: ``` '38.255199' ``` (4 signs lost!) At the moment I solved specifying: ``` '%.10f' % 38.2551994324 ``` which returns '38.2551994324' as expected… b...
*but should I really force manually how many decimal numbers I want?* Yes. And even with specifying 10 decimal digits, you are still not printing all of them. Floating point numbers don't have that kind of precision anyway, they are mostly *approximations* of decimal numbers (they are really binary fractions added up)...
"with" statement in python, why must the "as" section be a single object
20,588,708
6
2013-12-14T21:57:38Z
20,588,747
26
2013-12-14T22:01:02Z
[ "python", "with-statement", "contextmanager" ]
With Python one can say: ``` a,b,c=something_that_returns_a_3_tuple() ``` But a `with` statement like: ``` class thing(object): def __enter__(self): return (1,2,3) def __exit__(self,a,b,c): pass with thing() as a,b,c: print a print b print c ``` will not work work One must ha...
You cannot use a tuple target *without parenthesis* in the syntax, because otherwise you cannot distinguish between multiple *context managers*: ``` with contextmanager1 as target1, contextmanager2 as target2: ``` See the comma there? Because the grammar allows for specifying multiple context managers, the compiler c...
override truediv in python
20,589,436
3
2013-12-14T23:25:51Z
20,589,453
7
2013-12-14T23:28:51Z
[ "python", "methods", "override", "division" ]
In Python 2.7.5 I tried the following: ``` class compl1: def __mul__(A,B): adb=56 return adb def __truediv__(A,B): adb=56 return adb u=compl1() z=compl1() print u*z print u/z ``` Why does only u\*z work, while u/z gives: ``` TypeError: unsupported operand type(s) for /: 'in...
In Python 2, unless you add: ``` from __future__ import division ``` the `__truediv__` hook is not used. Normally `__div__` is used instead: ``` >>> class compl1: ... def __div__(self, B): ... return 'division' ... def __truediv__(self, B): ... return 'true division' ... >>> compl1() / compl...
SyntaxError when using cx_freeze on PyQt app
20,590,113
4
2013-12-15T01:03:49Z
20,590,114
9
2013-12-15T01:03:49Z
[ "python", "python-3.x", "pyqt", "cx-freeze" ]
This is quite annoying problem that occurs when trying to build .exe file from Python 3 script using PyQt4. I think it is connected with using `uic` module for dynamic loading of `.ui` files. `cx_freeze` returns: ``` File "E:\Python32_32\lib\site-packages\cx_Freeze\finder.py", line 366, in _LoadModule module.cod...
Problem lies in fact that `cx_freeze` tries to use `uic` submodule for Python 2, not 3 and encounters Py3-incompatible syntax in one of files. Solution is quite simple: Find `uic` directory, it should be located in `your_python_dir\Lib\site-packages\PyQt4\uic`. There are two directories there: `port_v2` and `port_v3`....
Python, BeautifulSoup - <div> text and <img> attributes in correct order
20,590,624
5
2013-12-15T02:36:46Z
20,590,676
7
2013-12-15T02:45:58Z
[ "python", "html", "beautifulsoup" ]
I have a short piece of HTML that I would like to run through using BeautifulSoup. I've got basic navigation down, but this one has me stumped. Here's an example piece of HTML (totally made it up): ``` <div class="textbox"> Buying this item will cost you <img align="adsbottom" alt="1" src="/1.jpg;type=symbol...
You can loop through all children of a tag, including text; test for their type to see if they are `Tag` or `NavigableString` objects: ``` from bs4 import Tag result = [] for child in html.find('div', class_='textbox').children: if isinstance(child, Tag): result.append(child.get('alt', '')) else: ...
Bad operand type for unary +: 'str'
20,591,385
2
2013-12-15T05:04:13Z
20,721,293
10
2013-12-21T16:52:37Z
[ "python", "operands" ]
I cannot figure out a problem I am having with code written in Python 2.7. I am converting the references to ints, but I keep getting a type exception `bad operand type for unary +: 'str'`. Can anyone assist? ``` import urllib2 import time import datetime stocksToPull = 'EBAY', 'AAPL' def pullData(stock): try: ...
You say that `if int(splitLine[0]) > int(lastUnix):` is causing the trouble, but you don't actually show anything which suggests that. I think this line is the problem instead: ``` print 'Pulled', + stock ``` Do you see why this line could cause that error message? You want either ``` >>> stock = "AAAA" >>> print 'P...
Why aren't POST names with Unicode sent correctly when using multipart/form-data?
20,591,599
3
2013-12-15T05:43:57Z
20,592,910
15
2013-12-15T09:05:18Z
[ "python", "http", "unicode", "python-requests", "multipartform-data" ]
I want to sent a POST request with a file attached, though some of the field names have Unicode characters in them. But they aren't received correctly by the server, as seen below: ``` >>> # normal, without unicode >>> resp = requests.post('http://httpbin.org/post', data={'snowman': 'hello'}, files={('kitten.jpg', ope...
From the wireshark comments, it looks like python-requests is doing it wrong, but that there might not be a "right answer". [RFC 2388](http://tools.ietf.org/html/rfc2388) says > Field names originally in non-ASCII character sets may be encoded within the value of the "name" parameter using the standard method describ...
Count occurence in a list with time complexity of O(nlogn)
20,591,831
5
2013-12-15T06:21:00Z
20,591,850
7
2013-12-15T06:23:10Z
[ "python", "list", "python-3.x" ]
This is what I have so far: ``` alist=[1,1,1,2,2,3,4,2,2,3,2,2,1] def icount(alist): adic={} for i in alist: adic[i]=alist.count(i) return adic print(icount(alist)) ``` I did some research to find out that the time complexity of list.count() is O(n), thus , this code will be O(n^2). Is there a w...
You can use `Counter` like this ``` from collections import Counter alist=[1,1,1,2,2,3,4,2,2,3,2,2,1] print Counter(alist) ``` If you want to use your solution, you can improve it like this ``` def icount(alist): adic = {} for i in alist: adic[i] = adic.get(i, 0) + 1 return adic ``` Even better,...
How to iterate and update documents with PyMongo?
20,592,404
3
2013-12-15T07:52:53Z
20,597,593
7
2013-12-15T17:38:09Z
[ "python", "mongodb", "pymongo" ]
I have a simple, single-client setup for MongoDB and PyMongo 2.6.3. The goal is to iterate over each document in the collection `collection` and update (`save`) each document in the process. The approach I'm using looks roughly like: ``` cursor = collection.find({}) index = 0 count = cursor.count() while index != coun...
Found the answer in MongoDB [documentation](http://docs.mongodb.org/manual/core/cursors/): > Because the cursor is not isolated during its lifetime, intervening write operations on a document may result in a cursor that returns a document more than once if that document has changed. To handle this situation, see the i...
7-bits up to 0xEF
20,594,475
8
2013-12-15T12:26:03Z
20,594,551
10
2013-12-15T12:34:53Z
[ "python", "python-3.x", "unicode" ]
While researching Unicode issues in Python3, I can across this [often-quoted document](http://python-notes.curiousefficiency.org/en/latest/python3/text_file_processing.html) which lays out the initial ideas behind Python3 Unicode support. A quote from that page: > For historical reasons, the most widely used encoding ...
Yes, `0xEF` appears to be a simple typo. The section makes perfect sense with that replaced by `0x7F`.
Installing Pillow for Python on Windows
20,596,204
5
2013-12-15T15:32:18Z
20,597,007
11
2013-12-15T16:44:21Z
[ "python", "windows", "python-3.x", "python-imaging-library", "pillow" ]
I am fairly new to Python and trying to install the Pillow package on Windows 7. I downloaded and ran the MS Windows installer Pillow-2.2.1.win-amd64-py3.3.exe from [here](https://pypi.python.org/pypi/Pillow/2.2.1#downloads). It appeared to install fine. If I run the simple line of code: ``` from PIL import Image ``` ...
For third-party modules for Windows, my go-to resource is Christoph Gohlke's [Python Extension Packages for Windows](http://www.lfd.uci.edu/~gohlke/pythonlibs/). You can find the latest version of Pillow [here](http://www.lfd.uci.edu/~gohlke/pythonlibs/#pillow). Make sure you're working with the python.org version of P...
Python Exception in thread Thread-1 (most likely raised during interpreter shutdown)?
20,596,918
11
2013-12-15T16:37:16Z
20,598,791
23
2013-12-15T19:32:10Z
[ "python", "multithreading", "numpy", "queue", "pygame" ]
My friend and I have been working on a large project to learn and for fun in python and PyGame. Basically it is an AI simulation of a small village. we wanted a day/night cycle so I found a neat way to change the color of an entire surface using numpy (specifically the cross-fade tutorial) - <http://www.pygame.org/docs...
This is pretty common when using daemon threads. Why are you setting `.daemon = True` on your threads? Think about it. While there are legitimate uses for daemon threads, *most* times a programmer does it because they're confused, as in "I don't know how to shut my threads down cleanly, and the program will freeze on e...
Python Variable Naming vs C++ Variable Naming
20,597,557
2
2013-12-15T17:34:31Z
20,597,637
8
2013-12-15T17:41:40Z
[ "python" ]
I am starting to get deeper in learning Python and having a great time doing it but there is one thing that is bothering me. Why is it in C++ answers/tutorial/books are variables namedLikeThis and in Python they are named\_like\_this? Is this just personal preference or is it a convention that should be followed for r...
People writing Python generally follow PEP8 (<http://www.python.org/dev/peps/pep-0008/>).
re/regex pattern for string python
20,598,241
3
2013-12-15T18:44:32Z
20,598,261
8
2013-12-15T18:46:27Z
[ "python", "regex" ]
I'm trying to figure out a regex pattern to find all occurrences in a string for this: ``` string = "List[5] List[6], List[10], List[100:] List[-2:] List[-2]" re.findall("List[(.*?)]" , string) # Expected output ['5', '6', '10', '100:', '-2:', '-2'] # Output: [] ``` What would be a good regex pattern to get the numb...
Square brackets are special characters in [Regex's syntax](http://docs.python.org/2/library/re.html#regular-expression-syntax). So, you need to escape them: ``` >>> import re >>> string = "List[5] List[6], List[10], List[100:] List[-2:] List[-2]" >>> re.findall("List\[(.*?)\]", string) ['5', '6', '10', '100:', '-2:', ...
How to use scrapy to crawl multiple pages?
20,598,606
6
2013-12-15T19:13:49Z
20,601,740
9
2013-12-16T00:36:02Z
[ "python", "scrapy" ]
All examples i found of Scrapy talk about how to crawl a single page, pages with the same url schema or all the pages of a website. I need to crawl series of pages A, B, C where in A you got the link to B and so on.. For example the website structure is: ``` A ----> B ---------> C D E ``` I need to crawl all the C pa...
see [scrapy Request structure](http://doc.scrapy.org/en/latest/topics/request-response.html#request-objects), to crawl such chain you'll have to use the callback parameter like the following: ``` class MySpider(BaseSpider): ... # spider starts here def parse(self, response): ... # A, D, E a...
Splitting comma delimited strings in python
20,599,233
9
2013-12-15T20:12:23Z
20,599,372
9
2013-12-15T20:27:26Z
[ "python", "regex", "string", "split" ]
This question has been asked and answered many times before. Some examples: [[1]](http://stackoverflow.com/q/4998629/788553), [[2]](http://stackoverflow.com/q/4982531/788553). But there doesn't seem to be something somewhat more general. What I'm looking for is for a way to split strings at commas that are not within q...
While it's not possible to use a Regular Expression, the following simple code will achieve the desired result: ``` def split_at(text, delimiter, opens='<([', closes='>)]', quotes='"\''): result = [] buff = "" level = 0 is_quoted = False for char in text: if char in delimiter and level == ...
What is the purpose of checking self.__class__ ? - python
20,599,375
4
2013-12-15T20:27:34Z
20,688,458
8
2013-12-19T17:52:50Z
[ "python", "class", "oop", "interface", "self" ]
What is the purpose of checking `self.__class__` ? I've found some code that creates an abstract interface class and then checks whether its `self.__class__` is itself, e.g. ``` class abstract1 (object): def __init__(self): if self.__class__ == abstract1: raise NotImplementedError("Interfaces can't be ins...
`self.__class__` is a reference to the *type* of the current instance. For instances of `abstract1`, that'd be the `abstract1` class *itself*, which is what you don't want with an abstract class. Abstract classes are only meant to be subclassed, not to create instances directly: ``` >>> abstract1() Traceback (most re...
Simple customization of matplotlib/pandas bar chart (labels, ticks, etc.)
20,600,006
4
2013-12-15T21:27:07Z
20,600,378
7
2013-12-15T22:02:20Z
[ "python", "matplotlib", "pandas" ]
I am new to matplotlib and I am trying to use it within pandas to plot some simple charts. I have a DataFrame that contains two labels "score" and "person", derived from another DF. ``` df1 = DataFrame(df, columns=['score','person']) ``` Producing this output: ![table output](http://i.stack.imgur.com/o61hu.png) I a...
I guess this will give you the idea: ``` df = pd.DataFrame({'score':np.random.randn(6), 'person':[x*3 for x in list('ABCDEF')]}) ax = plt.subplot(111) df.score.plot(ax=ax, kind='barh', color=list('rgbkym'), title='ranking') ax.axis('off') for i, x in enumerate(df.person): ax.text(0, i + .5, x, ...
How do I calculate the angle between the hour and minutes hands?
20,601,427
6
2013-12-15T23:50:47Z
20,601,672
13
2013-12-16T00:27:36Z
[ "python", "math", "clock" ]
I'm trying to workout this problem, but I am still struggling to understand the logic to solve this problem. ``` hour degree = 360 / 12 = 30 minutes degree = 360 / 12 / 60 = 0.5 ``` So, according to this, I thought I could formulate the following function in python: ``` def clockangles(hour, min): return (hour *...
Okay. You are trying to find the angle between the two hands. Then this: ``` minutes degree = 360 / 12 / 60 = 0.5 ``` Is just the number of degrees the *hour* hand moves per minute. Think about it - the minute hand travels a full 360 each hour. Therefore there are only 60 minutes in a full revolution. 360/60 = 6 degr...
Append column to pandas dataframe
20,602,947
4
2013-12-16T03:23:41Z
20,603,020
9
2013-12-16T03:33:50Z
[ "python", "pandas" ]
This is probably easy, but I have the following data: In data frame 1: ``` index dat1 0 9 1 5 ``` In data frame 2: ``` index dat2 0 7 1 6 ``` I want a data frame with the following form: ``` index dat1 dat2 0 9 7 1 5 6 ``` I've tried using the `append` method, but I get a cross j...
It seems in general you're just looking for a join: ``` > dat1 = pd.DataFrame({'dat1': [9,5]}) > dat2 = pd.DataFrame({'dat2': [7,6]}) > dat1.join(dat2) dat1 dat2 0 9 7 1 5 6 ```
find the best way for factorial in python?
20,604,185
2
2013-12-16T05:38:44Z
20,604,197
11
2013-12-16T05:39:39Z
[ "python", "factorial" ]
I am researching on speed of factorial. But I am using two ways only, ``` import timeit def fact(N): B = N while N > 1: B = B * (N-1) N = N-1 return B def fact1(N): B = 1 for i in range(1, N+1): B = B * i return B print timeit.timeit('fact(5)', setup="from __main__ i...
If you're looking for the best, why not use the one provided in the math module? ``` >>> import math >>> math.factorial <built-in function factorial> >>> math.factorial(10) 3628800 ``` And a comparison of timings on my machine: ``` >>> print timeit.timeit('fact(5)', setup="from __main__ import fact"), fact(5) 0.8401...
"Return" in Function only Returning one Value
20,604,773
3
2013-12-16T06:30:00Z
20,604,793
8
2013-12-16T06:31:26Z
[ "python", "function", "for-loop", "printing", "return" ]
Let's say I write a for loop that will output all the numbers 1 to x: ``` x=4 for number in xrange(1,x+1): print number, #Output: 1 2 3 4 ``` Now, putting that same for loop into a function: ``` def counter(x): for number in xrange(1,x+1): return number print counter(4) #Output: 1 ``` Why do I only ...
`return` does exactly like the keyword's name implies. When you hit that statement, it *returns* and the rest of the function is not executed. What you might want instead is the `yield` keyword. This will create a generator function (a function that returns a generator). Generators are iterable. They "yield" one eleme...
String format with optional dict key-value
20,608,470
6
2013-12-16T10:24:37Z
20,608,505
8
2013-12-16T10:27:05Z
[ "python", "string-formatting" ]
Is there any way to format string with dict but optionally without key errors? This works fine: ``` opening_line = '%(greetings)s %(name)s !!!' opening_line % {'greetings': 'hello', 'name': 'john'} ``` But let's say I don't know the name, and I would like to format above line only for `'greetings'`. Something like,...
Use [defaultdict](http://docs.python.org/2/library/collections.html#collections.defaultdict), this will allow you to specify a default value for keys which don't exist in the dictionary. For example: ``` >>> from collections import defaultdict >>> d = defaultdict(lambda: 'UNKNOWN') >>> d.update({'greetings': 'hello'})...
In Python, importing twice with class instantiation?
20,609,500
5
2013-12-16T11:12:32Z
20,609,532
11
2013-12-16T11:14:12Z
[ "python" ]
In `models.py` I have: ``` ... db = SQLAlchemy(app) class User(db.Document): ... ``` In my app both `serve.py` and `models.py` call: ``` from models import User ``` Is that double import going to instantiate the db twice and potentially cause a problem?
> Is that double import going to instantiate the db twice and potentially cause a problem? No it will not. Once a module is imported it remains available regardless of any further imports via the `import` statement. The module is stored in `sys.modules` once imported. If you want to **reload the module** you have to...
How can I run my currently edited file in a PyCharm console in a way that I can type into the command line afterwards?
20,609,581
21
2013-12-16T11:16:26Z
20,609,799
11
2013-12-16T11:28:15Z
[ "python", "console", "pycharm" ]
I want this so I can retain the command line history after repeated runs, and to paste lines from the console into tests etc. Exactly like in IDLE. [I realize this question is basically a duplicate of [Running a module from the pycharm console](http://stackoverflow.com/questions/16874046/running-a-module-from-the-pych...
Select the code fragment or the entire file, then use **Execute Selection in Console** from the context menu.
How can I run my currently edited file in a PyCharm console in a way that I can type into the command line afterwards?
20,609,581
21
2013-12-16T11:16:26Z
27,237,910
7
2014-12-01T21:44:18Z
[ "python", "console", "pycharm" ]
I want this so I can retain the command line history after repeated runs, and to paste lines from the console into tests etc. Exactly like in IDLE. [I realize this question is basically a duplicate of [Running a module from the pycharm console](http://stackoverflow.com/questions/16874046/running-a-module-from-the-pych...
`Shift+Alt+E`would execute the selected code.
There is a 4 in my prime number list generated in Python
20,610,157
6
2013-12-16T11:45:22Z
20,610,192
11
2013-12-16T11:46:29Z
[ "python" ]
Here is my code. ``` #Prime numbers between 0-100 for i in range(2,100): flg=0 for j in range(2,int(i/2)): if i%j==0: flg=1 break if flg!=1: print(i) ``` And the output is ``` 2 3 4 <- 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 ``` I have n...
The reason is that range is not inclusive, i.e. ``` >>> range(2,2) [] ``` So when you access 4, you don't check for divisors. Change for example to `range(2,int(i/2)+1)` To speed up your calculation, you can use math.sqrt instead of /2 operation, for example as: ``` import math ``` and then ``` for j in range(2, ...
Find python lxml version
20,611,504
26
2013-12-16T12:56:38Z
20,611,797
29
2013-12-16T13:11:50Z
[ "python", "lxml" ]
How can I find the installed python-lxml version in a Linux system? ``` >>> import lxml >>> lxml.__version__ Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute '__version__' >>> from pprint import pprint >>> pprint(dir(lxml)) ['__builtins__', '__...
You can get the version by looking at `etree`: ``` >>> from lxml import etree >>> etree.LXML_VERSION (3, 0, -198, 0) ``` Other versions of interest can be: `etree.LIBXML_VERSION`, `etree.LIBXML_COMPILED_VERSION`, `etree.LIBXSLT_VERSION` and `etree.LIBXSLT_COMPILED_VERSION`.
Get rid of get_profile() in a migration to Django 1.6
20,613,315
25
2013-12-16T14:30:27Z
20,850,094
62
2013-12-31T01:02:24Z
[ "python", "django", "deprecated", "user-profile" ]
With Django 1.5 and the introduction of custom user models the `AUTH_PROFILE_MODULE` became deprecated. In my existing Django application I use the `User` model and I also have a `Profile` model with a foreign key to the `User` and store other stuff about the user in the profile. Currently using `AUTH_PROFILE_MODULE` a...
Using a profile model with a relation to the built-in `User` is still a totally legitimate construct for storing additional user information (and recommended in many cases). The `AUTH_PROFILE_MODULE` and `get_profile()` stuff that is now deprecated just ended up being unnecessary, given that built-in Django 1-to-1 synt...
close() never close connections in pymongo?
20,613,339
5
2013-12-16T14:32:09Z
20,613,627
8
2013-12-16T14:45:41Z
[ "python", "mongodb", "pymongo" ]
I use MongoDB and I connect to it through pymongo. Here's my code: ``` >>> import pymongo >>> con=pymongo.Connection('localhost',27017) >>> con.database_names() ['local', 'bookdb'] >>> con.close() >>> con.database_names() ['local', 'bookdb'] ``` I use `con.close()` to disconnect to the MongoDB, but after that, I can ...
Just read the docs, faster and more detailed. > If this instance is used again it will be automatically re-opened. [http://api.mongodb.org/python/current/api/pymongo/connection.html](http://api.mongodb.org/python/current/api/pymongo/mongo_client.html#pymongo.mongo_client.MongoClient.close)
Python email script fails unless smtplib is first called in interactive window
20,613,687
2
2013-12-16T14:48:38Z
20,614,053
10
2013-12-16T15:04:49Z
[ "python", "smtplib" ]
I have a script that sends an email via a mail server. The script only works when I call `import smtplib` first in the interactive window. Otherwise, I get the following error: > ImportError: No module named MIMEMultipart Can someone help me understand the underlying reason behind this behavior? ``` import smtplib f...
Could it be that either your script is named "email.py" or that you have an "email.py" (or "email.pyc" etc) file in your current directory ?
Python XLWT can not specify row height
20,613,875
6
2013-12-16T14:57:19Z
20,614,198
14
2013-12-16T15:12:28Z
[ "python", "xlwt" ]
I'm trying to use xlwt with row.(i).height, but I had no result. My Code: ``` import xlwt book = xlwt.Workbook(encoding='latin-1') sheet = sheet.add_sheet('KPI.TiempoRespuesta',cell_overwrite_ok=True) sheet.write(1, 4, "BLABLABLABLABLABLABLABLABLABLABLABLA") sheet.row(4).height = 256*20 book.save("book.xls") ``` I w...
You should tell xlwt row height and default font height do not match: ``` sheet.row(4).height_mismatch = True sheet.row(4).height = 256*20 ```
Can't install Python Imaging Library using pip
20,614,185
5
2013-12-16T15:11:57Z
20,614,273
7
2013-12-16T15:16:34Z
[ "python", "pip" ]
When trying to install Python Imaging Library(PIL) using PIP, the installation failed with the following error: ``` SyntaxError: invalid syntax Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 16, in <module> File "/tmp/pip_build_root/pil/setup.py", line ...
There is a new fork of PIL called Pillow which seems to work more consistently than PIL for a lot of people. It's easy to install also. Look [here](https://pillow.readthedocs.org/en/latest/)(for info/docs) and [here](http://www.lfd.uci.edu/~gohlke/pythonlibs/#pillow)(to install). Though I think `pip install Pillow` sho...
Python - Merge two lists with a simultaneous concatenation
20,616,563
3
2013-12-16T17:09:37Z
20,616,587
9
2013-12-16T17:10:45Z
[ "python", "python-3.x", "merge", "concatenation" ]
``` ListA = [1,2,3] ListB = [10,20,30] ``` I want to add the contents of the lists together `(1+10,2+20,3+30)` creating the following list: ``` ListC = [11,22,33] ``` Is there a function that merges lists specifically in this manner?
This works: ``` >>> ListA = [1,2,3] >>> ListB = [10,20,30] >>> list(map(sum, zip(ListA, ListB))) [11, 22, 33] >>> ``` All of the built-ins used above are explained [here](http://docs.python.org/3.2/library/functions.html). --- Another solution would be to use a [list comprehension](http://docs.python.org/3.2/tutori...
Travis special requirements for each python version
20,617,600
20
2013-12-16T17:59:30Z
20,621,143
27
2013-12-16T21:21:09Z
[ "python", "travis-ci", "requirements.txt" ]
I need unittest2 and importlib for python 2.6 that is not required for other python versions that travis tests against. Is there a way to tell Travis-CI to have different requirements.txt files for each python version?
Travis CI adds an environment variable called `$TRAVIS_PYTHON_VERSION` that can be referenced in your .travis.yml: ``` python: - 2.6 - 2.7 - 3.2 - 3.3 - pypy install: - if [[ $TRAVIS_PYTHON_VERSION == 2.6 ]]; then pip install importlib unittest2; fi - pip install -r requirements.txt ``` This would cause...
Python logging.Formatter(): is there any way to fix the width of a field and justify it left/right?
20,618,570
7
2013-12-16T18:53:25Z
20,618,659
7
2013-12-16T18:58:35Z
[ "python", "logging", "formatting" ]
Here's a sample of log records from the logging tutorial: ``` 2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message 2005-03-19 15:38:55,979 - simpleExample - INFO - info message 2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message 2005-03-19 15:38:56,055 - simpleExample - ERROR - error message 20...
Field width can be specified by adding a number in front of the type specifier: ``` >>> "%(foo)8s" % {'foo': 'bar'} ' bar' ``` You can use this in your format string passed to the formatter. For your example, that'd be: ``` "%(asctime)s %(filename)s: %(levelname)8s %(message)s" ```
How to write to file without parenthesis in python
20,618,640
2
2013-12-16T18:57:07Z
20,618,689
7
2013-12-16T18:59:41Z
[ "python", "fwrite" ]
When i write to file my results: ``` output=knew[i][0],knew[i][1], knew[i][2],eigenval[k],group[i] value=str(output) o.write(value+'\n') ``` I get: ``` (0.05, 0.05, 0.166667, -0.8513056, 0.9881956035137526) (0.05, 1.05, 0.166667, -0.8513056, 0.011652226336523394) (0.05, -0.9500000000000002, 0.166667, -0.8513056, 0.0...
Instead of ``` value = str(output) ``` you can do ``` value = ', '.join(map(str, output)) ``` What you see is the string representation of a tuple. It's there because you called `str` on it. What the [`str.join`](http://docs.python.org/library/stdtypes.html#str.join) method does is join an iterable (e.g. a tuple o...
How to smooth a curve in the right way?
20,618,804
56
2013-12-16T19:06:31Z
20,619,164
46
2013-12-16T19:24:44Z
[ "python", "numpy", "scipy", "signal-processing", "data-processing" ]
Lets assume we have a dataset which might be given approximately by ``` import numpy as np x = np.linspace(0,2*np.pi,100) y = np.sin(x) + np.random.random(100) * 0.2 ``` Therefore we have a variation of 20% of the dataset. My first idea was to use the UnivariateSpline function of scipy, but the problem is that this d...
If you are interested in a "smooth" version of a signal that is periodic (like your example), then a FFT is the right way to go. Take the fourier transform and subtract out the low-contributing frequencies: ``` import numpy as np import scipy.fftpack N = 100 x = np.linspace(0,2*np.pi,N) y = np.sin(x) + np.random.rand...
How to smooth a curve in the right way?
20,618,804
56
2013-12-16T19:06:31Z
20,619,392
22
2013-12-16T19:36:27Z
[ "python", "numpy", "scipy", "signal-processing", "data-processing" ]
Lets assume we have a dataset which might be given approximately by ``` import numpy as np x = np.linspace(0,2*np.pi,100) y = np.sin(x) + np.random.random(100) * 0.2 ``` Therefore we have a variation of 20% of the dataset. My first idea was to use the UnivariateSpline function of scipy, but the problem is that this d...
Fitting a moving average to your data would smooth out the noise, see this [this answer](http://stackoverflow.com/a/11352216/54557) for how to do that. If you'd like to use [LOWESS](http://en.wikipedia.org/wiki/Local_regression) to fit your data (it's similar to a moving average but more sophisticated), you can do tha...
How to smooth a curve in the right way?
20,618,804
56
2013-12-16T19:06:31Z
20,642,478
58
2013-12-17T19:01:21Z
[ "python", "numpy", "scipy", "signal-processing", "data-processing" ]
Lets assume we have a dataset which might be given approximately by ``` import numpy as np x = np.linspace(0,2*np.pi,100) y = np.sin(x) + np.random.random(100) * 0.2 ``` Therefore we have a variation of 20% of the dataset. My first idea was to use the UnivariateSpline function of scipy, but the problem is that this d...
I prefer a [Savitzky-Golay filter](http://en.wikipedia.org/wiki/Savitzky%E2%80%93Golay_filter_for_smoothing_and_differentiation). It uses least squares to regress a small window of your data onto a polynomial, then uses the polynomial to estimate the point in the center of the window. Finally the window is shifted forw...
How to smooth a curve in the right way?
20,618,804
56
2013-12-16T19:06:31Z
26,337,730
18
2014-10-13T10:23:04Z
[ "python", "numpy", "scipy", "signal-processing", "data-processing" ]
Lets assume we have a dataset which might be given approximately by ``` import numpy as np x = np.linspace(0,2*np.pi,100) y = np.sin(x) + np.random.random(100) * 0.2 ``` Therefore we have a variation of 20% of the dataset. My first idea was to use the UnivariateSpline function of scipy, but the problem is that this d...
A quick and dirty way to smooth data I use, based on a moving average box (by convolution): ``` x = np.linspace(0,2*np.pi,100) y = np.sin(x) + np.random.random(100) * 0.8 def smooth(y, box_pts): box = np.ones(box_pts)/box_pts y_smooth = np.convolve(y, box, mode='same') return y_smooth plot(x, y,'o') plot...
How do I go to a random website? - python
20,619,746
3
2013-12-16T19:56:23Z
20,619,808
7
2013-12-16T20:00:25Z
[ "python", "url", "random", "website", "browser" ]
How to generate a random yet valid website link, regardless of languages. Actually, the more diverse the language of the website it generates, the better it is. I've been doing it by using other people's script on their webpage, **how can i not rely on these random site forwarding script and make my own?**. I've been ...
> I've been doing it by using other people's script on their webpage, how can i not rely on these random site forwarding script and make my own? There are two ways to do this: * Create your own [spider](http://en.wikipedia.org/wiki/Web_spider) that amasses a huge collection of websites, and pick from that collection....