gurudesh/pytracebugs huggingface dataset:
# Buggy code
def decryptPassword(cryptPass):
    hsm = _get_hsm()
    try:
        ret = hsm.decrypt_password(cryptPass)
    except Exception as exx:  # pragma: no cover
        log.warning(exx)
        ret = "FAILED TO DECRYPT PASSWORD!"
    return ret


# Traceback (SMTPAuthenticationError)
SMTPAuthenticationError: (535, '5.7.8 Error: authentication failed:')
[2016-03-28 19:55:39,479][30338][140453494273792][WARNING][privacyidea.lib.crypto:326] 'NoneType' object has no attribute 'find'
[2016-03-28 19:55:41,528][30338][140453494273792][ERROR][privacyidea.app:1423] Exception on /smtpserver/send_test_email [POST]
Traceback (most recent call last):
File "/opt/privacyidea/venv/local/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/opt/privacyidea/venv/local/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/opt/privacyidea/venv/local/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/opt/privacyidea/venv/local/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/opt/privacyidea/venv/local/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/opt/privacyidea/privacyidea/api/lib/prepolicy.py", line 96, in policy_wrapper
return wrapped_function(*args, **kwds)
File "/opt/privacyidea/privacyidea/lib/log.py", line 125, in log_wrapper
f_result = func(*args, **kwds)
File "/opt/privacyidea/privacyidea/api/smtpserver.py", line 146, in test
"The configuration %s is working." % identifier)
File "/opt/privacyidea/privacyidea/lib/smtpserver.py", line 93, in test_email
mail.login(config.username, password)
File "/usr/lib/python2.7/smtplib.py", line 613, in login
raise SMTPAuthenticationError(code, resp)

# Fixed code
def decryptPassword(cryptPass):
    hsm = _get_hsm()
    try:
        ret = hsm.decrypt_password(cryptPass)
    except Exception as exx:  # pragma: no cover
        log.warning(exx)
        ret = FAILED_TO_DECRYPT_PASSWORD
    return ret
# Buggy code
def _display_as_base(cls):
    """
    A decorator that makes an exception class look like its base.

    We use this to hide subclasses that are implementation details - the user
    should catch the base type, which is what the traceback will show them.

    Classes decorated with this decorator are subject to removal without a
    deprecation warning.
    """
    assert issubclass(cls, Exception)
    cls.__name__ = cls.__base__.__name__
    cls.__qualname__ = cls.__base__.__qualname__
    set_module(cls.__base__.__module__)(cls)
    return cls


# Traceback (numpy.core._exceptions.UFuncTypeError)
Traceback (most recent call last):
File "ufunctypeerror.py", line 6, in <module>
numpy.ones(1) * "foo"
numpy.core._exceptions.UFuncTypeError: ufunc 'multiply' did not contain a loop with signature matching types (dtype('<U32'), dtype('<U32')) -> dtype('<U32')

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "ufunctypeerror.py", line 8, in <module>
pickle.dumps(e)
_pickle.PicklingError: Can't pickle <class 'numpy.core._exceptions.UFuncTypeError'>: it's not the same object as numpy.core._exceptions.UFuncTypeError

# Fixed code
def _display_as_base(cls):
    """
    A decorator that makes an exception class look like its base.

    We use this to hide subclasses that are implementation details - the user
    should catch the base type, which is what the traceback will show them.

    Classes decorated with this decorator are subject to removal without a
    deprecation warning.
    """
    assert issubclass(cls, Exception)
    cls.__name__ = cls.__base__.__name__
    return cls
# Buggy code
def _raw_fft(a, n, axis, is_real, is_forward, fct):
    axis = normalize_axis_index(axis, a.ndim)
    if n is None:
        n = a.shape[axis]

    if n < 1:
        raise ValueError("Invalid number of FFT data points (%d) specified." % n)

    if a.shape[axis] != n:
        s = list(a.shape)
        if s[axis] > n:
            index = [slice(None)] * len(s)
            index[axis] = slice(0, n)
            a = a[tuple(index)]
        else:
            index = [slice(None)] * len(s)
            index[axis] = slice(0, s[axis])
            s[axis] = n
            z = zeros(s, a.dtype.char)
            z[tuple(index)] = a
            a = z

    if axis == a.ndim - 1:
        r = pfi.execute(a, is_real, is_forward, fct)
    else:
        a = swapaxes(a, axis, -1)
        r = pfi.execute(a, is_real, is_forward, fct)
        r = swapaxes(r, axis, -1)
    return r


# Traceback (ZeroDivisionError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<__array_function__ internals>", line 6, in ifft
File "/home/peter/.local/lib/python3.7/site-packages/numpy/fft/pocketfft.py", line 274, in ifft
fct = 1/n
ZeroDivisionError: division by zero

# Fixed code
def _raw_fft(a, n, axis, is_real, is_forward, inv_norm):
    axis = normalize_axis_index(axis, a.ndim)
    if n is None:
        n = a.shape[axis]

    if n < 1:
        raise ValueError("Invalid number of FFT data points (%d) specified." % n)

    fct = 1 / inv_norm

    if a.shape[axis] != n:
        s = list(a.shape)
        if s[axis] > n:
            index = [slice(None)] * len(s)
            index[axis] = slice(0, n)
            a = a[tuple(index)]
        else:
            index = [slice(None)] * len(s)
            index[axis] = slice(0, s[axis])
            s[axis] = n
            z = zeros(s, a.dtype.char)
            z[tuple(index)] = a
            a = z

    if axis == a.ndim - 1:
        r = pfi.execute(a, is_real, is_forward, fct)
    else:
        a = swapaxes(a, axis, -1)
        r = pfi.execute(a, is_real, is_forward, fct)
        r = swapaxes(r, axis, -1)
    return r
# Buggy code
def __init__(
    self, pyfunc, otypes=None, doc=None, excluded=None, cache=False, signature=None
):
    self.pyfunc = pyfunc
    self.cache = cache
    self.signature = signature
    self._ufunc = None  # Caching to improve default performance

    if doc is None:
        self.__doc__ = pyfunc.__doc__
    else:
        self.__doc__ = doc

    if isinstance(otypes, str):
        for char in otypes:
            if char not in typecodes["All"]:
                raise ValueError("Invalid otype specified: %s" % (char,))
    elif iterable(otypes):
        otypes = "".join([_nx.dtype(x).char for x in otypes])
    elif otypes is not None:
        raise ValueError("Invalid otype specification")
    self.otypes = otypes

    # Excluded variable support
    if excluded is None:
        excluded = set()
    self.excluded = set(excluded)

    if signature is not None:
        self._in_and_out_core_dims = _parse_gufunc_signature(signature)
    else:
        self._in_and_out_core_dims = None


# Traceback (ValueError)
Traceback (most recent call last):
File "function.py", line 17, in <module>
g(np.arange(3.0))  # Crash!
File "/home/hylke/.local/lib/python3.8/site-packages/numpy/lib/function_base.py", line 2091, in __call__
return self._vectorize_call(func=func, args=vargs)
File "/home/hylke/.local/lib/python3.8/site-packages/numpy/lib/function_base.py", line 2167, in _vectorize_call
outputs = ufunc(*inputs)
ValueError: invalid number of arguments

# Fixed code
def __init__(
    self, pyfunc, otypes=None, doc=None, excluded=None, cache=False, signature=None
):
    self.pyfunc = pyfunc
    self.cache = cache
    self.signature = signature
    self._ufunc = {}  # Caching to improve default performance

    if doc is None:
        self.__doc__ = pyfunc.__doc__
    else:
        self.__doc__ = doc

    if isinstance(otypes, str):
        for char in otypes:
            if char not in typecodes["All"]:
                raise ValueError("Invalid otype specified: %s" % (char,))
    elif iterable(otypes):
        otypes = "".join([_nx.dtype(x).char for x in otypes])
    elif otypes is not None:
        raise ValueError("Invalid otype specification")
    self.otypes = otypes

    # Excluded variable support
    if excluded is None:
        excluded = set()
    self.excluded = set(excluded)

    if signature is not None:
        self._in_and_out_core_dims = _parse_gufunc_signature(signature)
    else:
        self._in_and_out_core_dims = None
# Buggy code
def _ctype_ndarray(element_type, shape):
    """Create an ndarray of the given element type and shape"""
    for dim in shape[::-1]:
        element_type = element_type * dim
    return element_type


# Traceback (KeyError)
KeyError                                  Traceback (most recent call last)
<ipython-input-3-e5712fdde6f3> in <module>()
----> 1 b = np.ctypeslib.as_ctypes(a)

/home/chug/.local/lib/python2.7/site-packages/numpy/ctypeslib.py in as_ctypes(obj)
419         if readonly:
420             raise TypeError("readonly arrays unsupported")
--> 421         tp = _typecodes[ai["typestr"]]
422         for dim in ai["shape"][::-1]:
423             tp = tp * dim

KeyError: '|b1'

# Fixed code
def _ctype_ndarray(element_type, shape):
    """Create an ndarray of the given element type and shape"""
    for dim in shape[::-1]:
        element_type = dim * element_type
        # prevent the type name include np.ctypeslib
        element_type.__module__ = None
    return element_type
# Buggy code
def as_ctypes(obj):
    """Create and return a ctypes object from a numpy array.  Actually
    anything that exposes the __array_interface__ is accepted."""
    ai = obj.__array_interface__
    if ai["strides"]:
        raise TypeError("strided arrays not supported")
    if ai["version"] != 3:
        raise TypeError("only __array_interface__ version 3 supported")
    addr, readonly = ai["data"]
    if readonly:
        raise TypeError("readonly arrays unsupported")
    tp = _ctype_ndarray(_typecodes[ai["typestr"]], ai["shape"])
    result = tp.from_address(addr)
    result.__keep = obj
    return result


# Traceback (KeyError)
KeyError                                  Traceback (most recent call last)
<ipython-input-3-e5712fdde6f3> in <module>()
----> 1 b = np.ctypeslib.as_ctypes(a)

/home/chug/.local/lib/python2.7/site-packages/numpy/ctypeslib.py in as_ctypes(obj)
419         if readonly:
420             raise TypeError("readonly arrays unsupported")
--> 421         tp = _typecodes[ai["typestr"]]
422         for dim in ai["shape"][::-1]:
423             tp = tp * dim

KeyError: '|b1'

# Fixed code
def as_ctypes(obj):
    """Create and return a ctypes object from a numpy array.  Actually
    anything that exposes the __array_interface__ is accepted."""
    ai = obj.__array_interface__
    if ai["strides"]:
        raise TypeError("strided arrays not supported")
    if ai["version"] != 3:
        raise TypeError("only __array_interface__ version 3 supported")
    addr, readonly = ai["data"]
    if readonly:
        raise TypeError("readonly arrays unsupported")

    dtype = _dtype((ai["typestr"], ai["shape"]))
    result = as_ctypes_type(dtype).from_address(addr)
    result.__keep = obj
    return result
# Buggy code
def decorator(implementation):
    # TODO: only do this check when the appropriate flag is enabled or for
    # a dev install. We want this check for testing but don't want to
    # slow down all numpy imports.
    if verify:
        verify_matching_signatures(implementation, dispatcher)

    @functools.wraps(implementation)
    def public_api(*args, **kwargs):
        relevant_args = dispatcher(*args, **kwargs)
        return array_function_implementation_or_override(
            implementation, public_api, relevant_args, args, kwargs
        )

    if module is not None:
        public_api.__module__ = module

    return public_api


# Traceback (TypeError)
In [1]: import numpy as np

In [2]: class Sub(np.ndarray):
...:     def __array_function__(*args, **kwargs):
...:         return NotImplemented
...:

In [3]: repr(np.array(1).view(Sub))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-d6ff958f4fcf> in <module>()
----> 1 repr(np.array(1).view(Sub))

~/dev/numpy/numpy/core/overrides.py in public_api(*args, **kwargs)
149             relevant_args = dispatcher(*args, **kwargs)
150             return array_function_implementation_or_override(
--> 151                 implementation, public_api, relevant_args, args, kwargs)
152         return public_api
153

~/dev/numpy/numpy/core/overrides.py in array_function_implementation_or_override(implementation, public_api, relevant_args, args, kwargs)
108     raise TypeError('no implementation found for {} on types that implement '
109                     '__array_function__: {}'
--> 110                     .format(public_api, list(map(type, overloaded_args))))
111
112

TypeError: no implementation found for <function array_repr at 0x105692e18> on types that implement __array_function__: [<class '__main__.Sub'>]

# Fixed code
def decorator(implementation):
    # TODO: only do this check when the appropriate flag is enabled or for
    # a dev install. We want this check for testing but don't want to
    # slow down all numpy imports.
    if verify:
        verify_matching_signatures(implementation, dispatcher)

    @functools.wraps(implementation)
    def public_api(*args, **kwargs):
        relevant_args = dispatcher(*args, **kwargs)
        return array_function_implementation_or_override(
            implementation, public_api, relevant_args, args, kwargs
        )

    if module is not None:
        public_api.__module__ = module

    # TODO: remove this when we drop Python 2 support (functools.wraps
    # adds __wrapped__ automatically in later versions)
    public_api.__wrapped__ = implementation

    return public_api
# Buggy code
def __init__(self, format_functions):
    self.format_functions = format_functions


# Traceback (TypeError)
import numpy as np
x = np.zeros(3, dtype=('i4',[('r','u1'), ('g','u1'), ('b','u1'), ('a','u1')]))
x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/tos/py3npy/lib/python3.6/site-packages/numpy-1.14.0.dev0+1f4ed32-py3.6-macosx-10.12-x86_64.egg/numpy/core/arrayprint.py", line 955, in array_repr
', ', class_name + "(")
File "/Users/tos/py3npy/lib/python3.6/site-packages/numpy-1.14.0.dev0+1f4ed32-py3.6-macosx-10.12-x86_64.egg/numpy/core/arrayprint.py", line 521, in array2string
lst = _array2string(a, options, separator, prefix)
File "/Users/tos/py3npy/lib/python3.6/site-packages/numpy-1.14.0.dev0+1f4ed32-py3.6-macosx-10.12-x86_64.egg/numpy/core/arrayprint.py", line 363, in wrapper
return f(self, *args, **kwargs)
File "/Users/tos/py3npy/lib/python3.6/site-packages/numpy-1.14.0.dev0+1f4ed32-py3.6-macosx-10.12-x86_64.egg/numpy/core/arrayprint.py", line 392, in _array2string
options['edgeitems'], summary_insert)[:-1]
File "/Users/tos/py3npy/lib/python3.6/site-packages/numpy-1.14.0.dev0+1f4ed32-py3.6-macosx-10.12-x86_64.egg/numpy/core/arrayprint.py", line 565, in _formatArray
word = format_function(a[-i]) + separator
File "/Users/tos/py3npy/lib/python3.6/site-packages/numpy-1.14.0.dev0+1f4ed32-py3.6-macosx-10.12-x86_64.egg/numpy/core/arrayprint.py", line 886, in __call__
for field, format_function in zip(x, self.format_functions):
TypeError: zip argument #1 must support iteration

# Fixed code
def __init__(self, *args, **kwargs):
    # NumPy 1.14, 2018-02-14
    warnings.warn(
        "StructureFormat has been replaced by StructuredVoidFormat",
        DeprecationWarning,
        stacklevel=2,
    )
    super(StructureFormat, self).__init__(*args, **kwargs)
# Buggy code
def _void_scalar_repr(x):
    """
    Implements the repr for structured-void scalars. It is called from the
    scalartypes.c.src code, and is placed here because it uses the elementwise
    formatters defined above.
    """
    return StructureFormat.from_data(array(x), **_format_options)(x)


# Traceback (TypeError)
import numpy as np
x = np.zeros(3, dtype=('i4',[('r','u1'), ('g','u1'), ('b','u1'), ('a','u1')]))
x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/tos/py3npy/lib/python3.6/site-packages/numpy-1.14.0.dev0+1f4ed32-py3.6-macosx-10.12-x86_64.egg/numpy/core/arrayprint.py", line 955, in array_repr
', ', class_name + "(")
File "/Users/tos/py3npy/lib/python3.6/site-packages/numpy-1.14.0.dev0+1f4ed32-py3.6-macosx-10.12-x86_64.egg/numpy/core/arrayprint.py", line 521, in array2string
lst = _array2string(a, options, separator, prefix)
File "/Users/tos/py3npy/lib/python3.6/site-packages/numpy-1.14.0.dev0+1f4ed32-py3.6-macosx-10.12-x86_64.egg/numpy/core/arrayprint.py", line 363, in wrapper
return f(self, *args, **kwargs)
File "/Users/tos/py3npy/lib/python3.6/site-packages/numpy-1.14.0.dev0+1f4ed32-py3.6-macosx-10.12-x86_64.egg/numpy/core/arrayprint.py", line 392, in _array2string
options['edgeitems'], summary_insert)[:-1]
File "/Users/tos/py3npy/lib/python3.6/site-packages/numpy-1.14.0.dev0+1f4ed32-py3.6-macosx-10.12-x86_64.egg/numpy/core/arrayprint.py", line 565, in _formatArray
word = format_function(a[-i]) + separator
File "/Users/tos/py3npy/lib/python3.6/site-packages/numpy-1.14.0.dev0+1f4ed32-py3.6-macosx-10.12-x86_64.egg/numpy/core/arrayprint.py", line 886, in __call__
for field, format_function in zip(x, self.format_functions):
TypeError: zip argument #1 must support iteration

# Fixed code
def _void_scalar_repr(x):
    """
    Implements the repr for structured-void scalars. It is called from the
    scalartypes.c.src code, and is placed here because it uses the elementwise
    formatters defined above.
    """
    return StructuredVoidFormat.from_data(array(x), **_format_options)(x)
# Buggy code
def from_data(cls, data, **options):
    """
    This is a second way to initialize StructureFormat, using the raw data
    as input. Added to avoid changing the signature of __init__.
    """
    format_functions = []
    for field_name in data.dtype.names:
        format_function = _get_format_function(data[field_name], **options)
        if data.dtype[field_name].shape != ():
            format_function = SubArrayFormat(format_function)
        format_functions.append(format_function)
    return cls(format_functions)


# Traceback (TypeError)
import numpy as np
x = np.zeros(3, dtype=('i4',[('r','u1'), ('g','u1'), ('b','u1'), ('a','u1')]))
x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/tos/py3npy/lib/python3.6/site-packages/numpy-1.14.0.dev0+1f4ed32-py3.6-macosx-10.12-x86_64.egg/numpy/core/arrayprint.py", line 955, in array_repr
', ', class_name + "(")
File "/Users/tos/py3npy/lib/python3.6/site-packages/numpy-1.14.0.dev0+1f4ed32-py3.6-macosx-10.12-x86_64.egg/numpy/core/arrayprint.py", line 521, in array2string
lst = _array2string(a, options, separator, prefix)
File "/Users/tos/py3npy/lib/python3.6/site-packages/numpy-1.14.0.dev0+1f4ed32-py3.6-macosx-10.12-x86_64.egg/numpy/core/arrayprint.py", line 363, in wrapper
return f(self, *args, **kwargs)
File "/Users/tos/py3npy/lib/python3.6/site-packages/numpy-1.14.0.dev0+1f4ed32-py3.6-macosx-10.12-x86_64.egg/numpy/core/arrayprint.py", line 392, in _array2string
options['edgeitems'], summary_insert)[:-1]
File "/Users/tos/py3npy/lib/python3.6/site-packages/numpy-1.14.0.dev0+1f4ed32-py3.6-macosx-10.12-x86_64.egg/numpy/core/arrayprint.py", line 565, in _formatArray
word = format_function(a[-i]) + separator
File "/Users/tos/py3npy/lib/python3.6/site-packages/numpy-1.14.0.dev0+1f4ed32-py3.6-macosx-10.12-x86_64.egg/numpy/core/arrayprint.py", line 886, in __call__
for field, format_function in zip(x, self.format_functions):
TypeError: zip argument #1 must support iteration

# Fixed code
def from_data(cls, data, **options):
    """
    This is a second way to initialize StructuredVoidFormat, using the raw data
    as input. Added to avoid changing the signature of __init__.
    """
    format_functions = []
    for field_name in data.dtype.names:
        format_function = _get_format_function(data[field_name], **options)
        if data.dtype[field_name].shape != ():
            format_function = SubArrayFormat(format_function)
        format_functions.append(format_function)
    return cls(format_functions)
# Buggy code
def __new__(self):
    return self._data.view(self)


# Traceback (AttributeError)
np.ma.masked.fill_value
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "numpy/ma/core.py", line 3353, in get_fill_value
if self._fill_value is None:
AttributeError: 'MaskedConstant' object has no attribute '_fill_value'

# Fixed code
def __new__(cls):
    if cls.__singleton is None:
        # We define the masked singleton as a float for higher precedence.
        # Note that it can be tricky sometimes w/ type comparison
        data = np.array(0.0)
        mask = np.array(True)

        # prevent any modifications
        data.flags.writeable = False
        mask.flags.writeable = False

        # don't fall back on MaskedArray.__new__(MaskedConstant), since
        # that might confuse it - this way, the construction is entirely
        # within our control
        cls.__singleton = MaskedArray(data, mask=mask).view(cls)

    return cls.__singleton
# Buggy code
def __array_finalize__(self, obj):
    return


# Traceback (AttributeError)
np.ma.masked.fill_value
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "numpy/ma/core.py", line 3353, in get_fill_value
if self._fill_value is None:
AttributeError: 'MaskedConstant' object has no attribute '_fill_value'

# Fixed code
def __array_finalize__(self, obj):
    if self.__singleton is None:
        # this handles the `.view` in __new__, which we want to copy across
        # properties normally
        return super(MaskedConstant, self).__array_finalize__(obj)
    elif self is self.__singleton:
        # not clear how this can happen, play it safe
        pass
    else:
        # everywhere else, we want to downcast to MaskedArray, to prevent a
        # duplicate maskedconstant.
        self.__class__ = MaskedArray
        MaskedArray.__array_finalize__(self, obj)
# Buggy code
def __repr__(self):
    return "masked"


# Traceback (AttributeError)
np.ma.masked.fill_value
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "numpy/ma/core.py", line 3353, in get_fill_value
if self._fill_value is None:
AttributeError: 'MaskedConstant' object has no attribute '_fill_value'

# Fixed code
def __repr__(self):
    if self is self.__singleton:
        return "masked"
    else:
        # it's a subclass, or something is wrong, make it obvious
        return object.__repr__(self)
# Buggy code
def __init__(self, axis=0, matrix=False, ndmin=1, trans1d=-1):
    self._axis = axis
    self._matrix = matrix
    self.axis = axis
    self.matrix = matrix
    self.col = 0
    self.trans1d = trans1d
    self.ndmin = ndmin


# Traceback (ValueError)
Traceback (most recent call last):
File "test.py", line 13, in <module>
print(numpy.r_[a, b.reshape((3, 3, 1))])
File "/usr/local/lib/python2.7/dist-packages/numpy/lib/index_tricks.py", line 338, in __getitem__
res = _nx.concatenate(tuple(objs), axis=self.axis)
ValueError: all the input array dimensions except for the concatenation axis must match exactly

# Fixed code
def __init__(self, axis=0, matrix=False, ndmin=1, trans1d=-1):
    self.axis = axis
    self.matrix = matrix
    self.trans1d = trans1d
    self.ndmin = ndmin
# Buggy code
def __getitem__(self, key):
    if isinstance(key, str):
        raise MAError("Unavailable for masked array.")
    if not isinstance(key, tuple):
        key = (key,)
    objs = []
    scalars = []
    final_dtypedescr = None
    for k in range(len(key)):
        scalar = False
        if isinstance(key[k], slice):
            step = key[k].step
            start = key[k].start
            stop = key[k].stop
            if start is None:
                start = 0
            if step is None:
                step = 1
            if isinstance(step, complex):
                size = int(abs(step))
                newobj = np.linspace(start, stop, num=size)
            else:
                newobj = np.arange(start, stop, step)
        elif isinstance(key[k], str):
            if key[k] in "rc":
                self.matrix = True
                self.col = key[k] == "c"
                continue
            try:
                self.axis = int(key[k])
                continue
            except (ValueError, TypeError):
                raise ValueError("Unknown special directive")
        elif type(key[k]) in np.ScalarType:
            newobj = asarray([key[k]])
            scalars.append(k)
            scalar = True
        else:
            newobj = key[k]
        objs.append(newobj)
        if isinstance(newobj, ndarray) and not scalar:
            if final_dtypedescr is None:
                final_dtypedescr = newobj.dtype
            elif newobj.dtype > final_dtypedescr:
                final_dtypedescr = newobj.dtype
    if final_dtypedescr is not None:
        for k in scalars:
            objs[k] = objs[k].astype(final_dtypedescr)
    res = concatenate(tuple(objs), axis=self.axis)
    return self._retval(res)


# Traceback (ValueError)
Traceback (most recent call last):
File "test.py", line 13, in <module>
print(numpy.r_[a, b.reshape((3, 3, 1))])
File "/usr/local/lib/python2.7/dist-packages/numpy/lib/index_tricks.py", line 338, in __getitem__
res = _nx.concatenate(tuple(objs), axis=self.axis)
ValueError: all the input array dimensions except for the concatenation axis must match exactly

# Fixed code
def __getitem__(self, key):
    # matrix builder syntax, like 'a, b; c, d'
    if isinstance(key, str):
        raise MAError("Unavailable for masked array.")

    return super(MAxisConcatenator, self).__getitem__(key)
# Buggy code
def roots(p):
    """
    Return the roots of a polynomial with coefficients given in p.

    The values in the rank-1 array `p` are coefficients of a polynomial.
    If the length of `p` is n+1 then the polynomial is described by::

      p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*x + p[n]

    Parameters
    ----------
    p : array_like
        Rank-1 array of polynomial coefficients.

    Returns
    -------
    out : ndarray
        An array containing the roots of the polynomial.

    Raises
    ------
    ValueError
        When `p` cannot be converted to a rank-1 array.

    See also
    --------
    poly : Find the coefficients of a polynomial with a given sequence
           of roots.
    polyval : Compute polynomial values.
    polyfit : Least squares polynomial fit.
    poly1d : A one-dimensional polynomial class.

    Notes
    -----
    The algorithm relies on computing the eigenvalues of the
    companion matrix [1]_.

    References
    ----------
    .. [1] R. A. Horn & C. R. Johnson, *Matrix Analysis*.  Cambridge, UK:
        Cambridge University Press, 1999, pp. 146-7.

    Examples
    --------
    >>> coeff = [3.2, 2, 1]
    >>> np.roots(coeff)
    array([-0.3125+0.46351241j, -0.3125-0.46351241j])

    """
    # If input is scalar, this makes it an array
    p = atleast_1d(p)
    if p.ndim != 1:
        raise ValueError("Input must be a rank-1 array.")

    # find non-zero array entries
    non_zero = NX.nonzero(NX.ravel(p))[0]

    # Return an empty array if polynomial is all zeros
    if len(non_zero) == 0:
        return NX.array([])

    # find the number of trailing zeros -- this is the number of roots at 0.
    trailing_zeros = len(p) - non_zero[-1] - 1

    # strip leading and trailing zeros
    p = p[int(non_zero[0]) : int(non_zero[-1]) + 1]

    # casting: if incoming array isn't floating point, make it floating point.
    if not issubclass(p.dtype.type, (NX.floating, NX.complexfloating)):
        p = p.astype(float)

    N = len(p)
    if N > 1:
        # build companion matrix and find its eigenvalues (the roots)
        A = diag(NX.ones((N - 2,), p.dtype), -1)
        A[0, :] = -p[1:] / p[0]
        roots = eigvals(A)
    else:
        roots = NX.array([])

    # tack any zeros onto the back of the array
    roots = hstack((roots, NX.zeros(trailing_zeros, roots.dtype)))
    return roots


# Traceback (AttributeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/python3.5/inspect.py", line 2987, in signature
return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
File "/python3.5/inspect.py", line 2737, in from_callable
follow_wrapper_chains=follow_wrapped)
File "/python3.5/inspect.py", line 2228, in _signature_from_callable
if _signature_is_builtin(obj):
File "/python3.5/inspect.py", line 1785, in _signature_is_builtin
obj in (type, object))
File "/python3.5/site-packages/numpy/lib/polynomial.py", line 1203, in __eq__
if self.coeffs.shape != other.coeffs.shape:
AttributeError: type object 'type' has no attribute 'coeffs'

# Fixed code
def roots(self):
    """The roots of the polynomial, where self(x) == 0"""
    return roots(self._coeffs)
# Buggy code
def __init__(self, c_or_r, r=0, variable=None):
    if isinstance(c_or_r, poly1d):
        for key in c_or_r.__dict__.keys():
            self.__dict__[key] = c_or_r.__dict__[key]
        if variable is not None:
            self.__dict__["variable"] = variable
        return
    if r:
        c_or_r = poly(c_or_r)
    c_or_r = atleast_1d(c_or_r)
    if c_or_r.ndim > 1:
        raise ValueError("Polynomial must be 1d only.")
    c_or_r = trim_zeros(c_or_r, trim="f")
    if len(c_or_r) == 0:
        c_or_r = NX.array([0.0])
    self.__dict__["coeffs"] = c_or_r
    self.__dict__["order"] = len(c_or_r) - 1
    if variable is None:
        variable = "x"
    self.__dict__["variable"] = variable


# Traceback (AttributeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/python3.5/inspect.py", line 2987, in signature
return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
File "/python3.5/inspect.py", line 2737, in from_callable
follow_wrapper_chains=follow_wrapped)
File "/python3.5/inspect.py", line 2228, in _signature_from_callable
if _signature_is_builtin(obj):
File "/python3.5/inspect.py", line 1785, in _signature_is_builtin
obj in (type, object))
File "/python3.5/site-packages/numpy/lib/polynomial.py", line 1203, in __eq__
if self.coeffs.shape != other.coeffs.shape:
AttributeError: type object 'type' has no attribute 'coeffs'

# Fixed code
def __init__(self, c_or_r, r=False, variable=None):
    if isinstance(c_or_r, poly1d):
        self._variable = c_or_r._variable
        self._coeffs = c_or_r._coeffs

        if set(c_or_r.__dict__) - set(self.__dict__):
            msg = (
                "In the future extra properties will not be copied "
                "across when constructing one poly1d from another"
            )
            warnings.warn(msg, FutureWarning, stacklevel=2)
            self.__dict__.update(c_or_r.__dict__)

        if variable is not None:
            self._variable = variable
        return
    if r:
        c_or_r = poly(c_or_r)
    c_or_r = atleast_1d(c_or_r)
    if c_or_r.ndim > 1:
        raise ValueError("Polynomial must be 1d only.")
    c_or_r = trim_zeros(c_or_r, trim="f")
    if len(c_or_r) == 0:
        c_or_r = NX.array([0.0])
    self._coeffs = c_or_r
    if variable is None:
        variable = "x"
    self._variable = variable
# Buggy code
def __eq__(self, other):
    if self.coeffs.shape != other.coeffs.shape:
        return False
    return (self.coeffs == other.coeffs).all()


# Traceback (AttributeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/python3.5/inspect.py", line 2987, in signature
return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
File "/python3.5/inspect.py", line 2737, in from_callable
follow_wrapper_chains=follow_wrapped)
File "/python3.5/inspect.py", line 2228, in _signature_from_callable
if _signature_is_builtin(obj):
File "/python3.5/inspect.py", line 1785, in _signature_is_builtin
obj in (type, object))
File "/python3.5/site-packages/numpy/lib/polynomial.py", line 1203, in __eq__
if self.coeffs.shape != other.coeffs.shape:
AttributeError: type object 'type' has no attribute 'coeffs'

# Fixed code
def __eq__(self, other):
    if not isinstance(other, poly1d):
        return NotImplemented
    if self.coeffs.shape != other.coeffs.shape:
        return False
    return (self.coeffs == other.coeffs).all()
# Buggy code
def __ne__(self, other):
    return not self.__eq__(other)


# Traceback (AttributeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/python3.5/inspect.py", line 2987, in signature
return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
File "/python3.5/inspect.py", line 2737, in from_callable
follow_wrapper_chains=follow_wrapped)
File "/python3.5/inspect.py", line 2228, in _signature_from_callable
if _signature_is_builtin(obj):
File "/python3.5/inspect.py", line 1785, in _signature_is_builtin
obj in (type, object))
File "/python3.5/site-packages/numpy/lib/polynomial.py", line 1203, in __eq__
if self.coeffs.shape != other.coeffs.shape:
AttributeError: type object 'type' has no attribute 'coeffs'

# Fixed code
def __ne__(self, other):
    if not isinstance(other, poly1d):
        return NotImplemented
    return not self.__eq__(other)
# Buggy code
def __setitem__(self, key, val):
    ind = self.order - key
    if key < 0:
        raise ValueError("Does not support negative powers.")
    if key > self.order:
        zr = NX.zeros(key - self.order, self.coeffs.dtype)
        self.__dict__["coeffs"] = NX.concatenate((zr, self.coeffs))
        self.__dict__["order"] = key
        ind = 0
    self.__dict__["coeffs"][ind] = val
    return


# Traceback (AttributeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/python3.5/inspect.py", line 2987, in signature
return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
File "/python3.5/inspect.py", line 2737, in from_callable
follow_wrapper_chains=follow_wrapped)
File "/python3.5/inspect.py", line 2228, in _signature_from_callable
if _signature_is_builtin(obj):
File "/python3.5/inspect.py", line 1785, in _signature_is_builtin
obj in (type, object))
File "/python3.5/site-packages/numpy/lib/polynomial.py", line 1203, in __eq__
if self.coeffs.shape != other.coeffs.shape:
AttributeError: type object 'type' has no attribute 'coeffs'

# Fixed code
def __setitem__(self, key, val):
    ind = self.order - key
    if key < 0:
        raise ValueError("Does not support negative powers.")
    if key > self.order:
        zr = NX.zeros(key - self.order, self.coeffs.dtype)
        self._coeffs = NX.concatenate((zr, self.coeffs))
        ind = 0
    self._coeffs[ind] = val
    return
# Buggy code
def __call__(self, a, *args, **params):
    if self.reversed:
        args = list(args)
        arr = args[0]
        args[0] = a
        a = arr
    # Get the method from the array (if possible)
    method_name = self.__name__
    method = getattr(a, method_name, None)
    if method is not None:
        return method(*args, **params)
    # Still here ? Then a is not a MaskedArray
    method = getattr(MaskedArray, method_name, None)
    if method is not None:
        return method(MaskedArray(a), *args, **params)
    # Still here ? OK, let's call the corresponding np function
    method = getattr(np, method_name)
    return method(a, *args, **params)


# Traceback (TypeError)
np.ma.copy([1,2,3])  # unexpected behaviour
[1, 2, 3]

np.copy([1,2,3])  # expected behaviour
array([1, 2, 3])

np.ma.count([1,2,3])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Programming\Anaconda\envs\test\lib\site-packages\numpy\ma\core.py", line 6389, in __call__
return method(*args, **params)
TypeError: count() takes exactly one argument (0 given)

# Fixed code
def __call__(self, a, *args, **params):
    if self.reversed:
        args = list(args)
        a, args[0] = args[0], a

    marr = asanyarray(a)
    method_name = self.__name__
    method = getattr(type(marr), method_name, None)
    if method is None:
        # use the corresponding np function
        method = getattr(np, method_name)

    return method(marr, *args, **params)
# Buggy code
def asanyarray(a, dtype=None):
    """
    Convert the input to a masked array, conserving subclasses.

    If `a` is a subclass of `MaskedArray`, its class is conserved.
    No copy is performed if the input is already an `ndarray`.

    Parameters
    ----------
    a : array_like
        Input data, in any form that can be converted to an array.
    dtype : dtype, optional
        By default, the data-type is inferred from the input data.
    order : {'C', 'F'}, optional
        Whether to use row-major ('C') or column-major ('FORTRAN') memory
        representation.  Default is 'C'.

    Returns
    -------
    out : MaskedArray
        MaskedArray interpretation of `a`.

    See Also
    --------
    asarray : Similar to `asanyarray`, but does not conserve subclass.

    Examples
    --------
    >>> x = np.arange(10.).reshape(2, 5)
    >>> x
    array([[ 0.,  1.,  2.,  3.,  4.],
           [ 5.,  6.,  7.,  8.,  9.]])
    >>> np.ma.asanyarray(x)
    masked_array(data =
     [[ 0.  1.  2.  3.  4.]
     [ 5.  6.  7.  8.  9.]],
                 mask =
     False,
           fill_value = 1e+20)
    >>> type(np.ma.asanyarray(x))
    <class 'numpy.ma.core.MaskedArray'>

    """
    return masked_array(a, dtype=dtype, copy=False, keep_mask=True, subok=True)


# Traceback (TypeError)
np.ma.copy([1,2,3])  # unexpected behaviour
[1, 2, 3]

np.copy([1,2,3])  # expected behaviour
array([1, 2, 3])

np.ma.count([1,2,3])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Programming\Anaconda\envs\test\lib\site-packages\numpy\ma\core.py", line 6389, in __call__
return method(*args, **params)
TypeError: count() takes exactly one argument (0 given)

# Fixed code
def asanyarray(a, dtype=None):
    """
    Convert the input to a masked array, conserving subclasses.

    If `a` is a subclass of `MaskedArray`, its class is conserved.
    No copy is performed if the input is already an `ndarray`.

    Parameters
    ----------
    a : array_like
        Input data, in any form that can be converted to an array.
    dtype : dtype, optional
        By default, the data-type is inferred from the input data.
    order : {'C', 'F'}, optional
        Whether to use row-major ('C') or column-major ('FORTRAN') memory
        representation.  Default is 'C'.

    Returns
    -------
    out : MaskedArray
        MaskedArray interpretation of `a`.

    See Also
    --------
    asarray : Similar to `asanyarray`, but does not conserve subclass.

    Examples
    --------
    >>> x = np.arange(10.).reshape(2, 5)
    >>> x
    array([[ 0.,  1.,  2.,  3.,  4.],
           [ 5.,  6.,  7.,  8.,  9.]])
    >>> np.ma.asanyarray(x)
    masked_array(data =
     [[ 0.  1.  2.  3.  4.]
     [ 5.  6.  7.  8.  9.]],
                 mask =
     False,
           fill_value = 1e+20)
    >>> type(np.ma.asanyarray(x))
    <class 'numpy.ma.core.MaskedArray'>

    """
    # workaround for #8666, to preserve identity. Ideally the bottom line
    # would handle this for us.
    if isinstance(a, MaskedArray) and (dtype is None or dtype == a.dtype):
        return a
    return masked_array(a, dtype=dtype, copy=False, keep_mask=True, subok=True)
# Buggy code
def clean_up_temporary_directory():
    for d in _tmpdirs:
        try:
            shutil.rmtree(d)
        except OSError:
            pass


# Traceback (TypeError)
Error in atexit._run_exitfuncs:
Traceback (most recent call last):
File "/usr/lib/python2.7/atexit.py", line 24, in _run_exitfuncs
func(*targs, **kargs)
File "/usr/lib/python2.7/dist-packages/numpy/distutils/misc_util.py", line 27, in clean_up_temporary_directory
for d in _tmpdirs:
TypeError: 'NoneType' object is not iterable
Error in atexit._run_exitfuncs:
Traceback (most recent call last):
File "/usr/lib/python2.7/atexit.py", line 24, in _run_exitfuncs
func(*targs, **kargs)
File "/usr/lib/python2.7/dist-packages/numpy/distutils/misc_util.py", line 27, in clean_up_temporary_directory
for d in _tmpdirs:
TypeError: 'NoneType' object is not iterable
Error in atexit._run_exitfuncs:
Traceback (most recent call last):
File "/usr/lib/python2.7/atexit.py", line 24, in _run_exitfuncs
func(*targs, **kargs)
File "/usr/lib/python2.7/dist-packages/numpy/distutils/misc_util.py", line 27, in clean_up_temporary_directory
for d in _tmpdirs:
TypeError: 'NoneType' object is not iterable
Error in sys.exitfunc:
Traceback (most recent call last):
File "/usr/lib/python2.7/atexit.py", line 24, in _run_exitfuncs
func(*targs, **kargs)
File "/usr/lib/python2.7/dist-packages/numpy/distutils/misc_util.py", line 27, in clean_up_temporary_directory
for d in _tmpdirs:
TypeError: 'NoneType' object is not iterable

# Fixed code
def clean_up_temporary_directory():
    if _tmpdirs is not None:
        for d in _tmpdirs:
            try:
                shutil.rmtree(d)
            except OSError:
                pass
# Buggy code
def __getitem__(self, indx):
    """
    Get the index.

    """
    m = self._mask
    if m is not nomask and m[indx]:
        return masked
    return self._data[indx]


# Traceback (ValueError)
In [17]: numpy.version.version
Out[17]: '1.11.0.dev0+e711c95'

In [18]: A = ma.masked_array(data=[([0,1,2],), ([3,4,5],)], mask=[([True, False, False],), ([False, True, False],)], dtype=[("A", ">i2", (3,))])

In [19]: x = A[0]

In [20]: y = x["A"]
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-20-795ad5dbbe43> in <module>()
----> 1 y = x["A"]

/home/users/gholl/venv/stable-3.5/lib/python3.5/site-packages/numpy/ma/core.py in __getitem__(self, indx)
5851         """
5852         m = self._mask
-> 5853         if m is not nomask and m[indx]:
5854             return masked
5855         return self._data[indx]

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

# Fixed code
def __getitem__(self, indx):
    """
    Get the index.

    """
    m = self._mask
    if isinstance(m[indx], ndarray):
        # Can happen when indx is a multi-dimensional field:
        # A = ma.masked_array(data=[([0,1],)], mask=[([True,
        #                     False],)], dtype=[("A", ">i2", (2,))])
        # x = A[0]; y = x["A"]; then y.mask["A"].size==2
        # and we can not say masked/unmasked.
        # The result is no longer mvoid!
        # See also issue #6724.
        return masked_array(
            data=self._data[indx],
            mask=m[indx],
            fill_value=self._fill_value[indx],
            hard_mask=self._hardmask,
        )
    if m is not nomask and m[indx]:
        return masked
    return self._data[indx]
# Buggy code
def __add__(self, other):
    if isinstance(other, ABCPolyBase):
        if not self.has_sametype(other):
            raise TypeError("Polynomial types differ")
        elif not self.has_samedomain(other):
            raise TypeError("Domains differ")
        elif not self.has_samewindow(other):
            raise TypeError("Windows differ")
        else:
            coef = self._add(self.coef, other.coef)
    else:
        try:
            coef = self._add(self.coef, other)
        except:
            return NotImplemented
    return self.__class__(coef, self.domain, self.window)


# Traceback (UnboundLocalError)
In [1]: import numpy.polynomial.polynomial as npp

In [2]: p1 = npp.Polynomial([1,2])

In [3]: p2 = npp.Polynomial([3,4])

In [4]: npp.polydiv(p1, p2)
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-4-00c25f56fb20> in <module>()
----> 1 npp.polydiv(p1, p2)

/Users/warren/anaconda/lib/python2.7/site-packages/numpy/polynomial/polynomial.pyc in polydiv(c1, c2)
406     len2 = len(c2)
407     if len2 == 1 :
--> 408         return c1/c2[-1], c1[:1]*0
409     elif len1 < len2 :
410         return c1[:1]*0, c1

/Users/warren/anaconda/lib/python2.7/site-packages/numpy/polynomial/polynomial.pyc in __rtruediv__(self, other)

UnboundLocalError: local variable 'quo' referenced before assignment

# Fixed code
def __add__(self, other):
    try:
        othercoef = self._get_coefficients(other)
        coef = self._add(self.coef, othercoef)
    except TypeError as e:
        raise e
    except:
        return NotImplemented
    return self.__class__(coef, self.domain, self.window)
# Buggy code
def __sub__(self, other):
    if isinstance(other, ABCPolyBase):
        if not self.has_sametype(other):
            raise TypeError("Polynomial types differ")
        elif not self.has_samedomain(other):
            raise TypeError("Domains differ")
        elif not self.has_samewindow(other):
            raise TypeError("Windows differ")
        else:
            coef = self._sub(self.coef, other.coef)
    else:
        try:
            coef = self._sub(self.coef, other)
        except:
            return NotImplemented
    return self.__class__(coef, self.domain, self.window)


# Traceback (UnboundLocalError)
In [1]: import numpy.polynomial.polynomial as npp

In [2]: p1 = npp.Polynomial([1,2])

In [3]: p2 = npp.Polynomial([3,4])

In [4]: npp.polydiv(p1, p2)
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-4-00c25f56fb20> in <module>()
----> 1 npp.polydiv(p1, p2)

/Users/warren/anaconda/lib/python2.7/site-packages/numpy/polynomial/polynomial.pyc in polydiv(c1, c2)
406     len2 = len(c2)
407     if len2 == 1 :
--> 408         return c1/c2[-1], c1[:1]*0
409     elif len1 < len2 :
410         return c1[:1]*0, c1

/Users/warren/anaconda/lib/python2.7/site-packages/numpy/polynomial/polynomial.pyc in __rtruediv__(self, other)

UnboundLocalError: local variable 'quo' referenced before assignment

# Fixed code
def __sub__(self, other):
    try:
        othercoef = self._get_coefficients(other)
        coef = self._sub(self.coef, othercoef)
    except TypeError as e:
        raise e
    except:
        return NotImplemented
    return self.__class__(coef, self.domain, self.window)
# Buggy code
def __mul__(self, other):
    if isinstance(other, ABCPolyBase):
        if not self.has_sametype(other):
            raise TypeError("Polynomial types differ")
        elif not self.has_samedomain(other):
            raise TypeError("Domains differ")
        elif not self.has_samewindow(other):
            raise TypeError("Windows differ")
        else:
            coef = self._mul(self.coef, other.coef)
    else:
        try:
            coef = self._mul(self.coef, other)
        except:
            return NotImplemented
    return self.__class__(coef, self.domain, self.window)


# Traceback (UnboundLocalError)
In [1]: import numpy.polynomial.polynomial as npp

In [2]: p1 = npp.Polynomial([1,2])

In [3]: p2 = npp.Polynomial([3,4])

In [4]: npp.polydiv(p1, p2)
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-4-00c25f56fb20> in <module>()
----> 1 npp.polydiv(p1, p2)

/Users/warren/anaconda/lib/python2.7/site-packages/numpy/polynomial/polynomial.pyc in polydiv(c1, c2)
406     len2 = len(c2)
407     if len2 == 1 :
--> 408         return c1/c2[-1], c1[:1]*0
409     elif len1 < len2 :
410         return c1[:1]*0, c1

/Users/warren/anaconda/lib/python2.7/site-packages/numpy/polynomial/polynomial.pyc in __rtruediv__(self, other)

UnboundLocalError: local variable 'quo' referenced before assignment

# Fixed code
def __mul__(self, other):
    try:
        othercoef = self._get_coefficients(other)
        coef = self._mul(self.coef, othercoef)
    except TypeError as e:
        raise e
    except:
        return NotImplemented
    return self.__class__(coef, self.domain, self.window)