Create a NDArray function from the FunctionHandle.
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
92129
function makeFunctionWrapper(original, functionName) {
  //log("wrap fn: " + functionName);
  var f = original[functionName];
  return function() {
    //log("call: " + functionName);
    var result = f.apply(original, arguments);
    return result;
  };
}
140737
def python(self, func, *args, **kwargs):
        """"""
        self.ops.append(lambda: func(*args, **kwargs))
1346542
def from_array(cls, arr):
        """"""
        return cls().with_columns([(f, arr[f]) for f in arr.dtype.names])
133298
def _function_handler(function, args, kwargs, future):
    """"""
    future.set_running_or_notify_cancel()

    try:
        result = function(*args, **kwargs)
    except BaseException as error:
        error.traceback = format_exc()
        future.set_exception(error)
    else:
        future.set_result(result)
1270865
def function_parser(function, parser):
    """"""

    # Store the function pointer on the parser for later use
    parser.set_defaults(func=function)

    # Get the help text and parse it for params
    help_text = inspect.getdoc(function)
    main_text, params_help = parser_help_text(help_text)

    # Get the function information
    args, varargs, keywords, defaults = inspect.getargspec(function)
    if args is None:
        args = []

    if defaults is None:
        defaults = []

    # If the function is a class method, it will have a self that needs to be removed
    if len(args) and args[0] == 'self':
        args.pop(0)

    # Work out whether the argument has a default by subtracting the length
    # of the default args from the number of arguments
    num_required_args = len(args) - len(defaults)
    for idx, arg in enumerate(args):
        if idx < num_required_args:
            arg_name, arg_params = calculate_default_type(arg, False, None, params_help)
        else:
            default_value = defaults[idx - num_required_args]
            arg_name, arg_params = calculate_default_type(arg, True, default_value, params_help)

        parser.add_argument(arg_name, **arg_params)
1065233
def c_array(ctype, values):
    """"""
    if isinstance(values, np.ndarray) and values.dtype.itemsize == ctypes.sizeof(ctype):
        return (ctype * len(values)).from_buffer_copy(values)
    return (ctype * len(values))(*values)
702819
def _new_alloc_handle(shape, ctx, delay_alloc, dtype=mx_real_t):
    
    hdl = NDArrayHandle()
    check_call(_LIB.MXNDArrayCreateEx(
        c_array_buf(mx_uint, native_array('I', shape)),
        mx_uint(len(shape)),
        ctypes.c_int(ctx.device_typeid),
        ctypes.c_int(ctx.device_id),
        ctypes.c_int(int(delay_alloc)),
        ctypes.c_int(int(_DTYPE_NP_TO_MX[np.dtype(dtype).type])),
        ctypes.byref(hdl)))
    return hdl
1125500
def func(nargs: Optional[int] = None, nouts: Optional[int] = None, ndefs: Optional[int] = None):
    
    return lambda f: wraps(f)(WrappedFunction(f, nargs=nargs, nouts=nouts, ndefs=ndefs))
1108758
def ufunc_functional_factory(name, nargin, nargout, docstring):
    """"""

    assert 0 <= nargin <= 2

    def __init__(self, field):
        """Initialize an instance.

        Parameters
        ----------
        field : `Field`
            The domain of the functional.
        """
        if not isinstance(field, Field):
            raise TypeError('`field` {!r} not a `Field`'.format(space))

        if _is_integer_only_ufunc(name):
            raise ValueError("ufunc '{}' only defined with integral dtype"
                             "".format(name))

        linear = name in LINEAR_UFUNCS
        Functional.__init__(self, space=field, linear=linear)

    def _call(self, x):
        """Return ``self(x)``."""
        if nargin == 1:
            return getattr(np, name)(x)
        else:
            return getattr(np, name)(*x)

    def __repr__(self):
        """Return ``repr(self)``."""
        return '{}({!r})'.format(name, self.domain)

    # Create example (also functions as doctest)

    if nargin != 1:
        raise NotImplementedError('Currently not suppored')

    if nargout != 1:
        raise NotImplementedError('Currently not suppored')

    space = RealNumbers()
    val = 1.0
    arg = '{}'.format(val)
    with np.errstate(all='ignore'):
        result = np.float64(getattr(np, name)(val))

    examples_docstring = RAW_EXAMPLES_DOCSTRING.format(space=space, name=name,
                                                       arg=arg, result=result)
    full_docstring = docstring + examples_docstring

    attributes = {"__init__": __init__,
                  "_call": _call,
                  "gradient": property(gradient_factory(name)),
                  "__repr__": __repr__,
                  "__doc__": full_docstring}

    full_name = name + '_op'

    return type(full_name, (Functional,), attributes)
135447
def preprocess_xarray(func):
    
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        args = tuple(a.metpy.unit_array if isinstance(a, xr.DataArray) else a for a in args)
        kwargs = {name: (v.metpy.unit_array if isinstance(v, xr.DataArray) else v)
                  for name, v in kwargs.items()}
        return func(*args, **kwargs)
    return wrapper
1132282
def execute_function(self, func, *nargs, **kwargs):
        
        # makes a copy of the func
        import types
        fn = types.FunctionType(func.func_code,
                                func.func_globals.copy(),
                                name=func.func_name,
                                argdefs=func.func_defaults,
                                closure=func.func_closure)
        fn.func_globals.update(self.globals)

        error_class = Exception if config.catch_rex_errors else None

        try:
            return fn(*nargs, **kwargs)
        except RexError:
            raise
        except error_class as e:
            from inspect import getfile

            stack = traceback.format_exc()
            filename = getfile(func)

            raise RexError("Failed to exec %s:\n\n%s" % (filename, stack))
1260933
def create_method(self, func):
    """"""
    # pylint: disable=missing-docstring
    @functools.wraps(func)
    def method(input_layer, *args, **kwargs):
      return func(input_layer, *args, **self.fill_kwargs(input_layer, kwargs))

    return method
942811
def _call(self, func, out=None, **kwargs):
        """"""
        mesh = self.grid.meshgrid
        if out is None:
            out = func(mesh, **kwargs)
        else:
            with writable_array(out) as out_arr:
                func(mesh, out=out_arr, **kwargs)
        return out
541977
def arg_to_array(func):
    
    def fn(self, arg, *args, **kwargs):
        """Function

        Parameters
        ----------
        arg : array-like
            Argument to convert.
        *args : tuple
            Arguments.
        **kwargs : dict
            Keyword arguments.

        Returns
        -------
        value : object
            The return value of the function.
        """
        return func(self, np.array(arg), *args, **kwargs)
    return fn
840889
def __init_from_np2d(self, mat, params_str, ref_dataset):
        """"""
        if len(mat.shape) != 2:
            raise ValueError('Input numpy.ndarray must be 2 dimensional')

        self.handle = ctypes.c_void_p()
        if mat.dtype == np.float32 or mat.dtype == np.float64:
            data = np.array(mat.reshape(mat.size), dtype=mat.dtype, copy=False)
        else:
            # change non-float data to float data, need to copy
            data = np.array(mat.reshape(mat.size), dtype=np.float32)

        ptr_data, type_ptr_data, _ = c_float_array(data)
        _safe_call(_LIB.LGBM_DatasetCreateFromMat(
            ptr_data,
            ctypes.c_int(type_ptr_data),
            ctypes.c_int(mat.shape[0]),
            ctypes.c_int(mat.shape[1]),
            ctypes.c_int(C_API_IS_ROW_MAJOR),
            c_str(params_str),
            ref_dataset,
            ctypes.byref(self.handle)))
        return self
99721
def _createFuture(func, *args, **kwargs):
    """"""
    assert callable(func), (
        "The provided func parameter is not a callable."
    )

    if scoop.IS_ORIGIN and "SCOOP_WORKER" not in sys.modules:
        sys.modules["SCOOP_WORKER"] = sys.modules["__main__"]

    # If function is a lambda or class method, share it (or its parent object)
    # beforehand
    lambdaType = type(lambda: None)
    funcIsLambda = isinstance(func, lambdaType) and func.__name__ == '<lambda>'
    # Determine if function is a method. Methods derived from external
    # languages such as C++ aren't detected by ismethod.
    funcIsMethod = ismethod(func)
    if funcIsLambda or funcIsMethod:
        from .shared import SharedElementEncapsulation
        func = SharedElementEncapsulation(func)

    return Future(control.current.id, func, *args, **kwargs)