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:edu.cmu.tetrad.data.DataUtils.java

public static DataSet reorderColumns(DataSet dataModel) {
    List<Node> vars = new ArrayList<Node>();

    List<Node> variables = dataModel.getVariables();
    Collections.shuffle(variables);

    for (Node node : variables) {
        Node _node = dataModel.getVariable(node.getName());

        if (_node != null) {
            vars.add(_node);/*from   w  w  w.  j ava 2  s.c o  m*/
        }
    }

    return dataModel.subsetColumns(vars);
}

From source file:com.yahoo.pulsar.broker.loadbalance.impl.SimpleLoadManagerImpl.java

private Map<Long, Set<ResourceUnit>> getAvailableBrokers(ServiceUnitId serviceUnitId) throws Exception {
    Map<Long, Set<ResourceUnit>> availableBrokers = sortedRankings.get();

    // Normal case: we are the leader and we do have load reports information available

    if (availableBrokers.isEmpty()) {
        // Create a map with all available brokers with no load information
        Set<String> activeBrokers = availableActiveBrokers.get(LOADBALANCE_BROKERS_ROOT);
        List<String> brokersToShuffle = new ArrayList<>(activeBrokers);
        Collections.shuffle(brokersToShuffle);
        activeBrokers = new HashSet<>(brokersToShuffle);

        availableBrokers = Maps.newTreeMap();
        for (String broker : activeBrokers) {
            ResourceUnit resourceUnit = new SimpleResourceUnit(String.format("http://%s", broker),
                    new PulsarResourceDescription());
            availableBrokers.computeIfAbsent(0L, key -> Sets.newTreeSet()).add(resourceUnit);
        }/*from  w  w w.  j  a  va  2  s  .co m*/
        log.info("Choosing at random from broker list: [{}]", availableBrokers.values());
    }
    return availableBrokers;
}

From source file:edu.cmu.tetrad.data.DataUtils.java

public static List<DataSet> reorderColumns(List<DataSet> dataSets) {
    List<Node> vars = new ArrayList<Node>();

    List<Node> variables = dataSets.get(0).getVariables();
    Collections.shuffle(variables);

    for (Node node : variables) {
        Node _node = dataSets.get(0).getVariable(node.getName());

        if (_node != null) {
            vars.add(_node);//from w w  w.  ja  va2 s  .  co  m
        }
    }

    List<DataSet> ret = new ArrayList<DataSet>();

    for (DataSet m : dataSets) {
        ret.add(m.subsetColumns(vars));
    }

    return ret;
}

From source file:edu.cmu.tetrad.data.DataUtils.java

public static ICovarianceMatrix reorderColumns(ICovarianceMatrix cov) {
    List<String> vars = new ArrayList<String>();

    List<Node> variables = new ArrayList<Node>(cov.getVariables());
    Collections.shuffle(variables);

    for (Node node : variables) {
        Node _node = cov.getVariable(node.getName());

        if (_node != null) {
            vars.add(_node.getName());//  ww  w .j a  v  a 2s .c om
        }
    }

    return cov.getSubmatrix(vars);
}

From source file:com.cloud.storage.StorageManagerImpl.java

@Override
public Pair<Long, Answer[]> sendToPool(StoragePool pool, long[] hostIdsToTryFirst, List<Long> hostIdsToAvoid,
        Commands cmds) throws StorageUnavailableException {
    List<Long> hostIds = getUpHostsInPool(pool.getId());
    Collections.shuffle(hostIds);
    if (hostIdsToTryFirst != null) {
        for (int i = hostIdsToTryFirst.length - 1; i >= 0; i--) {
            if (hostIds.remove(hostIdsToTryFirst[i])) {
                hostIds.add(0, hostIdsToTryFirst[i]);
            }/*from   w w  w .  j  av  a2s. c o m*/
        }
    }

    if (hostIdsToAvoid != null) {
        hostIds.removeAll(hostIdsToAvoid);
    }
    if (hostIds == null || hostIds.isEmpty()) {
        throw new StorageUnavailableException("Unable to send command to the pool " + pool.getId()
                + " due to there is no enabled hosts up in this cluster", pool.getId());
    }
    for (Long hostId : hostIds) {
        try {
            List<Answer> answers = new ArrayList<Answer>();
            Command[] cmdArray = cmds.toCommands();
            for (Command cmd : cmdArray) {
                long targetHostId = _hvGuruMgr.getGuruProcessedCommandTargetHost(hostId, cmd);
                answers.add(_agentMgr.send(targetHostId, cmd));
            }
            return new Pair<Long, Answer[]>(hostId, answers.toArray(new Answer[answers.size()]));
        } catch (AgentUnavailableException e) {
            s_logger.debug("Unable to send storage pool command to " + pool + " via " + hostId, e);
        } catch (OperationTimedoutException e) {
            s_logger.debug("Unable to send storage pool command to " + pool + " via " + hostId, e);
        }
    }

    throw new StorageUnavailableException("Unable to send command to the pool ", pool.getId());
}

From source file:com.devicehive.service.UserServiceTest.java

@Test
@DirtiesContext(methodMode = DirtiesContext.MethodMode.BEFORE_METHOD)
public void should_return_list_of_users_sorted() throws Exception {
    String suffix = RandomStringUtils.randomAlphabetic(5);
    List<String> prefixes = Arrays.asList("a", "b", "c", "d", "e");
    Collections.shuffle(prefixes);
    for (String prefix : prefixes) {
        UserVO user = new UserVO();
        user.setLogin(prefix + "_" + suffix);
        user.setStatus(UserStatus.ACTIVE);
        userService.createUser(user, RandomStringUtils.randomAlphabetic(10));
    }//from  w  ww  . j  a v a 2s.  c om
    handleListUserRequest();
    userService.list(null, "%" + suffix, null, null, "login", true, 100, 0).thenAccept(users -> {
        assertThat(users, not(empty()));
        assertThat(users, hasSize(5));

        assertThat(users.get(0).getLogin(), startsWith("a"));
        assertThat(users.get(1).getLogin(), startsWith("b"));
        assertThat(users.get(2).getLogin(), startsWith("c"));
        assertThat(users.get(3).getLogin(), startsWith("d"));
        assertThat(users.get(4).getLogin(), startsWith("e"));
    }).get(15, TimeUnit.SECONDS);

    userService.list(null, "%" + suffix, null, null, "login", false, 100, 0).thenAccept(users -> {
        assertThat(users, not(empty()));
        assertThat(users, hasSize(5));

        assertThat(users.get(0).getLogin(), startsWith("e"));
        assertThat(users.get(1).getLogin(), startsWith("d"));
        assertThat(users.get(2).getLogin(), startsWith("c"));
        assertThat(users.get(3).getLogin(), startsWith("b"));
        assertThat(users.get(4).getLogin(), startsWith("a"));
    }).get(15, TimeUnit.SECONDS);

    verify(requestHandler, times(2)).handle(argument.capture());
}

From source file:com.cloud.network.vpc.NetworkACLServiceImplTest.java

@Test
public void getAllAclRulesSortedByNumberTest() {
    List<NetworkACLItemVO> networkAclItemVos = new ArrayList<>();

    NetworkACLItemVO networkACLItemVO1 = new NetworkACLItemVO();
    networkACLItemVO1.setNumber(1);/*from   w  w  w. j ava2 s  . c  o  m*/

    NetworkACLItemVO networkACLItemVO2 = new NetworkACLItemVO();
    networkACLItemVO2.setNumber(2);

    NetworkACLItemVO networkACLItemVO3 = new NetworkACLItemVO();
    networkACLItemVO3.setNumber(3);

    NetworkACLItemVO networkACLItemVO4 = new NetworkACLItemVO();
    networkACLItemVO4.setNumber(4);

    networkAclItemVos.add(networkACLItemVO1);
    networkAclItemVos.add(networkACLItemVO2);
    networkAclItemVos.add(networkACLItemVO3);
    networkAclItemVos.add(networkACLItemVO4);

    Collections.shuffle(networkAclItemVos);

    Mockito.doReturn(networkAclItemVos).when(networkAclItemDaoMock).listByACL(networkAclMockId);

    List<NetworkACLItemVO> allAclRulesSortedByNumber = networkAclServiceImpl
            .getAllAclRulesSortedByNumber(networkAclMockId);

    Assert.assertEquals(networkAclItemVos.size(), allAclRulesSortedByNumber.size());
    Assert.assertEquals(networkACLItemVO1, networkAclItemVos.get(0));
    Assert.assertEquals(networkACLItemVO2, networkAclItemVos.get(1));
    Assert.assertEquals(networkACLItemVO3, networkAclItemVos.get(2));
    Assert.assertEquals(networkACLItemVO4, networkAclItemVos.get(3));

}

From source file:mzb.Balancer.java

/**
 * Balance all namenodes./*from ww w.  j  ava2 s .  com*/
 * For each iteration,
 * for each namenode,
 * execute a {@link Balancer} to work through all datanodes once.  
 */
static int run(Collection<URI> namenodes, Configuration conf) throws IOException, InterruptedException {
    final long sleeptime = 2000 * conf.getLong(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY,
            DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_DEFAULT);
    LOG.info("namenodes = " + namenodes);
    //    LOG.info("p         = " + p);

    final Formatter formatter = new Formatter(System.out);
    System.out.println(
            "Time Stamp               Iteration#  Bytes Already Moved  Bytes Left To Move  Bytes Being Moved");

    final List<NameNodeConnector> connectors = new ArrayList<NameNodeConnector>(namenodes.size());
    try {
        for (URI uri : namenodes) {
            connectors.add(new NameNodeConnector(uri, conf));
        }

        boolean done = false;
        for (int iteration = 0; !done; iteration++) {
            done = true;
            Collections.shuffle(connectors);
            for (NameNodeConnector nnc : connectors) {
                final Balancer b = new Balancer(nnc, conf);
                final ReturnStatus r = b.run(iteration, formatter, conf);
                // clean all lists
                b.resetData(conf);
                if (r == ReturnStatus.IN_PROGRESS) {
                    done = false;
                } else if (r != ReturnStatus.SUCCESS) {
                    //must be an error statue, return.
                    return r.code;
                }
            }

            if (!done) {
                Thread.sleep(sleeptime);
            }
        }
    } finally {
        for (NameNodeConnector nnc : connectors) {
            nnc.close();
        }
    }
    return ReturnStatus.SUCCESS.code;
}

From source file:com.cloud.resource.ResourceManagerImpl.java

@Override
public HypervisorType getAvailableHypervisor(final long zoneId) {
    HypervisorType defaultHype = getDefaultHypervisor(zoneId);
    if (defaultHype == HypervisorType.None) {
        final List<HypervisorType> supportedHypes = getSupportedHypervisorTypes(zoneId, false, null);
        if (supportedHypes.size() > 0) {
            Collections.shuffle(supportedHypes);
            defaultHype = supportedHypes.get(0);
        }/*from  w ww  .j av a  2  s. com*/
    }

    if (defaultHype == HypervisorType.None) {
        defaultHype = HypervisorType.Any;
    }
    return defaultHype;
}

From source file:de.uhh.l2g.dao.VideoDao.java

/**
 * Gets the popular videos rnd./*from w ww.j  av a2 s  . c  om*/
 *
 * @param facilityId the facility id
 * @param limit the limit
 * @return the popular videos rnd
 */
@SuppressWarnings("unchecked")
public List<Video> getPopularVideosRnd(Integer facilityId, Integer limit) {

    List<Video> liste = new ArrayList<Video>();
    List<Video> returnList = new ArrayList<Video>();
    String sqlquery = "";
    JdbcTemplate jdbst = new JdbcTemplate(this.getDataSource());
    // ohne Facility
    if (facilityId == 0) {
        sqlquery = "SELECT v.id, v.title, m.creator, l.name, v.filename,  v.generationDate, f.typ, v.lectureseriesId, v.metadataId, v.hostId, v.producerId FROM videohitlist vh, video v, metadata m, lectureseries l, facility f WHERE (v.id = vh.id AND v.metadataId = m.id AND v.lectureseriesId = l.id AND v.facilityId=f.id) GROUP BY v.id";
        liste = jdbst.query(sqlquery, new VideoResultSearchRowMapper());
    }

    //Die Liste Randomisieren
    Collections.shuffle(liste);

    // Die ersten i-Rauspicken (je nachdem wie viele Angezeigt werden sollen), Pruefung auf Listengroesse wichtig falls Liste < Anzeiggroesse
    for (int i = 0; i < limit && i < liste.size(); i++) {
        if (liste.get(i) != null)
            returnList.add(liste.get(i));
    }

    return returnList;
}