Example usage for java.util Collections shuffle

List of usage examples for java.util Collections shuffle

Introduction

In this page you can find the example usage for java.util Collections shuffle.

Prototype

public static void shuffle(List<?> list) 

Source Link

Document

Randomly permutes the specified list using a default source of randomness.

Usage

From source file:br.com.autonomiccs.autonomic.plugin.common.services.AutonomiccsSystemVmDeploymentService.java

/**
 * This method will try to find a host in the given {@link HostPodVO} to deploy an Autonomiccs system vm.
 * The search steps are the following://  www .  j  a  va  2 s . c om
 *  <ul>
 *      <li>We load all enabled clusters, then we randomize the list;
 *      <li>then, try to look for a host using method {@link #searchForRandomHostInClusterToDeployAutonomiccsSystemVm(ClusterVO)}
 *  </ul>
 * @param pod - the Pod in which we will try to look for a host to deploy a system VM
 * @return {@link HostVO} that is going to be used to deploy a system VM. It may be returned a null value, which indicates that we did not find a suitable host to deploy the system VM in the given pod
 */
public HostVO searchForRandomHostInPodToDeployAutonomiccsSystemVm(HostPodVO pod) {
    List<ClusterVO> allClustersFromPod = clusterService.listAllClustersFromPod(pod.getId());
    Collections.shuffle(allClustersFromPod);
    for (ClusterVO c : allClustersFromPod) {
        HostVO host = searchForRandomHostInClusterToDeployAutonomiccsSystemVm(c);
        if (host != null) {
            return host;
        }
    }
    logger.info(String.format(
            "Could not find any suitable hosts to deploy the system VM into pod [podId=%d, podName=%s]",
            pod.getId(), pod.getName()));
    return null;
}

From source file:org.berlin.crawl.parse.WebParser.java

public List<BotLink> parse(final BotLink origLink, final URIBuilder lastBuilder, final String document) {
    final SessionFactory sf = (SessionFactory) ctx.getBean("sessionFactory");
    final Session session = sf.openSession();
    try {/*from   www . j av a2  s.c om*/
        final InputStream input = new ByteArrayInputStream(document.getBytes());
        final LinkContentHandler linkHandler = new LinkContentHandler();
        final ContentHandler textHandler = new BodyContentHandler();
        final ToHTMLContentHandler toHTMLHandler = new ToHTMLContentHandler();
        final TeeContentHandler teeHandler = new TeeContentHandler(linkHandler, textHandler, toHTMLHandler);
        final Metadata metadata = new Metadata();
        final ParseContext parseContext = new ParseContext();
        final HtmlParser parser = new HtmlParser();
        parser.parse(input, teeHandler, metadata, parseContext);

        final String titleOfPage = metadata.get("title");
        // For analytical data, ignore pages that don't have titles
        if (!NullRef.hasValue(titleOfPage)) {
            logger.warn("Warning, invalid title for page, EXITING logic, link=" + origLink);
            return null;
        }

        // Continue with parsing //
        final List<BotLink> linksForProcessing = new ArrayList<BotLink>();
        final Set<String> urls = new HashSet<String>();

        int fullLinkCount = 0;
        for (final Link link : linkHandler.getLinks()) {
            fullLinkCount++;
        }
        int linkcount = 0;
        // Loop through the links on the page
        // And add a set number to the queue.
        final Random rchk = new Random(System.currentTimeMillis());
        final List<Link> linksFromPage = linkHandler.getLinks();
        Collections.shuffle(linksFromPage);
        for (final Link link : linksFromPage) {
            // Add a 30% chance of adding this link
            final double rval = rchk.nextDouble();
            final boolean okToAdd = rval > 0.65;
            if (okToAdd && link.getUri() != null) {
                linkcount++;
                if (linkcount > MAX_LINKS_PAGE) {
                    // Only process a given number of links on a page //
                    break;
                } // End of if max reached
                final String fullURL = this.fullURL(link, lastBuilder, urls);
                if (fullURL != null) {
                    try {
                        this.processFullURL(linksForProcessing, link, fullURL);
                    } catch (final Throwable te) {
                        te.printStackTrace();
                    }
                }
            } // End of the if //             
        } // End of the for through the links //

        // Parse the available URLS //
        logger.info("In Web Parser for " + lastBuilder + " # availableNumberOfLinks=" + urls.size()
                + " fullLinkCount=" + fullLinkCount);

        // Persist the current link // 
        origLink.setNumberLinks(fullLinkCount);
        this.writeFileAndSave(origLink, session, metadata, document, textHandler.toString());

        processLinksForQueue(linksForProcessing);
        return linksForProcessing;

    } catch (final Throwable e) {
        e.printStackTrace();
    } finally {
        if (session != null) {
            session.close();
        }
    } // End of the try - catch //
    return null;
}

From source file:ml.shifu.shifu.core.dvarsel.wrapper.CandidateGenerator.java

private CandidateSeed hybrid(CandidateSeed father, CandidateSeed mather) {
    Set<Integer> geneSet = new HashSet<Integer>();
    geneSet.addAll(father.getColumnIdList());
    geneSet.addAll(mather.getColumnIdList());

    List<Integer> wholeGeneList = new ArrayList<Integer>(geneSet);

    List<Integer> indexList = new ArrayList<Integer>(wholeGeneList.size());
    for (int i = 0; i < wholeGeneList.size(); i++) {
        indexList.add(i);/*from   w  w  w  .ja v a2  s  .com*/
    }
    Collections.shuffle(indexList);

    List<Integer> childGeneList = new ArrayList<Integer>(father.getColumnIdList().size());
    for (int i = 0; i < father.getColumnIdList().size(); i++) {
        childGeneList.add(wholeGeneList.get(indexList.get(i)));
    }

    return new CandidateSeed(this.genSeedId(), childGeneList);
}

From source file:com.gs.collections.impl.parallel.SerialParallelPerformanceTest.java

private MutableList<Function0<Iterable<String>>> getRandomWordsGenerators(int count) {
    MutableList<Function0<Iterable<String>>> generators = FastList.newList();
    generators.add(() -> this.generateWordsList(count));
    generators.add(() -> this.generateWordsList(count).toImmutable());
    generators.add(() -> this.generateWordsSet(count));
    Collections.shuffle(generators);
    return generators;
}

From source file:de.tudarmstadt.ukp.dkpro.spelling.experiments.artificialerrors.SpellingErrorAdder.java

private void addErrors(JCas jcas, FeaturePathInfo fp, List<AnnotationFS> annotations, int nrOfErrors) {

    // shuffle to avoid always adding error in first position
    Collections.shuffle(annotations);

    int addedErrors = 0;
    for (AnnotationFS a : annotations) {
        String term = fp.getValue(a);
        if (addedErrors < nrOfErrors) {
            if (addCandidate(jcas, a, term)) {
                nrOfItemsAdded++;/*w  w w  .jav  a 2  s.c o  m*/
                addedErrors++;
            }
        }
    }
}

From source file:jp.ikedam.jenkins.plugins.scoringloadbalancer.ScoringLoadBalancer.java

/**
 * sort {@link ExecutorChunk}s (that is, nodes) by scores.
 * /* ww w.  j  a  v  a  2  s.c  o m*/
 * @param executors
 * @param nodesScore
 */
protected void sortExecutors(List<ExecutorChunk> executors, NodesScore nodesScore) {
    Collections.shuffle(executors);
    Collections.sort(executors, nodesScore.new ExecutorComparator());
}

From source file:edu.pitt.csb.stability.StabilityUtils.java

private static int[] subSampleIndices(int N, int subSize) {
    List<Integer> indices = new ArrayList<Integer>(N);
    for (int i = 0; i < N; i++) {
        indices.add(i);//  w w w .ja v a 2s .  c  om
    }

    Collections.shuffle(indices);
    int[] samp = new int[subSize];
    for (int i = 0; i < subSize; i++) {
        samp[i] = indices.get(i);
    }
    return samp;
}

From source file:com.netflix.discovery.shared.Application.java

private void _shuffleAndStoreInstances(boolean filterUpInstances, boolean indexByRemoteRegions,
        @Nullable Map<String, Applications> remoteRegionsRegistry, @Nullable EurekaClientConfig clientConfig,
        @Nullable InstanceRegionChecker instanceRegionChecker) {
    List<InstanceInfo> instanceInfoList;
    synchronized (instances) {
        instanceInfoList = new ArrayList<InstanceInfo>(instances);
    }//from ww  w.java 2s.  co m
    if (indexByRemoteRegions || filterUpInstances) {
        Iterator<InstanceInfo> it = instanceInfoList.iterator();
        while (it.hasNext()) {
            InstanceInfo instanceInfo = it.next();
            if (filterUpInstances && !InstanceStatus.UP.equals(instanceInfo.getStatus())) {
                it.remove();
            } else if (indexByRemoteRegions && null != instanceRegionChecker && null != clientConfig
                    && null != remoteRegionsRegistry) {
                String instanceRegion = instanceRegionChecker.getInstanceRegion(instanceInfo);
                if (!instanceRegionChecker.isLocalRegion(instanceRegion)) {
                    Applications appsForRemoteRegion = remoteRegionsRegistry.get(instanceRegion);
                    if (null == appsForRemoteRegion) {
                        appsForRemoteRegion = new Applications();
                        remoteRegionsRegistry.put(instanceRegion, appsForRemoteRegion);
                    }

                    Application remoteApp = appsForRemoteRegion
                            .getRegisteredApplications(instanceInfo.getAppName());
                    if (null == remoteApp) {
                        remoteApp = new Application(instanceInfo.getAppName());
                        appsForRemoteRegion.addApplication(remoteApp);
                    }

                    remoteApp.addInstance(instanceInfo);
                    this.removeInstance(instanceInfo, false);
                    it.remove();
                }
            }
        }

    }
    Collections.shuffle(instanceInfoList);
    this.shuffledInstances.set(instanceInfoList);
}

From source file:com.graphaware.neo4j.webexpo.database.DataGenerator.java

private void doGenerateAttendanceAtTheEnd() {
    List<String> saturdayTalks = findTalksOnDay("Saturday");

    for (String attendee : findAllAttendees()) {
        Collections.shuffle(saturdayTalks);
        for (int i = 0; i < ATTENDED_TALKS_PER_DAY; i++) {
            TalkEvaluation evaluation = randomEvaluation();
            System.out.println(attendee + " evaluating " + saturdayTalks.get(i) + " as " + evaluation);
            attendeeService.evaluateTalk(attendee, saturdayTalks.get(i), evaluation);
        }/*from   ww  w . j av a  2 s .  c  o m*/
    }
}

From source file:outfox.dict.contest.service.CrontabService.java

public void updateInfoInCache() {
    LOG.info("updateInfo in cache Start...");

    HttpResponse response = null;//from ww  w  .jav  a2  s  .c om
    try {
        response = HttpToolKit.getInstance().doGet(ContestConsts.LIST_VOTE_INTERFACE);
        if (response != null) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                JSONObject jsonObj = JSON.parseObject(EntityUtils.toString(entity));
                // ?json?
                if (jsonObj != null) {
                    JSONArray dataArray = jsonObj.getJSONArray("data");
                    if (dataArray != null) {
                        JSONObject dataObj = dataArray.getJSONObject(0);
                        if (dataObj != null) {
                            // ??
                            JSONObject voteinfo = dataObj.getJSONObject("voteinfo");

                            // ??
                            long startTime = 0, endTime = 0;
                            if (voteinfo != null) {
                                startTime = voteinfo.getLong("startTime");
                                endTime = voteinfo.getLong("endTime");
                            }

                            // ???
                            JSONArray optionArray = dataObj.getJSONArray("options");

                            // options???
                            if (optionArray != null) {
                                Object[] objArray = optionArray.toArray();
                                List<Map<String, String>> optionList = new ArrayList<Map<String, String>>();
                                Multimap<String, BaseEntity> rankMap = ArrayListMultimap.create();

                                for (Object obj : objArray) {
                                    JSONObject option = JSON.parseObject(obj.toString());
                                    SingerEntity singer = new SingerEntity();
                                    int optionId = option.getIntValue("id");
                                    int voteNum = option.getIntValue("voteNum");
                                    singer.setOptionId(optionId);
                                    singer.setPhotoUrl(option.getString("picture"));
                                    singer.setVoteNum(voteNum);
                                    singer.setStartTime(startTime);
                                    singer.setEndTime(endTime);
                                    String content = option.getString("content");
                                    String areaName = null;
                                    int state = 0;
                                    if (StringUtils.isNotBlank(content)) {
                                        JSONObject contentObj = JSON.parseObject(content);
                                        singer.setId(contentObj.getIntValue("id"));
                                        singer.setName(contentObj.getString("name"));
                                        singer.setSchool(contentObj.getString("school"));
                                        areaName = contentObj.getString("areaName");
                                        singer.setAreaName(areaName);
                                        singer.setAudioUrl(contentObj.getString("audioUrl"));
                                        singer.setMusicName(contentObj.getString("musicName"));
                                        state = contentObj.getIntValue("state");
                                        singer.setState(state);
                                    }

                                    /** 1: ?mapkey?+optionid+statevalue? **/
                                    singerInfoMap.put(ContestConsts.SINGER_INFO_PREFIX_KEY + optionId,
                                            JSON.toJSONString(singer));

                                    /** 2: ???mapid??? **/
                                    // 2.1: ??
                                    rankMap.put(ContestConsts.RANK_PREFIX_KEY + areaName + ":" + state,
                                            new BaseEntity(optionId, voteNum));

                                    // 2.2: ??
                                    rankMap.put(ContestConsts.RANK_PREFIX_KEY + state,
                                            new BaseEntity(optionId, voteNum));

                                    /** 3: ?mapid??? **/
                                    // 3.1: ?idmap
                                    Map<String, String> map = new HashMap<String, String>();
                                    map.put("areaName", areaName);
                                    map.put("optionId", String.valueOf(optionId));
                                    map.put("state", String.valueOf(state));
                                    optionList.add(map);
                                }

                                // 3.2: ??
                                Collections.shuffle(optionList);

                                // 3.3: ??map
                                Multimap<String, Integer> randomMap = ArrayListMultimap.create();
                                for (Map<String, String> map : optionList) {
                                    int optionId = Integer.parseInt(map.get("optionId"));
                                    int state = Integer.parseInt(map.get("state"));
                                    String areaName = map.get("areaName");
                                    // 3.3.1 ?
                                    randomMap.put(ContestConsts.RANDOM_SHOWN_PREFIX_KEY + state, optionId);

                                    // 3.3.2 ??
                                    randomMap.put(
                                            ContestConsts.RANDOM_SHOWN_PREFIX_KEY + areaName + ":" + state,
                                            optionId);
                                }
                                singersRandomMap = randomMap;

                                /** 4???????? **/
                                // 4.1: ????
                                for (int state = 0; state <= 1; state++) {
                                    String key = ContestConsts.RANK_PREFIX_KEY + state;
                                    List<BaseEntity> globalRankList = (List<BaseEntity>) rankMap.get(key);
                                    Collections.sort(globalRankList, voteNumComparator);
                                    singersRankMap.put(key, globalRankList);
                                }

                                // 4.2: ??????100?????
                                List<AreaEntity> areaList = contestDAO.listContestAreas(ContestConsts.PERIOD);
                                if (areaList != null) {
                                    for (AreaEntity area : areaList) {
                                        // 4.2.1: ????
                                        String key = ContestConsts.RANK_PREFIX_KEY + area.getName() + ":0";
                                        List<BaseEntity> areaRankList = (List<BaseEntity>) rankMap.get(key);
                                        Collections.sort(areaRankList, voteNumComparator);
                                        singersRankMap.put(key, areaRankList);

                                        // 4.2.2: ?12???????12??1413??
                                        if (areaRankList != null) {
                                            int rank = 0, lastVoteNum = -1, index = 1;
                                            for (BaseEntity ele : areaRankList) {
                                                String singerStr = singerInfoMap.get(
                                                        ContestConsts.SINGER_INFO_PREFIX_KEY + ele.getId());
                                                if (singerStr != null) {
                                                    SingerEntity singer = JSON.parseObject(singerStr,
                                                            SingerEntity.class);
                                                    if (lastVoteNum != singer.getVoteNum()) {
                                                        rank++;
                                                    }
                                                    singer.setRanking(rank);
                                                    singer.setStartTime(area.getVoteStartTime());
                                                    singer.setEndTime(area.getVoteEndTime());
                                                    singerInfoMap.put(
                                                            ContestConsts.SINGER_INFO_PREFIX_KEY + ele.getId(),
                                                            JSON.toJSONString(singer));
                                                    index++;
                                                    lastVoteNum = singer.getVoteNum();
                                                    // ?12????
                                                    if (index > ContestConsts.RANK_NUM) {
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        LOG.error("CrontabService.singerInfoUpdate error...", e);
    } finally {
        HttpToolKit.closeQuiet(response);
    }
    LOG.info("updateInfo in cache End...");
}