Example usage for java.util Random nextLong

List of usage examples for java.util Random nextLong

Introduction

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

Prototype

public long nextLong() 

Source Link

Document

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

Usage

From source file:org.apache.hadoop.hive.ql.Context.java

/**
 * Generate a unique executionId.  An executionId, together with user name and
 * the configuration, will determine the temporary locations of all intermediate
 * files.//from w w  w .  j  av a2s. com
 *
 * In the future, users can use the executionId to resume a query.
 */
public static String generateExecutionId() {
    Random rand = new Random();
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss_SSS");
    String executionId = "hive_" + format.format(new Date()) + "_" + Math.abs(rand.nextLong());
    return executionId;
}

From source file:org.openmeetings.test.poll.TestClientListManager.java

@Test
public void addClientListItem() {
    Random rnd = new Random();
    assertNotNull("RoomClientId created is null", clientListManager.addClientListItem(
            rnd.nextLong() + "ABCDE" + rnd.nextLong(), "scopeName", 66666, "remoteAddress", "swfUrl", false));
}

From source file:com.jivesoftware.os.jive.utils.id.IdTest.java

@Test
public void idStringTest() throws Exception {
    final Random r = new Random(1234);
    for (int i = 0; i < 100; i++) {
        long id = Math.abs(r.nextLong());
        Id wid = new Id(id);
        Id rid = MAPPER.readValue(MAPPER.writeValueAsString(wid), Id.class);

        Assert.assertEquals(rid, wid, "Failed to map Id through String: " + id);
    }/*from   w  w w.  jav a  2 s  .c o m*/
}

From source file:com.jivesoftware.os.jive.utils.id.IdTest.java

@Test
public void idBytesTest() throws Exception {
    final Random r = new Random(1234);
    for (int i = 0; i < 100; i++) {
        long id = Math.abs(r.nextLong());
        Id wid = new Id(id);
        Id rid = MAPPER.readValue(MAPPER.writeValueAsBytes(wid), Id.class);

        Assert.assertEquals(rid, wid, "Failed to map Id through bytes: " + id);
    }//ww w. ja v a 2 s .c o  m
}

From source file:com.winvector.logistic.demo.MapReduceScore.java

public double run(final String modelFileName, final String testFileName, final String resultFileName)
        throws Exception {
    final Log log = LogFactory.getLog(MapReduceScore.class);
    final Random rand = new Random();
    final String tmpPrefix = "TMPAC_" + rand.nextLong();
    final Configuration mrConfig = getConf();
    log.info("start");
    log.info("reading model: " + modelFileName);
    final Model model;
    {//ww  w  . j  ava  2  s  . c  o m
        final Path modelPath = new Path(modelFileName);
        final FSDataInputStream fdi = modelPath.getFileSystem(mrConfig).open(modelPath);
        final ObjectInputStream ois = new ObjectInputStream(fdi);
        model = (Model) ois.readObject();
        ois.close();
    }
    log.info("model:\n" + model.config.formatSoln(model.coefs));
    final Path testFile = new Path(testFileName);
    final Path resultFile = new Path(resultFileName);
    log.info("scoring data: " + testFile);
    log.info("writing: " + resultFile);
    final SigmoidLossMultinomial underlying = new SigmoidLossMultinomial(model.config.dim(),
            model.config.noutcomes());
    final WritableVariableList lConfig = WritableVariableList.copy(model.config.def());
    final String headerLine = WritableUtils.readFirstLine(mrConfig, testFile);
    final Pattern sepPattern = Pattern.compile("\t");
    final LineBurster burster = new HBurster(sepPattern, headerLine, false);
    mrConfig.set(MapRedScan.BURSTERSERFIELD, SerialUtils.serializableToString(burster));
    final StringBuilder b = new StringBuilder();
    b.append("predict" + "." + model.config.def().resultColumn + "\t");
    b.append("predict" + "." + model.config.def().resultColumn + "." + "score" + "\t");
    for (int i = 0; i < model.config.noutcomes(); ++i) {
        final String cat = model.config.outcome(i);
        b.append("predict" + "." + model.config.def().resultColumn + "." + cat + "." + "score" + "\t");
    }
    b.append(headerLine);
    mrConfig.set(MapRedScore.IDEALHEADERFIELD, b.toString());
    final MapRedScore sc = new MapRedScore(underlying, lConfig, model.config.useIntercept(), mrConfig,
            testFile);
    sc.score(model.coefs, resultFile);
    final MapRedAccuracy ac = new MapRedAccuracy(underlying, lConfig, model.config.useIntercept(), tmpPrefix,
            mrConfig, testFile);
    final long[] testAccuracy = ac.score(model.coefs);
    final double accuracy = testAccuracy[0] / (double) testAccuracy[1];
    log.info("test accuracy: " + testAccuracy[0] + "/" + testAccuracy[1] + "\t" + accuracy);
    log.info("done");
    return accuracy;
}

From source file:com.winvector.logistic.demo.MapReduceLogisticTrain.java

public double run(final String trainFileName, final String formulaStr, final String weightKey,
        final String resultFileName, final int maxNewtonRounds) throws Exception {
    final Log log = LogFactory.getLog(MapReduceLogisticTrain.class);
    log.info("start");
    final Formula formula = new Formula(formulaStr); // force an early parse error if wrong
    final Random rand = new Random();
    final String tmpPrefix = "TMPLR_" + rand.nextLong();
    final Configuration mrConfig = getConf();
    final Path trainFile = new Path(trainFileName);
    final Path resultFile = new Path(resultFileName);
    final String headerLine = WritableUtils.readFirstLine(mrConfig, trainFile);
    final Pattern sepPattern = Pattern.compile("\t");
    final LineBurster burster = new HBurster(sepPattern, headerLine, false);
    mrConfig.set(MapRedScan.BURSTERSERFIELD, SerialUtils.serializableToString(burster));
    final WritableVariableList lConfig = MapRedScan.initialScan(tmpPrefix, mrConfig, trainFile, formulaStr);
    log.info("formula:\t" + formulaStr + "\n" + lConfig.formatState());
    final VariableEncodings defs = new VariableEncodings(lConfig, true, weightKey);
    //final WritableSigmoidLossBinomial underlying = new WritableSigmoidLossBinomial(defs.dim());
    final SigmoidLossMultinomial underlying = new SigmoidLossMultinomial(defs.dim(), defs.noutcomes());
    final MapRedFn f = new MapRedFn(underlying, lConfig, defs.useIntercept(), tmpPrefix, mrConfig, trainFile);
    final ArrayList<VectorFn> fns = new ArrayList<VectorFn>();
    fns.add(f);//from   w  w w.  j a v a  2 s  . com
    fns.add(new NormPenalty(f.dim(), 1.0e-5, defs.adaptions));
    final VectorFn sl = new SumFn(fns);
    final VectorOptimizer nwt = new Newton();
    final VEval opt = nwt.maximize(sl, null, maxNewtonRounds);
    log.info("done training");
    log.info("soln vector:\n" + LinUtil.toString(opt.x));
    log.info("soln details:\n" + defs.formatSoln(opt.x));
    {
        final Model model = new Model();
        model.config = defs;
        model.coefs = opt.x;
        model.origFormula = formula;
        log.info("writing " + resultFile);
        final FSDataOutputStream fdo = resultFile.getFileSystem(mrConfig).create(resultFile, true);
        final ObjectOutputStream oos = new ObjectOutputStream(fdo);
        oos.writeObject(model);
        oos.close();
    }
    final MapRedAccuracy sc = new MapRedAccuracy(underlying, lConfig, defs.useIntercept(), tmpPrefix, mrConfig,
            trainFile);
    final long[] trainAccuracy = sc.score(opt.x);
    final double accuracy = trainAccuracy[0] / (double) trainAccuracy[1];
    log.info("train accuracy: " + trainAccuracy[0] + "/" + trainAccuracy[1] + "\t" + accuracy);
    return accuracy;
}

From source file:enumj.EnumerableGenerator.java

public Supplier<IntSupplier> boundRnd(int bound) {
    final long seed = rnd.nextLong();
    return () -> {
        final Random rnd = new Random(seed);
        return () -> rnd.nextInt(bound);
    };/* w  ww  .  j  a  va  2 s  .co  m*/
}

From source file:org.apache.hadoop.mapred.TestSequenceFileAsBinaryInputFormat.java

public void testBinary() throws IOException {
    JobConf job = new JobConf();
    FileSystem fs = FileSystem.getLocal(job);
    Path dir = new Path(System.getProperty("test.build.data", ".") + "/mapred");
    Path file = new Path(dir, "testbinary.seq");
    Random r = new Random();
    long seed = r.nextLong();
    r.setSeed(seed);//from w  w  w . j  a  v a 2  s  .  c  o m

    fs.delete(dir, true);
    FileInputFormat.setInputPaths(job, dir);

    Text tkey = new Text();
    Text tval = new Text();

    SequenceFile.Writer writer = new SequenceFile.Writer(fs, job, file, Text.class, Text.class);
    try {
        for (int i = 0; i < RECORDS; ++i) {
            tkey.set(Integer.toString(r.nextInt(), 36));
            tval.set(Long.toString(r.nextLong(), 36));
            writer.append(tkey, tval);
        }
    } finally {
        writer.close();
    }

    InputFormat<BytesWritable, BytesWritable> bformat = new SequenceFileAsBinaryInputFormat();

    int count = 0;
    r.setSeed(seed);
    BytesWritable bkey = new BytesWritable();
    BytesWritable bval = new BytesWritable();
    Text cmpkey = new Text();
    Text cmpval = new Text();
    DataInputBuffer buf = new DataInputBuffer();
    final int NUM_SPLITS = 3;
    FileInputFormat.setInputPaths(job, file);
    for (InputSplit split : bformat.getSplits(job, NUM_SPLITS)) {
        RecordReader<BytesWritable, BytesWritable> reader = bformat.getRecordReader(split, job, Reporter.NULL);
        try {
            while (reader.next(bkey, bval)) {
                tkey.set(Integer.toString(r.nextInt(), 36));
                tval.set(Long.toString(r.nextLong(), 36));
                buf.reset(bkey.getBytes(), bkey.getLength());
                cmpkey.readFields(buf);
                buf.reset(bval.getBytes(), bval.getLength());
                cmpval.readFields(buf);
                assertTrue("Keys don't match: " + "*" + cmpkey.toString() + ":" + tkey.toString() + "*",
                        cmpkey.toString().equals(tkey.toString()));
                assertTrue("Vals don't match: " + "*" + cmpval.toString() + ":" + tval.toString() + "*",
                        cmpval.toString().equals(tval.toString()));
                ++count;
            }
        } finally {
            reader.close();
        }
    }
    assertEquals("Some records not found", RECORDS, count);
}

From source file:com.relicum.ipsum.Commands.WorldCreate.java

@Override
public boolean onCommand(CommandSender sender, Command command, String[] args) {
    Validate.notNull(args[1]);// w ww.  j  a v a2  s  .c o m
    if (Bukkit.getWorld(args[0]) != null) {
        sender.sendMessage(ChatColor.RED + "Error: world with that name already exists");
        return true;
    }

    Random random = new Random();

    long n = random.nextLong();

    Worlds worlds = new Worlds(plugin, args[0]);
    configManager.initConfig(args[0], worlds);
    worlds.setName(args[0]);
    worlds.setSeed(n);
    worlds.setGenerator(args[1]);
    WorldCreator worldCreator = new WorldCreator(args[0]);
    worldCreator.seed(n).generateStructures(worlds.getGenerateStructures()).environment(worlds.getEnvironment())
            .type(worlds.getWorldType()).generator(args[1]);

    try {
        worlds.save();
        worldCreator.createWorld();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    Bukkit.getScheduler().scheduleSyncDelayedTask(getPlugin(), () -> {
        if (Bukkit.getWorld(args[0]) != null)

            sender.sendMessage(ChatColor.GREEN + "New World Created Successfully");
        else {
            sender.sendMessage(ChatColor.RED + "Error creating new world");
        }
    }, 60l);

    return true;
}

From source file:com.facebook.stats.cardinality.TestHyperLogLog.java

private Set<Long> makeRandomSet(int count) {
    Random random = new Random();

    Set<Long> result = new HashSet<Long>();
    while (result.size() < count) {
        result.add(random.nextLong());
    }/*  ww  w.j a v a2s.com*/

    return result;
}