Example usage for java.util HashMap size

List of usage examples for java.util HashMap size

Introduction

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

Prototype

int size

To view the source code for java.util HashMap size.

Click Source Link

Document

The number of key-value mappings contained in this map.

Usage

From source file:com.bizideal.whoami.utils.cloopen.CCPRestSmsSDK.java

/**
 * @description xml??map/*from w ww  . j a  va 2  s .  c o m*/
 * @param xml
 * @return Map
 */
private HashMap<String, Object> xmlToMap(String xml) {
    HashMap<String, Object> map = new HashMap<String, Object>();
    Document doc = null;
    try {
        doc = DocumentHelper.parseText(xml); // XML
        Element rootElt = doc.getRootElement(); // ?
        HashMap<String, Object> hashMap2 = new HashMap<String, Object>();
        for (Iterator i = rootElt.elementIterator(); i.hasNext();) {
            Element e = (Element) i.next();
            if ("statusCode".equals(e.getName()) || "statusMsg".equals(e.getName()))
                map.put(e.getName(), e.getText());
            else {
                if ("SubAccount".equals(e.getName()) || "totalCount".equals(e.getName())
                        || "token".equals(e.getName()) || "downUrl".equals(e.getName())) {
                    if (!"SubAccount".equals(e.getName())) {
                        hashMap2.put(e.getName(), e.getText());
                    } else {
                        ArrayList<HashMap<String, Object>> arrayList = new ArrayList<HashMap<String, Object>>();
                        HashMap<String, Object> hashMap3 = new HashMap<String, Object>();
                        for (Iterator i2 = e.elementIterator(); i2.hasNext();) {
                            Element e2 = (Element) i2.next();
                            hashMap3.put(e2.getName(), e2.getText());
                            arrayList.add(hashMap3);
                        }
                        hashMap2.put("SubAccount", arrayList);
                    }
                    map.put("data", hashMap2);
                } else {

                    HashMap<String, Object> hashMap3 = new HashMap<String, Object>();
                    for (Iterator i2 = e.elementIterator(); i2.hasNext();) {
                        Element e2 = (Element) i2.next();
                        // hashMap2.put(e2.getName(),e2.getText());
                        hashMap3.put(e2.getName(), e2.getText());
                    }
                    if (hashMap3.size() != 0) {
                        hashMap2.put(e.getName(), hashMap3);
                    } else {
                        hashMap2.put(e.getName(), e.getText());
                    }
                    map.put("data", hashMap2);
                }
            }
        }
    } catch (DocumentException e) {
        e.printStackTrace();
        LoggerUtil.error(e.getMessage());
    } catch (Exception e) {
        LoggerUtil.error(e.getMessage());
        e.printStackTrace();
    }
    return map;
}

From source file:amie.keys.CSAKey.java

/**
 * It outputs all the conditional keys on a KB given a minimum support 
 * threshold./*  w  w  w.ja  v  a  2s .c o  m*/
 * @param support
 * @param kb
 */
public void discoverConditionalKeys(Set<Rule> output) {
    HashMap<Rule, Graph> ruleToGraphFirstLevel = new HashMap<>();
    /** 
     * We build a graph (subset lattice) for each property. The graph contains nodes
     * for each of the other properties and all its possible combinations.
     * For instance given the relations 1, 2, 3, 4. The graph for property 1
     * contains as nodes: 2, 3, 4, 23, 24, 34, 234 with their corresponding
     * parent relationships, e.g., 23 has 2 and 3 as parents. While relations
     * are strings, we have mapped them to an integer space (that is why the key
     * is an integer)
     **/
    HashMap<Integer, Graph> instantiatedProperty2Graph = buildPropertyGraphs((int) support);
    //System.out.println(instantiatedProperty2Graph);
    /**
     * Here we find all conditional keys when the condition has size 1, i.e., it involves
     * only one property such as residence=Paris | zipCode, field.
     * The map contains the conditions as keys and the list of potential properties that could
     * be used to extend this condition as values.
     */
    HashMap<Rule, HashSet<String>> conditionsToPotentialExtensions = discoverConditionalKeysFirstLevel(
            ruleToGraphFirstLevel, instantiatedProperty2Graph, output);

    //for (Rule rule : ruleToGraphFirstLevel.keySet()) {
    //    System.out.println("rule:" + rule + " => " + ruleToGraphFirstLevel.get(rule) + "\tThread" + Thread.currentThread().getId() );
    //}

    if (conditionsToPotentialExtensions.size() != 0) {
        // If there is room for extension, we look for conditional keys of longer size.
        discoverConditionalKeysPerLevel(conditionsToPotentialExtensions, ruleToGraphFirstLevel,
                ruleToGraphFirstLevel, output);
    }
    System.out.println("We found " + conditions2Keys.valueSize() + " key(s)");

}

From source file:edu.sjsu.pokemonclassifier.classification.UserPreferenceInfo.java

public Map<String, Integer> getRecommendPokemon() {
    // API for downard module
    //  Put all strongerCandidates to GMM model
    List<Pair<Integer, Double>> weightPairList = new ArrayList<>();
    GaussianMixtureModel model = gmmTrainer.getModel();
    for (int j = 0; j < model.getK(); j++) {
        weightPairList.add(Pair.of(j, model.weights()[j]));
    }//from   www.  j  av a  2  s. co m

    Collections.sort(weightPairList, new Comparator<Pair<Integer, Double>>() {
        @Override
        public int compare(Pair<Integer, Double> o1, Pair<Integer, Double> o2) {
            if (o1.getValue() < o2.getKey())
                return -1;
            else if (o1.getValue().equals(o2.getValue()))
                return 0;
            else
                return 1;
        }
    });

    // Get top-5
    // 5 is temp number
    // <String, Interger> -> <PokemonName, Rank#>
    HashMap<String, Integer> rankedPokemon = new HashMap<String, Integer>();
    HashMap<Integer, String> strongerCandidatesMap = new HashMap<Integer, String>();

    for (String strongerCandidate : strongerCandidates) {

        strongerCandidatesMap.put(strongerCandidates.indexOf(strongerCandidate), strongerCandidate);
    }

    //        for (int i = 0; i < strongerCandidates.size(); i++) {
    //
    //           strongerCandidatesMap.put(i, strongerCandidates.get(i).toLowerCase());
    //        }

    // modified by sidmishraw for getting top 10 pokemons rather than 5
    int totalClusters = Math.min(model.getK(), 10);

    int rank = 1;

    for (int i = totalClusters - 1; i >= 0; i--) {
        int modelIdx = weightPairList.get(i).getKey();
        double[] meanVector = model.gaussians()[modelIdx].mean().toArray();

        double att = meanVector[0];
        double def = meanVector[1];
        double hp = meanVector[2];

        double minDist = Double.MAX_VALUE;
        int minIdx = 0;
        String bestFitName = null;

        for (int j = 0; j < strongerCandidatesMap.size(); j++) {

            String name = strongerCandidatesMap.get(j);

            if (name == null) {

                continue;
            }

            //name = name.toLowerCase();
            System.out.println("HARMLESS:::: name = " + name);
            System.out.println("HARMLESS:::: att2 = " + PokemonDict.getInstance().getAttack(name));
            System.out.println("HARMLESS:::: def2 = " + PokemonDict.getInstance().getDefense(name));
            System.out.println("HARMLESS:::: hp2 = " + PokemonDict.getInstance().getHP(name));

            int att2 = PokemonDict.getInstance().getAttack(name);
            int def2 = PokemonDict.getInstance().getDefense(name);
            int hp2 = PokemonDict.getInstance().getHP(name);

            double dist = Math
                    .sqrt((att - att2) * (att - att2) + (def - def2) * (def - def2) + (hp - hp2) * (hp - hp2));
            if (dist < minDist) {
                minDist = dist;
                minIdx = j;
                bestFitName = name;
            }
        }

        strongerCandidatesMap.remove(minIdx);
        rankedPokemon.put(bestFitName, rank);
        rank++;
    }

    return rankedPokemon;
}

From source file:com.google.gwt.emultest.java.util.HashMapTest.java

public void testIteration_withCollidingHashCodesAndFullIteration() {

    List<Object> keys = new ArrayList<>();
    HashMap<Object, String> testMap = new HashMap<>();
    for (int i = 0; i < 100; i++) {
        Object key = createObjectWithHashCode((i + 10) / 10);
        keys.add(key);/*from  ww w .  j  av  a 2 s.c  o m*/
        testMap.put(key, "" + i);
    }

    int expectedSize = keys.size();

    for (Iterator<Object> it = testMap.keySet().iterator(); it.hasNext(); expectedSize--) {
        Object key = it.next();
        assertTrue("Unexpected key was returned", keys.contains(key));
        keys.remove(key);
        it.remove();
        assertEquals("Map size", expectedSize - 1, testMap.size());
    }

    assertEquals("expected size", 0, expectedSize);
    assertTrue(testMap.isEmpty());
    assertTrue(keys.isEmpty());
}

From source file:net.morematerials.manager.UpdateManager.java

private void updateSmp(File file) throws Exception {
    ZipFile smpFile = new ZipFile(file);
    Enumeration<? extends ZipEntry> entries = smpFile.entries();
    String smpName = file.getName().substring(0, file.getName().lastIndexOf("."));

    // First we need to know what files are in this .smp file, because the old format uses magic filename matching.
    ArrayList<String> containedFiles = new ArrayList<String>();
    HashMap<String, YamlConfiguration> materials = new HashMap<String, YamlConfiguration>();

    // Now we walk through the file once and store every file.
    ZipEntry entry;//from  w  w  w . ja v a2 s  .c o  m
    YamlConfiguration yaml;
    while (entries.hasMoreElements()) {
        entry = entries.nextElement();

        // Only if its a .yml file
        if (entry.getName().endsWith(".yml")) {
            // Load the .yml file
            yaml = new YamlConfiguration();
            yaml.load(smpFile.getInputStream(entry));

            // Texture is required for new package format.
            if (!yaml.contains("Texture")) {
                materials.put(entry.getName().substring(0, entry.getName().lastIndexOf(".")), yaml);
            } else {
                containedFiles.add(entry.getName());
            }
        } else {
            containedFiles.add(entry.getName());
        }
    }

    // If this map contains any entry, we need to convert something.
    if (materials.size() > 0) {
        this.plugin.getUtilsManager().log("Deprecated .smp found: " + file.getName() + ". Updating...");

        // We need a temporary directory to update the .smp in.
        this.tempDir.mkdir();

        // First extract all untouched assets:
        for (String filename : containedFiles) {
            InputStream in = smpFile.getInputStream(smpFile.getEntry(filename));
            OutputStream out = new FileOutputStream(new File(this.tempDir, filename));
            int read;
            byte[] bytes = new byte[1024];
            while ((read = in.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            out.flush();
            out.close();
            in.close();
        }

        // Now convert each .yml file in this archive.
        YamlConfiguration oldYaml;
        YamlConfiguration newYaml;
        for (String materialName : materials.keySet()) {
            oldYaml = materials.get(materialName);
            newYaml = new YamlConfiguration();

            // Required "Type" which is Block or Item. Old format didnt support Tools anyway.
            newYaml.set("Type", oldYaml.getString("Type"));
            // Title is now required and falls back to filename.
            newYaml.set("Title", oldYaml.getString("Title", materialName));

            // Now call the converter methods.
            if (newYaml.getString("Type").equals("Block")) {
                this.convertBlock(oldYaml, newYaml, materialName, containedFiles);
                this.convertBlockHandlers(oldYaml, newYaml);
            } else if (newYaml.getString("Type").equals("Item")) {
                this.convertItem(oldYaml, newYaml, materialName, containedFiles);
                this.convertItemHandlers(oldYaml, newYaml);
            }

            // Copy over recipes - nothing changed here!
            if (oldYaml.contains("Recipes")) {
                newYaml.set("Recipes", oldYaml.getList("Recipes"));
            }

            // Finally store the new .yml file.
            String yamlString = newYaml.saveToString();
            BufferedWriter out = new BufferedWriter(
                    new FileWriter(new File(this.tempDir, materialName + ".yml")));
            out.write(this.fixYamlProblems(yamlString));
            out.close();

            // Also update itemmap entry!
            for (Integer i = 0; i < this.itemMap.size(); i++) {
                String oldMaterial = this.itemMap.get(i).replaceAll("^[0-9]+:MoreMaterials.", "");
                if (oldMaterial.equals(newYaml.getString("Title"))) {
                    this.itemMap.set(i, this.itemMap.get(i).replaceAll("^([0-9]+:MoreMaterials.).+$",
                            "$1" + smpName + "." + materialName));
                    break;
                }
            }

            // And we need to tell SpoutPlugin that this material must be renamed!
            SpoutManager.getMaterialManager().renameMaterialKey(this.plugin, newYaml.getString("Title"),
                    smpName + "." + materialName);
        }

        // First remove old .smp file
        smpFile.close();
        file.delete();

        // Then repack the new .smp file
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file));
        for (File entryFile : this.tempDir.listFiles()) {
            FileInputStream in = new FileInputStream(entryFile);
            out.putNextEntry(new ZipEntry(entryFile.getName()));
            Integer len;
            byte[] buf = new byte[1024];
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            out.closeEntry();
            in.close();
        }
        out.close();

        // At last remove the temp directory.
        FileUtils.deleteDirectory(this.tempDir);
    } else {
        // At last, close the file handle.
        smpFile.close();
    }
}

From source file:edu.ku.brc.specify.toycode.ResFileCompare.java

@SuppressWarnings("unchecked")
public void fixPropertiesFiles(final String baseFileName, final String lang, final boolean doBranch) {
    System.out.println("-------------------- " + baseFileName + " --------------------");
    File engFile;//from www  . jav  a  2 s. c  o m
    File lngFile;

    String engName = String.format("src/%s_en.properties", baseFileName);
    String langName = String.format("src/%s_%s.properties", baseFileName, lang);

    if (doBranch) {
        engFile = new File(
                String.format("/home/rods/workspace/Specify_6202SF/src/%s_en.properties", baseFileName));
        lngFile = new File(
                String.format("/home/rods/workspace/Specify_6202SF/src/%s_%s.properties", baseFileName, lang));
    } else {
        engFile = new File(engName);
        lngFile = new File(langName);
    }

    try {
        List<String> engList = (List<String>) FileUtils.readLines(engFile, "UTF8");
        List<String> lngListTmp = (List<String>) FileUtils.readLines(lngFile, "UTF8");

        int lineCnt = -1;
        HashMap<String, String> transHash = new HashMap<String, String>();
        for (String line : lngListTmp) {
            lineCnt++;

            if (line.startsWith("#") || StringUtils.deleteWhitespace(line).length() < 3
                    || line.indexOf('=') == -1) {
                continue;
            }

            String[] toks = StringUtils.split(line, '=');
            if (toks.length > 1) {
                if (toks.length == 2) {
                    transHash.put(toks[0], toks[1]);

                } else {
                    StringBuilder sb = new StringBuilder();
                    for (int i = 1; i < toks.length; i++) {
                        sb.append(String.format("%s=", toks[i]));
                    }
                    sb.setLength(sb.length() - 1); // chomp extra '='
                    transHash.put(toks[0], sb.toString());
                }
            } else {
                log.error("Skipping:[" + line + "] Line:" + lineCnt);
            }
        }

        log.info(String.format("Lines Eng: %d;  Terms Hash size: %s: %d", engList.size(), lang,
                transHash.size()));

        File dir = new File("translations");
        if (!dir.exists()) {
            if (!dir.mkdir()) {
                log.error("Unable to create directory[" + dir.getAbsolutePath() + "]");
                return;
            }
        }

        File transFile = new File(dir.getPath() + File.separator + langName.substring(4));
        PrintWriter transFileOutput = new PrintWriter(transFile, "UTF8");

        for (String line : engList) {
            if (line.startsWith("#") || StringUtils.deleteWhitespace(line).length() < 3
                    || line.indexOf('=') == -1) {
                transFileOutput.println(line);
                continue;
            }

            boolean doMove = true;
            String[] toks = StringUtils.split(line, '=');
            if (toks.length > 1) {
                String key = null;
                String value = null;
                if (toks.length == 2) {
                    key = toks[0];
                    value = toks[1];

                } else {
                    key = toks[0];
                    StringBuilder sb = new StringBuilder();
                    for (int i = 1; i < toks.length; i++) {
                        sb.append(String.format("%s=", toks[i]));
                    }
                    sb.setLength(sb.length() - 1); // chomp extra '='
                    value = sb.toString();
                }

                if (key != null) {
                    String text = transHash.get(key);
                    transFileOutput.println(String.format("%s=%s", key, text != null ? text : value));

                    if (text == null) {
                        log.info("Adding new term: " + key);
                    }
                    doMove = false;
                } else {
                    log.info("Adding new term: " + key);
                }
            }

            if (doMove) {
                transFileOutput.println(line);
            }
        }

        transFileOutput.flush();
        transFileOutput.close();

        log.info(String.format("Write file: %s", transFile.getPath()));

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.oneops.transistor.service.BomManagerImpl.java

protected void check4Secondary(CmsCI platform, List<CmsCIRelation> platformCloudRels, String nsPath) {
    //get manifest clouds and priority; what is intended
    Map<Long, Integer> intendedCloudpriority = platformCloudRels.stream().filter(cloudUtil::isCloudActive)
            .collect(toMap(CmsCIRelationBasic::getToCiId, this::getPriority, (i, j) -> i));
    //are there any secondary clouds for deployment
    long numberOfSecondaryClouds = intendedCloudpriority.entrySet().stream()
            .filter(entry -> (entry.getValue().equals(SECONDARY_CLOUD_STATUS))).count();
    if (numberOfSecondaryClouds == 0) {
        return;//from  w w w .j a v a2s.  c  o m
    }

    String finalNsPath = nsPath;
    //what is deployed currently.
    String entryPoint = getEntryPoint(platform);
    if (entryPoint == null) {
        //for platforms which dont have entry points, like schema.
        logger.info("Skipping secondary check , as entry point is absent for this " + nsPath + " platform ciId "
                + platform.getCiId());
        return;
    }

    Map<Long, Integer> existingCloudPriority = platformCloudRels.stream().map(CmsCIRelationBasic::getToCiId)
            .flatMap(cloudId -> cmProcessor
                    .getToCIRelationsByNs(cloudId, CmsConstants.DEPLOYED_TO, null, entryPoint, finalNsPath)
                    .stream())
            .collect(toMap(CmsCIRelationBasic::getToCiId, this::getPriority, (i, j) -> {
                return Math.max(i, j);
            }));

    HashMap<Long, Integer> computedCloudPriority = new HashMap<>(existingCloudPriority);
    computedCloudPriority.putAll(intendedCloudpriority);

    //Now, take  all offline clouds from
    Map<Long, Integer> offlineClouds = platformCloudRels.stream().filter(cloudUtil::isCloudOffline)
            .collect(toMap(CmsCIRelationBasic::getToCiId, this::getPriority, (i, j) -> i));
    if (!offlineClouds.isEmpty()) {
        offlineClouds.forEach((k, v) -> {
            if (computedCloudPriority.containsKey(k)) {
                computedCloudPriority.remove(k);
            }
        });
    }

    long count = computedCloudPriority.entrySet().stream()
            .filter(entry -> (entry.getValue().equals(CmsConstants.SECONDARY_CLOUD_STATUS))).count();
    if (computedCloudPriority.size() == count) {
        //throw transistor exception
        String message = "";
        String clouds = platformCloudRels.stream().filter(rel -> !cloudUtil.isCloudActive(rel))
                .filter(rel -> (getPriority(rel) == PRIMARY_CLOUD_STATUS)).map(rel -> rel.getToCi().getCiName())
                .collect(joining(","));

        if (StringUtils.isNotEmpty(clouds)) {
            message = String.format(
                    "The deployment will result in no instances in primary clouds for platform %s. Primary clouds <%s>  are not in active state for this platform.  ",
                    nsPath, clouds);
        } else {
            message = String.format(
                    "The deployment will result in no instances in primary clouds for platform %s. Please check the cloud priority of the clouds. .  ",
                    nsPath);
        }

        throw new TransistorException(TRANSISTOR_ALL_INSTANCES_SECONDARY, message);
    }
}

From source file:my.home.model.datasource.AutoCompleteItemDataSourceImpl.java

private void setItemWeight(Context context, ArrayList<AutoCompleteItem> items, String from) {
    List<HistoryItem> historyItems = DBStaticManager.getLatestItems(context, from, HISTORY_ITEM_MAX_NUM);
    if (historyItems == null || historyItems.size() == 0) {
        Log.d(TAG, "no history from: " + from + ". Use default value.");
        return;/*from  w  ww.  j a  v  a 2 s. c om*/
    }

    int hLen = historyItems.size();
    /* TODO move to Util class */
    HashMap<String, Integer> counter = new HashMap<>(hLen);
    for (HistoryItem item : historyItems) {
        String key = item.getFrom() + item.getTo();
        if (counter.containsKey(key)) {
            counter.put(key, counter.get(key) + 1);
        } else {
            counter.put(key, 1);
        }
    }

    String lastValue = "";
    float lastWeight = 0.0f;
    HashMap<String, Float> resultMap = new HashMap<>();
    for (int i = 0; i < hLen; i++) {
        HistoryItem cItem = historyItems.get(i);
        String key = cItem.getFrom() + cItem.getTo();
        // pos weight
        float pos_w = (i + 1) * 1.0f / hLen;
        pos_w = pos_w * pos_w;
        // occ weight
        float occ_w = counter.get(key) * 1.0f / hLen;
        // ctu weight
        float ctu_w = 0.0f;
        if (lastValue.equals(key)) {
            ctu_w = lastWeight / 2;
        }
        lastWeight = pos_w + occ_w + ctu_w;
        lastValue = key;

        if (resultMap.containsKey(key)) {
            resultMap.put(key, resultMap.get(key) + lastWeight);
        } else {
            resultMap.put(key, lastWeight);
        }
    }
    if (resultMap.size() != 0) {
        for (AutoCompleteItem item : items) {
            if (resultMap.containsKey(from + item.getContent())) {
                Log.d(TAG, "item:" + item.getContent() + " | " + resultMap.get(from + item.getContent()));
                item.setWeight(resultMap.get(from + item.getContent()));
            }
        }
    }
}

From source file:com.nextgis.rehacompdemo.RoutingActivity.java

@Override
public void onLocationChanged(Location currentLocation) {
    GeoEnvelope area = getArea(currentLocation);
    Location nextLocation = new Location(LocationManager.GPS_PROVIDER);
    Location previousLocation = new Location(LocationManager.GPS_PROVIDER);

    TreeMap<Float, Location> perpendiculars = new TreeMap<>();
    HashMap<Location, GeoLineString> snapsToSegments = new HashMap<>();
    for (GeoLineString segment : mRouteSegments)
        if (area.intersects(segment.getEnvelope()) || area.contains(segment.getEnvelope())) {
            previousLocation.setLongitude(Geo.mercatorToWgs84SphereX(segment.getPoint(0).getX()));
            previousLocation.setLatitude(Geo.mercatorToWgs84SphereY(segment.getPoint(0).getY()));
            nextLocation.setLongitude(Geo.mercatorToWgs84SphereX(segment.getPoint(1).getX()));
            nextLocation.setLatitude(Geo.mercatorToWgs84SphereY(segment.getPoint(1).getY()));
            Location snap = snapToLine(previousLocation, nextLocation, currentLocation, false);
            Float perpendicular = currentLocation.distanceTo(snap);
            perpendiculars.put(perpendicular, snap);
            snapsToSegments.put(snap, segment);
        }//  w w  w  . j a  v a  2  s.c  o m

    if (perpendiculars.size() > 0 && snapsToSegments.size() > 0) {
        Location snappedLocation = perpendiculars.firstEntry().getValue();
        GeoLineString segment = snapsToSegments.get(snappedLocation);
        previousLocation.setLongitude(Geo.mercatorToWgs84SphereX(segment.getPoint(0).getX()));
        previousLocation.setLatitude(Geo.mercatorToWgs84SphereY(segment.getPoint(0).getY()));
        nextLocation.setLongitude(Geo.mercatorToWgs84SphereX(segment.getPoint(1).getX()));
        nextLocation.setLatitude(Geo.mercatorToWgs84SphereY(segment.getPoint(1).getY()));

        GeoPoint point = segment.getPoint(1);
        if (snappedLocation.distanceTo(previousLocation) < snappedLocation.distanceTo(nextLocation)) {
            point = segment.getPoint(0);
            nextLocation.setLongitude(previousLocation.getLongitude());
            nextLocation.setLatitude(previousLocation.getLatitude());
        }

        if (snappedLocation.distanceTo(nextLocation) <= mActivationDistance) {
            long id = -1;
            for (IGeometryCacheItem cachePoint : mAllPoints) {
                if (point.equals(cachePoint.getGeometry()))
                    id = cachePoint.getFeatureId();
            }

            int position = mAdapter.getItemPosition(id);
            if (position != -1) {
                mSteps.requestFocusFromTouch();
                mSteps.setSelection(position);
            }
        }
    }
}

From source file:org.powertac.common.TariffEvaluatorTest.java

@Test
public void singleNewTariffSmallChunk() {
    subscribeTo(defaultConsumption, customer.getPopulation());
    TariffSpecification newTS = new TariffSpecification(bob, PowerType.CONSUMPTION)
            .addRate(new Rate().withValue(-0.59));
    Tariff newTariff = new Tariff(newTS);
    initTariff(newTariff);//from ww w . jav a2 s  .c  om
    ArrayList<Tariff> tariffs = new ArrayList<Tariff>();
    tariffs.add(defaultConsumption);
    tariffs.add(newTariff);
    when(tariffRepo.findRecentActiveTariffs(anyInt(), any(PowerType.class))).thenReturn(tariffs);

    double[] profile = { 1.0, 2.0 };
    cma.capacityProfile = profile;
    cma.setChoiceSamples(0.4, 0.6);

    // capture calls to tariffMarket
    final HashMap<Tariff, Integer> calls = new HashMap<Tariff, Integer>();
    doAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) {
            Object[] args = invocation.getArguments();
            assertEquals("correct customer", customer, args[1]);
            calls.put((Tariff) args[0], (Integer) args[2]);
            return null;
        }
    }).when(tariffMarket).subscribeToTariff(any(Tariff.class), any(CustomerInfo.class), anyInt());

    evaluator.withChunkSize(50); // 200 chunks
    evaluator.evaluateTariffs();
    assertEquals("two tariffs", 2, calls.size());
    assertEquals("-5000 for default", new Integer(-5000), calls.get(defaultConsumption));
    assertEquals("+5000 for new", new Integer(5000), calls.get(newTariff));
}