Calls ``func(*args, **kwargs)``; if it raises an exception, break into
    the ``pdb`` debugger.
420007
def pdb_run(func: Callable, *args: Any, **kwargs: Any) -> None:
    
    # noinspection PyBroadException
    try:
        func(*args, **kwargs)
    except:  # nopep8
        type_, value, tb = sys.exc_info()
        traceback.print_exc()
        pdb.post_mortem(tb)
406833
def inside_try(func, options={}):
    
    if six.PY2:
        name = func.func_name
    else:
        name = func.__name__

    @wraps(func)
    def silenceit(*args, **kwargs):
        """ the function func to be silenced is wrapped inside a
        try catch and returned, exceptions are logged
        exceptions are returned in an error dict
        takes all kinds of arguments and passes to the original func
        """
        excpt = None
        try:
            return func(*args, **kwargs)
        # pylint: disable=W0703
        # inside_try.silenceit: Catching too general exception Exception
        # that's the idea!
        except Exception as excpt:
            # first tell the object in charge
            if 'ctx' in kwargs:
                ctx = kwargs['ctx']
            else:
                # otherwise tell object defined in options
                # if we can be sure there is a context
                ctx = get_try_option(None, 'ctx')

            if not ctx:
                # tell a new object
                ctx = Bubble('Inside Try')
                # ctx.set_verbose(100); #todo: move to magic

            head = name + ': silenced function inside_try:Error:'
            if get_try_option(ctx, 'count_it'):
                ctx.gbc.cry(head + 'counting')
            if get_try_option(ctx, 'print_it'):
                ctx.gbc.cry(head + 'printing:' + str(excpt))
            if get_try_option(ctx, 'print_args'):
                ctx.gbc.cry(head + 'printing ak:' + str(excpt))
                ctx.gbc.cry('args', stuff=args)
                ctx.gbc.cry('kwargs', stuff=kwargs)
            if get_try_option(ctx, 'inspect_it'):
                ctx.gbc.cry(head + 'inspecting:', stuff=excpt)
                for s in inspect.stack():
                    ctx.gbc.cry(head + ':stack:', stuff=s)
            if get_try_option(ctx, 'log_it'):
                ctx.gbc.cry(head + 'logging')
                for s in inspect.stack():
                    ctx.gbc.cry(head + ':stack:', stuff=s)
            if get_try_option(ctx, 'reraise_it'):
                ctx.gbc.cry(head + 'reraising')
                raise excpt
            # always return error
            return {'error': str(excpt),
                    'silenced': name,
                    'args': args,
                    'kwargs': kwargs}
    return silenceit
1136482
def throws(exc):
    '''
    
    '''
    if not __CHECKING__:
        return lambda f: f

    def wrap(f):
        def call(*args, **kwd):
            res = f(*args, **kwd)
            # raise UncheckedExceptionError if exc is not automatically
            # registered by a function decorated with @catches(exc);
            # otherwise do nothing
            exc_checker.throwing(exc)
            return res
        call.__name__ = f.__name__
        return call
    return wrap
97541
def raise_if(self, exception, message, *args, **kwargs):
        
        if issubclass(exception, self.minimum_defect):
            raise exception(*args, **kwargs)
        warn(message, SyntaxWarning, *args, **kwargs)
482417
def _catch(f, exception_type):
  """"""
  if not (inspect.isclass(exception_type)
          and issubclass(exception_type, Exception)):
    exception_type = Exception

  @functools.wraps(f)
  def wrap(*args, **kw):
    try:
      return f(*args, **kw)
    except exception_type as e:  # pylint: disable=broad-except
      qj(e, 'Caught an exception in %s' % f, d=1, _depth=2)
  return wrap
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))
337674
def clean_fail(func):
    '''
    
    '''
    def func_wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except botocore.exceptions.ClientError as e:
            print(str(e), file=sys.stderr)
            sys.exit(1)
    return func_wrapper
404788
def safecall(func):
    """"""
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception:
            pass
    return wrapper
1356865
def callable_check(func, arg_count=1, arg_value=None, allow_none=False):
        """"""
        if func is None:
            if not allow_none:
                raise ValueError('callable cannot be None')
        elif not arg_checker(func, *[arg_value for _ in range(arg_count)]):
            raise ValueError('callable %s invalid (for %d arguments)' % (func, arg_count))
749867
def throws_errors(func):
    
    @wraps(func)
    def wrapper(*args, **kwargs):
        response = func(*args, **kwargs)

        # if no status code is provided, assume 400
        if isinstance(response, BugZooException):
            err_jsn = flask.jsonify(response.to_dict())
            return err_jsn, 400

        if isinstance(response, tuple) \
           and isinstance(response[0], BugZooException):
            err = response[0] # type: BugZooException
            err_jsn = flask.jsonify(err.to_dict())
            return (err_jsn, *response[1:])

        return response

    return wrapper
1316452
def log_exception(func, handler, args, kwargs):
    
    # safe-guard: expected arguments -> log_exception(self, typ, value, tb)
    value = args[1] if len(args) == 3 else None
    if value is None:
        return func(*args, **kwargs)

    tracing = handler.settings.get('opentracing_tracing')
    if not isinstance(value, HTTPError) or 500 <= value.status_code <= 599:
        tracing._finish_tracing(handler, error=value)

    return func(*args, **kwargs)
766719
def on_exception_report_input(func_=None, force=False, keys=None):
    
    def _closure_onexceptreport(func):
        if not ONEX_REPORT_INPUT and not force:
            return func
        @ignores_exc_tb(outer_wrapper=False)
        #@wraps(func)
        def wrp_onexceptreport(*args, **kwargs):
            try:
                #import utool
                #if utool.DEBUG:
                #    print('[IN EXCPRPT] args=%r' % (args,))
                #    print('[IN EXCPRPT] kwargs=%r' % (kwargs,))
                return func(*args, **kwargs)
            except Exception as ex:
                from utool import util_str
                print('ERROR occured! Reporting input to function')
                if keys is not None:
                    from utool import util_inspect
                    from utool import util_list
                    from utool import util_dict
                    argspec = util_inspect.get_func_argspec(func)
                    in_kwargs_flags = [key in kwargs for key in keys]
                    kwarg_keys = util_list.compress(keys, in_kwargs_flags)
                    kwarg_vals = [kwargs.get(key) for key in kwarg_keys]
                    flags = util_list.not_list(in_kwargs_flags)
                    arg_keys = util_list.compress(keys, flags)
                    arg_idxs = [argspec.args.index(key) for key in arg_keys]
                    num_nodefault = len(argspec.args) - len(argspec.defaults)
                    default_vals = (([None] * (num_nodefault)) +
                                    list(argspec.defaults))
                    args_ = list(args) + default_vals[len(args) + 1:]
                    arg_vals = util_list.take(args_, arg_idxs)
                    requested_dict = dict(util_list.flatten(
                        [zip(kwarg_keys, kwarg_vals), zip(arg_keys, arg_vals)]))
                    print('input dict = ' + util_str.repr4(
                        util_dict.dict_subset(requested_dict, keys)))
                    # (print out specific keys only)
                    pass
                arg_strs = ', '.join([repr(util_str.truncate_str(str(arg)))
                                      for arg in args])
                kwarg_strs = ', '.join([
                    util_str.truncate_str('%s=%r' % (key, val))
                    for key, val in six.iteritems(kwargs)])
                msg = ('\nERROR: funcname=%r,\n * args=%s,\n * kwargs=%r\n' % (
                    meta_util_six.get_funcname(func), arg_strs, kwarg_strs))
                msg += ' * len(args) = %r\n' % len(args)
                msg += ' * len(kwargs) = %r\n' % len(kwargs)
                util_dbg.printex(ex, msg, pad_stdout=True)
                raise
        wrp_onexceptreport = preserve_sig(wrp_onexceptreport, func)
        return wrp_onexceptreport
    if func_ is None:
        return _closure_onexceptreport
    else:
        return _closure_onexceptreport(func_)
62749
def wrap_rethink_errors(func_, *args, **kwargs):
    
    try:
        return func_(*args, **kwargs)
    except WRAP_RETHINK_ERRORS as reql_err:
        raise ValueError(str(reql_err))
1061214
def ExceptionHookPDB(exctype, value, tb):
    '''
    

    '''

    for line in traceback.format_exception_only(exctype, value):
        log.error(line.replace('\n', ''))
    for line in traceback.format_tb(tb):
        log.error(line.replace('\n', ''))
    sys.__excepthook__(exctype, value, tb)
    pdb.pm()
1231930
def call(self, func, *args, **kwargs):
        
        guessed_kwargs = self._guess_kwargs(func)
        for key, val in guessed_kwargs.items():
            kwargs.setdefault(key, val)
        try:
            return func(*args, **kwargs)
        except TypeError as exc:
            msg = (
                "tried calling function %r but failed, probably "
                "because it takes arguments that cannot be resolved"
            ) % func
            raise DiayException(msg) from exc
764845
def on_call(self, node):
        """"""
        #  ('func', 'args', 'keywords'. Py<3.5 has 'starargs' and 'kwargs' too)
        func = self.run(node.func)
        if not hasattr(func, '__call__') and not isinstance(func, type):
            msg = "'%s' is not callable!!" % (func)
            self.raise_exception(node, exc=TypeError, msg=msg)

        args = [self.run(targ) for targ in node.args]
        starargs = getattr(node, 'starargs', None)
        if starargs is not None:
            args = args + self.run(starargs)

        keywords = {}
        if six.PY3 and func == print:
            keywords['file'] = self.writer

        for key in node.keywords:
            if not isinstance(key, ast.keyword):
                msg = "keyword error in function call '%s'" % (func)
                self.raise_exception(node, msg=msg)
            keywords[key.arg] = self.run(key.value)

        kwargs = getattr(node, 'kwargs', None)
        if kwargs is not None:
            keywords.update(self.run(kwargs))

        try:
            return func(*args, **keywords)
        except Exception as ex:
            self.raise_exception(
                node, msg="Error running function call '%s' with args %s and "
                "kwargs %s: %s" % (func.__name__, args, keywords, ex))
991878
def _call_function(name, returner=None, **kwargs):
    '''
    
    '''
    argspec = salt.utils.args.get_function_argspec(__salt__[name])

    # func_kw is initialized to a dictionary of keyword arguments the function to be run accepts
    func_kw = dict(zip(argspec.args[-len(argspec.defaults or []):],  # pylint: disable=incompatible-py3-code
                   argspec.defaults or []))

    # func_args is initialized to a list of positional arguments that the function to be run accepts
    func_args = argspec.args[:len(argspec.args or []) - len(argspec.defaults or [])]
    arg_type, kw_to_arg_type, na_type, kw_type = [], {}, {}, False
    for funcset in reversed(kwargs.get('func_args') or []):
        if not isinstance(funcset, dict):
            # We are just receiving a list of args to the function to be run, so just append
            # those to the arg list that we will pass to the func.
            arg_type.append(funcset)
        else:
            for kwarg_key in six.iterkeys(funcset):
                # We are going to pass in a keyword argument. The trick here is to make certain
                # that if we find that in the *args* list that we pass it there and not as a kwarg
                if kwarg_key in func_args:
                    kw_to_arg_type[kwarg_key] = funcset[kwarg_key]
                    continue
                else:
                    # Otherwise, we're good and just go ahead and pass the keyword/value pair into
                    # the kwargs list to be run.
                    func_kw.update(funcset)
    arg_type.reverse()
    for arg in func_args:
        if arg in kw_to_arg_type:
            arg_type.append(kw_to_arg_type[arg])
    _exp_prm = len(argspec.args or []) - len(argspec.defaults or [])
    _passed_prm = len(arg_type)
    missing = []
    if na_type and _exp_prm > _passed_prm:
        for arg in argspec.args:
            if arg not in func_kw:
                missing.append(arg)
    if missing:
        raise SaltInvocationError('Missing arguments: {0}'.format(', '.join(missing)))
    elif _exp_prm > _passed_prm:
        raise SaltInvocationError('Function expects {0} parameters, got only {1}'.format(
            _exp_prm, _passed_prm))

    mret = __salt__[name](*arg_type, **func_kw)
    if returner is not None:
        returners = salt.loader.returners(__opts__, __salt__)
        if returner in returners:
            returners[returner]({'id': __opts__['id'], 'ret': mret,
                                 'fun': name, 'jid': salt.utils.jid.gen_jid(__opts__)})

    return mret