Canonicalizes a list of import statements by deduplicating and merging imports for the same
namespace, and sorting the result.
192777
private static List<ImportStatement> canonicalizeImports(
      Multimap<String, ImportStatement> importsByNamespace) {
    List<ImportStatement> canonicalImports = new ArrayList<>();

    for (String namespace : importsByNamespace.keySet()) {
      Collection<ImportStatement> allImports = importsByNamespace.get(namespace);

      // Find the strongest primitive across all existing imports. Every emitted import for this
      // namespace will use this primitive. This makes the logic simpler and cannot change runtime
      // behavior, but may produce spurious changes when multiple aliasing imports of differing
      // strength exist (which are already in violation of the style guide).
      ImportPrimitive strongestPrimitive =
          allImports.stream()
              .map(ImportStatement::primitive)
              .reduce(ImportPrimitive.WEAKEST, ImportPrimitive::stronger);

      // Emit each aliasing import separately, as deduplicating them would require code references
      // to be rewritten.
      boolean hasAliasing = false;
      for (ImportStatement stmt : Iterables.filter(allImports, ImportStatement::isAliasing)) {
        canonicalImports.add(stmt.upgrade(strongestPrimitive));
        hasAliasing = true;
      }

      // Emit a single destructuring import with a non-empty pattern, merged from the existing
      // destructuring imports.
      boolean hasDestructuring = false;
      ImmutableList<Node> destructuringNodes =
          allImports.stream()
              .filter(ImportStatement::isDestructuring)
              .flatMap(i -> i.nodes().stream())
              .collect(toImmutableList());
      ImmutableList<DestructuringBinding> destructures =
          allImports.stream()
              .filter(ImportStatement::isDestructuring)
              .flatMap(i -> i.destructures().stream())
              .distinct()
              .sorted()
              .collect(toImmutableList());
      if (!destructures.isEmpty()) {
        canonicalImports.add(
            ImportStatement.of(
                destructuringNodes,
                strongestPrimitive,
                namespace,
                /* alias= */ null,
                destructures));
        hasDestructuring = true;
      }

      // Emit a standalone import unless an aliasing or destructuring one already exists.
      if (!hasAliasing && !hasDestructuring) {
        ImmutableList<Node> standaloneNodes =
            allImports.stream()
                .filter(ImportStatement::isStandalone)
                .flatMap(i -> i.nodes().stream())
                .collect(toImmutableList());
        canonicalImports.add(
            ImportStatement.of(
                standaloneNodes,
                strongestPrimitive,
                namespace,
                /* alias= */ null,
                /* destructures= */ null));
      }
    }

    // Sorting by natural order yields the correct result due to the implementation of
    // ImportStatement#compareTo.
    Collections.sort(canonicalImports);

    return canonicalImports;
  }
1183021
def _at_dump_imports(self, calculator, rule, scope, block):
        
        sys.stderr.write("%s\n" % repr(rule.namespace._imports))
270764
def _list_merge(src, dest):
    
    for k in src:
        if type(src[k]) != dict:
            dest[k] = src[k]
        else:
            # ---
            # src could have a key whose value is a list
            # and does not yet exist on dest
            if k not in dest:
                dest[k] = {}
            _list_merge(src[k], dest[k])
59433
def retrieve_import_alias_mapping(names_list):
    """"""
    import_alias_names = dict()

    for alias in names_list:
        if alias.asname:
            import_alias_names[alias.asname] = alias.name
    return import_alias_names
161658
def _normalize_merge_diff_incr(diff):
        
        new_diff = []

        changes_found = False
        for line in diff.splitlines():
            if re.search(r"order-dependent line.*re-ordered", line):
                changes_found = True
            elif "No changes were found" in line:
                # IOS in the re-order case still claims "No changes were found"
                if not changes_found:
                    return ""
                else:
                    continue

            if line.strip() == "end":
                continue
            elif "List of Commands" in line:
                continue
            # Filter blank lines and prepend +sign
            elif line.strip():
                if re.search(r"^no\s+", line.strip()):
                    new_diff.append("-" + line)
                else:
                    new_diff.append("+" + line)
        return "\n".join(new_diff)
910188
def _deduplicate(lst):
    """"""
    out = []
    for i in lst:
        if i not in out:
            out.append(i)
    return out
1343580
private Map<String, ImportConfiguration> loadNewConfigAndBundles(CatalogContext catalogContext) {
        Map<String, ImportConfiguration> newProcessorConfig;

        ImportType importElement = catalogContext.getDeployment().getImport();
        if (importElement == null || importElement.getConfiguration().isEmpty()) {
            newProcessorConfig = new HashMap<>();
        } else {
            newProcessorConfig = CatalogUtil.getImportProcessorConfig(importElement);
        }

        Iterator<Map.Entry<String, ImportConfiguration>> iter = newProcessorConfig.entrySet().iterator();
        while (iter.hasNext()) {
            String configName = iter.next().getKey();
            ImportConfiguration importConfig = newProcessorConfig.get(configName);
            Properties properties = importConfig.getmoduleProperties();

            String importBundleJar = properties.getProperty(ImportDataProcessor.IMPORT_MODULE);
            Preconditions.checkNotNull(importBundleJar,
                    "Import source is undefined or custom import plugin class missing.");
            if (!importConfig.checkProcedures(catalogContext, importLog, configName)) {
                iter.remove();
                continue;
            }
            // NOTE: if bundle is already loaded, loadImporterBundle does nothing and returns true
            boolean bundlePresent = loadImporterBundle(properties);
            if (!bundlePresent) {
                iter.remove();
            }
        }
        m_formatterFactories.clear();
        for (ImportConfiguration config : newProcessorConfig.values()) {
            Map<String, FormatterBuilder> formatters = config.getFormatterBuilders();
            if (formatters != null) {
                try {
                    for (FormatterBuilder builder : formatters.values()) {
                        String module = builder.getFormatterProperties().getProperty(ImportDataProcessor.IMPORT_FORMATTER);
                        AbstractFormatterFactory formatterFactory = m_formatterFactories.get(module);
                        if (formatterFactory == null) {
                            URI moduleURI = URI.create(module);
                            formatterFactory = m_moduleManager.getService(moduleURI, AbstractFormatterFactory.class);
                            if (formatterFactory == null) {
                                VoltDB.crashLocalVoltDB("Failed to initialize formatter from: " + module);
                            }
                            m_formatterFactories.put(module, formatterFactory);
                        }
                        builder.setFormatterFactory(formatterFactory);
                    }
                } catch(Throwable t) {
                    VoltDB.crashLocalVoltDB("Failed to initialize formatter.");
                }
            }
        }

        importLog.info("Final importer count:" + newProcessorConfig.size());
        return newProcessorConfig;
    }
1109040
def canonicalize_spec(spec, parent_context):
  """"""

  test_specs = {k:v for (k,v) in spec.items() if k.startswith("Test")}
  local_context = {k:v for (k,v) in spec.items() if not k.startswith("Test")}

  context = reduce_contexts(parent_context, local_context)

  if test_specs:
    return {k: canonicalize_spec(v, context) for (k,v) in test_specs.items()}
  else:
    program_chunks = sum([resolve_module(m,context['Definitions']) for m in context['Modules']],[]) + [context['Program']]
    test_spec = {
      'Arguments': context['Arguments'],
      'Program': "\n".join(program_chunks),
      'Expect': context['Expect'],
    }
    return test_spec
418458
def merge_inner(clsdict):
    
    samelist = False
    done = {}
    while not samelist:
        samelist = True
        classlist = list(clsdict.keys())
        for classname in classlist:
            parts_name = classname.rsplit('$', 1)
            if len(parts_name) > 1:
                mainclass, innerclass = parts_name
                innerclass = innerclass[:-1]  # remove ';' of the name
                mainclass += ';'
                if mainclass in clsdict:
                    clsdict[mainclass].add_subclass(innerclass,
                                                    clsdict[classname])
                    clsdict[classname].name = innerclass
                    done[classname] = clsdict[classname]
                    del clsdict[classname]
                    samelist = False
                elif mainclass in done:
                    cls = done[mainclass]
                    cls.add_subclass(innerclass, clsdict[classname])
                    clsdict[classname].name = innerclass
                    done[classname] = done[mainclass]
                    del clsdict[classname]
                    samelist = False
1370729
def enumerate_dynamic_imports(tokens):
    
    imported_modules = []
    import_line = False
    for index, tok in enumerate(tokens):
        token_type = tok[0]
        token_string = tok[1]
        if token_type == tokenize.NEWLINE:
            import_line = False
        elif token_string == "import":
            try:
                if tokens[index-1][0] == tokenize.NEWLINE:
                    import_line = True
            except IndexError:
                import_line = True # Just means this is the first line
        elif import_line:
            if token_type == tokenize.NAME and tokens[index+1][1] != 'as':
                if token_string not in reserved_words:
                    if token_string not in imported_modules:
                        imported_modules.append(token_string)
    return imported_modules
1053011
private void prepareAssocBeanImports() {

    importTypes.remove(DB);
    importTypes.remove(TQROOTBEAN);
    importTypes.remove(DATABASE);
    importTypes.add(TQASSOCBEAN);
    if (isEntity()) {
      importTypes.add(TQPROPERTY);
      importTypes.add(origDestPackage + ".Q" + origShortName);
    }

    // remove imports for the same package
    Iterator<String> importsIterator = importTypes.iterator();
    String checkImportStart = destPackage + ".QAssoc";
    while (importsIterator.hasNext()) {
      String importType = importsIterator.next();
      if (importType.startsWith(checkImportStart)) {
        importsIterator.remove();
      }
    }
  }
809496
public ImportDescr importStatement(PackageDescrBuilder pkg) throws RecognitionException {
        try {
            String kwd;
            if (helper.validateLT(2, kwd = DroolsSoftKeywords.ACC) ||
                    helper.validateLT(2, kwd = DroolsSoftKeywords.ACCUMULATE)) {
                AccumulateImportDescrBuilder imp = helper.start(pkg,
                        AccumulateImportDescrBuilder.class,
                        null);

                try {
                    // import
                    match(input,
                            DRL6Lexer.ID,
                            DroolsSoftKeywords.IMPORT,
                            null,
                            DroolsEditorType.KEYWORD);
                    if (state.failed)
                        return null;

                    // import accumulate
                    match(input,
                            DRL6Lexer.ID,
                            kwd,
                            null,
                            DroolsEditorType.KEYWORD);
                    if (state.failed)
                        return null;

                    // qualifiedIdentifier
                    String target = qualifiedIdentifier();
                    if (state.failed)
                        return null;
                    
                    // function name
                    Token id = match(input,
                            DRL6Lexer.ID,
                            null,
                            null,
                            DroolsEditorType.IDENTIFIER);
                    if (state.failed)
                        return null;
                    if (state.backtracking == 0) {
                        imp.target(target).functionName(id.getText());
                    }

                    return (imp != null) ? imp.getDescr() : null;
                } finally {
                    helper.end(AccumulateImportDescrBuilder.class,
                            imp);
                }
            } else {
                ImportDescrBuilder imp = helper.start(pkg,
                        ImportDescrBuilder.class,
                        null);

                try {
                    // import
                    match(input,
                            DRL6Lexer.ID,
                            DroolsSoftKeywords.IMPORT,
                            null,
                            DroolsEditorType.KEYWORD);
                    if (state.failed)
                        return null;

                    if (helper.validateIdentifierKey(kwd = DroolsSoftKeywords.FUNCTION) ||
                            helper.validateIdentifierKey(kwd = DroolsSoftKeywords.STATIC)) {
                        // function
                        match(input,
                                DRL6Lexer.ID,
                                kwd,
                                null,
                                DroolsEditorType.KEYWORD);
                        if (state.failed)
                            return null;
                    }

                    // qualifiedIdentifier
                    String target = qualifiedIdentifier();
                    if (state.failed)
                        return null;

                    if (input.LA(1) == DRL6Lexer.DOT && input.LA(2) == DRL6Lexer.STAR) {
                        // .*
                        match(input,
                                DRL6Lexer.DOT,
                                null,
                                null,
                                DroolsEditorType.IDENTIFIER);
                        if (state.failed)
                            return null;
                        match(input,
                                DRL6Lexer.STAR,
                                null,
                                null,
                                DroolsEditorType.IDENTIFIER);
                        if (state.failed)
                            return null;
                        target += ".*";
                    }
                    if (state.backtracking == 0)
                        imp.target(target);
                    return (imp != null) ? imp.getDescr() : null;
                } finally {
                    helper.end(ImportDescrBuilder.class,
                            imp);
                }
            }

        } catch (RecognitionException re) {
            reportError(re);
        }
        return null;
    }
1105257
def parse_imports(self, src):
        "  "
        result = []

        def child(obj):
            result.append(obj.group(1))
        src = self.import_re.sub(child, src)
        return src, result
592774
public void setImports(String[] imports) {
        module.bind(CodegenModule.IMPORTS, new HashSet<String>(Arrays.asList(imports)));
    }
331007
@Nonnull
	public Imports copyAndAdd(final Imports imports) {
		Check.notNull(imports, "imports");
		return copyAndAdd(imports.asList());
	}
805204
function looksLikeImport(node) {
            return node.type === "ImportDeclaration" || node.type === "ImportSpecifier" ||
                node.type === "ImportDefaultSpecifier" || node.type === "ImportNamespaceSpecifier";
        }
267332
void recomposeImports()
  {

    m_importNumber = getStylesheetRoot().getImportNumber(this);

    StylesheetRoot root = getStylesheetRoot();
    int globalImportCount = root.getGlobalImportCount();

    m_importCountComposed = (globalImportCount - m_importNumber) - 1;
    
    // Now get the count of composed imports from this stylesheet's imports
    int count = getImportCount();
    if ( count > 0)
    {
      m_endImportCountComposed += count;
      while (count > 0)
        m_endImportCountComposed += this.getImport(--count).getEndImportCountComposed();
    }
    
    // Now get the count of composed imports from this stylesheet's
    // composed includes.
    count = getIncludeCountComposed();
    while (count>0)
    {
      int imports = getIncludeComposed(--count).getImportCount();
      m_endImportCountComposed += imports;
      while (imports > 0)
        m_endImportCountComposed +=getIncludeComposed(count).getImport(--imports).getEndImportCountComposed();
     
    }                                                            
  }