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(int bound) 

Source Link

Document

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.

Usage

From source file:edu.umn.cs.sthadoop.operations.HSPKNNQ.java

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

    //./hadoop jar /export/scratch/louai/idea-stHadoop/st-hadoop-uber.jar pknn /mntgIndex/yyyy-MM-dd/2017-08-03 /pknn k:2 point:-78.9659,35.7998 shape:edu.umn.cs.sthadoop.mntg.STPointMntg -overwrite  
    //    args = new String[8];
    //    args[0] = "/export/scratch/mntgData/mntgIndex";
    //    args[1] = "/export/scratch/mntgData/pknn";
    //    args[2] = "-overwrite";
    //    args[3] = "k:10";
    //    args[4] = "point:-78.9659063204100,35.7903907684998";
    //    args[5] = "shape:edu.umn.cs.sthadoop.trajectory.STPointTrajectory";
    //    args[6] = "interval:2017-08-03,2017-08-04";
    //    args[7] = "-overwrite";
    final OperationsParams params = new OperationsParams(new GenericOptionsParser(args));
    Path[] paths = params.getPaths();
    if (paths.length <= 1 && !params.checkInput()) {
        printUsage();/* w  w  w.  ja va2  s  .  c  o  m*/
        System.exit(1);
    }
    if (paths.length > 1 && !params.checkInputOutput()) {
        printUsage();
        System.exit(1);
    }

    if (params.get("interval") == null) {
        System.err.println("Temporal range missing");
        printUsage();
        System.exit(1);
    }

    TextSerializable inObj = params.getShape("shape");
    if (!(inObj instanceof STPoint)) {
        if (!(inObj instanceof STRectangle)) {
            LOG.error("Shape is not instance of STPoint or instance of STRectangle");
            printUsage();
            System.exit(1);
        }

    }

    // path to the spatio-temporal index.
    List<Path> STPaths = new ArrayList<Path>();

    try {
        STPaths = STRangeQuery.getIndexedSlices(params);

    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    for (Path input : STPaths) {

        final Path inputFile = input;
        int count = params.getInt("count", 1);
        double closeness = params.getFloat("closeness", -1.0f);
        final Point[] queryPoints = closeness < 0 ? params.getShapes("point", new Point()) : new Point[count];
        final FileSystem fs = inputFile.getFileSystem(params);
        final int k = params.getInt("k", 1);
        int concurrency = params.getInt("concurrency", 100);
        if (k == 0) {
            LOG.warn("k = 0");
        }

        if (queryPoints.length == 0) {
            printUsage();
            throw new RuntimeException("Illegal arguments");
        }
        final Path outputPath = paths.length > 1 ? new Path(paths[1].toUri() + "-" + input.getName()) : null;

        if (closeness >= 0) {
            // Get query points according to its closeness to grid intersections
            GlobalIndex<Partition> gindex = SpatialSite.getGlobalIndex(fs, inputFile);
            long seed = params.getLong("seed", System.currentTimeMillis());
            Random random = new Random(seed);
            for (int i = 0; i < count; i++) {
                int i_block = random.nextInt(gindex.size());
                int direction = random.nextInt(4);
                // Generate a point in the given direction
                // Get center point (x, y)
                Iterator<Partition> iterator = gindex.iterator();
                while (i_block-- >= 0)
                    iterator.next();
                Partition partition = iterator.next();
                double cx = (partition.x1 + partition.x2) / 2;
                double cy = (partition.y1 + partition.y2) / 2;
                double cw = partition.x2 - partition.x1;
                double ch = partition.y2 - partition.y1;
                int signx = ((direction & 1) == 0) ? 1 : -1;
                int signy = ((direction & 2) == 1) ? 1 : -1;
                double x = cx + cw * closeness / 2 * signx;
                double y = cy + ch * closeness / 2 * signy;
                queryPoints[i] = new Point(x, y);
            }
        }

        final BooleanWritable exceptionHappened = new BooleanWritable();

        Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
            public void uncaughtException(Thread th, Throwable ex) {
                ex.printStackTrace();
                exceptionHappened.set(true);
            }
        };

        // Run each query in a separate thread
        final Vector<Thread> threads = new Vector<Thread>();
        for (int i = 0; i < queryPoints.length; i++) {
            Thread thread = new Thread() {
                @Override
                public void run() {
                    try {
                        Point query_point = queryPoints[threads.indexOf(this)];
                        OperationsParams newParams = new OperationsParams(params);
                        OperationsParams.setShape(newParams, "point", query_point);
                        Job job = knn(inputFile, outputPath, params);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            };
            thread.setUncaughtExceptionHandler(h);
            threads.add(thread);
        }

        long t1 = System.currentTimeMillis();
        do {
            // Ensure that there is at least MaxConcurrentThreads running
            int i = 0;
            while (i < concurrency && i < threads.size()) {
                Thread.State state = threads.elementAt(i).getState();
                if (state == Thread.State.TERMINATED) {
                    // Thread already terminated, remove from the queue
                    threads.remove(i);
                } else if (state == Thread.State.NEW) {
                    // Start the thread and move to next one
                    threads.elementAt(i++).start();
                } else {
                    // Thread is still running, skip over it
                    i++;
                }
            }
            if (!threads.isEmpty()) {
                try {
                    // Sleep for 10 seconds or until the first thread terminates
                    threads.firstElement().join(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } while (!threads.isEmpty());
        long t2 = System.currentTimeMillis();
        if (exceptionHappened.get())
            throw new RuntimeException("Not all jobs finished correctly");

        System.out.println("Time for " + queryPoints.length + " jobs is " + (t2 - t1) + " millis");
        System.out.println("Total iterations: " + TotalIterations);
    }
}

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 ww  . j  av  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:com.yahoo.ycsb.db.AsyncHBaseClient.java

public static void main(String[] args) {
    if (args.length != 4) {
        System.out.println("usage: ahc zkquorum zkpath threadcount operation_count");
        System.exit(0);//from   w  ww.  j  a  v  a  2  s.  c o m
    }

    final int keyspace = 10000; //120000000;
    final String zkQuorum = args[0];
    final String zkPath = args[1];
    final int threadcount = Integer.parseInt(args[2]);
    final int opcount = Integer.parseInt(args[3]) / threadcount;

    Vector<Thread> allthreads = new Vector<Thread>();

    for (int i = 0; i < threadcount; i++) {
        Thread t = new Thread() {
            public void run() {
                try {
                    Random random = new Random();

                    AsyncHBaseClient cli = new AsyncHBaseClient();

                    Properties props = new Properties();
                    props.setProperty("columnfamily", "f1");
                    props.setProperty("zkquorum", zkQuorum);
                    props.setProperty("zkpath", zkPath);
                    props.setProperty("debug", "true");
                    cli.setProperties(props);

                    cli.init();

                    HashMap<String, ByteIterator> result = Maps.newHashMap();

                    long accum = 0;

                    for (int i = 0; i < opcount; i++) {
                        int keynum = random.nextInt(keyspace);
                        String key = "user" + keynum;
                        long st = System.currentTimeMillis();
                        int rescode;

                        HashMap<String, ByteIterator> hm = Maps.newHashMap();
                        hm.put("field1", new ByteArrayByteIterator("value1".getBytes("UTF-8")));
                        hm.put("field2", new ByteArrayByteIterator("value2".getBytes("UTF-8")));
                        hm.put("field3", new ByteArrayByteIterator("value3".getBytes("UTF-8")));
                        hm.put("efield", new ByteArrayByteIterator(HBaseClient.EMPTY_ARRAY));
                        rescode = cli.insert("bench", key, hm);
                        HashSet<String> s = Sets.newHashSet();
                        s.add("field1");
                        s.add("field2");

                        rescode = cli.read("bench", key, s, result);
                        rescode = cli.delete("bench", key);
                        rescode = cli.read("bench", key, s, result);

                        HashSet<String> scanFields = Sets.newHashSet();
                        scanFields.add("field1");
                        scanFields.add("field3");
                        Vector<HashMap<String, ByteIterator>> scanResults = new Vector<HashMap<String, ByteIterator>>();
                        rescode = cli.scan("bench", "user2", 20, null, scanResults);

                        long en = System.currentTimeMillis();

                        accum += (en - st);

                        if (rescode != Ok) {
                            System.out.println("Error " + rescode + " for " + key);
                        }

                        if (i % 10 == 0) {
                            System.out.println(
                                    i + " operations, average latency: " + (((double) accum) / ((double) i)));
                        }
                    }

                    System.out.println(new ToStringBuilder(cli._client.stats(), ToStringStyle.MULTI_LINE_STYLE)
                            .toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        allthreads.add(t);
    }

    long st = System.currentTimeMillis();
    for (Thread t : allthreads) {
        t.start();
    }

    for (Thread t : allthreads) {
        try {
            t.join();
        } catch (InterruptedException e) {
        }
    }
    long en = System.currentTimeMillis();

    System.out.println("Throughput: " + ((1000.0) * (((double) (opcount * threadcount)) / ((double) (en - st))))
            + " ops/sec");

}

From source file:com.glaf.core.util.StringTools.java

public static void main(String[] args) {
    String text = "123,234,345,567,789";
    List<String> rows = StringTools.split(text, ",");
    System.out.println(rows.get(2));
    System.out.println(rows);/*from  ww w  . j a v a2s .  com*/
    for (int i = 0, len = rows.size(); i < len; i++) {
        System.out.println(rows.get(i));
    }

    Set<String> x = new HashSet<String>();
    for (int i = 0; i < 9999; i++) {
        String str = StringTools.random();
        x.add(str);
        System.out.println(str);
    }
    System.out.println("size=" + x.size());

    Random random = new Random();

    for (int i = 1; i < 100; i++) {
        int k = Math.abs(random.nextInt(9999));
        int a = String.valueOf(k).length();
        int b = String.valueOf(9999).length();
        System.out.println("a=" + a);
        System.out.println("b=" + b);
        String xx = "";
        if (a != b) {
            for (int j = 0; j < (b - a); j++) {
                xx = "0" + xx;
            }
        }
        xx = xx + k;
        System.out.println(xx);
    }

    System.out.println(toUnderLineName("ISOCertifiedStaff"));
    System.out.println(toUnderLineName("CertifiedStaff"));
    System.out.println(toUnderLineName("UserID"));
    System.out.println(toCamelCase("iso_certified_staff"));
    System.out.println(toCamelCase("certified_staff"));
    System.out.println(toCamelCase("user_id"));
}

From source file:com.yahoo.pasc.paxos.client.PaxosClient.java

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

    CommandLineParser parser = new PosixParser();
    Options options;//from   ww w  .j  a v a 2s. c om

    {
        Option id = new Option("i", true, "client id");
        Option clients = new Option("c", true, "number of clients");
        Option host = new Option("l", true, "leader (hostname:port)");
        Option servers = new Option("s", true, "number of servers");
        Option quorum = new Option("q", true, "necesarry quorum at the client");
        Option port = new Option("p", true, "port used by client");
        Option buffer = new Option("b", true, "number of concurrent clients");
        Option timeout = new Option("t", true, "timeout in milliseconds");
        Option udp = new Option("u", false, "use UDP");
        Option zookeeper = new Option("z", true, "zookeeper connection string");
        Option warmup = new Option("w", true, "warmup messagges");
        Option measuring = new Option("m", true, "measuring time");
        Option request = new Option("r", true, "request size");
        Option frequency = new Option("f", true, "frequency of throughput info");
        Option anm = new Option("a", false, "use protection");
        Option inlineThresh = new Option("n", true, "threshold for sending requests iNline with accepts ");
        Option asynSize = new Option("y", true, "size of async messages queue");

        options = new Options();
        options.addOption(id).addOption(host).addOption(servers).addOption(quorum).addOption(port)
                .addOption(warmup).addOption(buffer).addOption(timeout).addOption(udp).addOption(zookeeper)
                .addOption(clients).addOption(measuring).addOption(request).addOption(frequency).addOption(anm)
                .addOption(inlineThresh).addOption(asynSize);
    }

    CommandLine line = null;
    try {
        line = parser.parse(options, args);

        String host = line.hasOption('l') ? line.getOptionValue('l')
                : "localhost:20548,localhost:20748,localhost:20778";
        String zkConnection = line.hasOption('z') ? line.getOptionValue('z') : "localhost:2181";
        int clientIds = line.hasOption('i') ? Integer.parseInt(line.getOptionValue('i')) : 0;
        int servers = line.hasOption('s') ? Integer.parseInt(line.getOptionValue('s')) : 3;
        int quorum = line.hasOption('q') ? Integer.parseInt(line.getOptionValue('q')) : 1;
        int buffer = line.hasOption('b') ? Integer.parseInt(line.getOptionValue('b')) : 1;
        int timeout = line.hasOption('t') ? Integer.parseInt(line.getOptionValue('t')) : 5000;
        int clients = line.hasOption('c') ? Integer.parseInt(line.getOptionValue('c')) : 1;
        int requestSize = line.hasOption('r') ? Integer.parseInt(line.getOptionValue('r')) : 0;
        int inlineThreshold = line.hasOption('n') ? Integer.parseInt(line.getOptionValue('n')) : 1000;
        int asynSize = line.hasOption('y') ? Integer.parseInt(line.getOptionValue('y')) : 100;
        boolean protection = line.hasOption('a');

        int threads = Runtime.getRuntime().availableProcessors() * 2;
        final ExecutionHandler executor = new ExecutionHandler(new OrderedMemoryAwareThreadPoolExecutor(threads,
                1024 * 1024, 1024 * 1024 * 1024, 30, TimeUnit.SECONDS, Executors.defaultThreadFactory()));

        String[] serverHosts = host.split(",");

        ServerHelloHandler shello = new ServerHelloHandler();
        ReplyHandler reply = new ReplyHandler();
        SubmitHandler submit = new SubmitHandler();
        TimeoutHandler tout = new TimeoutHandler();
        AsyncMessageHandler asyncm = new AsyncMessageHandler();
        ByeHandler bye = new ByeHandler();
        HelloHandler hello = new HelloHandler();

        Random rnd = new Random();

        for (int i = 0; i < buffer; ++i) {
            ClientState clientState = new ClientState(servers, quorum, inlineThreshold, asynSize);
            final PascRuntime<ClientState> runtime = new PascRuntime<ClientState>(protection);
            runtime.setState(clientState);
            runtime.addHandler(ServerHello.class, shello);
            runtime.addHandler(Reply.class, reply);
            runtime.addHandler(Submit.class, submit);
            runtime.addHandler(Timeout.class, tout);
            runtime.addHandler(AsyncMessage.class, asyncm);
            runtime.addHandler(Bye.class, bye);
            runtime.addHandler(Hello.class, hello);

            final PaxosClientHandler handler = new PaxosClientHandler(runtime, new SimpleClient(requestSize),
                    serverHosts, clients, timeout, zkConnection, executor);

            if (line.hasOption('w'))
                handler.setWarmup(Integer.parseInt(line.getOptionValue('w')));
            if (line.hasOption('m'))
                handler.setMeasuringTime(Integer.parseInt(line.getOptionValue('m')));
            if (line.hasOption('f'))
                handler.setPeriod(Integer.parseInt(line.getOptionValue('f')));

            handler.start();

            Thread.sleep(rnd.nextInt(200));
        }
    } catch (Exception e) {
        System.err.println("Unexpected exception " + e);
        e.printStackTrace();

        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Paxos", options);

        System.exit(-1);
    }
}

From source file:knop.psfj.FovDataSet.java

/**
 * The main method./* w  w  w .j av  a  2s.c om*/
 *
 * @param args the arguments
 */
public static void main(String[] args) {

    FovDataSet fdt = new FovDataSet();

    FovDataSet fdt2 = new FovDataSet();

    Random rn = new Random();

    /*
     * for (int i = 0; i != 10; i++) { fdt.addValue("bead", rn.nextInt(15));
     * fdt.addValue("x", rn.nextDouble()); fdt.addValue("y", rn.nextDouble());
     * fdt.addValue("z", rn.nextDouble());
     * 
     * fdt.addValue("fwhmX", rn.nextDouble() * 3); fdt.addValue("fwhmY",
     * rn.nextDouble() * 2); fdt.addValue("fwhmZ", rn.nextDouble() * 5); }
     */

    for (int i = 0; i != 10; i++) {
        // fdt.addValue("Index",i);
        fdt.addValue("xSource", rn.nextInt(100));
        fdt2.addValue("xSource", rn.nextDouble() * 200);
        fdt.addValue("xTarget", rn.nextInt(100));
        fdt2.addValue("xTarget", rn.nextInt(200));
        fdt.addValue("a name", "toi");
        fdt2.addValue("a name", "et moi");
    }
    fdt.setSeparator("\t");
    System.out.println(fdt.getColumnStatistics("xSource"));
    fdt.mergeDataSet(fdt2);
    System.out.println(fdt.exportToString());

    //fdt.exportToCrappyFormat("/home/cyril/test.xls");

}

From source file:Main.java

public static int getRandom(int minNumber, int maxNumber) {
    Random rand = new Random();
    int randomNum = rand.nextInt(maxNumber - minNumber);
    return randomNum;
}

From source file:Main.java

public static <E> E sample(List<E> l, Random r) {
    int i = r.nextInt(l.size());
    return l.get(i);
}

From source file:Main.java

public static Color randomColor(Random r) {
    return new Color(r.nextInt(127) + 127, r.nextInt(127) + 127, r.nextInt(127) + 127);
}

From source file:Main.java

public static int throwDice() {
    Random r = new Random();
    return r.nextInt(6) + 1; //0~5 + 1 = 1~6
}