Method decorator for 'generator type' methods
970334
def _ha_gen_method(func):
        '''  '''
        def wrapped(self, *args, **kw):
            self._reset_retries()
            while(True): # switch between all namenodes
                try:
                    results = func(self, *args, **kw)
                    while(True): # yield all results
                        yield results.next()
                except RequestError as e:
                    self.__handle_request_error(e)
                except socket.error as e:
                    self.__handle_socket_error(e)
        return wrapped
1332641
def generator_family(cls):
		
		if cls.__generator_family__ is not None:
			if isinstance(cls.__generator_family__, str) is False:
				raise TypeError('"__generator_class__"  if defined must be a str instance')

		if cls.__generator_family__ is not None:
			return cls.__generator_family__.upper()
988976
def generator_to_list(fn):
    
    def wrapper(*args, **kw):
        return list(fn(*args, **kw))
    return wrapper
1307451
def return_self_updater(func):
    '''
    
    '''
    @functools.wraps(func)
    def decorator(k,v):
        func(k,v)
        return v
    return decorator
934485
def check_types(func):
    
    call = PythonCall(func)

    @wraps(func)
    def decorator(*args, **kwargs):
        parameters = call.bind(args, kwargs)
        for arg_name, expected_type in func.__annotations__.items():
            if not isinstance(parameters[arg_name], expected_type):
                raise TypeError("{} must be a {}".format(
                    arg_name, expected_type))
        return call.apply(args, kwargs)
    return decorator
621657
def syncify(*types):
    
    # Our asynchronous generators all are `RequestIter`, which already
    # provide a synchronous iterator variant, so we don't need to worry
    # about asyncgenfunction's here.
    for t in types:
        for name in dir(t):
            if not name.startswith('_') or name == '__call__':
                if inspect.iscoroutinefunction(getattr(t, name)):
                    _syncify_wrap(t, name)
75582
def isgenerator(obj):
    '''  '''
    return isinstance(obj, GeneratorType) or (hasattr(obj, 'iterable') and
           isinstance(getattr(obj, 'iterable'), GeneratorType))
890231
def optional_arg_class_decorator(fn):
    
    @functools.wraps(fn)
    def wrapped_decorator(*args, **kwargs):
        if len(args) == 1 and isinstance(args[0], type) and not kwargs:
            return fn(args[0])
        else:
            def real_decorator(decoratee):
                return fn(decoratee, *args, **kwargs)
            return real_decorator
    return wrapped_decorator
888703
def dict_of(**kwargs):
    

    class DictOfKeyGenerators(ArbitraryInterface):
        """
        A closure class around the keys and generators specified above, which
        generates a dict of the keys and generators.
        """

        @classmethod
        def arbitrary(cls):
            """
            Generate a dict of the enclosed keys and generators.
            """
            return {
                key: arbitrary(generator)
                for key, generator in kwargs.iteritems()
            }

    DictOfKeyGenerators.__name__ = ''.join([
        'dict_of(', ', '.join([
            key + '=' + generator.__name__
            for key, generator in kwargs.iteritems()
        ]), ')'
    ])
    return DictOfKeyGenerators
624367
def for_all(*generators):
    
    # Pass in n as an argument
    n = 100

    def test_property(property_function):
        """
        A closure which takes a property and tests it against arbitrary
        instances of the generators in the closure.
        """
        for generator in generators:
            assert (issubclass(generator, ArbitraryInterface)
                    or generator in arbitrary)

        def test_once():
            """
            Tests the property against a single set of instances of the
            generators.
            """
            instances = [arbitrary(generator) for generator in generators]
            try:
                assert property_function(*instances)
            except AssertionError:
                generator_names = ', '.join(
                    generator.__name__ for generator in generators)
                stringed_instances = ', '.join(
                    str(instance) for instance in instances)
                error_message = ' '.join([
                    'Instances <', stringed_instances, '> of <',
                    generator_names, '> do not satisfy a property.'
                ])
                raise AssertionError(error_message)

        for _ in range(n):
            test_once()

    return test_property
449087
def decorate(decorator_cls, *args, **kwargs):
    """"""
    global _wrappers

    wrapper_cls = _wrappers.get(decorator_cls, None)
    if wrapper_cls is None:

        class PythonWrapper(decorator_cls):
            pass

        wrapper_cls = PythonWrapper
        wrapper_cls.__name__ = decorator_cls.__name__ + "PythonWrapper"
        _wrappers[decorator_cls] = wrapper_cls

    def decorator(fn):
        wrapped = wrapper_cls(fn, *args, **kwargs)
        _update_wrapper(wrapped, fn)
        return wrapped

    return decorator
245555
def decorator(caller, _func=None):
    """"""
    if _func is not None:  # return a decorated function
        # this is obsolete behavior; you should use decorate instead
        return decorate(_func, caller)
    # else return a decorator function
    if inspect.isclass(caller):
        name = caller.__name__.lower()
        callerfunc = get_init(caller)
        doc = 'decorator(%s) converts functions/generators into ' \
            'factories of %s objects' % (caller.__name__, caller.__name__)
        fun = getfullargspec(callerfunc).args[1]  # second arg
    elif inspect.isfunction(caller):
        if caller.__name__ == '<lambda>':
            name = '_lambda_'
        else:
            name = caller.__name__
        callerfunc = caller
        doc = caller.__doc__
        fun = getfullargspec(callerfunc).args[0]  # first arg
    else:  # assume caller is an object with a __call__ method
        name = caller.__class__.__name__.lower()
        callerfunc = caller.__call__.__func__
        doc = caller.__call__.__doc__
        fun = getfullargspec(callerfunc).args[1]  # second arg
    evaldict = callerfunc.__globals__.copy()
    evaldict['_call_'] = caller
    evaldict['_decorate_'] = decorate
    return FunctionMaker.create(
        '%s(%s)' % (name, fun),
        'return _decorate_(%s, _call_)' % fun,
        evaldict, call=caller, doc=doc, module=caller.__module__,
        __wrapped__=caller)
604434
def decorate_method(cls, func):
        
        func_args = [arg for arg in function_arguments(func) if arg != 'self']
        method_return_types = \
            Endpoint._parse_function_return_types_from_doc(func.__doc__)
        name = '%s.%s' % (cls.path, func.__name__)

        @wraps(func)
        def method_decorator(self, *args, **kwargs):
            for i in range(len(args)):
                kwargs[func_args[i]] = args[i]

            api_call = self.connection._pre_process_call(
                name, endpoint_params=kwargs)
            try:
                data = func(**kwargs)
            except RestException as e:
                api_call.error = e
                raise e

            except Exception as e:
                call_queue = self.connection._call_queue.get(
                    self.connection._get_thread_id(), [])
                if api_call in call_queue:
                    call_queue.remove(api_call)
                e = RestException(original_error=e,
                                  stack=traceback.format_exc())
                log.error('ApiCall Exception: %s' % e, exc_info=True)
                raise e
            return self.connection._post_process_call(
                api_call, data, method_return_types)

        method_decorator.rest_method = True
        return method_decorator
706272
def gen_orm_classes_from_base(base: Type) -> Generator[Type, None, None]:
    
    for cls in gen_all_subclasses(base):
        if _get_immediate_cls_attr(cls, '__abstract__', strict=True):
            # This is SQLAlchemy's own way of detecting abstract classes; see
            # sqlalchemy.ext.declarative.base
            continue  # NOT an ORM class
        yield cls
542963
def _method_is_async_generator(self, method):
        
        if hasattr(method, "func"):
            func = method.func
        else:
            func = method

        return getattr(func, "_is_coroutine", False)
414234
def dual_use_decorator(fn):
    """"""
    @functools.wraps(fn)
    def decorator(*args, **kw):
        if len(args) == 1 and not kw and callable(args[0]):
            return fn()(args[0])
        else:
            return fn(*args, **kw)
    return decorator
954601
def coll_to_tuples(cls, coll):
        
        if isinstance(coll, basestring):
            raise exc.CollectionCoerceError(
                passed=coll,
                colltype=cls,
            )
        if isinstance(coll, collections.Mapping):
            i = 0
            for k in sorted(coll.keys()):
                yield (i, coll[k])
        elif isinstance(coll, (collections.Sequence, types.GeneratorType)) or (
            hasattr(coll, "next") and callable(coll.next)
        ) or (
            hasattr(coll, "__iter__") and callable(coll.__iter__)
        ):
            i = 0
            for v in coll:
                yield i, v
                i += 1
        elif not coll:
            return
        else:
            raise exc.CollectionCoerceError(
                passed=coll,
                colltype=cls,
            )