List of usage examples for java.util Collections shuffle
public static void shuffle(List<?> list)
From source file:net.nelz.simplesm.test.ReadThroughMultiCacheTest.java
@Test public void test() { final Long rawNow = System.currentTimeMillis(); final Long now = (rawNow / 1000) * 10000; final List<Long> subset = new ArrayList<Long>(); final List<Long> superset = new ArrayList<Long>(); final List<Long> jumbleset = new ArrayList<Long>(); for (Long ix = 1 + now; ix < 35 + now; ix++) { if (ix % 3 == 0) { subset.add(ix);/*w ww .j av a 2 s . com*/ } superset.add(ix); jumbleset.add(ix); } Collections.shuffle(jumbleset); final TestSvc test = (TestSvc) context.getBean("testSvc"); // Get all the results for the subset ids. // Ensure the ids line up with the results, and have the same timestamp. final List<String> subsetResult = test.getTimestampValues(subset); assertEquals(subset.size(), subsetResult.size()); String subsetTime = null; for (int ix = 0; ix < subset.size(); ix++) { final Long key = subset.get(ix); final String value = subsetResult.get(ix); System.out.println("Subset: " + value); final String[] parts = value.split("-X-"); if (subsetTime == null) { subsetTime = parts[0]; } else { assertEquals(subsetTime, parts[0]); } assertEquals(key.toString(), parts[1]); } // Now call the full list. // Ensure id's line up, and that results from ids that got passed in the subset // have the older time stamp. final List<String> supersetResult = test.getTimestampValues(superset); assertEquals(superset.size(), supersetResult.size()); String supersetTime = null; for (int ix = 0; ix < superset.size(); ix++) { final Long key = superset.get(ix); final String value = supersetResult.get(ix); System.out.println("Superset: " + value); final String[] parts = value.split("-X-"); final boolean inSubset = subset.contains(key); if (!inSubset && supersetTime == null) { supersetTime = parts[0]; } else if (inSubset) { assertEquals(subsetTime, parts[0]); } else { assertEquals(supersetTime, parts[0]); } assertEquals(key.toString(), parts[1]); } // Now call for the results again, but with a randomized // set of keys. This is to ensure the proper values line up with // the given keys. final List<String> jumblesetResult = test.getTimestampValues(jumbleset); assertEquals(jumbleset.size(), jumblesetResult.size()); for (int ix = 0; ix < jumbleset.size(); ix++) { final Long key = jumbleset.get(ix); final String value = jumblesetResult.get(ix); System.out.println("Jumbleset: " + value); final String[] parts = value.split("-X-"); final boolean inSubset = subset.contains(key); if (inSubset) { assertEquals(subsetTime, parts[0]); } else { assertEquals(supersetTime, parts[0]); } assertEquals(key.toString(), parts[1]); } }
From source file:com.rabbitmq.jms.sample.StockQuoter.java
@Scheduled(fixedRate = 5000L) // every 5 seconds public void publishQuote() { // Pick a random stock symbol Collections.shuffle(stocks); String symbol = stocks.get(0); // Toss a coin and decide if the price goes... if (RandomUtils.nextBoolean()) { // ...up by a random 0-10% lastPrice.put(symbol, new Double( Math.round(lastPrice.get(symbol) * (1 + RandomUtils.nextInt(10) / 100.0) * 100) / 100)); } else {//from w w w . j av a 2s.c o m // ...or down by a similar random amount lastPrice.put(symbol, new Double( Math.round(lastPrice.get(symbol) * (1 - RandomUtils.nextInt(10) / 100.0) * 100) / 100)); } // Log new price locally log.info("Quote..." + symbol + " is now " + lastPrice.get(symbol)); // Coerce a javax.jms.MessageCreator MessageCreator messageCreator = (Session session) -> { return session.createObjectMessage("Quote..." + symbol + " is now " + lastPrice.get(symbol)); }; // And publish to RabbitMQ using Spring's JmsTemplate jmsTemplate.send("rabbit-trader-channel", messageCreator); }
From source file:com.cloudera.oryx.ml.param.GridSearch.java
/** * @param ranges ranges of hyperparameters to try, one per hyperparameters * @param howMany how many combinations of hyperparameters to return * @return combinations of concrete hyperparameter values. For example, for 5 parameters each * with 3 values to try, the total number of combinations returned could be up to pow(3,5) * or 243. The number could be less if the ranges do not actually have that many distinct * values. If {@code howMany} is smaller than the total number of combinations, a random * subset of all combinations are returned. The order is shuffled randomly. If no parameters * are specified or {@code perParam} is 0, a single empty combination is returned. *///from ww w . ja v a 2 s. co m static List<List<?>> chooseHyperParameterCombos(List<HyperParamValues<?>> ranges, int howMany) { // Put some reasonable upper limit on the number of combos Preconditions.checkArgument(howMany > 0 && howMany <= MAX_COMBOS); int numParams = ranges.size(); int perParam = chooseValuesPerHyperParam(ranges, howMany); if (numParams == 0 || perParam == 0) { return Collections.singletonList(Collections.emptyList()); } int howManyCombos = 1; List<List<?>> paramRanges = new ArrayList<>(numParams); for (HyperParamValues<?> range : ranges) { List<?> values = range.getTrialValues(perParam); paramRanges.add(values); howManyCombos *= values.size(); } List<List<?>> allCombinations = new ArrayList<>(howManyCombos); for (int combo = 0; combo < howManyCombos; combo++) { List<Object> combination = new ArrayList<>(numParams); for (int param = 0; param < numParams; param++) { int whichValueToTry = combo; for (int i = 0; i < param; i++) { whichValueToTry /= paramRanges.get(i).size(); } whichValueToTry %= paramRanges.get(param).size(); combination.add(paramRanges.get(param).get(whichValueToTry)); } allCombinations.add(combination); } if (howMany >= howManyCombos) { Collections.shuffle(allCombinations); return allCombinations; } RandomDataGenerator rdg = new RandomDataGenerator(RandomManager.getRandom()); int[] indices = rdg.nextPermutation(howManyCombos, howMany); List<List<?>> result = new ArrayList<>(indices.length); for (int i = 0; i < indices.length; i++) { result.add(allCombinations.get(i)); } Collections.shuffle(result); return result; }
From source file:com.joyent.manta.client.MantaObjectDepthComparatorTest.java
public void verifyOrderingWithMoreSubdirectoriesDataSet() { List<MantaObject> objects = new ArrayList<>(); List<MantaObject> dirs = dirObjects(29); for (MantaObject dir : dirs) { objects.add(dir);//from ww w. j a v a2 s. c om objects.addAll(fileObjects(dir, 24)); MantaObject subdir = mockDirectory(dir.getPath() + MantaClient.SEPARATOR + "subdir"); objects.add(subdir); objects.addAll(fileObjects(subdir, 3)); } Collections.shuffle(objects); objects.sort(MantaObjectDepthComparator.INSTANCE); assertOrdering(objects); }
From source file:com.twitter.distributedlog.service.balancer.CountBasedStreamChooser.java
CountBasedStreamChooser(Map<SocketAddress, Set<String>> streams) { Preconditions.checkArgument(streams.size() > 0, "Only support no-empty streams distribution"); streamsDistribution = new ArrayList<Pair<SocketAddress, LinkedList<String>>>(streams.size()); for (Map.Entry<SocketAddress, Set<String>> entry : streams.entrySet()) { LinkedList<String> randomizedStreams = new LinkedList<String>(entry.getValue()); Collections.shuffle(randomizedStreams); streamsDistribution.add(Pair.of(entry.getKey(), randomizedStreams)); }/* w w w . j a va 2 s . c o m*/ // sort the hosts by the number of streams in descending order Collections.sort(streamsDistribution, this); pivot = 0; pivotCount = streamsDistribution.get(0).getValue().size(); findNextPivot(); next = 0; }
From source file:com.github.fge.uritemplate.SpecExamplesBySectionTest.java
@DataProvider public Iterator<Object[]> getData() { final List<Object[]> list = Lists.newArrayList(); VariableMapBuilder builder;/*from ww w. ja va2 s . com*/ Iterator<Map.Entry<String, JsonNode>> iterator; Map.Entry<String, JsonNode> entry; for (final JsonNode node : data) { // Cycle through values builder = VariableMap.newBuilder(); iterator = node.get("variables").fields(); while (iterator.hasNext()) { entry = iterator.next(); if (entry.getValue().isNull()) continue; builder.addValue(entry.getKey(), Util.fromJson(entry.getValue())); } for (final JsonNode n : node.get("testcases")) list.add(new Object[] { n.get(0).textValue(), builder.freeze(), n.get(1) }); } Collections.shuffle(list); return list.iterator(); }
From source file:com.serphacker.serposcope.di.CaptchaSolverFactoryImpl.java
@Override public CaptchaSolver get(Config config) { if (config == null) { return null; }/*from w ww .j ava 2s. c om*/ List<CaptchaSolver> solvers = new ArrayList<>(); if (!StringUtils.isEmpty(config.getDbcUser()) && !StringUtils.isEmpty(config.getDbcPass())) { DeathByCaptchaSolver solver = new DeathByCaptchaSolver(config.getDbcUser(), config.getDbcPass()); if (init(solver)) { solvers.add(solver); } } if (!StringUtils.isEmpty(config.getDecaptcherUser()) && !StringUtils.isEmpty(config.getDecaptcherPass())) { DecaptcherSolver solver = new DecaptcherSolver(config.getDecaptcherUser(), config.getDecaptcherPass()); if (init(solver)) { solvers.add(solver); } } if (!StringUtils.isEmpty(config.getAnticaptchaKey())) { AntiCaptchaSolver solver = new AntiCaptchaSolver(config.getAnticaptchaKey()); if (init(solver)) { solvers.add(solver); } } if (solvers.isEmpty()) { return null; } Collections.shuffle(solvers); return new FailoverCaptchaSolver(solvers); }
From source file:com.adaptris.core.fs.enhanced.FileSorterCase.java
protected List<File> createFiles(int count, String prefix, String suffix, long pause) throws Exception { List<Integer> nums = new ArrayList<Integer>(); List<File> result = new ArrayList<File>(); for (int i = 1; i <= count; i++) { nums.add(Integer.valueOf(i)); }//from ww w . j av a 2 s. co m Collections.shuffle(nums); for (Integer i : nums) { File f = new File(baseDir, String.format("%1$s-%2$03d%3$s", prefix, i, suffix)); // Write it in gradients of 512bytes ensureSize(512 * i, f); result.add(f); if (pause > 0) { Thread.sleep(pause); } } log("createFiles", result); return result; }
From source file:com.streamreduce.util.SecurityUtil.java
public static String generateRandomString(int n) { Random rd = new Random(); char lowerChars[] = "abcdefghijklmnopqrstuvwxyz".toCharArray(); char upperChars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray(); char numbers[] = "0123456789".toCharArray(); //char specialChars[] = "~!@#$%^&*()-_=+[{]}|;:<>/?".toCharArray(); char specialChars[] = "!$-_+".toCharArray(); // limited subset List<Character> pwdLst = new ArrayList<>(); for (int g = 0; g <= n; g++) { for (int z = 0; z < 1; z++) { if (g == 0) { pwdLst.add(numbers[rd.nextInt(10)]); // must match char array length(s) above } else if (g == 1) { pwdLst.add(lowerChars[rd.nextInt(26)]); } else if (g == 2) { pwdLst.add(upperChars[rd.nextInt(26)]); } else if (g == 3) { pwdLst.add(specialChars[rd.nextInt(5)]); }//from w w w.ja va 2 s. co m } if (pwdLst.size() == n) { break; } if (g + 1 == 4) { g = (int) (Math.random() * 5); } } StringBuilder password = new StringBuilder(); Collections.shuffle(pwdLst); for (Character aPwdLst : pwdLst) { password.append(aPwdLst); } return password.toString(); }
From source file:org.flite.cach3.test.l2.L2ReadThroughSingleTest.java
@Test public void test() { final TestSvc test = (TestSvc) context.getBean("testSvc"); final String g1 = RandomStringUtils.randomAlphabetic(4) + "-"; final List<Long> ids = new ArrayList<Long>(); final long base = System.currentTimeMillis() - 200000; for (int ix = 0; ix < 10; ix++) { final long id = base + ix; ids.add(id);//from ww w . ja v a2s . c o m assertTrue(test.getL2SingleDelta(id, g1).startsWith(g1)); } final String g2 = RandomStringUtils.randomAlphabetic(6) + "-"; final List<Long> addls = new ArrayList<Long>(); addls.addAll(ids); for (int ix = 0; ix < 10; ix++) { addls.add(1000L + ix); } Collections.shuffle(addls); final List<String> results = test.getL2MultiAlpha(addls, g2); for (int ix = 0; ix < addls.size(); ix++) { final Long key = addls.get(ix); final String result = results.get(ix); System.out.println(result); assertTrue(StringUtils.contains(result, key.toString())); assertTrue(result.startsWith(ids.contains(key) ? g1 : g2)); } }