List of usage examples for java.util Random nextBoolean
public boolean nextBoolean()
From source file:org.apache.wicket.MarkupContainerTest.java
/** * Tests whether two iterators being used simultaneously keep correct score of where they are. *///w w w . j a v a 2 s. c o m @Test public void twoIteratorsWorkInTandem() { int n = NUMBER_OF_CHILDREN_FOR_A_MAP * 2; WebMarkupContainer wmc = new WebMarkupContainer("id"); addNChildren(wmc, n); Iterator<Component> iterator1 = wmc.iterator(); Iterator<Component> iterator2 = wmc.iterator(); Random r = new Random(); for (int i = 0; i < n; i++) { if (r.nextBoolean()) { iterator1.next(); iterator1.remove(); } else { iterator2.next(); iterator2.remove(); } } // after 2*N removals there should not be any child left assertThat(iterator1.hasNext(), is(false)); assertThat(iterator2.hasNext(), is(false)); }
From source file:org.apache.wicket.MarkupContainerTest.java
/** * This tests a functional bug in the iterator implementation where you have multiple iterators * traversing the children, a detach happens and one of the iterators removes a child component * before the other iterator has a chance to update its internal state to the new world. This is * a known bug and we expect that this doesn't pose a problem in real world usage. *///from w w w . j ava 2s . c om @Test(expected = ConcurrentModificationException.class) public void knownBugForDetachWithTwoIteratorsAndRemovals() { int n = NUMBER_OF_CHILDREN_FOR_A_MAP * 2; WebMarkupContainer wmc = new WebMarkupContainer("id"); addNChildren(wmc, n); Iterator<Component> iterator1 = wmc.iterator(); Iterator<Component> iterator2 = wmc.iterator(); Random r = new Random(); for (int i = 0; i < NUMBER_OF_CHILDREN_FOR_A_MAP; i++) { if (r.nextBoolean()) { iterator1.next(); iterator1.remove(); } else { iterator2.next(); iterator2.remove(); } } wmc.detach(); iterator1.next(); iterator1.remove(); // implementation detail that gets in the way of properly solving this exotic use case: at // this moment iterator 2 doesn't know that the modification count was reset before the // iterator 1 removed the component. iterator2.next(); // code never reaches this point due to the ConcurrentModificationException }
From source file:org.apache.wicket.MarkupContainerTest.java
/** * This test is the working case for the above scenario where two iterators traverse the * children, the component gets detached and in this case both iterators have a chance to update * their internal state to the new world, before they continue to traverse the children. *///from ww w . j av a2s.c o m @Test public void detachWithTwoIteratorsAndRemovalsWork() { int n = NUMBER_OF_CHILDREN_FOR_A_MAP * 2; WebMarkupContainer wmc = new WebMarkupContainer("id"); addNChildren(wmc, n); Iterator<Component> iterator1 = wmc.iterator(); Iterator<Component> iterator2 = wmc.iterator(); Random r = new Random(); for (int i = 0; i < NUMBER_OF_CHILDREN_FOR_A_MAP; i++) { Iterator<Component> iterator = r.nextBoolean() ? iterator1 : iterator2; if (iterator.hasNext()) { iterator.next(); iterator.remove(); } } wmc.detach(); iterator1.next(); iterator2.next(); iterator1.remove(); while (iterator1.hasNext() || iterator2.hasNext()) { Iterator<Component> iterator = r.nextBoolean() ? iterator1 : iterator2; if (iterator.hasNext()) { iterator.next(); iterator.remove(); } } assertThat(iterator1.hasNext(), is(false)); assertThat(iterator2.hasNext(), is(false)); }
From source file:com.gatf.generator.core.GatfTestGeneratorMojo.java
private Object getPrimitiveValue(Type claz) { if (isPrimitive(claz)) { if (claz.equals(boolean.class) || claz.equals(Boolean.class)) { Random rand = new Random(); return rand.nextBoolean(); } else if (claz.equals(Date.class)) { return new Date(); } else if (claz.equals(Double.class) || claz.equals(double.class)) { Random rand = new Random(12345678L); return rand.nextDouble(); } else if (claz.equals(Float.class) || claz.equals(float.class)) { Random rand = new Random(12345678L); return rand.nextFloat(); } else if (claz.equals(String.class)) { return RandomStringUtils.randomAlphabetic(10); } else if (claz.equals(Long.class) || claz.equals(long.class) || claz.equals(Number.class)) { Random rand = new Random(); return new Long(rand.nextInt(123)); } else if (claz.equals(Integer.class) || claz.equals(int.class)) { Random rand = new Random(); return new Integer(rand.nextInt(123)); } else if (claz.equals(BigInteger.class)) { Random rand = new Random(); return new BigInteger(new BigInteger("1234567890123456789").bitLength(), rand); } else if (claz.equals(BigDecimal.class)) { Random rand = new Random(); return new BigDecimal(rand.nextInt(123)); } else if (claz.equals(Short.class) || claz.equals(short.class)) { Random rand = new Random(); return new Short((short) rand.nextInt(123)); }/*from w ww . jav a 2 s . c o m*/ } return null; }
From source file:org.terracotta.offheapstore.paging.TableStealingFromStorageIT.java
@Test @Ignore/*w ww. j av a 2s. co m*/ public void testSelfStealingIsStable() throws IOException { PageSource source = new UpfrontAllocatingPageSource(new HeapBufferSource(), MEGABYTES.toBytes(2), MEGABYTES.toBytes(1)); OffHeapHashMap<Integer, byte[]> selfStealer = new WriteLockedOffHeapClockCache<>(source, true, new SplitStorageEngine<>(new IntegerStorageEngine(), new OffHeapBufferHalfStorageEngine<>(source, KILOBYTES.toBytes(16), ByteArrayPortability.INSTANCE, false, true))); // failing seed value //long seed = 1302292028471110000L; long seed = System.nanoTime(); System.err.println("Random Seed = " + seed); Random rndm = new Random(seed); int payloadSize = rndm.nextInt(KILOBYTES.toBytes(1)); System.err.println("Payload Size = " + payloadSize); List<Long> sizes = new ArrayList<>(); List<Long> tableSizes = new ArrayList<>(); int terminalKey = 0; for (int key = 0; true; key++) { int size = selfStealer.size(); byte[] payload = new byte[payloadSize]; Arrays.fill(payload, (byte) key); selfStealer.put(key, payload); sizes.add((long) selfStealer.size()); tableSizes.add(selfStealer.getTableCapacity()); if (size >= selfStealer.size()) { terminalKey = key; selfStealer.remove(terminalKey); break; } } System.err.println("Terminal Key = " + terminalKey); int shrinkCount = 0; for (int key = terminalKey; key < 10 * terminalKey; key++) { byte[] payload = new byte[payloadSize]; Arrays.fill(payload, (byte) key); long preTableSize = selfStealer.getTableCapacity(); selfStealer.put(key, payload); if (rndm.nextBoolean()) { selfStealer.remove(rndm.nextInt(key)); } long postTableSize = selfStealer.getTableCapacity(); if (preTableSize > postTableSize) { shrinkCount++; } sizes.add((long) selfStealer.size()); tableSizes.add(postTableSize); } if (shrinkCount != 0) { Map<String, List<? extends Number>> data = new HashMap<>(); data.put("actual size", sizes); data.put("table size", tableSizes); JFreeChart chart = ChartFactory.createXYLineChart("Cache Size", "operations", "size", new LongListXYDataset(data), PlotOrientation.VERTICAL, true, false, false); File plotOutput = new File("target/TableStealingFromStorageTest.testSelfStealingIsStable.png"); ChartUtilities.saveChartAsPNG(plotOutput, chart, 640, 480); fail("Expected no shrink events after reaching equilibrium : saw " + shrinkCount + " [plot in " + plotOutput + "]"); } }
From source file:com.linkedin.pinot.common.utils.DataTableBuilderTest.java
@Test public void testSimple() throws Exception { final DataType[] columnTypes = DataType.values(); final String[] columnNames = new String[columnTypes.length]; for (int i = 0; i < columnTypes.length; i++) { columnNames[i] = columnTypes[i].toString(); }//ww w.ja v a 2 s . c o m final DataSchema schema = new DataSchema(columnNames, columnTypes); final DataTableBuilder builder = new DataTableBuilder(schema); builder.open(); final Random r = new Random(); final int NUM_ROWS = 100; final boolean[] boolArr = new boolean[NUM_ROWS]; final char[] cArr = new char[NUM_ROWS]; final byte[] bArr = new byte[NUM_ROWS]; final short[] sArr = new short[NUM_ROWS]; final int[] iArr = new int[NUM_ROWS]; final float[] fArr = new float[NUM_ROWS]; final long[] lArr = new long[NUM_ROWS]; final double[] dArr = new double[NUM_ROWS]; final String[] strArr = new String[NUM_ROWS]; final Object[] oArr = new Object[NUM_ROWS]; for (int rowId = 0; rowId < NUM_ROWS; rowId++) { builder.startRow(); for (int colId = 0; colId < schema.columnNames.length; colId++) { final DataType type = columnTypes[colId]; switch (type) { case BOOLEAN: final boolean bool = r.nextBoolean(); boolArr[rowId] = bool; builder.setColumn(colId, bool); break; case CHAR: final char ch = (char) (r.nextInt(26) + 'a'); cArr[rowId] = ch; builder.setColumn(colId, ch); break; case BYTE: final byte b = (byte) (r.nextInt((int) Math.pow(2, 8))); bArr[rowId] = b; builder.setColumn(colId, b); break; case SHORT: final short s = (short) (r.nextInt((int) Math.pow(2, 16))); sArr[rowId] = s; builder.setColumn(colId, s); break; case INT: final int i = (r.nextInt()); iArr[rowId] = i; builder.setColumn(colId, i); break; case LONG: final long l = (r.nextLong()); lArr[rowId] = l; builder.setColumn(colId, l); break; case FLOAT: final float f = (r.nextFloat()); fArr[rowId] = f; builder.setColumn(colId, f); break; case DOUBLE: final double d = (r.nextDouble()); dArr[rowId] = d; builder.setColumn(colId, d); break; case STRING: final String str = new BigInteger(130, r).toString(32); strArr[rowId] = str; builder.setColumn(colId, str); break; case OBJECT: final A obj = new A(r.nextInt()); oArr[rowId] = obj; builder.setColumn(colId, obj); break; default: break; } } builder.finishRow(); } builder.seal(); final DataTable dataTable = builder.build(); //System.out.println(dataTable); validate(dataTable, NUM_ROWS, schema, boolArr, cArr, bArr, sArr, iArr, fArr, lArr, dArr, strArr, oArr); final byte[] bytes = dataTable.toBytes(); final DataTable newDataTable = new DataTable(bytes); validate(newDataTable, NUM_ROWS, schema, boolArr, cArr, bArr, sArr, iArr, fArr, lArr, dArr, strArr, oArr); }
From source file:org.apache.hadoop.hive.serde2.binarysortable.TestBinarySortableFast.java
private void testBinarySortableFastCase(int caseNum, boolean doNonRandomFill, Random r, SerdeRandomRowSource.SupportedTypes supportedTypes, int depth) throws Throwable { SerdeRandomRowSource source = new SerdeRandomRowSource(); // UNDONE: Until Fast BinarySortable supports complex types -- disable. source.init(r, supportedTypes, depth); int rowCount = 1000; Object[][] rows = source.randomRows(rowCount); if (doNonRandomFill) { MyTestClass.nonRandomRowFill(rows, source.primitiveCategories()); }//from w ww. j ava 2 s .co m // We need to operate on sorted data to fully test BinarySortable. source.sort(rows); StructObjectInspector rowStructObjectInspector = source.rowStructObjectInspector(); TypeInfo[] typeInfos = source.typeInfos(); int columnCount = typeInfos.length; int writeColumnCount = columnCount; StructObjectInspector writeRowStructObjectInspector = rowStructObjectInspector; boolean doWriteFewerColumns = r.nextBoolean(); if (doWriteFewerColumns) { writeColumnCount = 1 + r.nextInt(columnCount); if (writeColumnCount == columnCount) { doWriteFewerColumns = false; } else { writeRowStructObjectInspector = source.partialRowStructObjectInspector(writeColumnCount); } } String fieldNames = ObjectInspectorUtils.getFieldNames(rowStructObjectInspector); String fieldTypes = ObjectInspectorUtils.getFieldTypes(rowStructObjectInspector); String order; order = StringUtils.leftPad("", columnCount, '+'); String nullOrder; nullOrder = StringUtils.leftPad("", columnCount, 'a'); AbstractSerDe serde_ascending = TestBinarySortableSerDe.getSerDe(fieldNames, fieldTypes, order, nullOrder); AbstractSerDe serde_ascending_fewer = null; if (doWriteFewerColumns) { String partialFieldNames = ObjectInspectorUtils.getFieldNames(writeRowStructObjectInspector); String partialFieldTypes = ObjectInspectorUtils.getFieldTypes(writeRowStructObjectInspector); serde_ascending_fewer = TestBinarySortableSerDe.getSerDe(partialFieldNames, partialFieldTypes, order, nullOrder); } order = StringUtils.leftPad("", columnCount, '-'); nullOrder = StringUtils.leftPad("", columnCount, 'z'); AbstractSerDe serde_descending = TestBinarySortableSerDe.getSerDe(fieldNames, fieldTypes, order, nullOrder); AbstractSerDe serde_descending_fewer = null; if (doWriteFewerColumns) { String partialFieldNames = ObjectInspectorUtils.getFieldNames(writeRowStructObjectInspector); String partialFieldTypes = ObjectInspectorUtils.getFieldTypes(writeRowStructObjectInspector); serde_descending_fewer = TestBinarySortableSerDe.getSerDe(partialFieldNames, partialFieldTypes, order, nullOrder); } boolean[] columnSortOrderIsDesc = new boolean[columnCount]; Arrays.fill(columnSortOrderIsDesc, false); byte[] columnNullMarker = new byte[columnCount]; Arrays.fill(columnNullMarker, BinarySortableSerDe.ZERO); byte[] columnNotNullMarker = new byte[columnCount]; Arrays.fill(columnNotNullMarker, BinarySortableSerDe.ONE); /* * Acending. */ testBinarySortableFast(source, rows, columnSortOrderIsDesc, columnNullMarker, columnNotNullMarker, serde_ascending, rowStructObjectInspector, serde_ascending_fewer, writeRowStructObjectInspector, /* ascending */ true, typeInfos, /* useIncludeColumns */ false, /* doWriteFewerColumns */ false, r); testBinarySortableFast(source, rows, columnSortOrderIsDesc, columnNullMarker, columnNotNullMarker, serde_ascending, rowStructObjectInspector, serde_ascending_fewer, writeRowStructObjectInspector, /* ascending */ true, typeInfos, /* useIncludeColumns */ true, /* doWriteFewerColumns */ false, r); if (doWriteFewerColumns) { testBinarySortableFast(source, rows, columnSortOrderIsDesc, columnNullMarker, columnNotNullMarker, serde_ascending, rowStructObjectInspector, serde_ascending_fewer, writeRowStructObjectInspector, /* ascending */ true, typeInfos, /* useIncludeColumns */ false, /* doWriteFewerColumns */ true, r); testBinarySortableFast(source, rows, columnSortOrderIsDesc, columnNullMarker, columnNotNullMarker, serde_ascending, rowStructObjectInspector, serde_ascending_fewer, writeRowStructObjectInspector, /* ascending */ true, typeInfos, /* useIncludeColumns */ true, /* doWriteFewerColumns */ true, r); } /* * Descending. */ Arrays.fill(columnSortOrderIsDesc, true); testBinarySortableFast(source, rows, columnSortOrderIsDesc, columnNullMarker, columnNotNullMarker, serde_descending, rowStructObjectInspector, serde_ascending_fewer, writeRowStructObjectInspector, /* ascending */ false, typeInfos, /* useIncludeColumns */ false, /* doWriteFewerColumns */ false, r); testBinarySortableFast(source, rows, columnSortOrderIsDesc, columnNullMarker, columnNotNullMarker, serde_descending, rowStructObjectInspector, serde_ascending_fewer, writeRowStructObjectInspector, /* ascending */ false, typeInfos, /* useIncludeColumns */ true, /* doWriteFewerColumns */ false, r); if (doWriteFewerColumns) { testBinarySortableFast(source, rows, columnSortOrderIsDesc, columnNullMarker, columnNotNullMarker, serde_descending, rowStructObjectInspector, serde_descending_fewer, writeRowStructObjectInspector, /* ascending */ false, typeInfos, /* useIncludeColumns */ false, /* doWriteFewerColumns */ true, r); testBinarySortableFast(source, rows, columnSortOrderIsDesc, columnNullMarker, columnNotNullMarker, serde_descending, rowStructObjectInspector, serde_descending_fewer, writeRowStructObjectInspector, /* ascending */ false, typeInfos, /* useIncludeColumns */ true, /* doWriteFewerColumns */ true, r); } }
From source file:org.voltdb.TestExecutionSite.java
private void queueTransactions(long firstTxnId, int totalTransactions, Random rand) { for (int i = 0; i <= totalTransactions; ++i) { boolean rollback = rand.nextBoolean(); // Disabling this as it results in too many all-failures currently //boolean rollback_all = rand.nextBoolean(); boolean rollback_all = false; boolean readOnly = rand.nextBoolean(); long txnid = i + firstTxnId; long safe_txnid = txnid; long initiator = selectRandomInitiator(rand); int partition = i % PARTITION_COUNT; int wheelOfDestiny = rand.nextInt(100); if (i == totalTransactions) { testLog.info("Queueing final heartbeat."); int offset = 0; for (long inid : getInitiatorIds()) { createHeartBeat(txnid + offset, txnid + offset, inid); ++offset;/* w w w . j a v a2 s .co m*/ } } else if (wheelOfDestiny < 50) { createSPInitiation(readOnly, txnid, safe_txnid, initiator, partition); } else if (wheelOfDestiny < 70) { int numberOfBatches = rand.nextInt(4) + 1; List<Long> participants = new ArrayList<Long>(); long coordinator = selectCoordinatorAndParticipants(rand, partition, initiator, participants); createMPInitiation(rollback, rollback_all, readOnly, numberOfBatches, txnid, safe_txnid, initiator, partition, coordinator, participants); } else { createHeartBeat(txnid, safe_txnid, initiator); } } }
From source file:uk.ac.imperial.presage2.web.export.TestDataExport.java
@Test public void testTransientAgentPropertyWithCondition() throws JSONException { Random rand = new Random(); // prepare test data logger.info("Creating conditioned TransientAgentProperty test data set"); int simCount = rand.nextInt(9) + 1; long[] simIds = new long[simCount]; // expectations of test data. int[] expectedCount1 = new int[100]; int[] expectedCount2 = new int[100]; Arrays.fill(expectedCount2, 0); int[] expectedCount3 = new int[100]; Arrays.fill(expectedCount3, 0); for (int s = 0; s < simCount; s++) { int finishAt = 1 + rand.nextInt(99); int agentCount = 1 + rand.nextInt(20); PersistentSimulation sim = sto.createSimulation("Test", "test", "TEST", finishAt); sto.setSimulation(sim);// ww w .j a va 2 s. c o m sim.setCurrentTime(finishAt); Set<PersistentAgent> agents = new HashSet<PersistentAgent>(); for (int a = 0; a < agentCount; a++) { PersistentAgent ag = sto.createAgent(uk.ac.imperial.presage2.core.util.random.Random.randomUUID(), "agent" + a); agents.add(ag); boolean test = rand.nextBoolean(); ag.setProperty("testA", Boolean.toString(test)); if (test) { for (int j = 0; j < finishAt; j++) { expectedCount1[j]++; } } } for (int i = 0; i < finishAt; i++) { for (PersistentAgent a : agents) { int datapoint = rand.nextInt(100); a.getState(i).setProperty("test", Integer.toString(datapoint)); if (datapoint > 50) expectedCount2[i]++; if (datapoint <= 75 && a.getProperty("testA").equalsIgnoreCase("true")) expectedCount3[i]++; } } simIds[s] = sim.getID(); logger.info("Sim " + sim.getID() + ", " + finishAt + " steps, " + agentCount + " agents."); } // prepare input JSON JSONObject inputJson = new JSONObject(); inputJson.put("sources", new JSONArray(simIds)); inputJson.put("parameters", new JSONArray(new String[] { "time" })); JSONObject test1 = new JSONObject(); test1.put("type", "AGENT"); test1.put("property", "test"); test1.put("function", "COUNT"); JSONObject test1Condition = new JSONObject(); test1Condition.put("testA", true); test1.put("condition", test1Condition); JSONObject test2 = new JSONObject(); test2.put("type", "AGENT"); test2.put("property", "test"); test2.put("function", "COUNT"); JSONObject test2Condition = new JSONObject("{\"$t\":{\"test\":{\"$gt\":50}}}"); test2.put("condition", test2Condition); JSONObject test3 = new JSONObject(); test3.put("type", "AGENT"); test3.put("property", "test"); test3.put("function", "COUNT"); JSONObject test3Condition = new JSONObject(); test3Condition.put("testA", true); test3Condition.put("$t", new JSONObject("{\"test\":{\"$lte\":75}}")); test3.put("condition", test3Condition); inputJson.put("columns", new JSONArray(new JSONObject[] { test1, test2, test3 })); logger.info("Test json input: " + inputJson.toString()); // test servlet Iterable<Iterable<String>> actual = servletUnderTest.processRequest(inputJson); // check expectations int row = -1; int col = 0; for (Iterable<String> iterable : actual) { logger.info("Test results row: " + row); for (String string : iterable) { if (row == -1) { switch (col) { case 0: assertEquals("timestep", string); break; } } else { switch (col) { // timestep col case 0: assertEquals(row, Integer.parseInt(string)); break; // min col case 1: assertEquals(expectedCount1[row], Integer.parseInt(string)); break; // max col case 2: assertEquals(expectedCount2[row], Integer.parseInt(string)); break; // mean col case 3: assertEquals(expectedCount3[row], Integer.parseInt(string)); break; } } col++; } col = 0; row++; } }
From source file:com.pivotal.gemfire.tools.pulse.testbed.PropMockDataUpdater.java
private void refresh(Member m) { if (LOGGER.infoEnabled()) { LOGGER.info(resourceBundle.getString("LOG_MSG_REFRESHING_MEMBER_DATA") + " : " + m.getName()); }/*from w ww . j a va 2 s. c om*/ Random r = new Random(System.currentTimeMillis()); m.setUptime(System.currentTimeMillis()); m.setQueueBacklog("" + Math.abs(r.nextInt(500))); m.setCurrentHeapSize(Math.abs(r.nextInt(Math.abs((int) m.getMaxHeapSize())))); m.setTotalDiskUsage(Math.abs(r.nextInt(100))); Float cpuUsage = r.nextFloat() * 100; m.getCpuUsageSamples().add(cpuUsage); m.setCpuUsage(cpuUsage); m.getHeapUsageSamples().add(m.getCurrentHeapSize()); m.setLoadAverage((double) Math.abs(r.nextInt(100))); m.setNumThreads(Math.abs(r.nextInt(100))); m.setGarbageCollectionCount((long) Math.abs(r.nextInt(100))); m.getGarbageCollectionSamples().add(m.getGarbageCollectionCount()); m.setTotalFileDescriptorOpen((long) Math.abs(r.nextInt(100))); m.setThroughputWrites(Math.abs(r.nextInt(10))); m.getThroughputWritesTrend().add(m.getThroughputWrites()); m.setGetsRate(Math.abs(r.nextInt(5000))); m.getGetsPerSecond().add(m.getGetsRate()); m.setPutsRate(Math.abs(r.nextInt(5000))); m.getPutsPerSecond().add(m.getPutsRate()); Alert[] alerts = cluster.getAlertsList(); List<Alert> alertsList = new ArrayList<Alert>(Arrays.asList(alerts)); if (r.nextBoolean()) { // Generate alerts if (r.nextBoolean()) { if (r.nextInt(10) > 5) { alertsList.add(createAlert(Alert.SEVERE, m.getName(), alertsList.size())); if (alertsList.size() > ALERTS_MAX_SIZE) { alertsList.remove(0); } } } if (r.nextBoolean()) { if (r.nextInt(10) > 5) { alertsList.add(createAlert(Alert.ERROR, m.getName(), alertsList.size())); if (alertsList.size() > ALERTS_MAX_SIZE) { alertsList.remove(0); } } } if (r.nextBoolean()) { if (r.nextInt(10) > 5) { alertsList.add(createAlert(Alert.WARNING, m.getName(), alertsList.size())); if (alertsList.size() > ALERTS_MAX_SIZE) { alertsList.remove(0); } } } } }