List of usage examples for org.apache.commons.cli CommandLine getArgs
public String[] getArgs()
From source file:apps.quantification.LearnQuantificationSVMLight.java
public static void main(String[] args) throws IOException { String cmdLineSyntax = LearnQuantificationSVMLight.class.getName() + " [OPTIONS] <path to svm_light_learn> <path to svm_light_classify> <trainingIndexDirectory> <outputDirectory>"; Options options = new Options(); OptionBuilder.withArgName("f"); OptionBuilder.withDescription("Number of folds"); OptionBuilder.withLongOpt("f"); OptionBuilder.isRequired(true);// ww w . j a v a 2 s.com OptionBuilder.hasArg(); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("c"); OptionBuilder.withDescription("The c value for svm_light (default 1)"); OptionBuilder.withLongOpt("c"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("k"); OptionBuilder.withDescription("Kernel type (default 0: linear, 1: polynomial, 2: RBF, 3: sigmoid)"); OptionBuilder.withLongOpt("k"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("t"); OptionBuilder.withDescription("Path for temporary files"); OptionBuilder.withLongOpt("t"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("v"); OptionBuilder.withDescription("Verbose output"); OptionBuilder.withLongOpt("v"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(false); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("s"); OptionBuilder.withDescription("Don't delete temporary training file in svm_light format (default: delete)"); OptionBuilder.withLongOpt("s"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(false); options.addOption(OptionBuilder.create()); SvmLightLearnerCustomizer classificationLearnerCustomizer = null; SvmLightClassifierCustomizer classificationCustomizer = null; int folds = -1; GnuParser parser = new GnuParser(); String[] remainingArgs = null; try { CommandLine line = parser.parse(options, args); remainingArgs = line.getArgs(); classificationLearnerCustomizer = new SvmLightLearnerCustomizer(remainingArgs[0]); classificationCustomizer = new SvmLightClassifierCustomizer(remainingArgs[1]); folds = Integer.parseInt(line.getOptionValue("f")); if (line.hasOption("c")) classificationLearnerCustomizer.setC(Float.parseFloat(line.getOptionValue("c"))); if (line.hasOption("k")) { System.out.println("Kernel type: " + line.getOptionValue("k")); classificationLearnerCustomizer.setKernelType(Integer.parseInt(line.getOptionValue("k"))); } if (line.hasOption("v")) classificationLearnerCustomizer.printSvmLightOutput(true); if (line.hasOption("s")) classificationLearnerCustomizer.setDeleteTrainingFiles(false); if (line.hasOption("t")) { classificationLearnerCustomizer.setTempPath(line.getOptionValue("t")); classificationCustomizer.setTempPath(line.getOptionValue("t")); } } catch (Exception exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(cmdLineSyntax, options); System.exit(-1); } assert (classificationLearnerCustomizer != null); if (remainingArgs.length != 4) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(cmdLineSyntax, options); System.exit(-1); } String indexFile = remainingArgs[2]; File file = new File(indexFile); String indexName = file.getName(); String indexPath = file.getParent(); String outputPath = remainingArgs[3]; SvmLightLearner classificationLearner = new SvmLightLearner(); classificationLearner.setRuntimeCustomizer(classificationLearnerCustomizer); FileSystemStorageManager fssm = new FileSystemStorageManager(indexPath, false); fssm.open(); IIndex training = TroveReadWriteHelper.readIndex(fssm, indexName, TroveContentDBType.Full, TroveClassificationDBType.Full); final TextualProgressBar progressBar = new TextualProgressBar("Learning the quantifiers"); IOperationStatusListener status = new IOperationStatusListener() { @Override public void operationStatus(double percentage) { progressBar.signal((int) percentage); } }; QuantificationLearner quantificationLearner = new QuantificationLearner(folds, classificationLearner, classificationLearnerCustomizer, classificationCustomizer, ClassificationMode.PER_CATEGORY, new LogisticFunction(), status); IQuantifier[] quantifiers = quantificationLearner.learn(training); File executableFile = new File(classificationLearnerCustomizer.getSvmLightLearnPath()); IDataManager classifierDataManager = new SvmLightDataManager(new SvmLightClassifierCustomizer( executableFile.getParentFile().getAbsolutePath() + Os.pathSeparator() + "svm_light_classify")); String description = "_SVMLight_C-" + classificationLearnerCustomizer.getC() + "_K-" + classificationLearnerCustomizer.getKernelType(); if (classificationLearnerCustomizer.getAdditionalParameters().length() > 0) description += "_" + classificationLearnerCustomizer.getAdditionalParameters(); String quantifierPrefix = indexName + "_Quantifier-" + folds + description; FileSystemStorageManager fssmo = new FileSystemStorageManager( outputPath + File.separatorChar + quantifierPrefix, true); fssmo.open(); QuantificationLearner.write(quantifiers, fssmo, classifierDataManager); fssmo.close(); BufferedWriter bfs = new BufferedWriter( new FileWriter(outputPath + File.separatorChar + quantifierPrefix + "_rates.txt")); TShortDoubleHashMap simpleTPRs = quantificationLearner.getSimpleTPRs(); TShortDoubleHashMap simpleFPRs = quantificationLearner.getSimpleFPRs(); TShortDoubleHashMap scaledTPRs = quantificationLearner.getScaledTPRs(); TShortDoubleHashMap scaledFPRs = quantificationLearner.getScaledFPRs(); ContingencyTableSet contingencyTableSet = quantificationLearner.getContingencyTableSet(); short[] cats = simpleTPRs.keys(); for (int i = 0; i < cats.length; ++i) { short cat = cats[i]; String catName = training.getCategoryDB().getCategoryName(cat); ContingencyTable contingencyTable = contingencyTableSet.getCategoryContingencyTable(cat); double simpleTPR = simpleTPRs.get(cat); double simpleFPR = simpleFPRs.get(cat); double scaledTPR = scaledTPRs.get(cat); double scaledFPR = scaledFPRs.get(cat); String line = quantifierPrefix + "\ttrain\tsimple\t" + catName + "\t" + cat + "\t" + contingencyTable.tp() + "\t" + contingencyTable.fp() + "\t" + contingencyTable.fn() + "\t" + contingencyTable.tn() + "\t" + simpleTPR + "\t" + simpleFPR + "\n"; bfs.write(line); line = quantifierPrefix + "\ttrain\tscaled\t" + catName + "\t" + cat + "\t" + contingencyTable.tp() + "\t" + contingencyTable.fp() + "\t" + contingencyTable.fn() + "\t" + contingencyTable.tn() + "\t" + scaledTPR + "\t" + scaledFPR + "\n"; bfs.write(line); } bfs.close(); }
From source file:apps.quantification.QuantifySVMLight.java
public static void main(String[] args) throws IOException { String cmdLineSyntax = QuantifySVMLight.class.getName() + " [OPTIONS] <path to svm_light_classify> <testIndexDirectory> <quantificationModelDirectory>"; Options options = new Options(); OptionBuilder.withArgName("d"); OptionBuilder.withDescription("Dump confidences file"); OptionBuilder.withLongOpt("d"); OptionBuilder.isRequired(false);/*from w w w .ja va2s .c o m*/ OptionBuilder.hasArg(false); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("t"); OptionBuilder.withDescription("Path for temporary files"); OptionBuilder.withLongOpt("t"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("v"); OptionBuilder.withDescription("Verbose output"); OptionBuilder.withLongOpt("v"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(false); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("s"); OptionBuilder.withDescription("Don't delete temporary files in svm_light format (default: delete)"); OptionBuilder.withLongOpt("s"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(false); options.addOption(OptionBuilder.create()); SvmLightClassifierCustomizer customizer = null; GnuParser parser = new GnuParser(); String[] remainingArgs = null; try { CommandLine line = parser.parse(options, args); remainingArgs = line.getArgs(); customizer = new SvmLightClassifierCustomizer(remainingArgs[0]); if (line.hasOption("v")) customizer.printSvmLightOutput(true); if (line.hasOption("s")) { System.out.println("Keeping temporary files."); customizer.setDeleteTestFiles(false); customizer.setDeletePredictionsFiles(false); } if (line.hasOption("t")) customizer.setTempPath(line.getOptionValue("t")); } catch (Exception exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(cmdLineSyntax, options); System.exit(-1); } if (remainingArgs.length != 3) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(cmdLineSyntax, options); System.exit(-1); } String indexFile = remainingArgs[1]; File file = new File(indexFile); String indexName = file.getName(); String indexPath = file.getParent(); String quantifierFilename = remainingArgs[2]; FileSystemStorageManager indexFssm = new FileSystemStorageManager(indexPath, false); indexFssm.open(); IIndex test = TroveReadWriteHelper.readIndex(indexFssm, indexName, TroveContentDBType.Full, TroveClassificationDBType.Full); indexFssm.close(); FileSystemStorageManager quantifierFssm = new FileSystemStorageManager(quantifierFilename, false); quantifierFssm.open(); SvmLightDataManager classifierDataManager = new SvmLightDataManager(customizer); FileSystemStorageManager fssm = new FileSystemStorageManager(quantifierFilename, false); fssm.open(); IQuantifier[] quantifiers = QuantificationLearner.read(fssm, classifierDataManager, ClassificationMode.PER_CATEGORY); fssm.close(); quantifierFssm.close(); Quantification ccQuantification = quantifiers[0].quantify(test); Quantification paQuantification = quantifiers[1].quantify(test); Quantification accQuantification = quantifiers[2].quantify(test); Quantification maxQuantification = quantifiers[3].quantify(test); Quantification sccQuantification = quantifiers[4].quantify(test); Quantification spaQuantification = quantifiers[5].quantify(test); Quantification trueQuantification = new Quantification("True", test.getClassificationDB()); File quantifierFile = new File(quantifierFilename); String quantificationName = quantifierFile.getParent() + Os.pathSeparator() + indexName + "_" + quantifierFile.getName() + ".txt"; BufferedWriter writer = new BufferedWriter(new FileWriter(quantificationName)); IShortIterator iterator = test.getCategoryDB().getCategories(); while (iterator.hasNext()) { short category = iterator.next(); String prefix = quantifierFile.getName() + "\t" + indexName + "\t" + test.getCategoryDB().getCategoryName(category) + "\t" + category + "\t" + trueQuantification.getQuantification(category) + "\t"; writer.write(prefix + ccQuantification.getName() + "\t" + ccQuantification.getQuantification(category) + "\n"); writer.write(prefix + paQuantification.getName() + "\t" + paQuantification.getQuantification(category) + "\n"); writer.write(prefix + accQuantification.getName() + "\t" + accQuantification.getQuantification(category) + "\n"); writer.write(prefix + maxQuantification.getName() + "\t" + maxQuantification.getQuantification(category) + "\n"); writer.write(prefix + sccQuantification.getName() + "\t" + sccQuantification.getQuantification(category) + "\n"); writer.write(prefix + spaQuantification.getName() + "\t" + spaQuantification.getQuantification(category) + "\n"); } writer.close(); BufferedWriter bfs = new BufferedWriter(new FileWriter(quantifierFile.getParent() + Os.pathSeparator() + indexName + "_" + quantifierFile.getName() + "_rates.txt")); TShortDoubleHashMap simpleTPRs = ((CCQuantifier) quantifiers[0]).getSimpleTPRs(); TShortDoubleHashMap simpleFPRs = ((CCQuantifier) quantifiers[0]).getSimpleFPRs(); TShortDoubleHashMap maxTPRs = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3]).getInternalQuantifier()) .getSimpleTPRs(); TShortDoubleHashMap maxFPRs = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3]).getInternalQuantifier()) .getSimpleFPRs(); TShortDoubleHashMap scaledTPRs = ((PAQuantifier) quantifiers[1]).getScaledTPRs(); TShortDoubleHashMap scaledFPRs = ((PAQuantifier) quantifiers[1]).getScaledFPRs(); ContingencyTableSet simpleContingencyTableSet = ((CCQuantifier) quantifiers[0]).getContingencyTableSet(); ContingencyTableSet maxContingencyTableSet = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3]) .getInternalQuantifier()).getContingencyTableSet(); short[] cats = simpleTPRs.keys(); for (int i = 0; i < cats.length; ++i) { short cat = cats[i]; String catName = test.getCategoryDB().getCategoryName(cat); ContingencyTable simpleContingencyTable = simpleContingencyTableSet.getCategoryContingencyTable(cat); ContingencyTable maxContingencyTable = maxContingencyTableSet.getCategoryContingencyTable(cat); double simpleTPR = simpleTPRs.get(cat); double simpleFPR = simpleFPRs.get(cat); double maxTPR = maxTPRs.get(cat); double maxFPR = maxFPRs.get(cat); double scaledTPR = scaledTPRs.get(cat); double scaledFPR = scaledFPRs.get(cat); String line = indexName + "_" + quantifierFile.getName() + "\ttest\tsimple\t" + catName + "\t" + cat + "\t" + simpleContingencyTable.tp() + "\t" + simpleContingencyTable.fp() + "\t" + simpleContingencyTable.fn() + "\t" + simpleContingencyTable.tn() + "\t" + simpleTPR + "\t" + simpleFPR + "\n"; bfs.write(line); line = indexName + "_" + quantifierFile.getName() + "\ttest\tmax\t" + catName + "\t" + cat + "\t" + maxContingencyTable.tp() + "\t" + maxContingencyTable.fp() + "\t" + maxContingencyTable.fn() + "\t" + maxContingencyTable.tn() + "\t" + maxTPR + "\t" + maxFPR + "\n"; bfs.write(line); line = indexName + "_" + quantifierFile.getName() + "\ttest\tscaled\t" + catName + "\t" + cat + "\t" + simpleContingencyTable.tp() + "\t" + simpleContingencyTable.fp() + "\t" + simpleContingencyTable.fn() + "\t" + simpleContingencyTable.tn() + "\t" + scaledTPR + "\t" + scaledFPR + "\n"; bfs.write(line); } bfs.close(); }
From source file:apps.quantification.QuantifySVMPerf.java
public static void main(String[] args) throws IOException { String cmdLineSyntax = QuantifySVMPerf.class.getName() + " [OPTIONS] <path to svm_perf_classify> <testIndexDirectory> <quantificationModelDirectory>"; Options options = new Options(); OptionBuilder.withArgName("d"); OptionBuilder.withDescription("Dump confidences file"); OptionBuilder.withLongOpt("d"); OptionBuilder.isRequired(false);//from ww w .j a va 2 s . com OptionBuilder.hasArg(false); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("t"); OptionBuilder.withDescription("Path for temporary files"); OptionBuilder.withLongOpt("t"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("v"); OptionBuilder.withDescription("Verbose output"); OptionBuilder.withLongOpt("v"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(false); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("s"); OptionBuilder.withDescription("Don't delete temporary files in svm_perf format (default: delete)"); OptionBuilder.withLongOpt("s"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(false); options.addOption(OptionBuilder.create()); SvmPerfClassifierCustomizer customizer = null; GnuParser parser = new GnuParser(); String[] remainingArgs = null; try { CommandLine line = parser.parse(options, args); remainingArgs = line.getArgs(); customizer = new SvmPerfClassifierCustomizer(remainingArgs[0]); if (line.hasOption("v")) customizer.printSvmPerfOutput(true); if (line.hasOption("s")) { System.out.println("Keeping temporary files."); customizer.setDeleteTestFiles(false); customizer.setDeletePredictionsFiles(false); } if (line.hasOption("t")) customizer.setTempPath(line.getOptionValue("t")); } catch (Exception exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(cmdLineSyntax, options); System.exit(-1); } if (remainingArgs.length != 3) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(cmdLineSyntax, options); System.exit(-1); } String indexFile = remainingArgs[1]; File file = new File(indexFile); String indexName = file.getName(); String indexPath = file.getParent(); String quantifierFilename = remainingArgs[2]; FileSystemStorageManager indexFssm = new FileSystemStorageManager(indexPath, false); indexFssm.open(); IIndex test = TroveReadWriteHelper.readIndex(indexFssm, indexName, TroveContentDBType.Full, TroveClassificationDBType.Full); indexFssm.close(); FileSystemStorageManager quantifierFssm = new FileSystemStorageManager(quantifierFilename, false); quantifierFssm.open(); SvmPerfDataManager classifierDataManager = new SvmPerfDataManager(customizer); FileSystemStorageManager fssm = new FileSystemStorageManager(quantifierFilename, false); fssm.open(); IQuantifier[] quantifiers = QuantificationLearner.read(fssm, classifierDataManager, ClassificationMode.PER_CATEGORY); fssm.close(); quantifierFssm.close(); Quantification ccQuantification = quantifiers[0].quantify(test); Quantification paQuantification = quantifiers[1].quantify(test); Quantification accQuantification = quantifiers[2].quantify(test); Quantification maxQuantification = quantifiers[3].quantify(test); Quantification sccQuantification = quantifiers[4].quantify(test); Quantification spaQuantification = quantifiers[5].quantify(test); Quantification trueQuantification = new Quantification("True", test.getClassificationDB()); File quantifierFile = new File(quantifierFilename); String quantificationName = quantifierFile.getParent() + Os.pathSeparator() + indexName + "_" + quantifierFile.getName() + ".txt"; BufferedWriter writer = new BufferedWriter(new FileWriter(quantificationName)); IShortIterator iterator = test.getCategoryDB().getCategories(); while (iterator.hasNext()) { short category = iterator.next(); String prefix = quantifierFile.getName() + "\t" + indexName + "\t" + test.getCategoryDB().getCategoryName(category) + "\t" + category + "\t" + trueQuantification.getQuantification(category) + "\t"; writer.write(prefix + ccQuantification.getName() + "\t" + ccQuantification.getQuantification(category) + "\n"); writer.write(prefix + paQuantification.getName() + "\t" + paQuantification.getQuantification(category) + "\n"); writer.write(prefix + accQuantification.getName() + "\t" + accQuantification.getQuantification(category) + "\n"); writer.write(prefix + maxQuantification.getName() + "\t" + maxQuantification.getQuantification(category) + "\n"); writer.write(prefix + sccQuantification.getName() + "\t" + sccQuantification.getQuantification(category) + "\n"); writer.write(prefix + spaQuantification.getName() + "\t" + spaQuantification.getQuantification(category) + "\n"); } writer.close(); BufferedWriter bfs = new BufferedWriter(new FileWriter(quantifierFile.getParent() + Os.pathSeparator() + indexName + "_" + quantifierFile.getName() + "_rates.txt")); TShortDoubleHashMap simpleTPRs = ((CCQuantifier) quantifiers[0]).getSimpleTPRs(); TShortDoubleHashMap simpleFPRs = ((CCQuantifier) quantifiers[0]).getSimpleFPRs(); TShortDoubleHashMap maxTPRs = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3]).getInternalQuantifier()) .getSimpleTPRs(); TShortDoubleHashMap maxFPRs = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3]).getInternalQuantifier()) .getSimpleFPRs(); TShortDoubleHashMap scaledTPRs = ((PAQuantifier) quantifiers[1]).getScaledTPRs(); TShortDoubleHashMap scaledFPRs = ((PAQuantifier) quantifiers[1]).getScaledFPRs(); ContingencyTableSet simpleContingencyTableSet = ((CCQuantifier) quantifiers[0]).getContingencyTableSet(); ContingencyTableSet maxContingencyTableSet = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3]) .getInternalQuantifier()).getContingencyTableSet(); short[] cats = simpleTPRs.keys(); for (int i = 0; i < cats.length; ++i) { short cat = cats[i]; String catName = test.getCategoryDB().getCategoryName(cat); ContingencyTable simpleContingencyTable = simpleContingencyTableSet.getCategoryContingencyTable(cat); ContingencyTable maxContingencyTable = maxContingencyTableSet.getCategoryContingencyTable(cat); double simpleTPR = simpleTPRs.get(cat); double simpleFPR = simpleFPRs.get(cat); double maxTPR = maxTPRs.get(cat); double maxFPR = maxFPRs.get(cat); double scaledTPR = scaledTPRs.get(cat); double scaledFPR = scaledFPRs.get(cat); String line = indexName + "_" + quantifierFile.getName() + "\ttest\tsimple\t" + catName + "\t" + cat + "\t" + simpleContingencyTable.tp() + "\t" + simpleContingencyTable.fp() + "\t" + simpleContingencyTable.fn() + "\t" + simpleContingencyTable.tn() + "\t" + simpleTPR + "\t" + simpleFPR + "\n"; bfs.write(line); line = indexName + "_" + quantifierFile.getName() + "\ttest\tmax\t" + catName + "\t" + cat + "\t" + maxContingencyTable.tp() + "\t" + maxContingencyTable.fp() + "\t" + maxContingencyTable.fn() + "\t" + maxContingencyTable.tn() + "\t" + maxTPR + "\t" + maxFPR + "\n"; bfs.write(line); line = indexName + "_" + quantifierFile.getName() + "\ttest\tscaled\t" + catName + "\t" + cat + "\t" + simpleContingencyTable.tp() + "\t" + simpleContingencyTable.fp() + "\t" + simpleContingencyTable.fn() + "\t" + simpleContingencyTable.tn() + "\t" + scaledTPR + "\t" + scaledFPR + "\n"; bfs.write(line); } bfs.close(); }
From source file:co.paralleluniverse.photon.Photon.java
public static void main(final String[] args) throws InterruptedException, IOException { final Options options = new Options(); options.addOption("rate", true, "Requests per second (default " + rateDefault + ")"); options.addOption("duration", true, "Minimum test duration in seconds: will wait for <duration> * <rate> requests to terminate or, if progress check enabled, no progress after <duration> (default " + durationDefault + ")"); options.addOption("maxconnections", true, "Maximum number of open connections (default " + maxConnectionsDefault + ")"); options.addOption("timeout", true, "Connection and read timeout in millis (default " + timeoutDefault + ")"); options.addOption("print", true, "Print cycle in millis, 0 to disable intermediate statistics (default " + printCycleDefault + ")"); options.addOption("check", true, "Progress check cycle in millis, 0 to disable progress check (default " + checkCycleDefault + ")"); options.addOption("stats", false, "Print full statistics when finish (default false)"); options.addOption("minmax", false, "Print min/mean/stddev/max stats when finish (default false)"); options.addOption("name", true, "Test name to print in the statistics (default '" + testNameDefault + "')"); options.addOption("help", false, "Print help"); try {/*from w w w .j a v a 2 s.c om*/ final CommandLine cmd = new BasicParser().parse(options, args); final String[] ar = cmd.getArgs(); if (cmd.hasOption("help") || ar.length != 1) printUsageAndExit(options); final String url = ar[0]; final int timeout = Integer.parseInt(cmd.getOptionValue("timeout", timeoutDefault)); final int maxConnections = Integer .parseInt(cmd.getOptionValue("maxconnections", maxConnectionsDefault)); final int duration = Integer.parseInt(cmd.getOptionValue("duration", durationDefault)); final int printCycle = Integer.parseInt(cmd.getOptionValue("print", printCycleDefault)); final int checkCycle = Integer.parseInt(cmd.getOptionValue("check", checkCycleDefault)); final String testName = cmd.getOptionValue("name", testNameDefault); final int rate = Integer.parseInt(cmd.getOptionValue("rate", rateDefault)); final MetricRegistry metrics = new MetricRegistry(); final Meter requestMeter = metrics.meter("request"); final Meter responseMeter = metrics.meter("response"); final Meter errorsMeter = metrics.meter("errors"); final Logger log = LoggerFactory.getLogger(Photon.class); final ConcurrentHashMap<String, AtomicInteger> errors = new ConcurrentHashMap<>(); final HttpGet request = new HttpGet(url); final StripedTimeSeries<Long> sts = new StripedTimeSeries<>(30000, false); final StripedHistogram sh = new StripedHistogram(60000, 5); log.info("name: " + testName + " url:" + url + " rate:" + rate + " duration:" + duration + " maxconnections:" + maxConnections + ", " + "timeout:" + timeout); final DefaultConnectingIOReactor ioreactor = new DefaultConnectingIOReactor(IOReactorConfig.custom() .setConnectTimeout(timeout).setIoThreadCount(10).setSoTimeout(timeout).build()); Runtime.getRuntime().addShutdownHook(new Thread(() -> { final List<ExceptionEvent> events = ioreactor.getAuditLog(); if (events != null) events.stream().filter(event -> event != null).forEach(event -> { System.err.println( "Apache Async HTTP Client I/O Reactor Error Time: " + event.getTimestamp()); //noinspection ThrowableResultOfMethodCallIgnored if (event.getCause() != null) //noinspection ThrowableResultOfMethodCallIgnored event.getCause().printStackTrace(); }); if (cmd.hasOption("stats")) printFinishStatistics(errorsMeter, sts, sh, testName); if (!errors.keySet().isEmpty()) errors.entrySet().stream() .forEach(p -> log.info(testName + " " + p.getKey() + " " + p.getValue() + "ms")); System.out.println( testName + " responseTime(90%): " + sh.getHistogramData().getValueAtPercentile(90) + "ms"); if (cmd.hasOption("minmax")) { final HistogramData hd = sh.getHistogramData(); System.out.format("%s %8s%8s%8s%8s\n", testName, "min", "mean", "sd", "max"); System.out.format("%s %8d%8.2f%8.2f%8d\n", testName, hd.getMinValue(), hd.getMean(), hd.getStdDeviation(), hd.getMaxValue()); } })); final PoolingNHttpClientConnectionManager mngr = new PoolingNHttpClientConnectionManager(ioreactor); mngr.setDefaultMaxPerRoute(maxConnections); mngr.setMaxTotal(maxConnections); final CloseableHttpAsyncClient ahc = HttpAsyncClientBuilder.create().setConnectionManager(mngr) .setDefaultRequestConfig(RequestConfig.custom().setLocalAddress(null).build()).build(); try (final CloseableHttpClient client = new FiberHttpClient(ahc)) { final int num = duration * rate; final CountDownLatch cdl = new CountDownLatch(num); final Semaphore sem = new Semaphore(maxConnections); final RateLimiter rl = RateLimiter.create(rate); spawnStatisticsThread(printCycle, cdl, log, requestMeter, responseMeter, errorsMeter, testName); for (int i = 0; i < num; i++) { rl.acquire(); if (sem.availablePermits() == 0) log.debug("Maximum connections count reached, waiting..."); sem.acquireUninterruptibly(); new Fiber<Void>(() -> { requestMeter.mark(); final long start = System.nanoTime(); try { try (final CloseableHttpResponse ignored = client.execute(request)) { responseMeter.mark(); } catch (final Throwable t) { markError(errorsMeter, errors, t); } } catch (final Throwable t) { markError(errorsMeter, errors, t); } finally { final long now = System.nanoTime(); final long millis = TimeUnit.NANOSECONDS.toMillis(now - start); sts.record(start, millis); sh.recordValue(millis); sem.release(); cdl.countDown(); } }).start(); } spawnProgressCheckThread(log, duration, checkCycle, cdl); cdl.await(); } } catch (final ParseException ex) { System.err.println("Parsing failed. Reason: " + ex.getMessage()); } }
From source file:client.MultiplexingClient.java
public static void main(String[] args) throws Exception { // Prepare to parse the command line Options options = new Options(); Option sslOpt = new Option("s", "ssl", false, "Use SSL"); Option debugOpt = new Option("d", true, "Debug level (NONE, FINER, FINE, CONFIG, INFO, WARNING, SEVERE. Default INFO."); Option numConnectionsOpt = new Option("n", true, "Number of connections to establish. [Default: 1]"); Option numPcktOpt = new Option("p", true, "Number of packets to send in each connection. [Default: 20]"); Option pcktMaxSizeOpt = new Option("m", true, "Maximum size of packets. [Default: 4096]"); Option help = new Option("h", "print this message"); options.addOption(help);// w w w. j ava2 s .co m options.addOption(debugOpt); options.addOption(numConnectionsOpt); options.addOption(numPcktOpt); options.addOption(pcktMaxSizeOpt); options.addOption(sslOpt); CommandLineParser parser = new PosixParser(); // parse the command line arguments CommandLine line = parser.parse(options, args); if (line.hasOption(help.getOpt()) || line.getArgs().length < 1) { showUsage(options); return; } if (line.hasOption(sslOpt.getOpt())) { channelFactory = new SSLChannelFactory(true, TRUSTSTORE, TRUSTSTORE_PASSWORD); } else { channelFactory = new PlainChannelFactory(); } if (line.hasOption(numConnectionsOpt.getOpt())) { connectionCount = Integer.parseInt(line.getOptionValue(numConnectionsOpt.getOpt())); } else { connectionCount = 1; } if (line.hasOption(numPcktOpt.getOpt())) { packetsToSend = Integer.parseInt(line.getOptionValue(numPcktOpt.getOpt())); } else { packetsToSend = 20; } if (line.hasOption(pcktMaxSizeOpt.getOpt())) { maxPcktSize = Integer.parseInt(line.getOptionValue(pcktMaxSizeOpt.getOpt())); } else { maxPcktSize = 4096; } InetSocketAddress remotePoint; try { String host = line.getArgs()[0]; int colonIndex = host.indexOf(':'); remotePoint = new InetSocketAddress(host.substring(0, colonIndex), Integer.parseInt(host.substring(colonIndex + 1))); } catch (Exception e) { showUsage(options); return; } // Setups the logging context for Log4j // NDC.push(Thread.currentThread().getName()); st = new SelectorThread(); for (int i = 0; i < connectionCount; i++) { new MultiplexingClient(remotePoint); // Must sleep for a while between opening connections in order // to give the remote host enough time to handle them. Otherwise, // the remote host backlog will get full and the connection // attemps will start to be refused. Thread.sleep(100); } }
From source file:com.genentech.retrival.tabExport.TABExporter.java
public static void main(String[] args) throws ParseException, JDOMException, IOException { long start = System.currentTimeMillis(); int nStruct = 0; // create command line Options object Options options = new Options(); Option opt = new Option("sqlFile", true, "sql-xml file"); opt.setRequired(true);//from w ww . j av a 2 s . c om options.addOption(opt); opt = new Option("sqlName", true, "name of SQL element in xml file"); opt.setRequired(true); options.addOption(opt); opt = new Option("o", true, "output file"); opt.setRequired(false); options.addOption(opt); opt = new Option("newLineReplacement", true, "If given newlines in fields will be replaced by this string."); options.addOption(opt); opt = new Option("noHeader", false, "Do not output header line"); options.addOption(opt); CommandLineParser parser = new BasicParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (Exception e) { System.err.println(e.getMessage()); exitWithHelp(options); } args = cmd.getArgs(); String outFile = cmd.getOptionValue("o"); String sqlFile = cmd.getOptionValue("sqlFile"); String sqlName = cmd.getOptionValue("sqlName"); String newLineReplacement = cmd.getOptionValue("newLineReplacement"); args = cmd.getArgs(); try { PrintStream out = System.out; if (outFile != null) out = new PrintStream(outFile); SQLStatement stmt = SQLStatement.createFromFile(new File(sqlFile), sqlName); Object[] sqlArgs = args; if (stmt.getParamTypes().length != args.length) { System.err.printf( "\nWarining sql statement needs %d parameters but got only %d. Filling up with NULLs.\n", stmt.getParamTypes().length, args.length); sqlArgs = new Object[stmt.getParamTypes().length]; System.arraycopy(args, 0, sqlArgs, 0, args.length); } Selecter sel = Selecter.factory(stmt); if (!sel.select(sqlArgs)) { System.err.println("No rows returned!"); System.exit(0); } String[] fieldNames = sel.getFieldNames(); if (fieldNames.length == 0) { System.err.println("Query did not return any columns"); exitWithHelp(options); } if (!cmd.hasOption("noHeader")) { StringBuilder sb = new StringBuilder(200); for (String f : fieldNames) sb.append(f).append('\t'); if (sb.length() > 1) sb.setLength(sb.length() - 1); // chop last \t String header = sb.toString(); out.println(header); } StringBuilder sb = new StringBuilder(200); while (sel.hasNext()) { Record sqlRec = sel.next(); sb.setLength(0); for (int i = 0; i < fieldNames.length; i++) { String fld = sqlRec.getStrg(i); if (newLineReplacement != null) fld = NEWLinePattern.matcher(fld).replaceAll(newLineReplacement); sb.append(fld).append('\t'); } if (sb.length() > 1) sb.setLength(sb.length() - 1); // chop last \t String row = sb.toString(); out.println(row); nStruct++; } } catch (Exception e) { throw new Error(e); } finally { System.err.printf("TABExporter: Exported %d records in %dsec\n", nStruct, (System.currentTimeMillis() - start) / 1000); } }
From source file:com.aerospike.examples.Main.java
/** * Main entry point.//from w ww .j a va2 s .c om */ public static void main(String[] args) { try { Options options = new Options(); options.addOption("h", "host", true, "Server hostname (default: localhost)"); options.addOption("p", "port", true, "Server port (default: 3000)"); options.addOption("U", "user", true, "User name"); options.addOption("P", "password", true, "Password"); options.addOption("n", "namespace", true, "Namespace (default: test)"); options.addOption("s", "set", true, "Set name. Use 'empty' for empty set (default: demoset)"); options.addOption("g", "gui", false, "Invoke GUI to selectively run tests."); options.addOption("d", "debug", false, "Run in debug mode."); options.addOption("u", "usage", false, "Print usage."); CommandLineParser parser = new PosixParser(); CommandLine cl = parser.parse(options, args, false); if (args.length == 0 || cl.hasOption("u")) { logUsage(options); return; } Parameters params = parseParameters(cl); String[] exampleNames = cl.getArgs(); if ((exampleNames.length == 0) && (!cl.hasOption("g"))) { logUsage(options); return; } // Check for all. for (String exampleName : exampleNames) { if (exampleName.equalsIgnoreCase("all")) { exampleNames = ExampleNames; break; } } if (cl.hasOption("d")) { Log.setLevel(Level.DEBUG); } if (cl.hasOption("g")) { GuiDisplay.startGui(params); } else { Console console = new Console(); runExamples(console, params, exampleNames); } } catch (Exception ex) { System.out.println(ex.getMessage()); ex.printStackTrace(); } }
From source file:microbiosima.Microbiosima.java
/** * @param args//from w w w .j ava 2 s . c o m * the command line arguments * @throws java.io.FileNotFoundException * @throws java.io.UnsupportedEncodingException */ public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException { //Init with default values int populationSize = 500; int microSize = 1000; int numberOfSpecies = 150; int numberOfGeneration = 10000; int numberOfObservation = 100; int numberOfReplication = 1; double pctEnv = 0; double pctPool = 0; Options options = new Options(); Option help = new Option("h", "help", false, "print this message"); Option version = new Option("v", "version", false, "print the version information and exit"); options.addOption(help); options.addOption(version); options.addOption(Option.builder("o").longOpt("obs").hasArg().argName("OBS") .desc("Number generation for observation [default: 100]").build()); options.addOption(Option.builder("r").longOpt("rep").hasArg().argName("REP") .desc("Number of replication [default: 1]").build()); Builder C = Option.builder("c").longOpt("config").numberOfArgs(4).argName("Pop Micro Spec Gen") .desc("Four Parameters in the following orders: " + "(1) population size, (2) microbe size, (3) number of species, (4) number of generation" + " [default: 500 1000 150 10000]"); options.addOption(C.build()); HelpFormatter formatter = new HelpFormatter(); String syntax = "microbiosima pctEnv pctPool"; String header = "\nSimulates the evolutionary and ecological dynamics of microbiomes within a population of hosts.\n\n" + "required arguments:\n" + " pctEnv Percentage of environmental acquisition\n" + " pctPool Percentage of pooled environmental component\n" + "\noptional arguments:\n"; String footer = "\n"; formatter.setWidth(80); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); String[] pct_config = cmd.getArgs(); if (cmd.hasOption("h") || args.length == 0) { formatter.printHelp(syntax, header, options, footer, true); System.exit(0); } if (cmd.hasOption("v")) { System.out.println("Microbiosima " + VERSION); System.exit(0); } if (pct_config.length != 2) { System.out.println("ERROR! Required exactly two argumennts for pct_env and pct_pool. It got " + pct_config.length + ": " + Arrays.toString(pct_config)); formatter.printHelp(syntax, header, options, footer, true); System.exit(3); } else { pctEnv = Double.parseDouble(pct_config[0]); pctPool = Double.parseDouble(pct_config[1]); if (pctEnv < 0 || pctEnv > 1) { System.out.println( "ERROR: pctEnv (Percentage of environmental acquisition) must be between 0 and 1 (pctEnv=" + pctEnv + ")! EXIT"); System.exit(3); } if (pctPool < 0 || pctPool > 1) { System.out.println( "ERROR: pctPool (Percentage of pooled environmental component must) must be between 0 and 1 (pctPool=" + pctPool + ")! EXIT"); System.exit(3); } } if (cmd.hasOption("config")) { String[] configs = cmd.getOptionValues("config"); populationSize = Integer.parseInt(configs[0]); microSize = Integer.parseInt(configs[1]); numberOfSpecies = Integer.parseInt(configs[2]); numberOfGeneration = Integer.parseInt(configs[3]); } if (cmd.hasOption("obs")) { numberOfObservation = Integer.parseInt(cmd.getOptionValue("obs")); } if (cmd.hasOption("rep")) { numberOfReplication = Integer.parseInt(cmd.getOptionValue("rep")); } } catch (ParseException e) { e.printStackTrace(); System.exit(3); } StringBuilder sb = new StringBuilder(); sb.append("Configuration Summary:").append("\n\tPopulation size: ").append(populationSize) .append("\n\tMicrobe size: ").append(microSize).append("\n\tNumber of species: ") .append(numberOfSpecies).append("\n\tNumber of generation: ").append(numberOfGeneration) .append("\n\tNumber generation for observation: ").append(numberOfObservation) .append("\n\tNumber of replication: ").append(numberOfReplication).append("\n"); System.out.println(sb.toString()); // System.exit(3); // LogNormalDistribution lgd=new LogNormalDistribution(0,1); // environment=lgd.sample(150); // double environment_sum=0; // for (int i=0;i<No;i++){ // environment_sum+=environment[i]; // } // for (int i=0;i<No;i++){ // environment[i]/=environment_sum; // } double[] environment = new double[numberOfSpecies]; for (int i = 0; i < numberOfSpecies; i++) { environment[i] = 1 / (double) numberOfSpecies; } for (int rep = 0; rep < numberOfReplication; rep++) { String prefix = "" + (rep + 1) + "_"; String sufix = "_E" + pctEnv + "_P" + pctPool + ".txt"; System.out.println("Output 5 result files in the format of: " + prefix + "[****]" + sufix); try { PrintWriter file1 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "gamma_diversity" + sufix))); PrintWriter file2 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "alpha_diversity" + sufix))); PrintWriter file3 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "beta_diversity" + sufix))); PrintWriter file4 = new PrintWriter(new BufferedWriter(new FileWriter(prefix + "sum" + sufix))); PrintWriter file5 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "inter_generation_distance" + sufix))); PrintWriter file6 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "environment_population_distance" + sufix))); Population population = new Population(microSize, environment, populationSize, pctEnv, pctPool, 0, 0); while (population.getNumberOfGeneration() < numberOfGeneration) { population.sumSpecies(); if (population.getNumberOfGeneration() % numberOfObservation == 0) { file1.println(population.gammaDiversity(true)); file2.println(population.alphaDiversity(true)); file3.print(population.betaDiversity(true)); file3.print("\t"); file3.println(population.BrayCurtis(true)); file4.println(population.printOut()); file5.println(population.interGenerationDistance()); file6.println(population.environmentPopulationDistance()); } population.getNextGen(); } file1.close(); file2.close(); file3.close(); file4.close(); file5.close(); file6.close(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:androidimporter.AndroidImporter.java
public static void main(String[] args) throws ParseException { //"/usr/local/apache-ant/bin/ant" String antPath = System.getProperty("ANT_PATH", System.getenv("ANT_PATH")); if (antPath == null || !new File(antPath).exists()) { throw new RuntimeException("Cannot find ant at " + antPath + ". Please specify location to ant via the ANT_PATH environment variable or java system property."); }/*w w w. ja va 2 s . com*/ Options opts = new Options() .addOption("i", "android-resource-dir", true, "Android project res directory path") .addOption("o", "cn1-project-dir", true, "Path to the CN1 output project directory.") .addOption("r", "cn1-resource-file", false, "Path to CN1 output .res file. Defaults to theme.res in project dir") .addOption("p", "package", true, "Java package to place GUI forms in.") .addOption("h", "help", false, "Usage instructions"); CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(opts, args); if (line.hasOption("help")) { showHelp(opts); System.exit(0); } args = line.getArgs(); if (args.length < 1) { System.out.println("No command provided."); showHelp(opts); System.exit(0); } switch (args[0]) { case "import-project": { if (!line.hasOption("android-resource-dir") || !line.hasOption("cn1-project-dir") || !line.hasOption("package")) { System.out.println("Please provide android-resource-dir, package, and cn1-project-dir options"); showHelp(opts); System.exit(1); } File resDir = findResDir(new File(line.getOptionValue("android-resource-dir"))); if (resDir == null || !resDir.isDirectory()) { System.out.println("Failed to find android resource directory from provided value"); showHelp(opts); System.exit(1); } File projDir = new File(line.getOptionValue("cn1-project-dir")); File resFile = new File(projDir, "src" + File.separator + "theme.res"); if (line.hasOption("cn1-resource-file")) { resFile = new File(line.getOptionValue("cn1-resource-file")); } JavaSEPort.setShowEDTViolationStacks(false); JavaSEPort.setShowEDTWarnings(false); JFrame frm = new JFrame("Placeholder"); frm.setVisible(false); Display.init(frm.getContentPane()); JavaSEPort.setBaseResourceDir(resFile.getParentFile()); try { System.out.println("About to import project at " + resDir.getAbsolutePath()); System.out.println("Codename One Output Project: " + projDir.getAbsolutePath()); System.out.println("Resource file: " + resFile.getAbsolutePath()); System.out.println("Java Package: " + line.getOptionValue("package")); AndroidProjectImporter.importProject(resDir, projDir, resFile, line.getOptionValue("package")); Runtime.getRuntime().exec(new String[] { antPath, "init" }, new String[] {}, resFile.getParentFile().getParentFile()); //runAnt(new File(resFile.getParentFile().getParentFile(), "build.xml"), "init"); System.exit(0); } catch (Exception ex) { ex.printStackTrace(); } finally { System.exit(0); } break; } default: System.out.println("Unknown command " + args[0]); showHelp(opts); break; } }
From source file:com.genentech.chemistry.openEye.apps.SDFTopologicalIndexer.java
/** * @param args/*ww w. ja v a2 s . c o m*/ */ public static void main(String... args) throws IOException { // create command line Options object Options options = new Options(); Option opt = new Option(OPT_INFILE, true, "input file oe-supported Use .sdf|.smi to specify the file type."); opt.setRequired(true); opt.setArgName("fn"); options.addOption(opt); opt = new Option(OPT_OUTFILE, true, "output file oe-supported. Use .sdf|.smi to specify the file type."); opt.setRequired(true); opt.setArgName("fn"); options.addOption(opt); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (Exception e) { System.err.println(e.getMessage()); exitWithHelp(options); } args = cmd.getArgs(); if (cmd.hasOption("d")) { System.err.println("Start debugger and press return:"); new BufferedReader(new InputStreamReader(System.in)).readLine(); } if (args.length == 0) { System.err.println("Specify at least one index type"); exitWithHelp(options); } String inFile = cmd.getOptionValue(OPT_INFILE); String outFile = cmd.getOptionValue(OPT_OUTFILE); Set<String> selectedIndexes = new HashSet<String>(args.length); if (args.length == 1 && "all".equalsIgnoreCase(args[0])) selectedIndexes = AVAILIndexes; else selectedIndexes.addAll(Arrays.asList(args)); if (!AVAILIndexes.containsAll(selectedIndexes)) { selectedIndexes.removeAll(AVAILIndexes); StringBuilder err = new StringBuilder("Unknown Index types: "); for (String it : selectedIndexes) err.append(it).append(" "); System.err.println(err); exitWithHelp(options); } SDFTopologicalIndexer sdfIndexer = new SDFTopologicalIndexer(outFile, selectedIndexes); sdfIndexer.run(inFile); sdfIndexer.close(); }