Example usage for java.lang StringBuilder append

List of usage examples for java.lang StringBuilder append

Introduction

In this page you can find the example usage for java.lang StringBuilder append.

Prototype

@Override
    public StringBuilder append(double d) 

Source Link

Usage

From source file:com.linkedin.pinotdruidbenchmark.DruidResponseTime.java

public static void main(String[] args) throws Exception {
    if (args.length != 4 && args.length != 5) {
        System.err.println(//w  w w. jav  a 2s.co m
                "4 or 5 arguments required: QUERY_DIR, RESOURCE_URL, WARM_UP_ROUNDS, TEST_ROUNDS, RESULT_DIR (optional).");
        return;
    }

    File queryDir = new File(args[0]);
    String resourceUrl = args[1];
    int warmUpRounds = Integer.parseInt(args[2]);
    int testRounds = Integer.parseInt(args[3]);
    File resultDir;
    if (args.length == 4) {
        resultDir = null;
    } else {
        resultDir = new File(args[4]);
        if (!resultDir.exists()) {
            if (!resultDir.mkdirs()) {
                throw new RuntimeException("Failed to create result directory: " + resultDir);
            }
        }
    }

    File[] queryFiles = queryDir.listFiles();
    assert queryFiles != null;
    Arrays.sort(queryFiles);

    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        HttpPost httpPost = new HttpPost(resourceUrl);
        httpPost.addHeader("content-type", "application/json");

        for (File queryFile : queryFiles) {
            StringBuilder stringBuilder = new StringBuilder();
            try (BufferedReader bufferedReader = new BufferedReader(new FileReader(queryFile))) {
                int length;
                while ((length = bufferedReader.read(CHAR_BUFFER)) > 0) {
                    stringBuilder.append(new String(CHAR_BUFFER, 0, length));
                }
            }
            String query = stringBuilder.toString();
            httpPost.setEntity(new StringEntity(query));

            System.out.println(
                    "--------------------------------------------------------------------------------");
            System.out.println("Running query: " + query);
            System.out.println(
                    "--------------------------------------------------------------------------------");

            // Warm-up Rounds
            System.out.println("Run " + warmUpRounds + " times to warm up...");
            for (int i = 0; i < warmUpRounds; i++) {
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                httpResponse.close();
                System.out.print('*');
            }
            System.out.println();

            // Test Rounds
            System.out.println("Run " + testRounds + " times to get response time statistics...");
            long[] responseTimes = new long[testRounds];
            long totalResponseTime = 0L;
            for (int i = 0; i < testRounds; i++) {
                long startTime = System.currentTimeMillis();
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                httpResponse.close();
                long responseTime = System.currentTimeMillis() - startTime;
                responseTimes[i] = responseTime;
                totalResponseTime += responseTime;
                System.out.print(responseTime + "ms ");
            }
            System.out.println();

            // Store result.
            if (resultDir != null) {
                File resultFile = new File(resultDir, queryFile.getName() + ".result");
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                try (BufferedInputStream bufferedInputStream = new BufferedInputStream(
                        httpResponse.getEntity().getContent());
                        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(resultFile))) {
                    int length;
                    while ((length = bufferedInputStream.read(BYTE_BUFFER)) > 0) {
                        bufferedWriter.write(new String(BYTE_BUFFER, 0, length));
                    }
                }
                httpResponse.close();
            }

            // Process response times.
            double averageResponseTime = (double) totalResponseTime / testRounds;
            double temp = 0;
            for (long responseTime : responseTimes) {
                temp += (responseTime - averageResponseTime) * (responseTime - averageResponseTime);
            }
            double standardDeviation = Math.sqrt(temp / testRounds);
            System.out.println("Average response time: " + averageResponseTime + "ms");
            System.out.println("Standard deviation: " + standardDeviation);
        }
    }
}

From source file:com.alibaba.jstorm.daemon.worker.Worker.java

/**
 * worker entrance/*from  www  .j a  v a  2  s .com*/
 * 
 * @param args
 */
@SuppressWarnings("rawtypes")
public static void main(String[] args) {
    if (args.length < 5) {
        StringBuilder sb = new StringBuilder();
        sb.append("The length of args is less than 5 ");
        for (String arg : args) {
            sb.append(arg + " ");
        }
        LOG.error(sb.toString());
        System.exit(-1);
    }

    StringBuilder sb = new StringBuilder();
    try {
        String topology_id = args[0];
        String supervisor_id = args[1];
        String port_str = args[2];
        String worker_id = args[3];
        String jar_path = args[4];

        killOldWorker(port_str);

        Map conf = Utils.readStormConfig();
        StormConfig.validate_distributed_mode(conf);

        JStormServerUtils.startTaobaoJvmMonitor();

        sb.append("topologyId:" + topology_id + ", ");
        sb.append("port:" + port_str + ", ");
        sb.append("workerId:" + worker_id + ", ");
        sb.append("jar_path:" + jar_path + "\n");

        WorkerShutdown sd = mk_worker(conf, null, topology_id, supervisor_id, Integer.parseInt(port_str),
                worker_id, jar_path);
        sd.join();

        LOG.info("Successfully shutdown worker " + sb.toString());
    } catch (Throwable e) {
        String errMsg = "Failed to create worker, " + sb.toString();
        LOG.error(errMsg, e);
        JStormUtils.halt_process(-1, errMsg);
    }
}

From source file:com.sun.faban.harness.util.CLI.java

/**
 * The first argument to the CLI is the action. It can be:<ul>
 * <li>pending</li>//from   w ww  .ja v a 2 s  .c  o  m
 * <li>status runId</li>
 * <li>submit benchmark profile configfile.xml</ul>
 * </ul>
 *
 * @param args The command line arguments.
 */
public static void main(String[] args) {

    if (args.length == 0) {
        printUsage();
        System.exit(1);
    }

    ArrayList<String> argList = new ArrayList<String>();
    // Do the getopt thing.
    char opt = (char) -1;
    String master = null;
    String user = null;
    String password = null;

    for (String arg : args) {
        if (arg.startsWith("-M")) {
            String optArg = arg.substring(2);
            if (optArg.length() == 0) {
                opt = 'M';
                continue;
            }
            master = optArg;
        } else if (arg.startsWith("-U")) {
            String optArg = arg.substring(2);
            if (optArg.length() == 0) {
                opt = 'U';
                continue;
            }
            user = optArg;
        } else if (arg.startsWith("-P")) {
            String optArg = arg.substring(2);
            if (optArg.length() == 0) {
                opt = 'P';
                continue;
            }
            password = optArg;
        } else if (opt != (char) -1) {
            switch (opt) {
            case 'M':
                master = arg;
                opt = (char) -1;
                break;
            case 'U':
                user = arg;
                opt = (char) -1;
                break;
            case 'P':
                password = arg;
                opt = (char) -1;
                break;
            }
        } else {
            argList.add(arg);
            opt = (char) -1;
        }
    }

    if (master == null)
        master = "http://localhost:9980/";
    else if (!master.endsWith("/"))
        master += '/';

    CLI cli = new CLI();
    String action = argList.get(0);

    try {
        if ("pending".equals(action)) {
            cli.doGet(master + "pending");
        } else if ("status".equals(action)) {
            if (argList.size() > 1)
                cli.doGet(master + "status/" + argList.get(1));
            else
                printUsage();
        } else if ("submit".equals(action)) {
            if (argList.size() > 3) {
                cli.doPostSubmit(master, user, password, argList);
            } else {
                printUsage();
                System.exit(1);
            }
        } else if ("kill".equals(action)) {
            if (argList.size() > 1) {
                cli.doPostKill(master, user, password, argList);
            } else {
                printUsage();
                System.exit(1);
            }
        } else if ("wait".equals(action)) {
            if (argList.size() > 1) {
                cli.pollStatus(master + "status/" + argList.get(1));
            } else {
                printUsage();
                System.exit(1);
            }
        } else if ("showlogs".equals(action)) {
            StringBuilder url = new StringBuilder();
            if (argList.size() > 1) {
                url.append(master).append("logs/");
                url.append(argList.get(1));
            } else {
                printUsage();
            }
            for (int i = 2; i < argList.size(); i++) {
                if ("-t".equals(argList.get(i)))
                    url.append("/tail");
                if ("-f".equals(argList.get(i)))
                    url.append("/follow");
                if ("-ft".equals(argList.get(i)))
                    url.append("/tail/follow");
                if ("-tf".equals(argList.get(i)))
                    url.append("/tail/follow");
            }
            cli.doGet(url.toString());
        } else {
            printUsage();
        }
    } catch (IOException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }
}

From source file:JALPTest.java

/**
 * The main method that gets called to test JALoP.
 *
 * @param args   the command line arguments
 *//*from   ww  w . j  a  va  2  s  .  co m*/
public static void main(String[] args) {
    Producer producer = null;
    try {
        Options options = createOptions();
        CommandLineParser parser = new PosixParser();
        CommandLine cmd = parser.parse(options, args);

        String pathToXML = null;
        String type = null;
        String input = null;
        String privateKeyPath = null;
        String publicKeyPath = null;
        String certPath = null;
        String socketPath = null;
        Boolean hasDigest = false;
        File file = null;
        ApplicationMetadataXML xml = null;

        if (cmd.hasOption("h")) {
            System.out.println(usage);
            return;
        }
        if (cmd.hasOption("a")) {
            pathToXML = cmd.getOptionValue("a");
        }
        if (cmd.hasOption("t")) {
            type = cmd.getOptionValue("t");
        }
        if (cmd.hasOption("p")) {
            file = new File(cmd.getOptionValue("p"));
        }
        if (cmd.hasOption("s")) {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            StringBuilder sb = new StringBuilder();
            String s;
            while ((s = in.readLine()) != null && s.length() != 0) {
                sb.append(s);
                sb.append("\n");
            }
            input = sb.toString();
        }
        if (cmd.hasOption("j")) {
            socketPath = cmd.getOptionValue("j");
        }
        if (cmd.hasOption("k")) {
            privateKeyPath = cmd.getOptionValue("k");
        }
        if (cmd.hasOption("b")) {
            publicKeyPath = cmd.getOptionValue("b");
        }
        if (cmd.hasOption("c")) {
            certPath = cmd.getOptionValue("c");
        }
        if (cmd.hasOption("d")) {
            hasDigest = true;
        }

        if (pathToXML != null) {
            xml = createXML(readXML(pathToXML));
        }

        producer = createProducer(xml, socketPath, privateKeyPath, publicKeyPath, certPath, hasDigest);
        callSend(producer, type, input, file);

    } catch (IOException e) {
        if (producer != null) {
            System.out.println("Failed to open socket: " + producer.getSocketFile());
        } else {
            System.out.println("Failed to create Producer");
        }
    } catch (Exception e) {
        error(e.toString());
        return;
    }
}

From source file:microbiosima.SelectiveMicrobiosima.java

/**
 * @param args/* w  w  w  . j  a v  a  2s.c  o m*/
 *            the command line arguments
 * @throws java.io.FileNotFoundException
 * @throws java.io.UnsupportedEncodingException
 */

public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
    int populationSize = 500;//Integer.parseInt(parameters[1]);
    int microSize = 1000;//Integer.parseInt(parameters[2]);
    int numberOfSpecies = 150;//Integer.parseInt(parameters[3]);
    int numberOfGeneration = 10000;
    int Ngene = 10;
    int numberOfObservation = 100;
    int numberOfReplication = 10;
    double Ngenepm = 5;
    double pctEnv = 0;
    double pctPool = 0;
    double msCoeff = 1;
    double hsCoeff = 1;
    boolean HMS_or_TMS = true;

    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(6).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, (5) number of total traits, (6)number of traits per microbe"
                    + " [default: 500 1000 150 10000 10 5]");
    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"
            + "  msCoeff            Parameter related to microbe selection strength\n"
            + "  hsCoeff            Parameter related to host selection strength\n"
            + "  HMS_or_TMS         String HMS or TMS to specify host-mediated or trait-mediated microbe selection\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 != 5) {
            System.out.println(
                    "ERROR! Required exactly five argumennts for pct_env, pct_pool, msCoeff, hsCoeff and HMS_or_TMS. 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]);
            msCoeff = Double.parseDouble(pct_config[2]);
            hsCoeff = Double.parseDouble(pct_config[3]);
            if (pct_config[4].equals("HMS"))
                HMS_or_TMS = true;
            if (pct_config[4].equals("TMS"))
                HMS_or_TMS = false;
            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 (msCoeff < 1) {
                System.out.println(
                        "ERROR: msCoeff (parameter related to microbe selection strength) must be not less than 1 (msCoeff="
                                + msCoeff + ")! EXIT");
                System.exit(3);
            }
            if (hsCoeff < 1) {
                System.out.println(
                        "ERROR: hsCoeff (parameter related to host selection strength) must be not less than 1 (hsCoeff="
                                + hsCoeff + ")! EXIT");
                System.exit(3);
            }
            if (!(pct_config[4].equals("HMS") || pct_config[4].equals("TMS"))) {
                System.out.println(
                        "ERROR: HMS_or_TMS (parameter specifying host-mediated or trait-mediated selection) must be either 'HMS' or 'TMS' (HMS_or_TMS="
                                + pct_config[4] + ")! 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]);
            Ngene = Integer.parseInt(configs[4]);
            Ngenepm = Double.parseDouble(configs[5]);
            if (Ngenepm > Ngene) {
                System.out.println(
                        "ERROR: number of traits per microbe must not be greater than number of total traits! EXIT");
                System.exit(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\tNumber of total traits: ").append(Ngene).append("\n\tNumber of traits per microbe: ")
            .append(Ngenepm).append("\n");
    System.out.println(sb.toString());

    double[] environment = new double[numberOfSpecies];
    for (int i = 0; i < numberOfSpecies; i++) {
        environment[i] = 1 / (double) numberOfSpecies;
    }
    int[] fitnessToHost = new int[Ngene];
    int[] fitnessToMicrobe = new int[Ngene];

    for (int rep = 0; rep < numberOfReplication; rep++) {
        String prefix = "" + (rep + 1) + "_";
        String sufix;
        if (HMS_or_TMS)
            sufix = "_E" + pctEnv + "_P" + pctPool + "_HS" + hsCoeff + "_HMS" + msCoeff + ".txt";
        else
            sufix = "_E" + pctEnv + "_P" + pctPool + "_HS" + hsCoeff + "_TMS" + msCoeff + ".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)));
            PrintWriter file7 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "host_fitness" + sufix)));
            PrintWriter file8 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "cos_theta" + sufix)));
            PrintWriter file9 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "host_fitness_distribution" + sufix)));
            PrintWriter file10 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "microbiome_fitness_distribution" + sufix)));
            PrintWriter file11 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "bacteria_contents" + sufix)));
            PrintWriter file12 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "individual_bacteria_contents" + sufix)));
            for (int i = 0; i < Ngene; i++) {
                fitnessToMicrobe[i] = MathUtil.getNextInt(2) - 1;
                fitnessToHost[i] = MathUtil.getNextInt(2) - 1;
            }
            MathUtil.setSeed(rep % numberOfReplication);
            SelectiveSpeciesRegistry ssr = new SelectiveSpeciesRegistry(numberOfSpecies, Ngene, Ngenepm,
                    msCoeff, fitnessToHost, fitnessToMicrobe);
            MathUtil.setSeed();
            SelectivePopulation population = new SelectivePopulation(microSize, environment, populationSize,
                    pctEnv, pctPool, 0, 0, ssr, hsCoeff, HMS_or_TMS);

            while (population.getNumberOfGeneration() < numberOfGeneration) {
                population.sumSpecies();
                if (population.getNumberOfGeneration() % numberOfObservation == 0) {
                    //file1.print(population.gammaDiversity(false));
                    //file2.print(population.alphaDiversity(false));
                    //file1.print("\t");
                    //file2.print("\t");
                    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());
                    file7.print(population.averageHostFitness());
                    file7.print("\t");
                    file7.println(population.varianceHostFitness());
                    file8.println(population.cosOfMH());
                    file9.println(population.printOutHFitness());
                    file10.println(population.printOutMFitness());
                    file11.println(population.printBacteriaContents());
                }
                population.getNextGen();
            }
            for (SelectiveIndividual host : population.getIndividuals()) {
                file12.println(host.printBacteriaContents());
            }
            file1.close();
            file2.close();
            file3.close();
            file4.close();
            file5.close();
            file6.close();
            file7.close();
            file8.close();
            file9.close();
            file10.close();
            file11.close();
            file12.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.genentech.chemistry.tool.mm.SDFMMMinimize.java

/**
 * Main function for running on the command line
 * @param args/*from ww w  .ja va 2s. co m*/
 */
public static void main(String... args) throws IOException {
    // Get the available options from the programs
    Map<String, List<String>> allowedProgramsAndForceFields = getAllowedProgramsAndForceFields();
    Map<String, List<String>> allowedProgramsAndSolvents = getAllowedProgramsAndSolvents();

    // 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);
    options.addOption(opt);

    opt = new Option(OPT_OUTFILE, true, "output file oe-supported. Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    StringBuilder programOptions = new StringBuilder("Program to use for minimization.  Choices are\n");

    for (String program : allowedProgramsAndForceFields.keySet()) {
        programOptions.append("\n***   -program " + program + "   ***\n");
        String forcefields = "";
        for (String option : allowedProgramsAndForceFields.get(program)) {
            forcefields += option + " ";
        }
        programOptions.append("-forcefield " + forcefields + "\n");

        String solvents = "";
        for (String option : allowedProgramsAndSolvents.get(program)) {
            solvents += option + " ";
        }
        programOptions.append("-solvent " + solvents + "\n");
    }

    opt = new Option(OPT_PROGRAM, true, programOptions.toString());
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_FORCEFIELD, true, "Forcefield options.  See -program for choices");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_SOLVENT, true, "Solvent options.  See -program for choices");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_FIXED_ATOM_TAG, true, "SD tag name which contains the atom numbers to be held fixed.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_FIX_TORSION, true,
            "true/false. if true, the atoms in fixedAtomTag contains 4 indices of atoms defining a torsion angle to be held fixed");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_WORKING_DIR, true, "Working directory to put files.");
    opt.setRequired(false);
    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 (args.length != 0) {
        System.err.println("Unknown arguments" + args);
        exitWithHelp(options);
    }

    if (cmd.hasOption("d")) {
        System.err.println("Start debugger and press return:");
        new BufferedReader(new InputStreamReader(System.in)).readLine();
    }

    String inFile = cmd.getOptionValue(OPT_INFILE);
    String outFile = cmd.getOptionValue(OPT_OUTFILE);
    String fixedAtomTag = cmd.getOptionValue(OPT_FIXED_ATOM_TAG);
    boolean fixTorsion = (cmd.getOptionValue(OPT_FIX_TORSION) != null
            && cmd.getOptionValue(OPT_FIX_TORSION).equalsIgnoreCase("true"));
    String programName = cmd.getOptionValue(OPT_PROGRAM);
    String forcefield = cmd.getOptionValue(OPT_FORCEFIELD);
    String solvent = cmd.getOptionValue(OPT_SOLVENT);
    String workDir = cmd.getOptionValue(OPT_WORKING_DIR);

    if (workDir == null || workDir.trim().length() == 0)
        workDir = ".";

    // Create a minimizer 
    SDFMMMinimize minimizer = new SDFMMMinimize();
    minimizer.setMethod(programName, forcefield, solvent);
    minimizer.run(inFile, outFile, fixedAtomTag, fixTorsion, workDir);
    minimizer.close();
    System.err.println("Minimization complete.");
}

From source file:org.eclipse.swt.snippets.Snippet373.java

@SuppressWarnings("restriction")
public static void main(String[] args) {
    System.setProperty("swt.autoScale", "quarter");
    Display display = new Display();
    final Image eclipse = new Image(display, filenameProvider);
    final Image eclipseToolBar1 = new Image(display, filenameProvider);
    final Image eclipseToolBar2 = new Image(display, filenameProvider);
    final Image eclipseTableHeader = new Image(display, filenameProvider);
    final Image eclipseTableItem = new Image(display, filenameProvider);
    final Image eclipseTree1 = new Image(display, filenameProvider);
    final Image eclipseTree2 = new Image(display, filenameProvider);
    final Image eclipseCTab1 = new Image(display, filenameProvider);
    final Image eclipseCTab2 = new Image(display, filenameProvider);

    Shell shell = new Shell(display);
    shell.setText("Snippet 373");
    shell.setImage(eclipse);/*from   w  ww . j a va2 s. c  om*/
    shell.setText("DynamicDPI @ " + DPIUtil.getDeviceZoom());
    shell.setLayout(new RowLayout(SWT.VERTICAL));
    shell.setLocation(100, 100);
    shell.setSize(500, 600);
    shell.addListener(SWT.ZoomChanged, new Listener() {
        @Override
        public void handleEvent(Event e) {
            if (display.getPrimaryMonitor().equals(shell.getMonitor())) {
                MessageBox box = new MessageBox(shell, SWT.PRIMARY_MODAL | SWT.OK | SWT.CANCEL);
                box.setText(shell.getText());
                box.setMessage("DPI changed, do you want to exit & restart ?");
                e.doit = (box.open() == SWT.OK);
                if (e.doit) {
                    shell.close();
                    System.out.println("Program exit.");
                }
            }
        }
    });

    // Menu
    Menu bar = new Menu(shell, SWT.BAR);
    shell.setMenuBar(bar);
    MenuItem fileItem = new MenuItem(bar, SWT.CASCADE);
    fileItem.setText("&File");
    fileItem.setImage(eclipse);
    Menu submenu = new Menu(shell, SWT.DROP_DOWN);
    fileItem.setMenu(submenu);
    MenuItem subItem = new MenuItem(submenu, SWT.PUSH);
    subItem.addListener(SWT.Selection, e -> System.out.println("Select All"));
    subItem.setText("Select &All\tCtrl+A");
    subItem.setAccelerator(SWT.MOD1 + 'A');
    subItem.setImage(eclipse);

    // CTabFolder
    CTabFolder folder = new CTabFolder(shell, SWT.BORDER);
    for (int i = 0; i < 2; i++) {
        CTabItem cTabItem = new CTabItem(folder, i % 2 == 0 ? SWT.CLOSE : SWT.NONE);
        cTabItem.setText("Item " + i);
        Text textMsg = new Text(folder, SWT.MULTI);
        textMsg.setText("Content for Item " + i);
        cTabItem.setControl(textMsg);
        cTabItem.setImage((i % 2 == 1) ? eclipseCTab1 : eclipseCTab2);
    }

    // PerMonitorV2 setting
    //      Label label = new Label (shell, SWT.BORDER);
    //      label.setText("PerMonitorV2 value before:after:Error");
    //      Text text = new Text(shell, SWT.BORDER);
    //      text.setText(DPIUtil.BEFORE + ":" + DPIUtil.AFTER + ":" + DPIUtil.RESULT);

    // Composite for Label, Button, Tool-bar
    Composite composite = new Composite(shell, SWT.BORDER);
    composite.setLayout(new RowLayout(SWT.HORIZONTAL));

    // Label with Image
    Label label1 = new Label(composite, SWT.BORDER);
    label1.setImage(eclipse);

    // Label with text only
    Label label2 = new Label(composite, SWT.BORDER);
    label2.setText("No Image");

    // Button with text + Old Image Constructor
    Button oldButton1 = new Button(composite, SWT.PUSH);
    oldButton1.setText("Old Img");
    oldButton1.setImage(new Image(display, IMAGE_PATH_100));

    // Button with Old Image Constructor
    //      Button oldButton2 = new Button(composite, SWT.PUSH);
    //      oldButton2.setImage(new Image(display, filenameProvider.getImagePath(100)));

    // Button with Image
    Button createDialog = new Button(composite, SWT.PUSH);
    createDialog.setText("Child Dialog");
    createDialog.setImage(eclipse);
    createDialog.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent event) {
            final Shell dialog = new Shell(shell, SWT.DIALOG_TRIM | SWT.RESIZE);
            dialog.setText("Child Dialog");
            RowLayout rowLayout = new RowLayout(SWT.VERTICAL);
            dialog.setLayout(rowLayout);
            Label label = new Label(dialog, SWT.BORDER);
            label.setImage(eclipse);
            Point location = shell.getLocation();
            dialog.setLocation(location.x + 250, location.y + 50);
            dialog.pack();
            dialog.open();
        }
    });

    // Toolbar with Image
    ToolBar toolBar = new ToolBar(composite, SWT.FLAT | SWT.BORDER);
    Rectangle clientArea = shell.getClientArea();
    toolBar.setLocation(clientArea.x, clientArea.y);
    for (int i = 0; i < 2; i++) {
        int style = i % 2 == 1 ? SWT.DROP_DOWN : SWT.PUSH;
        ToolItem toolItem = new ToolItem(toolBar, style);
        toolItem.setImage((i % 2 == 0) ? eclipseToolBar1 : eclipseToolBar2);
        toolItem.setEnabled(i % 2 == 0);
    }
    toolBar.pack();

    Button button = new Button(shell, SWT.PUSH);
    button.setText("Refresh-Current Monitor : Zoom");
    Text text1 = new Text(shell, SWT.BORDER);
    Monitor monitor = button.getMonitor();
    text1.setText("" + monitor.getZoom());
    button.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseDown(MouseEvent e) {
            Monitor monitor = button.getMonitor();
            text1.setText("" + monitor.getZoom());
        }
    });
    Button button2 = new Button(shell, SWT.PUSH);
    button2.setText("Refresh-Both Monitors : Zoom");
    Text text2 = new Text(shell, SWT.BORDER);
    Monitor[] monitors = display.getMonitors();
    StringBuilder text2String = new StringBuilder();
    for (int i = 0; i < monitors.length; i++) {
        text2String.append(monitors[i].getZoom() + (i < (monitors.length - 1) ? " - " : ""));
    }
    text2.setText(text2String.toString());
    button2.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseDown(MouseEvent e) {
            Monitor[] monitors = display.getMonitors();
            StringBuilder text2String = new StringBuilder();
            for (int i = 0; i < monitors.length; i++) {
                text2String.append(monitors[i].getZoom() + (i < (monitors.length - 1) ? " - " : ""));
            }
            text2.setText(text2String.toString());
        }
    });

    // Table
    Table table = new Table(shell, SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION);
    table.setLinesVisible(true);
    table.setHeaderVisible(true);
    String titles[] = { "Title 1" };
    for (int i = 0; i < titles.length; i++) {
        TableColumn column = new TableColumn(table, SWT.NONE);
        column.setText(titles[i]);
        column.setImage(eclipseTableHeader);
    }
    for (int i = 0; i < 1; i++) {
        TableItem item = new TableItem(table, SWT.NONE);
        item.setText(0, "Data " + i);
        item.setImage(0, eclipseTableItem);
    }
    for (int i = 0; i < titles.length; i++) {
        table.getColumn(i).pack();
    }

    // Tree
    final Tree tree = new Tree(shell, SWT.BORDER);
    for (int i = 0; i < 1; i++) {
        TreeItem iItem = new TreeItem(tree, 0);
        iItem.setText("TreeItem (0) -" + i);
        iItem.setImage(eclipseTree1);
        TreeItem jItem = null;
        for (int j = 0; j < 1; j++) {
            jItem = new TreeItem(iItem, 0);
            jItem.setText("TreeItem (1) -" + j);
            jItem.setImage(eclipseTree2);
            jItem.setExpanded(true);
        }
        tree.select(jItem);
    }

    // Shell Location
    Monitor primary = display.getPrimaryMonitor();
    Rectangle bounds = primary.getBounds();
    Rectangle rect = shell.getBounds();
    int x = bounds.x + (bounds.width - rect.width) / 2;
    int y = bounds.y + (bounds.height - rect.height) / 2;
    shell.setLocation(x, y);
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:de.citec.csra.elancsv.parser.SimpleParser.java

public static void main(String[] args) throws IOException, ParseException {

    Options opts = new Options();
    opts.addOption("file", true, "Tab-separated ELAN export file to load.");
    opts.addOption("tier", true,
            "Tier to analyze. Optional: Append ::num to interpret annotations numerically.");
    opts.addOption("format", true,
            "How to read information from the file name. %V -> participant, %A -> annoatator, %C -> condition, e.g. \"%V - %A\"");
    opts.addOption("help", false, "Print this help and exit");

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(opts, args);
    if (cmd.hasOption("help")) {
        helpExit(opts, "where OPTION includes:");
    }/*from  w w  w .jav  a2 s. c  om*/

    String infile = cmd.getOptionValue("file");
    if (infile == null) {
        helpExit(opts, "Error: no file given.");
    }

    String format = cmd.getOptionValue("format");
    if (format == null) {
        helpExit(opts, "Error: no format given.");
    }

    String tier = cmd.getOptionValue("tier");
    if (tier == null) {
        helpExit(opts, "Error: no tier given.");
    }

    //      TODO count values in annotations (e.g. search all robot occurrences)
    String[] tn = tier.split("::");
    boolean numeric = false;
    if (tn.length == 2 && tn[1].equals("num")) {
        numeric = true;
        tier = tn[0];
    }

    format = "^" + format + "$";
    format = format.replaceFirst("%V", "(?<V>.*?)");
    format = format.replaceFirst("%A", "(?<A>.*?)");
    format = format.replaceFirst("%C", "(?<C>.*?)");
    Pattern pa = Pattern.compile(format);

    Map<String, Participant> participants = new HashMap<>();
    BufferedReader br = new BufferedReader(new FileReader(infile));
    String line;
    int lineno = 0;
    while ((line = br.readLine()) != null) {
        String[] parts = line.split("\t");
        lineno++;
        if (parts.length < 5) {
            System.err.println("WARNING: line '" + lineno + "' too short '" + line + "'");
            continue;
        }
        Annotation a = new Annotation(Long.valueOf(parts[ElanFormat.START.field]),
                Long.valueOf(parts[ElanFormat.STOP.field]), Long.valueOf(parts[ElanFormat.DURATION.field]),
                parts[ElanFormat.VALUE.field]);
        String tname = parts[ElanFormat.TIER.field];
        String file = parts[ElanFormat.FILE.field].replaceAll(".eaf", "");

        Matcher m = pa.matcher(file);
        String vp = file;
        String condition = "?";
        String annotator = "?";
        String participantID = vp;

        if (m.find()) {
            vp = m.group("V");
            if (format.indexOf("<A>") > 0) {
                annotator = m.group("A");
            }

            if (format.indexOf("<C>") > 0) {
                condition = m.group("C");
            }
        }
        participantID = vp + ";" + annotator;

        if (!participants.containsKey(participantID)) {
            participants.put(participantID, new Participant(vp, condition, annotator));
        }
        Participant p = participants.get(participantID);

        if (!p.tiers.containsKey(tname)) {
            p.tiers.put(tname, new Tier(tname));
        }

        p.tiers.get(tname).annotations.add(a);

    }

    Map<String, Map<String, Number>> values = new HashMap<>();
    Set<String> rownames = new HashSet<>();

    String allCountKey = "c: all values";
    String allDurationKey = "d: all values";
    String allMeanKey = "m: all values";

    for (Map.Entry<String, Participant> e : participants.entrySet()) {
        //         System.out.println(e);
        Tier t = e.getValue().tiers.get(tier);
        String participantID = e.getKey();

        if (!values.containsKey(participantID)) {
            values.put(participantID, new HashMap<String, Number>());
        }
        Map<String, Number> row = values.get(participantID); //participant id

        if (t != null) {

            row.put(allCountKey, 0l);
            row.put(allDurationKey, 0l);
            row.put(allMeanKey, 0l);

            for (Annotation a : t.annotations) {

                long countAll = (long) row.get(allCountKey) + 1;
                long durationAll = (long) row.get(allDurationKey) + a.duration;
                long meanAll = durationAll / countAll;

                row.put(allCountKey, countAll);
                row.put(allDurationKey, durationAll);
                row.put(allMeanKey, meanAll);

                if (!numeric) {
                    String countKey = "c: " + a.value;
                    String durationKey = "d: " + a.value;
                    String meanKey = "m: " + a.value;

                    if (!row.containsKey(countKey)) {
                        row.put(countKey, 0l);
                    }
                    if (!row.containsKey(durationKey)) {
                        row.put(durationKey, 0l);
                    }
                    if (!row.containsKey(meanKey)) {
                        row.put(meanKey, 0d);
                    }

                    long count = (long) row.get(countKey) + 1;
                    long duration = (long) row.get(durationKey) + a.duration;
                    double mean = duration * 1.0 / count;

                    row.put(countKey, count);
                    row.put(durationKey, duration);
                    row.put(meanKey, mean);

                    rownames.add(countKey);
                    rownames.add(durationKey);
                    rownames.add(meanKey);
                } else {
                    String countKey = "c: " + t.name;
                    String sumKey = "s: " + t.name;
                    String meanKey = "m: " + t.name;

                    if (!row.containsKey(countKey)) {
                        row.put(countKey, 0l);
                    }
                    if (!row.containsKey(sumKey)) {
                        row.put(sumKey, 0d);
                    }
                    if (!row.containsKey(meanKey)) {
                        row.put(meanKey, 0d);
                    }

                    double d = 0;
                    try {
                        d = Double.valueOf(a.value);
                    } catch (NumberFormatException ex) {

                    }

                    long count = (long) row.get(countKey) + 1;
                    double sum = (double) row.get(sumKey) + d;
                    double mean = sum / count;

                    row.put(countKey, count);
                    row.put(sumKey, sum);
                    row.put(meanKey, mean);

                    rownames.add(countKey);
                    rownames.add(sumKey);
                    rownames.add(meanKey);
                }

            }
        }

    }

    ArrayList<String> list = new ArrayList(rownames);
    Collections.sort(list);
    StringBuilder header = new StringBuilder("ID;Annotator;");
    header.append(allCountKey);
    header.append(";");
    header.append(allDurationKey);
    header.append(";");
    header.append(allMeanKey);
    header.append(";");
    for (String l : list) {
        header.append(l);
        header.append(";");
    }
    System.out.println(header);

    for (Map.Entry<String, Map<String, Number>> e : values.entrySet()) {
        StringBuilder row = new StringBuilder(e.getKey());
        row.append(";");
        if (e.getValue().containsKey(allCountKey)) {
            row.append(e.getValue().get(allCountKey));
        } else {
            row.append("0");
        }
        row.append(";");
        if (e.getValue().containsKey(allDurationKey)) {
            row.append(e.getValue().get(allDurationKey));
        } else {
            row.append("0");
        }
        row.append(";");
        if (e.getValue().containsKey(allMeanKey)) {
            row.append(e.getValue().get(allMeanKey));
        } else {
            row.append("0");
        }
        row.append(";");
        for (String l : list) {
            if (e.getValue().containsKey(l)) {
                row.append(e.getValue().get(l));
            } else {
                row.append("0");
            }
            row.append(";");
        }
        System.out.println(row);
    }
}

From source file:marytts.tools.analysis.CopySynthesis.java

/**
 * @param args/*ww  w.  j  a  v  a  2s. c o  m*/
 */
public static void main(String[] args) throws Exception {
    String wavFilename = null;
    String labFilename = null;
    String pitchFilename = null;
    String textFilename = null;

    String locale = System.getProperty("locale");
    if (locale == null) {
        throw new IllegalArgumentException("No locale given (-Dlocale=...)");
    }

    for (String arg : args) {
        if (arg.endsWith(".txt"))
            textFilename = arg;
        else if (arg.endsWith(".wav"))
            wavFilename = arg;
        else if (arg.endsWith(".ptc"))
            pitchFilename = arg;
        else if (arg.endsWith(".lab"))
            labFilename = arg;
        else
            throw new IllegalArgumentException("Don't know how to treat argument: " + arg);
    }

    // The intonation contour
    double[] contour = null;
    double frameShiftTime = -1;
    if (pitchFilename == null) { // need to create pitch contour from wav file 
        if (wavFilename == null) {
            throw new IllegalArgumentException("Need either a pitch file or a wav file");
        }
        AudioInputStream ais = AudioSystem.getAudioInputStream(new File(wavFilename));
        AudioDoubleDataSource audio = new AudioDoubleDataSource(ais);
        PitchFileHeader params = new PitchFileHeader();
        params.fs = (int) ais.getFormat().getSampleRate();
        F0TrackerAutocorrelationHeuristic tracker = new F0TrackerAutocorrelationHeuristic(params);
        tracker.pitchAnalyze(audio);
        frameShiftTime = tracker.getSkipSizeInSeconds();
        contour = tracker.getF0Contour();
    } else { // have a pitch file -- ignore any wav file
        PitchReaderWriter f0rw = new PitchReaderWriter(pitchFilename);
        if (f0rw.contour == null) {
            throw new NullPointerException("Cannot read f0 contour from " + pitchFilename);
        }
        contour = f0rw.contour;
        frameShiftTime = f0rw.header.skipSizeInSeconds;
    }
    assert contour != null;
    assert frameShiftTime > 0;

    // The ALLOPHONES data and labels
    if (labFilename == null) {
        throw new IllegalArgumentException("No label file given");
    }
    if (textFilename == null) {
        throw new IllegalArgumentException("No text file given");
    }
    MaryTranscriptionAligner aligner = new MaryTranscriptionAligner();
    aligner.SetEnsureInitialBoundary(false);
    String labels = MaryTranscriptionAligner.readLabelFile(aligner.getEntrySeparator(),
            aligner.getEnsureInitialBoundary(), labFilename);
    MaryHttpClient mary = new MaryHttpClient();
    String text = FileUtils.readFileToString(new File(textFilename), "ASCII");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    mary.process(text, "TEXT", "ALLOPHONES", locale, null, null, baos);
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setNamespaceAware(true);
    DocumentBuilder builder = docFactory.newDocumentBuilder();
    Document doc = builder.parse(bais);
    aligner.alignXmlTranscriptions(doc, labels);
    assert doc != null;

    // durations
    double[] endTimes = new LabelfileDoubleDataSource(new File(labFilename)).getAllData();
    assert endTimes.length == labels.split(Pattern.quote(aligner.getEntrySeparator())).length;

    // Now add durations and f0 targets to document
    double prevEnd = 0;
    NodeIterator ni = MaryDomUtils.createNodeIterator(doc, MaryXML.PHONE, MaryXML.BOUNDARY);
    for (int i = 0; i < endTimes.length; i++) {
        Element e = (Element) ni.nextNode();
        if (e == null)
            throw new IllegalStateException("More durations than elements -- this should not happen!");
        double durInSeconds = endTimes[i] - prevEnd;
        int durInMillis = (int) (1000 * durInSeconds);
        if (e.getTagName().equals(MaryXML.PHONE)) {
            e.setAttribute("d", String.valueOf(durInMillis));
            e.setAttribute("end", new Formatter(Locale.US).format("%.3f", endTimes[i]).toString());
            // f0 targets at beginning, mid, and end of phone
            StringBuilder f0String = new StringBuilder();
            double startF0 = getF0(contour, frameShiftTime, prevEnd);
            if (startF0 != 0 && !Double.isNaN(startF0)) {
                f0String.append("(0,").append((int) startF0).append(")");
            }
            double midF0 = getF0(contour, frameShiftTime, prevEnd + 0.5 * durInSeconds);
            if (midF0 != 0 && !Double.isNaN(midF0)) {
                f0String.append("(50,").append((int) midF0).append(")");
            }
            double endF0 = getF0(contour, frameShiftTime, endTimes[i]);
            if (endF0 != 0 && !Double.isNaN(endF0)) {
                f0String.append("(100,").append((int) endF0).append(")");
            }
            if (f0String.length() > 0) {
                e.setAttribute("f0", f0String.toString());
            }
        } else { // boundary
            e.setAttribute("duration", String.valueOf(durInMillis));
        }
        prevEnd = endTimes[i];
    }
    if (ni.nextNode() != null) {
        throw new IllegalStateException("More elements than durations -- this should not happen!");
    }

    // TODO: add pitch values

    String acoustparams = DomUtils.document2String(doc);
    System.out.println("ACOUSTPARAMS:");
    System.out.println(acoustparams);
}

From source file:gov.nih.nci.caaersinstaller.util.CsmJaasFileCopier.java

public static void main(String args[]) throws Exception {

    //      File csmJaasTemplateFile = new File("/Users/Moni/temp/installer/postgres.csm_jaas.config");
    //      File csmJassConfigFile = new File("/Users/Moni/temp/installer/csm_jaas.config");

    File csmJaasTemplateFile = new File(args[0]);
    File csmJassConfigFile = new File(args[1]);

    if (csmJassConfigFile.exists()) {
        //append content of csmJaasTemplateFile to existing csmJaasConfigFile
        String csmJaasTemplateFileContent = FileUtils.readFileToString(csmJaasTemplateFile);
        StringBuilder stringBuilder = new StringBuilder(FileUtils.readFileToString(csmJassConfigFile));

        int start = stringBuilder.indexOf("caaers {");
        if (start != -1) {
            //If caaers context exisits then replace it.
            int end = stringBuilder.indexOf("};", start);
            end = end + 2;/*  w w  w.j  av  a  2 s  . c o m*/
            stringBuilder.replace(start, end, csmJaasTemplateFileContent);
        } else {
            //if caaers context does not exist then add it 
            stringBuilder.append("\n");
            stringBuilder.append("\n");
            stringBuilder.append(csmJaasTemplateFileContent);
        }

        FileUtils.writeStringToFile(csmJassConfigFile, stringBuilder.toString());
        System.out.println("Modified csm_jaas.config to add caaers context");

    } else {
        //Create a new File with Contents of csmJaasTemplateFile
        FileUtils.copyFile(csmJaasTemplateFile, csmJassConfigFile);
        System.out.println("Created csm_jaas.config");

    }
}