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
lxml installation error ubuntu 14.04 (internal compiler error)
24,455,238
48
2014-06-27T15:14:22Z
25,916,353
107
2014-09-18T15:09:12Z
[ "python", "install", "pip", "lxml", "ubuntu-14.04" ]
I am having problems with installing `lxml`. I have tried the solutions of the relative questions in this site and other sites but could not fix the problem. Need some suggestions/solution on this. I am providing the full log after executing `pip install lxml`, ``` Downloading/unpacking lxml Downloading lxml-3.3.5....
In this particular case, it has nothing to do with dependencies, it's a memory problem. I had this problem within a virtualbox VM. My solution was to increase memory allocated to the VM from the default 512Mb to 1024Mb.
lxml installation error ubuntu 14.04 (internal compiler error)
24,455,238
48
2014-06-27T15:14:22Z
26,762,938
128
2014-11-05T17:03:49Z
[ "python", "install", "pip", "lxml", "ubuntu-14.04" ]
I am having problems with installing `lxml`. I have tried the solutions of the relative questions in this site and other sites but could not fix the problem. Need some suggestions/solution on this. I am providing the full log after executing `pip install lxml`, ``` Downloading/unpacking lxml Downloading lxml-3.3.5....
Possible solution (if you have no ability to increase memory on that machine) is to add swap file. ``` sudo dd if=/dev/zero of=/swapfile bs=1024 count=524288 sudo chmod 600 /swapfile sudo mkswap /swapfile sudo swapon /swapfile ``` from <https://github.com/pydata/pandas/issues/1880#issuecomment-9920484> This worked f...
Why do the Python docs say I need to define __ne__ when I define __eq__?
24,455,406
13
2014-06-27T15:23:36Z
24,456,042
15
2014-06-27T15:55:30Z
[ "python", "operator-overloading", "equality", "inequality" ]
According to the [Python docs](https://docs.python.org/3/reference/datamodel.html#object.__ne__): "when defining `__eq__()`, one should also define `__ne__()` so that the operators will behave as expected". However, it appears that Python computes `__ne__` as `not __eq__` automatically: ``` In [8]: class Test: de...
Python 3 changed behaviour for the `==` case, see [Python 3, What's New](https://docs.python.org/3/whatsnew/3.0.html#operators-and-special-methods): > `!=` now returns the opposite of `==`, unless `==` returns `NotImplemented`. It was deemed [a useful change](http://hg.python.org/cpython/annotate/834da52eb2a4/Objects...
Label encoding across multiple columns in scikit-learn
24,458,645
33
2014-06-27T18:29:40Z
30,267,328
24
2015-05-15T19:27:05Z
[ "python", "pandas", "scikit-learn" ]
I'm trying to use scikit-learn's `LabelEncoder` to encode a pandas `DataFrame` of string labels. As the dataframe has many (50+) columns, I want to avoid creating a `LabelEncoder` object for each column; I'd rather just have one big `LabelEncoder` objects that works across *all* my columns of data. Throwing the entire...
As mentioned by larsmans, [LabelEncoder() only takes a 1-d array as an argument](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html). That said, it is quite easy to roll your own label encoder that operates on multiple columns of your choosing, and returns a transformed dataframe. ...
Label encoding across multiple columns in scikit-learn
24,458,645
33
2014-06-27T18:29:40Z
31,939,145
34
2015-08-11T10:21:03Z
[ "python", "pandas", "scikit-learn" ]
I'm trying to use scikit-learn's `LabelEncoder` to encode a pandas `DataFrame` of string labels. As the dataframe has many (50+) columns, I want to avoid creating a `LabelEncoder` object for each column; I'd rather just have one big `LabelEncoder` objects that works across *all* my columns of data. Throwing the entire...
You can easily do this though, ``` df.apply(LabelEncoder().fit_transform) ``` EDIT: Since this answer is over a year ago, and generated many upvotes (including a bounty), I should probably extend this further. For inverse\_transform and transform, you have to do a little bit of hack. ``` from collections import de...
How to get Python to use Assembly
24,462,681
4
2014-06-28T01:12:42Z
24,463,369
10
2014-06-28T03:47:07Z
[ "python", "windows", "assembly", "64bit" ]
I am a beginner in assembly, but a master in Python. I have just recently started to learn x86\_64 NASM for windows, and I wish to combine the power of assembly, and the flexibility of Python. I have looked all over, and I have not found a way to use a NASM assembly procedure from within Python. By this I do not mean i...
You could create a [C extension](https://docs.python.org/2/extending/extending.html) wrapper for the functions implemented in assembly and link it to the OBJ file created by nasm. A dummy example (for 32 bit Python 2; not tested): **myfunc.asm:** ``` ;http://www.nasm.us/doc/nasmdoc9.html global _myfunc section .te...
TypeError: get() takes no keyword arguments
24,463,202
12
2014-06-28T03:08:22Z
24,463,211
8
2014-06-28T03:09:39Z
[ "python" ]
I'm new at Python, and I'm trying to basically make a hash table that checks if a key points to a value in the table, and if not, initializes it to an empty array. The offending part of my code is the line: ``` converted_comments[submission.id] = converted_comments.get(submission.id, default=0) ``` I get the error: ...
The error message says that `get` takes no keyword arguments but you are providing one with `default=0` ``` converted_comments[submission.id] = converted_comments.get(submission.id, 0) ```
TypeError: get() takes no keyword arguments
24,463,202
12
2014-06-28T03:08:22Z
24,463,222
25
2014-06-28T03:12:31Z
[ "python" ]
I'm new at Python, and I'm trying to basically make a hash table that checks if a key points to a value in the table, and if not, initializes it to an empty array. The offending part of my code is the line: ``` converted_comments[submission.id] = converted_comments.get(submission.id, default=0) ``` I get the error: ...
Due to the way the Python C-level APIs developed, a lot of built-in functions and methods don't actually have names for their arguments. Even if the documentation calls the argument `default`, the function doesn't recognize the name `default` as referring to the optional second argument. You have to provide the argumen...
"cannot concatenate 'str' and 'int' objects" error
24,463,245
3
2014-06-28T03:17:37Z
24,463,265
7
2014-06-28T03:23:15Z
[ "python", "string", "for-loop" ]
I keep getting a "cannot concatenate 'str' and 'int' objects" error when I try to run the following code. I'm pointed to line 6 as the source of the problem, but I really can't see the error! My types all *seem* to be consistent. ``` def DashInsert(num): num_str = str(num) new_str = '' for i in num_str: va...
``` for i in num_str: ``` `i` is not an index in this case, it is a string character. For example, if `num` in your code is 42, the work flow will be: ``` num_str = str(42) # '42' for i in num_str: # First iteration var1 = num_str['4':'4'+1] # Python: '4' + 1 = ERROR ``` What you are probably looking for is: `...
gaierror [Errno 8] when send_mail with Django python and gmail
24,465,277
5
2014-06-28T09:02:13Z
24,473,555
7
2014-06-29T05:57:29Z
[ "python", "django", "gmail" ]
I'm new with Django an Python. I was following this tutorial ["Try Django 16"](https://www.youtube.com/watch?v=51mmqf5a0Ss) I don't get it work. I added `fail_silent=false` to get the error. ``` [Errno 8] nodename nor servname provided, or not known ``` Is there anyone who can help me find this problem? ``` gaierror...
``` EMAIL_HOST = 'smpt.gmail.com' ``` What is smpt? ``` should be EMAIL_HOST = 'smtp.gmail.com' ``` <http://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol>
Calculate area of polygon given (x,y) coordinates
24,467,972
10
2014-06-28T14:49:03Z
24,468,019
18
2014-06-28T14:55:02Z
[ "python", "coordinates", "polygon", "area" ]
I have a set of points and would like to know if there is a function (for the sake of convenience and probably speed) that can calculate the area enclosed by a set of points. for example: ``` x = np.arange(0,1,0.001) y = np.sqrt(1-x**2) points = zip(x,y) ``` given `points` the area should be approximately equal to ...
You can use the [shoelace formula](http://en.wikipedia.org/wiki/Shoelace_formula), eg ``` def PolygonArea(corners): n = len(corners) # of corners area = 0.0 for i in range(n): j = (i + 1) % n area += corners[i][0] * corners[j][1] area -= corners[j][0] * corners[i][1] area = abs(...
Calculate area of polygon given (x,y) coordinates
24,467,972
10
2014-06-28T14:49:03Z
30,408,825
16
2015-05-23T04:13:54Z
[ "python", "coordinates", "polygon", "area" ]
I have a set of points and would like to know if there is a function (for the sake of convenience and probably speed) that can calculate the area enclosed by a set of points. for example: ``` x = np.arange(0,1,0.001) y = np.sqrt(1-x**2) points = zip(x,y) ``` given `points` the area should be approximately equal to ...
Implementation of [Shoelace formula](https://en.wikipedia.org/wiki/Shoelace_formula) could be done in `Numpy`. Assuming these vertices: ``` import numpy as np x = np.arange(0,1,0.001) y = np.sqrt(1-x**2) ``` We can define the following function to find the area: ``` def PolyArea(x,y): return 0.5*np.abs(np.dot(x,...
Defining a gradient with respect to a subtensor in Theano
24,468,482
7
2014-06-28T15:49:52Z
24,496,769
9
2014-06-30T18:40:12Z
[ "python", "machine-learning", "theano" ]
I have what is conceptually a simple question about Theano but I haven't been able to find the answer (I'll confess upfront to not really understanding how shared variables work in Theano, despite many hours with the tutorials). I'm trying to implement a "deconvolutional network"; specifically I have a 3-tensor of inp...
To summarize the findings: Assigning `grad_var = codes[idx]`, then making a new variable such as: `subgrad = T.set_subtensor(codes[input_index], codes[input_index] - learning_rate*del_codes[input_index])` Then calling `train_codes = function([input_index], loss, updates = [[codes, subgrad]])` seemed to do the trick....
How to Redirect Logger Output into PyQt Text Widget
24,469,662
5
2014-06-28T18:16:06Z
24,469,889
8
2014-06-28T18:47:48Z
[ "python", "pyqt" ]
A code posted on [Redirecting Output in PyQt](http://stackoverflow.com/questions/11465971/redirecting-output-in-pyqt) does two good things at once: it takes advantage of `logging` module to nicely format messages and it redirects standard `stdout` and `stderr` in to QT `QTextBrowser` widget. But I would like `QTextBrow...
You can create a custom [`logging.Handler`](https://docs.python.org/2/library/logging.html#handler-objects) and add it to your `logger`: ``` import logging logger = logging.getLogger(__name__) class QtHandler(logging.Handler): def __init__(self): logging.Handler.__init__(self) def emit(self, record)...
How many times does a for loop evaluate its expression list?
24,470,072
3
2014-06-28T19:13:26Z
24,470,079
8
2014-06-28T19:14:20Z
[ "python", "for-loop" ]
I have the following code: ``` list1 = [4,1,2,6] for elem in sorted(list1): #some task ``` I was wondering how many times does Python sort the list using the `sorted()` method? Is it for each iteration or just once? In other words is the following code more efficient? ``` list1 = [4,1,2,6] list1 = sorted(list1)...
In both code examples, the list is sorted only once. The expression on the right of the `in` operator in a for-loop header is evaluated just once, before looping commences. You can read about this in the [documentation](https://docs.python.org/3/reference/compound_stmts.html#for): > ``` > for_stmt ::= "for" target_l...
Integral of Intensity function in python
24,470,389
4
2014-06-28T19:52:33Z
24,470,571
10
2014-06-28T20:15:57Z
[ "python", "scipy", "integral", "numerical-integration" ]
There is a function which determine the intensity of the Fraunhofer diffraction pattern of a circular aperture... ([more information](http://en.wikipedia.org/wiki/Airy_Disk)) Integral of the function in distance x= [-3.8317 , 3.8317] must be about 83.8% ( If assume that I0 is 100) and when you increase the distance to...
The problem seems to be in the function's behaviour near zero. If the function is plotted, it looks smooth: ![enter image description here](http://i.stack.imgur.com/WKx3D.png) However, `scipy.integrate.quad` complains about round-off errors, which is very strange with this beautiful curve. However, the function is no...
Set values on the diagonal of pandas.DataFrame
24,475,094
6
2014-06-29T10:16:03Z
24,475,214
13
2014-06-29T10:30:32Z
[ "python", "numpy", "pandas" ]
I have a pandas dataframe I would like to se the diagonal to 0 ``` import numpy import pandas df = pandas.DataFrame(numpy.random.rand(5,5)) df Out[6]: 0 1 2 3 4 0 0.536596 0.674319 0.032815 0.908086 0.215334 1 0.735022 0.954506 0.889162 0.71...
``` In [21]: df.values[[np.arange(5)]*2] = 0 In [22]: df Out[22]: 0 1 2 3 4 0 0.000000 0.931374 0.604412 0.863842 0.280339 1 0.531528 0.000000 0.641094 0.204686 0.997020 2 0.137725 0.037867 0.000000 0.983432 0.458053 3 0.594542 0.943542 0.826738 0.000000 0...
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 23: ordinal not in range(128)
24,475,393
13
2014-06-29T10:54:19Z
24,475,405
23
2014-06-29T10:56:06Z
[ "python", "encoding", "utf-8" ]
when I try to concatenate this, I get the UnicodeDecodeError when the field contains 'ñ' or '´'. If the field that contains the 'ñ' or '´' is the last I get no error. ``` #... nombre = fabrica nombre = nombre.encode("utf-8") + '-' + sector.encode("utf-8") nombre = nombre.encode("utf-8") + '-' + unidad.encode("utf...
You are encoding to UTF-8, then *re*-encoding to UTF-8. Python can only do this if it first *decodes* again to Unicode, but it has to use the default ASCII codec: ``` >>> u'ñ' u'\xf1' >>> u'ñ'.encode('utf8') '\xc3\xb1' >>> u'ñ'.encode('utf8').encode('utf8') Traceback (most recent call last): File "<stdin>", line ...
pygal rendering png/svg black pictures
24,476,029
8
2014-06-29T12:21:09Z
25,360,101
17
2014-08-18T09:29:46Z
[ "python", "svg", "rendering", "data-visualization", "pygal" ]
I am using python (with a virtual env in LinuxMint), I installed `pygal`. Everything works fine (rendering to html) but not rendering to svg or png . The result : Nothing but a black background. I installed `cssselect` and `tinycss` like mentioned [here](https://github.com/Kozea/pygal/issues/2) . It works for the fi...
You need to install lxml as well. So assuming you are in a virtualenv run the following command on your bash/zsh prompt: `pip install lxml` If you only have the other 3 libraries, i.e. cssselect, pycairo, tinycss. Then you will be able to properly render an SVG but the PNG render function will produce a solid black i...
UnboundLocalError: local variable 'error' referenced before assignment
24,476,594
4
2014-06-29T13:42:09Z
24,476,692
7
2014-06-29T13:53:46Z
[ "python", "python-3.x" ]
I've looked at other questions regarding this particular error but in those cases there was a route in the process where the variable is never defined and hence fails when called later. However with my program I set the variables before the try method, have those variables changed in the try method under certain criter...
In Python 3, the variable to which you assign the exception in a `except SomeException as e:` statement is [deleted](http://legacy.python.org/dev/peps/pep-3110/#semantic-changes) on exiting the `except` block: ``` >>> e = "something" >>> try: ... 1/0 ... except ZeroDivisionError as e: ... print(e) ... divisio...
How to list available tests with python?
24,478,727
2
2014-06-29T17:57:19Z
24,478,809
10
2014-06-29T18:09:38Z
[ "python", "python-unittest", "test-suite" ]
How to just list all discovered tests? I found this command: ``` python3.4 -m unittest discover -s . ``` But it's not exactly what I want, because the above command executes tests. I mean let's have a project with a lot of tests. Execution time is a few minutes. This force me to wait until tests are finished. What I...
Command line command `discover` is implemented using [`unittest.TestLoader`](https://docs.python.org/3/library/unittest.html?highlight=discover#unittest.TestLoader). Here's the somewhat elegant solution ``` import unittest def print_suite(suite): if hasattr(suite, '__iter__'): for x in suite: ...
Why is random() * random() different to random() ** 2?
24,479,310
7
2014-06-29T19:09:43Z
24,479,662
13
2014-06-29T19:49:54Z
[ "python", "random", "random-sample" ]
Is there are difference between `random() * random()` and `random() ** 2`? `random()` returns a value between 0 and 1 from a uniform distribution. When testing both versions of random square numbers I noticed a little difference. I created 100000 random square numbers and counted how many numbers are in each interval ...
Let's simplify the problem somewhat. Consider throwing two dice and multiplying the result against throwing one die and squaring it. In the first case you have a 1 in 36 chance of throwing a double 1, therefore a 1 in 36 chance the product is 1. On the other hand the second case obviously has a 1 in 6 chance that the s...
Why is random() * random() different to random() ** 2?
24,479,310
7
2014-06-29T19:09:43Z
24,480,300
16
2014-06-29T21:09:30Z
[ "python", "random", "random-sample" ]
Is there are difference between `random() * random()` and `random() ** 2`? `random()` returns a value between 0 and 1 from a uniform distribution. When testing both versions of random square numbers I noticed a little difference. I created 100000 random square numbers and counted how many numbers are in each interval ...
Here are some plots: All the possibilities for `random() * random()`: ![A 2D heatmap with most intensity in the top-right.](http://i.stack.imgur.com/9W8S4.png) The x-axis is one random variable increasing rightwards, and the y-axis is another increasing upwards. You can see that if either is low, the result will be...
Pandas: Timestamp index rounding to the nearest 5th minute
24,479,577
7
2014-06-29T19:39:51Z
25,542,523
8
2014-08-28T06:54:16Z
[ "python", "pandas" ]
I have a `df` with the usual timestamps as an index: ``` 2011-04-01 09:30:00 2011-04-01 09:30:10 ... 2011-04-01 09:36:20 ... 2011-04-01 09:37:30 ``` How can I create a column to this dataframe with the same timestamp but rounded to the nearest 5th minute interval? Like this: ``` index ...
Above answer is correct but complicated and very slow. Make use of the nice `Timstamp` in pandas. ``` import numpy as np import pandas as pd ns5min=5*60*1000000000 # 5 minutes in nanoseconds pd.DatetimeIndex(((df.index.astype(np.int64) // ns5min + 1 ) * ns5min)) ``` Let's test the speed: ``` rng = pd.date_range(...
Python subprocess not executing properly
24,482,419
2
2014-06-30T03:01:49Z
24,482,434
7
2014-06-30T03:03:40Z
[ "python", "linux", "bash", "screen", "subprocess" ]
I am having problems outputting a command to a running screen. Using the following code: ``` import subprocess subprocess.call(["screen", "-S jcmp", "-X stuff", "'kick Jman100'`echo -ne '\015'`"]) ``` returns the following: ``` Use: screen [-opts] [cmd [args]] or: screen -r [host.tty] Options: -a Force...
You're getting that message because you are not passing the arguments correctly. Each argument should be an individual string in the list. That is, `-S jcmp` should not be a single argument but two; same for `-X stuff`. ``` subprocess.call(["screen", "-S", "jcmp", "-X", "stuff", "'kick Jman100'`echo -ne '\015'`"]) ``...
Understand lambda usage in given python code
24,485,932
9
2014-06-30T08:31:12Z
24,485,984
12
2014-06-30T08:34:50Z
[ "python", "lambda" ]
On reading through some code, I came across the below snippet which I am not able to understand. Would anyone be able to guide/provide hints/link or a basic explanation of line 3 below ``` def do_store(*args, **kwargs): try: key = (args, tuple(sorted(kwargs.items(), key=lambda i:i[0]))) results = f...
With the `lambda` keyword, you create "anonymous functions". They don't have (and don't need to have) a name, because they are immediately assigned (usually) to a callback function. ``` lambda i:i[0] ``` is just the body of the function ``` def f(i): return i[0] ``` The `key` parameter of the `sorted` function ha...
Understand lambda usage in given python code
24,485,932
9
2014-06-30T08:31:12Z
24,486,079
7
2014-06-30T08:41:12Z
[ "python", "lambda" ]
On reading through some code, I came across the below snippet which I am not able to understand. Would anyone be able to guide/provide hints/link or a basic explanation of line 3 below ``` def do_store(*args, **kwargs): try: key = (args, tuple(sorted(kwargs.items(), key=lambda i:i[0]))) results = f...
Three equivalent ways to write this: ``` sorted(kwargs.items(), key=lambda i:i[0]) ``` (which is the one you have) ``` def first_item(aList): return aList[0] sorted(kwargs.items(), key=first_item) from operator import itemgetter sorted(kwargs.items(), key=itemgetter(0)) ``` In all cases the argument `key` is passe...
Understand lambda usage in given python code
24,485,932
9
2014-06-30T08:31:12Z
24,486,403
9
2014-06-30T08:59:30Z
[ "python", "lambda" ]
On reading through some code, I came across the below snippet which I am not able to understand. Would anyone be able to guide/provide hints/link or a basic explanation of line 3 below ``` def do_store(*args, **kwargs): try: key = (args, tuple(sorted(kwargs.items(), key=lambda i:i[0]))) results = f...
The other answers already explain well what `lambda` and `sorted`'s `key` parameter do. In short: * `key` is used to provide a [comparison key function](https://docs.python.org/3/library/functions.html#sorted) for the sort, lets call it *f*, such that if *f(x) < f(y)*, then *x* will appear before *y* in the sorted lis...
Python enum - getting value of enum on string conversion
24,487,405
10
2014-06-30T09:54:24Z
24,487,545
19
2014-06-30T10:01:17Z
[ "python", "python-3.x", "enums", "python-3.4" ]
I have following enum defined ``` from enum import Enum class D(Enum): x = 1 y = 2 print(D.x) ``` now the printed value is ``` D.x ``` instead I wanted the enum's value to be print ``` 1 ``` what can be done to achieve this functionality.
You are printing the enum *object*. Use the `.value` attribute if you wanted just to print that: ``` print(D.x.value) ``` See the [*Programmatic access to enumeration members and their attributes* section](https://docs.python.org/3/library/enum.html#programmatic-access-to-enumeration-members-and-their-attributes): >...
gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> django
24,488,891
27
2014-06-30T11:15:21Z
24,550,912
14
2014-07-03T10:14:23Z
[ "python", "django", "gunicorn" ]
I have a django app and trying to set it up with gunicorn first and later with supervisor and nginx. The app is running with the normal django command perfectly like `python manage.py runserver` I installed the gunicorn using pip like `pip install gunicorn` and django version is `1.5.3` when i run the below command ...
Actually the problem here was the wsgi file itself, previously before django 1.3 the wsgi file was named with an extension of `.wsgi`, but now in the recent versions it will be created with and extension of `.py` that is the wsgi file must be a python module so the file should be `hello_wsgi.py` and command should be ...
How can I install PySide on Travis?
24,489,588
6
2014-06-30T11:56:05Z
24,545,890
11
2014-07-03T05:52:04Z
[ "python", "qt", "pyside", "travis-ci", "python-3.4" ]
My tests for [Quamash](https://github.com/aknuds1/quamash) depend on [PySide](http://qt-project.org/wiki/pyside) (or PyQt eventually) for Python 3.4, so I'm wondering how I can install this dependency on [Travis](https://travis-ci.org/) so that it's available to the tests? I am aware that I can install PySide from sou...
Installing via apt-get is currently not possible. See [github issue](https://github.com/travis-ci/travis-ci/issues/2219#issuecomment-41804942) and [travis docs](http://docs.travis-ci.com/user/languages/python/#Travis-CI-Uses-Isolated-virtualenvs). Three other options. ## Just use pip Your `.travis.yml` will include:...
In Python is there a function for the "in" operator
24,492,550
6
2014-06-30T14:32:30Z
24,492,588
10
2014-06-30T14:33:52Z
[ "python", "function", "operators" ]
Is there any Python function for the "in" operator like what we have for operator.lt, operator.gt, .. I wan't to use this function to do something like: ``` operator.in(5, [1,2,3,4,5,6]) >> True operator.in(10, [1,2,3,4,5,6]) >> False ```
Yes, use [`operator.contains()`](https://docs.python.org/2/library/operator.html#operator.contains); note that the order of operands is reversed: ``` >>> import operator >>> operator.contains([1,2,3,4,5,6], 5) True >>> operator.contains([1,2,3,4,5,6], 10) False ``` You may have missed the handy [mapping table](https:...
'from flask import Flask' throws up a syntax error - Python
24,494,104
2
2014-06-30T15:49:49Z
24,494,137
11
2014-06-30T15:51:28Z
[ "python", "flask" ]
I just tried a simple hello world app in Python using Flask (From Flask's documentation). I installed Flask using 'pip install flask'. I uninstalled it and installed it again. Still, the issue persists. Code: ``` from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if...
Flask does not support Python 3.2; only 3.3+ (and 2.6+) So you need to install a supported Python version.
How could an "also if" be implemented in Python?
24,494,596
2
2014-06-30T16:18:56Z
24,494,639
9
2014-06-30T16:21:31Z
[ "python", "if-statement", "series" ]
I want to implement something conceptually like the following: ``` if condition1: action1() also if condition2: action2() also if condition3: action3() also if condition4: action4() also if condition5: action5() also if condition6: action6() else: print("None of the conditions was met.") ``...
I would suggest: ``` if condition1: action1() if condition2: action2() ... if not any(condition1, condition2, ...): print(...) ```
How could an "also if" be implemented in Python?
24,494,596
2
2014-06-30T16:18:56Z
24,495,556
7
2014-06-30T17:20:19Z
[ "python", "if-statement", "series" ]
I want to implement something conceptually like the following: ``` if condition1: action1() also if condition2: action2() also if condition3: action3() also if condition4: action4() also if condition5: action5() also if condition6: action6() else: print("None of the conditions was met.") ``...
Okay, based on the clarification, something like this would work well: ``` class Accumulator(object): none = None def also(self, condition): self.none = not condition and (self.none is None or self.none) return condition acc = Accumulator() also = acc.also if also(condition1): action1() i...
Excluding directory
24,495,088
4
2014-06-30T16:48:47Z
24,495,151
7
2014-06-30T16:52:44Z
[ "python", "django", "static-analysis", "pyflakes" ]
I am working on a django project and am trying to run pyflakes on an app in it. I need to exclude the "migrations" directory from pyflakes. For pep8 I can do ``` pep8 --exclude=migrations app_name ``` Is there any similar way for pyflakes? I couldn't find any proper documentation for pyflakes.
Use [`flake8`](https://pypi.python.org/pypi/flake8) tool instead - it is a wrapper around `pyflakes`, `pep8` and `mccabe`. Besides other features, it has an `--exclude` option: ``` --exclude=patterns exclude files or directories which match these comma separated patterns (default: ...
Pandas: Get unique MultiIndex level values by label
24,495,695
14
2014-06-30T17:30:57Z
24,496,435
23
2014-06-30T18:18:25Z
[ "python", "pandas" ]
Say you have this MultiIndex-ed DataFrame: ``` df = pd.DataFrame({'co':['DE','DE','FR','FR'], 'tp':['Lake','Forest','Lake','Forest'], 'area':[10,20,30,40], 'count':[7,5,2,3]}) df = df.set_index(['co','tp']) ``` Which looks like this: ``` area count...
I guess u want unique values in a certain level (and by level names) of a multiindex. I usually do the following, which is a bit long. ``` In [11]: df.index.get_level_values('co').unique() Out[11]: array(['DE', 'FR'], dtype=object) ```
Set a Read-Only Attribute in Python?
24,497,316
10
2014-06-30T19:16:01Z
24,498,525
11
2014-06-30T20:36:30Z
[ "python", "python-2.7", "stdout", "readonlyattribute" ]
Given how dynamic Python is, I'll be shocked if this isn't somehow possible: I would like to change the implementation of `sys.stdout.write`. I got the idea from this answer to another question of mine: <http://stackoverflow.com/a/24492990/901641> I tried to simply write this: ``` original_stdoutWrite = sys.stdout....
Despite its dynamicity, Python does not allow monkey-patching built-in types such as `file`. It even prevents you to do so by modifying the `__dict__` of such a type — the `__dict__` property returns the dict wrapped in a read-only proxy, so both assignment to `file.write` and to `file.__dict__['write']` fail. And fo...
Generator vs Sequence object
24,499,624
5
2014-06-30T22:01:22Z
24,499,682
9
2014-06-30T22:06:59Z
[ "python" ]
I know the difference between `range` and `xrange`. But I was surprised to see that `xrange` wasn't a`generator` but a `sequence object`. What's the difference then, how to create a `sequence object` and when used it over a `generator`?
The reason that `xrange` is a sequence object is because it supports the [sequence methods interface](https://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange). For example you can index it (which is something you can't do with a vanilla generator): ``` print xrange...
sort mongodb documents by timestamp (in desc order)
24,501,756
5
2014-07-01T02:41:16Z
24,501,957
11
2014-07-01T03:11:15Z
[ "python", "mongodb", "timestamp" ]
I have a bunch of documents in mongodb and all have a timestamp field with timestamp stored as "1404008160". I want to sort all docs in this collection by desc order. I do it by: ``` sort = [('timestamp', DESCENDING)] collection.find(limit=10).sort(sort) ``` However, I don't get results sorted by timestamp in desc or...
Assuming your timestamp indicates when the document was created, [you can use `_id` instead](http://docs.mongodb.org/manual/reference/object-id/#convert-an-objectid-into-a-timestamp). `_id` ObjectId in mongo stores your timestamp. Try the following: ``` sort = {'_id': -1} collection.find({}, limit=10).sort(sort) ``` ...
What's causing this error when I try and install virtualenv? IOError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/virtualenv.py'
24,504,231
7
2014-07-01T07:01:44Z
24,504,466
8
2014-07-01T07:15:05Z
[ "python", "flask", "virtualenv" ]
I'm trying to install a virtual environment using the command: `pip install virtualenv` but I get the following error: `IOError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/virtualenv.py'` How do I fix this?
At a glance it looks like you need admin permissions to install packages on your system. Try starting pip as admin or your OS equivalent.
How to limit log file size in python
24,505,145
6
2014-07-01T07:55:02Z
24,505,345
13
2014-07-01T08:09:00Z
[ "python", "logging", "filehandler", "log-files" ]
I am using windows 7 and python 2.7 I want to limit my log file size to 5MB. My app when starts writes to log file, and then app terminates. When again my app starts, it will write in same log file. So app is not continuosly running. App initiates, do process and terminates. My code for logging is: ``` import logging...
Lose basicConfig and try this: ``` import logging from logging.handlers import RotatingFileHandler log_formatter = logging.Formatter('%(asctime)s %(levelname)s %(funcName)s(%(lineno)d) %(message)s') logFile = 'C:\\Temp\\log' my_handler = RotatingFileHandler(logFile, mode='a', maxBytes=5*1024*1024, ...
How to deal with certificates using Selenium?
24,507,078
29
2014-07-01T09:41:34Z
24,508,400
8
2014-07-01T10:49:11Z
[ "python", "selenium", "python-3.x", "selenium-webdriver", "browser" ]
I am using [Selenium](http://en.wikipedia.org/wiki/Selenium_%28software%29) to launch a browser. How can I deal with the webpages (URLs) that will ask the browser to accept a certificate or not? In Firefox, I may have a website like that asks me to accept its certificate like this: ![Firefox](http://i.stack.imgur.com...
For Firefox: ``` ProfilesIni profile = new ProfilesIni(); FirefoxProfile myprofile = profile.getProfile("default"); myprofile.setAcceptUntrustedCertificates(true); myprofile.setAssumeUntrustedCertificateIssuer(true); WebDriver driver = new FirefoxDriver(myprofile); ``` For **Chrome** we can use: ``` DesiredCapabilit...
How to deal with certificates using Selenium?
24,507,078
29
2014-07-01T09:41:34Z
25,063,706
35
2014-07-31T15:59:33Z
[ "python", "selenium", "python-3.x", "selenium-webdriver", "browser" ]
I am using [Selenium](http://en.wikipedia.org/wiki/Selenium_%28software%29) to launch a browser. How can I deal with the webpages (URLs) that will ask the browser to accept a certificate or not? In Firefox, I may have a website like that asks me to accept its certificate like this: ![Firefox](http://i.stack.imgur.com...
For the Firefox, you need to set `accept_untrusted_certs` `FirefoxProfile()` option to `True`: ``` from selenium import webdriver profile = webdriver.FirefoxProfile() profile.accept_untrusted_certs = True driver = webdriver.Firefox(firefox_profile=profile) driver.get('https://cacert.org/') driver.close() ``` For C...
Swapping Columns with NumPy arrays
24,507,550
5
2014-07-01T10:06:24Z
24,507,847
7
2014-07-01T10:20:43Z
[ "python", "arrays", "numpy", "iterable-unpacking" ]
When I have `a=1` and `b=2`, I can write `a,b=b,a` so that `a` and `b` are interchanged with each other. I use this matrix as an array: ``` [ 1, 2, 0, -2] [ 0, 0, 1, 2] [ 0, 0, 0, 0] ``` Swapping the columns of a numpy array does not work: ``` import numpy as np x = np.array([[ 1, 2, 0, -2], ...
When you use the `x[:] = y[:]` syntax with a numpy array, the values of y are copied directly into x; no temporaries are made. So when you do `x[:, 1], x[:,2] = x[:, 2], x[:, 1]`, first the third column of x is copied directly into the second column, and then the second column is copied directly into the third. The se...
Finding network (external) IP addresses using Python
24,508,730
8
2014-07-01T11:06:12Z
24,509,080
11
2014-07-01T11:24:36Z
[ "python", "ip", "python-2.x" ]
I want to know my internet provider (external) IP address (broadband or something else) with Python. There are multiple machines are connected to that network. I tried in different way's but I got only the local and public IP my machine. How do I find my external IP address through Python? Thanks in advance.
Use this script : ``` import urllib, json data = json.loads(urllib.urlopen("http://ip.jsontest.com/").read()) print data["ip"] ``` Without json : ``` import urllib, re data = re.search('"([0-9.]*)"', urllib.urlopen("http://ip.jsontest.com/").read()).group(1) print data ```
Finding network (external) IP addresses using Python
24,508,730
8
2014-07-01T11:06:12Z
36,984,432
7
2016-05-02T14:05:51Z
[ "python", "ip", "python-2.x" ]
I want to know my internet provider (external) IP address (broadband or something else) with Python. There are multiple machines are connected to that network. I tried in different way's but I got only the local and public IP my machine. How do I find my external IP address through Python? Thanks in advance.
Secure option (with `https` support) ``` from requests import get get('https://ipapi.co/ip/').text ``` Complete [JSON response](https://ipapi.co/json/) P.S. `requests` module is convenient for `https` support. You can try [httplib](http://stackoverflow.com/a/2146467/6250071) though.
How to partially copy using python an Hdf5 file into a new one keeping the same structure?
24,510,240
4
2014-07-01T12:25:16Z
24,532,983
8
2014-07-02T13:52:48Z
[ "python", "hdf5", "h5py" ]
I have a large hdf5 file that looks something like this: ``` A/B/dataset1, dataset2 A/C/dataset1, dataset2 A/D/dataset1, dataset2 A/E/dataset1, dataset2 ``` ... I want to create a new file with only that: A/B/dataset1, dataset2 A/C/dataset1, dataset2 What is the easiest way in python? I did: ``` fs = h5py.File('s...
`fs.copy('A/B', fd)` doesn't copy the path `/A/B/` into `fd`, it only copies the group `B` (as you've found out!). So you first need to create the rest of the path: ``` fd.create_group('A') fs.copy('A/B', fd['/A']) ``` or, if you will be using the group a lot: ``` fd_A = fd.create_group('A') fs.copy('A/B', fd_A) ```...
Installing external or unverified packages with Pip on Elastic Beanstalk
24,511,572
5
2014-07-01T13:31:11Z
24,512,040
8
2014-07-01T13:53:30Z
[ "python", "pip" ]
I'm attempting to deploy a Django application to Elastic Beanstalk. When it comes to installing from `requirements.txt`, Python complains that some of my requirements require the `--allow-external` or `--allow-unverified` flags. How do I set these flags in the configuration file?
According to the latest (1.5.6) documentation [Requirements File Format](https://pip.pypa.io/en/latest/reference/pip_install.html#requirements-file-format): > Additionally, the following Package Index Options are supported: > > ``` > -i, -–index-url > –-extra-index-url > –-no-index > -f, -–find-links > -–all...
traceback from a warning
24,513,013
10
2014-07-01T14:38:35Z
24,513,078
24
2014-07-01T14:41:40Z
[ "python", "warnings", "traceback" ]
I have a code which, at some point shows a warning, I think that it is having a problem calculating a `mean()` I would like to know if there is any way to force python to tell me where, or which line, or whatever more information than just this message: ``` C:\Python27\lib\site-packages\numpy\core\_methods.py:55: Run...
You can turn warnings into exceptions: ``` import warnings warnings.simplefilter("error") ``` Now instead of printing a warning, an exception will be raised, giving you a traceback. You can play with the other [`warnings.simplefilter()` arguments](https://docs.python.org/2/library/warnings.html#warnings.simplefilte...
Get all combinations of neighbour elements in list
24,515,991
3
2014-07-01T17:19:13Z
24,516,041
8
2014-07-01T17:22:53Z
[ "python", "list", "math", "combinations" ]
Is it possible to get all combinations of elements in case they are neighbours? Here is the example: EDIT: I want to use it on strings, not only numbers. For example: `[Explain,it,to,me,please]` List: ``` [0,1,2,3,4] ``` Result: ``` [0,1,2,3,4], [0,1,2,3], [1,2,3,4], [0,1,2], [1,2,3], [2,3,4], [0,1], [1,2], [2,3...
You can do: ``` >>> L = [0,1,2,3,4] >>> result = [L[i:j] for i in xrange(len(L)) for j in xrange(i + 1, len(L) + 1)] >>> pprint.pprint(result) [[0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4], [1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [2], [2, 3], [2, 3, 4], [3], [3, 4], [4]] ``` Then, to sort by desc...
PyCharm with Git. Shall I ignore the .idea folder?
24,516,814
7
2014-07-01T18:15:09Z
24,530,928
8
2014-07-02T12:19:03Z
[ "python", "git", "pycharm" ]
The question is all in the title. I read about Git integration in PyCharm, and created a Git repository from PyCharm. I did this in PyCharm because I was hoping PyCharm would know whether the `.idea` folder should be ignored, and if that's the case, it would automatically create a `.gitignore` file with the line `.idea...
Ignoring the whole .idea folder is not necessarily the best idea. There's a number of similar discussions here about this. * [How to deal with IntelliJ IDEA project files under Git source control constantly changing?](http://stackoverflow.com/questions/7060727/how-to-deal-with-intellij-idea-project-files-under-git-sou...
Python official installer missing python27.dll
24,517,754
13
2014-07-01T19:20:30Z
25,917,824
14
2014-09-18T16:25:07Z
[ "python", "windows", "dll", "installation" ]
I installed Python 2.7.7 32-bit on Windows from official website and it is missing python27.dll. How can I get this DLL?
At least for the ActiveState Python distribution, and in the official Python distribution: <https://docs.python.org/2/faq/windows.html#id7> The dll is in ``` C:\Windows\System\PythonNN.dll ``` where NN is the version number. On a 64-bit, a 32 bit dll will be installed here: ``` %SystemRoot%\SysWoW64 ``` and a run...
Run Python script at startup in Ubuntu
24,518,522
11
2014-07-01T20:10:57Z
25,805,871
13
2014-09-12T10:11:08Z
[ "python", "linux", "shell", "ubuntu" ]
I have a short Python script that needs to run at startup - Ubuntu 13.10. I have tried everything I can think of but can't get it to run. The script: ``` #!/usr/bin/python import time with open("/home/username/Desktop/startup.txt", 'a') as f: f.write(str(time.time()) + " It worked!") ``` (The actual script is a b...
Put this in `/etc/init` (Use `/etc/systemd` in Ubuntu 15.x) **mystartupscript.conf** ``` start on runlevel [2345] stop on runlevel [!2345] exec /path/to/script.py ``` By placing this conf file there you hook into ubuntu's [upstart](http://upstart.ubuntu.com/cookbook/) service that runs services on startup. manual ...
Try/except when using Python requests module
24,518,944
3
2014-07-01T20:42:41Z
24,519,419
7
2014-07-01T21:18:20Z
[ "python", "python-requests", "try-except" ]
Doing some API testing and trying to create a function that given an inputted URL it will return the json response, however if a HTTP error is the response an error message will be returned. I was using urllib2 before, but now trying to use requests instead. However it looks like my except block is never executed, reg...
How you handle this all depends on what you consider an HTTP error. There's status codes, but not everything other than `200` necessarily means there's an error of some sort. As you noticed, the request library considers those just another aspect of a HTTP response and doesn't raise an exception. HTTP status `302` for...
Regex to Match "Chinese+Number" pattern in Python
24,522,394
2
2014-07-02T03:24:30Z
24,522,549
9
2014-07-02T03:46:58Z
[ "python", "regex" ]
In Python 3.3, I want to match the pattern below, but it keeps failing. ``` 摄氏零下253 ``` I used the regex below. ``` [^\x00-\x47\x58-\x7F]+ ``` Dosen't it exclude all of ascii except digits?
Depending on what programming language you are using, you could use the following. ``` [\p{Han}\p{N}]+ ``` > `\p{Han}` matches characters in the Han script. > `\p{N}` matches any kind of numeric character in any script. [**Live Demo**](http://regex101.com/r/xG0oF5/2)
Python program hangs forever when called from subprocess
24,522,467
34
2014-07-02T03:35:07Z
24,543,006
19
2014-07-03T00:07:44Z
[ "python", "subprocess" ]
The pip test suite employs subprocess calls to run integration tests. Recently a PR was placed which removed some older compatability code. Specically it replaced a `b()` function with explicitly uses of the `b""` literal. However this has seemingly broken something to where a particular subprocess call will hang forev...
In Python 2, if a set of objects are linked together in a chain (reference cycle) and, at least, one object has a `__del__` method, the garbage collector will not delete these objects. If you have a reference cycle, adding a `__del__()` method may just hide bugs (workaround bugs). According to your update #3, it looks...
How can I add N milliseconds to a datetime in Python
24,522,793
8
2014-07-02T04:18:47Z
24,522,827
11
2014-07-02T04:22:17Z
[ "python", "datetime" ]
I'm setting a datetime var as such: ``` fulldate = datetime.datetime.strptime(date + ' ' + time, "%Y-%m-%d %H:%M:%S.%f") ``` where date and time are string of the appropriate nature for datetime. How can I increment this datetime by N milliseconds?
Use `timedelta` To increment by 500 ms: ``` fulldate = datetime.datetime.strptime(date + ' ' + time, "%Y-%m-%d %H:%M:%S.%f") fulldate = fulldate + datetime.timedelta(milliseconds=500) ``` You can use it to increment minutes, hours, days etc. Documentation: <https://docs.python.org/2/library/datetime.html#timedelta-...
How can I get the output of a matplotlib plot as an SVG?
24,525,111
11
2014-07-02T07:19:55Z
24,534,503
11
2014-07-02T15:00:00Z
[ "python", "svg", "matplotlib", "interpolation", "cairo" ]
I need to take the output of a matplotlib plot and turn it into an SVG path that I can use on a laser cutter. ``` import matplotlib.pyplot as plt import numpy as np x = np.arange(0,100,0.00001) y = x*np.sin(2*pi*x) plt.plot(y) plt.show() ``` For example, below you see a waveform. I would like to be able to output or ...
Depending on the backend you use (I tested on TkAgg and Agg) it should be as easy as specifying it within the savefig() call: ``` import matplotlib.pyplot as plt ...
How can I get the output of a matplotlib plot as an SVG?
24,525,111
11
2014-07-02T07:19:55Z
24,535,532
14
2014-07-02T15:45:00Z
[ "python", "svg", "matplotlib", "interpolation", "cairo" ]
I need to take the output of a matplotlib plot and turn it into an SVG path that I can use on a laser cutter. ``` import matplotlib.pyplot as plt import numpy as np x = np.arange(0,100,0.00001) y = x*np.sin(2*pi*x) plt.plot(y) plt.show() ``` For example, below you see a waveform. I would like to be able to output or ...
You will most probably want to fix the image size and get rid of all sorts of backgrounds and axis markers: ``` import matplotlib.pyplot as plt import numpy as np plt.figure(figsize=[6,6]) x = np.arange(0,100,0.00001) y = x*np.sin(2*pi*x) plt.plot(y) plt.axis('off') plt.gca().set_position([0, 0, 1, 1]) plt.savefig("t...
Building Cython-compiled python code with PyInstaller
24,525,861
13
2014-07-02T07:59:46Z
31,025,619
9
2015-06-24T11:44:00Z
[ "python", "cython", "pyinstaller" ]
I am trying to build a Python multi-file code with `PyInstaller`. For that I have compiled the code with `Cython`, and am using `.so` files generated in place of `.py` files. Assuming the 1st file is `main.py` and the imported ones are `file_a.py` and `file_b.py`, I get `file_a.so` and `file_b.so` after Cython compila...
So I got this to work for you. Please have a look at [Bundling Cython extensions with Pyinstaller](https://github.com/prologic/pyinstaller-cython-bundling) **Quick Start:** ``` git clone https://github.com/prologic/pyinstaller-cython-bundling.git cd pyinstaller-cython-bundling ./dist/build.sh ``` This produces a st...
Split a generator into chunks without pre-walking it
24,527,006
14
2014-07-02T09:04:00Z
24,527,424
21
2014-07-02T09:24:40Z
[ "python", "generator" ]
(This question is related to [this one](http://stackoverflow.com/q/8290397/647991) and [this one](http://stackoverflow.com/q/312443/647991), but those are pre-walking the generator, which is exactly what I want to avoid) I would like to split a generator in chunks. The requirements are: * do not pad the chunks: if th...
One way would be to peek at the first element, if any, and then create and return the actual generator. ``` def head(iterable, max=10): first = next(iterable) # raise exception when depleted def head_inner(): yield first # yield the extracted first element for cnt, el in enumer...
Why does Django South 1.0 use iteritems()?
24,529,618
19
2014-07-02T11:10:58Z
24,529,760
23
2014-07-02T11:17:54Z
[ "python", "django", "python-3.x", "django-south" ]
I've just installed South 1.0 and when I was about to do my first migration I got this error message: ``` ... /lib/python3.4/site-packages/south/migration/migrators.py", line 186, in _run_migration for name, db in south.db.dbs.iteritems(): AttributeError: 'dict' object has no attribute 'iteritems' ``` I've fixed it b...
**Update**: South 1.0.1 was released on October 27th, 2014, which [includes the fix for this issue](https://bitbucket.org/andrewgodwin/south/src/6927b49f3e36b62c06c061aa69387dc2cf8f891e/docs/releasenotes/1.0.1.rst?at=1.0.1): > ### South 1.0.1 > > This is a small bugfix release of South with two changes: > > * Python 3...
Collaborative filtering in Python
24,530,925
5
2014-07-02T12:18:53Z
24,877,135
7
2014-07-22T00:43:01Z
[ "python", "graphlab" ]
I work now with the [Graphlab](http://graphlab.org/projects/index.html). After installing of this program, I could run the algorithms of Collaborative filtering. Now I try to work with Graphlab in the Python. I have found already this brilliant [toolkits](http://graphlab.com/products/create/docs/graphlab.toolkits.html#...
Check out the [recommender package](http://graphlab.com/products/create/docs/graphlab.toolkits.recommender.html) in GraphLab Create. It lets you create a collaborative filtering model in just a few lines. ``` import graphlab sf = graphlab.SFrame.read_csv('my_data.csv') m = graphlab.recommender.create(data) recs = m.re...
Working with unicode keys in a python dictionary
24,532,229
4
2014-07-02T13:20:20Z
24,532,329
9
2014-07-02T13:24:22Z
[ "python", "twitter", "dictionary", "unicode" ]
I am learning about the Twitter API using Python 2.7.x. I've saved a number of random tweets and I am trying to process them. Each tweet is converted to a dictionary with json.loads and all the dictionaries are part of a list. Given a single tweet, I want to be able to extract certain fields from the dictionary. The k...
Python 2 handles translation between `str` and `unicode` keys transparently for you, provided the text can be encoded to ASCII: ``` >>> d = {u'text': u'Foo'} >>> d.keys() [u'text'] >>> 'text' in d True >>> u'text' in d True >>> d['text'] u'Foo' >>> d[u'text'] u'Foo' ``` This means that if you get a `KeyError` for `tw...
How to mock os.walk in python with a temporary filesystem?
24,533,243
11
2014-07-02T14:05:38Z
24,533,453
13
2014-07-02T14:14:43Z
[ "python", "testing", "mocking", "python-mock" ]
I'm trying to test some code that uses os.walk. I want to create a temporary, in-memory filesystem that I can populate with sample (empty) files and directories that os.walk will then return. This should save me the complexity of mocking os.walk calls to simulate recursion. Specifically, the code I want to test is: `...
No. `os.walk()` is constructed entirely around [`os.listdir()`](https://docs.python.org/2/library/os.html#os.listdir), with assistance of `os.path.islink()` and `os.path.isdir()`. These are essentially system calls, so you'd have to mock your filesystem *at the system level*. Unless you want to write a [FUSE plugin](ht...
Difference between "data" and "params" in Python requests?
24,535,920
7
2014-07-02T16:03:36Z
24,535,938
12
2014-07-02T16:04:21Z
[ "python", "python-requests" ]
I was curious what the difference was between the `data` parameter and the `params` parameter in a `python-requests` request, and when each should be used. One example is I have an array of dicts `users=[{"email_hash": "fh7834uifre8houi3f"}, ... ]` and I try to do a POST (`requests.post()`) with ``` params = { "a...
`params` form the [*query string*](http://en.wikipedia.org/wiki/Query_string) in the URL, `data` is used to fill the *body* of a request (together with `files`). `GET` and `HEAD` requests have no body. For the *majority* of servers accepting a `POST` request, the data is expected to be passed in as the request *body*....
Custom Authenication(User Model) for Cloud Endpoints-Python
24,537,865
10
2014-07-02T17:55:27Z
24,725,978
11
2014-07-13T18:37:05Z
[ "python", "google-app-engine", "google-cloud-endpoints" ]
I am developing an Android application with a GAE backend, for sessions etc. I want to use Google Cloud Endpoint and develop an API with custom authentication user model. I dont want to use the google's oauth. I want to implement a simple email/pass user authentication model with a session based token. I have no experi...
You're in for a ride. It's not a simple process, but I've managed to do just what you're looking for--albeit in a slightly hackish way. First, there's a boilerplate project for GAE (in Python) that implements a custom email/pwd login system using webapp2's extras: <http://appengine.beecoss.com/> It follows the guidel...
Regarding The os.fork() Function In Python
24,538,466
6
2014-07-02T18:29:24Z
24,538,619
12
2014-07-02T18:37:59Z
[ "python", "fork" ]
I'm just beginning with python and I developed a simple program to fork a parent process. Here's the code I've written so far... ``` #!/usr/bin/env python import os def child(): print "We are in the child process with PID= %d"%os.getpid() def parent(): print "We are in the parent process with PID= %d"%os.get...
After you return from `fork`, you now have *two processes* executing the code immediately following `fork`. So your statement: > since we are already in the parent process is only half-true. After `os.fork` returns, the parent process continues executing the code as the parent process, but the child process continue...
Python Asyncio subprocess never finishes
24,541,192
5
2014-07-02T21:18:05Z
24,542,396
9
2014-07-02T22:57:47Z
[ "python", "python-asyncio" ]
i have a simple python program that I'm using to test asyncio with subprocesses: ``` import sys, time for x in range(100): print("processing (%s/100) " % x) sys.stdout.flush() print("enjoy") sys.stdout.flush() ``` Running this on the command line produces the desired results. However, when called from asy...
I suspect your issue is just related to how you're calling `asyncio.create_subprocess_exec` and `process.communiate()`. This complete example works fine for me: ``` import asyncio from asyncio import subprocess @asyncio.coroutine def do_work(): process = yield from asyncio.create_subprocess_exec( *["pytho...
Calling R script from python using rpy2
24,544,190
6
2014-07-03T02:53:07Z
24,544,362
9
2014-07-03T03:17:32Z
[ "python", "call", "rpy2" ]
I'm very new to rpy2, as well as R. I basically have a R script, script.R, which contains functions, such as rfunc(folder). It is located in the same directory as my python script. I want to call it from Python, and then launch one of its functions. I do not need any output from this R function. I know it must be very...
`source` is a `r` function, which runs a `r` source file. Therefore in `rpy2`, we have two ways to call it, either: ``` r['source']("script.R") ``` or ``` r.source("script.R") ``` `r[r.source("script.R")]` is a wrong way to do it. Same idea may apply to the next line.
How to get IP address of the launched instance with Boto
24,547,010
4
2014-07-03T07:00:19Z
24,547,413
8
2014-07-03T07:20:16Z
[ "python", "amazon-ec2", "boto", "openstack" ]
I am launching instance in openstack using boto ``` myinstance = conn.run_instances('ami-0000007d',min_count=1,max_count=1, instance_type = 'm1.small') newmachine=myinstance.instances[0] ``` newMachine has the info related to the launched instance. I have tried ``` vars(newmachine) ``` and the ip\_address and priv...
Refresh the value until the instance enters Running state. At that point, the IP should be present (not that there's anything you could do with the IP before the instance is in running state). ``` reservation = conn.run_instances(...) instance = reservation.instances[0] while instance.update() != "running": time...
How to make matplotlib graphs look professionally done like this?
24,547,047
5
2014-07-03T07:02:09Z
24,549,558
9
2014-07-03T09:11:50Z
[ "python", "matplotlib", "plot", "data-visualization" ]
Default matplotlib graphs look really unattractive and even unprofessional. I tried out couple of packages include seaborn as well as prettyplotlib but both of these just barely improves the styles. So far I've gotten to following using seaborn package: ![enter image description here](http://i.stack.imgur.com/YVZ1I.p...
This is really a matter of taste, and also a matter of target audience. `matplotlib` tries to produce clear illustrations for scientific purposes. This is - necessarily - a compromise, and the illustrations are not something you would print in a magazine or show in an advertisement. There are some good news and some b...
Is del or pop preferred when removing elements from dicts
24,547,223
3
2014-07-03T07:10:15Z
24,547,309
7
2014-07-03T07:14:33Z
[ "python", "python-2.7" ]
I'm relatively new to Python, and was wondering if there is any reason to prefer one of these methods over the other when removing elements from a `dict`? **A) Using `del`** ``` # d is a dict, k is a key if k in d: del k ``` **B) Using `pop`** ``` d.pop(k, None) ``` My first thought was that approach (A) needs ...
I would not worry about the performance differences unless you have specific reason to believe that they are causing meaningful slowdowns in your program, which is unlikely. The real reason you might choose to use `del` vs `pop` is because they have different behaviors. `pop` returns the value for the popped key, so y...
Python: Length of longest common subsequence of lists
24,547,641
3
2014-07-03T07:32:56Z
24,547,864
7
2014-07-03T07:43:40Z
[ "python", "list", "longest-substring" ]
Is there a built-in function in python which returns a length of longest common subsequence of two lists? ``` a=[1,2,6,5,4,8] b=[2,1,6,5,4,4] print a.llcs(b) >>> 3 ``` I tried to find longest common subsequence and then get length of it but I think there must be a better solution.
You can easily retool a LCS into a LLCS: ``` def lcs_length(a, b): table = [[0] * (len(b) + 1) for _ in xrange(len(a) + 1)] for i, ca in enumerate(a, 1): for j, cb in enumerate(b, 1): table[i][j] = ( table[i - 1][j - 1] + 1 if ca == cb else max(table[i][j - 1...
How to go back in PyCharm while browsing code like we have a back button in eclipse?
24,548,398
12
2014-07-03T08:15:02Z
24,548,487
17
2014-07-03T08:19:14Z
[ "python", "intellij-idea", "pycharm", "intellij-plugin" ]
While browsing the code in PyCharm(community edition) how to go back to the previously browsed section? I am looking for eclipse back button type functionality with Pycharm.
in pycharm you have `view` in view please make sure that `toolbar` is checked ![enter image description here](http://i.stack.imgur.com/v9E63.png) ![enter image description here](http://i.stack.imgur.com/bsPqF.png)
How to go back in PyCharm while browsing code like we have a back button in eclipse?
24,548,398
12
2014-07-03T08:15:02Z
24,550,763
9
2014-07-03T10:07:37Z
[ "python", "intellij-idea", "pycharm", "intellij-plugin" ]
While browsing the code in PyCharm(community edition) how to go back to the previously browsed section? I am looking for eclipse back button type functionality with Pycharm.
You could use `Ctrl + Alt + Left Arrow` (which is more convenient from my point of view) or clicking arrows as [suggested](http://stackoverflow.com/a/24548487/3240679).
Why doesn't unicodedata recognise certain characters?
24,552,786
9
2014-07-03T11:42:30Z
24,553,272
7
2014-07-03T12:06:12Z
[ "python", "unicode" ]
In Python 2 at least, `unicodedata.name()` doesn't recognise certain characters. ``` ActivePython 2.7.0.2 (ActiveState Software Inc.) based on Python 2.7 (r27:82500, Aug 23 2010, 17:17:51) [MSC v.1500 64 bit (AMD64)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> from unicodedata ...
The `unicodedata.name()` lookup relies on column 2 of the [UnicodeData.txt database in the standard](http://www.unicode.org/Public/5.2.0/ucd/UnicodeData.txt) (Python 2.7 uses Unicode 5.2.0). If that name starts with `<` it is ignored. All control codes, including newlines, are in that category; the first column has *n...
python numpy ValueError: operands could not be broadcast together with shapes
24,560,298
16
2014-07-03T17:52:22Z
24,564,003
10
2014-07-03T22:08:51Z
[ "python", "numpy" ]
In numpy, I have two "arrays", X is (m,n) and y is a vector (n,1) using ``` X*y # or, even np.dot(X,y) ``` I am getting the error ``` ValueError: operands could not be broadcast together with shapes (97,2) (2,1) ``` When (97,2)x(2,1) is clearly a legal matrix operation and should give me a (97,1) vector EDIT: I ...
We have two arrays: * `X`, shape (97,2) * `y`, shape (2,1) With Numpy arrays the operation ``` X * y ``` is done element-wise, but one or both of the values can be expanded in one or more dimensions to make them compatible. This operation are called broadcasting. Dimensions where size is 1 or which are missing can ...
python numpy ValueError: operands could not be broadcast together with shapes
24,560,298
16
2014-07-03T17:52:22Z
24,564,015
7
2014-07-03T22:10:05Z
[ "python", "numpy" ]
In numpy, I have two "arrays", X is (m,n) and y is a vector (n,1) using ``` X*y # or, even np.dot(X,y) ``` I am getting the error ``` ValueError: operands could not be broadcast together with shapes (97,2) (2,1) ``` When (97,2)x(2,1) is clearly a legal matrix operation and should give me a (97,1) vector EDIT: I ...
Per Wes McKinney's *Python for Data Analysis* > **The Broadcasting Rule**: Two arrays are compatable for broadcasting if for each *trailing dimension* (that is, starting from the end), the axis lengths match or if either of the lengths is 1. Broadcasting is then performed over the missing and/or length 1 dimensions. ...
Directly Reference Python's Standard Library
24,562,216
2
2014-07-03T19:49:39Z
24,562,251
8
2014-07-03T19:51:18Z
[ "python", "python-2.7", "pyqt4", "standard-library" ]
So it turns out that PyQt redefines a function `hex()`, which unfortunately renders the python standard library `hex()` unusable. I'm working on a large software project and it's been set up with \*imports: ``` from PyQt4.QtCore import * from PyQt4.QtGui import * ``` ...etc I need the standard python `hex()` functio...
``` from __builtin__ import hex ``` Use the [`__builtin__` module](https://docs.python.org/2/library/__builtin__.html).
pandas unable to read from large StringIO object
24,562,869
8
2014-07-03T20:33:50Z
24,563,849
13
2014-07-03T21:53:53Z
[ "python", "csv", "pandas", "stringio", "cstringio" ]
I'm using pandas to manage a large array of 8-byte integers. These integers are included as space-delimited elements of a column in a comma-delimited CSV file, and the array size is about 10000x10000. Pandas is able to quickly read the comma-delimited data from the first few columns as a DataFrame, and also quickly st...
There are two issues here, one fundamental and one you simply haven't come across yet. :^) First, after you write to `c`, you're at the end of the (virtual) file. You need to `seek` back to the start. We'll use a smaller grid as an example: ``` >>> a = np.random.randint(0,256,(10,10)).astype('uint8') >>> b = pd.DataF...
Bulk-fetching emails in the new Gmail API
24,562,981
15
2014-07-03T20:42:25Z
24,586,740
13
2014-07-05T13:04:41Z
[ "python", "google-api", "gmail-api" ]
I'm using the python version of the newly released Gmail API by Google. The following call returns just a list of message ids: ``` service.users().messages().list(userId = 'me').execute() ``` But then I just have a list of message ids and need to iterate over them and fetch them one-by-one. Is there a way to get th...
Here is an example of batch request in Java where I get all the threads using threads ids. This can be easily adapted for your need. ``` BatchRequest b = service.batch(); //callback function. (Can also define different callbacks for each request, as required) JsonBatchCallback<Thread> bc = new JsonBatchCallback<Thread...
demystify super in python?
24,564,908
3
2014-07-03T23:56:41Z
24,565,192
8
2014-07-04T00:40:17Z
[ "python", "super" ]
I was trying to understand how super works in python and tried the following example: ``` class A(object): def __init__(self): print "in A's init" class B(object): def __init__(self): print "in B's init" class C(A,B): def __init__(self): super(C,self).__init__() print "In ...
Python's *super()* should have been been called "next-in-mro" because it doesn't necessarily call upwards to a parent; rather, it can call a sibling instead. It is easy to inspect the method resolution order of your class structure: ``` >>> C.__mro__ (<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>...
Searching by related fields in django admin
24,569,687
9
2014-07-04T08:16:32Z
24,573,069
17
2014-07-04T11:15:20Z
[ "python", "django", "relational-database" ]
I've been looking at [the docs](https://docs.djangoproject.com/en/1.6/ref/contrib/admin/#django.contrib.admin.ModelAdmin.search_fields) for `search_fields` in django admin in the attempt to allow searching of related fields. So, here are some of my models. ``` # models.py class Team(models.Model): name = models.C...
The documentation reads: *These fields should be some kind of text field, such as `CharField` or `TextField`.* so you should use `'result__runner__team__name'`.
return max value from panda dataframe as a whole, not based on column or rows
24,571,005
6
2014-07-04T09:27:25Z
24,571,145
8
2014-07-04T09:34:53Z
[ "python", "pandas", "max", "dataframe" ]
I am trying to get the max value from a panda dataframe as whole. I am not interested in what row or column it came from. I am just interested in a single max value within the dataframe. Here is my dataframe: ``` df = pd.DataFrame({'group1': ['a','a','a','b','b','b','c','c','d','d','d','d','d'], ...
The max of all the values in the DataFrame can be obtained using `df.values.max()`: ``` In [10]: df.values.max() Out[10]: 'f' ``` The max is `f` rather than 43.0 since, in CPython2, ``` In [11]: 'f' > 43.0 Out[11]: True ``` In CPython2, [Objects of different types ... are ordered by their **type names**](http://doc...
Install python packages on OpenShift
24,572,276
3
2014-07-04T10:28:23Z
24,573,415
9
2014-07-04T11:37:03Z
[ "python", "openshift", "packages", "simplejson" ]
I'm trying to install python packages on OpenShift but I see a dearth of pages about the best way to do this. Can someone please suggest the best way of getting on say `oauth2` and `simplejson`. I've tried including these in the `setup.py`, but I have no idea whether these are actually available or I'll have to upload ...
Did you install `rhc` (made by OpenShift.com) ? If not then see on OpenShift.com: [Installing OpenShift RHC Client Tools](https://www.openshift.com/developers/rhc-client-tools-install) Now you can access server with `rhc` ``` rhc ssh ``` and then you can do as always: checking python version (with big V) ``` pyt...
Read file and plot CDF in Python
24,575,869
3
2014-07-04T13:52:00Z
24,576,863
7
2014-07-04T14:52:26Z
[ "python", "numpy", "matplotlib", "scipy", "cdf" ]
I need to read long file with timestamp in seconds, and plot of CDF using numpy or scipy. I did try with numpy but seems the output is NOT what it is supposed to be. The code below: Any suggestions appreciated. ``` import numpy as np import matplotlib.pyplot as plt data = np.loadtxt('Filename.txt') sorted_data = np.s...
You have two options: 1: you can bin the data first. This can be done easily with the `numpy.histogram` function: ``` import numpy as np import matplotlib.pyplot as plt data = np.loadtxt('Filename.txt') # Choose how many bins you want here num_bins = 20 # Use the histogram function to bin the data counts, bin_edge...
Flask Download a File
24,577,349
8
2014-07-04T15:23:24Z
24,578,372
10
2014-07-04T16:46:02Z
[ "python", "flask", "download" ]
Noob here. I'm trying to create a webapp with Flask that let a user upload a file and serve them to another user. Right now, I can upload the file to the upload\_folder correctly. But I can't seem to find a way to let the user download it back. I'm storing the name of the filename into a database. I got a view servin...
You need to make sure that `app.config['UPLOAD_FOLDER']` is an absolute path, corrected for the *current* location of your application. The best way to do this is to configure it as a relative path (no leading slash), then make it absolute by prepending `current_app.root_path`: ``` @app.route('/uploads/<path:filename...
Selenium can't connect to GhostDriver (but only sometimes)
24,578,879
7
2014-07-04T17:38:32Z
25,674,162
8
2014-09-04T20:09:00Z
[ "python", "selenium", "phantomjs", "ghostdriver" ]
I've setup a simple webscraping script in Python w/ Selenium and PhantomJS. I've got about 200 URLs in total to scrape. The script runs fine at first then after about 20-30 URLs (it can be more/less as it seems random when it fails and isn't related to any particular URL) I get the following error in python: ``` selen...
I had the same problem to fix it **I installed phantomjs from source**. ``` For Linux (Debian): sudo apt-get update sudo apt-get install build-essential chrpath git-core libssl-dev libfontconfig1-dev libxft-dev git clone git://github.com/ariya/phantomjs.git cd phantomjs git checkout 1.9 ./build.sh For Mac os: git clo...
Breaking ties in Python sort
24,579,202
2
2014-07-04T18:13:37Z
24,579,215
14
2014-07-04T18:15:19Z
[ "python", "sorting" ]
I have a `list` of `tuple`s, each tuple contains two integers. I need to sort the the list (in reverse order) according to the difference of the integers in each tuple, but break ties with the larger first integer. **Example** For `[(5, 6), (4, 1), (6, 7)]`, we should get `[(4, 1), (6, 7), (5, 6)]`. **My way** I ha...
Use a `key` function to `sorted()` and return a tuple; values will be sorted lexicographically: ``` sorted(yourlst, key=lambda t: (abs(t[0] - t[1])), t[0]), reverse=True) ``` I'm using `abs()` here to calculate a difference, regardless of which of the two integers is larger. For your sample input, the key produces `...
SciPy medfilt wrong result
24,585,706
4
2014-07-05T10:59:37Z
24,586,639
10
2014-07-05T12:53:02Z
[ "python", "numpy", "scipy", "median" ]
Hi python enthusiasts! I'm currently working with signal filtering for research purposes and decided to use SciPy. Nothing special, just automation of routine work. So, here is the code ``` from scipy.signal import medfilt print(medfilt([2,6,5,4,0,3,5,7,9,2,0,1], 5)) ``` But the matter is that returned sequense is ...
I believe that both you and SciPy have correct results. The difference is in what happens at the boundaries, but I believe that both you and SciPy have made valid choices. The question is **what should happen when your sliding window is at the edges, and there is no valid data to use to fill in your sliding window**. ...
Why does numpy.float16 break the OpenBlas/Atlas functionalities?
24,587,433
4
2014-07-05T14:31:40Z
24,590,380
11
2014-07-05T20:38:09Z
[ "python", "performance", "numpy", "atlas", "openblas" ]
Ok, I know `float16` is not a real primitive type, but it's simulated by Python/numpy. However, the question is: if that exists and Python allows to use it in arrays multiplication using the `numpy.dot()` function, why doesn't OpenBlas (or ATLAS) properly work? I mean, the multiplication works, but the parallel computa...
Numpy `float16` is a strange and possibly evil beast. It is an IEEE 754 half-precision floating point number with 1-bit of sign, 5 bits of exponent and 10 bits of mantissa. While it is a standard floating point number, it is a newcomer and not in wide use. Some GPUs support it, but the hardware support is not common i...
Convert date to float for linear regression on Pandas data frame
24,588,437
3
2014-07-05T16:32:18Z
24,590,666
12
2014-07-05T21:20:21Z
[ "python", "pandas", "time-series" ]
It seems that for OLS linear regression to work well in Pandas, the arguments must be floats. I'm starting with a csv (called "gameAct.csv") of the form: ``` date, city, players, sales 2014-04-28,London,111,1091.28 2014-04-29,London,100,1100.44 2014-04-28,Paris,87,1001.33 ... ``` I want to perform linear regressi...
For this kind of regression, I usually convert the dates or timestamps to an integer number of days since the start of the data. This does the trick nicely: ``` df = pd.read_csv('test.csv') df['date'] = pd.to_datetime(df['date']) df['date_delta'] = (df['date'] - df['date'].min()) / np.timedelta64(1,'D') city_dat...
How to cache sql alchemy calls with Flask-cache and redis?
24,589,123
11
2014-07-05T18:00:24Z
24,652,751
17
2014-07-09T11:41:26Z
[ "python", "sql", "redis", "sqlalchemy", "flask-cache" ]
I have a flask app that takes parameters from a web form, queries a DB w/ SQL alchemy and returns a jinja-generated template showing a table with the results. I want to cache the calls to the DB. I looked into redis, [Using redis as an LRU cache for postgres](http://stackoverflow.com/questions/24583263/using-redis-as-a...
You don't need to create custom `RedisCache` class. The docs is just teaching how you would create new backends that are not available in `flask-cache`. But `RedisCache` is already available in `werkzeug >= 0.7`, which you might have already installed because it is one of the core dependencies of flask. This is how I ...
Incorrect result with islower when using ctypes
24,590,878
4
2014-07-05T21:54:37Z
24,590,959
7
2014-07-05T22:08:26Z
[ "python", "c", "ctypes" ]
``` >>> from ctypes import * >>> import ctypes.util >>> libc = CDLL("libc.so.6") >>> libc.printf("%c\n", 104) h 2 >>> libc.islower(104) # Works fine 512 >>> libc.islower.restype = c_bool # But when i do this... >>> libc.islower(104) False >>> c_bool(512) c_bool(True) ``` personally, i think 'h' is lower case.. Is thi...
`restype` is not there just to tell the Python output type, but, most importantly, to tell what is the C type to expect, and thus how to marshal it. `islower` returns an `int`, which is typically 4 bytes wide; if you say it returns a `bool` (which is normally 1 byte) you are breaking the expectations of the marshaling ...
Is Beautiful Soup available for Python 3.4.1?
24,592,036
8
2014-07-06T01:50:18Z
24,592,072
14
2014-07-06T02:00:07Z
[ "python", "beautifulsoup" ]
I want to try and make a program that downloads images from the internet, and I have found a guide that uses Beautiful soup. I have heard of Beautiful Soup before, so I figured that I would try it out. My only issue is that I can't seem to find a version for Python 3. I went to their website, but I was unable to find a...
[BeautifulSoup4](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-beautiful-soup) installs fine with python3. ``` pip install beautifulsoup4 ``` Make sure your version of `pip` is for python3! ``` pip -V ```
Static files on OpenShift Django
24,595,223
4
2014-07-06T11:14:04Z
24,656,169
7
2014-07-09T14:16:47Z
[ "python", "django", "openshift" ]
I'm having issues serving up static files - i.e. style sheets and images required from my html pages. I cannot seem to fathom why these static images are not being found. Here is what I have in my `settings.py` ``` STATIC_URL = PROJECT_PATH + '/static/' # Additional locations of static files STATICFILES_DIRS = (P...
**1)** You've mixed up STATIC\_URL and STATIC\_ROOT variables. STATIC\_ROOT: Needs to point to the directory where you want your static files to be collected. In this case, it seems it is PROJECT\_PATH + '/static/'. **Make sure** this directory is correct. STATIC\_URL: The url your static files are accessed. /static/...
how to remove positive infinity from numpy array...if it is already converted to num a number?
24,599,618
5
2014-07-06T19:36:50Z
24,599,670
11
2014-07-06T19:43:37Z
[ "python", "numpy", "infinity", "graph-tool" ]
How does one remove positive infinity numbers from a numpy array once these are already converted into a number format? I am using a package which uses numpy internally, however when returning certain arrays, certain values are returned as the 1.79769313486e+308 positive infinity number. Is there an elegant and fast w...
First of all, `1.79769313486e+308` is not the same as `+inf`. The former is the largest number which can be expressed with a 64-bit float, the latter is a special float. If you just have very large numbers in your array, then: ``` A[A > 1e308] = 0 ``` is sufficient. Thet'll replace oll elements above `1e308` with 0....
How can I use functools.singledispatch with instance methods?
24,601,722
14
2014-07-07T00:50:41Z
24,602,374
16
2014-07-07T02:37:35Z
[ "python", "python-3.x", "python-3.4", "instance-method", "single-dispatch" ]
Python 3.4 [added](https://docs.python.org/3/library/functools.html#functools.singledispatch) the ability to define function overloading with static methods. This is essentially the example from the documentation: ``` from functools import singledispatch class TestClass(object): @singledispatch def test_meth...
Looking at the [source](http://hg.python.org/cpython/file/f6f691ff27b9/Lib/functools.py#l706) for `singledispatch`, we can see that the decorator returns a function `wrapper()`, which selects a function to call from those registered based on the type of `args[0]` ... ``` def wrapper(*args, **kw): return di...