List of usage examples for java.util Map put
V put(K key, V value);
From source file:cn.dehui.zbj1984105.GetAccountHierarchy.java
public static void main(String[] args) { try {// w ww . j ava 2 s. co m // Log SOAP XML request and response. AdWordsServiceLogger.log(); // Get AdWordsUser from "~/adwords.properties". AdWordsUser user = new AdWordsUser("adwords.properties").generateClientAdWordsUser(null); // Get the ServicedAccountService. ManagedCustomerServiceInterface managedCustomerService = user .getService(AdWordsService.V201209.MANAGED_CUSTOMER_SERVICE); // Create selector. Selector selector = new Selector(); selector.setFields(new String[] { "Login", "CustomerId" }); // Get results. ManagedCustomerPage page = managedCustomerService.get(selector); if (page.getEntries() != null) { // Create map from customerId to customer node. Map<Long, ManagedCustomerTreeNode> customerIdToCustomerNode = new HashMap<Long, ManagedCustomerTreeNode>(); // Create account tree nodes for each customer. for (ManagedCustomer customer : page.getEntries()) { ManagedCustomerTreeNode node = new ManagedCustomerTreeNode(); node.managedCustomer = customer; customerIdToCustomerNode.put(customer.getCustomerId(), node); } // For each link, connect nodes in tree. if (page.getLinks() != null) { for (ManagedCustomerLink link : page.getLinks()) { ManagedCustomerTreeNode managerNode = customerIdToCustomerNode .get(link.getManagerCustomerId()); ManagedCustomerTreeNode childNode = customerIdToCustomerNode .get(link.getClientCustomerId()); childNode.parentNode = managerNode; if (managerNode != null) { managerNode.childAccounts.add(childNode); } } } // Find the root account node in the tree. ManagedCustomerTreeNode rootNode = null; for (ManagedCustomer account : page.getEntries()) { if (customerIdToCustomerNode.get(account.getCustomerId()).parentNode == null) { rootNode = customerIdToCustomerNode.get(account.getCustomerId()); break; } } // Display account tree. System.out.println("Login, CustomerId (Status)"); System.out.println(rootNode.toTreeString(0, new StringBuffer())); } else { System.out.println("No serviced accounts were found."); } } catch (Exception e) { e.printStackTrace(); } }
From source file:DeliverWork.java
public static void main(String[] args) throws UnsupportedEncodingException, MessagingException { JdbcFactory jdbcFactoryChanye = new JdbcFactory( "jdbc:mysql://127.0.0.1:3306/fp_guimin?useUnicode=true&characterEncoding=UTF-8", "guimin_db", "guimin@98fhi3p2hUFHfdfoi", "com.mysql.jdbc.Driver"); connection = jdbcFactoryChanye.getConnection(); Map<String, String> map = new HashMap(); try {/*w w w .j a va 2s . c om*/ PreparedStatement ps = connection.prepareStatement(selectAccount); ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { map.put(resultSet.getString(1), resultSet.getString(2)); } ps.close(); map.forEach((k, v) -> { syncTheFile(k, v); }); connection.close(); } catch (SQLException e) { e.printStackTrace(); } finally { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } }
From source file:com.mycompany.javaapplicaton3.LerArquivo2.java
/** * @param args//from w ww . ja v a 2s .c o m * @throws Exception */ public static void main(String[] args) throws Exception { String SAMPLE_PERSON_DATA_FILE_PATH = "C:/Users/lprates/Documents/arquivo2013.xlsx"; // Input File initialize File file = new File(SAMPLE_PERSON_DATA_FILE_PATH); InputStream inputStream = new FileInputStream(file); // Excel Cell Mapping Map<String, String> cellMapping0150 = new HashMap<String, String>(); cellMapping0150.put("HEADER", "REG,COD_PART,NOME,COD_PAIS,CNPJ,CPF,IE,COD_MUN,SUFRAMA,END,NUM,COMPL,BAIRRO,BPE_VIGENCIA_FIN"); cellMapping0150.put("A", "reg"); cellMapping0150.put("B", "codPart"); cellMapping0150.put("C", "nome"); cellMapping0150.put("D", "codPais"); cellMapping0150.put("E", "cnpj"); cellMapping0150.put("F", "cpf"); cellMapping0150.put("G", "ie"); cellMapping0150.put("H", "codMun"); cellMapping0150.put("I", "suframa"); cellMapping0150.put("J", "end"); cellMapping0150.put("K", "num"); cellMapping0150.put("L", "compl"); cellMapping0150.put("M", "bairro"); cellMapping0150.put("N", "bpeVigenciaFin"); // Excel Cell Mapping Map<String, String> cellMapping0200 = new HashMap<String, String>(); cellMapping0200.put("HEADER", "REG,COD_ITEM,DESCR_ITEM,COD_BARRA,COD_ANT_ITEM,UNID_INV,TIPO_ITEM,COD_NCM,EX_IPI,COD_GEN,COD_LST,ALIQ_ICMS"); cellMapping0200.put("A", "reg"); cellMapping0200.put("B", "codItem"); cellMapping0200.put("C", "descrItem"); cellMapping0200.put("D", "codBarra"); cellMapping0200.put("E", "codAntItem"); cellMapping0200.put("F", "unidInv"); cellMapping0200.put("G", "tipoItem"); cellMapping0200.put("H", "codNcm"); cellMapping0200.put("I", "exIpi"); cellMapping0200.put("J", "codGen"); cellMapping0200.put("K", "codLst"); cellMapping0200.put("L", "aliqIcms"); // Excel Cell Mapping Map<String, String> cellMappingC100_C170 = new HashMap<String, String>(); cellMappingC100_C170.put("A", "campo1"); cellMappingC100_C170.put("B", "campo2"); cellMappingC100_C170.put("C", "campo3"); cellMappingC100_C170.put("D", "campo4"); cellMappingC100_C170.put("E", "campo5"); cellMappingC100_C170.put("F", "campo6"); cellMappingC100_C170.put("G", "campo7"); cellMappingC100_C170.put("H", "campo8"); cellMappingC100_C170.put("I", "campo9"); cellMappingC100_C170.put("J", "campo10"); cellMappingC100_C170.put("K", "campo11"); cellMappingC100_C170.put("L", "campo12"); cellMappingC100_C170.put("M", "campo13"); cellMappingC100_C170.put("N", "campo14"); cellMappingC100_C170.put("O", "campo15"); cellMappingC100_C170.put("P", "campo16"); cellMappingC100_C170.put("Q", "campo17"); cellMappingC100_C170.put("R", "campo18"); cellMappingC100_C170.put("S", "campo19"); cellMappingC100_C170.put("T", "campo20"); cellMappingC100_C170.put("U", "campo21"); cellMappingC100_C170.put("V", "campo22"); cellMappingC100_C170.put("W", "campo23"); cellMappingC100_C170.put("X", "campo24"); cellMappingC100_C170.put("Y", "campo25"); cellMappingC100_C170.put("Z", "campo26"); cellMappingC100_C170.put("AA", "campo27"); cellMappingC100_C170.put("AB", "campo28"); cellMappingC100_C170.put("AC", "campo29"); cellMappingC100_C170.put("AD", "campo30"); cellMappingC100_C170.put("AE", "campo31"); cellMappingC100_C170.put("AF", "campo32"); cellMappingC100_C170.put("AG", "campo33"); cellMappingC100_C170.put("AH", "campo34"); cellMappingC100_C170.put("AI", "campo35"); cellMappingC100_C170.put("AJ", "campo36"); cellMappingC100_C170.put("AK", "campo37"); cellMappingC100_C170.put("AL", "campo38"); cellMappingC100_C170.put("AM", "campo39"); cellMappingC100_C170.put("AN", "campo40"); cellMappingC100_C170.put("AO", "campo41"); cellMappingC100_C170.put("AP", "campo42"); cellMappingC100_C170.put("AQ", "campo43"); cellMappingC100_C170.put("AR", "campo44"); cellMappingC100_C170.put("AS", "campo45"); cellMappingC100_C170.put("AT", "campo46"); cellMappingC100_C170.put("AU", "campo47"); cellMappingC100_C170.put("AV", "campo48"); cellMappingC100_C170.put("AW", "campo49"); cellMappingC100_C170.put("AX", "campo50"); cellMappingC100_C170.put("AY", "campo51"); cellMappingC100_C170.put("AZ", "campo52"); cellMappingC100_C170.put("BA", "campo53"); cellMappingC100_C170.put("BB", "campo54"); cellMappingC100_C170.put("BC", "campo55"); cellMappingC100_C170.put("BD", "campo56"); cellMappingC100_C170.put("BE", "campo57"); cellMappingC100_C170.put("BF", "campo58"); cellMappingC100_C170.put("BG", "campo59"); cellMappingC100_C170.put("BH", "campo60"); cellMappingC100_C170.put("BI", "campo61"); cellMappingC100_C170.put("BJ", "campo62"); cellMappingC100_C170.put("BK", "campo63"); cellMappingC100_C170.put("BL", "campo64"); cellMappingC100_C170.put("BM", "campo65"); cellMappingC100_C170.put("BN", "campo66"); cellMappingC100_C170.put("BO", "campo67"); cellMappingC100_C170.put("BP", "campo68"); cellMappingC100_C170.put("BQ", "campo69"); cellMappingC100_C170.put("BR", "campo70"); cellMappingC100_C170.put("BS", "campo71"); // The package open is instantaneous, as it should be. OPCPackage pkg = null; try { ExcelWorkSheetHandler<Reg0150> workSheetHandler = new ExcelWorkSheetHandler<Reg0150>(Reg0150.class, cellMapping0150); pkg = OPCPackage.open(inputStream); ExcelSheetCallback sheetCallback = new ExcelSheetCallback() { private int sheetNumber = 0; public void startSheet(int sheetNum, String sheetName) { this.sheetNumber = sheetNum; System.out.println("Started processing sheet number=" + sheetNumber + " and Sheet Name is '" + sheetName + "'"); } @Override public void endSheet() { System.out.println("Processing completed for sheet number=" + sheetNumber); } public void startSheet(int sheetNum) { System.out.println("Started processing sheet number=" + sheetNum); } }; /*** Leitura Registro 0150 ***/ System.out.println("Constructor: pkg, workSheetHandler, sheetCallback"); ExcelReader example1 = new ExcelReader(pkg, workSheetHandler, sheetCallback); example1.process("0150"); if (workSheetHandler.getValueList().isEmpty()) { // No data present LOG.error("sHandler.getValueList() is empty"); } else { LOG.info(workSheetHandler.getValueList().size() + " no. of records read from given excel worksheet successfully."); // Displaying data ead from Excel file displayPersonList(workSheetHandler.getValueList()); } /*** Leitura Registro 0200 ***/ ExcelWorkSheetHandler<Reg0200> workSheetHandler0200 = new ExcelWorkSheetHandler<Reg0200>(Reg0200.class, cellMapping0200); ExcelReader example2 = new ExcelReader(pkg, workSheetHandler0200, null); example2.process("0200"); if (workSheetHandler0200.getValueList().isEmpty()) { LOG.error("sHandler.getValueList() is empty"); } else { LOG.info(workSheetHandler0200.getValueList().size() + " no. of records read from given excel worksheet successfully."); displayPersonList0200(workSheetHandler0200.getValueList()); } /*** Leitura Registro C100 e C170 ***/ ExcelWorkSheetHandler<RegC100_C170> workSheetHandlerC100_C170 = new ExcelWorkSheetHandler<RegC100_C170>( RegC100_C170.class, cellMappingC100_C170, 4); workSheetHandlerC100_C170.setVerifiyHeader(false); ExcelReader example3 = new ExcelReader(pkg, workSheetHandlerC100_C170, null); example3.process("201302"); if (workSheetHandlerC100_C170.getValueList().isEmpty()) { LOG.error("sHandler.getValueList() is empty"); } else { LOG.info(workSheetHandlerC100_C170.getValueList().size() + " no. of records read from given excel worksheet successfully."); displayPersonListC100_C170(workSheetHandlerC100_C170.getValueList()); } } catch (RuntimeException are) { LOG.error(are.getMessage(), are.getCause()); } catch (InvalidFormatException ife) { LOG.error(ife.getMessage(), ife.getCause()); } catch (IOException ioe) { LOG.error(ioe.getMessage(), ioe.getCause()); } finally { IOUtils.closeQuietly(inputStream); try { if (null != pkg) { pkg.close(); } } catch (IOException e) { // just ignore IO exception } } }
From source file:com.ipeirotis.gal.core.CategoryPair.java
public static void main(String[] args) { Category a = new Category("A"); Category b = new Category("B"); a.setPrior(0.5);// w ww . j av a 2 s . c o m b.setPrior(0.5); a.setCost("A", 0.0); a.setCost("B", 1.0); b.setCost("A", 1.0); b.setCost("B", 0.0); Collection<Category> categories = new HashSet<Category>(); categories.add(a); categories.add(b); Map<String, Category> map = new HashMap<String, Category>(); map.put("A", a); map.put("B", b); ConfusionMatrix cm = new ConfusionMatrix(categories); // FOR TESTS: // q=1 should return 0 cost // q=1 should not be affected by m /* cm.setErrorRate("A", "A", 0.9); cm.setErrorRate("A", "B", 0.1); cm.setErrorRate("B", "B", 0.0); cm.setErrorRate("B", "A", 1.0); double tau=0.01; double w = cm.getWorkerWage(1.0, tau, map); double pwage = Double.valueOf(new DecimalFormat("#.####").format(w)); double pworkers = Double.valueOf(new DecimalFormat("#.####").format(1.0/w)); System.out.print("\t"+pwage+"\t"+pworkers); */ //double q=0.9; for (int Q = 95; Q >= 55; Q -= 5) { double q = Q / 100.0; cm.setErrorRate("A", "A", q); cm.setErrorRate("A", "B", 1 - q); cm.setErrorRate("B", "B", q); cm.setErrorRate("B", "A", 1 - q); // Classification cost of a set of m workers with the confusion matrix given above /* for (int m = 1; m<=40; m+=2) { System.out.print(q+"\t"+m); Double c = cm.getWorkerCost(m, map, 100*m*m); System.out.println("\t"+Math.round(100000*c)/100000.0); } */ for (double tau = 0.1; tau > 0.0001; tau /= 1.5) { double pq = Double.valueOf(new DecimalFormat("#.##").format(q)); double ptau = Double.valueOf(new DecimalFormat("#.####").format((1 - tau))); System.out.print(pq + "\t" + ptau); double w = cm.getWorkerWage(1.0, tau, map); double pwage = Double.valueOf(new DecimalFormat("#.####").format(w)); double pworkers = Double.valueOf(new DecimalFormat("#.####").format(1.0 / w)); System.out.print("\t" + pwage + "\t" + pworkers); double wr = cm.getWorkerWageRegr(1.0, tau, map); double pwager = Double.valueOf(new DecimalFormat("#.####").format(wr)); double pworkersr = Double.valueOf(new DecimalFormat("#.####").format(1.0 / wr)); System.out.print("\t" + pwager + "\t" + pworkersr); System.out.println(); } } }
From source file:fr.inria.atlanmod.kyanos.benchmarks.KyanosGraphQuery.java
public static void main(String[] args) { Options options = new Options(); Option inputOpt = OptionBuilder.create(IN); inputOpt.setArgName("INPUT"); inputOpt.setDescription("Input Kyanos resource directory"); inputOpt.setArgs(1);//from ww w. j a v a 2 s .c om inputOpt.setRequired(true); Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS); inClassOpt.setArgName("CLASS"); inClassOpt.setDescription("FQN of EPackage implementation class"); inClassOpt.setArgs(1); inClassOpt.setRequired(true); Option optFileOpt = OptionBuilder.create(OPTIONS_FILE); optFileOpt.setArgName("FILE"); optFileOpt.setDescription("Properties file holding the options to be used in the Kyanos Resource"); optFileOpt.setArgs(1); options.addOption(inputOpt); options.addOption(inClassOpt); options.addOption(optFileOpt); CommandLineParser parser = new PosixParser(); try { PersistenceBackendFactoryRegistry.getFactories().put(NeoBlueprintsURI.NEO_GRAPH_SCHEME, new BlueprintsPersistenceBackendFactory()); CommandLine commandLine = parser.parse(options, args); URI uri = NeoBlueprintsURI.createNeoGraphURI(new File(commandLine.getOptionValue(IN))); Class<?> inClazz = KyanosGraphQuery.class.getClassLoader() .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS)); inClazz.getMethod("init").invoke(null); ResourceSet resourceSet = new ResourceSetImpl(); resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap() .put(NeoBlueprintsURI.NEO_GRAPH_SCHEME, PersistentResourceFactory.eINSTANCE); Resource resource = resourceSet.createResource(uri); Map<String, Object> loadOpts = new HashMap<String, Object>(); if (commandLine.hasOption(OPTIONS_FILE)) { Properties properties = new Properties(); properties.load(new FileInputStream(new File(commandLine.getOptionValue(OPTIONS_FILE)))); for (final Entry<Object, Object> entry : properties.entrySet()) { loadOpts.put((String) entry.getKey(), (String) entry.getValue()); } } resource.load(loadOpts); { LOG.log(Level.INFO, "Start query"); long begin = System.currentTimeMillis(); EList<MethodDeclaration> list = JavaQueries.getUnusedMethodsList(resource); long end = System.currentTimeMillis(); LOG.log(Level.INFO, "End query"); LOG.log(Level.INFO, MessageFormat.format("Query result (list) contains {0} elements", list.size())); LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin))); } { LOG.log(Level.INFO, "Start query"); long begin = System.currentTimeMillis(); EList<MethodDeclaration> list = JavaQueries.getUnusedMethodsLoop(resource); long end = System.currentTimeMillis(); LOG.log(Level.INFO, "End query"); LOG.log(Level.INFO, MessageFormat.format("Query result (loops) contains {0} elements", list.size())); LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin))); } if (resource instanceof PersistentResourceImpl) { PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) resource); } else { resource.unload(); } } catch (ParseException e) { MessageUtil.showError(e.toString()); MessageUtil.showError("Current arguments: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar <this-file.jar>", options, true); } catch (Throwable e) { MessageUtil.showError(e.toString()); } }
From source file:org.apache.asterix.experiment.client.LSMExperimentSetRunner.java
public static void main(String[] args) throws Exception { java.util.logging.Logger.getLogger("org.apache.http.headers").setLevel(Level.FINEST); // LogManager.getRootLogger().setLevel(org.apache.log4j.Level.OFF); LSMExperimentSetRunnerConfig config = new LSMExperimentSetRunnerConfig( String.valueOf(System.currentTimeMillis()), 3); CmdLineParser clp = new CmdLineParser(config); try {//w ww . ja v a 2 s . co m clp.parseArgument(args); } catch (CmdLineException e) { System.err.println(e.getMessage()); clp.printUsage(System.err); System.exit(1); } final String pkg = "org.apache.asterix.experiment.builder.suite"; Reflections reflections = //new Reflections("org.apache.asterix.experiment.builder.suite"); new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage(pkg)) .filterInputsBy(new FilterBuilder().includePackage(pkg)) .setScanners(new TypeElementsScanner().publicOnly(), new MethodParameterScanner())); Map<String, AbstractLSMBaseExperimentBuilder> nameMap = new TreeMap<>(); for (Constructor c : reflections.getConstructorsMatchParams(LSMExperimentSetRunnerConfig.class)) { AbstractLSMBaseExperimentBuilder b = (AbstractLSMBaseExperimentBuilder) c.newInstance(config); nameMap.put(b.getName(), b); } Pattern p = config.getRegex() == null ? null : Pattern.compile(config.getRegex()); SequentialActionList exps = new SequentialActionList(); for (Map.Entry<String, AbstractLSMBaseExperimentBuilder> e : nameMap.entrySet()) { if (p == null || p.matcher(e.getKey()).matches()) { exps.add(e.getValue().build()); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.info("Added " + e.getKey() + " to run list..."); } } } exps.perform(); }
From source file:com.act.analysis.surfactant.AnalysisDriver.java
public static void main(String[] args) throws Exception { Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());/*ww w.j a v a 2s . c o m*/ } CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { System.err.format("Argument parsing failed: %s\n", e.getMessage()); HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); return; } Set<String> seenOutputIds = new HashSet<>(); TSVWriter<String, String> tsvWriter = null; if (cl.hasOption(OPTION_OUTPUT_FILE)) { File outputFile = new File(cl.getOptionValue(OPTION_OUTPUT_FILE)); List<Map<String, String>> oldResults = null; if (outputFile.exists()) { System.err.format( "Output file already exists, reading old results and skipping processed molecules.\n"); TSVParser outputParser = new TSVParser(); outputParser.parse(outputFile); oldResults = outputParser.getResults(); for (Map<String, String> row : oldResults) { // TODO: verify that the last row was written cleanly/completely. seenOutputIds.add(row.get("id")); } } List<String> header = new ArrayList<>(); header.add("name"); header.add("id"); header.add("inchi"); header.add("label"); for (SurfactantAnalysis.FEATURES f : SurfactantAnalysis.FEATURES.values()) { header.add(f.toString()); } // TODO: make this API more auto-closable friendly. tsvWriter = new TSVWriter<>(header); tsvWriter.open(outputFile); if (oldResults != null) { System.out.format("Re-writing %d existing result rows\n", oldResults.size()); tsvWriter.append(oldResults); } } try { Map<SurfactantAnalysis.FEATURES, Double> analysisFeatures; LicenseManager.setLicenseFile(cl.getOptionValue(OPTION_LICENSE_FILE)); if (cl.hasOption(OPTION_INCHI)) { analysisFeatures = SurfactantAnalysis.performAnalysis(cl.getOptionValue(OPTION_INCHI), cl.hasOption(OPTION_DISPLAY)); Map<String, String> tsvFeatures = new HashMap<>(); // Convert features to strings to avoid some weird formatting issues. It's ugly, but it works. for (Map.Entry<SurfactantAnalysis.FEATURES, Double> entry : analysisFeatures.entrySet()) { tsvFeatures.put(entry.getKey().toString(), String.format("%.6f", entry.getValue())); } tsvFeatures.put("name", "direct-inchi-input"); if (tsvWriter != null) { tsvWriter.append(tsvFeatures); } } else if (cl.hasOption(OPTION_INPUT_FILE)) { TSVParser parser = new TSVParser(); parser.parse(new File(cl.getOptionValue(OPTION_INPUT_FILE))); int i = 0; List<Map<String, String>> inputRows = parser.getResults(); for (Map<String, String> row : inputRows) { i++; // Just for warning messages. if (!row.containsKey("name") || !row.containsKey("id") || !row.containsKey("inchi")) { System.err.format( "WARNING: TSV rows must contain at least name, id, and inchi, skipping row %d\n", i); continue; } if (seenOutputIds.contains(row.get("id"))) { System.out.format("Skipping input row with id already in output: %s\n", row.get("id")); continue; } System.out.format("Analysis for chemical %s\n", row.get("name")); try { analysisFeatures = SurfactantAnalysis.performAnalysis(row.get("inchi"), false); } catch (Exception e) { // Ignore exceptions for now. Sometimes the regression analysis or Chemaxon processing chokes unexpectedly. System.err.format("ERROR caught exception while processing '%s':\n", row.get("name")); System.err.format("%s\n", e.getMessage()); e.printStackTrace(System.err); System.err.println("Skipping..."); continue; } System.out.format("--- Done analysis for chemical %s\n", row.get("name")); // This is a duplicate of the OPTION_INCHI block code, but it's inside of a tight loop, so... Map<String, String> tsvFeatures = new HashMap<>(); for (Map.Entry<SurfactantAnalysis.FEATURES, Double> entry : analysisFeatures.entrySet()) { tsvFeatures.put(entry.getKey().toString(), String.format("%.6f", entry.getValue())); } tsvFeatures.put("name", row.get("name")); tsvFeatures.put("id", row.get("id")); tsvFeatures.put("inchi", row.get("inchi")); tsvFeatures.put("label", row.containsKey("label") ? row.get("label") : "?"); if (tsvWriter != null) { tsvWriter.append(tsvFeatures); // Flush every time in case we crash or get interrupted. The features must flow! tsvWriter.flush(); } } } else { throw new RuntimeException("Must specify inchi or input file"); } } finally { if (tsvWriter != null) { tsvWriter.close(); } } }
From source file:com.seavus.wordcountermaven.WordCounter.java
/** * @param args the command line arguments * @throws java.io.FileNotFoundException *//* ww w. j av a2 s .co m*/ public static void main(String[] args) throws FileNotFoundException { InputStream fileStream = WordCounter.class.getClassLoader().getResourceAsStream("test.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(fileStream)); Map<String, Integer> wordMap = new HashMap<>(); String line; boolean tokenFound = false; try { while ((line = br.readLine()) != null) { String[] tokens = line.trim().split("\\s+"); //trims surrounding whitespaces and splits lines into tokens for (String token : tokens) { for (Map.Entry<String, Integer> entry : wordMap.entrySet()) { if (StringUtils.equalsIgnoreCase(token, entry.getKey())) { wordMap.put(entry.getKey(), (wordMap.get(entry.getKey()) + 1)); tokenFound = true; } } if (!token.equals("") && !tokenFound) { wordMap.put(token.toLowerCase(), 1); } tokenFound = false; } } br.close(); } catch (IOException ex) { Logger.getLogger(WordCounter.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("string : " + "frequency\r\n" + "-------------------"); //prints out each unique word (i.e. case-insensitive string token) and its frequency to the console for (Map.Entry<String, Integer> entry : wordMap.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue()); } }
From source file:AIR.Common.DB.AbstractDLL.java
public static void main(String[] argv) { final String TEMPLATE = "select top 1 clientname from TDSCONFIGS_Client_TestScoreFeatures where clientname = ${client} and TestID = ${testID} and (ReportToStudent = 1 or ReportToProctor = 1 or ReportToParticipation = 1 or UseForAbility = 1)"; Map<String, Object> parameters = new CaseInsensitiveMap<Object>(); parameters.put("testID", "ELPA_6-8"); parameters.put("client", "Oregon"); System.err.println(StrSubstitutor.replace(TEMPLATE, parameters)); SqlParametersMaps parametersSql = new SqlParametersMaps(); parametersSql.put("client", "Oregon"); parametersSql.put("testID", "ELPA_6-8"); }
From source file:fr.inria.atlanmod.kyanos.benchmarks.ase2015.NeoEMFGraphQueryGetBranchStatements.java
public static void main(String[] args) { Options options = new Options(); Option inputOpt = OptionBuilder.create(IN); inputOpt.setArgName("INPUT"); inputOpt.setDescription("Input Kyanos resource directory"); inputOpt.setArgs(1);//from w ww . j a va 2s .c om inputOpt.setRequired(true); Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS); inClassOpt.setArgName("CLASS"); inClassOpt.setDescription("FQN of EPackage implementation class"); inClassOpt.setArgs(1); inClassOpt.setRequired(true); Option optFileOpt = OptionBuilder.create(OPTIONS_FILE); optFileOpt.setArgName("FILE"); optFileOpt.setDescription("Properties file holding the options to be used in the Kyanos Resource"); optFileOpt.setArgs(1); options.addOption(inputOpt); options.addOption(inClassOpt); options.addOption(optFileOpt); CommandLineParser parser = new PosixParser(); try { PersistenceBackendFactoryRegistry.getFactories().put(NeoBlueprintsURI.NEO_GRAPH_SCHEME, new BlueprintsPersistenceBackendFactory()); CommandLine commandLine = parser.parse(options, args); URI uri = NeoBlueprintsURI.createNeoGraphURI(new File(commandLine.getOptionValue(IN))); Class<?> inClazz = NeoEMFGraphQueryGetBranchStatements.class.getClassLoader() .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS)); inClazz.getMethod("init").invoke(null); ResourceSet resourceSet = new ResourceSetImpl(); resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap() .put(NeoBlueprintsURI.NEO_GRAPH_SCHEME, PersistentResourceFactory.eINSTANCE); Resource resource = resourceSet.createResource(uri); Map<String, Object> loadOpts = new HashMap<String, Object>(); if (commandLine.hasOption(OPTIONS_FILE)) { Properties properties = new Properties(); properties.load(new FileInputStream(new File(commandLine.getOptionValue(OPTIONS_FILE)))); for (final Entry<Object, Object> entry : properties.entrySet()) { loadOpts.put((String) entry.getKey(), (String) entry.getValue()); } } // Add the LoadedObjectCounter store List<StoreOption> storeOptions = new ArrayList<StoreOption>(); // storeOptions.add(PersistentResourceOptions.EStoreOption.LOADED_OBJECT_COUNTER_LOGGING); storeOptions.add(BlueprintsResourceOptions.EStoreGraphOption.AUTOCOMMIT); loadOpts.put(PersistentResourceOptions.STORE_OPTIONS, storeOptions); resource.load(loadOpts); { Runtime.getRuntime().gc(); long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); LOG.log(Level.INFO, MessageFormat.format("Used memory before query: {0}", MessageUtil.byteCountToDisplaySize(initialUsedMemory))); LOG.log(Level.INFO, "Start query"); long begin = System.currentTimeMillis(); Set<TextElement> list = ASE2015JavaQueries.getCommentsTagContent(resource); long end = System.currentTimeMillis(); LOG.log(Level.INFO, "End query"); LOG.log(Level.INFO, MessageFormat.format("Query result contains {0} elements", list.size())); LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin))); Runtime.getRuntime().gc(); long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); LOG.log(Level.INFO, MessageFormat.format("Used memory after query: {0}", MessageUtil.byteCountToDisplaySize(finalUsedMemory))); LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}", MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory))); } if (resource instanceof PersistentResourceImpl) { PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) resource); } else { resource.unload(); } } catch (ParseException e) { MessageUtil.showError(e.toString()); MessageUtil.showError("Current arguments: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar <this-file.jar>", options, true); } catch (Throwable e) { MessageUtil.showError(e.toString()); } }