List of usage examples for java.util Map get
V get(Object key);
From source file:act.installer.brenda.BrendaChebiOntology.java
public static void main(String[] args) throws Exception { // We provide a proof of concept in this main function. This should later be moved to either a test or removed. // Connect to the BRENDA DB SQLConnection brendaDB = new SQLConnection(); brendaDB.connect("127.0.0.1", 3306, "brenda_user", ""); // Get the ontology map (ChebiId -> ChebiOntology object) Map<String, ChebiOntology> ontologyMap = fetchOntologyMap(brendaDB); // Get "is subtype of" relationships Map<String, Set<String>> isSubTypeOfRelationships = fetchIsSubtypeOfRelationships(brendaDB); // Get "has role" relationships Map<String, Set<String>> hasRoleRelationships = fetchHasRoleRelationships(brendaDB); // Get the applications for all chemical entities Map<ChebiOntology, ChebiApplicationSet> chemicalEntityToApplicationsMap = getApplications(ontologyMap, isSubTypeOfRelationships, hasRoleRelationships); ChebiOntology applicationOntology = ontologyMap.get("CHEBI:46195"); // Convert ChebiApplicationSet to JSON string and pretty print String chebiApplicationSetString = mapper.writerWithDefaultPrettyPrinter() .writeValueAsString(chemicalEntityToApplicationsMap.get(applicationOntology)); System.out.println(chebiApplicationSetString); // Disconnect from the BRENDA DB brendaDB.disconnect();//from w ww . ja v a 2s . co m }
From source file:com.sccl.attech.generate.Generate.java
/** * The main method.//from w ww. j a v a 2s.c o m * * @param args the arguments * @throws Exception the exception */ public static void main(String[] args) throws Exception { // ========== ?? ====================1412914 // ?????? // ?{packageName}/{moduleName}/{dao,entity,service,web}/{subModuleName}/{className} // packageName ????applicationContext.xmlsrping-mvc.xml?base-package?packagesToScan?4? String packageName = "com.sccl.attech.modules"; String moduleName = "mobil"; // ???sys String subModuleName = ""; // ????? String className = "updateApp"; // ??user List<GenerateField> fields = Lists.newArrayList(); fields.add(new GenerateField("name", "??")); fields.add(new GenerateField("type", "")); fields.add(new GenerateField("version", "")); fields.add(new GenerateField("path", "")); String classAuthor = "zzz"; // zhaozz String functionName = "App?"; // ?? // ??? //Boolean isEnable = false; Boolean isEnable = true; // ========== ?? ==================== if (!isEnable) { logger.error("????isEnable = true"); return; } if (StringUtils.isBlank(moduleName) || StringUtils.isBlank(moduleName) || StringUtils.isBlank(className) || StringUtils.isBlank(functionName)) { logger.error("??????????????"); return; } // ? String separator = File.separator; // ? File projectPath = new DefaultResourceLoader().getResource("").getFile(); while (!new File(projectPath.getPath() + separator + "src" + separator + "main").exists()) { projectPath = projectPath.getParentFile(); } logger.info("Project Path: {}", projectPath); // ? String tplPath = StringUtils.replace(projectPath + "/src/main/java/com/sccl/attech/generate/template", "/", separator); logger.info("Template Path: {}", tplPath); // Java String javaPath = StringUtils.replaceEach( projectPath + "/src/main/java/" + StringUtils.lowerCase(packageName), new String[] { "/", "." }, new String[] { separator, separator }); logger.info("Java Path: {}", javaPath); // String viewPath = StringUtils.replace(projectPath + "/WebRoot/pages", "/", separator); logger.info("View Path: {}", viewPath); String resPath = StringUtils.replace(projectPath + "/WebRoot/assets/js", "/", separator); logger.info("Res Path: {}", resPath); // ??? Configuration cfg = new Configuration(); cfg.setDefaultEncoding("UTF-8"); cfg.setDirectoryForTemplateLoading(new File(tplPath)); // ??? Map<String, Object> model = Maps.newHashMap(); model.put("packageName", StringUtils.lowerCase(packageName)); model.put("moduleName", StringUtils.lowerCase(moduleName)); model.put("fields", fields); model.put("subModuleName", StringUtils.isNotBlank(subModuleName) ? "." + StringUtils.lowerCase(subModuleName) : ""); model.put("className", StringUtils.uncapitalize(className)); model.put("ClassName", StringUtils.capitalize(className)); model.put("classAuthor", StringUtils.isNotBlank(classAuthor) ? classAuthor : "Generate Tools"); model.put("classVersion", DateUtils.getDate()); model.put("functionName", functionName); model.put("tableName", model.get("moduleName") + (StringUtils.isNotBlank(subModuleName) ? "_" + StringUtils.lowerCase(subModuleName) : "") + "_" + model.get("className")); model.put("urlPrefix", model.get("moduleName") + (StringUtils.isNotBlank(subModuleName) ? "/" + StringUtils.lowerCase(subModuleName) : "") + "/" + model.get("className")); model.put("viewPrefix", //StringUtils.substringAfterLast(model.get("packageName"),".")+"/"+ model.get("urlPrefix")); model.put("permissionPrefix", model.get("moduleName") + (StringUtils.isNotBlank(subModuleName) ? ":" + StringUtils.lowerCase(subModuleName) : "") + ":" + model.get("className")); // ? Entity Template template = cfg.getTemplate("entity.ftl"); String content = FreeMarkers.renderTemplate(template, model); String filePath = javaPath + separator + model.get("moduleName") + separator + "entity" + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + ".java"; writeFile(content, filePath); logger.info("Entity: {}", filePath); // ? Dao template = cfg.getTemplate("dao.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = javaPath + separator + model.get("moduleName") + separator + "dao" + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + "Dao.java"; writeFile(content, filePath); logger.info("Dao: {}", filePath); // ? Service template = cfg.getTemplate("service.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = javaPath + separator + model.get("moduleName") + separator + "service" + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + "Service.java"; writeFile(content, filePath); logger.info("Service: {}", filePath); // ? Controller createJavaFile(subModuleName, separator, javaPath, cfg, model); // ? ViewForm template = cfg.getTemplate("viewForm.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = viewPath//+separator+StringUtils.substringAfterLast(model.get("packageName"),".") + separator + model.get("moduleName") + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("className") + "Form.html"; writeFile(content, filePath); logger.info("ViewForm: {}", filePath); // ? ViewFormJs template = cfg.getTemplate("viewFormJs.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = resPath//+separator+StringUtils.substringAfterLast(model.get("packageName"),".") + separator + model.get("moduleName") + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("className") + "FormCtrl.js"; writeFile(content, filePath); logger.info("ViewFormJs: {}", filePath); // ? ViewList template = cfg.getTemplate("viewList.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = viewPath//+separator+StringUtils.substringAfterLast(model.get("packageName"),".") + separator + model.get("moduleName") + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("className") + "List.html"; writeFile(content, filePath); logger.info("ViewList: {}", filePath); // ? ViewListJs template = cfg.getTemplate("viewListJs.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = resPath//+separator+StringUtils.substringAfterLast(model.get("packageName"),".") + separator + model.get("moduleName") + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("className") + "ListCtrl.js"; writeFile(content, filePath); logger.info("ViewList: {}", filePath); // ? ??sql template = cfg.getTemplate("sql.ftl"); model.put("uid", IdGen.uuid()); model.put("uid1", IdGen.uuid()); content = FreeMarkers.renderTemplate(template, model); filePath = viewPath//+separator+StringUtils.substringAfterLast(model.get("packageName"),".") + separator + model.get("moduleName") + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("className") + ".sql"; writeFile(content, filePath); logger.info("ViewList: {}", filePath); logger.info("Generate Success."); }
From source file:org.ala.dao.CassandraPelopsHelper.java
public static void main(String[] args) throws Exception { CassandraPelopsHelper helper = new CassandraPelopsHelper(); helper.init();//from w w w. ja va2s.com Map<String, Object> map = helper.getSubColumnsByGuid("tc", "103067807"); Set<String> keys = map.keySet(); Iterator<String> it = keys.iterator(); while (it.hasNext()) { String key = it.next(); ColumnType type = ColumnType.getColumnType(key); Object o = map.get(type.getColumnName()); if (o instanceof List) { List l = (List) o; } else { Comparable c = (Comparable) o; } } /* TaxonConcept t = null; List<Comparable> l = new ArrayList<Comparable>(); for(int i=0; i< 10; i++){ t = new TaxonConcept(); t.setId(i); t.setGuid("urn:lsid:"+i); t.setNameString("Aus bus"); t.setAuthor("Smith"); t.setAuthorYear("2008"); t.setInfoSourceName("AFD"); t.setInfoSourceURL("http://afd.org.au"); helper.putSingle("taxonConcept", "tc", "taxonConcept", t.getGuid(), t); l.add(t); if(i % 1000==0){ System.out.println("id: "+i); } } helper.putList("taxonConcept", "tc", "taxonConcept", "128", l, true); CommonName c1 = new CommonName(); c1.setNameString("Dave"); CommonName c2 = new CommonName(); c2.setNameString("Frank"); helper.putSingle("taxonConcept", "tc", "taxonConcept", "123", t); helper.put("taxonConcept", "tc", "commonName", "123", c1); helper.put("taxonConcept", "tc", "commonName", "123", c2); helper.putSingle("taxonConcept", "tc", "taxonConcept", "124", t); TaxonConcept tc = (TaxonConcept) helper.get("taxonConcept", "tc", "taxonConcept", "123", TaxonConcept.class); System.out.println("Retrieved: "+tc.getNameString()); List<CommonName> cns = (List) helper.getList("taxonConcept", "tc", "commonName", "123", CommonName.class); System.out.println("Retrieved: "+cns); */ //cassandra scanning Scanner scanner = helper.getScanner("taxonConcept", "tc", "taxonConcept"); for (int i = 0; i < 10; i++) { System.out.println(new String(scanner.getNextGuid())); } System.exit(0); }
From source file:com.di.bi.nextgen.installattribution.searchcountrycode.SearchCountryCode.java
public static void main(String[] args) throws Exception { Map<String, String> map = CSVReader(); List<String> miss = new ArrayList<>(); List<String[]> data = new ArrayList<>(); String csv = "infinity.csv"; CSVWriter writer = new CSVWriter(new FileWriter(csv)); List<String[]> outList = new ArrayList<>(); JSONArray arry = ReadJson();/*from w w w. ja va 2 s.co m*/ for (String key : map.keySet()) { String[] arr = key.split(";"); boolean isf = false; for (int i = 0; i < arry.length(); ++i) { JSONObject o = arry.getJSONObject(i); if (arr.length > 1) { if (o.keySet().contains(arr[1].toUpperCase())) { System.out.println("arr[]1" + arr[1]); System.out.println("o.keySet() " + o.keySet()); System.out.println(" bu " + o.keySet().contains(arr[1].toUpperCase())); JSONArray arryC = o.getJSONArray(arr[1].toUpperCase()); for (int j = 0; j < arryC.length(); ++j) { String[] tmp = { map.get(key) + "," + key + ";" + arryC.getString(j) }; outList.add(tmp); } isf = true; break; } } } if (!isf) { miss.add(key); isf = false; } } writer.writeAll(outList); writer.close(); System.out.println("Miissing" + miss); }
From source file:com.act.lcms.db.analysis.PathwayProductAnalysis.java
public static void main(String[] args) throws Exception { Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());// w ww . j a v a 2 s .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; } File lcmsDir = new File(cl.getOptionValue(OPTION_DIRECTORY)); if (!lcmsDir.isDirectory()) { System.err.format("File at %s is not a directory\n", lcmsDir.getAbsolutePath()); HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } Double fontScale = null; if (cl.hasOption("font-scale")) { try { fontScale = Double.parseDouble(cl.getOptionValue("font-scale")); } catch (IllegalArgumentException e) { System.err.format("Argument for font-scale must be a floating point number.\n"); System.exit(1); } } try (DB db = DB.openDBFromCLI(cl)) { Set<Integer> takeSamplesFromPlateIds = null; if (cl.hasOption(OPTION_FILTER_BY_PLATE_BARCODE)) { String[] plateBarcodes = cl.getOptionValues(OPTION_FILTER_BY_PLATE_BARCODE); System.out.format("Considering only sample wells in plates: %s\n", StringUtils.join(plateBarcodes, ", ")); takeSamplesFromPlateIds = new HashSet<>(plateBarcodes.length); for (String plateBarcode : plateBarcodes) { Plate p = Plate.getPlateByBarcode(db, plateBarcode); if (p == null) { System.err.format("WARNING: unable to find plate in DB with barcode %s\n", plateBarcode); } else { takeSamplesFromPlateIds.add(p.getId()); } } // Allow filtering on barcode even if we couldn't find any in the DB. } System.out.format("Loading/updating LCMS scan files into DB\n"); ScanFile.insertOrUpdateScanFilesInDirectory(db, lcmsDir); System.out.format("Processing LCMS scans\n"); Pair<List<LCMSWell>, Set<Integer>> positiveWellsAndPlateIds = Utils.extractWellsAndPlateIds(db, cl.getOptionValues(OPTION_STRAINS), cl.getOptionValues(OPTION_CONSTRUCT), takeSamplesFromPlateIds, false); List<LCMSWell> positiveWells = positiveWellsAndPlateIds.getLeft(); if (positiveWells.size() == 0) { throw new RuntimeException("Found no LCMS wells for specified strains/constructs"); } // Only take negative samples from the plates where we found the positive samples. Pair<List<LCMSWell>, Set<Integer>> negativeWellsAndPlateIds = Utils.extractWellsAndPlateIds(db, cl.getOptionValues(OPTION_NEGATIVE_STRAINS), cl.getOptionValues(OPTION_NEGATIVE_CONSTRUCTS), positiveWellsAndPlateIds.getRight(), true); List<LCMSWell> negativeWells = negativeWellsAndPlateIds.getLeft(); if (negativeWells == null || negativeWells.size() == 0) { System.err.format("WARNING: no valid negative samples found in same plates as positive samples\n"); } // Extract the chemicals in the pathway and their product masses, then look up info on those chemicals List<Pair<ChemicalAssociatedWithPathway, Double>> productMasses = Utils .extractMassesForChemicalsAssociatedWithConstruct(db, cl.getOptionValue(OPTION_CONSTRUCT)); List<Pair<String, Double>> searchMZs = new ArrayList<>(productMasses.size()); List<ChemicalAssociatedWithPathway> pathwayChems = new ArrayList<>(productMasses.size()); for (Pair<ChemicalAssociatedWithPathway, Double> productMass : productMasses) { String chemName = productMass.getLeft().getChemical(); searchMZs.add(Pair.of(chemName, productMass.getRight())); pathwayChems.add(productMass.getLeft()); } System.out.format("Searching for intermediate/side-reaction products:\n"); for (Pair<String, Double> searchMZ : searchMZs) { System.out.format(" %s: %.3f\n", searchMZ.getLeft(), searchMZ.getRight()); } // Look up the standard by name. List<StandardWell> standardWells = new ArrayList<>(); if (cl.hasOption(OPTION_STANDARD_WELLS)) { Plate standardPlate = Plate.getPlateByBarcode(db, cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE)); Map<Integer, StandardWell> pathwayIdToStandardWell = extractStandardWellsFromOptionsList(db, pathwayChems, cl.getOptionValues(OPTION_STANDARD_WELLS), standardPlate); for (ChemicalAssociatedWithPathway c : pathwayChems) { // TODO: we can avoid this loop. StandardWell well = pathwayIdToStandardWell.get(c.getId()); if (well != null) { standardWells.add(well); } } } else { for (ChemicalAssociatedWithPathway c : pathwayChems) { String standardName = c.getChemical(); System.out.format("Searching for well containing standard %s\n", standardName); List<StandardWell> wells = StandardIonAnalysis.getStandardWellsForChemical(db, c.getChemical()); if (wells != null) { standardWells.addAll(wells); } } } boolean useFineGrainedMZ = cl.hasOption("fine-grained-mz"); boolean useSNR = cl.hasOption(OPTION_USE_SNR); /* Process the standard, positive, and negative wells, producing ScanData containers that will allow them to be * iterated over for graph writing. We do not need to specify granular includeIons and excludeIons since * this would not take advantage of our caching strategy which uses a list of metlin ions as an index. */ HashMap<Integer, Plate> plateCache = new HashMap<>(); Pair<List<ScanData<StandardWell>>, Double> allStandardScans = AnalysisHelper.processScans(db, lcmsDir, searchMZs, ScanData.KIND.STANDARD, plateCache, standardWells, useFineGrainedMZ, EMPTY_SET, EMPTY_SET, useSNR); Pair<List<ScanData<LCMSWell>>, Double> allPositiveScans = AnalysisHelper.processScans(db, lcmsDir, searchMZs, ScanData.KIND.POS_SAMPLE, plateCache, positiveWells, useFineGrainedMZ, EMPTY_SET, EMPTY_SET, useSNR); Pair<List<ScanData<LCMSWell>>, Double> allNegativeScans = AnalysisHelper.processScans(db, lcmsDir, searchMZs, ScanData.KIND.NEG_CONTROL, plateCache, negativeWells, useFineGrainedMZ, EMPTY_SET, EMPTY_SET, useSNR); String fmt = "pdf"; String outImg = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + "." + fmt; String outData = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + ".data"; String outAnalysis = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + ".tsv"; System.err.format("Writing combined scan data to %s and graphs to %s\n", outData, outImg); String plottingDirectory = cl.getOptionValue(OPTION_PLOTTING_DIR); List<ScanData<LCMSWell>> posNegWells = new ArrayList<>(); posNegWells.addAll(allPositiveScans.getLeft()); posNegWells.addAll(allNegativeScans.getLeft()); Map<Integer, String> searchIons; if (cl.hasOption(OPTION_PATHWAY_SEARCH_IONS)) { searchIons = extractPathwayStepIons(pathwayChems, cl.getOptionValues(OPTION_PATHWAY_SEARCH_IONS), cl.getOptionValue(OPTION_SEARCH_ION, "M+H")); /* This is pretty lazy, but works with the existing API. Extract all selected ions for all search masses when * performing the scan, then filter down to the desired ions for the plot at the end. * TODO: specify the masses and scans per sample rather than batching everything together. It might be slower, * but it'll be clearer to read. */ } else { // We need to make sure that the standard metlin ion we choose is consistent with the ion modes of // the given positive, negative and standard scan files. For example, we should not pick a negative // metlin ion if all our available positive control scan files are in the positive ion mode. Map<Integer, Pair<Boolean, Boolean>> ionModes = new HashMap<>(); for (ChemicalAssociatedWithPathway chemical : pathwayChems) { boolean isPositiveScanPresent = false; boolean isNegativeScanPresent = false; for (ScanData<StandardWell> scan : allStandardScans.getLeft()) { if (chemical.getChemical().equals(scan.getWell().getChemical()) && chemical.getChemical().equals(scan.getTargetChemicalName())) { if (MS1.IonMode.valueOf( scan.getScanFile().getMode().toString().toUpperCase()) == MS1.IonMode.POS) { isPositiveScanPresent = true; } if (MS1.IonMode.valueOf( scan.getScanFile().getMode().toString().toUpperCase()) == MS1.IonMode.NEG) { isNegativeScanPresent = true; } } } for (ScanData<LCMSWell> scan : posNegWells) { if (chemical.getChemical().equals(scan.getWell().getChemical()) && chemical.getChemical().equals(scan.getTargetChemicalName())) { if (MS1.IonMode.valueOf( scan.getScanFile().getMode().toString().toUpperCase()) == MS1.IonMode.POS) { isPositiveScanPresent = true; } if (MS1.IonMode.valueOf( scan.getScanFile().getMode().toString().toUpperCase()) == MS1.IonMode.NEG) { isNegativeScanPresent = true; } } } ionModes.put(chemical.getId(), Pair.of(isPositiveScanPresent, isNegativeScanPresent)); } // Sort in descending order of media where MeOH and Water related media are promoted to the top and // anything derived from yeast media are demoted. We do this because we want to first process the water // and meoh media before processing the yeast media since the yeast media depends on the analysis of the former. Collections.sort(standardWells, new Comparator<StandardWell>() { @Override public int compare(StandardWell o1, StandardWell o2) { if (StandardWell.doesMediaContainYeastExtract(o1.getMedia()) && !StandardWell.doesMediaContainYeastExtract(o2.getMedia())) { return 1; } else { return 0; } } }); searchIons = extractPathwayStepIonsFromStandardIonAnalysis(pathwayChems, lcmsDir, db, standardWells, plottingDirectory, ionModes); } produceLCMSPathwayHeatmaps(lcmsDir, outData, outImg, outAnalysis, pathwayChems, allStandardScans, allPositiveScans, allNegativeScans, fontScale, cl.hasOption(OPTION_USE_HEATMAP), searchIons); } }
From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step7aLearningDataProducer.java
@SuppressWarnings("unchecked") public static void main(String[] args) throws IOException { String inputDir = args[0];//from w w w . ja v a2 s .com File outputDir = new File(args[1]); if (!outputDir.exists()) { outputDir.mkdirs(); } Collection<File> files = IOHelper.listXmlFiles(new File(inputDir)); // for generating ConvArgStrict use this String prefix = "no-eq_DescendingScoreArgumentPairListSorter"; // for oversampling using graph transitivity properties use this // String prefix = "generated_no-eq_AscendingScoreArgumentPairListSorter"; Iterator<File> iterator = files.iterator(); while (iterator.hasNext()) { File file = iterator.next(); if (!file.getName().startsWith(prefix)) { iterator.remove(); } } int totalGoldPairsCounter = 0; Map<String, Integer> goldDataDistribution = new HashMap<>(); DescriptiveStatistics statsPerTopic = new DescriptiveStatistics(); int totalPairsWithReasonSameAsGold = 0; DescriptiveStatistics ds = new DescriptiveStatistics(); for (File file : files) { List<AnnotatedArgumentPair> argumentPairs = (List<AnnotatedArgumentPair>) XStreamTools.getXStream() .fromXML(file); int pairsPerTopicCounter = 0; String name = file.getName().replaceAll(prefix, "").replaceAll("\\.xml", ""); PrintWriter pw = new PrintWriter(new File(outputDir, name + ".csv"), "utf-8"); pw.println("#id\tlabel\ta1\ta2"); for (AnnotatedArgumentPair argumentPair : argumentPairs) { String goldLabel = argumentPair.getGoldLabel(); if (!goldDataDistribution.containsKey(goldLabel)) { goldDataDistribution.put(goldLabel, 0); } goldDataDistribution.put(goldLabel, goldDataDistribution.get(goldLabel) + 1); pw.printf(Locale.ENGLISH, "%s\t%s\t%s\t%s%n", argumentPair.getId(), goldLabel, multipleParagraphsToSingleLine(argumentPair.getArg1().getText()), multipleParagraphsToSingleLine(argumentPair.getArg2().getText())); pairsPerTopicCounter++; int sameInOnePair = 0; // get gold reason statistics for (AnnotatedArgumentPair.MTurkAssignment assignment : argumentPair.mTurkAssignments) { String label = assignment.getValue(); if (goldLabel.equals(label)) { sameInOnePair++; } } ds.addValue(sameInOnePair); totalPairsWithReasonSameAsGold += sameInOnePair; } totalGoldPairsCounter += pairsPerTopicCounter; statsPerTopic.addValue(pairsPerTopicCounter); pw.close(); } System.out.println("Total reasons matching gold " + totalPairsWithReasonSameAsGold); System.out.println(ds); System.out.println("Total gold pairs: " + totalGoldPairsCounter); System.out.println(statsPerTopic); int totalPairs = 0; for (Integer pairs : goldDataDistribution.values()) { totalPairs += pairs; } System.out.println("Total pairs: " + totalPairs); System.out.println(goldDataDistribution); }
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 va 2 s .c o m*/ 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:com.gzj.tulip.jade.statement.SystemInterpreter.java
public static void main(String[] args) throws Exception { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("table", "my_table_name"); parameters.put("id", "my_id"); parameters.put(":1", "first_param"); final Pattern PATTERN = Pattern.compile("\\{([a-zA-Z0-9_\\.\\:]+)\\}|##\\((.+)\\)"); String sql = "select form ##(:table) {name} where {id}='{1}'"; StringBuilder sb = new StringBuilder(sql.length() + 200); Matcher matcher = PATTERN.matcher(sql); int start = 0; while (matcher.find(start)) { sb.append(sql.substring(start, matcher.start())); String group = matcher.group(); String key = null;//from ww w . j a v a 2 s .c o m if (group.startsWith("{")) { key = matcher.group(1); } else if (group.startsWith("##(")) { key = matcher.group(2); } System.out.println(key); if (key == null || key.length() == 0) { continue; } Object value = parameters.get(key); // {paramName}?{:1}? if (value == null) { if (key.startsWith(":") || key.startsWith("$")) { value = parameters.get(key.substring(1)); // {:paramName} } else { char ch = key.charAt(0); if (ch >= '0' && ch <= '9') { value = parameters.get(":" + key); // {1}? } } } if (value == null) { value = parameters.get(key); // ? } if (value != null) { sb.append(value); } else { sb.append(group); } start = matcher.end(); } sb.append(sql.substring(start)); System.out.println(sb); }
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;/* w ww .j a v a 2s . 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:ClassFileUtilities.java
/** * Program that computes the dependencies between the Batik jars. * <p>/*from w ww . j ava 2 s . c o m*/ * Run this from the main Batik distribution directory, after building * the jars. For every jar file in the batik-xxx/ build directory, * it will determine which other jar files it directly depends on. * The output is lines of the form: * </p> * <pre> <i>number</i>,<i>from</i>,<i>to</i></pre> * <p> * where mean that the <i>from</i> jar has <i>number</i> class files * that depend on class files in the <i>to</i> jar. * </p> */ public static void main(String[] args) { boolean showFiles = false; if (args.length == 1 && args[0].equals("-f")) { showFiles = true; } else if (args.length != 0) { System.err.println("usage: ClassFileUtilities [-f]"); System.err.println(); System.err.println(" -f list files that cause each jar file dependency"); System.exit(1); } File cwd = new File("."); File buildDir = null; String[] cwdFiles = cwd.list(); for (int i = 0; i < cwdFiles.length; i++) { if (cwdFiles[i].startsWith("batik-")) { buildDir = new File(cwdFiles[i]); if (!buildDir.isDirectory()) { buildDir = null; } else { break; } } } if (buildDir == null || !buildDir.isDirectory()) { System.out.println("Directory 'batik-xxx' not found in current directory!"); return; } try { Map cs = new HashMap(); Map js = new HashMap(); collectJars(buildDir, js, cs); Set classpath = new HashSet(); Iterator i = js.values().iterator(); while (i.hasNext()) { classpath.add(((Jar) i.next()).jarFile); } i = cs.values().iterator(); while (i.hasNext()) { ClassFile fromFile = (ClassFile) i.next(); // System.out.println(fromFile.name); Set result = getClassDependencies(fromFile.getInputStream(), classpath, false); Iterator j = result.iterator(); while (j.hasNext()) { ClassFile toFile = (ClassFile) cs.get(j.next()); if (fromFile != toFile && toFile != null) { fromFile.deps.add(toFile); } } } i = cs.values().iterator(); while (i.hasNext()) { ClassFile fromFile = (ClassFile) i.next(); Iterator j = fromFile.deps.iterator(); while (j.hasNext()) { ClassFile toFile = (ClassFile) j.next(); Jar fromJar = fromFile.jar; Jar toJar = toFile.jar; if (fromFile.name.equals(toFile.name) || toJar == fromJar || fromJar.files.contains(toFile.name)) { continue; } Integer n = (Integer) fromJar.deps.get(toJar); if (n == null) { fromJar.deps.put(toJar, new Integer(1)); } else { fromJar.deps.put(toJar, new Integer(n.intValue() + 1)); } } } List triples = new ArrayList(10); i = js.values().iterator(); while (i.hasNext()) { Jar fromJar = (Jar) i.next(); Iterator j = fromJar.deps.keySet().iterator(); while (j.hasNext()) { Jar toJar = (Jar) j.next(); Triple t = new Triple(); t.from = fromJar; t.to = toJar; t.count = ((Integer) fromJar.deps.get(toJar)).intValue(); triples.add(t); } } Collections.sort(triples); i = triples.iterator(); while (i.hasNext()) { Triple t = (Triple) i.next(); System.out.println(t.count + "," + t.from.name + "," + t.to.name); if (showFiles) { Iterator j = t.from.files.iterator(); while (j.hasNext()) { ClassFile fromFile = (ClassFile) j.next(); Iterator k = fromFile.deps.iterator(); while (k.hasNext()) { ClassFile toFile = (ClassFile) k.next(); if (toFile.jar == t.to && !t.from.files.contains(toFile.name)) { System.out.println("\t" + fromFile.name + " --> " + toFile.name); } } } } } } catch (IOException e) { e.printStackTrace(); } }