Example usage for java.util Map containsKey

List of usage examples for java.util Map containsKey

Introduction

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

Prototype

boolean containsKey(Object key);

Source Link

Document

Returns true if this map contains a mapping for the specified key.

Usage

From source file:Main.java

public static void main(String args[]) {
    Map<String, Integer> atomNums = new TreeMap<String, Integer>();

    atomNums.put("A", 1);
    atomNums.put("B", 2);
    atomNums.put("C", 3);
    atomNums.put("D", 4);
    atomNums.put("E", 5);
    atomNums.put("F", 6);

    System.out.println("The map contains these " + atomNums.size() + " entries:");

    Set<Map.Entry<String, Integer>> set = atomNums.entrySet();

    for (Map.Entry<String, Integer> me : set) {
        System.out.print(me.getKey() + ", Atomic Number: ");
        System.out.println(me.getValue());
    }/*from w ww. j  a v  a2  s .  com*/
    TreeMap<String, Integer> atomNums2 = new TreeMap<String, Integer>();

    atomNums2.put("Q", 30);
    atomNums2.put("W", 82);

    atomNums.putAll(atomNums2);

    set = atomNums.entrySet();

    System.out.println("The map now contains these " + atomNums.size() + " entries:");
    for (Map.Entry<String, Integer> me : set) {
        System.out.print(me.getKey() + ", Atomic Number: ");
        System.out.println(me.getValue());
    }

    if (atomNums.containsKey("A"))
        System.out.println("A has an atomic number of " + atomNums.get("A"));

    if (atomNums.containsValue(82))
        System.out.println("The atomic number 82 is in the map.");
    System.out.println();

    if (atomNums.remove("A") != null)
        System.out.println("A has been removed.\n");
    else
        System.out.println("Entry not found.\n");

    Set<String> keys = atomNums.keySet();
    for (String str : keys)
        System.out.println(str + " ");

    Collection<Integer> vals = atomNums.values();
    for (Integer n : vals)
        System.out.println(n + " ");

    atomNums.clear();
    if (atomNums.isEmpty())
        System.out.println("The map is now empty.");
}

From source file:edu.cuhk.hccl.evaluation.EvaluationApp.java

public static void main(String[] args) throws IOException, TasteException {
    File realFile = new File(args[0]);
    File estimateFile = new File(args[1]);

    // Build real-rating map
    Map<String, long[]> realMap = buildRatingMap(realFile);

    // Build estimate-rating map
    Map<String, long[]> estimateMap = buildRatingMap(estimateFile);

    // Compare realMap with estimateMap
    Map<Integer, List<Double>> realList = new HashMap<Integer, List<Double>>();
    Map<Integer, List<Double>> estimateList = new HashMap<Integer, List<Double>>();

    // Use set to store non-duplicate pairs only
    Set<String> noRatingList = new HashSet<String>();

    for (String pair : realMap.keySet()) {
        long[] realRatings = realMap.get(pair);
        long[] estimateRatings = estimateMap.get(pair);

        if (realRatings == null || estimateRatings == null)
            continue;

        for (int i = 0; i < realRatings.length; i++) {
            long real = realRatings[i];
            long estimate = estimateRatings[i];

            // continue if the aspect rating can not be estimated due to incomplete reviews
            if (estimate <= 0) {
                noRatingList.add(pair.replace("@", "\t"));
                continue;
            }/*from w  w w  .  ja  v a 2s .c  o  m*/

            if (real > 0 && estimate > 0) {
                if (!realList.containsKey(i))
                    realList.put(i, new ArrayList<Double>());

                realList.get(i).add((double) real);

                if (!estimateList.containsKey(i))
                    estimateList.put(i, new ArrayList<Double>());

                estimateList.get(i).add((double) estimate);
            }
        }
    }

    System.out.println("[INFO] RMSE, MAE for estimate ratings: ");
    System.out.println("------------------------------");
    System.out.println("Index \t RMSE \t MAE");
    for (int i = 1; i < 6; i++) {
        double rmse = Metric.computeRMSE(realList.get(i), estimateList.get(i));
        double mae = Metric.computeMAE(realList.get(i), estimateList.get(i));

        System.out.printf("%d \t %.3f \t %.3f \n", i, rmse, mae);
    }

    System.out.println("------------------------------");

    if (noRatingList.size() > 0) {
        String noRatingFileName = "evaluation-no-ratings.txt";
        FileUtils.writeLines(new File(noRatingFileName), noRatingList, false);

        System.out.println("[INFO] User-item pairs with no ratings are saved in file: " + noRatingFileName);
    } else {
        System.out.println("[INFO] All user-item pairs have ratings.");
    }
}

From source file:de.huxhorn.lilith.Lilith.java

public static void main(String[] args) {
    {/*  w  w  w  .  j  a  v  a  2  s. c  o m*/
        // initialize java.util.logging to use slf4j...
        Handler handler = new Slf4JHandler();
        java.util.logging.Logger rootLogger = java.util.logging.Logger.getLogger("");
        rootLogger.addHandler(handler);
        rootLogger.setLevel(java.util.logging.Level.WARNING);
    }

    StringBuilder appTitle = new StringBuilder();
    appTitle.append(APP_NAME).append(" V").append(APP_VERSION);
    if (APP_SNAPSHOT) {
        // always append timestamp for SNAPSHOT
        appTitle.append(" (").append(APP_TIMESTAMP_DATE).append(")");
    }

    CommandLineArgs cl = new CommandLineArgs();
    JCommander commander = new JCommander(cl);
    Cat cat = new Cat();
    commander.addCommand(Cat.NAME, cat);
    Tail tail = new Tail();
    commander.addCommand(Tail.NAME, tail);
    Filter filter = new Filter();
    commander.addCommand(Filter.NAME, filter);
    Index index = new Index();
    commander.addCommand(Index.NAME, index);
    Md5 md5 = new Md5();
    commander.addCommand(Md5.NAME, md5);
    Help help = new Help();
    commander.addCommand(Help.NAME, help);

    try {
        commander.parse(args);
    } catch (ParameterException ex) {
        printAppInfo(appTitle.toString(), false);
        System.out.println(ex.getMessage() + "\n");
        printHelp(commander);
        System.exit(-1);
    }
    if (cl.verbose) {
        if (!APP_SNAPSHOT) {
            // timestamp is always appended for SNAPSHOT
            // don't append it twice
            appTitle.append(" (").append(APP_TIMESTAMP_DATE).append(")");
        }
        appTitle.append(" - ").append(APP_REVISION);
    }

    String appTitleString = appTitle.toString();
    if (cl.showHelp) {
        printAppInfo(appTitleString, false);
        printHelp(commander);
        System.exit(0);
    }

    String command = commander.getParsedCommand();
    if (!Tail.NAME.equals(command) && !Cat.NAME.equals(command) && !Filter.NAME.equals(command)) // don't print info in case of cat, tail or filter
    {
        printAppInfo(appTitleString, true);
    }

    if (cl.logbackConfig != null) {
        File logbackFile = new File(cl.logbackConfig);
        if (!logbackFile.isFile()) {
            System.out.println(logbackFile.getAbsolutePath() + " is not a valid file.");
            System.exit(-1);
        }
        try {
            initLogbackConfig(logbackFile.toURI().toURL());
        } catch (MalformedURLException e) {
            System.out.println("Failed to convert " + logbackFile.getAbsolutePath() + " to URL. " + e);
            System.exit(-1);
        }
    } else if (cl.verbose) {
        initVerboseLogging();
    }

    if (cl.printBuildTimestamp) {
        System.out.println("Build-Date     : " + APP_TIMESTAMP_DATE);
        System.out.println("Build-Revision : " + APP_REVISION);
        System.out.println("Build-Timestamp: " + APP_TIMESTAMP);
        System.exit(0);
    }

    if (Help.NAME.equals(command)) {
        commander.usage();
        if (help.commands == null || help.commands.size() == 0) {
            commander.usage(Help.NAME);
        } else {
            Map<String, JCommander> commands = commander.getCommands();
            for (String current : help.commands) {
                if (commands.containsKey(current)) {
                    commander.usage(current);
                } else {
                    System.out.println("Unknown command '" + current + "'!");
                }
            }
        }
        System.exit(0);
    }

    if (Md5.NAME.equals(command)) {
        List<String> files = md5.files;
        if (files == null || files.isEmpty()) {
            printHelp(commander);
            System.out.println("Missing files!");
            System.exit(-1);
        }
        boolean error = false;
        for (String current : files) {
            if (!CreateMd5Command.createMd5(new File(current))) {
                error = true;
            }
        }
        if (error) {
            System.exit(-1);
        }
        System.exit(0);
    }

    if (Index.NAME.equals(command)) {
        if (!cl.verbose && cl.logbackConfig == null) {
            initCLILogging();
        }
        List<String> files = index.files;
        if (files == null || files.size() == 0) {
            printHelp(commander);
            System.exit(-1);
        }
        boolean error = false;
        for (String current : files) {
            if (!IndexCommand.indexLogFile(new File(current))) {
                error = true;
            }
        }
        if (error) {
            System.exit(-1);
        }
        System.exit(0);
    }

    if (Cat.NAME.equals(command)) {
        if (!cl.verbose && cl.logbackConfig == null) {
            initCLILogging();
        }
        List<String> files = cat.files;
        if (files == null || files.size() != 1) {
            printHelp(commander);
            System.exit(-1);
        }
        if (CatCommand.catFile(new File(files.get(0)), cat.pattern, cat.numberOfLines)) {
            System.exit(0);
        }
        System.exit(-1);
    }

    if (Tail.NAME.equals(command)) {
        if (!cl.verbose && cl.logbackConfig == null) {
            initCLILogging();
        }
        List<String> files = tail.files;
        if (files == null || files.size() != 1) {
            printHelp(commander);
            System.exit(-1);
        }
        if (TailCommand.tailFile(new File(files.get(0)), tail.pattern, tail.numberOfLines, tail.keepRunning)) {
            System.exit(0);
        }
        System.exit(-1);
    }

    if (Filter.NAME.equals(command)) {
        if (!cl.verbose && cl.logbackConfig == null) {
            initCLILogging();
        }
        if (FilterCommand.filterFile(new File(filter.input), new File(filter.output),
                new File(filter.condition), filter.searchString, filter.pattern, filter.overwrite,
                filter.keepRunning, filter.exclusive)) {
            System.exit(0);
        }
        System.exit(-1);
    }

    if (cl.flushPreferences) {
        flushPreferences();
    }

    if (cl.exportPreferencesFile != null) {
        exportPreferences(cl.exportPreferencesFile);
    }

    if (cl.importPreferencesFile != null) {
        importPreferences(cl.importPreferencesFile);
    }

    if (cl.exportPreferencesFile != null || cl.importPreferencesFile != null) {
        System.exit(0);
    }

    if (cl.flushLicensed) {
        flushLicensed();
    }

    startLilith(appTitleString);
}

From source file:fr.sewatech.sewatoool.impress.Main.java

/**
 * @param args cf. usage.txt/*from   ww w  .  ja  v a2 s  .  c om*/
 * 
 * @author "Alexis Hassler (alexis.hassler@sewatech.org)"
 */
public static void main(String[] args) {
    // Analyse des arguments
    if (args.length == 0) {
        message(MESSAGE_WRONG_ARGS);
        logger.warn("Probleme d'arguments : pas d'argument");
    }

    Map<String, String> arguments = new HashMap<String, String>();
    String argName = null;
    String documentLocation = null;
    for (String arg : args) {
        if ("--".equals(arg.substring(0, 2))) {
            argName = arg.substring(2);
            arguments.put(argName, "");
        } else if (argName != null) {
            arguments.put(argName, arg);
            argName = null;
        } else if (documentLocation == null) {
            documentLocation = arg;
        } else {
            message(MESSAGE_WRONG_ARGS);
            logger.warn("Probleme d'arguments : 2 fois le nom du fichier");
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Liste des arguments pris en compte : ");
        for (Entry<String, String> option : arguments.entrySet()) {
            logger.debug("  Argument " + option.getKey() + "=" + option.getValue());
        }
    }

    if (arguments.containsKey("help")) {
        if (logger.isDebugEnabled()) {
            logger.debug("Affichage de l'aide");
        }
        doHelp();
    }

    try {
        ImpressService service = new ImpressService();

        ImpressDocument document = service.loadDocument(documentLocation, arguments.containsKey("hidden"));

        doToc(arguments, service, document);

        doPdf(arguments, service, document);

        if (!arguments.containsKey("no-save")) {
            service.save(document);
        }
        if (!arguments.containsKey("no-close")) {
            service.close(document);
        }

    } catch (Throwable e) {
        logger.error("Il y a un probleme...", e);
    } finally {
        System.exit(0);
    }
}

From source file:com.ifeng.sorter.NginxApp.java

public static void main(String[] args) {

    String input = "src/test/resources/data/nginx_report.txt";

    PrintWriter pw = null;/*from ww w  . j  av a  2  s .  c om*/

    Map<String, List<LogBean>> resultMap = new HashMap<String, List<LogBean>>();
    List<String> ips = new ArrayList<String>();

    try {
        List<String> lines = FileUtils.readLines(new File(input));
        List<LogBean> items = new ArrayList<LogBean>();

        for (String line : lines) {
            String[] values = line.split("\t");

            if (values != null && values.length == 3) {// ip total seria
                try {
                    String ip = values[0].trim();
                    String total = values[1].trim();
                    String seria = values[2].trim();

                    LogBean bean = new LogBean(ip, Integer.parseInt(total), seria);

                    items.add(bean);

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

        Collections.sort(items);

        for (LogBean bean : items) {
            String key = bean.getIp();

            if (resultMap.containsKey(key)) {
                resultMap.get(key).add(bean);
            } else {
                List<LogBean> keyList = new ArrayList<LogBean>();
                keyList.add(bean);
                resultMap.put(key, keyList);

                ips.add(key);
            }
        }

        pw = new PrintWriter("src/test/resources/output/result.txt", "UTF-8");

        for (String ip : ips) {
            List<LogBean> list = resultMap.get(ip);

            for (LogBean bean : list) {
                pw.append(bean.toString());
                pw.println();
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        pw.flush();
        pw.close();
    }
}

From source file:com.joliciel.talismane.terminology.TalismaneTermExtractorMain.java

public static void main(String[] args) throws Exception {
    String termFilePath = null;//from w w  w.j  av  a 2  s.  c  o m
    String outFilePath = null;
    Command command = Command.extract;
    int depth = -1;
    String databasePropertiesPath = null;
    String projectCode = null;
    String terminologyPropertiesPath = null;

    Map<String, String> argMap = StringUtils.convertArgs(args);

    String logConfigPath = argMap.get("logConfigFile");
    if (logConfigPath != null) {
        argMap.remove("logConfigFile");
        Properties props = new Properties();
        props.load(new FileInputStream(logConfigPath));
        PropertyConfigurator.configure(props);
    }

    Map<String, String> innerArgs = new HashMap<String, String>();
    for (Entry<String, String> argEntry : argMap.entrySet()) {
        String argName = argEntry.getKey();
        String argValue = argEntry.getValue();

        if (argName.equals("command"))
            command = Command.valueOf(argValue);
        else if (argName.equals("termFile"))
            termFilePath = argValue;
        else if (argName.equals("outFile"))
            outFilePath = argValue;
        else if (argName.equals("depth"))
            depth = Integer.parseInt(argValue);
        else if (argName.equals("databaseProperties"))
            databasePropertiesPath = argValue;
        else if (argName.equals("terminologyProperties"))
            terminologyPropertiesPath = argValue;
        else if (argName.equals("projectCode"))
            projectCode = argValue;
        else
            innerArgs.put(argName, argValue);
    }
    if (termFilePath == null && databasePropertiesPath == null)
        throw new TalismaneException("Required argument: termFile or databasePropertiesPath");

    if (termFilePath != null) {
        String currentDirPath = System.getProperty("user.dir");
        File termFileDir = new File(currentDirPath);
        if (termFilePath.lastIndexOf("/") >= 0) {
            String termFileDirPath = termFilePath.substring(0, termFilePath.lastIndexOf("/"));
            termFileDir = new File(termFileDirPath);
            termFileDir.mkdirs();
        }
    }

    long startTime = new Date().getTime();
    try {
        if (command.equals(Command.analyse)) {
            innerArgs.put("command", "analyse");
        } else {
            innerArgs.put("command", "process");
        }

        String sessionId = "";
        TalismaneServiceLocator locator = TalismaneServiceLocator.getInstance(sessionId);
        TalismaneService talismaneService = locator.getTalismaneService();

        TalismaneConfig config = talismaneService.getTalismaneConfig(innerArgs, sessionId);

        TerminologyServiceLocator terminologyServiceLocator = TerminologyServiceLocator.getInstance(locator);
        TerminologyService terminologyService = terminologyServiceLocator.getTerminologyService();
        TerminologyBase terminologyBase = null;

        if (projectCode == null)
            throw new TalismaneException("Required argument: projectCode");

        File file = new File(databasePropertiesPath);
        FileInputStream fis = new FileInputStream(file);
        Properties dataSourceProperties = new Properties();
        dataSourceProperties.load(fis);
        terminologyBase = terminologyService.getPostGresTerminologyBase(projectCode, dataSourceProperties);

        TalismaneSession talismaneSession = talismaneService.getTalismaneSession();

        if (command.equals(Command.analyse) || command.equals(Command.extract)) {
            Locale locale = talismaneSession.getLocale();
            Map<TerminologyProperty, String> terminologyProperties = new HashMap<TerminologyProperty, String>();
            if (terminologyPropertiesPath != null) {
                Map<String, String> terminologyPropertiesStr = StringUtils.getArgMap(terminologyPropertiesPath);
                for (String key : terminologyPropertiesStr.keySet()) {
                    try {
                        TerminologyProperty property = TerminologyProperty.valueOf(key);
                        terminologyProperties.put(property, terminologyPropertiesStr.get(key));
                    } catch (IllegalArgumentException e) {
                        throw new TalismaneException("Unknown terminology property: " + key);
                    }
                }
            } else {
                terminologyProperties = getDefaultTerminologyProperties(locale);
            }
            if (depth <= 0 && !terminologyProperties.containsKey(TerminologyProperty.maxDepth))
                throw new TalismaneException("Required argument: depth");

            InputStream regexInputStream = getInputStreamFromResource(
                    "parser_conll_with_location_input_regex.txt");
            Scanner regexScanner = new Scanner(regexInputStream, "UTF-8");
            String inputRegex = regexScanner.nextLine();
            regexScanner.close();
            config.setInputRegex(inputRegex);

            Charset outputCharset = config.getOutputCharset();

            TermExtractor termExtractor = terminologyService.getTermExtractor(terminologyBase,
                    terminologyProperties);
            if (depth > 0)
                termExtractor.setMaxDepth(depth);
            termExtractor.setOutFilePath(termFilePath);

            if (outFilePath != null) {
                if (outFilePath.lastIndexOf("/") >= 0) {
                    String outFileDirPath = outFilePath.substring(0, outFilePath.lastIndexOf("/"));
                    File outFileDir = new File(outFileDirPath);
                    outFileDir.mkdirs();
                }
                File outFile = new File(outFilePath);
                outFile.delete();
                outFile.createNewFile();

                Writer writer = new BufferedWriter(
                        new OutputStreamWriter(new FileOutputStream(outFilePath), outputCharset));
                TermAnalysisWriter termAnalysisWriter = new TermAnalysisWriter(writer);
                termExtractor.addTermObserver(termAnalysisWriter);
            }

            Talismane talismane = config.getTalismane();
            talismane.setParseConfigurationProcessor(termExtractor);
            talismane.process();
        } else if (command.equals(Command.list)) {

            List<Term> terms = terminologyBase.findTerms(2, null, 0, null, null);
            for (Term term : terms) {
                LOG.debug("Term: " + term.getText());
                LOG.debug("Frequency: " + term.getFrequency());
                LOG.debug("Heads: " + term.getHeads());
                LOG.debug("Expansions: " + term.getExpansions());
                LOG.debug("Contexts: " + term.getContexts());
            }
        }
    } finally {
        long endTime = new Date().getTime();
        long totalTime = endTime - startTime;
        LOG.info("Total time: " + totalTime);
    }
}

From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step1PrepareContainers.java

public static void main(String[] args) throws IOException {
    // queries with narratives in CSV
    File queries = new File(args[0]);
    File relevantInformationExamplesFile = new File(args[1]);

    Map<Integer, Map<Integer, List<String>>> relevantInformationMap = parseRelevantInformationFile(
            relevantInformationExamplesFile);

    // output dir
    File outputDir = new File(args[2]);
    if (!outputDir.exists()) {
        outputDir.mkdirs();/*from  ww  w . ja v  a2 s  .c  om*/
    }

    // iterate over queries
    CSVParser csvParser = CSVParser.parse(queries, Charset.forName("utf-8"), CSVFormat.DEFAULT);
    for (CSVRecord record : csvParser) {
        // create new container, fill, and store
        QueryResultContainer container = new QueryResultContainer();
        container.qID = record.get(0);
        container.query = record.get(1);

        // Fill some dummy text first
        container.relevantInformationExamples.addAll(Collections.singletonList("ERROR. Information missing."));
        container.irrelevantInformationExamples
                .addAll(Collections.singletonList("ERROR. Information missing."));

        // and now fill it with existing information if available
        Integer queryID = Integer.valueOf(container.qID);
        if (relevantInformationMap.containsKey(queryID)) {
            if (relevantInformationMap.get(queryID).containsKey(0)) {
                container.irrelevantInformationExamples = new ArrayList<>(
                        relevantInformationMap.get(queryID).get(0));
            }

            if (relevantInformationMap.get(queryID).containsKey(1)) {
                container.relevantInformationExamples = new ArrayList<>(
                        relevantInformationMap.get(queryID).get(1));
            }
        }

        File outputFile = new File(outputDir, container.qID + ".xml");
        FileUtils.writeStringToFile(outputFile, container.toXML());
        System.out.println("Finished " + outputFile);
    }
}

From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step6HITPreparator.java

public static void main(String[] args) throws Exception {
    // input dir - list of xml query containers
    // step5-linguistic-annotation/
    System.err.println("Starting step 6 HIT Preparation");

    File inputDir = new File(args[0]);

    // output dir
    File outputDir = new File(args[1]);
    if (outputDir.exists()) {
        outputDir.delete();/*  ww  w  . j a v a 2s .co  m*/
    }
    outputDir.mkdir();

    List<String> queries = new ArrayList<>();

    // iterate over query containers
    int countClueWeb = 0;
    int countSentence = 0;
    for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) {
        QueryResultContainer queryResultContainer = QueryResultContainer
                .fromXML(FileUtils.readFileToString(f, "utf-8"));
        if (queries.contains(f.getName()) || queries.size() == 0) {
            // groups contain only non-empty documents
            Map<Integer, List<QueryResultContainer.SingleRankedResult>> groups = new HashMap<>();

            // split to groups according to number of sentences
            for (QueryResultContainer.SingleRankedResult rankedResult : queryResultContainer.rankedResults) {
                if (rankedResult.originalXmi != null) {
                    byte[] bytes = new BASE64Decoder()
                            .decodeBuffer(new ByteArrayInputStream(rankedResult.originalXmi.getBytes()));
                    JCas jCas = JCasFactory.createJCas();
                    XmiCasDeserializer.deserialize(new ByteArrayInputStream(bytes), jCas.getCas());

                    Collection<Sentence> sentences = JCasUtil.select(jCas, Sentence.class);

                    int groupId = sentences.size() / 40;
                    if (rankedResult.originalXmi == null) {
                        System.err.println("Empty document: " + rankedResult.clueWebID);
                    } else {
                        if (!groups.containsKey(groupId)) {
                            groups.put(groupId, new ArrayList<>());

                        }
                    }
                    //handle it
                    groups.get(groupId).add(rankedResult);
                    countClueWeb++;
                }
            }

            for (Map.Entry<Integer, List<QueryResultContainer.SingleRankedResult>> entry : groups.entrySet()) {
                Integer groupId = entry.getKey();
                List<QueryResultContainer.SingleRankedResult> rankedResults = entry.getValue();

                // make sure the results are sorted
                // DEBUG
                //                for (QueryResultContainer.SingleRankedResult r : rankedResults) {
                //                    System.out.print(r.rank + "\t");
                //                }

                Collections.sort(rankedResults, (o1, o2) -> o1.rank.compareTo(o2.rank));

                // iterate over results for one query and group
                for (int i = 0; i < rankedResults.size() && i < TOP_RESULTS_PER_GROUP; i++) {
                    QueryResultContainer.SingleRankedResult rankedResult = rankedResults.get(i);

                    QueryResultContainer.SingleRankedResult r = rankedResults.get(i);
                    int rank = r.rank;
                    MustacheFactory mf = new DefaultMustacheFactory();
                    Mustache mustache = mf.compile("template/template.html");
                    String queryId = queryResultContainer.qID;
                    String query = queryResultContainer.query;
                    // make the first letter uppercase
                    query = query.substring(0, 1).toUpperCase() + query.substring(1);

                    List<String> relevantInformationExamples = queryResultContainer.relevantInformationExamples;
                    List<String> irrelevantInformationExamples = queryResultContainer.irrelevantInformationExamples;
                    byte[] bytes = new BASE64Decoder()
                            .decodeBuffer(new ByteArrayInputStream(rankedResult.originalXmi.getBytes()));

                    JCas jCas = JCasFactory.createJCas();
                    XmiCasDeserializer.deserialize(new ByteArrayInputStream(bytes), jCas.getCas());

                    List<generators.Sentence> sentences = new ArrayList<>();
                    List<Integer> paragraphs = new ArrayList<>();
                    paragraphs.add(0);

                    for (WebParagraph webParagraph : JCasUtil.select(jCas, WebParagraph.class)) {
                        for (Sentence s : JCasUtil.selectCovered(Sentence.class, webParagraph)) {

                            String sentenceBegin = String.valueOf(s.getBegin());
                            generators.Sentence sentence = new generators.Sentence(s.getCoveredText(),
                                    sentenceBegin);
                            sentences.add(sentence);
                            countSentence++;
                        }
                        int SentenceID = paragraphs.get(paragraphs.size() - 1);
                        if (sentences.size() > 120)
                            while (SentenceID < sentences.size()) {
                                if (!paragraphs.contains(SentenceID))
                                    paragraphs.add(SentenceID);
                                SentenceID = SentenceID + 120;
                            }
                        paragraphs.add(sentences.size());

                    }
                    System.err.println("Output dir: " + outputDir);
                    int startID = 0;
                    int endID;

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

                        endID = paragraphs.get(j);
                        int sentLength = endID - startID;
                        if (sentLength > 120 || j == paragraphs.size() - 1) {
                            if (sentLength > 120) {

                                endID = paragraphs.get(j - 1);
                                j--;
                            }
                            sentLength = endID - startID;
                            if (sentLength <= 40)
                                groupId = 40;
                            else if (sentLength <= 80 && sentLength > 40)
                                groupId = 80;
                            else if (sentLength > 80)
                                groupId = 120;

                            File folder = new File(outputDir + "/" + groupId);
                            if (!folder.exists()) {
                                System.err.println("creating directory: " + outputDir + "/" + groupId);
                                boolean result = false;

                                try {
                                    folder.mkdir();
                                    result = true;
                                } catch (SecurityException se) {
                                    //handle it
                                }
                                if (result) {
                                    System.out.println("DIR created");
                                }
                            }

                            String newHtmlFile = folder.getAbsolutePath() + "/" + f.getName() + "_"
                                    + rankedResult.clueWebID + "_" + sentLength + ".html";
                            System.err.println("Printing a file: " + newHtmlFile);
                            File newHTML = new File(newHtmlFile);
                            int t = 0;
                            while (newHTML.exists()) {
                                newHTML = new File(folder.getAbsolutePath() + "/" + f.getName() + "_"
                                        + rankedResult.clueWebID + "_" + sentLength + "." + t + ".html");
                                t++;
                            }
                            mustache.execute(new PrintWriter(new FileWriter(newHTML)),
                                    new generators(query, relevantInformationExamples,
                                            irrelevantInformationExamples, sentences.subList(startID, endID),
                                            queryId, rank))
                                    .flush();
                            startID = endID;
                        }
                    }
                }
            }

        }
    }
    System.out.println("Printed " + countClueWeb + " documents with " + countSentence + " sentences");
}

From source file:com.techmahindra.vehicletelemetry.chart.CarEventServlet.java

public static void main(String[] args) throws TypeMismatchException {

    List<CarEvent> carData = new LinkedList<>();
    /*carData.add(new CarEvent("city1","model1",41));
    carData.add(new CarEvent("city1","model2",17));
            //from   w  w w  .  j  a v  a2  s  .c  om
    carData.add(new CarEvent("city2","model1",31));
    carData.add(new CarEvent("city2","model2",39));
            
    carData.add(new CarEvent("Bellevue","model1",47));*/

    /*carData.add(new CarEvent("Seattle","MediumSUV",1038)); 
    carData.add(new CarEvent("Seattle","LargeSUV",2415));
    carData.add(new CarEvent("Seattle","FamilySaloon",2388));
    carData.add(new CarEvent("Seattle","SportsCar",1626)); 
    //aggDrivers.add(new CarEvent("Seattle","sports car",276)); 
    carData.add(new CarEvent("Seattle","Compactcar",204)); 
    carData.add(new CarEvent("Seattle","SmallSUV",1133)); 
    carData.add(new CarEvent("Seattle","StationWagon",1769)); 
    carData.add(new CarEvent("Seattle","CompactCar",839)); 
    carData.add(new CarEvent("Seattle","Hybrid",2603)); 
    carData.add(new CarEvent("Seattle","Coupe",1081)); 
    carData.add(new CarEvent("Seattle","Sedan",2603));
    carData.add(new CarEvent("Seattle","Convertible",1608));
            
    carData.add(new CarEvent("Redmond","MediumSUV",590));
    carData.add(new CarEvent("Redmond","LargeSUV",1407)); 
    carData.add(new CarEvent("Redmond","FamilySaloon",1535)); 
    carData.add(new CarEvent("Redmond","SportsCar",1115)); 
            
    //aggDrivers.add(new CarEvent("Redmond","sports car",102)); 
    carData.add(new CarEvent("Redmond","Compactcar",102)); 
    carData.add(new CarEvent("Redmond","SmallSUV",637)); 
    carData.add(new CarEvent("Redmond","StationWagon",1079));
    carData.add(new CarEvent("Redmond","CompactCar",606));
    carData.add(new CarEvent("Redmond","Hybrid",1635));
    carData.add(new CarEvent("Redmond","Coupe",605)); 
    carData.add(new CarEvent("Redmond","Sedan",1568)); 
    carData.add(new CarEvent("Redmond","Convertible",955)); 
            
    carData.add(new CarEvent("ammamish","SportsCar",1)); 
    carData.add(new CarEvent("ammamish","Sedan",21)); 
            
    carData.add(new CarEvent("ellevue","MediumSUV",778));
    carData.add(new CarEvent("ellevue","LargeSUV",2035));
    carData.add(new CarEvent("ellevue","FamilySaloon",1952)); 
    carData.add(new CarEvent("ellevue","SportsCar",1226));
    carData.add(new CarEvent("ellevue","Compactcar",162));
    //aggDrivers.add(new CarEvent("ellevue","sports car",192)); 
    carData.add(new CarEvent("ellevue","SmallSUV",895));
    carData.add(new CarEvent("ellevue","StationWagon",1469));
    carData.add(new CarEvent("ellevue","CompactCar",629));
    carData.add(new CarEvent("ellevue","Hybrid",1989)); 
    carData.add(new CarEvent("ellevue","Coupe",811)); 
    carData.add(new CarEvent("ellevue","Sedan",2004));
    carData.add(new CarEvent("ellevue","Convertible",1122));*/

    Map<String, List<Map<String, String>>> cityModelsMap = new LinkedHashMap<>();
    for (CarEvent carEvent1 : carData) {
        Map<String, String> modelMap = new HashMap<>();
        List<Map<String, String>> modelCountsList = new ArrayList<>();
        if (!cityModelsMap.containsKey(carEvent1.getCity())) {
            modelMap.put(carEvent1.getModel(), carEvent1.getCount());
            modelCountsList.add(modelMap);
            cityModelsMap.put(carEvent1.getCity(), modelCountsList);
        } else {
            List<Map<String, String>> existingModelCountsList = cityModelsMap.get(carEvent1.getCity());

            modelMap.put(carEvent1.getModel(), carEvent1.getCount());
            modelCountsList.add(modelMap);
            existingModelCountsList.addAll(modelCountsList);
            cityModelsMap.put(carEvent1.getCity(), existingModelCountsList);
        }
    }
    System.out.println("CityModelMap:" + cityModelsMap);
    //CityModelMap:{city1=[{model1=41}, {model11=17}, {model12=36}], city2=[{model2=31}, {model22=37}], city3=[{model3=47}, {model33=31}]}
    DataTable data = new DataTable();
    data.addColumn(new ColumnDescription(CITY_COLUMN, ValueType.TEXT, "city"));
    for (String cityKey : cityModelsMap.keySet()) {
        List<Map<String, String>> existingModelCountsList = cityModelsMap.get(cityKey);
        for (Map existingModelCountMap : existingModelCountsList) {
            Set set = existingModelCountMap.keySet();
            for (Object objModel : set) {
                String model = objModel.toString();
                if (!(data.containsColumn(model))) {
                    data.addColumn(new ColumnDescription(model, ValueType.NUMBER, model));
                    System.out.println("Column added:" + model);
                }
            }
        }
    }

    for (String cityKey : cityModelsMap.keySet()) {
        TableRow row = new TableRow();
        for (ColumnDescription selectionColumn : data.getColumnDescriptions()) {
            String columnName = selectionColumn.getId();
            if (columnName.equals(CITY_COLUMN)) {
                row.addCell(cityKey);
                continue;
            }
            List<Map<String, String>> existingModelCountsList = cityModelsMap.get(cityKey);
            for (Map existingModelCountMap : existingModelCountsList) {
                for (Object objModel : existingModelCountMap.keySet()) {
                    String model = objModel.toString();
                    Integer count = Integer.parseInt(existingModelCountMap.get(objModel).toString());
                    System.out.println("Model :" + model + " Count:" + count);
                    if (columnName.equals(model)) {
                        row.addCell(count);
                        continue;
                    }
                }
            }
        }
        data.addRow(row);
        System.out.println("Adding row");
    }
    System.out.println("Data is now:" + data.toString());

}

From source file:com.github.fritaly.graphml4j.samples.GradleDependencies.java

public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.out.println(String.format("%s <output-file>", GradleDependencies.class.getSimpleName()));
        System.exit(1);// w  ww. j  ava 2  s  .c  o  m
    }

    final File file = new File(args[0]);

    System.out.println("Writing GraphML file to " + file.getAbsolutePath() + " ...");

    FileWriter fileWriter = null;
    GraphMLWriter graphWriter = null;
    Reader reader = null;
    LineNumberReader lineReader = null;

    try {
        fileWriter = new FileWriter(file);
        graphWriter = new GraphMLWriter(fileWriter);

        // Customize the rendering of nodes
        final NodeStyle nodeStyle = graphWriter.getNodeStyle();
        nodeStyle.setWidth(250.0f);

        graphWriter.setNodeStyle(nodeStyle);

        // The dependency graph has been generated by Gradle with the
        // command "gradle dependencies". The output of this command has
        // been saved to a text file which will be parsed to rebuild the
        // dependency graph
        reader = new InputStreamReader(GradleDependencies.class.getResourceAsStream("gradle-dependencies.txt"));
        lineReader = new LineNumberReader(reader);

        String line = null;

        // Stack containing the node identifiers per depth inside the
        // dependency graph (the topmost dependency is the first one in the
        // stack)
        final Stack<String> parentIds = new Stack<String>();

        // Open the graph
        graphWriter.graph();

        // Map storing the node identifiers per label
        final Map<String, String> nodeIdsByLabel = new TreeMap<String, String>();

        while ((line = lineReader.readLine()) != null) {
            // Determine the depth of the current dependency inside the
            // graph. The depth can be inferred from the indentation used by
            // Gradle. Each level of depth adds 5 more characters of
            // indentation
            final int initialLength = line.length();

            // Remove the strings used by Gradle to indent dependencies
            line = StringUtils.replace(line, "+--- ", "");
            line = StringUtils.replace(line, "|    ", "");
            line = StringUtils.replace(line, "\\--- ", "");
            line = StringUtils.replace(line, "     ", "");

            // The depth can easily be inferred now
            final int depth = (initialLength - line.length()) / 5;

            // Remove unnecessary node ids
            while (depth <= parentIds.size()) {
                parentIds.pop();
            }

            // Compute a nice label from the dependency (group, artifact,
            // version) tuple
            final String label = computeLabel(line);

            // Has this dependency already been added to the graph ?
            if (!nodeIdsByLabel.containsKey(label)) {
                // No, add the node
                nodeIdsByLabel.put(label, graphWriter.node(label));
            }

            final String nodeId = nodeIdsByLabel.get(label);

            parentIds.push(nodeId);

            if (parentIds.size() > 1) {
                // Generate an edge between the current node and its parent
                graphWriter.edge(parentIds.get(parentIds.size() - 2), nodeId);
            }
        }

        // Close the graph
        graphWriter.closeGraph();

        System.out.println("Done");
    } finally {
        // Calling GraphMLWriter.close() is necessary to dispose the underlying resources
        graphWriter.close();
        fileWriter.close();
        lineReader.close();
        reader.close();
    }
}