A wrapper function that converts numpy ndarray arguments to cupy
    arrays, and convert any cupy arrays returned by the wrapped
    function into numpy ndarrays.
426287
def cupy_wrapper(func):
    

    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        args = list(args)
        for n, a in enumerate(args):
            if isinstance(a, np.ndarray):
                args[n] = cp.asarray(a)
        for k, v in kwargs.items():
            if isinstance(v, np.ndarray):
                kwargs[k] = cp.asarray(v)
        rtn = func(*args, **kwargs)
        if isinstance(rtn, (list, tuple)):
            for n, a in enumerate(rtn):
                if isinstance(a, cp.core.core.ndarray):
                    rtn[n] = cp.asnumpy(a)
        else:
            if isinstance(rtn, cp.core.core.ndarray):
                rtn = cp.asnumpy(rtn)
        return rtn
    return wrapped
324620
def _make_ndarray_function(handle, name, func_name):
    """"""
    code, doc_str = _generate_ndarray_function_code(handle, name, func_name)

    local = {}
    exec(code, None, local)  # pylint: disable=exec-used
    ndarray_function = local[func_name]
    ndarray_function.__name__ = func_name
    ndarray_function.__doc__ = doc_str
    ndarray_function.__module__ = 'mxnet.ndarray'
    return ndarray_function
817755
def arraylike_to_numpy(array_like):
    """"""

    orig_type = type(array_like)

    # Convert to np.ndarray
    if isinstance(array_like, np.ndarray):
        pass
    elif isinstance(array_like, list):
        array_like = np.array(array_like)
    elif issparse(array_like):
        array_like = array_like.toarray()
    elif isinstance(array_like, torch.Tensor):
        array_like = array_like.numpy()
    elif not isinstance(array_like, np.ndarray):
        array_like = np.array(array_like)
    else:
        msg = f"Input of type {orig_type} could not be converted to 1d " "np.ndarray"
        raise ValueError(msg)

    # Correct shape
    if (array_like.ndim > 1) and (1 in array_like.shape):
        array_like = array_like.flatten()
    if array_like.ndim != 1:
        raise ValueError("Input could not be converted to 1d np.array")

    # Convert to ints
    if any(array_like % 1):
        raise ValueError("Input contains at least one non-integer value.")
    array_like = array_like.astype(np.dtype(int))

    return array_like
1291001
def to_float(*args):
    
    floats = [np.array(a, dtype=np.float32) for a in args]
    return floats[0] if len(floats) == 1 else floats
201860
def _to_numpy(nd4j_array):
    
    buff = nd4j_array.data()
    address = buff.pointer().address()
    dtype = get_context_dtype()
    mapping = {
        'double': ctypes.c_double,
        'float': ctypes.c_float
    }
    Pointer = ctypes.POINTER(mapping[dtype])
    pointer = ctypes.cast(address, Pointer)
    np_array = np.ctypeslib.as_array(pointer, tuple(nd4j_array.shape()))
    return np_array
182905
def _coerce_to_ndarray(cls, data):
        

        if not isinstance(data, (np.ndarray, Index)):
            if data is None or is_scalar(data):
                cls._scalar_data_error(data)

            # other iterable of some kind
            if not isinstance(data, (ABCSeries, list, tuple)):
                data = list(data)
            data = np.asarray(data)
        return data
877853
def torecarray(*args, **kwargs):
    

    import numpy as np
    return toarray(*args, **kwargs).view(np.recarray)
1186195
def to_arrays(data, columns, coerce_float=False, dtype=None):
    
    if isinstance(data, ABCDataFrame):
        if columns is not None:
            arrays = [data._ixs(i, axis=1).values
                      for i, col in enumerate(data.columns) if col in columns]
        else:
            columns = data.columns
            arrays = [data._ixs(i, axis=1).values for i in range(len(columns))]

        return arrays, columns

    if not len(data):
        if isinstance(data, np.ndarray):
            columns = data.dtype.names
            if columns is not None:
                return [[]] * len(columns), columns
        return [], []  # columns if columns is not None else []
    if isinstance(data[0], (list, tuple)):
        return _list_to_arrays(data, columns, coerce_float=coerce_float,
                               dtype=dtype)
    elif isinstance(data[0], abc.Mapping):
        return _list_of_dict_to_arrays(data, columns,
                                       coerce_float=coerce_float, dtype=dtype)
    elif isinstance(data[0], ABCSeries):
        return _list_of_series_to_arrays(data, columns,
                                         coerce_float=coerce_float,
                                         dtype=dtype)
    elif isinstance(data[0], Categorical):
        if columns is None:
            columns = ibase.default_index(len(data))
        return data, columns
    elif (isinstance(data, (np.ndarray, ABCSeries, Index)) and
          data.dtype.names is not None):

        columns = list(data.dtype.names)
        arrays = [data[k] for k in columns]
        return arrays, columns
    else:
        # last ditch effort
        data = lmap(tuple, data)
        return _list_to_arrays(data, columns, coerce_float=coerce_float,
                               dtype=dtype)
35092
def _parse_array(self, tensor_proto):
        """"""
        try:
            from onnx.numpy_helper import to_array
        except ImportError:
            raise ImportError("Onnx and protobuf need to be installed. "
                              + "Instructions to install - https://github.com/onnx/onnx")
        if len(tuple(tensor_proto.dims)) > 0:
            np_array = to_array(tensor_proto).reshape(tuple(tensor_proto.dims))
        else:
            # If onnx's params are scalar values without dims mentioned.
            np_array = np.array([to_array(tensor_proto)])
        return nd.array(np_array)
232081
def npy_to_numpy(npy_array):  # type: (object) -> np.array
    
    stream = BytesIO(npy_array)
    return np.load(stream, allow_pickle=True)
1240965
def _prepare_src_array(source_array, dtype):
    
    if not isinstance(source_array, NDArray) and not isinstance(source_array, np.ndarray):
        try:
            source_array = np.array(source_array, dtype=dtype)
        except:
            raise TypeError('values must be array like object')
    return source_array
774858
def fromNumpy(cls, data):
        
        assert np is not None
        if isinstance(data, np.ndarray):
            index = []
            if len(data.shape) == 1:
                columns = [('value', data.tolist())]
            elif len(data.shape) == 2:
                columns = [
                    ('c{}'.format(i), col)
                    for i, col in enumerate(zip(*data.tolist()))
                ]
            else:
                raise TypeError
        else:
            raise TypeError
        return cls(index=index, columns=columns)
942246
def _array_star(args):
    
    fn, cls, genelist, kwargs = args
    return _array(fn, cls, genelist, **kwargs)
506021
def decode_numpy_dict_values(attrs: Mapping[K, V]) -> Dict[K, V]:
    
    attrs = dict(attrs)
    for k, v in attrs.items():
        if isinstance(v, np.ndarray):
            attrs[k] = v.tolist()
        elif isinstance(v, np.generic):
            attrs[k] = v.item()
    return attrs
659344
def p_array_type(self, p):
        ''''''
        if len(p) == 2:
            p[0] = p[1][0],
        elif len(p) == 5 and p[4] == ']':
            def args(t):
                return t.__args__ if isinstance(t, NDArray) else (t,)
            p[0] = tuple(NDArray[args(t) + p[3]] for t in p[1])
561577
def array(a, dtype:type=None, **kwargs)->np.ndarray:
    ""
    if not isinstance(a, collections.Sized) and not getattr(a,'__array_interface__',False):
        a = list(a)
    if np.int_==np.int32 and dtype is None and is_listy(a) and len(a) and isinstance(a[0],int):
        dtype=np.int64
    return np.array(a, dtype=dtype, **kwargs)
1116256
def vectorize(fn):
    

    @functools.wraps(fn)
    def vectorized_method(self, values, *vargs, **kwargs):
        wrap = not isinstance(values, (list, tuple))
        should_unwrap = not kwargs.setdefault('wrap', False)
        unwrap = wrap and should_unwrap
        del kwargs['wrap']
        
        if wrap:
            values = [values]

        results = [fn(self, value, *vargs, **kwargs) for value in values]

        if unwrap:
            results = results[0]

        return results

    return vectorized_method