List of usage examples for java.util Collections shuffle
@SuppressWarnings({ "rawtypes", "unchecked" }) public static void shuffle(List<?> list, Random rnd)
From source file:edu.byu.nlp.util.Collections3.java
/** * Creates a copy the iterable and uses the provided RandomGenerator to shuffle the copy. *//*from ww w. ja v a 2 s. c om*/ public static <E> List<E> shuffledCopyOf(Iterable<? extends E> it, RandomGenerator rnd) { List<E> list = Lists.newArrayList(it); Collections.shuffle(list, new RandomAdaptor(rnd)); return list; }
From source file:mase.app.soccer.ProgSoccerAgent.java
@Override public void step(SimState state) { super.step(state); Soccer soc = (Soccer) state;/*from w ww .j a v a 2 s . co m*/ Ball ball = soc.ball; /** * ***** Update agent status ****** */ // the agent just kicked the ball (is over the ball), do nothing if (justKicked) { return; } // Is the agent free to drible towards the goal? SoccerAgent impedingDrible = closestInFront(oppGoal.subtract(getLocation()).angle(), openDistance, openAngle); this.openToDrible = impedingDrible == null; // Update the justPassed flag if (justPassed) { if (ball.getCurrentSpeed() < 0.01) { justPassed = false; } else { for (SoccerAgent a : others) { if (a.hasPossession) { justPassed = false; break; } } } } /** * ***** Actions ****** */ // Execute the first possible action // If the agent has possession of the ball: // -- Shoot to goal if it has clear shot and it is within range // -- Pass to a teammate that is open and closer to the goal // -- Drible towards the goal if open // -- Drible away from the closest agent in front, if there is space to do so // -- Pass the ball to any teammate open to drible // -- Pass the ball to any teammate with clear pass // -- Shoot the ball away from the closest agent in front // If the agent doesnt have the ball: // -- Move towards the ball if it is the closest teammate closest to it // -- Move towards the ball if it is the closest teammate to it with the path clear (clearDist = agentRadius) // -- Defend the goal if it is the closest teammate to it // -- If on defense or team possession is undefined: // -- Mark the nearest undefended opponent (undefended = no nearby teammate, move to between the opponent and their goal) // -- If on attack // -- ?? // -- Keep within passing distance of the closest agent (what about 2 isolate agents, with no ball) // -- Get open if (hasPossession) { // Shoot to goal if it has clear shot and it is within range List<Double2D> shuffledTargets = new ArrayList<>(goalTargets); Collections.shuffle(shuffledTargets, rand); for (Double2D target : shuffledTargets) { if (clearShot(ball, target, kickRange, clearDistance)) { kickTowards(ball, target, kickSpeed); lastAction = "Clear shot to goal: " + target; return; } } // Pass to a teammate that is open and closer to the goal List<SoccerAgent> shuffledTeam = new ArrayList<>(teamMates); Collections.shuffle(shuffledTeam, rand); double distToGoal = this.distanceTo(oppGoal); for (SoccerAgent mate : shuffledTeam) { // at least one robot of distance closer if (((ProgSoccerAgent) mate).openToDrible && mate.distanceTo(oppGoal) < distToGoal - soc.par.agentRadius * 2) { double d = this.distanceTo(mate); if (clearShot(ball, mate, kickRange, clearDistance)) { kickTowards(ball, mate.getLocation(), optimalKickSpeed(d)); lastAction = "Pass to advanced teammate: " + mate; justPassed = true; return; } } } // Drible towards the goal if open if (openToDrible) { kickTowards(ball, oppGoal, dribleSpeed); lastAction = "Drible towards goal"; return; } // Drible away from closest in front if there is space to do so // Calculate the vectors perpendicular to the agent-obstacle vector Double2D agToClosest = impedingDrible.getLocation().subtract(getLocation()); Double2D awayOne = agToClosest.rotate(-Math.PI / 2); Double2D awayTwo = agToClosest.rotate(Math.PI / 2); Double2D futureOne = ball.getLocation().add(awayOne.normalize().multiply(openDistance)); Double2D futureTwo = ball.getLocation().add(awayTwo.normalize().multiply(openDistance)); // One is the closest to goal, Two is the farthest if (futureTwo.distance(oppGoal) < futureOne.distance(oppGoal)) { Double2D temp = futureOne; futureOne = futureTwo; futureTwo = temp; temp = awayOne; awayOne = awayTwo; awayTwo = temp; } // Try to move in the One direction, checking if it is inside the field and is clear if (futureOne.x < field.width && futureOne.x > 0 && futureOne.y > 0 && futureOne.y < field.height && closestInFront(awayOne.angle(), openDistance, openAngle) == null) { kickBall(awayOne.angle(), dribleSpeed); lastAction = "Drible away from closest (1): " + impedingDrible; return; } // Otherwise, try to move in the Two direction if (futureTwo.x < field.width && futureTwo.x > 0 && futureTwo.y > 0 && futureTwo.y < field.height && closestInFront(awayTwo.angle(), openDistance, openAngle) == null) { kickBall(awayTwo.angle(), dribleSpeed); lastAction = "Drible away from closest (2): " + impedingDrible; return; } // Pass to any teammate that can drible towards goal for (SoccerAgent mate : shuffledTeam) { if (((ProgSoccerAgent) mate).openToDrible && clearShot(ball, mate, kickRange, clearDistance)) { kickTowards(ball, mate.getLocation(), optimalKickSpeed(this.distanceTo(mate))); lastAction = "Pass to any teammate open to drible: " + mate; justPassed = true; return; } } // Pass to any teammate with clear pass for (SoccerAgent mate : shuffledTeam) { if (clearShot(ball, mate, kickRange, clearDistance)) { kickTowards(ball, mate.getLocation(), optimalKickSpeed(this.distanceTo(mate))); lastAction = "Pass to any teammate with clear pass: " + mate; justPassed = true; return; } } // Shoot ball away from closest in front -- last case scenario, should this exist? kickBall(awayOne.angle(), kickSpeed); lastAction = "Shooting away from the closest agent"; } else { // NO BALL POSSESSION List<Pair<SoccerAgent, Double>> sorted = sortByProximity(ownTeam, ball.getLocation()); // Move towards the ball it is the closest agent, regardless of clear paths if (!justPassed && sorted.get(0).getLeft() == this) { moveTowards(ball.getLocation()); lastAction = "Closest, move to the ball"; return; } // Defend the goal if it is the closest to it (excluding the agent closest to the ball) sorted = sortByProximity(ownTeam, ownGoal); boolean closestToGoal = false; for (Pair<SoccerAgent, Double> p : sorted) { ProgSoccerAgent pp = (ProgSoccerAgent) p.getLeft(); if (!pp.lastAction.equals("Closest, move to the ball")) { closestToGoal = (pp == this); break; } } if (closestToGoal) { Double2D gkPosition = new Double2D( ownGoal.x < oppGoal.x ? ownGoal.x + soc.par.agentRadius + 1 : ownGoal.x - soc.par.agentRadius - 1, Math.min(ownGoal.y + soc.par.goalWidth / 2, Math.max(ownGoal.y - soc.par.goalWidth / 2, ball.getLocation().y))); moveTowards(gkPosition); lastAction = "Goalkeeper duty: " + gkPosition; return; } if (!justPassed) { // Move towards the ball if it is the closest one with clear line boolean closestClear = false; for (Pair<SoccerAgent, Double> p : sorted) { ProgSoccerAgent pp = (ProgSoccerAgent) p.getLeft(); if (pp.clearPath(ball.getLocation(), pp.getRadius())) { closestClear = (pp == this); break; } } if (closestClear) { moveTowards(ball.getLocation()); lastAction = "Closest with clear path, move to the ball"; return; } } // If on defense if (soc.referee.teamPossession == null || soc.referee.teamPossession != this.teamColor) { // Mark the nearest opponent that I'm the closest SoccerAgent closestOpp = null; double min = Double.POSITIVE_INFINITY; for (SoccerAgent a : oppTeam) { if (closestTeammate(a.getLocation(), true, true) == this) { // check if I'm the closest double d = this.distanceTo(a); if (d < min) { min = d; closestOpp = a; } } } if (closestOpp != null) { // Move to between the agent and my goal Double2D intersect = ownGoal.subtract(closestOpp.getLocation()).normalize() .multiply(soc.par.agentRadius * 3).add(closestOpp.getLocation()); moveTowards(intersect); lastAction = "Mark closest: " + closestOpp; return; } } else { // On attack // Find the closest agent between me and the ball SoccerAgent closestOther = null; double min = Double.POSITIVE_INFINITY; for (SoccerAgent a : others) { if (StaticPolygon.distToSegment(a.getLocation(), this.getLocation(), ball.getLocation()) < soc.par.agentRadius * 2) { double d = this.distanceTo(a); if (d < min) { min = d; closestOther = a; } } } // Move perendicularly to the agent-ball vector, in the direction opposite to the closest agent if (closestOther != null) { boolean left = StaticPolygon.isLeftOf(closestOther.getLocation(), this.getLocation(), ball.getLocation()); double angle = ball.getLocation().subtract(this.getLocation()).angle(); if (left) { // Go to right super.move(angle - Math.PI / 2, moveSpeed); } else { super.move(angle + Math.PI / 2, moveSpeed); } lastAction = "Get open"; return; } } lastAction = "Do nothing without the ball"; } }
From source file:org.apache.solr.client.solrj.impl.HttpSolrClientConPoolTest.java
public void testLBClient() throws IOException, SolrServerException { PoolingHttpClientConnectionManager pool = HttpClientUtil.createPoolingConnectionManager(); final HttpSolrClient client1; int threadCount = atLeast(2); final ExecutorService threads = ExecutorUtil.newMDCAwareFixedThreadPool(threadCount, new SolrjNamedThreadFactory(getClass().getSimpleName() + "TestScheduler")); CloseableHttpClient httpClient = HttpClientUtil.createClient(new ModifiableSolrParams(), pool); try {/*w w w. j a v a 2s .co m*/ final LBHttpSolrClient roundRobin = new LBHttpSolrClient.Builder().withBaseSolrUrl(fooUrl) .withBaseSolrUrl(barUrl).withHttpClient(httpClient).build(); List<ConcurrentUpdateSolrClient> concurrentClients = Arrays.asList( new ConcurrentUpdateSolrClient.Builder(fooUrl).withHttpClient(httpClient) .withThreadCount(threadCount).withQueueSize(10).withExecutorService(threads).build(), new ConcurrentUpdateSolrClient.Builder(barUrl).withHttpClient(httpClient) .withThreadCount(threadCount).withQueueSize(10).withExecutorService(threads).build()); for (int i = 0; i < 2; i++) { roundRobin.deleteByQuery("*:*"); } for (int i = 0; i < 57; i++) { final SolrInputDocument doc = new SolrInputDocument("id", "" + i); if (random().nextBoolean()) { final ConcurrentUpdateSolrClient concurrentClient = concurrentClients .get(random().nextInt(concurrentClients.size())); concurrentClient.add(doc); // here we are testing that CUSC and plain clients reuse pool concurrentClient.blockUntilFinished(); } else { if (random().nextBoolean()) { roundRobin.add(doc); } else { final UpdateRequest updateRequest = new UpdateRequest(); updateRequest.add(doc); // here we mimic CloudSolrClient impl final List<String> urls = Arrays.asList(fooUrl, barUrl); Collections.shuffle(urls, random()); LBHttpSolrClient.Req req = new LBHttpSolrClient.Req(updateRequest, urls); roundRobin.request(req); } } } for (int i = 0; i < 2; i++) { roundRobin.commit(); } int total = 0; for (int i = 0; i < 2; i++) { total += roundRobin.query(new SolrQuery("*:*")).getResults().getNumFound(); } assertEquals(57, total); PoolStats stats = pool.getTotalStats(); //System.out.println("\n"+stats); assertEquals("expected number of connections shouldn't exceed number of endpoints" + stats, 2, stats.getAvailable()); } finally { threads.shutdown(); HttpClientUtil.close(httpClient); } }
From source file:info.rmarcus.birkhoffvonneumann.MatrixUtils.java
public static int[] randomPermutationSparse(Random r, int n) { List<Integer> s = IntStream.range(0, n).mapToObj(i -> i) .collect(Collectors.toCollection(() -> new ArrayList<Integer>(n))); Collections.shuffle(s, r); return NullUtils.orThrow(s.stream().mapToInt(i -> i).toArray(), () -> new BVNRuntimeException("Could not convert ArrayList to array!")); }
From source file:com.github.rinde.opt.localsearch.Swaps.java
static <C, T> ImmutableList<ImmutableList<T>> opt2(ImmutableList<ImmutableList<T>> schedule, IntList startIndices, C context, RouteEvaluator<C, T> evaluator, boolean depthFirst, Optional<RandomGenerator> rng, Optional<? extends ProgressListener<T>> listener) throws InterruptedException { checkArgument(schedule.size() == startIndices.size()); final Schedule<C, T> baseSchedule = Schedule.create(context, schedule, startIndices, evaluator); final Object2DoubleLinkedOpenHashMap<ImmutableList<T>> routeCostCache = new Object2DoubleLinkedOpenHashMap<>( CACHE_SIZE);/*from w ww. j av a 2 s . c om*/ for (int i = 0; i < baseSchedule.routes.size(); i++) { routeCostCache.put(baseSchedule.routes.get(i), baseSchedule.objectiveValues.getDouble(i)); } Schedule<C, T> bestSchedule = baseSchedule; boolean isImproving = true; while (isImproving) { isImproving = false; final Schedule<C, T> curBest = bestSchedule; Iterator<Swap<T>> it = swapIterator(curBest); if (depthFirst) { // randomize ordering of swaps final List<Swap<T>> swaps = newArrayList(it); Collections.shuffle(swaps, new RandomAdaptor(rng.get())); it = swaps.iterator(); } while (it.hasNext()) { if (Thread.interrupted()) { throw new InterruptedException(); } final Swap<T> swapOperation = it.next(); final Optional<Schedule<C, T>> newSchedule = swap(curBest, swapOperation, bestSchedule.objectiveValue - curBest.objectiveValue, routeCostCache); if (newSchedule.isPresent()) { isImproving = true; bestSchedule = newSchedule.get(); if (listener.isPresent()) { listener.get().notify(bestSchedule.routes, bestSchedule.objectiveValue); } if (depthFirst) { // first improving swap is chosen as new starting point (depth // first). break; } } } } return bestSchedule.routes; }
From source file:org.elasticsearch.http.DeprecationHttpIT.java
/** * Run a request that receives a predictably randomized number of deprecation warnings. * <p>/* ww w . j av a 2s . c o m*/ * Re-running this back-to-back helps to ensure that warnings are not being maintained across requests. */ private void doTestDeprecationWarningsAppearInHeaders() throws IOException { final boolean useDeprecatedField = randomBoolean(); final boolean useNonDeprecatedSetting = randomBoolean(); // deprecated settings should also trigger a deprecation warning final List<Setting<Boolean>> settings = new ArrayList<>(3); settings.add(TEST_DEPRECATED_SETTING_TRUE1); if (randomBoolean()) { settings.add(TEST_DEPRECATED_SETTING_TRUE2); } if (useNonDeprecatedSetting) { settings.add(TEST_NOT_DEPRECATED_SETTING); } Collections.shuffle(settings, random()); // trigger all deprecations Response response = getRestClient().performRequest("GET", "/_test_cluster/deprecated_settings", Collections.emptyMap(), buildSettingsRequest(settings, useDeprecatedField)); assertThat(response.getStatusLine().getStatusCode(), equalTo(OK.getStatus())); final List<String> deprecatedWarnings = getWarningHeaders(response.getHeaders()); final List<Matcher<String>> headerMatchers = new ArrayList<>(4); headerMatchers.add(equalTo(TestDeprecationHeaderRestAction.DEPRECATED_ENDPOINT)); if (useDeprecatedField) { headerMatchers.add(equalTo(TestDeprecationHeaderRestAction.DEPRECATED_USAGE)); } for (Setting<?> setting : settings) { if (setting.isDeprecated()) { headerMatchers.add(equalTo("[" + setting.getKey() + "] setting was deprecated in Elasticsearch and will be removed in a future release! " + "See the breaking changes documentation for the next major version.")); } } assertThat(deprecatedWarnings, hasSize(headerMatchers.size())); for (final String deprecatedWarning : deprecatedWarnings) { assertThat(deprecatedWarning, matches(WARNING_HEADER_PATTERN.pattern())); } final List<String> actualWarningValues = deprecatedWarnings.stream() .map(DeprecationLogger::extractWarningValueFromWarningHeader).collect(Collectors.toList()); for (Matcher<String> headerMatcher : headerMatchers) { assertThat(actualWarningValues, hasItem(headerMatcher)); } }
From source file:edu.byu.nlp.data.app.AnnotationStream2Annotators.java
public static int[] clusterAnnotatorParameters(double[][][] annotatorParameters, ClusteringMethod clusteringMethod, int k, int maxIterations, double smooth, RandomGenerator rnd) { Preconditions.checkNotNull(annotatorParameters); Preconditions.checkArgument(annotatorParameters.length > 0); int numAnnotators = annotatorParameters.length; // put each annotator in a singleton cluster List<Annotator> annotators = Lists.newArrayList(); for (int i = 0; i < numAnnotators; i++) { annotators.add(new Annotator(annotatorParameters[i], i, i)); }// w ww . j a v a 2 s . c o m // precompute potenially useful quantities double uniformClusterSize = (double) numAnnotators / k; // transformed confusion matrices switch (clusteringMethod) { case NONE: break; case RANDOM: // shuffle, then assign in equal blocks Collections.shuffle(annotators, new RandomAdaptor(rnd)); for (int c = 0; c < k; c++) { int start = (int) Math.floor(c * uniformClusterSize); int end = (int) Math.floor(c * uniformClusterSize + uniformClusterSize); for (int a = start; a < end; a++) { annotators.get(a).clusterAssignment = c; } } break; case ACCURACY: logger.debug("sorting annotators by accuracy"); Collections.sort(annotators); // re-order annotators so that more accurate ones appear first for (int i = 0; i < annotatorParameters.length; i++) { logger.debug("annotator #" + i + " accuracy=" + accuracyOf(annotatorParameters[i])); } // now divide annotators into equal chunks--like accuracies will cluster together for (int c = 0; c < k; c++) { int start = (int) Math.floor(c * uniformClusterSize); int end = (int) Math.floor(c * uniformClusterSize + uniformClusterSize); for (int a = start; a < end; a++) { annotators.get(a).clusterAssignment = c; } } break; case KMEANS: assignKMeansClusters(annotators, k, maxIterations, rnd); break; default: throw new IllegalArgumentException("unknown aggregation method=" + clusteringMethod); } // return the mapping vector int[] clusterAssignments = new int[numAnnotators]; for (int a = 0; a < numAnnotators; a++) { Annotator annotator = annotators.get(a); clusterAssignments[annotator.index] = annotator.clusterAssignment; } return clusterAssignments; }
From source file:com.mgmtp.jfunk.core.mail.MailAccountManager.java
/** * Reserves an available mail account from the specified pool under the specified reservation * key. The method blocks until an account is available. * //from w w w . ja v a2 s . co m * @param pool * the mail address pool to reserve an account from * @param accountReservationKey * the key under which to reserve the account * @return the reserved mail account */ public MailAccount reserveMailAccount(final String accountReservationKey, final String pool) { if (pool == null && emailAddressPools.keySet().size() > 1) { throw new IllegalStateException("No pool specified but multiple pools available."); } String poolKey = pool == null ? defaultPool : pool; List<MailAccount> addressPool = newArrayList(emailAddressPools.get(poolKey)); Collections.shuffle(addressPool, random.getRandom()); return reserveAvailableMailAccount(accountReservationKey, addressPool); }
From source file:org.apache.solr.core.BlobRepository.java
private Replica getSystemCollReplica() { ZkStateReader zkStateReader = this.coreContainer.getZkController().getZkStateReader(); ClusterState cs = zkStateReader.getClusterState(); DocCollection coll = cs.getCollectionOrNull(CollectionsHandler.SYSTEM_COLL); if (coll == null) throw new SolrException(SERVICE_UNAVAILABLE, ".system collection not available"); ArrayList<Slice> slices = new ArrayList<>(coll.getActiveSlices()); if (slices.isEmpty()) throw new SolrException(SERVICE_UNAVAILABLE, "No active slices for .system collection"); Collections.shuffle(slices, RANDOM); //do load balancing Replica replica = null;/*from w w w.j ava2 s. com*/ for (Slice slice : slices) { List<Replica> replicas = new ArrayList<>(slice.getReplicasMap().values()); Collections.shuffle(replicas, RANDOM); for (Replica r : replicas) { if (r.getState() == Replica.State.ACTIVE) { if (zkStateReader.getClusterState().getLiveNodes() .contains(r.get(ZkStateReader.NODE_NAME_PROP))) { replica = r; break; } else { log.info("replica {} says it is active but not a member of live nodes", r.get(ZkStateReader.NODE_NAME_PROP)); } } } } if (replica == null) { throw new SolrException(SERVICE_UNAVAILABLE, ".no active replica available for .system collection"); } return replica; }
From source file:com.ifesdjeen.cascading.cassandra.hadoop.ColumnFamilyInputFormat.java
public List<InputSplit> getSplits(JobContext context) throws IOException { Configuration conf = context.getConfiguration(); validateConfiguration(conf);//from ww w . jav a 2 s. c o m // cannonical ranges and nodes holding replicas List<TokenRange> masterRangeNodes = getRangeMap(conf); keyspace = ConfigHelper.getInputKeyspace(context.getConfiguration()); cfName = ConfigHelper.getInputColumnFamily(context.getConfiguration()); partitioner = ConfigHelper.getInputPartitioner(context.getConfiguration()); logger.debug("partitioner is " + partitioner); // cannonical ranges, split into pieces, fetching the splits in parallel ExecutorService executor = Executors.newCachedThreadPool(); List<InputSplit> splits = new ArrayList<InputSplit>(); try { List<Future<List<InputSplit>>> splitfutures = new ArrayList<Future<List<InputSplit>>>(); KeyRange jobKeyRange = ConfigHelper.getInputKeyRange(conf); Range<Token> jobRange = null; if (jobKeyRange != null && jobKeyRange.start_token != null) { assert partitioner .preservesOrder() : "ConfigHelper.setInputKeyRange(..) can only be used with a order preserving paritioner"; assert jobKeyRange.start_key == null : "only start_token supported"; assert jobKeyRange.end_key == null : "only end_token supported"; jobRange = new Range<Token>(partitioner.getTokenFactory().fromString(jobKeyRange.start_token), partitioner.getTokenFactory().fromString(jobKeyRange.end_token), partitioner); } for (TokenRange range : masterRangeNodes) { if (jobRange == null) { // for each range, pick a live owner and ask it to compute bite-sized splits splitfutures.add(executor.submit(new SplitCallable(range, conf))); } else { Range<Token> dhtRange = new Range<Token>( partitioner.getTokenFactory().fromString(range.start_token), partitioner.getTokenFactory().fromString(range.end_token), partitioner); if (dhtRange.intersects(jobRange)) { for (Range<Token> intersection : dhtRange.intersectionWith(jobRange)) { range.start_token = partitioner.getTokenFactory().toString(intersection.left); range.end_token = partitioner.getTokenFactory().toString(intersection.right); // for each range, pick a live owner and ask it to compute bite-sized splits splitfutures.add(executor.submit(new SplitCallable(range, conf))); } } } } // wait until we have all the results back for (Future<List<InputSplit>> futureInputSplits : splitfutures) { try { splits.addAll(futureInputSplits.get()); } catch (Exception e) { throw new IOException("Could not get input splits", e); } } } finally { executor.shutdownNow(); } assert splits.size() > 0; Collections.shuffle(splits, new Random(System.nanoTime())); return splits; }