Example usage for java.util SortedMap put

List of usage examples for java.util SortedMap put

Introduction

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

Prototype

V put(K key, V value);

Source Link

Document

Associates the specified value with the specified key in this map (optional operation).

Usage

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

/**
 * Other statistics: we want to report how many documents and sentences
 * were judged and how many were found relevant among those.
 * Having the total + standard deviation over queries is enough.
 *//*www.j  a va  2 s .  c  o  m*/
public static void statistics5(File inputDir, File outputDir) throws IOException {
    PrintWriter pw = new PrintWriter(new FileWriter(new File(outputDir, "stats5.csv")));

    SortedMap<String, DescriptiveStatistics> result = new TreeMap<>();
    result.put("annotatedDocumentsPerQuery", new DescriptiveStatistics());
    result.put("annotatedSentencesPerQuery", new DescriptiveStatistics());
    result.put("relevantSentencesPerQuery", 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);

        int annotatedDocuments = 0;
        int relevantSentences = 0;
        int totalSentences = 0;

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

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

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

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

        result.get("annotatedDocumentsPerQuery").addValue(annotatedDocuments);
        result.get("annotatedSentencesPerQuery").addValue(totalSentences);
        result.get("relevantSentencesPerQuery").addValue(relevantSentences);
    }

    // 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:org.fede.util.Util.java

private static MoneyAmountSeries read(String name) {

    try (InputStream is = Util.class.getResourceAsStream("/" + name)) {

        final JSONSeries series = CONSULTATIO_SERIES.contains(name) ? readConsultatioSeries(is, OM)
                : OM.readValue(is, JSONSeries.class);

        final SortedMap<YearMonth, MoneyAmount> interpolatedData = new TreeMap<>();
        final String currency = series.getCurrency();
        for (JSONDataPoint dp : series.getData()) {
            if (interpolatedData.put(new YearMonth(dp.getYear(), dp.getMonth()),
                    new MoneyAmount(dp.getValue(), currency)) != null) {
                throw new IllegalArgumentException("Series " + name + " has two values for year " + dp.getYear()
                        + " and month " + dp.getMonth());
            }//from   w ww. ja  v a2  s . co m
        }

        final InterpolationStrategy strategy = InterpolationStrategy.valueOf(series.getInterpolation());

        YearMonth ym = interpolatedData.firstKey();
        final YearMonth last = interpolatedData.lastKey();
        while (ym.monthsUntil(last) > 0) {
            YearMonth next = ym.next();
            if (!interpolatedData.containsKey(next)) {
                interpolatedData.put(next, strategy.interpolate(interpolatedData.get(ym), ym, currency));
            }
            ym = ym.next();
        }
        return new SortedMapMoneyAmountSeries(currency, interpolatedData);

    } catch (IOException ioEx) {
        throw new IllegalArgumentException("Could not read series named " + name, ioEx);
    }

}

From source file:com.asakusafw.yaess.tools.GenerateExecutionId.java

static Configuration parseConfiguration(String[] args) throws ParseException {
    assert args != null;
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(OPTIONS, args);

    String batchId = cmd.getOptionValue(OPT_BATCH_ID.getOpt());
    String flowId = cmd.getOptionValue(OPT_FLOW_ID.getOpt());
    Properties arguments = cmd.getOptionProperties(OPT_ARGUMENT.getOpt());

    SortedMap<String, String> pairs = new TreeMap<>();
    for (Map.Entry<Object, Object> entry : arguments.entrySet()) {
        Object key = entry.getKey();
        Object value = entry.getValue();
        if (key instanceof String && value instanceof String) {
            pairs.put((String) key, (String) value);
        }//ww w. j a  v  a2 s.co  m
    }
    Configuration result = new Configuration();
    result.batchId = batchId;
    result.flowId = flowId;
    result.arguments = pairs;
    return result;
}

From source file:com.pinterest.secor.parser.MessageParser.java

public static List[] listFromJsonSorted(org.json.JSONObject json) {
    if (json == null)
        return null;
    SortedMap map = new TreeMap();
    Iterator i = json.keys();//from  w  w w .j  a v  a  2 s.  co  m
    while (i.hasNext()) {
        try {
            String key = i.next().toString();
            //System.out.println(key);
            String j = json.getString(key);
            map.put(key, j);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    LinkedList keys = new LinkedList(map.keySet());
    LinkedList values = new LinkedList(map.values());
    List[] variable = new List[2];
    variable[0] = keys;
    variable[1] = values;
    return variable;
}

From source file:com.cloudera.oryx.kmeans.common.Weighted.java

/**
 * Sample items from a {@code List<Weighted>} where items with higher weights
 * have a higher probability of being included in the sample.
 * /*w ww  . j  a v  a 2 s.  co m*/
 * @param things The iterable to sample from
 * @param size The number of items to sample
 * @return A list containing the sampled items
 */
public static <T extends Weighted<?>> List<T> sample(Iterable<T> things, int size, RandomGenerator random) {
    if (random == null) {
        random = RandomManager.getRandom();
    }
    SortedMap<Double, T> sampled = Maps.newTreeMap();
    for (T thing : things) {
        if (thing.weight() > 0) {
            double score = Math.log(random.nextDouble()) / thing.weight();
            if (sampled.size() < size || score > sampled.firstKey()) {
                sampled.put(score, thing);
            }
            if (sampled.size() > size) {
                sampled.remove(sampled.firstKey());
            }
        }
    }
    return Lists.newArrayList(sampled.values());
}

From source file:annis.CSVHelper.java

public static SortedMap<Integer, SortedSet<String>> exportCSVHeader(Iterator<AnnotatedMatch> matches,
        PrintWriter w) {//from w w  w .j  av  a2s .  c  o m
    // figure out what annotations are used at each match position
    SortedMap<Integer, SortedSet<String>> columnsByNodePos = new TreeMap<>();
    while (matches.hasNext()) {
        AnnotatedMatch match = matches.next();
        for (int j = 0; j < match.size(); ++j) {
            AnnotatedSpan span = match.get(j);
            if (columnsByNodePos.get(j) == null) {
                columnsByNodePos.put(j, new TreeSet<String>());
            }
            for (Annotation annotation : span.getAnnotations()) {
                columnsByNodePos.get(j).add("anno_" + annotation.getQualifiedName());
            }

            for (Annotation meta : span.getMetadata()) {
                columnsByNodePos.get(j).add("meta_" + meta.getQualifiedName());
            }

        }
    }

    CSVWriter csvWriter = new CSVWriter(w, '\t', CSVWriter.NO_QUOTE_CHARACTER, '\\');
    // print column names and data types
    int count = columnsByNodePos.keySet().size();
    ArrayList<String> headerLine = new ArrayList<>();

    for (int j = 0; j < count; ++j) {
        headerLine.add(fullColumnName(j + 1, "id"));
        headerLine.add(fullColumnName(j + 1, "span"));

        SortedSet<String> annotationNames = columnsByNodePos.get(j);
        for (String name : annotationNames) {
            headerLine.add(fullColumnName(j + 1, name));
        }
    }
    csvWriter.writeNext(headerLine.toArray(new String[headerLine.size()]));

    return columnsByNodePos;
}

From source file:org.eel.kitchen.jsonschema.util.JacksonUtils.java

/**
 * Return a sorted map out of an object instance
 *
 * <p>This is used by syntax validation especially: it is more convenient to
 * present validation messages in key order.</p>
 *
 * @param node the node/*from  w ww  . j  av a  2s  . c  om*/
 * @return a mutable map made of the instance's entries
 */
public static SortedMap<String, JsonNode> nodeToTreeMap(final JsonNode node) {
    final SortedMap<String, JsonNode> ret = Maps.newTreeMap();

    final Iterator<Map.Entry<String, JsonNode>> iterator = node.fields();

    Map.Entry<String, JsonNode> entry;
    while (iterator.hasNext()) {
        entry = iterator.next();
        ret.put(entry.getKey(), entry.getValue());
    }

    return ret;
}

From source file:com.facebook.buck.util.unarchive.Unzip.java

private static void fillIntermediatePaths(Path path, SortedMap<Path, ZipArchiveEntry> pathMap) {
    for (Path p = path.getParent(); p != null; p = p.getParent()) {
        if (pathMap.containsKey(p)) {
            break;
        }/* www . j  a  v  a 2  s  . c  om*/
        pathMap.put(p, new ZipArchiveEntry(p + "/"));
    }
}

From source file:annis.WekaHelper.java

public static String exportAsArff(List<AnnotatedMatch> annotatedMatches) {
    StringBuilder sb = new StringBuilder();

    // header: relation name (unused)
    sb.append("@relation name\n");
    sb.append("\n");

    // figure out what annotations are used at each match position
    SortedMap<Integer, SortedSet<String>> columnsByNodePos = new TreeMap<Integer, SortedSet<String>>();

    for (int i = 0; i < annotatedMatches.size(); ++i) {
        AnnotatedMatch match = annotatedMatches.get(i);
        for (int j = 0; j < match.size(); ++j) {
            AnnotatedSpan span = match.get(j);
            if (columnsByNodePos.get(j) == null) {
                columnsByNodePos.put(j, new TreeSet<String>());
            }/*w  ww  .j  a v a 2 s  .  c  o m*/
            for (Annotation annotation : span.getAnnotations()) {
                columnsByNodePos.get(j).add("anno_" + annotation.getQualifiedName());
            }

            for (Annotation meta : span.getMetadata()) {
                columnsByNodePos.get(j).add("meta_" + meta.getQualifiedName());
            }

        }
    }

    // print column names and data types
    int count = columnsByNodePos.keySet().size();

    for (int j = 0; j < count; ++j) {
        sb.append("@attribute ").append(fullColumnName(j + 1, "id")).append(" string\n");
        sb.append("@attribute ").append(fullColumnName(j + 1, "span")).append(" string\n");
        SortedSet<String> annotationNames = columnsByNodePos.get(j);
        for (String name : annotationNames) {
            sb.append("@attribute ").append(fullColumnName(j + 1, name)).append(" string\n");
        }
    }
    sb.append("\n@data\n\n");

    // print values
    for (AnnotatedMatch match : annotatedMatches) {
        List<String> line = new ArrayList<String>();
        int k = 0;
        for (; k < match.size(); ++k) {
            AnnotatedSpan span = match.get(k);
            Map<String, String> valueByName = new HashMap<String, String>();

            if (span != null) {
                if (span.getAnnotations() != null) {
                    for (Annotation annotation : span.getAnnotations()) {
                        valueByName.put("anno_" + annotation.getQualifiedName(), annotation.getValue());
                    }
                }
                if (span.getMetadata() != null) {
                    for (Annotation meta : span.getMetadata()) {
                        valueByName.put("meta_" + meta.getQualifiedName(), meta.getValue());
                    }
                }

                line.add("'" + span.getId() + "'");
                line.add("'" + span.getCoveredText().replace("'", "\\'") + "'");
            }

            for (String name : columnsByNodePos.get(k)) {
                if (valueByName.containsKey(name)) {
                    line.add("'" + valueByName.get(name).replace("'", "\\'") + "'");
                } else {
                    line.add("'NULL'");
                }
            }
        }
        for (int l = k; l < count; ++l) {
            line.add("'NULL'");
            for (int m = 0; m <= columnsByNodePos.get(l).size(); ++m) {
                line.add("'NULL'");
            }
        }
        sb.append(StringUtils.join(line, ","));
        sb.append("\n");
    }

    return sb.toString();
}

From source file:com.redhat.rhn.frontend.action.kickstart.PowerManagementAction.java

/**
 * Sets up and returns a list of supported Cobbler power types.
 * @param request the current request/*  ww w. ja v a2 s. c  om*/
 * @param strutsDelegate the Struts delegate
 * @param errors ActionErrors that might have already been raised
 * @return the types
 */
public static SortedMap<String, String> setUpPowerTypes(HttpServletRequest request,
        StrutsDelegate strutsDelegate, ActionErrors errors) {
    SortedMap<String, String> types = new TreeMap<String, String>();
    String typeString = ConfigDefaults.get().getCobblerPowerTypes();
    if (typeString != null) {
        List<String> typeNames = Arrays.asList(typeString.split(" *, *"));
        for (String typeName : typeNames) {
            types.put(LocalizationService.getInstance().getPlainText("cobbler.powermanagement." + typeName),
                    typeName);
        }
    }
    request.setAttribute(TYPES, types);

    if (types.size() == 0) {
        strutsDelegate.addError(errors, "kickstart.powermanagement.jsp.no_types",
                ConfigDefaults.POWER_MANAGEMENT_TYPES);
        strutsDelegate.saveMessages(request, errors);
    }
    return types;
}