Import object by complete namespace
325193
def import_object_by_string(namespace):
    """"""
    segments = namespace.split('.')
    module = importlib.import_module('.'.join(segments[:-1]))
    return getattr(module, segments[-1])
490814
def _import_class(self, module2cls):
        """"""
        d = module2cls.rfind(".")
        classname = module2cls[d + 1: len(module2cls)]
        m = __import__(module2cls[0:d], globals(), locals(), [classname])
        return getattr(m, classname)
463589
function transformNamespaceImports(j, root, importPath, targetPath) {
  // find namespace imports
  root.find(j.ImportDeclaration, { source: { value: importPath } }).forEach(importDeclaration => {
    const namespaceImportSpecifier = importDeclaration.node.specifiers.find(
      specifier => specifier.type === 'ImportNamespaceSpecifier',
    );
    if (namespaceImportSpecifier) {
      j(importDeclaration).replaceWith(
        j.importDeclaration(
          [j.importNamespaceSpecifier(j.identifier(namespaceImportSpecifier.local.name))],
          j.literal(targetPath),
        ),
      );
      transformMemberExpressions(namespaceImportSpecifier.local.name, j, root);
    }
  });
}
760549
def import_global(node: Node, key: str, path: Any):
    """"""
    node.node_globals[key] = import_path(path)
429502
def _Import(self, t):
        
        self._fill("import ")
        
        for i, (name,asname) in enumerate(t.names):
            if i != 0:
                self._write(", ")
            self._write(name)
            if asname is not None:
                self._write(" as "+asname)
697559
def _import_component(name):
    
    for f in (_get_from_module, _get_from_class):
        try:
            return f(name)
        except:
            pass
    log.debug("Couldn't load %s" % name)
1071638
def load_object_by_name(obj_name):
    
    parts = obj_name.split('.')
    t = __import__('.'.join(parts[:-1]), fromlist=(parts[-1],))
    return getattr(t, parts[-1])
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();
    }
  }
271596
def my_import(name):
    
    module, attr = name.rsplit('.', 1)
    mod = __import__(module, fromlist=[attr])
    klass = getattr(mod, attr)
    return klass()
1151947
function buildNamespaceReexport(metadata, namespace, loose) {
  return (loose
    ? template.statement`
        Object.keys(NAMESPACE).forEach(function(key) {
          if (key === "default" || key === "__esModule") return;
          VERIFY_NAME_LIST;

          EXPORTS[key] = NAMESPACE[key];
        });
      `
    : template.statement`
        Object.keys(NAMESPACE).forEach(function(key) {
          if (key === "default" || key === "__esModule") return;
          VERIFY_NAME_LIST;

          Object.defineProperty(EXPORTS, key, {
            enumerable: true,
            get: function() {
              return NAMESPACE[key];
            },
          });
        });
    `)({
    NAMESPACE: namespace,
    EXPORTS: metadata.exportName,
    VERIFY_NAME_LIST: metadata.exportNameListName
      ? template`
            if (Object.prototype.hasOwnProperty.call(EXPORTS_LIST, key)) return;
          `({ EXPORTS_LIST: metadata.exportNameListName })
      : null,
  });
}
403312
function (namespace) {
        var declaration = importDeclaration(context)

        var imports = Exports.get(declaration.source.value, context)
        if (imports == null) return null

        if (imports.errors.length) {
          imports.reportErrors(context, declaration)
          return
        }

        if (!imports.size) {
          context.report(namespace,
            `No exported names found in module '${declaration.source.value}'.`)
        }
      }
253754
def to_foreign(self, obj, name, value):  # pylint:disable=unused-argument
		""""""
		
		namespace = self.namespace
		
		try:
			explicit = self.explicit
		except AttributeError:
			explicit = not namespace
		
		if not isinstance(value, (str, unicode)):
			value = canon(value)
		
		if namespace and ':' in value:  # Try to reduce to a known plugin short name.
			for point in iter_entry_points(namespace):  # TODO: Isolate.
				qualname = point.module_name
				
				if point.attrs:
					qualname += ':' + '.'.join(point.attrs)
				
				if qualname == value:
					value = point.name
					break
		
		if ':' in value:
			if not explicit:
				raise ValueError("Explicit object references not allowed.")
			
			return value
		
		if namespace and value not in (i.name for i in iter_entry_points(namespace)):
			raise ValueError('Unknown plugin "' + value + '" for namespace "' + namespace + '".')
		
		return value
94924
def from_name(cls, fullname, soco, *args, **kwargs):
        """"""

        _LOG.info('Loading plugin %s', fullname)

        parts = fullname.split('.')
        modname = '.'.join(parts[:-1])
        clsname = parts[-1]

        mod = importlib.import_module(modname)
        class_ = getattr(mod, clsname)

        _LOG.info('Loaded class %s', class_)

        return class_(soco, *args, **kwargs)
639928
def import_plugin(self, plugin):
        '''
        
        '''
        names = [
            '%s%s%s' % (namespace, '' if namespace[-1] == '_' else '.', plugin)
            if namespace else
            plugin
            for namespace in self.namespaces
            ]

        for name in names:
            if name in sys.modules:
                return sys.modules[name]

        for name in names:
            try:
                __import__(name)
                return sys.modules[name]
            except (ImportError, KeyError):
                pass

        raise PluginNotFoundError(
            'No plugin module %r found, tried %r' % (plugin, names),
            plugin, names)
182915
function parseClassName(fullClassName, namespaces) {
		const result = {};
		let className = fullClassName;
		// Extract the namespace
		if (namespaces.length) {
			const namespaceIndex = namespaces.findIndex((namespace) => {
				return className.startsWith(namespace);
			});
			if (namespaceIndex === -1) {
				return result;
			}
			const namespace = namespaces[namespaceIndex];
			result.namespace = namespace;
			className = className.substr(namespace.length);
		}
		// Handle className with helper prefixes
		const helperPrefix = className.split('-')[0];
		if (validHelperPrefixes.indexOf(helperPrefix) !== -1) {
			result.helper = helperPrefix;
			className = className.substr(helperPrefix.length + 1);
		}
		// Handle classNames with prefixes
		const patternPrefix = className.split('-')[0];
		if (validPatternPrefixes.indexOf(patternPrefix) !== -1) {
			result.pattern = patternPrefix;
			className = className.substr(patternPrefix.length + 1);
		}
		result.name = className;
		result.parts = className.split(/__|--/);
		return result;
	}
1318242
def iobject_import(self,
                       id_and_rev_info,
                       elt_name,
                       obj_dict,
                       markings=None,
                       cybox_id=None):
        

        iobject_type_ns = None

        # Derive the namespace information
        if ('@xsi:type' in obj_dict or
                    '@@embedded_type_info' in obj_dict or
                    '@xsi:type' in obj_dict.get('Properties', {}) or
                    '@xsi:type' in obj_dict.get('Defined_Object', {}) ):
            if '@xsi:type' in obj_dict:
                iobject_type_ns = obj_dict['@xsi:type'].split(':')[0]
            elif '@xsi:type' in obj_dict.get('Properties', {}):
                iobject_type_ns = obj_dict['Properties']['@xsi:type'].split(':')[0]
            elif '@xsi:type' in obj_dict.get('Defined_Object', {}):
                iobject_type_ns = obj_dict['Defined_Object']['@xsi:type'].split(':')[0]
            else:
                iobject_type_ns = obj_dict['@@embedded_type_info']

        # Find out what the type of the Information Object to be created should be
        type_info = self.derive_iobject_type(obj_dict['@@ns'], iobject_type_ns, elt_name)

        if (not 'id' in id_and_rev_info or not id_and_rev_info['id']) and (not 'id_ns' in id_and_rev_info):
            logger.info("Object of type %s without id information encountered, skipping" % elt_name)
            return
        if 'id_ns' in id_and_rev_info:
            namespace_uri = id_and_rev_info['id_ns']
            uid = id_and_rev_info['id_uid']
        else:
            (namespace, namespace_uri, uid) = self.split_qname(id_and_rev_info['id'])

        object_timestamp = id_and_rev_info.get('timestamp',None)
        if not object_timestamp:
            object_timestamp = self.default_timestamp

        (info_obj, existed) = MantisImporter.create_iobject(iobject_family_name=type_info['iobject_family_name'],
                                                            iobject_family_revision_name=type_info[
                                                                'iobject_family_revision_name'],
                                                            iobject_type_name=type_info['iobject_type_name'],
                                                            iobject_type_namespace_uri=type_info[
                                                                'iobject_type_namespace_uri'],
                                                            iobject_type_revision_name=type_info[
                                                                'iobject_type_revision_name'],
                                                            iobject_data=obj_dict,
                                                            uid=uid,
                                                            identifier_ns_uri=namespace_uri,
                                                            timestamp= object_timestamp,
                                                            create_timestamp=self.create_timestamp,
                                                            markings=markings,
                                                            config_hooks={
                                                            'special_ft_handler': self.fact_handler_list(),
                                                            'datatype_extractor': self.cybox_datatype_extractor,
                                                            'attr_ignore_predicate': self.attr_ignore_predicate,
                                                            'force_nonleaf_fact_predicate': self.force_nonleaf_fact_predicate},
                                                            namespace_dict=self.namespace_dict,
        )

        return (info_obj, existed)
442679
def import_handle(self, original, loc, tokens):
        """"""
        if len(tokens) == 1:
            imp_from, imports = None, tokens[0]
        elif len(tokens) == 2:
            imp_from, imports = tokens
            if imp_from == "__future__":
                self.strict_err_or_warn("unnecessary from __future__ import (Coconut does these automatically)", original, loc)
                return ""
        else:
            raise CoconutInternalException("invalid import tokens", tokens)
        if self.strict:
            self.unused_imports.update(imported_names(imports))
        return universal_import(imports, imp_from=imp_from, target=self.target)