Java Code Examples for org.apache.commons.lang3.RandomUtils#nextInt()

The following examples show how to use org.apache.commons.lang3.RandomUtils#nextInt() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CudaZeroHandler.java    From deeplearning4j with Apache License 2.0 6 votes vote down vote up
private void pickupHostAllocation(AllocationPoint point) {
    int numBuckets = configuration.getNumberOfGcThreads();
    long bucketId = RandomUtils.nextInt(0, numBuckets);

    long reqMemory = point.getNumberOfBytes();

    zeroUseCounter.addAndGet(reqMemory);

    point.setBucketId(bucketId);

    if (!zeroAllocations.containsKey(bucketId)) {
        log.debug("Creating bucketID: " + bucketId);
        synchronized (this) {
            if (!zeroAllocations.containsKey(bucketId)) {
                zeroAllocations.put(bucketId, new ConcurrentHashMap<Long, Long>());
            }
        }
    }

    zeroAllocations.get(bucketId).put(point.getObjectId(), point.getObjectId());
}
 
Example 2
Source File: CudaZeroHandler.java    From nd4j with Apache License 2.0 6 votes vote down vote up
private void pickupHostAllocation(AllocationPoint point) {
    int numBuckets = configuration.getNumberOfGcThreads();
    long bucketId = RandomUtils.nextInt(0, numBuckets);

    long reqMemory = AllocationUtils.getRequiredMemory(point.getShape());

    zeroUseCounter.addAndGet(reqMemory);

    point.setBucketId(bucketId);

    if (!zeroAllocations.containsKey(bucketId)) {
        log.debug("Creating bucketID: " + bucketId);
        synchronized (this) {
            if (!zeroAllocations.containsKey(bucketId)) {
                zeroAllocations.put(bucketId, new ConcurrentHashMap<Long, Long>());
            }
        }
    }

    zeroAllocations.get(bucketId).put(point.getObjectId(), point.getObjectId());
}
 
Example 3
Source File: CollectionHelper.java    From customstuff4 with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Gets a random element from the given collection where each element has a weight provided by weightFunction.
 * A higher weight makes an element more likely to be selected.
 *
 * @return A random element or null if the collection was empty.
 */
@Nonnull
public static <T> Optional<T> randomElement(Collection<T> collection, ToIntFunction<T> weightFunction)
{
    int totalWeight = collection.stream().mapToInt(weightFunction).sum();
    int randomWeight = RandomUtils.nextInt(1, totalWeight + 1);

    for (T t : collection)
    {
        randomWeight -= weightFunction.applyAsInt(t);
        if (randomWeight <= 0)
            return Optional.of(t);
    }

    return Optional.empty();
}
 
Example 4
Source File: SysIforgetController.java    From mumu with Apache License 2.0 5 votes vote down vote up
/**
 * 发送邮箱验证码
 * @param email 邮箱账号
 * @param request
 * @return
 */
@ResponseBody
@RequestMapping(value = "/sendEmail",method = RequestMethod.POST)
public ResponseEntity sendEmail(String email, HttpServletRequest request){
    if(email==null||!ValidateUtils.isEmail(email)){
        return new ResponseEntity(400,"error","邮箱账号错误!");
    }
    //发送注册邮件
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+ request.getContextPath()+"/";
    Map<String,Object> modelMap=new HashMap<String,Object>();
    modelMap.put("USERNAME","baby慕慕");
    modelMap.put("LOGOIMG",basePath+"resources/img/logo.png");
    int verifyCode = RandomUtils.nextInt(100000, 999999);
    request.getSession().setAttribute("VERIFYCODE",String.valueOf(verifyCode));
    modelMap.put("VERIFYCODE",verifyCode);
    modelMap.put("IFORGOTURL",basePath+"system/iforget");
    modelMap.put("LOGINURL",basePath+"system/login");
    modelMap.put("OFFICIALURL",basePath);
    String content= VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "tpl/verifyCodeEmail.html","UTF-8",modelMap);
    try {
        boolean sendSuccess=emailService.send(email,null,"baby慕慕开放平台-验证码找回密码",content);
        if(sendSuccess){
            return new ResponseEntity(200,"success","验证码发送成功");
        }
    } catch (EmailException e) {
        e.printStackTrace();
    }
    return new ResponseEntity(400,"error","邮箱发送失败!");
}
 
Example 5
Source File: JdbcDataSource.java    From kafka-connectors with Apache License 2.0 5 votes vote down vote up
private Connection randomDataSource() {
    if (dataSourceMap.size() == 1) {
        return dataSourceMap.values().iterator().next();
    }
    Set<Map.Entry<String, Connection>> entrySet = dataSourceMap.entrySet();
    List<Map.Entry<String, Connection>> entryArrayList = new ArrayList<>(entrySet);
    int randomIdx = RandomUtils.nextInt(0, entryArrayList.size());
    return entryArrayList.get(randomIdx).getValue();
}
 
Example 6
Source File: RandomServerPort.java    From open-capacity-platform with Apache License 2.0 5 votes vote down vote up
public int nextValue(int start, int end) {
    start = start < this.start? this.start: start;
    end = end > this.end? this.end: end;

    if (serverPort == 0){
        synchronized (this){
            if (serverPort == 0){
                serverPort = RandomUtils.nextInt(start, end);
            }
        }
    }
    return serverPort;
}
 
Example 7
Source File: TestPayOrderRepository.java    From jigsaw-payment with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateAndGet() {
	PayOrder.Builder builder = PayOrder.newBuilder();
	long uid = System.nanoTime();
	String code = UUID.randomUUID().toString();
	builder.setId(System.currentTimeMillis());
	builder.setAppId("myapp");
	builder.setCreateTime(new Date().getTime());
	builder.setCurrentKey(19283745);
	builder.setDestPayType(1982);
	builder.setSubId(uid);
	Calendar expireTime = Calendar.getInstance();
	expireTime.add(Calendar.HOUR, 1);
	builder.setExpireTime(expireTime.getTime().getTime());
	int fee = RandomUtils.nextInt(1, 1000000);
	builder.setFee(fee);
	builder.setFeeReal(RandomUtils.nextInt(1, fee));
	builder.setFeeUnit(FeeUnit.CNY_VALUE);
	builder.setNotifyUrl("http://localhost/notify");
	builder.setReturnUrl("http://localhost/returnUrl");
	builder.setOrderDetail("OrderDetail");
	builder.setOrderId(UUID.randomUUID().toString());
	repository.create(builder.build());
	PayOrder order = repository.get(uid, code);
	assertEquals(order.getSubId(), uid);

}
 
Example 8
Source File: StringUtil.java    From xmfcn-spring-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * 创建一个随机数.
 *
 * @return 随机六位数+当前时间yyyyMMddHHmmss
 */
public static String randomCodeUtil() {
    String cteateTime = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss");
    int num = RandomUtils.nextInt(100000, 1000000);
    String result = cteateTime + StringUtils.leftPad(num + "", 6, "0");
    return result;
}
 
Example 9
Source File: CarreraAsyncRequest.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public CarreraAsyncRequest(UpstreamJob job, AtomicInteger permits, String groupCluster, BlockingQueue<CarreraAsyncRequest> retryQueue, Set<CarreraAsyncRequest> inflightRequests, ScheduledExecutorService scheduler) {
    this.job = job;
    this.permits = permits;
    this.groupCluster = groupCluster;
    this.retryRequestQueue = retryQueue;
    this.scheduler = scheduler;
    this.inflightRequests = inflightRequests;
    startIdx = RandomUtils.nextInt(0, job.getUrls().size());
}
 
Example 10
Source File: WinRegistryTest.java    From PeerWasp with MIT License 5 votes vote down vote up
@Test
public void testSetApiServerPort() {
	for (int i = 0; i < NUMBER_ITERATIONS; ++i) {
		int port = RandomUtils.nextInt(0, 65536);
		WinRegistry.setApiServerPort(port);
		assertPort(port);
	}
}
 
Example 11
Source File: C3P0PoolSlaveManager.java    From openzaly with Apache License 2.0 5 votes vote down vote up
public static java.sql.Connection getConnection() throws SQLException {
	if (cpdsList == null || cpdsList.size() == 0) {
		return C3P0PoolManager.getConnection();
	}
	int index = RandomUtils.nextInt(0, cpdsList.size());// [0,len)
	return cpdsList.get(index).getConnection();
}
 
Example 12
Source File: RandomDirLoadGenerator.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
@Override
public void generateLoad() throws Exception {
  int index = RandomUtils.nextInt();
  String keyName = getKeyName(index);
  fsBucket.createDirectory(keyName);
  fsBucket.readDirectory(keyName);
}
 
Example 13
Source File: ComponentTestUtils.java    From riposte with Apache License 2.0 5 votes vote down vote up
public static String generatePayload(int payloadSize, String dictionary) {
    StringBuilder payload = new StringBuilder();

    for(int i = 0; i < payloadSize; i++) {
        int randomInt = RandomUtils.nextInt(0, dictionary.length() - 1);
        payload.append(dictionary.charAt(randomInt));
    }

    return payload.toString();
}
 
Example 14
Source File: BaseSeimiCrawler.java    From SeimiCrawler with Apache License 2.0 4 votes vote down vote up
@Override
public String getUserAgent() {
    int index = RandomUtils.nextInt(0, defUAs.length);
    return defUAs[index];
}
 
Example 15
Source File: ImportExampleData.java    From tablestore-examples with Apache License 2.0 4 votes vote down vote up
private String randomGender() {
    return RandomUtils.nextInt(0, 2) == 1 ? "male" : "female";
}
 
Example 16
Source File: DataSourceChartSerializerTest.java    From pinpoint with Apache License 2.0 4 votes vote down vote up
private SampledDataSource createSampledDataSource(long timestamp, int maxConnectionSize) {
    int testObjectSize = RandomUtils.nextInt(1, CREATE_TEST_OBJECT_MAX_SIZE);
    List<DataSourceBo> dataSourceBoList = DataSourceTestUtils.createDataSourceBoList(1, testObjectSize, maxConnectionSize);
    return sampler.sampleDataPoints(0, timestamp, dataSourceBoList, null);
}
 
Example 17
Source File: RandomRouter.java    From deeplearning4j with Apache License 2.0 4 votes vote down vote up
protected short getNextShard() {
    return (short) RandomUtils.nextInt(0, numShards);
}
 
Example 18
Source File: TestDataUtil.java    From tablesaw with Apache License 2.0 4 votes vote down vote up
public static String randomUsState() {
  return usStateArray[RandomUtils.nextInt(0, usStateArray.length)];
}
 
Example 19
Source File: StringUtil.java    From mumu with Apache License 2.0 4 votes vote down vote up
/** 生成订单编号 */
public static String generateOrdrNo() {
	String cc = DateUtils.currentTime()+(RandomUtils.nextInt(10000, 90000));
	//BigInteger bi = new BigInteger(cc);
	return cc;
}
 
Example 20
Source File: ReadMyWriteWorkflow.java    From azure-cosmosdb-java with MIT License 3 votes vote down vote up
/**
 * Given a document list generates a randomly generated sql query which can find only and only the documents
 * <p>
 * The generated query may have a top, orderby, top and orderby.
 *
 * @param documentList list of documents to be queried for
 * @return SqlQuerySpec
 */
private SqlQuerySpec generateQuery(List<Document> documentList) {
    int top = RandomUtils.nextInt(0, MAX_TOP_QUERY_COUNT);
    boolean useOrderBy = RandomUtils.nextBoolean();

    return generateQuery(documentList, top >= documentList.size() ? top : null, useOrderBy);
}