Example usage for java.util Random nextInt

List of usage examples for java.util Random nextInt

Introduction

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

Prototype

public int nextInt() 

Source Link

Document

Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence.

Usage

From source file:SortUtils.java

/**
 * Test method//from w w w.j  a v a  2  s. co  m
 */
public static void main(String[] args) {
    Comparator cmp = new Comparator() {
        public int compare(Object o1, Object o2) {
            return ((Comparable) o1).compareTo(o2);
        }
    };

    int n = 1000000;
    if (args.length == 1)
        try {
            n = Integer.parseInt(args[0]);
        } catch (Exception e) {
            System.err.println(e);
        }
    System.out.println("Generating " + n + " random integers...");
    java.util.Random random = new java.util.Random();
    Integer[] data = new Integer[n];
    for (int i = 0; i < n; i++) {
        data[i] = new Integer(Math.abs(random.nextInt()));
        //      data[i] = new Integer(i);
    }
    int[] indices;
    long time;

    System.out.print("Arrays.sort...");
    time = System.currentTimeMillis();
    Integer[] clone = (Integer[]) data.clone();
    Arrays.sort(clone, cmp);
    System.out.println(System.currentTimeMillis() - time + "ms");

    System.out.print("quicksort...");
    indices = identity(n);
    time = System.currentTimeMillis();
    sort(indices, data, cmp, false);
    System.out.println(System.currentTimeMillis() - time + "ms");
    for (int i = 1; i < n; i++)
        if (cmp.compare(data[indices[i - 1]], data[indices[i]]) > 0)
            System.err.println("proplem: quickSort at " + i);

    System.out.print("quicksort stable...");
    //    indices = identity(n);
    time = System.currentTimeMillis();
    sort(indices, data, cmp, true);
    System.out.println(System.currentTimeMillis() - time + "ms");
    for (int i = 1; i < n; i++) {
        int res = cmp.compare(data[indices[i - 1]], data[indices[i]]);
        if (res > 0)
            System.err.println("proplem: quickSort stable at " + i);
        if (res == 0 && indices[i - 1] > indices[i])
            System.err.println("proplem: quickSort stable (not stable) at " + i);
    }

    //    System.out.print("cheapsort...");
    //    time = System.currentTimeMillis();
    //    indices = cheapSort(data, cmp);
    //    System.out.println(System.currentTimeMillis()-time + "ms");
    //    for (int i = 1; i < n; i++)
    //      if (cmp.compare(data[indices[i-1]], data[indices[i]]) > 0)
    //        System.err.println("proplem: cheapSort at " + i);

    System.out.print("permutate copy...");
    time = System.currentTimeMillis();
    Object[] data_copy = permute(inverse(indices), data, true);
    System.out.println(System.currentTimeMillis() - time + "ms");
    for (int i = 1; i < n; i++)
        if (cmp.compare(data_copy[i - 1], data_copy[i]) > 0)
            System.err.println("proplem: permute copy at " + i);

    System.out.print("permutate original...");
    time = System.currentTimeMillis();
    permute(inverse(indices), data, false);
    System.out.println(System.currentTimeMillis() - time + "ms");
    for (int i = 1; i < n; i++)
        if (cmp.compare(data[i - 1], data[i]) > 0)
            System.err.println("proplem: permute original at " + i);
}

From source file:com.cloud.test.utils.TestClient.java

public static void main(String[] args) {
    String host = "http://localhost";
    String port = "8080";
    String testUrl = "/client/test";
    int numThreads = 1;

    try {/*from  w ww. j a  va2s.co  m*/
        // Parameters
        List<String> argsList = Arrays.asList(args);
        Iterator<String> iter = argsList.iterator();
        while (iter.hasNext()) {
            String arg = iter.next();
            // host
            if (arg.equals("-h")) {
                host = "http://" + iter.next();
            }

            if (arg.equals("-p")) {
                port = iter.next();
            }

            if (arg.equals("-t")) {
                numThreads = Integer.parseInt(iter.next());
            }

            if (arg.equals("-s")) {
                sleepTime = Long.parseLong(iter.next());
            }

            if (arg.equals("-c")) {
                cleanUp = Boolean.parseBoolean(iter.next());
                if (!cleanUp)
                    sleepTime = 0L; // no need to wait if we don't ever cleanup
            }

            if (arg.equals("-r")) {
                repeat = Boolean.parseBoolean(iter.next());
            }

            if (arg.equals("-u")) {
                numOfUsers = Integer.parseInt(iter.next());
            }

            if (arg.equals("-i")) {
                internet = Boolean.parseBoolean(iter.next());
            }
        }

        final String server = host + ":" + port + testUrl;
        s_logger.info("Starting test against server: " + server + " with " + numThreads + " thread(s)");
        if (cleanUp)
            s_logger.info("Clean up is enabled, each test will wait " + sleepTime + " ms before cleaning up");

        if (numOfUsers > 0) {
            s_logger.info("Pre-generating users for test of size : " + numOfUsers);
            users = new String[numOfUsers];
            Random ran = new Random();
            for (int i = 0; i < numOfUsers; i++) {
                users[i] = Math.abs(ran.nextInt()) + "-user";
            }
        }

        for (int i = 0; i < numThreads; i++) {
            new Thread(new Runnable() {
                public void run() {
                    do {
                        String username = null;
                        try {
                            long now = System.currentTimeMillis();
                            Random ran = new Random();
                            if (users != null) {
                                username = users[Math.abs(ran.nextInt()) % numOfUsers];
                            } else {
                                username = Math.abs(ran.nextInt()) + "-user";
                            }
                            NDC.push(username);

                            String url = server + "?email=" + username + "&password=" + username
                                    + "&command=deploy";
                            s_logger.info("Launching test for user: " + username + " with url: " + url);
                            HttpClient client = new HttpClient();
                            HttpMethod method = new GetMethod(url);
                            int responseCode = client.executeMethod(method);
                            boolean success = false;
                            String reason = null;
                            if (responseCode == 200) {
                                if (internet) {
                                    s_logger.info("Deploy successful...waiting 5 minute before SSH tests");
                                    Thread.sleep(300000L); // Wait 60 seconds so the linux VM can boot up.

                                    s_logger.info("Begin Linux SSH test");
                                    reason = sshTest(method.getResponseHeader("linuxIP").getValue());

                                    if (reason == null) {
                                        s_logger.info("Linux SSH test successful");
                                        s_logger.info("Begin Windows SSH test");
                                        reason = sshWinTest(method.getResponseHeader("windowsIP").getValue());
                                    }
                                }
                                if (reason == null) {
                                    if (internet) {
                                        s_logger.info("Windows SSH test successful");
                                    } else {
                                        s_logger.info("deploy test successful....now cleaning up");
                                        if (cleanUp) {
                                            s_logger.info(
                                                    "Waiting " + sleepTime + " ms before cleaning up vms");
                                            Thread.sleep(sleepTime);
                                        } else {
                                            success = true;
                                        }
                                    }
                                    if (users == null) {
                                        s_logger.info("Sending cleanup command");
                                        url = server + "?email=" + username + "&password=" + username
                                                + "&command=cleanup";
                                    } else {
                                        s_logger.info("Sending stop DomR / destroy VM command");
                                        url = server + "?email=" + username + "&password=" + username
                                                + "&command=stopDomR";
                                    }
                                    method = new GetMethod(url);
                                    responseCode = client.executeMethod(method);
                                    if (responseCode == 200) {
                                        success = true;
                                    } else {
                                        reason = method.getStatusText();
                                    }
                                } else {
                                    // Just stop but don't destroy the VMs/Routers
                                    s_logger.info("SSH test failed with reason '" + reason + "', stopping VMs");
                                    url = server + "?email=" + username + "&password=" + username
                                            + "&command=stop";
                                    responseCode = client.executeMethod(new GetMethod(url));
                                }
                            } else {
                                // Just stop but don't destroy the VMs/Routers
                                reason = method.getStatusText();
                                s_logger.info("Deploy test failed with reason '" + reason + "', stopping VMs");
                                url = server + "?email=" + username + "&password=" + username + "&command=stop";
                                client.executeMethod(new GetMethod(url));
                            }

                            if (success) {
                                s_logger.info("***** Completed test for user : " + username + " in "
                                        + ((System.currentTimeMillis() - now) / 1000L) + " seconds");
                            } else {
                                s_logger.info("##### FAILED test for user : " + username + " in "
                                        + ((System.currentTimeMillis() - now) / 1000L)
                                        + " seconds with reason : " + reason);
                            }
                        } catch (Exception e) {
                            s_logger.warn("Error in thread", e);
                            try {
                                HttpClient client = new HttpClient();
                                String url = server + "?email=" + username + "&password=" + username
                                        + "&command=stop";
                                client.executeMethod(new GetMethod(url));
                            } catch (Exception e1) {
                            }
                        } finally {
                            NDC.clear();
                        }
                    } while (repeat);
                }
            }).start();
        }
    } catch (Exception e) {
        s_logger.error(e);
    }
}

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

public static void main(String[] args) {
    final Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("Snippet 151");
    shell.setLayout(new FillLayout());
    final Table table = new Table(shell, SWT.BORDER | SWT.VIRTUAL);
    table.addListener(SWT.SetData, e -> {
        TableItem item = (TableItem) e.item;
        int index = table.indexOf(item);
        item.setText("Item " + data[index]);
    });//from   w w  w  . ja  v  a2s  . c o  m
    Thread thread = new Thread() {
        @Override
        public void run() {
            int count = 0;
            Random random = new Random();
            while (count++ < 500) {
                if (table.isDisposed())
                    return;
                // add 10 random numbers to array and sort
                int grow = 10;
                int[] newData = new int[data.length + grow];
                System.arraycopy(data, 0, newData, 0, data.length);
                int index = data.length;
                data = newData;
                for (int j = 0; j < grow; j++) {
                    data[index++] = random.nextInt();
                }
                Arrays.sort(data);
                display.syncExec(() -> {
                    if (table.isDisposed())
                        return;
                    table.setItemCount(data.length);
                    table.clearAll();
                });
                try {
                    Thread.sleep(500);
                } catch (Throwable t) {
                }
            }
        }
    };
    thread.start();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:MersenneTwisterFast.java

/**
 * Tests the code./*from  w  ww . ja  v  a  2 s  . c o m*/
 */
public static void main(String args[]) {
    int j;

    MersenneTwisterFast r;

    // CORRECTNESS TEST
    // COMPARE WITH http://www.math.keio.ac.jp/matumoto/CODES/MT2002/mt19937ar.out

    r = new MersenneTwisterFast(new int[] { 0x123, 0x234, 0x345, 0x456 });
    System.out.println("Output of MersenneTwisterFast with new (2002/1/26) seeding mechanism");
    for (j = 0; j < 1000; j++) {
        // first, convert the int from signed to "unsigned"
        long l = (long) r.nextInt();
        if (l < 0)
            l += 4294967296L; // max int value
        String s = String.valueOf(l);
        while (s.length() < 10)
            s = " " + s; // buffer
        System.out.print(s + " ");
        if (j % 5 == 4)
            System.out.println();
    }

    // SPEED TEST

    final long SEED = 4357;

    int xx;
    long ms;
    System.out.println("\nTime to test grabbing 100000000 ints");

    Random rr = new Random(SEED);
    xx = 0;
    ms = System.currentTimeMillis();
    for (j = 0; j < 100000000; j++)
        xx += rr.nextInt();
    System.out
            .println("java.util.Random: " + (System.currentTimeMillis() - ms) + "          Ignore this: " + xx);

    r = new MersenneTwisterFast(SEED);
    ms = System.currentTimeMillis();
    xx = 0;
    for (j = 0; j < 100000000; j++)
        xx += r.nextInt();
    System.out.println(
            "Mersenne Twister Fast: " + (System.currentTimeMillis() - ms) + "          Ignore this: " + xx);

    // TEST TO COMPARE TYPE CONVERSION BETWEEN
    // MersenneTwisterFast.java AND MersenneTwister.java

    System.out.println("\nGrab the first 1000 booleans");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextBoolean() + " ");
        if (j % 8 == 7)
            System.out.println();
    }
    if (!(j % 8 == 7))
        System.out.println();

    System.out.println("\nGrab 1000 booleans of increasing probability using nextBoolean(double)");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextBoolean((double) (j / 999.0)) + " ");
        if (j % 8 == 7)
            System.out.println();
    }
    if (!(j % 8 == 7))
        System.out.println();

    System.out.println("\nGrab 1000 booleans of increasing probability using nextBoolean(float)");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextBoolean((float) (j / 999.0f)) + " ");
        if (j % 8 == 7)
            System.out.println();
    }
    if (!(j % 8 == 7))
        System.out.println();

    byte[] bytes = new byte[1000];
    System.out.println("\nGrab the first 1000 bytes using nextBytes");
    r = new MersenneTwisterFast(SEED);
    r.nextBytes(bytes);
    for (j = 0; j < 1000; j++) {
        System.out.print(bytes[j] + " ");
        if (j % 16 == 15)
            System.out.println();
    }
    if (!(j % 16 == 15))
        System.out.println();

    byte b;
    System.out.println("\nGrab the first 1000 bytes -- must be same as nextBytes");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print((b = r.nextByte()) + " ");
        if (b != bytes[j])
            System.out.print("BAD ");
        if (j % 16 == 15)
            System.out.println();
    }
    if (!(j % 16 == 15))
        System.out.println();

    System.out.println("\nGrab the first 1000 shorts");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextShort() + " ");
        if (j % 8 == 7)
            System.out.println();
    }
    if (!(j % 8 == 7))
        System.out.println();

    System.out.println("\nGrab the first 1000 ints");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextInt() + " ");
        if (j % 4 == 3)
            System.out.println();
    }
    if (!(j % 4 == 3))
        System.out.println();

    System.out.println("\nGrab the first 1000 ints of different sizes");
    r = new MersenneTwisterFast(SEED);
    int max = 1;
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextInt(max) + " ");
        max *= 2;
        if (max <= 0)
            max = 1;
        if (j % 4 == 3)
            System.out.println();
    }
    if (!(j % 4 == 3))
        System.out.println();

    System.out.println("\nGrab the first 1000 longs");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextLong() + " ");
        if (j % 3 == 2)
            System.out.println();
    }
    if (!(j % 3 == 2))
        System.out.println();

    System.out.println("\nGrab the first 1000 longs of different sizes");
    r = new MersenneTwisterFast(SEED);
    long max2 = 1;
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextLong(max2) + " ");
        max2 *= 2;
        if (max2 <= 0)
            max2 = 1;
        if (j % 4 == 3)
            System.out.println();
    }
    if (!(j % 4 == 3))
        System.out.println();

    System.out.println("\nGrab the first 1000 floats");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextFloat() + " ");
        if (j % 4 == 3)
            System.out.println();
    }
    if (!(j % 4 == 3))
        System.out.println();

    System.out.println("\nGrab the first 1000 doubles");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextDouble() + " ");
        if (j % 3 == 2)
            System.out.println();
    }
    if (!(j % 3 == 2))
        System.out.println();

    System.out.println("\nGrab the first 1000 gaussian doubles");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextGaussian() + " ");
        if (j % 3 == 2)
            System.out.println();
    }
    if (!(j % 3 == 2))
        System.out.println();

}

From source file:MersenneTwisterFast.java

/**
 * Tests the code./*from w  w  w . j  a  v  a2s  . c  om*/
 * @param args arguments
 */
@SuppressWarnings({ "ConstantConditions" })
public static void main(String args[]) {
    int j;

    MersenneTwisterFast r;

    // CORRECTNESS TEST
    // COMPARE WITH http://www.math.keio.ac.jp/matumoto/CODES/MT2002/mt19937ar.out

    r = new MersenneTwisterFast(new int[] { 0x123, 0x234, 0x345, 0x456 });
    System.out.println("Output of MersenneTwisterFast with new (2002/1/26) seeding mechanism");
    for (j = 0; j < 1000; j++) {
        // first, convert the int from signed to "unsigned"
        long l = (long) r.nextInt();
        if (l < 0)
            l += 4294967296L; // max int value
        String s = String.valueOf(l);
        while (s.length() < 10)
            s = " " + s; // buffer
        System.out.print(s + " ");
        if (j % 5 == 4)
            System.out.println();
    }

    // SPEED TEST

    final long SEED = 4357;

    int xx;
    long ms;
    System.out.println("\nTime to test grabbing 100000000 ints");

    Random rr = new Random(SEED);
    xx = 0;
    ms = System.currentTimeMillis();
    for (j = 0; j < 100000000; j++)
        xx += rr.nextInt();
    System.out
            .println("java.util.Random: " + (System.currentTimeMillis() - ms) + "          Ignore this: " + xx);

    r = new MersenneTwisterFast(SEED);
    ms = System.currentTimeMillis();
    xx = 0;
    for (j = 0; j < 100000000; j++)
        xx += r.nextInt();
    System.out.println(
            "Mersenne Twister Fast: " + (System.currentTimeMillis() - ms) + "          Ignore this: " + xx);

    // TEST TO COMPARE TYPE CONVERSION BETWEEN
    // MersenneTwisterFast.java AND MersenneTwister.java

    System.out.println("\nGrab the first 1000 booleans");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextBoolean() + " ");
        if (j % 8 == 7)
            System.out.println();
    }
    if (!(j % 8 == 7))
        System.out.println();

    System.out.println("\nGrab 1000 booleans of increasing probability using nextBoolean(double)");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextBoolean(j / 999.0) + " ");
        if (j % 8 == 7)
            System.out.println();
    }
    if (!(j % 8 == 7))
        System.out.println();

    System.out.println("\nGrab 1000 booleans of increasing probability using nextBoolean(float)");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextBoolean(j / 999.0f) + " ");
        if (j % 8 == 7)
            System.out.println();
    }
    if (!(j % 8 == 7))
        System.out.println();

    byte[] bytes = new byte[1000];
    System.out.println("\nGrab the first 1000 bytes using nextBytes");
    r = new MersenneTwisterFast(SEED);
    r.nextBytes(bytes);
    for (j = 0; j < 1000; j++) {
        System.out.print(bytes[j] + " ");
        if (j % 16 == 15)
            System.out.println();
    }
    if (!(j % 16 == 15))
        System.out.println();

    byte b;
    System.out.println("\nGrab the first 1000 bytes -- must be same as nextBytes");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print((b = r.nextByte()) + " ");
        if (b != bytes[j])
            System.out.print("BAD ");
        if (j % 16 == 15)
            System.out.println();
    }
    if (!(j % 16 == 15))
        System.out.println();

    System.out.println("\nGrab the first 1000 shorts");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextShort() + " ");
        if (j % 8 == 7)
            System.out.println();
    }
    if (!(j % 8 == 7))
        System.out.println();

    System.out.println("\nGrab the first 1000 ints");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextInt() + " ");
        if (j % 4 == 3)
            System.out.println();
    }
    if (!(j % 4 == 3))
        System.out.println();

    System.out.println("\nGrab the first 1000 ints of different sizes");
    r = new MersenneTwisterFast(SEED);
    int max = 1;
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextInt(max) + " ");
        max *= 2;
        if (max <= 0)
            max = 1;
        if (j % 4 == 3)
            System.out.println();
    }
    if (!(j % 4 == 3))
        System.out.println();

    System.out.println("\nGrab the first 1000 longs");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextLong() + " ");
        if (j % 3 == 2)
            System.out.println();
    }
    if (!(j % 3 == 2))
        System.out.println();

    System.out.println("\nGrab the first 1000 longs of different sizes");
    r = new MersenneTwisterFast(SEED);
    long max2 = 1;
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextLong(max2) + " ");
        max2 *= 2;
        if (max2 <= 0)
            max2 = 1;
        if (j % 4 == 3)
            System.out.println();
    }
    if (!(j % 4 == 3))
        System.out.println();

    System.out.println("\nGrab the first 1000 floats");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextFloat() + " ");
        if (j % 4 == 3)
            System.out.println();
    }
    if (!(j % 4 == 3))
        System.out.println();

    System.out.println("\nGrab the first 1000 doubles");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextDouble() + " ");
        if (j % 3 == 2)
            System.out.println();

    }
    if (!(j % 3 == 2))
        System.out.println();

    System.out.println("\nGrab the first 1000 gaussian doubles");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextGaussian() + " ");
        if (j % 3 == 2)
            System.out.println();
    }
    if (!(j % 3 == 2))
        System.out.println();

}

From source file:com.cloud.test.stress.StressTestDirectAttach.java

public static void main(String[] args) {
    String host = "http://localhost";
    String port = "8092";
    String devPort = "8080";
    String apiUrl = "/client/api";

    try {/*from ww w  . jav  a  2 s  .co  m*/
        // Parameters
        List<String> argsList = Arrays.asList(args);
        Iterator<String> iter = argsList.iterator();
        while (iter.hasNext()) {
            String arg = iter.next();
            // host
            if (arg.equals("-h")) {
                host = "http://" + iter.next();
            }

            if (arg.equals("-p")) {
                port = iter.next();
            }
            if (arg.equals("-dp")) {
                devPort = iter.next();
            }

            if (arg.equals("-t")) {
                numThreads = Integer.parseInt(iter.next());
            }

            if (arg.equals("-s")) {
                sleepTime = Long.parseLong(iter.next());
            }
            if (arg.equals("-a")) {
                accountName = iter.next();
            }

            if (arg.equals("-c")) {
                cleanUp = Boolean.parseBoolean(iter.next());
                if (!cleanUp)
                    sleepTime = 0L; // no need to wait if we don't ever
                // cleanup
            }

            if (arg.equals("-r")) {
                repeat = Boolean.parseBoolean(iter.next());
            }

            if (arg.equals("-i")) {
                internet = Boolean.parseBoolean(iter.next());
            }

            if (arg.equals("-w")) {
                wait = Integer.parseInt(iter.next());
            }

            if (arg.equals("-z")) {
                zoneId = iter.next();
            }

            if (arg.equals("-so")) {
                serviceOfferingId = iter.next();
            }

        }

        final String server = host + ":" + port + "/";
        final String developerServer = host + ":" + devPort + apiUrl;
        s_logger.info("Starting test against server: " + server + " with " + numThreads + " thread(s)");
        if (cleanUp)
            s_logger.info("Clean up is enabled, each test will wait " + sleepTime + " ms before cleaning up");

        for (int i = 0; i < numThreads; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    do {
                        String username = null;
                        try {
                            long now = System.currentTimeMillis();
                            Random ran = new Random();
                            username = Math.abs(ran.nextInt()) + "-user";
                            NDC.push(username);

                            s_logger.info("Starting test for the user " + username);
                            int response = executeDeployment(server, developerServer, username);
                            boolean success = false;
                            String reason = null;

                            if (response == 200) {
                                success = true;
                                if (internet) {
                                    s_logger.info("Deploy successful...waiting 5 minute before SSH tests");
                                    Thread.sleep(300000L); // Wait 60
                                    // seconds so
                                    // the windows VM
                                    // can boot up and do a sys prep.

                                    s_logger.info("Begin Linux SSH test for account " + _account.get());
                                    reason = sshTest(_linuxIP.get(), _linuxPassword.get());

                                    if (reason == null) {
                                        s_logger.info(
                                                "Linux SSH test successful for account " + _account.get());
                                    }
                                }
                                if (reason == null) {
                                    if (internet) {
                                        s_logger.info(
                                                "Windows SSH test successful for account " + _account.get());
                                    } else {
                                        s_logger.info("deploy test successful....now cleaning up");
                                        if (cleanUp) {
                                            s_logger.info(
                                                    "Waiting " + sleepTime + " ms before cleaning up vms");
                                            Thread.sleep(sleepTime);
                                        } else {
                                            success = true;
                                        }
                                    }

                                    if (usageIterator >= numThreads) {
                                        int eventsAndBillingResponseCode = executeEventsAndBilling(server,
                                                developerServer);
                                        s_logger.info(
                                                "events and usage records command finished with response code: "
                                                        + eventsAndBillingResponseCode);
                                        usageIterator = 1;

                                    } else {
                                        s_logger.info(
                                                "Skipping events and usage records for this user: usageIterator "
                                                        + usageIterator + " and number of Threads "
                                                        + numThreads);
                                        usageIterator++;
                                    }

                                    if ((users == null) && (accountName == null)) {
                                        s_logger.info("Sending cleanup command");
                                        int cleanupResponseCode = executeCleanup(server, developerServer,
                                                username);
                                        s_logger.info("cleanup command finished with response code: "
                                                + cleanupResponseCode);
                                        success = (cleanupResponseCode == 200);
                                    } else {
                                        s_logger.info("Sending stop DomR / destroy VM command");
                                        int stopResponseCode = executeStop(server, developerServer, username);
                                        s_logger.info("stop(destroy) command finished with response code: "
                                                + stopResponseCode);
                                        success = (stopResponseCode == 200);
                                    }

                                } else {
                                    // Just stop but don't destroy the
                                    // VMs/Routers
                                    s_logger.info("SSH test failed for account " + _account.get()
                                            + "with reason '" + reason + "', stopping VMs");
                                    int stopResponseCode = executeStop(server, developerServer, username);
                                    s_logger.info(
                                            "stop command finished with response code: " + stopResponseCode);
                                    success = false; // since the SSH test
                                    // failed, mark the
                                    // whole test as
                                    // failure
                                }
                            } else {
                                // Just stop but don't destroy the
                                // VMs/Routers
                                s_logger.info("Deploy test failed with reason '" + reason + "', stopping VMs");
                                int stopResponseCode = executeStop(server, developerServer, username);
                                s_logger.info("stop command finished with response code: " + stopResponseCode);
                                success = false; // since the deploy test
                                // failed, mark the
                                // whole test as failure
                            }

                            if (success) {
                                s_logger.info("***** Completed test for user : " + username + " in "
                                        + ((System.currentTimeMillis() - now) / 1000L) + " seconds");

                            } else {
                                s_logger.info("##### FAILED test for user : " + username + " in "
                                        + ((System.currentTimeMillis() - now) / 1000L)
                                        + " seconds with reason : " + reason);
                            }
                            s_logger.info("Sleeping for " + wait + " seconds before starting next iteration");
                            Thread.sleep(wait);
                        } catch (Exception e) {
                            s_logger.warn("Error in thread", e);
                            try {
                                int stopResponseCode = executeStop(server, developerServer, username);
                                s_logger.info("stop response code: " + stopResponseCode);
                            } catch (Exception e1) {
                            }
                        } finally {
                            NDC.clear();
                        }
                    } while (repeat);
                }
            }).start();
        }
    } catch (Exception e) {
        s_logger.error(e);
    }
}

From source file:com.cloud.test.stress.TestClientWithAPI.java

public static void main(String[] args) {
    String host = "http://localhost";
    String port = "8092";
    String devPort = "8080";
    String apiUrl = "/client/api";

    try {/*from  w  ww.  j av  a2  s.c  o m*/
        // Parameters
        List<String> argsList = Arrays.asList(args);
        Iterator<String> iter = argsList.iterator();
        while (iter.hasNext()) {
            String arg = iter.next();
            // host
            if (arg.equals("-h")) {
                host = "http://" + iter.next();
            }

            if (arg.equals("-p")) {
                port = iter.next();
            }
            if (arg.equals("-dp")) {
                devPort = iter.next();
            }

            if (arg.equals("-t")) {
                numThreads = Integer.parseInt(iter.next());
            }

            if (arg.equals("-s")) {
                sleepTime = Long.parseLong(iter.next());
            }
            if (arg.equals("-a")) {
                accountName = iter.next();
            }

            if (arg.equals("-c")) {
                cleanUp = Boolean.parseBoolean(iter.next());
                if (!cleanUp)
                    sleepTime = 0L; // no need to wait if we don't ever
                // cleanup
            }

            if (arg.equals("-r")) {
                repeat = Boolean.parseBoolean(iter.next());
            }

            if (arg.equals("-u")) {
                numOfUsers = Integer.parseInt(iter.next());
            }

            if (arg.equals("-i")) {
                internet = Boolean.parseBoolean(iter.next());
            }

            if (arg.equals("-w")) {
                wait = Integer.parseInt(iter.next());
            }

            if (arg.equals("-z")) {
                zoneId = iter.next();
            }

            if (arg.equals("-snapshot")) {
                snapshot_test = "yes";
            }

            if (arg.equals("-so")) {
                serviceOfferingId = iter.next();
            }

            if (arg.equals("-do")) {
                diskOfferingId = iter.next();
            }

            if (arg.equals("-no")) {
                networkOfferingId = iter.next();
            }

            if (arg.equals("-pass")) {
                vmPassword = iter.next();
            }

            if (arg.equals("-url")) {
                downloadUrl = iter.next();
            }

        }

        final String server = host + ":" + port + "/";
        final String developerServer = host + ":" + devPort + apiUrl;
        s_logger.info("Starting test against server: " + server + " with " + numThreads + " thread(s)");
        if (cleanUp)
            s_logger.info("Clean up is enabled, each test will wait " + sleepTime + " ms before cleaning up");

        if (numOfUsers > 0) {
            s_logger.info("Pre-generating users for test of size : " + numOfUsers);
            users = new String[numOfUsers];
            Random ran = new Random();
            for (int i = 0; i < numOfUsers; i++) {
                users[i] = Math.abs(ran.nextInt()) + "-user";
            }
        }

        for (int i = 0; i < numThreads; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    do {
                        String username = null;
                        try {
                            long now = System.currentTimeMillis();
                            Random ran = new Random();
                            if (users != null) {
                                username = users[Math.abs(ran.nextInt()) % numOfUsers];
                            } else {
                                username = Math.abs(ran.nextInt()) + "-user";
                            }
                            NDC.push(username);

                            s_logger.info("Starting test for the user " + username);
                            int response = executeDeployment(server, developerServer, username, snapshot_test);
                            boolean success = false;
                            String reason = null;

                            if (response == 200) {
                                success = true;
                                if (internet) {
                                    s_logger.info("Deploy successful...waiting 5 minute before SSH tests");
                                    Thread.sleep(300000L); // Wait 60
                                    // seconds so
                                    // the windows VM
                                    // can boot up and do a sys prep.

                                    if (accountName == null) {
                                        s_logger.info("Begin Linux SSH test for account " + _account.get());
                                        reason = sshTest(_linuxIP.get(), _linuxPassword.get(), snapshot_test);
                                    }

                                    if (reason == null) {
                                        s_logger.info(
                                                "Linux SSH test successful for account " + _account.get());
                                        s_logger.info("Begin WindowsSSH test for account " + _account.get());

                                        reason = sshTest(_linuxIP.get(), _linuxPassword.get(), snapshot_test);
                                        // reason = sshWinTest(_windowsIP.get());
                                    }

                                    // release the linux IP now...
                                    _linuxIP.set(null);
                                    // release the Windows IP now
                                    _windowsIP.set(null);
                                }

                                // sleep for 3 min before getting the latest network stat
                                // s_logger.info("Sleeping for 5 min before getting the lates network stat for the account");
                                // Thread.sleep(300000);
                                // verify that network stat is correct for the user; if it's not - stop all the resources
                                // for the user
                                // if ((reason == null) && (getNetworkStat(server) == false) ) {
                                // s_logger.error("Stopping all the resources for the account " + _account.get() +
                                // " as network stat is incorrect");
                                // int stopResponseCode = executeStop(
                                // server, developerServer,
                                // username, false);
                                // s_logger
                                // .info("stop command finished with response code: "
                                // + stopResponseCode);
                                // success = false; // since the SSH test
                                //
                                // } else
                                if (reason == null) {
                                    if (internet) {
                                        s_logger.info(
                                                "Windows SSH test successful for account " + _account.get());
                                    } else {
                                        s_logger.info("deploy test successful....now cleaning up");
                                        if (cleanUp) {
                                            s_logger.info(
                                                    "Waiting " + sleepTime + " ms before cleaning up vms");
                                            Thread.sleep(sleepTime);
                                        } else {
                                            success = true;
                                        }
                                    }

                                    if (usageIterator >= numThreads) {
                                        int eventsAndBillingResponseCode = executeEventsAndBilling(server,
                                                developerServer);
                                        s_logger.info(
                                                "events and usage records command finished with response code: "
                                                        + eventsAndBillingResponseCode);
                                        usageIterator = 1;

                                    } else {
                                        s_logger.info(
                                                "Skipping events and usage records for this user: usageIterator "
                                                        + usageIterator + " and number of Threads "
                                                        + numThreads);
                                        usageIterator++;
                                    }

                                    if ((users == null) && (accountName == null)) {
                                        s_logger.info("Sending cleanup command");
                                        int cleanupResponseCode = executeCleanup(server, developerServer,
                                                username);
                                        s_logger.info("cleanup command finished with response code: "
                                                + cleanupResponseCode);
                                        success = (cleanupResponseCode == 200);
                                    } else {
                                        s_logger.info("Sending stop DomR / destroy VM command");
                                        int stopResponseCode = executeStop(server, developerServer, username,
                                                true);
                                        s_logger.info("stop(destroy) command finished with response code: "
                                                + stopResponseCode);
                                        success = (stopResponseCode == 200);
                                    }

                                } else {
                                    // Just stop but don't destroy the
                                    // VMs/Routers
                                    s_logger.info("SSH test failed for account " + _account.get()
                                            + "with reason '" + reason + "', stopping VMs");
                                    int stopResponseCode = executeStop(server, developerServer, username,
                                            false);
                                    s_logger.info(
                                            "stop command finished with response code: " + stopResponseCode);
                                    success = false; // since the SSH test
                                    // failed, mark the
                                    // whole test as
                                    // failure
                                }
                            } else {
                                // Just stop but don't destroy the
                                // VMs/Routers
                                s_logger.info("Deploy test failed with reason '" + reason + "', stopping VMs");
                                int stopResponseCode = executeStop(server, developerServer, username, true);
                                s_logger.info("stop command finished with response code: " + stopResponseCode);
                                success = false; // since the deploy test
                                // failed, mark the
                                // whole test as failure
                            }

                            if (success) {
                                s_logger.info("***** Completed test for user : " + username + " in "
                                        + ((System.currentTimeMillis() - now) / 1000L) + " seconds");

                            } else {
                                s_logger.info("##### FAILED test for user : " + username + " in "
                                        + ((System.currentTimeMillis() - now) / 1000L)
                                        + " seconds with reason : " + reason);
                            }
                            s_logger.info("Sleeping for " + wait + " seconds before starting next iteration");
                            Thread.sleep(wait);
                        } catch (Exception e) {
                            s_logger.warn("Error in thread", e);
                            try {
                                int stopResponseCode = executeStop(server, developerServer, username, true);
                                s_logger.info("stop response code: " + stopResponseCode);
                            } catch (Exception e1) {
                            }
                        } finally {
                            NDC.clear();
                        }
                    } while (repeat);
                }
            }).start();
        }
    } catch (Exception e) {
        s_logger.error(e);
    }
}

From source file:edu.usc.cssl.tacit.classify.naivebayes.services.Vectors2Classify.java

public static ArrayList<String> main(String[] args) throws bsh.EvalError, java.io.IOException {
    result.clear();/*from  w w w  . ja va2s  . c  o  m*/
    classifierTrainerStrings = new ArrayList<String>();
    ReportOptions = new boolean[][] { { false, false, false, false }, { false, false, false, false },
            { false, false, false, false } };

    double pvalue = 0;
    // Process the command-line options
    CommandOption.setSummary(Vectors2Classify.class,
            "A tool for training, saving and printing diagnostics from a classifier on vectors.");
    CommandOption.process(Vectors2Classify.class, args);

    // handle default trainer here for now; default argument processing
    // doesn't work
    if (!trainerConstructor.wasInvoked()) {
        classifierTrainerStrings.add("new NaiveBayesTrainer()");
    }

    if (!report.wasInvoked()) {
        ReportOptions = new boolean[][] { { true, false, false, false }, { true, false, true, false },
                { false, false, false, false } };
        //report.postParsing(null); // force postprocessing of default value

    }

    int verbosity = verbosityOption.value;

    Logger rootLogger = ((MalletLogger) progressLogger).getRootLogger();

    if (verbosityOption.wasInvoked()) {
        rootLogger.setLevel(MalletLogger.LoggingLevels[verbosity]);
    }

    if (noOverwriteProgressMessagesOption.value == false) {
        // install special formatting for progress messages
        // find console handler on root logger; change formatter to one
        // that knows about progress messages
        Handler[] handlers = rootLogger.getHandlers();
        for (int i = 0; i < handlers.length; i++) {
            if (handlers[i] instanceof ConsoleHandler) {
                handlers[i].setFormatter(new ProgressMessageLogFormatter());
            }
        }
    }

    boolean separateIlists = testFile.wasInvoked() || trainingFile.wasInvoked() || validationFile.wasInvoked();
    InstanceList ilist = null;
    InstanceList testFileIlist = null;
    InstanceList trainingFileIlist = null;
    InstanceList validationFileIlist = null;

    if (!separateIlists) { // normal case, --input-file specified
        // Read in the InstanceList, from stdin if the input filename is
        // "-".
        ilist = InstanceList.load(new File(inputFile.value));
        //ilist = new InstanceList(ilist.getAlphabet(), ilist.getAlphabet());
    } else { // user specified separate files for testing and training sets.
        trainingFileIlist = InstanceList.load(new File(trainingFile.value));
        logger.info("Training vectors loaded from " + trainingFile.value);

        if (testFile.wasInvoked()) {
            testFileIlist = InstanceList.load(new File(testFile.value));
            logger.info("Testing vectors loaded from " + testFile.value);

            if (!testFileIlist.getPipe().alphabetsMatch(trainingFileIlist.getPipe())) {
                throw new RuntimeException(trainingFileIlist.getPipe().getDataAlphabet() + "\n"
                        + testFileIlist.getPipe().getDataAlphabet() + "\n"
                        + trainingFileIlist.getPipe().getTargetAlphabet() + "\n"
                        + testFileIlist.getPipe().getTargetAlphabet() + "\n"
                        + "Training and testing alphabets don't match!\n");
            }
        }

        if (validationFile.wasInvoked()) {
            validationFileIlist = InstanceList.load(new File(validationFile.value));
            logger.info("validation vectors loaded from " + validationFile.value);
            if (!validationFileIlist.getPipe().alphabetsMatch(trainingFileIlist.getPipe())) {
                throw new RuntimeException(trainingFileIlist.getPipe().getDataAlphabet() + "\n"
                        + validationFileIlist.getPipe().getDataAlphabet() + "\n"
                        + trainingFileIlist.getPipe().getTargetAlphabet() + "\n"
                        + validationFileIlist.getPipe().getTargetAlphabet() + "\n"
                        + "Training and validation alphabets don't match!\n");
            }
        } else {
            validationFileIlist = new InstanceList(new cc.mallet.pipe.Noop());
        }

    }

    if (crossValidation.wasInvoked() && trainingProportionOption.wasInvoked()) {
        logger.warning(
                "Both --cross-validation and --training-portion were invoked.  Using cross validation with "
                        + crossValidation.value + " folds.");
    }
    if (crossValidation.wasInvoked() && validationProportionOption.wasInvoked()) {
        logger.warning(
                "Both --cross-validation and --validation-portion were invoked.  Using cross validation with "
                        + crossValidation.value + " folds.");
    }
    if (crossValidation.wasInvoked() && numTrialsOption.wasInvoked()) {
        logger.warning("Both --cross-validation and --num-trials were invoked.  Using cross validation with "
                + crossValidation.value + " folds.");
    }

    int numTrials;
    if (crossValidation.wasInvoked()) {
        numTrials = crossValidation.value;
    } else {
        numTrials = numTrialsOption.value;
    }

    Random r = randomSeedOption.wasInvoked() ? new Random(randomSeedOption.value) : new Random();

    int numTrainers = classifierTrainerStrings.size();

    double trainAccuracy[][] = new double[numTrainers][numTrials];
    double testAccuracy[][] = new double[numTrainers][numTrials];
    double validationAccuracy[][] = new double[numTrainers][numTrials];

    String trainConfusionMatrix[][] = new String[numTrainers][numTrials];
    String testConfusionMatrix[][] = new String[numTrainers][numTrials];
    String validationConfusionMatrix[][] = new String[numTrainers][numTrials];

    double t = trainingProportionOption.value;
    double v = validationProportionOption.value;

    if (!separateIlists) {
        if (crossValidation.wasInvoked()) {
            logger.info("Cross-validation folds = " + crossValidation.value);
        } else {
            logger.info("Training portion = " + t);
            logger.info(" Unlabeled training sub-portion = " + unlabeledProportionOption.value);
            logger.info("Validation portion = " + v);
            logger.info("Testing portion = " + (1 - v - t));
        }
    }

    // for (int i=0; i<3; i++){
    // for (int j=0; j<4; j++){
    // System.out.print(" " + ReportOptions[i][j]);
    // }
    // System.out.println();
    // }

    CrossValidationIterator cvIter;
    if (crossValidation.wasInvoked()) {
        if (crossValidation.value < 2) {
            throw new RuntimeException(
                    "At least two folds (set with --cross-validation) are required for cross validation");
        }
        //System.out.println("Alphabets : "+ ilist.getDataAlphabet() +":"+ ilist.getTargetAlphabet());
        cvIter = new CrossValidationIterator(ilist, crossValidation.value, r);
    } else {
        cvIter = null;
    }

    String[] trainerNames = new String[numTrainers];
    for (int trialIndex = 0; trialIndex < numTrials; trialIndex++) {
        System.out.println("\n-------------------- Trial " + trialIndex + "  --------------------\n");
        InstanceList[] ilists;
        BitSet unlabeledIndices = null;
        if (!separateIlists) {
            if (crossValidation.wasInvoked()) {
                InstanceList[] cvSplit = cvIter.next();
                ilists = new InstanceList[3];
                ilists[0] = cvSplit[0];
                ilists[1] = cvSplit[1];
                ilists[2] = cvSplit[0].cloneEmpty();
            } else {
                ilists = ilist.split(r, new double[] { t, 1 - t - v, v });
            }
        } else {
            ilists = new InstanceList[3];
            ilists[0] = trainingFileIlist;
            ilists[1] = testFileIlist;
            ilists[2] = validationFileIlist;
        }

        if (unlabeledProportionOption.value > 0)
            unlabeledIndices = new cc.mallet.util.Randoms(r.nextInt()).nextBitSet(ilists[0].size(),
                    unlabeledProportionOption.value);

        // InfoGain ig = new InfoGain (ilists[0]);
        // int igl = Math.min (10, ig.numLocations());
        // for (int i = 0; i < igl; i++)
        // System.out.println
        // ("InfoGain["+ig.getObjectAtRank(i)+"]="+ig.getValueAtRank(i));
        // ig.print();

        // FeatureSelection selectedFeatures = new FeatureSelection (ig,
        // 8000);
        // ilists[0].setFeatureSelection (selectedFeatures);
        // OddsRatioFeatureInducer orfi = new OddsRatioFeatureInducer
        // (ilists[0]);
        // orfi.induceFeatures (ilists[0], false, true);

        // System.out.println
        // ("Training with "+ilists[0].size()+" instances");
        long time[] = new long[numTrainers];
        for (int c = 0; c < numTrainers; c++) {
            time[c] = System.currentTimeMillis();
            ClassifierTrainer trainer = getTrainer(classifierTrainerStrings.get(c));
            trainer.setValidationInstances(ilists[2]);
            // ConsoleView.writeInConsole("Trial " + trialIndex + " Training " + trainer + " with " + ilists[0].size() + " instances");
            ConsoleView.printlInConsoleln("Training " + trainer + " with " + ilists[0].size() + " instances");
            if (unlabeledProportionOption.value > 0)
                ilists[0].hideSomeLabels(unlabeledIndices);
            Classifier classifier = trainer.train(ilists[0]);
            if (unlabeledProportionOption.value > 0)
                ilists[0].unhideAllLabels();

            //ConsoleView.writeInConsole("Trial " + trialIndex + " Training " + trainer.toString() + " finished");
            ConsoleView.printlInConsoleln("Training " + trainer.toString() + " finished");
            time[c] = System.currentTimeMillis() - time[c];
            Trial trainTrial = new Trial(classifier, ilists[0]);
            // assert (ilists[1].size() > 0);
            Trial testTrial = new Trial(classifier, ilists[1]);
            Trial validationTrial = new Trial(classifier, ilists[2]);

            // gdruck - only perform evaluation if requested in report
            // options
            if (ReportOptions[ReportOption.train][ReportOption.confusion] && ilists[0].size() > 0)
                trainConfusionMatrix[c][trialIndex] = new ConfusionMatrix(trainTrial).toString();
            if (ReportOptions[ReportOption.test][ReportOption.confusion] && ilists[1].size() > 0)
                testConfusionMatrix[c][trialIndex] = new ConfusionMatrix(testTrial).toString();
            if (ReportOptions[ReportOption.validation][ReportOption.confusion] && ilists[2].size() > 0)
                validationConfusionMatrix[c][trialIndex] = new ConfusionMatrix(validationTrial).toString();

            // gdruck - only perform evaluation if requested in report
            // options
            if (ReportOptions[ReportOption.train][ReportOption.accuracy])
                trainAccuracy[c][trialIndex] = trainTrial.getAccuracy();
            if (ReportOptions[ReportOption.test][ReportOption.accuracy])
                testAccuracy[c][trialIndex] = testTrial.getAccuracy();
            if (ReportOptions[ReportOption.validation][ReportOption.accuracy])
                validationAccuracy[c][trialIndex] = validationTrial.getAccuracy();

            if (outputFile.wasInvoked()) {
                String filename = outputFile.value;
                if (numTrainers > 1)
                    filename = filename + trainer.toString();
                if (numTrials > 1)
                    filename = filename + ".trial" + trialIndex;
                try {
                    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename));
                    oos.writeObject(classifier);
                    oos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new IllegalArgumentException("Couldn't write classifier to filename " + filename);
                }
            }

            // New Reporting

            // raw output
            if (ReportOptions[ReportOption.train][ReportOption.raw]) {
                System.out.println("Trial " + trialIndex + " Trainer " + trainer.toString());
                System.out.println(" Raw Training Data");
                printTrialClassification(trainTrial);
            }

            if (ReportOptions[ReportOption.test][ReportOption.raw]) {
                System.out.println("Trial " + trialIndex + " Trainer " + trainer.toString());
                System.out.println(" Raw Testing Data");
                printTrialClassification(testTrial);
                //System.out.println("Report Option :"+(ReportOptions[ReportOption.test][ReportOption.raw]));
            }

            if (ReportOptions[ReportOption.validation][ReportOption.raw]) {
                System.out.println("Trial " + trialIndex + " Trainer " + trainer.toString());
                System.out.println(" Raw Validation Data");
                printTrialClassification(validationTrial);
            }
            System.out.println(
                    "Bino test vars size " + ilists[1].size() + "and accuracy + " + testTrial.getAccuracy()
                            + " then success " + (int) testTrial.getAccuracy() * ilists[1].size());
            BinomialTest binomtest = new BinomialTest();
            double p = 0.5;

            // train
            if (ReportOptions[ReportOption.train][ReportOption.confusion]) {
                //ConsoleView.writeInConsole("Trial " + trialIndex + " Trainer "    + trainer.toString() + " Training Data Confusion Matrix");
                ConsoleView.printlInConsoleln(trainer.toString() + " Training Data Confusion Matrix");
                if (ilists[0].size() > 0)
                    ConsoleView.printlInConsoleln(trainConfusionMatrix[c][trialIndex]);
            }

            if (ReportOptions[ReportOption.train][ReportOption.accuracy]) {
                pvalue = binomtest.binomialTest(ilists[0].size(),
                        (int) (trainTrial.getAccuracy() * ilists[0].size()), p,
                        AlternativeHypothesis.TWO_SIDED);
                if (pvalue != 0) {
                    if (pvalue > 0.5)
                        pvalue = Math.abs(pvalue - 1);
                    ConsoleView.printlInConsoleln("Binomial 2-Sided P value = " + pvalue + "\n");
                }

                //ConsoleView.writeInConsole("Trial " + trialIndex + " Trainer " + trainer.toString() + " training data accuracy= " + trainAccuracy[c][trialIndex]);
                ConsoleView.printlInConsoleln(
                        trainer.toString() + " training data accuracy= " + trainAccuracy[c][trialIndex]);
            }

            if (ReportOptions[ReportOption.train][ReportOption.f1]) {
                String label = ReportOptionArgs[ReportOption.train][ReportOption.f1];
                //ConsoleView.writeInConsole("Trial " + trialIndex + " Trainer "+ trainer.toString() + " training data F1(" + label + ") = " + trainTrial.getF1(label));
                ConsoleView.printlInConsoleln(
                        trainer.toString() + " training data F1(" + label + ") = " + trainTrial.getF1(label));
            }

            // validation
            if (ReportOptions[ReportOption.validation][ReportOption.confusion]) {
                //   ConsoleView.writeInConsole("Trial " + trialIndex + " Trainer " + trainer.toString() + " Validation Data Confusion Matrix");
                ConsoleView.printlInConsoleln(trainer.toString() + " Validation Data Confusion Matrix");
                if (ilists[2].size() > 0)
                    ConsoleView.printlInConsoleln(validationConfusionMatrix[c][trialIndex]);
            }

            if (ReportOptions[ReportOption.validation][ReportOption.accuracy]) {
                //ConsoleView.writeInConsole("Trial " + trialIndex + " Trainer " + trainer.toString() + " validation data accuracy= " + validationAccuracy[c][trialIndex]);
                ConsoleView.printlInConsoleln(
                        trainer.toString() + " validation data accuracy= " + validationAccuracy[c][trialIndex]);
            }

            if (ReportOptions[ReportOption.validation][ReportOption.f1]) {
                String label = ReportOptionArgs[ReportOption.validation][ReportOption.f1];
                //ConsoleView.writeInConsole("Trial " + trialIndex + " Trainer " + trainer.toString() + " validation data F1(" + label + ") = " + validationTrial.getF1(label));
                ConsoleView.printlInConsoleln(trainer.toString() + " validation data F1(" + label + ") = "
                        + validationTrial.getF1(label));
            }

            // test
            if (ReportOptions[ReportOption.test][ReportOption.confusion]) {
                //ConsoleView.writeInConsole("Trial " + trialIndex + " Trainer " + trainer.toString() + " Test Data Confusion Matrix");
                ConsoleView.printlInConsoleln(trainer.toString() + " Test Data Confusion Matrix");
                if (ilists[1].size() > 0)
                    ConsoleView.printlInConsoleln(testConfusionMatrix[c][trialIndex]);
            }

            if (ReportOptions[ReportOption.test][ReportOption.accuracy]) {
                pvalue = binomtest.binomialTest(ilists[1].size(),
                        (int) (testTrial.getAccuracy() * ilists[1].size()), 0.5,
                        AlternativeHypothesis.TWO_SIDED);
                if (pvalue != 0) {
                    if (pvalue > 0.5)
                        pvalue = Math.abs(pvalue - 1);
                    ConsoleView.printlInConsoleln("Binomial 2-Sided P value = " + pvalue + " \n");
                }

                //ConsoleView.writeInConsole("Trial " + trialIndex + " Trainer " + trainer.toString() + " test data accuracy= " + testAccuracy[c][trialIndex]);
                ConsoleView.printlInConsoleln(
                        trainer.toString() + " test data accuracy= " + testAccuracy[c][trialIndex]);
            }

            if (ReportOptions[ReportOption.test][ReportOption.f1]) {
                String label = ReportOptionArgs[ReportOption.test][ReportOption.f1];
                //ConsoleView.writeInConsole("Trial " + trialIndex + " Trainer " + trainer.toString() + " test data F1(" + label + ") = " + testTrial.getF1(label));
                ConsoleView.printlInConsoleln(
                        trainer.toString() + " test data F1(" + label + ") = " + testTrial.getF1(label));
            }

            if (trialIndex == 0)
                trainerNames[c] = trainer.toString();

        } // end for each trainer
    } // end for each trial

    // New reporting
    // "[train|test|validation]:[accuracy|f1|confusion|raw]"
    for (int c = 0; c < numTrainers; c++) {
        ConsoleView.printlInConsole("\n" + trainerNames[c].toString() + "\n");
        if (ReportOptions[ReportOption.train][ReportOption.accuracy]) {
            /*ConsoleView.printlInConsoleln("Summary. train accuracy mean = "
                  + MatrixOps.mean(trainAccuracy[c]) + " stddev = "
                  + MatrixOps.stddev(trainAccuracy[c]) + " stderr = "
                  + MatrixOps.stderr(trainAccuracy[c])); */

            String trainResult = "";
            if (pvalue != 0)
                trainResult += "Summary. train accuracy = " + MatrixOps.mean(trainAccuracy[c]);
            else
                trainResult += "Summary. train accuracy = " + MatrixOps.mean(trainAccuracy[c]);

            if (numTrials > 1) {
                trainResult += " stddev = " + MatrixOps.stddev(trainAccuracy[c]) + " stderr = "
                        + MatrixOps.stderr(trainAccuracy[c]);
            }
            ConsoleView.printlInConsoleln(trainResult);

        }

        if (ReportOptions[ReportOption.validation][ReportOption.accuracy]) {
            /*
            ConsoleView.printlInConsoleln("Summary. validation accuracy mean = "
                  + MatrixOps.mean(validationAccuracy[c]) + " stddev = "
                  + MatrixOps.stddev(validationAccuracy[c])
                  + " stderr = "
                  + MatrixOps.stderr(validationAccuracy[c]));*/

            String validationResult = "";
            if (pvalue != 0)
                validationResult += "Summary. validation accuracy = " + MatrixOps.mean(validationAccuracy[c]);
            else
                validationResult += "Summary. validation accuracy = " + MatrixOps.mean(validationAccuracy[c]);

            if (numTrials > 1) {
                validationResult += " stddev = " + MatrixOps.stddev(validationAccuracy[c]) + " stderr = "
                        + MatrixOps.stderr(validationAccuracy[c]);
            }
            ConsoleView.printlInConsoleln(validationResult);

        }

        if (ReportOptions[ReportOption.test][ReportOption.accuracy]) {
            String testResult = "";
            if (pvalue != 0)
                testResult += "Summary. test accuracy = " + MatrixOps.mean(testAccuracy[c])
                        + " Binomial 2-Sided Pvalue = " + pvalue;
            else
                testResult += "Summary. test accuracy = " + MatrixOps.mean(testAccuracy[c])
                        + " Pvalue < 10^(-1022)\n";

            if (numTrials > 1) {
                testResult += " stddev = " + MatrixOps.stddev(testAccuracy[c]) + " stderr = "
                        + MatrixOps.stderr(testAccuracy[c]);
            }
            ConsoleView.printlInConsoleln(testResult);

            /*
            if (pvalue != 0)
               ConsoleView.printlInConsoleln("Summary. test accuracy mean = "
             + MatrixOps.mean(testAccuracy[c]) + " stddev = "
             + MatrixOps.stddev(testAccuracy[c]) + " stderr = "
             + MatrixOps.stderr(testAccuracy[c]) + " pvalue = "
             + pvalue);
            else
               ConsoleView.printlInConsoleln("Summary. test accuracy mean = "
             + MatrixOps.mean(testAccuracy[c]) + " stddev = "
             + MatrixOps.stddev(testAccuracy[c]) + " stderr = "
             + MatrixOps.stderr(testAccuracy[c])
             + " P value < 10^(-1022)\n"); */
        }

        // If we are testing the classifier with two folders, result will be
        // empty - no report is generated
        if (result.isEmpty()) {
            if (pvalue != 0)
                result.add("Summary. test accuracy = " + MatrixOps.mean(testAccuracy[c])
                        + " Binomial 2-Sided  Pvalue = " + pvalue);
            else
                result.add("Summary. test accuracy = " + MatrixOps.mean(testAccuracy[c])
                        + " Pvalue < 10^(-1022)\n");

            if (numTrials > 1) {
                result.add(" stddev = " + MatrixOps.stddev(testAccuracy[c]) + " stderr = "
                        + MatrixOps.stderr(testAccuracy[c]));
            }
        }
    } // end for each trainer

    return result;
}

From source file:Main.java

public synchronized static String getOutTradeNo() {
    SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss", Locale.getDefault());
    Date date = new Date();
    String key = format.format(date);
    Random r = new Random();
    key = key + r.nextInt();
    key = key.substring(0, 15);//from   ww w .  j  a v  a 2  s  . com
    return key;
}

From source file:Main.java

public static String getRandomFileName() {
    String _df = android.text.format.DateFormat.format("MMddyyyyhhmmss", new java.util.Date()).toString();
    Random r = new Random();
    int random = Math.abs(r.nextInt() % 100);
    return String.format("%d%s.jpg", random, _df);
}