public void handle(PeerMessage event) { PeerAddress oldFriend; PeerAddress sender = event.getMSPeerSource(); PeerAddress newFriend = event.getNewFriend(); // add the sender address to the list of friends if (!friends.contains(sender)) { if (friends.size() == viewSize) { oldFriend = friends.get(rand.nextInt(viewSize)); friends.remove(oldFriend); fdUnregister(oldFriend); Snapshot.removeFriend(serverPeerAddress, oldFriend); } friends.addElement(sender); fdRegister(sender); Snapshot.addFriend(serverPeerAddress, sender); } // add the received new friend from the sender to the list of friends if (!friends.contains(newFriend) && !serverPeerAddress.equals(newFriend)) { if (friends.size() == viewSize) { oldFriend = friends.get(rand.nextInt(viewSize)); friends.remove(oldFriend); fdUnregister(oldFriend); Snapshot.removeFriend(serverPeerAddress, oldFriend); } friends.addElement(newFriend); fdRegister(newFriend); Snapshot.addFriend(serverPeerAddress, newFriend); } }
@Test(expected = FileNotFoundException.class) public final void testNoSuchFile() throws Exception { QueryIdFactory.reset(); SubQueryId schid = QueryIdFactory.newSubQueryId(QueryIdFactory.newQueryId()); QueryUnitId qid1 = QueryIdFactory.newQueryUnitId(schid); QueryUnitId qid2 = QueryIdFactory.newQueryUnitId(schid); File qid1Dir = new File(TEST_DATA + "/" + qid1.toString() + "/out"); qid1Dir.mkdirs(); File qid2Dir = new File(TEST_DATA + "/" + qid2.toString() + "/out"); qid2Dir.mkdirs(); Random rnd = new Random(); FileWriter writer = new FileWriter(qid1Dir + "/" + "testHttp"); String watermark1 = "test_" + rnd.nextInt(); writer.write(watermark1); writer.flush(); writer.close(); writer = new FileWriter(qid2Dir + "/" + "testHttp"); String watermark2 = "test_" + rnd.nextInt(); writer.write(watermark2); writer.flush(); writer.close(); InterDataRetriever ret = new InterDataRetriever(); HttpDataServer server = new HttpDataServer(NetUtils.createSocketAddr("127.0.0.1:0"), ret); server.start(); ret.register(qid1, qid1Dir.getPath()); InetSocketAddress addr = server.getBindAddress(); assertDataRetrival(qid1, addr.getPort(), watermark1); ret.unregister(qid1); assertDataRetrival(qid1, addr.getPort(), watermark1); }
public static void bang() throws LineUnavailableException, InterruptedException { AudioFormat af = new AudioFormat( SAMPLE_RATE, // sampleRate 8, // sampleSizeInBits 1, // channels true, // signed false); // bigEndian SourceDataLine sdl = AudioSystem.getSourceDataLine(af); sdl.open(af); sdl.start(); byte[] buf = new byte[1]; Random r = new Random(); boolean silence = true; for (int i = 0; i < 8000; i++) { while (r.nextInt() % 10 != 0) { buf[0] = silence ? 0 : (byte) Math.abs( r.nextInt() % (int) (1. + 63. * (1. + Math.cos(((double) i) * Math.PI / 8000.)))); i++; sdl.write(buf, 0, 1); } silence = !silence; } sdl.drain(); sdl.stop(); sdl.close(); }
public void testWebSocketServer() { try { // randomly select two clients from the collection. for (int i = 0; i <= 1000; i++) { NettyTestClient from = clients.get(random.nextInt(clients.size())); NettyTestClient to = clients.get(random.nextInt(clients.size())); // this needs to be here when testing max size or max connections. if (to.isClosed()) { continue; } SocketMessage msg = messages.get(random.nextInt(messages.size())); msg.setText("Hola!"); msg.setFrom(from.getUuid()); msg.setTo(to.getUuid()); msg.setDate(new Date()); String json = JSONUtils.toJson(msg); from.send(json); Thread.sleep(TestConfig.getInstance().getMessageDelay()); } } catch (Exception e) { e.printStackTrace(); } }
/** Gets a WorldGen appropriate for this biome. */ @Override public WorldGenAbstractTree func_150567_a(Random par1Random) { if (par1Random.nextInt(3) == 0) return new WorldGenTreeAsh(16, 8, false); else if (par1Random.nextInt(2) == 0) return new WorldGenTrees(false, 5 + par1Random.nextInt(4), 0, 0, false); else return this.treeGenCache; }
@Override public void populate(Chunk chunk, Random random) { if (chunk.getY() != 4) { return; } final World world = chunk.getWorld(); if (random.nextInt(WATER_ODD) == 0) { final int x = chunk.getBlockX(random); final int z = chunk.getBlockZ(random); final int y = random.nextInt(128); WATER_POND.setRandom(random); WATER_POND.randomize(); if (WATER_POND.canPlaceObject(world, x, y, z)) { WATER_POND.placeObject(world, x, y, z); } } if (random.nextInt(LAVA_ODD) == 0) { final int x = chunk.getBlockX(random); final int z = chunk.getBlockZ(random); final int y = random.nextInt(120) + 8; if (y >= 63 && random.nextInt(LAVA_SURFACE_ODD) != 0) { return; } LAVA_POND.setRandom(random); LAVA_POND.randomize(); if (LAVA_POND.canPlaceObject(world, x, y, z)) { LAVA_POND.placeObject(world, x, y, z); } } }
public static void main(String[] args) { List<Map<String, Integer>> list = new ArrayList<Map<String, Integer>>(); for (int i = 24; i <= 28; i++) { Map<String, Integer> map = new HashMap<String, Integer>(); map.put("day", i); map.put("havedata", 0); list.add(map); } Random r = new Random(); for (int i = 1; i <= 31; i++) { Map<String, Integer> map = new HashMap<String, Integer>(); map.put("day", i); map.put("havedata", 1); map.put("nowfee", 3216 + r.nextInt(1000000)); map.put("oldfee", 3216 + r.nextInt(1000000)); map.put("dau", 3216 + r.nextInt(1000000)); map.put("dnu", 3216 + r.nextInt(1000000)); list.add(map); } for (int i = 1; i <= 6; i++) { Map<String, Integer> map = new HashMap<String, Integer>(); map.put("day", i); map.put("havedata", 0); list.add(map); } System.out.println(array2JsonString(list)); String json = "{\"code\":0,\"info\":\"success\",\"data\":{\"systemMail\":{\"mailVer\":19,\"target\":0,\"condition\":0,\"value\":2,\"title\":\"???è?????é??\",\"content\":\"???è?????é?????è?????é??\",\"sendTime\":1402555848,\"award\":{\"awardId\":0,\"gold\":2,\"heart\":2,\"diamond\":333,\"items\":[12,123],\"itemsCount\":[1,2]}}},\"sys_time\":1402555848}"; JSONObject obj = getObj(json); System.out.println(obj.getJSONObject("data").getJSONObject("systemMail").getInt("mailVer")); System.out.println(obj.getInt("code")); }
@Test public void testSerializeIndexed() throws Exception { idbm.wipeDatabase(); Random r = new Random(1L); Set<TestThrift> tts = new HashSet<TestThrift>(); for (int test = 0; test < 10000; test++) { TestThrift tt = new TestThrift( null, r.nextInt(), r.nextLong(), r.nextBoolean(), (byte) r.nextInt(), (short) r.nextInt(), r.nextDouble(), generateString(r, 16), "abc"); tts.add(tt); idbm.create(tt); idbm.commit(); } idbm.dump(TestThrift.class, new File(".")); idbm.wipeDatabase(); idbm.load(TestThrift.class, new File(".")); for (TestThrift tt : tts) { TestThrift tt2 = idbm.get(TestThrift.class, tt.id); Assert.assertEquals(tt, tt2); } new File("TestThrift.zombiedb.bz2").delete(); }
private static void sendSimpleEmails(String toUserName, int count) throws MessagingException, InterruptedException, IOException { Session session = Session.getInstance(getEmailProperties()); Random random = new Random(); int emailSize = emails.length; for (int i = 1; i <= count; i++) { Thread.sleep(10000); MimeMessage msg = new MimeMessage(session); InternetAddress from = new InternetAddress(emails[random.nextInt(emailSize)]); InternetAddress to = new InternetAddress(toUserName); msg.setFrom(from); msg.addRecipient(Message.RecipientType.TO, to); msg.setSentDate(new Date()); SimpleMessage randomMessage = SimpleMessage.values()[random.nextInt(SimpleMessage.values().length)]; msg.setSubject(randomMessage.name()); msg.setText(randomMessage.getBody()); Transport.send(msg); } }
public static Observation makeObservationFor(POMDPDomain d, GroundedAction a, POMDPState s) { ObjectInstance indexer = s.getObject(Names.OBJ_INDEXER); int index = indexer.getDiscValForAttribute(Names.ATTR_INDEX); if (index == iterations) { return d.getObservation(Names.OBS_COMPLETE); } ObjectInstance leftDoor = s.getObject(Names.OBJ_LEFT_DOOR); ObjectInstance rightDoor = s.getObject(Names.OBJ_RIGHT_DOOR); int leftDoorTiger = leftDoor.getDiscValForAttribute(Names.ATTR_TIGERNESS); java.util.Random random = new java.util.Random(); if (a.action.getName().equals(Names.ACTION_LISTEN)) { Observation left = d.getObservation(Names.OBS_LEFT_DOOR + random.nextInt(observationsPerState)); Observation right = d.getObservation(Names.OBS_RIGHT_DOOR + random.nextInt(observationsPerState)); if (leftDoorTiger == 1) { return random.nextDouble() < 1 - noise ? left : right; } else { return random.nextDouble() < 1 - noise ? right : left; } } else { return d.getObservation(Names.OBS_NULL); } }
protected static Data generateData() { char[] name = new char[16]; for (int i = 0; i < name.length; i++) { name[i] = CHARS.charAt(random.nextInt(CHARS.length())); } return new Data(random.nextInt(), random.nextLong(), new String(name)); }
private void trySpawnSticks(World world, BlockPos pos, Random random) { int x = pos.getX(); int y = pos.getY(); int z = pos.getZ(); y++; if (!world.isAirBlock(new BlockPos(x, y, z))) { return; } y++; if (!BlockTools.isTopValidAndSolid(world, pos)) { return; } for (int i = 0; i < 15; i++) { if (!world.isAirBlock(new BlockPos(x, y, z))) { if (isLeafBlock(world.getBlockState(new BlockPos(x, y, z)).getBlock())) { world.setBlockState( pos.up(), ModBlocks.sticksBlock .getDefaultState() .withProperty( GenericBlock.FACING_HORIZ, EnumFacing.getHorizontal(random.nextInt(4))), 3); SticksTE sticksTE = (SticksTE) world.getTileEntity(pos.up()); sticksTE.setSticks(random.nextInt(6) + 1); } return; } y++; } }
/* * @param i - accepts int i for person number * @return - new positions */ public int[] getNewPosition(int i) { // logic to auto select for computer player: if (i != 0) { // while space is not selected, randomly select rooms and spaces. while (spaceSelected == false) { // generate random number Random generator = new Random(); int room = generator.nextInt(10); // random select a room allRooms[room].doClick(); // generate random space int space = generator.nextInt(524); // randomly select a space btn[space].doClick(); } } // if (debugBoardPanel) { System.out.println("[526] boardPanel.getNewPosition(): Called.") ; } int[] newPositions = {newPositionColumn, newPositionRow}; // if (debugBoardPanel) { System.out.println("[530] boardPanel.getNewPosition().newPositions: " // + newPositions[0] + ", " + newPositions[1]); } return newPositions; }
public void setButtonDefs() { // Preconditions: words is initialized, preloaded is initialized. // Postconditions: definitions of words are added onto the radio buttons. // Sets the buttons to be set to random definitions from the preloaded list. // Making sure to not load the same definitions. Random rnd = new Random(); HashMap duplicates = new HashMap(5); String[] defs = new String[4]; // Mastery Factor: Implementing an ADT // Uses a Hash Map to check for duplicates amongst the options. duplicates.add(words[current].getDefinition()); for (int i = 0; i < 4; i++) { String def = preload[rnd.nextInt(PRELOADEDWORDS)].getDefinition(); while (duplicates.contains(def)) { def = preload[rnd.nextInt(PRELOADEDWORDS)].getDefinition(); } duplicates.add(def); defs[i] = def; } aRadBtn.setText(defs[0]); bRadBtn.setText(defs[1]); cRadBtn.setText(defs[2]); dRadBtn.setText(defs[3]); }
private String makeOneLetterOptions(int n, String answer, String longOptions, String avoid) { String abc; if (longOptions == null || longOptions.length() == 0) { abc = "ABCDEFGHIJKLMNOPRSTUVYÆØÅ"; } else abc = longOptions; int nOptions = n; if (nOptions > abc.length()) nOptions = abc.length(); String options = ""; int pos = random.nextInt(nOptions); for (int i = 0; i < nOptions; i++) { if (i == pos) { // input correct answer as option options += answer; } else { // find a random character different from correct answer while (true) { char a = abc.charAt(random.nextInt(abc.length())); if (a == answer.charAt(0)) continue; if (options.indexOf(a, 0) >= 0) continue; // new character found options += Character.toString(a); break; } } if (i != n) options += ","; } return options; }
// select n options from the string allOptionsStr // make sure it contains 'answer' private String selectTwoLetterOptions(int nOptions, String answer, String allOptionsStr) { String[] allOptions = allOptionsStr.split(","); int n = nOptions; if (n > allOptions.length) n = allOptions.length; int posAnswer = random.nextInt(n); ArrayList<String> options = new ArrayList<String>(); for (int i = 0; i < n; i++) { if (i == posAnswer) { // input correct answer as option options.add(answer); } else { // find a random option different from correct answer while (true) { String candidate = allOptions[random.nextInt(allOptions.length)]; if (candidate.equals(answer)) continue; if (options.contains(candidate)) continue; // new option found options.add(candidate); break; } } } return joinArray(options); }
public void Checkplanets() { GreenfootImage star = new GreenfootImage("Images/star.png"); starW = star.getWidth(); // = 10 starH = star.getHeight(); // = 10 if (!topleft) { // 3 random stars if planets are not in the top left for (int x = 0; x < 3; x++) { starX = rgen.nextInt(Q1X); starY = rgen.nextInt(Q1Y); getBackground().drawImage(star, starX, starY); } } if (!topright) { for (int x = 0; x < 3; x++) { starX = rgen.nextInt(Q2X - Q1X) + Q1X; starY = rgen.nextInt(Q2Y); getBackground().drawImage(star, starX, starY); } } if (!bottomleft) { for (int x = 0; x < 3; x++) { starX = rgen.nextInt(Q1X); starY = rgen.nextInt(Q2Y) + Q2Y; getBackground().drawImage(star, starX, starY); } } if (!bottomright) { for (int x = 0; x < 3; x++) { starX = rgen.nextInt(Q1X) + Q1X; starY = rgen.nextInt(Q2Y) + Q2Y; getBackground().drawImage(star, starX, starY); } } }
/** * Determines if this number represents a special number. A Dozen, a Half-Dozen, a Six-Pack, One * Miiiiilion, etc. * * @param decimal * @return */ private static String getSpecialLargeIntegerString(BigDecimal decimal) { String number = decimal.toPlainString(); String returnVal = "" + number; switch (number) { case "144": switch (random.nextInt(2)) { case 0: returnVal = "One Gross (144)"; break; case 1: returnVal = "144"; break; default: break; } break; case "1000": switch (random.nextInt(2)) { case 0: returnVal = "One Thousand"; break; case 1: returnVal = "144"; break; default: break; } break; case "1000000": switch (random.nextInt(2)) { case 0: returnVal = "One Miiiiiiillion"; break; case 1: returnVal = "144"; break; default: break; } break; case "1000000000": switch (random.nextInt(2)) { case 0: returnVal = "One Biiiiiiillion"; break; case 1: returnVal = "144"; break; default: break; } break; default: // format it nicely DecimalFormat formatter = new DecimalFormat("#,###"); returnVal = formatter.format(decimal); break; } return returnVal; }
@Override public List<BaseRequest> getBaseRequest() { int orderId = 1; List<BaseRequest> baseRequestList = new ArrayList<BaseRequest>(); // MVCs Pos mvc1 = createPos(10, 0); Pos mvc2 = createPos(30, 0); Pos[] mvc = new Pos[2]; mvc[0] = mvc1; mvc[1] = mvc2; ArrayList<Pos> loc = new ArrayList<Pos>(); // int[] xx = {0,20,40,60,80}; int[] xx = {0, 20, 39}; for (int i = 0; i < TASKS_NUM; i++) { // loc.add(createPos(29*rnd.nextInt(1), 10 + rnd.nextInt(20))); loc.add(createPos(xx[rnd.nextInt(3)], 10 + rnd.nextInt(10))); List<LocPriority> productList = new ArrayList<LocPriority>(); productList.add(new LocPriority(loc.get(i), 0.99)); BaseRequest br = new BaseRequest(orderId++, new Mvc(mvc[i % 2], MvcType.INPUT), productList); baseRequestList.add(br); } return baseRequestList; }
private Path[] createFiles() throws IOException { int numberOfStreams = Math.max(2, rnd.nextInt(10)); mergeFactor = Math.max(mergeFactor, numberOfStreams); LOG.info("No of streams : " + numberOfStreams); Path[] paths = new Path[numberOfStreams]; for (int i = 0; i < numberOfStreams; i++) { paths[i] = new Path(baseDir, "ifile_" + i + ".out"); FSDataOutputStream out = fs.create(paths[i]); // write data with RLE IFile.Writer writer = new IFile.Writer(conf, out, keyClass, valClass, null, null, null, true); Map<Writable, Writable> data = createData(); for (Map.Entry<Writable, Writable> entry : data.entrySet()) { writer.append(entry.getKey(), entry.getValue()); originalData.put(entry.getKey(), entry.getValue()); if (rnd.nextInt() % 2 == 0) { for (int j = 0; j < rnd.nextInt(100); j++) { // add some duplicate keys writer.append(entry.getKey(), entry.getValue()); originalData.put(entry.getKey(), entry.getValue()); } } } LOG.info("Wrote " + data.size() + " in " + paths[i]); data.clear(); writer.close(); out.close(); } return paths; }
@Override public void generate( Random rand, int chunkX, int chunkZ, World world, IChunkProvider chunkGenerator, IChunkProvider chunkProvider) { chunkX = chunkX << 4; chunkZ = chunkZ << 4; final BiomeGenBase biome = world.getBiomeGenForCoords(chunkX, chunkZ); if (BiomeSettings.GREENSWAMP.getBiome().isPresent() && biome == BiomeSettings.GREENSWAMP.getBiome().get() || BiomeSettings.MOUNTAINRIDGE.getBiome().isPresent() && biome == BiomeSettings.MOUNTAINRIDGE.getBiome().get() || BiomeSettings.REDWOODLUSH.getBiome().isPresent() && biome == BiomeSettings.REDWOODLUSH.getBiome().get() || BiomeSettings.WOODLANDS.getBiome().isPresent() && biome == BiomeSettings.WOODLANDS.getBiome().get()) for (int i = 0; i < 2; i++) { final int x = chunkX + rand.nextInt(16) + 8; final int y = rand.nextInt(128); final int z = chunkZ + rand.nextInt(16) + 8; leafPileGen.generate(world, rand, x, y, z); } }
@StressTest @UiThreadTest public void testRandomTouch() { MemoryLogger memoryLogger = new MemoryLogger("testRandomTouch", 100); viewManager.setKeyboardLayout(KeyboardLayout.TWELVE_KEYS); final int actions = 500; final Random random = new Random(); Rect rect = getViewRect(); memoryLogger.logMemory("start"); for (int i = 0; i < actions; i++) { final int x = rect.left + random.nextInt(rect.width()); final int y = rect.top + random.nextInt(rect.height()); inputView.dispatchTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_DOWN, x, y, 0)); inputView.dispatchTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_UP, x, y, 0)); // updateRequest sends asynchronous message to server. So we need to wait a moment // for server processing. sleep(200); memoryLogger.logMemoryInterval(); } memoryLogger.logMemory("start"); }
private void appendRandomChars(StringBuilder str, char[] chars, int minlen, int maxlen) { int len = rand.nextInt(maxlen - minlen) + minlen; int charsLen = chars.length; for (int i = 0; i < len; i++) { str.append(chars[rand.nextInt(charsLen)]); } }
@Test public void testSoakTestWithRandomData() throws IOException, InterruptedException { // for (int i = 30; i < 50; i++) { System.out.print("SoakTesting "); int max = 1000000; for (int j = 1; j < max; j++) { if (j % 100 == 0) System.out.print("."); Random rnd = new Random(System.currentTimeMillis()); final ChronicleMap<Integer, CharSequence> map = rnd.nextBoolean() ? map1 : map2; if (rnd.nextBoolean()) { map.put((int) rnd.nextInt(100), "test" + j); } else { map.remove((int) rnd.nextInt(100)); } } System.out.println("\nwaiting till equal"); waitTillUnchanged(1000); System.out.println("time t=" + t); Assert.assertEquals(new TreeMap(map1), new TreeMap(map2)); }
public void generateStructures(World world, Random rand, BlockPos position, int radius) { for (int i = 0; radius >= 0 && i < 3; ++i) { int j = radius + rand.nextInt(2); int k = (radius + rand.nextInt(2)); int l = radius + rand.nextInt(2); float f = (float) (j + k + l) * 0.333F + 0.5F; for (BlockPos blockpos : BlockPos.getAllInBox(position.add(-j, -k, -l), position.add(j, k, l))) { if (blockpos.distanceSq(position) <= (double) (f * f) && world.isAirBlock(blockpos) && world .getBlockState(blockpos.down()) .getBlock() .getUnlocalizedName() .contains("frozen")) { int chance = rand.nextInt(100); if (chance < 4) { int chance2 = rand.nextInt(20); System.out.println(chance2); switch (chance2) { default: generateGoldPile(world, rand, blockpos); break; case 1: generateArchNS(world, rand, blockpos); break; case 2: generateArchEW(world, rand, blockpos); break; } } } } } }
private Object sample(Class<?> type) { if (type.isPrimitive()) { if (type == long.class) { return random.nextLong(); } if (type == boolean.class) { return random.nextBoolean(); } } else if (type.isEnum()) { Object[] candidates = type.getEnumConstants(); return candidates[random.nextInt(candidates.length)]; } else if (!type.isArray()) { if (type == String.class) { StringBuilder result = new StringBuilder(); for (int len = 5 + random.nextInt(10); len > 0; len--) { result.append('a' + random.nextInt('z' - 'a')); } return result.toString(); } if (type == Long.class) { return random.nextLong(); } return mock(type); } throw new UnsupportedOperationException( "doesn't support " + type + " please add support for it."); }
private int getRandomColor() { Random randomGenerator = new Random(); int red = randomGenerator.nextInt(255); int green = randomGenerator.nextInt(255); int blue = randomGenerator.nextInt(255); return Color.rgb(red, green, blue); }
/** * The entry point to start the program. * * @param args parameters */ public static void main(String[] args) { NameGenerator generator = new NameGenerator(); // Load the source file String[] sourceArray = generator.loadFile("source"); try (Writer writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream("generated.txt"), "utf-8"))) { // Randomly generate 100 names (including first name and last name) for (int i = 0; i < 100; i++) { // To generate two random number without duplication Random random = new Random(); int first = random.nextInt(110) + 1; int second = -1; while (second == -1 || first == second) { second = random.nextInt(110) + 1; } // Write the name to the target file writer.write(sourceArray[first - 1] + " " + sourceArray[second - 1] + "\n"); } } catch (Exception e) { e.printStackTrace(); } }
/* */ public static String getName() /* */ { /* 19 */ Random rnd = new Random(); /* 20 */ String name = firstNames[rnd.nextInt(firstNameLength)] + secondNames[rnd.nextInt(secondNameLength)]; /* */ /* 22 */ return name; /* */ }
public static BigInteger getRandomNumber(final int digCount, Random rnd) { final char[] ch = new char[digCount]; for (int i = 0; i < digCount; i++) { ch[i] = (char) ('0' + (i == 0 ? rnd.nextInt(9) + 1 : rnd.nextInt(10))); } return new BigInteger(new String(ch)); }