Example usage for java.util HashMap keySet

List of usage examples for java.util HashMap keySet

Introduction

In this page you can find the example usage for java.util HashMap keySet.

Prototype

public Set<K> keySet() 

Source Link

Document

Returns a Set view of the keys contained in this map.

Usage

From source file:fr.inria.edelweiss.kgimport.RdfSplitter.java

/**
 * Saves a set of RDF fragments to RDF files.
 *
 * @param fragments the input fragments to be persisted.
 *//*from   w  ww. j  av  a2s .  c o m*/
public void saveFragmentsRDF(HashMap<String, Model> fragments) {
    int i = 1;
    for (String k : fragments.keySet()) {
        Model frag = fragments.get(k);
        File oF = new File(
                this.getOutputDirPath() + "/" + k.replace("/", "_").replace(":", "_") + "-frag-" + i + ".rdf");
        OutputStream oS;
        try {
            oS = new FileOutputStream(oF);
            frag.write(oS, "RDF/XML");
            logger.info("Written " + oF.getAbsolutePath() + " - size = " + frag.size() + " triples");
            i++;
        } catch (FileNotFoundException ex) {
            logger.error("File " + oF.getAbsolutePath() + " not found !");
        }
    }
}

From source file:fr.inria.edelweiss.kgimport.RdfSplitter.java

/**
 * Saves a set of RDF fragments to a JENA TDB backend.
 *
 * @param fragments the input fragments to be persisted.
 */// w  w  w .ja v a  2 s. c om
public void saveFragmentsTDB(HashMap<String, Model> fragments) {
    int i = 1;
    for (String k : fragments.keySet()) {
        Model frag = fragments.get(k);

        String directory = this.getOutputDirPath() + "/" + k.replace("/", "_").replace(":", "_") + "-TDB#" + i;
        Dataset dataset = TDBFactory.createDataset(directory);
        dataset.begin(ReadWrite.WRITE);
        Model tdbModel = dataset.getDefaultModel();
        tdbModel.add(frag);
        dataset.commit();
        dataset.end();

        logger.info("Written " + directory + " - size = " + tdbModel.size() + " triples");
        i++;
    }
}

From source file:gr.cti.android.experimentation.service.ModelService.java

public String assignColor(HashMap<Integer, String> deviceColors, Integer deviceID) {
    String color = "http://maps.google.com/mapfiles/ms/icons/blue-dot.png";

    if (deviceColors.containsKey(deviceID)) {
        color = deviceColors.get(deviceID);
        return color;
    }//ww w . j  ava2  s .com
    int numOfDev = deviceColors.keySet().size();
    if (numOfDev % 6 == 0)
        color = "http://maps.google.com/mapfiles/ms/icons/blue-dot.png";
    else if (numOfDev % 6 == 1)
        color = "http://maps.google.com/mapfiles/ms/icons/red-dot.png";
    else if (numOfDev % 6 == 2)
        color = "http://maps.google.com/mapfiles/ms/icons/green-dot.png";
    else if (numOfDev % 6 == 3)
        color = "http://maps.google.com/mapfiles/ms/icons/yellow-dot.png";
    else if (numOfDev % 6 == 4)
        color = "http://maps.google.com/mapfiles/ms/icons/purple-dot.png";
    else if (numOfDev % 6 == 5)
        color = "http://maps.google.com/mapfiles/ms/icons/pink-dot.png";
    deviceColors.put(deviceID, color);
    return color;
}

From source file:fast.servicescreen.server.RequestServiceImpl.java

@Override
public String sendHttpRequest_GET(String url, HashMap<String, String> headers) {
    // create httpClient and httpGET container
    DefaultHttpClient httpclient_GET = new DefaultHttpClient();
    httpget = new HttpGet(url);

    //add all headers
    if (headers != null) {
        for (Iterator<String> iterator = headers.keySet().iterator(); iterator.hasNext();) {
            String tmpKey = (String) iterator.next();
            String tmpVal = headers.get(tmpKey);
            httpget.addHeader(tmpKey, tmpVal);
        }/*from w  w  w.  j  a va 2 s.c  o  m*/
    }

    // Create response handler
    responseHandler = new BasicResponseHandler();

    try {
        // send the GET request
        responseBody = httpclient_GET.execute(httpget, responseHandler);
    } catch (Exception e) {
        e.printStackTrace();
        responseBody = "-1";
    }
    return responseBody;
}

From source file:com.compomics.util.experiment.identification.psm_scoring.psm_scores.HyperScore.java

/**
 * Returns the interpolation values for the given score histogram in the
 * form {a, b}./*  w w w . j  av  a2s .c o m*/
 *
 * @param scoreHistogram the score histogram
 * @param useCache if true the interpolation values will be stored in the
 * histograms in cache
 *
 * @return the interpolation values for the given score histogram
 */
public double[] getInterpolationValues(HashMap<Integer, Integer> scoreHistogram, boolean useCache) {

    ArrayList<Integer> bins = new ArrayList<Integer>(scoreHistogram.keySet());
    Collections.sort(bins, Collections.reverseOrder());
    ArrayList<Double> evalueFunctionX = new ArrayList<Double>(scoreHistogram.size());
    ArrayList<Double> evalueFunctionY = new ArrayList<Double>(scoreHistogram.size());
    Integer currentSum = 0;
    for (Integer bin : bins) {
        Integer nInBin = scoreHistogram.get(bin);
        if (nInBin != null) {
            currentSum += nInBin;
        }
        if (currentSum > 0) {
            Double xValue = new Double(bin);
            xValue = FastMath.log10(xValue);
            evalueFunctionX.add(xValue);
            Double yValue = new Double(currentSum);
            yValue = FastMath.log10(yValue);
            evalueFunctionY.add(yValue);
        }
    }
    if (evalueFunctionX.size() <= 1) {
        return null;
    }
    RegressionStatistics regressionStatistics = LinearRegression.getSimpleLinearRegression(evalueFunctionX,
            evalueFunctionY);
    if (useCache) {
        Double roundedA = Util.roundDouble(regressionStatistics.a, 2);
        Double roundedB = Util.roundDouble(regressionStatistics.b, 2);
        Integer nA = as.get(roundedA);
        if (nA == null) {
            as.put(roundedA, 1);
        } else {
            as.put(roundedA, nA + 1);
        }
        Integer nB = bs.get(roundedB);
        if (nB == null) {
            bs.put(roundedB, 1);
        } else {
            bs.put(roundedB, nB + 1);
        }
    }
    return new double[] { regressionStatistics.a, regressionStatistics.b };
}

From source file:com.marketcloud.marketcloud.Json.java

/**
 * Parses a JSONObject, looking for the given structure. <br />
 * <br />/* w  w  w .  j  a v a 2 s  .  c o  m*/
 * It differs from the other parseData because the user should provide a pre-prepared Hashmap that will be
 * filled by the method. The keys of the map will be used as the string array of the other parseData.
 * <br />
 * In order to avoid override of data that you need to keep, and to use the method without getting an
 * exception, you could pass an "ignore" list containing the keys that you want the method to ignore,
 * simply adding all the keys you want to ignore to the method call. <br />
 * Example: parseData(map, jsonObject, "price", "source"); <br />
 * If the map contains the keys "price" and "source", then the method will ignore them. <br />
 * The normal method call remains: parseData(map, jsonObject) .
 * <br />
 * Note: if the structure is not correct, the method will throw an exception and fail. If the JSONObject
 * contains a JSONArray, only the first argument of the array (the first object) will be parsed.
 *
 * @param map pre-prepared Hashmap
 * @return an Hashmap with the parsed data
 */
@SuppressWarnings("unused")
public HashMap<String, Object> parseData(HashMap<String, Object> map, JSONObject jsonObject, String... ignore)
        throws JSONException {
    if (jsonObject.has("data"))
        jsonObject = getData(jsonObject)[0];

    ArrayList<String> ignorelist = new ArrayList<>();

    Collections.addAll(ignorelist, ignore);

    for (String key : map.keySet()) {
        if (!ignorelist.contains(key))
            map.put(key, jsonObject.get(key));
    }

    return map;
}

From source file:com.vincestyling.netroid.stack.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request) throws IOException, AuthFailureError {
    HashMap<String, String> map = new HashMap<String, String>();
    if (!TextUtils.isEmpty(mUserAgent)) {
        map.put(HTTP.USER_AGENT, mUserAgent);
    }//from www.j a  v a 2  s. com
    map.putAll(request.getHeaders());

    URL parsedUrl = new URL(request.getUrl());
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }

    setConnectionParametersForRequest(connection, request);

    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }

    StatusLine responseStatus = new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1),
            connection.getResponseCode(), connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) {
        response.setEntity(entityFromConnection(connection));
    }

    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }

    return response;
}

From source file:edu.illinois.cs.cogcomp.transliteration.WikiTransliteration.java

/**
 * Gets counts for productions by (conceptually) summing over all the possible alignments
 * and weighing each alignment (and its constituent productions) by the given probability table.
 * probSum is important (and memoized for input word pairs)--it keeps track and returns the sum of the
 * probabilities of all possible alignments for the word pair
 *
 * This is Algorithm 3 in the paper.//from  w  ww .  j av  a2 s . c  o  m
 *
 * @param word1
 * @param word2
 * @param maxSubstringLength1
 * @param maxSubstringLength2
 * @param probs
 * @param memoizationTable
 * @return a hashmap and double as a pair. The double is y, a normalization constant. The hashmap is a table of substring pairs
 * and their unnormalized counts
 */
public static Pair<HashMap<Production, Double>, Double> CountWeightedAlignmentsHelper(String word1,
        String word2, int maxSubstringLength1, int maxSubstringLength2, HashMap<Production, Double> probs,
        HashMap<Production, Pair<HashMap<Production, Double>, Double>> memoizationTable) {
    double probSum;

    Pair<HashMap<Production, Double>, Double> memoization;
    for (int orig = 0; orig < SPModel.numOrigins; orig++) {
        if (memoizationTable.containsKey(new Production(word1, word2, orig))) {
            memoization = memoizationTable.get(new Production(word1, word2, orig));
            probSum = memoization.getSecond(); //stored probSum
            return new Pair<>(memoization.getFirst(), probSum); //table of probs
        }
    }

    HashMap<Production, Double> result = new HashMap<>(); // this is C in Algorithm 3 in the paper
    probSum = 0; // this is R in Algorithm 3 in the paper

    if (word1.length() == 0 && word2.length() == 0) //record probabilities
    {
        probSum = 1; //null -> null is always a perfect alignment
        return new Pair<>(result, probSum); //end of the line
    }

    int maxSubstringLength1f = Math.min(word1.length(), maxSubstringLength1);
    int maxSubstringLength2f = Math.min(word2.length(), maxSubstringLength2);

    for (int orig = 0; orig < SPModel.numOrigins; orig++) {
        for (int i = 1; i <= maxSubstringLength1f; i++) //for each possible substring in the first word...
        {
            String substring1 = word1.substring(0, i);

            for (int j = 1; j <= maxSubstringLength2f; j++) //for possible substring in the second
            {
                if ((word1.length() - i) * maxSubstringLength2 >= word2.length() - j
                        && (word2.length() - j) * maxSubstringLength1 >= word1.length() - i) //if we get rid of these characters, can we still cover the remainder of word2?
                {
                    String substring2 = word2.substring(0, j);

                    Production production = new Production(substring1, substring2, orig);
                    double prob = probs.get(production);

                    // recurse here. Result is Q in Algorithm 3
                    Pair<HashMap<Production, Double>, Double> Q = CountWeightedAlignmentsHelper(
                            word1.substring(i), word2.substring(j), maxSubstringLength1, maxSubstringLength2,
                            probs, memoizationTable);

                    HashMap<Production, Double> remainderCounts = Q.getFirst();
                    Double remainderProbSum = Q.getSecond();

                    Dictionaries.IncrementOrSet(result, production, prob * remainderProbSum,
                            prob * remainderProbSum);

                    //update our probSum
                    probSum += remainderProbSum * prob;

                    //update all the productions that come later to take into account their preceding production's probability
                    for (Production key : remainderCounts.keySet()) {
                        Double value = remainderCounts.get(key);
                        Dictionaries.IncrementOrSet(result, key, prob * value, prob * value);
                    }
                }
            }
        }
    }

    for (int orig = 0; orig < SPModel.numOrigins; orig++) {
        memoizationTable.put(new Production(word1, word2, orig), new Pair<>(result, probSum));
    }
    return new Pair<>(result, probSum);
}

From source file:de.uzk.hki.da.metadata.EadMetsMetadataStructure.java

@Override
public List<File> getReferencedFiles(File metadataFile, List<String> references,
        List<de.uzk.hki.da.model.Document> documents) {
    HashMap<File, Boolean> fileExistenceMap = checkExistenceOfReferencedFiles(metadataFile, references,
            documents);//from   ww  w .  j  a va2  s .com
    List<File> existingMetsFiles = new ArrayList<File>();
    for (File file : fileExistenceMap.keySet()) {
        if (fileExistenceMap.get(file) == true) {
            existingMetsFiles.add(file);
        }
    }
    return existingMetsFiles;
}

From source file:eu.planets_project.pp.plato.evaluation.evaluators.XCLEvaluator.java

public HashMap<MeasurementInfoUri, Value> evaluate(Alternative alternative, SampleObject sample,
        DigitalObject result, List<MeasurementInfoUri> measurementInfoUris, IStatusListener listener)
        throws EvaluatorException {
    HashMap<MeasurementInfoUri, Value> results = new HashMap<MeasurementInfoUri, Value>();

    // maybe we should characterise objects where xcdl descriptions are missing
    if ((sample.getXcdlDescription() == null) || !sample.getXcdlDescription().isDataExistent()) {
        listener.updateStatus(/* ww  w  .j av a  2 s  .c om*/
                "XCDL description of sample object " + sample.getFullname() + " is missing. Please generate!");
        return results;
    }
    if ((result.getXcdlDescription() == null) || !result.getXcdlDescription().isDataExistent()) {
        listener.updateStatus("XCDL description of result of action " + alternative.getName() + " for sample "
                + sample.getFullname() + " is missing.  Please generate!");
        return results;
    }

    setUp();

    try {
        // dump XCDL descriptions to temp files
        String tempPath = OS.completePathWithSeparator(tempDir.getAbsolutePath());
        String sampleXCDLFile = tempPath + "sample.xcdl";
        String resultXCDLFile = tempPath + "result.xcdl";

        FileUtils.writeToFile(new ByteArrayInputStream(sample.getXcdlDescription().getData().getData()),
                new FileOutputStream(sampleXCDLFile));
        FileUtils.writeToFile(new ByteArrayInputStream(result.getXcdlDescription().getData().getData()),
                new FileOutputStream(resultXCDLFile));

        // only pass xcl measurement uris to the comparator
        List<MeasurementInfoUri> xclMeasurements = new LinkedList<MeasurementInfoUri>();
        for (MeasurementInfoUri infoUri : measurementInfoUris) {
            String path = infoUri.getPath();
            if ((path != null) && (path.startsWith("object/xcl/"))) {
                xclMeasurements.add(infoUri);

            }
        }

        XCLComparator comp = new XCLComparator(descriptor);
        HashMap<MeasurementInfoUri, Value> compResult = comp.compare(tempDir.getAbsolutePath(), sampleXCDLFile,
                resultXCDLFile, xclMeasurements);

        // compResult can be null when the comparator for instance can't handle a specific file format
        if (compResult == null) {
            return results;
        }

        // add comments to results
        for (MeasurementInfoUri info : compResult.keySet()) {
            Value v = compResult.get(info);
            if (v != null) {
                v.setComment(v.getComment() + "\n - evaluated with XCL tools");
                results.put(info, v);
            }
        }
        return results;
    } catch (Exception e) {
        throw new EvaluatorException(e);
    } finally {
        // clean up
        tearDown();
    }
}