public void prepare(ColumnFamilyStore cfs) { if (tree.partitioner() instanceof RandomPartitioner) { // You can't beat an even tree distribution for md5 tree.init(); } else { List<DecoratedKey> keys = new ArrayList<DecoratedKey>(); for (DecoratedKey sample : cfs.keySamples(request.range)) { assert request.range.contains(sample.token) : "Token " + sample.token + " is not within range " + request.range; keys.add(sample); } if (keys.isEmpty()) { // use an even tree distribution tree.init(); } else { int numkeys = keys.size(); Random random = new Random(); // sample the column family using random keys from the index while (true) { DecoratedKey dk = keys.get(random.nextInt(numkeys)); if (!tree.split(dk.token)) break; } } } logger.debug("Prepared AEService tree of size " + tree.size() + " for " + request); ranges = tree.invalids(); }
public Object call() throws Exception { _barrier.await(); // barrier, to force racing start for (long j = 0; j < _count; j++) _map.put( j + _offset, new TestKey(_rand.nextLong(), _rand.nextInt(), (short) _rand.nextInt(Short.MAX_VALUE))); return null; }
public void run() { try { while (!Thread.interrupted()) { TimeUnit.MILLISECONDS.sleep(rand.nextInt(300)); customers.put(new Customer(rand.nextInt(1000))); } } catch (InterruptedException e) { System.out.println("CustomerGenerator interrupted"); } System.out.println("CustomerGenerator terminating"); }
// Insert a random delay to produce the effect // of a calculation time: private void pause(int factor) { try { TimeUnit.MILLISECONDS.sleep(100 + rand.nextInt(factor)); } catch (InterruptedException e) { print("sleep() interrupted"); } }
protected void prepare( Map stormConf, final TopologyContext context, final IOutputCollector collector) { _rand = new Random(); _collector = collector; _context = context; heartbeatTimeoutMills = getHeartbeatTimeoutMillis(stormConf); _process = new NuShellProcess(_command, this, this); // subprocesses must send their pid first thing Number subpid = _process.launch(stormConf, context); LOG.info("Launched subprocess with pid " + subpid); this.pid = subpid.longValue(); /** * randomizing the initial delay would prevent all shell bolts from heartbeating at the same * time frame */ int initialDelayMillis = random.nextInt(4000) + 1000; BoltHeartbeatTimerTask task = new BoltHeartbeatTimerTask(this); heartBeatExecutorService.scheduleAtFixedRate( task, initialDelayMillis, getHeartbeatPeriodMillis(stormConf), TimeUnit.MILLISECONDS); }
/** @throws Exception If failed. */ public void testClientAffinity() throws Exception { GridClientData partitioned = client.data(PARTITIONED_CACHE_NAME); Collection<Object> keys = new ArrayList<>(); keys.addAll(Arrays.asList(Boolean.TRUE, Boolean.FALSE, 1, Integer.MAX_VALUE)); Random rnd = new Random(); StringBuilder sb = new StringBuilder(); // Generate some random strings. for (int i = 0; i < 100; i++) { sb.setLength(0); for (int j = 0; j < 255; j++) // Only printable ASCII symbols for test. sb.append((char) (rnd.nextInt(0x7f - 0x20) + 0x20)); keys.add(sb.toString()); } // Generate some more keys to achieve better coverage. for (int i = 0; i < 100; i++) keys.add(UUID.randomUUID()); for (Object key : keys) { UUID nodeId = grid(0).mapKeyToNode(PARTITIONED_CACHE_NAME, key).id(); UUID clientNodeId = partitioned.affinity(key); assertEquals( "Invalid affinity mapping for REST response for key: " + key, nodeId, clientNodeId); } }
private static void slowExample(WorkerPool workerPool, int nTasks) { List<Callable<Integer>> taskList = new ArrayList<Callable<Integer>>(); Random random = new Random(); int maxWait = 10000; for (int i = 1; i <= nTasks; i++) { final int wait = random.nextInt(maxWait); Callable<Integer> callable = new Callable<Integer>() { @Override public Integer call() throws Exception { Thread.sleep(wait); return wait; } }; taskList.add(callable); } long start = System.currentTimeMillis(); List<Integer> waits = workerPool.invokeAll(taskList); long finish = System.currentTimeMillis(); int longestWait = 0; int totalWait = 0; for (int wait : waits) { longestWait = wait > longestWait ? wait : longestWait; totalWait += wait; } System.out.println( String.format( "elapsed time: %5d ms (%.2f%%)", finish - start, 100 * (1.0 * (finish - start)) / totalWait)); System.out.println(String.format("longest wait: %5d ms", longestWait)); System.out.println(String.format("average wait: %5d ms", totalWait / nTasks)); System.out.println(String.format("total wait: %5d ms", totalWait)); }
public static void main(String[] args) throws Exception { ExecutorService exec = Executors.newCachedThreadPool(); for (int i = 0; i < N_ELEMENTS; i++) for (int j = 0; j < N_GENES; j++) GRID[i][j] = new AtomicInteger(rand.nextInt(1000)); for (int i = 0; i < N_EVOLVERS; i++) exec.execute(new Evolver()); TimeUnit.SECONDS.sleep(5); exec.shutdownNow(); }
/** * Returns true if the chosen target was also a seed. False otherwise * * @param message message to sent * @param epSet a set of endpoint from which a random endpoint is chosen. * @return true if the chosen endpoint is also a seed. */ boolean sendGossip(Message message, Set<InetAddress> epSet) { int size = epSet.size(); /* Generate a random number from 0 -> size */ List<InetAddress> liveEndpoints = new ArrayList<InetAddress>(epSet); int index = (size == 1) ? 0 : random_.nextInt(size); InetAddress to = liveEndpoints.get(index); if (logger_.isTraceEnabled()) logger_.trace("Sending a GossipDigestSynMessage to {} ...", to); MessagingService.instance().sendOneWay(message, to); return seeds_.contains(to); }
@Override @EventHandler public void onChatReceived(ChatReceivedEvent event) { super.onChatReceived(event); String message = Util.stripColors(event.getMessage()); if (message.startsWith("Please register with \"/register")) { String password = Util.generateRandomString(10 + random.nextInt(6)); bot.say("/register " + password + " " + password); } else if (message.contains("You are not member of any faction.") && spamMessage != null && createFaction) { String msg = "/f create " + Util.generateRandomString(7 + random.nextInt(4)); bot.say(msg); } for (String s : captchaList) { Matcher captchaMatcher = Pattern.compile(s).matcher(message); if (captchaMatcher.matches()) bot.say(captchaMatcher.group(1)); } }
public static void main(String[] args) { Random rand = new Random(47); ExecutorService exec = Executors.newCachedThreadPool(); DelayQueue<DelayedTask> queue = new DelayQueue<DelayedTask>(); // Fill with tasks that have random delays: for (int i = 0; i < 20; i++) queue.put(new DelayedTask(rand.nextInt(5000))); // Set the stopping point queue.add(new DelayedTask.EndSentinel(5000, exec)); exec.execute(new DelayedTaskConsumer(queue)); }
@BeforeMethod public void beforeMethod() throws IOException { if (buffer != null) { buffer.close(); deleteUsedFiles(FILE_COUNT); } initBuffer(); Random random = new Random(); seed = (byte) (random.nextInt() & 0xFF); }
public void run() { try { while (!Thread.interrupted()) { // A new customer arrives; assign a WaitPerson: WaitPerson wp = waitPersons.get(rand.nextInt(waitPersons.size())); Customer c = new Customer(wp); exec.execute(c); TimeUnit.MILLISECONDS.sleep(100); } } catch (InterruptedException e) { print("Restaurant interrupted"); } print("Restaurant closing"); }
public void run() { try { while (!Thread.interrupted()) { TimeUnit.MILLISECONDS.sleep(100 + rand.nextInt(500)); // Make toast Toast t = new Toast(count++); print(t); // Insert into queue toastQueue.put(t); } } catch (InterruptedException e) { print("Toaster interrupted"); } print("Toaster off"); }
public void run() { try { while (!Thread.interrupted()) { // Blocks until an order appears: Order order = restaurant.orders.take(); Food requestedItem = order.item(); // Time to prepare order: TimeUnit.MILLISECONDS.sleep(rand.nextInt(500)); Plate plate = new Plate(order, requestedItem); order.getWaitPerson().filledOrders.put(plate); } } catch (InterruptedException e) { print(this + " interrupted"); } print(this + " off duty"); }
CrawlerC(BlockingQueue<String> q) { this.q = q; try { Random generator = new Random(); r = generator.nextInt(100); myService = new BloggerService("Mongo-BlogFeed-" + r); // myService.setReadTimeout(3000); mysqlConn = DriverManager.getConnection(GetComments.myConnString); myStm = mysqlConn.createStatement(); myStm.executeQuery("set wait_timeout = 7200"); // System.out.println(r+": Start()"); } catch (Exception e) { System.out.println(r + "bye:" + e.getMessage()); } }
@EventHandler public void onTick(TickEvent event) { if (!bot.hasSpawned() || !bot.isConnected()) return; if (tickDelay > 0) { tickDelay--; return; } MainPlayerEntity player = bot.getPlayer(); if (player == null || !bot.hasSpawned() || spamMessage == null) return; if (nextMessage > 0) { nextMessage--; return; } try { String message = spamMessage; MessageFormatter formatter = new MessageFormatter(); synchronized (bots) { if (bots.size() > 0) { DarkBotMCSpambot bot = bots.get(++nextBot >= bots.size() ? nextBot = 0 : nextBot); if (bot != null && bot.bot != null && bot.bot.getSession() != null) formatter.setVariable("bot", bot.bot.getSession().getUsername()); } } if (spamList.length > 0) { formatter.setVariable( "spamlist", spamList[++nextSpamList >= spamList.length ? nextSpamList = 0 : nextSpamList]); } formatter.setVariable("rnd", Util.generateRandomString(15 + random.nextInt(6))); formatter.setVariable( "msg", Character.toString( msgChars[++nextMsgChar >= msgChars.length ? nextMsgChar = 0 : nextMsgChar])); message = formatter.format(message); bot.say(message); } catch (Exception e) { e.printStackTrace(); } nextMessage = messageDelay; }
@Test public void testSubmitToMembersRunnable() throws InterruptedException { final int k = simpleTestNodeCount; TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(k); final HazelcastInstance[] instances = factory.newInstances(new Config()); final AtomicInteger count = new AtomicInteger(0); final CountDownLatch latch = new CountDownLatch(k); final MultiExecutionCallback callback = new MultiExecutionCallback() { public void onResponse(Member member, Object value) { count.incrementAndGet(); } public void onComplete(Map<Member, Object> values) { latch.countDown(); } }; int sum = 0; final Set<Member> membersSet = instances[0].getCluster().getMembers(); final Member[] members = membersSet.toArray(new Member[membersSet.size()]); final Random random = new Random(); for (int i = 0; i < k; i++) { final IExecutorService service = instances[i].getExecutorService("testSubmitToMembersRunnable"); final String script = "hazelcast.getAtomicLong('testSubmitToMembersRunnable').incrementAndGet();"; final int n = random.nextInt(k) + 1; sum += n; Member[] m = new Member[n]; System.arraycopy(members, 0, m, 0, n); service.submitToMembers(new ScriptRunnable(script, null), Arrays.asList(m), callback); } assertTrue(latch.await(30, TimeUnit.SECONDS)); final IAtomicLong result = instances[0].getAtomicLong("testSubmitToMembersRunnable"); assertEquals(sum, result.get()); assertEquals(sum, count.get()); }
public void run() { while (!Thread.interrupted()) { // Randomly select an element to work on: int element = rand.nextInt(N_ELEMENTS); for (int i = 0; i < N_GENES; i++) { int previous = element - 1; if (previous < 0) previous = N_ELEMENTS - 1; int next = element + 1; if (next >= N_ELEMENTS) next = 0; int oldvalue = GRID[element][i].get(); // Perform some kind of modeling calculation: int newvalue = oldvalue + GRID[previous][i].get() + GRID[next][i].get(); newvalue /= 3; // Average the three values if (!GRID[element][i].compareAndSet(oldvalue, newvalue)) { // Policy here to deal with failure. Here, we // just report it and ignore it; our model // will eventually deal with it. System.out.println("Old value changed from " + oldvalue); } } } }
@EventHandler public void onPacketProcess(PacketProcessEvent event) { // System.out.println("Packet received: " + event.getPacket().getId() // + " (" + event.getPacket() + ")"); Packet packet = event.getPacket(); switch (packet.getId()) { case 0: connectionHandler.sendPacket(new Packet0KeepAlive(new Random().nextInt())); break; case 3: String message = ((Packet3Chat) packet).message; message = removeColors(message); System.out.println("[" + bot.getSession().getUsername() + "] " + message); String testMessage = "[MineCaptcha] To be unmuted answer this question: What is "; String testMessage2 = "Please type '"; String testMessage3 = "' to continue sending messages/commands"; if (message.contains(testMessage)) { try { String captcha = message.split(Pattern.quote(testMessage))[1].split("[ \\?]")[0]; ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine engine = mgr.getEngineByName("JavaScript"); String solved = engine.eval(captcha).toString(); solved = solved.split("\\.")[0]; connectionHandler.sendPacket(new Packet3Chat(solved)); } catch (Exception exception) { exception.printStackTrace(); } } else if (message.contains(testMessage2) && message.contains(testMessage3)) { try { String captcha = message.split(Pattern.quote(testMessage2))[1].split(Pattern.quote(testMessage3))[0]; connectionHandler.sendPacket(new Packet3Chat(captcha)); } catch (Exception exception) { exception.printStackTrace(); } } else if (message.startsWith("Please register with \"/register")) { String password = ""; for (int i = 0; i < 10 + random.nextInt(6); i++) password += alphas[random.nextInt(alphas.length)]; bot.say("/register " + password + " " + password); } else if (message.startsWith("/uc ")) { connectionHandler.sendPacket(new Packet3Chat(message)); } else if ((message.contains("do the crime") && message.contains("do the time")) || message.contains("You have been muted")) { connectionHandler.sendPacket(new Packet3Chat("\247Leaving!")); } else if (message.contains(owner + " has requested to teleport to you.")) { connectionHandler.sendPacket(new Packet3Chat("/tpaccept")); } else if (message.contains(owner)) { if (message.contains("Go ")) { spamMessage = message.substring(message.indexOf("Go ") + "Go ".length()); } else if (message.contains("Stop")) { spamMessage = null; bot.getTaskManager().stopAll(); } else if (message.contains("Die")) { die = true; } else if (message.contains("Say ")) { connectionHandler.sendPacket( new Packet3Chat(message.substring(message.indexOf("Say ") + "Say ".length()))); } else if (message.contains("Leave")) { connectionHandler.sendPacket(new Packet255KickDisconnect("Quit")); } else if (message.contains("Tool")) { MainPlayerEntity player = bot.getPlayer(); if (player == null) return; PlayerInventory inventory = player.getInventory(); inventory.setCurrentHeldSlot( Integer.parseInt( message.substring(message.indexOf("Tool ") + "Tool ".length()).split(" ")[0])); } else if (message.contains("DropId ")) { MainPlayerEntity player = bot.getPlayer(); PlayerInventory inventory = player.getInventory(); String substring = message.substring(message.indexOf("DropId ") + "DropId ".length()).split(" ")[0]; int id = Integer.parseInt(substring); for (int slot = 0; slot < 40; slot++) { ItemStack item = inventory.getItemAt(slot); if (item != null && item.getId() == id) { inventory.selectItemAt(slot, true); inventory.dropSelectedItem(); } } inventory.close(); } else if (message.contains("Drop")) { MainPlayerEntity player = bot.getPlayer(); PlayerInventory inventory = player.getInventory(); if (message.contains("Drop ")) { String substring = message.substring(message.indexOf("Drop ") + "Drop ".length()).split(" ")[0]; try { int slot = Integer.parseInt(substring); if (slot < 0 || slot >= 40) return; if (inventory.getItemAt(slot) != null) { inventory.selectItemAt(slot, true); inventory.dropSelectedItem(); } return; } catch (NumberFormatException e) { } } for (int slot = 0; slot < 40; slot++) { if (inventory.getItemAt(slot) != null) { inventory.selectItemAt(slot, true); inventory.dropSelectedItem(); } } inventory.close(); } else if (message.contains("Switch ")) { MainPlayerEntity player = bot.getPlayer(); PlayerInventory inventory = player.getInventory(); String substring = message.substring(message.indexOf("Switch ") + "Switch ".length()); try { int slot1 = Integer.parseInt(substring.split(" ")[0]); int slot2 = Integer.parseInt(substring.split(" ")[1]); if (slot1 < 0 || slot1 >= 45 || slot2 < 0 || slot2 >= 45) return; inventory.selectItemAt(slot1); inventory.selectItemAt(slot2); inventory.selectItemAt(slot1); } catch (NumberFormatException e) { } // inventory.close(); } else if (message.contains("Equip")) { MainPlayerEntity player = bot.getPlayer(); PlayerInventory inventory = player.getInventory(); boolean helmet = inventory.getArmorAt(0) != null; boolean chestplate = inventory.getArmorAt(1) != null; boolean leggings = inventory.getArmorAt(2) != null; boolean boots = inventory.getArmorAt(3) != null; boolean changed = false; for (int i = 0; i < 36; i++) { ItemStack item = inventory.getItemAt(i); if (item == null) continue; int armorSlot; int id = item.getId(); if (!helmet && (id == 86 || id == 298 || id == 302 || id == 306 || id == 310 || id == 314)) { armorSlot = 0; helmet = true; } else if (!chestplate && (id == 299 || id == 303 || id == 307 || id == 311 || id == 315)) { armorSlot = 1; chestplate = true; } else if (!leggings && (id == 300 || id == 304 || id == 308 || id == 312 || id == 316)) { armorSlot = 2; leggings = true; } else if (!boots && (id == 301 || id == 305 || id == 309 || id == 313 || id == 317)) { armorSlot = 3; boots = true; } else if (helmet && chestplate && leggings && boots) break; else continue; inventory.selectItemAt(i); inventory.selectArmorAt(armorSlot); changed = true; } if (!changed) { for (int i = 0; i < 36; i++) { ItemStack item = inventory.getItemAt(i); if (item != null) continue; int armorSlot; if (helmet) { armorSlot = 0; helmet = false; } else if (chestplate) { armorSlot = 1; chestplate = false; } else if (leggings) { armorSlot = 2; leggings = false; } else if (boots) { armorSlot = 3; boots = false; } else if (!helmet && !chestplate && !leggings && !boots) break; else continue; inventory.selectArmorAt(armorSlot); inventory.selectItemAt(i); } } inventory.close(); bot.say("Equipped armor."); } else if (message.contains("Owner ")) { String name = message.substring(message.indexOf("Owner ") + "Owner ".length()).split(" ")[0]; owner = name; bot.say("Set owner to " + name); } } else if (message.contains("You are not member of any faction.") && spamMessage != null && createFaction) { String msg = "/f create "; for (int i = 0; i < 7 + random.nextInt(3); i++) msg += alphas[random.nextInt(alphas.length)]; bot.say(msg); } if (message.matches("[\\*]*SPQR [\\w]{1,16} invited you to SPQR")) { bot.say("/f join SPQR"); bot.say("\247asdf"); } break; case 8: Packet8UpdateHealth updateHealth = (Packet8UpdateHealth) packet; if (updateHealth.healthMP <= 0) connectionHandler.sendPacket(new Packet205ClientCommand(1)); break; case 9: TaskManager taskManager = bot.getTaskManager(); taskManager.stopAll(); break; } }
public void nextCharacter() { handler.fireNewCharacter(this, (int) chars[random.nextInt(chars.length)]); }
private DarkBotMCSpambot( DarkBot darkBot, String server, String username, String password, String sessionId, String loginProxy, String proxy, String owner) { synchronized (bots) { bots.add(this); // slotsTaken.incrementAndGet(); synchronized (slotsTaken) { slotsTaken.notifyAll(); } } MinecraftBotData.Builder builder = MinecraftBotData.builder(); // botData.nickname = ""; // for(int i = 0; i < 10; i++) // botData.nickname += alphas[random.nextInt(alphas.length)]; if (proxy != null && !proxy.isEmpty()) { int port = 80; ProxyType type = ProxyType.SOCKS; if (proxy.contains(":")) { String[] parts = proxy.split(":"); proxy = parts[0]; port = Integer.parseInt(parts[1]); if (parts.length > 2) type = ProxyType.values()[Integer.parseInt(parts[2]) - 1]; } builder.withSocksProxy(new ProxyData(proxy, port, type)); this.proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(proxy, port)); } if (loginProxy != null && !loginProxy.isEmpty()) { int port = 80; if (loginProxy.contains(":")) { String[] parts = loginProxy.split(":"); loginProxy = parts[0]; port = Integer.parseInt(parts[1]); } builder.withHttpProxy(new ProxyData(loginProxy, port, ProxyType.HTTP)); this.loginProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(loginProxy, port)); } builder.withUsername(username); if (sessionId != null) builder.withSessionId(sessionId); else builder.withPassword(password); if (server != null && !server.isEmpty()) { int port = 25565; if (server.contains(":")) { String[] parts = server.split(":"); server = parts[0]; port = Integer.parseInt(parts[1]); } builder.withServer(server).withPort(port); } else throw new IllegalArgumentException("Unknown server!"); this.owner = owner; MinecraftBotData botData = builder.build(); System.setProperty("socksProxyHost", ""); System.setProperty("socksProxyPort", ""); System.out.println("[" + username + "] Connecting..."); bot = new MinecraftBot(darkBot, botData); bot.setMovementDisabled(true); connectionHandler = bot.getConnectionHandler(); Session session = bot.getSession(); // System.gc(); System.out.println("[" + username + "] Done! (" + amountJoined.incrementAndGet() + ")"); bot.getEventManager().registerListener(this); bot.getGameHandler().registerListener(this); long lastShoutTime = System.currentTimeMillis(); while (bot.isConnected()) { if (die) { connectionHandler.sendPacket(new Packet255KickDisconnect("Goodbye")); return; } try { Thread.sleep(3000 + random.nextInt(1000)); } catch (InterruptedException exception) { exception.printStackTrace(); } if (!bot.hasSpawned()) continue; connectionHandler.sendPacket(new Packet0KeepAlive(random.nextInt())); if (spamMessage == null || !canSpam) continue; String message = spamMessage; if (message.contains("%skill")) message = message.replace("%skill", skills[nextSkill++]); if (nextSkill >= skills.length) nextSkill = 0; if (message.contains("%bot")) { synchronized (bots) { message = message.replace( "%bot", bots.get(nextBot > bots.size() ? (nextBot = 0) * 0 : nextBot++) .bot .getSession() .getUsername()); } } if (message.contains("%spamlist")) message = message.replace("%spamlist", spamList[nextSpamList++]); if (nextSpamList >= spamList.length) nextSpamList = 0; if (message.contains("%rnd")) { int length = 1; int index = message.indexOf("%rnd") + "%rnd".length(); int lastIndex; for (lastIndex = index; lastIndex < message.length(); lastIndex++) if (Character.isDigit(message.charAt(lastIndex))) lastIndex++; else break; if (lastIndex > message.length()) lastIndex--; try { System.out.println(index + "," + lastIndex + "," + message.length()); length = Integer.parseInt(message.substring(index, lastIndex)); } catch (Exception exception) { } String randomChars = ""; for (int i = 0; i < length; i++) randomChars += alphas[random.nextInt(alphas.length)]; message = message.replace("%rnd", randomChars); } if (message.contains("%msg")) message = "/msg " + msgChars[nextMsgChar++] + " " + message.replace("%msg", ""); if (message.contains("%ernd")) { message = message.replace("%ernd", ""); int extraMessageLength = 15 + random.nextInt(6); message = message.substring(0, Math.min(100 - extraMessageLength, message.length())) + " ["; extraMessageLength -= 3; for (int i = 0; i < extraMessageLength; i++) message += alphas[random.nextInt(alphas.length)]; message += "]"; } else message = message.substring(0, Math.min(100, message.length())); connectionHandler.sendPacket(new Packet3Chat(message)); } synchronized (bots) { bots.remove(this); } amountJoined.decrementAndGet(); slotsTaken.decrementAndGet(); synchronized (slotsTaken) { slotsTaken.notifyAll(); } }
private void pause() throws InterruptedException { if (ponderFactor == 0) return; TimeUnit.MILLISECONDS.sleep(rand.nextInt(ponderFactor * 250)); }