dimanche 30 septembre 2018

Get MULTIPLE random records using Entity Framework?

I have checked this answered question and other articles on Stack Overflow. I prefer the Skip method. However, they are all for single record. Now assume I want to take 20 random records from a table, how can I do that?

I am trying two possibilities:

  1. Generate an array of indexes and use Skip for each. This, however, results in 20 queries (and each is ordered by Id too).

  2. Fetch the list of all Ids and pick randomly into an array and perform a 2nd query for detailed info all selected Ids.

  3. Or just use OrderBy as the other post suggested. I think this can be bad because the entire table is ordered?

Please tell me if there is any better solution.




Linear transformation of Gaussian Random vector

Matrix U is (PxQ) dimension gaussian random vector which is partitioned in p-vector Z and Q-vector Y. For any (PXQ) matrix A, Matrix U is transformation to U' is given by Z'=Z-AY and Y and transformation is 1:1. I need to find matrix A for which Z' and Y and statistically independent. I started with COV(Z') and COV(Y) to show that they must be diagonal with diagonal values to be variances and off-diagonal to be 0s. But I am not sure how it can help me find matrix A. Any opinions.

P.S. mean of matrix U is m_u and variance is A(u)




6 random number to get result

I need help with one application. There is one random number from the set (1-999) to which solution should be obtained using arithmetic operations using four random numbers of 1-9, one number from the set (10,15 and 20), and one number from the set (25,50, 75 and 100). So, the program should help these with thes 6 numbers. Any idea ?




Randomly selecting items froma list without repeating Python

I was given this problem: Program that randomly shows 53 cards one by one every 5 seconds or so without repeating them.

My code right now looks extremly basic as Im still trying to figure out how to make it work. I have managed to randomly print the items from the list without repeating but when it runs out of options i get an error. Here's a part of my code:

let = ['CARD 1','CARD2','CARD 3']#Theres only 3 cards until i figure how to do it
if var=='iniciar' or 'INICIAR':
  while True:
    random.choice(let)
    while len(let):
    print let.pop()
    import time
    time.sleep(.5)

Can any of you figure out how to do it or have an example I can use?




Generating serie of numbers and letters

I want to generate a serie of numbers from 1 to 5, I wrote the following code

<?php
   $tag = range(1,5);
   echo "Numbers : ".implode(" - F",$tag)."<br>";
?>

I expect to get this result :

F1 - F2 - F3 - F4 - F5

But I am getting that instead :

1 - F2 - F3 - F4 - F5

What should I modify to get the wanted result ?




UPDATE column1 value in a table. Value will be 3 types(Nominated, Standy, Entry)

I am having a problem with my algorithm. Is this possible to solve? 3 queries in one function? Queries should be step by step.

Let's say that there are already rows inside the table. Some have the value of Column1 as Nominated, some are Standby, and others are Entry

  1. First update query, those entry that have the value of 'Nominated' will change into 'Standby'. /i'm done with this. I'm stuck at the lower parts/

  2. There are entries in the table where the value of Column1 is 'Entry'(by default). After the first query, this query should run. The function will get random(any number) rows which the value of Column1 is 'Entry' will change into 'Nominated'.

  3. There are entries in the table where the value of Column1 is 'Standby'. The rows from first query SHOULD NOT be included in this part. Those rows that already have the value of 'Standby' before the function start, should change into 'Entry'.

I need advices from you guys. Which is better, which is not. I'm having trouble from the 2-3 parts. Is this possible? If not, what are your suggestions?




Is it possible to replace pseudo-random in a language globally?

Many languages contains both "secure" and "insecure" PRNG functions. What the possible consequenceses could be there if we make obsolete insecure implementation by making aliases?

"Insecure" PRNG is usually very fast and produces easily predictable sequences based on a seed. "Secure" PRNG is usually uses PRNG from underlying OS/kernel which in most cases is secure.

Note 1: This question is a language-agnostic as it's a very common pattern, but answers could be per-language.

Note 2: We are not speaking about history and old slow computers




PHP Rand function seems to be weighted

I am using the following code to test a function I have, but it seems like the rand function is generating weighted results:

$D22[] = rand(1,2)*10+rand(1,2);

Testing this is generating one of four numbers: 11,12,21,22. It should be running about 25% each, but 11 is actually only showing up about 5% of the time (only ran it 20 times).

What is causing this, and is there a better random function for PHP?

P.S.: I know this question is probably not valid for reasons. :)




Push selection to another array for storage

Hi wrote probably my first JavaScript code, I have a slight problem with it.

I want to randomly select a country and then the random selection should be added to the array called sel_count_arr

so if you push the button 5 times then five random countries should be pushed to the sel_count_arr

the selecting random countries part is working, but pushing the selection to the empty arrey is not.

can someone help me to figure this out?

<button type="button" onclick="document.getElementById('countries').innerHTML = random_countries(country_list)">Click for random country</button>
<p id="countries"> </p>

<h3>Selected countries:</h3>
<p id="selected_countries"></p>

<script>
function random_countries(country_list)
{
 return country_list[Math.floor(Math.random()*country_list.length)];
}
var country_list = ["Afghanistan","Albania","Algeria","Andorra","Angola","Anguilla","Antigua &amp; Barbuda","Argentina","Armenia","Aruba","Australia","Austria","Azerbaijan","Bahamas"
        ,"Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bermuda","Bhutan","Bolivia","Bosnia &amp; Herzegovina","Botswana","Brazil","British Virgin Islands"
        ,"Brunei","Bulgaria","Burkina Faso","Burundi","Cambodia","Cameroon","Canada","Cape Verde","Cayman Islands","Chad","Chile","China","Colombia","Congo","Cook Islands","Costa Rica"
        ,"Cote D Ivoire","Croatia","Cruise Ship","Cuba","Cyprus","Czech Republic","Denmark","Djibouti","Dominica","Dominican Republic","Ecuador","Egypt","El Salvador","Equatorial Guinea"
        ,"Estonia","Ethiopia","Falkland Islands","Faroe Islands","Fiji","Finland","France","French Polynesia","French West Indies","Gabon","Gambia","Georgia","Germany","Ghana"
        ,"Gibraltar","Greece","Greenland","Grenada","Guam","Guatemala","Guernsey","Guinea","Guinea Bissau","Guyana","Haiti","Honduras","Hong Kong","Hungary","Iceland","India"
        ,"Indonesia","Iran","Iraq","Ireland","Isle of Man","Israel","Italy","Jamaica","Japan","Jersey","Jordan","Kazakhstan","Kenya","Kuwait","Kyrgyz Republic","Laos","Latvia"
        ,"Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg","Macau","Macedonia","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Mauritania"
        ,"Mauritius","Mexico","Moldova","Monaco","Mongolia","Montenegro","Montserrat","Morocco","Mozambique","Namibia","Nepal","Netherlands","Netherlands Antilles","New Caledonia"
        ,"New Zealand","Nicaragua","Niger","Nigeria","Norway","Oman","Pakistan","Palestine","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Poland","Portugal"
        ,"Puerto Rico","Qatar","Reunion","Romania","Russia","Rwanda","Saint Pierre &amp; Miquelon","Samoa","San Marino","Satellite","Saudi Arabia","Senegal","Serbia","Seychelles"
        ,"Sierra Leone","Singapore","Slovakia","Slovenia","South Africa","South Korea","Spain","Sri Lanka","St Kitts &amp; Nevis","St Lucia","St Vincent","St. Lucia","Sudan"
        ,"Suriname","Swaziland","Sweden","Switzerland","Syria","Taiwan","Tajikistan","Tanzania","Thailand","Timor L'Este","Togo","Tonga","Trinidad &amp; Tobago","Tunisia"
        ,"Turkey","Turkmenistan","Turks &amp; Caicos","Uganda","Ukraine","United Arab Emirates","United Kingdom","United States","United States Minor Outlying Islands","Uruguay"
        ,"Uzbekistan","Venezuela","Vietnam","Virgin Islands (US)","Yemen","Zambia","Zimbabwe"];

var sel_count_arr = [];

document.getElementById("selected_countries").innerHTML = sel_count_arr.push(random_countries(country_list));

</script>



samedi 29 septembre 2018

Storing ASCII characters in an array in C

I am trying to make a random generator using ASCII characters and due to my minimal knowledge, I am having difficulty trying to identify the best way to go about making this random generator.

Currently, I have managed to make a simple array which currently holds 6 values.

#include <stdio.h>
#include <conio.h>

    int main()
{
    int i;

    int  array[255] = {1, 2, 3 , 4, 5, 6 };

    for(i = 0; i < 6; i++)
    {
        printf("%d", array[i]); /* Prints out all values declared in the array*/
    }

    return 0;
}

output: 123456

What I am currently stuck on now is trying to find out how to replace the numbers with ASCII characters. If anyone could help me figure this out, I would be very grateful.




C# Random not Random at all

I am creating a LAN panic-button application, where the Server (TCP Server that handles multiple clients) will send a "panic" string to clients and the clients should pick a random website from a List of websites and open it.

So far, I tried my way (example below), opened multiple instances of the client on my PC and fired the panic button on the server.

The problem is that all clients open the same website and not a randomly selected one, so I end up with 10 new tabs on Chrome, navigating to the same website.

Why, although they are different instances, the randomly selected element is the same?

static string randomSite()
{
    Random Ram = new Random(DateTime.Now.Millisecond);
    List<string> sites = new List<string>();
    sites.Add("https://www.google.com");
    sites.Add("https://www.youtube.com");
    sites.Add("http://www.skai.gr");
    return sites[Ram.Next(0, sites.Count)];
}




How to use numba.cuda.jit to generate random numbers?

Below are my first attempts to use Python Numba for CUDA.

import numba
import random

@numba.jit
def test_jit():
    total = 0
    for i in range(10**6):
        total += random.gauss(0, 1)
    return total

print('jit', test_jit())

@numba.cuda.jit
def test_cuda():
    total = 0
    for i in range(10**6):
        total += random.gauss(0, 1)
    return total

print('cuda', test_cuda())

Running the above yields

jit -1358.6125717954903
[...]
TypingError: Failed at nopython (nopython frontend)
Unknown attribute 'gauss' of type Module(<module 'random' from 'D:\\Anaconda3\\lib\\random.py'>)
[...]

While using jit on my Gaussian Monte Carlo sum test works fine, cuda.jit does not understand random.gauss resulting in an error message. Using 'from random import gauss' and calling 'gauss(0, 1)' without 'random.' instead yields:

[...]
TypingError: Failed at nopython (nopython frontend)
Untyped global name 'gauss': cannot determine Numba type of <class 'method'>
[...]

How to fix this? Is there maybe some CUDA random number generator that couldbe used instead (maybe involving Cython)?




Generating 8 couples of integers

I want to have 8 couples of integers such that they all have different coordinates and they are all within 5 units of each other (using the euclidean distance).

To clarify, I want to have

(x1, y1)

(x2, y2)

(x3, y3)

(x4, y4)

(x5, y5)

(x6, y6)

(x7, y7)

(x8, y8)

where the xi's and yi's are randomly generated integers (via nextInt) so that there are no indexes i, j such that xi = xj and yi = yj and such that for all indexes i, j sqrt( (xi - xj)^2 + (yi - yj)^2 ) <= 5.




vendredi 28 septembre 2018

Numpy RNG non-deterministic even when seeded

I'm using numpy.random for a Monte Carlo simulation where very small acceptance/rejection probabilities are possible. Although I'm seeding the RNG, I'm unable to reproduce the same sequence of random numbers. In numpy 1.15.1's documentation it says:

Compatibility Guarantee: A fixed seed and a fixed series of calls to ‘RandomState’ methods using the same parameters will always produce the same results up to roundoff error except when the values were incorrect. Incorrect values will be fixed and the NumPy version in which the fix was made will be noted in the relevant docstring. Extension of existing parameter ranges and the addition of new parameters is allowed as long the previous behavior remains unchanged.

First of all, what do they mean by incorrect values? Second, how is roundoff error handled? Aren't values always rounded in precisely the same way? Is it possible at all that my code is not fully deterministic even though I provide a seed? I am certain that the seed is nowhere else reset because I provide my RNG object to each of my function as an argument.




Generate random array of integers with a number of appearance of each integer

I need to create a random array of 6 integers between 1 and 5 in Python but I also have another data say a=[2 2 3 1 2] which can be considered as the capacity. It means 1 can occur no more than 2 times or 3 can occur no more than 3 times.

I need to set up a counter for each integer from 1 to 5 to make sure each integer is not generated by the random function more than a[i].

Here is the initial array I created in python but I need to find out how I can make sure about the condition I described above. For example, I don't need a solution like [2 1 5 4 5 4] where 4 is shown twice or [2 2 2 2 1 2].

solution = np.array([np.random.randint(1,6) for i in range(6)])

Even if I can add probability, that should work. Any help is appreciated on this.




Random allocation in R with runif()

In R, I would like to be able to randomly assign values to groups.

If G = number of groups and V = number of values, with G <= V, I want allocation in the range of [1, V / G] inclusive. The caveat is that the total number of values across all groups must be fixed at V.

Ex. If G = 3 and V = 21, I can have (7, 7, 7) or (10, 6, 5) or ...

Is there a straightforward way of doing this with runif() (which doesn't include endpoints)? The caveat mentioned above is the complicated part.

Any thoughts?




Generate Unique Random Number in Java help of ArrayList

I am trying to generate unique random number every time. For checking it,

   `randomNumbers = new ArrayList<>();
    int letterIndex;
    do {
        Random randomLetter = new Random();
    }while (randomNumbers.contains(letterIndex));
    randomNumbers.add(letterIndex);`

But it doesn't work properly. Is there anyone to make suggestion? Thanks in advance.




Using the random() in LiveCode

I have an issue with using

the random defined function in livecode.

Here is a code snippet:

// 97 -> 122 = lower case...
put random(97,122) into randASCII

The program is to create an order number, the order number consists of the first character of the first name, first character of last name, random number between 1 and 9, and a random ASCII value between 97 and 122 (the lower case characters.)

Thank you very much!




After random import the simulation is always breaking down

I want to generate a random number and use it later. It also works, the simulation loads like for 0.5 sec and then I see it. But then the simulation breaks down and the simulation window quits. I also can't use e.g. import random it happens the same thing. Could it be that the random package doesn't work with Vpython?

from vpython import*
import random from randint



#Sonne
sun = sphere(pos = vec(0,0,0), radius = 9, make_trail = True ) 
sun.mass = 2e30   
sun.velocity = vec(0,0,0)

#Merkur
mercury_pos_x = randint(1, 100)
mercury = sphere(pos = vec(mercury_pos_x,0,0), radius = 5, color=color.red, make_trail = True ) 
mercury.mass = 3.25e23
mercury.velocity = vec(0,0,-47000)

#Venus
venus_pos_x = randint(1, 100)
venus = sphere(pos = vec(venus_pos_x,0,0), radius = 6, color=color.cyan, make_trail = True ) 
venus.mass = 4.9e24
venus.velocity = vec(0,0,-35000)




Simulate an unfair die

So, I have to simulate the tossing of an unfair die in MATLAB, which has a 20% of probability to show each face between 1 and 4, and 10% of probability to show each face of 5 and 6. I have to generate 5000 random integers, representing the outcomes of tossing the die. I also have to print out the simulated expected value and standard deviation using 5000 repeated trials.

This is the code I wrote in MATLAB:

x=randi(6,1,5000); %Generate 5000 random values from 1-6

mean_x = mean(x);    %Find expected value
std_x = std(x);      %Find standard deviation

range_x = [1:6];

bar(range_x, pmf);    %plot the pmf

xlabel('Value of face')
ylabel('Simulated probability mass function')

fprintf('The expected value is %4.2f\n',mean_x);
fprintf('The standard deviation is %4.2f\n', std_x);


function pmf=finitepmf(sx,px,x) %function that finds pmf

    pmf=zeros(size(x(:))); 

    for i=1:length(x) 
        switch x(i)
            case 1 
                px = 0.2;
            case 2 
                px = 0.2;
            case 3 
                px = 0.2;
            case 4 
                px = 0.2;
            case 5 
                px = 0.1;
            case 6 
                px = 0.1;
        end
        pmf(i)= sum(px(find(sx==x(i)))); 
    end

end

However, I get the same pmf I would if the die was fair. What am I doing wrong?




jeudi 27 septembre 2018

How to generate a random size crop using tensorflow.dataset module

I want to generate a random size crop when using tensorflow dataset API with tfrecord file. Here is my code

dataset = tf.data.TFRecordDataset(filenames)
dataset = dataset.map(parse_func)
dataset.shuffle(buffer_size=10000).batch(batch_size).repeat()
iterator = dataset.make_initializable_iterator()
data_in_tsr, data_gt_tsr,  = iterator.get_next()

def parse_func(example_proto):
    features = {
        'in': tf.FixedLenFeature(image_size, tf.float32),
        'gt': tf.FixedLenFeature(image_size, tf.float32)}

    parsed_features = tf.parse_single_example(example_proto, features)
    mag_in = parsed_features['mag_in']
    mag_gt = parsed_features['mag_gt']

    # random crop 128x128
    crop_sz = random.randint(mag_in.shape[0]//2, mag_in.shape[0])
    mag_in = tf.random_crop(mag_in, (crop_sz, crop_sz, mag_in.shape[2]))

    return mag_in, mag_gt

The problem is the map() function is called ONLY once, so a random crop of fix size is accquired each time. How to generate a random size crop?




Printing Random Number Between 1 and 6 in Java [duplicate]

This question already has an answer here:

I am trying to print a random number between 1 and 6 in Java, but am having trouble doing so (getting errors). It is my first time using random numbers in Java. Can anybody tell me what I am doing wrong in my code?? I think I am actually calling the method right but some of the other code is not working properly.

import java.util.Random;
public class Random {

    public static void main(String args[]) {
        Random random = new Random();
        int ans = random.nextInt(7);
        System.out.println(ans);
    }
}




How to use/insert a generated random number?

I generate a number in the range 1 to 100. This number should be in the first coordinate of the pos = vec(0,0,0) (so on the x-axis). The other axes should stay 0. How can I transfer the generated number to this point?

from vpython import *
from random import randint

print(randint(1, 100))


#Sonne
sun = sphere(pos = vec(0,0,0), radius = s_rad1, make_trail = True ) 
sun.mass = 2e30   
sun.velocity = vec(0,0,0)

#Merkur
mercury = sphere(pos = vec(0,0,0), radius = s_rad1/2, color=color.red, make_trail = True ) 
mercury.mass = 3.25e23
mercury.velocity = vec(0,0,-47000)

#Venus
venus = sphere(pos = vec(0,0,0), radius = s_rad1/1.8, color=color.cyan, make_trail = True ) 
venus.mass = 4.9e24
venus.velocity = vec(0,0,-35000)




Best way to revert to a random seed after temporarily fixing it?

Is this the only way to 'unseed' the random number generator:

np.random.seed(int(time.time()))

If you have some code that you want to be repeatable (e.g. a test) in a loop with other code that you want to be random each loop, how do you 'reset' the seed to random number generator after setting it?

The following code illustrates the issue:

import numpy as np

def test():
    np.random.seed(2)
    print("Repeatable test:", [np.random.randint(10) for i in range(3)])

for i in range(4):
    print("Random number:", np.random.randint(10))
    test()

Random number: 8
Repeatable test: [8, 8, 6]
Random number: 2
Repeatable test: [8, 8, 6]
Random number: 2
Repeatable test: [8, 8, 6]
Random number: 2
Repeatable test: [8, 8, 6]

Desired result: I want random number to be random each loop.

I am happy to import the time module if this is the only way to do it but I thought there might be a simpler, more robust way.

(You can't get the current seed according to this post)




Does anyone can help me with pseudorandom number and binary key question?

I'm having difficulties to solve two questions. One of the question is about binary key and another is about pseudorandom number. I have been trying to solve the questions for 3 days. This is my last resort. Unfortunately, I can't upload the question over here. Can anyone kindly give me your email address so i can send you the question? Desperately need help from any kind soul...




PHPUnit test coverage for condition triggered by reference

I have a method that makes a call to a builtin PHP function, openssl_random_pseudo_bytes.

public function generateRandomBytes()
{
    $crypto_secure = TRUE;
    $random_bytes = openssl_random_pseudo_bytes(16, $crypto_secure);
    if (!$crypto_secure)
    {
        throw new Security_Exception('Random bytes not generated by a cryptographically secure PRNG algorithm');
    }
    return $random_bytes;
}

I have one PHPUnit test case to test this method (all it does is verify that the randomly generated string is 16 bytes long).

public function testRandomBytesLength()
{
    $myclass = new MyClass();

    $this->assertEquals(16, strlen($myclass->generateRandomBytes()));
}

My question is, how do I test the case in which $crypto_secure is FALSE and an exception must be thrown? Since this value is passed in and modified as a reference to openssl_random_pseudo_bytes, I'm not sure how I could get test coverage for this execution path. My first thought was that maybe there's a php.ini configuration that I could use to force openssl_random_pseudo_bytes to use a cryptographically insecure algorithm (via ini_set in the test case). Any suggestions?




How to shuffle an array of numbers without two consecutive elements repeating?

I'm currently trying to get an array of numbers like this one randomly shuffled:

label_array = np.repeat(np.arange(6), 12)

The only constrain is that no consecutive elements of the shuffle must be the same number. For that I'm currently using this code:

# Check if there are any occurrences of two consecutive 
# elements being of the same category (same number)
num_occurrences = np.sum(np.diff(label_array) == 0)

# While there are any occurrences of this...
while num_occurrences != 0:
    # ...shuffle the array...
    np.random.shuffle(label_array)

    # ...create a flag for occurrences...
    flag = np.hstack(([False], np.diff(label_array) == 0))
    flag_array = label_array[flag]

    # ...and shuffle them.
    np.random.shuffle(flag_array)

    # Then re-assign them to the original array...
    label_array[flag] = flag_array

    # ...and check the number of occurrences again.
    num_occurrences = np.sum(np.diff(label_array) == 0)

Although this works for an array of this size, I don't know if it would work for much bigger arrays. And even so, it may take a lot of time.

So, is there a better way of doing this?




Random number out of three number in js

Hi I wanna get random numbers out of 2,3,5 . So i use this code.

function Random(low, hi) {
     return Math.floor(Math.random() * (hi - low + 1) + low);
 }

But this is only for 2 numbers , But i wanna get for 1 time for example 3 for 2 time 5, and 3 time 3 , but of course not exactly in that order . Any ideas ?




mercredi 26 septembre 2018

I've set up a RNG and a continue button but it wont update the result after continuing

#Setting up RNG
loop = "y"
while loop == "y" or loop == "yes":
    from random import randint
    dice = (randint(1,10))
    dice2 = (randint(1,10))
    roll = (dice + dice2)
    win = 3
    loss = 2
    cash = 20
    if roll == 3 or roll == 7 or roll == 11 or roll == 17:
        cash += (win)
    else:
        cash -= (loss)
    #Starting game
    print("""Welcome to, Gambling for School!

    You have $20 and must earn as much money as possible

    If you roll a 3, 7, 11, or 17, you will win $3 but any other number 
takes $2

    You have a 20% of winning
""")
x = input("Press ENTER to start.")
#Results
if roll == 11 or roll == 8 or roll == 18:
    print("You rolled an " + str(roll) + "!")
else:
    print("You rolled a " + str(roll) + "!")
print("")
print("Cash - $" + str(cash))
loop = input("Continue? (Y/N) ").lower()

Had to change the indenting to show it as code

When it runs, I hit enter to start the game and it adds and subtracts correctly but when I select continue, it plays as if I never lost or gained any money. It is 1AM and idk if my brain died but I can't think of anything to fix it




JavaScript - Generate a random number between 1 and 5, but never the same number twice consecutively

Okay hello everyone. I'm going to try to explain this the best I can....I have some simple code to generate a random number between 1 and 5. Depending on what number is pulled, a certain sound file will play..... HOWEVER.....how could I prevent this simple program from generating the same number twice in a row consequently making the same audio to play twice? For example: a roll of the dice is never the same twice consecutively....meaning you cannot roll a 2 if you just rolled a 2 etc.

I was experimenting with if else statements and kind of backed myself into a corner. I know this may seem like a simple problem but I'm at my wits end on this one. Any advice will be much appreciated! Thanks!

<!DOCTYPE html>
<html>
<body>

<p>Click the button to display a random number between 1 and 5.</p>

<button onclick="myFunction()">ROLL DICE</button>

<p id="demo"></p>

<script>
function myFunction() {
var x = Math.floor((Math.random() * 5) + 1);
document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>




Printing random even value between two values using inheritance

I am trying to print a list of random even numbers (5 times) using a bounds. Example being from 0 to 30 (including both those numbers). This is what I have so far (this is in its own class):

public int nextEven(int h){
        int n = rand.nextEven(h) % 2;
        return n;
        }

This is where it would print from my main method:

System.out.println("Random Even:");
    for (int i = 0; i < 5; i++){
        System.out.println(rand.nextEven(30));
    }

When I run the program it gives me an error and I am not quite sure how to solve this. This is an example of the desired output of even numbers from 0 to 30:

4 26 12 10 20




I wanted to apply random forest regression in R ..The error is Error in `[.default`(xj, i) : invalid subscript type 'list'

I am a civil student learning R for my data related to civil work.So my level of understanding is very basic.Please help out with the issue I am facing.

 library(randomForest)
model1<-randomForest(Manhours~.,data = numdata,subset=training_set,importance= TRUE,na.action = na.roughfix)
model1
plot(model1)

oob.err=double(5)
test.err=double(5)
for(mtry in 1:5) 
{
  rf=randomForest(Manhours~.,data = numedata,subset=training_set,ntree =500 
                  ,mtry = mtry,importance = TRUE,na.action = na.roughfix) 
  oob.err[mtry] = rf$mse[400] 

  prediction<-predict(rf,newdata = numdata[-training_set] ) 
  test.err[mtry]= with(numdata[-training_set], mean( (Manhours- pred)^2)) 
  cat(mtry," ")   

}




Where can I find or how can I create a sparse matrix version of the facebook fast randomized svd?

I have a Lanscos implementation of a rank-reduced SVD that can be distributed and handle very sparse matrixes with hundreds of millions of rows and columns. As you can imagine, it sometimes takes a few days to do its work.

I recently came across the Facebook fast randomized SVD at https://research.fb.com/fast-randomized-svd/ with code at http://tygert.com/software.html and I would like to try it, but the fortran code only supports dense matrix input, and at my scale there is no way I can use this.

So, does anyone know of a (preferably a distributed fortran) version of this or similar code that I could use?

Or, since the code I found includes source code, is there a simple way I can create a sparse matrix version from the dense matrix code?

FWIW, the code is built on BLAS and LAPACK.

Thanks for any help you can provide!




I need a code generator script for Javascript [on hold]

I need help! I'm new to Javascript and what I'm trying to do is too complex for me. I want to have a code that I can put into devtool console that will do a series of commands. I need it to type a code into a text box (It has to be 20 letters long with only uppercase letters and numbers from 0-9) I also need it to execute a button on this website and if the code doesn't work, it loops. So basically it keep typing a random code in and clicking the button until it finds one that works




Writing a function inside a class to generate a list of SIX random numbers between a given range

I want to generate a list of random numbers where the range and the length of the list can be varied later without modifying the function.So i thought of creating a function and the code i tried using python 3x is as follows:

class Traffic_matrix:

  def All_traffic(self,first,last,length):
      all_t=[]
      for i in range(length):
        all_t.append (random.randint(first, last))
all_t = Traffic_matrix()
print(all_t.All_traffic(23,56,6))

I know i have made a mistake somewhere and dont know what it is. Please help me out to sort this.




How to generate random number table in R?

I want to generate random number table. Let us consider I have to generate 100 random number of length 5. First digit denote Group 1 or 2 and second digit denote version-1, or 2 and last 3 digit are random numbers ranging from 001 to 999. For Example 11200, 12001, 21891....21005, 22105 are hundred random numbers.




Generate random numbers till Button click (UWP)

I have a textblock and a button.

I want the textblock to be filled with a random number when I click the button and it should change the random number every 5 seconds. When I click the button a second time it should stop at the last random number.

How do I make this? This is what I tried:

    bool thisStatus = false;

    private void btn_click(object sender, RoutedEventArgs e)
    {
        if (thisStatus == false)
        {
            thisStatus = true;
        }
        else thisStatus = false;
        random();
    }

        private void random()
    {
        while (thisStatus)
        {
            Random random = new Random();
            int RandomNumber = random.Next(0, 100);
            txtBlck.Text = RandomNumber.ToString();
            Task.Delay(5000);
        }
    }




Why does std::uniform_real_distribution

I want to generate random numbers in the whole double range. Doing it like

std::uniform_real_distribution<double> doubleDist(std::numeric_limits<double>::lowest(),
                                                  std::numeric_limits<double>::max());

produces IND / NaN, though. It took me a while to understand that this is according to documentation:

Requires that a ≤ b and b-a ≤ std::numeric_limits<RealType>::max()

Clearly std::numeric_limits<double>::max() - std::numeric_limits<double>::lowest() is larger than ::max, since :lowest is negative (unlike ::min).

Why can't I generate numbers between lowest and max this way and what is the rationale behind?




Select 5 random rows based on certain criteria

I want to get 5 random cases per Agent from a RawData where [Reviewer] = 'G'. If an agent does not have 5 cases that match this criteria then take the required number of random cases where [Reviewer] = 'P'

  • John has 5 cases where [Reviewer] = 'G' so these 5 cases should appear in the results
  • Dan has 2 cases where [Reviewer] = 'G' so 3 random cases where [Reviewer] = 'P' should be included in results
  • Pat has 6 cases where [Reviewer] = 'P' so 5 random cases should be in the results
  • Mary has 2 cases where [Reviewer] = 'G' so 3 random cases where [Reviewer] = 'P' should be included in results
  • Joe has 1 case where [Reviewer] = 'G' and only 2 cases where [Reviewer] = 'P' so all three cases should be included in results

Raw Data & Example of desired results




How to have a RNG in visual studio text based game

so I've been tasked to make a text based game similar to stuff like zork and it doesn't have to be complex, i would just like to know how to create an RNG in C# and have it do a console write line, and remember it so i can have the user repeat it back to get the win condition, using visual studio 2017 any help is thoroughly appreciated




Simplest random number generator without C library?

I would need to add some randomization to my Cortex M0 CPU firmware. The randomness is not important but the speed is.

I tested two functions I found online. With random() I managed to generate 1 number per 31 clock cycles, while random_uint generated 1 number in 20 cycles. My target is less than 10. What are other functions can I use?

unsigned random()
{
    unsigned b;

    b = t1 ^ (t1 >> 2) ^ (t1 >> 6) ^ (t1 >> 7);
    t1 = (t1 >> 1) | (~b << 31);

    b = (t2 << 1) ^ (t2 << 2) ^ (t1 << 3) ^ (t2 << 4);
    t2 = (t2 << 1) | (~b >> 31);

    return t1 ^ t2;
}



unsigned random_uint() {
    m_z = 36969 * (m_z & 65535) + (m_z >> 16);
    m_w = 18000 * (m_w & 65535) + (m_w >> 16);
    return (m_z << 16) + m_w;
}




How can I get a list with m tails? Python

So I need to create a list with m tails. The elements of the list will be a random choice between tail and head. I did like :

Def S(m):
    list=[]
    counter=0
    signs=["head","tail"]
    while counter<(m):
        list.append(random.choice(signs))
        for k in list:
            if k=="tail":
               counter+=1
    print(list)

So this one gives me a list but not with m tails. I think the while is wrong here but I am not sure how to write the code. Can you help me to change it?




Excel unique 4 digit random numbers

I want to program a column in excel to produce a unique 4 digit random numbers and to take into consideration the previous numbers that were in the column. For example, if 3333 is already there I want it to skip it and put another random number. Any ideas how can I do it? any suggestion is appreciated.

Thank you.




generate all unique triplets

there is a series of triplets:

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12],[13, 14, 15]]

(can be longer than that). They are all unique.

Q: What is the efficient way of generating all possible combinations of these triplets such that none of the items that have met before, 'meet' again?

So for instance in this sequence none of triplets contain any items that encountered before:

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12],[13, 14, 15]]
[[1, 5, 9], [4, 8, 12], [7, 11, 15], [10, 14, 3],[2, 6, 13]]
[[1, 4, 7], [5, 8, 11], [9, 12, 15], [10, 13, 2],[14, 3, 6]]

but this one would not work:

[[1, 5, 9], [4, 6, 12], [7, 11, 15], [10, 14, 3],[2, 8, 13]]

because 4 and 6 from the second triplet have been in the same triplet before, specifically in [4, 5, 6] of the first record

I think that it can be done by picking random triplets from initial sequence using random.sample(l, 3) and then check if this triplet has not been used before, but it looks pretty unefficient and I wonder if there is a nicer way.




mardi 25 septembre 2018

How to do random sampling based on customer ID

I have a data set as below

Cust_ID SubDepartment Date Bill_Value 1513 Detergent Bars 20180204 30 1513 French Fries 20180803 160 1513 Fruit Based Juices 20180204 30 1513 Containers 20180803 79 1513 Candies & Lollypops 20180803 165 1513 Cheese 20180204 203.04 1513 Cleaners & Wipers 20180803 159 1513 Chocolates 20180803 448 1513 Frozen Veg Snacks 20180803 570 1860 Salted Biscuits 20180110 40 1860 Oats 20180705 60 1860 Pastries 20180815 198 1860 Cheese 20180110 85 1860 Veg Powdered Soups 20180814 20 1860 Paneer 20180123 99 1860 North Indian Mixes 20180502 59 1860 Flavoured Milk 20180502 40

sample data set

I have want to do random sampling of the data based on customer id such that it picks all the transaction of the selected customers




Casting to int when generating a random distribution - Python

I was messing around with graphing random distributions, and found faint, but distinct and regularly spaced, lines appear when I graphed a distribution created by int(random.random() * random.random()). Here is the code I was using:

import random
import matplotlib.pyplot as plt

x = []
y = []

for i in range(50000):
    x.append(int(100*(random.random() + random.random())))
    y.append(int(100*(random.random() + random.random())))

plt.figure(figsize = (12,12))
plt.scatter(x,y,s=3)

And this is the graph I got: Scatter-plot of distribution with distinct faint lines

If you take out the integer casting, then the whole thing looks as expected:Scatter-plot of distribution without integer casting

Oddly enough, it seems that only the x-axis is responsible for the vertical lines, as removing the cast on the x-axis gets rid of the lines. The y-axis doesn't display any faint horizontal lines, but there are a couple darker lines. Scatter-plot with integer casting removed on the x-axis only

Obviously the fainter lines have something to do with casting to integer, but why and how does that affect the overall distribution this way. Also, why is it only in the vertical direction and not applied symmetrically across both dimensions?




Dynamically generate numbers that meet criteria

I feel like there is an elegant Python solution for this problem that I've been trying to solve with VBA. Can someone please help?

How can I generate a list of numbers that meet the following criteria:

  1. Are all integers
  2. The total is first split between types.
  3. The numbers are further split into subtypes and optimized to meet the required percentages.
  4. The total sum does not exceed the specified Total.

An example of this problem: You plan to build a maximum of 102 residential units.

40% of them will be Studios and 60% will be Townhouse type of construction type. (Could have more or less types)

There are two Priority lists for the future occupants for the apartments: Assisted and Unassisted. The unit allocation percentages in the Assisted(A) list are required to be fully met and the Unassisted(U) list is flexible.

We'd like the Unassisted(U) list to be up to 20% of the Total units if possible, but we definitely need a minimum of 80% of the Total units to be Assisted(A) units.

The Assisted(A) units are a total of 102x80%= 81.6 units. (Already not an integer...) A minimum of 10% of the Assisted(A) list units must be for elderly individuals. A minimum of 40% of the Assisted(A) list units must be for families. The remaining 50% of the Assisted(A) list units are for aspiring data scientists.

The remaining 20% of the Total units are Unassisted(U) occupancy units.

So:

  • Total: 102 units.
  • Construction_type_categories=[.4, .6] (102 units split into Studios and Townhouses: 40% and 60%)
  • Assisted=[.1,.4,.5] (80%+ of the total units are Assisted, further categorized as elderly, family, other occupancy according to the percentages in the list)
  • Unassisted units are the remaining units that were not part of the 80%+ of the Assisted list. (up to 20% of total units)

Result:

[4,16,12,8,7,25,19,11]

Breakdown:

  • 4 Studio Units Assisted for elderly
  • 16 Studio Units Assisted for families
  • 12 Studio Units for other Assisted occupancy type
  • 8 Studio Units (Unassisted)
  • 7 Townhouse Units Assisted for elderly
  • 25 Townhouse Units Assisted for families
  • 19 Townhouse Units for other Assisted occupancy type
  • 11 Townhouse Units (Unassisted).

I thought of first generating a preliminary array of rounded numbers and then looping through and making adjustments. It looked so tedious I've started considering generating a large matrix of numbers using numpy and filtering by the outlined criteria.

It has been time consuming to generate and optimize the numbers manually so I appreciate any help with a better solution.

Thank you




What is the runtime complexity of training a forest of T extremely randomized trees in terms of the Big O notation?

If n is the number of samples and there are m attributes then tree learning is O(m* n* log n), a Random forest which optimises for best split is O(T* m* n* log n) where there are T trees.

For extremely randomised trees where we don't optimise for best split locally we drop the linear dependence on n, so it is O(T* m* log n)?




need help to create random number for firebase data in quiz app

I am making an Quiz app wherein questions and answers are taken from firebase. I have uploaded questions with its options in firebase and now want to retrieve them randomly I have tried Random number = new Random(); number.nextInt(25); the problem is I dont need repeats I need one number to be generated only once and when questions end an alert bar should show and send user to score activity here is my main activity

   @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (mScore != 0){
    mScore = savedInstanceState.getInt("QK");

    }
    else{
        mScore = 0;

    }
    setContentView(R.layout.activity_bioquiz);
    setAndroidContext(this);
    choice1b = findViewById(R.id.choice1);
    choice2b = findViewById(R.id.choice2);
    choice3b = findViewById(R.id.choice3);
    choice4b = findViewById(R.id.choice4);
    mScoreTextView = findViewById(R.id.Score);
    mQuestionTextView = findViewById(R.id.questionTextView);

        Random m = new Random();

    int mQuestionNo = m.nextInt(25);



    updateQuestion();
    View.OnClickListener A = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (choice1b.getText().equals(mAnswer)) {
                choice1b.setBackgroundColor(Color.GREEN);
                mScore = mScore + 1;
                mScoreTextView.setText("Score "+String.valueOf(mScore) + "/"+ " 100");
                Toast.makeText(Bioquiz.this, "You got it!", Toast.LENGTH_SHORT).show();
                updateQuestion();
            } else {
                updateQuestion();
                v.setBackgroundColor(Color.RED);
                Toast.makeText(Bioquiz.this, "oops Wrong Answer", Toast.LENGTH_SHORT).show();
            }

        }
    };
    View.OnClickListener B = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (choice2b.getText().equals(mAnswer)) {
                choice1b.setBackgroundColor(Color.GREEN);
                mScore = mScore + 1;
                mScoreTextView.setText("Score "+String.valueOf(mScore) + "/"+ " 100");
                Toast.makeText(Bioquiz.this, "You got it!", Toast.LENGTH_SHORT).show();
                updateQuestion();
            } else {
                updateQuestion();
                v.setBackgroundColor(Color.RED);
                Toast.makeText(Bioquiz.this, "oops Wrong Answer", Toast.LENGTH_SHORT).show();

            }

        }

    };
    View.OnClickListener C = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (choice4b.getText().equals(mAnswer)) {
                choice1b.setBackgroundColor(Color.GREEN);
                mScore = mScore + 1;
                mScoreTextView.setText("Score "+String.valueOf(mScore) + "/"+ " 100");
                Toast.makeText(Bioquiz.this, "You got it!", Toast.LENGTH_SHORT).show();
                updateQuestion();
            } else {
                v.setBackgroundColor(Color.RED);
                updateQuestion();
                Toast.makeText(Bioquiz.this, "oops Wrong Answer", Toast.LENGTH_SHORT).show();
            }

        }
    };

    View.OnClickListener D = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (choice4b.getText().equals(mAnswer)) {
                choice1b.setBackgroundColor(Color.GREEN);
                mScore = mScore + 1;
                mScoreTextView.setText("Score "+String.valueOf(mScore) + "/"+ " 100");
                Toast.makeText(Bioquiz.this, "You got it!", Toast.LENGTH_SHORT).show();
                updateQuestion();

            } else {

                v.setBackgroundColor(Color.RED);
                updateQuestion();
                Toast.makeText(Bioquiz.this, "oops Wrong Answer", Toast.LENGTH_SHORT).show();
            }

        }
    };
    choice1b.setOnClickListener(A);
    choice2b.setOnClickListener(B);
    choice3b.setOnClickListener(C);
    choice4b.setOnClickListener(D);

}

    public void updateQuestion() {
        Random number = new Random();
        number.nextInt(25);



    Firebase questionRef = new Firebase("https://mcatbiologymcqs.firebaseio.com/"+mQuestionNo+"/question");
    questionRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String question = dataSnapshot.getValue(String.class);
            mQuestionTextView.setText(question);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });
    Firebase choice1Ref = new Firebase("https://mcatbiologymcqs.firebaseio.com/" +mQuestionNo + "/choice1");
    choice1Ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String choice1 = dataSnapshot.getValue(String.class);
            choice1b.setText(choice1);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });
    mChoice2Ref = new Firebase("https://mcatbiologymcqs.firebaseio.com/"+mQuestionNo+"/choice2");
    mChoice2Ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String choice2 = dataSnapshot.getValue(String.class);
            choice2b.setText(choice2);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });
    mChoice3Ref = new Firebase("https://mcatbiologymcqs.firebaseio.com/"+mQuestionNo+"/choice3");
    mChoice3Ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String choice3 = dataSnapshot.getValue(String.class);
            choice3b.setText(choice3);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });
    mChoice4Ref = new Firebase("https://mcatbiologymcqs.firebaseio.com/"+mQuestionNo+"/choice4");
    mChoice4Ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String choice4 = dataSnapshot.getValue(String.class);
            choice4b.setText(choice4);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });
    Firebase answerRef = new Firebase("https://mcatbiologymcqs.firebaseio.com/"+mQuestionNo+"/answer");
    answerRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            mAnswer = dataSnapshot.getValue(String.class);

        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });

    if (mScoreTextView == null){

        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle("Quiz Over");
        if (mScore ==20){alert.setMessage("Very Good");}
        else {
            alert.setMessage("You need to Work Hard");
        }
        alert.setPositiveButton("View Score", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
           Intent score = new Intent(Bioquiz.this,Score.class);

           startActivity(score);
            }
        });
        alert.setCancelable(false);
        alert.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
           finish();
            }
        });
        alert.show();


        }
    }

@Override
public void onBackPressed() {
    super.onBackPressed();
    Intent m = new Intent(Bioquiz.this,MainActivity.class);
    startActivity(m);
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("SK",mScore);





}}

please help me with a solution. Noob here :(




Generate uniform pseudo-random numbers in a closed interval

What's the best way to generate pseudo-random numbers in the closed interval [0,1] instead of the usual [0,1)? One idea I've came up with is to reject values in (1/2,1), then double the number. I wonder if there is a better method.

real x
do
   call random_number(x)
   if (x <= 0.5) exit
end do
x = 2*x
print *, x
end

The most important requirement is that the algorithm should not make a worse distribution (in terms of uniformity and correlation) than that generated by random_number(). Also I'd favour simplicity. A wrapper around random_number() would be perfectly good, I'm not looking to implement a whole new generator.


As @francescalus points out in the comments, with the algorithm above lots of numbers in [0,1] will have zero probability of appearing. The following code implements a slightly different approach: the interval is enlarged a bit, then values in excess of 1 are cut out. It should behave better in that aspect.

real x
do
   call random_number(x)
   x = x*(1 + 1e-6)
   if (x <= 1.) exit
end do
print *, x
end




how to apply probability weights to get population estimates

am new to stack overflow and survey analysis in general, so apologies if this is a rather basic question.

i have a survey data of stratified randomly sampled firms, and information on the number of employees per firm, as well as probability weights assigned to each firm.

if i want to find out the estimated total number of employees for all firms in the population, should i just multiply the number of employees by the probability weights and add them all up?

e.g. if Firm A has 7 employees and has a probability weight of 1.32; Total number of employees in the population that work in firms similar to Firm A= 7x1.32. Am I on the right track or totally off?




How do I randomly shuffle an array, container strings of names?

have been stuck on this for some time now. Working on React project for Table Tennis Game Generator. Struggling to find a solution to randomly shuffle an array of names, that have been entered by the user. It will not even console.log anything! Many thanks.

import React, { Fragment } from "react";

const FixturesList = playerNamesArray => {
let shuffledPlayers = [...playerNamesArray];

let arr1 = shuffledPlayers.slice(); // copy array
let arr2 = shuffledPlayers.slice(); // copy array again

 arr1.sort(function() {
 return 0.5 - Math.random();
  }); // shuffle arrays
 arr2.sort(function() {
 return 0.5 - Math.random();
 });

 while (arr1.length) {
 let player1 = arr1.pop(), // get the last value of arr1
  player2 = arr2[0] === player1 ? arr2.pop() : arr2.shift();
 //        ^^ if the first value is the same as name1,
 //           get the last value, otherwise get the first
 console.log(player1 + " gets " + player2);
 }

return (
 <Fragment>
  <section>
     <h1>Fixtures</h1>
  </section>
</Fragment>
);
};

export default FixturesList;




MySql : Get two random rows with different value

I have this table : enter image description here

I want two get 2 random rows on condition be published and have different location values ( exemple : if the first row is vertical , the second must be horizontal)

Thanks !




Generating random numbers with a cumulative distribution function

I am aware of the fact that rand returns a single uniformly distributed random number in the interval (0,1).

But I am also asked for using the following cumulative distribution function:

F(x) = \int_{-\inf}^{x} f(y) dy

I know how to generate uniformly distributed random numbers within an interval with the formula:

r = a + (b-a).*rand(N,1).

Where (a,b) is the interval and N the number of #

But how can I use uniformly distributed random numbers (in the interval [0,1] of course) and the inverse of the cumulative distribution function defined above in order to generate random numbers distributed uniformly in an interval (let's say [-2,1])?

NOTE: Sorry about the way I showed the integral but MathJax does not work in Stackoverflow. I do not know if there is another way to expose it. Please let me know if there is and I will change it. Thank you




os.listdir() - choose randomly from the returned list based on a condition

I have a directory containing thousands of images from three different domains

let's say the file names are xxx_A.png and yyy_B.png and zzz_C.png there are thousands from each domain

os.listdir() will return a list for all image names inside the directory

I then want to filter this list based on some percentages

Example: I specify that I want to have out of these thousands of images, only 100 shuffled images where 30% of them will be from domainA, 30% from domainB and 60% of domainC

So simply given a certain number, I have these percentages, and I choose x number of random images (based on the image name for sure, because they are already specified), and this will be the new list

Example:

Input:

['1_A.png', '2_A.png', '3_A.png', '4_A.png', '5_A.png', '6_A.png', '7_A.png', '8_A.png', '9_A.png', '10_A.png', '1_B.png', '2_B.png', '3_B.png', '4_B.png', '5_B.png', '6_B.png', '7_B.png', '8_B.png', '9_B.png', '10_B.png', '1_C.png', '2_C.png', '3_C.png', '4_C.png', '5_C.png', '6_C.png', '7_C.png', '8_C.png', '9_C.png', '10_C.png']

I want 12 images, 30% from domain A, 30% from domain B and 60% from domain C

Output:

 ['1_C.png', '10_C.png', '2_B.png', '4_A.png', '3_A.png', '9_C.png', '7_C.png', '6_A.png', '8_B.png', '10_B.png', '3_C.png', '5_C.png']

How can I make this ?




Set style to class names that have a random number

If I have a class like

.pin_12345_btn_select

Where the 12345 is a random number (which can be 5 to 12 characters long)

Is there a way I can set a single class style to all of these that are present in the site using a random number as above.

For example;

.pin_#####_btn_select { Z-index:99; width:220px; }

Thanks

Greg




lundi 24 septembre 2018

Python - Using the random module to give you a value in the range of [0.0, 1.0), multiply it, and round it

Trying to figure out how to, using the random module, obtain five values in the range from [0.0, 1.0), multiplying each value spit out by 5000, and rounding it to zero decimal places all the while using the random() and range() functions.

I've experimented with this question for some time now and am running into the issue of my range values being floats. How would I go about resolving the float issue along with my multiplication/rounding/random and range function question?




convert unknown code to python for random mandala designs

There is a code on this website that I have no idea what language it is in. https://mathematica.stackexchange.com/questions/136974/code-that-generates-a-mandala

I would like to convert it to python. But I have no idea how to start on this project. what module are needed how to script it correctly.

Clear[MakeSeedSegment]
MakeSeedSegment[radius_, angle_, n_Integer: 10, connectingFunc_: Polygon, keepGridPoints_: False] :=
  Block[{t},
   t = Table[
     Line[{radius*r*{Cos[angle], Sin[angle]}, {radius*r, 0}}], {r, 0, 1, 1/n}];
   Join[If[TrueQ[keepGridPoints], t, {}], {GrayLevel[0.25], 
     connectingFunc@
      RandomSample[Flatten[t /. Line[{x_, y_}] :> {x, y}, 1]]}]
   ];

seed = MakeSeedSegment[10, \[Pi]/12, 10];
Graphics[seed, Frame -> True]

Clear[MakeSymmetric]
MakeSymmetric[seed_] := {seed, 
   GeometricTransformation[seed, ReflectionTransform[{0, 1}]]};

seed = MakeSymmetric[seed];
Graphics[seed, Frame -> True]

Clear[MakeMandala]
MakeMandala[opts : OptionsPattern[]] :=     
  MakeMandala[
   MakeSymmetric[
    MakeSeedSegment[20, \[Pi]/12, 12, 
     RandomChoice[{Line, Polygon, BezierCurve, 
       FilledCurve[BezierCurve[#]] &}], False]], \[Pi]/6, opts];
MakeMandala[seed_, angle_?NumericQ, opts : OptionsPattern[]] :=
  Graphics[GeometricTransformation[seed, 
    Table[RotationMatrix[a], {a, 0, 2 \[Pi] - angle, angle}]], opts];

n = 12;
Multicolumn@
 MapThread[
  If[#1,
    MakeMandala[MakeSeedSegment[10, #2, #3], #2],
    MakeMandala[MakeSymmetric[MakeSeedSegment[10, #2, #3, #4, False]],
      2 #2]
    ] &, {RandomChoice[{False, True}, n], 
   RandomChoice[{\[Pi]/7, \[Pi]/8, \[Pi]/6}, n], 
   RandomInteger[{8, 14}, n], 
   RandomChoice[{Line, Polygon, BezierCurve, FilledCurve[BezierCurve[#]] &}, n]}]

With my work schedule I have no time figure this problem out at this moment or spend weeks dissecting the code line by line and googling it. It would be nice to have this code available on python and share it with the community. Your help is much appreciated.




How the computer generates a random number?

For example, in JavaScript, we just use a Math.random() and it gives us every time different numbers.

Questions:

  1. How the computer generates these different numbers every time?
  2. Which algorithm or mathematical basis is used to generate these numbers?



Calculating a probability that a random number will be between two numbers from a data set

So, I have generated a random, normally distributed population of data that has a mean of 341.08 and a standard deviation of 3.07. Here's that code:

pop<-rnorm(1000, mean=341.08,sd=3.07)

Now, I need to find out the probability that a random number picked will fall between 337 and 343 (both numbers included). How would I execute this?




C++: Get state of linear congruential generator

It seems that if I write

#include <random>
std::minstd_rand engine(1);

std::cout << engine;

then this prints out the internal state of the engine (which is a linear congruential generator). Right now the state equals the seed (1), but if I call a random number and print out engine, it returns some large number, which is probably the state.

How do I actually get the state, in a variable?




C - Middle Square Random Number Generator

So, I tried to implement the Middle Square PRNG method, to generate the first 100 numbers. It works well until a certain point, when I get as a result negative numbers. I used the time library to change the values on my temp array, so that it won't get stuck on the same sequence, where the number ends with two zeros.

My code :

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

time_t now;
struct tm *tm;

unsigned long int prng(int seed)
{
    int num = seed * seed;
    int t[10], inc = 0;
    //Reverse number in an array
    while(num != 0)
    {
        t[inc] = num%10;
        num /= 10;
        inc++;
    }
    int min = inc/4;
    int max = inc / 2 + min;
    int temp[10];

    //Assign the middle square part to another table
    for(int i = min; i <= max; i++)
    {
        temp[i-min] = t[i];
    }

    for(int i=0; i < max-min; i++)
    {
        //Check if there is a "0" "0" sequence, if TRUE - replace with current time (seconds)
        if(temp[i] == 0 && temp[i+1] == 0)
        {
            now = time(0);
            tm = localtime(&now);
            temp[i] = tm->tm_sec/10;
            temp[i + 1] = tm->tm_sec%10;
        }
    }

    //Transform the squared array into an integer
    unsigned long int k = 0;
    for (int i = 0; i <= max-min; i++)
        k = 10 * k + temp[i];


    return k;
}

int main()
{
    unsigned long int n = 123; //seed
    printf("%d ", n);
    for(int i = 0; i<100; i++)
    {
        n = prng(n);
        printf("\n%d ", n);
    }
    return 0;
}

The results that I get:

123
215
226
701
419
6557
24992
7064
7099
85930
-696950
8997
6490
10212
94824
36561
760763
-724206
30238
66334
22325
65048
-94273
...




MySQL Predictable Random Ordering

I am very surprised that I can't figure this out.

I'm currently outputting a table from MySQL in a somewhat random order. I say somewhat because there is a formula that is partially reliant on RAND(). In any case, we can assume the order is effectively random for my question.

This was all working great, except I want to keep the same order for a "session". I don't want it to keep jumping around while actively using the data. I have been trying to figure out how to have MySQL generate the same sequence a second time.

I know that you can do RAND(N) where N is a seed, but as far as I can tell that will be the exact same number each time. So basically there will be no random factor at all if I use that.

What I would like is a way I can feed a seed into my ORDER BY and always get a reliable output order. For the same seed, I will get the same order, and if I feed in a different seed, it will be a different random order.

The best I could come up with is that I could create an additional table cell with a RAND for each row and use that for sorting. There are a few issues:

  • Additional memory is used in the database.
  • It doesn't work for multiple users, because I'd need a separate column for each user.

I have to think about this, but I'm pretty certain that there is a clever solution here that doesn't involve me adding an additional column to the database. Has anyone else ever encountered the need to do something like this?




Arduino Random Number Generator with pushbutton

I'm new to Arduino, trying to make a random number generator with pushbutton.

My questions are:

1.How can I do that,if I press the pushbutton once, then I will get one random number between 0 and 1024. After that, I want to loop from 0 to the random number and then back to 0.

2.How can I debounce the pushbutton

void setup(){

Serial.begin(57600);
pinMode(2,INPUT_PULLUP);
attachInterrupt(0,randomnumber,FALLING);

}

void randomnumber(){

int number=random(0,1024);
for(int x=0;x<=number; x++){
  Serial.println(x);
  delay(1000);

}

for(int y=number;y>=0; y--){
  Serial.println(y);
  delay(1000);

}

} void loop(){

}

Any good suggestion?




Get random number focused on limitations

My mathematical knowledge might be limited to solve this myself. I've found a similar question, however, with focus on center and not borders.

I would like to create random numbers with max and min but with focus on the max and min, so numbers closer to max and min's should appear more frequent than the ones in between.

I remember that in mathematics there is a function to create a parabola curve: enter image description here

And using this online tool i kind of generated the function I am looking for, which should be like

y = 0.05 * x^2

This is my basic idea and trying to turn it into javascript i ended up with this:

for (let i = 0; i < 100; i++) {
  // Create random x with ^ 2 with max=100 and min=0
  let x = Math.pow(Math.floor(Math.random() * (100 - 0 + 1)) + 0, 2);
  // log the random number in the console
  console.log(0.05 * x);
}

But of course this doesn't make any real sense as I also can see in the console (I ordered them so it's more clear to see)

> 0 0
> 0.05
> 0.05
> 0.2
> 0.2
> 0.8
> 2.45
> 3.2
> 3.2
> 3.2
> 4.05
> 4.05
> 4.05
> 6.05
> 8.45
> 8.45
> 14.45
> 16.2
> 16.2
> 16.2 20 20
> 22.05
> 22.05
> 22.05
> 26.45
> 28.8
> 28.8
> 31.25
> 33.8
> 36.45
> 39.2
> 42.05
> 48.05
> 48.05
> 48.05
> 51.2
> 57.8
> 57.8
> 57.8
> 64.8
> 64.8
> 64.8
> 68.45
> 76.05
> 88.2
> 88.2
> 92.45
> 92.45
> 92.45
> 96.8
> 101.25
> 105.8
> 110.45 125
> 130.05
> 130.05
> 135.2
> 140.45
> 140.45
> 145.8
> 145.8
> 145.8
> 156.8
> 162.45
> 162.45
> 162.45 180 180
> 198.45
> 204.8
> 204.8
> 224.45
> 231.2
> 231.2
> 231.2
> 231.2
> 238.05
> 238.05
> 259.2 320 320
> 328.05
> 344.45
> 352.8
> 352.8
> 361.25
> 369.8
> 387.2
> 387.2
> 423.2
> 423.2
> 432.45
> 451.25
> 460.8
> 470.45
> 470.45
> 490.05
> 490.05

Anybody who maybe has an idea?




Visual Basic: Slot machine values all return the same values

I have attempted to create a simple slot machine in visual basic windows form creator. Here is my code so far:

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim List1 = New String() {"Banana", "Cherry", "Watermelon", "Bell", "Skull", "Apricot"}
        Dim List2 = New String() {"Banana", "Cherry", "Watermelon", "Bell", "Skull", "Apricot"}
        Dim List3 = New String() {"Banana", "Cherry", "Watermelon", "Bell", "Skull", "Apricot"}
        Dim rn1 = New Random()
        Dim rn2 = New Random()
        Dim rn3 = New Random()
        Dim x As Integer = 0
        While x < 30
            Dim Choice = List1(rn1.Next(0, List1.Count))
            Dim Choice2 = List2(rn2.Next(0, List2.Count))
            Dim Choice3 = List3(rn3.Next(0, List3.Count))

            Select Case Choice
                Case "Banana"
                    Slot1.Image = Fruit_Machine.My.Resources.Resources.Banana
                Case "Cherry"
                    Slot1.Image = Fruit_Machine.My.Resources.Resources.Cherry
                Case "Watermelon"
                    Slot1.Image = Fruit_Machine.My.Resources.Resources.Watermelon
                Case "Skull"
                    Slot1.Image = Fruit_Machine.My.Resources.Resources.Skull
                Case "Apricot"
                    Slot1.Image = Fruit_Machine.My.Resources.Resources.Apricot
                Case "Bell"
                    Slot1.Image = Fruit_Machine.My.Resources.Resources.Bell
            End Select
            Select Case Choice2
                Case "Banana"
                    Slot2.Image = Fruit_Machine.My.Resources.Resources.Banana
                Case "Cherry"
                    Slot2.Image = Fruit_Machine.My.Resources.Resources.Cherry
                Case "Watermelon"
                    Slot2.Image = Fruit_Machine.My.Resources.Resources.Watermelon
                Case "Skull"
                    Slot2.Image = Fruit_Machine.My.Resources.Resources.Skull
                Case "Apricot"
                    Slot2.Image = Fruit_Machine.My.Resources.Resources.Apricot
                Case "Bell"
                    Slot2.Image = Fruit_Machine.My.Resources.Resources.Bell
            End Select
            Select Case Choice3
                Case "Banana"
                    Slot3.Image = Fruit_Machine.My.Resources.Resources.Banana
                Case "Cherry"
                    Slot3.Image = Fruit_Machine.My.Resources.Resources.Cherry
                Case "Watermelon"
                    Slot3.Image = Fruit_Machine.My.Resources.Resources.Watermelon
                Case "Skull"
                    Slot3.Image = Fruit_Machine.My.Resources.Resources.Skull
                Case "Apricot"
                    Slot3.Image = Fruit_Machine.My.Resources.Resources.Apricot
                Case "Bell"
                    Slot3.Image = Fruit_Machine.My.Resources.Resources.Bell
            End Select

            x = x + 1
            Application.DoEvents()
        End While
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    End Sub
End Class

This does work: each outcome of the slot machine is randomised... to an extent. I am aware that the code is overcomplicated but this is simply a test project and nothing that anyone else is going to see. Being new to VB I understand that this code is probably... messy. However, the main issue arises when the results of the fruit machine show that all 3 slots are the same value. I.E.

This displays that the result is all 3 skulls

I need a solution to this. Any ideas?




Biased random number generator function in C

Trying to create the following function in C:

bool randBool(double bias)

which returns either 0 or 1 randomly.

The part that is tripping me up is that I would like to allow for the user to input a "bias" in the range [-1.0, 1.0], which represents the likelihood that the output will be 0 or 1.

Here are a few examples of how the inputted bias should influence the function:

=======================================================

randBool(-1.0) should return 0 100% of the time.

randBool(1.0) should return 1 100% of the time.

randBool(-0.5) is 50% more likely to return 0 than 1.

randBool(0.05) is 5% more likely to return 1 than 0.

randBool(0.0) is no more likely to return 0 than 1.

=======================================================

I am almost certain that this is a probability problem, but I am not so familiar with the topic, so I am stumped on how to implement this function.




Generating a random real number between 100 and 200 using the random function in Python [duplicate]

This question already has an answer here:

How can I generate a random real number between 100 and 200 using the random function in Python? The default range is 0-1




Why do I get this particular color pattern when using rand()?

I tried to create a bmp file, like this:

 uint8_t raw_r[pixel_width][pixel_height];
 uint8_t raw_g[pixel_width][pixel_height];
 uint8_t raw_b[pixel_width][pixel_height];
 uint8_t blue(uint32_t x, uint32_t y)
 {
     return (rand()%2)? (x+y)%rand() : ((x*y%1024)%rand())%2 ? (x-y)%rand() : rand();
 }
 uint8_t green(uint32_t x, uint32_t y)
 {
     return (rand()%2)? (x-y)%rand() : ((x*y%1024)%rand())%2 ? (x+y)%rand() : rand();
 }
 uint8_t red(uint32_t x, uint32_t y)
 {
     return (rand()%2)? (y-x)%rand() : ((x*y%1024)%rand())%2 ? (x+y)%rand() : rand();
 }

 for (y=0; y<pixel_height; ++y)
 {
     for (x=0; x<pixel_width; ++x)
     {
         raw_b[x][y]=blue(x, y);
         raw_g[x][y]=green(x, y);
         raw_r[x][y]=red(x, y);
     }
 }

I expected to get something random (white noise). However, the output is interesting:

enter image description here

Do you know the reason why?


Now, it is clear that it has nothing to do with rand(). Also try this code:

for (x=0; x<pixel_width; ++x)
         for (y=0; y<pixel_height; ++y)
         {
             r[x][y] = (x+y);
             g[x][y] = (y-x);
             /* b[x][y] = rand()%2? x : y; */
         }

enter image description here




How to implement Random.nextDouble() in javascript?

I am using Math.floor((Math.random() * max-min)+min) for random number generation, what is the difference between this function and random.nextDouble() ? How to implement random.nextDouble in Javascript?




dimanche 23 septembre 2018

initializing two different random variables at the same time

I am writing a script using 'java.util.Random' and I am trying to initialize two random variables for the same println but it only works if I comment out one of the variables. Here is the code where my problem is:

Random a = new Random();
        date = a.nextInt(29) + 1;
        year = a.nextInt(2019 - 2044)+ 1;

        System.out.println("The best day of your life will be on " + month +       " " + date + ","+ " " + year + ".....give or take.\n");
        System.out.println("Which date of the month do you believe is your   luckiest?");

I can't figure out how to initialize 'date' and 'year' at the same time. Any help is appreciated.




Bernoulli sampling in Excel with different row weights

This is probably both an excel question as well as a statistical question.

Say I have the following data:

enter image description here

What I need to do is generate a column 'Assigned' (column C) which is an indicator whether a customer has been assigned to a program or not. The probability of a customer being assigned to the program is, let's say, 0.4.

BUT the complication is that the customers in column A are a sample, based on different strata, and so each customer represents one or more customers, as identified in column B. So Customer A is worth a single customer in the population, while customer B is worth 4 customers in the population.

How do I randomly sample across this 'weighted' set of customers so that on the whole there is a 40% chance that a single customer in the population be assigned to the program?

Thanks all!




run only one java method at random

okay, so I have to run a java program that generates a random tetronimo. I have the code for all seven stored inside separate methods. `public class TetrisComponent extends JComponent{

public void paintComponent(Graphics g){ Graphics2D g2 = (Graphics2D)g;

    Rectangle2D.Double i = new Rectangle2D.Double(0, 100, 50, 50);
    g2.setColor(Color.black);
    g2.draw(i);
    g2.setColor(Color.CYAN);
    g2.fill(i);

    Rectangle2D.Double i2 = new Rectangle2D.Double(50, 100, 50, 50);
    g2.setColor(Color.black);
    g2.draw(i2);
    g2.setColor(Color.CYAN);
    g2.fill(i2);

    Rectangle2D.Double i3 = new Rectangle2D.Double(100, 100, 50, 50);
    g2.setColor(Color.black);
    g2.draw(i3);
    g2.setColor(Color.CYAN);
    g2.fill(i3);

    Rectangle2D.Double i4 = new Rectangle2D.Double(150, 100, 50, 50);
    g2.setColor(Color.black);
    g2.draw(i4);
    g2.setColor(Color.CYAN);
    g2.fill(i4);
    }

public void paintComponentj(Graphics g){
        Graphics2D g2 = (Graphics2D)g;

    Rectangle2D.Double j = new Rectangle2D.Double(200, 500, 50, 50);
    g2.setColor(Color.black);
    g2.draw(j);
    g2.setColor(Color.blue);
    g2.fill(j);

    Rectangle2D.Double j2 = new Rectangle2D.Double(250, 500, 50, 50);
    g2.setColor(Color.black);
    g2.draw(j2);
    g2.setColor(Color.blue);
    g2.fill(j2);

    Rectangle2D.Double j3 = new Rectangle2D.Double(300, 500, 50, 50);
    g2.setColor(Color.black);
    g2.draw(j3);
    g2.setColor(Color.blue);
    g2.fill(j3);

    Rectangle2D.Double j4 = new Rectangle2D.Double(300, 550, 50, 50);
    g2.setColor(Color.black);
    g2.draw(j4);
    g2.setColor(Color.blue);
    g2.fill(j4);
    }`

so how would i run this program (I have a separate TetrisViewer class) to either run only the painComponent method or painComponentj method, but at random? Is there even a way to do that?




Python list, array,random

I have two separate arrays one called nList which contains the name of players and a second array called pList which has an array size of 5. pList will randomly generate numbers 1-5 to fill the array without making any duplicates. shown below. How do I put the players into new array with the player with position 1 at the start of the array.

Player a Postition [5]
Player b Postition [3]
Player c Postition [1]
Player e Postition [2]
Player f Postition [4]




Generating different numbers in Python

How can I generate different random numbers from 1 to 49 for my bingo-like program? I was thinking about creating empty array and filling it with numbers if they are different from the ones that are already in array but I'm having trouble making that. How could I do that and is there an easier way of doing this.




Why this program works without functions but with them it doesn't?

This generate well slots in the array (eg. arr[0] =753, [1] = 324, [2] = 876)

int main(void){
// Introducing the 'n' number, the max number in the array
int num;
cout << "Introduce the quantity of random numbers between 100 and 999\nNumber: "; cin >> num;
int arr[num];

// Generating random numbers for the i's slots in the array
srand(time(0));

// Filling the array
for(int i = 0; i < num; i++)
    arr[i] = (rand() % 900) + 100;

// Printing the array
for(int i = 0; i < num; i++)
    printf("item [%i] = %i\n", i, arr[i]);}

But this one generates things like arr[0] = 9, [1] = 425345, [2] = 0, [3] = 324, [4] = 48, [5] = 232424 But just when I put a n >= 8, from 1 to 7 works, but with 8 or higher it doesn't work

void randomArray(int size)
{
int arr[size];

// Generating random numbers for the i's slots in the array
srand(time(0));

for(int i = 0; i < size; i++)
    arr[i] = (rand() % 900) + 100;

}

void printArray(int size)
{
int arr[size];

for(int i = 0; i < size; i++)
    printf("item [%i] = %i\n", i, arr[i]);
}

int main(void)
{
// Introducing the 'n' number, the max number in the array
int num;
cout << "Introduce the quantity of random numbers between 100 and 999\nNumber: "; cin >> num;
int arr[num];


srand(time(0));

// Filling the array
randomArray(num);

// Printing the array
printArray(num);}




Why is random number generation from a kernel distribution up to 1000x slower if truncated?

I would prefer to truncate my Distribution, but at the moment it is simply not possible given the time penalty.

Standard Kernel Distribution:

expectation=fitdist(BTS,'kernel');

Result:

tic;expectation.random(10000,1);toc;
Elapsed time is 0.000745 seconds.

Truncate Code:

Exp{i,j}=truncate(expectation,min(BTS)-1,max(BTS)+1);

Result:

tic;random(Exp{i,j},1,10000);toc
Elapsed time is 0.772295 seconds.




How to generate random numbers of unique modulus values in python

import random
value = 1000
a = []
i = 0
b = [None] * 16
print('value = ',1000)
for x in range(value):
    a.append(x)
    random.Random(4).shuffle(a)
print(a)
for x in range(16):
    b[x] = a[x]
print(b)

This code generate 16 random numbers selected up to the range 1000.But how to generate numbers that has unique modulus values like this in python ?




Generate a random decimal between min and max

How to generate a random System.Decimal between a given min and max (both inclusively) under the following conditions:

  • The distribution should either be uniform w.r.t. the finite number of representable decimals (i.e., each bit pattern representing numbers between min and max is equally likely) OR uniform w.r.t. the continuous number line (i.e., each interval between min and max is equally likely to be hit).
  • The probability for each representable number between min and max should be greater than 0, i.e., the algorithm must not target a subset of the decimal range only.

(I've already read the number one question on the topic here on SO Generating a Random Decimal in C#, also read various articles on the web about decimals, including Jon Skeet's and the .NET docs - they couldn't help me so far)

My current approach is similar to my algorithm for generating a random float/double: I want to somehow get the count of representable bit patterns between min and max (see also my question here), then generate a random number between 0 and count, then map this number back to the bit patterns somehow. Unfortunately, I'm not sure whether the last part of my algorithm is "possible" (i.e., without really enumerating each possible bit pattern between the two).

I hope you guys have some kind of good idea how to do that in a much better way.




make two or more objects and use them in rotation or random in node js

i have config.js file contain :

exports.smtp = {
    host: "smtp.mailtrap.io",
    port: "2525",
    auth: true,
    user: "3295b90cbc8837",
    pass: "x"
};

in another file i nget the smtp element like this :

var smtp = {
    host: config.smtp.host,
    port: config.smtp.port,
    secure: false
};

i need to create multiple smtp object and randomly choose which one to use . example :

exports.smtp = {
    host: "smtp.mailtrap.io",
    port: "2525",
    auth: true,
    user: "3295b90cbc8837",
    pass: "x"
};

exports.smtp = {
    host: "smtp.mailtrap.io",
    port: "2525",
    auth: true,
    user: "3295b90cbc8837",
    pass: "x"
};

between the two objects will be used in rotation .what ways might I do to make it like that?




samedi 22 septembre 2018

I have created difficulty variable but I want a random Difficulty value between two numbers [duplicate]

This question already has an answer here:

I have created Min_difficulty =2; and max difficulty =8; how can I make the program randomly choose difficulty between min and max difficulty.




Leetcode 384 - why does this doesn't work. Is there anything wrong with the random function?

class Solution {

    int[] arr;

    public Solution(int[] nums) {
        this.arr = nums.clone();
    }

    /** Resets the array to its original configuration and return it. */
    public int[] reset() {
        return this.arr;
    }

    /** Returns a random shuffling of the array. */
    public int[] shuffle() {
        int[] arr1 = this.arr.clone();
        for(int i = 0; i < arr1.length; i++){
            int a = (int)(Math.random())*(i+1);
            swap(arr1,i,a);
        }
        return arr1;
    }

    public void swap(int[] arr, int i, int j){
        int temp = arr[i];
        arr[i]=arr[j];
        arr[j]=temp;
    }


}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(nums);
 * int[] param_1 = obj.reset();
 * int[] param_2 = obj.shuffle();
 */

```

Why doesn't this work. It does genereate a random sequence in the shuffle method. For question: https://leetcode.com/problems/shuffle-an-array/description/




php random with foreach function

Hey i have problem how to randomize get only one code to page. Maybe later can be more codes like 10 and i need only one code use to website randomize after restart page or if can for all 10seconds delay to randomize

    foreach($videoList->items as $item){
        if(isset($item->snippet)){
            echo '<img src="'.$item->snippet->thumbnails->default->url.'"/><br /><a href="'.$item->snippet->customUrl.'">'.$item->snippet->title.'</a>';
        }

    }
    foreach($videoChannel->items as $item){
        if(isset($item->snippet)){
            echo '<img src="'.$item->snippet->thumbnails->default->url.'"/><br /><a href="'.$item->snippet->customUrl.'">'.$item->snippet->title.'</a>';
        }

    }




PostgreSQL Get random value between two timestamps with hours constraint

Using: PostgreSQL 10.5

This question is somewhat similar to:

PostgreSQL Get a random datetime/timestamp between two datetime/timestamp

The answer given by @pozs solves the problem but doesn't let me constraint the hours within random timestamp returned.

Task

The difference is that I need to get a random timestamp between two timestamps, but the hour in the output value has to be between 10:00:00 and 18:00:00.

My attempt

I've been trying to do it time efficiently, but for now have only come up with the idea of storing different parts of: date, time and miliseconds and then combining them with 3 selects using ORDER BY random() LIMIT 1. This is, however, far from a fast solution.

tmp_data holds dates, tmp_time holds time and tmp_ms holds miliseconds, which I add together using a function to get proper output:

  (SELECT data FROM tmp_data ORDER BY random() LIMIT 1) 
+ (SELECT czas FROM tmp_time WHERE czas BETWEEN '10:00:00' AND '18:00:00' ORDER BY random() LIMIT 1) 
+ (SELECT ms FROM tmp_ms ORDER BY random() LIMIT 1)

This get's the job done, but requires some time due to 3 selects with sorting (and it will need to be computed for every row).

Sample data / Explanation

Given time constraints of:

  • start_timestamp => 2016-01-01 10:00:00
  • end_timestamp => 2017-12-31 18:00:00

Let's generate random timestamp in terms of every part but hour (hour has to be between 10 and 18).

Sample output - randomly generated

 2016-09-12 11:54:59.4919
 2016-01-10 10:39:03.626985
 2016-01-03 15:58:19.599016
 2016-04-11 10:05:07.527829
 2016-07-04 12:57:33.125333
 2017-12-15 14:17:46.975731
 2016-10-04 16:55:01.701048
 2016-09-26 13:36:59.71145
 2017-09-06 17:25:09.426963
 2016-09-08 17:08:00.917743

Each hour here is between 10 and 18, but every other part of the timestamp is random.




What is a real life example of The Las Vegas Algorithm?

I understand the Algorithm but can't seem to find how it's implemented in real life? Anyone have any examples for a better understanding?




MATLAB — How to eliminate equal matrices that are created randomly inside loop?

The code segment I'm working on is given below:

 NphaseSteps = 6;
 phases = exp( 2*pi*1i * (0:(NphaseSteps-1))/NphaseSteps );
 i = 1;
 while i <= 10  %number of iterations
     ind = randi([1 NphaseSteps],10,10);
     inField{i} = phases(ind);
     save('inField.mat', 'inField')
     i = i + 1;
 end

Now, what I want is to keep track of these randomly created matrices "inField{i}" and eliminate the ones that are equal to each other. I know that I can use "if" condition but since I'm new to programming I don't know how to use it more efficiently so that it doesn't take too much time. So, I need your help for a fast working program that does the job. Thanks in advance.




tensorflow distribute integers according to probabilities

I would like to distribute an integer for example 20, into four parts following the probability for each part:p=[0.02,0.5,0.3,0.18]

The corresponding python code is:

frequency=np.random.choice([1,2,3,4],20,p=[0.02,0.5,0.3,0.18])
from collections import Counter
Counter(frequency)

# Out[86]:
# Counter({1: 1, 2: 9, 3: 8, 4: 2})

However, I have over 1e6~ many parts that I would like to use tensorflow gpu to conquer this issue. Does anyone know how to do this?




Generating Predictable Secure Random Numbers

How can I instantiate a predictable and secure random number generator which will generate consistent random numbers across Java versions and operating systems?

The following code used to work in Java 8 but no longer works in Java 10:

import java.security.SecureRandom;

public class PredictableRandom {

public static void main(String[] args) {
    PredictableRandom predictableRandom = new PredictableRandom();
    predictableRandom.execute();
}

private void execute() {
    SecureRandom secureRandom = new SecureRandom();
    System.out.println(secureRandom.getAlgorithm());
    System.out.println(secureRandom.getProvider());
    long seed = 12345678L;
    secureRandom.setSeed(seed);
    System.out.println(secureRandom.nextLong());
    SecureRandom secureRandom2 = new SecureRandom();
    secureRandom2.setSeed(seed);
    System.out.println(secureRandom2.nextLong());
}
}

In Java 8 - good, different random objects generate the same random number:

SHA1PRNG
SUN version 1.8
3325995872096263519
3325995872096263519

In Java 10 - bad, different random objects generate different random number:

DRBG
SUN version 10
-3526685326322256981
-2373261409119309182




How to generate a random dice roll in Rust?

How you I generate a random dice roll in Rust?

I know I can use rand::random, but that requires I want to generate a value of an integer type. Using rand::random<u8>() % 6 introduces a bias.




vendredi 21 septembre 2018

Why rand() call considered as potentially dangerous

I have been using rand() function to generate random numbers. When I checked my code through a CWE check tool, It is considering rand() as a potentially dangerous function and suggesting to use crypto libraries. Can anyone please elaborate it? What is the best and secure alternative to generate random numbers




Issues using a variable to get a image in batch

I was trying to make a batch file that would create a random number between 1 and 13 and get the file called "[random number].jpg", but it isn't working.

The code:

`SET /A rand=%RANDOM% * 13 / 32768 + 1
IF NOT EXIST "IMGS\%rand%.jpg" (
    ECHO ERR: File " %rand%.jpg " not found
    pause
    EXIT
)`

The output: ERR: File " 6.jpg " not found

Any thoughts on why it's doing this?




How can I filter/sort to pick the most relevant samples in R?

I am new to R and just finished basic courses. I am trying to do some statistical and interesting findings on golf shots (whether it's the ball speed, or distance). However the test sample for those players' skills vary so I see a lot of outlier data which really might not contribute a lot of the analysis. My ultimate goal is to see a trend in player's historical shot data/consistency and a possible cause of performance change.

If I were to have 1000 shots, how would I be able to sort them to ensure that I'm capturing solidly hit shots (whether I put that range manually by myself or what not) so that I can get rid of the outliers?

For example, if I have 1000 shots of the following parameters: Ball Speed, Launch Angle, Launch Direction, Ball Spin, Carry Distance, Impact Point and whatever the center struck shots that went far enough should only be counted (i.e. by pulling out Impact Point and Carry distance), what would be the code to do that?

Or just making sure regardless of the parameters, can I make R to handpick the best shots that had really good parameters overall for each shot?

Thank you.




Why I got pattern with rand()?

I tried to create a bmp file, like this:

 uint8_t raw_r[pixel_width][pixel_height];
 uint8_t raw_g[pixel_width][pixel_height];
 uint8_t raw_b[pixel_width][pixel_height];
 uint8_t blue(uint32_t x, uint32_t y)
 {
     return (rand()%2)? (x+y)%rand() : ((x*y%1024)%rand())%2 ? (x-y)%rand() : rand();
 }
 uint8_t green(uint32_t x, uint32_t y)
 {
     return (rand()%2)? (x-y)%rand() : ((x*y%1024)%rand())%2 ? (x+y)%rand() : rand();
 }
 uint8_t red(uint32_t x, uint32_t y)
 {
     return (rand()%2)? (y-x)%rand() : ((x*y%1024)%rand())%2 ? (x+y)%rand() : rand();
 }

 for (y=0; y<pixel_height; ++y)
 {
     for (x=0; x<pixel_width; ++x)
     {
         raw_b[x][y]=blue(x, y);
         raw_g[x][y]=green(x, y);
         raw_r[x][y]=red(x, y);
     }
 }

I excepted to get something random. However, the output is interesting:

enter image description here

Do you know the reason why?




C# execlude numbers from a list in random generation

i am making a tic tac toe game and i am making it to be unbeatable but first i have to let the copmuter know the rules

i'm stack in a step that is => when it's the computer's turn and we have just started the game so no win case so it's up to the coputer the generate a random number that will be the computer choise ( the block where he mark X or O ) so i need it to gennerate a number from 1 to 9 but by excluding the already used blocks ( numbers ) i tried doing that by making a list and adding a number every time the humain player use a block but i can't find a way to use those numbers from the list as exclusion for the random choise of the computer here is what i tried and thnx in advance :

    //random

    List<int> cas = new List<int>();
    if (c1 == true)
    {
        cas.Add(1);
    }
    if (c2 == true)
    {
        cas.Add(2);
    }
    if (c3 == true)
    {
        cas.Add(3);
    }
    if (c4 == true)
    {
        cas.Add(4);
    }
    if (c5 == true)
    {
        cas.Add(5);
    }
    if (c6 == true)
    {
        cas.Add(6);
    }
    if (c7 == true)
    {
        cas.Add(7);
    }
    if (c8 == true)
    {
        cas.Add(8);
    }
    if (c9 == true)
    {
        cas.Add(9);
    }


    for (int i = 0; i < cas.Count; i++)
    {
        random_except_list(cas[]);
    }

public static int random_except_list(int[] x)
{
    Random r = new Random();
    int result = r.Next(1, 9 - );

    for (int i = 0; i < x.Length; i++)
    {
        if (result < x[i])
            return result;
        result++;
    }
    return result;
}




How do i Pick a Random Number from an array in c++? [on hold]

int array[5];
int Random;
for (int i = 0; i <5; i++)
{
    cin>>array[i];
}
for (int j = 0; j < 5; j++)
{
    Random = array[rand() % array[j]];
}
cout << Random << endl;

This is giving me continously return 1 but i want different number every time




What is the difference between Math.round and Math.random and which one is better

Hello i would like to know the differences between :

Math.round(Math.random() * (900000 - 600000)) + 600000;

and

Math.random() * (900000 - 600000) + 600000; 

In my case i would like to get a random number between 600000 ms and 900000 ms.

Can you please tell me which way is the best ?

Best regards




how to end a loop when a random number reaches 0

I'm not great at python and couldn't find a solution that i could understand. I'm trying to get the program to output "random timer has ended" once a random countdown has finished.

import time
from random import randint

RandomTimer = randint(1,10) #picks random number of seconds for countdown
while RandomTimer > 0:
    time.sleep(1)
    RandomTimer - 1  #reduces random number every second until it reaches 0
print("random timer ended")

The code here doesn't work as the countdown never seems to finish, even after 10 seconds. I know there's something i'm doing wrong but can figure it out.




How to predict Rand() function in C?

I try to make oracle which predicts next random number in a sequence. I have an array of random generated numbers.




pass C++ random number distribution to a function

I have looked for similar questions but haven't found them. I want to generate normally distributed random numbers. I used to code C and some C++98 but am now trying to go back and learn C++11.

I have a function to return a seeded RNG

auto seeded_rng () {
      ....  //do seeding.
     std::default_random_engine Eng(/*seeds*/);
     return Eng;
}

In my main function I bind the RNG to say a gaussian distribution

auto binded = std::bind(std::normal_distribution{0,1.0},seeded_rng);

This function works fine. I can call "binded()" directly in main and it generates the numbers

I want to have a simulation object that needs random numbers to be created. My question related to how to pass in the "RNG_PART" below.

class sim
{
public:
       sim( RNG_PART & rng, int_number_of sims ){ /* Do whatever */}
}

So if in main, I then want to create a simulation object

sim A(binded, 100);

it complains. I tried declaring

sim::sim(std::default_random_engine &rng, int number_of_sims){}

but it is complaining. What type should I use to pass in the "binded" distribution to the constructor? Or am I going about this completely incorrectly. Should I just declare the RNG engine globally? I'd prefer not to do that.

Apologies if this is very basic!