示例#1
0
 /**
  * Add three {@link AbundanceColumn} into {@link AbundanceColumn}, {@link #optionalColumnMapping}
  * and {@link #columnMapping} at one time. The header like: {Section}_abundance_study_variable[1],
  * {Section}_abundance_stdev_study_variable[1], {Section}_abundance_std_error_study_variable[1].
  *
  * @see AbundanceColumn#createOptionalColumns(Section, StudyVariable, String)
  * @param studyVariable SHOULD NOT empty.
  */
 public String addAbundanceOptionalColumn(StudyVariable studyVariable) {
   SortedMap<String, MZTabColumn> columns =
       AbundanceColumn.createOptionalColumns(
           section, studyVariable, getColumnOrder(columnMapping.lastKey()));
   abundanceColumnMapping.putAll(columns);
   optionalColumnMapping.putAll(columns);
   columnMapping.putAll(columns);
   return columns.lastKey();
 }
示例#2
0
 /**
  * Coefficient squarefree factorization.
  *
  * @param coeff coefficient.
  * @return [p_1 -&gt; e_1, ..., p_k -&gt; e_k] with P = prod_{i=1,...,k} p_i^{e_i} and p_i
  *     squarefree.
  */
 @Override
 public SortedMap<C, Long> squarefreeFactors(C coeff) {
   if (coeff == null) {
     return null;
   }
   SortedMap<C, Long> factors = new TreeMap<C, Long>();
   RingFactory<C> cfac = (RingFactory<C>) coeff.factory();
   if (aCoFac != null) {
     AlgebraicNumber<C> an = (AlgebraicNumber<C>) (Object) coeff;
     if (cfac.isFinite()) {
       SquarefreeFiniteFieldCharP<C> reng =
           (SquarefreeFiniteFieldCharP) SquarefreeFactory.getImplementation(cfac);
       SortedMap<C, Long> rfactors = reng.rootCharacteristic(coeff); // ??
       logger.info("rfactors,finite = " + rfactors);
       factors.putAll(rfactors);
       // return factors;
     } else {
       SquarefreeInfiniteAlgebraicFieldCharP<C> reng =
           (SquarefreeInfiniteAlgebraicFieldCharP) SquarefreeFactory.getImplementation(cfac);
       SortedMap<AlgebraicNumber<C>, Long> rfactors = reng.squarefreeFactors(an);
       logger.info("rfactors,infinite,algeb = " + rfactors);
       for (Map.Entry<AlgebraicNumber<C>, Long> me : rfactors.entrySet()) {
         AlgebraicNumber<C> c = me.getKey();
         if (!c.isONE()) {
           C cr = (C) (Object) c;
           Long rk = me.getValue(); // rfactors.get(c);
           factors.put(cr, rk);
         }
       }
     }
   } else if (qCoFac != null) {
     Quotient<C> q = (Quotient<C>) (Object) coeff;
     SquarefreeInfiniteFieldCharP<C> reng =
         (SquarefreeInfiniteFieldCharP) SquarefreeFactory.getImplementation(cfac);
     SortedMap<Quotient<C>, Long> rfactors = reng.squarefreeFactors(q);
     logger.info("rfactors,infinite = " + rfactors);
     for (Map.Entry<Quotient<C>, Long> me : rfactors.entrySet()) {
       Quotient<C> c = me.getKey();
       if (!c.isONE()) {
         C cr = (C) (Object) c;
         Long rk = me.getValue(); // rfactors.get(c);
         factors.put(cr, rk);
       }
     }
   } else if (cfac.isFinite()) {
     SquarefreeFiniteFieldCharP<C> reng =
         (SquarefreeFiniteFieldCharP) SquarefreeFactory.getImplementation(cfac);
     SortedMap<C, Long> rfactors = reng.rootCharacteristic(coeff); // ??
     logger.info("rfactors,finite = " + rfactors);
     factors.putAll(rfactors);
     // return factors;
   } else {
     logger.warn("case " + cfac + " not implemented");
   }
   return factors;
 }
  /** @see it.matrix.aod.postel.at.ATParserImpl#buildDetailsDataMap(java.util.TreeMap) */
  @Override
  public SortedMap<Integer, String> buildDetailsDataMap(TreeMap<Integer, String> rawMap) {

    SortedMap<Integer, String> _sm = new TreeMap<Integer, String>();
    SortedMap<Integer, String> _smtmp = new TreeMap<Integer, String>();

    Iterator<Entry<Integer, String>> mit = rawMap.entrySet().iterator();

    Integer[] fromKey = new Integer[15]; // max 15 pagine, è sufficiente Nicò? :-))	
    Integer[] toKey = new Integer[15];
    int i = 0;
    //		Integer fromKey = 0;
    //		Integer toKey = 0;
    while (mit.hasNext()) {
      Entry<Integer, String> entry = (Entry<Integer, String>) mit.next();
      if (entry.getValue().startsWith("!SPA -100")) {
        fromKey[i] = entry.getKey();
        i++;
      }

      if (entry.getValue().contains("!SPA 2;INL 0")) {
        toKey[i] = entry.getKey();
      }
    }

    for (int j = 0; j < i; j++) {
      // mit = rawMap.entrySet().iterator();
      _smtmp = rawMap.subMap(fromKey[j] + 1, fromKey[j] + ParserConstants.DAHLIA_DETAILS_PAG_SIZE);
      _sm.putAll(_smtmp);
    }

    return _sm;
  }
  public SortedMap<String, Requirement> read() throws IOException {
    SortedMap<String, Requirement> map = new ChildrenFirstOrderedMap();
    File jsonFile = new File(outputDirectory, rootDirectory + ".json");
    if (!jsonFile.exists()) {
      return map;
    }

    SortedMap<String, Requirement> storedRequirementsMap;
    Type requirementsMapType = new TypeToken<SortedMap<String, Requirement>>() {}.getType();
    try (FileReader reader = new FileReader(jsonFile)) {
      storedRequirementsMap = gson.fromJson(reader, requirementsMapType);
      if (storedRequirementsMap == null) {
        storedRequirementsMap = Collections.emptySortedMap();
      }
    }
    map.putAll(storedRequirementsMap);

    // reset the parents
    for (Map.Entry<String, Requirement> entry : storedRequirementsMap.entrySet()) {
      String key = entry.getKey();
      if (key.contains(".")) {
        String parent = key.substring(0, key.lastIndexOf("."));
        Requirement child = entry.getValue();
        updateParentChildren(map, parent, child);
      }
    }
    return map;
  }
示例#5
0
 public static SortedMap<Integer, AgreementSummaryInstance> findAllAgreementSummaries(
     int ucn, List<Integer> ucns, boolean primary, char status, char neStatus) throws Exception {
   SortedMap<Integer, AgreementSummaryInstance> agreementMap =
       findBillAgreementSummaries(ucn, null, primary, status, neStatus);
   agreementMap.putAll(findSiteAgreementSummaries(ucn, primary, status, neStatus));
   return agreementMap;
 }
示例#6
0
 public static SortedMap<Integer, Double> shortestPath(DirectedGraph g, int source) {
   final SortedMap<Integer, Double> previousDistances = new TreeMap<Integer, Double>();
   final SortedMap<Integer, Double> currentDistances = new TreeMap<Integer, Double>();
   currentDistances.put(source, 0d);
   for (Integer v : g.getVertices()) {
     if (v != source) {
       currentDistances.put(v, Double.POSITIVE_INFINITY);
     }
   }
   for (int i = 1; i <= g.getNumVertices(); i++) {
     previousDistances.clear();
     previousDistances.putAll(currentDistances);
     currentDistances.clear();
     for (Integer v : g.getVertices()) {
       Double currentDistance = Double.POSITIVE_INFINITY;
       Double previousDistance = previousDistances.get(v);
       if (previousDistance < currentDistance) {
         currentDistance = previousDistance;
       }
       for (Edge e : g.getIncomingEdges(v)) {
         Double alternativeDistance = previousDistances.get(e.getVertexA()) + e.getLength();
         if (alternativeDistance < currentDistance) {
           currentDistance = alternativeDistance;
         }
       }
       currentDistances.put(v, currentDistance);
     }
   }
   if (!previousDistances.equals(currentDistances)) {
     // there are negative cost cycles
     return null;
   }
   return previousDistances;
 }
示例#7
0
  @Override
  public boolean rollbackTx() throws Exception {
    if (consumingEntries.isEmpty()) {
      return true;
    }

    // Put the consuming entries back to cache
    entryCache.putAll(consumingEntries);

    // If not committed, no need to update HBase.
    if (!committed) {
      return true;
    }
    commitCount -= consumingEntries.size();

    // Revert changes in HBase rows
    // If it is FIFO, restore to the CLAIMED state. This instance will retry it on the next dequeue.
    if (consumerConfig.getDequeueStrategy() == DequeueStrategy.FIFO
        && consumerConfig.getGroupSize() > 1) {
      byte[] stateContent = encodeStateColumn(ConsumerEntryState.CLAIMED);
      updateState(consumingEntries.keySet(), stateColumnName, stateContent);
    } else {
      undoState(consumingEntries.keySet(), stateColumnName);
    }
    return true;
  }
  /**
   * @param boundType
   * @return
   * @see javax.xml.bind.annotation.adapters.XmlAdapter#marshal(java.lang.Object)
   */
  @Override
  public S marshal(final Map<K, V> boundType) {
    // Do not generate an empty tag for an empty map
    if ((boundType == null) || boundType.isEmpty()) {
      return null;
    }
    // Sort incoming map
    // Default sort
    SortedMap<K, V> sortedMap = CollectionUtil.newSortedMap();

    // Specified sort
    if (comparator != null) {
      sortedMap = CollectionUtil.newSortedMap(comparator);
    }

    sortedMap.putAll(boundType);

    // Convert to a list
    final List<E> list = CollectionUtil.newList();
    for (final Map.Entry<K, V> entry : sortedMap.entrySet()) {
      final E entryEntity = newEntryTypeInstance();
      entryEntity.setKey(entry.getKey());
      entryEntity.setValue(entry.getValue());
      list.add(entryEntity);
    }

    final S map = newValueTypeInstance();
    setValueTypeArray(map, list);
    return map;
  }
 private SortedMap<String, NamedTestResult> indexByTestName(
     List<NamedTestResult> namedTestResults) {
   Map<String, NamedTestResult> indexedTestResults =
       index(namedTestResults, on(NamedTestResult.class).getTestName());
   SortedMap<String, NamedTestResult> sortedTestResults = Maps.newTreeMap();
   sortedTestResults.putAll(indexedTestResults);
   return sortedTestResults;
 }
示例#10
0
 /** Deserializes a {@link DescriptorSupport} from an {@link ObjectInputStream}. */
 private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
   ObjectInputStream.GetField fields = in.readFields();
   Map<String, Object> descriptor = cast(fields.get("descriptor", null));
   init(null);
   if (descriptor != null) {
     descriptorMap.putAll(descriptor);
   }
 }
示例#11
0
  /** Přidá geotaging vzory, ty jsou asynchronně a později */
  public void addPatterns(
      final SortedMap<String, String> pattsSouradnice,
      final SortedMap<String, String> pattsGeocoding) {
    allPatterns.clear();
    if (pattsSouradnice != null) {
      souradnicovePatterns.clear();
      souradnicovePatterns.putAll(pattsSouradnice);
    }
    allPatterns.putAll(souradnicovePatterns);

    if (pattsGeocoding != null) {
      geotaggingPatterns.clear();
      geotaggingPatterns.putAll(pattsGeocoding);
    }
    allPatterns.putAll(geotaggingPatterns);

    keys.clear();
    keys.addAll(allPatterns.keySet());
    vyskladejCheckBox();
  }
  /**
   * Create a math evaluator with the same constants, variables, function handlers and relaxation
   * setting as the supplied evaluator.
   */
  public MathEval(MathEval oth) {
    super();

    operators = oth.operators;

    constants = new TreeMap<String, Double>(String.CASE_INSENSITIVE_ORDER);
    constants.putAll(oth.constants);

    variables = new TreeMap<String, Double>(String.CASE_INSENSITIVE_ORDER);
    variables.putAll(oth.variables);

    pureFunctions = new TreeMap<String, FunctionHandler>(String.CASE_INSENSITIVE_ORDER);
    impureFunctions = new TreeMap<String, FunctionHandler>(String.CASE_INSENSITIVE_ORDER);
    pureFunctions.putAll(oth.pureFunctions);
    impureFunctions.putAll(oth.impureFunctions);

    relaxed = oth.relaxed;
    separators = oth.separators;

    offset = 0;
    isConstant = false;
  }
  /**
   * Sorts the specified {@link Map} according to the natural ordering of its values.
   *
   * @param map The {@link Map} to sort
   * @return The {@link SortedMap}
   */
  public static <K, V extends Comparable<V>> SortedMap<K, V> sortByValues(final Map<K, V> map) {
    Comparator<K> valueComparator =
        new Comparator<K>() {
          public int compare(K k1, K k2) {
            int compare = map.get(k1).compareTo(map.get(k2));
            if (compare == 0) return 1;
            else return compare;
          }
        };

    SortedMap<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);
    sortedByValues.putAll(map);
    return sortedByValues;
  }
 public void saveJSONData(
     File reportDir,
     String data,
     List<ScriptCoverageCount> unloadJSData,
     UriFileTranslator uriFileTranslator) {
   try {
     lockOnReportDir(reportDir);
     reportDir.mkdirs();
     File jsonFile = new File(reportDir, "jscoverage.json");
     SortedMap<String, FileData> dataMap = new TreeMap<String, FileData>();
     if (jsonFile.exists()) {
       logger.info("Saving/merging JSON with existing JSON");
       String existingJSON = ioUtils.toString(jsonFile);
       if (uriFileTranslator.mutates()) {
         translateUris(data, uriFileTranslator, dataMap);
         dataMap =
             jsonDataMerger.mergeJSONCoverageMaps(dataMap, jsonDataMerger.jsonToMap(existingJSON));
       } else dataMap.putAll(jsonDataMerger.mergeJSONCoverageStrings(existingJSON, data));
       ioUtils.copy(jsonDataMerger.toJSON(dataMap), jsonFile);
     } else if (unloadJSData != null) {
       logger.info("Saving/merging JSON with unloaded JavaScript JSON");
       // Only scan for unloaded JS if JSON not saved before
       dataMap.putAll(jsonDataMerger.createEmptyJSON(unloadJSData));
       if (uriFileTranslator.mutates()) translateUris(data, uriFileTranslator, dataMap);
       else dataMap.putAll(jsonDataMerger.jsonToMap(data));
       ioUtils.copy(jsonDataMerger.toJSON(dataMap), jsonFile);
     } else {
       logger.info("Saving JSON");
       if (uriFileTranslator.mutates()) {
         translateUris(data, uriFileTranslator, dataMap);
         ioUtils.copy(jsonDataMerger.toJSON(dataMap), jsonFile);
       } else ioUtils.copy(data, jsonFile);
     }
   } finally {
     unlockOnReportDir(reportDir);
   }
 }
 @SuppressWarnings("unchecked")
 @Override
 protected void updateFromSnapshot(ObjectInput in, PersistentCollectionSnapshot snapshot) {
   if (snapshot.isInitialized()) {
     Comparator<? super K> comparator = null;
     try {
       comparator = snapshot.newComparator(in);
     } catch (Exception e) {
       throw new RuntimeException("Could not create instance of comparator", e);
     }
     SortedMap<K, V> map = new TreeMap<K, V>(comparator);
     map.putAll((Map<K, V>) snapshot.getElementsAsMap());
     init(map, snapshot.getDetachedState(), snapshot.isDirty());
   } else init(null, snapshot.getDetachedState(), false);
 }
  private String createSign(Map<String, String> params) {
    SortedMap<String, String> sortedMap = new TreeMap<>();
    sortedMap.putAll(params);

    List<String> keys = new ArrayList<>(params.keySet());
    Collections.sort(keys);

    StringBuffer toSign = new StringBuffer();
    for (int i = 0; i < keys.size(); i++) {
      String key = keys.get(i);
      String value = params.get(key);
      if (null != value && !"".equals(value)) {
        if (i == keys.size() - 1) {
          toSign.append(key + "=" + value);
        } else {
          toSign.append(key + "=" + value + "&");
        }
      }
    }
    String sign = hmacSha1(toSign.toString(), quickPayConfigStorage.getBankbaseKey());
    return sign;
  }
示例#17
0
  // use this method if you only have the input event
  private String registerEventOrDefinition(
      Event event, Map<String, Object> attributes, EventDefinition inputDef) {

    boolean gotInputDef = (inputDef != null);

    String escapedEventType;
    SortedMap<String, Class> map;

    if (gotInputDef) {
      map = inputDef.getProperties();
      escapedEventType = EsperNamingUtils.checkWordIsLegalEsperName(inputDef.getEventType());
    } else if (event == null || attributes == null) {
      log.warn("Got null input event or attributes in registerEventOrDefinition");
      return null;
    } else {
      // create map from attributes, throw out nulls
      map = new TreeMap<String, Class>();
      for (String name : attributes.keySet()) {
        Object attr = attributes.get(name);
        if (attr == null) continue;
        Class propertyClass = attr.getClass();
        map.put(name, propertyClass);
      }
      escapedEventType = EsperNamingUtils.checkWordIsLegalEsperName(event.getEventType());
    }

    // prepare event signature
    String eventSignature = getInputEventSignature(map);

    // see if we've seen this event before at all
    if (!inputEvents.containsKey(escapedEventType)) {

      log.info("registering new event definition: %s", escapedEventType);
      addInputEventSignature(escapedEventType, eventSignature);

      // first see if we have a pre-existing outputEvent, and if so, we need to merge properties
      // in case our new upper level event is narrower than previously registered base event
      // TODO: this is just a guard for the case where we have prevOutputDef one level down
      // TODO: (it won't help in case for multi-level distance, need to replace this with plugin
      // specific handling,
      // TODO:  to possibly find an ancestor prev def to use)
      EventDefinition prevOutputDef = this.getOutputEventDefinition(escapedEventType);
      EventDefinition newDef = null;
      if (prevOutputDef != null) {
        String msg =
            String.format(
                "detected differences with previously registered outputEvent: %s",
                escapedEventType);
        if (logPropertyDifferences(msg, prevOutputDef.getProperties(), map)) {

          if (gotInputDef) {
            // make a copy of def props
            map = new TreeMap<String, Class>();
            map.putAll(inputDef.getProperties());
            updateMapWithPrevOutputProperties(map, prevOutputDef.getProperties());
            newDef =
                new EventDefinition(
                    inputDef.getSourceEventClass(), escapedEventType, inputDef.getEvtClass(), map);
          } else {
            updateMapWithPrevOutputProperties(map, prevOutputDef.getProperties());
            newDef = new EventDefinition(event, escapedEventType, event.getClass(), map);
          }

          String updatedEventSignature = getInputEventSignature(map);
          addInputEventSignature(escapedEventType, updatedEventSignature);
        }
      }

      if (newDef == null) {
        if (!gotInputDef)
          newDef = new EventDefinition(event, escapedEventType, event.getClass(), map);
        else newDef = inputDef;
      }

      inputEvents.put(escapedEventType, newDef);
      registerEventStream(newDef);
    } else if (eventSignature != null
        && !checkInputEventSignatureRegistered(escapedEventType, eventSignature)) {
      log.info("got new signature for event type: %s", escapedEventType);

      // see if we have a new variant signature for a previously registered event
      if (gotInputDef) {
        // make a copy of def props
        map = new TreeMap<String, Class>();
        map.putAll(inputDef.getProperties());
      }

      String combinedEventSignature = null;
      EventDefinition prevDef = inputEvents.get(escapedEventType);
      String msg = String.format("detected updated event definition: %s", escapedEventType);

      if (logPropertyDifferences(msg, prevDef.getProperties(), map)) {
        map.putAll(prevDef.getProperties());
        combinedEventSignature = getInputEventSignature(map);
      } else {
        combinedEventSignature = eventSignature;
      }

      if (!checkInputEventSignatureRegistered(escapedEventType, combinedEventSignature)) {

        log.info("updating event definition registration: %s", escapedEventType);

        addInputEventSignature(escapedEventType, combinedEventSignature);

        EventDefinition combinedDef;
        if (gotInputDef) {
          combinedDef =
              new EventDefinition(
                  inputDef.getSourceEventClass(), escapedEventType, inputDef.getEvtClass(), map);
        } else {
          combinedDef = new EventDefinition(event, escapedEventType, event.getClass(), map);
        }
        inputEvents.put(escapedEventType, combinedDef);

        updateEventStream(combinedDef);
      }
      addInputEventSignature(escapedEventType, eventSignature);
    } else if (!inputEventRegistrationsValid.contains(escapedEventType)) {
      // this is a previously registered stream, but no currently valid EPL statements
      log.info("revalidating event type: %s", escapedEventType);
      inputEventRegistrationsValid.add(escapedEventType);
      notifyEventRegistered(inputEvents.get(escapedEventType));
    }

    return escapedEventType;
  }
 /**
  * Puts the contents of the specified builder into this builder.
  *
  * <p>The points are added one by one. If a date is duplicated it will overwrite an earlier entry.
  *
  * @param other the other builder
  * @return this builder
  */
 public LocalDateDoubleTimeSeriesBuilder putAll(LocalDateDoubleTimeSeriesBuilder other) {
   ArgChecker.notNull(other, "other");
   entries.putAll(other.entries);
   containsWeekends = containsWeekends || other.containsWeekends;
   return this;
 }
 public void putAll(Map<? extends K, ? extends V> map) {
   checkInit();
   delegate.putAll(map);
 }
示例#20
0
 private void init(Map<String, ?> initMap) {
   descriptorMap = new TreeMap<String, Object>(String.CASE_INSENSITIVE_ORDER);
   if (initMap != null) descriptorMap.putAll(initMap);
 }
  /**
   * Given concept vector which represents a text, calculate the category probabilities.
   *
   * @param cv
   * @param conceptLimit only conceptLimit concepts are used to calculate the category path
   *     distribution
   * @return category id -> scores
   */
  public SortedMap<Integer, Double> getCategoryDistribution(ConceptVector cv, int conceptLimit)
      throws WikitException {
    ConceptIterator conceptIterator = cv.orderedIterator();

    // Category ID --> Category
    Map<Integer, Category> bags = new HashMap<>();
    int count = 0;
    while (conceptIterator.next() && count++ < conceptLimit) {
      int conceptId = conceptIterator.getId();
      ConceptItem conceptItem = new ConceptItem(conceptId, conceptIterator.getValue());
      Set<Integer> catIds = treeCache.getCategoryIdsByConceptId(conceptId);
      conceptItem.catIds = catIds;

      for (int catId : catIds) {
        if (bags.containsKey(catId)) {
          bags.get(catId).addItem(conceptItem);
        } else {
          Category category = new Category(catId);
          category.addItem(conceptItem);
          bags.put(catId, category);
        }
      }
    }
    double totalScore = 0;
    SortedMap<Integer, Double> sortedScores = null;
    // category id -> score
    Map<Integer, Double> scores = new HashMap<>();

    //        LOG.info("Method 1:");
    //        for (Map.Entry<Integer, Category> entry : bags.entrySet()) {
    //            double categoryScore = 0;
    //            Category category = entry.getValue();
    //            for (ConceptItem item : category.concepts()) {
    //                categoryScore += item.value;
    //            }
    //            double normalizedScore = categoryScore/entry.getValue().size();
    //            scores.put(entry.getKey(), normalizedScore);
    //            totalScore += normalizedScore;
    //        }
    //
    //        sortedScores = new TreeMap<Integer,Double>(new ValueComparator(scores));
    //        sortedScores.putAll(scores);

    // Method 2, take link into account"
    double LAMBDA = 0.6;
    totalScore = 0;
    scores = new HashMap<>();
    for (Map.Entry<Integer, Category> entry : bags.entrySet()) {
      double categoryScore = 0;
      Category category = entry.getValue();
      for (ConceptItem conceptItem : category.concepts()) {
        double v1 = conceptItem.value;
        double v2 = 0.0;
        Set<Integer> inlinkIds = conceptCache.getInlinkIds(conceptItem.id);
        for (int inlinkId : inlinkIds) {
          if (category.hasConcept(inlinkId)) {
            v2 += category.getConcept(inlinkId).value;
            // System.out.println(inlink + "==>" + item.id + "\t" + item.title);
          }
        }
        if (inlinkIds.size() > 0) {
          v2 = v2 / inlinkIds.size(); // normalize
        }

        // if item connected with
        double v = LAMBDA * v1 + (1 - LAMBDA) * v2;
        categoryScore += v;
      }

      double normalizedScore = categoryScore / category.size();
      scores.put(category.id, normalizedScore);
      totalScore += normalizedScore;
    }

    sortedScores = new TreeMap<Integer, Double>(new ValueComparator<>(scores));

    boolean normalize = true;
    if (normalize) {
      // normalized the value
      for (Map.Entry<Integer, Double> entry : scores.entrySet()) {
        sortedScores.put(entry.getKey(), entry.getValue() / totalScore);
      }
    } else {
      sortedScores.putAll(scores);
    }
    return sortedScores;
  }
示例#22
0
  private <K, V> void verify(
      SortedMap<K, V> immutableMap, SortedMap<K, V> mutableMap, K key1, K key2, V value) {
    try {
      immutableMap.clear();

      Assert.assertTrue(mutableMap.isEmpty());
    } catch (UnsupportedOperationException e) {
      Assert.assertFalse(mutableMap.isEmpty());
    }

    Assert.assertEquals(immutableMap.containsKey(key1), mutableMap.containsKey(key1));
    Assert.assertEquals(immutableMap.containsKey(key2), mutableMap.containsKey(key2));

    Assert.assertEquals(immutableMap.containsValue(value), mutableMap.containsValue(value));
    Assert.assertEquals(immutableMap.containsValue(null), mutableMap.containsValue(null));

    Assert.assertEquals(immutableMap.entrySet(), mutableMap.entrySet());

    Assert.assertEquals(immutableMap.get(key1), mutableMap.get(key1));
    Assert.assertEquals(immutableMap.get(key2), mutableMap.get(key2));

    Assert.assertEquals(immutableMap.isEmpty(), mutableMap.isEmpty());

    Assert.assertEquals(immutableMap.keySet(), mutableMap.keySet());

    try {
      immutableMap.put(key1, value);
      Assert.fail();
    } catch (UnsupportedOperationException e) {
    }

    try {
      immutableMap.putAll(java.util.Collections.singletonMap(key1, value));
      Assert.fail();
    } catch (UnsupportedOperationException e) {
    }

    try {
      immutableMap.remove(key1);
    } catch (UnsupportedOperationException e) {
    }

    Assert.assertEquals(immutableMap.size(), mutableMap.size());

    // Is it OK that this fails?
    // Assert.assertEquals(immutableMap.values(), mutableMap.values());
    Assert.assertEquals(immutableMap.values().size(), mutableMap.values().size());
    if (!mutableMap.isEmpty()) {
      Assert.assertEquals(
          immutableMap.values().iterator().next(), mutableMap.values().iterator().next());
    }

    Assert.assertSame(immutableMap.comparator(), mutableMap.comparator());

    if (!mutableMap.isEmpty()) {
      Assert.assertEquals(immutableMap.firstKey(), mutableMap.firstKey());
      Assert.assertEquals(immutableMap.lastKey(), mutableMap.lastKey());
    } else {
      try {
        immutableMap.firstKey();
        Assert.fail();
      } catch (NoSuchElementException e) {
      }

      try {
        immutableMap.lastKey();
        Assert.fail();
      } catch (NoSuchElementException e) {
      }
    }

    Assert.assertEquals(immutableMap.headMap(key1), mutableMap.headMap(key1));
    Assert.assertEquals(immutableMap.headMap(key2), mutableMap.headMap(key2));

    Assert.assertEquals(immutableMap.subMap(key1, key2), mutableMap.subMap(key1, key2));

    Assert.assertEquals(immutableMap.tailMap(key1), mutableMap.tailMap(key1));
    Assert.assertEquals(immutableMap.tailMap(key2), mutableMap.tailMap(key2));
  }