Sort MCS solution by stereo and bond type matches.
@throws CDKException
777634
public synchronized void sortResultsByStereoAndBondMatch() throws CDKException {

        //        System.out.println("\n\n\n\nSort By ResultsByStereoAndBondMatch");

        Map<Integer, Map<Integer, Integer>> allStereoMCS = new HashMap<Integer, Map<Integer, Integer>>();
        Map<Integer, Map<IAtom, IAtom>> allStereoAtomMCS = new HashMap<Integer, Map<IAtom, IAtom>>();

        Map<Integer, Integer> fragmentScoreMap = new TreeMap<Integer, Integer>();
        Map<Integer, Double> energyScoreMap = new TreeMap<Integer, Double>();
        Map<Integer, Double> stereoScoreMap = new HashMap<Integer, Double>();

        initializeMaps(allStereoMCS, allStereoAtomMCS, stereoScoreMap, fragmentScoreMap, energyScoreMap);

        boolean stereoMatchFlag = getStereoBondChargeMatch(stereoScoreMap, allStereoMCS, allStereoAtomMCS);

        boolean flag = false;
        if (stereoMatchFlag) {

            //Higher Score is mapped preferred over lower
            stereoScoreMap = sortMapByValueInDecendingOrder(stereoScoreMap);
            double higestStereoScore = stereoScoreMap.isEmpty() ? 0 : stereoScoreMap.values().iterator().next();
            double secondhigestStereoScore = higestStereoScore;
            for (Integer key : stereoScoreMap.keySet()) {
                if (secondhigestStereoScore < higestStereoScore && stereoScoreMap.get(key) > secondhigestStereoScore) {
                    secondhigestStereoScore = stereoScoreMap.get(key);
                } else if (secondhigestStereoScore == higestStereoScore
                        && stereoScoreMap.get(key) < secondhigestStereoScore) {
                    secondhigestStereoScore = stereoScoreMap.get(key);
                }
            }

            if (!stereoScoreMap.isEmpty()) {
                flag = true;
                clear();
            }

            /* Put back the sorted solutions */

            int counter = 0;
            for (Integer i : stereoScoreMap.keySet()) {
                //                System.out.println("Sorted Map key " + I + " Sorted Value: " + stereoScoreMap.get(I));
                //                System.out.println("Stereo MCS " + allStereoMCS.get(I) + " Stereo Value: "
                //                        + stereoScoreMap.get(I));
                if (higestStereoScore == stereoScoreMap.get(i).doubleValue()) {
                    //|| secondhigestStereoScore == stereoScoreMap.get(I).doubleValue()) {
                    addSolution(counter, i, allStereoAtomMCS, allStereoMCS, stereoScoreMap, energyScoreMap,
                            fragmentScoreMap);
                    counter++;

                    //                    System.out.println("Sorted Map key " + I + " Sorted Value: " + stereoScoreMap.get(I));
                    //                    System.out.println("Stereo MCS " + allStereoMCS.get(I) + " Stereo Value: "
                    //                            + stereoScoreMap.get(I));
                }
            }
            if (flag) {
                firstSolution.putAll(allMCS.get(0));
                firstAtomMCS.putAll(allAtomMCS.get(0));
                clear(allStereoMCS, allStereoAtomMCS, stereoScoreMap, fragmentScoreMap, energyScoreMap);
            }
        }

    }
531378
@Override
    public void searchMCS(boolean shouldMatchBonds) {

        CDKRMapHandler rmap = new CDKRMapHandler();

        try {

            if ((source.getAtomCount() == target.getAtomCount()) && source.getBondCount() == target.getBondCount()) {
                rOnPFlag = true;
                rmap.calculateOverlapsAndReduceExactMatch(source, target, shouldMatchBonds);

            } else if (source.getAtomCount() > target.getAtomCount() && source.getBondCount() != target.getBondCount()) {
                rOnPFlag = true;
                rmap.calculateOverlapsAndReduce(source, target, shouldMatchBonds);

            } else {
                rOnPFlag = false;
                rmap.calculateOverlapsAndReduce(target, source, shouldMatchBonds);
            }

            setAllMapping();
            setAllAtomMapping();
            setFirstMapping();
            setFirstAtomMapping();

        } catch (CDKException e) {
            rmap = null;
            //            System.err.println("WARNING: graphContainer: most probably time out error ");
        }
    }
829464
public void rsort ()
    {
        sort(new Comparator<T>() {
            public int compare (T o1, T o2) {
                return _comp.compare(o2, o1);
            }
        });
    }
1012523
private IChemFile readChemFile(IChemFile chemFile) throws CDKException, IOException {
        IChemSequence sequence = chemFile.getBuilder().newInstance(IChemSequence.class);
        IChemModel model = null;
        String line = input.readLine();
        String levelOfTheory;
        String description;
        int modelCounter = 0;

        // Find first set of coordinates by skipping all before "Standard orientation"
        while (input.ready() && (line != null)) {
            if (line.indexOf("Standard orientation:") >= 0) {

                // Found a set of coordinates
                model = chemFile.getBuilder().newInstance(IChemModel.class);
                readCoordinates(model);
                break;
            }
            line = input.readLine();
        }
        if (model != null) {

            // Read all other data
            line = input.readLine().trim();
            while (input.ready() && (line != null)) {
                if (line.indexOf('#') == 0) {
                    // Found the route section
                    // Memorizing this for the description of the chemmodel
                    lastRoute = line;
                    modelCounter = 0;

                } else if (line.indexOf("Standard orientation:") >= 0) {

                    // Found a set of coordinates
                    // Add current frame to file and create a new one.
                    if (!readOptimizedStructureOnly.isSet()) {
                        sequence.addChemModel(model);
                    } else {
                        logger.info("Skipping frame, because I was told to do");
                    }
                    fireFrameRead();
                    model = chemFile.getBuilder().newInstance(IChemModel.class);
                    modelCounter++;
                    readCoordinates(model);
                } else if (line.indexOf("SCF Done:") >= 0) {

                    // Found an energy
                    model.setProperty(CDKConstants.REMARK, line.trim());
                } else if (line.indexOf("Harmonic frequencies") >= 0) {

                    // Found a set of vibrations
                    // readFrequencies(frame);
                } else if (line.indexOf("Total atomic charges") >= 0) {
                    readPartialCharges(model);
                } else if (line.indexOf("Magnetic shielding") >= 0) {

                    // Found NMR data
                    readNMRData(model, line);

                } else if (line.indexOf("GINC") >= 0) {

                    // Found calculation level of theory
                    levelOfTheory = parseLevelOfTheory(line);
                    logger.debug("Level of Theory for this model: " + levelOfTheory);
                    description = lastRoute + ", model no. " + modelCounter;
                    model.setProperty(CDKConstants.DESCRIPTION, description);
                } else {
                    //logger.debug("Skipping line: " + line);
                }
                line = input.readLine();
            }

            // Add last frame to file
            sequence.addChemModel(model);
            fireFrameRead();
        }
        chemFile.addChemSequence(sequence);

        return chemFile;
    }
664785
public void placeAliphaticHeavyChain(IAtomContainer molecule, IAtomContainer chain) throws CDKException {
        //logger.debug("******** Place aliphatic Chain *********");
        int[] first = new int[2];
        int counter = 1;
        int nextAtomNr = 0;
        String id1 = "";
        String id2 = "";
        String id3 = "";
        first = findHeavyAtomsInChain(molecule, chain);
        distances = new double[first[1]];
        firstAtoms = new int[first[1]];
        angles = new double[first[1]];
        secondAtoms = new int[first[1]];
        dihedrals = new double[first[1]];
        thirdAtoms = new int[first[1]];
        firstAtoms[0] = first[0];
        molecule.getAtom(firstAtoms[0]).setFlag(CDKConstants.VISITED, true);
        int hybridisation = 0;
        for (int i = 0; i < chain.getAtomCount(); i++) {
            if (isHeavyAtom(chain.getAtom(i))) {
                if (!chain.getAtom(i).getFlag(CDKConstants.VISITED)) {
                    //logger.debug("Counter:" + counter);
                    nextAtomNr = molecule.indexOf(chain.getAtom(i));
                    id2 = molecule.getAtom(firstAtoms[counter - 1]).getAtomTypeName();
                    id1 = molecule.getAtom(nextAtomNr).getAtomTypeName();

                    if (molecule.getBond(molecule.getAtom(firstAtoms[counter - 1]), molecule.getAtom(nextAtomNr)) == null)
                        throw new CDKException("atoms do not form a chain, please use ModelBuilder3D");

                    distances[counter] = getBondLengthValue(id1, id2);
                    //logger.debug(" Distance:" + distances[counter]);
                    firstAtoms[counter] = nextAtomNr;
                    secondAtoms[counter] = firstAtoms[counter - 1];
                    if (counter > 1) {
                        id3 = molecule.getAtom(firstAtoms[counter - 2]).getAtomTypeName();
                        hybridisation = getHybridisationState(molecule.getAtom(firstAtoms[counter - 1]));
                        angles[counter] = getAngleValue(id1, id2, id3);
                        //Check if sp,sp2
                        if (angles[counter] == -1) {
                            if (hybridisation == 3) {
                                angles[counter] = DEFAULT_SP3_ANGLE;
                            } else if (hybridisation == 2) {
                                angles[counter] = DEFAULT_SP2_ANGLE;
                            } else if (hybridisation == 1) {
                                angles[counter] = DEFAULT_SP_ANGLE;
                            }
                        }
                        thirdAtoms[counter] = firstAtoms[counter - 2];
                        //logger.debug(" Angle:" + angles[counter]);
                    } else {
                        angles[counter] = -1;
                        thirdAtoms[counter] = -1;
                    }
                    if (counter > 2) {
                        //double bond
                        try {
                            if (getDoubleBondConfiguration2D(
                                    molecule.getBond(molecule.getAtom(firstAtoms[counter - 1]),
                                            molecule.getAtom(firstAtoms[counter - 2])),
                                    (molecule.getAtom(firstAtoms[counter])).getPoint2d(),
                                    (molecule.getAtom(firstAtoms[counter - 1])).getPoint2d(),
                                    (molecule.getAtom(firstAtoms[counter - 2])).getPoint2d(),
                                    (molecule.getAtom(firstAtoms[counter - 3])).getPoint2d()) == 5) {
                                dihedrals[counter] = DIHEDRAL_BRANCHED_CHAIN;
                            } else {
                                dihedrals[counter] = DIHEDRAL_EXTENDED_CHAIN;
                            }
                        } catch (CDKException ex1) {
                            dihedrals[counter] = DIHEDRAL_EXTENDED_CHAIN;
                        }
                    } else {
                        dihedrals[counter] = -1;
                    }
                    counter++;
                }
            }
        }
    }
74473
public void readBondBlock(IAtomContainer readData) throws CDKException {
        logger.info("Reading BOND block");
        boolean foundEND = false;
        while (isReady() && !foundEND) {
            String command = readCommand(readLine());
            if ("END BOND".equals(command)) {
                foundEND = true;
            } else {
                logger.debug("Parsing bond from: " + command);
                StringTokenizer tokenizer = new StringTokenizer(command);
                IBond bond = readData.getBuilder().newBond();
                // parse the index
                try {
                    String indexString = tokenizer.nextToken();
                    bond.setID(indexString);
                } catch (Exception exception) {
                    String error = "Error while parsing bond index";
                    logger.error(error);
                    logger.debug(exception);
                    throw new CDKException(error, exception);
                }
                // parse the order
                try {
                    String orderString = tokenizer.nextToken();
                    int order = Integer.parseInt(orderString);
                    if (order >= 4) {
                        logger.warn("Query order types are not supported (yet). File a bug if you need it");
                    } else {
                        bond.setOrder(BondManipulator.createBondOrder((double) order));
                    }
                } catch (Exception exception) {
                    String error = "Error while parsing bond index";
                    logger.error(error);
                    logger.debug(exception);
                    throw new CDKException(error, exception);
                }
                // parse index atom 1
                try {
                    String indexAtom1String = tokenizer.nextToken();
                    int indexAtom1 = Integer.parseInt(indexAtom1String);
                    IAtom atom1 = readData.getAtom(indexAtom1 - 1);
                    bond.setAtom(atom1, 0);
                } catch (Exception exception) {
                    String error = "Error while parsing index atom 1 in bond";
                    logger.error(error);
                    logger.debug(exception);
                    throw new CDKException(error, exception);
                }
                // parse index atom 2
                try {
                    String indexAtom2String = tokenizer.nextToken();
                    int indexAtom2 = Integer.parseInt(indexAtom2String);
                    IAtom atom2 = readData.getAtom(indexAtom2 - 1);
                    bond.setAtom(atom2, 1);
                } catch (Exception exception) {
                    String error = "Error while parsing index atom 2 in bond";
                    logger.error(error);
                    logger.debug(exception);
                    throw new CDKException(error, exception);
                }

                List<IAtom> endpts = new ArrayList<>();
                String attach = null;

                // the rest are key=value fields
                if (command.indexOf('=') != -1) {
                    Map<String, String> options = parseOptions(exhaustStringTokenizer(tokenizer));
                    for (String key : options.keySet()) {
                        String value = options.get(key);
                        try {
                            switch (key) {
                                case "CFG":
                                    int configuration = Integer.parseInt(value);
                                    if (configuration == 0) {
                                        bond.setStereo(IBond.Stereo.NONE);
                                    } else if (configuration == 1) {
                                        bond.setStereo(IBond.Stereo.UP);
                                    } else if (configuration == 2) {
                                        bond.setStereo((IBond.Stereo) CDKConstants.UNSET);
                                    } else if (configuration == 3) {
                                        bond.setStereo(IBond.Stereo.DOWN);
                                    }
                                    break;
                                case "ENDPTS":
                                    String[] endptStr = value.split(" ");
                                    // skip first value that is count
                                    for (int i = 1; i < endptStr.length; i++) {
                                        endpts.add(readData.getAtom(Integer.parseInt(endptStr[i]) - 1));
                                    }
                                    break;
                                case "ATTACH":
                                    attach = value;
                                    break;
                                default:
                                    logger.warn("Not parsing key: " + key);
                                    break;
                            }
                        } catch (Exception exception) {
                            String error = "Error while parsing key/value " + key + "=" + value + ": "
                                           + exception.getMessage();
                            logger.error(error);
                            logger.debug(exception);
                            throw new CDKException(error, exception);
                        }
                    }
                }

                // storing bond
                readData.addBond(bond);

                // storing positional variation
                if ("ANY".equals(attach)) {
                    Sgroup sgroup = new Sgroup();
                    sgroup.setType(SgroupType.ExtMulticenter);
                    sgroup.addAtom(bond.getBegin()); // could be other end?
                    sgroup.addBond(bond);
                    for (IAtom endpt : endpts)
                        sgroup.addAtom(endpt);

                    List<Sgroup> sgroups = readData.getProperty(CDKConstants.CTAB_SGROUPS);
                    if (sgroups == null)
                        readData.setProperty(CDKConstants.CTAB_SGROUPS, sgroups = new ArrayList<>(4));
                    sgroups.add(sgroup);
                }

                logger.debug("Added bond: " + bond);
            }
        }
    }
193638
public synchronized void sortResultsByFragments() {

        //        System.out.println("\nSort By Fragment");
        Map<Integer, Map<Integer, Integer>> allFragmentMCS = new TreeMap<Integer, Map<Integer, Integer>>();
        Map<Integer, Map<IAtom, IAtom>> allFragmentAtomMCS = new TreeMap<Integer, Map<IAtom, IAtom>>();

        Map<Integer, Double> stereoScoreMap = new TreeMap<Integer, Double>();
        Map<Integer, Double> energyScoreMap = new TreeMap<Integer, Double>();
        Map<Integer, Integer> fragmentScoreMap = new TreeMap<Integer, Integer>();

        initializeMaps(allFragmentMCS, allFragmentAtomMCS, stereoScoreMap, fragmentScoreMap, energyScoreMap);

        int minFragmentScore = 9999;
        for (Integer key : allFragmentAtomMCS.keySet()) {
            Map<IAtom, IAtom> mcsAtom = allFragmentAtomMCS.get(key);
            int fragmentCount = getMappedMoleculeFragmentSize(mcsAtom);
            fragmentScoreMap.put(key, fragmentCount);
            if (minFragmentScore > fragmentCount) {
                minFragmentScore = fragmentCount;
            }
        }
        boolean flag = false;
        if (minFragmentScore < 9999) {
            flag = true;
            clear();
        }
        int counter = 0;
        for (Map.Entry<Integer, Integer> map : fragmentScoreMap.entrySet()) {
            if (minFragmentScore == map.getValue().intValue()) {
                addSolution(counter, map.getKey(), allFragmentAtomMCS, allFragmentMCS, stereoScoreMap, energyScoreMap,
                        fragmentScoreMap);
                counter++;
                //                System.out.println("Fragment key " + map.getKey() + " Size: " + fragmentScoreMap.get(map.getKey()));
                //                System.out.println("Fragment MCS " + allFragmentMCS.get(map.getKey()) + " Stereo Value: "
                //                        + stereoScoreMap.get(map.getKey()));
            }
        }

        if (flag) {
            firstSolution.putAll(allMCS.get(0));
            firstAtomMCS.putAll(allAtomMCS.get(0));
            clear(allFragmentMCS, allFragmentAtomMCS, stereoScoreMap, fragmentScoreMap, energyScoreMap);
        }

    }
1371674
protected void fixupWithComparator(int k) {
        if (onMinLevel(k)) {
            int p = k / 2;
            K kValue = array[k];
            if (p > 0 && comparator.compare(array[p], kValue) < 0) {
                array[k] = array[p];
                array[p] = kValue;
                fixupMaxWithComparator(p);
            } else {
                fixupMinWithComparator(k);
            }
        } else {
            int p = k / 2;
            K kValue = array[k];
            if (p > 0 && comparator.compare(kValue, array[p]) < 0) {
                array[k] = array[p];
                array[p] = kValue;
                fixupMinWithComparator(p);
            } else {
                fixupMaxWithComparator(k);
            }
        }
    }
569434
private void searchAndPlaceBranches(IAtomContainer molecule, IAtomContainer chain, AtomPlacer3D ap3d,
            AtomTetrahedralLigandPlacer3D atlp3d, AtomPlacer atomPlacer) throws CDKException {
        //logger.debug("****** SEARCH AND PLACE ****** Chain length: "+chain.getAtomCount());
        List atoms = null;
        IAtomContainer branchAtoms = molecule.getBuilder().newInstance(IAtomContainer.class);
        IAtomContainer connectedAtoms = molecule.getBuilder().newInstance(IAtomContainer.class);
        for (int i = 0; i < chain.getAtomCount(); i++) {
            atoms = molecule.getConnectedAtomsList(chain.getAtom(i));
            for (int j = 0; j < atoms.size(); j++) {
                IAtom atom = (IAtom) atoms.get(j);
                if (!(atom.getSymbol()).equals("H") & !(atom.getFlag(CDKConstants.ISPLACED))
                        & !(atom.getFlag(CDKConstants.ISINRING))) {
                    //logger.debug("SEARCH PLACE AND FOUND Branch Atom "+molecule.indexOf(chain.getAtomAt(i))+
                    //		" New Atom:"+molecule.indexOf(atoms[j])+" -> STORE");
                    connectedAtoms.add(ap3d.getPlacedHeavyAtoms(molecule, chain.getAtom(i)));
                    //logger.debug("Connected atom1:"+molecule.indexOf(connectedAtoms.getAtomAt(0))+" atom2:"+
                    //molecule.indexOf(connectedAtoms.getAtomAt(1))+ " Length:"+connectedAtoms.getAtomCount());
                    try {
                        setBranchAtom(molecule, atom, chain.getAtom(i), connectedAtoms, ap3d, atlp3d);
                    } catch (CDKException ex2) {
                        logger.error("SearchAndPlaceBranchERROR: Cannot find enough neighbour atoms due to"
                                + ex2.toString());
                        throw new CDKException("SearchAndPlaceBranchERROR: Cannot find enough neighbour atoms: "
                                + ex2.getMessage(), ex2);
                    }
                    branchAtoms.addAtom(atom);
                    connectedAtoms.removeAllElements();
                }
            }

        }//for ac.getAtomCount
        placeLinearChains3D(molecule, branchAtoms, ap3d, atlp3d, atomPlacer);
    }
949296
@Override
    public void saturate(IAtomContainer atomContainer) throws CDKException {
        logger.info("Saturating atomContainer by adjusting bond orders...");
        boolean allSaturated = allSaturated(atomContainer);
        if (!allSaturated) {
            logger.info("Saturating bond orders is needed...");
            IBond[] bonds = new IBond[atomContainer.getBondCount()];
            for (int i = 0; i < bonds.length; i++)
                bonds[i] = atomContainer.getBond(i);
            boolean succeeded = saturate(bonds, atomContainer);
            if (!succeeded) {
                throw new CDKException("Could not saturate this atomContainer!");
            }
        }
    }
740327
void sortPrefixes() {
        if (whitelistPrefixesSet != null) {
            whitelistPrefixes = new ArrayList<>(whitelistPrefixesSet);
        }
        if (whitelistPrefixes != null) {
            CollectionUtils.sortIfNotEmpty(whitelistPrefixes);
        }
        if (blacklistPrefixes != null) {
            CollectionUtils.sortIfNotEmpty(blacklistPrefixes);
        }
    }
160518
@Override
    public void write(IChemObject object) throws CDKException {
        if (object instanceof IAtomContainerSet) {
            writeAtomContainerSet((IAtomContainerSet) object);
        } else if (object instanceof IAtomContainer) {
            writeAtomContainer((IAtomContainer) object);
        } else {
            throw new CDKException("Only supported is writing of ChemFile and Molecule objects.");
        }
    }
725771
public static double calculate(IAtomContainer molecule) throws CDKException {
        if (atomTypeList == null) {
            atomTypeList = AtomTypeFactory.getInstance("org/openscience/cdk/dict/data/cdk-atom-types.owl",
                    molecule.getBuilder() // take whatever we got first
                    );
        }

        double sum = 0.0;
        int totalHCount = 0;
        for (IAtom atom : molecule.atoms()) {
            Double bondiiVolume = bondiiVolumes.get(atom.getSymbol());
            if (bondiiVolume == null) throw new CDKException("Unsupported element.");

            sum += bondiiVolume;

            // add volumes of implicit hydrogens?
            IAtomType type = atomTypeList.getAtomType(atom.getAtomTypeName());
            if (type == null) throw new CDKException("Unknown atom type for atom: " + atom.getSymbol());
            if (type.getFormalNeighbourCount() == null)
                throw new CDKException("Formal neighbor count not given for : " + type.getAtomTypeName());
            int hCount = type.getFormalNeighbourCount() - molecule.getConnectedBondsCount(atom);
            sum += (hCount * bondiiVolumes.get("H"));
            totalHCount += hCount;
        }
        sum -= 5.92 * (molecule.getBondCount() + totalHCount);

        boolean[] originalFlags = molecule.getFlags();
        Aromaticity.cdkLegacy().apply(molecule);
        IRingSet ringSet = Cycles.sssr(molecule).toRingSet();
        if (ringSet.getAtomContainerCount() > 0) {
            int aromRingCount = 0;
            int nonAromRingCount = 0;
            for (IAtomContainer ring : ringSet.atomContainers()) {
                if (ringIsAromatic(ring)) {
                    aromRingCount++;
                } else {
                    nonAromRingCount++;
                }
            }
            molecule.setFlags(originalFlags);
            sum -= 14.7 * aromRingCount;
            sum -= 3.8 * nonAromRingCount;
        }

        return sum;
    }
246668
private void setActiveCenters(IAtomContainer reactant) throws CDKException {
        Iterator<IBond> bonds = reactant.bonds().iterator();
        while (bonds.hasNext()) {
            IBond bondi = bonds.next();
            IAtom atom1 = bondi.getBegin();
            IAtom atom2 = bondi.getEnd();
            if (bondi.getOrder() == IBond.Order.SINGLE
                    && (atom1.getFormalCharge() == CDKConstants.UNSET ? 0 : atom1.getFormalCharge()) == 0
                    && (atom2.getFormalCharge() == CDKConstants.UNSET ? 0 : atom2.getFormalCharge()) == 0
                    && reactant.getConnectedSingleElectronsCount(atom1) == 0
                    && reactant.getConnectedSingleElectronsCount(atom2) == 0) {
                bondi.setFlag(CDKConstants.REACTIVE_CENTER, true);
                atom1.setFlag(CDKConstants.REACTIVE_CENTER, true);
                atom2.setFlag(CDKConstants.REACTIVE_CENTER, true);
            }
        }
    }
388773
def sort_nts(self, nt_list, codekey):
        """"""
        # Problem is that some members in the nt_list do NOT have
        # codekey=EvidenceCode, then it returns None, which breaks py34 and 35
        # The fix here is that for these members, default to -1 (is this valid?)
        sortby = lambda nt: self.ev2idx.get(getattr(nt, codekey), -1)
        return sorted(nt_list, key=sortby)
131446
def sort_permutations(permutations, user_deps)
      # Cache for versions converted to Gem::Version instances
      versions = {}

      map = lambda do |m, p|
        if p =~ Lyp::PACKAGE_RE
          m[$1] = versions[p] ||= (Lyp.version($2 || '0.0') rescue nil)
        end
        m
      end

      compare = lambda do |x, y|
        x_versions = x.inject({}, &map)
        y_versions = y.inject({}, &map)

        # If the dependency is direct (not transitive), just compare its versions.
        # Otherwise, add the result of comparison to score.
        x_versions.inject(0) do |score, kv|
          package = kv[0]
          cmp = kv[1] <=> y_versions[package]
          if user_deps.include?(package) && cmp != 0
            return cmp
          else
            score += cmp unless cmp.nil?
          end
          score
        end
      end

      permutations.sort(&compare)
    end
1225560
public static <S> int findIndexOfBestSolution(List<S> solutionList, Comparator<S> comparator) {
    if (solutionList == null) {
      throw new NullSolutionListException();
    } else if (solutionList.isEmpty()) {
      throw new EmptySolutionListException();
    } else if (comparator == null) {
      throw new JMetalException("The comparator is null");
    }

    int index = 0;
    S bestKnown = solutionList.get(0);
    S candidateSolution;

    int flag;
    for (int i = 1; i < solutionList.size(); i++) {
      candidateSolution = solutionList.get(i);
      flag = comparator.compare(bestKnown, candidateSolution);
      if (flag == 1) {
        index = i;
        bestKnown = candidateSolution;
      }
    }

    return index;
  }