當前位置: 首頁>>代碼示例>>Java>>正文


Java RandomUtils.nextInt方法代碼示例

本文整理匯總了Java中org.apache.commons.lang.math.RandomUtils.nextInt方法的典型用法代碼示例。如果您正苦於以下問題:Java RandomUtils.nextInt方法的具體用法?Java RandomUtils.nextInt怎麽用?Java RandomUtils.nextInt使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在org.apache.commons.lang.math.RandomUtils的用法示例。


在下文中一共展示了RandomUtils.nextInt方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: main

import org.apache.commons.lang.math.RandomUtils; //導入方法依賴的package包/類
public static void main(String[] args) {
		byte[] data=new byte[1024*1024];
		for(int i=0;i<data.length;i++)
		{
			data[i]=(byte) RandomUtils.nextInt(255);
		}
		Test t=new Test();
		Scanner sc=new Scanner(System.in);
		sc.nextLine();
//		t.testtMap(data);
//		sc.nextLine();
//		t.testMap(data);
//		sc.nextLine();
		t.testNMap(data);
		sc.nextLine();
	}
 
開發者ID:juebanlin,項目名稱:util4j,代碼行數:17,代碼來源:NodeMap4.java

示例2: run

import org.apache.commons.lang.math.RandomUtils; //導入方法依賴的package包/類
@Override
public void run() {
  // Add some jitter.
  int jitter = RandomUtils.nextInt((int) periodMs);
  LOG.info("Sleeping for " + jitter + " to add jitter");
  Threads.sleep(jitter);

  while (!isStopped()) {
    long start = System.currentTimeMillis();
    runOneIteration();

    if (isStopped()) return;
    long sleepTime = periodMs - (System.currentTimeMillis() - start);
    if (sleepTime > 0) {
      LOG.info("Sleeping for: " + sleepTime);
      Threads.sleep(sleepTime);
    }
  }
}
 
開發者ID:fengchen8086,項目名稱:ditb,代碼行數:20,代碼來源:PeriodicPolicy.java

示例3: chore

import org.apache.commons.lang.math.RandomUtils; //導入方法依賴的package包/類
@Override protected void chore() {
  final StringBuffer whyFlush = new StringBuffer();
  for (Region r : this.server.onlineRegions.values()) {
    if (r == null) continue;
    if (((HRegion) r).shouldFlush(whyFlush)) {
      FlushRequester requester = server.getFlushRequester();
      if (requester != null) {
        long randomDelay = RandomUtils.nextInt(RANGE_OF_DELAY) + MIN_DELAY_TIME;
        LOG.info(getName() + " requesting flush of " + r.getRegionInfo().getRegionNameAsString()
            + " because " + whyFlush.toString() + " after random delay " + randomDelay + "ms");
        //Throttle the flushes by putting a delay. If we don't throttle, and there
        //is a balanced write-load on the regions in a table, we might end up
        //overwhelming the filesystem with too many flushes at once.
        requester.requestDelayedFlush(r, randomDelay, false);
      }
    }
  }
}
 
開發者ID:fengchen8086,項目名稱:ditb,代碼行數:19,代碼來源:HRegionServer.java

示例4: testResetGlobalPermissionsForClientManager

import org.apache.commons.lang.math.RandomUtils; //導入方法依賴的package包/類
/**
 * Test for {@link BlogManagement#resetGlobalPermissions()} when a client manager calls the
 * method.
 *
 * @throws BlogAccessException
 * @throws BlogNotFoundException
 */
@Test
public void testResetGlobalPermissionsForClientManager() throws BlogNotFoundException,
BlogAccessException {
    User user = TestUtils.createRandomUser(true);
    List<Long> blogIds = new ArrayList<Long>();
    for (int i = 10 + RandomUtils.nextInt(10); i > 0; i--) {
        blogIds.add(TestUtils.createRandomBlog(i % 2 == 0, i % 2 == 1, user).getId());
    }
    AuthenticationTestUtils.setSecurityContext(user);
    blogManagement.resetGlobalPermissions();
    for (Long blogId : blogIds) {
        Blog blog = blogManagement.getBlogById(blogId, false);
        Assert.assertFalse(blog.isAllCanRead());
        Assert.assertFalse(blog.isAllCanWrite());
    }
}
 
開發者ID:Communote,項目名稱:communote-server,代碼行數:24,代碼來源:BlogManagementTest2.java

示例5: testGetNextScheduledTask

import org.apache.commons.lang.math.RandomUtils; //導入方法依賴的package包/類
/**
 * Tests for {@link TaskManagement#getNextScheduledTask()}.
 *
 * @throws Exception
 *             in case the test failed
 */
@Test
public void testGetNextScheduledTask() throws Exception {
    TaskTO task = taskManagement.getNextScheduledTask();
    Assert.assertNull(task);
    String uniqueTaskNamePrefix = UUID.randomUUID().toString() + "_getNext_";
    String uniqueTaskName = uniqueTaskNamePrefix + "single";
    taskManagement.addTask(UUID.randomUUID().toString(), true, 0L, new Date(5000000000L),
            new HashMap<String, String>(), TestTaskHandler.class);
    Assert.assertNotNull(taskManagement.getNextScheduledTask());
    Assert.assertNull(taskManagement.getNextScheduledTask(new Date(5000000000L)));
    for (int i = 10 + RandomUtils.nextInt(32); i > 0; i--) {
        uniqueTaskName = uniqueTaskNamePrefix + i;
        taskManagement.addTask(uniqueTaskName, true, 0L, new Date(10000000 * i),
                new HashMap<String, String>(), TestTaskHandler.class);
        task = taskManagement.getNextScheduledTask();
        Assert.assertNotNull(task);
        Assert.assertEquals(task.getUniqueName(), uniqueTaskName);
    }
}
 
開發者ID:Communote,項目名稱:communote-server,代碼行數:26,代碼來源:TaskManagementTest.java

示例6: loadByAliasForWebServices

import org.apache.commons.lang.math.RandomUtils; //導入方法依賴的package包/類
public InfoText loadByAliasForWebServices(String alias) {
    alias = StringUtils.trimToEmpty(alias);
    final InfoTextQuery query = new InfoTextQuery();
    query.setOnlyActive(true);
    query.setAlias(alias);
    final List<InfoText> result = infoTextDao.search(query);
    final int size = result.size();
    if (size == 0) {
        throw new EntityNotFoundException(InfoText.class);
    } else if (size == 1) {
        return result.get(0);
    } else { // size > 1
        final int index = RandomUtils.nextInt(result.size());
        return result.get(index);
    }
}
 
開發者ID:mateli,項目名稱:OpenCyclos,代碼行數:17,代碼來源:InfoTextServiceImpl.java

示例7: lessThanWriteRestraintTest

import org.apache.commons.lang.math.RandomUtils; //導入方法依賴的package包/類
@Test
public void lessThanWriteRestraintTest() throws InterruptedException {
    if (ASTATICISM_TEST) {
        return;
    }

    int executCount = 10;
    int writeCount = RandomUtils.nextInt(executCount);

    MockServer.setConfigInfo(TAtomConstants.getAppDataId(APPNAME, DBKEY_0),
        " maxPoolSize=100\r\nuserName=tddl\r\nminPoolSize=1\r\nwriteRestrictTimes=" + executCount + "\r\n");
    TimeUnit.SECONDS.sleep(SLEEP_TIME);

    String sql = "update normaltbl_0001 set gmt_create=? where pk=?";
    for (int i = 0; i < writeCount; i++) {
        try {
            int rs = tddlJT.update(sql, new Object[] { nextDay, RANDOM_ID });
            Assert.assertEquals(1, rs);
            executCount--;
        } catch (DataAccessException ex) {
        }
    }
    Assert.assertTrue(executCount >= 0);
}
 
開發者ID:beebeandwer,項目名稱:TDDL,代碼行數:25,代碼來源:AtomWriteRestraintTest.java

示例8: startServer

import org.apache.commons.lang.math.RandomUtils; //導入方法依賴的package包/類
@BeforeClass
public void startServer() throws Exception {
  int port = 49152 + RandomUtils.nextInt(65535 - 49152);
  String serverUrl = "http://localhost:" + port + "/jax";
  SelectChannelConnector connector = new SelectChannelConnector();
  connector.setPort(port);
  _jettyServer = new Server();
  _jettyServer.setConnectors(new Connector[]{connector});
  ContextHandlerCollection contexts = new ContextHandlerCollection();
  HandlerCollection handlers = new HandlerCollection();
  handlers.addHandler(contexts);
  WebAppContext ogWebAppContext = new WebAppContext("RemoteViewRunnerTest", "/");
  org.springframework.core.io.Resource resource = new ClassPathResource("web-engine");
  ogWebAppContext.setBaseResource(Resource.newResource(resource.getFile()));
  DataViewRunnerResource viewRunnerResource = new DataViewRunnerResource(new TestViewRunner());
  ComponentRepository repo = new ComponentRepository(ComponentLogger.Console.VERBOSE);
  repo.getRestComponents().publishResource(viewRunnerResource);
  repo.getRestComponents().publishHelper(new FudgeObjectBinaryConsumer());
  repo.getRestComponents().publishHelper(new FudgeObjectBinaryProducer());
  ogWebAppContext.setEventListeners(new EventListener[]{new ComponentRepositoryServletContextListener(repo)});
  handlers.addHandler(ogWebAppContext);
  _jettyServer.setHandler(handlers);
  _jettyServer.start();
  _remoteViewRunner = new RemoteViewRunner(URI.create(serverUrl));
}
 
開發者ID:DevStreet,項目名稱:FinanceAnalytics,代碼行數:26,代碼來源:RemoteViewRunnerTest.java

示例9: chore

import org.apache.commons.lang.math.RandomUtils; //導入方法依賴的package包/類
@Override
protected void chore() {
    for (HRegion r : this.server.onlineRegions.values()) {
        if (r == null)
            continue;
        if (r.shouldFlush()) {
            FlushRequester requester = server.getFlushRequester();
            if (requester != null) {
                long randomDelay = RandomUtils.nextInt(RANGE_OF_DELAY) + MIN_DELAY_TIME;
                LOG.info(getName() + " requesting flush for region " + r.getRegionNameAsString() +
                        " after a delay of " + randomDelay);
                //Throttle the flushes by putting a delay. If we don't throttle, and there
                //is a balanced write-load on the regions in a table, we might end up
                //overwhelming the filesystem with too many flushes at once.
                requester.requestDelayedFlush(r, randomDelay);
            }
        }
    }
}
 
開發者ID:grokcoder,項目名稱:pbase,代碼行數:20,代碼來源:HRegionServer.java

示例10: lessThanReadRestraintByDynamicTest

import org.apache.commons.lang.math.RandomUtils; //導入方法依賴的package包/類
@Test
public void lessThanReadRestraintByDynamicTest() throws InterruptedException {
    if (ASTATICISM_TEST) {
        return;
    }

    int executCount = 10;
    int readCount = RandomUtils.nextInt(executCount);

    MockServer.setConfigInfo(TAtomConstants.getAppDataId(APPNAME, DBKEY_0),
        " maxPoolSize=100\r\nuserName=tddl\r\nminPoolSize=1\r\nreadRestrictTimes=" + executCount + "\r\n");
    TimeUnit.SECONDS.sleep(SLEEP_TIME);

    String sql = "select * from normaltbl_0001 where pk=?";
    for (int i = 0; i < readCount; i++) {
        try {
            Map rs = tddlJT.queryForMap(sql, new Object[] { RANDOM_ID });
            Assert.assertEquals(time, String.valueOf(rs.get("gmt_create")));
            executCount--;
        } catch (DataAccessException ex) {
        }
    }

    Assert.assertTrue(executCount >= 0);
}
 
開發者ID:beebeandwer,項目名稱:TDDL,代碼行數:26,代碼來源:AtomReadRestraintTest.java

示例11: convert

import org.apache.commons.lang.math.RandomUtils; //導入方法依賴的package包/類
@Override
public void convert(Document doc) {
    log.debug("Converting artifacts cleanup system property to a cron expression based configuration descriptor.");

    Element rootElement = doc.getRootElement();
    Namespace namespace = rootElement.getNamespace();

    // Create cron expression element with random times from 04:00AM to 05:59AM
    Element cronExpElement = new Element("cronExp", namespace);
    int minutes = RandomUtils.nextInt(60); // 0-59
    int hours = RandomUtils.nextInt(2) + 4; // 4-5
    cronExpElement.setText("0 " + minutes + " " + hours + " * * ?");

    Element cleanupElement = new Element("cleanupConfig", namespace);
    cleanupElement.addContent(cronExpElement);

    rootElement.addContent(cleanupElement);

    log.debug("Finished converting the artifacts cleanup system property.");
}
 
開發者ID:alancnet,項目名稱:artifactory,代碼行數:21,代碼來源:CleanupConfigConverter.java

示例12: unbalanceRegions

import org.apache.commons.lang.math.RandomUtils; //導入方法依賴的package包/類
protected void unbalanceRegions(ClusterStatus clusterStatus,
    List<ServerName> fromServers, List<ServerName> toServers,
    double fractionOfRegions) throws Exception {
  List<byte[]> victimRegions = new LinkedList<byte[]>();
  for (ServerName server : fromServers) {
    ServerLoad serverLoad = clusterStatus.getLoad(server);
    // Ugh.
    List<byte[]> regions = new LinkedList<byte[]>(serverLoad.getRegionsLoad().keySet());
    int victimRegionCount = (int)Math.ceil(fractionOfRegions * regions.size());
    LOG.debug("Removing " + victimRegionCount + " regions from " + server.getServerName());
    for (int i = 0; i < victimRegionCount; ++i) {
      int victimIx = RandomUtils.nextInt(regions.size());
      String regionId = HRegionInfo.encodeRegionName(regions.remove(victimIx));
      victimRegions.add(Bytes.toBytes(regionId));
    }
  }

  LOG.info("Moving " + victimRegions.size() + " regions from " + fromServers.size()
      + " servers to " + toServers.size() + " different servers");
  HBaseAdmin admin = this.context.getHBaseIntegrationTestingUtility().getHBaseAdmin();
  for (byte[] victimRegion : victimRegions) {
    int targetIx = RandomUtils.nextInt(toServers.size());
    admin.move(victimRegion, Bytes.toBytes(toServers.get(targetIx).getServerName()));
  }
}
 
開發者ID:tenggyut,項目名稱:HIndex,代碼行數:26,代碼來源:Action.java

示例13: perform

import org.apache.commons.lang.math.RandomUtils; //導入方法依賴的package包/類
@Override
public void perform() throws Exception {
  HBaseTestingUtility util = context.getHBaseIntegrationTestingUtility();
  HBaseAdmin admin = util.getHBaseAdmin();

  LOG.info("Performing action: Merge random adjacent regions of table " + tableName);
  List<HRegionInfo> regions = admin.getTableRegions(tableNameBytes);
  if (regions == null || regions.size() < 2) {
    LOG.info("Table " + tableName + " doesn't have enough regions to merge");
    return;
  }

  int i = RandomUtils.nextInt(regions.size() - 1);
  HRegionInfo a = regions.get(i++);
  HRegionInfo b = regions.get(i);
  LOG.debug("Merging " + a.getRegionNameAsString() + " and " + b.getRegionNameAsString());
  try {
    admin.mergeRegions(a.getEncodedNameAsBytes(), b.getEncodedNameAsBytes(), false);
  } catch (Exception ex) {
    LOG.warn("Merge failed, might be caused by other chaos: " + ex.getMessage());
  }
  if (sleepTime > 0) {
    Thread.sleep(sleepTime);
  }
}
 
開發者ID:tenggyut,項目名稱:HIndex,代碼行數:26,代碼來源:MergeRandomAdjacentRegionsOfTableAction.java

示例14: selectWeightedRandomItem

import org.apache.commons.lang.math.RandomUtils; //導入方法依賴的package包/類
/** Selects a random item from the given items with weights*/
public static <T> T selectWeightedRandomItem(List<Pair<T, Integer>> items) {
  int totalWeight = 0;
  for (Pair<T, Integer> pair : items) {
    totalWeight += pair.getSecond();
  }

  int cutoff = RandomUtils.nextInt(totalWeight);
  int cummulative = 0;
  T item = null;

  //warn: O(n)
  for (int i=0; i<items.size(); i++) {
    int curWeight = items.get(i).getSecond();
    if ( cutoff < cummulative + curWeight) {
      item = items.get(i).getFirst();
      break;
    }
    cummulative += curWeight;
  }

  return item;
}
 
開發者ID:tenggyut,項目名稱:HIndex,代碼行數:24,代碼來源:PolicyBasedChaosMonkey.java

示例15: sampleAllTreesOnce

import org.apache.commons.lang.math.RandomUtils; //導入方法依賴的package包/類
@Override
public void sampleAllTreesOnce(final int currentIteration,
		final int totalIterations, final AtomicBoolean stop) {

	// Add new trees, if any
	final int sizeOfCorpus = (int) Math
			.ceil((INITIAL_TREE_CORPUS_SIZE * Math.pow(
					1 + TREE_CORPUS_INCREASE_PER_ITERATION,
					currentIteration))
					* (treesToBeAdded.size() + treeCorpus.size()));

	while (treeCorpus.size() < sizeOfCorpus && !treesToBeAdded.isEmpty()) {
		final int nextTreePos = RandomUtils.nextInt(treesToBeAdded.size());
		final TreeNode<TSGNode> treeToBeAdded = treesToBeAdded
				.get(nextTreePos);

		treeCorpus.add(treeToBeAdded);
		addTSGRulesToSampleGrammar(treeToBeAdded);
		treesToBeAdded.remove(nextTreePos);
	}

	if (currentIteration % HYPERPARAM_OPTIMIZATION_FREQ == HYPERPARAM_OPTIMIZATION_FREQ - 1) {
		posteriorComputer.optimizeHyperparameters(treeCorpus);
	}
	super.sampleAllTreesOnce(currentIteration, totalIterations, stop);
}
 
開發者ID:mast-group,項目名稱:codemining-treelm,代碼行數:27,代碼來源:CollapsedGibbsSampler.java


注:本文中的org.apache.commons.lang.math.RandomUtils.nextInt方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。