Example usage for java.util Random nextBoolean

List of usage examples for java.util Random nextBoolean

Introduction

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

Prototype

public boolean nextBoolean() 

Source Link

Document

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

Usage

From source file:airport.dispatcher.weather.Humidity.java

@Override
public void update() {
    if (value == MAX_DEGREE) {
        value--;//from   ww  w . ja  v  a2 s.  c om
        return;
    }

    if (value == MIN_DEGREE) {
        value++;
        return;
    }

    Random random = new Random();

    if (random.nextBoolean()) {
        value++;
    } else {
        value--;
    }

    if (LOG.isInfoEnabled()) {
        LOG.info("update Humidity. New value : " + value);
    }
}

From source file:airport.dispatcher.weather.TemperatureCentigrade.java

@Override
public void update() {
    if (degree == MAX_DEGREE) {
        degree--;/*  ww w.  j av a 2 s. c o  m*/
        return;
    }

    if (degree == MIN_DEGREE) {
        degree++;
        return;
    }

    Random random = new Random();

    if (random.nextBoolean()) {
        degree++;
    } else {
        degree--;
    }

    if (LOG.isInfoEnabled()) {
        LOG.info("update. New value : " + degree);
    }
}

From source file:org.zanata.webtrans.client.presenter.UserConfigHolderTest.java

@Test
public void randomSetterAndGetter() throws Exception {
    Random random = new Random(System.nanoTime());
    boolean value = random.nextBoolean();

    configHolder.setEnterSavesApproved(value);
    configHolder.setDisplayButtons(value);
    configHolder.setShowError(value);/*from  w  w w . j a v  a2s. c  om*/

    assertThat(configHolder.getState().isEnterSavesApproved()).isEqualTo(value);
    assertThat(configHolder.getState().isDisplayButtons()).isEqualTo(value);
    assertThat(configHolder.getState().isShowError()).isEqualTo(value);
}

From source file:org.sonar.server.platform.db.migration.version.v65.DeleteCeWorkerCountSettingTest.java

public void insertProperty(String propertyName) {
    Random random = new Random();
    db.executeInsert(TABLE_PROPERTIES, "prop_key", propertyName, "is_empty", valueOf(random.nextBoolean()),
            "text_value", random.nextBoolean() ? null : RandomStringUtils.randomAlphabetic(2));
}

From source file:com.samsung.sjs.theorysolver.TheorySolverTest.java

/**
 * This tests the {@link TheorySolver} using a theory which has a random set of
 * blacklisted objects. We verify that the TheorySolver always finds the entire
 * set of non-blacklisted objects.//  w  w w .  jav  a2 s.  co m
 */
@Test
public void testBasics() {

    List<Object> all = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h");

    for (int i = 0; i < 100; ++i) {
        Random r = new Random(SEED + i);

        Collection<Object> truthy = all.stream().filter(x -> r.nextBoolean()).collect(Collectors.toSet());

        Theory<Object, Void> theory = positive -> {
            Collection<Object> bad = positive.stream().filter(x -> !truthy.contains(x))
                    .collect(Collectors.toSet());
            if (bad.size() > 0) {
                // Construct a random, nonempty unsat core.
                Collection<Object> unsat = new HashSet<>();
                unsat.add(bad.iterator().next());
                bad.stream().filter(x -> r.nextBoolean()).forEach(unsat::add);
                return Either.right(unsat);
            } else {
                return Either.left(null);
            }
        };

        Pair<Void, Collection<Object>> result = TheorySolver.solve(theory,
                new SatFixingSetFinder<>(new Sat4J()), Collections.emptyList(), all);

        Assert.assertEquals(all.size() - truthy.size(), result.getRight().size());
        Assert.assertEquals(truthy,
                all.stream().filter(x -> !result.getRight().contains(x)).collect(Collectors.toSet()));
    }

}

From source file:org.apache.solr.common.util.TestJavaBinCodec.java

public static void doDecodePerf(String[] args) throws Exception {
    int arg = 0;/* w  w  w.  j  a  v  a  2 s.c  om*/
    int nThreads = Integer.parseInt(args[arg++]);
    int nBuffers = Integer.parseInt(args[arg++]);
    final long iter = Long.parseLong(args[arg++]);
    int cacheSz = Integer.parseInt(args[arg++]);

    Random r = new Random(0);

    final byte[][] buffers = new byte[nBuffers][];

    for (int bufnum = 0; bufnum < nBuffers; bufnum++) {
        SolrDocument sdoc = new SolrDocument();
        sdoc.put("id", "my_id_" + bufnum);
        sdoc.put("author", str(r, 10 + r.nextInt(10)));
        sdoc.put("address", str(r, 20 + r.nextInt(20)));
        sdoc.put("license", str(r, 10));
        sdoc.put("title", str(r, 5 + r.nextInt(10)));
        sdoc.put("modified_dt", r.nextInt(1000000));
        sdoc.put("creation_dt", r.nextInt(1000000));
        sdoc.put("birthdate_dt", r.nextInt(1000000));
        sdoc.put("clean", r.nextBoolean());
        sdoc.put("dirty", r.nextBoolean());
        sdoc.put("employed", r.nextBoolean());
        sdoc.put("priority", r.nextInt(100));
        sdoc.put("dependents", r.nextInt(6));
        sdoc.put("level", r.nextInt(101));
        sdoc.put("education_level", r.nextInt(10));
        // higher level of reuse for string values
        sdoc.put("state", "S" + r.nextInt(50));
        sdoc.put("country", "Country" + r.nextInt(20));
        sdoc.put("some_boolean", "" + r.nextBoolean());
        sdoc.put("another_boolean", "" + r.nextBoolean());

        buffers[bufnum] = getBytes(sdoc);
    }

    int ret = 0;
    final RTimer timer = new RTimer();
    ConcurrentLRUCache underlyingCache = cacheSz > 0
            ? new ConcurrentLRUCache<>(cacheSz, cacheSz - cacheSz / 10, cacheSz, cacheSz / 10, false, true,
                    null)
            : null; // the cache in the first version of the patch was 10000,9000,10000,1000,false,true,null
    final JavaBinCodec.StringCache stringCache = underlyingCache == null ? null
            : new JavaBinCodec.StringCache(underlyingCache);
    if (nThreads <= 0) {
        ret += doDecode(buffers, iter, stringCache);
    } else {
        runInThreads(nThreads, () -> {
            try {
                doDecode(buffers, iter, stringCache);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    long n = iter * Math.max(1, nThreads);
    System.out.println("ret=" + ret + " THROUGHPUT=" + (n * 1000 / timer.getTime()));
    if (underlyingCache != null)
        System.out.println("cache: hits=" + underlyingCache.getStats().getCumulativeHits() + " lookups="
                + underlyingCache.getStats().getCumulativeLookups() + " size="
                + underlyingCache.getStats().getCurrentSize());
}

From source file:org.apache.tinkerpop.gremlin.neo4j.AbstractNeo4jGraphProvider.java

private void createIndices(final Neo4jGraph graph, final LoadGraphWith.GraphData graphData) {
    final Random random = new Random();
    final boolean pick = random.nextBoolean();
    if (graphData.equals(LoadGraphWith.GraphData.GRATEFUL)) {
        if (pick) {
            graph.tx().readWrite();//from w  ww  . j a va2 s . c o m
            if (random.nextBoolean())
                graph.cypher("CREATE INDEX ON :artist(name)").iterate();
            if (random.nextBoolean())
                graph.cypher("CREATE INDEX ON :song(name)").iterate();
            if (random.nextBoolean())
                graph.cypher("CREATE INDEX ON :song(songType)").iterate();
            if (random.nextBoolean())
                graph.cypher("CREATE INDEX ON :song(performances)").iterate();
            graph.tx().commit();
        } // else no indices
    } else if (graphData.equals(LoadGraphWith.GraphData.MODERN)) {
        if (pick) {
            graph.tx().readWrite();
            if (random.nextBoolean())
                graph.cypher("CREATE INDEX ON :person(name)").iterate();
            if (random.nextBoolean())
                graph.cypher("CREATE INDEX ON :person(age)").iterate();
            if (random.nextBoolean())
                graph.cypher("CREATE INDEX ON :software(name)").iterate();
            if (random.nextBoolean()) {
                graph.cypher("CREATE INDEX ON :software(lang)").iterate();
            }
            graph.tx().commit();
        } // else no indices
    } else if (graphData.equals(LoadGraphWith.GraphData.CLASSIC)) {
        if (pick) {
            graph.tx().readWrite();
            if (random.nextBoolean())
                graph.cypher("CREATE INDEX ON :vertex(name)").iterate();
            if (random.nextBoolean())
                graph.cypher("CREATE INDEX ON :vertex(age)").iterate();
            if (random.nextBoolean())
                graph.cypher("CREATE INDEX ON :vertex(lang)").iterate();
            graph.tx().commit();
        } // else no indices
    } else {
        // TODO: add CREW work here.
        // TODO: add meta_property indices when meta_property graph is provided
        //throw new RuntimeException("Could not load graph with " + graphData);
    }
}

From source file:org.apache.edgent.samples.utils.sensor.PeriodicRandomSensor.java

/**
 * Create a periodic sensor stream with readings from {@link Random#nextBoolean()}.
 * @param t the topology to add the sensor stream to
 * @param periodMsec how frequently to generate a reading
 * @return the sensor value stream//from  w  ww  .j  a  v a 2 s .  c  om
 */
public TStream<Pair<Long, Boolean>> newBoolean(Topology t, long periodMsec) {
    Random r = newRandom();
    return t.poll(() -> new Pair<Long, Boolean>(System.currentTimeMillis(), r.nextBoolean()), periodMsec,
            TimeUnit.MILLISECONDS);

}

From source file:org.primefaces.extensions.showcase.controller.timeline.LazyTimelineController.java

private void generateRandomEvents(Date startDate, Date endDate, TimelineUpdater timelineUpdater) {
    Calendar cal = Calendar.getInstance();
    Date curDate = startDate;// w ww  .ja v a 2s .co  m
    Random rnd = new Random();

    while (curDate.before(endDate)) {
        // create events in the given time range
        if (rnd.nextBoolean()) {
            // event with only one date
            model.add(new TimelineEvent("Event " + RandomStringUtils.randomNumeric(5), curDate),
                    timelineUpdater);
        } else {
            // event with start and end dates
            cal.setTimeInMillis(curDate.getTime());
            cal.add(Calendar.HOUR, 18);
            model.add(new TimelineEvent("Event " + RandomStringUtils.randomNumeric(5), curDate, cal.getTime()),
                    timelineUpdater);
        }

        cal.setTimeInMillis(curDate.getTime());
        cal.add(Calendar.HOUR, 24);

        curDate = cal.getTime();
    }
}

From source file:org.vaadin.viritin.it.aspect.MTableLazyLoadingWithEntityAspect.java

@Override
public Component getTestComponent() {

    Random r = new Random(0);

    final List<User> listOfPersons = Service.getListOfPersons(1000).stream().map(person -> {
        User u = new User(person);
        u.setLocale(r.nextBoolean() ? Locale.ENGLISH : Locale.FRENCH);
        return u;
    }).collect(Collectors.toList());

    MTable<User> table = new MTable<>((firstRow, sortAscending, property) -> {
        if (property != null) {
            if (property.equals("localizedSalutation")) {
                Collections.sort(listOfPersons, new Comparator<User>() {
                    @Override/*  w ww.j a  v  a2s.  c o m*/
                    public int compare(User o1, User o2) {
                        return localizedSalutation(o1).compareTo(localizedSalutation(o2));
                    }
                });
            } else {
                Collections.sort(listOfPersons, new BeanComparator<>(property));

            }
            if (!sortAscending) {
                Collections.reverse(listOfPersons);
            }
        }
        int last = firstRow + LazyList.DEFAULT_PAGE_SIZE;
        if (last > listOfPersons.size()) {
            last = listOfPersons.size();
        }
        return new ArrayList<User>(listOfPersons.subList(firstRow, last));
    }, () -> (int) Service.count())
            .withProperties("localizedSalutation", "locale", "person.firstName", "person.lastName")
            .withColumnHeaders("Salutation", "Locale", "Forename", "Name").withFullWidth()
            .withGeneratedColumn("localizedSalutation", u -> localizedSalutation(u));

    return table;
}