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:org.powertac.common.TariffEvaluatorTest.java

@Test
public void twoTariffInertia() {
    // do two evals to bump up inertia
    this.noTariffTest();
    evaluator.evaluateTariffs();//from   w w w.  j a va2s . co m

    // inertia should now be 0.4
    TariffSpecification bobTS = new TariffSpecification(bob, PowerType.CONSUMPTION)
            .addRate(new Rate().withValue(-0.4));
    Tariff bobTariff = new Tariff(bobTS);
    initTariff(bobTariff);
    TariffSpecification jimTS = new TariffSpecification(jim, PowerType.CONSUMPTION)
            .withMinDuration(TimeService.DAY * 5).addRate(new Rate().withValue(-0.4));
    Tariff jimTariff = new Tariff(jimTS);
    initTariff(jimTariff);
    ArrayList<Tariff> tariffs = new ArrayList<Tariff>();
    tariffs.add(defaultConsumption);
    tariffs.add(bobTariff);
    tariffs.add(jimTariff);
    when(tariffRepo.findRecentActiveTariffs(anyInt(), any(PowerType.class))).thenReturn(tariffs);

    double[] profile = { 1.0, 2.0 };
    cma.capacityProfile = profile;
    cma.setChoiceSamples(0.4, 0.6);
    cma.setInertiaSamples(0.35, 0.45); // half should skip

    // 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("three tariffs", 3, calls.size());
    assertEquals("-5000 for default", new Integer(-5000), calls.get(defaultConsumption));
    assertEquals("+2500 for bob", new Integer(2500), calls.get(bobTariff));
    assertEquals("+2500 for jim", new Integer(2500), calls.get(jimTariff));
}

From source file:gedi.riboseq.inference.orf.OrfFinder.java

public MemoryIntervalTreeStorage<Orf> computeByGenes(Progress progress) throws IOException {
    HashMap<String, ArrayList<ImmutableReferenceGenomicRegion<Transcript>>> geneMap = getGeneMap(progress);

    MemoryIntervalTreeStorage<Orf> re = new MemoryIntervalTreeStorage<Orf>(Orf.class);
    progress.init().setCount(geneMap.size());
    for (String gene : geneMap.keySet()) {
        re.fill(computeGene(gene, progress));
    }/*  ww w  .jav  a2s  . c  om*/

    progress.finish();
    return re;
}

From source file:com.trellmor.berrymotes.sync.SubredditEmoteDownloader.java

private List<EmoteImage> getEmoteList() throws IOException, RemoteException, OperationApplicationException,
        URISyntaxException, InterruptedException {
    Log.debug("Getting emote list");
    List<EmoteImage> emotes = downloadEmoteList();

    if (emotes != null) {
        checkInterrupted();// w  w w .  jav a 2 s  .  co m

        HashMap<String, EmoteImage> emotesHash = new HashMap<String, EmoteImage>();
        int i = 0;
        while (i < emotes.size()) {
            EmoteImage emote = emotes.get(i);
            if (!mDownloadNSFW && emote.isNsfw()) {
                Log.debug("Skipped emote " + emote.getImage() + " (NSFW)");
                emotes.remove(i);
                continue;
            } else {
                if (!emotesHash.containsKey(emote.getHash())) {
                    emotesHash.put(emote.getHash(), emote);
                } else {
                    EmoteImage collision = emotesHash.get(emote.getHash());
                    Log.error("Hash collission! " + emote.getImage() + " (" + emote.getHash() + ") <-> "
                            + collision.getImage() + " (" + collision.getHash() + ")");
                }
            }
            i++;
        }
        Log.info("Removed ignored emotes, " + Integer.toString(emotesHash.size()) + " left.");

        checkInterrupted();
        Cursor c = mContentResolver.query(EmotesContract.Emote.CONTENT_URI_DISTINCT,
                new String[] { EmotesContract.Emote.COLUMN_HASH, EmotesContract.Emote.COLUMN_IMAGE },
                EmotesContract.Emote.COLUMN_SUBREDDIT + "=?", new String[] { mSubreddit }, null);
        if (c != null) {
            ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();
            try {
                if (c.moveToFirst()) {
                    final int POS_HASH = c.getColumnIndex(EmotesContract.Emote.COLUMN_HASH);
                    final int POS_IMAGE = c.getColumnIndex(EmotesContract.Emote.COLUMN_IMAGE);
                    do {
                        String hash = c.getString(POS_HASH);
                        if (!emotesHash.containsKey(hash)) {
                            Log.debug("Removing " + c.getString(POS_IMAGE) + " (" + hash
                                    + ") (not in emote list)");
                            batch.add(ContentProviderOperation.newDelete(EmotesContract.Emote.CONTENT_URI)
                                    .withSelection(EmotesContract.Emote.COLUMN_HASH + "=?",
                                            new String[] { hash })
                                    .build());

                            mEmoteDownloader.checkStorageAvailable();
                            File file = new File(c.getString(POS_IMAGE));
                            if (file.exists()) {
                                file.delete();
                            }
                        }
                    } while (c.moveToNext());
                }

                c.close();

            } finally {
                Log.debug("Removing emotes from DB");
                applyBatch(batch);
                mSyncResult.stats.numDeletes += batch.size();
                Log.info("Removed " + Integer.toString(batch.size()) + " emotes from DB");
            }
        }
    }
    return emotes;
}

From source file:fr.zcraft.zlib.components.rawtext.RawTextTest.java

@Test
public void styleNameTest() {
    HashMap<ChatColor, String> styleNames = new HashMap<>();
    styleNames.put(ChatColor.AQUA, "aqua");
    styleNames.put(ChatColor.BLACK, "black");
    styleNames.put(ChatColor.BLUE, "blue");
    styleNames.put(ChatColor.BOLD, "bold");
    styleNames.put(ChatColor.DARK_AQUA, "dark_aqua");
    styleNames.put(ChatColor.DARK_BLUE, "dark_blue");
    styleNames.put(ChatColor.DARK_GRAY, "dark_gray");
    styleNames.put(ChatColor.DARK_GREEN, "dark_green");
    styleNames.put(ChatColor.DARK_PURPLE, "dark_purple");
    styleNames.put(ChatColor.DARK_RED, "dark_red");
    styleNames.put(ChatColor.GOLD, "gold");
    styleNames.put(ChatColor.GRAY, "gray");
    styleNames.put(ChatColor.GREEN, "green");
    styleNames.put(ChatColor.ITALIC, "italic");
    styleNames.put(ChatColor.LIGHT_PURPLE, "light_purple");
    styleNames.put(ChatColor.MAGIC, "obfuscated");
    styleNames.put(ChatColor.RED, "red");
    styleNames.put(ChatColor.STRIKETHROUGH, "strikethrough");
    styleNames.put(ChatColor.UNDERLINE, "underline");
    styleNames.put(ChatColor.WHITE, "white");
    styleNames.put(ChatColor.YELLOW, "yellow");

    Assert.assertEquals("All values (except reset) are covered", ChatColor.values().length - 1,
            styleNames.size());

    for (ChatColor color : styleNames.keySet()) {
        Assert.assertEquals(RawText.toStyleName(color), styleNames.get(color));
    }//from   ww  w . j av  a2 s .  c o  m
}

From source file:com.globalsight.machineTranslation.AbstractTranslator.java

/**
 * Translate batch segments with tags in segments.
 * /*from w w  w  .j a  va  2s .  c o  m*/
 * @param sourceLocale
 * @param targetLocale
 * @param segments
 * @return
 * @throws MachineTranslationException
 */
private String[] translateSegmentsWithTags(Locale sourceLocale, Locale targetLocale, String[] segments)
        throws MachineTranslationException {
    if (sourceLocale == null || targetLocale == null || segments == null || segments.length < 1) {
        return null;
    }

    String[] results = new String[segments.length];

    HashMap<String, String> map = new HashMap<String, String>();
    for (int k = 0; k < segments.length; k++) {
        String[] segmentsFromGxml = MTHelper.getSegmentsInGxml(segments[k]);
        if (segmentsFromGxml == null || segmentsFromGxml.length < 1) {
            results[k] = segments[k];
        } else {
            for (int count = 0; count < segmentsFromGxml.length; count++) {
                String key = String.valueOf(k) + "-" + count;
                map.put(key, segmentsFromGxml[count]);
            }
        }
    }

    // for MS & Google MT(batch translation)
    if (map.size() > 0) {
        // Put all keys into "keysInArray"
        String[] keysInArray = new String[map.keySet().size()];
        Iterator<String> keysInIter = map.keySet().iterator();
        int countKey = 0;
        while (keysInIter.hasNext()) {
            keysInArray[countKey] = (String) keysInIter.next();
            countKey++;
        }

        // Put all values into "valuesInArray"
        String[] valuesInArray = new String[map.values().size()];
        Iterator<String> valuesInIter = map.values().iterator();
        int countValue = 0;
        while (valuesInIter.hasNext()) {
            valuesInArray[countValue] = (String) valuesInIter.next();
            countValue++;
        }

        // Do batch translation
        String[] translatedSegments = doBatchTranslation(sourceLocale, targetLocale, valuesInArray);

        // Put sub texts back to GXML corresponding positions.
        if (translatedSegments != null) {
            for (int m = 0; m < segments.length; m++) {
                String gxml = segments[m];
                // Retrieve all TextNode that need translate.
                GxmlElement gxmlRoot = MTHelper.getGxmlElement(gxml);
                List items2 = MTHelper.getImmediateAndSubImmediateTextNodes(gxmlRoot);

                int count = 0;
                for (Iterator iter = items2.iterator(); iter.hasNext();) {
                    TextNode textNode = (TextNode) iter.next();

                    for (int n = 0; n < translatedSegments.length; n++) {
                        int dashIndex = keysInArray[n].indexOf("-");
                        int index = -1;
                        int subIndex = -1;
                        if (dashIndex < 0) {
                            index = Integer.parseInt(keysInArray[n]);
                        } else {
                            index = Integer.parseInt(keysInArray[n].substring(0, dashIndex));
                            subIndex = Integer.parseInt(keysInArray[n].substring(dashIndex + 1));
                        }

                        if (index == m && subIndex == count) {
                            textNode.setTextBuffer(new StringBuffer(
                                    translatedSegments[n] == null ? "" : translatedSegments[n]));
                            count++;
                            break;
                        }
                    }
                }

                String finalSegment = gxmlRoot.toGxml();
                results[m] = finalSegment;
            }
        }
    }

    return results;
}

From source file:jp.co.conit.sss.sp.ex1.billing.BillingService.java

/**
 * ????//ww  w .  j av  a 2  s  .  c  om
 * 
 * @param purchases
 */
private void notificationVerifiedProduct(List<VerifiedProduct> purchases) {

    Context context = getApplicationContext();
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    HashMap<String, VerifiedProduct> orderMap = new HashMap<String, VerifiedProduct>();
    int size = purchases.size() - 1;

    // ????Map???????????
    for (int i = size; i >= 0; i--) {
        VerifiedProduct vp = purchases.get(i);
        if (vp.getPurchaseState() == PurchaseState.PURCHASED) {
            orderMap.put(vp.getProductId(), vp);
        }
    }

    // ?????Notification??
    // ?????
    if (orderMap.size() > 0) {

        Notification notification = new Notification();
        notification.icon = R.drawable.ic_status;
        notification.tickerText = context.getString(R.string.notification_buy_result);
        notification.flags = Notification.FLAG_AUTO_CANCEL;

        Intent intent = new Intent();
        PendingIntent pendingintent = PendingIntent.getActivity(context, 0, intent, 0);

        String title = context.getString(R.string.notification_book);

        notification.setLatestEventInfo(context, context.getString(R.string.notification_buy_finish, title),
                context.getString(R.string.notification_urge_download), pendingintent);

        notificationManager.notify(0, notification);
    }

}

From source file:org.openscience.cdk.applications.taverna.weka.classification.EvaluateClassificationResultsAsPDFActivity.java

private void createDataset(Instances dataset, Classifier classifier, DefaultCategoryDataset chartDataset,
        LinkedList<Double> setPercentage, String setname) throws Exception {
    WekaTools tools = new WekaTools();
    HashMap<UUID, Double> orgClassMap = new HashMap<UUID, Double>();
    HashMap<UUID, Double> calcClassMap = new HashMap<UUID, Double>();
    Instances trainUUIDSet = Filter.useFilter(dataset, tools.getIDGetter(dataset));
    dataset = Filter.useFilter(dataset, tools.getIDRemover(dataset));
    for (int k = 0; k < dataset.numInstances(); k++) {
        double pred = classifier.classifyInstance(dataset.instance(k));
        UUID uuid = UUID.fromString(trainUUIDSet.instance(k).stringValue(0));
        calcClassMap.put(uuid, pred);/*w w w  . ja v  a  2s.c  o m*/
        orgClassMap.put(uuid, dataset.instance(k).classValue());
    }
    HashMap<Double, Integer> correctPred = new HashMap<Double, Integer>();
    HashMap<Double, Integer> occurances = new HashMap<Double, Integer>();
    for (int k = 0; k < dataset.numInstances(); k++) {
        UUID uuid = UUID.fromString(trainUUIDSet.instance(k).stringValue(0));
        double pred = calcClassMap.get(uuid);
        double org = orgClassMap.get(uuid);
        Integer oc = occurances.get(org);
        if (oc == null) {
            occurances.put(org, 1);
        } else {
            occurances.put(org, ++oc);
        }
        if (pred == org) {
            Integer co = correctPred.get(org);
            if (co == null) {
                correctPred.put(org, 1);
            } else {
                correctPred.put(org, ++co);
            }
        }
    }
    double overall = 0;
    for (Entry<Double, Integer> entry : occurances.entrySet()) {
        Double key = entry.getKey();
        int occ = entry.getValue();
        Integer pred = correctPred.get(key);
        int pre = pred == null ? 0 : pred;
        double ratio = pre / (double) occ * 100;
        overall += ratio;
        chartDataset.addValue(ratio, setname, dataset.classAttribute().value(key.intValue()));
    }
    overall /= occurances.size();
    setPercentage.add(overall);
    chartDataset.addValue(overall, setname, "Overall");
}

From source file:com.yahoo.ycsb.workloads.MailAppCassandraWorkload.java

public void doTransactionPopReadOnly(DB db) throws WorkloadException {
    //choose a random key
    int keynum = nextKeynum();

    String keynameInbox = buildKeyName(keynum, inboxSuffix);

    HashSet<String> fields = null;

    HashSet<String> counterColumnNames = new HashSet<String>();
    counterColumnNames.add(messagecountfieldkey);
    counterColumnNames.add(mailboxsizefieldkey);

    HashMap<String, ByteIterator> counterResult = new HashMap<String, ByteIterator>();
    HashMap<String, ByteIterator> uidlResult = new HashMap<String, ByteIterator>();
    HashMap<String, ByteIterator> result = new HashMap<String, ByteIterator>();

    HashSet<String> retrievedMessageIDList = new HashSet<String>();
    long st = System.nanoTime();

    //read counter Table (POP3 STAT Command)
    db.read(incrementTag + countertable, keynameInbox, counterColumnNames, counterResult);
    if (counterResult.isEmpty()) {
        long en = System.nanoTime();
        Measurements.getMeasurements().measure("POP_ReadOnly-Transaction", (int) ((en - st) / 1000));
        return;//from  w  w w  .  j  av  a 2  s .  c  om
    }
    //get UIDL/List-List
    db.read(sizetable, keynameInbox, fields, uidlResult);
    //Retr x Messages
    int retrieveCount = getMessageRetrieveCountGenerator(0, uidlResult.size()).nextInt();
    for (int i = 0; i < retrieveCount; i++) {
        //request one message by key and single column name
        String columnName = uidlResult.entrySet().iterator().next().getKey();
        HashSet<String> requestColumn = new HashSet<String>();
        requestColumn.add(columnName);
        db.read(mailboxtable, keynameInbox, requestColumn, result);
        retrievedMessageIDList.add(columnName);
    }
    long en = System.nanoTime();
    Measurements.getMeasurements().measure("POP_ReadOnly-Transaction", (int) ((en - st) / 1000));

}