Example usage for java.util Scanner nextInt

List of usage examples for java.util Scanner nextInt

Introduction

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

Prototype

public int nextInt() 

Source Link

Document

Scans the next token of the input as an int .

Usage

From source file:fi.jyu.it.ties456.week38.Main.Main.java

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

    TeacherRegistryService connect = new TeacherRegistryService();
    TeacherRegistry teacher = connect.getTeacherRegistryPort();
    CourseISService connectCourse = new CourseISService();
    CourseIS course = connectCourse.getCourseISPort();
    int i;/*from  w w w  . j a va  2s  . com*/
    Scanner inputchoice = new Scanner(System.in);
    Scanner cin = new Scanner(System.in);

    do {
        System.out.println("0: Quit the application");
        System.out.println("1: Search the teacher Info");
        System.out.println("2: Create the Course");
        i = inputchoice.nextInt();
        switch (i) {
        case 0:
            System.out.println("quit the application");
            break;
        case 1:
            System.out.println("Input search info of teacher");
            String searchString = cin.nextLine();
            JSONObject result = searchTeacher(teacher, searchString);
            if (result == null)
                System.out.println("No person found");
            else
                System.out.println(result);
            break;
        case 2:
            createCourse(teacher, course);
            break;
        default:
            System.err.println("Not a valid choice");

        }
    } while (i != 0);
}

From source file:org.apache.mahout.classifier.sequencelearning.hmm.BaumWelchTrainer.java

public static void main(String[] args) throws IOException {
    DefaultOptionBuilder optionBuilder = new DefaultOptionBuilder();
    ArgumentBuilder argumentBuilder = new ArgumentBuilder();

    Option inputOption = DefaultOptionCreator.inputOption().create();

    Option outputOption = DefaultOptionCreator.outputOption().create();

    Option stateNumberOption = optionBuilder.withLongName("nrOfHiddenStates")
            .withDescription("Number of hidden states").withShortName("nh")
            .withArgument(argumentBuilder.withMaximum(1).withMinimum(1).withName("number").create())
            .withRequired(true).create();

    Option observedStateNumberOption = optionBuilder.withLongName("nrOfObservedStates")
            .withDescription("Number of observed states").withShortName("no")
            .withArgument(argumentBuilder.withMaximum(1).withMinimum(1).withName("number").create())
            .withRequired(true).create();

    Option epsilonOption = optionBuilder.withLongName("epsilon").withDescription("Convergence threshold")
            .withShortName("e")
            .withArgument(argumentBuilder.withMaximum(1).withMinimum(1).withName("number").create())
            .withRequired(true).create();

    Option iterationsOption = optionBuilder.withLongName("max-iterations")
            .withDescription("Maximum iterations number").withShortName("m")
            .withArgument(argumentBuilder.withMaximum(1).withMinimum(1).withName("number").create())
            .withRequired(true).create();

    Group optionGroup = new GroupBuilder().withOption(inputOption).withOption(outputOption)
            .withOption(stateNumberOption).withOption(observedStateNumberOption).withOption(epsilonOption)
            .withOption(iterationsOption).withName("Options").create();

    try {//w  w  w  .  j  a v a2s.  c  o  m
        Parser parser = new Parser();
        parser.setGroup(optionGroup);
        CommandLine commandLine = parser.parse(args);

        String input = (String) commandLine.getValue(inputOption);
        String output = (String) commandLine.getValue(outputOption);

        int nrOfHiddenStates = Integer.parseInt((String) commandLine.getValue(stateNumberOption));
        int nrOfObservedStates = Integer.parseInt((String) commandLine.getValue(observedStateNumberOption));

        double epsilon = Double.parseDouble((String) commandLine.getValue(epsilonOption));
        int maxIterations = Integer.parseInt((String) commandLine.getValue(iterationsOption));

        //constructing random-generated HMM
        HmmModel model = new HmmModel(nrOfHiddenStates, nrOfObservedStates, new Date().getTime());
        List<Integer> observations = Lists.newArrayList();

        //reading observations
        Scanner scanner = new Scanner(new FileInputStream(input), "UTF-8");
        try {
            while (scanner.hasNextInt()) {
                observations.add(scanner.nextInt());
            }
        } finally {
            scanner.close();
        }

        int[] observationsArray = new int[observations.size()];
        for (int i = 0; i < observations.size(); ++i) {
            observationsArray[i] = observations.get(i);
        }

        //training
        HmmModel trainedModel = HmmTrainer.trainBaumWelch(model, observationsArray, epsilon, maxIterations,
                true);

        //serializing trained model
        DataOutputStream stream = new DataOutputStream(new FileOutputStream(output));
        try {
            LossyHmmSerializer.serialize(trainedModel, stream);
        } finally {
            Closeables.close(stream, false);
        }

        //printing tranied model
        System.out.println("Initial probabilities: ");
        for (int i = 0; i < trainedModel.getNrOfHiddenStates(); ++i) {
            System.out.print(i + " ");
        }
        System.out.println();
        for (int i = 0; i < trainedModel.getNrOfHiddenStates(); ++i) {
            System.out.print(trainedModel.getInitialProbabilities().get(i) + " ");
        }
        System.out.println();

        System.out.println("Transition matrix:");
        System.out.print("  ");
        for (int i = 0; i < trainedModel.getNrOfHiddenStates(); ++i) {
            System.out.print(i + " ");
        }
        System.out.println();
        for (int i = 0; i < trainedModel.getNrOfHiddenStates(); ++i) {
            System.out.print(i + " ");
            for (int j = 0; j < trainedModel.getNrOfHiddenStates(); ++j) {
                System.out.print(trainedModel.getTransitionMatrix().get(i, j) + " ");
            }
            System.out.println();
        }
        System.out.println("Emission matrix: ");
        System.out.print("  ");
        for (int i = 0; i < trainedModel.getNrOfOutputStates(); ++i) {
            System.out.print(i + " ");
        }
        System.out.println();
        for (int i = 0; i < trainedModel.getNrOfHiddenStates(); ++i) {
            System.out.print(i + " ");
            for (int j = 0; j < trainedModel.getNrOfOutputStates(); ++j) {
                System.out.print(trainedModel.getEmissionMatrix().get(i, j) + " ");
            }
            System.out.println();
        }
    } catch (OptionException e) {
        CommandLineUtil.printHelp(optionGroup);
    }
}

From source file:org.jboss.as.security.vault.VaultTool.java

public static void main(String[] args) {

    VaultTool tool = null;//from w w w.j  a  va  2 s.  c  o m

    if (args != null && args.length > 0) {
        int returnVal = 0;
        try {
            tool = new VaultTool(args);
            returnVal = tool.execute();
        } catch (Exception e) {
            System.err.println(SecurityLogger.ROOT_LOGGER.problemOcurred());
            e.printStackTrace(System.err);
            System.exit(1);
        }
        System.exit(returnVal);
    } else {
        tool = new VaultTool();

        System.out.println("**********************************");
        System.out.println("****  JBoss Vault  ***************");
        System.out.println("**********************************");

        Console console = System.console();

        if (console == null) {
            System.err.println(SecurityLogger.ROOT_LOGGER.noConsole());
            System.exit(1);
        }

        Scanner in = new Scanner(System.in);
        while (true) {
            System.out.println(SecurityLogger.ROOT_LOGGER.interactiveCommandString());
            try {
                int choice = in.nextInt();
                switch (choice) {
                case 0:
                    System.out.println(SecurityLogger.ROOT_LOGGER.startingInteractiveSession());
                    VaultInteractiveSession vsession = new VaultInteractiveSession();
                    tool.setSession(vsession);
                    vsession.start();
                    break;
                case 1:
                    System.out.println(SecurityLogger.ROOT_LOGGER.removingInteractiveSession());
                    tool.setSession(null);
                    break;
                default:
                    in.close();
                    System.exit(0);
                }
            } catch (InputMismatchException e) {
                in.close();
                System.exit(0);
            }
        }
    }
}

From source file:uk.co.jwlawson.jcluster.demos.Mutator.java

/**
 * @param args//from  w w w.  ja va  2  s  .c  om
 */
public static void main(String[] args) {
    System.out.println("Mutator demo from jCluster  Copyright (C) 2014 John Lawson");
    System.out.println("This program comes with ABSOLUTELY NO WARRANTY. This is free");
    System.out.println("software, and you are welcome to redistribute it under certain");
    System.out.println("conditions.");
    if (Mutator.isValidArgs(args)) {
        Mutator mut = new Mutator(args);
        Scanner scan = new Scanner(System.in);
        System.out.println("Initial matrix:");
        mut.printMatrix();
        while (true) {
            System.out.print("Enter vertex to mutate at or q to quit: ");
            if (scan.hasNextInt()) {
                int k = scan.nextInt();
                mut.mutate(k);
                mut.printMatrix();
                System.out.println();
            } else {
                break;
            }
        }
        scan.close();
    } else {
        System.out.println("Usage:");
        System.out.println("    Mutator <diagram>");
        System.out.println("    Where diagram is the name of a Dynkin diagram");
        System.out.println();
        System.out.println("    e.g. Mutator A6");
    }
}

From source file:pa55.java.core.PA55.java

public static void main(String[] args)
        throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException {
    System.out.println("**** This is a reference implementation version " + APP_VERSION
            + " of pa55. Please see the project page (http://anirbanbasu.github.io/pa55/) for details. ****\r\n");
    Console inputConsole = System.console(); //If it is available, we need Console for masking passwords.
    Scanner inputConsoleScanner;/*  www  .jav a 2s. c  om*/
    Scanner echoOptionScanner = new Scanner(System.in);
    boolean disableEcho = false;
    if (inputConsole != null) {
        //We can hide the input, but should we? Ask the user.
        System.out.println(
                "Do you want to hide the master secret and the password hint as you type them? Enter 1 to hide or 0 to not hide.");
        disableEcho = echoOptionScanner.nextInt() == 0 ? false : true;
    }
    String echoNotice;
    if (disableEcho) {
        inputConsoleScanner = new Scanner(inputConsole.reader());
        echoNotice = " (your input will NOT be visible as you type)";
    } else {
        inputConsoleScanner = new Scanner(System.in);
        echoNotice = " (your input will be visible as you type)";
    }
    PA55 core = new PA55();
    String lineInput = "";
    System.out.println("Enter master secret" + echoNotice);
    lineInput = (disableEcho ? new String(inputConsole.readPassword()) : inputConsoleScanner.nextLine().trim());
    while (lineInput.length() == 0) {
        System.out.println("Please enter a non-empty string" + echoNotice);
        lineInput = (inputConsole != null ? new String(inputConsole.readPassword())
                : inputConsoleScanner.nextLine().trim());
    }
    core.setMasterSecret(lineInput);
    System.out.println("Enter password hint" + echoNotice);
    lineInput = (disableEcho ? new String(inputConsole.readPassword()) : inputConsoleScanner.nextLine().trim());
    while (lineInput.length() == 0) {
        System.out.println("Please enter a non-empty string" + echoNotice);
        lineInput = (inputConsole != null ? new String(inputConsole.readPassword())
                : inputConsoleScanner.nextLine().trim());
    }
    core.setPasswordHint(lineInput);
    int choiceInput = 0;
    System.out.println(
            "Choose desired length in characters:\r\n (0) default: 12 characters\r\n (1) 8 characters\r\n (2) 12 characters\r\n (3) 16 characters\r\n (4) 20 characters\r\n (5) 24 characters\r\n (6) 28 characters\r\n (7) 32 characters");
    choiceInput = inputConsoleScanner.nextInt();
    while (choiceInput < 0 || choiceInput > 7) {
        System.out.println("Please enter a choice between 0 and 7.");
        choiceInput = inputConsoleScanner.nextInt();
    }
    if (choiceInput == 0) {
        choiceInput = 2;
    }
    core.setPbkdfLength((choiceInput + 1) * 3);
    System.out.println(
            "Choose the password iterations:\r\n (0) default: 500K\r\n (1) Low (10K)\r\n (2) 250K\r\n (3) 500K\r\n (4) 750K\r\n (5) 1M\r\n (6) 1.25M\r\n (7) 1.5M");
    choiceInput = inputConsoleScanner.nextInt();
    while (choiceInput < 0 || choiceInput > 7) {
        System.out.println("Please enter a choice between 0 and 7.");
        choiceInput = inputConsoleScanner.nextInt();
    }
    if (choiceInput == 0) {
        choiceInput = 3;
    }
    if (choiceInput != 1) {
        core.setPbkdfRounds((choiceInput - 1) * 250000);
    } else {
        core.setPbkdfRounds(10000);
    }
    System.out.println(
            "Choose the HMAC algorithm:\r\n (0) default: SHA256\r\n (1) SHA1\r\n (2) SHA256\r\n (3) SHA512");
    choiceInput = inputConsoleScanner.nextInt();
    while (choiceInput < 0 || choiceInput > 3) {
        System.out.println("Please enter a choice between 0 and 3.");
        choiceInput = inputConsoleScanner.nextInt();
    }
    if (choiceInput == 0) {
        choiceInput = 2;
    }
    core.setPbkdfAlgorithm(HMACHashFunction.values()[choiceInput - 1]);
    inputConsoleScanner.close();
    echoOptionScanner.close();
    System.out.print("Generating password...\r");
    core.generatePBKDF2Password();
    System.out.println("Your password is: " + core.getPbkdfGeneratedPassword());
}

From source file:Clima.Clima.java

public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub
    Scanner lea = new Scanner(System.in);

    int op;//from  www.jav  a2  s .c  om

    do {
        System.out.println("----------\nMENU\n-----------");
        System.out.println("1- Ver todos los datos clima");
        System.out.println("2- Ver longuitud y Latitud");
        System.out.println("3- Temperatura minima y maxima");
        System.out.println("4- Humedad y Velocidad");
        System.out.println("Escoja Opcion: ");
        op = lea.nextInt();
        System.out.println("------------------------------------");
        System.out.println("Ingrase la ciudad que decea ver clima");
        System.out.println("-------------------------------------");
        String cuida = lea.next();
        System.out.println("--------------------------------------");

        switch (op) {
        case 1:
            try {

                String respuesta = getHTML("http://api.openweathermap.org/data/2.5/weather?q=" + cuida
                        + ",uk&appid=edf6a6fe68ae2a1259efacb437914a55");
                JSONObject obj = new JSONObject(respuesta);
                double temp = obj.getJSONObject("main").getDouble("temp") - 273.15;
                double lon = obj.getJSONObject("coord").getDouble("lon");
                double lat = obj.getJSONObject("coord").getDouble("lat");
                double pressure = obj.getJSONObject("main").getDouble("pressure");
                double humidity = obj.getJSONObject("main").getDouble("humidity");
                double temp_min = obj.getJSONObject("main").getDouble("temp_min") - 273.15;
                double temp_max = obj.getJSONObject("main").getDouble("temp_max") - 273.15;
                double speed = obj.getJSONObject("wind").getDouble("speed");
                System.out.println("Los datos optenidos de " + cuida);
                System.out.println("***************************************1");
                System.out.println("La temperatura es: " + temp + " Celsius");
                System.out.println("longuitud  es: " + lon);
                System.out.println("Latitud es: " + lat);
                System.out.println("La presurisacion  es: " + pressure);
                System.out.println("La humedad es: " + humidity);
                System.out.println("La temperatura minima es: " + temp_min + " Celsius");
                System.out.println("La temperatura maxima es: " + temp_max + " Celsius");
                System.out.println("La velocidad es: " + speed);

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Clima.main(null);
            break;
        case 2:
            try {

                String respuesta = getHTML("http://api.openweathermap.org/data/2.5/weather?q=" + cuida
                        + ",uk&appid=edf6a6fe68ae2a1259efacb437914a55");
                JSONObject obj = new JSONObject(respuesta);
                double lon = obj.getJSONObject("coord").getDouble("lon");
                double lat = obj.getJSONObject("coord").getDouble("lat");
                System.out.println("Los datos optenidos de" + cuida + "son:");
                System.out.print("longuitud  es: " + lon);
                System.out.print("Latitud es: " + lat);

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Clima.main(null);
            break;
        case 3:
            try {

                String respuesta = getHTML("http://api.openweathermap.org/data/2.5/weather?q=" + cuida
                        + ",uk&appid=edf6a6fe68ae2a1259efacb437914a55");
                JSONObject obj = new JSONObject(respuesta);
                double temp_min = obj.getJSONObject("main").getDouble("temp_min") - 273.15;
                double temp_max = obj.getJSONObject("main").getDouble("temp_max") - 273.15;
                System.out.println("Los datos optenidos de" + cuida + "son:");
                System.out.print("La temperatura minima es: " + temp_min + " Celsius");
                System.out.print("La temperatura maxima es: " + temp_max + " Celsius");

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Clima.main(null);
            break;
        case 4:
            try {

                String respuesta = getHTML("http://api.openweathermap.org/data/2.5/weather?q=" + cuida
                        + ",uk&appid=edf6a6fe68ae2a1259efacb437914a55");
                JSONObject obj = new JSONObject(respuesta);
                double humidity = obj.getJSONObject("main").getDouble("humidity");
                double speed = obj.getJSONObject("wind").getDouble("speed");
                System.out.println("Los datos optenidos de" + cuida + "son:");
                System.out.print("La humedad es: " + humidity);
                System.out.print("La velocidad es: " + speed);

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Clima.main(null);
            break;

        }
    } while (op != 8);

}

From source file:org.apache.tomcat.vault.VaultTool.java

public static void main(String[] args) {

    VaultTool tool = null;/*from   w  ww .j a v a  2 s . c o  m*/

    if (args != null && args.length > 0) {
        int returnVal = 0;
        try {
            tool = new VaultTool(args);
            returnVal = tool.execute();
            if (!skipSummary) {
                tool.summary();
            }
        } catch (Exception e) {
            System.err.println("Problem occured:");
            System.err.println(e.getMessage());
            System.exit(1);
        }
        System.exit(returnVal);
    } else {
        tool = new VaultTool();

        Console console = System.console();

        if (console == null) {
            System.err.println("No console.");
            System.exit(1);
        }

        Scanner in = new Scanner(System.in);
        while (true) {
            String commandStr = "Please enter a Digit::   0: Start Interactive Session "
                    + " 1: Remove Interactive Session " + " Other: Exit";

            System.out.println(commandStr);
            int choice = -1;

            try {
                choice = in.nextInt();
            } catch (InputMismatchException e) {
                System.err.println("'" + in.next() + "' is not a digit. Restart and enter a digit.");
                System.exit(3);
            }

            switch (choice) {
            case 0:
                System.out.println("Starting an interactive session");
                VaultInteractiveSession vsession = new VaultInteractiveSession();
                tool.setSession(vsession);
                vsession.start();
                break;
            case 1:
                System.out.println("Removing the current interactive session");
                tool.setSession(null);
                break;
            default:
                System.exit(0);
            }
        }

    }

}

From source file:com.github.horrorho.inflatabledonkey.Main.java

/**
 * @param args the command line arguments
 * @throws IOException/*from  w w  w .  j a va 2 s . co m*/
 */
public static void main(String[] args) throws IOException {
    try {
        if (!PropertyLoader.instance().test(args)) {
            return;
        }
    } catch (IllegalArgumentException ex) {
        System.out.println("Argument error: " + ex.getMessage());
        System.out.println("Try '" + Property.APP_NAME.value() + " --help' for more information.");
        System.exit(-1);
    }

    // SystemDefault HttpClient.
    // TODO concurrent
    CloseableHttpClient httpClient = HttpClients.custom().setUserAgent("CloudKit/479 (13A404)")
            .useSystemProperties().build();

    // Auth
    // TODO rework when we have UncheckedIOException for Authenticator
    Auth auth = Property.AUTHENTICATION_TOKEN.value().map(Auth::new).orElse(null);

    if (auth == null) {
        auth = Authenticator.authenticate(httpClient, Property.AUTHENTICATION_APPLEID.value().get(),
                Property.AUTHENTICATION_PASSWORD.value().get());
    }
    logger.debug("-- main() - auth: {}", auth);
    logger.info("-- main() - dsPrsID:mmeAuthToken: {}:{}", auth.dsPrsID(), auth.mmeAuthToken());

    if (Property.ARGS_TOKEN.booleanValue().orElse(false)) {
        System.out.println("DsPrsID:mmeAuthToken " + auth.dsPrsID() + ":" + auth.mmeAuthToken());
        return;
    }

    logger.info("-- main() - Apple ID: {}", Property.AUTHENTICATION_APPLEID.value());
    logger.info("-- main() - password: {}", Property.AUTHENTICATION_PASSWORD.value());
    logger.info("-- main() - token: {}", Property.AUTHENTICATION_TOKEN.value());

    // Account
    Account account = Accounts.account(httpClient, auth);

    // Backup
    Backup backup = Backup.create(httpClient, account);

    // BackupAccount
    BackupAccount backupAccount = backup.backupAccount(httpClient);
    logger.debug("-- main() - backup account: {}", backupAccount);

    // Devices
    List<Device> devices = backup.devices(httpClient, backupAccount.devices());
    logger.debug("-- main() - device count: {}", devices.size());

    // Snapshots
    List<SnapshotID> snapshotIDs = devices.stream().map(Device::snapshots).flatMap(Collection::stream)
            .collect(Collectors.toList());
    logger.info("-- main() - total snapshot count: {}", snapshotIDs.size());

    Map<String, Snapshot> snapshots = backup.snapshot(httpClient, snapshotIDs).stream().collect(
            Collectors.toMap(s -> s.record().getRecordIdentifier().getValue().getName(), Function.identity()));

    boolean repeat = false;
    do {

        for (int i = 0; i < devices.size(); i++) {
            Device device = devices.get(i);
            List<SnapshotID> deviceSnapshotIDs = device.snapshots();

            System.out.println(i + " " + device.info());

            for (int j = 0; j < deviceSnapshotIDs.size(); j++) {
                SnapshotID sid = deviceSnapshotIDs.get(j);
                System.out.println("\t" + j + snapshots.get(sid.id()).info() + "   " + sid.timestamp());
            }
        }
        if (Property.PRINT_SNAPSHOTS.booleanValue().orElse(false)) {
            return;
        }
        // Selection
        Scanner input = new Scanner(System.in);

        int deviceIndex;
        int snapshotIndex = Property.SELECT_SNAPSHOT_INDEX.intValue().get();

        if (devices.size() > 1) {
            System.out.printf("Select a device [0 - %d]: ", devices.size() - 1);
            deviceIndex = input.nextInt();
        } else
            deviceIndex = Property.SELECT_DEVICE_INDEX.intValue().get();

        if (deviceIndex >= devices.size() || deviceIndex < 0) {
            System.out.println("No such device: " + deviceIndex);
            System.exit(-1);
        }

        Device device = devices.get(deviceIndex);
        System.out.println("Selected device: " + deviceIndex + ", " + device.info());

        if (device.snapshots().size() > 1) {
            System.out.printf("Select a snapshot [0 - %d]: ", device.snapshots().size() - 1);
            snapshotIndex = input.nextInt();
        } else
            snapshotIndex = Property.SELECT_SNAPSHOT_INDEX.intValue().get();

        if (snapshotIndex >= devices.get(deviceIndex).snapshots().size() || snapshotIndex < 0) {
            System.out.println("No such snapshot for selected device: " + snapshotIndex);
            System.exit(-1);
        }

        logger.info("-- main() - arg device index: {}", deviceIndex);
        logger.info("-- main() - arg snapshot index: {}", snapshotIndex);

        String selected = devices.get(deviceIndex).snapshots().get(snapshotIndex).id();
        Snapshot snapshot = snapshots.get(selected);
        System.out.println("Selected snapshot: " + snapshotIndex + ", " + snapshot.info());

        // Asset list.
        List<Assets> assetsList = backup.assetsList(httpClient, snapshot);
        logger.info("-- main() - assets count: {}", assetsList.size());

        // Domains filter --domain option
        String chosenDomain = Property.FILTER_DOMAIN.value().orElse("").toLowerCase(Locale.US);
        logger.info("-- main() - arg domain substring filter: {}", Property.FILTER_DOMAIN.value());
        // Output domains --domains option
        if (Property.PRINT_DOMAIN_LIST.booleanValue().orElse(false)) {
            System.out.println("Domains / file count:");
            assetsList.stream().filter(a -> a.domain().isPresent())
                    .map(a -> a.domain().get() + " / " + a.files().size()).sorted()
                    .forEach(System.out::println);

            System.out.print("Type a domain ('null' to exit): ");
            chosenDomain = input.next().toLowerCase(Locale.US);
            if (chosenDomain.equals("null"))
                return;
            // TODO check Assets without domain information.
        }

        String domainSubstring = chosenDomain;

        Predicate<Optional<String>> domainFilter = domain -> domain.map(d -> d.toLowerCase(Locale.US))
                .map(d -> d.contains(domainSubstring)).orElse(false);

        List<String> files = Assets.files(assetsList, domainFilter);
        logger.info("-- main() - domain filtered file count: {}", files.size());

        // Output folders.
        Path outputFolder = Paths.get(Property.OUTPUT_FOLDER.value().orElse("output"));
        Path assetOutputFolder = outputFolder.resolve("assets"); // TODO assets value injection
        Path chunkOutputFolder = outputFolder.resolve("chunks"); // TODO chunks value injection
        logger.info("-- main() - output folder chunks: {}", chunkOutputFolder);
        logger.info("-- main() - output folder assets: {}", assetOutputFolder);

        // Download tools.
        AuthorizeAssets authorizeAssets = AuthorizeAssets.backupd();
        DiskChunkStore chunkStore = new DiskChunkStore(chunkOutputFolder);
        StandardChunkEngine chunkEngine = new StandardChunkEngine(chunkStore);
        AssetDownloader assetDownloader = new AssetDownloader(chunkEngine);
        KeyBagManager keyBagManager = backup.newKeyBagManager();

        // Mystery Moo. 
        Moo moo = new Moo(authorizeAssets, assetDownloader, keyBagManager);

        // Filename extension filter.
        String filenameExtension = Property.FILTER_EXTENSION.value().orElse("").toLowerCase(Locale.US);
        logger.info("-- main() - arg filename extension filter: {}", Property.FILTER_EXTENSION.value());

        Predicate<Asset> assetFilter = asset -> asset.relativePath().map(d -> d.toLowerCase(Locale.US))
                .map(d -> d.endsWith(filenameExtension)).orElse(false);

        // Batch process files in groups of 100.
        // TODO group files into batches based on file size.
        List<List<String>> batches = ListUtils.partition(files, 100);

        for (List<String> batch : batches) {
            List<Asset> assets = backup.assets(httpClient, batch).stream().filter(assetFilter::test)
                    .collect(Collectors.toList());
            logger.info("-- main() - filtered asset count: {}", assets.size());
            moo.download(httpClient, assets, assetOutputFolder);
        }
        System.out.print("Download other snapshot (Y/N)? ");
        repeat = input.next().toLowerCase(Locale.US).charAt(0) == 'y';
    } while (repeat == true);
}

From source file:math2605.gn_log.java

/**
 * @param args the command line arguments
 *///from  w  w w  .  ja  v  a2  s .co  m
public static void main(String[] args) {
    //get file name
    System.out.println("Please enter a file name:");
    Scanner scanner = new Scanner(System.in);
    String fileName = scanner.nextLine();
    List<String[]> pairs = new ArrayList<>();
    //get coordinate pairs and add to arraylist
    try {
        BufferedReader br = new BufferedReader(new FileReader(fileName));
        String line;
        while ((line = br.readLine()) != null) {
            String[] pair = line.split(",");
            pairs.add(pair);
        }
        br.close();
    } catch (Exception e) {
    }

    System.out.println("Please enter the value of a:");
    double a = scanner.nextInt();
    System.out.println("Please enter the value of b:");
    double b = scanner.nextInt();
    System.out.println("Please enter the value of c:");
    double c = scanner.nextInt();
    //init B, vector with 3 coordinates
    RealMatrix B = new Array2DRowRealMatrix(3, 1);
    B.setEntry(0, 0, a);
    B.setEntry(1, 0, b);
    B.setEntry(2, 0, c);

    System.out.println("Please enter the number of iteration for the Gauss-newton:");
    //init N, number of iterations
    int N = scanner.nextInt();

    //init r, vector of residuals
    RealMatrix r = new Array2DRowRealMatrix();
    setR(pairs, a, b, c, r);

    //init J, Jacobian of r
    RealMatrix J = new Array2DRowRealMatrix();
    setJ(pairs, a, b, c, r, J);

    System.out.println("J");
    System.out.println(J);
    System.out.println("r");
    System.out.println(r);

    RealMatrix sub = findQR(J, r);

    for (int i = N; i > 0; i--) {
        B = B.subtract(sub);
        double B0 = B.getEntry(0, 0);
        double B1 = B.getEntry(1, 0);
        double B2 = B.getEntry(2, 0);
        //CHANGE ABC TO USE B0, B1, B2
        setR(pairs, B0, B1, B2, r);
        setJ(pairs, B0, B1, B2, r, J);
    }
    System.out.println("B");
    System.out.println(B.toString());
}

From source file:math2605.gn_exp.java

/**
 * @param args the command line arguments
 *///from   w  w w  . ja  v  a2s .  c o  m
public static void main(String[] args) {
    //get file name
    System.out.println("Please enter a file name:");
    Scanner scanner = new Scanner(System.in);
    String fileName = scanner.nextLine();
    List<String[]> pairs = new ArrayList<>();
    //get coordinate pairs and add to arraylist
    try {
        BufferedReader br = new BufferedReader(new FileReader(fileName));
        String line;
        while ((line = br.readLine()) != null) {
            String[] pair = line.split(",");
            pairs.add(pair);
        }
        br.close();
    } catch (Exception e) {
    }

    System.out.println("Please enter the value of a:");
    double a = scanner.nextInt();
    System.out.println("Please enter the value of b:");
    double b = scanner.nextInt();
    System.out.println("Please enter the value of c:");
    double c = scanner.nextInt();
    //init B, vector with 3 coordinates
    RealMatrix B = new Array2DRowRealMatrix(3, 1);
    B.setEntry(0, 0, a);
    B.setEntry(1, 0, b);
    B.setEntry(2, 0, c);

    System.out.println("Please enter the number of iteration for the Gauss-newton:");
    //init N, number of iterations
    int N = scanner.nextInt();

    //init r, vector of residuals
    RealMatrix r = new Array2DRowRealMatrix();
    setR(pairs, a, b, c, r);

    //init J, Jacobian of r
    RealMatrix J = new Array2DRowRealMatrix();
    setJ(pairs, a, b, c, r, J);

    System.out.println("J");
    System.out.println(J);
    System.out.println("r");
    System.out.println(r);

    RealMatrix sub = findQR(J, r);

    for (int i = N; i > 0; i--) {
        B = B.subtract(sub);
        double B0 = B.getEntry(0, 0);
        double B1 = B.getEntry(1, 0);
        double B2 = B.getEntry(2, 0);
        //CHANGE ABC TO USE B0, B1, B2
        setR(pairs, B0, B1, B2, r);
        setJ(pairs, B0, B1, B2, r, J);
    }
    System.out.println("B");
    System.out.println(B.toString());

}