List of usage examples for java.util Collections shuffle
public static void shuffle(List<?> list)
From source file:net.sourceforge.subsonic.service.sonos.SonosHelper.java
public List<AbstractMedia> forShuffleAlbumList(AlbumListType albumListType, int count, String username, HttpServletRequest request) {//from ww w. j ava 2 s . c o m AlbumList albumList = createAlbumList(albumListType, 0, 40, username); List<MediaFile> songs = new ArrayList<MediaFile>(); for (MediaFile album : albumList.getAlbums()) { songs.addAll(filterMusic(mediaFileService.getChildrenOf(album, true, false, false))); } Collections.shuffle(songs); songs = songs.subList(0, Math.min(count, songs.size())); return forMediaFiles(songs, username, request); }
From source file:ch.gianulli.flashcards.SessionFragment.java
private void fetchCards() { if (mCardsLoader != null) { mCardsLoader.cancel(true);// w w w . ja v a 2 s . c o m mCardsLoader = null; } mCardsLoader = new AsyncTask<Void, Void, Boolean>() { @Override protected void onPreExecute() { super.onPreExecute(); setActivePage(Page.PROGRESS); } @Override protected Boolean doInBackground(Void... params) { try { mList = TrelloList.getList(mTrelloApi, null, mListId); if (mList != null) { // Select cards mCards = mList.getCards(); int mode = getArguments().getInt(KEY_MODE); int n = getArguments().getInt(KEY_NBR_OF_CARDS); if (mode == SessionActivity.MODE_AT_RANDOM) { mCards = new ArrayList<>(mCards); // cards in list stay untouched Collections.shuffle(mCards); mCards = new ArrayList<>(mCards.subList(0, Math.min(n, mCards.size()))); } else if (mode == SessionActivity.MODE_FROM_TOP) { mCards = new ArrayList<>(mCards.subList(0, Math.min(n, mCards.size()))); } else if (mode == SessionActivity.MODE_FROM_BOTTOM) { mCards = new ArrayList<>(mCards.subList(Math.max(0, mCards.size() - n), mCards.size())); Collections.reverse(mCards); } return true; } else { throw new TrelloNotAccessibleException("Result was null."); } } catch (TrelloNotAuthorizedException e) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { mTrelloApi.requestAuthorization(getActivity().getSupportFragmentManager()); } }); } catch (TrelloNotAccessibleException e) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { setActivePage(Page.NO_CONNECTION); } }); Log.d("test", "Trello not accessible: " + e.getMessage()); } return false; } @Override protected void onPostExecute(Boolean success) { if (success) { mAdapter.setCards(mCards); setActivePage(Page.SESSION_VIEW); mViewPager.setCurrentItem(0); // Update page indicator mPageIndicator.setText(getResources().getString(R.string.page_indicator_text, mViewPager.getCurrentItem() + 1, mAdapter.getCount())); } } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); }
From source file:com.example.anthony.bigscreenforreddit.MainFragment.java
private void loadRows() { /*mRowsAdapter = new ArrayObjectAdapter(new ListRowPresenter()); // ww w.j a va2s . c o m */ /* GridItemPresenter *//* HeaderItem gridItemPresenterHeader = new HeaderItem(0, "GridItemPresenter"); GridItemPresenter mGridPresenter = new GridItemPresenter(); ArrayObjectAdapter gridRowAdapter = new ArrayObjectAdapter(mGridPresenter); gridRowAdapter.add("ITEM 1"); gridRowAdapter.add("ITEM 2"); gridRowAdapter.add("ITEM 3"); mRowsAdapter.add(new ListRow(gridItemPresenterHeader, gridRowAdapter)); *//* CardPresenter *//* HeaderItem cardPresenterHeader = new HeaderItem(1, "CardPresenter"); CardPresenter cardPresenter = new CardPresenter(); ArrayObjectAdapter cardRowAdapter = new ArrayObjectAdapter(cardPresenter); for(int i=0; i<10; i++) { Movie movie = new Movie(); if(i%3 == 0) { movie.setCardImageUrl("http://heimkehrend.raindrop.jp/kl-hacker/wp-content/uploads/2014/08/DSC02580.jpg"); } else if (i%3 == 1) { movie.setCardImageUrl("http://heimkehrend.raindrop.jp/kl-hacker/wp-content/uploads/2014/08/DSC02630.jpg"); } else { movie.setCardImageUrl("http://heimkehrend.raindrop.jp/kl-hacker/wp-content/uploads/2014/08/DSC02529.jpg"); } movie.setTitle("title" + i); movie.setStudio("studio" + i); cardRowAdapter.add(movie); mRowsAdapter.add(new ListRow(cardPresenterHeader, cardRowAdapter)); *//* Set *//* setAdapter(mRowsAdapter); }*/ //List<PostInfo> list = PostList.setupReddit(); List<RedditObject> list = RedditObjectWrapper.class; mRowsAdapter = new ArrayObjectAdapter(new ListRowPresenter()); mCardPresenter = new CardPresenter(); int i; for (i = 0; i < NUM_ROWS; i++) { if (i != 0) { Collections.shuffle(list); } ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(mCardPresenter); for (int j = 0; j < NUM_COLS; j++) { listRowAdapter.add(list.get(j % 5)); } // HeaderItem header = new HeaderItem(i, MovieList.MOVIE_CATEGORY[i], null); HeaderItem header = new HeaderItem(i, Constants.Reddit.DEFAULT_SUBREDDITS[i]); mRowsAdapter.add(new ListRow(header, listRowAdapter)); } // HeaderItem gridHeader = new HeaderItem(i, "PREFERENCES", null); HeaderItem gridHeader = new HeaderItem(i, "PREFERENCES"); GridItemPresenter mGridPresenter = new GridItemPresenter(); ArrayObjectAdapter gridRowAdapter = new ArrayObjectAdapter(mGridPresenter); gridRowAdapter.add(getResources().getString(R.string.grid_view)); gridRowAdapter.add(getString(R.string.error_fragment)); gridRowAdapter.add(getResources().getString(R.string.personal_settings)); gridRowAdapter.add(getString(R.string.Login)); mRowsAdapter.add(new ListRow(gridHeader, gridRowAdapter)); setAdapter(mRowsAdapter); }
From source file:ga.rugal.jpt.common.tracker.server.TrackedTorrent.java
/** * Get a list of peers we can return in an announce response for this * torrent.//from w w w. j a va 2s . c o m * * @param peer The peer making the request, so we can exclude it from the * list of returned peers. * * @return A list of peers we can include in an announce response. */ public List<Peer> getSomePeers(TrackedPeer peer) { List<Peer> peers = new LinkedList<>(); List<TrackedPeer> candidates; candidates = new LinkedList<>(this.peers.values()); Collections.shuffle(candidates); int count = 0; for (TrackedPeer candidate : candidates) { // Collect unfresh peers, and obviously don't serve them as well. if (!candidate.isFresh() || (candidate.looksLike(peer) && !candidate.equals(peer))) { LOG.debug(CommonLogContent.STALE_PEERS, candidate); this.peers.remove(candidate.getHexPeerId()); continue; } // Don't include the requesting peer in the answer. if (peer.looksLike(candidate)) { continue; } // Collect unfresh peers, and obviously don't serve them as well. if (!candidate.isFresh()) { LOG.debug(CommonLogContent.STALE_PEERS, candidate.getHexPeerId()); this.peers.remove(candidate.getHexPeerId()); continue; } // Only serve at most ANSWER_NUM_PEERS peers if (count++ > this.answerPeers) { break; } peers.add(candidate); } return peers; }
From source file:edu.umd.cs.guitar.runner.GuitarController.java
/** * Replays top k generated test cases.// ww w . ja v a 2 s.c om * * @param k number of test case to replay. * @param randomized <code>true</code> if replay in a random order */ public void replayTopTests(int k, boolean randomized) { System.out.println("==========================="); System.out.println("START REPLAYING...."); System.out.println("==========================="); File testcaseDir = new File(testCaseDir); File[] testcases = testcaseDir.listFiles(); if (randomized) { Collections.shuffle(Arrays.asList(testcases)); } for (int i = 0; i < k && i < testcases.length; i++) { File testcase = testcases[i]; String testcasePath = testcase.getAbsolutePath(); replaySingleTestCase(testcasePath); } System.out.println("==========================="); System.out.println("DONE REPLAYING!!!"); System.out.println("==========================="); }
From source file:edu.txstate.dmlab.clusteringwiki.web.RegisterController.java
@RequestMapping("captcha.*") public void getCaptcha(HttpServletRequest request, HttpServletResponse response, Model model) { //prepare vars HttpSession session = request.getSession(); String action = request.getParameter("action"); if (action == null) { sendOutput(response, "Error: invalid action received."); return;//w ww. j a va 2s .c om } if (action.equals("verify")) { String captcha = request.getParameter("captcha"); String answer = (String) session.getAttribute("captchaAnswer"); if (captcha == null || captcha.length() < 10 || answer == null) { sendOutput(response, "Error: invalid verify request received."); return; } if (captcha.substring(10).equals(answer)) { sendOutput(response, "{\"status\":\"success\"}"); return; } else { sendOutput(response, "{\"status\":\"error\"}"); return; } } // tops: star: 120, heart: 0; bwm: 56; diamond: 185 List<Integer> topPositions = new ArrayList<Integer>(4); topPositions.add(120); topPositions.add(0); topPositions.add(56); topPositions.add(185); //randomize images Collections.shuffle(topPositions); //generate new codes Random r = new Random(); List<String> codes = new ArrayList<String>(4); codes.add(Long.toString(Math.abs(r.nextLong()), 36)); codes.add(Long.toString(Math.abs(r.nextLong()), 36)); codes.add(Long.toString(Math.abs(r.nextLong()), 36)); codes.add(Long.toString(Math.abs(r.nextLong()), 36)); //pick a random item to check against - between 0 and 4 int chosen = r.nextInt(4); //create the html code String template = "<div class=\"captchaWrapper\" id=\"captchaWrapper\">" + " <a href=\"#\" class=\"captchaRefresh\"></a>" + " <div id=\"draggable_{c0}\" class=\"draggable\" " + " style=\"left: 15px; background-position: -{t0}px -3px\"></div>" + " <a href=\"#\" class=\"captchaRefresh\"></a>" + " <div id=\"draggable_{c1}\" class=\"draggable\" " + " style=\"left: 83px; background-position: -{t1}px -3px;\"></div>" + " <a href=\"#\" class=\"captchaRefresh\"></a>" + " <div id=\"draggable_{c2}\" class=\"draggable\" " + " style=\"left: 151px; background-position: -{t2}px -3px;\"></div>" + " <a href=\"#\" class=\"captchaRefresh\"></a>" + " <div id=\"draggable_{c3}\" class=\"draggable\" " + " style=\"left: 219px; background-position: -{t3}px -3px;\"></div>" + " <div class=\"targetWrapper\">" + " <div class=\"target\" style=\"background-position: -{t4}px -66px;\"></div>" + " </div>" + " <input type=\"hidden\" class=\"captchaAnswer\" name=\"captcha\" value=\"\" />" + "</div>"; template = template.replace("{c0}", codes.get(0)).replace("{c1}", codes.get(1)) .replace("{c2}", codes.get(2)).replace("{c3}", codes.get(3)) .replace("{t0}", String.valueOf(topPositions.get(0))) .replace("{t1}", String.valueOf(topPositions.get(1))) .replace("{t2}", String.valueOf(topPositions.get(2))) .replace("{t3}", String.valueOf(topPositions.get(3))); // the chosen image template = template.replace("{t4}", String.valueOf(topPositions.get(chosen))); //store the chosen code in the session session.setAttribute("captchaAnswer", codes.get(chosen)); //display captcha sendOutput(response, template); }
From source file:com.gs.collections.impl.parallel.SerialParallelPerformanceTest.java
private MutableList<Function0<Iterable<Integer>>> getIntegerListGenerators(int count) { Interval interval = Interval.fromTo(-(count / 2), count / 2 - 1); MutableList<Function0<Iterable<Integer>>> generators = FastList.newList(); generators.add(() -> {//from www. j a v a 2s. c o m MutableList<Integer> integers = interval.toList(); Collections.shuffle(integers); return integers; }); generators.add(() -> { MutableList<Integer> integers = interval.toList(); Collections.shuffle(integers); return integers.toImmutable(); }); generators.add(interval::toSet); Collections.shuffle(generators); return generators; }
From source file:com.digitalpebble.stormcrawler.elasticsearch.persistence.CollapsingSpout.java
@Override public void onResponse(SearchResponse response) { long timeTaken = System.currentTimeMillis() - timeStartESQuery; SearchHit[] hits = response.getHits().getHits(); int numBuckets = hits.length; // no more results? if (numBuckets == 0) { lastDate = null;/*from w w w.j a v a2 s .co m*/ lastStartOffset = 0; } // still got some results but paging won't help else if (numBuckets < maxBucketNum) { lastStartOffset = 0; } else { lastStartOffset += numBuckets; } // reset the value for next fetch date if the previous one is too old if (resetFetchDateAfterNSecs != -1) { Calendar diffCal = Calendar.getInstance(); diffCal.setTime(lastDate); diffCal.add(Calendar.SECOND, resetFetchDateAfterNSecs); // compare to now if (diffCal.before(Calendar.getInstance())) { LOG.info("{} lastDate set to null based on resetFetchDateAfterNSecs {}", logIdprefix, resetFetchDateAfterNSecs); lastDate = null; lastStartOffset = 0; } } int alreadyprocessed = 0; int numDocs = 0; synchronized (buffer) { for (SearchHit hit : hits) { Map<String, SearchHits> innerHits = hit.getInnerHits(); // wanted just one per bucket : no inner hits if (innerHits == null) { numDocs++; if (!addHitToBuffer(hit)) { alreadyprocessed++; } continue; } // more than one per bucket SearchHits inMyBucket = innerHits.get("urls_per_bucket"); for (SearchHit subHit : inMyBucket.hits()) { numDocs++; if (!addHitToBuffer(subHit)) { alreadyprocessed++; } } } // Shuffle the URLs so that we don't get blocks of URLs from the // same host or domain if (numBuckets != numDocs) { Collections.shuffle((List) buffer); } } esQueryTimes.addMeasurement(timeTaken); // could be derived from the count of query times above eventCounter.scope("ES_queries").incrBy(1); eventCounter.scope("ES_docs").incrBy(numDocs); eventCounter.scope("already_being_processed").incrBy(alreadyprocessed); LOG.info("{} ES query returned {} hits from {} buckets in {} msec with {} already being processed", logIdprefix, numDocs, numBuckets, timeTaken, alreadyprocessed); // remove lock isInESQuery.set(false); }
From source file:org.flite.cach3.test.UpdateMultiCacheTest.java
@Test public void testVelocity() { final String original = RandomStringUtils.randomAlphanumeric(7); final Long second = Long.valueOf("1337" + RandomStringUtils.randomNumeric(5)); final List<Long> firsts = new ArrayList<Long>(); final List<String> baseIds = new ArrayList<String>(); final long base = RandomUtils.nextInt(2000) + 1000; for (int ix = 0; ix < 3; ix++) { final Long val = base + ix; firsts.add(val); baseIds.add(val + "&&" + second); }//from w w w . ja va 2 s . c om final Long extra = base + 10; final String extraString = original + extra.toString(); final TestSvc test = (TestSvc) context.getBean("testSvc"); final StubUpdateMultiCacheListenerImpl listener = (StubUpdateMultiCacheListenerImpl) context .getBean("stubUM"); final int previous = listener.getTriggers().size(); final List<String> results = test.updateCompoundStrings(second, original, firsts); // Testing that the listener got invoked as required. assertTrue("Doesn't look like the listener got called.", listener.getTriggers().size() == previous + 1); final String expected = StubUpdateMultiCacheListenerImpl.formatTriggers(TestDAOImpl.COMPOUND_NAMESPACE, TestDAOImpl.COMPOUND_PREFIX, baseIds, (List<Object>) (List) results, // Using Erasure to satisfy the compiler. YUCK! results, new Object[] { second, original, firsts }); assertEquals(expected, listener.getTriggers().get(listener.getTriggers().size() - 1)); // This part just double-checks the sublist aspect of the ReadThroughMultiCache firsts.add(extra); Collections.shuffle(firsts); final List<String> r2 = test.getCompoundStrings(firsts, extraString, second); for (int ix = 0; ix < firsts.size(); ix++) { final Long value = firsts.get(ix); assertEquals(value.equals(extra) ? extraString : original, r2.get(ix)); } }
From source file:android.math.practice.VideoDetailsFragment.java
private void setupMovieListRow() { String subcategories[] = { getString(R.string.related_movies) }; List<Movie> list = MovieList.list; Collections.shuffle(list); ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(new CardPresenter()); for (int j = 0; j < NUM_COLS; j++) { listRowAdapter.add(list.get(j % 5)); }// w w w . java 2s . c om HeaderItem header = new HeaderItem(0, subcategories[0]); mAdapter.add(new ListRow(header, listRowAdapter)); }