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
Django's LiveServerTestCase Always Fails Due to Conflicting Address... Despite Address Appearing Free
20,619,846
10
2013-12-16T20:03:18Z
22,060,076
12
2014-02-27T05:47:44Z
[ "python", "django" ]
I'm currently working on cleaning my Django functional tests to use the LiveServerTestCase rather than bouncing selenium based tests off an instance of the development environment running in the background, and I've hit a wall. Every time I try to run a LiveServerTestCase test, I get the following error: ``` =========...
This started happening to me when running subsequent tests after a previous one generated an internal server error. On a mac, use lsof to find the program using the port, and kill it. E.g.: ``` $ sudo lsof -i :8081 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME firefox-b 1097 username 3u I...
Django's LiveServerTestCase Always Fails Due to Conflicting Address... Despite Address Appearing Free
20,619,846
10
2013-12-16T20:03:18Z
23,648,838
10
2014-05-14T08:00:57Z
[ "python", "django" ]
I'm currently working on cleaning my Django functional tests to use the LiveServerTestCase rather than bouncing selenium based tests off an instance of the development environment running in the background, and I've hit a wall. Every time I try to run a LiveServerTestCase test, I get the following error: ``` =========...
You can set (in settings.py) the environment variable DJANGO\_LIVE\_TEST\_SERVER\_ADDRESS to include multiple ranges of ports that will be attempted: ``` os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS']="localhost:8000-8010,8080,9200-9300" ``` Had the same issue myself, maybe this helps someone out.
pandas equivalent of Stata's encode
20,619,851
14
2013-12-16T20:03:40Z
20,619,971
16
2013-12-16T20:10:37Z
[ "python", "pandas", "stata" ]
I'm looking for a way to replicate the [encode](http://www.stata.com/help.cgi?encode) behaviour in Stata, which will convert a categorical string column into a number column. ``` x = pd.DataFrame({'cat':['A','A','B'], 'val':[10,20,30]}) x = x.set_index('cat') ``` Which results in: ``` val cat A 10 A ...
You could use `pd.factorize`: ``` import pandas as pd x = pd.DataFrame({'cat':('A','A','B'), 'val':(10,20,30)}) labels, levels = pd.factorize(x['cat']) x['cat'] = labels x = x.set_index('cat') print(x) ``` yields ``` val cat 0 10 0 20 1 30 ``` You could add 1 to `labels` if you wish to replic...
Comparing dictionaries based on a combination of keys
20,620,985
7
2013-12-16T21:11:12Z
20,621,333
8
2013-12-16T21:32:36Z
[ "python", "algorithm", "dictionary" ]
I have a list "records" like this ``` data = [ {'id':1, 'name': 'A', 'price': 10, 'url': 'foo'}, {'id':2, 'name': 'A', 'price': 20, 'url': 'bar'}, {'id':3, 'name': 'A', 'price': 30, 'url': 'baz'}, {'id':4, 'name': 'A', 'price': 10, 'url': 'baz'}, {'id':5, 'name': 'A', 'price': 20, 'url': 'bar'}, ...
The way to avoid doing this in `O(n^2)` time is to build an index for each query you want to do. Once you've got the machinery to query any value in constant time, your `O(n^2)` turns into `O(n)`, trivially. And you can build all of the indices in `O(n)` time, too. Assuming each of your values has the same fields, it ...
Pyplot: show only first 3 lines in legend
20,622,060
7
2013-12-16T22:17:21Z
20,622,111
10
2013-12-16T22:20:15Z
[ "python", "matplotlib" ]
I'm running a simulation 200 times and plotting the 3 output lists as 3 lines with high transparency. This allows me to show variance between simulations. The problem is that my legend shows 3x200 items instead of 3 items. How do I get it to show the legend for each line once? ``` for simulation in range(200): ...
add ``` plt.plot( ... , label='_nolegend_') ``` for any plotting that you do not want to show up in the legend. so in your code you may for example do: ``` ..., label='_nolegend_' if simulation else 'susceptible', ... ``` and similarly for others, or if you do not like iffy code: ``` ..., label=simulation and '_no...
Class() vs self.__class__() when creating object?
20,623,925
10
2013-12-17T00:53:09Z
20,623,981
9
2013-12-17T00:58:23Z
[ "python" ]
What are the advantages/disadvantages of using Class() or self.\_\_class\_\_() to create a new object within a class? Is one way generally preferred over the other? Here is a contrived example of what I am talking about. ``` class Foo(object): def __init...
`self.__class__` will use the type of a subclass if you call that method from a subclass instance. Using the class explicitly will use whatever class you explicitly specify (naturally) e.g.: ``` class Foo(object): def create_new(self): return self.__class__() def create_new2(self): return Fo...
TypeError: execv() arg 2 must contain only strings
20,624,342
3
2013-12-17T01:31:19Z
20,624,419
8
2013-12-17T01:39:30Z
[ "python" ]
I am getting the following error when running the script below,can anyhelp to identify what the problem is and how to overcome it ``` import subprocess import sys import os def main (): to = '' ssh_command = ["ssh", "-p", "29418", "review-android.quicinc.com", "gerrit", "query", "--format=J...
The third element in `ssh_command` is an integer. It needs to be a string. e.g: ``` ssh_command = ["ssh", "-p", 29418, ... # ^ problem ``` And the solution is simple, just add some quotes: ``` ssh_command = ["ssh", "-p", "29418", ... # ^Now it's a string. ```
Why can't LinearSVC do this simple classification?
20,624,353
3
2013-12-17T01:32:35Z
20,624,521
11
2013-12-17T01:52:15Z
[ "python", "scikit-learn", "libsvm", "liblinear" ]
I'm trying to do the following simple classification using the `LinearSVC` object in `scikit-learn`. I've tried using both version 0.10 and 0.14. Using the code: ``` from sklearn.svm import LinearSVC, SVC from numpy import * data = array([[ 1007., 1076.], [ 1017., 1009.], [ 2021., 2029....
The algorithm underlying `LinearSVC` is very sensitive to extreme values in its input: ``` >>> svc = LinearSVC(verbose=1) >>> svc.fit(data, groups) [LibLinear].................................................................................................... optimization finished, #iter = 1000 WARNING: reaching max ...
Python | Access the sole element of a set
20,625,579
9
2013-12-17T03:47:45Z
20,625,596
9
2013-12-17T03:49:30Z
[ "python", "set" ]
I have a `set` in Python from which I am removing elements one by one based on a condition. When the set is left with just 1 element, I need to return that element. How do I access this element from the set? A simplified example: ``` S = set(range(5)) for i in range(4): S = S - {i} # now S has only 1 element: 4 r...
Use [`set.pop`](http://docs.python.org/2.7/library/stdtypes.html#set.pop): ``` >>> {1}.pop() 1 >>> ``` In your case, it would be: ``` return S.pop() ``` --- Note however that this will remove the item from the set. If this is undesirable, you can use [`min`](http://docs.python.org/2.7/library/functions.html#min)|[...
Python | Access the sole element of a set
20,625,579
9
2013-12-17T03:47:45Z
22,693,614
9
2014-03-27T16:28:07Z
[ "python", "set" ]
I have a `set` in Python from which I am removing elements one by one based on a condition. When the set is left with just 1 element, I need to return that element. How do I access this element from the set? A simplified example: ``` S = set(range(5)) for i in range(4): S = S - {i} # now S has only 1 element: 4 r...
I would use: ``` e = next(iter(S)) ``` This is non-destructive and works even when there is more than one element in the set. You could also use unpacking: ``` e, = S ``` The unpacking technique is likely to be the fastest way and it includes error checking to make sure the set has only one member. The downside is...
How to deal with SettingWithCopyWarning in Pandas?
20,625,582
95
2013-12-17T03:48:02Z
20,627,316
118
2013-12-17T06:20:23Z
[ "python", "pandas" ]
I just upgraded my Pandas from 0.11 to 0.13.0rc1. Now, the application is popping out many new warnings. One of them like this: ``` E:\FinReporter\FM_EXT.py:449: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_index,col_indexer] = value instead quote_df['...
From what I gather, `SettingWithCopyWarning` was created to flag potentially confusing "chained" assignments, such as the following, which don't always work as expected, particularly when the first selection returns a *copy*. [see [GH5390](https://github.com/pydata/pandas/pull/5390) and [GH5597](https://github.com/pyda...
How to deal with SettingWithCopyWarning in Pandas?
20,625,582
95
2013-12-17T03:48:02Z
20,644,369
43
2013-12-17T20:49:10Z
[ "python", "pandas" ]
I just upgraded my Pandas from 0.11 to 0.13.0rc1. Now, the application is popping out many new warnings. One of them like this: ``` E:\FinReporter\FM_EXT.py:449: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_index,col_indexer] = value instead quote_df['...
In general the point of the `SettingWithCopyWarning` is to show users (and esp new users) that they *may* be operating on a copy and not the original as they think. There *are* False positives (IOW you know what you are doing, so it *ok*). One possibility is simply to turn off the (by default *warn*) warning as @Garret...
Using IF after Else in python
20,626,058
2
2013-12-17T04:41:32Z
20,626,085
8
2013-12-17T04:44:03Z
[ "python", "python-2.7", "conditional-statements" ]
I am a beginner in python programming. I have a small doubt that while performing some conditional expression using "if-elif-else" block, if i am using "if" after "else" would the code under "if" run or not. I know its a bad practice, but i have to integrate a pre-written code with my application. for example: ``` jk=...
The `...` says that you are still within the code block for the `else` and python doesn't expect the dedent for the next `if`. Try hitting `ENTER` one more time for the `...` to turn back into a `>>>` and your code will work!
How to calculate the inverse of the normal cumulative distribution function in python?
20,626,994
20
2013-12-17T05:57:49Z
20,627,638
42
2013-12-17T06:44:02Z
[ "python", "scipy", "normal-distribution" ]
How do I calculate the inverse of the cumulative distribution function (CDF) of the normal distribution in Python? Which library should I use? Possibly scipy?
[NORMSINV](http://support.microsoft.com/kb/826772) (mentioned in a comment) is the inverse of the CDF of the standard normal distribution. Using `scipy`, you can compute this with the `ppf` method of the [`scipy.stats.norm`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.norm.html) object. The acronym ...
creating a new text file using heredoc
20,627,588
6
2013-12-17T06:41:06Z
20,627,730
9
2013-12-17T06:49:58Z
[ "python", "heredoc" ]
In my shell script, I use heredoc block to create a file on the fly. What is the python equivalent? ``` cat > myserver.pem << "heredoc" -----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAnTsiYssvsuM1DRjyhqD8+ZB8ESqUFHgzeBYONp3yqjK8ICw/LRrxjXGXidAW aPBXfktv3zN/kFsLMEFJKrJs/TLCfXG1CwFHMZzJRLM4aE6E0j6j+KF96cY5rfAo82rvP5kQdT...
You can't use the code as-is, but you can simply use a triple-quoted string for the text, and combine it with the usual file manipulation built-ins: ``` with open("myserver.pem", "w") as w: w.write("""\ -----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAnTsiYssvsuM1DRjyhqD8+ZB8ESqUFHgzeBYONp3yqjK8ICw/LRrxjXGXidAW aPB...
djangorestframework serializer errors: {u'non_field_errors': [u'No input provided']}
20,628,611
11
2013-12-17T07:44:34Z
20,632,868
16
2013-12-17T11:26:32Z
[ "python", "django", "serialization", "django-models", "django-rest-framework" ]
I'm using djangorestframework, and someone makes a PUT request to a `.../peoplelist/2/markAsSeen`, passing in just a Person object's id in the URL. I fetch the Person object (2 in this case) and then simply change the fetched Person object's field `has_been_viewed` to True. The updated Person object is then to be seria...
You're providing a person instance to be updated by the serializer, but no accompanying data to update that instance with. If you want to deserialize some request data to update that instance with then you're missing the `data` argument, for example: ``` PersonSerializer(person, data=request.DATA, partial=True) ``` ...
Pandas - how to convert r dataframe back to pandas?
20,630,121
13
2013-12-17T09:14:22Z
20,808,449
9
2013-12-27T22:06:03Z
[ "python", "pandas" ]
I converted a pandas df to r using the the below: ``` import pandas as pd import pandas.rpy.common as com import rpy2.robjects as ro from rpy2.robjects.packages import importr rdf = com.convert_to_r_dataframe(df) ``` How do I convert rdf back to a pandas df? ``` df = f(rdf) ? ```
Converting data frames back and forth between `rpy2` and `pandas` will be in the rpy2 release 2.4.0, and should be largely automated (no need to convert explicitly, it will be done on the fly) ``` from rpy2.robjects import pandas2ri pandas2ri.activate() ``` If wishing to convert explicitly for any reason, the functio...
Django Rest Framework - Get related model field in serializer
20,633,313
31
2013-12-17T11:48:52Z
20,636,415
40
2013-12-17T14:12:52Z
[ "python", "django", "serialization", "foreign-keys", "django-rest-framework" ]
I'm trying to return a HttpResponse from Django Rest Framework including data from 2 linked models. The models are: ``` class Wine(models.Model): color = models.CharField(max_length=100, blank=True) country = models.CharField(max_length=100, blank=True) region = models.CharField(max_length=100, blank=True...
Simple as that, adding the WineSerializer as a field solved it. ``` class BottleSerializer(serializers.HyperlinkedModelSerializer): wine = WineSerializer(source='wine') class Meta: model = Bottle fields = ('url', 'wine', 'user', 'date_rated', 'rating', 'comment', 'get_more') ``` with: ``` cl...
How can I see all packages that depend on a certain package with PIP?
20,635,230
7
2013-12-17T13:17:27Z
20,635,891
7
2013-12-17T13:47:19Z
[ "python", "package", "pip" ]
I would like to see a list of packages that depend on a certain package with PIP. That is, given `django`, I would like to see `django-cms`, `django-filer`, because I have these packages installed and they all have `django` as dependency.
Quite straightforward: ``` pip show <insert_package_name_here>| grep ^Requires ``` Or the other way around: (sorry i got it wrong!) ``` for NAME in $(pip list|cut -d' ' -f1); do REQ=$(pip show $NAME| grep Requires); if [[ "$REQ" =~ "$REQUIRES" ]]; then echo $REQ;echo "Package: $NAME"; echo "---" ; fi; done ``` bef...
Using GZIP Module with Python
20,635,245
11
2013-12-17T13:18:22Z
20,635,502
22
2013-12-17T13:31:14Z
[ "python", "gzip" ]
I'm trying to use the Python GZIP module to simply uncompress several .gz files in a directory. Note that I do not want to read the files, only uncompress them. After searching this site for a while, I have this code segment, but it does not work: ``` import gzip import glob import os for file in glob.glob(PATH_TO_FIL...
If you get no error, the gzip module probably **is** being executed properly. > I do not want to read the files, only uncompress them The `gzip` module doesn't work as a desktop archiving program like 7-zip - you can't "uncompress" a file without "reading" it. What you probably mean by "uncompress" is more accuratell...
Using openpyxl to read file from memory
20,635,778
4
2013-12-17T13:42:23Z
20,667,890
7
2013-12-18T20:36:41Z
[ "python", "excel" ]
I downloaded a google-spreadsheet as an object in python. How can I use openpyxl use the workbook without having it to save to disk first? I know that xlrd can do this by: ``` book = xlrd.open_workbook(file_contents=downloaded_spreadsheet.read()) ``` with "downloaded\_spreadsheet" being my downloaded xlsx-file as a...
SOLVED.. Okay I was really dumb and didn't read the manual. In the function load\_workbook it says: ``` #:param filename: the path to open or a file-like object ``` ..so it was capeable of it all the time.. It reads a path or takes a file-like object. I only had to convert my file-like object returned by urlopen, to ...
Skip rows during csv import pandas
20,637,439
13
2013-12-17T14:59:34Z
20,637,559
17
2013-12-17T15:04:27Z
[ "python", "csv", "pandas" ]
I'm trying to import a .csv file using `pandas.read_csv()`, however I don't want to import the 2nd row of the data file (the row with index = 1 for 0-indexing). I can't see how not to import it because the arguments used with the command seem ambiguous: From the pandas website: "skiprows : list-like or integer Row ...
You can try yourself: ``` >>> import pandas as pd >>> from StringIO import StringIO >>> s = """1, 2 ... 3, 4 ... 5, 6""" >>> pd.read_csv(StringIO(s), skiprows=[1], header=None) 0 1 0 1 2 1 5 6 >>> pd.read_csv(StringIO(s), skiprows=1, header=None) 0 1 0 3 4 1 5 6 ```
Skip rows during csv import pandas
20,637,439
13
2013-12-17T14:59:34Z
23,739,252
8
2014-05-19T13:35:52Z
[ "python", "csv", "pandas" ]
I'm trying to import a .csv file using `pandas.read_csv()`, however I don't want to import the 2nd row of the data file (the row with index = 1 for 0-indexing). I can't see how not to import it because the arguments used with the command seem ambiguous: From the pandas website: "skiprows : list-like or integer Row ...
I don't have reputation to comment yet, but I want to add to [alko](http://stackoverflow.com/a/20637559/1896459) answer for further reference. From the [docs](http://pandas.pydata.org/pandas-docs/stable/io.html#io-read-csv-table): > skiprows: A collection of numbers for rows in the file to skip. Can also be an intege...
Convert list of dictionaries to Dataframe
20,638,006
155
2013-12-17T15:24:51Z
20,638,258
207
2013-12-17T15:35:13Z
[ "python", "dictionary", "pandas", "dataframe" ]
I have a list of dictionaries like this: ``` [{'points': 50, 'time': '5:00', 'year': 2010}, {'points': 25, 'time': '6:00', 'month': "february"}, {'points':90, 'time': '9:00', 'month': 'january'}, {'points_h1':20, 'month': 'june'}] ``` and I want to turn this into a pandas `DataFrame` like this: ``` month p...
Supposing `d` is your list of dicts, simply: ``` pd.DataFrame(d) ```
Convert list of dictionaries to Dataframe
20,638,006
155
2013-12-17T15:24:51Z
33,020,669
14
2015-10-08T15:59:32Z
[ "python", "dictionary", "pandas", "dataframe" ]
I have a list of dictionaries like this: ``` [{'points': 50, 'time': '5:00', 'year': 2010}, {'points': 25, 'time': '6:00', 'month': "february"}, {'points':90, 'time': '9:00', 'month': 'january'}, {'points_h1':20, 'month': 'june'}] ``` and I want to turn this into a pandas `DataFrame` like this: ``` month p...
in pandas 16.2, I had to do `pd.DataFrame.from_records(d)` to get this to work.
glob exclude pattern
20,638,040
15
2013-12-17T15:26:28Z
20,638,064
11
2013-12-17T15:27:33Z
[ "python", "glob" ]
I have a directory with a bunch of files inside: `eee2314`, `asd3442` ... and `eph`. I want to exclude all files that start with `eph` with the `glob` function. How can I do it?
You can't exclude patterns with the `glob` function, globs only allow for *inclusion* patterns. You'll have to do your own filtering; a list comprehension usually works nicely here: ``` files = [fn for fn in glob('somepath/*.txt') if not os.path.basename(fn).startswith('eph')] ```
glob exclude pattern
20,638,040
15
2013-12-17T15:26:28Z
21,502,564
12
2014-02-01T19:33:42Z
[ "python", "glob" ]
I have a directory with a bunch of files inside: `eee2314`, `asd3442` ... and `eph`. I want to exclude all files that start with `eph` with the `glob` function. How can I do it?
You can deduct sets: ``` set(glob("*")) - set(glob("eph")) ```
glob exclude pattern
20,638,040
15
2013-12-17T15:26:28Z
36,295,481
7
2016-03-29T21:32:39Z
[ "python", "glob" ]
I have a directory with a bunch of files inside: `eee2314`, `asd3442` ... and `eph`. I want to exclude all files that start with `eph` with the `glob` function. How can I do it?
The pattern rules for glob are not regular expressions. Instead, they follow standard Unix path expansion rules. There are only a few special characters: two different wild-cards, and character ranges are supported [from [glob].](https://pymotw.com/2/glob/) So you can exclude some files with patterns. For example to...
Python - List comprehension with 2 for loops & a ADD AND operand
20,638,223
6
2013-12-17T15:33:45Z
20,638,295
8
2013-12-17T15:36:44Z
[ "python", "list", "python-3.x", "add", "list-comprehension" ]
``` outgoing=[ [27, 42, 66, 85, 65, 64, 68, 68, 77, 58], [24, 39, 58, 79, 60, 62, 67, 62, 55, 35], [3, 3, 8, 6, 5, 2, 1, 6, 22, 23], [3, 3, 8, 6, 5, 2, 1, 6, 22, 23], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] incoming=[ [459, 469, 549, 740, 695, 629, 780, 571, 574, 599], ...
You want to use [`zip()`](http://docs.python.org/3/library/functions.html#zip) here to combine your lists into pairs: ``` joint = [[x + y for x, y in zip(*row)] for row in zip(outgoing, incoming)] ``` The outer loop pairs up the rows from `outgoing` and `incoming` into pairs, so `outgoing[0]` together with `incoming[...
Using Pylint to display error and warnings
20,639,173
3
2013-12-17T16:14:43Z
20,639,659
12
2013-12-17T16:35:16Z
[ "python", "pylint" ]
So I started using Pylint but since I am using tabs instead of spaces it is giving me as warnings, also since some methods are from base class, that are also as instance of 'GalleryUi' has no 'setModel' member while it is has QAbstractTableModel as base class, so how do i set up the Pylint to not consider these things....
You can use a **`~/.pylintrc`** file to configure Pylint - amongst other things, this allows you to ignore warnings you don't care about. If you must use tabs, tell Pylint by setting the `indent-string` option to the tab character: ``` [FORMAT] indent-string=\t ``` Pylint then will only warn you about places where yo...
python list comprehension explained
20,639,180
24
2013-12-17T16:15:04Z
20,639,246
27
2013-12-17T16:17:20Z
[ "python", "list" ]
I have no problem for understanding this: ``` a = [1,2,3,4] b = [x for x in a] ``` I thought that was all, but then I found this snippet: ``` a = [[1,2],[3,4],[5,6]] b = [x for xs in a for x in xs] ``` Which makes `b = [1,2,3,4,5,6]`. The problem is I'm having troubles to understand the syntax in `[x for xs in a fo...
Ah, the incomprehensible "nested" comprehensions. Loops unroll in the same order as in the comprehension. ``` [leaf for branch in tree for leaf in branch] ``` It helps to think of it like this. ``` for branch in tree: for leaf in branch: yield leaf ``` The [PEP202](http://www.python.org/dev/peps/pep-020...
python list comprehension explained
20,639,180
24
2013-12-17T16:15:04Z
20,639,516
11
2013-12-17T16:28:19Z
[ "python", "list" ]
I have no problem for understanding this: ``` a = [1,2,3,4] b = [x for x in a] ``` I thought that was all, but then I found this snippet: ``` a = [[1,2],[3,4],[5,6]] b = [x for xs in a for x in xs] ``` Which makes `b = [1,2,3,4,5,6]`. The problem is I'm having troubles to understand the syntax in `[x for xs in a fo...
if `a = [[1,2],[3,4],[5,6]]`, then if we unroll that list comp, we get: ``` +----------------a------------------+ | +--xs---+ , +--xs---+ , +--xs---+ | for xs in a | | x , x | | x , x | | x , x | | for x in xs a = [ [ 1 , 2 ] , [ 3 , 4 ] , [ 5 , 6 ] ] b = [ x for xs in a for x in xs ] == [1,...
Flask route giving 404 with floating point numbers in the URL
20,639,363
6
2013-12-17T16:22:04Z
20,640,550
10
2013-12-17T17:15:06Z
[ "python", "routes", "flask", "http-status-code-404", "werkzeug" ]
I have the following route definition in my Flask app's server.py: ``` @app.route('/nearby/<float:lat>/<float:long>') def nearby(lat, long): for truck in db.trucks.find({'loc': {'$near': [lat, long]}}).limit(5): if truck.has_key('loc'): del truck['loc'] return json.dumps(trucks) ``` But wh...
As mentioned in the comments, the built-in FloatConverter does not handle negative numbers. You can write a custom converter to handle negatives. This converter also treats integers as floats, which also would have failed. ``` from werkzeug.routing import FloatConverter as BaseFloatConverter class FloatConverter(Bas...
Flask route giving 404 with floating point numbers in the URL
20,639,363
6
2013-12-17T16:22:04Z
20,643,139
7
2013-12-17T19:36:25Z
[ "python", "routes", "flask", "http-status-code-404", "werkzeug" ]
I have the following route definition in my Flask app's server.py: ``` @app.route('/nearby/<float:lat>/<float:long>') def nearby(lat, long): for truck in db.trucks.find({'loc': {'$near': [lat, long]}}).limit(5): if truck.has_key('loc'): del truck['loc'] return json.dumps(trucks) ``` But wh...
Since the built in FloatConverter can only handle positive numbers, I pass the coordinates as strings, and use Python's float() method to convert them to floats.
Why is time difference on calculating this so big?
20,639,578
4
2013-12-17T16:31:12Z
20,639,765
8
2013-12-17T16:40:27Z
[ "python" ]
I need to round lots of UNIX timestamps down to their respective minutes (expressed as timestamp again). Out of pure curiosity I timed two methods: ``` %timeit (127/60)*60 10000000 loops, best of 3: 76.2 ns per loop %timeit 127 - 127%60 10000000 loops, best of 3: 34.1 ns per loop ``` I ran this several times and se...
``` >>> import dis >>> method1 = lambda: (127 / 60) * 60 >>> method2 = lambda: 127 - 127 % 60 >>> dis.dis(method1) 1 0 LOAD_CONST 1 (127) 3 LOAD_CONST 2 (60) 6 BINARY_DIVIDE 7 LOAD_CONST 2 (60) 10 BINARY_...
how to install numpy and pandas on windows
20,641,199
5
2013-12-17T17:47:28Z
20,641,320
8
2013-12-17T17:54:06Z
[ "python", "numpy", "installation", "pandas" ]
I'll preface by saying I'm a programming n00b by stack standards. I have experience with data analysis and scripting -- this is what I do professionally at a financial firm -- but I have no idea what I'm doing on the back end. I'm trying to start using pandas and python --- moving away from matlab/vba but I can't figu...
The best resource for third-party modules for Windows is Christoph Gohlke's [Python Extension Packages for Windows](http://www.lfd.uci.edu/~gohlke/pythonlibs/) repository. Each module is available as a self-extracting `.exe` installer, for use with the [python.org](http://python.org) version of Python - make sure you g...
Using Python threads to make thousands of calls to a slow API with a rate limit
20,643,184
6
2013-12-17T19:39:41Z
20,644,609
9
2013-12-17T21:02:58Z
[ "python", "multithreading", "python-3.x", "synchronization" ]
I want to make thousands of calls to an API which is kind of slow -- tens of seconds to get a response. The only limit is that I can make at most one request per second. What's the best way to do this? I think the following code works, but I feel I should be able to make better use of the threading library somehow. I'm...
If you want to run a bunch of jobs using a fixed-size thread pool, you can use [`concurrent.futures.ThreadPoolExecutor`](http://docs.python.org/3/library/concurrent.futures.html#threadpoolexecutor), like this: ``` from concurrent.futures import ThreadPoolExecutor with ThreadPoolExecutor(max_workers=5) as executor: ...
replicating R/ggplot2 colours in python
20,643,291
3
2013-12-17T19:46:01Z
20,643,644
8
2013-12-17T20:06:26Z
[ "python", "matplotlib", "python-ggplot" ]
This link has R code to replicate ggplot's colours: [Plotting family of functions with qplot without duplicating data](http://stackoverflow.com/questions/15726096/plotting-family-of-functions-with-qplot-without-duplicating-data) I have had a go at replicating the code in python - but the results are not right ... ```...
You should check [mpltools](http://tonysyu.github.io/mpltools/index.html) a really neat matplotlib extension. There is a ggplot style see [here](http://tonysyu.github.io/mpltools/auto_examples/style/plot_ggplot.html). E.g. (from link): ![enter image description here](http://i.stack.imgur.com/5xwTk.png)
Create pandas dataframe from json objects
20,643,437
2
2013-12-17T19:54:29Z
20,644,150
8
2013-12-17T20:35:46Z
[ "python", "json", "pandas" ]
I finally have output of data I need from a file with many json objects but I need some help with converting the below output into a single dataframe as it loops through the data. Here is the code to produce the output including a sample of what the output looks like: original data: ``` { "zipcode":"08989", "current"...
### Note: For those of you arriving at this question looking to parse json into pandas, if you do have *valid* json (this question doesn't) then you should use pandas [`read_json`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.json.read_json.html) function: ``` # can either pass string of the json, o...
Reading a json file and encoding problems
20,643,728
3
2013-12-17T20:10:53Z
20,643,769
7
2013-12-17T20:13:52Z
[ "python", "json", "python-2.7" ]
I would like to parse a JSON file and print `source` in this code fragment : ``` { "trailers": { "quicktime": [], "youtube": [ { "source": "mmNhzU6ySL8", "type": "Trailer", "name": "Trailer 1", ...
Assuming the JSON is formatted properly, the problem is that your code includes this check: ``` if k == "youtube": for innerk, innerv in k.iteritems(): ``` Given that you just asked for `k` to be `"youtube"` (an instance of `str` or `unicode`), it won't make sense to expect `k` to have an `iteritems` method. I b...
How to create ENUM in SQLAlchemy?
20,644,292
6
2013-12-17T20:44:46Z
20,646,024
14
2013-12-17T22:28:00Z
[ "python", "mysql", "database", "enums", "sqlalchemy" ]
``` from sqlalchemy import * from migrate import * meta = MetaData() race_enums = ('asian','mideastern','black','nativeamerican','indian','pacific','hispanic','white','other'); profiles_profiles = Table( 'profiles_profiles', meta, Column('id', Integer, primary_key = True), Column('user_id', Integer, nullab...
You need pass `race_enum` as an argument for `Enum`, not `Column` You can either pass in your `tuple` as whole ``` Column('race', Enum('asian','mideastern','black','nativeamerican','indian','pacific','hispanic','white','other')) ``` or use `*` to unpack `race_enums`: ``` Column('race', Enum(*race_enums)) ```
Square of each element of a column in pandas
20,644,536
11
2013-12-17T20:59:05Z
20,644,575
15
2013-12-17T21:01:26Z
[ "python", "pandas" ]
Very stupid question,but how can I square each element of a column/series of a dataFrame in pandas (and create another column)?
``` >>> import pandas as pd >>> df = pd.DataFrame([[1,2],[3,4]], columns=list('ab')) >>> df a b 0 1 2 1 3 4 >>> df['c'] = df['b']**2 >>> df a b c 0 1 2 4 1 3 4 16 ```
Pycharm exit code 0
20,645,129
10
2013-12-17T21:33:36Z
20,645,211
21
2013-12-17T21:38:04Z
[ "python", "pycharm" ]
Whenever I run any code, my console always ends with `Process finished with exit code 0`. For example, if i were to just print("hellow"): ``` pydev debugger: process 21021 is connecting Connected to pydev debugger (build 131.618) hellow Process finished with exit code 0 ``` Is there any way to make the output just...
You realize it ain't part of the output don't you? It's just additional information provided by the IDE's console. The real program is just outputting `hellow` as expected. Saying that the `Process finished with exit code 0` means that everything worked ok. If an exception occurs in your program or otherwise an `exit`...
How does os.path.join() work?
20,645,420
3
2013-12-17T21:50:50Z
20,645,450
13
2013-12-17T21:52:30Z
[ "python", "osx", "path", "builtin" ]
Please help me understand how the builtin os.path.join() function works. For example: ``` import os print os.path.join('cat','dog') # 'cat/dog' no surprise here print os.path.join('cat','dog').join('fish') # 'fcat/dogicat/dogscat/dogh' ``` On Mac (and i guess linux too) os.name is an alias for posixpath. So looking i...
You can't chain `os.path.join` like that. `os.path.join` returns a string; calling the `join` method of that calls the regular string [`join` method](http://docs.python.org/2/library/stdtypes.html#str.join), which is entirely unrelated.
how to spawn new independent process in python
20,646,519
8
2013-12-17T23:07:29Z
20,647,387
9
2013-12-18T00:21:05Z
[ "python", "subprocess", "fork", "daemon", "spawn" ]
I have a some python code that occasionally needs to span a new process to run a shell script in a "fire and forget" manner, ie without blocking. The shell script will not communicate with the original python code, and will in fact probably terminate the calling python process, so the launched shell script cannot be a ...
try prepending "nohup" to script.sh <http://en.wikipedia.org/wiki/Nohup>. You'll probably need to decide what to do with stdout and stderr, i just drop it in the example. ``` import os from subprocess import Popen devnull = open(os.devnull, 'wb') # use this in python < 3.3 # python >= 3.3 has subprocess.DEVNULL Popen...
How to serve static files in Flask
20,646,822
146
2013-12-17T23:31:02Z
20,647,057
39
2013-12-17T23:50:03Z
[ "python", "flask", "static-files" ]
So this is embarrassing. I've got an application that I threw together in `Flask` and for now it is just serving up a single static HTML page with some links to CSS and JS. And I can't find where in the documentation `Flask` describes returning static files. Yes, I could use `render_template` but I know the data is not...
I'm sure you'll find what you need there: <http://flask.pocoo.org/docs/quickstart/#static-files> Basically you just need a "static" folder at the root of your package, and then you can use `url_for('static', filename='foo.bar')` or directly link to your files with <http://example.com/static/foo.bar>. **EDIT**: As sug...
How to serve static files in Flask
20,646,822
146
2013-12-17T23:31:02Z
20,647,713
22
2013-12-18T00:52:38Z
[ "python", "flask", "static-files" ]
So this is embarrassing. I've got an application that I threw together in `Flask` and for now it is just serving up a single static HTML page with some links to CSS and JS. And I can't find where in the documentation `Flask` describes returning static files. Yes, I could use `render_template` but I know the data is not...
What I use (and it's been working great) is a "templates" directory and a "static" directory. I place all my .html files/Flask templates inside the templates directory, and static contains CSS/JS. render\_template works fine for generic html files to my knowledge, regardless of the extent at which you used Flask's temp...
How to serve static files in Flask
20,646,822
146
2013-12-17T23:31:02Z
20,648,053
203
2013-12-18T01:25:40Z
[ "python", "flask", "static-files" ]
So this is embarrassing. I've got an application that I threw together in `Flask` and for now it is just serving up a single static HTML page with some links to CSS and JS. And I can't find where in the documentation `Flask` describes returning static files. Yes, I could use `render_template` but I know the data is not...
The preferred method is to use nginx or another web server to serve static files; they'll be able to do it more efficiently than Flask. However, you can use [`send_from_directory`](http://flask.pocoo.org/docs/latest/api/#flask.send_from_directory) to send files from a directory, which can be pretty convenient in some ...
How to serve static files in Flask
20,646,822
146
2013-12-17T23:31:02Z
25,501,783
13
2014-08-26T08:56:59Z
[ "python", "flask", "static-files" ]
So this is embarrassing. I've got an application that I threw together in `Flask` and for now it is just serving up a single static HTML page with some links to CSS and JS. And I can't find where in the documentation `Flask` describes returning static files. Yes, I could use `render_template` but I know the data is not...
A simplest working example based on the other answers is the following: ``` from flask import Flask, request app = Flask(__name__, static_url_path='') @app.route('/index/') def root(): return app.send_static_file('index.html') if __name__ == '__main__': app.run(debug=True) ``` With the HTML called *index.html...
How to serve static files in Flask
20,646,822
146
2013-12-17T23:31:02Z
26,554,578
20
2014-10-24T19:02:06Z
[ "python", "flask", "static-files" ]
So this is embarrassing. I've got an application that I threw together in `Flask` and for now it is just serving up a single static HTML page with some links to CSS and JS. And I can't find where in the documentation `Flask` describes returning static files. Yes, I could use `render_template` but I know the data is not...
You can also, and this is my favorite, set a folder as static path so that the files inside are reachable for everyone. ``` app = Flask(__name__, static_url_path='/static') ``` With that set you can use the standard HTML: ``` <link rel="stylesheet" type="text/css" href="/static/style.css"> ```
How to serve static files in Flask
20,646,822
146
2013-12-17T23:31:02Z
28,758,723
12
2015-02-27T06:17:07Z
[ "python", "flask", "static-files" ]
So this is embarrassing. I've got an application that I threw together in `Flask` and for now it is just serving up a single static HTML page with some links to CSS and JS. And I can't find where in the documentation `Flask` describes returning static files. Yes, I could use `render_template` but I know the data is not...
You can use this function : > > send\_static\_file(filename) > > Function used internally to send static > > files from the static folder to the browser. ``` app = Flask(__name__) @app.route('/<path:path>') def static_file(path): return app.send_static_file(path) ```
Computing diffs within groups of a dataframe
20,648,346
10
2013-12-18T01:57:14Z
20,648,462
11
2013-12-18T02:08:49Z
[ "python", "pandas" ]
Say I have a dataframe with 3 columns: Date, Ticker, Value (no index, at least to start with). I have many dates and many tickers, but each `(ticker, date)` tuple is unique. (But obviously the same date will show up in many rows since it will be there for multiple tickers, and the same ticker will show up in multiple r...
wouldn't be just easier to do what yourself describe, namely ``` df.sort(['ticker', 'date'], inplace=True) df['diffs'] = df['value'].diff() ``` and then correct for borders: ``` mask = df.ticker != df.ticker.shift(1) df['diffs'][mask] = np.nan ``` to maintain the original index you may do `idx = df.index` in the be...
Python BeautifulSoup give multiple tags to findAll
20,648,660
10
2013-12-18T02:28:35Z
20,649,408
25
2013-12-18T04:01:04Z
[ "python", "beautifulsoup" ]
I'm looking for a way to use findAll to get two tags, in the order they appear on the page. Currently I have: ``` import requests import BeautifulSoup def get_soup(url): request = requests.get(url) page = request.text soup = BeautifulSoup(page) get_tags = soup.findAll('hr' and 'strong') for each ...
You could [pass a list](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#a-list), to find either `hr` or `strong` tags: ``` tags = soup.find_all(['hr', 'strong']) ```
Python try-except with of if else
20,652,527
3
2013-12-18T07:56:17Z
20,652,575
10
2013-12-18T07:58:45Z
[ "python", "refactoring", "try-catch" ]
I am quite new to python. I have the following code: ``` try: pk = a_method_that_may_raise_an_exception() except: method_to_be_executed_in_case_of_exception_or_pk_is_false() else: if pk: process_pk() else: method_to_be_executed_in_case_of_exception_or...
What about something like: ``` try: pk = a_method_that_may_rise_an_exception() except HandleableErrors: pk = False finally: if pk: process_pk() else: method_to_be_executed_in_case_of_exception_or_pk_is_false() ``` --- Really, we don't even need the `finally` clause here... ``` try: ...
Python - how to speed up calculation of distances between cities
20,654,918
5
2013-12-18T10:00:01Z
20,660,764
7
2013-12-18T14:26:12Z
[ "python", "django", "algorithm", "distance" ]
I have 55249 cities in my database. Every single one has got latitude longitude values. For every city I want to calculate distances to every other city and store those that are no further than 30km. Here is my algorithm: ``` # distance function from math import sin, cos, sqrt, atan2, radians def distance(obj1, obj2)...
You can't afford to compute the distance between every pair of cities. Instead, you need to put your cities in a [space-partitioning data structure](https://en.wikipedia.org/wiki/Space_partitioning) for which you can make fast nearest-neighbour queries. [SciPy](http://www.scipy.org/) comes with a [*kd*-tree](https://en...
Intersecting matplotlib graph with unsorted data
20,655,246
6
2013-12-18T10:13:53Z
20,655,299
8
2013-12-18T10:16:15Z
[ "python", "numpy", "matplotlib", "plot" ]
When plotting some points with `matplotlib` I encountered some strange behavior when creating a graph. Here is the code to produce this graph. ``` import matplotlib.pyplot as plt desc_x =[4000,3000,2000,2500,2750,2250,2300,2400,2450,2350] rmse_desc = [.31703 , .31701, .31707, .31700, .31713, .31698, .31697, .31688, .3...
You can maintain the order using numpy's [`argsort`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html) function. Argsort "...returns an array of indices of the same shape as a that index data along the given axis in sorted order.", so we can use this to re-order the x and y coordinates together. ...
Matplotlib/Pandas error using histogram
20,656,663
20
2013-12-18T11:17:05Z
20,657,592
40
2013-12-18T11:58:14Z
[ "python", "matplotlib", "pandas", "histogram" ]
I have a problem making histograms from pandas series objects and I can't understand why it does not work. The code has worked fine before but now it does not. Here is a bit of my code (specifically, a pandas series object I'm trying to make a histogram of): ``` type(dfj2_MARKET1['VSPD2_perc']) ``` which outputs the...
This error occurs among other things when you have NaN values in the Series. Could that be the case? These NaN's are not handled well by the `hist` function of matplotlib. For example: ``` s = pd.Series([1,2,3,2,2,3,5,2,3,2,np.nan]) fig, ax = plt.subplots() ax.hist(s, alpha=0.9, color='blue') ``` produces the same e...
Python PySide and Progress Bar Threading
20,657,753
12
2013-12-18T12:05:10Z
20,661,135
20
2013-12-18T14:43:55Z
[ "python", "multithreading", "qt", "pyside" ]
I have this code: ``` from PySide import QtCore, QtGui import time class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(400, 133) self.progressBar = QtGui.QProgressBar(Dialog) self.progressBar.setGeometry(QtCore.QRect(20, 10, 361, 23)) ...
I think you may be mistaken. You want the work you're doing in a separate thread so it doesn't freeze the application. But you also want to be able to update the progress bar. You can achieve this by creating a worker class using a `QThread`. QThreads are able emit signals, which your UI can listen for and act appropri...
Python PySide and Progress Bar Threading
20,657,753
12
2013-12-18T12:05:10Z
20,665,160
7
2013-12-18T17:58:43Z
[ "python", "multithreading", "qt", "pyside" ]
I have this code: ``` from PySide import QtCore, QtGui import time class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(400, 133) self.progressBar = QtGui.QProgressBar(Dialog) self.progressBar.setGeometry(QtCore.QRect(20, 10, 361, 23)) ...
It's a mistake to think you always need to use multi-threading for things like this. If you can break up your long-running task into a series of small steps, all you need to do is ensure that any pending events are processed sufficiently often for the GUI to remain responsive. This can be done safely from the *within*...
How to ignore the escaping \ python list?
20,658,032
3
2013-12-18T12:18:58Z
20,658,059
8
2013-12-18T12:20:20Z
[ "python", "list", "escaping" ]
I want to ignore the escape character in the following code. ``` >>> a=['\%'] >>> print a ['\\%'] ``` I want to output like `['\%']`. Is there any way to do that?
Using `string_escape`, `unicode_escape` encoding (See [Python Specific Encodings](http://docs.python.org/2/library/codecs.html#python-specific-encodings)): ``` >>> a = ['\%'] >>> print str(a).decode('string_escape') ['\%'] >>> print str(a).decode('unicode_escape') ['\%'] ```
ZeroMQ PubSub not working w\ Pyzmq
20,658,238
5
2013-12-18T12:28:40Z
20,659,002
10
2013-12-18T13:03:51Z
[ "python", "zeromq", "publish-subscribe", "pyzmq" ]
There is probably something very small that I am missing but I am unable to get a simple pub-sub example working in Python using the official Pyzmq package (<https://github.com/zeromq/pyzmq>). I am using the latest ZeroMQ stable release 4.0.3 and am able to get a simple example working pretty easily in c. I've tried o...
Assuming that you launch subscriber first and then publisher, subscriber eternally tries to connect to publisher. When publisher appears, the connection procedure on the subscriber's side takes some time and your publisher doesn't really care about this. While it fires with messages as soon as it can, subscriber is try...
Python requests - print entire http request (raw)?
20,658,572
50
2013-12-18T12:43:03Z
20,660,170
26
2013-12-18T13:59:45Z
[ "python", "http", "python-requests" ]
While using the [`requests` module](http://requests.readthedocs.org/en/latest/), is there any way to print the raw HTTP request? I don't want just the headers, I want the request line, headers, and content printout. Is it possible to see what ultimately is constructed from HTTP request?
**Note: this answer is outdated. Newer versions of `requests` support getting the request content directly, as [AntonioHerraizS's answer](http://stackoverflow.com/a/23816211/1595865) documents**. It's not possible to get the *true* raw content of the request out of `requests`, since it only deals with higher level obj...
Python requests - print entire http request (raw)?
20,658,572
50
2013-12-18T12:43:03Z
23,816,211
45
2014-05-22T20:11:08Z
[ "python", "http", "python-requests" ]
While using the [`requests` module](http://requests.readthedocs.org/en/latest/), is there any way to print the raw HTTP request? I don't want just the headers, I want the request line, headers, and content printout. Is it possible to see what ultimately is constructed from HTTP request?
[Since v1.2.3](http://docs.python-requests.org/en/v1.2.3/user/advanced/#prepared-requests) Requests added the PreparedRequest object. As per the documentation "it contains the exact bytes that will be sent to the server". One can use this to pretty print a request, like so: ``` import requests req = requests.Request...
zip generators passing parameters from a list of tuples
20,658,719
3
2013-12-18T12:49:21Z
20,658,763
7
2013-12-18T12:51:14Z
[ "python", "iterator", "tuples" ]
I have a function: ``` def func(i, k): j = 0 while True: yield j * i + k j += 1 ``` And some `i` and `k` instances: ``` pars = [(2, 4), (1, 5), (7, 2)] ``` How can I zip over func of pars without knowing the length of pars? Like this: ``` for func_tups in zip(func(2, 4), func(1, 5), func(7, 2)): pri...
``` for func_tup in zip(*(func(*p) for p in pairs)): print func_tup ``` Although this probably reads better as two lines: ``` iterators = (func(*pair) for pair in pairs) # aka starmap for func_tup in zip(*iterators): print func_tup ```
zip generators passing parameters from a list of tuples
20,658,719
3
2013-12-18T12:49:21Z
20,658,781
7
2013-12-18T12:52:10Z
[ "python", "iterator", "tuples" ]
I have a function: ``` def func(i, k): j = 0 while True: yield j * i + k j += 1 ``` And some `i` and `k` instances: ``` pars = [(2, 4), (1, 5), (7, 2)] ``` How can I zip over func of pars without knowing the length of pars? Like this: ``` for func_tups in zip(func(2, 4), func(1, 5), func(7, 2)): pri...
You are looking for [`itertools.starmap()`](http://docs.python.org/3/library/itertools.html#itertools.starmap): ``` from itertools import starmap for func_tups in zip(*starmap(func, pairs)): # warning, infinite loop unless you have a break condition ``` Here `starmap()` applies an arbitrary length `pairs` as arg...
Firefox Add-on SDK error
20,658,834
3
2013-12-18T12:55:26Z
20,720,212
7
2013-12-21T14:52:40Z
[ "python", "windows", "firefox", "firefox-addon-sdk" ]
I try to launch:`cfx run`but I'm getting following error: ``` (C:\Users\michal smoczyk\Downloads\addon-sdk-1.14) C:\Users\michal smoczyk\Downloads\addon-sdk-1.14\my-addon>cfx run Using binary at 'C:\Program Files\Mozilla Firefox\firefox.exe'. Using profile at 'c:\users\michal~1\appdata\local\temp\tmpkcrwv7.mozrunner'....
The current 1.15 version of the Add-on SDK seems to be incomaptible with Python 2.7.6. I got the same error and downgraded to Python 2.7.5 to solve this issue. Here are some relevant bug reports: [Bug 950894 - [mozprocess] TypeError under windows evironment in cpython 2.7.6](https://bugzilla.mozilla.org/show_bug.cg...
Python - should all member variables be initialized in __init__
20,661,448
19
2013-12-18T14:58:33Z
20,661,498
13
2013-12-18T15:01:07Z
[ "python", "oop", "instance-variables" ]
Maybe this is more of a style question than a technical one but I have a python class with several member variables and I want to have it work so that some of the member variables are initialized when the user first creates an instance of the class (i.e. in the `__init__` function) and I want the other member variables...
In object-oriented programming it's up to the developer to ensure an object is always in a consistent state after instantiation and after a method finishes. Other than that you're free to develop the class as you wish (keeping in mind certain principles with subclassing / overriding and so on). A tool such as [Pylint]...
Save python random forest model to file
20,662,023
14
2013-12-18T15:25:49Z
20,662,980
17
2013-12-18T16:09:18Z
[ "python", "machine-learning", "scikit-learn", "random-forest" ]
In R, after running "random forest" model, I can use `save.image("***.RData")` to store the model. Afterwards, I can just load the model to do predictions directly. Can you do a similar thing in python? I separate the Model and Prediction into two files. And in Model file: ``` rf= RandomForestRegressor(n_estimators=2...
``` ... import cPickle rf = RandomForestRegresor() rf.fit(X, y) with open('path/to/file', 'wb') as f: cPickle.dump(rf, f) # in your prediction file ...
Scrapy: Passing item between methods
20,663,162
4
2013-12-18T16:18:14Z
20,663,772
11
2013-12-18T16:46:59Z
[ "python", "scrapy" ]
Suppose I have a Bookitem, I need to add information to it in both the parse phase and detail phase ``` def parse(self, response) data = json.loads(response) for book in data['result']: item = BookItem(); item['id'] = book['id'] url = book['url'] yield Request(url, callback=self...
There is an argument named `meta` for Request: ``` yield Request(url, callback=self.detail, meta={'item': item}) ``` then in function `detail`, access it this way: ``` item = response.meta['item'] ``` See more details [here](http://doc.scrapy.org/en/latest/topics/jobs.html#request-serialization) about jobs topic.
Is there a simple way to handle key doesn't exist in python for loop?
20,663,644
2
2013-12-18T16:40:48Z
20,663,669
8
2013-12-18T16:42:03Z
[ "python" ]
Given the following code: ``` for bar in myDict['foo']: ``` Is there a simple way to handle key not found error? I am already aware of using `myDict.get('foo', defaultValue)` Can I use that here? What would I return? None is not iterable. I am also aware that I can precede the loop with ``` if 'foo' in myDict: `...
If you need an empty iterable just return the (`[]`) empty list: ``` for bar in myDict.get('foo',[]): ```
PyQt QPushButton Background color
20,668,060
5
2013-12-18T20:47:28Z
20,668,186
10
2013-12-18T20:54:27Z
[ "python", "pyqt4" ]
I have the follow code: ``` self.pushButton = QtGui.QPushButton(Form) self.pushButton.setGeometry(QtCore.QRect(0, 550, 150, 31)) self.pushButton.setObjectName(_fromUtf8("pushButton")) ``` How do I get the background color of this button to change. I have tried using Palette and I am having no success. I would like th...
You can change the style of the button: ``` self.pushButton.setStyleSheet("background-color: red") ``` It's like CSS.
Why am I getting an import error for importing process on python 3.3?
20,669,263
3
2013-12-18T21:55:51Z
20,669,304
17
2013-12-18T21:58:25Z
[ "python", "multiprocessing", "importerror" ]
I am receiving the following error when importing Process in python 3.3. Is there any reason I would get such an error, or is this a bug? I am running the django server in another terminal window, but I doubt that would have anything to do with this. ``` Python 3.3.2 (default, Nov 8 2013, 13:38:57) [GCC 4.8.2 201310...
The line `File "./multiprocessing.py"` in your traceback suggests that you have a file named `multiprocessing.py` in the working directory. Try removing/renaming it, because it shadows the real `multiprocessing` module. The problem here is that the very first entry in your `sys.path` is always `''`, so a file in the w...
Is there a quick way to get the R equivalent of ls() in Python?
20,669,375
4
2013-12-18T22:03:27Z
20,669,412
10
2013-12-18T22:05:40Z
[ "python" ]
I'm new to Python and normally use R, and regularly use `ls()` to get a vector of all the objects in my current environment, is there something that does the same thing quickly in Python?
You're probably looking for [`dir`](http://docs.python.org/3/library/functions.html#dir): > Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object. This may not be entirely obvious at first, but when you're at global scope...
how to make subprocess called with call/Popen inherit environment variables
20,669,558
4
2013-12-18T22:14:11Z
20,669,704
10
2013-12-18T22:23:17Z
[ "python", "bash", "shell", "environment-variables", "subprocess" ]
First off, apologies for what I'm sure will be obvious is my rudimentary understanding of bash and shells and subprocesses. I am trying to use Python to automate calls to a program called Freesurfer (actually, the subprogram I'm calling is called recon-all.) If I were doing this directly at the command line, I'd "sou...
If you look at the docs for [`Popen`](http://docs.python.org/2/library/subprocess.html#subprocess.Popen), it takes an `env` parameter: > If *env* is not `None`, it must be a mapping that defines the environment variables for the new process; these are used instead of inheriting the current process’ environment, whic...
WxFormBuilder has no Python option
20,670,324
2
2013-12-18T23:03:50Z
23,126,997
7
2014-04-17T07:23:47Z
[ "python", "wxpython", "wxformbuilder" ]
How can I generate python code? I know I need to change code\_generation property from C++ to Python, but there is no Python option... How can i fix this? I have already tried looking for this problem on the internet, but I couldn't find anything.
Since you didn't specify your OS, I will just review tips for the 3 major ones. For **Windows**, the beta release from [wxFormBuilder's SourceForge page](http://sourceforge.net/projects/wxformbuilder/files/wxformbuilder-nightly/3.4.2-beta/), version 3.4.x, is able to generate Python code so perhaps try installing that...
Pandas and unicode
20,670,370
7
2013-12-18T23:07:00Z
20,670,901
18
2013-12-18T23:48:52Z
[ "python", "unicode", "pandas" ]
This is a string I'm getting out of `pandas.DataFrame.to_json()`, putting it into redis, getting it out of redis elsewhere, and trying to read it via `pandas.read_json()`: ``` DFJ {"args":{"0":"[]","1":"[]","2":"[]","3":"[]","4":"[]","5":"[]","6":"[]","7":"[]"},"date":{"0":1385944439000000000,"1":1385944439000000000,"...
Seems your roundtripping IS causing some unicode. Not sure why that is, but easy to fix. You cannot store unicode in a HDFStore Table in python 2, (this works correctly in python 3 however). You could do it as a Fixed format if you want though (it would be pickled). See [here](http://pandas.pydata.org/pandas-docs/dev/i...
Calling multiple iterators on xrange objects
20,670,525
7
2013-12-18T23:19:40Z
20,670,641
8
2013-12-18T23:28:54Z
[ "python", "iterator", "generator" ]
Why does ``` zip(*[xrange(5)]*2) ``` give `[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]` but ``` zip(*[iter(xrange(5))]*2) ``` give `[(0, 1), (2, 3)]`? I always though that generator were iterators, so `iter` on a generator was a no-op. For example, ``` list(iter(xrange(5))) [0, 1, 2, 3, 4] ``` is the same as ``` ...
Theres a difference between an *iterable* and an *iterator*. You can use `iter(x)` to build an iterator for any given iterable `x`. An iterator encapsulates the state of an iteration, while an iterable is something you can create a new iterator from. `xrange()` is an iterable, but not an iterator. You can create multi...
Computing diffs in Pandas after using groupby leads to unexpected result
20,670,726
16
2013-12-18T23:34:19Z
20,671,047
11
2013-12-19T00:00:36Z
[ "python", "pandas" ]
I've got a dataframe, and I'm trying to append a column of sequential differences to it. I have found a method that I like a lot (and generalizes well for my use case). But I noticed one weird thing along the way. Can you help me make sense of it? Here is some data that has the right structure (code modeled on an answ...
Nice easy to reproduce example!! more questions should be like this! Just pass a lambda to transform (this is tantamount to passing afuncton object, e.g. np.diff (or Series.diff) directly. So this equivalent to data1/data2 ``` In [32]: data3['diffs'] = data3.groupby('ticker')['value'].transform(Series.diff) In [34]:...
Is 'input' a keyword in Python?
20,670,732
11
2013-12-18T23:34:38Z
20,670,757
15
2013-12-18T23:36:17Z
[ "python" ]
I'm new to Python. I'm writing some code in Sublime and it highlights the word 'input' I use it as a variable name and it seems to work, so I wondered whether it may be a keyword in a newer version. (I'm currently using 2.7.5)
No, `input` is not a keyword. Instead, it is a [built-in function](http://docs.python.org/2.7/library/functions.html). And yes, you *can* create a variable with the name `input`. **But please don't**. Doing so is a bad practice because it overshadows the built-in (makes it unusable in the current scope). If you *must...
Time Series Decomposition function in Python
20,672,236
20
2013-12-19T02:10:31Z
28,284,962
20
2015-02-02T19:10:49Z
[ "python", "time-series" ]
Time series decomposition is a method that separates a time series data set into 3 components a general equation is the following: ``` x(t)=s(t)+m(t)+e(t) where t is a time period x is the data s is the seasonal component e is the random error term m is the trend ``` In R I would do the functions [decompose](http://...
I've been having a similar issue and am trying to find the best path forward. Try moving your data into a [Pandas](http://pandas.pydata.org/) DataFrame and then call [StatsModels](http://statsmodels.sourceforge.net/) `tsa.seasonal_decompose`. See the [following example](http://statsmodels.sourceforge.net/stable/release...
Convert a numpy boolean array to int one with distinct values
20,672,478
4
2013-12-19T02:36:42Z
20,672,567
7
2013-12-19T02:46:46Z
[ "python", "numpy" ]
I've read through most of [Python: convert boolean array to int array](http://stackoverflow.com/questions/17506163/python-convert-boolean-array-to-int-array) , but I was still at loss with, how to (most efficiently) convert a `numpy` bool array to an int array, but with distinct values. For instance, I have: ``` >>> k...
Seems like `numpy.where` is exactly what you want: ``` >>> import numpy as np >>> k = np.array([True, False, False, True, False]) >>> np.where(k, 2, 5) array([2, 5, 5, 2, 5]) ```
How to enable line wrapping in ipython notebook
20,672,537
12
2013-12-19T02:42:56Z
20,699,918
10
2013-12-20T09:08:30Z
[ "python", "ipython", "ipython-notebook" ]
I have been trying to enable line wrapping in ipython notebook. I googled it with no results and i typed ipython notebook --help in a terminal. This gives me a ton of configuration commands for a config file, but no line wrapping. Does anyone know if ipnotebook has this feature and if so how to enable it? Your help wou...
As @Matt pointed out you have to configure CodeMirror to enable wrapping. However, this can be achieved by simply adding the following line to your `custom.js`: ``` IPython.Cell.options_default.cm_config.lineWrapping = true; ``` So there is no need to loop through all the cells. In a similar fashion you can enable ...
ImportError: No module named PytQt5
20,672,918
9
2013-12-19T03:21:41Z
20,701,815
7
2013-12-20T10:44:56Z
[ "python", "pyqt5" ]
following are my python, qt and sip versions ``` root@thura:~# python -V Python 2.7.3 root@thura:~# qmake --version QMake version 3.0 Using Qt version 5.0.2 in /usr/lib/i386-linux-gnu root@thura:~# sip -V 4.15.3 ``` I tried to import the PyQt5 by following by [this](http://pyqt.sourceforge.net/Docs/PyQt5/designer.htm...
After getting the help from @Blender, @ekhumoro and @Dan, I understand the Linux and Python more than before. Thank you. I got the an idea by @ekhumoro, it is I didn't install PyQt5 correctly. So I delete PyQt5 folder and download again. And redo everything from very start. After redoing, I got the error as my last up...
Is it possible to use "Domain-wide Delegation of Authority" with gdata-python-client?
20,676,513
3
2013-12-19T08:16:20Z
20,688,587
8
2013-12-19T18:00:27Z
[ "python", "google-oauth" ]
I'm using `gdata-python-client` to access the [Google Domain Shared Contacts API](https://developers.google.com/admin-sdk/domain-shared-contacts/). > In enterprise applications you may want to programmatically access users data without any manual authorization on their part. There was a protocol called 2LO (2 legged ...
Here's an example of how to do domain-wide delegation in Python, in Google App Engine using gdata libraries: 1. Create a project (<https://cloud.google.com/console#/project>). 2. Under "APIs & Auth" enable the APIs you need to use (some gdata APIs don't appear here, if so, skip this step). 3. Under "APIs & Auth" -> "C...
Python Wave byte data
20,677,390
5
2013-12-19T09:08:35Z
20,677,733
12
2013-12-19T09:26:37Z
[ "python", "audio", "wave" ]
I'm trying to read the data from a .wav file. ``` import wave wr = wave.open("~/01 Road.wav", 'r') # sample width is 2 bytes # number of channels is 2 wave_data = wr.readframes(1) print(wave_data) ``` This gives: ``` b'\x00\x00\x00\x00' ``` Which is the "first frame" of the song. These 4 bytes obviously correspond ...
If you want to understand what the 'frame' is you will have to read the **standard** of the wave file format. For instance: <https://web.archive.org/web/20140221054954/http://home.roadrunner.com/~jgglatt/tech/wave.htm> From that document: > The sample points that are meant to be "played" ie, sent to a Digital to Anal...
How do I compute the intersection point of two lines in Python?
20,677,795
12
2013-12-19T09:29:24Z
20,677,983
9
2013-12-19T09:38:19Z
[ "python", "lines", "intersect" ]
I have two lines that intersect at a point. I know the endpoints of the two lines. How do I compute the intersection point in Python? ``` # Given these endpoints #line 1 A = [X, Y] B = [X, Y] #line 2 C = [X, Y] D = [X, Y] # Compute this: point_of_intersection = [X, Y] ```
Unlike other suggestions, this is short and doesn't use external libraries like `numpy`. (Not that using other libraries is bad...it's nice not need to, especially for such a simple problem.) ``` def line_intersection(line1, line2): xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0]) ydiff = (line1[...
How do I compute the intersection point of two lines in Python?
20,677,795
12
2013-12-19T09:29:24Z
20,679,579
19
2013-12-19T10:46:47Z
[ "python", "lines", "intersect" ]
I have two lines that intersect at a point. I know the endpoints of the two lines. How do I compute the intersection point in Python? ``` # Given these endpoints #line 1 A = [X, Y] B = [X, Y] #line 2 C = [X, Y] D = [X, Y] # Compute this: point_of_intersection = [X, Y] ```
Can't stand aside, So we have linear system: > A1 \* x + B1 \* y = C1 > A2 \* x + B2 \* y = C2 let's do it with Cramer's rule, so solution can be found in determinants: > x = Dx/D > y = Dy/D where *D* is main determinant of the system: > A1 B1 > A2 B2 and *Dx* and *Dy* can be found from matricies: > C1 B1...
Python print last traceback only?
20,677,923
10
2013-12-19T09:34:59Z
20,677,992
19
2013-12-19T09:38:45Z
[ "python", "python-3.x", "traceback" ]
Consider the following code and traceback: ``` >>> try: ... raise KeyboardInterrupt ... except KeyboardInterrupt: ... raise Exception ... Traceback (most recent call last): File "<stdin>", line 2, in <module> KeyboardInterrupt During handling of the above exception, another exception occurred: Traceback (most r...
The perfect question for me. You can suppress the exception context, that is the first part of the traceback, by explicitly raising the exception `from None`: ``` >>> try: raise KeyboardInterrupt except: raise Exception from None Traceback (most recent call last): File "<pyshell#4>", line 4, in...
Readable C# equivalent of Python slice operation
20,678,653
11
2013-12-19T10:07:30Z
20,678,723
21
2013-12-19T10:10:24Z
[ "c#", "python", "slice", "equivalent" ]
What is the C# equivalent of Python slice operations? ``` my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] result1 = my_list[2:4] result2 = my_list[1:] result3 = my_list[:3] result4 = my_list[:3] + my_list[4:] ``` [Some of it is covered here](http://stackoverflow.com/questions/1301316/c-sharp-equivalent-of-rotating-a-li...
The closest is really LINQ [`.Skip()`](http://msdn.microsoft.com/en-us/library/bb358985.aspx) and [`.Take()`](http://msdn.microsoft.com/en-us/library/bb503062.aspx) Example: ``` var result1 = myList.Skip(2).Take(4); var result2 = myList.Skip(1); var result3 = myList.Skip(myList.Count() - 3); var result4 = myList.Skip...
Reading a CSV into pandas where one column is a json string
20,680,272
4
2013-12-19T11:15:42Z
20,683,341
8
2013-12-19T13:45:05Z
[ "python", "pandas" ]
I am working with CSV files where several of the columns have a simple json object (several key value pairs) while other columns are normal. Here is an example: ``` name,dob,stats john smith,1/1/1980,"{""eye_color"": ""brown"", ""height"": 160, ""weight"": 76}" dave jones,2/2/1981,"{""eye_color"": ""blue"", ""height""...
There is a slightly easier way, but ultimately you'll have to call json.loads There is a notion of a converter in pandas.read\_csv ``` converters : dict. optional Dict of functions for converting values in certain columns. Keys can either be integers or column labels ``` So first define your custom parser. In this c...
What's the fastest way to locate a list element within a list in python?
20,683,167
10
2013-12-19T13:35:06Z
20,683,224
12
2013-12-19T13:37:51Z
[ "python", "list", "python-2.7" ]
The list is similar to this: ``` [["12", "stuA", "stuB"], ["51", "stuC", "stuD"], ..., ["3234", "moreStuff", "andMore"]] ``` Now I need to locate an item (get index) only by its first value (e.g. `"332"`). Is there any better way to do this, apart from iterating from the first one to compare with each value? Code: ...
**No.** Without iterating you cannot find it, unless the list is already sorted. You can improve your code like this, with [`enumerate`](http://docs.python.org/2/library/functions.html#enumerate) and list comprehension. ``` [index for index, item in enumerate(thelist) if item[0] == "332"] ``` This will give the indic...
What's the fastest way to locate a list element within a list in python?
20,683,167
10
2013-12-19T13:35:06Z
20,683,555
9
2013-12-19T13:56:17Z
[ "python", "list", "python-2.7" ]
The list is similar to this: ``` [["12", "stuA", "stuB"], ["51", "stuC", "stuD"], ..., ["3234", "moreStuff", "andMore"]] ``` Now I need to locate an item (get index) only by its first value (e.g. `"332"`). Is there any better way to do this, apart from iterating from the first one to compare with each value? Code: ...
No-one's mentioned this yet, so I will - if you need to find an item by its value quickly (and presumably more than just once), you should change the data structure you use to be one that supports the kind of access you need. Lists support fast access by index, but not by item value. If you stored the information in a ...
Instancemethod or function?
20,683,985
10
2013-12-19T14:15:52Z
20,684,313
12
2013-12-19T14:31:24Z
[ "python", "python-2.7" ]
Today I defined a class just for testing what comes next: ``` class B(object): def p(self): print("p") ``` And later I did this: ``` >>> type(B.__dict__['p']) <type 'function'> >>> type(B.p) <type 'instancemethod'> ``` So, why? Aren't `B.p` and `B.__dict__['p']` the same object? My astonishment just in...
This is a very nice question. To clear a few things: 1. When a method name is accessed through its class (i.e `B.p`) it said to be *undbound*. 2. When otherwise the method is accessed through its class' instance (i.e `B().p`) is said to be *bound*. The main difference between *bound* and *unbound* is that if *bound*...
alternative (faster) war to 3 nested for loop python
20,684,377
5
2013-12-19T14:34:43Z
20,684,417
7
2013-12-19T14:36:38Z
[ "python" ]
How can i made this function faster? (I call it a lot of time and it could result in some speed improving) ``` def vectorr(I, J, K): vect = [] for k in range(0, K): for j in range(0, J): for i in range(0, I): vect.append([i, j, k]) return vect ```
You can try to take a look at [itertools.product](http://docs.python.org/2/library/itertools.html#itertools.product) > Equivalent to nested for-loops in a generator expression. For example, > product(A, B) returns the same as ((x,y) for x in A for y in B). > > The nested loops cycle like an odometer with the rightmost...
Can't get function to return false?
20,684,728
2
2013-12-19T14:50:41Z
20,684,742
11
2013-12-19T14:51:28Z
[ "python", "python-3.x" ]
I'm working with this exercise: > Write a function is\_member() that takes a value (i.e. a number, string, etc) x and a list of values a, and returns True if x is a member of a, False otherwise. (Note that this is exactly what the in operator does, but for the sake of the exercise you should pretend Python did not hav...
You need to take the `return False` out of the loop: ``` def isMember(value, list): for element in list: if(element == value): return True return False ``` The way you have it currently, `isMember` will return `False` if the `value` is not the *first* item in the `list`. Also, you should c...
AssertionError in django
20,685,749
3
2013-12-19T15:39:50Z
20,685,906
7
2013-12-19T15:47:22Z
[ "python", "django" ]
I've been pulling my hair out on this one and it seems like there is a really simple solution for it but I'm too blind to see it. I've upgraded from Django 1.4.3 to Django 1.6 and ever since then I get an assertion error while trying to get DateTimeField to work. Here's my model ``` class Article(models.Model): '''Ar...
`date_publish` is a `DateTimeField`, not a `DateField`. Use the [`datetimes()`](https://docs.djangoproject.com/en/1.6/ref/models/querysets/#django.db.models.query.QuerySet.datetimes) method instead of `dates()`. ``` Article.objects.datetimes('date_publish', 'month', order='DESC') ``` See the [1.6 release notes](https...
python string encoding issues
20,687,319
2
2013-12-19T16:53:33Z
20,687,344
7
2013-12-19T16:54:47Z
[ "python", "string", "unicode" ]
Is there a function in python that is equivalent to prefixing a string by 'u'? Let's say I have a string: ``` a = 'C\xc3\xa9dric Roger' ``` and I want to convert it to: ``` b = u'C\xc3\xa9dric Roger' ``` so that I can compare it to other unicode objects. How can I do this? My first instinct was to try: ``` >>>> b...
You need to specify an encoding: ``` unicode(a, 'utf8') ``` or, using `str.decode()`: ``` a.decode('utf8') ``` but do pick the right codec for your input; you clearly have UTF-8 data here but that may not always be the case. To understand what this does, I urge you to read: * [The Absolute Minimum Every Software ...
ImportError: cannot import name HTTPSHandler using PIP
20,688,034
49
2013-12-19T17:29:26Z
20,728,240
20
2013-12-22T10:06:15Z
[ "python", "ssl", "openssl", "pip" ]
Facing an HTTPSHandler error while installing python packages using pip, following is the stack trace, ``` --------desktop:~$ pip install Django==1.3 Traceback (most recent call last): File "/home/env/.genv/bin/pip", line 9, in <module> load_entry_point('pip==1.4.1', 'console_scripts', 'pip')() File "/home/env...
You need to install the OpenSSL header files before building Python if you need SSL support. On Debian and Ubuntu, they are in a package called `libssl-dev`. You might need some more dependencies, [as noted here](http://askubuntu.com/questions/101591/how-do-i-install-python-2-7-2-on-ubuntu).
ImportError: cannot import name HTTPSHandler using PIP
20,688,034
49
2013-12-19T17:29:26Z
24,111,505
9
2014-06-08T22:24:17Z
[ "python", "ssl", "openssl", "pip" ]
Facing an HTTPSHandler error while installing python packages using pip, following is the stack trace, ``` --------desktop:~$ pip install Django==1.3 Traceback (most recent call last): File "/home/env/.genv/bin/pip", line 9, in <module> load_entry_point('pip==1.4.1', 'console_scripts', 'pip')() File "/home/env...
You need to install OpenSSl before make and install Python to solve the problem. On Centos: ``` yum install openssl openssl-devel -y ``` [source](http://www.leonli.co.uk/blog/723/solve-python-importerror-cannot-import-name-httpshandler)
ImportError: cannot import name HTTPSHandler using PIP
20,688,034
49
2013-12-19T17:29:26Z
25,716,286
9
2014-09-08T01:24:57Z
[ "python", "ssl", "openssl", "pip" ]
Facing an HTTPSHandler error while installing python packages using pip, following is the stack trace, ``` --------desktop:~$ pip install Django==1.3 Traceback (most recent call last): File "/home/env/.genv/bin/pip", line 9, in <module> load_entry_point('pip==1.4.1', 'console_scripts', 'pip')() File "/home/env...
I was having this problem on Mac OSX, even after confirming my PATH, etc. Did a; pip uninstall virtualenv then install virtualenv and it seemed to works now. At the time I had forced brew to link openssl, unlinked it and virtualenv still seems to work but maybe that's because it was originally linked when I reinstall...