internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: numpy/numpy

Issue:
meshgrid silently ignores unknown arguments.
The `meshgrid` function silently ignores arguments.

``` python
>>> import numpy
>>> X, Y = numpy.meshgrid(range(3), range(4), indexing='ij')
>>> x, y = numpy.ogrid[:3,:4]
>>> np.allclose(X, x) and np.allclose(Y, y)
True
>>> X, Y = numpy.meshgrid(range(3), range(4), indices='ij')  # OOPS!
>>> np.allclose(X, x) and np.allclose(Y, y)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-17-f031cff10ee1> in <module>()
----> 1 np.allclose(X, x) and np.allclose(Y, y)
...
ValueError: operands could not be broadcast together with shapes (4,3) (3,1) 
```



Discussion:

Resolving patch:
diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py
--- a/numpy/lib/function_base.py
+++ b/numpy/lib/function_base.py
@@ -3370,9 +3370,13 @@ def meshgrid(*xi, **kwargs):
     """
     ndim = len(xi)
 
-    copy_ = kwargs.get('copy', True)
-    sparse = kwargs.get('sparse', False)
-    indexing = kwargs.get('indexing', 'xy')
+    copy_ = kwargs.pop('copy', True)
+    sparse = kwargs.pop('sparse', False)
+    indexing = kwargs.pop('indexing', 'xy')
+
+    if kwargs:
+        raise TypeError("meshgrid() got an unexpected keyword argument '%s'"
+                        % (list(kwargs)[0],))
 
     if not indexing in ['xy', 'ij']:
         raise ValueError(


Test patch:
diff --git a/numpy/lib/tests/test_function_base.py b/numpy/lib/tests/test_function_base.py
--- a/numpy/lib/tests/test_function_base.py
+++ b/numpy/lib/tests/test_function_base.py
@@ -1454,6 +1454,13 @@ def test_sparse(self):
         assert_array_equal(X, np.array([[1, 2, 3]]))
         assert_array_equal(Y, np.array([[4], [5], [6], [7]]))
 
+    def test_invalid_arguments(self):
+        # Test that meshgrid complains about invalid arguments
+        # Regression test for issue #4755:
+        # https://github.com/numpy/numpy/issues/4755
+        assert_raises(TypeError, meshgrid, 
+                      [1, 2, 3], [4, 5, 6, 7], indices='ij')
+
 
 class TestPiecewise(TestCase):
     def test_simple(self):
Repository: numpy/numpy

Issue:
removed/changed paths in 1.9.0rc1
I'm seeing the following errors from setup.py:

```
non-existing path in 'numpy/f2py': 'docs'
non-existing path in 'numpy/f2py': 'f2py.1'
non-existing path in 'numpy/lib': 'benchmarks'
```

It would be nice if f2py.1 was installed in /usr/share/man/man1/f2py.1.



Discussion:
The references in the various setup.py files need to be updated or removed.


Resolving patch:
diff --git a/numpy/f2py/setup.py b/numpy/f2py/setup.py
--- a/numpy/f2py/setup.py
+++ b/numpy/f2py/setup.py
@@ -32,12 +32,10 @@
 def configuration(parent_package='',top_path=None):
     config = Configuration('f2py', parent_package, top_path)
 
-    config.add_data_dir('docs')
     config.add_data_dir('tests')
 
     config.add_data_files('src/fortranobject.c',
                           'src/fortranobject.h',
-                          'f2py.1'
                           )
 
     config.make_svn_version_py()
diff --git a/numpy/lib/setup.py b/numpy/lib/setup.py
--- a/numpy/lib/setup.py
+++ b/numpy/lib/setup.py
@@ -13,7 +13,6 @@ def configuration(parent_package='',top_path=None):
                          sources=[join('src', '_compiled_base.c')]
                          )
 
-    config.add_data_dir('benchmarks')
     config.add_data_dir('tests')
 
     return config


Test patch:
Repository: numpy/numpy

Issue:
`bmat` does not document the arguments `ldict` and `gdict`
See:
- http://docs.scipy.org/doc/numpy/reference/generated/numpy.bmat.html
- https://github.com/numpy/numpy/blob/master/numpy/matrixlib/defmatrix.py#L1155



Discussion:

Resolving patch:
diff --git a/numpy/matrixlib/defmatrix.py b/numpy/matrixlib/defmatrix.py
--- a/numpy/matrixlib/defmatrix.py
+++ b/numpy/matrixlib/defmatrix.py
@@ -1161,6 +1161,12 @@ def bmat(obj, ldict=None, gdict=None):
     obj : str or array_like
         Input data.  Names of variables in the current scope may be
         referenced, even if `obj` is a string.
+    ldict : dict, optional
+        A dictionary that replaces local operands in current frame.
+        Ignored if `obj` is not a string or `gdict` is `None`.
+    gdict : dict, optional
+        A dictionary that replaces global operands in current frame.
+        Ignored if `obj` is not a string.
 
     Returns
     -------


Test patch:
Repository: numpy/numpy

Issue:
`array` function's docstring is not clear on default value for `order` parameter
In the docstring for `numpy.array`, it says that the default value for the `order` parameter is `'C'` (i.e., the output will be C-contiguous). This is true if `copy=True`, but if `copy=False` then `array` acts like `asarray` (not `ascontiguousarray`) and the output is not guaranteed to be contiguous. Explicitly setting `order='C'` forces a copy if the input is not C-contiguous.

The docstring needs to be changed to reflect this difference, so that it does not say that `'C'` is the default value for `order`.

`array` function's docstring is not clear on default value for `order` parameter
In the docstring for `numpy.array`, it says that the default value for the `order` parameter is `'C'` (i.e., the output will be C-contiguous). This is true if `copy=True`, but if `copy=False` then `array` acts like `asarray` (not `ascontiguousarray`) and the output is not guaranteed to be contiguous. Explicitly setting `order='C'` forces a copy if the input is not C-contiguous.

The docstring needs to be changed to reflect this difference, so that it does not say that `'C'` is the default value for `order`.



Discussion:

Resolving patch:
diff --git a/numpy/add_newdocs.py b/numpy/add_newdocs.py
--- a/numpy/add_newdocs.py
+++ b/numpy/add_newdocs.py
@@ -664,13 +664,13 @@ def luf(lamdaexpr, *args, **kwargs):
         nested sequence, or if a copy is needed to satisfy any of the other
         requirements (`dtype`, `order`, etc.).
     order : {'C', 'F', 'A'}, optional
-        Specify the order of the array.  If order is 'C' (default), then the
-        array will be in C-contiguous order (last-index varies the
-        fastest).  If order is 'F', then the returned array
-        will be in Fortran-contiguous order (first-index varies the
-        fastest).  If order is 'A', then the returned array may
-        be in any order (either C-, Fortran-contiguous, or even
-        discontiguous).
+        Specify the order of the array.  If order is 'C', then the array
+        will be in C-contiguous order (last-index varies the fastest).
+        If order is 'F', then the returned array will be in
+        Fortran-contiguous order (first-index varies the fastest).
+        If order is 'A' (default), then the returned array may be
+        in any order (either C-, Fortran-contiguous, or even discontiguous),
+        unless a copy is required, in which case it will be C-contiguous.
     subok : bool, optional
         If True, then sub-classes will be passed-through, otherwise
         the returned array will be forced to be a base-class array (default).


Test patch:
Repository: numpy/numpy

Issue:
savetxt raises a misleading error if array's shape is not rectangular
Hi,

```
a = np.array([[1., 2.], [1., 2., 3.]]
np.savetxt('/tmp/toto', a)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-4a2768c04067> in <module>()
----> 1 np.savetxt('/tmp/toto', a)

/usr/lib/python3.3/site-packages/numpy/lib/npyio.py in savetxt(fname, X, fmt, delimiter, newline, header, footer, comments)
   1061         else:
   1062             for row in X:
-> 1063                 fh.write(asbytes(format % tuple(row) + newline))
   1064         if len(footer) > 0:
   1065             footer = footer.replace('\n', '\n' + comments)

TypeError: a float is required
```

The error is misleading because all elements are made of floats. I agree that the array type is object but it would be easier to debug if we can distinguish between an array with mixed types and an array uncorrectly shaped. 

It took me half an hour to figure out my mistake.

I would be happy to hear your comments.
Thanks.



Discussion:
Not sure how to handle this. The array is an object array, which is OK, but the objects are lists, which is not. 1-D arrays are also OK. So it seems to me that the best we can do here is include the offending type as part of the error message.


Resolving patch:
diff --git a/numpy/lib/npyio.py b/numpy/lib/npyio.py
--- a/numpy/lib/npyio.py
+++ b/numpy/lib/npyio.py
@@ -1088,7 +1088,12 @@ def savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='',
                 fh.write(asbytes(format % tuple(row2) + newline))
         else:
             for row in X:
-                fh.write(asbytes(format % tuple(row) + newline))
+                try:
+                    fh.write(asbytes(format % tuple(row) + newline))
+                except TypeError:
+                    raise TypeError("Mismatch between array dtype ('%s') and "
+                                    "format specifier ('%s')"
+                                    % (str(X.dtype), format))
         if len(footer) > 0:
             footer = footer.replace('\n', '\n' + comments)
             fh.write(asbytes(comments + footer + newline))


Test patch:
Repository: numpy/numpy

Issue:
loadtxt(comments=None) considers the string 'None' as a comment symbol
Numpy 1.8.2
`numpy.loadtxt(comments=None)` considers the string `'None'` as a comment symbol.

Expected behaviour:
`comments=None` should indicate that there are no comments symbols. Certainly not cast `None` to a string, what is this, Javascript?



Discussion:

Resolving patch:
diff --git a/numpy/lib/npyio.py b/numpy/lib/npyio.py
--- a/numpy/lib/npyio.py
+++ b/numpy/lib/npyio.py
@@ -729,7 +729,8 @@ def loadtxt(fname, dtype=float, comments='#', delimiter=None,
 
     """
     # Type conversions for Py3 convenience
-    comments = asbytes(comments)
+    if comments is not None:
+        comments = asbytes(comments)
     user_converters = converters
     if delimiter is not None:
         delimiter = asbytes(delimiter)
@@ -802,7 +803,10 @@ def pack_items(items, packing):
 
     def split_line(line):
         """Chop off comments, strip, and split at delimiter."""
-        line = asbytes(line).split(comments)[0].strip(asbytes('\r\n'))
+        if comments is None:
+            line = asbytes(line).strip(asbytes('\r\n'))
+        else:
+            line = asbytes(line).split(comments)[0].strip(asbytes('\r\n'))
         if line:
             return line.split(delimiter)
         else:


Test patch:
diff --git a/numpy/lib/tests/test_io.py b/numpy/lib/tests/test_io.py
--- a/numpy/lib/tests/test_io.py
+++ b/numpy/lib/tests/test_io.py
@@ -786,6 +786,14 @@ def test_bad_line(self):
         # Check for exception and that exception contains line number
         assert_raises_regex(ValueError, "3", np.loadtxt, c)
 
+    def test_none_as_string(self):
+        # gh-5155, None should work as string when format demands it
+        c = TextIO()
+        c.write('100,foo,200\n300,None,400')
+        c.seek(0)
+        dt = np.dtype([('x', int), ('a', 'S10'), ('y', int)])
+        data = np.loadtxt(c, delimiter=',', dtype=dt, comments=None)
+
 
 class Testfromregex(TestCase):
     # np.fromregex expects files opened in binary mode.
Repository: numpy/numpy

Issue:
Error in help documentation of numpy.zeros
The help documentation for numpy zeros method (`import numpy; help(numpy.zeros)`) shows an example like this:

``` python
>>> np.zeros((5,), dtype=numpy.int)
array([0, 0, 0, 0, 0])
```

The documentation throughout `multiarray` module assumes that `numpy` is imported as `np` but the value for `dtype` keyword is passed as `numpy.int`.  While the above snippet conveys the point across, it will throw a name error if some one actually tried to execute it:

``` python
>>> import numpy as np
>>> np.zeros((5,), dtype=numpy.int)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'numpy' is not defined
```

This can be fixed by consitent usage of `numpy` or `np`. 



Discussion:

Resolving patch:
diff --git a/numpy/add_newdocs.py b/numpy/add_newdocs.py
--- a/numpy/add_newdocs.py
+++ b/numpy/add_newdocs.py
@@ -885,7 +885,7 @@ def luf(lamdaexpr, *args, **kwargs):
     >>> np.zeros(5)
     array([ 0.,  0.,  0.,  0.,  0.])
 
-    >>> np.zeros((5,), dtype=numpy.int)
+    >>> np.zeros((5,), dtype=np.int)
     array([0, 0, 0, 0, 0])
 
     >>> np.zeros((2, 1))


Test patch:
Repository: numpy/numpy

Issue:
BUG: numpy.ma.polyfit masks NaNs incorrectly
The current implementation of [`numpy.ma.polyfit`](https://github.com/numpy/numpy/blob/master/numpy/ma/extras.py#L1898) fails with masked arrays that mask NaNs.

For example this :

```
import numpy as np
x = np.array([1, 2, np.nan, 4])
y = np.array([1, 2, 3, 4])

x_masked = np.ma.masked_invalid(x)
y_masked = np.ma.masked_invalid(y)

print np.ma.polyfit(x_masked, y_masked, 1)
```

yields the following error message when run using numpy 1.9.0 and the latest development version with python 2.7.9 on mac OSX 10.10

```
** On entry to DLASCL, parameter number  4 had an illegal value
** On entry to DLASCL, parameter number  4 had an illegal value
** On entry to DLASCL, parameter number  4 had an illegal value
** On entry to DLASCL, parameter number  4 had an illegal value
** On entry to DLASCL, parameter number  5 had an illegal value
** On entry to DLASCL, parameter number  4 had an illegal value
[ nan  nan]
```

I think this is due to the way `numpy.ma.polyfit` is implemented. Currently it sets the weight of any point that is masked in the fit to zero which is fine for any finite value of the input arrays, however if one of the masked values is NaN then it will still propagate through to the result.



Discussion:

Resolving patch:
diff --git a/numpy/ma/extras.py b/numpy/ma/extras.py
--- a/numpy/ma/extras.py
+++ b/numpy/ma/extras.py
@@ -1921,12 +1921,12 @@ def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False):
         m = mask_or(m, getmask(w))
 
     if m is not nomask:
+        not_m = ~m
         if w is not None:
-            w = ~m*w
-        else:
-            w = ~m
-
-    return np.polyfit(x, y, deg, rcond, full, w, cov)
+            w = w[not_m]
+        return np.polyfit(x[not_m], y[not_m], deg, rcond, full, w, cov)
+    else:
+        return np.polyfit(x, y, deg, rcond, full, w, cov)
 
 polyfit.__doc__ = ma.doc_note(np.polyfit.__doc__, polyfit.__doc__)
 


Test patch:
diff --git a/numpy/ma/tests/test_extras.py b/numpy/ma/tests/test_extras.py
--- a/numpy/ma/tests/test_extras.py
+++ b/numpy/ma/tests/test_extras.py
@@ -734,6 +734,21 @@ def test_polyfit(self):
         for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)):
             assert_almost_equal(a, a_)
 
+    def test_polyfit_with_masked_NaNs(self):
+        x = np.random.rand(10)
+        y = np.random.rand(20).reshape(-1, 2)
+
+        x[0] = np.nan
+        y[-1,-1] = np.nan
+        x = x.view(MaskedArray)
+        y = y.view(MaskedArray)
+        x[0] = masked
+        y[-1,-1] = masked
+
+        (C, R, K, S, D) = polyfit(x, y, 3, full=True)
+        (c, r, k, s, d) = np.polyfit(x[1:-1], y[1:-1,:], 3, full=True)
+        for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)):
+            assert_almost_equal(a, a_)
 
 class TestArraySetOps(TestCase):
Repository: numpy/numpy

Issue:
f2py C to fortran mapping file files under python 3.3
Under python 3.3, f2py fails to read the file `.f2py_f2cmap`, for mapping fortran types to C types. It gives an exception `RuntimeError: dictionary size changed during iteration`. This is due to python 3's `keys()` and `items()` members of dictionaries returning iterators instead of lists. In `capi_maps.py` there is iteration over these functions, during which the dictionary is modified. This should be fixable by wrapping these calls with `list()`, which reproduces the old python 2 behaviour.



Discussion:

Resolving patch:
diff --git a/numpy/f2py/capi_maps.py b/numpy/f2py/capi_maps.py
--- a/numpy/f2py/capi_maps.py
+++ b/numpy/f2py/capi_maps.py
@@ -178,14 +178,14 @@
         f = open('.f2py_f2cmap', 'r')
         d = eval(f.read(), {}, {})
         f.close()
-        for k, d1 in d.items():
-            for k1 in d1.keys():
+        for k, d1 in list(d.items()):
+            for k1 in list(d1.keys()):
                 d1[k1.lower()] = d1[k1]
             d[k.lower()] = d[k]
-        for k in d.keys():
+        for k in list(d.keys()):
             if k not in f2cmap_all:
                 f2cmap_all[k]={}
-            for k1 in d[k].keys():
+            for k1 in list(d[k].keys()):
                 if d[k][k1] in c2py_map:
                     if k1 in f2cmap_all[k]:
                         outmess("\tWarning: redefinition of {'%s':{'%s':'%s'->'%s'}}\n"%(k, k1, f2cmap_all[k][k1], d[k][k1]))


Test patch:
Repository: numpy/numpy

Issue:
raising of NotImplementedError could be more helpful
numpy 1.9.0

numpy/ma/core.py line 5462 says:

```
    raise NotImplementedError("Not implemented yet, sorry...")
```

This is in MaskedArray.tofile().  I came across this when answering a user support question where my user asserted "I am not writing a masked array to the file".

There are a few places in this file that give ambiguous errors like that.  It would be more helpful if the exception message were to say what it is that is not implemented.  For example, in this case:

```
    raise NotImplementedError("cannot write masked array to file")
```

There are other places in ms/core.py where there are similarly ambiguous messages, so I conjecture there may be other ambiguous messages in other places.  I suggest a sweep of the full numpy source code for NotImplementedError and clarify all the messages.

I think this would be easy for a numpy developer.  I am not very familiar with numpy myself.  Since this is a trivial (mostly) change, I could possibly make a pull request, if I have some indication that it would be accepted without me making a major commitment to testing or learning the numpy developer work flow.  (Unfortunately, I don't have time to make a serious commitment to becoming a numpy developer.)



Discussion:
@stsci-sienkiew I am not a core numpy developer, but AFAICT, simple fixes like these are always welcome (and generally do not even require writing or modifying tests).


Resolving patch:
diff --git a/numpy/ma/core.py b/numpy/ma/core.py
--- a/numpy/ma/core.py
+++ b/numpy/ma/core.py
@@ -5569,7 +5569,7 @@ def tofile(self, fid, sep="", format="%s"):
             When `tofile` is called.
 
         """
-        raise NotImplementedError("Not implemented yet, sorry...")
+        raise NotImplementedError("MaskedArray.tofile() not implemented yet.")
 
     def toflex(self):
         """
@@ -7277,7 +7277,7 @@ def loads(strg):
 
 ################################################################################
 def fromfile(file, dtype=float, count= -1, sep=''):
-    raise NotImplementedError("Not yet implemented. Sorry")
+    raise NotImplementedError("fromfile() not yet implemented for a MaskedArray.")
 
 
 def fromflex(fxarray):


Test patch:
Repository: numpy/numpy

Issue:
_broadcast_shape is broken when 32 < nargs
xref https://github.com/numpy/numpy/pull/5371

``` python
>>> np.__version__
'1.10.0.dev0+30e3d41'
>>> from numpy.lib.stride_tricks import _broadcast_shape
>>> lst = [np.ones((5, 7, 11))] * 32 + [np.ones((2, 3))] * 32
>>> _broadcast_shape(*lst)
(2, 3)
>>> _broadcast_shape(*lst[::-1])  # process the list in reverse order
(5, 7, 11)
```

In [this line](https://github.com/numpy/numpy/blob/05b5335ecf25e59477956b4f85b9a8edbdf71bcc/numpy/lib/stride_tricks.py#L123) `b` is ultimately converted to an array of shape `1 x 1`; so it will broadcast with the rest of args regardless of their shape.



Discussion:

Resolving patch:
diff --git a/numpy/lib/stride_tricks.py b/numpy/lib/stride_tricks.py
--- a/numpy/lib/stride_tricks.py
+++ b/numpy/lib/stride_tricks.py
@@ -126,6 +126,10 @@ def _broadcast_shape(*args):
     b = np.broadcast(*args[:32])
     # unfortunately, it cannot handle 32 or more arguments directly
     for pos in range(32, len(args), 31):
+        # ironically, np.broadcast does not properly handle np.broadcast
+        # objects (it treats them as scalars)
+        # use broadcasting to avoid allocating the full array
+        b = broadcast_to(0, b.shape)
         b = np.broadcast(b, *args[pos:(pos + 31)])
     return b.shape
 


Test patch:
diff --git a/numpy/lib/tests/test_stride_tricks.py b/numpy/lib/tests/test_stride_tricks.py
--- a/numpy/lib/tests/test_stride_tricks.py
+++ b/numpy/lib/tests/test_stride_tricks.py
@@ -273,6 +273,11 @@ def test_broadcast_shape():
     assert_equal(_broadcast_shape(*([np.ones((1, 2))] * 32)), (1, 2))
     assert_equal(_broadcast_shape(*([np.ones((1, 2))] * 100)), (1, 2))
 
+    # regression tests for gh-5862
+    assert_equal(_broadcast_shape(*([np.ones(2)] * 32 + [1])), (2,))
+    bad_args = [np.ones(2)] * 32 + [np.ones(3)] * 32
+    assert_raises(ValueError, lambda: _broadcast_shape(*bad_args))
+
 
 def test_as_strided():
     a = np.array([None])
Repository: numpy/numpy

Issue:
Documentation error for numpy.loadtxt Example 1
[Line 699](https://github.com/numpy/numpy/blob/v1.9.1/numpy/lib/npyio.py#L699) should be:

from io import StringIO



Discussion:

Resolving patch:
diff --git a/numpy/lib/npyio.py b/numpy/lib/npyio.py
--- a/numpy/lib/npyio.py
+++ b/numpy/lib/npyio.py
@@ -798,7 +798,7 @@ def loadtxt(fname, dtype=float, comments='#', delimiter=None,
 
     Examples
     --------
-    >>> from StringIO import StringIO   # StringIO behaves like a file object
+    >>> from io import StringIO   # StringIO behaves like a file object
     >>> c = StringIO("0 1\\n2 3")
     >>> np.loadtxt(c)
     array([[ 0.,  1.],
@@ -1420,7 +1420,7 @@ def genfromtxt(fname, dtype=float, comments='#', delimiter=None,
 
     Examples
     ---------
-    >>> from StringIO import StringIO
+    >>> from io import StringIO
     >>> import numpy as np
 
     Comma delimited file with mixed dtype


Test patch:
Repository: numpy/numpy

Issue:
linspace should give a Warning or Exception when num is negative
I just finished tracking down a bug that would have been much easier to find if `linspace` did not just give back an empty array whan `num` is negative. An exception or at least a warning (to be backwards compatible) would have been nice to have.



Discussion:
A `ValueError` exception seems appropriate for `num <= 0`. If you want to make a PR that would be welcome.

`num == 0` looks valid to me, I would expect an array with 0 elements. Only strictly negative values have no meaning.
(Take this as a remark more than a strong opinion)


Resolving patch:
diff --git a/numpy/core/function_base.py b/numpy/core/function_base.py
--- a/numpy/core/function_base.py
+++ b/numpy/core/function_base.py
@@ -25,7 +25,7 @@ def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None):
         evenly spaced samples, so that `stop` is excluded.  Note that the step
         size changes when `endpoint` is False.
     num : int, optional
-        Number of samples to generate. Default is 50.
+        Number of samples to generate. Default is 50. Must be non-negative.
     endpoint : bool, optional
         If True, `stop` is the last sample. Otherwise, it is not included.
         Default is True.
@@ -82,6 +82,8 @@ def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None):
 
     """
     num = int(num)
+    if num < 0:
+        raise ValueError("Number of samples, %s, must be non-negative." % num)
     div = (num - 1) if endpoint else num
 
     # Convert float/complex array scalars to float, gh-3504


Test patch:
diff --git a/numpy/core/tests/test_function_base.py b/numpy/core/tests/test_function_base.py
--- a/numpy/core/tests/test_function_base.py
+++ b/numpy/core/tests/test_function_base.py
@@ -34,6 +34,7 @@ def test_basic(self):
         assert_(y[-1] == 10)
         y = linspace(2, 10, endpoint=0)
         assert_(y[-1] < 10)
+        assert_raises(ValueError, linspace, 0, 10, num=-1)
 
     def test_corner(self):
         y = list(linspace(0, 1, 1))