Given a free-standing function 'callable', return a new
        callable that will call 'callable' and report all exceptins,
        using 'call_and_report_errors'.
5678
def make_wrapper(self, callable_):
        """"""
        assert callable(callable_)
        def wrapper(*args, **kw):
            return self.call_and_report_errors(callable_, *args, **kw)
        return wrapper
932094
def print_errors(function):
    """"""

    def wrapper(*args, **kwargs):
        try:
            return function(*args, **kwargs)
        except BaseException as e:
            print ("Exception raise calling %s: %s"
                   % (reflect.canonical_name(function),
                      get_exception_message(e)))
            raise

    return wrapper
1054026
def build(self, callable: Callable) -> Callable[..., CaptureResult]:
        
        def capturing_callable(*args, **kwargs) -> CaptureResult:
            return CaptureResult(return_value=callable(*args, **kwargs))

        if self.capture_exceptions:
            # Need to capture exceptions first else other (non-return) captured information will be lost
            exceptions_wrapper = CaptureWrapBuilder._create_capture_exceptions(self.capture_exceptions)
            capturing_callable = CaptureWrapBuilder._wrap(capturing_callable, exceptions_wrapper)
        if self.capture_stdout:
            capturing_callable = CaptureWrapBuilder._wrap(capturing_callable, CaptureWrapBuilder._capture_stdout)
        if self.capture_stderr:
            capturing_callable = CaptureWrapBuilder._wrap(capturing_callable, CaptureWrapBuilder._capture_stderr)

        return capturing_callable
1238741
def decorate_with_checker(func: CallableT) -> CallableT:
    """"""
    assert not hasattr(func, "__preconditions__"), \
        "Expected func to have no list of preconditions (there should be only a single contract checker per function)."

    assert not hasattr(func, "__postconditions__"), \
        "Expected func to have no list of postconditions (there should be only a single contract checker per function)."

    assert not hasattr(func, "__postcondition_snapshots__"), \
        "Expected func to have no list of postcondition snapshots (there should be only a single contract checker " \
        "per function)."

    sign = inspect.signature(func)
    param_names = list(sign.parameters.keys())

    # Determine the default argument values.
    kwdefaults = dict()  # type: Dict[str, Any]

    # Add to the defaults all the values that are needed by the contracts.
    for param in sign.parameters.values():
        if param.default != inspect.Parameter.empty:
            kwdefaults[param.name] = param.default

    def wrapper(*args, **kwargs):
        """Wrap func by checking the preconditions and postconditions."""
        preconditions = getattr(wrapper, "__preconditions__")  # type: List[List[Contract]]
        snapshots = getattr(wrapper, "__postcondition_snapshots__")  # type: List[Snapshot]
        postconditions = getattr(wrapper, "__postconditions__")  # type: List[Contract]

        resolved_kwargs = _kwargs_from_call(param_names=param_names, kwdefaults=kwdefaults, args=args, kwargs=kwargs)

        if postconditions:
            if 'result' in resolved_kwargs:
                raise TypeError("Unexpected argument 'result' in a function decorated with postconditions.")

            if 'OLD' in resolved_kwargs:
                raise TypeError("Unexpected argument 'OLD' in a function decorated with postconditions.")

        # Assert the preconditions in groups. This is necessary to implement "require else" logic when a class
        # weakens the preconditions of its base class.
        violation_err = None  # type: Optional[ViolationError]
        for group in preconditions:
            violation_err = None
            try:
                for contract in group:
                    _assert_precondition(contract=contract, resolved_kwargs=resolved_kwargs)
                break
            except ViolationError as err:
                violation_err = err

        if violation_err is not None:
            raise violation_err  # pylint: disable=raising-bad-type

        # Capture the snapshots
        if postconditions:
            old_as_mapping = dict()  # type: MutableMapping[str, Any]
            for snap in snapshots:
                # This assert is just a last defense.
                # Conflicting snapshot names should have been caught before, either during the decoration or
                # in the meta-class.
                assert snap.name not in old_as_mapping, "Snapshots with the conflicting name: {}"
                old_as_mapping[snap.name] = _capture_snapshot(a_snapshot=snap, resolved_kwargs=resolved_kwargs)

            resolved_kwargs['OLD'] = _Old(mapping=old_as_mapping)

        # Execute the wrapped function
        result = func(*args, **kwargs)

        if postconditions:
            resolved_kwargs['result'] = result

            # Assert the postconditions as a conjunction
            for contract in postconditions:
                _assert_postcondition(contract=contract, resolved_kwargs=resolved_kwargs)

        return result  # type: ignore

    # Copy __doc__ and other properties so that doctests can run
    functools.update_wrapper(wrapper=wrapper, wrapped=func)

    assert not hasattr(wrapper, "__preconditions__"), "Expected no preconditions set on a pristine contract checker."
    assert not hasattr(wrapper, "__postcondition_snapshots__"), \
        "Expected no postcondition snapshots set on a pristine contract checker."
    assert not hasattr(wrapper, "__postconditions__"), "Expected no postconditions set on a pristine contract checker."

    # Precondition is a list of condition groups (i.e. disjunctive normal form):
    # each group consists of AND'ed preconditions, while the groups are OR'ed.
    #
    # This is necessary in order to implement "require else" logic when a class weakens the preconditions of
    # its base class.
    setattr(wrapper, "__preconditions__", [])
    setattr(wrapper, "__postcondition_snapshots__", [])
    setattr(wrapper, "__postconditions__", [])

    return wrapper
1270498
def _maybe_add_callable(data, out):
    
    callable_bed = dd.get_sample_callable(data)
    if callable_bed:
        out.append({"path": callable_bed, "type": "bed", "ext": "callable"})
    perbase_bed = tz.get_in(["depth", "variant_regions", "per_base"], data)
    if perbase_bed:
        out.append({"path": perbase_bed, "type": "bed.gz", "ext": "depth-per-base"})
    return out
368595
def _start_callables(self, row, callables):
        
        id_vals = {c: row[c] for c in self.ids}

        def callback(tab, cols, result):
            if isinstance(result, Mapping):
                pass
            elif isinstance(result, tuple):
                result = dict(zip(cols, result))
            elif len(cols) == 1:
                # Don't bother raising an exception if cols != 1
                # because it would be lost in the thread.
                result = {cols[0]: result}
            result.update(id_vals)
            tab._write(result)

        if self._pool is None:
            self._pool = Pool()
        if self._lock is None:
            self._lock = multiprocessing.Lock()

        for cols, fn in callables:
            cb_func = partial(callback, self, cols)

            gen = None
            if inspect.isgeneratorfunction(fn):
                gen = fn()
            elif inspect.isgenerator(fn):
                gen = fn

            if gen:
                def callback_for_each():
                    for i in gen:
                        cb_func(i)
                self._pool.apply_async(callback_for_each)
            else:
                self._pool.apply_async(fn, callback=cb_func)
1065674
private function createErrorHandler()
    {
        /**
         * @param int $errno
         * @param string $errstr
         * @param string $errfile
         * @param int $errline
         * @return void
         * @throws \ErrorException if error is not within the error_reporting mask.
         */
        return function ($errno, $errstr, $errfile, $errline) {
            if (! (error_reporting() & $errno)) {
                // error_reporting does not include this error
                return;
            }

            throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
        };
    }
3177
def copy_func(func: Callable) -> Callable:
    
    copied = types.FunctionType(
        func.__code__, func.__globals__, name=func.__name__,
        argdefs=func.__defaults__, closure=func.__closure__)
    copied = functools.update_wrapper(copied, func)
    copied.__kwdefaults__ = func.__kwdefaults__
    return copied
1193079
public static <T> Callable<T> recover(Callable<T> callable, Function<Exception, T> exceptionHandler){
        return () -> {
            try{
                return callable.call();
            }catch (Exception exception){
                return exceptionHandler.apply(exception);
            }
        };
    }
1223560
def errors_handler(self, *custom_filters, exception=None, run_task=None, **kwargs):
        

        def decorator(callback):
            self.register_errors_handler(self._wrap_async_task(callback, run_task),
                                         *custom_filters, exception=exception, **kwargs)
            return callback

        return decorator
602172
def expose_request(func):
    
    if not python.callable(func):
        raise TypeError("func must be callable")

    if isinstance(func, types.UnboundMethodType):
        setattr(func.im_func, '_pyamf_expose_request', True)
    else:
        setattr(func, '_pyamf_expose_request', True)

    return func
1178487
function onFailure(/*callable*/$callable)
    {
        if ($callable === false)
        {
            // Disable On Failure Handler
            //
            $this->_onFailure = $callable;
            return $this;
        }


        if (! is_callable($callable) )
            throw new \Exception(sprintf(
                'The argument given is not callable; given: (%s).'
                , \Poirot\Std\flatten($callable)
            ));


        ## bind it into latest bind object
        #
        // DO_LEAST_PHPVER_SUPPORT 5.4 closure bindto
        if ($callable instanceof \Closure && version_compare(phpversion(), '5.4.0') > 0) {
            $callable = \Closure::bind(
                $callable
                , $this
                , get_class($this)
            );
        }

        $this->_onFailure = $callable;
        return $this;
    }
776454
public static <V> Try<V> tryCall(Callable<V> callable) {
        try {
            return Try.succeeded(callable.call());
        } catch (Exception e) {
            return Try.failed(e);
        }
    }
404137
protected static <U> U checkedCall(Callable<U> callable) {
        try {
            return callable.call();
        } catch (Throwable ex) {
            if (ex instanceof RuntimeException) {
                throw (RuntimeException)ex;
            }
            if (ex instanceof Error) {
                throw (Error)ex;
            }
            throw new RuntimeException(ex);
        }
    }
327358
def uncurry(f):
    
    ensure_callable(f)

    result = lambda args=(), kwargs=None: f(*args, **(kwargs or {}))
    functools.update_wrapper(result, f, ('__name__', '__module__'))
    return result
157173
def callgraph(func):
    ''' 
    '''
    import pycallgraph
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        pycallgraph.start_trace()
        func(*args, **kwargs)
        pycallgraph.save_dot('callgraph.log')
        pycallgraph.make_dot_graph('callgraph.png')
        #pycallgraph.make_dot_graph('callgraph.jpg', format='jpg', tool='neato')
    return wrapper
1186320
def runcall(self, func, *args, **kw):
        
        # XXX where is this used ? can be removed ?
        self.enable_by_count()
        try:
            return func(*args, **kw)
        finally:
            self.disable_by_count()