Example usage for java.lang Math toIntExact

List of usage examples for java.lang Math toIntExact

Introduction

In this page you can find the example usage for java.lang Math toIntExact.

Prototype

public static int toIntExact(long value) 

Source Link

Document

Returns the value of the long argument; throwing an exception if the value overflows an int .

Usage

From source file:net.openhft.chronicle.timeseries.Columns.java

public static void generateBrownian(DoubleColumn col, double start, double end, double sd) {
    long length = col.length();
    double sd2 = sd / Math.sqrt(length);
    NormalDistribution nd = new NormalDistribution(0, sd2 * CHUNK_SIZE);
    int trendLength = Math.toIntExact((length - 1) / CHUNK_SIZE + 2);
    BytesStore trend = NativeBytesStore.lazyNativeBytesStoreWithFixedCapacity(trendLength * 8L);
    double x = start;
    RandomGenerator rand = new MersenneTwister();
    for (int i = 0; i < trendLength - 1; i++) {
        float f = rand.nextFloat();
        trend.writeDouble((long) i << 3, x);
        x += nd.inverseCumulativeProbability(f);
    }/* w ww. ja v  a 2s. c  o m*/
    trend.writeDouble((long) (trendLength - 1) << 3, x);
    double diff = end - x;
    double gradient = diff / (trendLength - 1);
    for (int i = 0; i < trendLength; i++) {
        double y = trend.addAndGetDoubleNotAtomic((long) i << 3, i * gradient);
        //            System.out.println(i + ": "+y);
    }
    int procs = Runtime.getRuntime().availableProcessors();
    int chunksPerTask = (trendLength - 1) / procs + 1;
    ForkJoinPool fjp = ForkJoinPool.commonPool();
    List<ForkJoinTask> tasks = new ArrayList<>(procs);
    for (int i = 0; i < procs; i++) {
        int si = i * chunksPerTask;
        int ei = Math.min(trendLength, si + chunksPerTask);
        tasks.add(fjp.submit(() -> {
            NormalDistribution nd2 = new NormalDistribution(0, sd2);
            RandomGenerator rand2 = new MersenneTwister();
            for (int j = si; j < ei; j++) {
                generateBrownian(col, (long) j * CHUNK_SIZE, trend.readDouble((long) j << 3),
                        trend.readDouble((long) (j + 1) << 3), nd2, rand2);
            }
        }));
    }
    for (ForkJoinTask task : tasks) {
        task.join();
    }
    trend.release();
}

From source file:alluxio.cli.fs.command.FreeCommand.java

@Override
protected void runPlainPath(AlluxioURI path, CommandLine cl) throws AlluxioException, IOException {
    int interval = Math.toIntExact(Configuration.getMs(PropertyKey.WORKER_BLOCK_HEARTBEAT_INTERVAL_MS));
    FreeOptions options = FreeOptions.defaults().setRecursive(true).setForced(cl.hasOption("f"));
    mFileSystem.free(path, options);/* w  w  w.j a  va  2 s.co  m*/
    CommonUtils.waitFor("file to be freed. Another user may be loading it.", (v) -> {
        try {
            boolean freed = mFileSystem.getStatus(path).getInAlluxioPercentage() == 0;
            if (!freed) {
                mFileSystem.free(path, options);
            }
            return freed;
        } catch (Exception e) {
            Throwables.propagateIfPossible(e);
            throw new RuntimeException(e);
        }
    }, WaitForOptions.defaults().setTimeoutMs(10 * Math.toIntExact(interval)).setInterval(interval));
    System.out.println(path + " was successfully freed from memory.");
}

From source file:cats.twitter.webapp.controller.module.ApiController.java

/**
 * Modules have to query here when they want to retrieve a corpus.
 * @param token The token sent in the initialisation request (/init)
 * @param from (not required) Pagination
 * @param to (not required) Pagination//from  w  w w  . jav  a2  s  .c  o m
 * @return The list of tweets of the corpus in JSON
 */
// @CrossOrigin(origins = "http://localhost:3000")
@RequestMapping(value = "/api", method = RequestMethod.GET)
public List<Tweet> api(@RequestHeader("token") String token,
        @RequestParam(value = "from", required = false) Integer from,
        @RequestParam(value = "to", required = false) Integer to) {
    Optional<Request> req = reqRepository.findOneByToken(token);
    if (!req.isPresent()) {
        throw new IllegalAccessError("Please verify your token!");
    }
    Corpus corpus = req.get().getCorpus();

    if (from == null)
        from = 0;
    if (to == null)
        to = Math.toIntExact(tweetRepository.countByCorpusId(corpus.getId()));

    return tweetRepository.findByCorpusId(corpus.getId(), new ChunkRequest(from, to - from)).getContent();

}

From source file:com.baifendian.swordfish.webserver.dto.ExecutionNodeDto.java

/**
 *  executionNode ??/*from   ww w.j  av  a  2s  .c o  m*/
 */
public void mergeExecutionNode(ExecutionNode executionNode) {
    if (executionNode != null) {
        this.startTime = executionNode.getStartTime();
        this.endTime = executionNode.getEndTime();

        this.duration = (startTime == null) ? 0
                : Math.toIntExact(((endTime == null) ? System.currentTimeMillis() - startTime.getTime()
                        : endTime.getTime() - startTime.getTime()) / 1000);

        this.status = executionNode.getStatus();

        // link ??
        List<String> appIds = executionNode.getAppLinkList();

        if (CollectionUtils.isNotEmpty(appIds)) {
            this.appLinks = new ArrayList<>();

            for (String appId : appIds) {
                this.appLinks.add(ConfigurationUtil.getWebappAddress(appId));
            }
        }

        this.jobId = executionNode.getJobId();
    }
}

From source file:net.longfalcon.web.AdminGroupController.java

@RequestMapping(value = "/admin/group-list", method = RequestMethod.GET)
public String groupListView(
        @RequestParam(value = "offset", required = false, defaultValue = "0") Integer offset, Model model) {
    List<Group> groupList = groupDAO.getGroups(offset, PAGE_SIZE);

    int pagerTotalItems = Math.toIntExact(groupDAO.getGroupsCount());

    model.addAttribute("title", "Group List");
    model.addAttribute("groupList", groupList);
    model.addAttribute("dateView", new DateView());
    model.addAttribute("groupService", groupService);
    model.addAttribute("pagerTotalItems", pagerTotalItems);
    model.addAttribute("pagerOffset", offset);
    model.addAttribute("pagerItemsPerPage", PAGE_SIZE);

    return "admin/group-list";
}

From source file:org.jbb.system.web.cache.logic.FormCacheTranslator.java

public CacheSettingsForm fillCacheSettingsForm(CacheSettings cacheSettings, CacheSettingsForm form) {

    form.setApplicationCacheEnabled(cacheSettings.isApplicationCacheEnabled());
    form.setSecondLevelCacheEnabled(cacheSettings.isSecondLevelCacheEnabled());
    form.setQueryCacheEnabled(cacheSettings.isQueryCacheEnabled());
    form.setProviderName(cacheSettings.getCurrentCacheProvider().toString());

    HazelcastServerSettings hazelcastServerSettings = cacheSettings.getHazelcastServerSettings();
    HazelcastServerSettingsForm hazelcastServerForm = form.getHazelcastServerSettings();
    hazelcastServerForm.setGroupName(hazelcastServerSettings.getGroupName());
    hazelcastServerForm.setMembers(String.join(", ", hazelcastServerSettings.getMembers()));
    hazelcastServerForm.setServerPort(hazelcastServerSettings.getServerPort());
    hazelcastServerForm.setManagementCenterEnabled(hazelcastServerSettings.isManagementCenterEnabled());
    hazelcastServerForm.setManagementCenterUrl(hazelcastServerSettings.getManagementCenterUrl());

    HazelcastClientSettings hazelcastClientSettings = cacheSettings.getHazelcastClientSettings();
    HazelcastClientSettingsForm hazelcastClientForm = form.getHazelcastClientSettings();
    hazelcastClientForm.setGroupName(hazelcastClientSettings.getGroupName());
    hazelcastClientForm.setMembers(String.join(", ", hazelcastClientSettings.getMembers()));
    hazelcastClientForm.setConnectionAttemptLimit(hazelcastClientSettings.getConnectionAttemptLimit());
    hazelcastClientForm.setConnectionAttemptPeriod(
            Math.toIntExact(hazelcastClientSettings.getConnectionAttemptPeriod().toMillis()));
    hazelcastClientForm/*ww w. jav  a2 s . c  o m*/
            .setConnectionTimeout(Math.toIntExact(hazelcastClientSettings.getConnectionTimeout().toMillis()));

    return form;
}

From source file:net.longfalcon.web.AdminGameController.java

@RequestMapping("/admin/console-list")
public String listConsoleView(
        @RequestParam(value = "offset", required = false, defaultValue = "0") Integer offset, Model model) {
    title = "Console List";

    int pagerTotalItems = Math.toIntExact(consoleInfoDAO.countConsoleInfos());
    List<ConsoleInfo> consoleInfoList = consoleInfoDAO.getConsoleInfos(offset, PAGE_SIZE);

    model.addAttribute("title", title);
    model.addAttribute("consoleInfoList", consoleInfoList);
    model.addAttribute("pagerTotalItems", pagerTotalItems);
    model.addAttribute("pagerOffset", offset);
    model.addAttribute("pagerItemsPerPage", PAGE_SIZE);
    return "admin/console-list";
}

From source file:org.cgiar.ccafs.marlo.action.center.json.monitoring.project.ValidateSyncCode.java

@Override
public String execute() throws Exception {

    message = new HashMap<>();
    message.put("code", syncCode);

    switch (Math.toIntExact(syncTypeID)) {
    // Validate OCS Code
    case 1:/*  w ww  . j  a  v a 2 s  .  c o m*/
        agreement = ocsClient.getagreement(syncCode);
        if (agreement != null) {

            CenterProject centerProject = centerProjectManager.getCenterProjectsByOcsCode(syncCode);
            if (centerProject != null) {
                message.put("status", false);
            } else {
                message.put("status", true);
            }
        } else {
            message.put("status", false);
        }
        break;
    // Validate MARLO CRP Project
    case 2:
        long projectID = Long.parseLong(syncCode);
        Project project = projectManager.getProjectById(projectID);
        if (project != null) {

            CenterProject centerProject = project.getCenterProject();
            if (centerProject != null) {
                message.put("status", false);
            } else {
                message.put("status", true);
            }
        } else {
            message.put("status", false);
        }
        break;

    default:
        break;
    }

    return SUCCESS;
}

From source file:org.shareok.data.redis.RedisUtil.java

public static void sortJobList(List<RedisJob> jobList) {
    jobList.sort(new Comparator<RedisJob>() {
        @Override/*  w  w  w.  java  2s .c o  m*/
        public int compare(RedisJob o1, RedisJob o2) {
            int result = 0;
            try {
                if (null != o1 && null != o2) {
                    result = Math.toIntExact(o1.getJobId() - o2.getJobId());
                }
            } catch (UnsupportedOperationException uoex) {
                logger.error("Cannot compare the tow job objects", uoex);
            }
            return result;
        }
    });
}

From source file:ru.mystamps.web.util.Pager.java

public Pager(long totalRecords, int recordsPerPage, int currentPage) {
    Validate.isTrue(totalRecords >= 0, "Total records must be greater than or equal to zero");
    Validate.isTrue(recordsPerPage > 0, "Records per page must be greater than zero");
    Validate.isTrue(currentPage > 0, "Current page must be greater than zero");

    this.totalRecords = Math.toIntExact(totalRecords);
    this.totalPages = countTotalPages(this.totalRecords, recordsPerPage);
    this.recordsPerPage = recordsPerPage;
    this.currentPage = currentPage;
    this.items = createItems(this.totalRecords, recordsPerPage, currentPage, this.totalPages);
    this.prev = findPrev(currentPage);
    this.next = findNext(currentPage, this.totalPages);
}