Example usage for org.apache.commons.cli Options Options

List of usage examples for org.apache.commons.cli Options Options

Introduction

In this page you can find the example usage for org.apache.commons.cli Options Options.

Prototype

Options

Source Link

Usage

From source file:eu.edisonproject.classification.main.BatchMain.java

public static void main(String[] args) throws Exception {
    try {/*from   w w w  . ja v  a 2s .com*/
        //            args = new String[1];
        //            args[0] = "..";
        //            TestDataFlow.execute(args);
        //            System.exit(0);
        //            TestTFIDF.execute(args);

        Options options = new Options();

        Option operation = new Option("op", "operation", true, "type of operation to perform. "
                + "To convert txt to avro 'a'.\n" + "For running clasification on avro documents 'c'");
        operation.setRequired(true);
        options.addOption(operation);

        Option input = new Option("i", "input", true, "input path");
        input.setRequired(false);
        options.addOption(input);

        Option output = new Option("o", "output", true, "output file");
        output.setRequired(false);
        options.addOption(output);

        Option competencesVector = new Option("c", "competences-vector", true, "competences vectors");
        competencesVector.setRequired(false);
        options.addOption(competencesVector);

        Option v1 = new Option("v1", "vector1", true, "");
        v1.setRequired(false);
        options.addOption(v1);

        Option v2 = new Option("v2", "vector2", true, "");
        v2.setRequired(false);
        options.addOption(v2);

        Option popertiesFile = new Option("p", "properties", true, "path for a properties file");
        popertiesFile.setRequired(false);
        options.addOption(popertiesFile);

        CommandLineParser parser = new BasicParser();
        CommandLine cmd = parser.parse(options, args);
        String propPath = cmd.getOptionValue("properties");
        MyProperties prop;
        if (propPath == null) {
            prop = ConfigHelper
                    .getProperties(".." + File.separator + "etc" + File.separator + "configure.properties");
        } else {
            prop = ConfigHelper.getProperties(propPath);
        }

        switch (cmd.getOptionValue("operation")) {
        case "a":
            text2Avro(cmd.getOptionValue("input"), cmd.getOptionValue("output"), prop);
            break;
        case "c":
            calculateTFIDF(cmd.getOptionValue("input"), cmd.getOptionValue("output"),
                    cmd.getOptionValue("competences-vector"), prop);
            break;
        case "p":
            //                    -op p -v2 $HOME/Downloads/msc.csv -v1 $HOME/Downloads/job.csv -p $HOME/workspace/E-CO-2/etc/classification.properties
            profile(cmd.getOptionValue("v1"), cmd.getOptionValue("v2"), cmd.getOptionValue("output"));
            break;
        }

    } catch (IllegalArgumentException | ParseException | IOException ex) {
        Logger.getLogger(BatchMain.class.getName()).log(Level.SEVERE, null, ex);
    }

}

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 .ja v  a2  s  . co  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_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: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  ww  w .j ava  2 s .  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:SequentialPersonalizedPageRank.java

@SuppressWarnings({ "static-access" })
public static void main(String[] args) throws IOException {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT));
    options.addOption(/*from   w  w w .  j  ava2s . co  m*/
            OptionBuilder.withArgName("val").hasArg().withDescription("random jump factor").create(JUMP));
    options.addOption(OptionBuilder.withArgName("node").hasArg()
            .withDescription("source node (i.e., destination of the random jump)").create(SOURCE));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();

    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT) || !cmdline.hasOption(SOURCE)) {
        System.out.println("args: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp(SequentialPersonalizedPageRank.class.getName(), options);
        ToolRunner.printGenericCommandUsage(System.out);
        System.exit(-1);
    }

    String infile = cmdline.getOptionValue(INPUT);
    final String source = cmdline.getOptionValue(SOURCE);
    float alpha = cmdline.hasOption(JUMP) ? Float.parseFloat(cmdline.getOptionValue(JUMP)) : 0.15f;

    int edgeCnt = 0;
    DirectedSparseGraph<String, Integer> graph = new DirectedSparseGraph<String, Integer>();

    BufferedReader data = new BufferedReader(new InputStreamReader(new FileInputStream(infile)));

    String line;
    while ((line = data.readLine()) != null) {
        line.trim();
        String[] arr = line.split("\\t");

        for (int i = 1; i < arr.length; i++) {
            graph.addEdge(new Integer(edgeCnt++), arr[0], arr[i]);
        }
    }

    data.close();

    if (!graph.containsVertex(source)) {
        System.err.println("Error: source node not found in the graph!");
        System.exit(-1);
    }

    WeakComponentClusterer<String, Integer> clusterer = new WeakComponentClusterer<String, Integer>();

    Set<Set<String>> components = clusterer.transform(graph);
    int numComponents = components.size();
    System.out.println("Number of components: " + numComponents);
    System.out.println("Number of edges: " + graph.getEdgeCount());
    System.out.println("Number of nodes: " + graph.getVertexCount());
    System.out.println("Random jump factor: " + alpha);

    // Compute personalized PageRank.
    PageRankWithPriors<String, Integer> ranker = new PageRankWithPriors<String, Integer>(graph,
            new Transformer<String, Double>() {
                @Override
                public Double transform(String vertex) {
                    return vertex.equals(source) ? 1.0 : 0;
                }
            }, alpha);

    ranker.evaluate();

    // Use priority queue to sort vertices by PageRank values.
    PriorityQueue<Ranking<String>> q = new PriorityQueue<Ranking<String>>();
    int i = 0;
    for (String pmid : graph.getVertices()) {
        q.add(new Ranking<String>(i++, ranker.getVertexScore(pmid), pmid));
    }

    // Print PageRank values.
    System.out.println("\nPageRank of nodes, in descending order:");
    Ranking<String> r = null;
    while ((r = q.poll()) != null) {
        System.out.println(r.rankScore + "\t" + r.getRanked());
    }
}

From source file:executables.Align.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws IOException {
    Options options = new Options()
            .addOption(OptionBuilder.withArgName("f1").withDescription("Fasta file 1").hasArg().create("f1"))
            .addOption(OptionBuilder.withArgName("f2").withDescription("Fasta file 2").hasArg().create("f2"))
            .addOption(OptionBuilder.withArgName("s1").withDescription("sequence 1").hasArg().create("s1"))
            .addOption(OptionBuilder.withArgName("s2").withDescription("sequence 2").hasArg().create("s2"))
            .addOption(OptionBuilder.withArgName("gap-linear").withDescription("Linear gap cost").hasArg()
                    .create("gl"))
            .addOption(OptionBuilder.withArgName("gap-open").withDescription("Affine gap open cost").hasArg()
                    .create("go"))
            .addOption(OptionBuilder.withArgName("gap-extend").withDescription("Affine gap extend cost")
                    .hasArg().create("ge"))
            .addOption(OptionBuilder.withArgName("gap-function").withDescription("Gap function file").hasArg()
                    .create("gf"))
            .addOption(/*from w ww .  ja  va 2s.co  m*/
                    OptionBuilder.withArgName("gapless").withDescription("Gapless alignment").create("gapless"))
            .addOption(OptionBuilder.withArgName("mode")
                    .withDescription("Alignment mode: global,local,freeshift (Default: freeshift)").hasArg()
                    .create('m'))
            .addOption(OptionBuilder.withArgName("match").withDescription("Match score").hasArg().create("ma"))
            .addOption(OptionBuilder.withArgName("mismatch").withDescription("Mismatch score").hasArg()
                    .create("mi"))
            .addOption(OptionBuilder.withDescription("Do not append unaligned flanking sequences")
                    .create("noflank"))
            .addOption(OptionBuilder.withArgName("check").withDescription("Calculate checkscore").create('c'))
            .addOption(OptionBuilder.withArgName("format").withDescription(
                    "Output format, see String.format, parameters are: id1,id2,score,alignment (alignment only, if -f is specified); (default: '%s %s %.4f' w/o -f and '%s %s %.4f\n%s' w/ -f)")
                    .hasArg().create("format"))
            .addOption(OptionBuilder.withArgName("matrix")
                    .withDescription("Output dynamic programming matrix as well").create("matrix"))
            .addOption(OptionBuilder.withArgName("quasar-format")
                    .withDescription("Scoring matrix in quasar format").hasArg().create('q'))
            .addOption(
                    OptionBuilder.withArgName("pairs").withDescription("Pairs file").hasArg().create("pairs"))
            .addOption(OptionBuilder.withArgName("output").withDescription("Output").hasArg().create('o'))
            .addOption(OptionBuilder.withArgName("seqlib").withDescription("Seqlib file").hasArg()
                    .create("seqlib"))
            .addOption(OptionBuilder.withArgName("full").withDescription("Full output").create('f'));

    CommandLineParser parser = new PosixParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        LongScoring<CharSequence> scoring = createScoring(cmd);
        AlignmentMode mode = createMode(cmd);
        if (mode == null)
            throw new ParseException("Mode unknown: " + cmd.getOptionValue('m'));

        Iterator<MutablePair<String, String>> idIterator = createSequences(scoring, cmd);

        GapCostFunction gap = createGapFunction(cmd);
        String format = getFormat(cmd);

        LongAligner<CharSequence> aligner;
        if (gap instanceof AffineGapCostFunction)
            aligner = new LongAligner<CharSequence>(scoring, ((AffineGapCostFunction) gap).getGapOpen(),
                    ((AffineGapCostFunction) gap).getGapExtend(), mode);
        else if (gap instanceof LinearGapCostFunction)
            aligner = new LongAligner<CharSequence>(scoring, ((LinearGapCostFunction) gap).getGap(), mode);
        else if (gap instanceof InfiniteGapCostFunction)
            aligner = new LongAligner<CharSequence>(scoring, mode);
        else
            throw new RuntimeException("Gap cost function " + gap.toString() + " currently not supported!");

        SimpleAlignmentFormatter formatter = cmd.hasOption('f')
                ? new SimpleAlignmentFormatter().setAppendUnaligned(!cmd.hasOption("noflank"))
                : null;

        CheckScore checkscore = cmd.hasOption('c') ? new CheckScore() : null;
        Alignment alignment = checkscore != null || formatter != null ? new Alignment() : null;

        float score;
        String ali;
        LineOrientedFile out = new LineOrientedFile(
                cmd.hasOption('o') ? cmd.getOptionValue('o') : LineOrientedFile.STDOUT);
        Writer wr = out.startWriting();

        while (idIterator.hasNext()) {
            MutablePair<String, String> ids = idIterator.next();

            score = alignment == null ? aligner.alignCache(ids.Item1, ids.Item2)
                    : aligner.alignCache(ids.Item1, ids.Item2, alignment);
            ali = formatter != null ? formatter.format(alignment, scoring, gap, mode,
                    scoring.getCachedSubject(ids.Item1), scoring.getCachedSubject(ids.Item2)) : "";
            out.writeLine(String.format(Locale.US, format, ids.Item1, ids.Item2, score, ali));

            if (cmd.hasOption("matrix")) {
                aligner.writeMatrix(wr,
                        aligner.getScoring().getCachedSubject(ids.Item1).toString().toCharArray(),
                        aligner.getScoring().getCachedSubject(ids.Item2).toString().toCharArray());
            }

            if (checkscore != null)
                checkscore.checkScore(aligner, scoring.getCachedSubject(ids.Item1).length(),
                        scoring.getCachedSubject(ids.Item2).length(), alignment, score);

        }

        out.finishWriting();

    } catch (ParseException e) {
        e.printStackTrace();
        HelpFormatter f = new HelpFormatter();
        f.printHelp("Align", options);
    }
}

From source file:Jimbo.Cheerlights.TweetListener.java

/**
 * @param args the command line arguments
 * @throws twitter4j.TwitterException//from  w  ww .  ja v  a2 s  . co m
 * @throws java.io.IOException
 * @throws org.apache.commons.cli.ParseException In case of command line error
 */
public static void main(String[] args) throws TwitterException, IOException, ParseException {
    // Set up simpler logging to stdout
    Jimbo.Logging.Logging.useStdout();

    LOG.log(Level.INFO, "Starting twitter listener");

    Options options = new Options();

    options.addOption("b", Listener.MQTT_BROKER_KEY, true, "URL of the broker")
            .addOption("c", Listener.MQTT_CLIENT_KEY, true, "The MQTT client name to use")
            .addOption("t", Listener.MQTT_TOPIC_KEY, true, "The MQTT topic to use");

    CommandLineParser parser = new DefaultParser();
    CommandLine command = parser.parse(options, args);

    MQTTClient mqtt = null;
    String mqtt_topic = Listener.DEFAULT_MQTT_TOPIC;

    if (command.hasOption(Listener.MQTT_BROKER_KEY)) {
        if (!command.hasOption(Listener.MQTT_CLIENT_KEY))
            throw new ParseException("MQTT without client name");

        if (command.hasOption(Listener.MQTT_TOPIC_KEY))
            mqtt_topic = command.getOptionValue(Listener.MQTT_TOPIC_KEY);

        try {
            mqtt = new MQTTClient(command.getOptionValue(Listener.MQTT_BROKER_KEY),
                    command.getOptionValue(Listener.MQTT_CLIENT_KEY));
            mqtt.run();
        }

        catch (MqttException e) {
            LOG.log(Level.WARNING, "Failed to create MQTT client: {0}", e.toString());
        }
    } else {
        if (command.hasOption(Listener.MQTT_TOPIC_KEY))
            LOG.warning("MQTT topic supplied but no broker");

        if (command.hasOption(Listener.MQTT_CLIENT_KEY))
            LOG.warning("MQTT client name but no broker");
    }

    Twitter twitter = new TwitterFactory().getInstance();
    StatusListener listener = new listener("224.1.1.1", (short) 5123, mqtt, mqtt_topic);
    FilterQuery fq = new FilterQuery();

    String keywords[] = { "#cheerlights" };

    fq.track(keywords);

    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    twitterStream.addListener(listener);
    twitterStream.filter(fq);

    LOG.log(Level.INFO, "Up and running....");
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.KyanosGraphCreator.java

public static void main(String[] args) {
    Options options = new Options();

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input file");
    inputOpt.setArgs(1);/*from   w  w  w .ja  va2 s .co  m*/
    inputOpt.setRequired(true);

    Option outputOpt = OptionBuilder.create(OUT);
    outputOpt.setArgName("OUTPUT");
    outputOpt.setDescription("Output directory");
    outputOpt.setArgs(1);
    outputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    Option optFileOpt = OptionBuilder.create(OPTIONS_FILE);
    optFileOpt.setArgName("FILE");
    optFileOpt.setDescription("Properties file holding the options to be used in the Kyanos Resource");
    optFileOpt.setArgs(1);

    options.addOption(inputOpt);
    options.addOption(outputOpt);
    options.addOption(inClassOpt);
    options.addOption(optFileOpt);

    CommandLineParser parser = new PosixParser();

    try {

        PersistenceBackendFactoryRegistry.getFactories().put(NeoBlueprintsURI.NEO_GRAPH_SCHEME,
                new BlueprintsPersistenceBackendFactory());

        CommandLine commandLine = parser.parse(options, args);

        URI sourceUri = URI.createFileURI(commandLine.getOptionValue(IN));
        URI targetUri = NeoBlueprintsURI.createNeoGraphURI(new File(commandLine.getOptionValue(OUT)));

        Class<?> inClazz = KyanosGraphCreator.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();

        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi",
                new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("zxmi",
                new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap()
                .put(NeoBlueprintsURI.NEO_GRAPH_SCHEME, PersistentResourceFactory.eINSTANCE);

        Resource sourceResource = resourceSet.createResource(sourceUri);
        Map<String, Object> loadOpts = new HashMap<String, Object>();
        if ("zxmi".equals(sourceUri.fileExtension())) {
            loadOpts.put(XMIResource.OPTION_ZIP, Boolean.TRUE);
        }

        Runtime.getRuntime().gc();
        long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        LOG.log(Level.INFO, MessageFormat.format("Used memory before loading: {0}",
                MessageUtil.byteCountToDisplaySize(initialUsedMemory)));
        LOG.log(Level.INFO, "Loading source resource");
        sourceResource.load(loadOpts);
        LOG.log(Level.INFO, "Source resource loaded");
        Runtime.getRuntime().gc();
        long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        LOG.log(Level.INFO, MessageFormat.format("Used memory after loading: {0}",
                MessageUtil.byteCountToDisplaySize(finalUsedMemory)));
        LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}",
                MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory)));

        Resource targetResource = resourceSet.createResource(targetUri);

        Map<String, Object> saveOpts = new HashMap<String, Object>();

        if (commandLine.hasOption(OPTIONS_FILE)) {
            Properties properties = new Properties();
            properties.load(new FileInputStream(new File(commandLine.getOptionValue(OPTIONS_FILE))));
            for (final Entry<Object, Object> entry : properties.entrySet()) {
                saveOpts.put((String) entry.getKey(), (String) entry.getValue());
            }
        }
        List<StoreOption> storeOptions = new ArrayList<StoreOption>();
        storeOptions.add(BlueprintsResourceOptions.EStoreGraphOption.AUTOCOMMIT);
        saveOpts.put(BlueprintsResourceOptions.STORE_OPTIONS, storeOptions);
        targetResource.save(saveOpts);

        LOG.log(Level.INFO, "Start moving elements");
        targetResource.getContents().clear();
        targetResource.getContents().addAll(sourceResource.getContents());
        LOG.log(Level.INFO, "End moving elements");
        LOG.log(Level.INFO, "Start saving");
        targetResource.save(saveOpts);
        LOG.log(Level.INFO, "Saved");

        if (targetResource instanceof PersistentResourceImpl) {
            PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) targetResource);
        } else {
            targetResource.unload();
        }

    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:de.topobyte.livecg.LiveCG.java

public static void main(String[] args) {
    // @formatter:off
    Options options = new Options();
    OptionHelper.add(options, OPTION_CONFIG, true, false, "path", "config file");
    // @formatter:on

    CommandLineParser clp = new GnuParser();

    CommandLine line = null;//from w  w w.  j a  v a 2s. c  o m
    try {
        line = clp.parse(options, args);
    } catch (ParseException e) {
        System.err.println("Parsing command line failed: " + e.getMessage());
        new HelpFormatter().printHelp(HELP_MESSAGE, options);
        System.exit(1);
    }

    StringOption config = ArgumentHelper.getString(line, OPTION_CONFIG);
    if (config.hasValue()) {
        String configPath = config.getValue();
        LiveConfig.setPath(configPath);
    }

    Configuration configuration = PreferenceManager.getConfiguration();
    String lookAndFeel = configuration.getSelectedLookAndFeel();
    if (lookAndFeel == null) {
        lookAndFeel = UIManager.getSystemLookAndFeelClassName();
    }
    try {
        UIManager.setLookAndFeel(lookAndFeel);
    } catch (Exception e) {
        logger.error("error while setting look and feel '" + lookAndFeel + "': " + e.getClass().getSimpleName()
                + ", message: " + e.getMessage());
    }

    Content content = null;
    String filename = "res/presets/Startup.geom";

    String[] extra = line.getArgs();
    if (extra.length > 0) {
        filename = extra[0];
    }

    ContentReader reader = new ContentReader();
    InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream(filename);
    try {
        content = reader.read(input);
    } catch (Exception e) {
        logger.info("unable to load startup geometry file", e);
        logger.info("Exception: " + e.getClass().getSimpleName());
        logger.info("Message: " + e.getMessage());
    }

    final LiveCG runner = new LiveCG();
    final Content c = content;

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            runner.setup(true, c);
        }
    });
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            runner.frame.requestFocus();
        }
    });
}

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.");
    }/*  www .  jav  a2 s.  c o  m*/

    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;

    }

}