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

Issue:
jitclass __doc__ passthrough to instance
Jitclass is not exposing the docstring of the class nor the methods.



Discussion:
Thanks @sklam. QuantEcon (http://quantecon.org) is working on a Statistical Distributions package which makes use of `@jitclass` and it would be great to get this setup. 

https://github.com/QuantEcon/Distributions.py/issues/4


Resolving patch:
diff --git a/numba/jitclass/boxing.py b/numba/jitclass/boxing.py
--- a/numba/jitclass/boxing.py
+++ b/numba/jitclass/boxing.py
@@ -77,7 +77,9 @@ def _specialize_box(typ):
     if typ in _cache_specialized_box:
         return _cache_specialized_box[typ]
     dct = {'__slots__': (),
-           '_numba_type_': typ}
+           '_numba_type_': typ,
+           '__doc__': typ.class_type.class_def.__doc__,
+           }
     # Inject attributes as class properties
     for field in typ.struct:
         getter = _generate_getter(field)
@@ -91,7 +93,10 @@ def _specialize_box(typ):
             getter = _generate_getter(field)
         if 'set' in impdct:
             setter = _generate_setter(field)
-        dct[field] = property(getter, setter)
+        # get docstring from either the fget or fset
+        imp = impdct.get('get') or impdct.get('set') or None
+        doc = getattr(imp, '__doc__', None)
+        dct[field] = property(getter, setter, doc=doc)
     # Inject methods as class members
     for name, func in typ.methods.items():
         if not (name.startswith('__') and name.endswith('__')):
@@ -112,7 +117,8 @@ def _specialize_box(typ):
                 fast_fget = fget.compile((typ,))
                 fget.disable_compile()
                 setattr(subcls, k,
-                        property(fast_fget, prop.fset, prop.fdel))
+                        property(fast_fget, prop.fset, prop.fdel,
+                                 doc=prop.__doc__))
 
     return subcls
 


Test patch:
diff --git a/numba/tests/test_jitclasses.py b/numba/tests/test_jitclasses.py
--- a/numba/tests/test_jitclasses.py
+++ b/numba/tests/test_jitclasses.py
@@ -564,6 +564,26 @@ def test_annotations(self):
         self.assertEqual(obj.x, 5)
         self.assertEqual(obj.add(2), 7)
 
+    def test_docstring(self):
+
+        @jitclass([])
+        class Apple(object):
+            "Class docstring"
+            def __init__(self):
+                "init docstring"
+
+            def foo(self):
+                "foo method docstring"
+
+            @property
+            def aval(self):
+                "aval property docstring"
+
+        self.assertEqual(Apple.__doc__, 'Class docstring')
+        self.assertEqual(Apple.__init__.__doc__, 'init docstring')
+        self.assertEqual(Apple.foo.__doc__, 'foo method docstring')
+        self.assertEqual(Apple.aval.__doc__, 'aval property docstring')
+
 
 if __name__ == '__main__':
     unittest.main()
Repository: numba/numba

Issue:
Failed to handle structure dtype with attribute titles
from mailing list https://groups.google.com/a/continuum.io/d/msg/numba-users/WHpxHBlTXt0/Mx_5RBtgBgAJ

An "ValueError: too many values to unpack" error is raised when a translating a numpy structure dtype to a numba type.  The translation logic does not expect a title field for the attribution description.  



Discussion:

Resolving patch:
diff --git a/numba/numpy_support.py b/numba/numpy_support.py
--- a/numba/numpy_support.py
+++ b/numba/numpy_support.py
@@ -356,7 +356,10 @@ def from_struct_dtype(dtype):
         raise TypeError("Do not support dtype containing object")
 
     fields = {}
-    for name, (elemdtype, offset) in dtype.fields.items():
+
+    for name, info in dtype.fields.items():
+        # *info* may have 3 element if it has a "title", which can be ignored
+        [elemdtype, offset] = info[:2]
         fields[name] = from_dtype(elemdtype), offset
 
     # Note: dtype.alignment is not consistent.


Test patch:
diff --git a/numba/tests/test_record_dtype.py b/numba/tests/test_record_dtype.py
--- a/numba/tests/test_record_dtype.py
+++ b/numba/tests/test_record_dtype.py
@@ -663,6 +663,37 @@ def test_record_two_arrays(self):
         cfunc = self.get_cfunc(pyfunc, (nbrecord,))
         self.assertEqual(cfunc(rec), pyfunc(rec))
 
+    def test_structure_dtype_with_titles(self):
+        # the following is the definition of int4 vector type from pyopencl
+        vecint4 = np.dtype([(('x', 's0'), 'i4'), (('y', 's1'), 'i4'),
+                            (('z', 's2'), 'i4'), (('w', 's3'), 'i4')])
+        nbtype = numpy_support.from_dtype(vecint4)
+        self.assertEqual(len(nbtype.fields), len(vecint4.fields))
+
+        arr = np.zeros(10, dtype=vecint4)
+
+        def pyfunc(a):
+            for i in range(a.size):
+                j = i + 1
+                a[i]['s0'] = j * 2
+                a[i]['x'] += -1
+
+                a[i]['s1'] = j * 3
+                a[i]['y'] += -2
+
+                a[i]['s2'] = j * 4
+                a[i]['z'] += -3
+
+                a[i]['s3'] = j * 5
+                a[i]['w'] += -4
+
+            return a
+
+        expect = pyfunc(arr.copy())
+        cfunc = self.get_cfunc(pyfunc, (nbtype[:],))
+        got = cfunc(arr.copy())
+        np.testing.assert_equal(expect, got)
+
 
 def _get_cfunc_nopython(pyfunc, argspec):
     return jit(argspec, nopython=True)(pyfunc)
Repository: numba/numba

Issue:
cpu='parallel' on windows extremely slow after 0.23.1
Prior to numba=0.23.1 I could get the attached benchmark 
[cpu_parallel_benchmark.zip](https://github.com/numba/numba/files/428952/cpu_parallel_benchmark.zip)
yielding best times of 49 milli-seconds.

As of numba=0.23.1 and all later, the benchmark runs at about 8590 mili-seconds or about 170x slower. I've tested all of the revisions from 0.23.1 to 0.27 and they all have the same behavior for me.

I am on Windows x64 so presumably this has something to do with #1634 and target='parallel'?



Discussion:
Apologies, my benchmark code referenced a module that was not included. Here is a fixed version which demonstrates the same performance degradation post 0.23.0: 
[cpu_parallel_benchmark2.zip](https://github.com/numba/numba/files/429112/cpu_parallel_benchmark2.zip)


Resolving patch:
diff --git a/numba/npyufunc/parallel.py b/numba/npyufunc/parallel.py
--- a/numba/npyufunc/parallel.py
+++ b/numba/npyufunc/parallel.py
@@ -390,55 +390,6 @@ def build_gufunc_kernel(library, ctx, innerfunc, sig, inner_ndim):
 # ---------------------------------------------------------------------------
 
 
-class _ProtectEngineDestroy(object):
-    def __init__(self, set_cas, engine):
-        self.set_cas = set_cas
-        self.engine = engine
-
-    def __del__(self):
-        """
-        We need to set the CAS function to NULL to prevent the worker threads to
-        execute this function as LLVM is releasing the memory of the function.
-        """
-        self.set_cas(0)
-
-
-_keepalive = []
-
-
-def _make_cas_function():
-    """
-    Generate a compare-and-swap function for portability sake.
-    """
-    from numba.targets.registry import cpu_target
-
-    codegen = cpu_target.target_context.codegen()
-
-    # Generate IR
-    library = codegen.create_library('cas_for_parallel_ufunc')
-    mod = library.create_ir_module('cas_module')
-
-    llint = lc.Type.int()
-    llintp = lc.Type.pointer(llint)
-    fnty = lc.Type.function(llint, [llintp, llint, llint])
-    fn = mod.add_function(fnty, name='.numba.parallel.ufunc.cas')
-    ptr, old, repl = fn.args
-    bb = fn.append_basic_block('')
-    builder = lc.Builder(bb)
-    outpack = builder.cmpxchg(ptr, old, repl, ordering='monotonic')
-    out = builder.extract_value(outpack, 0)
-    failed = builder.extract_value(outpack, 1)
-    builder.ret(builder.select(failed, old, out))
-
-    # Build & Link
-    library.add_ir_module(mod)
-    library.finalize()
-
-    ptr = library.get_pointer_to_function(fn.name)
-
-    return library, ptr
-
-
 def _launch_threads():
     """
     Initialize work queues and workers
@@ -464,13 +415,6 @@ def _init():
     ll.add_symbol('numba_synchronize', lib.synchronize)
     ll.add_symbol('numba_ready', lib.ready)
 
-    set_cas = CFUNCTYPE(None, c_void_p)(lib.set_cas)
-
-    library, cas_ptr = _make_cas_function()
-    set_cas(c_void_p(cas_ptr))
-
-    _keepalive.append(_ProtectEngineDestroy(set_cas, library))
-
     _is_initialized = True
 
 


Test patch:
Repository: numba/numba

Issue:
'>>' applied to an unsigned number shall result in a logical shift
Please, see 
[http://stackoverflow.com/questions/38486442/logical-right-shift-in-numba](http://stackoverflow.com/questions/38486442/logical-right-shift-in-numba)

Thanks



Discussion:
I cannot reproduce your example. Which platform are you using?

Ok, I can reproduce if I try `hex(foo(2**64 - 1))` instead.


Resolving patch:
diff --git a/numba/typing/builtins.py b/numba/typing/builtins.py
--- a/numba/typing/builtins.py
+++ b/numba/typing/builtins.py
@@ -241,8 +241,15 @@ class PowerBuiltin(BinOpPower):
 
 
 class BitwiseShiftOperation(ConcreteTemplate):
-    cases = list(integer_binop_cases)
-
+    # For bitshifts, only the first operand's signedness matters
+    # to choose the operation's signedness (the second operand
+    # should always be positive but will generally be considered
+    # signed anyway, since it's often a constant integer).
+    # (also, see issue #1995 for right-shifts)
+    cases = [signature(max(op, types.intp), op, types.intp)
+             for op in sorted(types.signed_domain)]
+    cases += [signature(max(op, types.uintp), op, types.intp)
+              for op in sorted(types.unsigned_domain)]
 
 @infer
 class BitwiseLeftShift(BitwiseShiftOperation):


Test patch:
diff --git a/numba/tests/test_operators.py b/numba/tests/test_operators.py
--- a/numba/tests/test_operators.py
+++ b/numba/tests/test_operators.py
@@ -1370,9 +1370,16 @@ def check(xt, yt, control_func):
                            % (x, y, (xt, yt)))
                     self.assertPreciseEqual(got, expected, msg=msg)
 
-        for xt, yt in self.signed_pairs:
+        # For bitshifts, only the first operand's signedness matters
+        # to choose the operation's signedness.
+        signed_pairs = [(u, v) for u, v in self.type_pairs
+                        if u.signed]
+        unsigned_pairs = [(u, v) for u, v in self.type_pairs
+                          if not u.signed]
+
+        for xt, yt in signed_pairs:
             check(xt, yt, control_signed)
-        for xt, yt in self.unsigned_pairs:
+        for xt, yt in unsigned_pairs:
             check(xt, yt, control_unsigned)
 
     def test_lshift(self):
Repository: numba/numba

Issue:
array type created from record-dtype is unusable
``` python
In [11]: a=np.dtype([('a', np.int32)])

In [12]: typeof(a)[:]   # numba cannot consume this type
Out[12]: array(dtype(Record([('a', '<i4')])), 1d, A)

In [13]: typeof(np.empty(1, dtype=a))
Out[13]: unaligned array(Record([('a', '<i4')]), 1d, C)   # notice how it is different from previous
```



Discussion:

Resolving patch:
diff --git a/numba/types/npytypes.py b/numba/types/npytypes.py
--- a/numba/types/npytypes.py
+++ b/numba/types/npytypes.py
@@ -100,6 +100,10 @@ def key(self):
     def dtype(self):
         return self._dtype
 
+    def __getitem__(self, arg):
+        res = super(DType, self).__getitem__(arg)
+        return res.copy(dtype=self.dtype)
+
 
 class NumpyFlatType(SimpleIteratorType, MutableSequence):
     """


Test patch:
diff --git a/numba/tests/test_types.py b/numba/tests/test_types.py
--- a/numba/tests/test_types.py
+++ b/numba/tests/test_types.py
@@ -18,7 +18,7 @@
 from numba.utils import IS_PY3
 from numba import sigutils, types, typing
 from numba.types.abstract import _typecache
-from numba import jit, numpy_support
+from numba import jit, numpy_support, typeof
 from .support import TestCase, tag
 from .enum_usecases import *
 
@@ -176,6 +176,19 @@ def check(arrty, scalar, ndim, layout):
         check(scalar[:,::1], scalar, 2, 'C')
         check(scalar[::1,:], scalar, 2, 'F')
 
+    def test_array_notation_for_dtype(self):
+        def check(arrty, scalar, ndim, layout):
+            self.assertIs(arrty.dtype, scalar)
+            self.assertEqual(arrty.ndim, ndim)
+            self.assertEqual(arrty.layout, layout)
+        scalar = types.int32
+        dtyped = types.DType(scalar)
+        check(dtyped[:], scalar, 1, 'A')
+        check(dtyped[::1], scalar, 1, 'C')
+        check(dtyped[:,:], scalar, 2, 'A')
+        check(dtyped[:,::1], scalar, 2, 'C')
+        check(dtyped[::1,:], scalar, 2, 'F')
+
     @tag('important')
     def test_call_notation(self):
         # Function call signature
@@ -490,5 +503,33 @@ def check_error(sig, msg):
         check_error([], "invalid signature")
 
 
+class TestRecordDtype(unittest.TestCase):
+    def test_record_type_equiv(self):
+        rec_dt = np.dtype([('a', np.int32), ('b', np.float32)])
+        rec_ty = typeof(rec_dt)
+        art1 = rec_ty[::1]
+        arr = np.zeros(5, dtype=rec_dt)
+        art2 = typeof(arr)
+        self.assertEqual(art2.dtype.dtype, rec_ty)
+        self.assertEqual(art1, art2)
+
+    def test_user_specified(self):
+        rec_dt = np.dtype([('a', np.int32), ('b', np.float32)])
+        rec_type = typeof(rec_dt)
+
+        @jit((rec_type[:],), nopython=True)
+        def foo(x):
+            return x['a'], x['b']
+
+        arr = np.zeros(1, dtype=rec_dt)
+        arr[0]['a'] = 123
+        arr[0]['b'] = 32.1
+
+        a, b = foo(arr)
+
+        self.assertEqual(a, arr[0]['a'])
+        self.assertEqual(b, arr[0]['b'])
+
+
 if __name__ == '__main__':
     unittest.main()
Repository: numba/numba

Issue:
Support `dtype.type` for casting 
For example:

```python
def foo(arr, val):
    if val > 0:
         return arr[val]
    else:
         return arr.dtype.type(0)  # return 0 in the type of arr.dtype
```



Discussion:

Resolving patch:
diff --git a/numba/targets/arrayobj.py b/numba/targets/arrayobj.py
--- a/numba/targets/arrayobj.py
+++ b/numba/targets/arrayobj.py
@@ -1967,6 +1967,15 @@ def array_complex_attr(context, builder, typ, value, attr):
     return impl_ret_borrowed(context, builder, resultty, result._getvalue())
 
 
+#-------------------------------------------------------------------------------
+# DType attribute
+
+@lower_getattr(types.DType, 'type')
+def dtype_type(context, builder, dtypety, dtypeval):
+    # Just return a dummy opaque value
+    return context.get_dummy_value()
+
+
 #-------------------------------------------------------------------------------
 # Structured / record lookup
 
diff --git a/numba/typing/arraydecl.py b/numba/typing/arraydecl.py
--- a/numba/typing/arraydecl.py
+++ b/numba/typing/arraydecl.py
@@ -425,6 +425,15 @@ def generic_resolve(self, ary, attr):
                 return ary.copy(dtype=ary.dtype.typeof(attr), layout='A')
 
 
+@infer_getattr
+class DTypeAttr(AttributeTemplate):
+    key = types.DType
+
+    def resolve_type(self, ary):
+        # Wrap the numeric type in NumberClass
+        return types.NumberClass(ary.dtype)
+
+
 @infer
 class StaticGetItemArray(AbstractTemplate):
     key = "static_getitem"


Test patch:
diff --git a/numba/tests/test_types.py b/numba/tests/test_types.py
--- a/numba/tests/test_types.py
+++ b/numba/tests/test_types.py
@@ -531,5 +531,27 @@ def foo(x):
         self.assertEqual(b, arr[0]['b'])
 
 
+class TestDType(TestCase):
+    def test_type_attr(self):
+        # Test .type attribute of dtype
+        def conv(arr, val):
+            return arr.dtype.type(val)
+
+        jit_conv = jit(nopython=True)(conv)
+
+        def assert_matches(arr, val, exact):
+            expect = conv(arr, val)
+            got = jit_conv(arr, val)
+            self.assertPreciseEqual(expect, exact)
+            self.assertPreciseEqual(typeof(expect), typeof(got))
+            self.assertPreciseEqual(expect, got)
+
+        arr = np.zeros(5)
+        assert_matches(arr.astype(np.intp), 1.2, 1)
+        assert_matches(arr.astype(np.float64), 1.2, 1.2)
+        assert_matches(arr.astype(np.complex128), 1.2, (1.2 + 0j))
+        assert_matches(arr.astype(np.complex128), 1.2j, 1.2j)
+
+
 if __name__ == '__main__':
     unittest.main()
Repository: numba/numba

Issue:
Support np.trace at nopython mode
The following snippet fails at `nopython` mode:

```python
@jit(nopython=True)
def test():
    c = np.linalg.matrix_power(np.random.rand(10,10), 4)
    return np.trace(c)
```

with the error message:

```shell
Failed at nopython (nopython frontend)
np.trace() only supported for array types
[1] During: resolving callee type: Function(<unbound method OverloadTemplate_trace.trace>)
[2] During: typing of call at <ipython-input-37-ebf534a41ae3> (4)
```
I believe `np.trace` was added recently in #2175.  


Discussion:

Resolving patch:
diff --git a/numba/targets/linalg.py b/numba/targets/linalg.py
--- a/numba/targets/linalg.py
+++ b/numba/targets/linalg.py
@@ -725,6 +725,9 @@ def _check_linalg_matrix(a, func_name, la_prefix=True):
     # module
     prefix = "np.linalg" if la_prefix else "np"
     interp = (prefix, func_name)
+    # Unpack optional type
+    if isinstance(a, types.Optional):
+        a = a.type
     if not isinstance(a, types.Array):
         msg = "%s.%s() only supported for array types" % interp
         raise TypingError(msg)


Test patch:
diff --git a/numba/tests/test_linalg.py b/numba/tests/test_linalg.py
--- a/numba/tests/test_linalg.py
+++ b/numba/tests/test_linalg.py
@@ -2199,6 +2199,21 @@ def check(a, **kwargs):
             self.cfunc_w_offset, np.ones(
                 (2, 2)), offset=1.2)
 
+    def test_trace_w_optional_input(self):
+        "Issue 2314"
+        @jit("(optional(float64[:,:]),)", nopython=True)
+        def tested(a):
+            return np.trace(a)
+
+        a = np.ones((5, 5), dtype=np.float64)
+        tested(a)
+
+        with self.assertRaises(TypeError) as raises:
+            tested(None)
+
+        errmsg = str(raises.exception)
+        self.assertEqual('expected array(float64, 2d, A), got None', errmsg)
+
 
 class TestBasics(TestLinalgSystems):  # TestLinalgSystems for 1d test
Repository: numba/numba

Issue:
Type inference let through invalid cast in setitem
See comment in
https://github.com/numba/numba/pull/2400#discussion_r122973897

```
numba.errors.LoweringError: Failed at nopython (nopython mode backend)
Cannot cast complex128 to float64: %".268" = load {double, double}, {double, double}* %"$6.4.16"
```

Type inference should have prevented the lowering error and early rejected the code.


Discussion:

Resolving patch:
diff --git a/numba/typing/arraydecl.py b/numba/typing/arraydecl.py
--- a/numba/typing/arraydecl.py
+++ b/numba/typing/arraydecl.py
@@ -204,7 +204,8 @@ def generic(self, args, kws):
                 else:
                     # Incompatible scalar type
                     return
-        elif not isinstance(val, types.Array):
+        elif (not isinstance(val, types.Array) and
+              self.context.can_convert(val, res)):
             # Single item assignment
             res = val
         else:


Test patch:
diff --git a/numba/tests/test_typingerror.py b/numba/tests/test_typingerror.py
--- a/numba/tests/test_typingerror.py
+++ b/numba/tests/test_typingerror.py
@@ -44,6 +44,11 @@ def unknown_module():
 def nop(x, y, z):
     pass
 
+def array_setitem_invalid_cast():
+    arr = np.empty(1, dtype=np.float64)
+    arr[0] = 1j  # invalid cast from complex to float
+    return arr
+
 
 class Foo(object):
     def __repr__(self):
@@ -122,6 +127,12 @@ def test_imprecise_list(self):
         self.assertIn("Can't infer type of variable 'l': list(undefined)",
                       errmsg)
 
+    def test_array_setitem_invalid_cast(self):
+        with self.assertRaises(TypingError) as raises:
+            compile_isolated(array_setitem_invalid_cast, ())
+
+        errmsg = str(raises.exception)
+        self.assertIn("setitem: array(float64, 1d, C)[0] = complex128", errmsg)
 
 class TestArgumentTypingError(unittest.TestCase):
     """
Repository: numba/numba

Issue:
Search box in docs from RTD is failing
Search box in docs from RTD is failing, basicstrap has a seemingly related error. Try different theme to see if it fixes it.


Discussion:
Adding in this theme https://github.com/ryan-roemer/sphinx-bootstrap-theme and rebuilding makes the search box work again, so it's probably something broken in the basicstrap theme. Any suggestions for a new theme?
The sphinx-bootstrap-theme seems like a good alternative, maybe with the `"paper"` `bootswatch_theme` option: http://ryan-roemer.github.io/sphinx-bootstrap-theme/README.html#theme-options

Resolving patch:
diff --git a/docs/source/conf.py b/docs/source/conf.py
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -15,6 +15,7 @@
 
 import sys
 import os
+import sphinx_bootstrap_theme
 
 # If extensions (or modules to document with autodoc) are in another directory,
 # add these directories to sys.path here. If the directory is relative to the
@@ -114,16 +115,18 @@
 # a list of builtin themes.
 #html_theme = 'default'
 
-# pip install sphinxjp.themes.basicstrap
-html_theme = 'basicstrap'
+# pip install sphinx_bootstrap_theme
+html_theme = 'bootstrap'
 
 # Theme options are theme-specific and customize the look and feel of a theme
 # further.  For a list of options available for each theme, see the
 # documentation.
-#html_theme_options = {}
+html_theme_options = {
+  'bootswatch_theme': "paper",
+}
 
 # Add any paths that contain custom themes here, relative to this directory.
-#html_theme_path = []
+html_theme_path = sphinx_bootstrap_theme.get_html_theme_path()
 
 # The name for this set of Sphinx documents.  If None, it defaults to
 # "<project> v<release> documentation".
@@ -134,7 +137,7 @@
 
 # The name of an image file (relative to this directory) to place at the top
 # of the sidebar.
-#html_logo = None
+html_logo = "../_static/numba_blue_icon_rgb.png"
 
 # The name of an image file (within the static path) to use as favicon of the
 # docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32


Test patch: