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
Fitting a closed curve to a set of points
31,464,345
16
2015-07-16T20:54:42Z
31,464,962
14
2015-07-16T21:37:05Z
[ "python", "numpy", "scipy", "curve-fitting", "data-fitting" ]
I have a set of points `pts` which form a loop and it looks like this: ![enter image description here](http://i.stack.imgur.com/31KOr.png) This is somewhat similar to [31243002](http://stackoverflow.com/questions/31243002/higher-order-local-interpolation-of-implicit-curves-in-python), but instead of putting points in...
Your problem is because you're trying to work with x and y directly. The interpolation function you're calling assumes that the x-values are in sorted order and that each `x` value will have a unique y-value. Instead, you'll need to make a parameterized coordinate system (e.g. the index of your vertices) and interpola...
Fitting a closed curve to a set of points
31,464,345
16
2015-07-16T20:54:42Z
31,465,587
8
2015-07-16T22:24:47Z
[ "python", "numpy", "scipy", "curve-fitting", "data-fitting" ]
I have a set of points `pts` which form a loop and it looks like this: ![enter image description here](http://i.stack.imgur.com/31KOr.png) This is somewhat similar to [31243002](http://stackoverflow.com/questions/31243002/higher-order-local-interpolation-of-implicit-curves-in-python), but instead of putting points in...
Using the [ROOT Framework](https://root.cern.ch/drupal/) and the pyroot interface I was able to generate the following image ![Drawing Using pyroot](http://i.stack.imgur.com/qRnPM.png) With the following code(I converted your data to a CSV called data.csv so reading it into ROOT would be easier and gave the columns ti...
Fitting a closed curve to a set of points
31,464,345
16
2015-07-16T20:54:42Z
31,466,013
13
2015-07-16T23:05:18Z
[ "python", "numpy", "scipy", "curve-fitting", "data-fitting" ]
I have a set of points `pts` which form a loop and it looks like this: ![enter image description here](http://i.stack.imgur.com/31KOr.png) This is somewhat similar to [31243002](http://stackoverflow.com/questions/31243002/higher-order-local-interpolation-of-implicit-curves-in-python), but instead of putting points in...
Actually, you were not far from the solution in your question. Using [`scipy.interpolate.splprep`](http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.interpolate.splprep.html) for parametric B-spline interpolation would be the simplest approach. It also natively supports closed curves, if you provide the...
Is there an equivalent in Python of Fortran's "implicit none"?
31,467,987
8
2015-07-17T03:33:06Z
31,468,253
7
2015-07-17T04:09:31Z
[ "python", "python-2.7", "fortran" ]
In Fortran there is a statement `Implicit none` that throws a compilation error when a local variable is not declared but used. I understand that Python is a dynamically typed language and the scope of a variable may be determined at runtime. But I would like to avoid certain unintended errors that happen when I forge...
> So my question is that: Is there any way to ensure all variables used > in test() are local to it and that there are no side effects. There is a technique to validate that globals aren't accessed. Here's a decorator that scans a function's opcodes for a *LOAD\_GLOBAL*. ``` import dis, sys, re, StringIO def check_...
Why does the yield function not require parentheses in Python?
31,468,049
6
2015-07-17T03:41:39Z
31,468,074
7
2015-07-17T03:43:44Z
[ "python", "python-2.7", "python-3.x", "yield-keyword" ]
In Python, I have many times seen the `yield` function used to create a generator. Both this and the `print` function technically both perform the action of methods because they return a value. However, during the change from Python 2 to Python 3, the `print` function gained parentheses like a normal method call, but y...
`print` wasn't a function that gained parentheses: it went from being a statement to being a function. `yield` is still a statement, like `return`. Syntax highlighting is specific to your development environment. You can find more information about [the difference between expressions and statements here](http://stacko...
Why does the yield function not require parentheses in Python?
31,468,049
6
2015-07-17T03:41:39Z
31,468,124
15
2015-07-17T03:50:24Z
[ "python", "python-2.7", "python-3.x", "yield-keyword" ]
In Python, I have many times seen the `yield` function used to create a generator. Both this and the `print` function technically both perform the action of methods because they return a value. However, during the change from Python 2 to Python 3, the `print` function gained parentheses like a normal method call, but y...
So I went digging for an answer. [And it turns out, there is one](https://www.python.org/dev/peps/pep-0255/). From PEP 255, the pep that gave us the `yield` keyword > Q. Why a new keyword for "yield"? Why not a builtin function instead? > > A. Control flow is much better expressed via keyword in Python, and > yield is...
unable to load app 0 (mountpoint='') - Flask app with uwsgi
31,476,441
3
2015-07-17T12:59:55Z
31,478,026
14
2015-07-17T14:20:02Z
[ "python", "flask", "uwsgi" ]
I have a python flask app in below structure ``` Admin |-app | -__init__.py |-wsgi.py ``` My wsgi.py contents is as follows ``` #!/usr/bin/python from app import app from app import views if __name__ == '__main__': app.run() ``` Contents of **init**.py in app package ``` #!/usr/bin/python from...
"Callable not found is the issue" (not the import error, i suspect). Change: `uwsgi --socket 127.0.0.1:8080 --protocol=http -w wsgi` into this ``` uwsgi --socket 127.0.0.1:8080 --protocol=http -w wsgi:app ``` or ``` uwsgi --socket 127.0.0.1:8080 --protocol=http --module wsgi --callable app ``` see [here, search f...
In python the result of a /= 2.0 and a = a / 2.0 are not the same
31,481,031
3
2015-07-17T17:00:33Z
31,481,064
10
2015-07-17T17:02:35Z
[ "python", "numpy" ]
``` In [67]: import numpy as np In [68]: a = np.arange(10) In [69]: b = a.copy() In [70]: a /= 2.0 In [71]: a Out[71]: array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4]) In [72]: b = b / 2.0 In [73]: In [73]: b Out[73]: array([ 0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5]) ``` I don't know why it the results are dif...
`a = np.arange(10)` has an integer dtype. ``` >>> np.arange(10).dtype dtype('int64') ``` Modifying an array inplace -- for example, with `a /= 2.0` -- does not change the dtype. So the result contains ints. In contrast, `a/2.0` ["upcasts" the resultant array](http://wiki.scipy.org/Tentative_NumPy_Tutorial#head-4c1d5...
Linear regression with pymc3 and belief
31,483,818
4
2015-07-17T20:01:31Z
31,493,688
7
2015-07-18T17:29:58Z
[ "python", "bayesian", "pymc3" ]
I am trying to grasp Bayesain statistics with `pymc3` I ran this code for a simple linear regression ``` #Generating data y=a+bx import pymc3 import numpy as np N=1000 alpha,beta, sigma = 2.0, 0.5, 1.0 np.random.seed(47) X = np.linspace(0, 1, N) Y = alpha + beta*X + np.random.randn(N)*sigma #Fitting linear_model = p...
The `trace` is the output of the Markov Chain Monte Carlo (MCMC) process. It converges to a distribution (e.g., belief) of your parameters, given the data. You can view the trace using: ``` pymc3.traceplot(trace, vars=['alpha', 'beta', 'sigma']) ``` ![Trace Plot](http://i.stack.imgur.com/0MeeR.png) If you would lik...
Test if all values are in an iterable in a pythonic way
31,484,585
23
2015-07-17T20:56:47Z
31,484,606
7
2015-07-17T20:58:06Z
[ "python", "if-statement" ]
I am currently doing this: ``` if x in a and y in a and z in a and q in a and r in a and s in a: print b ``` Is there a more pythonic way to express this `if` statement?
``` if all(v in a for v in {x, y, z, q, r, s}): print(b) ```
Test if all values are in an iterable in a pythonic way
31,484,585
23
2015-07-17T20:56:47Z
31,484,610
29
2015-07-17T20:58:25Z
[ "python", "if-statement" ]
I am currently doing this: ``` if x in a and y in a and z in a and q in a and r in a and s in a: print b ``` Is there a more pythonic way to express this `if` statement?
Using the [all](https://docs.python.org/2/library/functions.html#all) function allows to write this in a nice and compact way: ``` if all(i in a for i in (x, y, z, q, r, s)): print b ``` This code should do almost exactly the same as your example, even if the objects are not hashable or if the `a` object has some...
Test if all values are in an iterable in a pythonic way
31,484,585
23
2015-07-17T20:56:47Z
31,484,694
18
2015-07-17T21:04:28Z
[ "python", "if-statement" ]
I am currently doing this: ``` if x in a and y in a and z in a and q in a and r in a and s in a: print b ``` Is there a more pythonic way to express this `if` statement?
Another way to do this is to use subsets: ``` if {x, y, z, q, r, s}.issubset(a): print(b) ``` REPL example: ``` >>> {0, 1, 2}.issubset([0, 1, 2, 3]) True >>> {0, 1, 2}.issubset([1, 2, 3]) False ``` One caveat with this approach is that all of `x`, `y`, `z`, etc. must be hashable.
Flask CORS - no Access-control-allow-origin header present on a redirect()
31,487,379
11
2015-07-18T03:06:45Z
31,488,389
8
2015-07-18T06:14:30Z
[ "python", "angularjs", "flask", "flask-restful" ]
I am implementing OAuth Twitter User-sign in (Flask API and Angular) I keep getting the following error when I click the sign in with twitter button and a pop up window opens: ``` XMLHttpRequest cannot load https://api.twitter.com/oauth/authenticate?oauth_token=r-euFwAAAAAAgJsmAAABTp8VCiE. No 'Access-Control-Allow-Or...
The problem is not yours. Your client-side application is sending requests to Twitter, so it isn't you that need to support CORS, it is Twitter. But the Twitter API does not currently support CORS, which effectively means that you cannot talk to it directly from the browser. A common practice to avoid this problem is ...
str.lstrip() unexpected behaviour
31,488,854
3
2015-07-18T07:21:32Z
31,488,873
8
2015-07-18T07:24:49Z
[ "python" ]
I am working on a scrapy project and was trying to parse my config The string is `attr_title` I have to strip 'attr\_' and get `title`. I used lstrip('attr\_'), but getting unexpected results. I know `lstrip` works out combinations and removes them, but having hard time understanding it. ``` In [17]: "attr.title".lst...
`lstrip` `iterates` over the result string until there is no more combination that matches the left most set of characters A little illustration is below. ``` In [1]: "attr.title".lstrip('attr.') Out[1]: 'itle' # Flow --> "attr." --> "t" --> Next char is 'i' which does not match any combination hence, iteration stop...
Matplotlib: Finding out xlim and ylim after zoom
31,490,436
3
2015-07-18T10:57:45Z
31,491,515
8
2015-07-18T13:11:50Z
[ "python", "matplotlib" ]
you for sure know a fast way how I can track down the limits of my figure after having zoomed in? I would like to know the coordinates precisely so I can reproduce the figure with `ax.set_xlim` and `ax.set_ylim`. I am using the standard qt4agg backend. edit: I know I can use the cursor to find out the two positions in...
matplotlib has an event handling API you can use to hook in to actions like the ones you're referring to. The [Event Handling](http://matplotlib.org/users/event_handling.html) page gives an overview of the events API, and there's a (very) brief mention of the x- and y- limits events on the [Axes](http://matplotlib.org/...
Calculating local means in a 1D numpy array
31,491,932
10
2015-07-18T14:00:22Z
31,492,039
10
2015-07-18T14:14:24Z
[ "python", "arrays", "numpy", "scipy", "mean" ]
I have 1D NumPy array as follows: ``` import numpy as np d = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]) ``` I want to calculate means of (1,2,6,7), (3,4,8,9), and so on. This involves mean of 4 elements: Two consecutive elements and two consecutive elements 5 positions after. I tried the followin...
Instead of indexing, you can approach this with a signal processing perspective. You are basically performing a [discrete convolution](https://en.m.wikipedia.org/wiki/Convolution#Discrete_convolution) of your input signal with a 7-tap kernel where the three centre coefficients are 0 while the extremities are 1, and sin...
Alternative to python's .sort() (for inserting into a large list and keeping it sorted)
31,493,603
8
2015-07-18T17:18:53Z
31,493,619
9
2015-07-18T17:20:56Z
[ "python", "python-2.7", "sorting" ]
I need to continuously add numbers to a pre-sorted list: ``` for num in numberList: list.append(num) list.sort() ``` Each iteration is short but when the given numberList contains tens of thousands of values this method slows way down. Is there a more efficient function available that leaves a list intact and...
See the native bisect.insort() which implements insertion sort on lists, this should perfectly fit your needs since the [complexity is O(n) at best and O(n^2) at worst](https://en.wikipedia.org/wiki/Insertion_sort#Best.2C_worst.2C_and_average_cases) instead of O(nlogn) with your current solution (resorting after insert...
Alternative to python's .sort() (for inserting into a large list and keeping it sorted)
31,493,603
8
2015-07-18T17:18:53Z
31,493,635
17
2015-07-18T17:22:15Z
[ "python", "python-2.7", "sorting" ]
I need to continuously add numbers to a pre-sorted list: ``` for num in numberList: list.append(num) list.sort() ``` Each iteration is short but when the given numberList contains tens of thousands of values this method slows way down. Is there a more efficient function available that leaves a list intact and...
You can use the [`bisect.insort()` function](https://docs.python.org/2/library/bisect.html#bisect.insort) to insert values into an already sorted list: ``` from bisect import insort insort(list, num) ``` Note that this'll still take some time as the remaining elements after the insertion point all have to be shifted...
pandas DataFrame "no numeric data to plot" error
31,494,870
5
2015-07-18T19:38:20Z
31,495,326
12
2015-07-18T20:35:31Z
[ "python", "pandas", "matplotlib" ]
I have a small DataFrame that I want to plot using pandas. ``` 2 3 0 1300 1000 1 242751149 199446827 2 237712649 194704827 3 16.2 23.0 ``` I am still trying to learn plotting from within pandas . I want a plot In the above example when I say . ``` df.plot() ``` I get the strangest error. ``...
Try the following before plotting: ``` df=df.astype(float) ```
Python file open function modes
31,502,329
20
2015-07-19T14:36:00Z
31,503,045
9
2015-07-19T15:51:45Z
[ "python" ]
I have noticed that, in addition to the documented mode characters, Python 2.7.5.1 in Windows XP and 8.1 also accepts modes `U` and `D` at least when reading files. Mode `U` is used in numpy's [`genfromtxt`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html). Mode `D` has the effect that the fil...
The `D` flag seems to be Windows specific. Windows seems to add several flags to the `fopen` function in its CRT, as described [here](https://msdn.microsoft.com/en-us/library/yeby3zcb.aspx). While Python does filter the mode string to make sure no errors arise from it, it does allow some of the special flags, as can b...
Python test if all N variables are different
31,505,075
4
2015-07-19T19:29:02Z
31,505,105
18
2015-07-19T19:33:17Z
[ "python", "idiomatic", "logical" ]
I'm currently doing a program and I have searched around but I cannot find a solution; My problem is where I want to make a condition where all variables selected are not equal and I can do that but only with long lines of text, is there a simpler way? My solution thus far is to do: ``` if A!=B and A!=C and B!=C: ``` ...
Create a set and check whether the number of elements in the set is the same as the number of variables in the list that you passed into it: ``` >>> variables = [a, b, c, d, e] >>> if len(set(variables)) == len(variables): ... print("All variables are different") ``` A set doesn't have duplicate elements so if yo...
Python: Variables are still accessible if defined in try or if?
31,505,149
7
2015-07-19T19:37:25Z
31,505,354
10
2015-07-19T19:58:32Z
[ "python", "scope" ]
I'm a Python beginner and I am from C/C++ background. I'm using Python 2.7. I read this article: [A Beginner’s Guide to Python’s Namespaces, Scope Resolution, and the LEGB Rule](http://spartanideas.msu.edu/2014/05/12/a-beginners-guide-to-pythons-namespaces-scope-resolution-and-the-legb-rule/), and I think I have s...
> My guess is that, in Python, `if` does not create new scope. All the variables that are newly defined in `if` are just in the scope that if resides in and this is why the variable is still accessible after the `if`. That is correct. In Python, [namespaces](https://docs.python.org/3/tutorial/classes.html#python-scope...
How to remove the trailing comma from a loop in Python?
31,505,452
5
2015-07-19T20:09:03Z
31,505,501
8
2015-07-19T20:13:03Z
[ "python", "python-3.x" ]
Here is my code so far: ``` def main(): for var in range (1, 101): num= IsPrime(var) if num == 'true': print(var, end=', ') ``` The IsPrime function calculates whether or not a function is prime. I need to print out the prime numbers from 1 to 100 formatted into a single line with co...
The idiomatic Python code in my opinion would look something like this: ``` print(', '.join([str(x) for x in xrange(1, 101) if IsPrime(x) == 'true'])) ``` (Things would be better if `IsPrime` actually returned `True` or `False` instead of a string) This is functional instead of imperative code. If you want imperati...
PIP install unable to find ffi.h even though it recognizes libffi
31,508,612
16
2015-07-20T03:54:51Z
31,508,663
54
2015-07-20T04:01:15Z
[ "python", "linux", "pip" ]
I have installed `libffi` on my Linux server as well as correctly set the `PKG_CONFIG_PATH` environment variable to the correct directory, as `pip` recognizes that it is installed; however, when trying to install pyOpenSSL, pip states that it cannot find file 'ffi.h'. I know both that`ffi.h` exists as well as its direc...
You need to install the development package as well. `libffi-dev` on Debian/Ubuntu, `libffi-devel` on Redhat/Centos/Fedora.
Pandas DataFrame: replace all values in a column, based on condition
31,511,997
6
2015-07-20T08:35:34Z
31,512,025
8
2015-07-20T08:37:09Z
[ "python", "python-2.7", "pandas", "dataframe" ]
I have a simple DataFrame like the following: ![Pandas DataFrame](http://i.stack.imgur.com/KjcSH.png) I want to select all values from the 'First Season' column and replace those that are over 1990 by 1. In this example, only Baltimore Ravens would have the 1996 replaced by 1 (keeping the rest of the data intact). I...
You need to select that column: ``` In [41]: df.loc[df['First Season'] > 1990, 'First Season'] = 1 df Out[41]: Team First Season Total Games 0 Dallas Cowboys 1960 894 1 Chicago Bears 1920 1357 2 Green Bay Packers 1921 1339 3 Miam...
pip install -r: OSError: [Errno 13] Permission denied
31,512,422
9
2015-07-20T08:58:05Z
31,512,489
13
2015-07-20T09:02:33Z
[ "python", "django", "pip" ]
I am trying to setup [Django](https://www.djangoproject.com). When I run `pip install -r requirements.txt`, I get the following exception: ``` Installing collected packages: amqp, anyjson, arrow, beautifulsoup4, billiard, boto, braintree, celery, cffi, cryptography, Django, django-bower, django-braces, django-celery,...
Perhaps **you are not root** and should do: ``` sudo pip install -r requirements.txt ``` Find more about `sudo` [here](https://wiki.archlinux.org/index.php/Sudo). Alternately, if you just cannot or **don't want to make system-wide changes**, follow this guide: [How can I install packages in my $HOME folder with pip?...
pip install -r: OSError: [Errno 13] Permission denied
31,512,422
9
2015-07-20T08:58:05Z
31,512,491
13
2015-07-20T09:02:40Z
[ "python", "django", "pip" ]
I am trying to setup [Django](https://www.djangoproject.com). When I run `pip install -r requirements.txt`, I get the following exception: ``` Installing collected packages: amqp, anyjson, arrow, beautifulsoup4, billiard, boto, braintree, celery, cffi, cryptography, Django, django-bower, django-braces, django-celery,...
Have you tried with *sudo*? ``` sudo pip install -r requirements.txt ```
Check what numbers in a list are divisible by certain numbers?
31,517,851
2
2015-07-20T13:30:50Z
31,517,922
7
2015-07-20T13:34:17Z
[ "python", "math", "for-loop", "list-comprehension" ]
Write a function that receives a list of numbers and a list of terms and returns only the elements that are divisible by all of those terms. You must use two nested list comprehensions to solve it. divisible\_numbers([12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], [2, 3]) # returns [12, 6] def divisible\_numbers(a\_list, a\...
The inner expression should check if for a particular number, that number is evenly divisible by all of the terms in the second list ``` all(i%j==0 for j in a_list_of_terms) ``` Then an outer list comprehension to iterate through the items of the first list ``` [i for i in a_list if all(i%j==0 for j in a_list_of_ter...
Plotting multiple lines with Bokeh and pandas
31,520,951
8
2015-07-20T15:52:00Z
31,707,031
9
2015-07-29T17:15:51Z
[ "python", "pandas", "bokeh" ]
I would like to give a pandas dataframe to Bokeh to plot a line chart with multiple lines. The x-axis should be the df.index and each df.columns should be a separate line. This is what I wouuld like to do: ``` import pandas as pd import numpy as np from bokeh.plotting import figure, show toy_df = pd.DataFrame(data=n...
You need to provide a list of colors to multi\_line. In your example, you would do, something like this: ``` p.multi_line(ts_list_of_list, vals_list_of_list, line_color=['red', 'green', 'blue']) ``` Here's a more general purpose modification of your second example that does more or less what you ended up with, but is...
groupby weighted average and sum in pandas dataframe
31,521,027
3
2015-07-20T15:55:39Z
31,521,177
10
2015-07-20T16:03:36Z
[ "python", "pandas" ]
I have a dataframe , ``` Out[78]: contract month year buys adjusted_lots price 0 W Z 5 Sell -5 554.85 1 C Z 5 Sell -3 424.50 2 C Z 5 Sell -2 424.00 3 C Z 5 Sell -2 423.75 4 C ...
To pass multiple functions to a groupby object, you need to pass a dictionary with the aggregation functions corresponding to the columns: ``` # Define a lambda function to compute the weighted mean: wm = lambda x: np.average(x, weights=df.loc[x.index, "adjusted_lots"]) # Define a dictionary with the functions to app...
pandas column convert currency to float
31,521,526
6
2015-07-20T16:21:19Z
31,521,773
14
2015-07-20T16:36:28Z
[ "python", "pandas", "currency" ]
I have a df with currency: ``` df = pd.DataFrame({'Currency':['$1.00','$2,000.00','(3,000.00)']}) Currency 0 $1.00 1 $2,000.00 2 (3,000.00) ``` I want to convert the 'Currency' dtype to float but I am having trouble with the parentheses string (which indicate a negative amount). This is my current code...
Just add `)` to the existing command, and then convert `(` to `-` to make numbers in parentheses negative. Then convert to float. ``` (df['Currency'].replace( '[\$,)]','', regex=True ) .replace( '[(]','-', regex=True ).astype(float)) Currency 0 1 1 2000 2 -3000 ```
Django: timezone.now() does not return current datetime
31,521,846
2
2015-07-20T16:39:56Z
31,585,771
7
2015-07-23T11:16:29Z
[ "python", "django", "datetime", "django-rest-framework" ]
Through a Django Rest Framework API, I am trying to serve all objects with a datetime in the future. **Problem is, once the server has started up, every time I submit the query, the API will serve all objects whose datetime is greater than the datetime at which the server started instead of the objects whose datetime ...
As the application code is currently written you're running `timezone.now()` once, when the class is first imported from anywhere. Rather than apply the time queryset filtering on the class attribute itself, do so in the `get_queryset()` method so that it'll be re-evaluated on each pass. Eg. ``` class BananasViewSet...
Must Python script define a function as main?
31,523,059
7
2015-07-20T17:47:10Z
31,523,074
10
2015-07-20T17:48:01Z
[ "python", "python-3.x", "coding-style" ]
Must/should a Python script have a `main()` function? For example is it ok to replace ``` if __name__ == '__main__': main() ``` with ``` if __name__ == '__main__': entryPoint() ``` (or some other meaningful name)
Using a function named `main()` is just a convention. You can give it any name you want to. Testing for the module name is *just a nice trick* to prevent code running when your code is not being executed as the `__main__` module (i.e. not when imported as the script Python started with, but imported as a module). You ...
Must Python script define a function as main?
31,523,059
7
2015-07-20T17:47:10Z
31,523,095
7
2015-07-20T17:49:40Z
[ "python", "python-3.x", "coding-style" ]
Must/should a Python script have a `main()` function? For example is it ok to replace ``` if __name__ == '__main__': main() ``` with ``` if __name__ == '__main__': entryPoint() ``` (or some other meaningful name)
No, a Python script doesn't have to have a `main()` function. It is just following conventions because the function that you put under the `if __name__ == '__main__':` statement is the function that really does all of the work for your script, so it is the main function. If there really is function name that would make...
How can I pass arguments to a docker container with a python entry-point script using command?
31,523,551
12
2015-07-20T18:17:06Z
31,523,657
13
2015-07-20T18:22:45Z
[ "python", "docker" ]
So I've got a docker image with a python script as the entry-point and I would like to pass arguments to the python script when the container is run. I've tried to get the arguments using sys.argv and sys.stdin, but neither has worked. I'm trying to run the container using: ``` docker run image argument ```
It depends how the entrypoint was set up. If it was set up in "exec form" then you simply pass the arguments after the `docker run` command, like this: ``` docker run image -a -b -c ``` If it was set up in "shell form" then you have to override the entrypoint, unfortunately. ``` $ docker run --entrypoint echo image ...
Get U, Σ, V* from Truncated SVD in scikit-learn
31,523,575
9
2015-07-20T18:18:17Z
31,528,944
10
2015-07-21T01:35:32Z
[ "python", "scipy", "scikit-learn", "sparse-matrix", "svd" ]
I am using truncated SVD from `scikit-learn` package. In the definition of SVD, an original matrix **A** is approxmated as a product **A** ≈ **UΣV\*** where **U** and **V** have orthonormal columns, and **Σ** is non-negative diagonal. I need to get the **U**, **Σ** and **V\*** matrices. Looking at the source c...
Looking into the source via the link you provided, `TruncatedSVD` is basically a wrapper around sklearn.utils.extmath.randomized\_svd; you can manually call this yourself like this: ``` from sklearn.utils.extmath import randomized_svd U, Sigma, VT = randomized_svd(X, n_components=15, ...
How to implement ZCA Whitening? Python
31,528,800
3
2015-07-21T01:14:02Z
31,528,936
9
2015-07-21T01:34:27Z
[ "python", "neural-network", "pca", "correlated" ]
Im trying to implement **ZCA whitening** and found some articles to do it, but they are a bit confusing.. can someone shine a light for me? Any tip or help is appreciated! Here is the articles i read : <http://courses.media.mit.edu/2010fall/mas622j/whiten.pdf> <http://bbabenko.tumblr.com/post/86756017649/learning-lo...
Is your data stored in an mxn matrix? Where m is the dimension of the data and n are the total number of cases? If that's not the case, you should resize your data. For instance if your images are of size 28x28 and you have only one image, you should have a 1x784 vector. You could use this function: ``` import numpy a...
Geo Django get cities from latitude and longitude
31,538,288
9
2015-07-21T11:51:10Z
31,588,101
7
2015-07-23T12:59:05Z
[ "python", "django", "geodjango" ]
I'm learning how to use Geo Django. When a user registers I save the latitude and longitude information as seen below: ``` from django.contrib.gis.db import models from django.contrib.gis.geos import Point class GeoModel(models.Model): """ Abstract model to provide GEO fields. """ latitude = models.Fl...
You have several solutions to do this: 1. Create another model City ``` from django.contrib.gis.db import models class City(models.Model): name = models.CharField(max_lenght=255) geometry = models.MultiPolygonField() objects = models.GeoManager() ``` Then you can find the name of th...
How to get alternating colours in dashed line using matplotlib?
31,540,258
9
2015-07-21T13:21:26Z
31,544,278
8
2015-07-21T16:10:29Z
[ "python", "matplotlib", "plot" ]
In matplotlib, I want to make a line using `matplotlib.pyplot` which is alternating black and yellow dashes, and then I want to include that line on the legend. How do I do that? I could do something like: ``` from matplotlib import pyplot as plt, gridspec import numpy as np grid = gridspec.GridSpec(1,1) ax = plt.su...
Try this. ``` from matplotlib import pyplot as plt, gridspec, lines import numpy as np grid = gridspec.GridSpec(1,1) ax = plt.subplot(grid[0,0]) x = np.arange(1,11) y = x * 2 ax.plot(x, y, '-', color = 'black', linewidth = 5) ax.plot(x, y, '--', color = 'lawngreen', linewidth = 5) dotted_line1 = lines.Line2D([], ...
inpolygon for Python - Examples of matplotlib.path.Path contains_points() method?
31,542,843
2
2015-07-21T15:04:43Z
31,543,337
11
2015-07-21T15:26:00Z
[ "python", "matlab", "numpy", "matplotlib" ]
I have been searching for a python alternative to MATLAB's inpolygon() and I have come across contains\_points as a good option. However, the docs are a little bare with no indication of what type of data contains\_points expects: > contains\_points(points, transform=None, radius=0.0) > > Returns a bool array which i...
Often in these situations, I find the source to be illuminating... We can see the source for [`path.contains_point`](https://github.com/matplotlib/matplotlib/blob/714d18788320325d0bff75184f62d472f67ceb91/lib/matplotlib/path.py#L483) accepts a container that has at least 2 elements. The source for `contains_points` is ...
How can I extend a set with a tuple?
31,544,050
3
2015-07-21T15:59:46Z
31,544,104
12
2015-07-21T16:02:18Z
[ "python", "set" ]
Unlike `list.extend(L)`, there is no `extend` function in `set`. How can I extend a tuple to a set in pythonic way? ``` t1 = (1, 2, 3) t2 = (3, 4, 5) t3 = (5, 6, 7) s = set() s.add(t1) s.add(t2) s.add(t3) print s set([(3, 4, 5), (5, 6, 7), (1, 2, 3)]) ``` My expected result is: ``` set([1, 2, 3, 4, 5, 6, 7]) ``` ...
Try the `union` method - ``` t1 = (1, 2, 3) t2 = (3, 4, 5) t3 = (5, 6, 7) s= set() s = s.union(t1) s = s.union(t2) s = s.union(t3) s >>> set([1, 2, 3, 4, 5, 6, 7]) ``` Or as indicated in the comments , cleaner method - ``` s = set().union(t1, t2, t3) ```
What misspellings / typos are supported in Python?
31,546,628
3
2015-07-21T18:13:45Z
31,546,629
7
2015-07-21T18:13:45Z
[ "python", "python-3.x" ]
What misspellings / typos are supported in Python? Not alternate spellings such as `is_dir` vs `isdir`, nor `color` vs `colour` but actual wrongly spelt aliases, such as `proprety` for `property` (which isn't supported).
As of Python 3.5 beta 3 the [unittest.mock](https://docs.python.org/3.5/library/unittest.mock.html#unittest.mock.Mock) object now supports `assret` standing in for `assert` -- note that this is not the keyword `assert`, but any attribute of a mock object that matches the regular expression `assert.*` or `assret.*`. So...
How can I solve system of linear equations in SymPy?
31,547,657
5
2015-07-21T19:12:00Z
31,547,816
8
2015-07-21T19:21:29Z
[ "python", "math", "sympy" ]
Sorry, I am pretty new to sympy and python in general. I want to solve the following underdetermined linear system of equations: ``` x + y + z = 1 x + y + 2z = 3 ```
SymPy recently got a new Linear system solver: `linsolve` in `sympy.solvers.solveset`, you can use that as follows: ``` In [38]: from sympy import * In [39]: from sympy.solvers.solveset import linsolve In [40]: x, y, z = symbols('x, y, z') ``` **List of Equations Form:** ``` In [41]: linsolve([x + y + z - 1, x + y...
Are haskell type declarations used the same way as python class/function documentation?
31,549,024
4
2015-07-21T20:30:51Z
31,549,711
8
2015-07-21T21:13:09Z
[ "python", "haskell", "type-declaration" ]
I am using the "Learn you a haskell tutorial" and have reached the type declarations section. I understand that they change the way GHCI gives you an error message, but do they also affect the way the actual function works? If not, is it essentially like a python function documentation written with """ """ underneath "...
Signatures aren't just for documentation (even though they are very useful for that as well). They are enforced by the compiler, which means that by adding signatures you can make the types of your functions more restrictive than they would be otherwise. Toy example: ``` add x y = x + y addInt :: Int -> Int -> Int ad...
Failed building wheel for rpy2
31,552,341
4
2015-07-22T01:21:53Z
31,588,516
7
2015-07-23T13:17:01Z
[ "python", "pip", "rpy2" ]
I'm running `Python v2.7.8` and `R v3.0.2 (2013-09-25) -- "Frisbee Sailing"` on my elementary OS Freya 64 bit (based on Ubuntu 14.04). I'm trying to install the `rpy2` package with: ``` pip install rpy2 ``` and it fails with the error: > Failed building wheel for rpy2 Down below I also see: > error: command 'gcc'...
Found the answer in [this post](http://sysads.co.uk/2014/06/install-r-base-3-1-0-ubuntu-14-04/). I just had to upgrade R from `v3.0.2` to the latest version available for my system (`v3.2.1`). ### Step 1: Uninstall Previous R-base installation ``` sudo apt-get remove r-base-core ``` ### Step 2: Update Sources.List F...
How do I make a class that is also a list?
31,552,432
7
2015-07-22T01:33:42Z
31,552,466
10
2015-07-22T01:38:33Z
[ "python" ]
I want to create a class in Python with various attributes and methods, but for it to inherit the functionality of a list, so that I can append objects to the object itself, not any of its attributes. I want to be able to say '`graph[3]`', rather than '`graph.node_list[3]`'. Is there a way to do this?
All you really need to do is provide a [`__getitem__`](https://docs.python.org/2/reference/datamodel.html#object.__getitem__) ``` In [1]: class Foo: ...: def __init__(self, *args): ...: self.args = args ...: def __getitem__(self, i): ...: return self.args[i] ...: In [2]: c ...
fluphenazine read as \xef\xac\x82uphenazine
31,553,324
5
2015-07-22T03:27:57Z
31,553,581
8
2015-07-22T03:54:35Z
[ "python", "unicode" ]
When I write ``` >>> st = "Piperazine (perphenazine, fluphenazine)" >>> st 'Piperazine (perphenazine, \xef\xac\x82uphenazine)' ``` What is happening? why doesn't it do this for any `fl`? How do I avoid this? It looks \xef\xac\x82 is not, in fact, `fl`. Is there any way to 'translate' this character into fl (as th...
This is what is called a "ligature". In printing, the f and l characters were typeset with a different amount of space between them from what normal pairs of sequential letters used - in fact, the f and l would merge into one character. Other ligatures include "th", "oe", and "st". That's what you're getting in your ...
Bokeh : save plot but don't show it
31,562,898
9
2015-07-22T12:17:20Z
31,562,899
10
2015-07-22T12:17:20Z
[ "python", "bokeh" ]
I am using [Bokeh](http://bokeh.pydata.org) to produce HTML code including figures with `show` method This method ends on opening default browser with HTML opened in it. I want to save the HTML code, without showing it. How can I do that ?
Solution is to replace calls to `show` by calls to `save`.
can't compile openssl because of 'cl' is not recognized
31,563,735
2
2015-07-22T12:53:18Z
31,568,246
7
2015-07-22T15:58:57Z
[ "python", "visual-studio", "openssl", "swig" ]
I am trying to compile openssl library for python script. I am using Windows x64 bit. I am now following steps in this like: <https://github.com/dsoprea/M2CryptoWindows> It worked till I type this command `nmake -f ms\ntdll.mak` in the Developer Command Prompt for VS 2015. I am getting this error: ``` 'cl' is not re...
The C++ tools are not being installed by default in Visual Studio 2015. Run the setup again, and install the C++ parts under "`custom`": [![enter image description here](http://i.stack.imgur.com/TtS5n.png)](http://i.stack.imgur.com/TtS5n.png)
KeyError: SPARK_HOME during SparkConf initialization
31,566,250
2
2015-07-22T14:34:54Z
31,566,695
8
2015-07-22T14:52:37Z
[ "python", "apache-spark", "pyspark" ]
I am a spark newbie and I want to run a Python script from the command line. I have tested pyspark interactively and it works. I get this error when trying to create the sc: ``` File "test.py", line 10, in <module> conf=(SparkConf().setMaster('local').setAppName('a').setSparkHome('/home/dirk/spark-1.4.1-bin-hadoop...
It seems like there are two problems here. The first one is a path you use. `SPARK_HOME` should point to the root directory of the Spark installation so in your case it should probably be `/home/dirk/spark-1.4.1-bin-hadoop2.6` not `/home/dirk/spark-1.4.1-bin-hadoop2.6/bin`. The second problem is a way how you use `se...
Set value for particular cell in pandas DataFrame with iloc
31,569,384
4
2015-07-22T16:52:44Z
31,569,794
7
2015-07-22T17:14:26Z
[ "python", "pandas" ]
I have a question similar to [this](http://stackoverflow.com/questions/26657378/how-to-modify-a-value-in-one-cell-of-a-pandas-data-frame) and [this](http://stackoverflow.com/questions/13842088/set-value-for-particular-cell-in-pandas-dataframe). The difference is that I have to select row by position, as I do not know t...
For mixed position and index, use `.ix`. BUT you need to make sure that your index is not of integer, otherwise it will cause confusions. ``` df.ix[0, 'COL_NAME'] = x ``` ### Update: Alternatively, try ``` df.iloc[0, df.columns.get_loc('COL_NAME')] = x ``` Example: ``` import pandas as pd import numpy as np # yo...
AttributeError: '_socketobject' object has no attribute 'set_tlsext_host_name'
31,576,258
11
2015-07-23T00:31:32Z
31,576,259
12
2015-07-23T00:31:32Z
[ "python", "ubuntu", "ssl", "https", "python-requests" ]
In python, on a Ubuntu server, I am trying to get the `requests` library to make https requests, like so: ``` import requests requests.post("https://example.com") ``` At first, I got the following: > /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl\_.py:90: > InsecurePlatformWarning: A true ...
The fix for me was the following: ``` sudo apt-get purge python-openssl sudo pip install pyopenssl ```
Python: Generating all ordered combinations of a list
31,581,425
3
2015-07-23T08:00:23Z
31,581,790
7
2015-07-23T08:17:51Z
[ "python", "list", "order", "combinations", "itertools" ]
I'm using Python 2.7. I'm having a list, and I want all possible ordered combinations. ``` import itertools stuff = ["a","b","c", "d"] for L in range(1, len(stuff)+1): for subset in itertools.combinations(stuff, L): print( ' '.join(subset)) ``` This will give the following output: ``` a b c d a b a c <-...
I believe what you are looking for are all possible *slices* of your original list. Your desired output translated into slices is this: ``` a # slices[0:1] b # slices[1:2] c # slices[2:3] d # slices[3:4] a b # slices[0:2] b c # slices[1:3] c d # slices[2:4] a b c #...
Which way is better to skip the 'NoneType' variable?
31,587,060
3
2015-07-23T12:14:50Z
31,587,137
7
2015-07-23T12:18:12Z
[ "python", "nonetype" ]
A list contains several `NoneType` elements. To skip the `NoneType`, ``` for item in list : if item is not None : fp.write(item + '\n') #OR for item in list : try : fp.write(item + '\n') except : pass ``` Which one is better and why?
As a general rule of thumb, you should not really be using the `try: except:` pattern for control flow if you can help it. There is some overhead involved with raising an exception that is unnecessary in this context. Hope this helps.
Monkey patching a @property
31,590,152
20
2015-07-23T14:21:02Z
31,591,589
12
2015-07-23T15:19:05Z
[ "python", "python-3.x", "monkeypatching" ]
Is it at all possible to monkey patch the value of a `@property` of an instance of a class that I do not control? ``` class Foo: @property def bar(self): return here().be['dragons'] f = Foo() print(f.bar) # baz f.bar = 42 # MAGIC! print(f.bar) # 42 ``` Obviously the above would produce an error ...
Subclass the base class (`Foo`) and change single instance's class to match the new subclass using `__class__` attribute: ``` >>> class Foo: ... @property ... def bar(self): ... return 'Foo.bar' ... >>> f = Foo() >>> f.bar 'Foo.bar' >>> class _SubFoo(Foo): ... bar = 0 ... >>> f.__class__ = _SubFoo ...
What is the difference between iter(x) and x.__iter__()?
31,590,858
4
2015-07-23T14:49:14Z
31,590,988
7
2015-07-23T14:54:36Z
[ "python" ]
What is the difference between `iter(x)` and `x.__iter__()`? From my understanding, they both return a `listiterator` object but, in the below example, I notice that they are not equal: ``` x = [1, 2, 3] y = iter(x) z = x.__iter__() y == z False ``` Is there something that I am not understanding about iterator objec...
Iter objects dont have equality based on this sort of thing. See that `iter(x) == iter(x)` returns `False` as well. This is because the iter function (which calls `__iter__`) returns an iter object that doesnt overload `__eq__` and therefore only returns `True` when the 2 objects are the same. Without overloading, `=...
Python '==' incorrectly returning false
31,591,914
4
2015-07-23T15:32:37Z
31,591,949
7
2015-07-23T15:34:24Z
[ "python", "python-3.x" ]
I'm trying to get a difference of two files line by line, and Python is always returning false; even when I do a diff of the same files, Python (almost) always returns false. Goofy example, but it replicates my problem on Python 3.4.3. ``` file1.txt (example) 1 2 3 file1 = r"pathtofile\file1.txt" file2 = r"pathtofile...
You have exhausted the iterator after the first iteration over `f2`, you need to `file.seek(0)` to go back to the start of the file. ``` for line1 in f1: found = False for line2 in f2: if repr(line1) == repr(line2): print("true") f2.seek(0) # reset pointer to start of file ``` You only...
pandas iloc vs ix vs loc explanation?
31,593,201
73
2015-07-23T16:34:10Z
31,593,712
145
2015-07-23T16:59:47Z
[ "python", "pandas", "indexing" ]
Can someone explain how these three methods of slicing are different? I've seen [the docs](http://pandas.pydata.org/pandas-docs/stable/indexing.html), and I've seen [these](http://stackoverflow.com/questions/28757389/loc-vs-iloc-vs-ix-vs-at-vs-iat) [answers](http://stackoverflow.com/questions/27667759/is-ix-always-be...
First, a recap: * `loc` works on *labels* in the index. * `iloc` works on the *positions* in the index (so it only takes integers). * `ix` usually tries to behave like `loc` but falls back to behaving like `iloc` if the label is not in the index. It's important to note some subtleties that can make `ix` slightly tric...
pandas iloc vs ix vs loc explanation?
31,593,201
73
2015-07-23T16:34:10Z
31,594,055
22
2015-07-23T17:17:27Z
[ "python", "pandas", "indexing" ]
Can someone explain how these three methods of slicing are different? I've seen [the docs](http://pandas.pydata.org/pandas-docs/stable/indexing.html), and I've seen [these](http://stackoverflow.com/questions/28757389/loc-vs-iloc-vs-ix-vs-at-vs-iat) [answers](http://stackoverflow.com/questions/27667759/is-ix-always-be...
`iloc` works based on integer positioning. So no matter what your row labels are, you can always, e.g., get the first row by doing ``` df.iloc[0] ``` or the last five rows by doing ``` df.iloc[-5:] ``` You can also use it on the columns. This retrieves the 3rd column: ``` df.iloc[:, 2] # the : in the first posi...
Scrapy spider memory leak
31,594,090
12
2015-07-23T17:19:07Z
32,027,424
7
2015-08-15T17:36:53Z
[ "python", "memory-leaks", "scrapy", "scrapyd" ]
My spider have a serious memory leak.. After 15 min of run its memory 5gb and scrapy tells (using prefs() ) that there 900k requests objects and thats all. What can be the reason for this high number of living requests objects? Request only goes up and doesnt goes down. All other objects are close to zero. My spider l...
There are a few possible issues I see right away. Before starting though, I wanted to mention that prefs() doesn't show the number of requests queued, it shows *the number of Request() objects that are alive*. It's possible to reference a request object and keep it alive, even if it's no longer queued to be downloaded...
How do I change the figure size for a seaborn.violin_plot?
31,594,549
5
2015-07-23T17:43:32Z
31,597,200
7
2015-07-23T20:13:37Z
[ "python", "seaborn" ]
How do I change the size of my image so it's suitable for printing? For example, I'd like to use to A4 paper, whose dimensions are 11.7 inches by 8.27 inches in landscape orientation.
You can set the context to be `poster` or manually set `fig_size`. ``` import numpy as np import seaborn as sns import matplotlib.pyplot as plt np.random.seed(0) n, p = 40, 8 d = np.random.normal(0, 2, (n, p)) d += np.log(np.arange(1, p + 1)) * -5 + 10 # plot sns.set_style('ticks') fig, ax = plt.subplots() # the si...
How do I change the figure size for a seaborn.violin_plot?
31,594,549
5
2015-07-23T17:43:32Z
31,597,278
9
2015-07-23T20:19:13Z
[ "python", "seaborn" ]
How do I change the size of my image so it's suitable for printing? For example, I'd like to use to A4 paper, whose dimensions are 11.7 inches by 8.27 inches in landscape orientation.
You need create the matplotlib Figure and Axes objects ahead of time, specifiying how big the figure is: ``` import matploltib.pyplot as plt import seaborn import mylib a4_dims = (11.7, 8.27) df = mylib.load_data() fig, ax = plt.subplots(figsize=a4_dims) seaborn.voilinplot(ax=ax, data=df, **violin_options) ```
sympy: how to sympify logical "NOT"
31,596,229
4
2015-07-23T19:16:31Z
31,596,361
8
2015-07-23T19:24:28Z
[ "python", "sympy" ]
The following code would work to sympify logical expressions: ``` sympify('a&b') # And(a, b) sympify('a|b') # Or(a, b) ``` But how do I get a result of `Not(a)`?
It turns out the symbol you are looking for is `~`. See the following: ``` >>> from sympy import sympify >>> sympify('a&b') And(a, b) >>> sympify('a|b') Or(a, b) >>> sympify('~a') Not(a) ```
How to find out programmatically if a domain name is registered or not
31,597,125
3
2015-07-23T20:09:05Z
31,597,579
14
2015-07-23T20:38:05Z
[ "python", "sockets", "domain-name", "pywhois" ]
I use [pywhois](https://bitbucket.org/richardpenman/pywhois) to determine if a domain name is registered or not. Here is my source code. (all permutations from `a.net` to `zzz.net`) ``` #!/usr/bin/env python import whois #pip install python-whois import string import itertools def main(): characters = list(strin...
This is a tricky problem to solve, trickier than most people realize. The reason for that is that some people don't *want* you to find that out. Most domain registrars apply lots of black magic (i.e. lots of TLD-specific hacks) to get the nice listings they provide, and often they get it wrong. Of course, in the end th...
Why list comprehension is much faster than numpy for multiplying arrays?
31,598,677
6
2015-07-23T21:50:13Z
31,598,746
9
2015-07-23T21:55:35Z
[ "python", "performance", "numpy", "list-comprehension", "matrix-multiplication" ]
Recently I answered to [THIS](http://stackoverflow.com/questions/31596979/multiplication-between-2-lists/31597029#31597029) question which wanted the multiplication of 2 lists,some user suggested the following way using numpy, alongside mine which I think is the proper way : ``` (a.T*b).T ``` Also I found that `aray....
Creation of numpy arrays is much slower than creation of lists: ``` In [153]: %timeit a = [[2,3,5],[3,6,2],[1,3,2]] 1000000 loops, best of 3: 308 ns per loop In [154]: %timeit a = np.array([[2,3,5],[3,6,2],[1,3,2]]) 100000 loops, best of 3: 2.27 µs per loop ``` There can also fixed costs incurred by NumPy function ...
Spark mllib predicting weird number or NaN
31,599,400
4
2015-07-23T22:53:25Z
31,610,206
7
2015-07-24T12:09:26Z
[ "python", "apache-spark", "pyspark", "apache-spark-mllib", "gradient-descent" ]
I am new to Apache Spark and trying to use the machine learning library to predict some data. My dataset right now is only about 350 points. Here are 7 of those points: ``` "365","4",41401.387,5330569 "364","3",51517.886,5946290 "363","2",55059.838,6097388 "362","1",43780.977,5304694 "361","7",46447.196,5471836 "360",...
The problem is that `LinearRegressionWithSGD` uses stochastic gradient descent (SGD) to optimize the weight vector of your linear model. SGD is really sensitive to the provided `stepSize` which is used to update the intermediate solution. What SGD does is to calculate the gradient `g` of the cost function given a samp...
Python 2.7.10 error "from urllib.request import urlopen" no module named request
31,601,238
4
2015-07-24T02:28:23Z
31,601,343
13
2015-07-24T02:43:28Z
[ "python", "urllib" ]
I opened python code from `github`. I assumed it was `python2.x` and got the above error when I tried to run it. From the reading I've seen Python 3 has depreciated `urllib` itself and replaced it with a number of libraries including `urllib.request`. It looks like the code was written in python 3 (a confirmation from...
Try using urllib2: <https://docs.python.org/2/library/urllib2.html> This line should work to replace urlopen: ``` from urllib2 import urlopen ``` Tested in Python 2.7 on Macbook Pro Try posting a link to the git in question.
How can I represent this regex to not get a "bad character range" error?
31,603,075
3
2015-07-24T05:47:21Z
31,605,097
11
2015-07-24T07:56:49Z
[ "python", "regex" ]
Is there a better way to do this? ``` $ python Python 2.7.9 (default, Jul 16 2015, 14:54:10) [GCC 4.1.2 20080704 (Red Hat 4.1.2-55)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import re >>> re.sub(u'[\U0001d300-\U0001d356]', "", "") Traceback (most recent call last): File "...
## Python narrow and wide build (Python versions below 3.3) The error suggests that you are using "narrow" (UCS-2) build, which only supports Unicode code points up to 65535 as one "Unicode character"1. Characters whose code points are above 65536 are represented as surrogate pairs, which means that the Unicode string...
Jupyter (IPython) notebook not plotting
31,609,600
8
2015-07-24T11:38:11Z
31,611,678
19
2015-07-24T13:22:33Z
[ "python", "pandas", "ipython" ]
I installed anaconda to use pandas and scipy. I reading and watching pandas tutorials and they all say to open the ipython notebook using ``` ipython notebook --pylab==inline ``` but when I do that I get a message saying ``` "Support for specifying --pylab on the command line has been removed. Please use '%pylab = ...
I believe the pylab magic was removed when they transitioned from IPython to a more general Jupyter notebook. Try: ``` %matplotlib inline ``` Also when you get a message like: ``` "matplotlib.axes._subplots.AxesSubplot at 0xebf8b70". ``` That's just IPython displaying the object. You need to specify IPython displa...
How to copy/paste DataFrame from StackOverflow into Python
31,610,889
11
2015-07-24T12:45:23Z
31,610,890
12
2015-07-24T12:45:23Z
[ "python", "pandas" ]
In [questions](http://stackoverflow.com/q/17729853/2071807) and [answers](http://stackoverflow.com/a/31609618/2071807), users very often post an example `DataFrame` which their question/answer works with: ``` In []: x Out[]: bar foo 0 4 1 1 5 2 2 6 3 ``` It'd be really useful to be able to get ...
Pandas is written by people that really know what people want to do. [Since version `0.13`](http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#id45) there's a function [`pd.read_clipboard`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_clipboard.html) which is absurdly effective at making th...
os.path.exists() gives false positives in %appdata% on Windows
31,617,936
2
2015-07-24T19:02:04Z
31,617,979
8
2015-07-24T19:04:37Z
[ "python", "windows", "python-3.x", "file-io" ]
I'm trying to make my game project not save in its own directory like it's 1995 or something. The standard library isn't cooperating. Basically, I'm trying to save in `%appdata%\MYGAMENAME\` (this is the value of \_savedir on win32.) `open()` will become understandably upset if such a folder does not exist, so I use ...
Python does not expand the value of `%appdata%`. Instead, a literal directory is created relative to the current working directory. Run `print(os.path.abspath(_savedir))`, that is where the file is created and exists. Use `os.environ['APPDATA']` to create an absolute path to the application data directory: ``` _saved...
AttributeError: 'module' object has no attribute 'ORB'
31,630,559
7
2015-07-25T19:58:39Z
31,632,268
16
2015-07-26T00:01:18Z
[ "python", "opencv", "opencv3.0" ]
when I run my python code ``` import numpy as np import cv2 import matplotlib.pyplot as plt img1 = cv2.imread('/home/shar/home.jpg',0) # queryImage img2 = cv2.imread('/home/shar/home2.jpg',0) # trainImage # Initiate SIFT detector orb = cv2.ORB() # find the keypoints and descriptors with SIFT kp1, des1 = or...
I found this also. I checked the actual contents of the `cv2` module and found `ORB_create()` rather than `ORB()` Use the line ``` orb = cv2.ORB_create() ``` instead of `orb = cv2.ORB()` and it will work. Verified on Python 3.4, OpenCV 3 on Windows, using the OpenCV test data set `box.png` and `box_in_scene.png` wi...
TypeError: Required argument 'outImg' (pos 6) not found
31,631,352
5
2015-07-25T21:33:04Z
31,631,995
7
2015-07-25T23:11:04Z
[ "python", "opencv", "opencv3.0" ]
When I run my python code ``` import numpy as np import cv2 import matplotlib.pyplot as plt img1 = cv2.imread('/home/shar/home.jpg',0) # queryImage img2 = cv2.imread('/home/shar/home2.jpg',0) # trainImage # Initiate SIFT detector sift = cv2.xfeatures2d.SIFT_create() # find the keypoints and descriptors wit...
You seem to be [following this tutorial page](http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_feature2d/py_matcher/py_matcher.html) (based on the code you've shown in this and your two related questions [1](http://stackoverflow.com/questions/31628505/matplotlib-importerror-cannot-import-name-pyplot#comment51209393_...
Label axes on Seaborn barplot
31,632,637
9
2015-07-26T01:08:48Z
31,632,745
17
2015-07-26T01:28:00Z
[ "python", "matplotlib", "seaborn" ]
I'm trying to use my own labels for a Seaborn barplot with the following code: ``` import pandas as pd import seaborn as sns fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]}) fig = sns.barplot(x = 'val', y = 'cat', data = fake, color = 'black') fig.set_axis...
Seaborn's barplot returns an axis-object (not a figure). This means you can do the following: ``` import pandas as pd import seaborn as sns import matplotlib.pyplot as plt fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]}) ax = sns.barplot(x = 'val', y = 'cat', data = fake, ...
python elasticsearch client set mappings during create index
31,635,828
12
2015-07-26T10:18:41Z
31,638,685
17
2015-07-26T15:24:41Z
[ "python", "pyelasticsearch", "elasticsearch-py" ]
I can set mappings of index being created in curl command like this: ``` { "mappings":{ "logs_june":{ "_timestamp":{ "enabled":"true" }, "properties":{ "logdate":{ "type":"date", "format":"dd/MM/yyy HH:mm:ss" } } } } } ``` But...
You can simply add the mapping in the `create` call like this: ``` from elasticsearch import Elasticsearch self.elastic_con = Elasticsearch([host], verify_certs=True) mapping = ''' { "mappings":{ "logs_june":{ "_timestamp":{ "enabled":"true" }, "properties":{ "logdate...
Is Python 3.5's grammar LL(1)?
31,637,435
2
2015-07-26T13:21:35Z
31,637,664
7
2015-07-26T13:45:56Z
[ "python", "parsing", "compiler-construction", "grammar" ]
I saw <http://matt.might.net/teaching/compilers/spring-2015/> saying Python 3.4 is LL(1) Is Python 3.5's grammar still LL(1) so one can write a recursive descent parser?
Yes. This is a deliberate language feature, and not just something that happened to be the case. [PEP 3099](https://www.python.org/dev/peps/pep-3099/) explicitly *rejected* any changes to this for the Python 2 -> 3 transition (a notably bigger transition than any 3.x -> 3.y will be): > * The parser won't be more compl...
What's the difference between homebrew python and caskroom python?
31,639,883
4
2015-07-26T17:28:24Z
31,639,943
8
2015-07-26T17:33:09Z
[ "python", "homebrew", "homebrew-cask" ]
The page [Installing Python on Mac OS X](http://docs.python-guide.org/en/latest/starting/install/osx/) suggests that the OS X version is OK for learning but not great for writing real programs; solution - install from Homebrew. I don't think the caskroom existed when they wrote this page though. Basically, I just want...
Caskroom python installs the Python Mac OS X packages from <https://www.python.org/downloads/mac-osx/> as they are provided there. `brew install python` will install from source and under `/usr/local/Cellar/python/...` and properly symlink `/usr/local/bin/python`. The latter is the "proper homebrew approach" (TM) and...
Python - list comprehension in this case is efficient?
31,640,246
12
2015-07-26T18:05:17Z
31,640,292
14
2015-07-26T18:09:28Z
[ "python" ]
The is the input "dirty" list in python ``` input_list = [' \n ',' data1\n ',' data2\n',' \n','data3\n'.....] ``` each list element contains either empty spaces with new line chars or data with newline chars Cleaned it up using the below code.. ``` cleaned_up_list = [data.strip() for data in input_list if dat...
Using your list comp strip *is* called twice, use a gen exp if you want to only call strip once and keep the comprehension: ``` input_list[:] = [x for x in (s.strip() for s in input_list) if x] ``` Input: ``` input_list = [' \n ',' data1\n ',' data2\n',' \n','data3\n'] ``` Output: ``` ['data1', 'data2', 'da...
Pythonic Django object reuse
31,642,325
2
2015-07-26T21:53:55Z
31,643,185
8
2015-07-26T23:54:18Z
[ "python", "django" ]
I've been racking my brain on this for the last few weeks and I just can't seem to understand it. I'm hoping you folks here can give me some clarity. **A LITTLE BACKGROUND** I've built an API to help serve a large website and like all of us, are trying to keep the API as efficient as possible. Part of this efficiency ...
You come from a background where everything *needs* to be a class, I've programmed web apps in Java too, and sometimes it's harder to unlearn old things than to learn new things, I understand. In Python / Django you wouldn't make anything a class unless you need many instances and need to keep state. For a service th...
Vagrant Not Starting Up. User that created VM doesn't match current user
31,644,222
48
2015-07-27T02:43:16Z
32,256,848
83
2015-08-27T18:25:05Z
[ "python", "vagrant", "virtual-machine", "virtualbox", "virtualenv" ]
I was trying to start up my vagrant machine, so I navigated to the folder where my vagrantfile is, and used: vagrant up && vagrant ssh but I got the following error message: > The VirtualBox VM was created with a user that doesn't match the > current user running Vagrant. VirtualBox requires that the same user > be ...
I ran into the same problem today. I edited my **UID** by opening the file `.vagrant/machines/default/virtualbox/creator_uid` and changing the **501** to a **0**. After I saved the file, the command vagrant up worked like a champ.
Vagrant Not Starting Up. User that created VM doesn't match current user
31,644,222
48
2015-07-27T02:43:16Z
32,977,467
13
2015-10-06T18:50:37Z
[ "python", "vagrant", "virtual-machine", "virtualbox", "virtualenv" ]
I was trying to start up my vagrant machine, so I navigated to the folder where my vagrantfile is, and used: vagrant up && vagrant ssh but I got the following error message: > The VirtualBox VM was created with a user that doesn't match the > current user running Vagrant. VirtualBox requires that the same user > be ...
Ran into this problem in a slightly different situation. The issue was that ".vagrant" was checked into the git repo, and the committer was running under a different UID than I was. Solution: add .vagrant to .gitignore.
No module named 'allauth.account.context_processors'
31,648,019
9
2015-07-27T08:13:03Z
31,675,023
35
2015-07-28T11:30:23Z
[ "python", "django", "packages", "django-allauth", "django-settings" ]
I want to use Django-Allauth, so I installed as following and it works perfectly in my laptop localhost; but when I pull it in my server, I encounter with the following error: ``` No module named 'allauth.account.context_processors' ``` What should I do? ``` # Django AllAuth TEMPLATES = [ { 'BACKEND': 'd...
This means you have different versions of Allauth in your dev machine and in your server. You should definitely use the same version on both sides. Into the why of the issue you are hitting on the server, in version 0.22 of django-allauth, the [context processors have been replaced by template tags](http://django-alla...
python requests ssl handshake failure
31,649,390
11
2015-07-27T09:24:43Z
31,678,467
14
2015-07-28T13:57:39Z
[ "python", "python-requests" ]
Every time I try to do: ``` requests.get('https://url') ``` I got this message: ``` import requests >>> requests.get('https://reviews.gethuman.com/companies') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/dist-packages/requests/api.py", line 55, in get ...
I resolve the problem in the end i updated my ubuntu from 14.04 to 14.10 and the problem was solved but in the older version of ubuntu and python I install those lib and it seems to fix all my problems ``` sudo apt-get install python-dev libssl-dev libffi-dev sudo pip2.7 install -U pyopenssl==0.13.1 pyasn1 ndg-httpsc...
python requests ssl handshake failure
31,649,390
11
2015-07-27T09:24:43Z
34,924,131
13
2016-01-21T12:40:57Z
[ "python", "python-requests" ]
Every time I try to do: ``` requests.get('https://url') ``` I got this message: ``` import requests >>> requests.get('https://reviews.gethuman.com/companies') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/dist-packages/requests/api.py", line 55, in get ...
On OSX, using python 2.7.10 / requests 2.9.1 I only had to to install `requests`using its security setup: ``` pip install requests[security] ``` This installs `pyOpenSSL`, `ndg-httpsclient` and `pyasn1`. <https://github.com/kennethreitz/requests/blob/master/setup.py#L70>
argparse argument named "print"
31,656,015
2
2015-07-27T14:35:22Z
31,656,028
7
2015-07-27T14:36:05Z
[ "python", "python-2.7", "arguments", "keyword", "argparse" ]
I want to add an argument named 'print' to my argument parser ``` arg_parser.add_argument('--print', action='store_true', help="print stuff") args = arg_parser.parse_args(sys.argv[1:]) if args.print: print "stuff" ``` Yields: ``` if args.print: ^ SyntaxError: invalid syntax ```
You can use `getattr()` to access attributes that happen to be [reserved keywords](https://docs.python.org/2/reference/lexical_analysis.html#keywords) too: ``` if getattr(args, 'print'): ``` However, you'll make it yourself much easier by just avoiding that name as a destination; use `print_` perhaps (via the [`dest`...
python map array of dictionaries to dictionary?
31,656,912
5
2015-07-27T15:18:22Z
31,656,965
9
2015-07-27T15:20:43Z
[ "python" ]
I've got an array of dictionaries that looks like this: ``` [ { 'country': 'UK', 'city': 'Manchester' }, { 'country': 'UK', 'city': 'Liverpool' }, { 'country': 'France', 'city': 'Paris' } ... ] ``` And I want to end up with a dictionary like this: ``` { 'Liverpool': 'UK', 'Manchester': 'UK', ... } ``` Obvious...
You can use a [*dict comprehension*](https://www.python.org/dev/peps/pep-0274/) : ``` >>> li = [ ... { 'country': 'UK', 'city': 'Manchester' }, ... { 'country': 'UK', 'city': 'Liverpool' }, ... { 'country': 'France', 'city': 'Paris' } ... ] >>> {d['city']: d['country'] for d in li} {'Paris': 'France', 'Liverpoo...
Python csv.DictReader: parse string?
31,658,115
3
2015-07-27T16:11:56Z
31,658,188
7
2015-07-27T16:15:36Z
[ "python", "csv" ]
I am downloading a CSV file directly from a URL using `requests`. How can I parse the resulting string with `csv.DictReader`? Right now I have this: ``` r = requests.get(url) reader_list = csv.DictReader(r.text) print reader_list.fieldnames for row in reader_list: print row ``` But I just get `['r']` as the res...
From documentation of [`csv`](https://docs.python.org/2/library/csv.html#csv.reader) , the first argument to `csv.reader` or `csv.DictReader` is `csvfile` - > csvfile can be any object which supports the iterator protocol and returns a string each time its next() method is called — file objects and list objects are ...
Spark iteration time increasing exponentially when using join
31,659,404
7
2015-07-27T17:22:39Z
31,662,127
13
2015-07-27T19:57:10Z
[ "python", "loops", "apache-spark", "iteration", "pyspark" ]
I'm quite new to Spark and I'm trying to implement some iterative algorithm for clustering (expectation-maximization) with centroid represented by Markov model. So I need to do iterations and joins. One problem that I experience is that each iterations time growth exponentially. After some experimenting I found that...
**Summary**: Generally speaking iterative algorithms, especially ones with self-join or self-union, require a control over: * Length of the lineage (see for example [Stackoverflow due to long RDD Lineage](http://stackoverflow.com/q/34461804/1560062) and [unionAll resulting in StackOverflow](http://stackoverflow.com/q...
Efficiently create sparse pivot tables in pandas?
31,661,604
8
2015-07-27T19:26:38Z
31,679,396
14
2015-07-28T14:33:36Z
[ "python", "pandas", "scipy", "scikit-learn", "sparse-matrix" ]
I'm working turning a list of records with two columns (A and B) into a matrix representation. I have been using the pivot function within pandas, but the result ends up being fairly large. Does pandas support pivoting into a sparse format? I know I can pivot it and then turn it into some kind of sparse representation,...
Here is a method that creates a sparse scipy matrix based on data and indices of person and thing. `person_u` and `thing_u` are lists representing the unique entries for your rows and columns of pivot you want to create. Note: this assumes that your count column already has the value you want in it. ``` from scipy.spa...
Asyncio + aiohttp - redis Pub/Sub and websocket read/write in single handler
31,670,127
9
2015-07-28T07:36:44Z
31,684,719
14
2015-07-28T18:46:57Z
[ "python", "redis", "python-asyncio", "aiohttp" ]
I'm currently playing with [aiohttp](http://aiohttp.readthedocs.org/) to see how it will perform as a server application for mobile app with websocket connection. Here is simple "Hello world" example ([as gist here](https://gist.github.com/anonymous/2b0432082e0171683beb)): ``` import asyncio import aiohttp from aioht...
You should use two `while` loops - one that handles messages from the websocket, and one that handles messages from redis. Your main handler can just kick off two coroutines, one handling each loop, and then wait on *both* of them: ``` class WebsocketEchoHandler: @asyncio.coroutine def __call__(self, request):...
Python: transform a list of lists of tuples
31,676,133
4
2015-07-28T12:18:56Z
31,676,183
7
2015-07-28T12:21:05Z
[ "python", "list", "tuples" ]
Suppose I have a data structure as follows: ``` [[ tuple11, tuple12, ... ], [ tuple21, tuple22, ... ], ...] ``` That is, the outer list can have any number of elements and each element (list) can contain any number of elements (tuples). How can I transform it to: ``` [[ tuple11, tuple21, ... ], ...
You want the columns, so you can use `zip` function : ``` zip(*main_list) ``` But since it returns the columns in tuple format if you only want list you can use `map` to convert them to list : ``` map(list,zip(*main_list)) ``` Demo: ``` >>> main_list=[[(1,2),(3,4)],[(5,6),(7,8)]] >>> zip(*main_list) [((1, 2), (5, ...
Python, where i am wrong for the function to remove vowels in a string?
31,676,580
3
2015-07-28T12:38:32Z
31,676,695
8
2015-07-28T12:44:12Z
[ "python" ]
I am following the codecademy tutorial, the question is "Define a function called anti\_vowel that takes one string, text, as input and returns the text with all of the vowels removed. For example: anti\_vowel("Hey You!") should return "Hy Y!"." The code: ``` def anti_vowel(text): textlist = list(text) print...
The reason is already explained in the comments by @jonrsharpe. I would like to show you an optimised version, which does work and uses list comprehension: ``` def anti_vowel(text): return "".join([x for x in text if x not in "aeiouAEIOU"]) print anti_vowel("Hey look Words!") ``` output: ``` Hy lk Wrds! ```
What is a Pythonic way for Dependency Injection?
31,678,827
23
2015-07-28T14:10:11Z
31,813,464
7
2015-08-04T15:34:39Z
[ "python", "oop", "authentication", "dependency-injection", "frameworks" ]
# Introduction For Java, Dependency Injection works as pure OOP, i.e. you provide an interface to be implemented and in your framework code accept an instance of a class that implements the defined interface. Now for Python, you are able to do the same way, but I think that method was too much overhead right in case ...
The way we do dependency injection in our project is by using the [inject](https://pypi.python.org/pypi/Inject/3.1.1) lib. Check out the [documentation](https://pypi.python.org/pypi/Inject/3.1.1). I highly recommend using it for DI. It kinda makes no sense with just one function but starts making lots of sense when you...
What is a Pythonic way for Dependency Injection?
31,678,827
23
2015-07-28T14:10:11Z
31,909,086
9
2015-08-09T21:38:05Z
[ "python", "oop", "authentication", "dependency-injection", "frameworks" ]
# Introduction For Java, Dependency Injection works as pure OOP, i.e. you provide an interface to be implemented and in your framework code accept an instance of a class that implements the defined interface. Now for Python, you are able to do the same way, but I think that method was too much overhead right in case ...
See [Raymond Hettinger - Super considered super! - PyCon 2015](https://www.youtube.com/watch?v=EiOglTERPEo) for an argument about how to use super and multiple inheritance instead of DI. If you don't have time to watch the whole video, jump to minute 15 (but I'd recommend watching all of it). Here is an example of how...
Python 2.7 Get month from 2 months ago (i.e get '05' from todays date)
31,679,821
2
2015-07-28T14:49:21Z
31,679,870
7
2015-07-28T14:51:16Z
[ "python", "python-2.7", "date", "datetime" ]
I'm sure there is an easy way to do this that I have missed with my efforts to find the answer. Basically how do I get the number of month i.e '05' or '04' from n number of months ago? Apologies if this was already answered but the questions I researched here could not answer my question. **Edit** There is no month...
With some simple modular arithmetic: ``` from datetime import date def months_ago(count): today = date.today() return ((today.month - count - 1) % 12) + 1 ``` Demo: ``` >>> date.today() datetime.date(2015, 7, 28) >>> for i in range(13): ... print(months_ago(i)) ... 7 6 5 4 3 2 1 12 11 10 9 8 7 ```
Making SVM run faster in python
31,681,373
13
2015-07-28T15:53:13Z
32,025,662
12
2015-08-15T14:23:48Z
[ "python", "scikit-learn", "svm" ]
Using the **code** below for svm in python: ``` from sklearn import datasets from sklearn.multiclass import OneVsRestClassifier from sklearn.svm import SVC iris = datasets.load_iris() X, y = iris.data, iris.target clf = OneVsRestClassifier(SVC(kernel='linear', probability=True, class_weight='auto')) clf.fit(X, y) prob...
If you want to stick with SVC as much as possible and train on the full dataset, you can use ensembles of SVCs that are trained on subsets of the data to reduce the number of records per classifier (which apparently has quadratic influence on complexity). Scikit supports that with the `BaggingClassifier` wrapper. That ...
Python list comprehension trick
31,682,890
2
2015-07-28T17:07:50Z
31,682,915
7
2015-07-28T17:09:37Z
[ "python", "list", "python-3.x", "list-comprehension" ]
It's probably a silly question, but... ``` list = [] for i in range(1, 5): for j in range(i): list.append(i) print(list) list2 = [[i]*i for i in range(1, 5)] print(list2) ``` With following code my output is like ``` [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]] ``` I understand...
Is this what you want? ``` >>> list2 = [i for i in range(1, 5) for j in range(i)] >>> list2 [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] ``` Trick is to put similar `for` loops in same order inside the list comprehension (and since you do not need list of lists, do not create those).
Suppress stderr within subprocess.check_output()
31,683,320
3
2015-07-28T17:31:03Z
31,683,402
7
2015-07-28T17:36:10Z
[ "python", "python-2.7", "subprocess" ]
I'm trying to find a way to ignore the stderr stream (something similar to `2> /dev/null`): ``` output = subprocess.check_output("netstat -nptl".split()) ``` What should I add to the above command to achieve this?
Just tell `subprocess` to redirect it for you: ``` import os import subprocess with open(os.devnull, 'w') as devnull: output = subprocess.check_output("netstat -nptl".split(), stderr=devnull) ``` Note that Python 3 adds a [`subprocess.DEVNULL` object](https://docs.python.org/3/library/subprocess.html#subprocess....
Automatically create requirements.txt
31,684,375
7
2015-07-28T18:29:03Z
31,684,470
9
2015-07-28T18:34:04Z
[ "python", "python-import" ]
Sometimes I download python source code from github and don't know how to install all the dependencies. If there is no requirements.txt file I have to create it by hands. The question is: Given python source code directory is it possible to create requirements.txt automatically from import section?
You can use the following code to generate a requirements.txt file: ``` pip install pipreqs pipreqs /path/to/project ``` more info related to pipreqs can be found [here](https://github.com/bndr/pipreqs). Sometimes you come across `pip freeze`, but this saves all packages in the environment including those that you ...
Automatically create requirements.txt
31,684,375
7
2015-07-28T18:29:03Z
33,468,993
7
2015-11-02T00:39:32Z
[ "python", "python-import" ]
Sometimes I download python source code from github and don't know how to install all the dependencies. If there is no requirements.txt file I have to create it by hands. The question is: Given python source code directory is it possible to create requirements.txt automatically from import section?
If you use virtual environment, `pip freeze > requirements.txt` just fine. If not, [pigar](https://github.com/Damnever/pigar) will be a good choice for you. By the way, I do not ensure it will work with 2.6.