Example usage for java.util.function Consumer Consumer

List of usage examples for java.util.function Consumer Consumer

Introduction

In this page you can find the example usage for java.util.function Consumer Consumer.

Prototype

Consumer

Source Link

Usage

From source file:com.diversityarrays.kdxplore.boxplot.BoxPlotPanel.java

@Override
public void updateSelectedSamples() {

    PlotsByTraitInstance plotsByTraitInstance = selectedValueStore.getSyncedPlotsByTrait();

    intervalMarker = null;/*from ww w  .j ava 2 s.  co m*/

    CategoryPlot categoryPlot = ((CategoryPlot) getChart().getPlot());

    categoryPlot.clearRangeMarkers();

    double min = categoryPlot.getRangeAxis().getLowerBound();
    double max = categoryPlot.getRangeAxis().getUpperBound();

    for (TraitInstance ti : plotsByTraitInstance.getTraitInstances()) {
        if (traitInstances.contains(ti)) {
            String tiIdentifier = InstanceIdentifierUtil.getInstanceIdentifier(ti);

            //             Set<Plot> plots = plotsByTraitInstance.getPlotSpecimens(ti).stream()
            //                 .map(pos -> plotInfoProvider.getPlotByPlotId(pos.getPlotId()))
            //                 .collect(Collectors.toSet());

            for (PlotOrSpecimen pos : plotsByTraitInstance.getPlotSpecimens(ti)) {
                if (usedPlotSpecimens.isEmpty() || usedPlotSpecimens.contains(pos)) {

                    Consumer<KdxSample> visitor = new Consumer<KdxSample>() {
                        @Override
                        public void accept(KdxSample sample) {
                            if (InstanceIdentifierUtil.getInstanceIdentifier(sample).equals(tiIdentifier)) {
                                if (checkIfSelected(sample, min, max) == AxisType.Y) {

                                    intervalMarker = new IntervalMarker(
                                            Double.parseDouble(sample.getTraitValue()) - 0.1,
                                            Double.parseDouble(sample.getTraitValue()) + 0.1);
                                    intervalMarker.setAlpha(0.3f);
                                    intervalMarker.setPaint(Color.RED);
                                    Stroke stroke = new BasicStroke();
                                    intervalMarker.setOutlinePaint(Color.RED);
                                    intervalMarker.setOutlineStroke(stroke);
                                    addRangeMarker(intervalMarker);
                                }
                            }
                        }
                    };
                    plotInfoProvider.visitSamplesForPlotOrSpecimen(pos, visitor);
                }
            }
        }
    }

    getChartPanel().repaint();

    if (null != curationControls) {
        curationControls.updateButtons(false);
    }
}

From source file:pt.ist.expenditureTrackingSystem.domain.organization.Unit.java

private static void evaluateAllProcesses(final ProcessEvaluator<GenericProcess> unitProcessEvaluator,
        final PaymentProcessYear year, final module.organization.domain.Unit unit) {
    unit.getChildAccountabilityStream().map(a -> a.getChild()).filter(p -> p.isUnit())
            .map(p -> (module.organization.domain.Unit) p)
            .forEach(new Consumer<module.organization.domain.Unit>() {

                @Override//ww  w .jav a2  s  .  c  o  m
                public void accept(module.organization.domain.Unit u) {
                    if (u.getExpenditureUnit() != null) {
                        u.getExpenditureUnit().evaluateAllProcesses(unitProcessEvaluator, year);
                    } else {
                        evaluateAllProcesses(unitProcessEvaluator, year, u);
                    }
                }
            });
    ;
}

From source file:utybo.branchingstorytree.swing.OpenBSTGUI.java

public void openStory(File f) {
    if (f != null) {
        final TabClient client = new TabClient(instance);
        loadFile(f, client, new Consumer<BranchingStory>() {
            private StoryPanel sp;

            @Override/* w ww . j a  v  a 2s.  c o  m*/
            public void accept(BranchingStory bs) {
                if (bs != null) {
                    try {
                        SwingUtilities.invokeAndWait(() -> sp = addStory(bs, f, client));
                        if (sp != null) {
                            try {
                                client.getBRMHandler().load();
                                if (Boolean.parseBoolean(bs.getTagOrDefault("img_requireinternal", "false")))
                                    IMGClient.initInternal();
                            } catch (BSTException e) {
                                LOG.error("Exception caught while loading resources", e);
                                showException(Lang.get("file.resourceerror").replace("$e", whichCause(e))
                                        .replace("$m", whichMessage(e)), e);
                            }
                            SwingUtilities.invokeAndWait(() -> sp.setupStory());
                        }
                    } catch (InvocationTargetException | InterruptedException e) {
                        LOG.warn("Swing invocation exception", e);
                    }

                }
            }

            private String whichMessage(BSTException e) {
                if (e.getCause() != null) {
                    return e.getCause().getMessage();
                } else {
                    return e.getMessage();
                }
            }

            private String whichCause(BSTException e) {
                if (e.getCause() != null) {
                    return e.getCause().getClass().getSimpleName();
                } else {
                    return e.getClass().getSimpleName();
                }
            }
        });
    }
}

From source file:utybo.branchingstorytree.swing.OpenBSTGUI.java

private void openEditor(File f) {
    if (f != null) {
        final TabClient client = new TabClient(instance);
        loadFile(f, client, new Consumer<BranchingStory>() {
            @Override//from w ww.java2s .c  om
            public void accept(BranchingStory bs) {
                try {
                    SwingUtilities.invokeAndWait(() -> {
                        try {
                            StoryEditor se = new StoryEditor(bs);
                            container.addTab(se.getTitle(), se);
                            container.setSelectedComponent(se);
                        } catch (Exception e) {
                            LOG.error("Error on story editor init", e);
                            Messagers.showException(OpenBSTGUI.this, "Error while creating the Story Editor ("
                                    + e.getClass().getSimpleName() + " : " + e.getMessage() + ")", e);
                        }
                    });
                } catch (Exception e) {
                    LOG.error(e);
                }
            }
        });
    }
}

From source file:gedi.atac.Atac.java

public static void testInPeaks(GenomicRegionStorage<? extends AlignedReadsData> storage, String contrasts,
        String peakFile, String rmq, String compOut, String bicOut, String out, boolean randomizeContrasts)
        throws IOException {

    DiskGenomicNumericBuilder clusterRmq = new DiskGenomicNumericBuilder(rmq);
    LineIterator it = new LineOrientedFile(peakFile).lineIterator();
    LineOrientedFile o = new LineOrientedFile(out);
    o.startWriting();/*from w ww. ja v a2  s  .  co m*/
    o.writef("%s\tComponents\tp.value\n", it.next());
    int offset = 4;

    ContrastMapping contr = new ContrastMapping();
    ExtendedIterator<String> coit = new LineOrientedFile(contrasts).lineIterator();
    if (randomizeContrasts) {
        String[] ca = coit.toArray(new String[0]);
        ArrayUtils.shuffleSlice(ca, 0, ca.length);
        coit = FunctorUtils.arrayIterator(ca);
    }
    coit.forEachRemaining(
            l -> contr.addMapping(contr.getNumOriginalConditions(), contr.getMappedIndexOrNext(l), l));

    LineOrientedFile co = new LineOrientedFile(compOut);
    co.startWriting();
    co.writef("Peak\tComponent");
    for (int i = 0; i < contr.getNumMergedConditions(); i++)
        co.writef("\t%s", contr.getMappedName(i));
    co.writeLine();

    LineOrientedFile bico = new LineOrientedFile(bicOut);
    bico.startWriting();
    bico.writef("Peak\tk\tBIC\n");

    Progress pr = new ConsoleProgress();
    pr.init();
    int peakCount = (int) new LineOrientedFile(peakFile).lineIterator().count() - 1;
    pr.setCount(peakCount);

    while (it.hasNext()) {
        String line = it.next();
        ImmutableReferenceGenomicRegion<Object> peak = ImmutableReferenceGenomicRegion
                .parse(StringUtils.splitField(line, '\t', 0));

        pr.setDescription(peak.toString());
        pr.incrementProgress();

        HashMap<FixedDoublePoint, Integer> pToPos = new HashMap<FixedDoublePoint, Integer>();
        FixedDoublePoint[] m = new FixedDoublePoint[peak.getRegion().getTotalLength()];
        for (int i = 0; i < m.length; i++) {
            m[i] = new FixedDoublePoint(new double[contr.getNumMergedConditions()]);
            pToPos.put(m[i], peak.getRegion().map(i));
        }

        Consumer<MutableReferenceGenomicRegion<? extends AlignedReadsData>> adder = new Consumer<MutableReferenceGenomicRegion<? extends AlignedReadsData>>() {

            @Override
            public void accept(MutableReferenceGenomicRegion<? extends AlignedReadsData> mrgr) {
                try {

                    int start = GenomicRegionPosition.Start.position(mrgr.getReference(), mrgr.getRegion(),
                            offset);
                    if (peak.getRegion().contains(start))
                        addDownsampled(contr, m[peak.getRegion().induce(start)].getPoint(),
                                mrgr.getData().getTotalCountsForConditions(ReadCountMode.All));

                    int stop = GenomicRegionPosition.Stop.position(mrgr.getReference(), mrgr.getRegion(),
                            -offset);
                    if (peak.getRegion().contains(stop))
                        addDownsampled(contr, m[peak.getRegion().induce(stop)].getPoint(),
                                mrgr.getData().getTotalCountsForConditions(ReadCountMode.All));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }

            private void addDownsampled(ContrastMapping contr, double[] re, double[] c) {
                double max = ArrayUtils.max(c);
                if (max > 0)
                    ArrayUtils.mult(c, 1 / max);
                for (int i = 0; i < c.length; i++)
                    if (contr.getMappedIndex(i) > -1)
                        re[contr.getMappedIndex(i)] += c[i];
            }
        };
        storage.iterateIntersectingMutableReferenceGenomicRegions(peak.getReference().toPlusStrand(),
                peak.getRegion()).forEachRemaining(adder);
        storage.iterateIntersectingMutableReferenceGenomicRegions(peak.getReference().toMinusStrand(),
                peak.getRegion()).forEachRemaining(adder);

        //         double[] total = new double[cond];
        //         for (int i=0; i<m.length; i++) 
        //            for (int j=0; j<cond; j++)
        //               total[j]+=m[i].getPoint()[j];
        //         ArrayUtils.normalize(total);
        //         
        //         double ll = 0;
        //         for (int i=0; i<m.length; i++)
        //            ll+=ddirichlet1(m[i].getPoint(), total);
        //         

        DoubleArrayList ll = new DoubleArrayList();
        ll.add(0);
        DoubleArrayList bic = new DoubleArrayList();
        bic.add(0);

        ArrayList<FixedDoublePoint> list = new ArrayList<FixedDoublePoint>();
        for (FixedDoublePoint p : m)
            if (ArrayUtils.sum(p.getPoint()) > 0)
                list.add(p);

        List<CentroidCluster<FixedDoublePoint>> ocl = null;
        double op = 0;

        for (int k = 1; k < Math.min(list.size(), 50); k++) {

            KMeansPlusPlusClusterer<FixedDoublePoint> kmeans = new KMeansPlusPlusClusterer<FixedDoublePoint>(k);
            List<CentroidCluster<FixedDoublePoint>> cl = kmeans.cluster(list);

            double cll = 0;
            for (CentroidCluster<FixedDoublePoint> c : cl) {
                double[] total = new double[contr.getNumMergedConditions()];
                Arrays.fill(total, 1);
                for (FixedDoublePoint p : c.getPoints())
                    for (int j = 0; j < contr.getNumMergedConditions(); j++)
                        total[j] += p.getPoint()[j];
                ArrayUtils.normalize(total);

                for (FixedDoublePoint p : c.getPoints())
                    cll += ddirichlet1(p.getPoint(), total);
            }

            // LLR test
            double LLR = 2 * cll - 2 * ll.getLastDouble();
            double p = 1
                    - new ChiSquaredDistribution(contr.getNumMergedConditions() - 1).cumulativeProbability(LLR);

            bic.add(-2 * cll + 2 * (contr.getNumMergedConditions() - 1) * k);
            bico.writef("%s\t%d\t%.1f\n", peak.toLocationString(), k, bic.getLastDouble());

            // bonferroni correction
            p = p * peakCount;

            if (p > 0.01) {
                if (ocl.size() > 1) {
                    for (int i = 0; i < ocl.size(); i++) {
                        co.writef("%s\t%d", peak.toLocationString(), i);
                        double[] total = new double[contr.getNumMergedConditions()];
                        Arrays.fill(total, 1);
                        for (FixedDoublePoint pp : ocl.get(i).getPoints()) {
                            clusterRmq.addValue(peak.getReference(), pToPos.get(pp).intValue(), (byte) i);
                            for (int j = 0; j < contr.getNumMergedConditions(); j++)
                                total[j] += pp.getPoint()[j];
                        }
                        ArrayUtils.normalize(total);
                        for (int c = 0; c < contr.getNumMergedConditions(); c++)
                            co.writef("\t%.4f", total[c]);
                        co.writeLine();

                    }
                }
                break;
            }

            ll.add(cll);
            ocl = cl;
            op = p;
        }

        o.writef("%s\t%d\t%.4g\n", line, ll.size() - 1, ll.size() == 2 ? Double.NaN : op);
    }

    pr.finish();
    o.finishWriting();
    co.finishWriting();

    clusterRmq.build();
}

From source file:com.github.totyumengr.minicubes.cluster.TimeSeriesMiniCubeManagerHzImpl.java

@Override
public Map<Integer, BigDecimal> sum(String indName, String groupByDimName,
        Map<String, List<Integer>> filterDims) {

    try {/*from  w  w w . ja v  a 2s  .  c  o  m*/
        Set<String> cubeIds = cubeIds();

        // Do execute
        List<Map<Integer, BigDecimal>> results = execute(new Sum2(indName, groupByDimName, filterDims), cubeIds,
                hzExecutorTimeout);
        LOGGER.debug("Group {} on {} with filter {} results is {}", indName, cubeIds, filterDims, results);

        Map<Integer, BigDecimal> result = new HashMap<Integer, BigDecimal>();
        results.stream().forEach(new Consumer<Map<Integer, BigDecimal>>() {

            @Override
            public void accept(Map<Integer, BigDecimal> t) {
                t.forEach((k, v) -> result.merge(k, v, BigDecimal::add));
            }
        });
        LOGGER.debug("Sum {} on {} with filter {} results is {}", indName, cubeIds, filterDims, result);

        return result;
    } finally {
        AGG_CONTEXT.remove();
    }
}

From source file:com.diversityarrays.kdxplore.curate.fieldview.FieldLayoutViewPanel.java

private void updatePlotAttributeTableModel(String fromWhere) {

    //      System.out.println("updatePlotAttributeTableModel( " + fromWhere + " )");

    boolean anyMultiple = false;
    Map<Integer, AttributeValue> valueByAttributeId = new HashMap<>();
    Map<Pair<Integer, Integer>, SampleValue> sampleMap = new HashMap<>();

    int vrows[] = fieldLayoutTable.getSelectedRows();
    if (vrows == null || vrows.length > 0) {
        int vcols[] = fieldLayoutTable.getSelectedColumns();

        //         System.out.println("rows:");
        //         for (int r : vrows) {
        //            System.out.print(" " + r);
        //         }
        //         System.out.println();
        //         System.out.println("cols:");
        //         for (int c : vcols) {
        //            System.out.print(" " + c);
        //         }
        //         System.out.println();

        for (int vrow : vrows) {
            for (int vcol : vcols) {
                if (fieldLayoutTable.isCellSelected(vrow, vcol)) {
                    // we don't allow sorting or column re-ordering
                    Plot plot = fieldLayoutTableModel.getPlot(vrow, vcol);
                    if (plot != null) {
                        for (PlotAttributeValue pav : plot.plotAttributeValues) {
                            AttributeValue aValue = valueByAttributeId.get(pav.getAttributeId());
                            if (aValue == null) {
                                valueByAttributeId.put(pav.getAttributeId(),
                                        new AttributeValue(pav.getAttributeId(), pav.getAttributeValue()));
                            } else {
                                if (!aValue.value.equals(pav.getAttributeValue())) {
                                    aValue.multiple = true;
                                    anyMultiple = true;
                                }/*from w  w  w . ja v  a  2s  .  c om*/
                            }
                        }

                        Consumer<KdxSample> visitor = new Consumer<KdxSample>() {
                            @Override
                            public void accept(KdxSample sample) {
                                String raw = sample.getTraitValue();
                                TraitValueType type = TraitValue.classify(raw);
                                String keyString = InstanceIdentifierUtil.getInstanceIdentifier(sample);
                                TraitInstance trait = traitById.get(keyString);
                                if (trait != null) {
                                    String displayValue = SampleValue.toDisplayValue(raw, type,
                                            trait.getTraitDataType(), dateFormat, trial.getTrialPlantingDate());

                                    Pair<Integer, Integer> key = new Pair<>(sample.getTraitId(),
                                            sample.getTraitInstanceNumber());
                                    SampleValue sampleValue = sampleMap.get(key);
                                    if (sampleValue == null) {
                                        sampleMap.put(key, new SampleValue(raw, type, displayValue));
                                    } else {
                                        sampleValue.addDisplayValue(displayValue);
                                    }
                                }
                            }
                        };

                        curationData.visitSamplesForPlotOrSpecimen(plot, visitor);
                    }
                }
            }
        }
    }

    plotCellChoicesPanel.updateData(sampleMap, valueByAttributeId, anyMultiple);
}

From source file:com.github.totyumengr.minicubes.cluster.TimeSeriesMiniCubeManagerHzImpl.java

@Override
public Map<Integer, Long> count(String indName, String groupByDimName, Map<String, List<Integer>> filterDims) {

    try {//from ww  w .jav  a 2  s  .c  om
        Set<String> cubeIds = cubeIds();

        // Do execute
        List<Map<Integer, Long>> results = execute(new Count2(indName, groupByDimName, filterDims), cubeIds,
                hzExecutorTimeout);
        LOGGER.debug("Group counting {} on {} with filter {} results is {}", indName, cubeIds, filterDims,
                results);

        Map<Integer, Long> result = new HashMap<Integer, Long>();
        results.stream().forEach(new Consumer<Map<Integer, Long>>() {

            @Override
            public void accept(Map<Integer, Long> t) {
                t.forEach((k, v) -> result.merge(k, v, Long::sum));
            }
        });
        LOGGER.debug("Count {} on {} with filter {} results is {}", indName, cubeIds, filterDims, result);

        return result;
    } finally {
        AGG_CONTEXT.remove();
    }
}

From source file:com.diversityarrays.kdxplore.trials.TrialOverviewPanel.java

private void doAddTraitInstances(Trial selectedTrial, Map<Trait, List<Integer>> instanceNumbersByTrait)
        throws IOException {

    List<Trait> unusedTraits = offlineData.getKdxploreDatabase().getAllTraits();

    Map<Integer, Trait> traitById = unusedTraits.stream()
            .collect(Collectors.toMap(Trait::getTraitId, Function.identity()));

    List<TraitInstance> instances = this.getAllTraitInstances(selectedTrial);

    Map<Trait, Integer> instancesByTrait = new HashMap<>();
    for (TraitInstance ti : instances) {
        Trait trait = traitById.get(ti.getTraitId());

        Integer inst = instancesByTrait.get(trait);
        if (inst == null) {
            inst = ti.getInstanceNumber();
        } else {//from   w  w  w. ja v a  2s . com
            inst++;
        }
        instancesByTrait.put(trait, inst);
    }

    for (Trait trait : instanceNumbersByTrait.keySet()) {
        List<Integer> newInstances = instanceNumbersByTrait.get(trait);

        if (!Check.isEmpty(newInstances)) {
            Integer currentCount = instancesByTrait.get(trait);

            if (currentCount != null) {
                List<Integer> toUse = new ArrayList<>();
                newInstances.stream().forEach(i -> toUse.add(i += currentCount));
                instanceNumbersByTrait.put(trait, toUse);
            }
        }
    }

    if (instanceNumbersByTrait.isEmpty()) {
        return;
    }

    int trialId = selectedTrial.getTrialId();

    int maxSso = 0;
    Bag<Integer> ssoUseCount = new HashBag<>();

    Map<Trait, Integer> traitSsoMap = trialTraitsTableModel.getTraitsSsoForTrial(selectedTrial);
    if (!Check.isEmpty(traitSsoMap)) {
        for (Integer sso : traitSsoMap.values()) {
            if (sso != null) {
                maxSso = Math.max(maxSso, sso);
                ssoUseCount.add(sso);
            }
        }
    }

    TraitNameStyle traitNameStyle = selectedTrial.getTraitNameStyle();

    final int firstInstanceNumber = traitNameStyle.getFirstInstanceNumber();

    int maxSsoIncrement = 1;
    if (ssoUseCount.uniqueSet().size() == 1 && maxSso == 0 && ssoUseCount.getCount(maxSso) > 1) {
        // Special hack for Trials that haven't yet been "sorted".
        // (i.e. all the SSOs are the same value
        maxSsoIncrement = 0;
    }

    List<Trait> ignored = new ArrayList<>();
    Map<TraitLevel, List<TraitInstance>> instancesByLevel = new HashMap<>();
    boolean multipleTraitInstances = false;

    Set<TraitInstance> traitInstances = new LinkedHashSet<>();
    for (Trait trait : instanceNumbersByTrait.keySet()) {

        switch (trait.getTraitLevel()) {
        case PLOT:
        case SPECIMEN:
            break;
        default:
            ignored.add(trait);
            continue;
        }
        maxSso += maxSsoIncrement;

        List<Integer> instancesNumbersWanted = instanceNumbersByTrait.get(trait);
        if (instancesNumbersWanted.size() > 1) {
            multipleTraitInstances = true;
        }

        for (Integer instanceNumber : instancesNumbersWanted) {
            TraitInstance ti = new TraitInstance();
            //                if (firstInstanceNumber <= 0) {
            //                    ti.setInstanceNumber(instanceNumber - 1);
            //                }
            //                else {
            ti.setInstanceNumber(instanceNumber);
            //                }
            ti.setScoringSortOrder(maxSso);
            ti.setTraitId(trait.getTraitId());
            ti.setTrialId(trialId);
            ti.setUsedForScoring(true);

            traitInstances.add(ti);

            List<TraitInstance> list = instancesByLevel.get(trait.getTraitLevel());
            if (list == null) {
                list = new ArrayList<>();
                instancesByLevel.put(trait.getTraitLevel(), list);
            }
            list.add(ti);
        }
    }

    KdxploreDatabase kdxdb = offlineData.getKdxploreDatabase();
    KDSmartDatabase kdsdb = kdxdb.getKDXploreKSmartDatabase();

    Map<Integer, DeviceIdentifier> devidMap = kdxdb.getDeviceIdentifierMap();
    Optional<DeviceIdentifier> opt_devid = devidMap.values().stream()
            .filter(devid -> DeviceType.EDITED.equals(devid.getDeviceType())).findFirst();

    List<KdxSample> samples;
    if (opt_devid.isPresent()) {
        DeviceIdentifier curated = opt_devid.get();
        List<SampleGroup> sampleGroups = kdxdb.getSampleGroups(trialId,
                KdxploreDatabase.WithSamplesOption.WITH_SAMPLES);
        int curatedSampleGroupId = curated.getDeviceIdentifierId();

        Optional<SampleGroup> opt_sg = sampleGroups.stream()
                .filter(sg -> curatedSampleGroupId == sg.getDeviceIdentifierId()).findFirst();
        if (opt_sg.isPresent()) {
            samples = new ArrayList<>();

            List<TraitInstance> plotInstances = instancesByLevel.get(TraitLevel.PLOT);
            List<TraitInstance> subPlotInstances = instancesByLevel.get(TraitLevel.SPECIMEN);

            Consumer<KdxSample> sampleConsumer = new Consumer<KdxSample>() {
                @Override
                public void accept(KdxSample sample) {
                    samples.add(sample);
                }
            };
            TrialItemVisitor<Plot> plotVisitor = new TrialItemVisitor<Plot>() {
                @Override
                public void setExpectedItemCount(int count) {
                }

                @Override
                public boolean consumeItem(Plot plot) {
                    DatabaseUtil.createSamples(trialId, plot, curatedSampleGroupId, null, // previousSamplesByKey
                            plotInstances, subPlotInstances, sampleConsumer);
                    return true;
                }
            };

            kdsdb.visitPlotsForTrial(trialId, SampleGroupChoice.NO_TAGS_SAMPLE_GROUP,
                    KDSmartDatabase.WithPlotAttributesOption.WITHOUT_PLOT_ATTRIBUTES, plotVisitor);
        } else {
            samples = null;
        }
    } else {
        samples = null;
    }

    BatchHandler<Void> batchHandler = new BatchHandler<Void>() {
        @Override
        public Void call() throws Exception {
            kdsdb.saveTraitInstances(traitInstances);
            if (!Check.isEmpty(samples)) {
                kdsdb.saveMultipleSamples(samples, false);
            }
            return null;
        }

        @Override
        public boolean checkSuccess(Void t) {
            return true;
        }
    };

    boolean saved = true;
    Either<Exception, Void> either = kdsdb.doBatch(batchHandler);
    if (either.isLeft()) {
        saved = false;
        MsgBox.error(TrialOverviewPanel.this, either.left(), "Database Error");
    }
    refreshTrialTableModel(offlineData.getKdxploreDatabase());

    trialTraitsTableModel.setSelectedTrial(selectedTrial);

    if (saved) {
        String prefix = multipleTraitInstances ? "Trait Instances Added:\n" : "Traits Added:\n";

        Function<Trait, String> nameFactory = new Function<Trait, String>() {
            @Override
            public String apply(Trait trait) {
                List<Integer> instanceNumbers = instanceNumbersByTrait.get(trait);
                if (instanceNumbers == null) {
                    return null;
                } else {
                    return instanceNumbers.stream().map(inum -> inum.toString())
                            .collect(Collectors.joining(",", trait.getTraitName() + ": ", ""));
                }
            }
        };

        String selection = instanceNumbersByTrait.keySet().stream().map(nameFactory).filter(n -> n != null)
                .collect(Collectors.joining("\n", prefix, "\n------")); //$NON-NLS-1$//$NON-NLS-2$

        messagePrinter.println(selection);

        if (samples != null) {
            messagePrinter.println("Samples Added: " + samples.size());
        }
    }
}

From source file:com.github.totyumengr.minicubes.cluster.TimeSeriesMiniCubeManagerHzImpl.java

@Override
public Map<Integer, RoaringBitmap> distinct(String distinctName, boolean isDim, String groupByDimName,
        Map<String, List<Integer>> filterDims) {

    try {// w  ww  .  j av a2 s .  c o m
        Set<String> cubeIds = cubeIds();

        // Do execute
        List<Map<Integer, RoaringBitmap>> results = execute(
                new Distinct(distinctName, isDim, groupByDimName, filterDims), cubeIds, hzExecutorTimeout);
        LOGGER.debug("Distinct {} on {} with filter {} results is {}", distinctName, cubeIds, filterDims,
                results);

        Map<Integer, RoaringBitmap> result = new HashMap<Integer, RoaringBitmap>(results.size());
        results.stream().forEach(new Consumer<Map<Integer, RoaringBitmap>>() {

            @Override
            public void accept(Map<Integer, RoaringBitmap> t) {
                t.forEach((k, v) -> result.merge(k, v,
                        new BiFunction<RoaringBitmap, RoaringBitmap, RoaringBitmap>() {

                            @Override
                            public RoaringBitmap apply(RoaringBitmap t, RoaringBitmap u) {
                                return RoaringBitmap.or(t, u);
                            }
                        }));
            }
        });
        LOGGER.debug("Distinct {} on {} with filter {} results is {}", distinctName, cubeIds, filterDims,
                result);
        return result;
    } finally {
        AGG_CONTEXT.remove();
    }
}