Example usage for java.util Scanner nextLine

List of usage examples for java.util Scanner nextLine

Introduction

In this page you can find the example usage for java.util Scanner nextLine.

Prototype

public String nextLine() 

Source Link

Document

Advances this scanner past the current line and returns the input that was skipped.

Usage

From source file:languages.TabFile.java

public static void main(String[] args) {
    if (args[0].equals("optimize")) {
        Scanner sc = new Scanner(System.in);
        String targetPath;/*from   w  w w  . j a  va 2s . c o  m*/
        String originPath;

        System.out.println("Please enter the path of the original *.tab-files:");

        originPath = sc.nextLine();

        System.out.println(
                "Please enter the path where you wish to save the optimized *.tab-files (Directories will be created, existing files with same filenames will be overwritten):");

        targetPath = sc.nextLine();

        sc.close();

        File folder = new File(originPath);
        File[] listOfFiles = folder.listFiles();

        assert listOfFiles != null;
        for (File file : listOfFiles) {
            if (!file.getName().equals("LICENSE")) {
                TabFile origin;
                try {
                    String originFileName = file.getAbsolutePath();
                    System.out.print("Reading file '" + originFileName + "'...");
                    origin = new TabFile(originFileName);
                    System.out.println("Done!");
                    System.out.print("Optimizing file...");
                    TabFile res = TabFile.optimizeDictionaries(origin, 2, true);
                    System.out.println("Done!");

                    String targetFileName = targetPath + File.separator + file.getName();

                    System.out.println("Saving new file as '" + targetFileName + "'...");
                    res.save(targetFileName);
                    System.out.println("Done!");
                } catch (IOException e) {
                    FOKLogger.log(TabFile.class.getName(), Level.SEVERE, "An error occurred", e);
                }
            }
        }
    } else if (args[0].equals("merge")) {
        System.err.println(
                "Merging dictionaries is not supported anymore. Please checkout commit 1a6fa16 to merge dictionaries.");
    }
}

From source file:com.hsbc.srbp.commonMsg.test.Main.java

/**
 * Load the Spring Integration Application Context
 *
 * @param args - command line arguments//from   ww  w  .  j a  v a2  s.  c om
 */
public static void main(final String... args) {

    final AbstractApplicationContext context = new ClassPathXmlApplicationContext(
            "jdbcInboundApplicationContext.xml");

    context.registerShutdownHook();

    final Scanner scanner = new Scanner(System.in);

    final CommonMessageService commonMessageService = context.getBean(CommonMessageService.class);

    System.out.println("\n========================================================="
            + "\n                                                         "
            + "\n    Please press 'q + Enter' to quit the application.    "
            + "\n                                                         "
            + "\n=========================================================");

    System.out.println("Please enter a choice and press <enter>: ");
    System.out.println("\t1. Create a new message detail");
    System.out.println("\tq. Quit the application");
    System.out.print("Enter you choice: ");
    while (true) {
        final String input = scanner.nextLine();
        if ("1".equals(input.trim())) {
            createMessageDetails(scanner, commonMessageService, context);
        } else if ("q".equals(input.trim())) {
            break;
        } else {
            System.out.println("Invalid choice\n\n");
        }

        System.out.println("Please enter a choice and press <enter>: ");
        System.out.println("\t1. Create a new message detail");
        System.out.println("\tq. Quit the application");
        System.out.print("Enter you choice: ");
    }

    System.out.println("Exiting application....");

    System.exit(0);

}

From source file:ExecSQL.java

public static void main(String args[]) {
        try {//  w  ww  .j a  va  2s .com
            Scanner in;
            if (args.length == 0)
                in = new Scanner(System.in);
            else
                in = new Scanner(new File(args[0]));

            Connection conn = getConnection();
            try {
                Statement stat = conn.createStatement();

                while (true) {
                    if (args.length == 0)
                        System.out.println("Enter command or EXIT to exit:");

                    if (!in.hasNextLine())
                        return;

                    String line = in.nextLine();
                    if (line.equalsIgnoreCase("EXIT"))
                        return;
                    if (line.trim().endsWith(";")) // remove trailing semicolon
                    {
                        line = line.trim();
                        line = line.substring(0, line.length() - 1);
                    }
                    try {
                        boolean hasResultSet = stat.execute(line);
                        if (hasResultSet)
                            showResultSet(stat);
                    } catch (SQLException ex) {
                        for (Throwable e : ex)
                            e.printStackTrace();
                    }
                }
            } finally {
                conn.close();
            }
        } catch (SQLException e) {
            for (Throwable t : e)
                t.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

From source file:com.blackboard.WebdavBulkDeleterClient.java

public static void main(String[] args) {
    if (System.getProperty("log4j.configuration") != null) {
        PropertyConfigurator.configure(System.getProperty("log4j.configuration"));
    } else {/* ww  w .  ja va 2  s.com*/
        BasicConfigurator.configure();
    }

    // Perform command line parsing in an as friendly was as possible. 
    // Could be improved
    CommandLineParser parser = new PosixParser();
    Options options = new Options();

    // Use a map to store our options and loop over it to check and parse options via
    // addAllOptions() and verifyOptions() below
    Map<String, String> optionsAvailable = new HashMap<String, String>();
    optionsAvailable.put("deletion-list", "The file containing the list of courses to delete");
    optionsAvailable.put("user", "User with deletion privileges, usually bbsupport");
    optionsAvailable.put("password", "Password - ensure you escape any shell characters");
    optionsAvailable.put("url", "The Learn URL - usually https://example.com/bbcswebdav/courses");

    options = addAllOptions(options, optionsAvailable);

    options.addOption(OptionBuilder.withLongOpt("no-verify-ssl").withDescription("Don't verify SSL")
            .hasArg(false).create());

    CommandLine line = null;
    try {
        line = parser.parse(options, args);
        verifyOptions(line, optionsAvailable);
    } catch (ParseException e) {
        // Detailed reason will be printed by verifyOptions above
        logger.fatal("Incorrect options specified, exiting...");
        System.exit(1);
    }

    Scanner scanner = null;
    try {
        scanner = new Scanner(new File(line.getOptionValue("deletion-list")));
    } catch (FileNotFoundException e) {
        logger.fatal("Cannot open file : " + e.getLocalizedMessage());
        System.exit(1);
    }

    // By default we verify SSL certs
    boolean verifyCertStatus = true;
    if (line.hasOption("no-verify-ssl")) {
        verifyCertStatus = false;
    }

    // Loop through deletion list and delete courses if they exist.
    LearnServer instance;
    try {
        logger.debug("Attempting to open connection");
        instance = new LearnServer(line.getOptionValue("user"), line.getOptionValue("password"),
                line.getOptionValue("url"), verifyCertStatus);
        String currentCourse = null;
        logger.debug("Connection open");
        while (scanner.hasNextLine()) {
            currentCourse = scanner.nextLine();
            if (instance.exists(currentCourse)) {
                try {
                    instance.deleteCourse(currentCourse);
                    logger.info("Processing " + currentCourse + " : Result - Deletion Successful");
                } catch (IOException ioe) {
                    logger.error("Processing " + currentCourse + " : Result - Could not Delete ("
                            + ioe.getLocalizedMessage() + ")");
                }
            } else {
                logger.info("Processing " + currentCourse + " : Result - Course does not exist");
            }
        }
    } catch (IllegalArgumentException e) {
        logger.fatal(e.getLocalizedMessage());
        System.exit(1);
    } catch (IOException ioe) {
        logger.debug(ioe);
        logger.fatal(ioe.getMessage());
    }

}

From source file:org.bitcoinrt.Main.java

/**
 * Load the Spring Integration Application Context
 *
 * @param args - command line arguments//from  w w w  .jav  a  2 s . c om
 */
public static void main(final String... args) {

    final Scanner scanner = new Scanner(System.in);

    System.out.println("\n========================================================="
            + "\n                                                         "
            + "\n    Welcome to the Spring Integration Bitcoin-rt Sample! "
            + "\n                                                         "
            + "\n=========================================================");

    System.out.println("Which WebSocket Client would you like to use? <enter>: ");
    System.out.println("\t1. Use Sonatype's Async HTTP Client implementation");
    System.out.println("\t2. Use Jetty's WebSocket client implementation");
    System.out.println("\t3. Use a Dummy client");

    System.out.println("\tq. Quit the application");
    System.out.print("Enter you choice: ");

    final GenericXmlApplicationContext context = new GenericXmlApplicationContext();

    while (true) {
        final String input = scanner.nextLine();

        if ("1".equals(input.trim())) {
            context.getEnvironment().setActiveProfiles("default");
            break;
        } else if ("2".equals(input.trim())) {
            context.getEnvironment().setActiveProfiles("jetty");
            break;
        } else if ("3".equals(input.trim())) {
            context.getEnvironment().setActiveProfiles("dummy");
            break;
        } else if ("q".equals(input.trim())) {
            System.out.println("Exiting application...bye.");
            System.exit(0);
        } else {
            System.out.println("Invalid choice\n\n");
            System.out.print("Enter you choice: ");
        }
    }

    context.load("classpath:META-INF/spring/integration/*-context.xml");
    context.registerShutdownHook();
    context.refresh();

    final ConnectionBroker connectionBroker = context.getBean(ConnectionBroker.class);

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("\n========================================================="
                + "\n                                                         "
                + "\n    Please press 'q + Enter' to quit the application.    "
                + "\n    For statistical information press 'i + Enter'.       "
                + "\n                                                         "
                + "\n    In your browser open:                                "
                + "\n    file:///.../src/main/webapp/index.html               "
                + "\n=========================================================");
    }

    while (true) {

        final String input = scanner.nextLine();

        if ("q".equals(input.trim())) {
            break;
        } else if ("i".equals(input.trim())) {
            LOGGER.info("\n========================================================="
                    + "\n                                                         "
                    + "\n Number of connected clients: " + connectionBroker.connectedClients()
                    + "\n                                                         "
                    + "\n=========================================================");
        }

    }

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Exiting application...bye.");
    }

    context.close();
    System.exit(0);

}

From source file:com.sds.acube.ndisc.xadmin.XNDiscAdminUtil.java

public static void main(String args[]) {

    if (args.length == 0) {
        XNDiscAdminUtil.printAdminUsage(null, null);
        // System.exit(0);
    }// w w w .  j av  a  2 s.c  o m

    XNDiscAdminFile file = new XNDiscAdminFile(printlog, out, logger);
    XNDiscAdminMedia media = new XNDiscAdminMedia(printlog, out, logger);
    XNDiscAdminVolume volume = new XNDiscAdminVolume(printlog, out, logger);
    XNDiscAdminEnDecrypt endecrypt = new XNDiscAdminEnDecrypt(printlog, out, logger);

    Scanner in = new Scanner(System.in);
    String input = "";
    List<String> options = null;
    Scanner part = null;
    do {
        input = in.nextLine();
        part = new Scanner(input).useDelimiter(" ");
        options = new ArrayList<String>();
        while (part.hasNext()) {
            String val = part.next().trim();
            if (StringUtils.isEmpty(val)) {
                continue;
            }
            options.add(val);
        }
        if (options.size() < 2 || input.equalsIgnoreCase("q")) {
            if (input != null && input.trim().equalsIgnoreCase("q")) {
                System.out.println(LINE_SEPERATOR + "XNDiscAdminUtil quit!!!" + LINE_SEPERATOR);
            } else {
                System.out
                        .println(LINE_SEPERATOR + "XNDiscAdminUtil are invalid parameters!!!" + LINE_SEPERATOR);
            }
            System.exit(0);
        }

        String main_op = (StringUtils.isEmpty(options.get(0))) ? "" : options.get(0);
        String process_op = (StringUtils.isEmpty(options.get(1))) ? "" : options.get(1);
        if (main_op.equals("clear")) {
            if (process_op.equals("screen")) {
                clearConsoleOutput();
            }
        } else if (main_op.equals("file")) {
            if (process_op.equals("ls")) {
                String fileid = "";
                if (options.size() > 2) {
                    fileid = options.get(2);
                }
                if (StringUtils.isEmpty(fileid)) {
                    file.selectFileList();
                } else {
                    file.selectFileById(fileid);
                }
            } else if (process_op.equals("reg")) {
                String host = "";
                int port = -1;
                String filepath = "";
                int vol = -1;
                if (options.size() == 4) {
                    host = XNDiscAdminConfig.getString(XNDiscAdminConfig.HOST);
                    port = XNDiscAdminConfig.getInt(XNDiscAdminConfig.PORT);
                    filepath = options.get(2);
                    if (isInteger(options.get(3))) {
                        vol = Integer.parseInt(options.get(3));
                    }
                } else if (options.size() > 5) {
                    host = options.get(2);
                    port = Integer.parseInt(options.get(3));
                    filepath = options.get(4);
                    if (isInteger(options.get(5))) {
                        vol = Integer.parseInt(options.get(5));
                    }
                }
                if (!StringUtils.isEmpty(host) && !StringUtils.isEmpty(filepath) && port > 0 && vol > 0) {
                    file.regFile(host, port, filepath, vol, "0");
                } else {
                    XNDiscAdminUtil.printAdminUsage(main_op, process_op);
                }
            } else if (process_op.equals("get")) {
                String host = "";
                int port = -1;
                String fileid = "";
                String filepath = "";
                if (options.size() == 4) {
                    host = XNDiscAdminConfig.getString(XNDiscAdminConfig.HOST);
                    port = XNDiscAdminConfig.getInt(XNDiscAdminConfig.PORT);
                    fileid = options.get(2);
                    filepath = options.get(3);
                } else if (options.size() > 5) {
                    host = options.get(2);
                    if (isInteger(options.get(3))) {
                        port = Integer.parseInt(options.get(3));
                    }
                    fileid = options.get(4);
                    filepath = options.get(5);
                }
                if (!StringUtils.isEmpty(host) && !StringUtils.isEmpty(fileid) && !StringUtils.isEmpty(filepath)
                        && port > 0) {
                    file.getFile(host, port, fileid, filepath);
                } else {
                    XNDiscAdminUtil.printAdminUsage(main_op, process_op);
                }
            } else if (process_op.equals("wh")) {
                String fileid = "";
                if (options.size() > 2) {
                    fileid = options.get(2);
                }
                if (!StringUtils.isEmpty(fileid)) {
                    file.getFilePathByFileId(fileid);
                } else {
                    XNDiscAdminUtil.printAdminUsage(main_op, process_op);
                }
            } else if (process_op.equals("rm")) {
                String host = "";
                int port = -1;
                String fileid = "";
                if (options.size() == 3) {
                    host = XNDiscAdminConfig.getString(XNDiscAdminConfig.HOST);
                    port = XNDiscAdminConfig.getInt(XNDiscAdminConfig.PORT);
                    fileid = options.get(2);
                } else if (options.size() > 4) {
                    host = options.get(2);
                    if (isInteger(options.get(3))) {
                        port = Integer.parseInt(options.get(3));
                    }
                    fileid = options.get(4);
                }
                if (!StringUtils.isEmpty(host) && !StringUtils.isEmpty(fileid) && port > 0) {
                    file.removeFile(host, port, fileid);
                } else {
                    XNDiscAdminUtil.printAdminUsage(main_op, process_op);
                }
            }
        } else if (main_op.equals("media")) {
            if (process_op.equals("mk")) {
                String host = "";
                int port = -1;
                String name = "";
                int type = 0;
                String path = "";
                String desc = " ";
                int maxsize = -1;
                int vol = -1;
                if (options.size() == 7) {
                    host = XNDiscAdminConfig.getString(XNDiscAdminConfig.HOST);
                    port = XNDiscAdminConfig.getInt(XNDiscAdminConfig.PORT);
                    name = options.get(2);
                    if (isInteger(options.get(3))) {
                        type = Integer.parseInt(options.get(3));
                    }
                    path = options.get(4);
                    if (isInteger(options.get(5))) {
                        maxsize = Integer.parseInt(options.get(5));
                    }
                    if (isInteger(options.get(6))) {
                        vol = Integer.parseInt(options.get(6));
                    }
                } else if (options.size() == 8) {
                    host = XNDiscAdminConfig.getString(XNDiscAdminConfig.HOST);
                    port = XNDiscAdminConfig.getInt(XNDiscAdminConfig.PORT);
                    name = options.get(2);
                    if (isInteger(options.get(3))) {
                        type = Integer.parseInt(options.get(3));
                    }
                    path = options.get(4);
                    desc = options.get(5) + " ";
                    if (isInteger(options.get(6))) {
                        maxsize = Integer.parseInt(options.get(6));
                    }
                    if (isInteger(options.get(7))) {
                        vol = Integer.parseInt(options.get(7));
                    }
                } else if (options.size() == 9) {
                    host = options.get(2);
                    if (isInteger(options.get(3))) {
                        port = Integer.parseInt(options.get(3));
                    }
                    name = options.get(4);
                    if (isInteger(options.get(5))) {
                        type = Integer.parseInt(options.get(5));
                    }
                    path = options.get(6);
                    if (isInteger(options.get(7))) {
                        maxsize = Integer.parseInt(options.get(7));
                    }
                    if (isInteger(options.get(8))) {
                        vol = Integer.parseInt(options.get(8));
                    }
                } else if (options.size() > 9) {
                    host = options.get(2);
                    if (isInteger(options.get(3))) {
                        port = Integer.parseInt(options.get(3));
                    }
                    name = options.get(4);
                    if (isInteger(options.get(5))) {
                        type = Integer.parseInt(options.get(5));
                    }
                    path = options.get(6);
                    desc = options.get(7) + " ";
                    if (isInteger(options.get(8))) {
                        maxsize = Integer.parseInt(options.get(8));
                    }
                    if (isInteger(options.get(9))) {
                        vol = Integer.parseInt(options.get(9));
                    }
                }
                if (!StringUtils.isEmpty(host) && !StringUtils.isEmpty(name) && !StringUtils.isEmpty(path)
                        && port > 0 && vol > 0 && maxsize > 0) {
                    media.makeMedia(host, port, name, type, path, desc, maxsize, vol);
                } else {
                    XNDiscAdminUtil.printAdminUsage(main_op, process_op);
                }
            } else if (process_op.equals("ls")) {
                String mediaid = "-1";
                if (options.size() > 2) {
                    mediaid = options.get(2);
                }
                if (StringUtils.isEmpty(mediaid) || mediaid.equals("-1")) {
                    media.selectMediaList();
                } else {
                    int id = -1;
                    if (isInteger(mediaid)) {
                        id = Integer.parseInt(mediaid);
                    }
                    if (id > 0) {
                        media.selectMediaById(id);
                    } else {
                        XNDiscAdminUtil.printAdminUsage(main_op, process_op);
                    }
                }
            } else if (process_op.equals("rm")) {
                String mediaid = "-1";
                if (options.size() > 2) {
                    mediaid = options.get(2);
                }
                if (!StringUtils.isEmpty(mediaid)) {
                    int id = -1;
                    if (isInteger(mediaid)) {
                        id = Integer.parseInt(options.get(2));
                    }
                    if (id > 0) {
                        media.removeMedia(id);
                    } else {
                        XNDiscAdminUtil.printAdminUsage(main_op, process_op);
                    }
                }
            } else if (process_op.equals("ch")) {
                int mediaid = -1;
                String name = "";
                int type = 0;
                String path = "";
                String desc = "";
                int maxsize = -1;
                int vol = -1;
                if (options.size() == 8) {
                    if (isInteger(options.get(2))) {
                        mediaid = Integer.parseInt(options.get(2));
                    }
                    name = options.get(3);
                    if (isInteger(options.get(4))) {
                        type = Integer.parseInt(options.get(4));
                    }
                    path = options.get(5);
                    if (isInteger(options.get(6))) {
                        maxsize = Integer.parseInt(options.get(6));
                    }
                    if (isInteger(options.get(7))) {
                        vol = Integer.parseInt(options.get(7));
                    }
                } else if (options.size() > 8) {
                    if (isInteger(options.get(2))) {
                        mediaid = Integer.parseInt(options.get(2));
                    }
                    name = options.get(3);
                    if (isInteger(options.get(4))) {
                        type = Integer.parseInt(options.get(4));
                    }
                    path = options.get(5);
                    desc = options.get(6);
                    if (isInteger(options.get(7))) {
                        maxsize = Integer.parseInt(options.get(7));
                    }
                    if (isInteger(options.get(8))) {
                        vol = Integer.parseInt(options.get(8));
                    }
                }
                if (!StringUtils.isEmpty(name) && !StringUtils.isEmpty(path) && mediaid > 0 && maxsize > 0
                        && vol > 0) {
                    media.changeMedia(mediaid, name, type, path, desc, maxsize, vol);
                } else {
                    XNDiscAdminUtil.printAdminUsage(main_op, process_op);
                }
            }
        } else if (main_op.equals("vol")) {
            if (process_op.equals("mk")) {
                String name = "";
                String access = "";
                String desc = " ";
                if (options.size() == 4) {
                    name = options.get(2);
                    access = options.get(3);
                } else if (options.size() > 4) {
                    name = options.get(2);
                    access = options.get(3);
                    desc = options.get(4) + " ";
                }
                if (!StringUtils.isEmpty(name) && !StringUtils.isEmpty(access)) {
                    volume.makeVolume(name, access, desc);
                } else {
                    XNDiscAdminUtil.printAdminUsage(main_op, process_op);
                }
            } else if (process_op.equals("ls")) {
                String volid = "-1";
                if (options.size() > 2) {
                    volid = options.get(2);
                }
                if (StringUtils.isEmpty(volid) || volid.equals("-1")) {
                    volume.selectVolumeList();
                } else {
                    int volumeid = -1;
                    if (isInteger(volid)) {
                        volumeid = Integer.parseInt(volid);
                    }
                    if (volumeid > 0) {
                        volume.selectVolumeById(volumeid);
                    } else {
                        XNDiscAdminUtil.printAdminUsage(main_op, process_op);
                    }
                }
            } else if (process_op.equals("rm")) {
                String volid = "-1";
                if (options.size() > 2) {
                    volid = options.get(2);
                }
                if (!StringUtils.isEmpty(volid)) {
                    int volumeid = -1;
                    if (isInteger(volid)) {
                        volumeid = Integer.parseInt(volid);
                    }
                    if (volumeid > 0) {
                        volume.removeVolume(volumeid);
                    }
                } else {
                    XNDiscAdminUtil.printAdminUsage(main_op, process_op);
                }
            } else if (process_op.equals("ch")) {
                int volumeid = -1;
                String name = "";
                String access = "";
                String desc = "";
                if (options.size() == 5) {
                    if (isInteger(options.get(2))) {
                        volumeid = Integer.parseInt(options.get(2));
                    }
                    name = options.get(3);
                    access = options.get(4);
                } else if (options.size() > 5) {
                    if (isInteger(options.get(2))) {
                        volumeid = Integer.parseInt(options.get(2));
                    }
                    name = options.get(3);
                    access = options.get(4);
                    desc = options.get(5) + " ";
                }
                if (!StringUtils.isEmpty(name) && !StringUtils.isEmpty(access) && volumeid > 0) {
                    volume.changeVolume(volumeid, name, access, desc);
                } else {
                    XNDiscAdminUtil.printAdminUsage(main_op, process_op);
                }
            }
        } else if (main_op.equals("id")) {
            String id = "";
            if (options.size() > 2) {
                id = options.get(2);
            }
            if (process_op.equals("enc")) {
                if (!StringUtils.isEmpty(id)) {
                    endecrypt.encrypt(id);
                } else {
                    XNDiscAdminUtil.printAdminUsage(main_op, process_op);
                }
            } else if (process_op.equals("dec")) {
                if (!StringUtils.isEmpty(id)) {
                    endecrypt.decrypt(id);
                } else {
                    XNDiscAdminUtil.printAdminUsage(main_op, process_op);
                }
            }
        }
        part.close();
    } while (!input.equalsIgnoreCase("q"));
    in.close();
}

From source file:edu.upenn.cis.FastAlign.java

/**
 * Prints alignments for options specified by command line arguments.
 * @param argv  parameters to be used by FastAlign.
 *//*from  w  ww.java2  s . c om*/
public static void main(String[] argv) {

    FastAlign align = FastAlign.initCommandLine(argv);
    if (align == null) {
        System.err.println("Usage: java " + FastAlign.class.getCanonicalName() + " -i file.fr-en\n"
                + " Standard options ([USE] = strongly recommended):\n" + "  -i: [REQ] Input parallel corpus\n"
                + "  -v: [USE] Use Dirichlet prior on lexical translation distributions\n"
                + "  -d: [USE] Favor alignment points close to the monotonic diagonoal\n"
                + "  -o: [USE] Optimize how close to the diagonal alignment points should be\n"
                + "  -r: Run alignment in reverse (condition on target and predict source)\n"
                + "  -c: Output conditional probability table\n"
                + "  -e: Start with existing conditional probability table\n" + " Advanced options:\n"
                + "  -I: number of iterations in EM training (default = 5)\n"
                + "  -p: p_null parameter (default = 0.08)\n" + "  -N: No null word\n"
                + "  -a: alpha parameter for optional Dirichlet prior (default = 0.01)\n"
                + "  -T: starting lambda for diagonal distance parameter (default = 4)\n");
        System.exit(1);
    }
    boolean use_null = !align.no_null_word;
    if (align.variational_bayes && align.alpha <= 0.0) {
        System.err.println("--alpha must be > 0\n");
        System.exit(1);
    }
    double prob_align_not_null = 1.0 - align.prob_align_null;
    final int kNULL = align.d.Convert("<eps>");
    TTable s2t = new TTable();
    if (!align.existing_probability_filename.isEmpty()) {
        boolean success = s2t.ImportFromFile(align.existing_probability_filename, '\t', align.d);
        if (!success) {
            System.err.println("Can't read table " + align.existing_probability_filename);
            System.exit(1);
        }
    }
    Map<Pair, Integer> size_counts = new HashMap<Pair, Integer>();
    double tot_len_ratio = 0;
    double mean_srclen_multiplier = 0;
    List<Double> probs = new ArrayList<Double>();
    ;
    // E-M Iterations Loop TODO move this into a method?
    for (int iter = 0; iter < align.iterations || (iter == 0 && align.iterations == 0); ++iter) {
        final boolean final_iteration = (iter >= (align.iterations - 1));
        System.err.println("ITERATION " + (iter + 1) + (final_iteration ? " (FINAL)" : ""));
        Scanner in = null;
        try {
            in = new Scanner(new File(align.input));
            if (!in.hasNextLine()) {
                System.err.println("Can't read " + align.input);
                System.exit(1);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.err.println("Can't read " + align.input);
            System.exit(1);
        }

        double likelihood = 0;
        double denom = 0.0;
        int lc = 0;
        boolean flag = false;
        String line;
        //         String ssrc, strg;
        ArrayList<Integer> src = new ArrayList<Integer>();
        ArrayList<Integer> trg = new ArrayList<Integer>();
        double c0 = 0;
        double emp_feat = 0;
        double toks = 0;
        // Iterate over each line of the input file
        while (in.hasNextLine()) {
            line = in.nextLine();
            ++lc;
            if (lc % 1000 == 0) {
                System.err.print('.');
                flag = true;
            }
            if (lc % 50000 == 0) {
                System.err.println(" [" + lc + "]\n");
                System.err.flush();
                flag = false;
            }
            src.clear();
            trg.clear(); // TODO this is redundant; src and tgt cleared in ParseLine
            // Integerize and split source and target lines.
            align.ParseLine(line, src, trg);
            if (align.is_reverse) {
                ArrayList<Integer> tmp = src;
                src = trg;
                trg = tmp;
            }
            // TODO Empty lines break the parser. Should this be true?
            if (src.size() == 0 || trg.size() == 0) {
                System.err.println("Error in line " + lc + "\n" + line);
                System.exit(1);
            }
            if (iter == 0) {
                tot_len_ratio += ((double) trg.size()) / ((double) src.size());
            }
            denom += trg.size();
            probs.clear();
            // Add to pair length counts only if first iteration.
            if (iter == 0) {
                Pair pair = new Pair(trg.size(), src.size());
                Integer value = size_counts.get(pair);
                if (value == null)
                    value = 0;
                size_counts.put(pair, value + 1);
            }
            boolean first_al = true; // used when printing alignments
            toks += trg.size();
            // Iterate through the English tokens
            for (int j = 0; j < trg.size(); ++j) {
                final int f_j = trg.get(j);
                double sum = 0;
                double prob_a_i = 1.0 / (src.size() + (use_null ? 1 : 0)); // uniform (model 1)
                if (use_null) {
                    if (align.favor_diagonal) {
                        prob_a_i = align.prob_align_null;
                    }
                    probs.add(0, s2t.prob(kNULL, f_j) * prob_a_i);
                    sum += probs.get(0);
                }
                double az = 0;
                if (align.favor_diagonal)
                    az = DiagonalAlignment.computeZ(j + 1, trg.size(), src.size(), align.diagonal_tension)
                            / prob_align_not_null;
                for (int i = 1; i <= src.size(); ++i) {
                    if (align.favor_diagonal)
                        prob_a_i = DiagonalAlignment.unnormalizedProb(j + 1, i, trg.size(), src.size(),
                                align.diagonal_tension) / az;
                    probs.add(i, s2t.prob(src.get(i - 1), f_j) * prob_a_i);
                    sum += probs.get(i);
                }
                if (final_iteration) {
                    double max_p = -1;
                    int max_index = -1;
                    if (use_null) {
                        max_index = 0;
                        max_p = probs.get(0);
                    }
                    for (int i = 1; i <= src.size(); ++i) {
                        if (probs.get(i) > max_p) {
                            max_index = i;
                            max_p = probs.get(i);
                        }
                    }
                    if (max_index > 0) {
                        if (first_al)
                            first_al = false;
                        else
                            System.out.print(' ');
                        if (align.is_reverse)
                            System.out.print("" + j + '-' + (max_index - 1));
                        else
                            System.out.print("" + (max_index - 1) + '-' + j);
                    }
                } else {
                    if (use_null) {
                        double count = probs.get(0) / sum;
                        c0 += count;
                        s2t.Increment(kNULL, f_j, count);
                    }
                    for (int i = 1; i <= src.size(); ++i) {
                        final double p = probs.get(i) / sum;
                        s2t.Increment(src.get(i - 1), f_j, p);
                        emp_feat += DiagonalAlignment.feature(j, i, trg.size(), src.size()) * p;
                    }
                }
                likelihood += Math.log(sum);
            }
            if (final_iteration)
                System.out.println();
        }

        // log(e) = 1.0
        double base2_likelihood = likelihood / Math.log(2);

        if (flag) {
            System.err.println();
        }
        if (iter == 0) {
            mean_srclen_multiplier = tot_len_ratio / lc;
            System.err.println("expected target length = source length * " + mean_srclen_multiplier);
        }
        emp_feat /= toks;
        System.err.println("  log_e likelihood: " + likelihood);
        System.err.println("  log_2 likelihood: " + base2_likelihood);
        System.err.println("     cross entropy: " + (-base2_likelihood / denom));
        System.err.println("        perplexity: " + Math.pow(2.0, -base2_likelihood / denom));
        System.err.println("      posterior p0: " + c0 / toks);
        System.err.println(" posterior al-feat: " + emp_feat);
        //System.err.println("     model tension: " + mod_feat / toks );
        System.err.println("       size counts: " + size_counts.size());
        if (!final_iteration) {
            if (align.favor_diagonal && align.optimize_tension && iter > 0) {
                for (int ii = 0; ii < 8; ++ii) {
                    double mod_feat = 0;
                    Iterator<Map.Entry<Pair, Integer>> it = size_counts.entrySet().iterator();
                    for (; it.hasNext();) {
                        Map.Entry<Pair, Integer> entry = it.next();
                        final Pair p = entry.getKey();
                        for (int j = 1; j <= p.first; ++j)
                            mod_feat += entry.getValue() * DiagonalAlignment.computeDLogZ(j, p.first, p.second,
                                    align.diagonal_tension);
                    }
                    mod_feat /= toks;
                    System.err.println("  " + ii + 1 + "  model al-feat: " + mod_feat + " (tension="
                            + align.diagonal_tension + ")");
                    align.diagonal_tension += (emp_feat - mod_feat) * 20.0;
                    if (align.diagonal_tension <= 0.1)
                        align.diagonal_tension = 0.1;
                    if (align.diagonal_tension > 14)
                        align.diagonal_tension = 14;
                }
                System.err.println("     final tension: " + align.diagonal_tension);
            }
            if (align.variational_bayes)
                s2t.NormalizeVB(align.alpha);
            else
                s2t.Normalize();
            //prob_align_null *= 0.8; // XXX
            //prob_align_null += (c0 / toks) * 0.2;
            prob_align_not_null = 1.0 - align.prob_align_null;
        }

    }
    if (!align.conditional_probability_filename.isEmpty()) {
        System.err.println("conditional probabilities: " + align.conditional_probability_filename);
        s2t.ExportToFile(align.conditional_probability_filename, align.d);
    }
    System.exit(0);
}

From source file:com.balero.test.Wizard.java

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    System.out.println(""
            + ".-. .-')     ('-.                 ('-.  _  .-')                                _   .-')      .-')    \n"
            + "\\  ( OO )   ( OO ).-.           _(  OO)( \\( -O )                              ( '.( OO )_   ( OO ). \n"
            + " ;-----.\\   / . --. / ,--.     (,------.,------.  .-'),-----.          .-----. ,--.   ,--.)(_)---\\_) \n"
            + " | .-.  |   | \\-.  \\  |  |.-')  |  .---'|   /`. '( OO'  .-.  '        '  .--./ |   `.'   | /    _ |  \n"
            + " | '-' /_).-'-'  |  | |  | OO ) |  |    |  /  | |/   |  | |  |        |  |('-. |         | \\  :` `.  \n"
            + " | .-. `.  \\| |_.'  | |  |`-' |(|  '--. |  |_.' |\\_) |  |\\|  |       /_) |OO  )|  |'.'|  |  '..`''.) \n"
            + " | |  \\  |  |  .-.  |(|  '---.' |  .--' |  .  '.'  \\ |  | |  |       ||  |`-'| |  |   |  | .-._)   \\ \n"
            + " | '--'  /  |  | |  | |      |  |  `---.|  |\\  \\    `'  '-'  '      (_'  '--'\\ |  |   |  | \\       / \n"
            + " `------'   `--' `--' `------'  `------'`--' '--'     `-----'          `-----' `--'   `--'  `-----'  \n"
            + "                                                                                  Enterprise Edition\n");
    System.out.println("Welcome to Balero CMS Setup Wizard\n");
    System.out.println("Provide your Database configuration.\n");

    String dbuser;/*from w w w . j a  va  2  s  .c om*/
    System.out.print("Insert MySQL Username\n");
    dbuser = sc.nextLine();

    String dbpass;
    System.out.print("Insert MySQL Password\n");
    dbpass = sc.nextLine();

    String opt;
    System.out.println("The MIT License (MIT)\n" + "\n" + "Copyright (c) 2014 Balero CMS Enterprise Edition.\n"
            + "\n" + "Permission is hereby granted, free of charge, to any person obtaining a copy\n"
            + "of this software and associated documentation files (the \"Software\"), to deal\n"
            + "in the Software without restriction, including without limitation the rights\n"
            + "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n"
            + "copies of the Software, and to permit persons to whom the Software is\n"
            + "furnished to do so, subject to the following conditions:\n" + "\n"
            + "The above copyright notice and this permission notice shall be included in\n"
            + "all copies or substantial portions of the Software.\n" + "\n"
            + "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n"
            + "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n"
            + "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n"
            + "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n"
            + "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n"
            + "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n" + "THE SOFTWARE.\n"
            + "Agree: Enter Decline: e");
    opt = sc.nextLine();
    exitWizard(opt);

    System.out.print("Setup wizard will create database tables\n" + "Continue: Enter or Exit: e\n");
    opt = sc.nextLine();
    exitWizard(opt);

    try {

        System.out.println("" + "     _( )_          _      Mounting CMS...\n" + "   _(     )_      _( )_\n"
                + "  (_________)   _(     )_\n" + "               (_________)\n"
                + "    0  1  0               \n" + "       1  0     0  1  0\n" + "          1       1  0");
        ;

        for (double progressPercentage = 0.0; progressPercentage < 1.0; progressPercentage += 0.01) {
            updateProgress(progressPercentage);
            Thread.sleep(100);
        }
    } catch (InterruptedException e) {

    }

}

From source file:com.richard.memorystore.udp.UDPServer.java

/**
 * Load the Spring Integration Application Context
 *
 * @param args - command line arguments/*from  w  ww .  j a  v  a  2 s.  c o m*/
 */
public static void main(String[] args) {

    final Scanner scanner = new Scanner(System.in);

    System.out.println("\n========================================================="
            + "\n                                                         "
            + "\n    Welcome to the Spring Integration                    "
            + "\n          TCP-Client-Server Sample!                      "
            + "\n                                                         "
            + "\n    For more information please visit:                   "
            + "\n    http://www.springintegration.org/                    "
            + "\n                                                         "
            + "\n=========================================================");

    final GenericXmlApplicationContext context = UDPServer.setupContext();
    //      final SimpleGateway gateway = context.getBean(SimpleGateway.class);
    //      final AbstractServerConnectionFactory crLfServer = context.getBean(AbstractServerConnectionFactory.class);

    System.out.print("Waiting for server to accept connections...");
    //TestingUtilities.waitListening(crLfServer, 10000L);
    System.out.println("running.\n\n");

    System.out.println("Please enter some text and press <enter>: ");
    System.out.println("\tNote:");
    System.out.println("\t- Entering FAIL will create an exception");
    System.out.println("\t- Entering q will quit the application");
    System.out.print("\n");
    System.out.println("\t--> Please also check out the other samples, " + "that are provided as JUnit tests.");
    //System.out.println("\t--> You can also connect to the server on port '" + crLfServer.getPort() + "' using Telnet.\n\n");

    while (true) {

        final String input = scanner.nextLine();

        if ("q".equals(input.trim())) {
            break;
        }
        //         else {
        //            final String result = gateway.send(input);
        //            System.out.println(result);
        //         }
    }

    System.out.println("Exiting application...bye.");
    System.exit(0);

}

From source file:com.haythem.integration.Main.java

/**
 * Load the Spring Integration Application Context
 *
 * @param args - command line arguments/*from w w w  .  j  a va  2 s. com*/
 */
public static void main(final String... args) {

    final Scanner scanner = new Scanner(System.in);

    System.out.println("\n========================================================="
            + "\n                                                         "
            + "\n    Welcome to the Spring Integration                    "
            + "\n          TCP-Client-Server Sample!                      "
            + "\n                                                         "
            + "\n    For more information please visit:                   "
            + "\n    http://www.springintegration.org/                    "
            + "\n                                                         "
            + "\n=========================================================");

    final GenericXmlApplicationContext context = Main.setupContext();
    final SimpleGateway gateway = context.getBean(SimpleGateway.class);
    final AbstractServerConnectionFactory crLfServer = context.getBean(AbstractServerConnectionFactory.class);

    System.out.print("Waiting for server to accept connections...");
    TestingUtilities.waitListening(crLfServer, 10000L);
    System.out.println("running.\n\n");

    System.out.println("Please enter some text and press <enter>: ");
    System.out.println("\tNote:");
    System.out.println("\t- Entering FAIL will create an exception");
    System.out.println("\t- Entering q will quit the application");
    System.out.print("\n");
    System.out.println("\t--> Please also check out the other samples, " + "that are provided as JUnit tests.");
    System.out.println("\t--> You can also connect to the server on port '" + crLfServer.getPort()
            + "' using Telnet.\n\n");

    while (true) {

        final String input = scanner.nextLine();

        if ("q".equals(input.trim())) {
            break;
        } else {
            final String result = gateway.send(input);
            System.out.println(result);
        }
    }

    System.out.println("Exiting application...bye.");
    System.exit(0);

}