Get the module name from an import node (import or export statement).
497537
private String getEs6ModuleNameFromImportNode(NodeTraversal t, Node n) {
    String importName = n.getLastChild().getString();
    boolean isNamespaceImport = importName.startsWith("goog:");
    if (isNamespaceImport) {
      // Allow importing Closure namespace objects (e.g. from goog.provide or goog.module) as
      //   import ... from 'goog:my.ns.Object'.
      // These are rewritten to plain namespace object accesses.
      return importName.substring("goog:".length());
    } else {
      ModuleLoader.ModulePath modulePath =
          t.getInput()
              .getPath()
              .resolveJsModule(importName, n.getSourceFileName(), n.getLineno(), n.getCharno());
      if (modulePath == null) {
        // The module loader issues an error
        // Fall back to assuming the module is a file path
        modulePath = t.getInput().getPath().resolveModuleAsPath(importName);
      }
      return modulePath.toModuleName();
    }
  }
484341
def getModulePath(project_path,module_name,verbose):
    ''''''
    if not module_name:
        return None
    sys.path.append(project_path)
    try:
        package = pkgutil.get_loader(module_name)
    except ImportError:
        if verbose:
            print("Parent module for "+module_name+" not found.")
        return None
    except:
        if verbose:
            print(module_name+" not loaded for bizarre reasons")
    try:
        if package: 
                if package.get_code(module_name):
                    filename = package.get_code(module_name).co_filename
                    return filename
                elif package.find_spec(module_name).has_location==False:
                    return None #built-in module such as itertools
                else:
                    pass #perhaps filename is in package.find_spec(module_name).origin?
                    pass #a good reference is https://www.python.org/dev/peps/pep-0302/
    except ImportError:
        if verbose:
            print("Code object unavailable for "+module_name)
        return None
    except AttributeError:
        if verbose:
            print(module_name+" is an ExtensionFileLoader object")
        return None
    except:
        if verbose:
            print(module_name+" not loaded for bizarre reasons")
        return None
    else:
        if verbose:
            print ("Module "+module_name+" not found.")
        return None
1235920
def do_import_module(self, modname=None):
        
        # handle special case where we are on a package node importing a module
        # using the same name as the package, which may end in an infinite loop
        # on relative imports
        # XXX: no more needed ?
        mymodule = self.root()
        level = getattr(self, "level", None)  # Import as no level
        if modname is None:
            modname = self.modname
        # XXX we should investigate deeper if we really want to check
        # importing itself: modname and mymodule.name be relative or absolute
        if mymodule.relative_to_absolute_name(modname, level) == mymodule.name:
            # FIXME: we used to raise InferenceError here, but why ?
            return mymodule

        return mymodule.import_module(
            modname, level=level, relative_only=level and level >= 1
        )
645512
def get_module_imports_on_top_of_file(source, import_line_index):
    
    def is_string_literal(line):
        if line[0] in 'uUbB':
            line = line[1:]
        if line and line[0] in 'rR':
            line = line[1:]
        return line and (line[0] == '"' or line[0] == "'")

    def is_future_import(line):
        nodes = ast.parse(line)
        for n in nodes.body:
            if isinstance(n, ast.ImportFrom) and n.module == '__future__':
                return True
        return False

    allowed_try_keywords = ('try', 'except', 'else', 'finally')
    in_docstring = False
    docstring_kind = '"""'
    for cnt, line in enumerate(source):
        if not in_docstring:
            m = DOCSTRING_START_REGEX.match(line.lstrip())
            if m is not None:
                in_docstring = True
                docstring_kind = m.group('kind')
                remain = line[m.end(): m.endpos].rstrip()
                if remain[-3:] == docstring_kind:  # one line doc
                    in_docstring = False
                continue
        if in_docstring:
            if line.rstrip()[-3:] == docstring_kind:
                in_docstring = False
            continue

        if not line.rstrip():
            continue
        elif line.startswith('#'):
            continue

        if line.startswith('import ') or line.startswith('from '):
            if cnt == import_line_index or is_future_import(line):
                continue
            return cnt
        elif pycodestyle.DUNDER_REGEX.match(line):
            continue
        elif any(line.startswith(kw) for kw in allowed_try_keywords):
            continue
        elif is_string_literal(line):
            return cnt
        else:
            return cnt
    return 0
191361
def visit_importfrom(self, node):
        ''''''
        module_filename = node.root().file
        if fnmatch.fnmatch(module_filename, '__init__.py*') and \
                not fnmatch.fnmatch(module_filename, 'test_*.py*'):
            return
        basename = node.modname
        self._check_blacklisted_module(node, basename)
429276
def name(self) -> str:
        
        if self.import_name == '__main__':
            path = Path(getattr(sys.modules['__main__'], '__file__', '__main__.py'))
            return path.stem
        return self.import_name
1001176
def get_ft_names(mod, include_inner=False)->List[str]:
    ""
    # If the module has an attribute __all__, it picks those.
    # Otherwise, it returns all the functions defined inside a module.
    fn_names = []
    for elt_name in get_exports(mod):
        elt = getattr(mod,elt_name)
        #This removes the files imported from elsewhere
        try:    fname = inspect.getfile(elt)
        except: continue
        if mod.__file__.endswith('__init__.py'):
            if inspect.ismodule(elt): fn_names.append(elt_name)
            else: continue
        else:
            if (fname != mod.__file__): continue
            if inspect.isclass(elt) or inspect.isfunction(elt): fn_names.append(elt_name)
            else: continue
        if include_inner and inspect.isclass(elt) and not is_enum(elt.__class__):
            fn_names.extend(get_inner_fts(elt))
    return fn_names
1236664
def visit_Module(self, node):
        
        node.body = [k for k in (self.visit(n) for n in node.body) if k]
        imports = [ast.Import([ast.alias(i, mangle(i))]) for i in self.imports]
        node.body = imports + node.body
        ast.fix_missing_locations(node)
        return node
1076719
def import_name(mod_name):
    
    try:
        mod_obj_old = sys.modules[mod_name]
    except KeyError:
        mod_obj_old = None

    if mod_obj_old is not None:
        return mod_obj_old

    __import__(mod_name)

    mod_obj = sys.modules[mod_name]

    return mod_obj
953551
def scan_module(self, pkgpath, modpath, node):
        """"""

        def scan_imports(node):
            if node_type(node) == 'Import':
                for binding in node.names:
                    name, asname = binding.name, binding.asname
                    if asname:
                        self.add(modpath, asname, name)
                    else:
                        top_name = name.split('.')[0]
                        self.add(modpath, top_name, top_name)
                    self.add_package_origins(name)

            elif node_type(node) == 'ImportFrom':
                frompath = resolve_frompath(pkgpath, node.module, node.level)
                for binding in node.names:
                    name, asname = binding.name, binding.asname
                    if name == '*':
                        for name in self.get_star_names(frompath):
                            self.add(modpath, name, frompath + '.' + name)
                        self.add_package_origins(frompath)
                    else:
                        self.add(modpath, asname or name, frompath + '.' + name)
                        self.add_package_origins(frompath + '.' + name)

            else:
                for_each_child(node, scan_imports)

        for_each_child(node, scan_imports)
1225877
private String extractName(GroovySourceAST typeNode) {
        String typeName = buildName(typeNode);
        if (!typeName.contains("/")) {
            String slashName = "/" + typeName;
            // Groovy currently resolves this to last found so traverse in reverse order
            for (int i = importedClassesAndPackages.size() - 1; i >= 0; i--) {
                String name = importedClassesAndPackages.get(i);
                if (!aliases.containsValue(name) && name.endsWith(slashName)) {
                    typeName = name;
                    break;
                }
            }
        }
        return typeName;
    }
1054741
def _get_node_name(self, node):
        """"""
        res = getattr(node, "name", None)
        if res is None:
            return res

        if isinstance(res, AST.TypeDecl):
            return res.declname
        
        return res
193651
def get_imported_modules(self, module):
    """"""
    for name, member in inspect.getmembers(module):
      if inspect.ismodule(member):
        yield name, member
1367866
def get_name(component):
    
    if six.callable(component):
        name = getattr(component, "__qualname__", component.__name__)
        return '.'.join([component.__module__, name])
    return str(component)
1165977
private String getEffectiveNodePackageName ()
  {
    if (this.packageName != null)
      return this.packageName.length () <= 0 ? SYNTAX_TREE : this.packageName + '.' + SYNTAX_TREE;

    if (this.nodePackageName != null)
      return this.nodePackageName;
    return SYNTAX_TREE;
  }
569944
def get_attribute(module_name: str, attribute_name: str):
    
    assert isinstance(module_name, str)
    assert isinstance(attribute_name, str)

    _module = importlib.import_module(module_name)
    return getattr(_module, attribute_name)
378712
function getImports(moduleTree) {
      var imports = [];

      function addImport(name) {
        if (indexOf.call(imports, name) == -1)
          imports.push(name);
      }

      // tree traversal, NB should use visitor pattern here
      function traverse(object, iterator, parent, parentProperty) {
        var key, child;
        if (iterator(object, parent, parentProperty) === false)
          return;
        for (key in object) {
          if (!object.hasOwnProperty(key))
            continue;
          if (key == 'location' || key == 'type')
            continue;
          child = object[key];
          if (typeof child == 'object' && child !== null)
            traverse(child, iterator, object, key);
        }
      }

      traverse(moduleTree, function(node) {
        // import {} from 'foo';
        // export * from 'foo';
        // export { ... } from 'foo';
        // import * as x from 'foo';
        if (node.type == 'EXPORT_DECLARATION') {
          if (node.declaration.moduleSpecifier)
            addImport(node.declaration.moduleSpecifier.token.processedValue);
        }
        else if (node.type == 'IMPORT_DECLARATION')
          addImport(node.moduleSpecifier.token.processedValue);
        else if (node.type == 'MODULE_DECLARATION')
          addImport(node.expression.token.processedValue);
      });
      return imports;
    }