Read connection args spec, exclude self from list of possible

        :param klass: Redis connection class.
516543
def _build_connection_args(self, klass):
        
        bases = [base for base in klass.__bases__ if base is not object]
        all_args = []
        for cls in [klass] + bases:
            try:
                args = inspect.getfullargspec(cls.__init__).args
            except AttributeError:
                args = inspect.getargspec(cls.__init__).args
            for arg in args:
                if arg in all_args:
                    continue
                all_args.append(arg)
        all_args.remove('self')
        return all_args
1364968
def get_class_alias(klass):
    
    for k, v in pyamf.ALIAS_TYPES.iteritems():
        for kl in v:
            try:
                if issubclass(klass, kl):
                    return k
            except TypeError:
                # not a class
                if hasattr(kl, '__call__'):
                    if kl(klass) is True:
                        return k
1321506
def get_class_meta(klass):
    
    if not isinstance(klass, python.class_types) or klass is object:
        raise TypeError('klass must be a class object, got %r' % type(klass))

    meta = {
        'static_attrs': None,
        'exclude_attrs': None,
        'readonly_attrs': None,
        'proxy_attrs': None,
        'amf3': None,
        'dynamic': None,
        'alias': None,
        'external': None,
        'synonym_attrs': None
    }

    if not hasattr(klass, '__amf__'):
        return meta

    a = klass.__amf__

    if type(a) is dict:
        in_func = lambda x: x in a
        get_func = a.__getitem__
    else:
        in_func = lambda x: hasattr(a, x)
        get_func = lambda x: getattr(a, x)

    for prop in ['alias', 'amf3', 'dynamic', 'external']:
        if in_func(prop):
            meta[prop] = get_func(prop)

    for prop in ['static', 'exclude', 'readonly', 'proxy', 'synonym']:
        if in_func(prop):
            meta[prop + '_attrs'] = get_func(prop)

    return meta
694945
def getDescriptor(klass, **kw):
    
    # XXX: ctypes Structure.__init__ ignores arguments which do not exist
    # as structure fields. So check it.
    # This is annoying, but not doing it is a huge waste of time for the
    # developer.
    empty = klass()
    assert hasattr(empty, 'bLength')
    assert hasattr(empty, 'bDescriptorType')
    unknown = [x for x in kw if not hasattr(empty, x)]
    if unknown:
        raise TypeError('Unknown fields %r' % (unknown, ))
    # XXX: not very pythonic...
    return klass(
        bLength=ctypes.sizeof(klass),
        # pylint: disable=protected-access
        bDescriptorType=klass._bDescriptorType,
        # pylint: enable=protected-access
        **kw
    )
447863
def get_or_connect(cls, **kwargs):
        
        try:
            inst = cls.get(**kwargs)
            created = False
        except DoesNotExist:
            inst = cls(**kwargs)
            created = True
        except Exception:
            raise
        return inst, created
1068327
def from_args(cls: Type[ConfigT], args: Namespace) -> ConfigT:
        
        parsed_args = cls.parse_args(args)
        return cls(args, host=args.host, port=args.port, debug=args.debug,
                   reject_insecure_auth=not args.insecure_login,
                   cert_file=args.cert, key_file=args.key,
                   **parsed_args)
515068
def execute_read_only(*args, **kwargs):
        # TODO: consolidate with execute
        

        # Inspect the call stack for the originating call
        args = CoyoteDb.__add_query_comment(args[0])

        # Execute the query
        db = CoyoteDb.__get_db_read_instance()
        cursor = db.cursor()
        try:
            cursor.execute(*args, **kwargs)
        except OperationalError, e:
            raise OperationalError('{} when executing: {}'.format(e.args, args[0]))
        return db, cursor
1126252
def grep(source, regex, stop_on_first=False):
    """"""
    loader = ClassLoader(source, max_cache=-1)
    r = re.compile(regex)

    def _matches(constant):
        return r.match(constant.value)

    for klass in loader.classes:
        it = loader.search_constant_pool(path=klass, type_=UTF8, f=_matches)
        if next(it, None):
            print(klass)
            if stop_on_first:
                break
471345
def instances(klass)
      files.map do |plugin_file|
        plugin_file.instances.select { |inst| inst.is_a?(klass) }
      end.flatten
    end
1244368
def get_connection(backend=None, fail_silently=False, **kwargs):
    
    klass = perform_import(backend or active_config.EMAIL_BACKEND)
    return klass(fail_silently=fail_silently, **kwargs)
589902
def _import(klass):
        ''''''
        mod = __import__(klass.rpartition('.')[0])
        for segment in klass.split('.')[1:-1]:
            mod = getattr(mod, segment)

        # Alright, now check the file associated with it. Note that clases
        # defined in __main__ don't have a __file__ attribute
        if klass not in BaseJob._loaded:
            BaseJob._loaded[klass] = time.time()
        if hasattr(mod, '__file__'):
            try:
                mtime = os.stat(mod.__file__).st_mtime
                if BaseJob._loaded[klass] < mtime:
                    mod = reload_module(mod)
            except OSError:
                logger.warn('Could not check modification time of %s',
                    mod.__file__)

        return getattr(mod, klass.rpartition('.')[2])
271211
def retry(f, exc_classes=DEFAULT_EXC_CLASSES, logger=None,
          retry_log_level=logging.INFO,
          retry_log_message="Connection broken in '{f}' (error: '{e}'); "
                            "retrying with new connection.",
          max_failures=None, interval=0,
          max_failure_log_level=logging.ERROR,
          max_failure_log_message="Max retries reached for '{f}'. Aborting."):
    
    exc_classes = tuple(exc_classes)

    @wraps(f)
    def deco(*args, **kwargs):
        failures = 0
        while True:
            try:
                return f(*args, **kwargs)
            except exc_classes as e:
                if logger is not None:
                    logger.log(retry_log_level,
                               retry_log_message.format(f=f.func_name, e=e))
                gevent.sleep(interval)
                failures += 1
                if max_failures is not None \
                        and failures > max_failures:
                    if logger is not None:
                        logger.log(max_failure_log_level,
                                   max_failure_log_message.format(
                                       f=f.func_name, e=e))
                    raise
    return deco
223362
def read_kioslaverc (kde_config_dir):
    """"""
    data = {}
    filename = os.path.join(kde_config_dir, "kioslaverc")
    with open(filename) as fd:
        # First read all lines into dictionary since they can occur
        # in any order.
        for line in  fd:
            line = line.rstrip()
            if line.startswith('['):
                in_proxy_settings = line.startswith("[Proxy Settings]")
            elif in_proxy_settings:
                if '=' not in line:
                    continue
                key, value = line.split('=', 1)
                key = key.strip()
                value = value.strip()
                if not key:
                    continue
                # trim optional localization
                key = loc_ro.sub("", key).strip()
                if not key:
                    continue
                add_kde_setting(key, value, data)
    resolve_kde_settings(data)
    return data
718402
@Override
   public <C extends ConnectionFactoryConfigurationBuilder<?>> C connectionFactory(Class<C> klass) {
      if (connectionFactory != null) {
         throw new IllegalStateException("A ConnectionFactory has already been configured for this store");
      }
      try {
         Constructor<C> constructor = klass.getDeclaredConstructor(AbstractJdbcStoreConfigurationBuilder.class);
         C builder = constructor.newInstance(this);
         this.connectionFactory = (ConnectionFactoryConfigurationBuilder<ConnectionFactoryConfiguration>) builder;
         return builder;
      } catch (Exception e) {
         throw new CacheConfigurationException("Could not instantiate loader configuration builder '" + klass.getName() + "'", e);
      }
   }
683752
def __deserialize(self, data, klass):
        
        if data is None:
            return None

        if type(klass) == str:
            from tradenity.resources.paging import Page
            if klass.startswith('page['):
                sub_kls = re.match('page\[(.*)\]', klass).group(1)
                return Page([self.__deserialize(sub_data, sub_kls)
                            for sub_data in data["items"]], self.__deserialize_page_info(data["__meta"]))
            if klass.startswith('list['):
                sub_kls = re.match('list\[(.*)\]', klass).group(1)
                return [self.__deserialize(sub_data, sub_kls)
                        for sub_data in data]

            if klass.startswith('dict('):
                sub_kls = re.match('dict\(([^,]*), (.*)\)', klass).group(2)
                return {k: self.__deserialize(v, sub_kls)
                        for k, v in six.iteritems(data)}

            # convert str to class
            if klass in self.NATIVE_TYPES_MAPPING:
                klass = self.NATIVE_TYPES_MAPPING[klass]
            else:
                klass = getattr(tradenity.resources, klass)

        if klass in self.PRIMITIVE_TYPES:
            return self.__deserialize_primitive(data, klass)
        elif klass == object:
            return self.__deserialize_object(data)
        elif klass == datetime.date:
            return self.__deserialize_date(data)
        elif klass == datetime.datetime:
            return self.__deserialize_datatime(data)
        else:
            return self.__deserialize_model(data, klass)
873353
def extract_init_args(instance):
    
    cls = instance.__class__
    args = [x for x in inspect.getargspec(cls.__init__).args if x != 'self']
    return [instance.__dict__[key] for key in args]
1345953
def wrap_connection_loader__get(name, *args, **kwargs):
    
    if name in ('docker', 'kubectl', 'jail', 'local', 'lxc',
                'lxd', 'machinectl', 'setns', 'ssh'):
        name = 'mitogen_' + name
    return connection_loader__get(name, *args, **kwargs)