Example usage for java.util TreeMap put

List of usage examples for java.util TreeMap put

Introduction

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

Prototype

public V put(K key, V value) 

Source Link

Document

Associates the specified value with the specified key in this map.

Usage

From source file:com.clust4j.algo.HDBSCAN.java

protected static int[] getLabels(ArrayList<CompQuadTup<Integer, Integer, Double, Integer>> condensed,
        TreeMap<Integer, Double> stability) {

    double subTreeStability;
    ArrayList<Integer> clusters = new ArrayList<Integer>();
    HSet<Integer> clusterSet;
    TreeMap<Integer, Integer> clusterMap = new TreeMap<>(), reverseClusterMap = new TreeMap<>();

    // Get descending sorted key set
    ArrayList<Integer> nodeList = GetLabelUtils.descSortedKeySet(stability);

    // Get tuples where child size > 1
    EntryPair<ArrayList<double[]>, Integer> entry = GetLabelUtils.childSizeGtOneAndMaxChild(condensed);
    ArrayList<double[]> clusterTree = entry.getKey();

    // Map of nodes to whether it's a cluster
    TreeMap<Integer, Boolean> isCluster = GetLabelUtils.initNodeMap(nodeList);

    // Get num points
    //int numPoints = entry.getValue();

    // Iter over nodes
    for (Integer node : nodeList) {
        subTreeStability = GetLabelUtils.subTreeStability(clusterTree, node, stability);

        if (subTreeStability > stability.get(node)) {
            isCluster.put(node, false);
            stability.put(node, subTreeStability);
        } else {/*from  ww w  .ja v a 2 s . c o  m*/
            for (Integer subNode : GetLabelUtils.breadthFirstSearchFromClusterTree(clusterTree, node))
                if (subNode.intValue() != node)
                    isCluster.put(subNode, false);
        }

    }

    // Now add to clusters
    for (Map.Entry<Integer, Boolean> c : isCluster.entrySet())
        if (c.getValue())
            clusters.add(c.getKey());
    clusterSet = new HSet<Integer>(clusters);

    // Build cluster map
    int n = 0;
    for (Integer clust : clusterSet) {
        clusterMap.put(clust, n);
        reverseClusterMap.put(n, clust);
        n++;
    }

    return doLabeling(condensed, clusters, clusterMap);
}

From source file:br.gov.lexml.oaicat.LexMLOAICatalog.java

/**
 * <b>LEXML ready</b>//  w  w  w. j av a 2 s  . co  m
 * 
 * @return lista dos sets da base lexml-db
 */
private ArrayList getSets() {
    TreeMap treeMap = new TreeMap();
    String propertyPrefix = "Sets.";
    List<ConjuntoItem> lista = m_ci_dao.list();
    if (null != lista) {
        Iterator<ConjuntoItem> iter = lista.iterator();
        int i = 0;
        while (iter.hasNext()) {
            i++;
            treeMap.put(propertyPrefix + i, helper.ConjuntoItem2Sets(iter.next()));
        }
    }
    return new ArrayList(treeMap.values());
}

From source file:com.nubits.nubot.trading.wrappers.BitSparkWrapper.java

private ApiResponse getBalanceImpl(Currency currency, CurrencyPair pair) {
    ApiResponse apiResponse = new ApiResponse();
    PairBalance balance = null;/*w w  w  .j  av a2 s  .c  om*/
    String url = API_BASE_URL;
    String method = API_GET_INFO;
    boolean isGet = true;
    TreeMap<String, String> query_args = new TreeMap<>();
    /*Params
     *
     */
    query_args.put("canonical_verb", "GET");
    query_args.put("canonical_uri", method);

    ApiResponse response = getQuery(url, method, query_args, true, isGet);
    if (response.isPositive()) {
        Amount NBTonOrder = null, NBTAvail = null, PEGonOrder = null, PEGAvail = null;
        JSONObject httpAnswerJson = (JSONObject) response.getResponseObject();
        JSONArray accounts = (JSONArray) httpAnswerJson.get("accounts");

        if (currency == null) { //Get all balances
            for (int i = 0; i < accounts.size(); i++) {
                JSONObject balanceObj = (JSONObject) accounts.get(i);
                String tempCurrency = balanceObj.get("currency").toString();

                String nbtCurrencyCode = pair.getOrderCurrency().getCode();
                String pegCurrencyCode = pair.getPaymentCurrency().getCode();

                if (tempCurrency.equalsIgnoreCase(nbtCurrencyCode)) {
                    NBTAvail = new Amount(Double.parseDouble(balanceObj.get("balance").toString()),
                            pair.getOrderCurrency());
                    NBTonOrder = new Amount(Double.parseDouble(balanceObj.get("locked").toString()),
                            pair.getOrderCurrency());
                }
                if (tempCurrency.equalsIgnoreCase(pegCurrencyCode)) {
                    PEGAvail = new Amount(Double.parseDouble(balanceObj.get("balance").toString()),
                            pair.getPaymentCurrency());
                    PEGonOrder = new Amount(Double.parseDouble(balanceObj.get("locked").toString()),
                            pair.getPaymentCurrency());
                }
            }
            if (NBTAvail != null && NBTonOrder != null && PEGAvail != null && PEGonOrder != null) {
                balance = new PairBalance(PEGAvail, NBTAvail, PEGonOrder, NBTonOrder);
                //Pack it into the ApiResponse
                apiResponse.setResponseObject(balance);
            } else {
                apiResponse.setError(errors.nullReturnError);
            }
        } else {//return available balance for the specific currency
            boolean found = false;
            Amount amount = null;
            for (int i = 0; i < accounts.size(); i++) {
                JSONObject balanceObj = (JSONObject) accounts.get(i);
                String tempCurrency = balanceObj.get("currency").toString();

                if (tempCurrency.equalsIgnoreCase(currency.getCode())) {
                    amount = new Amount(Double.parseDouble(balanceObj.get("balance").toString()), currency);

                    found = true;
                }
            }

            if (found) {
                apiResponse.setResponseObject(amount);
            } else {
                apiResponse.setError(new ApiError(21341,
                        "Can't find balance for" + " specified currency: " + currency.getCode()));
            }
        }
    } else {
        apiResponse = response;
    }

    return apiResponse;
}

From source file:com.att.aro.datacollector.ioscollector.utilities.AppSigningHelper.java

public String executeProcessExtractionCmd(String processList, String iosDeployPath) {
    TreeMap<Date, String> pidList = new TreeMap<>();
    if (processList != null) {
        String[] lineArr = processList.split(Util.LINE_SEPARATOR);
        SimpleDateFormat formatter = new SimpleDateFormat("hh:mma");
        for (String str : lineArr) {
            String[] strArr = str.split(" +");
            try {
                if (str.contains(iosDeployPath) && strArr.length >= 8) {
                    Date timestamp = formatter.parse(strArr[8]);
                    pidList.put(timestamp, strArr[1]);
                }/*from w  ww  . j  av  a2 s  .  com*/

            } catch (ParseException e) {
                LOGGER.error("Exception during pid extraction");
            }
        }
    }

    return pidList.lastEntry().getValue();
}

From source file:com.cmart.PageControllers.SellItemImagesController.java

/**
 * This method checks the page for any input errors that may have come from Client generator error
 * These would need to be check in real life to stop users attempting to hack and mess with things
 * //from w  ww .j ava  2  s  . c  om
 * @param request
 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
 */
public void checkInputs(HttpServletRequest request) {
    super.startTimer();

    if (request != null) {
        // If there is a multiform there are probably pictures
        if (ServletFileUpload.isMultipartContent(request)) {
            // Get the parameters
            try {
                // Create the objects needed to read the parameters
                factory = new DiskFileItemFactory();
                factory.setRepository(GV.LOCAL_TEMP_DIR);
                upload = new ServletFileUpload(factory);
                items = upload.parseRequest(request);
                Iterator<FileItem> iter = items.iterator();
                TreeMap<String, String> params = new TreeMap<String, String>();

                // Go through all the parameters and get the ones that are form fields
                while (iter.hasNext()) {
                    FileItem item = iter.next();

                    // If the item is a parameter, read it
                    if (item.isFormField()) {
                        params.put(item.getFieldName(), item.getString());
                    } else {
                        this.images.add(item);
                    }
                }

                /*
                 *  Get the parameters
                 */
                // Get the userID
                if (params.containsKey("userID")) {
                    try {
                        this.userID = Long.parseLong(params.get("userID"));

                        if (this.userID < 0)
                            if (!errors.contains(GlobalErrors.userIDLessThanZero))
                                errors.add(GlobalErrors.userIDLessThanZero);
                    } catch (NumberFormatException e) {
                        if (!errors.contains(GlobalErrors.userIDNotAnInteger))
                            errors.add(GlobalErrors.userIDNotAnInteger);

                    }
                } else {
                    if (!errors.contains(GlobalErrors.userIDNotPresent))
                        errors.add(GlobalErrors.userIDNotPresent);
                }

                // We nned to get the html5 tag as the parent cannot do the normal parsing
                if (params.containsKey("useHTML5")) {
                    try {
                        int u5 = Integer.parseInt(params.get("useHTML5"));
                        if (u5 == 1)
                            this.useHTML5 = true;
                        else
                            this.useHTML5 = false;
                    } catch (Exception e) {
                        this.useHTML5 = false;
                    }
                }

                // Get the authToken
                if (params.containsKey("authToken")) {
                    this.authToken = params.get("authToken");

                    if (this.authToken.equals(EMPTY))
                        if (!errors.contains(GlobalErrors.authTokenEmpty))
                            errors.add(GlobalErrors.authTokenEmpty);
                } else {
                    if (!errors.contains(GlobalErrors.authTokenNotPresent))
                        errors.add(GlobalErrors.authTokenNotPresent);
                }

                // Get the itemID
                if (params.containsKey("itemID")) {
                    try {
                        this.itemID = Long.parseLong(params.get("itemID"));

                        if (this.itemID <= 0)
                            if (!errors.contains(GlobalErrors.itemIDLessThanZero))
                                errors.add(GlobalErrors.itemIDLessThanZero);
                    } catch (NumberFormatException e) {
                        if (!errors.contains(GlobalErrors.itemIDNotAnInteger))
                            errors.add(GlobalErrors.itemIDNotAnInteger);
                    }
                } else {
                    if (!errors.contains(GlobalErrors.itemIDNotPresent))
                        errors.add(GlobalErrors.itemIDNotPresent);
                }
            } catch (FileUploadException e1) {
                // TODO Auto-generated catch block
                //System.out.println("SellItemImageController (checkInputs): There was an error in the multi-form");
                e1.printStackTrace();
            }
        }
        // Do normal request processing
        else {
            super.checkInputs(request);

            // Get the userID (if exists), we will pass it along to the next pages
            try {
                this.userID = CheckInputs.checkUserID(request);
            } catch (Error e) {
                // The user must be logged in to upload the images
                if (!errors.contains(e))
                    errors.add(e);
            }

            // Get the authToken (if exists), we will pass it along to the next pages
            try {
                this.authToken = CheckInputs.checkAuthToken(request);
            } catch (Error e) {
                if (!errors.contains(e))
                    errors.add(e);
            }

            // Get the itemID 
            try {
                this.itemID = CheckInputs.checkItemID(request);

                if (this.itemID <= 0)
                    if (!errors.contains(GlobalErrors.itemIDLessThanZero))
                        errors.add(GlobalErrors.itemIDLessThanZero);
            } catch (Error e) {
                if (!errors.contains(e))
                    errors.add(e);

                this.itemID = -1;
            }
        }
    }

    // Calculate how long that took
    super.stopTimerAddParam();
}

From source file:org.archive.crawler.framework.CrawlJob.java

public Map<String, Long> sizeTotalsReportData() {
    StatisticsTracker stats = getStats();
    if (stats == null) {
        return null;
    }//  w  w w.j  av a2s. c  o  m

    // stats.crawledBytesSummary() also includes totals, so add those in here
    TreeMap<String, Long> map = new TreeMap<String, Long>(stats.getCrawledBytes());
    map.put("total", stats.getCrawledBytes().getTotalBytes());
    map.put("totalCount", stats.getCrawledBytes().getTotalUrls());
    return map;
}

From source file:org.powertac.auctioneer.AuctionServiceTests.java

@SuppressWarnings("rawtypes")
@Before/*ww  w .jav  a 2  s  .c o  m*/
public void setUp() throws Exception {
    // clean up from previous tests
    timeslotRepo.recycle();
    reset(mockProxy);
    reset(mockControl);
    reset(mockServerProps);
    accountingArgs = new ArrayList<Object[]>();
    brokerMsgs = new ArrayList<Object>();

    // create a Competition, needed for initialization
    competition = Competition.newInstance("auctioneer-test").withTimeslotsOpen(4);
    Competition.setCurrent(competition);

    // mock the ServerProperties

    // Set up serverProperties mock
    config = new Configurator();
    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) {
            Object[] args = invocation.getArguments();
            config.configureSingleton(args[0]);
            return null;
        }
    }).when(mockServerProps).configureMe(anyObject());

    // Create some brokers who can trade
    b1 = new Broker("Buyer #1");
    b2 = new Broker("Buyer #2");
    s1 = new Broker("Seller #1");
    s2 = new Broker("Seller #2");

    // set the clock, create some useful timeslots
    Instant now = Competition.currentCompetition().getSimulationBaseTime();
    timeService.setCurrentTime(now);
    ts0 = timeslotRepo.makeTimeslot(now);
    ts1 = timeslotRepo.makeTimeslot(now.plus(TimeService.HOUR));
    ts2 = timeslotRepo.makeTimeslot(now.plus(TimeService.HOUR * 2));
    //timeslotRepo.makeTimeslot(now.plus(TimeService.HOUR * 3));
    //timeslotRepo.makeTimeslot(now.plus(TimeService.HOUR * 4));
    svc.clearEnabledTimeslots();

    // mock the AccountingService, capture args
    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) {
            Object[] args = invocation.getArguments();
            accountingArgs.add(args);
            return null;
        }
    }).when(accountingService).addMarketTransaction(isA(Broker.class), isA(Timeslot.class), anyDouble(),
            anyDouble());
    // mock the Broker Proxy, capture messages
    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) {
            Object[] args = invocation.getArguments();
            brokerMsgs.add(args[0]);
            return null;
        }
    }).when(mockProxy).broadcastMessage(anyObject());

    // Configure the AuctionService
    TreeMap<String, String> map = new TreeMap<String, String>();
    map.put("auctioneer.auctionService.sellerSurplusRatio", "0.5");
    map.put("auctioneer.auctionService.defaultMargin", "0.2");
    map.put("auctioneer.auctionService.defaultClearingPrice", "40.0");
    Configuration mapConfig = new MapConfiguration(map);
    config.setConfiguration(mapConfig);
    svc.initialize(competition, new ArrayList<String>());
}

From source file:gemlite.shell.admin.dao.AdminDao.java

/**
 * region//from   ww  w .j a va  2  s  . co  m
 * 
 * @return
 * @throws IOException
 */
private String showRegions() throws IOException {
    do {
        System.out.println("------------------------");
        Map param = new HashMap();
        param.put("beanName", "ListRegionsService");

        Execution execution = FunctionService.onServer(clientPool).withArgs(param);
        ResultCollector rc = execution.execute("REMOTE_ADMIN_FUNCTION");
        Object obj = rc.getResult();
        if (obj == null) {
            System.out.println("can't get regions list");
            return null;
        }
        ArrayList list = (ArrayList) obj;
        if (!(list.get(0) instanceof Set)) {
            System.out.println(list.get(0));
            return null;
        }
        TreeSet regionSet = (TreeSet) list.get(0);
        Iterator regionIters = regionSet.iterator();
        StringBuilder sb = new StringBuilder();
        TreeMap<String, String> regionMap = new TreeMap<String, String>();
        int no = 1;
        sb.append("NO.").append("\t").append("RegionName").append("\n");
        while (regionIters.hasNext()) {
            String fullPath = (String) regionIters.next();
            sb.append(no).append("\t").append(fullPath).append("\n");
            regionMap.put(String.valueOf(no), fullPath);
            no++;
        }
        System.out.println(sb.toString());
        System.out.println(
                "------------------------\nRegionNames,Your choice?No.or regionName,ALL(all) means export all regions,X to exit");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        String line = bufferedReader.readLine();
        if (line == null) {
            System.out.println("no input regionName!");
        } else if (!"x".equalsIgnoreCase(line.trim()) && !regionMap.entrySet().contains(line.trim())
                && !"ALL".equalsIgnoreCase(line.trim()) && !regionMap.keySet().contains(line.trim())) {
            System.out.println("error input:" + line);
        } else {
            if (regionMap.keySet().contains(line.trim()))
                return regionMap.get(String.valueOf(line.trim()));
            return line.trim();
        }
    } while (true);
}

From source file:com.acc.test.orders.AcceleratorTestOrderData.java

protected Map<String, Long> getEntryQuantityMap(final OrderModel order) {
    final TreeMap<String, Long> result = new TreeMap<String, Long>();

    for (final AbstractOrderEntryModel entry : order.getEntries()) {
        final ProductModel product = entry.getProduct();
        if (product != null) {
            final String productCode = product.getCode();
            if (result.containsKey(productCode)) {
                final long newQuantity = result.get(productCode).longValue() + entry.getQuantity().longValue();
                result.put(productCode, Long.valueOf(newQuantity));
            } else {
                result.put(productCode, entry.getQuantity());
            }//from   w w w  . j a v  a2  s  .c  o  m
        }
    }
    return result;
}