List of usage examples for java.lang String format
public static String format(Locale l, String format, Object... args)
From source file:com.twitter.bazel.checkstyle.PythonCheckstyle.java
public static void main(String[] args) throws IOException { CommandLineParser parser = new DefaultParser(); // create the Options Options options = new Options(); options.addOption(Option.builder("f").required(true).hasArg().longOpt("extra_action_file") .desc("bazel extra action protobuf file").build()); options.addOption(Option.builder("p").required(true).hasArg().longOpt("pylint_file") .desc("Executable pylint file to invoke").build()); try {/*from w ww .j a v a 2 s . c o m*/ // parse the command line arguments CommandLine line = parser.parse(options, args); String extraActionFile = line.getOptionValue("f"); String pylintFile = line.getOptionValue("p"); Collection<String> sourceFiles = getSourceFiles(extraActionFile); if (sourceFiles.size() == 0) { LOG.info("No python files found by checkstyle"); return; } LOG.info(sourceFiles.size() + " python files found by checkstyle"); // Create and run the command List<String> commandBuilder = new ArrayList<>(); commandBuilder.add(pylintFile); commandBuilder.addAll(sourceFiles); runLinter(commandBuilder); } catch (ParseException exp) { LOG.severe(String.format("Invalid input to %s: %s", CLASSNAME, exp.getMessage())); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java " + CLASSNAME, options); } }
From source file:com.cloudera.impala.testutil.SentryServicePinger.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { // Parse command line options to get config file path. Options options = new Options(); options.addOption(OptionBuilder.withLongOpt("config_file") .withDescription("Absolute path to a sentry-site.xml config file (string)").hasArg() .withArgName("CONFIG_FILE").isRequired().create('c')); options.addOption(OptionBuilder.withLongOpt("num_pings") .withDescription("Max number of pings to try before failing (int)").hasArg().isRequired() .withArgName("NUM_PINGS").create('n')); options.addOption(//from w w w. jav a 2s . c o m OptionBuilder.withLongOpt("sleep_secs").withDescription("Time (s) to sleep between pings (int)") .hasArg().withArgName("SLEEP_SECS").create('s')); BasicParser optionParser = new BasicParser(); CommandLine cmdArgs = optionParser.parse(options, args); SentryConfig sentryConfig = new SentryConfig(cmdArgs.getOptionValue("config_file")); int numPings = Integer.parseInt(cmdArgs.getOptionValue("num_pings")); int maxPings = numPings; int sleepSecs = Integer.parseInt(cmdArgs.getOptionValue("sleep_secs")); sentryConfig.loadConfig(); while (numPings > 0) { SentryPolicyService policyService = new SentryPolicyService(sentryConfig); try { policyService.listAllRoles(new User(System.getProperty("user.name"))); LOG.info("Sentry Service ping succeeded."); System.exit(0); } catch (Exception e) { LOG.error(String.format("Error issing RPC to Sentry Service (attempt %d/%d): ", maxPings - numPings + 1, maxPings), e); Thread.sleep(sleepSecs * 1000); } --numPings; } System.exit(1); }
From source file:test.TestJavaService.java
/** * Main. The cmdline arguments either do or don't contain the flag -remote: that's the only supported flag. If it is specified, * we test code on the AWS instance. If it is not, we test code running locally. * The first non-flag argument is the "verb", which (currently) should be one of the verbs set at the top of source file * org.qcert.javasrc.Main. Remaining non-flag arguments are file names. There must be at least one. The number of such * arguments and what they should contain depends on the verb. * @throws Exception//from w w w. ja va 2 s.c o m */ public static void main(String[] args) throws Exception { /* Parse command line */ List<String> files = new ArrayList<>(); String loc = "localhost", verb = null; for (String arg : args) { if (arg.equals("-remote")) loc = REMOTE_LOC; else if (arg.startsWith("-")) illegal(); else if (verb == null) verb = arg; else files.add(arg); } /* Simple consistency checks and verb-specific parsing */ if (files.size() == 0) illegal(); String file = files.remove(0); String schema = null; switch (verb) { case "parseSQL": case "serialRule2CAMP": case "sqlSchema2JSON": if (files.size() != 0) illegal(); break; case "techRule2CAMP": if (files.size() != 1) illegal(); schema = files.get(0); break; case "csv2JSON": if (files.size() < 1) illegal(); break; default: illegal(); } /* Assemble information from arguments */ String url = String.format("http://%s:9879?verb=%s", loc, verb); byte[] contents = Files.readAllBytes(Paths.get(file)); String toSend; if ("serialRule2CAMP".equals(verb)) toSend = Base64.getEncoder().encodeToString(contents); else toSend = new String(contents); if ("techRule2CAMP".equals(verb)) toSend = makeSpecialJson(toSend, schema); else if ("csv2JSON".equals(verb)) toSend = makeSpecialJson(toSend, files); HttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(url); StringEntity entity = new StringEntity(toSend); entity.setContentType("text/plain"); post.setEntity(entity); HttpResponse resp = client.execute(post); int code = resp.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { HttpEntity answer = resp.getEntity(); InputStream s = answer.getContent(); BufferedReader rdr = new BufferedReader(new InputStreamReader(s)); String line = rdr.readLine(); while (line != null) { System.out.println(line); line = rdr.readLine(); } rdr.close(); s.close(); } else System.out.println(resp.getStatusLine()); }
From source file:edu.cmu.lti.oaqa.annographix.apps.SolrIndexApp.java
public static void main(String[] args) { Options options = new Options(); options.addOption("t", null, true, "Text File"); options.addOption("a", null, true, "Annotation File"); options.addOption("u", null, true, "Solr URI"); options.addOption("n", null, true, "Batch size"); options.addOption(//from ww w.j av a 2s .c om OptionBuilder.withLongOpt(TEXT_FIELD_ARG).withDescription("Text field name").hasArg().create()); options.addOption(OptionBuilder.withLongOpt(ANNOT_FIELD_ARG).withDescription("Annotation field name") .hasArg().create()); CommandLineParser parser = new org.apache.commons.cli.GnuParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("t")) { docTextFile = cmd.getOptionValue("t"); } else { Usage("Specify Text File"); } if (cmd.hasOption("a")) { docAnnotFile = cmd.getOptionValue("a"); } else { Usage("Specify Annotation File"); } if (cmd.hasOption("u")) { solrURI = cmd.getOptionValue("u"); } else { Usage("Specify Solr URI"); } if (cmd.hasOption("n")) { batchQty = Integer.parseInt(cmd.getOptionValue("n")); } String textFieldName = UtilConst.DEFAULT_TEXT4ANNOT_FIELD; String annotFieldName = UtilConst.DEFAULT_ANNOT_FIELD; if (cmd.hasOption(TEXT_FIELD_ARG)) { textFieldName = cmd.getOptionValue(TEXT_FIELD_ARG); } if (cmd.hasOption(ANNOT_FIELD_ARG)) { annotFieldName = cmd.getOptionValue(ANNOT_FIELD_ARG); } System.out.println(String.format("Annotated text field: '%s', annotation field: '%s'", textFieldName, annotFieldName)); // Ignoring return value here SolrUtils.parseAndCheckConfig(solrURI, textFieldName, annotFieldName); System.out.println("Config is fine!"); DocumentReader.readDoc(docTextFile, textFieldName, docAnnotFile, batchQty, new SolrDocumentIndexer(solrURI, textFieldName, annotFieldName)); } catch (ParseException e) { Usage("Cannot parse arguments"); } catch (Exception e) { System.err.println("Terminating due to an exception: " + e); System.exit(1); } }
From source file:com.twitter.bazel.checkstyle.CppCheckstyle.java
public static void main(String[] args) throws IOException { CommandLineParser parser = new DefaultParser(); // create the Options Options options = new Options(); options.addOption(Option.builder("f").required(true).hasArg().longOpt("extra_action_file") .desc("bazel extra action protobuf file").build()); options.addOption(Option.builder("c").required(true).hasArg().longOpt("cpplint_file") .desc("Executable cpplint file to invoke").build()); try {//from w ww .ja v a 2 s .c o m // parse the command line arguments CommandLine line = parser.parse(options, args); String extraActionFile = line.getOptionValue("f"); String cpplintFile = line.getOptionValue("c"); Collection<String> sourceFiles = getSourceFiles(extraActionFile); if (sourceFiles.size() == 0) { LOG.fine("No cpp files found by checkstyle"); return; } LOG.fine(sourceFiles.size() + " cpp files found by checkstyle"); // Create and run the command List<String> commandBuilder = new ArrayList<>(); commandBuilder.add(cpplintFile); commandBuilder.add("--linelength=100"); // TODO: https://github.com/twitter/heron/issues/466, // Remove "runtime/references" when we fix all non-const references in our codebase. // TODO: https://github.com/twitter/heron/issues/467, // Remove "runtime/threadsafe_fn" when we fix all non-threadsafe libc functions commandBuilder.add("--filter=-build/header_guard,-runtime/references,-runtime/threadsafe_fn"); commandBuilder.addAll(sourceFiles); runLinter(commandBuilder); } catch (ParseException exp) { LOG.severe(String.format("Invalid input to %s: %s", CLASSNAME, exp.getMessage())); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java " + CLASSNAME, options); } }
From source file:de.tudarmstadt.lt.lm.app.GenerateNgrams.java
@SuppressWarnings("static-access") public static void main(String[] args) { Options opts = new Options(); opts.addOption(OptionBuilder.withLongOpt("help").withDescription("Display help message.").create("?")); opts.addOption(OptionBuilder.withLongOpt("ptype").withArgName("class").hasArg().withDescription( "specify the instance of the language model provider that you want to use: {LtSegProvider, BreakIteratorStringProvider, UimaStringProvider, PreTokenizedStringProvider} (default: LtSegProvider)") .create("p")); opts.addOption(OptionBuilder.withLongOpt("cardinality").withArgName("ngram-order").hasArg().withDescription( "Specify the cardinality of the ngrams (min. 1). Specify a range using 'from-to'. (Examples: 5 = extract 5grams; 1-5 = extract 1grams, 2grams, ..., 5grams; default: 1-5).") .create("n")); opts.addOption(OptionBuilder.withLongOpt("dir").withArgName("directory").isRequired().hasArg() .withDescription(/*www . j av a 2 s. co m*/ "specify the directory that contains '.txt' files that are used as source for generating ngrams.") .create("d")); opts.addOption(OptionBuilder.withLongOpt("overwrite").withDescription("Overwrite existing ngram file.") .create("w")); CommandLine cli = null; try { cli = new GnuParser().parse(opts, args); } catch (Exception e) { print_usage(opts, e.getMessage()); } if (cli.hasOption("?")) print_usage(opts, null); AbstractStringProvider prvdr = null; try { prvdr = StartLM .getStringProviderInstance(cli.getOptionValue("ptype", LtSegProvider.class.getSimpleName())); } catch (Exception e) { print_usage(opts, String.format("Could not instantiate LmProvider '%s': %s", cli.getOptionValue("ptype", LtSegProvider.class.getSimpleName()), e.getMessage())); } String n_ = cli.getOptionValue("cardinality", "1-5"); int dash_index = n_.indexOf('-'); int n_e = Integer.parseInt(n_.substring(dash_index + 1, n_.length()).trim()); int n_b = n_e; if (dash_index == 0) n_b = 1; if (dash_index > 0) n_b = Math.max(1, Integer.parseInt(n_.substring(0, dash_index).trim())); final File src_dir = new File(cli.getOptionValue("dir")); boolean overwrite = Boolean.parseBoolean(cli.getOptionValue("overwrite", "false")); generateNgrams(src_dir, prvdr, n_b, n_e, overwrite); }
From source file:com.joyent.manta.benchmark.Benchmark.java
/** * Entrance to benchmark utility./*from w w w . j a va 2 s . c o m*/ * @param argv param1: method, param2: size of object in kb, param3: no of iterations, param4: threads * @throws Exception when something goes wrong */ public static void main(final String[] argv) throws Exception { config = new ChainedConfigContext(new DefaultsConfigContext(), new SystemSettingsConfigContext()); client = new MantaClient(config); testDirectory = String.format("%s/stor/java-manta-integration-tests/benchmark-%s", config.getMantaHomeDirectory(), testRunId); if (argv.length == 0) { System.err.println("Benchmark requires the following parameters:\n" + "method, size of object in kb, number of iterations, concurrency"); } String method = argv[0]; try { if (argv.length > 1) { sizeInBytesOrNoOfDirs = Integer.parseInt(argv[1]); } else { sizeInBytesOrNoOfDirs = DEFAULT_OBJ_SIZE_KB; } final int iterations; if (argv.length > 2) { iterations = Integer.parseInt(argv[2]); } else { iterations = DEFAULT_ITERATIONS; } final int concurrency; if (argv.length > 3) { concurrency = Integer.parseInt(argv[3]); } else { concurrency = DEFAULT_CONCURRENCY; } final long actualIterations = perThreadCount(iterations, concurrency) * concurrency; System.out.printf( "Testing latencies on a %d kb object for %d " + "iterations with a concurrency value of %d\n", sizeInBytesOrNoOfDirs, actualIterations, concurrency); setupTestDirectory(); String path = addTestFile(FileUtils.ONE_KB * sizeInBytesOrNoOfDirs); if (concurrency == 1) { singleThreadedBenchmark(method, path, iterations); } else { multithreadedBenchmark(method, path, iterations, concurrency); } } catch (IOException e) { LOG.error("Error running benchmark", e); } finally { cleanUp(); client.closeWithWarning(); } }
From source file:es.uam.eps.ir.ranksys.examples.RerankerExample.java
public static void main(String[] args) throws Exception { String trainDataPath = args[0]; String featurePath = args[1]; String recIn = args[2];/*from w w w . j a va2s. c om*/ int cutoff = 100; PreferenceData<Long, Long> trainData = SimplePreferenceData .load(SimpleRatingPreferencesReader.get().read(trainDataPath, lp, lp)); FeatureData<Long, String, Double> featureData = SimpleFeatureData .load(SimpleFeaturesReader.get().read(featurePath, lp, sp)); Map<String, Supplier<Reranker<Long, Long>>> rerankersMap = new HashMap<>(); rerankersMap.put("MMR", () -> { double lambda = 0.5; ItemDistanceModel<Long> dist = new JaccardFeatureItemDistanceModel<>(featureData); return new MMR<>(lambda, cutoff, dist); }); rerankersMap.put("xQuAD", () -> { double lambda = 0.5; IntentModel<Long, Long, String> intentModel = new FeatureIntentModel<>(trainData, featureData); AspectModel<Long, Long, String> aspectModel = new ScoresAspectModel<>(intentModel); return new XQuAD<>(aspectModel, lambda, cutoff, true); }); rerankersMap.put("RxQuAD", () -> { double alpha = 0.5; double lambda = 0.5; IntentModel<Long, Long, String> intentModel = new FeatureIntentModel<>(trainData, featureData); AspectModel<Long, Long, String> aspectModel = new ScoresRelevanceAspectModel<>(intentModel); return new AlphaXQuAD<>(aspectModel, alpha, lambda, cutoff, true); }); rerankersMap.put("PM", () -> { double alpha = 0.5; double lambda = 0.9; BinomialModel<Long, Long, String> binomialModel = new BinomialModel<>(false, Stream.empty(), trainData, featureData, alpha); return new PM<>(featureData, binomialModel, lambda, cutoff); }); RecommendationFormat<Long, Long> format = new SimpleRecommendationFormat<>(lp, lp); rerankersMap.forEach(Unchecked.biConsumer((name, rerankerSupplier) -> { String recOut = Paths.get(Paths.get(recIn).getParent().toString(), String.format("%s-%s", name, FilenameUtils.getName(recIn))).toString(); System.out.printf("running %s, output to %s\n", name, recOut); Reranker<Long, Long> reranker = rerankerSupplier.get(); try (RecommendationFormat.Writer<Long, Long> writer = format.getWriter(recOut)) { format.getReader(recIn).readAll().map(rec -> reranker.rerankRecommendation(rec, cutoff)) .forEach(Unchecked.consumer(writer::write)); } })); }
From source file:br.com.autonomiccs.cloudTraces.main.CloudTracesSimulator.java
public static void main(String[] args) { validateInputFile(args);/* ww w . java 2s.co m*/ String cloudTracesFile = args[0]; Collection<VirtualMachine> virtualMachines = getAllVirtualMachinesFromCloudTraces(cloudTracesFile); logger.info(String.format("#VirtualMachines [%d] found on [%s].", virtualMachines.size(), cloudTracesFile)); Map<Integer, List<VirtualMachine>> mapVirtualMachinesTaskExecutionByTime = createMapVirtualMachinesTaskExecutionByTime( virtualMachines); logger.info(String.format("#Times [%d] that have tasks being executed by VMs ", mapVirtualMachinesTaskExecutionByTime.size())); Cloud cloud = createCloudEnvirtonmentToStartsimulation(); logger.info("Cloud configuration: " + cloud); List<Integer> timesToExecuteTasks = new ArrayList<>(mapVirtualMachinesTaskExecutionByTime.keySet()); Collections.sort(timesToExecuteTasks); Integer firstTimeInTimeUnitOfUsedCloudData = timesToExecuteTasks.get(0); Integer lastTimeInTimeUnitOfUserCloudData = timesToExecuteTasks.get(timesToExecuteTasks.size() - 1); logger.info("First time: " + firstTimeInTimeUnitOfUsedCloudData); logger.info("Last time: " + lastTimeInTimeUnitOfUserCloudData); double timeUnitPerLoopIteration = getTimeUnitPerLoopIteration(firstTimeInTimeUnitOfUsedCloudData, lastTimeInTimeUnitOfUserCloudData); logger.info("The time unit converted to trace time: " + timeUnitPerLoopIteration); double currentTime = firstTimeInTimeUnitOfUsedCloudData; long highetResourceAllocation = Long.MIN_VALUE; String cloudStateHighestMemoryAllocation = ""; while (currentTime < lastTimeInTimeUnitOfUserCloudData + 2 * timeUnitPerLoopIteration) { logger.debug("Current time of iteration: " + currentTime); if (cloud.getMemoryAllocatedInBytes() > highetResourceAllocation) { highetResourceAllocation = cloud.getMemoryAllocatedInBytes(); cloudStateHighestMemoryAllocation = cloud.toString(); } applyLoadOnCloudForCurrentTime(mapVirtualMachinesTaskExecutionByTime, cloud, currentTime); destroyVirtualMachinesIfNeeded(cloud, currentTime); logger.info(String.format("Time [%.3f], cloud state [%s] ", currentTime, cloud)); executeManagement(cloud, currentTime); logClustersConfigurationsAndStdAtTime(cloud.getClusters(), currentTime); currentTime += timeUnitPerLoopIteration; } logger.info("Cloud configuration after simulation: " + cloud); logger.info("Cloud highestResourceUsage: " + cloudStateHighestMemoryAllocation); }
From source file:com.genentech.struchk.sdfNormalizer.java
public static void main(String[] args) { long start = System.currentTimeMillis(); int nMessages = 0; int nErrors = 0; int nStruct = 0; // create command line Options object Options options = new Options(); Option opt = new Option("in", true, "input file [.ism,.sdf,...]"); opt.setRequired(true);// w w w. ja v a 2 s .c o m options.addOption(opt); opt = new Option("out", true, "output file"); opt.setRequired(true); options.addOption(opt); opt = new Option("mol", true, "molFile used for output: ORIGINAL(def)|NORMALIZED|TAUTOMERIC"); opt.setRequired(false); options.addOption(opt); opt = new Option("shortMessage", false, "Limit message to first 80 characters to conform with sdf file specs."); opt.setRequired(false); options.addOption(opt); CommandLineParser parser = new PosixParser(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException e) { exitWithHelp(options, e.getMessage()); throw new Error(e); // avoid compiler errors } args = cmd.getArgs(); if (args.length != 0) { System.err.print("Unknown options: " + args + "\n\n"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("sdfNormalizer", options); System.exit(1); } String molOpt = cmd.getOptionValue("mol"); OUTMolFormat outMol = OUTMolFormat.ORIGINAL; if (molOpt == null || "original".equalsIgnoreCase(molOpt)) outMol = OUTMolFormat.ORIGINAL; else if ("NORMALIZED".equalsIgnoreCase(molOpt)) outMol = OUTMolFormat.NORMALIZED; else if ("TAUTOMERIC".equalsIgnoreCase(molOpt)) outMol = OUTMolFormat.TAUTOMERIC; else { System.err.printf("Unkown option for -mol: %s\n", molOpt); System.exit(1); } String inFile = cmd.getOptionValue("in"); String outFile = cmd.getOptionValue("out"); boolean limitMessage = cmd.hasOption("shortMessage"); try { oemolistream ifs = new oemolistream(inFile); oemolostream ofs = new oemolostream(outFile); URL cFile = OEStruchk.getResourceURL(OEStruchk.class, "Struchk.xml"); // create OEStruchk from config file OEStruchk strchk = new OEStruchk(cFile, CHECKConfig.ASSIGNStructFlag, false); OEGraphMol mol = new OEGraphMol(); StringBuilder sb = new StringBuilder(2000); while (oechem.OEReadMolecule(ifs, mol)) { if (!strchk.applyRules(mol, null)) nErrors++; switch (outMol) { case NORMALIZED: mol.Clear(); oechem.OEAddMols(mol, strchk.getTransformedMol("parent")); break; case TAUTOMERIC: mol.Clear(); oechem.OEAddMols(mol, strchk.getTransformedMol(null)); break; case ORIGINAL: break; } oechem.OESetSDData(mol, "CTISMILES", strchk.getTransformedIsoSmiles(null)); oechem.OESetSDData(mol, "CTSMILES", strchk.getTransformedSmiles(null)); oechem.OESetSDData(mol, "CISMILES", strchk.getTransformedIsoSmiles("parent")); oechem.OESetSDData(mol, "Strutct_Flag", strchk.getStructureFlag().getName()); List<Message> msgs = strchk.getStructureMessages(null); nMessages += msgs.size(); for (Message msg : msgs) sb.append(String.format("\t%s:%s", msg.getLevel(), msg.getText())); if (limitMessage) sb.setLength(Math.min(sb.length(), 80)); oechem.OESetSDData(mol, "NORM_MESSAGE", sb.toString()); oechem.OEWriteMolecule(ofs, mol); sb.setLength(0); nStruct++; } strchk.delete(); mol.delete(); ifs.close(); ifs.delete(); ofs.close(); ofs.delete(); } catch (Exception e) { throw new Error(e); } finally { System.err.printf("sdfNormalizer: Checked %d structures %d errors, %d messages in %dsec\n", nStruct, nErrors, nMessages, (System.currentTimeMillis() - start) / 1000); } }