Example usage for java.util Random nextDouble

List of usage examples for java.util Random nextDouble

Introduction

In this page you can find the example usage for java.util Random nextDouble.

Prototype

public double nextDouble() 

Source Link

Document

Returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence.

Usage

From source file:org.jtransforms.utils.IOUtils.java

/**
 * Fills 3D matrix with random numbers./*from w w w  .  jav  a  2 s.c  om*/
* @param n1  slices
* @param n2  rows
* @param n3  columns
* @param m   3D matrix
*/
public static void fillMatrix_3D(long n1, long n2, long n3, DoubleLargeArray m) {
    Random r = new Random(2);
    long sliceStride = n2 * n3;
    long rowStride = n3;
    for (long i = 0; i < n1; i++) {
        for (long j = 0; j < n2; j++) {
            for (long k = 0; k < n3; k++) {
                m.setDouble(i * sliceStride + j * rowStride + k, r.nextDouble());
            }
        }
    }
}

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 {//w w w  . j  av  a2 s  . c  o  m
        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:com.persistent.cloudninja.controller.TenantTaskListController.java

/**
 * Method added to generate simulated data for bytes sent and received
 * @return String : Random generated String
 *//*from ww w .  j  a v  a  2  s .c  om*/
@RequestMapping(value = "/showTrafficSimulationPage.htm")
public ModelAndView showTrafficsimulation(HttpServletRequest request, HttpServletResponse response,
        @CookieValue(value = "CLOUDNINJAAUTH", required = false) String cookie) {

    int START_INDEX = 2;
    int END_INDEX = 100;
    TrafficSimulationDTO trafficSimulationDTO = new TrafficSimulationDTO();

    if (cookie == null) {
        cookie = request.getAttribute("cookieNameAttr").toString();
    }

    String tenantId = AuthFilterUtils.getFieldValueFromCookieString(CloudNinjaConstants.COOKIE_TENANTID_PREFIX,
            cookie);
    response.addCookie(getTenantLogoCookieInResponse(tenantId, cookie));

    Random randomGen = new Random();
    int randomNum = randomGen.nextInt(END_INDEX - START_INDEX + 1) + START_INDEX;

    StringBuilder strbldr = new StringBuilder();
    for (int i = 0; i < randomNum; i++) {
        strbldr.append(Character.toChars((int) (Math.floor(26 * randomGen.nextDouble()) + 65)));
    }

    trafficSimulationDTO.setTenantId(tenantId);
    trafficSimulationDTO.setRandomString(strbldr.toString());
    return new ModelAndView("trafficSimulation", "trafficSimulationDTO", trafficSimulationDTO);

}

From source file:org.lenskit.pf.PMFModel.java

public void initialize(double weightShpPrior, double activityShpPrior, double meanActivityPrior,
        int userOrItemNum, int featureCount, double maxOffsetShp, double maxOffsetRte, Random random) {
    final double activityRte = activityShpPrior + featureCount;
    PMFModel model = IntStream.range(0, userOrItemNum).parallel().mapToObj(e -> {
        ModelEntry entry = new ModelEntry(e, featureCount, weightShpPrior, activityShpPrior, meanActivityPrior);
        for (int k = 0; k < featureCount; k++) {
            double valueShp = weightShpPrior + maxOffsetShp * random.nextDouble();
            double valueRte = activityShpPrior + maxOffsetRte * random.nextDouble();
            entry.setWeightShpEntry(k, valueShp);
            entry.setWeightRteEntry(k, valueRte);
        }/*  ww w.j  a  v  a2s . com*/
        double activityShp = activityShpPrior + maxOffsetShp * random.nextDouble();
        entry.setActivityRte(activityRte);
        entry.setActivityShp(activityShp);
        return entry;
    }).collect(new PMFModelCollector());
    addAll(model);
}

From source file:org.deidentifier.arx.criteria.EDDifferentialPrivacy.java

/**
 * Creates a random sample based on beta
 *
 * @param manager//from w w  w.  j  a  v a2s .  com
 */
public void initialize(DataManager manager) {

    // Needed for consistent de-serialization. We need to call this
    // method in the constructor of the class DataManager. The following
    // condition should hold, when this constructor is called during 
    // de-serialization, when we must not change the subset.
    if (subset != null && this.manager == null) {
        this.manager = manager;
        return;
    }

    // Needed to prevent inconsistencies. We need to call this
    // method in the constructor of the class DataManager. It will be called again, when
    // ARXConfiguration is initialized(). During the second call we must not change the subset.
    if (subset != null && this.manager == manager) {
        return;
    }

    // Create RNG
    Random random;
    if (deterministic) {
        random = new Random(0xDEADBEEF);
    } else {
        random = new SecureRandom();
    }

    // Create a data subset via sampling based on beta
    Set<Integer> subsetIndices = new HashSet<Integer>();
    int records = manager.getDataGeneralized().getDataLength();
    for (int i = 0; i < records; ++i) {
        if (random.nextDouble() < beta) {
            subsetIndices.add(i);
        }
    }
    this.subset = DataSubset.create(records, subsetIndices);
    this.manager = manager;
}

From source file:fall2015.b565.wisBreastCancer.KMeans.java

public List<Centroid> generateCentroids(int k) throws Exception {
    // read number of centroids from properties file
    List<Centroid> randomCentroids = new ArrayList<Centroid>();
    Random random = new Random();
    for (int j = 0; j < k; j++) {
        Record record = new Record(0, totalAttributes);
        for (int i = 0; i < totalAttributes; i++) {
            int r = (int) (random.nextDouble() * 10);
            record.setAttribute(i, r);//from   ww w.  j a  v a 2  s  . c  o m
        }
        Centroid centroid = new Centroid(record, j);
        randomCentroids.add(centroid);
    }
    return randomCentroids;
}

From source file:net.sf.mzmine.modules.peaklistmethods.peakpicking.adap3decompositionV1_5.ADAP3DecompositionV1_5SetupDialog.java

/**
 * Cluster list of PeakInfo based on the chromatographic shapes
 * //from   w  ww  .jav a 2 s  .com
 * @param peaks list of ADAP peaks
 * @param outClusters output of clusters
 * @param outText output of tooltip text
 * @param outColors output of colors
 */

private void shapeCluster(List<Peak> peaks, List<List<NavigableMap<Double, Double>>> outClusters,
        List<List<String>> outText, List<Double> outColors) {
    NumberFormat numberFormat = NumberFormat.getNumberInstance();

    Double edgeToHeightRatio = parameterSet.getParameter(ADAP3DecompositionV1_5Parameters.EDGE_TO_HEIGHT_RATIO)
            .getValue();
    Double deltaToHeightRatio = parameterSet
            .getParameter(ADAP3DecompositionV1_5Parameters.DELTA_TO_HEIGHT_RATIO).getValue();
    Boolean useIsShared = parameterSet.getParameter(ADAP3DecompositionV1_5Parameters.USE_ISSHARED).getValue();
    Double shapeSimThreshold = parameterSet.getParameter(ADAP3DecompositionV1_5Parameters.SHAPE_SIM_THRESHOLD)
            .getValue();
    Double minModelPeakSharpness = parameterSet
            .getParameter(ADAP3DecompositionV1_5Parameters.MIN_MODEL_SHARPNESS).getValue();
    List<Range<Double>> deprecatedMZValues = parameterSet
            .getParameter(ADAP3DecompositionV1_5Parameters.MZ_VALUES).getValue();

    if (edgeToHeightRatio == null || deltaToHeightRatio == null || useIsShared == null
            || shapeSimThreshold == null || minModelPeakSharpness == null || deprecatedMZValues == null)
        return;

    List<Peak> modelPeakCandidates = TwoStepDecomposition.filterPeaks(peaks, useIsShared, edgeToHeightRatio,
            deltaToHeightRatio, minModelPeakSharpness, deprecatedMZValues);

    if (modelPeakCandidates.isEmpty())
        return;

    List<List<Peak>> clusters = TwoStepDecomposition.getShapeClusters(modelPeakCandidates, shapeSimThreshold);

    outClusters.clear();
    outText.clear();
    outColors.clear();

    Random rand = new Random();
    rand.setSeed(0);

    int colorIndex = 0;
    final int numColors = 10;
    final double[] colors = new double[numColors];

    for (int i = 0; i < numColors; ++i)
        colors[i] = rand.nextDouble();

    for (List<Peak> cluster : clusters) {
        List<NavigableMap<Double, Double>> c = new ArrayList<>(cluster.size());

        List<String> texts = new ArrayList<>(cluster.size());

        for (Peak peak : cluster) {
            c.add(peak.getChromatogram());
            texts.add(peak.getInfo() + "\nSharpness: "
                    + numberFormat.format(FeatureTools.sharpnessYang(peak.getChromatogram())));
        }
        outClusters.add(c);
        outText.add(texts);

        outColors.add(colors[colorIndex % numColors]);
        ++colorIndex;
    }
}

From source file:com.adflake.AdFlakeManager.java

/**
 * Gets the darted ration.//from w  w  w .ja v  a 2  s  . c  o m
 * 
 * @return the darted ration
 */
public Ration getDartedRation() {
    Random random = new Random();

    double r = random.nextDouble() * _totalWeight;
    double s = 0;

    Log.d(AdFlakeUtil.ADFLAKE, "Dart is <" + r + "> of <" + _totalWeight + ">");

    Iterator<Ration> it = this._rationsList.iterator();
    Ration ration = null;
    while (it.hasNext()) {
        ration = it.next();
        s += ration.weight;

        if (s >= r) {
            break;
        }
    }

    return ration;
}

From source file:net.ftb.util.DownloadUtils.java

/**
 * Used to load all available download servers in a thread to prevent wait.
 *//*from   w ww .  j a va  2 s .co  m*/
@Override
public void run() {
    setName("DownloadUtils");
    if (!Locations.hasDLInitialized) {
        Benchmark.start("DlUtils");
        Logger.logInfo("DownloadUtils.run() starting");
        downloadServers.put("Automatic", Locations.masterRepoNoHTTP);
        Random r = new Random();
        double choice = r.nextDouble();
        try { // Super catch-all to ensure the launcher always renders
            try {
                // Fetch the percentage json first
                String json = IOUtils.toString(new URL(Locations.masterRepo + "/FTB2/static/balance.json"));
                JsonElement element = new JsonParser().parse(json);

                if (element != null && element.isJsonObject()) {
                    JsonObject jso = element.getAsJsonObject();
                    if (jso != null && jso.get("minUsableLauncherVersion") != null) {
                        LaunchFrame.getInstance().minUsable = jso.get("minUsableLauncherVersion").getAsInt();
                    }
                    if (jso != null && jso.get("chEnabled") != null) {
                        Locations.chEnabled = jso.get("chEnabled").getAsBoolean();
                    }
                    if (jso != null && jso.get("repoSplitCurse") != null) {
                        JsonElement e = jso.get("repoSplitCurse");
                        Logger.logDebug("Balance Settings: " + e.getAsDouble() + " > " + choice);
                        if (e != null && e.getAsDouble() > choice) {
                            Logger.logInfo("Balance has selected Automatic:CurseCDN");
                        } else {
                            Logger.logInfo("Balance has selected Automatic:CreeperRepo");
                            Locations.masterRepoNoHTTP = Locations.chRepo.replaceAll("http://", "");
                            Locations.masterRepo = Locations.chRepo;
                            Locations.primaryCH = true;
                            downloadServers.remove("Automatic");
                            downloadServers.put("Automatic", Locations.masterRepoNoHTTP);
                        }
                    }
                }
                Benchmark.logBenchAs("DlUtils", "Download Utils Bal");
                if (Locations.chEnabled) {
                    // Fetch servers from creeperhost using edges.json first
                    parseJSONtoMap(new URL(Locations.chRepo + "/edges.json"), "CH", downloadServers, false,
                            "edges.json");
                    Benchmark.logBenchAs("DlUtils", "Download Utils CH");
                }
                // Fetch servers list from curse using edges.json second
                parseJSONtoMap(new URL(Locations.curseRepo + "/edges.json"), "Curse", downloadServers, false,
                        "edges.json");
                Benchmark.logBenchAs("DlUtils", "Download Utils Curse");
                LoadingDialog.setProgress(80);
            } catch (IOException e) {
                int i = 10;

                // If fetching edges.json failed, assume new. is inaccessible
                // Try alternate mirrors from the cached server list in resources
                downloadServers.clear();

                Logger.logInfo("Primary mirror failed, Trying alternative mirrors");
                LoadingDialog.setProgress(i);
                parseJSONtoMap(this.getClass().getResource("/edges.json"), "Backup", downloadServers, true,
                        "edges.json");
            }
            LoadingDialog.setProgress(90);

            if (downloadServers.size() == 0) {
                Logger.logError(
                        "Could not find any working mirrors! If you are running a software firewall please allow the FTB Launcher permission to use the internet.");

                // Fall back to new. (old system) on critical failure
                downloadServers.put("Automatic", Locations.masterRepoNoHTTP);
            } else if (!downloadServers.containsKey("Automatic")) {
                // Use a random server from edges.json as the Automatic server
                int index = (int) (Math.random() * downloadServers.size());
                List<String> keys = Lists.newArrayList(downloadServers.keySet());
                String defaultServer = downloadServers.get(keys.get(index));
                downloadServers.put("Automatic", defaultServer);
                Logger.logInfo("Selected " + keys.get(index) + " mirror for Automatic assignment");
            }
        } catch (Exception e) {
            Logger.logError("Error while selecting server", e);
            downloadServers.clear();
            downloadServers.put("Automatic", Locations.masterRepoNoHTTP);
        }

        LoadingDialog.setProgress(100);
        Locations.serversLoaded = true;

        // This line absolutely must be hit, or the console will not be shown
        // and the user/we will not even know why an error has occurred. 
        Logger.logInfo("DL ready");

        String selectedMirror = Settings.getSettings().getDownloadServer();
        String selectedHost = downloadServers.get(selectedMirror);
        String resolvedIP = "UNKNOWN";
        String resolvedHost = "UNKNOWN";
        String resolvedMirror = "UNKNOWN";

        try {
            InetAddress ipAddress = InetAddress.getByName(selectedHost);
            resolvedIP = ipAddress.getHostAddress();
        } catch (UnknownHostException e) {
            Logger.logError("Failed to resolve selected mirror: " + e.getMessage());
        }

        try {
            for (String key : downloadServers.keySet()) {
                if (key.equals("Automatic"))
                    continue;

                InetAddress host = InetAddress.getByName(downloadServers.get(key));

                if (resolvedIP.equalsIgnoreCase(host.getHostAddress())) {
                    resolvedMirror = key;
                    resolvedHost = downloadServers.get(key);
                    break;
                }
            }
        } catch (UnknownHostException e) {
            Logger.logError("Failed to resolve mirror: " + e.getMessage());
        }

        Logger.logInfo("Using download server " + selectedMirror + ":" + resolvedMirror + " on host "
                + resolvedHost + " (" + resolvedIP + ")");
        Benchmark.logBenchAs("DlUtils", "Download Utils Init");
    }
    Locations.hasDLInitialized = true;
}

From source file:de.upb.timok.run.GenericSmacPipeline.java

private int testAndWriteAnomaly(int anomalies, int insertedAnomalies, double anomalyPercentage, String line,
        BufferedWriter testWriter, Random mutation, boolean force) throws IOException {
    final String newLine = line;
    TimedSequence ts = new TimedSequence(newLine, true, false);
    int insertionCount = 0;
    if (insertedAnomalies < anomalies && (force || mutation.nextDouble() < anomalyPercentage)) {
        ts = mutate(ts, anomalyInsertionType, mutation);
        insertionCount++;/*www.  ja  va  2s.c  o  m*/
    } else {
        ts.setLabel(ClassLabel.NORMAL);
    }
    writeSample(ts.toLabeledString(), testWriter);
    return insertedAnomalies + insertionCount;
}