Example usage for java.util SortedMap get

List of usage examples for java.util SortedMap get

Introduction

In this page you can find the example usage for java.util SortedMap get.

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:eu.stratosphere.pact.runtime.hash.HashFunctionCollisionBenchmark.java

private void checkBoundaries(BucketBoundaries[] boundaries) {
    for (int level = 0; level < boundaries.length; level++) {
        int lowerBound = boundaries[level].getLowerBound();
        int upperBound = boundaries[level].getUpperBound();
        int bucketCountInLevel = 0;
        int bucketCountOutOfRange = 0;

        SortedMap<Integer, Integer> levelMap = bucketSizesPerLevel.get(level);
        Iterator<Integer> bucketSizeIterator = levelMap.keySet().iterator();

        while (bucketSizeIterator.hasNext()) {
            int bucketSize = bucketSizeIterator.next();
            if (bucketSize != 0) {
                int countForBucketSize = levelMap.get(bucketSize);
                bucketCountInLevel += countForBucketSize;
                if (lowerBound > bucketSize || upperBound < bucketSize) {
                    bucketCountOutOfRange += countForBucketSize;
                }//from   w ww .  j  a  v a 2 s .  c om

            }
        }
        double bucketsOutOfRange = (double) bucketCountOutOfRange / (double) bucketCountInLevel;
        double maxBucketsOutOfRange = boundaries[level].getPercentOutOfRange();
        Assert.assertTrue(
                "More than " + (maxBucketsOutOfRange * 100) + "% of buckets out of range in level " + level,
                bucketsOutOfRange <= maxBucketsOutOfRange);

        int maxEmpty = boundaries[level].getMaxEmpty();
        Assert.assertTrue("More than " + maxEmpty + " empty buckets in level " + level,
                (maxEmpty == BucketBoundaries.MAX_EMPTY_UNBOUNDED)
                        || (levelMap.get(0) <= boundaries[level].getMaxEmpty()));
    }
}

From source file:org.opennaas.extensions.genericnetwork.test.capability.circuitstatistics.CircuitStatisticsCapabilityTest.java

@Test
@SuppressWarnings("unchecked")
public void filterByTimePeriodTest() throws SecurityException, IllegalArgumentException, IllegalAccessException,
        CapabilityException, NoSuchMethodException, InvocationTargetException {

    GenericNetworkModel model = new GenericNetworkModel();

    SortedMap<Long, List<CircuitStatistics>> circuitStatistics = new TreeMap<Long, List<CircuitStatistics>>();
    circuitStatistics.put(FIRST_TIMESTAMP, Arrays.asList(firstStatistics, secondStatistics));
    circuitStatistics.put(SECOND_TIMESTAMP, Arrays.asList(thirdStatistics));

    model.setCircuitStatistics(circuitStatistics);
    IResource resource = new Resource();
    resource.setModel(model);// w  ww .ja  v  a  2  s . c  o  m

    injectPrivateField(circuitStatisticsCapab, resource, "resource");

    TimePeriod timePeriod = new TimePeriod(FIRST_TIMESTAMP - 2L, FIRST_TIMESTAMP - 1L);
    String statisticsInCSV = circuitStatisticsCapab.getStatistics(timePeriod);
    Assert.assertTrue("Capability should not contain any statistic for this time period",
            statisticsInCSV.isEmpty());

    timePeriod = new TimePeriod(SECOND_TIMESTAMP + 1L, SECOND_TIMESTAMP + 2L);
    statisticsInCSV = circuitStatisticsCapab.getStatistics(timePeriod);
    Assert.assertTrue("Capability should not contain any statistic for this time period",
            statisticsInCSV.isEmpty());

    timePeriod = new TimePeriod(FIRST_TIMESTAMP, SECOND_TIMESTAMP - 1L);
    statisticsInCSV = circuitStatisticsCapab.getStatistics(timePeriod);
    Assert.assertFalse("Capability should contain statistics for this time period", statisticsInCSV.isEmpty());

    // call private method by reflection in order to parse CSV and make assertions
    Method method = circuitStatisticsCapab.getClass().getDeclaredMethod("parseCSV", String.class);
    method.setAccessible(true);
    SortedMap<Long, List<CircuitStatistics>> statistics = (SortedMap<Long, List<CircuitStatistics>>) method
            .invoke(circuitStatisticsCapab, statisticsInCSV);

    Assert.assertEquals("There's only one timestamp between this period of time", 1,
            statistics.keySet().size());
    Assert.assertNotNull("There should be statistics between this period of time.",
            statistics.get(FIRST_TIMESTAMP));
    Assert.assertEquals("There should be two statistics between this period of time.", 2,
            statistics.get(FIRST_TIMESTAMP).size());
    Assert.assertEquals(statistics.get(FIRST_TIMESTAMP).get(0), firstStatistics);
    Assert.assertEquals(statistics.get(FIRST_TIMESTAMP).get(1), secondStatistics);

    timePeriod = new TimePeriod(SECOND_TIMESTAMP - 1L, SECOND_TIMESTAMP);
    statisticsInCSV = circuitStatisticsCapab.getStatistics(timePeriod);
    Assert.assertFalse("Capability should contain statistics for this time period", statisticsInCSV.isEmpty());

    // call private method by reflection in order to parse CSV and make assertions
    method = circuitStatisticsCapab.getClass().getDeclaredMethod("parseCSV", String.class);
    method.setAccessible(true);
    statistics = (SortedMap<Long, List<CircuitStatistics>>) method.invoke(circuitStatisticsCapab,
            statisticsInCSV);

    Assert.assertEquals("There's only one timestamp between this period of time", 1,
            statistics.keySet().size());
    Assert.assertNotNull("There should be statistics between this period of time.",
            statistics.get(SECOND_TIMESTAMP));
    Assert.assertEquals("There should be one statistic between this period of time.", 1,
            statistics.get(SECOND_TIMESTAMP).size());
    Assert.assertEquals(statistics.get(SECOND_TIMESTAMP).get(0), thirdStatistics);

}

From source file:org.mitre.mpf.interop.JsonDetectionOutputObject.java

private int compareMap(SortedMap<String, String> map1, SortedMap<String, String> map2) {
    if (map1 == null && map2 == null) {
        return 0;
    } else if (map1 == null) {
        return -1;
    } else if (map2 == null) {
        return 1;
    } else {//from   w  w w.ja  va2 s  .  com
        int result = 0;
        if ((result = Integer.compare(map1.size(), map2.size())) != 0) {
            return result;
        }
        StringBuilder map1Str = new StringBuilder();
        for (String key : map1.keySet()) {
            map1Str.append(key).append(map1.get(key));
        }
        StringBuilder map2Str = new StringBuilder();
        for (String key : map2.keySet()) {
            map2Str.append(key).append(map2.get(key));
        }
        if ((result = ObjectUtils.compare(map1Str.toString(), map2Str.toString())) != 0) {
            return result;
        }
    }
    return 0;
}

From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step11GoldDataStatistics.java

/**
 * Relevant sentences per document (per query)
 *///from w ww. j  a  v  a  2  s . com
public static void statistics6(File inputDir, File outputDir) throws IOException {
    PrintWriter pw = new PrintWriter(new FileWriter(new File(outputDir, "stats6.csv")));

    SortedMap<String, DescriptiveStatistics> result = new TreeMap<>();
    result.put("relevantSentencesDocumentPercent", new DescriptiveStatistics());

    // print header
    for (String mapKey : result.keySet()) {
        pw.printf(Locale.ENGLISH, "%s\t%sStdDev\t", mapKey, mapKey);
    }
    pw.println();

    // iterate over query containers
    for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) {
        QueryResultContainer queryResultContainer = QueryResultContainer
                .fromXML(FileUtils.readFileToString(f, "utf-8"));
        System.out.println("Processing " + f);

        for (QueryResultContainer.SingleRankedResult rankedResult : queryResultContainer.rankedResults) {

            if (rankedResult.plainText != null && !rankedResult.plainText.isEmpty()) {

                int relevantSentences = 0;
                int totalSentences = 0;

                if (rankedResult.goldEstimatedLabels != null) {
                    for (QueryResultContainer.SingleSentenceRelevanceVote sentenceRelevanceVote : rankedResult.goldEstimatedLabels) {
                        totalSentences++;

                        if (Boolean.valueOf(sentenceRelevanceVote.relevant)) {
                            relevantSentences++;
                        }
                    }

                    // percent relevant

                    result.get("relevantSentencesDocumentPercent")
                            .addValue((double) relevantSentences / (double) totalSentences);
                }
            }
        }
    }

    // print results
    // print header
    for (String mapKey : result.keySet()) {
        pw.printf(Locale.ENGLISH, "%.3f\t%.3f\t", result.get(mapKey).getMean(),
                result.get(mapKey).getStandardDeviation());
    }

    pw.close();

}

From source file:com.android.build.gradle.internal.pipeline.InjectTransformManager.java

/**
 * ??Transform?Transform?//w w  w .  ja va2 s  . co m
 *
 * @param transformClazz
 * @param injectTransform
 * @param scope
 * @param <T>
 * @return
 */
public <T extends InjectTransform> TransformTask addInjectTransformBeforeTransform(
        Class<? extends Transform> transformClazz, T injectTransform, @NonNull VariantScope scope) {
    TaskCollection<DefaultAndroidTask> androidTasks = project.getTasks().withType(DefaultAndroidTask.class);
    SortedMap<String, DefaultAndroidTask> androidTaskSortedMap = androidTasks.getAsMap();
    TransformTask oprTransformTask = null; // ??
    for (String taskName : androidTaskSortedMap.keySet()) {
        DefaultAndroidTask androidTask = androidTaskSortedMap.get(taskName);
        if (variantName.equals(androidTask.getVariantName())) {
            if (androidTask instanceof TransformTask
                    && ((TransformTask) androidTask).getTransform().getClass().equals(transformClazz)) {
                oprTransformTask = (TransformTask) androidTask;
                break;
            }
        }
    }
    if (null == oprTransformTask) {
        throw new StopExecutionException(
                "TransformTask with transfrom type:" + transformClazz.getName() + " can not found!");
    }
    transforms.add(injectTransform);
    //2Transform??,?typetype
    checkTransformConfig(oprTransformTask.getTransform(), injectTransform);

    String taskName = scope.getTaskName(getTaskNamePrefix(injectTransform));

    try {
        IntermediateStream outputStream = getOutputStream(injectTransform, scope, taskName);

        // ?TransformTask
        TransformTaskParam transformTaskParam = getTransformParam(oprTransformTask);
        TransformTask.ConfigAction<T> configAction = new TransformTask.ConfigAction<T>(variantName, taskName,
                injectTransform, transformTaskParam.consumedInputStreams,
                transformTaskParam.referencedInputStreams, outputStream, ThreadRecorder.get(), null);

        TransformTask injectTransformTask = project.getTasks().create(configAction.getName(),
                configAction.getType());
        oprTransformTask.dependsOn(injectTransformTask);
        for (TransformStream transformStream : transformTaskParam.consumedInputStreams) {
            if (null != transformStream.getDependencies()) {
                injectTransformTask.dependsOn(transformStream.getDependencies());
            }
        }

        for (TransformStream transformStream : transformTaskParam.referencedInputStreams) {
            if (null != transformStream.getDependencies()) {
                injectTransformTask.dependsOn(transformStream.getDependencies());
            }
        }

        if (transformTaskList.size() > 0) {
            injectTransformTask.dependsOn(transformTaskList.get(transformTaskList.size() - 1));
        }
        transformTaskList.add(taskName);
        configAction.execute(injectTransformTask);

        //oprTransformTask
        if (injectTransform.updateNextTransformInput()) {
            Collection<TransformStream> newInputStream = Lists.newArrayList();
            newInputStream.add(outputStream);
            updateTransformTaskConfig(oprTransformTask, newInputStream,
                    transformTaskParam.referencedInputStreams, transformTaskParam.outputStream);
        }

        return injectTransformTask;
    } catch (IllegalAccessException e) {
        throw new StopExecutionException(e.getMessage());
    }
}

From source file:org.kuali.kpme.tklm.leave.block.web.LeaveBlockDisplayAction.java

private List<LeaveBlockDisplay> getLeaveEntries(String principalId, LocalDate serviceDate, LocalDate beginDate,
        LocalDate endDate, List<AccrualCategory> accrualCategories) {
    List<LeaveBlockDisplay> leaveEntries = new ArrayList<LeaveBlockDisplay>();

    List<LeaveBlock> leaveBlocks = LmServiceLocator.getLeaveBlockService().getLeaveBlocks(principalId,
            beginDate, endDate);//from   w w w. j av  a 2s .  c om

    for (LeaveBlock leaveBlock : leaveBlocks) {
        if (!leaveBlock.getLeaveBlockType().equals(LMConstants.LEAVE_BLOCK_TYPE.CARRY_OVER)) {
            leaveEntries.add(new LeaveBlockDisplay(leaveBlock));
        }
    }
    Collections.sort(leaveEntries, new Comparator<LeaveBlockDisplay>() {
        @Override
        public int compare(LeaveBlockDisplay o1, LeaveBlockDisplay o2) {
            return ObjectUtils.compare(o1.getLeaveDate(), o2.getLeaveDate());
        }
    });

    SortedMap<String, BigDecimal> accrualBalances = getPreviousAccrualBalances(principalId, serviceDate,
            beginDate, accrualCategories);

    for (LeaveBlockDisplay leaveEntry : leaveEntries) {
        for (AccrualCategory accrualCategory : accrualCategories) {
            if (!accrualBalances.containsKey(accrualCategory.getAccrualCategory())) {
                accrualBalances.put(accrualCategory.getAccrualCategory(), BigDecimal.ZERO);
            }
            BigDecimal currentAccrualBalance = accrualBalances.get(accrualCategory.getAccrualCategory());

            if (StringUtils.equals(leaveEntry.getAccrualCategory(), accrualCategory.getAccrualCategory())) {
                BigDecimal accruedBalance = currentAccrualBalance.add(leaveEntry.getLeaveAmount());
                accrualBalances.put(accrualCategory.getAccrualCategory(), accruedBalance);
            }

            leaveEntry.setAccrualBalance(accrualCategory.getAccrualCategory(),
                    accrualBalances.get(accrualCategory.getAccrualCategory()));
        }
    }

    return leaveEntries;
}

From source file:org.opencms.workplace.editors.CmsWorkplaceEditorManager.java

/**
 * Returns the editor URI for the current resource type.<p>
 * //from w w w  .j a  v  a  2s  .  co m
 * @param context the request context
 * @param resourceType the current resource type
 * @param userAgent the user agent String that identifies the browser
 * @return a valid editor URI for the resource type or null, if no editor matches
 */
protected String getEditorUri(CmsRequestContext context, String resourceType, String userAgent) {

    // step 1: check if the user specified a preferred editor for the given resource type
    CmsUserSettings settings = new CmsUserSettings(context.getCurrentUser());
    String preferredEditorSetting = settings.getPreferredEditor(resourceType);
    if (preferredEditorSetting == null) {
        // no preferred editor setting found for this resource type, look for mapped resource type preferred editor
        Iterator i = m_editorConfigurations.iterator();
        while (i.hasNext()) {
            CmsWorkplaceEditorConfiguration currentConfig = (CmsWorkplaceEditorConfiguration) i.next();
            String mapping = currentConfig.getMappingForResourceType(resourceType);
            if (mapping != null) {
                preferredEditorSetting = settings.getPreferredEditor(mapping);
            }
            if (preferredEditorSetting != null) {
                break;
            }
        }
    }
    if (preferredEditorSetting != null) {
        CmsWorkplaceEditorConfiguration preferredConf = filterPreferredEditor(preferredEditorSetting);
        if ((preferredConf != null) && preferredConf.matchesBrowser(userAgent)) {
            // return preferred editor only if it matches the current users browser
            return preferredConf.getEditorUri();
        }
    }

    // step 2: filter editors for the given resoure type
    SortedMap filteredEditors = filterEditorsForResourceType(resourceType);

    // step 3: check if one of the editors matches the current users browser
    while (filteredEditors.size() > 0) {
        // check editor configuration with highest ranking 
        Float key = (Float) filteredEditors.lastKey();
        CmsWorkplaceEditorConfiguration conf = (CmsWorkplaceEditorConfiguration) filteredEditors.get(key);
        if (conf.matchesBrowser(userAgent)) {
            return conf.getEditorUri();
        }
        filteredEditors.remove(key);
    }

    // no valid editor found 
    return null;
}

From source file:com.streamsets.pipeline.stage.processor.statsaggregation.TestMetricAggregationProcessor.java

@Test
public void testCountersForMetricRecord() throws StageException {
    MetricsRuleDefinition metricsRuleDefinition1 = TestHelper.createTestMetricRuleDefinition("a < b", true,
            System.currentTimeMillis());
    Record metricRuleChangeRecord = AggregatorUtil.createMetricRuleChangeRecord(metricsRuleDefinition1);
    Record metricRecord = createTestMetricRecord();
    runner.runProcess(Arrays.asList(metricRuleChangeRecord, metricRecord));

    MetricRegistry metrics = metricAggregationProcessor.getMetrics();

    SortedMap<String, Counter> counters = metrics.getCounters();
    Assert.assertTrue(counters.containsKey(
            "stage.com_streamsets_pipeline_stage_origin_spooldir_SpoolDirDSource_1:com_streamsets_pipeline_stage_origin_spooldir_SpoolDirDSource_1OutputLane14578524215930.outputRecords.counter"));
    Assert.assertEquals(1000, counters.get(
            "stage.com_streamsets_pipeline_stage_origin_spooldir_SpoolDirDSource_1:com_streamsets_pipeline_stage_origin_spooldir_SpoolDirDSource_1OutputLane14578524215930.outputRecords.counter")
            .getCount());//from  w  ww  .  j  a v a 2 s . c o m
    Assert.assertTrue(counters.containsKey(
            "stage.com_streamsets_pipeline_stage_processor_fieldhasher_FieldHasherDProcessor_1:com_streamsets_pipeline_stage_processor_fieldhasher_FieldHasherDProcessor_1OutputLane14578524269500.outputRecords.counter"));
    Assert.assertEquals(750, counters.get(
            "stage.com_streamsets_pipeline_stage_processor_fieldhasher_FieldHasherDProcessor_1:com_streamsets_pipeline_stage_processor_fieldhasher_FieldHasherDProcessor_1OutputLane14578524269500.outputRecords.counter")
            .getCount());
    Assert.assertTrue(counters.containsKey(
            "stage.com_streamsets_pipeline_stage_processor_expression_ExpressionDProcessor_1:com_streamsets_pipeline_stage_processor_expression_ExpressionDProcessor_1OutputLane14578524390500.outputRecords.counter"));
    Assert.assertEquals(500, counters.get(
            "stage.com_streamsets_pipeline_stage_processor_expression_ExpressionDProcessor_1:com_streamsets_pipeline_stage_processor_expression_ExpressionDProcessor_1OutputLane14578524390500.outputRecords.counter")
            .getCount());
}

From source file:org.opencms.workplace.editors.CmsWorkplaceEditorManager.java

/**
 * Returns the editor URI for the current resource type.<p>
 * //from   w w w  .j  a v  a2 s  . c  o  m
 * @param context the request context
 * @param userAgent the user agent String that identifies the browser
 * @return a valid editor URI for the resource type or null, if no editor matches
 */
public String getWidgetEditor(CmsRequestContext context, String userAgent) {

    // step 1: check if the user specified a preferred editor for the resource type xmlpage
    CmsUserSettings settings = new CmsUserSettings(context.getCurrentUser());
    String resourceType = CmsResourceTypeXmlPage.getStaticTypeName();
    String preferredEditorSetting = settings.getPreferredEditor(resourceType);
    if (preferredEditorSetting == null) {
        // no preferred editor setting found for this resource type, look for mapped resource type preferred editor
        Iterator i = m_editorConfigurations.iterator();
        while (i.hasNext()) {
            CmsWorkplaceEditorConfiguration currentConfig = (CmsWorkplaceEditorConfiguration) i.next();
            String mapping = currentConfig.getMappingForResourceType(resourceType);
            if (mapping != null) {
                preferredEditorSetting = settings.getPreferredEditor(mapping);
            }
            if (preferredEditorSetting != null) {
                break;
            }
        }
    }
    if (preferredEditorSetting != null) {
        CmsWorkplaceEditorConfiguration preferredConf = filterPreferredEditor(preferredEditorSetting);
        if ((preferredConf != null) && preferredConf.isWidgetEditor()
                && preferredConf.matchesBrowser(userAgent)) {
            // return preferred editor only if it matches the current users browser
            return preferredConf.getWidgetEditor();
        }
    }

    // step 2: filter editors for the given resoure type
    SortedMap filteredEditors = filterEditorsForResourceType(resourceType);

    // step 3: check if one of the editors matches the current users browser
    while (filteredEditors.size() > 0) {
        // check editor configuration with highest ranking 
        Float key = (Float) filteredEditors.lastKey();
        CmsWorkplaceEditorConfiguration conf = (CmsWorkplaceEditorConfiguration) filteredEditors.get(key);
        if (conf.isWidgetEditor() && conf.matchesBrowser(userAgent)) {
            return conf.getWidgetEditor();
        }
        filteredEditors.remove(key);
    }

    // no valid editor found 
    return null;
}

From source file:es.uvigo.ei.sing.gc.model.entities.ExpertResult.java

private synchronized void initClassificationPerformance() {
    if (this.performance == null && this.samples != null && !this.samples.isEmpty()) {
        final Set<Object> classes = new HashSet<Object>();
        Boolean multi = null;//  w  w w.j  av a 2  s.c  o m
        for (SampleClassification sample : this.samples) {
            if (multi == null) {
                multi = sample.isMultiStep();
            } else if (multi != sample.isMultiStep()) {
                throw new IllegalStateException("Different sample types");
            }

            classes.add(sample.getRealClass());
        }

        final Object[] classArray = classes.toArray(new Object[classes.size()]);
        if (multi) {
            final SortedMap<Integer, List<SampleClassification>> sampleMap = new TreeMap<Integer, List<SampleClassification>>();

            for (SampleClassification sample : this.samples) {
                if (!sampleMap.containsKey(sample.getStep())) {
                    sampleMap.put(sample.getStep(), new LinkedList<SampleClassification>());
                }

                sampleMap.get(sample.getStep()).add(sample);
            }

            for (Map.Entry<Integer, List<SampleClassification>> entry : sampleMap.entrySet()) {
                if (this.performance == null) {
                    this.performance = new DefaultMultiStepClassificationPerformance(
                            ExpertResult.createClassificationPerformance(
                                    Integer.toString(this.getId()) + "-Step " + entry.getKey(), classArray,
                                    entry.getValue()));
                } else {
                    this.performance = this.performance.merge(ExpertResult.createClassificationPerformance(
                            Integer.toString(this.getId()) + "-Step " + entry.getKey(), classArray,
                            entry.getValue()));
                }
            }
        } else {
            this.performance = ExpertResult.createClassificationPerformance(Integer.toString(this.getId()),
                    classArray, samples);
        }
    }
}