Example usage for java.util Random Random

List of usage examples for java.util Random Random

Introduction

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

Prototype

public Random() 

Source Link

Document

Creates a new random number generator.

Usage

From source file:com.khartec.waltz.jobs.sample.EndUserAppMaker.java

public static void main(String[] args) {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(DIConfiguration.class);
    OrganisationalUnitDao organisationalUnitDao = ctx.getBean(OrganisationalUnitDao.class);

    DSLContext dsl = ctx.getBean(DSLContext.class);

    EndUserAppService endUserService = ctx.getBean(EndUserAppService.class);

    List<Long> ids = IdUtilities.toIds(organisationalUnitDao.findAll());

    String[] subjects = { "Trade", "Risk", "Balance", "PnL", "Rate", "Fines", "Party", "Confirmations",
            "Settlement", "Instruction", "Person", "Profit", "Margin", "Finance", "Account" };

    String[] types = { "Report", "Summary", "Draft", "Calculations", "Breaks", "Record", "Statement",
            "Information", "Pivot" };

    String[] tech = { "MS ACCESS", "MS EXCEL", "VBA" };

    dsl.delete(END_USER_APPLICATION).execute();
    final Long[] idCounter = { 1L };
    ids.forEach(ouId -> {//from   w w w.ja  v a 2  s .c o  m
        for (int i = 0; i < new Random().nextInt(100) + 40; i++) {
            EndUserApplicationRecord record = dsl.newRecord(END_USER_APPLICATION);
            String name = new StringBuilder().append(randomPick(subjects)).append(" ")
                    .append(randomPick(subjects)).append(" ").append(randomPick(types)).append(" ")
                    .append(randomPick(types)).toString();

            record.setName(name);
            record.setDescription("About the " + name + " End user app");
            record.setKind(randomPick(tech));
            record.setRiskRating(randomPick(RiskRating.values()).name());
            record.setLifecyclePhase(randomPick(LifecyclePhase.values()).name());
            record.setOrganisationalUnitId(ouId);

            record.setId(idCounter[0]++);
            record.insert();
        }
    });

}

From source file:FileList.java

public static void main(String[] args) {
    final int assumedLineLength = 50;
    File file = new File(args[0]);
    List<String> fileList = new ArrayList<String>((int) (file.length() / assumedLineLength) * 2);
    BufferedReader reader = null;
    int lineCount = 0;
    try {/* w  w w  . j a  va 2s .  co m*/
        reader = new BufferedReader(new FileReader(file));
        for (String line = reader.readLine(); line != null; line = reader.readLine()) {
            fileList.add(line);
            lineCount++;
        }
    } catch (IOException e) {
        System.err.format("Could not read %s: %s%n", file, e);
        System.exit(1);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
            }
        }
    }
    int repeats = Integer.parseInt(args[1]);
    Random random = new Random();
    for (int i = 0; i < repeats; i++) {
        System.out.format("%d: %s%n", i, fileList.get(random.nextInt(lineCount - 1)));
    }
}

From source file:de.ingrid.interfaces.csw.admin.IndexDriver.java

/**
 * @param args/*from w  ww .j  a  va 2  s.  c  o m*/
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    if (!System.getProperties().containsKey("jetty.webapp"))
        log.warn("Property 'jetty.webapp' not defined! Using default webapp directory, which is '"
                + DEFAULT_WEBAPP_DIR + "'.");
    if (!System.getProperties().containsKey("jetty.port"))
        log.warn("Property 'jetty.port' not defined! Using default port, which is '" + DEFAULT_JETTY_PORT
                + "'.");

    WebAppContext webAppContext = new WebAppContext(System.getProperty("jetty.webapp", DEFAULT_WEBAPP_DIR),
            "/");

    Server server = new Server(Integer.getInteger("jetty.port", DEFAULT_JETTY_PORT));
    // fix slow startup time on virtual machine env.
    HashSessionIdManager hsim = new HashSessionIdManager();
    hsim.setRandom(new Random());
    server.setSessionIdManager(hsim);
    server.setHandler(webAppContext);
    server.start();
    WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(
            webAppContext.getServletContext(),
            "org.springframework.web.servlet.FrameworkServlet.CONTEXT.springapp");
    IndexRunnable r = (IndexRunnable) wac.getBean("indexRunnable");
    r.run();
    System.out.println("Try to stopping the iPlug...");
    server.stop();
    System.out.println("iPlug is stopped.");
}

From source file:com.aestel.chemistry.openEye.fp.FPDictionarySorter.java

public static void main(String... args) throws IOException {
    long start = System.currentTimeMillis();
    int iCounter = 0;
    int fpCounter = 0;

    // create command line Options object
    Options options = new Options();
    Option opt = new Option("i", true, "input file [.ism,.sdf,...]");
    opt.setRequired(true);/*from   ww w . j  a  v a2s. c  om*/
    options.addOption(opt);

    opt = new Option("fpType", true, "fingerPrintType: maccs|linear7|linear7*4");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option("sampleFract", true, "fraction of input molecules to use (Default=1)");
    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 (cmd.hasOption("d")) {
        System.err.println("Start debugger and press return:");
        new BufferedReader(new InputStreamReader(System.in)).readLine();
    }

    if (args.length != 0) {
        exitWithHelp(options);
    }

    String type = cmd.getOptionValue("fpType");
    boolean updateDictionaryFile = false;
    boolean hashUnknownFrag = false;
    Fingerprinter fprinter = Fingerprinter.createFingerprinter(type, updateDictionaryFile, hashUnknownFrag);
    OEMolBase mol = new OEGraphMol();

    String inFile = cmd.getOptionValue("i");
    oemolistream ifs = new oemolistream(inFile);

    double fract = 2D;
    String tmp = cmd.getOptionValue("sampleFract");
    if (tmp != null)
        fract = Double.parseDouble(tmp);

    Random rnd = new Random();

    LearningStrcutureCodeMapper mapper = (LearningStrcutureCodeMapper) fprinter.getMapper();
    int dictSize = mapper.getMaxIdx() + 1;
    int[] freq = new int[dictSize];

    while (oechem.OEReadMolecule(ifs, mol)) {
        iCounter++;
        if (rnd.nextDouble() < fract) {
            fpCounter++;

            Fingerprint fp = fprinter.getFingerprint(mol);
            for (int bit : fp.getBits())
                freq[bit]++;
        }

        if (iCounter % 100 == 0)
            System.err.print(".");
        if (iCounter % 4000 == 0) {
            System.err.printf(" %d %d %dsec\n", iCounter, fpCounter,
                    (System.currentTimeMillis() - start) / 1000);
        }
    }

    System.err.printf("FPDictionarySorter: Read %d structures calculated %d fprints in %d sec\n", iCounter,
            fpCounter, (System.currentTimeMillis() - start) / 1000);

    mapper.reSortDictionary(freq);
    mapper.writeDictionary();
    fprinter.close();
}

From source file:com.asquareb.kaaval.MachineKey.java

/**
 * Main method to execute as a command line utility. Provides the option to
 * encrypt a string, decrypt a encrypted string or exit from the program
 *//*from w w w.  j a v a 2  s  . c o m*/
public static void main(String[] args) {
    String originalPassword = null;
    String encryptedPassword = null;
    try {
        final BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter E - Encrypt,D - Decrypt,X - Exit :");
        final String choice = cin.readLine();
        final Random rand = new Random();
        boolean phraseCorrect = false;
        String app = null;
        if (choice.equalsIgnoreCase("E")) {
            System.out.print("Enter the string to encrypt :");
            originalPassword = cin.readLine();
            System.out.println("Choose a phrase of min 8 chars in length ");
            System.out.println(" Also the password should include 2 Cap,");
            System.out.println(" 2 small letters,2 numeric and 2 non alpha numeric chars");
            while (!phraseCorrect) {
                System.out.print("Enter a phrase to encrypt :");
                password = cin.readLine().toCharArray();
                phraseCorrect = PasswordRules.verifyPassword(password);
            }
            System.out.print("Enter application code :");
            app = cin.readLine();
            app += (rand.nextInt(10000));
            encryptedPassword = encrypt(originalPassword, app);
            System.out.println("Encrypted password :" + encryptedPassword);
            System.out.println("Key stored in :" + app);
            System.out.println("*** Provide the encrypted string to app team");
            System.out.println("*** Store the key file in a secure durectory");
            System.out.println("*** Inform the key file name and location to app team");
        } else if (choice.equalsIgnoreCase("D")) {
            System.out.print("Enter the string to Decrypt :");
            encryptedPassword = cin.readLine();
            System.out.print("Enter the name of key file :");
            app = cin.readLine();
            final String decryptedPassword = decrypt(encryptedPassword, app);
            System.out.print("Decrypted string :" + decryptedPassword);
        }
        return;
    } catch (KaavalException e) {
        e.PrintProtectException();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:knop.utils.stats.DataSet.java

/**
 * The main method.//from w  w w.ja v a2  s. c  o m
 *
 * @param args the arguments
 */
public static void main(String[] args) {

    DataSet fdt = new DataSet();

    // fdt.importFile("/home/cyril/data.txt");

    Random rn = new Random();

    for (int i = 0; i != 10; i++) {

        fdt.addValue("c1", i);
        if (i % 2 == 0)
            fdt.addValue("c2", 2);
        if (i % 3 == 0)
            fdt.addValue("c3", 3);
        if (i % 4 == 0)
            fdt.addValue("c4", 4);
        if (i % 5 == 0)
            fdt.addValue("c5", 5);
        /*
        fdt.addValue("fwhmX", rn.nextDouble() * 3);
        fdt.addValue("fwhmY", rn.nextDouble() * 2);
        fdt.addValue("fwhmZ", rn.nextDouble() * 5);*/

    }

    //fdt.addValue("control", "positive");

    //fdt.threshold("x", 2, 0);
    //fdt.setTheoriticalValue("fwhmX", 3.2);
    //fdt.setTheoriticalValue("fwhmY", 2.3);
    //fdt.setTheoriticalValue("fwhmZ", 4.5);

    System.out.println(fdt.exportToString());
    System.out.println(fdt.exportToString());
    System.out.println(fdt.exportToString());
    //   System.out.println(fdt.getColumnStatistics("y"));

}

From source file:com.mapr.PurchaseLog.java

public static void main(String[] args) throws IOException {
    Options opts = new Options();
    CmdLineParser parser = new CmdLineParser(opts);
    try {/*from  w  w  w  .java  2s  . c  om*/
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println("Usage: -count <number>G|M|K [ -users number ]  log-file user-profiles");
        return;
    }

    Joiner withTab = Joiner.on("\t");

    // first generate lots of user definitions
    SchemaSampler users = new SchemaSampler(
            Resources.asCharSource(Resources.getResource("user-schema.txt"), Charsets.UTF_8).read());
    File userFile = File.createTempFile("user", "tsv");
    BufferedWriter out = Files.newBufferedWriter(userFile.toPath(), Charsets.UTF_8);
    for (int i = 0; i < opts.users; i++) {
        out.write(withTab.join(users.sample()));
        out.newLine();
    }
    out.close();

    // now generate a session for each user
    Splitter onTabs = Splitter.on("\t");
    Splitter onComma = Splitter.on(",");

    Random gen = new Random();
    SchemaSampler intermediate = new SchemaSampler(
            Resources.asCharSource(Resources.getResource("hit_step.txt"), Charsets.UTF_8).read());

    final int COUNTRY = users.getFieldNames().indexOf("country");
    final int CAMPAIGN = intermediate.getFieldNames().indexOf("campaign_list");
    final int SEARCH_TERMS = intermediate.getFieldNames().indexOf("search_keywords");
    Preconditions.checkState(COUNTRY >= 0, "Need country field in user schema");
    Preconditions.checkState(CAMPAIGN >= 0, "Need campaign_list field in step schema");
    Preconditions.checkState(SEARCH_TERMS >= 0, "Need search_keywords field in step schema");

    out = Files.newBufferedWriter(new File(opts.out).toPath(), Charsets.UTF_8);

    for (String line : Files.readAllLines(userFile.toPath(), Charsets.UTF_8)) {
        long t = (long) (TimeUnit.MILLISECONDS.convert(30, TimeUnit.DAYS) * gen.nextDouble());
        List<String> user = Lists.newArrayList(onTabs.split(line));

        // pick session length
        int n = (int) Math.floor(-30 * Math.log(gen.nextDouble()));

        for (int i = 0; i < n; i++) {
            // time on page
            int dt = (int) Math.floor(-20000 * Math.log(gen.nextDouble()));
            t += dt;

            // hit specific values
            JsonNode step = intermediate.sample();

            // check for purchase
            double p = 0.01;
            List<String> campaigns = Lists.newArrayList(onComma.split(step.get("campaign_list").asText()));
            List<String> keywords = Lists.newArrayList(onComma.split(step.get("search_keywords").asText()));
            if ((user.get(COUNTRY).equals("us") && campaigns.contains("5"))
                    || (user.get(COUNTRY).equals("jp") && campaigns.contains("7")) || keywords.contains("homer")
                    || keywords.contains("simpson")) {
                p = 0.5;
            }

            String events = gen.nextDouble() < p ? "1" : "-";

            out.write(Long.toString(t));
            out.write("\t");
            out.write(line);
            out.write("\t");
            out.write(withTab.join(step));
            out.write("\t");
            out.write(events);
            out.write("\n");
        }
    }
    out.close();
}

From source file:com.cloud.test.longrun.PerformanceWithAPI.java

public static void main(String[] args) {

    List<String> argsList = Arrays.asList(args);
    Iterator<String> iter = argsList.iterator();
    String host = "http://localhost";
    int numThreads = 1;

    while (iter.hasNext()) {
        String arg = iter.next();
        if (arg.equals("-h")) {
            host = "http://" + iter.next();
        }//  w w  w.  j ava  2  s .  co m
        if (arg.equals("-t")) {
            numThreads = Integer.parseInt(iter.next());
        }
        if (arg.equals("-n")) {
            numVM = Integer.parseInt(iter.next());
        }
    }

    final String server = host + ":" + _apiPort + "/";
    final String developerServer = host + ":" + _developerPort + _apiUrl;

    s_logger.info("Starting test in " + numThreads + " thread(s). Each thread is launching " + numVM + " VMs");

    for (int i = 0; i < numThreads; i++) {
        new Thread(new Runnable() {
            public void run() {
                try {

                    String username = null;
                    String singlePrivateIp = null;
                    String singlePublicIp = null;
                    Random ran = new Random();
                    username = Math.abs(ran.nextInt()) + "-user";

                    //Create User
                    User myUser = new User(username, username, server, developerServer);
                    try {
                        myUser.launchUser();
                        myUser.registerUser();
                    } catch (Exception e) {
                        s_logger.warn("Error code: ", e);
                    }

                    if (myUser.getUserId() != null) {
                        s_logger.info("User " + myUser.getUserName()
                                + " was created successfully, starting VM creation");
                        //create VMs for the user
                        for (int i = 0; i < numVM; i++) {
                            //Create a new VM, add it to the list of user's VMs
                            VirtualMachine myVM = new VirtualMachine(myUser.getUserId());
                            myVM.deployVM(_zoneId, _serviceOfferingId, _templateId, myUser.getDeveloperServer(),
                                    myUser.getApiKey(), myUser.getSecretKey());
                            myUser.getVirtualMachines().add(myVM);
                            singlePrivateIp = myVM.getPrivateIp();

                            if (singlePrivateIp != null) {
                                s_logger.info(
                                        "VM with private Ip " + singlePrivateIp + " was successfully created");
                            } else {
                                s_logger.info("Problems with VM creation for a user" + myUser.getUserName());
                                break;
                            }

                            //get public IP address for the User            
                            myUser.retrievePublicIp(_zoneId);
                            singlePublicIp = myUser.getPublicIp().get(myUser.getPublicIp().size() - 1);
                            if (singlePublicIp != null) {
                                s_logger.info("Successfully got public Ip " + singlePublicIp + " for user "
                                        + myUser.getUserName());
                            } else {
                                s_logger.info("Problems with getting public Ip address for user"
                                        + myUser.getUserName());
                                break;
                            }

                            //create ForwardProxy rules for user's VMs
                            int responseCode = CreateForwardingRule(myUser, singlePrivateIp, singlePublicIp,
                                    "22", "22");
                            if (responseCode == 500)
                                break;
                        }

                        s_logger.info("Deployment successful..." + numVM
                                + " VMs were created. Waiting for 5 min before performance test");
                        Thread.sleep(300000L); // Wait 

                        //Start performance test for the user
                        s_logger.info("Starting performance test for Guest network that has "
                                + myUser.getPublicIp().size() + " public IP addresses");
                        for (int j = 0; j < myUser.getPublicIp().size(); j++) {
                            s_logger.info("Starting test for user which has "
                                    + myUser.getVirtualMachines().size() + " vms. Public IP for the user is "
                                    + myUser.getPublicIp().get(j) + " , number of retries is " + _retry
                                    + " , private IP address of the machine is"
                                    + myUser.getVirtualMachines().get(j).getPrivateIp());
                            guestNetwork myNetwork = new guestNetwork(myUser.getPublicIp().get(j), _retry);
                            myNetwork.setVirtualMachines(myUser.getVirtualMachines());
                            new Thread(myNetwork).start();
                        }

                    }
                } catch (Exception e) {
                    s_logger.error(e);
                }
            }
        }).start();

    }
}

From source file:ch.epfl.lsir.xin.test.GlobalMeanTest.java

/**
 * @param args/*from   www  . ja  v a2s .  c  o  m*/
 */
public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub

    PrintWriter logger = new PrintWriter(".//results//GlobalMean");

    PropertiesConfiguration config = new PropertiesConfiguration();
    config.setFile(new File("conf//GlobalMean.properties"));
    try {
        config.load();
    } catch (ConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Read rating data...");
    DataLoaderFile loader = new DataLoaderFile(".//data//MoveLens100k.txt");
    loader.readSimple();
    DataSetNumeric dataset = loader.getDataset();
    System.out.println("Number of ratings: " + dataset.getRatings().size() + " Number of users: "
            + dataset.getUserIDs().size() + " Number of items: " + dataset.getItemIDs().size());
    logger.println("Number of ratings: " + dataset.getRatings().size() + ", Number of users: "
            + dataset.getUserIDs().size() + ", Number of items: " + dataset.getItemIDs().size());

    double totalMAE = 0;
    double totalRMSE = 0;
    int F = 5;
    logger.println(F + "- folder cross validation.");
    logger.flush();
    ArrayList<ArrayList<NumericRating>> folders = new ArrayList<ArrayList<NumericRating>>();
    for (int i = 0; i < F; i++) {
        folders.add(new ArrayList<NumericRating>());
    }
    while (dataset.getRatings().size() > 0) {
        int index = new Random().nextInt(dataset.getRatings().size());
        int r = new Random().nextInt(F);
        folders.get(r).add(dataset.getRatings().get(index));
        dataset.getRatings().remove(index);
    }
    for (int folder = 1; folder <= F; folder++) {
        System.out.println("Folder: " + folder);
        logger.println("Folder: " + folder);
        ArrayList<NumericRating> trainRatings = new ArrayList<NumericRating>();
        ArrayList<NumericRating> testRatings = new ArrayList<NumericRating>();
        for (int i = 0; i < folders.size(); i++) {
            if (i == folder - 1)//test data
            {
                testRatings.addAll(folders.get(i));
            } else {//training data
                trainRatings.addAll(folders.get(i));
            }
        }

        //create rating matrix
        HashMap<String, Integer> userIDIndexMapping = new HashMap<String, Integer>();
        HashMap<String, Integer> itemIDIndexMapping = new HashMap<String, Integer>();
        for (int i = 0; i < dataset.getUserIDs().size(); i++) {
            userIDIndexMapping.put(dataset.getUserIDs().get(i), i);
        }
        for (int i = 0; i < dataset.getItemIDs().size(); i++) {
            itemIDIndexMapping.put(dataset.getItemIDs().get(i), i);
        }
        RatingMatrix trainRatingMatrix = new RatingMatrix(dataset.getUserIDs().size(),
                dataset.getItemIDs().size());
        for (int i = 0; i < trainRatings.size(); i++) {
            trainRatingMatrix.set(userIDIndexMapping.get(trainRatings.get(i).getUserID()),
                    itemIDIndexMapping.get(trainRatings.get(i).getItemID()), trainRatings.get(i).getValue());
        }
        RatingMatrix testRatingMatrix = new RatingMatrix(dataset.getUserIDs().size(),
                dataset.getItemIDs().size());
        for (int i = 0; i < testRatings.size(); i++) {
            testRatingMatrix.set(userIDIndexMapping.get(testRatings.get(i).getUserID()),
                    itemIDIndexMapping.get(testRatings.get(i).getItemID()), testRatings.get(i).getValue());
        }
        System.out.println("Training: " + trainRatingMatrix.getTotalRatingNumber() + " vs Test: "
                + testRatingMatrix.getTotalRatingNumber());

        logger.println("Initialize a recommendation model based on global average method.");
        GlobalAverage algo = new GlobalAverage(trainRatingMatrix);
        algo.setLogger(logger);
        algo.build();
        algo.saveModel(".//localModels//" + config.getString("NAME"));
        logger.println("Save the model.");
        logger.flush();

        System.out.println(trainRatings.size() + " vs. " + testRatings.size());

        double RMSE = 0;
        double MAE = 0;
        int count = 0;
        for (int i = 0; i < testRatings.size(); i++) {
            NumericRating rating = testRatings.get(i);
            double prediction = algo.predict(rating.getUserID(), rating.getItemID());
            if (Double.isNaN(prediction)) {
                System.out.println("no prediction");
                continue;
            }
            MAE = MAE + Math.abs(rating.getValue() - prediction);
            RMSE = RMSE + Math.pow((rating.getValue() - prediction), 2);
            count++;
        }
        MAE = MAE / count;
        RMSE = Math.sqrt(RMSE / count);

        //         System.out.println("MAE: " + MAE + " RMSE: " + RMSE);
        logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " MAE: " + MAE
                + " RMSE: " + RMSE);
        logger.flush();
        totalMAE = totalMAE + MAE;
        totalRMSE = totalRMSE + RMSE;
    }

    System.out.println("MAE: " + totalMAE / F + " RMSE: " + totalRMSE / F);
    logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Final results: MAE: "
            + totalMAE / F + " RMSE: " + totalRMSE / F);
    logger.flush();
    logger.close();
    //MAE: 0.9338607074893257 RMSE: 1.1170971131112037 (MovieLens1M)
    //MAE: 0.9446876509332618 RMSE: 1.1256517870920375 (MovieLens100K)

}

From source file:ch.epfl.lsir.xin.test.UserAverageTest.java

/**
 * @param args//from  ww  w . j a  v  a2s. c o m
 */
public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub

    PrintWriter logger = new PrintWriter(".//results//UserAverage");
    PropertiesConfiguration config = new PropertiesConfiguration();
    config.setFile(new File(".//conf//UserAverage.properties"));
    try {
        config.load();
    } catch (ConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Read rating data...");
    DataLoaderFile loader = new DataLoaderFile(".//data//MoveLens100k.txt");
    loader.readSimple();
    DataSetNumeric dataset = loader.getDataset();
    System.out.println("Number of ratings: " + dataset.getRatings().size() + " Number of users: "
            + dataset.getUserIDs().size() + " Number of items: " + dataset.getItemIDs().size());
    logger.println("Number of ratings: " + dataset.getRatings().size() + " Number of users: "
            + dataset.getUserIDs().size() + " Number of items: " + dataset.getItemIDs().size());
    logger.flush();

    double totalMAE = 0;
    double totalRMSE = 0;
    int F = 5;
    logger.println(F + "- folder cross validation.");
    ArrayList<ArrayList<NumericRating>> folders = new ArrayList<ArrayList<NumericRating>>();
    for (int i = 0; i < F; i++) {
        folders.add(new ArrayList<NumericRating>());
    }
    while (dataset.getRatings().size() > 0) {
        int index = new Random().nextInt(dataset.getRatings().size());
        int r = new Random().nextInt(F);
        folders.get(r).add(dataset.getRatings().get(index));
        dataset.getRatings().remove(index);
    }
    for (int folder = 1; folder <= F; folder++) {
        logger.println("Folder: " + folder);
        System.out.println("Folder: " + folder);
        ArrayList<NumericRating> trainRatings = new ArrayList<NumericRating>();
        ArrayList<NumericRating> testRatings = new ArrayList<NumericRating>();
        for (int i = 0; i < folders.size(); i++) {
            if (i == folder - 1)//test data
            {
                testRatings.addAll(folders.get(i));
            } else {//training data
                trainRatings.addAll(folders.get(i));
            }
        }

        //create rating matrix
        HashMap<String, Integer> userIDIndexMapping = new HashMap<String, Integer>();
        HashMap<String, Integer> itemIDIndexMapping = new HashMap<String, Integer>();
        for (int i = 0; i < dataset.getUserIDs().size(); i++) {
            userIDIndexMapping.put(dataset.getUserIDs().get(i), i);
        }
        for (int i = 0; i < dataset.getItemIDs().size(); i++) {
            itemIDIndexMapping.put(dataset.getItemIDs().get(i), i);
        }
        RatingMatrix trainRatingMatrix = new RatingMatrix(dataset.getUserIDs().size(),
                dataset.getItemIDs().size());
        for (int i = 0; i < trainRatings.size(); i++) {
            trainRatingMatrix.set(userIDIndexMapping.get(trainRatings.get(i).getUserID()),
                    itemIDIndexMapping.get(trainRatings.get(i).getItemID()), trainRatings.get(i).getValue());
        }
        trainRatingMatrix.calculateGlobalAverage();
        RatingMatrix testRatingMatrix = new RatingMatrix(dataset.getUserIDs().size(),
                dataset.getItemIDs().size());
        for (int i = 0; i < testRatings.size(); i++) {
            testRatingMatrix.set(userIDIndexMapping.get(testRatings.get(i).getUserID()),
                    itemIDIndexMapping.get(testRatings.get(i).getItemID()), testRatings.get(i).getValue());
        }
        System.out.println("Training: " + trainRatingMatrix.getTotalRatingNumber() + " vs Test: "
                + testRatingMatrix.getTotalRatingNumber());

        logger.println("Initialize a recommendation model based on user average method.");
        UserAverage algo = new UserAverage(trainRatingMatrix);
        algo.setLogger(logger);
        algo.build();
        algo.saveModel(".//localModels//" + config.getString("NAME"));
        logger.println("Save the model.");
        System.out.println(trainRatings.size() + " vs. " + testRatings.size());

        double RMSE = 0;
        double MAE = 0;
        int count = 0;
        for (int i = 0; i < testRatings.size(); i++) {
            NumericRating rating = testRatings.get(i);
            double prediction = algo.predict(userIDIndexMapping.get(rating.getUserID()),
                    itemIDIndexMapping.get(rating.getItemID()));
            if (Double.isNaN(prediction)) {
                System.out.println("no prediction");
                continue;
            }
            MAE = MAE + Math.abs(rating.getValue() - prediction);
            RMSE = RMSE + Math.pow((rating.getValue() - prediction), 2);
            count++;
        }
        MAE = MAE / count;
        RMSE = Math.sqrt(RMSE / count);

        logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " MAE: " + MAE
                + " RMSE: " + RMSE);
        logger.flush();
        totalMAE = totalMAE + MAE;
        totalRMSE = totalRMSE + RMSE;
    }

    System.out.println("MAE: " + totalMAE / F + " RMSE: " + totalRMSE / F);
    logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Final results: MAE: "
            + totalMAE / F + " RMSE: " + totalRMSE / F);
    logger.flush();
    logger.close();
    //MAE: 0.8353035962363073 RMSE: 1.0422971886952053 (MovieLens 100k)
}