Example usage for java.util Map replace

List of usage examples for java.util Map replace

Introduction

In this page you can find the example usage for java.util Map replace.

Prototype

default V replace(K key, V value) 

Source Link

Document

Replaces the entry for the specified key only if it is currently mapped to some value.

Usage

From source file:it.incipict.tool.profiles.util.ProfilesToolUtils.java

public static List<Double> calcRanks(List<Survey> surveys) {
    List<Double> ranks = new ArrayList<Double>();
    Map<String, Double> TextualAnswersMap = new Survey().getTextualAnswersMap();

    int count = 0;
    for (Survey survey : surveys) {
        Map<String, Double> surveyMap = survey.getTextualAnswersMap();
        count++;/*from w  w w.j  a va  2s.  c om*/
        for (int i = 0; i < survey.getAnswers().size(); i++) {
            String r = survey.getAnswers().get(i);
            // first of all sum the answersVectors for all surveys of this
            // profile and store the sum in a new list
            // this condition match the numerical values
            if (r.matches("\\d*")) {
                if (count == 1) {
                    // first survey
                    ranks.add(Double.parseDouble(r));
                } else {
                    // sum all elements of vector (REMARK: A+B = a1+b1,
                    // a2+b2, ..., an+bn)
                    ranks.set(i, (ranks.get(i) + Double.parseDouble(r)));
                }
            }
            // now count all strings occurences in textualAnswers
            // (checkbox/radio/etc..)
            // for the current survey.
            else {
                if (surveyMap.containsKey(r)) {
                    Double old = TextualAnswersMap.get(r);
                    TextualAnswersMap.replace(r, (old + surveyMap.get(r)));
                }
            }
        }
    }
    // append in queue all hashmap's values.
    List<Double> mapValues = new ArrayList<Double>(TextualAnswersMap.values());
    ranks.addAll(mapValues);

    // finally calculate the statistical average for each element of vector
    // divided by total of surveys.
    for (int i = 0; i < ranks.size(); i++) {
        Double f = ranks.get(i);
        ranks.set(i, ((f / surveys.size())));
    }
    // Normalizing the matrix with 0-1 probabilistic value.
    // Note: in INCIPICT Survey Form the max range for the questions 1-27 is 5
    // Divide this answers per 5
    // because we want to obtain as result a probabilistic matrix with 0-1 values 
    // for this reason we divide all elements by they max range value
    // in this mode we obtain a percentage values 0%-100% represented by double values (0.00-1.00)
    ranks = (ProfilesToolUtils.divideByScalar(ranks, SCALAR, RANGE_START, RANGE_END));

    // return the ranks list for this profile.
    return ranks;
}

From source file:api.accounts.UserVerify.java

public Map<String, Object> addUserInfo(String userName, String password) {
    String queryStr = "SELECT * FROM Qashio_UserInfos WHERE userName=?";
    String updateStr = "INSERT INTO Qashio_UserInfos (userName, password, sessionId) VALUES (?,?,?)";
    Map<String, Object> results = new HashMap<>();
    Map<String, Object> checkOutcome = new HashMap<>();
    List<Object> paras = new ArrayList<>();
    List<Object> para = new ArrayList<>();
    paras.add(userName);/* w ww  . j a v  a  2  s. co  m*/
    para.add(userName);
    paras.add(password);
    paras.add(System.currentTimeMillis());

    try {
        checkOutcome.put("success", false);
        checkOutcome.put("method", "add");
        checkOutcome.put("msg", "");
        checkOutcome.put("sessionId", System.currentTimeMillis());
        results = db.findSingleResult(queryStr, para);
        if (results.get("userName") != null) {
            checkOutcome.replace("msg", "User already registered!");
        } else {
            Boolean flag = db.updateByPrepStmt(updateStr, paras);
            System.out.println("update: " + flag);
            //            db.connection.close();
            if (flag) {
                checkOutcome.replace("success", true);
            } else {
                checkOutcome.replace("msg", "update failure");
            }
        }
    } catch (SQLException ex) {
        Logger.getLogger(UserVerify.class.getName()).log(Level.SEVERE, null, ex);
    }

    return checkOutcome;
}

From source file:fr.univlorraine.mondossierweb.controllers.RechercheController.java

public void accessToMobileDetail(String code, String type, boolean fromSearch) {

    Map<String, String> parameterMap = new HashMap<>();
    parameterMap.put("code", code);
    parameterMap.put("type", type);

    //Si on vient de la recherche rapide, il faut que le bouton 'retour' de la recherche rapide arrive sur les favoris
    //Sinon boucle possible dans la navigation
    if (fromSearch) {
        MdwTouchkitUI.getCurrent().setRechercheFromView(FavorisMobileView.NAME);
    }//from   w  w w  .  ja  v  a2 s. c  o  m

    if (type.equals(Utils.TYPE_VET) || type.equals(Utils.VET) || type.equals(Utils.ELP)
            || type.equals(Utils.TYPE_ELP)) {
        if (type.equals(Utils.TYPE_VET))
            parameterMap.replace("type", Utils.VET);
        if (type.equals(Utils.TYPE_ELP))
            parameterMap.replace("type", Utils.ELP);
        if (fromSearch) {
            MdwTouchkitUI.getCurrent().navigateToListeInscritsFromSearch(parameterMap);
        } else {
            MdwTouchkitUI.getCurrent().navigateToListeInscritsFromFavoris(parameterMap);
        }
    }

    if (type.equals(Utils.TYPE_ETU) || type.equals(Utils.ETU)) {
        parameterMap.replace("type", Utils.ETU);

        if (MdwTouchkitUI.getCurrent().getEtudiant() == null
                || !MdwTouchkitUI.getCurrent().getEtudiant().getCod_etu().equals(code)) {
            MdwTouchkitUI.getCurrent().setEtudiant(new Etudiant(code));
            etudiantController.recupererEtatCivil();
            etudiantController.recupererCalendrierExamens();
            etudiantController.recupererNotesEtResultatsEnseignant(MdwTouchkitUI.getCurrent().getEtudiant());
        }
        if (fromSearch) {
            MdwTouchkitUI.getCurrent().navigateToDossierEtudiantFromSearch();
        } else {
            MdwTouchkitUI.getCurrent().navigateToDossierEtudiantFromListeInscrits();
        }
    }
}

From source file:nc.noumea.mairie.appock.services.impl.ExportExcelServiceImpl.java

private void remplitLigneArticle(Workbook wb, List<ArticleDemande> listeArticleDemande, Sheet sheet) {
    int numRow = 10;
    Map<ArticleCatalogue, Integer> mapArticleQuantite = new HashMap<>();

    for (ArticleDemande articleDemande : listeArticleDemande) {
        ArticleCatalogue articleCatalogue = articleDemande.getArticleCatalogue();
        Integer quantite = mapArticleQuantite.get(articleCatalogue);
        if (quantite != null) {
            mapArticleQuantite.replace(articleCatalogue, quantite + articleDemande.getQuantiteCommande());
        } else {//from  ww w . j a  v  a  2 s  .c  om
            mapArticleQuantite.put(articleCatalogue, articleDemande.getQuantiteCommande());
        }
    }

    List<ArticleCatalogue> listeArticleCatalogue = new ArrayList(mapArticleQuantite.keySet());
    Collections.sort(listeArticleCatalogue, new ArticleCatalogueComparator());

    for (ArticleCatalogue articleCatalogue : listeArticleCatalogue) {
        Row row = createRowGeneric(sheet, numRow, 500);
        row.createCell(0).setCellValue(articleCatalogue.getReference());
        row.createCell(1).setCellValue(articleCatalogue.getLibelle());
        row.createCell(2).setCellValue(articleCatalogue.getPrix());
        row.createCell(3).setCellValue(articleCatalogue.getLibelleColisage());
        row.createCell(4).setCellValue(mapArticleQuantite.get(articleCatalogue));

        String strFormula = "C" + (numRow + 1) + "*E" + (numRow + 1) + "";
        Cell cell = row.createCell(5);
        cell.setCellType(CellType.FORMULA);
        cell.setCellFormula(strFormula);

        CellStyle style = createCellWithBorderAndColor(wb, BorderStyle.THIN, IndexedColors.LIGHT_YELLOW, false);
        CellStyle stylePrix = createCellWithBorderAndColor(wb, BorderStyle.THIN, IndexedColors.LIGHT_YELLOW,
                false);
        stylePrix.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0"));

        row.getCell(0).setCellStyle(style);
        row.getCell(1).setCellStyle(style);
        row.getCell(2).setCellStyle(stylePrix);
        row.getCell(3).setCellStyle(style);
        row.getCell(4).setCellStyle(style);
        row.getCell(5).setCellStyle(stylePrix);
        numRow++;
    }
}

From source file:org.esa.snap.classification.gpf.maximumlikelihood.MaximumLikelihood.java

public void buildClassifier(Dataset data) {

    meanVector = new HashMap<>();
    invCov = new HashMap<>();
    determinant = new HashMap<>();

    // 1/[(2 PI)^(N/2)]
    constantTerm = 1.0 / (Math.pow(2.0 * Math.PI, (double) data.noAttributes() / 2.0));
    //SystemUtils.LOG.info("MaximumLikelihood: constantTerm = " + constantTerm);

    Map<Object, StorelessCovariance> covarianceMap = new HashMap<>();
    Map<Object, Integer> cntMap = new HashMap<>();
    for (Object o : data.classes()) {
        covarianceMap.put(o, new StorelessCovariance(data.noAttributes(), biasCorrected));
        meanVector.put(o, new double[data.noAttributes()]);
        cntMap.put(o, 0);/*from   w w w. jav  a  2s.c om*/
    }

    final double[] features = new double[data.noAttributes()];
    Object classVal;
    double featureVal;
    for (Instance i : data) {
        classVal = i.classValue();
        for (int j = 0; j < features.length; j++) {
            featureVal = i.value(j);
            features[j] = featureVal;
            meanVector.get(classVal)[j] += featureVal;
        }
        covarianceMap.get(classVal).increment(features);
        cntMap.replace(classVal, cntMap.get(classVal) + 1);
    }

    for (Object o : covarianceMap.keySet()) {
        for (int i = 0; i < data.noAttributes(); i++) {
            meanVector.get(o)[i] /= cntMap.get(o);
        }
        try {
            final RealMatrix m1 = covarianceMap.get(o).getCovarianceMatrix();
            final Jama.Matrix m2 = new Jama.Matrix(m1.getData());
            invCov.put(o, m2.inverse());
            determinant.put(o, Math.abs(m2.det()));
        } catch (Exception e) {
            SystemUtils.LOG
                    .info("MaximumLikelihood.buildClassifier: cannot classify " + o + ' ' + e.getMessage());
        }
    }
}

From source file:api.accounts.UserVerify.java

public Map<String, Object> checkUserInfo(String userName, String password) {
    //{id, name, venue, time, image, category
    String queryStr = "SELECT * FROM Qashio_UserInfos WHERE userName=?";
    Map<String, Object> results = new HashMap<>();
    Map<String, Object> checkOutcome = new HashMap<>();
    List<Object> paras = new ArrayList<>();
    paras.add(userName);/*w  w w  . ja v  a2  s. c  o m*/
    try {
        checkOutcome.put("success", false);
        checkOutcome.put("msg", "");
        checkOutcome.put("method", "check");
        checkOutcome.put("sessionId", System.currentTimeMillis());
        results = db.findSingleResult(queryStr, paras);
        System.out.println("here" + results);
        //            db.connection.close();
        if (results.get("userName") != null) {
            String dbPassword = results.get("password").toString();
            if (dbPassword != null && (dbPassword.trim() == null ? password.trim() == null
                    : dbPassword.trim().equals(password.trim()))) {
                checkOutcome.replace("success", true);
            } else {
                checkOutcome.replace("success", false);
                checkOutcome.replace("msg", "password wrong");
            }
        } else {
            checkOutcome.replace("success", false);
            checkOutcome.replace("msg", "username not exist");
        }
    } catch (SQLException ex) {
        Logger.getLogger(UserVerify.class.getName()).log(Level.SEVERE, null, ex);
    }

    return checkOutcome;
}

From source file:com.fcorti.aaar.GetNodeIdsModifiedBeforeWebScript.java

protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {

    // Parameters.
    Map<String, Object> parameters = null;
    try {//from w  w w.j  av  a  2  s  .  co  m
        parameters = getParameters(req);
    } catch (Exception e) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, e.getMessage());
    }

    // Query execution.
    ResultSet resultSet = searchService.query(getSearchParameters(parameters));
    Iterator<ResultSetRow> resultIterator = resultSet.iterator();

    // New parameter values.
    Date newParameterDt = (Date) parameters.get(PARAMETER_DATE);
    int newParameterSkip = (int) parameters.get(PARAMETER_SKIP);

    // Result composition.
    List<String> results = new ArrayList<String>();
    while (resultIterator.hasNext()) {

        ResultSetRow resultSetRow = resultIterator.next();
        resultSetRow.getValues();

        results.add(String.valueOf(resultSetRow.getValue(ContentModel.PROP_NODE_DBID)));

        ++newParameterSkip;
    }

    resultSet.close();

    // Parameter values.
    parameters.replace(PARAMETER_DATE, getDateAsString((Date) parameters.get(PARAMETER_DATE), DATE_FORMAT));
    parameters.replace(PARAMETER_LIMIT, String.valueOf(parameters.get(PARAMETER_LIMIT)));
    parameters.replace(PARAMETER_SKIP, String.valueOf(parameters.get(PARAMETER_SKIP)));

    // New parameters values.
    Map<String, Object> newParameters = new HashMap<String, Object>();
    newParameters.put(PARAMETER_BASETYPE, parameters.get(PARAMETER_BASETYPE));
    newParameters.put(PARAMETER_DATE, getDateAsString(newParameterDt, DATE_FORMAT));
    newParameters.put(PARAMETER_LIMIT, parameters.get(PARAMETER_LIMIT));
    newParameters.put(PARAMETER_SKIP, String.valueOf(newParameterSkip));

    // Model definition.
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("count", String.valueOf(results.size()));
    model.put("results", results);
    model.put("parameters", parameters);
    model.put("newParameters", newParameters);

    return model;
}

From source file:uk.ac.sanger.cgp.wwdocker.daemon.PrimaryDaemon.java

private void hostSet(BaseConfiguration config, Map<String, String> hosts) {
    // first remove the killed off hosts
    List toRemove = new ArrayList();
    for (Map.Entry<String, String> e : hosts.entrySet()) {
        if (e.getValue().equals("DELETE")) {
            toRemove.add(e.getKey());//from   www .j a v a 2 s  .  co  m
        }
    }
    hosts.keySet().removeAll(toRemove);

    // add the new hosts
    BaseConfiguration workerConf = Config.loadWorkers(config.getString("workerCfg"));
    String[] rawHosts = workerConf.getStringArray("hosts");
    if (rawHosts.length == 1 && rawHosts[0].equals(new String())) {
        rawHosts = new String[0];
    }
    Set<String> tmp = new LinkedHashSet<>();
    for (String h : rawHosts) {
        if (!hosts.containsKey(h)) {
            hosts.put(h, "TO_PROVISION");
        }
        tmp.add(h);
    }

    // identify which hosts need to be killed
    for (Map.Entry<String, String> e : hosts.entrySet()) {
        if (!tmp.contains(e.getKey())) {
            hosts.replace(e.getKey(), "KILL");
        }
    }
}

From source file:edu.cmu.lti.oaqa.knn4qa.apps.DataPointWrapper.java

/**
 * Adds ranks and scores obtained from a candidate provider.
 * // w w  w .  j a v a  2  s  . c  o m
 * @param docFeats        all features
 * @param resultsAll      result entries
 */
private void addScoresAndRanks(Map<String, DenseVector> docFeats, CandidateEntry[] resultsAll) {
    for (CandidateEntry e : resultsAll) {
        DenseVector oldVect = docFeats.get(e.mDocId);
        int oldSize = oldVect.size();
        DenseVector newVect = new DenseVector(oldSize + 2);
        newVect.set(0, e.mOrigRank);
        newVect.set(1, e.mOrigScore);
        for (int vi = 0; vi < oldSize; ++vi)
            newVect.set(vi + 2, oldVect.get(vi));
        docFeats.replace(e.mDocId, newVect);
    }

}

From source file:uk.ac.sanger.cgp.wwdocker.daemon.PrimaryDaemon.java

@Override
public void run(String mode)
        throws IOException, InterruptedException, TimeoutException, ConfigurationException {
    // lots of values that will be used over and over again
    String qPrefix = config.getString("qPrefix");
    File thisJar = Utils.thisJarFile();
    File tmpConf = new File(System.getProperty("java.io.tmpdir") + "/" + qPrefix + ".remote.cfg");
    tmpConf.deleteOnExit(); // contains passwords so cleanup
    config.save(tmpConf.getAbsolutePath()); // done like this so includes are pulled in
    Local.chmod(tmpConf, "go-rwx");

    // setup/*w  ww .j  a va  2s . c om*/
    Workflow workManager = new WorkflowFactory().getWorkflow(config);
    Map<String, String> envs = Config.getEnvs(config);

    /*
    * gets the list of worker hosts which CAN change during runtime
    * There is a way to get the config to load when changed, however it only
    * matters when we loop round so we may as well just rebuild the object
    */
    Map<String, String> hosts = new LinkedHashMap<>();
    hostSet(config, hosts);
    cleanHostQueues(config, hosts);

    if (mode != null && mode.equalsIgnoreCase("KILLALL")) {
        killAll(config, hosts, thisJar, tmpConf);
    }

    hosts.clear(); // needs to be clean before looping starts

    // this holds md5 of this JAR and the config (which lists the workflow code to use)
    WorkerState provState = new WorkerState(thisJar, tmpConf);

    int nextRetry = RETRY_INIT;

    while (true) {
        addWorkToPend(workManager, config);

        // this is a reload as this can change during execution
        hostSet(config, hosts);

        for (Map.Entry<String, String> e : hosts.entrySet()) {

            String host = e.getKey();
            if (e.getValue().equals("KILL")) {
                provState.setChangeStatusTo(HostStatus.KILL);
                messaging.sendMessage(qPrefix.concat(".").concat(host), Utils.objectToJson(provState));
                hosts.replace(host, "DELETE");
                continue;
            }

            provState.setChangeStatusTo(HostStatus.CHECKIN);
            provState.setReplyToQueue(qPrefix.concat(".ACTIVE"));

            if (e.getValue().equals("TO_PROVISION")
                    || ((e.getValue().equals("CURRENT") || e.getValue().equals("RETRY")) && nextRetry == 0)) {
                if (!messaging.queryGaveResponse(qPrefix.concat(".").concat(host), provState.getReplyToQueue(),
                        Utils.objectToJson(provState), 15000)) {
                    // no response from host... but is it still up
                    // see if docker is running before reprovision
                    Session hostSession = Remote.getSession(config, host);
                    boolean dockerRunning = Remote.dockerRunning(hostSession, hostSession.getUserName());
                    boolean workerRunning = Remote.workerRunning(hostSession, hostSession.getUserName());
                    Remote.closeSsh(hostSession);
                    if (dockerRunning || workerRunning) {
                        logger.trace("Retry host later: " + host);
                        hosts.replace(host, "RETRY");
                        continue;
                    }

                    logger.info("No response from host '".concat(host).concat("' (re)provisioning..."));
                    if (!workManager.provisionHost(host, PrimaryDaemon.config, thisJar, tmpConf, mode, envs)) {
                        hosts.replace(host, "BROKEN");
                        messaging.removeFromStateQueue(qPrefix.concat(".").concat("BROKEN"), host); // just incase it's already there
                        messaging.sendMessage(qPrefix.concat(".").concat("BROKEN"), "Failed to provision",
                                host);
                        break;
                    }
                }
                if (!e.getValue().equals("CURRENT")) {
                    hosts.replace(host, "CURRENT");
                    break; // so we start some work on this host before provisioning more
                }
            }
        }
        // we need a little sleep here or we'll kill the queues
        Thread.sleep(1000);
        if (nextRetry == 0) {
            nextRetry = RETRY_INIT;
        } else {
            nextRetry--;
        }
    }
}