Resolve dotted names:

    .. code-block:: python

        >>> maybedotted('irc3.config')
        <module 'irc3.config' from '...'>
        >>> maybedotted('irc3.utils.IrcString')
        <class 'irc3.utils.IrcString'>

    ..
484492
def maybedotted(name):
    
    if not name:
        raise LookupError(
            'Not able to resolve %s' % name)
    if not hasattr(name, '__name__'):
        try:
            mod = importlib.import_module(name)
        except ImportError:
            attr = None
            if '.' in name:
                names = name.split('.')
                attr = names.pop(-1)
                try:
                    mod = maybedotted('.'.join(names))
                except LookupError:
                    attr = None
                else:
                    attr = getattr(mod, attr, None)
            if attr is not None:
                return attr
            raise LookupError(
                'Not able to resolve %s' % name)
        else:
            return mod
    return name
834105
def import_string(dotted_path):
    
    try:
        module_path, class_name = dotted_path.rsplit('.', 1)
    except ValueError:
        msg = "%s doesn't look like a module path" % dotted_path
        six.reraise(ImportError, ImportError(msg), sys.exc_info()[2])

    module = import_module(module_path)

    try:
        return getattr(module, class_name)
    except AttributeError:
        msg = 'Module "%s" does not define a "%s" attribute/class' % (
            dotted_path, class_name
        )
        six.reraise(ImportError, ImportError(msg), sys.exc_info()[2])
1072130
def findModuleOfName(self, dotted_name, level, filename, extrapath=None):
        """"""
        if dotted_name.endswith('.*'):
            return dotted_name[:-2]
        name = dotted_name

        # extrapath is None only in a couple of test cases; in real life it's
        # always present
        if level and level > 1 and extrapath:
            # strip trailing path bits for each extra level to account for
            # relative imports
            # from . import X has level == 1 and nothing is stripped (the level > 1 check accounts for this case)
            # from .. import X has level == 2 and one trailing path component must go
            # from ... import X has level == 3 and two trailing path components must go
            extrapath = extrapath.split(os.path.sep)
            level -= 1
            extrapath = extrapath[0:-level]
            extrapath = os.path.sep.join(extrapath)

        while name:
            candidate = self.isModule(name, extrapath)
            if candidate:
                return candidate
            candidate = self.isPackage(name, extrapath)
            if candidate:
                return candidate
            name = name[:name.rfind('.')]
        self.warn(dotted_name, '%s: could not find %s', filename, dotted_name)
        return dotted_name
946395
def _get_module_name_from_fname(fname):
    """"""
    fname = fname.replace(".pyc", ".py")
    for mobj in sys.modules.values():
        if (
            hasattr(mobj, "__file__")
            and mobj.__file__
            and (mobj.__file__.replace(".pyc", ".py") == fname)
        ):
            module_name = mobj.__name__
            return module_name
    raise RuntimeError("Module could not be found")
1244340
def cfg(self):
        
        config = LStruct(self.defaults)
        module = config['CONFIG'] = os.environ.get(
            CONFIGURATION_ENVIRON_VARIABLE, config['CONFIG'])

        if module:
            try:
                module = import_module(module)
                config.update({
                    name: getattr(module, name) for name in dir(module)
                    if name == name.upper() and not name.startswith('_')
                })

            except ImportError as exc:
                config.CONFIG = None
                self.logger.error("Error importing %s: %s", module, exc)

        # Patch configuration from ENV
        for name in config:
            if name.startswith('_') or name != name.upper() or name not in os.environ:
                continue
            try:
                config[name] = json.loads(os.environ[name])
            except ValueError:
                pass

        return config
893712
def dotted(self):
        "  "
        obj = libcrypto.OBJ_nid2obj(self.nid)
        buf = create_string_buffer(256)
        libcrypto.OBJ_obj2txt(buf, 256, obj, 1)
        if pyver == 2:
            return buf.value
        else:
            return buf.value.decode('ascii')
660838
def resolve_str(name_or_func, module, default):
    
    assert isinstance(name_or_func, str)
    resolved = resolve(name_or_func, module=module)

    if isinstance(resolved, ModuleType):
        if not hasattr(resolved, default):
            raise ImportError("{}.{}".format(resolved.__name__, default))

        resolved = getattr(resolved, default)

    if not callable(resolved):
        raise TypeError("{!r} is not callable"
                        "".format(resolved))

    return resolved
1358533
function resolveName(pkgpath) {
  pkgpath = pkgpath.replace(RE_TRAILING, '');

  const cwd = process.cwd();
  const parts = pkgpath.split(path.sep);
  const len = parts.length;

  let idx = 1;

  // Handle packages nested under root
  if (!pkgpath.includes('node_modules') && cwd != pkgpath) {
    // Increase by distance from root
    idx += path.relative(cwd, pkgpath).split(path.sep).length;
    // Handle scoped node_modules
  } else if (parts[len - 2].charAt(0) == '@') {
    idx = 2;
  }

  return parts.slice(len - idx).join(path.sep);
}
1205558
def import_string(dotted_path: str) -> Any:
    
    try:
        module_path, class_name = dotted_path.strip(' ').rsplit('.', 1)
    except ValueError as e:
        raise ImportError(f'"{dotted_path}" doesn\'t look like a module path') from e

    module = import_module(module_path)
    try:
        return getattr(module, class_name)
    except AttributeError as e:
        raise ImportError(f'Module "{module_path}" does not define a "{class_name}" attribute') from e
409042
def linkcode_resolve(domain, info):
    
    if domain != 'py' or not info['module']:
        return None
    filename = info['module'].replace('.', '/')
    mod = importlib.import_module(info['module'])
    basename = os.path.splitext(mod.__file__)[0]
    if basename.endswith('__init__'):
        filename += '/__init__'
    item = mod
    lineno = ''
    for piece in info['fullname'].split('.'):
        item = getattr(item, piece)
        try:
            lineno = '#L%d' % inspect.getsourcelines(item)[1]
        except (TypeError, IOError):
            pass
    return ("https://github.com/%s/%s/blob/%s/%s.py%s" %
            (github_user, project, release, filename, lineno))
713006
private static void checkPattern(String s) throws ProblemException {
        // Package names like foo.bar.gamma are allowed, and
        // package names suffixed with .* like foo.bar.* are
        // also allowed.
        Pattern p = Pattern.compile("[a-zA-Z_]{1}[a-zA-Z0-9_]*(\\.[a-zA-Z_]{1}[a-zA-Z0-9_]*)*(\\.\\*)?+");
        Matcher m = p.matcher(s);
        if (!m.matches()) {
            throw new ProblemException("The string \""+s+"\" is not a proper package name pattern.");
        }
    }
657286
def make_python_patterns(additional_keywords=[], additional_builtins=[]):
    ""
    kwlist = keyword.kwlist + additional_keywords
    builtinlist = [str(name) for name in dir(builtins)
                   if not name.startswith('_')] + additional_builtins
    repeated = set(kwlist) & set(builtinlist)
    for repeated_element in repeated:
        kwlist.remove(repeated_element)
    kw = r"\b" + any("keyword", kwlist) + r"\b"
    builtin = r"([^.'\"\\#]\b|^)" + any("builtin", builtinlist) + r"\b"
    comment = any("comment", [r"#[^\n]*"])
    instance = any("instance", [r"\bself\b",
                                r"\bcls\b",
                                (r"^\s*@([a-zA-Z_][a-zA-Z0-9_]*)"
                                     r"(\.[a-zA-Z_][a-zA-Z0-9_]*)*")])
    number_regex = [r"\b[+-]?[0-9]+[lLjJ]?\b",
                    r"\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b",
                    r"\b[+-]?0[oO][0-7]+[lL]?\b",
                    r"\b[+-]?0[bB][01]+[lL]?\b",
                    r"\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?[jJ]?\b"]
    if PY3:
        prefix = "r|u|R|U|f|F|fr|Fr|fR|FR|rf|rF|Rf|RF|b|B|br|Br|bR|BR|rb|rB|Rb|RB"
    else:
        prefix = "r|u|ur|R|U|UR|Ur|uR|b|B|br|Br|bR|BR"
    sqstring =     r"(\b(%s))?'[^'\\\n]*(\\.[^'\\\n]*)*'?" % prefix
    dqstring =     r'(\b(%s))?"[^"\\\n]*(\\.[^"\\\n]*)*"?' % prefix
    uf_sqstring =  r"(\b(%s))?'[^'\\\n]*(\\.[^'\\\n]*)*(\\)$(?!')$" % prefix
    uf_dqstring =  r'(\b(%s))?"[^"\\\n]*(\\.[^"\\\n]*)*(\\)$(?!")$' % prefix
    sq3string =    r"(\b(%s))?'''[^'\\]*((\\.|'(?!''))[^'\\]*)*(''')?" % prefix
    dq3string =    r'(\b(%s))?"""[^"\\]*((\\.|"(?!""))[^"\\]*)*(""")?' % prefix
    uf_sq3string = r"(\b(%s))?'''[^'\\]*((\\.|'(?!''))[^'\\]*)*(\\)?(?!''')$" \
                   % prefix
    uf_dq3string = r'(\b(%s))?"""[^"\\]*((\\.|"(?!""))[^"\\]*)*(\\)?(?!""")$' \
                   % prefix
    # Needed to achieve correct highlighting in Python 3.6+
    # See issue 7324
    if PY36_OR_MORE:
        # Based on
        # https://github.com/python/cpython/blob/
        # 81950495ba2c36056e0ce48fd37d514816c26747/Lib/tokenize.py#L117
        # In order: Hexnumber, Binnumber, Octnumber, Decnumber,
        # Pointfloat + Exponent, Expfloat, Imagnumber
        number_regex = [
                r"\b[+-]?0[xX](?:_?[0-9A-Fa-f])+[lL]?\b",
                r"\b[+-]?0[bB](?:_?[01])+[lL]?\b",
                r"\b[+-]?0[oO](?:_?[0-7])+[lL]?\b",
                r"\b[+-]?(?:0(?:_?0)*|[1-9](?:_?[0-9])*)[lL]?\b",
                r"\b((\.[0-9](?:_?[0-9])*')|\.[0-9](?:_?[0-9])*)"
                "([eE][+-]?[0-9](?:_?[0-9])*)?[jJ]?\b",
                r"\b[0-9](?:_?[0-9])*([eE][+-]?[0-9](?:_?[0-9])*)?[jJ]?\b",
                r"\b[0-9](?:_?[0-9])*[jJ]\b"]
    number = any("number", number_regex)

    string = any("string", [sq3string, dq3string, sqstring, dqstring])
    ufstring1 = any("uf_sqstring", [uf_sqstring])
    ufstring2 = any("uf_dqstring", [uf_dqstring])
    ufstring3 = any("uf_sq3string", [uf_sq3string])
    ufstring4 = any("uf_dq3string", [uf_dq3string])
    return "|".join([instance, kw, builtin, comment,
                     ufstring1, ufstring2, ufstring3, ufstring4, string,
                     number, any("SYNC", [r"\n"])])
1099593
def to_constant_name(desc) #:nodoc:
      name = case desc
        when String then desc.starts_with?('::') ? desc[2..-1] : desc
        when Symbol then desc.to_s
        when Module
          raise ArgumentError, "Anonymous modules have no name to be referenced by" if desc.name.blank?
          desc.name
        else raise TypeError, "Not a valid constant descriptor: #{desc.inspect}"
      end
    end
143171
def traverse_imports(names):
    
    pending = [names]
    while pending:
        node = pending.pop()
        if node.type == token.NAME:
            yield node.value
        elif node.type == syms.dotted_name:
            yield "".join([ch.value for ch in node.children])
        elif node.type == syms.dotted_as_name:
            pending.append(node.children[0])
        elif node.type == syms.dotted_as_names:
            pending.extend(node.children[::-2])
        else:
            raise AssertionError("unkown node type")
1010861
def linkcode_resolve(domain, info):
    
    if domain != 'py':
        return None

    modname = info['module']
    fullname = info['fullname']

    submod = sys.modules.get(modname)
    if submod is None:
        return None

    obj = submod
    for part in fullname.split('.'):
        try:
            obj = getattr(obj, part)
        except AttributeError:
            return None

    try:
        # inspect.unwrap() was added in Python version 3.4
        if sys.version_info >= (3, 5):
            fn = inspect.getsourcefile(inspect.unwrap(obj))
        else:
            fn = inspect.getsourcefile(obj)
    except TypeError:
        fn = None
    if not fn:
        return None

    try:
        source, lineno = inspect.getsourcelines(obj)
    except OSError:
        lineno = None

    if lineno:
        linespec = "#L{:d}-L{:d}".format(lineno, lineno + len(source) - 1)
    else:
        linespec = ""

    fn = os.path.relpath(fn, start=os.path.dirname(pandas.__file__))

    if '+' in pandas.__version__:
        return ("http://github.com/pandas-dev/pandas/blob/master/pandas/"
                "{}{}".format(fn, linespec))
    else:
        return ("http://github.com/pandas-dev/pandas/blob/"
                "v{}/pandas/{}{}".format(pandas.__version__, fn, linespec))
892036
function resolveModule(module) {
  debug("resolveModule", module);

  const presetName = module;

  if (path.isAbsolute(presetName)) {
    return [getPresetName(module), module];
  }

  try {
    // Try the naive way
    return [presetName, require.resolve(module)];
  } catch (e) {
    // Try a more advanced way
    return [presetName, resolve.sync(process.cwd() + "/node_modules", module)];
  }
}
16609
def all_patterns(name):
    
    """

    # i_ denotes an import-like node
    # u_ denotes a node that appears to be a usage of the name
    if u'.' in name:
        name, attr = name.split(u'.', 1)
        simple_name = simple_name_match % (name)
        simple_attr = subname_match % (attr)
        dotted_name = dotted_name_match % (simple_name, simple_attr)
        i_from = from_import_match % (dotted_name)
        i_from_submod = from_import_submod_match % (simple_name, simple_attr, simple_attr, simple_attr, simple_attr)
        i_name = name_import_match % (dotted_name, dotted_name)
        u_name = power_twoname_match % (simple_name, simple_attr)
        u_subname = power_subname_match % (simple_attr)
        return u' | \n'.join((i_name, i_from, i_from_submod, u_name, u_subname))
    else:
        simple_name = simple_name_match % (name)
        i_name = name_import_match % (simple_name, simple_name)
        i_from = from_import_match % (simple_name)
        u_name = power_onename_match % (simple_name)
        return u' | \n'.join((i_name, i_from, u_name))