Example usage for java.util HashSet addAll

List of usage examples for java.util HashSet addAll

Introduction

In this page you can find the example usage for java.util HashSet addAll.

Prototype

boolean addAll(Collection<? extends E> c);

Source Link

Document

Adds all of the elements in the specified collection to this set if they're not already present (optional operation).

Usage

From source file:cc.flydev.launcher.Workspace.java

void removeItemsByPackageName(final ArrayList<String> packages) {
    final HashSet<String> packageNames = new HashSet<String>();
    packageNames.addAll(packages);

    // Filter out all the ItemInfos that this is going to affect
    final HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
    final HashSet<ComponentName> cns = new HashSet<ComponentName>();
    ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts();
    for (CellLayout layoutParent : cellLayouts) {
        ViewGroup layout = layoutParent.getShortcutsAndWidgets();
        int childCount = layout.getChildCount();
        for (int i = 0; i < childCount; ++i) {
            View view = layout.getChildAt(i);
            infos.add((ItemInfo) view.getTag());
        }//from   w w  w  .  j a v  a2 s.  co m
    }
    LauncherModel.ItemInfoFilter filter = new LauncherModel.ItemInfoFilter() {
        @Override
        public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
            if (packageNames.contains(cn.getPackageName())) {
                cns.add(cn);
                return true;
            }
            return false;
        }
    };
    LauncherModel.filterItemInfos(infos, filter);

    // Remove the affected components
    removeItemsByComponentName(cns);
}

From source file:com.klinker.android.launcher.launcher3.Workspace.java

public void disableShortcutsByPackageName(final ArrayList<String> packages, final UserHandleCompat user,
        final int reason) {
    final HashSet<String> packageNames = new HashSet<String>();
    packageNames.addAll(packages);

    mapOverItems(MAP_RECURSE, new ItemOperator() {
        @Override/*from www  . j a v a 2  s  . co m*/
        public boolean evaluate(ItemInfo info, View v, View parent) {
            if (info instanceof ShortcutInfo && v instanceof BubbleTextView) {
                ShortcutInfo shortcutInfo = (ShortcutInfo) info;
                ComponentName cn = shortcutInfo.getTargetComponent();
                if (user.equals(shortcutInfo.user) && cn != null
                        && packageNames.contains(cn.getPackageName())) {
                    shortcutInfo.isDisabled |= reason;
                    BubbleTextView shortcut = (BubbleTextView) v;
                    shortcut.applyFromShortcutInfo(shortcutInfo, mIconCache);

                    if (parent != null) {
                        parent.invalidate();
                    }
                }
            }
            // process all the shortcuts
            return false;
        }
    });
}

From source file:com.aidy.launcher3.ui.workspace.Workspace.java

public void removeItemsByPackageName(final ArrayList<String> packages) {
    final HashSet<String> packageNames = new HashSet<String>();
    packageNames.addAll(packages);

    // Filter out all the ItemInfos that this is going to affect
    final HashSet<ItemInfoBean> infos = new HashSet<ItemInfoBean>();
    final HashSet<ComponentName> cns = new HashSet<ComponentName>();
    ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts();
    for (CellLayout layoutParent : cellLayouts) {
        ViewGroup layout = layoutParent.getShortcutsAndWidgets();
        int childCount = layout.getChildCount();
        for (int i = 0; i < childCount; ++i) {
            View view = layout.getChildAt(i);
            infos.add((ItemInfoBean) view.getTag());
        }//from ww  w .j  a  v a  2  s .  c  o  m
    }
    LauncherModel.ItemInfoFilter filter = new LauncherModel.ItemInfoFilter() {
        @Override
        public boolean filterItem(ItemInfoBean parent, ItemInfoBean info, ComponentName cn) {
            if (packageNames.contains(cn.getPackageName())) {
                cns.add(cn);
                return true;
            }
            return false;
        }
    };
    LauncherModel.filterItemInfos(infos, filter);

    // Remove the affected components
    removeItemsByComponentName(cns);
}

From source file:gedi.riboseq.inference.orf.OrfFinder.java

/**
 * Coordinates are in codonsRegion space!
 * @param index//from w w w.  ja  v  a  2 s .  co  m
 * @param sequence
 * @param sg
 * @param codonsRegion
 * @return
 */
public ArrayList<OrfWithCodons> findOrfs(int index, String sequence, SpliceGraph sg,
        ImmutableReferenceGenomicRegion<IntervalTreeSet<Codon>> codonsRegion) {
    SimpleDirectedGraph<Codon> fg = new SimpleDirectedGraph<Codon>("Codongraph");

    //      if (!codonsRegion.getReference().toString().equals("chr4+") || !codonsRegion.getRegion().contains(140_283_087))
    //         return 0;

    LeftMostInFrameAndClearList buff = new LeftMostInFrameAndClearList();

    IntervalTreeSet<Codon> codons = codonsRegion.getData();
    codons.removeIf(c -> c.getTotalActivity() < minCodonActivity);
    if (codons.size() == 0)
        return new ArrayList<OrfWithCodons>();

    // add stop codons for easy orf inference
    HashSet<Codon> stopCodons = new HashSet<Codon>();
    Trie<String> stop = new Trie<String>();
    stop.put("TAG", "TAG");
    stop.put("TGA", "TGA");
    stop.put("TAA", "TAA");
    stop.iterateAhoCorasick(sequence)
            .map(r -> new Codon(new ArrayGenomicRegion(r.getStart(), r.getEnd()), r.getValue()))
            .toCollection(stopCodons);

    for (Intron intr : sg.iterateIntrons().loop()) {
        ArrayGenomicRegion reg = new ArrayGenomicRegion(intr.getStart() - 2, intr.getStart(), intr.getEnd(),
                intr.getEnd() + 1);
        String cod = stop.get(SequenceUtils.extractSequence(reg, sequence));
        if (cod != null)
            stopCodons.add(new Codon(reg, cod));

        reg = new ArrayGenomicRegion(intr.getStart() - 1, intr.getStart(), intr.getEnd(), intr.getEnd() + 2);
        cod = stop.get(SequenceUtils.extractSequence(reg, sequence));
        if (cod != null)
            stopCodons.add(new Codon(reg, cod));
    }
    stopCodons.removeAll(codons);
    codons.addAll(stopCodons);

    ArrayList<OrfWithCodons> re = new ArrayList<OrfWithCodons>();
    HashSet<Codon> usedForAnno = new HashSet<Codon>();

    if (assembleAnnotationFirst) {
        // new: first use annotated transcripts in a greedy fashion
        ArrayList<ImmutableReferenceGenomicRegion<Transcript>> transcripts = annotation.ei(codonsRegion)
                .filter(t -> t.getData().isCoding()).map(t -> codonsRegion.induce(t, "T")).list();

        int acount = 0;
        LinkedList<OrfWithCodons> orfs = new LinkedList<OrfWithCodons>();
        GenomicRegion best;
        HashSet<Codon> aremoved = new HashSet<Codon>();

        do {
            best = null;
            double bestSum = 0;
            for (ImmutableReferenceGenomicRegion<Transcript> tr : transcripts) {
                double[] a = new double[tr.getRegion().getTotalLength()];
                for (Codon c : codons) {
                    if (tr.getRegion().containsUnspliced(c)) {
                        int p = tr.induce(c.getStart());

                        assert a[p] == 0;

                        if (!aremoved.contains(c))
                            a[p] = c.totalActivity;
                        if (c.isStop())
                            a[p] = -1;
                    }
                }
                for (int f = 0; f < 3; f++) {
                    int s = -1;
                    double sum = 0;

                    for (int p = f; p < a.length; p += 3) {
                        if (a[p] == -1) {//stop
                            if (sum > bestSum) {
                                bestSum = sum;
                                best = tr.getRegion().map(new ArrayGenomicRegion(s, p + 3));
                            }
                            s = -1;
                            sum = 0;
                        } else
                            sum += a[p];

                        if (a[p] > 0 && s == -1)
                            s = p;
                    }
                }
            }
            if (best != null) {
                ArrayList<Codon> cods = new ArrayList<>();
                int uniqueCodons = 0;
                double uniqueActivity = 0;
                double totalActivity = 0;

                for (Codon c : codons) {
                    if (best.containsUnspliced(c) && best.induce(c.getStart()) % 3 == 0) {
                        if (aremoved.add(c)) {
                            uniqueActivity += c.totalActivity;
                            uniqueCodons++;
                        }
                        totalActivity += c.totalActivity;
                        if (c.totalActivity > 0)
                            cods.add(c);
                    }
                }
                //                  System.out.println(codonsRegion.map(best));
                if ((uniqueCodons >= minUniqueCodons || uniqueCodons == cods.size())
                        && uniqueActivity > minUniqueActivity && totalActivity > minOrfTotalActivity) {

                    Collections.sort(cods);
                    usedForAnno.addAll(cods);

                    OrfWithCodons orf = new OrfWithCodons(index, 0, acount++, best.toArrayGenomicRegion(), cods,
                            true);
                    orfs.add(orf);
                }

            }
        } while (best != null);

        if (orfs.size() > 1) {

            // they are not necessarily connected!
            LinkedList<OrfWithCodons>[] connected = findConnectedOrfs(orfs);
            orfs.clear();

            for (LinkedList<OrfWithCodons> corfs : connected) {
                for (boolean changed = true; changed && corfs.size() > 1;) {
                    changed = false;

                    if (useEM)
                        inferOverlappingOrfActivitiesEM(corfs);
                    else
                        overlapUniqueCoverage(corfs);

                    Iterator<OrfWithCodons> it = corfs.iterator();
                    while (it.hasNext()) {
                        OrfWithCodons orf = it.next();
                        if (orf.getEstimatedTotalActivity() < minOrfTotalActivity) {
                            it.remove();
                            changed = true;
                        }
                    }
                }

                if (corfs.size() > 1)
                    distributeCodons(corfs);
                orfs.addAll(corfs);
            }
        }
        re.addAll(orfs);
    }

    // as edges only are represented in the splice graph, singleton codons are discarded (which does make sense anyway)
    for (Codon c : codons) {
        if (!c.isStop()) {
            // find unspliced successors (can be more than one, when the successor codon itself is spliced! all of them have the same start!)
            int max = c.getEnd() + maxAminoDist * 3;
            for (Codon n : codons
                    .getIntervalsIntersecting(c.getEnd(), c.getEnd() + maxAminoDist * 3, buff.startAndClear(c))
                    .get()) {
                if (!containsInframeStop(sequence.substring(c.getEnd(), n.getStart())))
                    fg.addInteraction(c, n);
                max = n.getStart() + 2;
            }

            // find all spliced successors for each splice junction that comes before n or maxAminoDist
            sg.forEachIntronStartingBetween(c.getEnd(), max + 1, intron -> {
                for (Codon n : codons.getIntervalsIntersecting(intron.getEnd(),
                        intron.getEnd() + maxAminoDist * 3 - (intron.getStart() - c.getEnd()),
                        buff.startAndClear(c, intron)).get())
                    if (!containsInframeStop(SequenceUtils.extractSequence(new ArrayGenomicRegion(c.getStart(),
                            intron.getStart(), intron.getEnd(), n.getStart()), sequence)))
                        fg.addInteraction(c, n, intron);
            });
        }
    }

    int cc = 1;
    for (SimpleDirectedGraph<Codon> g : fg.getWeaklyConnectedComponents()) {
        if (EI.wrap(g.getSources()).mapToDouble(c -> c.getTotalActivity()).sum() == 0)
            continue;

        // iterate longest paths in g
        LinkedList<Codon> topo = g.getTopologicalOrder();
        HashSet<Codon> remInTopo = new HashSet<Codon>(topo);
        remInTopo.removeIf(c -> !stopCodons.contains(c) && !usedForAnno.contains(c));
        HashSet<Codon> removed = new HashSet<Codon>(remInTopo);

        //         double maxPathScore = 0;

        LinkedList<OrfWithCodons> orfs = new LinkedList<OrfWithCodons>();

        int count = 0;
        while (removed.size() < topo.size()) {
            HashMap<Codon, MutablePair<GenomicRegion, Double>> longestPrefixes = new HashMap<Codon, MutablePair<GenomicRegion, Double>>();
            for (Codon c : topo)
                longestPrefixes.put(c, new MutablePair<GenomicRegion, Double>(c,
                        removed.contains(c) ? 0 : (c.getTotalActivity())));

            Codon longestEnd = null;
            HashMap<Codon, Codon> backtracking = new HashMap<Codon, Codon>();

            for (Codon c : topo) {
                //               if (codonsRegion.map(c).getStart()==100_466_118)
                //                  System.out.println(c);
                //               
                //               if (codonsRegion.map(c).getStart()==100_465_842)
                //                  System.out.println(c);

                double len = longestPrefixes.get(c).Item2;
                for (AdjacencyNode<Codon> n = g.getTargets(c); n != null; n = n.next) {
                    MutablePair<GenomicRegion, Double> pref = longestPrefixes.get(n.node);

                    double nnact = removed.contains(n.node) ? 0 : (n.node.getTotalActivity());
                    if (pref.Item2 <= len + nnact) {
                        pref.set(extendFullPath(longestPrefixes.get(c).Item1, c, n.node, n.getLabel()),
                                len + nnact);
                        backtracking.put(n.node, c);
                    }
                }
                if (longestEnd == null || longestPrefixes.get(longestEnd).Item2 <= len)
                    longestEnd = c;

            }

            // determine longest path by backtracking and mark all codons on the path as removed
            ArrayList<Codon> orfCodons = new ArrayList<Codon>();
            double totalActivity = 0;
            double uniqueActivity = 0;
            int uniqueCodons = 0;
            for (Codon c = longestEnd; c != null; c = backtracking.get(c)) {
                if (removed.add(c) && c.getTotalActivity() > 0) {
                    uniqueCodons++;
                    uniqueActivity += c.getTotalActivity();
                }

                if (c.getTotalActivity() > 0) // to remove dummy stop codons
                    orfCodons.add(c);
                totalActivity += c.getTotalActivity();
            }

            //            System.out.println(codonsRegion.map(longestPrefixes.get(longestEnd).Item1));

            if ((uniqueCodons >= minUniqueCodons || uniqueCodons == orfCodons.size())
                    && uniqueActivity > minUniqueActivity && totalActivity > minOrfTotalActivity) {
                Collections.reverse(orfCodons);

                MutablePair<GenomicRegion, Double> triple = longestPrefixes.get(longestEnd);
                ArrayGenomicRegion region = triple.Item1.toArrayGenomicRegion();
                String lastCodon = SequenceUtils.extractSequence(
                        region.map(
                                new ArrayGenomicRegion(region.getTotalLength() - 3, region.getTotalLength())),
                        sequence);

                OrfWithCodons orf = new OrfWithCodons(index, cc, count++, region, orfCodons,
                        stop.containsKey(lastCodon));
                orfs.add(orf);
            }

            //            maxPathScore = Math.max(maxPathScore,totalActivity);
        }

        if (orfs.size() > 1) {

            // they are not necessarily connected!

            LinkedList<OrfWithCodons>[] connected = findConnectedOrfs(orfs);
            orfs.clear();

            for (LinkedList<OrfWithCodons> corfs : connected) {
                for (boolean changed = true; changed && corfs.size() > 1;) {
                    changed = false;

                    if (useEM)
                        inferOverlappingOrfActivitiesEM(corfs);
                    else
                        overlapUniqueCoverage(corfs);

                    Iterator<OrfWithCodons> it = corfs.iterator();
                    while (it.hasNext()) {
                        OrfWithCodons orf = it.next();
                        if (orf.getEstimatedTotalActivity() < minOrfTotalActivity) {
                            it.remove();
                            changed = true;
                        }
                    }
                }

                if (corfs.size() > 1)
                    distributeCodons(corfs);
                orfs.addAll(corfs);
            }

        }

        re.addAll(orfs);

        cc++;
    }

    return re;

}

From source file:imitationNLG.SFX.java

public Double evaluateGeneration(HashMap<String, JAROW> classifierAttrs,
        HashMap<String, HashMap<String, JAROW>> classifierWords, ArrayList<DatasetInstance> trainingData,
        ArrayList<DatasetInstance> testingData, HashMap<String, HashSet<String>> availableAttributeActions,
        HashMap<String, HashMap<String, HashSet<Action>>> availableWordActions,
        HashMap<Integer, HashSet<String>> nGrams, boolean printResults, int epoch) {
    System.out.println("Evaluate argument generation ");

    int totalArgDistance = 0;
    ArrayList<ScoredFeaturizedTranslation<IString, String>> generations = new ArrayList<>();
    ArrayList<ArrayList<Action>> generationActions = new ArrayList<>();
    HashMap<ArrayList<Action>, DatasetInstance> generationActionsMap = new HashMap<>();
    ArrayList<ArrayList<Sequence<IString>>> finalReferences = new ArrayList<>();
    ArrayList<String> predictedStrings = new ArrayList<>();
    ArrayList<String> predictedStringMRs = new ArrayList<>();
    ArrayList<Double> attrCoverage = new ArrayList<>();
    ArrayList<ArrayList<String>> predictedAttrLists = new ArrayList<>();
    HashSet<HashMap<String, HashSet<String>>> mentionedAttrs = new HashSet<HashMap<String, HashSet<String>>>();
    for (DatasetInstance di : testingData) {
        String predicate = di.getMeaningRepresentation().getPredicate();
        ArrayList<Action> predictedActionList = new ArrayList<>();
        ArrayList<Action> predictedWordList = new ArrayList<>();

        //PHRASE GENERATION EVALUATION
        String predictedAttr = "";
        ArrayList<String> predictedAttrValues = new ArrayList<>();
        ArrayList<String> predictedAttributes = new ArrayList<>();

        HashSet<String> attrValuesToBeMentioned = new HashSet<>();
        HashSet<String> attrValuesAlreadyMentioned = new HashSet<>();
        HashMap<String, ArrayList<String>> valuesToBeMentioned = new HashMap<>();
        for (String attribute : di.getMeaningRepresentation().getAttributes().keySet()) {
            for (String value : di.getMeaningRepresentation().getAttributes().get(attribute)) {
                attrValuesToBeMentioned.add(attribute.toLowerCase() + "=" + value.toLowerCase());
            }/*from  w  w w.j a  v a2s. co m*/
            valuesToBeMentioned.put(attribute,
                    new ArrayList<>(di.getMeaningRepresentation().getAttributes().get(attribute)));
        }
        if (attrValuesToBeMentioned.isEmpty()) {
            attrValuesToBeMentioned.add("empty=empty");
        }
        HashSet<String> attrValuesToBeMentionedCopy = new HashSet<>(attrValuesToBeMentioned);
        while (!predictedAttr.equals(SFX.TOKEN_END) && predictedAttrValues.size() < maxAttrRealizationSize) {
            if (!predictedAttr.isEmpty()) {
                attrValuesToBeMentioned.remove(predictedAttr);
            }
            Instance attrTrainingVector = SFX.this.createAttrInstance(predicate, "@TOK@", predictedAttrValues,
                    predictedActionList, attrValuesAlreadyMentioned, attrValuesToBeMentioned,
                    di.getMeaningRepresentation(), availableAttributeActions);

            if (attrTrainingVector != null) {
                Prediction predictAttr = classifierAttrs.get(predicate).predict(attrTrainingVector);
                if (predictAttr.getLabel() != null) {
                    predictedAttr = predictAttr.getLabel().trim();
                    String predictedValue = "";
                    if (!predictedAttr.equals(SFX.TOKEN_END)) {
                        predictedValue = chooseNextValue(predictedAttr, attrValuesToBeMentioned, trainingData);

                        HashSet<String> rejectedAttrs = new HashSet<String>();
                        while (predictedValue.isEmpty() && !predictedAttr.equals(SFX.TOKEN_END)) {
                            rejectedAttrs.add(predictedAttr);

                            predictedAttr = SFX.TOKEN_END;
                            double maxScore = -Double.MAX_VALUE;
                            for (String attr : predictAttr.getLabel2Score().keySet()) {
                                if (!rejectedAttrs.contains(attr) && (Double
                                        .compare(predictAttr.getLabel2Score().get(attr), maxScore) > 0)) {
                                    maxScore = predictAttr.getLabel2Score().get(attr);
                                    predictedAttr = attr;
                                }
                            }
                            if (!predictedAttr.equals(SFX.TOKEN_END)) {
                                predictedValue = chooseNextValue(predictedAttr, attrValuesToBeMentioned,
                                        trainingData);
                            }
                        }
                    }
                    if (!predictedAttr.equals(SFX.TOKEN_END)) {
                        predictedAttr += "=" + predictedValue;
                    }
                    predictedAttrValues.add(predictedAttr);

                    String attribute = predictedAttrValues.get(predictedAttrValues.size() - 1).split("=")[0];
                    String attrValue = predictedAttrValues.get(predictedAttrValues.size() - 1);
                    predictedAttributes.add(attrValue);

                    //GENERATE PHRASES
                    if (!attribute.equals(SFX.TOKEN_END)) {
                        if (classifierWords.get(predicate).containsKey(attribute)) {
                            String predictedWord = "";

                            boolean isValueMentioned = false;
                            String valueTBM = "";
                            if (attrValue.contains("=")) {
                                valueTBM = attrValue.substring(attrValue.indexOf('=') + 1);
                            }
                            if (valueTBM.isEmpty()) {
                                isValueMentioned = true;
                            }
                            ArrayList<String> subPhrase = new ArrayList<>();
                            while (!predictedWord.equals(RoboCup.TOKEN_END)
                                    && predictedWordList.size() < maxWordRealizationSize) {
                                ArrayList<String> predictedAttributesForInstance = new ArrayList<>();
                                for (int i = 0; i < predictedAttributes.size() - 1; i++) {
                                    predictedAttributesForInstance.add(predictedAttributes.get(i));
                                }
                                if (!predictedAttributes.get(predictedAttributes.size() - 1)
                                        .equals(attrValue)) {
                                    predictedAttributesForInstance
                                            .add(predictedAttributes.get(predictedAttributes.size() - 1));
                                }
                                Instance wordTrainingVector = createWordInstance(predicate,
                                        new Action("@TOK@", attrValue), predictedAttributesForInstance,
                                        predictedActionList, isValueMentioned, attrValuesAlreadyMentioned,
                                        attrValuesToBeMentioned, di.getMeaningRepresentation(),
                                        availableWordActions.get(predicate), nGrams, false);

                                if (wordTrainingVector != null) {
                                    if (classifierWords.get(predicate) != null) {
                                        if (classifierWords.get(predicate).get(attribute) != null) {
                                            Prediction predictWord = classifierWords.get(predicate)
                                                    .get(attribute).predict(wordTrainingVector);
                                            if (predictWord.getLabel() != null) {
                                                predictedWord = predictWord.getLabel().trim();
                                                predictedActionList.add(new Action(predictedWord, attrValue));
                                                if (!predictedWord.equals(SFX.TOKEN_END)) {
                                                    subPhrase.add(predictedWord);
                                                    predictedWordList.add(new Action(predictedWord, attrValue));
                                                }
                                            } else {
                                                predictedWord = SFX.TOKEN_END;
                                                predictedActionList.add(new Action(predictedWord, attrValue));
                                            }
                                        } else {
                                            predictedWord = SFX.TOKEN_END;
                                            predictedActionList.add(new Action(predictedWord, attrValue));
                                        }
                                    }
                                }
                                if (!isValueMentioned) {
                                    if (!predictedWord.equals(SFX.TOKEN_END)) {
                                        if (predictedWord.startsWith(SFX.TOKEN_X)
                                                && (valueTBM.matches("\"[xX][0-9]+\"")
                                                        || valueTBM.matches("[xX][0-9]+")
                                                        || valueTBM.startsWith(SFX.TOKEN_X))) {
                                            isValueMentioned = true;
                                        } else if (!predictedWord.startsWith(SFX.TOKEN_X)
                                                && !(valueTBM.matches("\"[xX][0-9]+\"")
                                                        || valueTBM.matches("[xX][0-9]+")
                                                        || valueTBM.startsWith(SFX.TOKEN_X))) {
                                            String valueToCheck = valueTBM;
                                            if (valueToCheck.equals("no") || valueToCheck.equals("yes")
                                                    || valueToCheck.equals("yes or no")
                                                    || valueToCheck.equals("none")
                                                    || valueToCheck.equals("dont_care")
                                                    || valueToCheck.equals("empty")) {
                                                if (attribute.contains("=")) {
                                                    valueToCheck = attribute.replace("=", ":");
                                                } else {
                                                    valueToCheck = attribute + ":" + valueTBM;
                                                }
                                            }
                                            if (!valueToCheck.equals("empty:empty")
                                                    && valueAlignments.containsKey(valueToCheck)) {
                                                for (ArrayList<String> alignedStr : valueAlignments
                                                        .get(valueToCheck).keySet()) {
                                                    if (endsWith(subPhrase, alignedStr)) {
                                                        isValueMentioned = true;
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    if (isValueMentioned) {
                                        attrValuesAlreadyMentioned.add(attrValue);
                                        attrValuesToBeMentioned.remove(attrValue);
                                    }
                                }
                                String mentionedAttrValue = "";
                                if (!predictedWord.startsWith(SFX.TOKEN_X)) {
                                    for (String attrValueTBM : attrValuesToBeMentioned) {
                                        if (attrValueTBM.contains("=")) {
                                            String value = attrValueTBM
                                                    .substring(attrValueTBM.indexOf('=') + 1);
                                            if (!(value.matches("\"[xX][0-9]+\"") || value.matches("[xX][0-9]+")
                                                    || value.startsWith(SFX.TOKEN_X))) {
                                                String valueToCheck = value;
                                                if (valueToCheck.equals("no") || valueToCheck.equals("yes")
                                                        || valueToCheck.equals("yes or no")
                                                        || valueToCheck.equals("none")
                                                        || valueToCheck.equals("dont_care")
                                                        || valueToCheck.equals("empty")) {
                                                    valueToCheck = attrValueTBM.replace("=", ":");
                                                }
                                                if (!valueToCheck.equals("empty:empty")
                                                        && valueAlignments.containsKey(valueToCheck)) {
                                                    for (ArrayList<String> alignedStr : valueAlignments
                                                            .get(valueToCheck).keySet()) {
                                                        if (endsWith(subPhrase, alignedStr)) {
                                                            mentionedAttrValue = attrValueTBM;
                                                            break;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                if (!mentionedAttrValue.isEmpty()) {
                                    attrValuesAlreadyMentioned.add(attrValue);
                                    attrValuesToBeMentioned.remove(mentionedAttrValue);
                                }
                            }
                            if (predictedWordList.size() >= maxWordRealizationSize && !predictedActionList
                                    .get(predictedActionList.size() - 1).getWord().equals(SFX.TOKEN_END)) {
                                predictedWord = SFX.TOKEN_END;
                                predictedActionList.add(new Action(predictedWord,
                                        predictedAttrValues.get(predictedAttrValues.size() - 1)));
                            }
                        } else {
                            String predictedWord = SFX.TOKEN_END;
                            predictedActionList.add(new Action(predictedWord, attrValue));
                        }
                    }
                } else {
                    predictedAttr = SFX.TOKEN_END;
                }
            }
        }
        ArrayList<String> predictedAttrs = new ArrayList<>();
        for (String attributeValuePair : predictedAttrValues) {
            predictedAttrs.add(attributeValuePair.split("=")[0]);
        }

        ArrayList<Action> cleanActionList = new ArrayList<Action>();
        for (Action action : predictedActionList) {
            if (!action.getWord().equals(SFX.TOKEN_END) && !action.getWord().equals(SFX.TOKEN_START)) {
                cleanActionList.add(action);
            }
        }
        for (int i = 0; i < cleanActionList.size(); i++) {
            for (ArrayList<Action> surrounds : punctPatterns.keySet()) {
                boolean matches = true;
                int m = 0;
                for (int s = 0; s < surrounds.size(); s++) {
                    if (surrounds.get(s) != null) {
                        if (i + s < cleanActionList.size()) {
                            if (!cleanActionList.get(i + s).getWord().equals(surrounds.get(s)
                                    .getWord()) /*|| !cleanActionList.get(i).getAttribute().equals(surrounds.get(s).getAttribute())*/) {
                                matches = false;
                                s = surrounds.size();
                            } else {
                                m++;
                            }
                        } else {
                            matches = false;
                            s = surrounds.size();
                        }
                    }
                }
                if (matches && m > 0) {
                    cleanActionList.add(i + 2, punctPatterns.get(surrounds));
                }
            }
        }

        String predictedString = "";
        ArrayList<String> predictedAttrList = new ArrayList<String>();
        HashSet<String> redundants = new HashSet<String>();
        for (Action action : cleanActionList) {
            if (action.getWord().startsWith(SFX.TOKEN_X)) {
                predictedString += di.getMeaningRepresentation().getDelexMap().get(action.getWord()) + " ";
                //predictedString += "x ";
                if (di.getMeaningRepresentation().getDelexMap().get(action.getWord()) == null
                        || di.getMeaningRepresentation().getDelexMap().get(action.getWord()).equals("null")) {
                    redundants.add(action.getWord());
                }
            } else {
                predictedString += action.getWord() + " ";
            }
            if (predictedAttrList.isEmpty()) {
                predictedAttrList.add(action.getAttribute());
            } else if (!predictedAttrList.get(predictedAttrList.size() - 1).equals(action.getAttribute())) {
                predictedAttrList.add(action.getAttribute());
            }
        }
        predictedAttrLists.add(predictedAttrList);
        if (attrValuesToBeMentionedCopy.size() != 0.0) {
            double redundAttrs = 0.0;
            double missingAttrs = 0.0;
            for (String attr : predictedAttrList) {
                if (!attrValuesToBeMentionedCopy.contains(attr)) {
                    redundAttrs += 1.0;
                }
            }
            for (String attr : attrValuesToBeMentionedCopy) {
                if (!predictedAttrList.contains(attr)) {
                    missingAttrs += 1.0;
                }
            }
            double attrSize = (double) attrValuesToBeMentionedCopy.size();
            attrCoverage.add((redundAttrs + missingAttrs) / attrSize);
        }

        if (predicate.startsWith("?")) {
            predictedString = predictedString.trim() + "?";
        } else {
            predictedString = predictedString.trim() + ".";
        }
        predictedString = predictedString.replaceAll("\\?", " \\? ").replaceAll(":", " : ")
                .replaceAll("\\.", " \\. ").replaceAll(",", " , ").replaceAll("  ", " ").trim();

        if (!mentionedAttrs.contains(di.getMeaningRepresentation().getAttributes())) {
            predictedStrings.add(predictedString);
            predictedStringMRs.add(di.getMeaningRepresentation().getMRstr());
            mentionedAttrs.add(di.getMeaningRepresentation().getAttributes());
        }

        Sequence<IString> translation = IStrings
                .tokenize(NISTTokenizer.tokenize(predictedString.toLowerCase()));
        ScoredFeaturizedTranslation<IString, String> tran = new ScoredFeaturizedTranslation<>(translation, null,
                0);
        generations.add(tran);
        generationActions.add(predictedActionList);
        generationActionsMap.put(predictedActionList, di);

        ArrayList<Sequence<IString>> references = new ArrayList<>();
        for (ArrayList<Action> realization : di.getEvalRealizations()) {
            String cleanedWords = "";
            for (Action nlWord : realization) {
                if (!nlWord.equals(new Action(SFX.TOKEN_START, ""))
                        && !nlWord.equals(new Action(SFX.TOKEN_END, ""))) {
                    if (nlWord.getWord().startsWith(SFX.TOKEN_X)) {
                        cleanedWords += di.getMeaningRepresentation().getDelexMap().get(nlWord.getWord()) + " ";
                    } else {
                        cleanedWords += nlWord.getWord() + " ";
                    }
                }
            }
            cleanedWords = cleanedWords.trim();
            if (!cleanedWords.endsWith(".")) {
                cleanedWords += ".";
            }
            cleanedWords = cleanedWords.replaceAll("\\?", " \\? ").replaceAll(":", " : ")
                    .replaceAll("\\.", " \\. ").replaceAll(",", " , ").replaceAll("  ", " ").trim();
            references.add(IStrings.tokenize(NISTTokenizer.tokenize(cleanedWords)));
        }
        finalReferences.add(references);

        //EVALUATE ATTRIBUTE SEQUENCE
        HashSet<ArrayList<String>> goldAttributeSequences = new HashSet<>();
        for (DatasetInstance di2 : testingData) {
            if (di2.getMeaningRepresentation().getAttributes()
                    .equals(di.getMeaningRepresentation().getAttributes())) {
                goldAttributeSequences.addAll(di2.getEvalMentionedAttributeSequences().values());
            }
        }

        int minTotArgDistance = Integer.MAX_VALUE;
        for (ArrayList<String> goldArgs : goldAttributeSequences) {
            int totArgDistance = 0;
            HashSet<Integer> matchedPositions = new HashSet<>();
            for (int i = 0; i < predictedAttrs.size(); i++) {
                if (!predictedAttrs.get(i).equals(SFX.TOKEN_START)
                        && !predictedAttrs.get(i).equals(SFX.TOKEN_END)) {
                    int minArgDistance = Integer.MAX_VALUE;
                    int minArgPos = -1;
                    for (int j = 0; j < goldArgs.size(); j++) {
                        if (!matchedPositions.contains(j)) {
                            if (goldArgs.get(j).equals(predictedAttrs.get(i))) {
                                int argDistance = Math.abs(j - i);

                                if (argDistance < minArgDistance) {
                                    minArgDistance = argDistance;
                                    minArgPos = j;
                                }
                            }
                        }
                    }

                    if (minArgPos == -1) {
                        totArgDistance += 100;
                    } else {
                        matchedPositions.add(minArgPos);
                        totArgDistance += minArgDistance;
                    }
                }
            }
            ArrayList<String> predictedCopy = (ArrayList<String>) predictedAttrs.clone();
            for (String goldArg : goldArgs) {
                if (!goldArg.equals(SFX.TOKEN_END)) {
                    boolean contained = predictedCopy.remove(goldArg);
                    if (!contained) {
                        totArgDistance += 1000;
                    }
                }
            }
            if (totArgDistance < minTotArgDistance) {
                minTotArgDistance = totArgDistance;
            }
        }
        totalArgDistance += minTotArgDistance;
    }

    previousResults = generationActions;

    crossAvgArgDistances.add(totalArgDistance / (double) testingData.size());

    NISTMetric NIST = new NISTMetric(finalReferences);
    BLEUMetric BLEU = new BLEUMetric(finalReferences, 4, false);
    BLEUMetric BLEUsmooth = new BLEUMetric(finalReferences, 4, true);
    Double nistScore = NIST.score(generations);
    Double bleuScore = BLEU.score(generations);
    Double bleuSmoothScore = BLEUsmooth.score(generations);

    double finalCoverage = 0.0;
    for (double c : attrCoverage) {
        finalCoverage += c;
    }
    finalCoverage /= (double) attrCoverage.size();
    crossNIST.add(nistScore);
    crossBLEU.add(bleuScore);
    crossBLEUSmooth.add(bleuSmoothScore);
    System.out.println("Avg arg distance: \t" + totalArgDistance / (double) testingData.size());
    System.out.println("NIST: \t" + nistScore);
    System.out.println("BLEU: \t" + bleuScore);
    System.out.println("COVERAGE: \t" + finalCoverage);
    System.out.println("g: " + generations);
    System.out.println("attr: " + predictedAttrLists);
    System.out.println("BLEU smooth: \t" + bleuSmoothScore);
    previousBLEU = bleuScore;

    if (printResults) {
        BufferedWriter bw = null;
        File f = null;
        try {
            f = new File("random_SFX" + dataset + "TextsAfter" + (epoch) + "_"
                    + JDAggerForSFX.earlyStopMaxFurtherSteps + "_" + JDAggerForSFX.p + "epochsTESTINGDATA.txt");
        } catch (NullPointerException e) {
            System.err.println("File not found." + e);
        }

        try {
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f)));
        } catch (FileNotFoundException e) {
            System.err.println("Error opening file for writing! " + e);
        }

        try {
            bw.write("BLEU:" + bleuScore);
            bw.write("\n");
        } catch (IOException e) {
            System.err.println("Write error!");
        }
        for (int i = 0; i < predictedStrings.size(); i++) {
            try {
                //Grafoume to String sto arxeio
                //SFX HOTEL TEXTS WITH LOLS -> 3
                //SFX RESTAURANT TEXTS WITH LOLS -> 5
                bw.write("MR;" + predictedStringMRs.get(i).replaceAll(";", ",") + ";");
                if (dataset.equals("hotel")) {
                    bw.write("LOLS_SFHOT;");
                } else {
                    bw.write("LOLS_SFRES;");
                }
                //bw.write("@@srcdoc@@" + (i + 1));
                /*String out = predictedStrings.get(i).replaceAll(" i ", " I ").replaceAll(" -ly ", "ly ").replaceAll(" s ", "s ").replaceAll("\\?", " \\? ").replaceAll(":", " : ").replaceAll("\\.", " \\. ").replaceAll(",", " , ").replaceAll("  ", " ");
                out = out.substring(0, 1).toUpperCase() + out.substring(1);
                bw.write(out + ";");
                if (dataset.equals("hotel")) {
                bw.write("WEN_SFHOT;");
                } else {
                bw.write("WEN_SFRES;");
                }
                if (!wenDaToGen.containsKey(predictedStringMRs.get(i).trim().toLowerCase())) {
                System.out.println(wenDaToGen.keySet());
                System.out.println(predictedStringMRs.get(i).trim().toLowerCase());
                System.exit(0);
                }
                out = wenDaToGen.get(predictedStringMRs.get(i).trim().toLowerCase()).replaceAll(" i ", " I ").replaceAll(" -ly ", "ly ").replaceAll(" s ", "s ").replaceAll("\\?", " \\? ").replaceAll(":", " : ").replaceAll("\\.", " \\. ").replaceAll(",", " , ").replaceAll("  ", " ");
                out = out.substring(0, 1).toUpperCase() + out.substring(1);
                bw.write(out + ";");*/
                //bw.write("@@judgeFluency@@-1");
                //bw.write("@@judgeInform@@-1");
                //bw.write("@@judgeQuality@@-1");

                bw.write("\n");
            } catch (IOException e) {
                System.err.println("Write error!");
            }
        }

        try {
            bw.close();
        } catch (IOException e) {
            System.err.println("Error closing file.");
        } catch (Exception e) {
        }
    }
    return bleuScore;
}

From source file:com.sonicle.webtop.calendar.CalendarManager.java

public List<LocalDate> listEventDates(Collection<Integer> calendarIds, DateTime from, DateTime to,
        DateTimeZone refTimezone) throws WTException {
    EventDAO evtDao = EventDAO.getInstance();
    Connection con = null;/*from w w  w. j av  a 2  s .c  o  m*/

    try {
        con = WT.getConnection(SERVICE_ID);

        List<Integer> okCalendarIds = calendarIds.stream()
                .filter(calendarId -> quietlyCheckRightsOnCalendarFolder(calendarId, "READ"))
                .collect(Collectors.toList());

        HashSet<LocalDate> dates = new HashSet<>();
        for (VVEvent vevt : evtDao.viewByCalendarRangeCondition(con, okCalendarIds, from, to, null)) {
            dates.addAll(CalendarUtils.getDatesSpan(vevt.getAllDay(), vevt.getStartDate(), vevt.getEndDate(),
                    DateTimeZone.forID(vevt.getTimezone())));
        }
        int noOfRecurringInst = Days.daysBetween(from, to).getDays() + 2;
        for (VVEvent vevt : evtDao.viewRecurringByCalendarRangeCondition(con, okCalendarIds, from, to, null)) {
            final List<SchedEventInstance> instances = calculateRecurringInstances(con,
                    new SchedEventInstanceMapper(vevt), from, to, refTimezone, noOfRecurringInst);
            for (SchedEventInstance instance : instances) {
                dates.addAll(CalendarUtils.getDatesSpan(instance.getAllDay(), instance.getStartDate(),
                        instance.getEndDate(), instance.getDateTimeZone()));
            }
        }
        return new ArrayList<>(dates);

    } catch (SQLException | DAOException ex) {
        throw wrapException(ex);
    } finally {
        DbUtils.closeQuietly(con);
    }
}

From source file:com.android.launcher3.Workspace.java

public void disableShortcutsByPackageName(final ArrayList<String> packages, final UserHandleCompat user,
        final int reason) {
    final HashSet<String> packageNames = new HashSet<String>();
    packageNames.addAll(packages);

    mapOverItems(MAP_RECURSE, new ItemOperator() {
        @Override//w  ww.  j a v  a2s. co m
        public boolean evaluate(ItemInfo info, View v, View parent) {
            if (info instanceof ShortcutInfo && v instanceof BubbleTextView) {
                ShortcutInfo shortcutInfo = (ShortcutInfo) info;
                ComponentName cn = shortcutInfo.getTargetComponent();
                if (user.equals(shortcutInfo.user) && cn != null
                        && packageNames.contains(cn.getPackageName())) {
                    shortcutInfo.isDisabled |= reason;
                    BubbleTextView shortcut = (BubbleTextView) v;
                    shortcut.applyFromShortcutInfo(shortcutInfo, mIconCache, true, false);

                    if (parent != null) {
                        parent.invalidate();
                    }
                }
            }
            // process all the shortcuts
            return false;
        }
    });
}

From source file:com.android.launcher3.Workspace.java

void removeItemsByPackageName(final ArrayList<String> packages, final UserHandleCompat user) {
    final HashSet<String> packageNames = new HashSet<String>();
    packageNames.addAll(packages);

    // Filter out all the ItemInfos that this is going to affect
    final HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
    final HashSet<ComponentName> cns = new HashSet<ComponentName>();
    ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts();
    for (CellLayout layoutParent : cellLayouts) {
        ViewGroup layout = layoutParent.getShortcutsAndWidgets();
        int childCount = layout.getChildCount();
        for (int i = 0; i < childCount; ++i) {
            View view = layout.getChildAt(i);
            infos.add((ItemInfo) view.getTag());
        }//from www. j a v a  2 s.c  om
    }
    LauncherModel.ItemInfoFilter filter = new LauncherModel.ItemInfoFilter() {
        @Override
        public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
            if (packageNames.contains(cn.getPackageName()) && info.user.equals(user)) {
                cns.add(cn);
                return true;
            }
            return false;
        }
    };
    LauncherModel.filterItemInfos(infos, filter);

    // Remove the affected components
    removeItemsByComponentName(cns, user);
}

From source file:org.apache.geode.internal.cache.GemFireCacheImpl.java

public Collection<DiskStoreImpl> listDiskStoresIncludingRegionOwned() {
    HashSet<DiskStoreImpl> allDiskStores = new HashSet<DiskStoreImpl>();
    allDiskStores.addAll(this.diskStores.values());
    allDiskStores.addAll(this.regionOwnedDiskStores.values());
    return allDiskStores;
}

From source file:org.freebxml.omar.common.BindingUtility.java

/**
 * Gets the Set of ReferenceInfo for all object references within specified RegistryObject.
 * TODO: replace with reflections API when JAXB bindings use special class for ReferenceURI.
 *
 * Reference attributes based on scanning rim.xsd for anyURI.
 *
 * @param ro specifies the RegistryObject whose ObjectRefs are being sought.
 *
 * @param idMap The Map with old temporary id to new permanent id mapping.
 *
 *//* w  ww .j a va 2  s.  c  om*/
public Set getObjectRefsInRegistryObject(RegistryObjectType ro, Map idMap, Set processedObjects, int depth)
        throws JAXRException {
    HashSet refInfos = new HashSet();

    if ((ro != null) && (!processedObjects.contains(ro))) {
        processedObjects.add(ro);
        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.RegistryObjectType", refInfos, idMap,
                "ObjectType");

        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.ClassificationNodeType", refInfos, idMap,
                "Parent");

        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.ClassificationType", refInfos, idMap,
                "ClassificationNode");
        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.ClassificationType", refInfos, idMap,
                "ClassificationScheme");
        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.ClassificationType", refInfos, idMap,
                "ClassifiedObject");

        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.ExternalIdentifierType", refInfos, idMap,
                "IdentificationScheme");
        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.ExternalIdentifierType", refInfos, idMap,
                "RegistryObject");

        //FederationType fed = (FederationType)ro;
        //TODO: Fix so it adds only Strings not ObjectRefType
        //refInfos.addAll(fed.getMembers().getObjectRef());

        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.AssociationType1", refInfos, idMap,
                "AssociationType");
        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.AssociationType1", refInfos, idMap,
                "SourceObject");
        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.AssociationType1", refInfos, idMap,
                "TargetObject");

        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.AuditableEventType", refInfos, idMap,
                "User");
        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.AuditableEventType", refInfos, idMap,
                "RequestId");

        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.OrganizationType", refInfos, idMap,
                "Parent");

        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.RegistryType", refInfos, idMap,
                "Operator");

        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.ServiceBindingType", refInfos, idMap,
                "Service");
        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.ServiceBindingType", refInfos, idMap,
                "TargetBinding");

        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.SpecificationLinkType", refInfos, idMap,
                "ServiceBinding");
        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.SpecificationLinkType", refInfos, idMap,
                "SpecificationObject");

        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.SubscriptionType", refInfos, idMap,
                "Selector");

        --depth;

        //Now process composed objects
        if (depth != 0) {
            Set composedObjects = getComposedRegistryObjects(ro, 1);
            Iterator iter = composedObjects.iterator();
            while (iter.hasNext()) {
                Object obj = iter.next();
                if (obj instanceof RegistryObjectType) {
                    RegistryObjectType composedObject = (RegistryObjectType) obj;
                    Set composedRefInfos = getObjectRefsInRegistryObject(composedObject, idMap,
                            processedObjects, depth);
                    refInfos.addAll(composedRefInfos);
                }
            }
        }
    }

    return refInfos;
}