lundi 31 mai 2021

Issue on passwd generator

I have issue with a code for generate password (code below)

from random import randint, choice

alphabet_min = [chr(i) for i in range(97, 123)]
alphabet_maj = [chr(i) for i in range(65, 91)]
chiffre = [chr(i) for i in range(48, 58)]
carac_spec = [chr(i) for i in range(33, 48)]


def pwd(n, min1=True, maj=True, chif= True, cs=True):
    alphabets = dict()
    key = 0
    if min1:
        alphabets[key] = alphabet_min
        key += 1
    if maj:
        alphabets[key] = alphabet_maj
        key += 1
    if chif:
        alphabets[key] = chiffre
        key += 1
    if cs:
        alphabets[key] = carac_spec
        key += 1

    mdp = ' '
    for i in range(n):
        clef = randint(0, key - 1)
        mdp += choice(alphabets[clef])

    return mdp

When I execute this, nothing appear

Code finding on internet and very beginner in Python code.

Anyone have an idea of the issue ?




Fast random/mutation algorithms (vector to vector)

I have been trying to create some very detailed procedural terrain recently and this has lead me to want to make my own custom noise functions. To do this at the centre I need a reliable random number generator and I was curious about what the most specialised algorithms for my use case is and how I can implement a version of it.

Essentially all I want is an algorithm that can take in a given string of data, of a predetermined size, say a vector, and output a different, random seeming string of data, again of a predetermined variant size.

The algorithm should be seedable and deterministic, and it's output shouldn't decay or produce any kind of bias or obvious looking pattern. basically it needs to be fairly robust when it comes to producing neat results for noise.

beyond this, my priority is speed, the fastest algorithm that can achieve these goals is the ideal. if you know of anything that can do this please let me know :)




Rand() always give the same number in C

I am new in C and I am making a simple code to get a random number. I tried to make a game More or less (random number and the player write a number) but when I launch the code in the terminal I always get the same number. Is that normal ? And if not, how can I repair that ?

#include <stdio.h>
#include <stdlib.h>
int main() {
    int essais = 10;
    int secret;
    int number;
    int win = 0;
    secret = rand()%100;
    while (essais > 0 && win != 1){
        printf("Quel est le nombre secret ? \n");
        scanf("%d",&number);
        if (number == secret){
            printf("Gagné !\n");
            win++;
        }
        else if (number < secret) {
            printf("Non c'est plus :/\n");
            essais--;
            printf("Il vous reste %d essais\n",essais);
        }
        else{
            printf("Non c'est moins :/\n");
            essais--;
            printf("Il vous reste %d essais\n",essais);
        }
        if (essais == 0)
            printf("Vous n'avez plus d'essais :(, vous aurez plus de chance la prochaine fois. Le nombre était %d",secret);
    }
}

PS : Sorry I am French so I wrote the code and the messages in French but the problem doesn't come here




Randomly select two items from an array and then remove them from the array, and randomly select one item from two already randomly selected items c# [duplicate]

I know this has probably been asked before but all the answers i could find i didn't know how to apply to my code.

here is my code

string[] teams = { "Team 1", "Team 2", "Team 3", "Team 4", "Team 5", "Team 6", "Team 7", "Team 8" };
        Console.WriteLine("The available teams are: ");
        for (int i = 0; i < teams.Length; i++)

        {
            Console.WriteLine(teams[i]);
        }

        Random rnd1 = new Random();
        int r1 = rnd1.Next(teams.Length);
        Random rnd2 = new Random();
        int r2 = rnd2.Next(teams.Length);
        Console.WriteLine("Round 1: " + teams[r1] + " vs " + teams[r2]);

How can I make it so that the two teams will always be different, and so that I can do a Round 2 which will be another two different teams.

Another thing that I need to do is to make it so that when the two teams are picked for a round (let's say it's Team 3 and Team 7) to randomly select out of those two teams so i can decide a winner. I've tried a bunch of things and none of it worked, I mostly need help with the first problem but if anyone can help with the second one as well that'd be appreciated




Generate random answers for each button in Javascript / JQuery

I have been pouring over answers on stack overflow for my problem. All of them have resulted in infinite loops which have caused my code to crash several times. Let me start by saying I am a beginner. I'd also like to iterate that for my current project I have to use Javascript/JQuery as requested. I am creating a math quiz game that generates random equations. Along with the random equations I would like to generate random answers. I have the random equations and answers generated, but for some reason I can't get my quiz app to generate unique random answers without crashing. I have tried populating the array first, then sorting the array, and splicing out duplicates and reiterating through the array. I have also tried to check for duplicates before the random number is populated in the array. None seem to work. I know there are similar questions to mine, and they work when NOT incorporated in my code. I think I'm going about it the wrong way, in which case I'd love for a second pair of eyes. Thanks!

let a, b, op, correctAnswer, ansb;

const novice = () => {
    const num = () => ~~(Math.random() * 10) + 1
    a = num()
    b = num()
    op = ["*", "+", "/", "-"][Math.floor(Math.random() * 4)];
    $("#question").text(`${a} ${op} ${b}`).show()
    correctAnswer = (() => {
        switch (op) {
            case "*": return a * b
            case "+": return a + b
            case "/": return a / b
            case "-": return a - b
        }
    })()
    if (!Number.isInteger(correctAnswer)) {
        novice()
        // equations.pop()
    }
    let randomAnswers = [correctAnswer]
    for (let x = 0; randomAnswers.length < 4; x++) {
        // ! i need to sort the array after its already pushed in there??
        let rand = Math.floor(Math.random() * correctAnswer + 20)
        // randomAnswers.push(rand)
        // console.log(randomAnswers.indexOf(x), randomAnswers.lastIndexOf(x))
        // if (randomAnswers.indexOf(rand) !== randomAnswers.indexOf(x)) {
        randomAnswers.push(rand)
        // }
    }
    let randAnsw = randomAnswers.sort(() => Math.random() - 0.5)
    $("#a0").text(randAnsw[0]).attr("value", `${randAnsw[0]}`)
    $("#a1").text(randAnsw[1]).attr("value", `${randAnsw[1]}`)
    $("#a2").text(randAnsw[2]).attr("value", `${randAnsw[2]}`)
    $("#a3").text(randAnsw[3]).attr("value", `${randAnsw[3]}`)
}

// const nextNov = () => {
//     novice()
//     selectNovAnswer()
// }
// const selectNovAnswer = () => {
//     $('#answer-buttons .btn').each(function () {
//         $(this).unbind("click").on("click", function () {
//             if ($(this).attr("value") == correctAnswer) {
//                 NextNov()
//             } else {
//                 // startOver()
//                 // $(".answ").attr("disabled", 'disabled')
//                 $("#question").append(`<span class="text-danger"> = ${correctAnswer}</span>`)

//             }
//         })
//     })
// }

$("#start").on("click", function () {
    novice()
    // selectNovAnswer()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fast Math Example</title>
    <link rel="stylesheet" href="bootstrap-4.5.3-dist/css/bootstrap.min.css">
</head>

<body>
    <button id="start" type="button">Start</button>
    <h1 id="question"></h1>
    <div id="answer-buttons">
        <button id="a0" class="btn" type="button"></button>
        <button id="a1" class="btn" type="button"></button>
        <button id="a2" class="btn" type="button"></button>
        <button id="a3" class="btn" type="button"></button>
    </div>


    <script src="jquery-3.6.0.min.js"></script>
    <script src="bootstrap-4.5.3-dist/js/bootstrap.min.js"></script>
    <script src="index.js"></script>
</body>

</html>



"Constant expression contains invalid operations" when initialize variable laravel [duplicate]

When I initialize a global variable with rand(), get this error on rand():

Constant expression contains invalid operations

This is my code:

class registerController extends Controller {

public $conto = rand(100,999);

public function create()
{ 
 ...
 $conto = $this->conto;
 ...    
}
public function countErrors() 
{
...
$conto = $this->conto;
}



Generating random/synthetic queries(around 10000 queries) at once based on Database

I have an IMDB database for which I need to generate synthetic queries(around 10000 queries) at once, for training my model, Is there any way to do that?




SAS: create covariance matrix with variables

I am working on a project in which we have to do some simulations. I am now at the point I want to use the RandNormal function, to generate multivariate normal data given a vector of means and a covariance matrix. For the covariance matrix, we have to use different parameters, so instead of putting the values in directly, I want to just put the variable name in the matrix (so we do not have to do the calculations by hand).

We get this error: ERROR: (execution) Character argument should be numeric. And this is our code. The dataset Simulatie also contains the variables defined in this proc iml.

proc iml;
use Simulatie;
read all;
close Simulatie;
sigma0sq = 2;
sigma1sq = 3;
sigma2sq = 1;
sigma0 = sqrt(sigma0sq);
sigma1 = sqrt(sigma1sq);
sigma2 = sqrt(sigma2sq);
rhoM = 0.7;
rhoV = 0.5;
rhoMsigma0sigma1 = rhoM*sigma0*sigma1;
rhoVsigma0sigma2 = rhoV*sigma0*sigma2;
rhoVsigma1sigma2 = rhoV*sigma1*sigma2;
Mean = {0, 0, 0}; /* population means */
Cov= {sigma0sq rhoMsigma0sigma1 rhoVsigma0sigma2, /* population covariances */
rhoMsigma0sigma1 sigma1sq rhoVsigma1sigma2,
rhoVsigma0sigma2 rhoVsigma1sigma2 sigma2sq};
N = 185; /* sample size */
call randseed(123);
X = RandNormal(N, Mean, Cov); /*x is a nx3 matrix */
SampleMean= mean(X);
SampleCov= cov(X);
quit;

We tried putting in for instance

Cov= {3 2 1, 2 4 0,1 0 5};

Which works perfectly nice, but when we change it to variable names, it gets an error. We did some googling but couldn't find the solution, could anyone help us out :) It seems like such a silly, easy-to-fix error, but we just don't succeed!

Thanks in advance.




How to make Python random.randrange more efficient to generate large range random number

Code to generate random integer

for i in range(10):
   count = 0
   dict = {}

   while count < 10000000:
      rnd = random.randrange(0, 7800000000)
      rndlen = len(str(rnd))
      if rndlen in dict:
         dict[rndlen] += 1
      else:
         dict[rndlen] = 1
      count += 1
        
   print(dict)

Results generated

{10: 8717806, 9: 1154071, 8: 115280, 6: 1133, 7: 11573, 5: 122, 4: 14, 3: 1}
{10: 8717846, 9: 1153444, 8: 115856, 7: 11615, 6: 1122, 5: 110, 4: 5, 3: 1, 2: 1}
{10: 8718446, 9: 1153425, 8: 115151, 7: 11667, 6: 1201, 5: 101, 4: 9}
{10: 8717658, 9: 1153838, 7: 11581, 8: 115641, 5: 114, 6: 1156, 4: 11, 3: 1}
{9: 1153775, 10: 8717832, 8: 115572, 7: 11556, 6: 1134, 5: 121, 4: 9, 3: 1}
{10: 8718564, 9: 1153704, 8: 115002, 7: 11498, 6: 1115, 5: 105, 4: 11, 3: 1}
{10: 8718322, 9: 1153617, 8: 115128, 7: 11590, 6: 1217, 5: 115, 4: 11}
{10: 8718181, 9: 1153681, 7: 11554, 8: 115270, 6: 1177, 5: 128, 4: 8, 3: 1}
{9: 1151777, 10: 8720590, 8: 115017, 7: 11333, 6: 1159, 5: 113, 4: 10, 3: 1}
{10: 8717127, 9: 1154596, 8: 115344, 7: 11591, 6: 1230, 5: 100, 4: 11, 3: 1}

The results show that the random integer generated more toward the max value instead of min value, ~87% on max value, less than 1% is near to min value.

How to solve this issue to generate a fair random range?




I want to do a random search on an array of size N

I need help fixing my code below. I want to do a random search on an array of size N. random search randomly picks up an integer from arr to compare; And the process repeats until the integer it is looking for is found (again it is remarked that the membership is guaranteed, otherwise random search obviously can enter an infinite loop). How do I search for the searchValue using random search?

public void randomSearch() {
  
  counter =new int[N];                    // Reset the counter
 
  int stepsTotal = 0;                    // Total number of steps/comparisons
  
  for (int i = 0; i < N; i++) {          // Comparison for all N from 0 to N-1
     int steps = 0;
     int searchValue = i;                // using i as our search value to check membership
        for (int j = 0; j < N; j++) {
           j = (int)(Math.random()*N);   // generate a random number from 0 to N-1
           steps++;                       // increment the steps for each record comparison    
           counter[j]++;                 // increment the number of records stored in the array       
           if (arr[j] != searchValue) {  // if the records are found in the array
            break;                       // found
           }
         }



Capitalize random letters of a string in PHP

I want to capitalize random letters in a string and echo the complete sentence from hello69.world to HeLlO69.WoRlD. Each time the functions run, it should capitalize random letters and exclude special characters and digits. I've tried this so far but it only selects the first 5 characters in string every time and outputs only Capitalized letters. How to fix this?

<?php
 $string = "hellohg.09ui8vkosjbdh";

    $selchr = substr($string,0, 5);
    $caps = strtoupper($selchr);
    echo substr_replace($string, $caps,0);
?>



dimanche 30 mai 2021

Time testing code issues for sorting methods with random numbers [duplicate]

I have working code for sort methods with time analysis code in the end, but when I put my random number generator code in the method call instead of the default assign int[] list = {9,1,8,2,7,3,6,4,5}; I get an error - Type mismatch: cannot convert from ArrayList to int[]." I tried changing generateRandomList to return an array but still get same error, then I tried changing every "array" to "list" in the InsertSort class, and still get the same error in the timing code "Type mismatch: cannot convert from ArrayList to int[], then presuming I have to change from arraylist to list in the Random class, but then when I do so for the Random class I get the error "Cannot instantiate the type List". Hopefully someone can show me what I'm doing wrong and help me fix this. Also, is the timing part done right? It doesn't seem like it should take that long, when I run I get something like 69391841667800 nanoseconds.

Here is my code for InsertSort timing analysis (InsertTime) -

public class InsertTime {
private int[] arr;
public InsertTime(int[] array) {
arr = array;
}
private boolean more(int value1, int value2)
{
return value1 > value2;
}
public void sort()
{
int size = arr.length;
int temp,j;
for(int i=1; i<size; i++)
{temp=arr[i];
for(j=i; j>0 && more(arr[j-1], temp); j--)
{
arr[j]=arr[j-1];
}
arr[j]=temp;
}
}
public static void main(String[] args)
{
    int[] array = Random.generateRandomList(5, 1, 10);
InsertSort bs = new InsertSort(array);
bs.sort();
for(int i=0;i<array.length ;i++)
{
System.out.print(array[i] + " ");
}
long endTime = System.nanoTime(); //Current system Time at end

long startTime = 0;
long duration = (endTime - startTime); //divide by 1000000 to get milliseconds.

System.out.print(duration);
}
}

This is my code for Random -

import java.util.ArrayList;

public class Random {

public static void main(String[] args)
{
    System.out.println(generateRandomList(5, 1, 10));
}

public static ArrayList<Integer> generateRandomList( int size, int min, int max) {
    ArrayList<Integer> list;
    list = new ArrayList<>();
    for(int i=0;i<size;i++) {
        int n = (int)(Math.random() * (max-min))+min;
        list.add(n);
    }
    return list;
}

}



Simulating a dice throw with threadlocalrandom does not converge to the expected value

I was trying to verify the expected value formula in java.
I did something very trivial, I simulated the roll of a dice, but I mapped each side to a specific value. So each value has probability of 1/6.
The expected value was determined as: 232.65
I run the dice simulation a very long number of runs, 10000000 to be precise but the number did not converge to 232.65 but was 232.74. Smaller runs also were fluxuating up to the value 233.97. Runs up to 2100000000gave 232.63.
So I am wondering if I am doing something wrong. My main premise here is that I shouldn't need to simulate 2 billion throws of a dice to eventually the expected value calculated via the formula.
So I am wondering if I am using the wrong random API. I can not get the seed so I can't verify if that changes per iteration. My code is the following:

Map<Integer, Float> map = new HashMap<>();
map.put(1, 17.2f);
map.put(2, 11f);
map.put(3, 128f);
map.put(4, 1f);
map.put(5, 1200f);
map.put(6, 38.7f);

double sum = 0;
int count = 0;

for(Map.Entry<Integer, Float> entry: map.entrySet()) {
     sum += (entry.getValue() * (1/6f));
}

System.out.println("EV " + sum);
sum = 0;

for(int j = 0; j < 2100000000; j++) {
    int dice = ThreadLocalRandom.current().nextInt(1, 7);
    sum += map.get(dice);
    ++count;
}
System.out.println(sum / count);

Output:

EV 232.65000109374523
232.63201358102154

I was expected after a much earlier number of runs I would consistently get something ~232.650...




Generating random number. How can I ensure no duplictes?

I'm writing an inventory application .For each entry, I need a random number generated as a ID for the transaction. Right now I have the following code:

Randomize 10
     newIDnum = Int(Rnd * 1000000)

I have a validation built in for if a duplicate gets added I get alerted, and from time to time I get such an alert.

I wanted to bring up the problem here to make sure I'm using this correctly for the intended outcome. I understand little about seeds and where the CPU gets the info to generate a random number (I understand its not truly random, but that's as far as I know). Simply I just need to make sure that no duplicate values are generated, or at least that I minimize the probability as low as possible.

Thank you!




Multiple Samples Without Replacement in R

I have a data set of roughly 20000 customers and some assorted indicator variables. I am trying to create 20 groups of 1000 unique customers. My original thought was to take 20 samples without replacement but I am finding it difficult to repeatedly sample. This is the code I initially thought about but it requires me to repeat this process 20 times which seems very clunky. Does anyone have thoughts about an easier way to create subsets of the data with no replacement.

set.seed(1)

sample1<-sample(fullindicators$customer_id,1000,replace=FALSE)

fullindicators$customer_id<-fullindicators$customerid[!(fullindicators$customer_id %in% sample1)]




Easiest way to random sampling from a multidimensional array with another multidimensional array in python

I have a 3d numpy array that looks like this

A = np.random.randin(0, 10, (23, 23, 39))        # H, W, D

And wish to random sample from its depth to reach a 2d array with H and W only

Note … this doesn't work

B = A[np.random.randint(0, 39, (23,23))]



samedi 29 mai 2021

Get a dynamic input to populate an array and display randomly

I've got some code that currently successfully displays a random quote to users with the below code.

<script type="text/javascript">

var q = ['“The only reason I am successful is because I have stayed true to myself.”-Lindsey Stirling', '“To send light into the darkness of men’s hearts—such is the duty of the artist.” -Robert Schumann', '“I know that the most joy in my life has come to me from my violin.” -Albert Einstein, physicist and amateur violin player','“When you play a violin piece, you are a storyteller, and you’re telling a story.”-Joshua Bell','“Music is about devotion, and knowing when to be free.”-Leonidas Kavakos','“"Life" is a like myriad of perpetually ever-changing sound waves. "Living it" is like enjoying listening to this unrepeated orchestra and comfortably jamming along.”-Bo Ratiwat','“Playing a violin is, after all, only scraping a cats entrails with horsehair.”-Alan Watts','“Love is not love, without a violin playing goat.”-Julia Roberts','“When you play a violin piece, you are a storyteller, and you are telling a story.”-Joshua Bell','“Violin playing is a physical art with great traditions behind it.”-Vanessa Mae','"A table, a chair, a bowl of fruit and a violin; what else does a man need to be happy?"-Albert Einstein','If I do not practice one day, I know it; two days, the critics know it; three days, the public knows it."-Jascha Heifetz','"I am not handsome, but when women hear me play, they come crawling to my feet."-Niccolo Paganini'];

var elem = document.getElementById("quotes_contact");
var inst = setInterval(change, 10000);
change();
function change() {
    var min=0;
    var max=q.length - 1;
    var random =Math.floor(Math.random() * (+max - +min)) + +min;
    elem.innerHTML = q[random];
}

But, the website has a functionality to add a quote which should be displayed, therefore I now need the code to pull the quotes from this input form (dynamically), rather than having to update the hard coded array of quotes.

Can anyone help me work out how to get this dynamic input into my random quote visualiser? Thanks!!

This is the code in the quotes file...

  @if(count($quote)>0)
                <div class="row margin-adjust">
                   <div class="col-lg-12">
                        <div class="card-box table-responsive">
                            <table id="datatableCustom" class="table table-striped table-bordered">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>Name</th>
                                        <th>Quote</th>
                                        <th class="control-label">Action</th>
                                    </tr>
                                </thead>
                                    <tbody>
                                    <?php $count = count($quote); ?>
                                    @for($i=0; $i<$count; $i++)
                                        <tr>
                                            <td></td>
                                            <td></td>
                                            <td></td>
                                            <td class="tabactions">
                                                <a onclick="deleteQuote()"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></a>
                                            </td>
                                        </tr>
                                    @endfor
                                </tbody>
                            </table>
                       </div>
                    </div>
                </div>
            @else
                <div class="row margin-adjust">
                   <div class="col-lg-12">
                        <div class="card-box table-responsive">
                            <div class="no_data">
                                No Quote Data.<br>
                            </div>
                       </div>
                    </div>
                </div>
            @endif



Why, when generating random numbers, the number of which corresponds to the maximum size of the number, unique numbers are always 0.63 of the size?

package com.company; import java.util.*;

public class Main {

public static void main(String[] args) {
    ArrayList<Integer> integers = new ArrayList<>();
    for (int i = 0; i < 20000000; i++) {
        integers.add((int) (Math.random()*20000000));
    }
    HashSet<Integer> unique = new HashSet<>(integers);

    System.out.println("Number of items in a list of numbers: " + integers.size());
    System.out.println("Number of unique elements: " + unique.size());
}
}



Adding a level counter that isn't linked to buildindex unity and randomising levels

I'm trying to add a Level counter to my game that isn't based on buildindex but haven't been able to find a way to do it so far. That leads to my next question, I need the counter to work inpendantly of buildindex because I want the levels to be played in a random order (with replaying the same level possible). So far to randomise levels I've come up with this:

private void NextLevel()
{
  SceneManager.LoadScene(SceneManger.buildIndex + range(0,x)); //x would be the number of scenes
}

I haven't finished enough scenes to be able to test this yet to know if it works, if anyone knows a better way or would be able to confirm is this works or I should try come up with something else I would love to know!

Thank you for your time and any advice




How do I properly implement "operator()" with "if constexpr" so that it works with std::generate?

I was trying to write a class that will fill a container with random numbers with the type that the container has:

template<typename random_type>
class rand_helper {
private:
    std::mt19937 random_engine;
    std::uniform_int_distribution<int> int_dist;
    std::uniform_real_distribution<double> real_dist;

public:
    rand_helper() = delete;
    rand_helper(random_type left_b, random_type right_b);
    random_type operator()();

};

template<typename random_type>
rand_helper<random_type>::rand_helper(const random_type left_b, const random_type right_b) :random_engine{ std::random_device{}()} {
    if constexpr (std::is_same_v<random_type, double>)
        real_dist(left_b, right_b );
    else
        int_dist( left_b, right_b );
}

template<typename random_type>
random_type rand_helper<random_type>::operator()() {
    if constexpr (std::is_same_v<random_type, double>)
        return real_dist(random_engine);
    else
        return int_dist(random_engine);
}

But here an error occurs somewhere, because when I call std::generate,then I get a lot of errors:

template<typename T,typename vec_type = typename T::value_type>
void fill_contain(T& container,vec_type left_b=vec_type(0), vec_type right_b= vec_type(100)) {
    std::generate(std::begin(container),std::end(container), rand_helper<vec_type>(left_b ,right_b));   
}

I thought it might be because of if constexpr but if just leave:

template<typename random_type>
random_type rand_helper<random_type>::operator()() {
    return int_dist(random_engine);
}

then the same errors are still returned. Here is the list of errors I get:

Error   C2825   '_Urng': must be a class or namespace when followed by '::'
Error   C2510   '_Urng' : left of '::' must be a class / struct / union
Error   C2061   syntax error : identifier 'result_type'
Error   C2065   '_Ty1' : undeclared identifier
Error   C2923   'std::conditional_t' : '_Ty1' is not a valid template type argument for parameter '_Ty2'

The function call goes like this:

 std::vector<int> for_sort;
    fill_contain(for_sort);




trying to figure out how to populate a list with random info when a button is clicked

ok i am working on creating a program that will allow me to click a button and display the information in the same window/stage?/scene? but in a listview area. i am building an application for generating random loot from a list, (pref one not written into the main code area) and then display that loot in a listview area in the same window. i understand the logic of the code i see inside the IDE im using (intellij, building the GUI with Scene Builder). but my problem (problems really as there seem to be many) is that i cant figure out either where to find the code snippets needed or the tutorials needed to explain to me what code is needed to tie the button click into looking at the loot list and then randomly pick a given amount of items to display and then display it in the listview area.... i have been trying to find a tutorial or snippets of code for a few days now and none of the main java coding tutorial site, video or text, have the info im looking for... those sites only give the system.out print example to have the app print to the console and i dont need that. i can provide a link to the github where this is currently residing in its current format if need... any help anyone can provide me would be greatly appreciated... if this seems a little random i apologize but its the best way i can think of to describe what im trying to do. thank you and may Nyx bless you




How to create randomized object at specific spot in a scene in unity?

Suppose there's a map. there 4 certain spots where an object spawns. But Each spot can appear a random item and those same item won't appear in another spot. How would you exactly code this in C#?




How can I generate a 16 digit random number with rand() function in C?

I'm trying to generate a 16 digit random card number in a function for a bank account creating sample. I tried the code below, but it didn't work.

void generate_card_number() {
    srand(time(0));
    long long int cardnumber = 0;
    int i, randctrl;

    for (i = 0; i < 15; i++) {
        do {
            randctrl = rand() % 9;
        } while (randctrl == 0);
        cardnumber += ((10^i) * randd);
    }
    printf("\nThe Card Number : %lld", cardnumber);
}

Could you help me, please?




vendredi 28 mai 2021

In Google Sheets how can I randomize the order of a set of values?

Maybe I'm missing a keyword in my searches for a solution, but I didn't find what I'm looking for. In Google Sheets I want to take a set of numbers and reorder it randomly. For example, start with the set [1,2,3,4] and get back [4,2,1,3]. Any ideas which function or a combination of functions may achieve this goal?

The entire process that I want to achieve is something like this: I have a set of 4 fields. Their sum is fixed. I want to assign them randomized values. So, I was thinking to iterate through this process:

  • Create a random integer between 0 and the max possible value (in the first iteration it's the fixed sum)
  • The new max value is the last max value minus the new random number.
  • Check if the new max is zero.
    • If not:
      • Return to the 1st step and repeat - This goes on until there are four values
      • If needed the 4th value shall be increased so the total will match the fixed sum.
    • Else, continue.
  • Randomize the order of the 4 values.
  • Assign the values to the 4 fields.



Order by random() on Redshift is horribly slow

So we have a database of 100 million records and our queries are running very fast on redshift, until we have to select random records. We are using " order by random()".

The largest set of records we might need a random sample of is 10 million.

Can someone please help me speed up this randomization process? Thanks in advance.




How to shuffle zipped list without none in output?

from random import * 

from numpy import *

a = []
l = int(input("please enter the numbers of number that you like to add to your password")) 
for i in range(l):
    s = int(input("please enter the numbers that you like to add to your password"))
    a.append(s)
print("some selected values are -", a)



b = []
m = int(input("please enter the number of alphabets that you like to have in ur password")) 
for j in range(m):
    t = input("please enter the alphabets you desire to insert to your password ")
    b.append(t)
print("the alphabets that are selected are -", b)


c = []
n = int(input("please enter the number of symbols that you like to have in your password"))
for k in range(n):
    u = (input("please enter the symbols you would like to have in your password"))
    c.append(u)
print("the symbols you desired are - ", c)
d = [a, b, c]
print(d)
u = (list(zip(a, b, c)))
print(u)
x = random.shuffle(u)
y = random.shuffle(d)
print(x)
print(y)

I actually tried to use the shuffle function in a random module and the output was shown as none. So, I please request some expert to help me out as I am learning to code for the first time.




Random normal distribution generator comparison

So i've written a couple random number generators for a project that relies on generating normally distributed random numbers. I have written a couple of different implementations of the generator - namely Box-Muller method, Marsaglia's Polar method and the Inverse cumulative distribution approximation method. I've compared them in terms of speed and it turns out Inverse method is the fastest of the 3, is this expected, or did I mess up while writing the other two? I know numpy used the Polar method for a long time, so i believe it should be the fastest of the 3?

I compiled using gcc9.3.0 and used -O3 flag.

here are the codes for the generators:

struct gaussGenState 
{
    float gauss;
    int has_gauss;
};

void initializeGauss(struct gaussGenState *state)
{
    state->has_gauss = 0;
    state->gauss = 0.0;
}

float gauss(struct gaussGenState *state)
{
    /*
        Implementation of Marsaglia's polar method for calculating normally distributed 
        gaussian variables
        seeding of rand needs to be done outside of function (with srand())
    */
    if (state->has_gauss){
        const float temp = state->gauss;
        state->has_gauss = 0;
        state->gauss = 0.0;
        return temp;
    }   
    else {
        float f, x1, x2, r2;

        do {
            x1 = ((float)rand() / RAND_MAX) * 2 - 1;
            x2 = ((float)rand() / RAND_MAX) * 2 - 1;
            r2 = x1 * x1 + x2 * x2;
        } while (r2 >= 1.0 || r2 == 0.0);

        f = sqrt(-2.0 * log(r2) / r2);

        state->gauss = f * x1;
        state->has_gauss = 1;
        return f * x2;
    }
}

float gaussbm(struct gaussGenState *state)
{
    /*
        Implementation of Box-Muller method for calculating normally distributed gaussian 
        variables
        seeding of rand needs to be done outside of function (with srand())
    */
    if (state->has_gauss){
        const float temp = state->gauss;
        state->has_gauss = 0;
        state->gauss = 0.0;
        return temp;
    }
    else {
        float u, v, f1, f2;

        u = ((float)rand() / RAND_MAX);
        v = ((float)rand() / RAND_MAX);

        f1 = sqrt(-2.0 * log(u));
        f2 = 2*M_PI*v;

        state->gauss = f1 * cos(f2);
        state->has_gauss = 1;
        return f1 * sin(f2);
    }
}

float gaussInv(void)
{
    /*
        Implementation of Inverse cumulative distribution method for calculating normally 
        distributed gaussian variables
        Approximation relative error less than 1.15 x 10e-9 in the entire region.
        seeding of rand needs to be done outside of function (with srand())
    */
    float p, q, r;

    float a[6] = {-3.969683028665376e+01,  2.209460984245205e+02,
                    -2.759285104469687e+02,  1.383577518672690e+02,
                    -3.066479806614716e+01,  2.506628277459239e+00};
    float b[5] = {-5.447609879822406e+01,  1.615858368580409e+02,
                    -1.556989798598866e+02,  6.680131188771972e+01,
                    -1.328068155288572e+01};
    float c[6] = {-7.784894002430293e-03, -3.223964580411365e-01,
                    -2.400758277161838e+00, -2.549732539343734e+00,
                     4.374664141464968e+00,  2.938163982698783e+00};
    float d[4] = { 7.784695709041462e-03,  3.224671290700398e-01,
                    2.445134137142996e+00,  3.754408661907416e+00};

    p = ((float)rand()/RAND_MAX);

    if (p < 0.02425){
        q = sqrt(-2*log(p));
        return ((((((c[0]*q+c[1])*q+c[2])*q+c[3])*q+c[4])*q+c[5]) /
               ((((d[0]*q+d[1])*q+d[2])*q+d[3])*q+1));
    }

    if ((1-0.02425) < p){
        q = sqrt(-2*log(1-p));
        return -((((((c[0]*q+c[1])*q+c[2])*q+c[3])*q+c[4])*q+c[5]) / 
                ((((d[0]*q+d[1])*q+d[2])*q+d[3])*q+1));
    }

    q = p - 0.5;
    r = q*q;
    return ((((((a[0]*r+a[1])*r+a[2])*r+a[3])*r+a[4])*r+a[5])*q /
           (((((b[0]*r+b[1])*r+b[2])*r+b[3])*r+b[4])*r+1));
}



Normally distributed random numbers with vsrnggaussian (Fortran)

I'm new to Fortran (gcc version 10.2.0) and try to use the subroutine 'vsrnggaussian' to generate normally distributed random numbers but always get following error:

"Error: Function 'vsrnggaussian' at (1) has no IMPLICIT type"

I don't get it since 'vsrnggaussian' is no variable that needs to be defined.

What's wrong with my code?

    program test_normaldistr_random_number
!
      USE iso_fortran_env, dp=>real64
!
      IMPLICIT NONE
!
      INTEGER :: VSL_RNG_METHOD_GAUSSIAN_BOXMULLER
      REAL(DP) :: n=1._dp, a=10._dp, sigma=2._dp, stream=1._dp
      REAL :: r = 1, status
!
      status = vsrnggaussian(VSL_RNG_METHOD_GAUSSIAN_BOXMULLER,
     &stream, n, r, a, sigma)
!
      print *, status
!
      end program



Error executing while-loop "Loop being escaped randomly" Python

I have this code that is made for a game similar like (Rock, Paper, Scissors). When the code starts running, sometimes it gives error in not running the actual loop and conditions correctly. For example when the code starts running, at the first time the loop runs normally:

Foot, Nuke or Cockroach? (Quit ends): Foot
You chose: Foot
Computer chose: Foot
It is a tie!
Foot, Nuke or Cockroach? (Quit ends): 

But if I re-run the code again, the while-loop does not get executed as in the following example:

Foot, Nuke or Cockroach? (Quit ends): Cockroach
Foot, Nuke or Cockroach? (Quit ends): 

Or it gives me elif condition that the input is incorrect even though the input is from the correct selection.

Here is the full code:


    import random
    
    def main():
        rounds = 0
        win = 0
        tie = 0
        choices = ["Foot", "Nuke", "Cockroach"]
        cpu = random.choice(choices)
    
        while True:
    
            inpt = input("Foot, Nuke or Cockroach? (Quit ends): ")
    
            if inpt == "Foot" and cpu == "Nuke" or inpt == "Cockroach" and \
                    cpu == "Foot":
                print(f"You chose: {inpt}")
                print(f"Computer chose: {cpu}")
                print("You LOSE!")
                rounds += 1
    
            elif inpt == "Nuke" and cpu == "Foot" or inpt == "Foot" and \
                    cpu == "Cockroach":
                print(f"You chose: {inpt}")
                print(f"Computer chose: {cpu}")
                print("You WIN!")
                rounds += 1
                win += 1
    
            elif inpt == "Foot" and cpu == "Foot" or inpt == "Cockroach" and \
                    cpu == "Cockroach" or inpt == "Nuke" and cpu == "Nuke":
                print(f"You chose: {inpt}")
                print(f"Computer chose: {cpu}")
                print("It is a tie!")
                rounds += 1
                tie += 1
    
            elif inpt == "Quit":
                print(f"You played {rounds} rounds, and won {win} rounds, "
                      f"playing tie in {tie} rounds.")
                break
    
            elif inpt != "Foot" and inpt != "Cockroach" and inpt != "Nuke":
                print("Incorrect selection.")
    
    
    if __name__ == "__main__":
        main()




jeudi 27 mai 2021

Bird Rock Water using method in Java

So my task is to make a Bird Rock Water game using methods. My problem is how to

  • let the program accepts the integer value from the user that denotes Bird (1), Rock(2) or Water(3).
  • let user play 3 times in one round. (the output for my code keep repeating more than 3 times)
  • let the program count user’s ties, win and lose using method.

Any ideas on how to implement this? or what I need to change to my code.

This is my code:

import java.util.Random;
import java.util.Scanner;
public class RockPaperScissors {
        public static Scanner   sc  = new Scanner(System.in);
        public static int score = 0;
        public static int gameCount = 0;

        public static void main(String[] args)
        {
            System.out.println("Welcome to Wan tu Som game");
            play();
            while (playAgain())
            {
                play();
            }
        }

        public static void play()
        {
             String computer = computerChoice();
             String user= userChoice();
             determineWinner(computer, user);
        }
        
        public static String computerChoice()
        {
            Random rand = new Random();
            int cinput = rand.nextInt(3) + 1;
            String computer = "thing";
            if (cinput == 1)
                computer = "Bird";
            if (cinput == 2)
                computer = "Rock";
            if (cinput == 3)
                computer = "Water";
            return computer;
        }

        public static boolean playAgain()
        {
            System.out.println("Would you like to play again?(y/n): ");
            String input = sc.nextLine();
            if (input.toLowerCase().equals("y"))
            {
                return true;
            } else if (input.toLowerCase().equals("n"))
            {
                return false;
            } else
            {
                System.out.println("Invalid Input");
                return playAgain();
            }

        }

        public static String userChoice()
        {

            String user = "default";
            do
            {
                System.out.println("Choose either Bird (1), Rock (2), Water (3) ");
                user = sc.nextLine();
            } while (!isValidChoice(user));
            return user;
        }

        public static boolean isValidChoice(String choice)
        {
            boolean status;
            if (choice.equals("Bird"))
                status = true;
            else if (choice.equals("Rock"))
                status = true;
            else if (choice.equals("Water"))
                status = true;
            else
            {
                status = false;
                System.out.println("Error! Make sure you are capitalizing your choices");
            }

            return status;
        }

        public static void determineWinner(String computer, String user)
        {
            gameCount++;
            System.out.println(computer + " vs " + user);
            if (computer.equals("Water") && user.equals("Rock"))
            {
                score--;
                System.out.println("You lost!");
            }
            if (computer.equals("Bird") && user.equals("Water"))
            {
                score--;
                System.out.println("You lost!");
            }
            if (computer.equals("Rock") && user.equals("Bird"))
            {
                score--;
                System.out.println("You lost!");
            }
            if (computer.equals("Bird") && user.equals("Rock"))
            {
                score++;
                System.out.println("You win!");
            }
            if (computer.equals("Rock") && user.equals("Water"))
            {
                score++;
                System.out.println("You win!");
            }
            if (computer.equals("Water") && user.equals("Bird"))
            {
                score++;
                System.out.println(" You win!");
            } else if (computer.equals(user))
            {
                System.out.println("Game ties!");
            }
            
            int ties = 0;
             ties += score;
             int userWins = 0;
             userWins += score;
             int userLost = 0;
             userLost += score;
             int compWins = 0;
             {
             for(int i = 0; i < 3; i ++){
                 computer = computerChoice();
                 user = userChoice();
                 determineWinner(computer, user);
             }
            System.out.println("You have ties for " + ties + " times");
            System.out.println("You have winning for " + userWins + " times");
            System.out.println("You have losing for " + userLost + " times");
            return;
        }

    }
}



Output:

Welcome to Wan tu Som game
Choose either Bird (1), Rock (2), Water (3) 
Bird
Bird vs Bird
Game ties!
Choose either Bird (1), Rock (2), Water (3) 
Water
Water vs Water
Game ties!
Choose either Bird (1), Rock (2), Water (3) 
Rock
Rock vs Rock
Game ties!
Choose either Bird (1), Rock (2), Water (3) 
Bird
Water vs Bird
 You win!
Choose either Bird (1), Rock (2), Water (3) 
Rock
Bird vs Rock
You win!
Choose either Bird (1), Rock (2), Water (3) 
Water
Water vs Water
Game ties!
Choose either Bird (1), Rock (2), Water (3) 

Expected output:

Welcome to Wan tu Som game                                                                                                  

Choose either Bird (1), Rock (2), or Water (3): 1                                                                               

You win!                                                                                                                        

Choose either Bird (1), Rock (2), or Water (3): 2                                                                               

Rock vs Bird: You win!                                                                                                          

Choose either Bird (1), Rock (2), or Water (3): 1                                                                               

Game ties!                                                                                                                      

Would you like to play again?: n                                                                                                

You have ties for 1 times                                                                                                       

You have winning for 2 times                                                                                                    

You have losing for 0 times




How to select random sample from 4 dimensional numpy array

I have an array with shape (100,505,555,2). I need to choose a sample with lower size in order to calculate correlation between points with size 100. So I need to choose from the second and third dimension of the array. for example get an array of size (100,50,50,2)

I tried to use

np.random.choice or np.random.Generator.choice but not successful.

can you please help??




How do I count the number of occurrences of a particular string in nasm?

I'm trying to write a nasm program where I take string input from the user and count the occurrence of 'a' in the string. I am able to accept and display string but it is not counting the occurrence of character 'a'. this is the code I have written so far: I don't know if my counter variable is incrementing and I don't know where I am going wrong.

%macro accept 2
mov eax,3
mov ebx,0
mov ecx,%1
mov edx,%2
int 80h
%endmacro

%macro display 2
mov eax,4
mov ebx,1
mov ecx,%1
mov edx,%2
int 80h
%endmacro 
section .text
    global _start       
_start:                     

accept str1,50
display msg,len 
display str1,50

dec al
mov byte[cnt],al
;mov ch,[count]
;and ch,0

l1: 
 mov esi,str1
 mov edi,str2
 
again1:
 mov al,[esi]
 cmp al, 'a'
 je l2
 cmp al,'A'
 je l2
 ;jmp again2
 
 
l2: 
 mov [edi],al
 inc esi
 inc edi
 dec cl
 jnz again1

 
;again2: 
 ;inc esi
 ;inc edi
 ;dec cl
 ;jnz again1
 
string:
 mov esi,str2
 
c_string:
 lodsb 
 cmp al,'x'
 je my
 inc ch
 jmp c_string
 
 
my: 
display msg1,len1
mov [count],ch
display count,1
jmp myend
 

 
myend: 
 mov eax,1
 int 80h
 

    

section .data

msg db  'Enter a string',0ah    
len equ $ - msg         
msg1 db 'Number of occurences of "a" is ',0ah
len1 equ $-msg1

section .bss
str1: resb 50
str2: resb 50
cnt resb 50
count resb 1




Is SecureRandom weaken when seed with Random?

Could a seed from java.util.Random for java.security.SecureRandom weaken the cryptographically strong random number generator?

I saw this code and wonder why this is done in that specific way.

randomGenerator = new SecureRandom();
final Random rnd = new Random();
randomGenerator.setSeed(rnd.nextLong());

From the documentation, the call of setSeed will never reduce randomness. So why is setSeed called anyway?

public void setSeed(long seed)
Reseeds this random object, using the eight bytes contained in the given long seed. The given seed supplements, rather than replaces, the existing seed. Thus, repeated calls are guaranteed never to reduce randomness.
docs.oracle.com




How to Generate 10 digit unique number sequentially in Java [closed]

I need to generate 10 digit unique number sequentially.

like my number should generate in below way.

0000000001 0000000002 0000000003 . . . . 0000000010 0000000011 . . . 9999999999

I have used java RandomStringUtils.randomNumeric(10); but I am getting some of the duplicate values.




mercredi 26 mai 2021

Number Guessing Game for 0A0B in R

• Game rules: At the beginning of the game, a number of 4 distinct digits is generated. A player is asked to guess the number. Each time the player guesses the number, the game gives a hint with “XAYB”, where X is the number of digits in the correct positions and Y is the number of correct digits but not in the right positions. For example,

enter image description here

• Requirements:

  1. Generate a number of 4 distinct digits named by “num”.
  2. Create a function(“hint”) that the guessing number is an input and outputs a hint.



Storing random strings without duplicates in a database

I am generating strings to use as IDs, so to avoid repetitions I must currently check in my database if that string has already been assigned and if so, generate another one, what I want is avoid the rework of calculating another string.

I can generate and store all possible strings to assign them more quickly but I am not convinced by this idea

Can you think of something more efficient?

I edit: the requirement demands that I use identifiers of this type, nothing personal;)

The lifetime of each ID is 24 hours




Generating a random sample from a population using NIST CTR DRBG in Python

I am trying to generate a random sample from a population that uses a cryptographically secure DRBG instead of the 'insecure' Mersenne Twister that is used by default in Python.

This library provides the DRBG and I repurposed the random.sample generation algorithm in the Python source code as the basis for my sampling algorithm.

The code works but for only samples substantially smaller than the population whereas the builtin Mersenne Twister does not fail even if the sample and population are equal.

The program will randomly select locations in an array for a character to reside in it. Overriding is not allowed as the string has to be reconstructed from the array after it has been placed into it (this part of the code has not been shown by explained in case it helps explain the problem).

Code:

import string
import secrets as secret
import random as rd
import numpy as np
from math import ceil, log
from aes_drbg import AES_DRBG
import timeit


# Initialize the AES DRBG
key = 1
aes_drbg = AES_DRBG(256)
aes_drbg.instantiate(bytes(key))

def random_number(limit):
    """Generate a random number within the limit using the AES DRBG."""
    sequence_length = 1
    if limit >= 4_294_967_296:
        sequence_length = 8
    elif limit >= 65_536:
        sequence_length = 4
    elif limit >= 256:
        sequence_length = 2

    random_number_bytes = aes_drbg.generate(sequence_length)
    random_number = int.from_bytes(random_number_bytes, byteorder="big")

    return random_number % limit

def sample(population, k):
    """Generate a random sample of size k from the given population"""
    randbelow = random_number
    n = len(population)
    if not 0 <= k <= n:
        raise ValueError("Sample larger than population or is negative")
    result = [None] * k
    setsize = 21  # size of a small set minus size of an empty list
    if k > 5:
        setsize += 4 ** ceil(log(k * 3, 4))  # table size for big sets
    if n <= setsize:
        # An n-length list is smaller than a k-length set
        pool = list(population)
        for i in range(k):  # invariant:  non-selected at [0,n-i)
            j = randbelow(n - i)
            result[i] = pool[j]
            pool[j] = pool[n - i - 1]  # move non-selected item into vacancy
    else:
        selected = set()
        selected_add = selected.add
        for i in range(k):
            j = randbelow(n)
            while j in selected:
                j = randbelow(n)
            selected_add(j)
            result[i] = population[j]
    return result


def string_generator(size):
    """Generate a random string of a given size."""
    chars = string.ascii_uppercase + string.ascii_lowercase
    return ''.join(secret.choice(chars) for _ in range(size))

def main():
    test = string_generator(50_000_000)  # Generate random string as test data.

    array = np.zeros([100_000_000])  # Initialize empty array.

    rd.seed(1)

    start_time = timeit.default_timer()
    rand_sample = sample(range(len(array)), len(test))  # use `sample` for AES DRBG; `rd.sample` for the Mersenne Twister
    end_time = timeit.default_timer()

    print(rand_sample)
    print(f"Execution time: {end_time - start_time}")

if __name__ == "__main__":
    main()

As the value of the len(test) approaches the value of the len(array) is when the DRBG stops outputting and runs indefinitely. I am not sure where I have gone wrong but I cannot diagnose the mistake.

The MWE is a simplification of my actual code by demonstrates the problem adequately as far as I can gather. The numbers for test and array are far larger in production (billions) so I'm open to any other more efficient algorithms or other cryptographically secure DRBGs such as XCHACHA20 or even other libraries that have secure DRBGs available that allow full control over the seeds so the results can be repeated. Any guidance is highly appreciated.




Errors and Exceptions:C2M5L4_Errors_and_Exceptions-V2

import random

participants = ['Jack','Jill','Larry','Tom']

def Guess(participants): my_participant_dict = {} for participant in participants: my_participant_dict[participant] = random.randint(1, 9) if my_participant_dict['Larry'] == 9: return True else: return False

print(Guess(participants))




Problems while creating a random numpy vector with unique elements?

I am creating lists like this:

In:

x = [[[random.randint(1,1000), random.randint(0,2)] for i,j in zip(range(1), range(1))][0] for i in range(5)]

Out:

[[76, 0], [128, 2], [194, 2], [851, 2], [123, 1]]

However, what is the most efficient way of making the first element of the sublist unique? It seems that randint doesnt have this option. How can I force 76, 128, 194, 851, 123 to be unique?




Why is the Mersenne twister prefered to using the wichmann hill algorithm to produce pseudo random numbers?

I read that in version by Python 2.3 https://stackless.readthedocs.io/en/2.7-slp/library/random.html the Mersenne twister replaced the Wichmann-Hill method as default generator. I was wondering if something can elaborate why this one would do that. I understand, that the period is a bigger for the Mersenne twister, but are there other features, that could drive this change?




np.random.binomial() vs random.choices() for simulating coin flips

I want to simulate repeated flips of a fair coin using Python. Two approaches seem reasonable, as shown in the code below. Are they equivalent please, and if so is there any good reason to prefer one over the other?

import random
import numpy as np

n = 10
p = 0.5

print(np.random.binomial(n, p))

results = random.choices([True, False], k=n)
print(results.count(True))



Randomize list without same entry successively

order_list_raw = []
for i in range(1, 73):
    order_list_raw.append(1)
    order_list_raw.append(2)
    order_list_raw.append(3)

How can I create the same list with a randomized order but without having the same entry successively (e.g. "1, 3, 2" is okay but not "1, 1, 3").

For randomization I would create a new list like this:

order_list = random.sample(order_list_raw, len(order_list_raw))



mardi 25 mai 2021

Is there any benefits of set.seed() with slice_sample()

I am using slice_sample() to select some rows from a dataframe. I am doing slice based on 2 loops. The code structure is like the below one

for (j in 1: 10)
{  
  df = dataset // dynamically loading dataset based on the value of j
  for (i in 1:4) {
    
  if(i==1){
    call_function(df, j, 0.3)
  }
  else if(i==2)
  {
    call_function(df, j, 0.4)
  }
  else if(i ==3){
    call_function(df, j, 0.5)
  }
  else{
    call_function(df, j,  0.6)
  }
}
}

The Call_Function() contains the slice_sample().

call_function(df, j, pro){
  slice_sample(df,  prop = pro) }

I have 10 datasets and for every j I am loading different datasets. Here, for every j the function is called 4 times (based on the if-else).

If I use random.seed() to keep the sample (random) index same for the every j it will works?

Actually, I need to keep the sample (random) index same for the every j.




R: Generate Random Numbers with "floor" and "runif"

I am using the R programming language. I am trying to generate random integers between 1 and 0. Using the following link (http://www.cookbook-r.com/Numbers/Generating_random_numbers/), I tried this code to generate 1000 random integers between 0 and 1:

x = floor(runif(1000, min=0, max=1))
y = floor(runif(1000, min=0, max=1))
group <- sample( LETTERS[1:2], 1000, replace=TRUE, prob=c(0.8,0.2) )

d = data.frame(x,y,group)
d$group = as.factor(d$group)

However, both "x" and "y" seem to only have a value of 0.

Does anyone know what I am doing wrong? Thanks




Custom numpy (or scipy?) probability distribution for random number generation

The issue

Tl;dr: I would like a function that randomly returns a float (or optionally an ndarray of floats) in an interval following a probability distribution that resembles the sum of a "Gaussian" and a uniform distributions.

The function (or class) - let's say custom_distr() - should have as inputs (with default values already given):

  • the lower and upper bounds of the interval: low=0.0, high=1.0
  • the mean and standard deviation parameters of the "Gaussian": loc=0.5, scale=0.02
  • the size of the output: size=None
  • size can be an integer or a tuple of integers. If so, then loc and scale can either both simultaneously be scalars, or ndarrays whose shape corresponds to size.

The output is a scalar or an ndarray, depending on size.

The output has to be scaled to certify that the cumulative distribution is equal to 1 (I'm uncertain how to do this).

Note that I'm following numpy.random.Generator's naming convention from uniform and normal distributions as reference, but the nomenclature and the utilized packages does not really matter to me.

What I've tried

Since I couldn't find a way to "add" numpy.random.Generator's uniform and Gaussian distributions directly, I've tried using scipy.stats.rv_continuous subclassing, but I'm stuck at how to define the _rvs method, or the _ppf method to make it fast.

From what I've understood of rv_continuous class definition in Github, _rvs uses numpy's random.RandomState (which is out of date in comparison to random.Generator) to make the distributions. This seems to defeat the purpose of using scipy.stats.rv_continuous subclassing.

Another option would be to define _ppf, the percent-point function of my custom distribution, since according to rv_generic class definition in Github, the default function _rvs uses _ppf. But I'm having trouble defining this function by hand.

Following, there is a MWE, tested using low=0.0, high=1.0, loc=0.3 and scale=0.02. The names are different than the "The issue" section, because terminologies of terms are different between numpy and scipy.

import numpy as np
from scipy.stats import rv_continuous
import scipy.special as sc
import matplotlib.pyplot as plt
import time


# The class definition
class custom_distr(rv_continuous):
    def __init__(self, my_loc=0.5, my_scale=0.5, a=0.0, b=1.0, *args, **kwargs):
        super(custom_distr, self).__init__(a, b, *args, **kwargs)
        self.a = a
        self.b = b
        self.my_loc = my_loc
        self.my_scale = my_scale

    def _pdf(self, x):
        # uniform distribution
        aux = 1/(self.b-self.a)
        # gaussian distribution
        aux += 1/np.sqrt(2*np.pi*self.my_scale**2) * \
                 np.exp(-(x-self.my_loc)**2/2/self.my_scale**2)
        return aux/2  # divide by 2?

    def _cdf(self, x):
        # uniform distribution
        aux = (x-self.a)/(self.b-self.a)
        # gaussian distribution
        aux += 0.5*(1+sc.erf((x-self.my_loc)/(self.my_scale*np.sqrt(2))))
        return aux/2  # divide by 2?


# Testing the class
if __name__ == "__main__":
    my_cust_distr = custom_distr(name="my_dist", my_loc=0.3, my_scale=0.02)

    x = np.linspace(0.0, 1.0, 10000)

    start_t = time.time()
    the_pdf = my_cust_distr.pdf(x)
    print("PDF calc time: {:4.4f}".format(time.time()-start_t))
    plt.plot(x, the_pdf, label='pdf')

    start_t = time.time()
    the_cdf = my_cust_distr.cdf(x)
    print("CDF calc time: {:4.4f}".format(time.time()-start_t))
    plt.plot(x, the_cdf, 'r', alpha=0.8, label='cdf')

    # Get 10000 random values according to the custom distribution
    start_t = time.time()
    r = my_cust_distr.rvs(size=10000)
    print("RVS calc time: {:4.4f}".format(time.time()-start_t))

    plt.hist(r, density=True, histtype='stepfilled', alpha=0.3, bins=40)

    plt.ylim([0.0, the_pdf.max()])
    plt.grid(which='both')
    plt.legend()

    print("Maximum of CDF is: {:2.1f}".format(the_cdf[-1]))

    plt.show()

The generated image is: enter image description here

The output is:

PDF calc time: 0.0010
CDF calc time: 0.0010
RVS calc time: 11.1120
Maximum of CDF is: 1.0

The time computing the RVS method is too slow in my approach.




Is this misprint at 2.5.8 example from [NIST SP800-22 Revision 1a.]?

I am reading the paper, NIST SP800-22 Revision 1a, which is about Randomness Test suite.

This is the link where I found, and read.

I summarized my question at the end of post. And below description is how my deduction drawn. And also, I haven't found misprint about 2.5.8 Example yet.

2.5.4 Test Description

chi_square

χ^2 is calculated as above equation.

2.5.8 Example

Examples

It is very nice of Example to show all variables. But, sadly, I cannot get χ^2 = 1.2619656 as expected. And I think this is misprint of this paper.

the reason why I think misprint

  1. I got χ^2 = 1.262580416458114

  2. I double-checked whether my code is wrong with golang new(big.Float).SetPrec(500)

  3. I triple-checked with Wolfram Alpha which is online equation calculator as below captured image.

wolframalpha

Question

  1. Am I wrong?

  2. If I wrong, what is the reason why I cannot get precise answer?
    (I don't think this is precision problem of floating-point or just simple mistake)

  3. If this is misprint, how can I report this?

  4. Or, 4 decimal places error, 1.262580416458114 - 1.2619656 = 0.000614..., is within the margin of error in the system of Randomness-test?




commnand to get random no 92 or 93 in shellscript

for example we are getting 2 digit no using command (((RANDOM % 10) +10)) then how we exact no 92 or 93 form random noenter code here echo $(((RANDOM%10)+10))




How to generate different random values at each subprocess during a multiprocessing?

I need to generate a different random value at each sub-process but I realized that this local variable is rewritten or shared between each sub-process. See the example below to understand the problem I am facing:

import numpy as np
from multiprocessing import Pool

def func(i):
    i2 = i**2
    random_variable = np.round(np.random.normal(), 3)
    return i2, random_variable

if __name__ == '__main__':
    with Pool() as pool:
        result = pool.map(func, [1, 2, 3, 4, 5])
        print(result)

output:

[(1, -0.122), (4, -0.122), (9, -0.122), (16, -0.122), (25, -0.122)]

What could be the reason of this output? And how can I generate a different random variable at each sub-process?




How do I generate a string that contains a keyword?

I'm currently making a program with many functions that utilise Math.rand(). I'm trying to generate a string with a given keyword (in this case, lathe). I want the program to log a string that has "lathe" (or any version of it, with capitals or not), but everything I've tried has the program hit its call stack size limit (I understand exactly why, I want the program to generate a string with the word without it hitting its call stack size).

What I have tried:

function generateStringWithKeyword(randNum: number) {
  const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/";
  let result = "";
  for(let i = 0; i < randNum; i++) {
    result += chars[Math.floor(Math.random() * chars.length)];
    if(result.includes("lathe")) {
      continue;
    } else {
      generateStringWithKeyword(randNum);
    }
  }
  console.log(result);
}

This is what I have now, after doing brief research on stackoverflow I learned that it might have been better to add the if/else block with a continue, rather than using

if(!result.includes("lathe")) return generateStringWithKeyword(randNum);

But both ways I had hit the call stack size limit.




Generate random numbers within a specific range

How do i generate 15 or more random number with range difference of 8-15

Eg If one of the generated number is 9 the next number should be either 17, 18, to 24 So the next number should not be less than 8 or greater than 15 Something like this

[5, 15, 23, 36, 45, 60, ......,]

Also it should start from 5 to 10

Please is this possible to achieve using javascript or flutter Also if you need more explanation or you don't understand please ask




lundi 24 mai 2021

Databricks : tablesample only using certain groups

I have a table in databricks with ~500 million rows covering 25 months of data (2018-2020). I want to pull a 1 million row sample for some quick analysis & modeling. When I use tablesample(1000000 rows) or limit 1000000 only 8 of the 25 months are represented in the sample. Is there a way to fix this?

%sql
with c1 as(
  select *
  from my_table
  TABLESAMPLE(1000000 ROWS)
)
select month_id, count(*) cnt
from c1
group by month_id
order by month_id

Returns 8 rows all in the last 8 months of the data set.

%sql
with c1 as(
  select *
  from my_table
  limit 1000000
)
select month_id, count(*) cnt
from c1
group by month_id
order by month_id

Returns 8 rows all in the last 8 months of the data set.

%sql
with c1 as(
  select *
  from my_table
  --TABLESAMPLE(1000000 ROWS)
  --limit 1000000
)
select month_id, count(*) cnt
from c1
group by month_id
order by month_id

Returns 25 rows covering all months




JAVA implementation of std::piecewise_linear_distribution

Is there a JAVA version of the std::piecewise_linear_distribution? I have a C++ code like the following that I need to convert to JAVA.

std::mt19937 g;
const std::vector<double> i{-3333333, -2222222, -11111,    0, 11111, 2222222, 4444444};
const std::vector<double> w{0.0005,     0.0057,    7.9, 9999,   7.9,  0.0057,  0.0005};
std::piecewise_linear_distribution<> IWrnd(i.begin(), i.end(), w.begin());

g.seed(seed);
randomNumber = IWrnd(g);

I do not know the algorithm of std::piecewise_linear_distribution and I was not able to understand from the STL templates so I am not sure how this should look like in JAVA.

Is there an implementation of this in some JAVA package like java.util.Random? Or can someone post the algorithm for this?




SQL : select n. random groups from a table

I have a table on Bigquery that looks like this:

authorId text     textid 
--------------------------     
12         bla      234
22         cat      134
22         fish    1312
33         dog      432
33         catcall  442
12         ..  
53
..

The table is very big with more than 100 million author Ids. I want to sample n=1000 random authors and each row from those authors. How can I do that?

The expected results would look like this for n=2

authorId text     textid 
------------------------    
12         bla      234
33         dog      432
33         catcall  442
12         ..  
..

I was thinking to create a list of random authors and then select rows where author id appears in the list, but I am not sure it is the best way to proceed.

In case it was, I can create a table with the unique ids as follows but I don't know how to then subset table1 based on this..

WITH table2 AS 
(
    SELECT authorId  
    FROM table1  
    GROUP BY authorId 
    ORDER BY RAND() 
    LIMIT 1000
)



Display Function with Random rows scala

I am trying to display data, but I want to look at random rows instead of always the first ones that show.

display(Matches .select( $"State", $"City", $"Zip",) )

Thanks in advance!




Populate a table column randomly with values from a list in PostgreSQL

I want to randomly populate a column in my table with the following values: Available, On Hold, Partial Downpayment, Sold/Unavailable, Token

I have tried using the following command but it populates the entire column with the first value it gets.

update mytable
set sold_status = (select (array['Available', 'On Hold', 'Partial Downpayment', 'Sold/Unavailable', 'Token Recieved'])[floor(random() * 5 + 1)])

I know how to achieve this with a programming language, but I would prefer a PostgreSQL query to achive this.




How to set a while loop?

I'm trying to set my code for counting math games, all math operations are fine except for division. I don't know how to set the while loop correctly. There is a problem with division, such that I would like the division to be residual, so I came up with one method which is given below. It is all in WPF Application. I would like to count only single-digit numbers.

Random number = new Random();
int maxValue = 10;
int total = 0;
int firstNumber = number.Next(1, maxValue);
int secondNumber = number.Next(1, firstNumber);
while (firstNumber % secondNumber != 0);
  {
  secondNumber++;
  }
total = firstNumber / secondNumber;

Why does it still show me the values ​​that have a residual division?

Thank you for any advice




Random number generator (rdtsc)

So Im working on a battleship project in asm for uni and I want to generate some random numbers between 1-100 for the game in order to place the ships in the matrix. I was told that for the random number generator I could use the rdstc function but it gives me errorA2085: instruction or register not accepted in current CPU mode when I try to use it. What should I change to make it work or what other options I could use to generate numbers?




dimanche 23 mai 2021

How do I pass a vector into cpp discrete_distribution?

cxx_std 14

I need to create a random number generator whose distribution matches a given histogram. The values of the histogram are stored in a file.

std::random_device rd;
std::default_random_engine dre(rd());
std::vector<int> weights;

// these histogram numbers will be read from a file (about 400 of them)
weights.push_back(10);
weights.push_back(20);
weights.push_back(30);
weights.push_back(40);
weights.push_back(10);

std::discrete_distribution<int> discrete_dist(weights); // this is line saying that it doesn't know how to take a vector like a good bi**h
G4double random_number;
for(int n=0; n < 1000; ++n) {
    random_number =
        min_num + ((discrete_dist(dre) + 1) * (max_num - min_num) / intervals_count );
    random_numbers->push_back(random_number);

error on compilation.

error: no matching function for call to 'std::discrete_distribution<int>::discrete_distribution(std::vector<int>&)'
   32 |     std::discrete_distribution<int> discrete_dist(weights);

This is how the documentation says it is to be done.

#include <iostream>
#include <map>
#include <random>
 
int main()
{
    std::random_device rd;
    std::mt19937 gen(rd());
    std::discrete_distribution<> d({40, 10, 10, 40});
    std::map<int, int> m;
    for(int n=0; n<10000; ++n) {
        ++m[d(gen)];
    }
    for(auto p : m) {
        std::cout << p.first << " generated " << p.second << " times\n";
    }
}

It seems weird that this could only be used by hardcoding the distribution. Any help will be appreciated, thank you.

PS: typecasting to std::discrete_distribution<int>::param_type did not help as it didn't know how to convert vector to that.




the way of efficiently generating two random samples with dependency

I would like to generate two set of variables, h_min and h_max,

h_max = [h_max_1, h_max_2, …h_max_2000]
h_min = [h_min_1, h_min_2,… h_min_2000]

Each element of h_max is generated based on uniform distribution, i.e.,

h_max = np.random.uniform(0,  20, 2000). 

For each element, h_min_i, it should be generated based on the uniform distribution with range of 0, and corresponding h_max_i In other words, h_min_i = np.random.uniform(0, h_max_i) In stead of using iteration, how to efficiently generate h_min




Scrapy rotating user agents in spider

I put a function in my spider which will generate a random user agent from a txt file. Now, I called this function from the start_requests function:

def start_requests(self):

        url = 'someurl'

        head = self.loadUserAgents() 
        
        headers =  {
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'en-US,en;q=0.5',
            'User-Agent': head
        }

        yield scrapy.http.Request(url,headers=headers)

I use a parse function that is able to follow the next page. I think that in this way the spider will only generate the random user agent once. How can I force the spider to generate a new user agent on each following page?

Thanks.




random empty list on 4th instance of List Shuffler [duplicate]

I'm using C# to write out a list shuffler for a list of possible answers for a multiple choice quiz game. THe list shuffler would shuffle the order of the items, and allow the answers to appear in a random order.

The code appears to function, but on the 3'rd or 4th instance of this code, it errors out with an indexoutofrange. While debugging, I've found that the unshuffledList is startingout empty.

The code is:

public static class ListShuffler
{public static List<string> ShuffleListItems(List<string> unshuffledList = null)
{
    List<string> shuffledList = new List<string> { };

    System.Random random = new System.Random();

    int index;
    if (unshuffledList == null )
    {
        shuffledList = new List<string>{ "error", "error", "error", "error" };
    }
    else {
        for (; unshuffledList.Count > 0;)
        {
            index = random.Next(0, unshuffledList.Count);
            shuffledList.Add(unshuffledList[index]);
            unshuffledList.RemoveAt(index);

            /* if (unshuffledList.Count == 1)
             {
                 shuffledList.Add(unshuffledList[0]);
                 unshuffledList.RemoveAt(index);
                 break;
             }
             */
        }
    } 
    
    
    
    return shuffledList;
}

}

The code is called using:

List<string> answerList = ListShuffler.ShuffleListItems(unshuffledList: question.Options);

The error is definitely somewhere in this block of code, since use of another list shuffler found online results in no error. I just want to understand where the error is coming from. Any help is appreciated!




Change output of random list shuffle slightly when changing seed slightly

Problem:

I would like to randomly shuffle a list, but using a seed value s so that, when changing s value only slightly, the shuffle's output also only changes slightly.

Details:

I have a sorted list of elements, for example:

[0,1,3,5,7]

This list should be shuffled multiple times, each time using a seed value s. When two seed values s1 and s2 = s1 + d lie close to each other, then the shuffled lists should also be "similar".

By "similar", I mean that elements in the new shuffled list are either the same as they were when using the original seed value s1, or they are replaced only by values which are close to them in the original list (for example their direct neighbors in the original list).

Example for the above list (note how adding the small value d only perturbs the list slightly, i.e. many values stay the same and if they change, they are usually replaced by their neighbors in the original list):

Seed: Output:
s [5,0,1,7,3]
s + d [5,0,3,7,1]
s + 2d [7,0,3,5,1]
s + 3d [7,0,1,3,5]

Is there an algorithm for this? Is there a common name for this problem (or other search terms I could use)?

Ideas I had thus far:

I could use simplex/perlin noise to sample elements: I generate a number between 0 and 1 and then use it to choose the next element from the list (0 meaning I choose the first element, 1 meaning I choose the last). Since these noise types can be "smooth", adding d will change the random value only slightly, meaning it will usually select elements in proximity of the ones it picked before adding d. However, I have a very hard time choosing a "good" frequency for the noise (high frequencies will remove the smoothness I need, low frequencies will result in no change when adding d). Also, once the list shrinks as I pick elements, the effect of d will decrease, because the range 0 to 1 will be mapped to fewer elements - and I don't really know if this is a problem yet...?




Strange randomness behaviour

Trying to make ants simulator using javaFX

I've had a problem that : the ants are not distributed equally on the whole frame. At first I had a problem to periodically update each ant at a random rate and to a random direction so say for example an ant will change it's direction after 0.5 s and after that it will change it randomly after 0.3s ..etc I've managed to solve this using this method,it's a bit complicated I'll try to make it as simple as I can:

Create an array chosenAnts which has a length of antCount/2 , this array , holds the indices of the randomly chosen ants that will change their direction in the next X seconds.

Using PauseTransition I loop through the chosenAnts array and then update the positions of the chosen ants , these ant will change their directions at the same moment to a random directions .

Update the chosenAnts array randomly , this provides the next random indices that'll be chosen for the next queue:

for(int i = 0 ; i < chosenAnts.length ;i++){
chosenAnts[i] = (int)(Math.random() * antCount);
}

Finally,update the position of the ants by updating the velocity on the x,y just like this with the above code, note that xvel and yvel are arrays that hold the velocity of each ant on both x ,y ; and please dont look to the right side it's just a mess in order to make the ant behave correctly and not crazily, in other words, the direction will be within the red triangle :

for(int i = 0 ; i < chosenAnts.length ;i++){
    chosenAnts[i] = (int)(Math.random() * antCount); 
            xvel[chosen[i]] = ((xvel[chosen[i]] - 0.2) + Math.random() * (xvel[chosen[i]] + .2)) % 1;
            yvel[chosen[i]] = ((yvel[chosen[i]] - 0.2) + Math.random() * (yvel[chosen[i]] + .2)) % 1;
    }

And this is how it looks like with 10 000 ants ,after few minutes of the start of the sim , note that the position of the colony is literally on the buttom right which is the opposite of where they are dense and there are borders.

enter image description here

enter image description here

enter image description here




MATLAB Linear Congruential Generator (LCG) for Random Numbers and 64-bit unsigned int multiplication

I would like to implement a 64-bit L'Ecuyer LCG on MATLAB, since I wrote it on C, to replicate some results.

The pure Mutiplicative LCG (MLCG) is easily obtained by X_{n+1} = a * X_{n} mod m, where a and m are the two constant taken from the table of L'Ecuyer's article. In my case I used

a = 1181783497276652981
m = 0xFFFFFFFFFFFFFFFF = 2^64 - 1

As pointed out e.g. here in C there are no problem in doing multiplication of 64-bits a and X_{n} is automagically truncated to the remainder of division by 2^64 - 1, so that I only need to do

rnd = A_ecu1b64 * rnd;

to obtain the successive random number. In MATLAB, sadly, this is not like so, instead when a * X_{n} is bigger than m is gets truncated to 2^64-1 and then the successive remainders are always 0.

How can I implement the same MLCG on MATLAB?




Choose one of N items given the probability of each item [duplicate]

I want to write a function that returns one out of N items, given the probability of each item (the sum of all probabilities is 1).

I found a lot of ways to do this in Python with numpy, but I'm interested in a JavaScript solution.

How do I do this?




C++ random number -infinity to +infinity

This is my code

For (int i = 0; i < 10000; i++) {
    random2 = (1.0 * rand() / RAND_MAX);

    if (random2 >= 0.5)
    {
        random = (1.0 * rand() / RAND_MAX);
    }
    else {
        random = -(1.0 * rand() / RAND_MAX);
    }

} I want to get a random number between -infinity and+infinity 10000 times.

I tries -1 between 1 to get a random number. but I need -infinity between +infinity random number. this is my best please give me your wisdom




samedi 22 mai 2021

How do you generate multiple unique random numbers within a range in mysql

I am working on a project where I print out 3 values each being within a certain range as shown in the example below. I pass in a value x.

I have tried this formula for if x = 1. This being:

SELECT (FLOOR(2 + RAND() * 32)) AS 'Low Range',
(FLOOR(33 + RAND() * 65)) AS 'Mid Range',
(FLOOR(66 + RAND() * 98)) AS 'High Range';

Unfortunately, this does not give me the desired results.

I also tried this formula:

SELECT FLOOR(RAND() * (33) + (x * 100)) AS 'Low Value',
(FLOOR(RAND() * (66) + (x * 100))) AS 'Mid Value',
(FLOOR(RAND() * (99) + (x * 100))) AS 'High Value';

But this does not work.

When I use:

SELECT FLOOR(RAND() * (200 - 100) + (x * 100)) AS RandomValue;

I can get the desired results for a single range between 100 and 200, or 200 and 300, but I cant figure out how to get 3 ranges.

This is what I would hope to achieve based on the value of x:

if x = 1

2 - 32, 33-65, 66-98

if x = 2

102 - 132, 133-165, 166-198

if x = 3

202 - 232, 233-265, 266-298

etc..

Essentially, I would like to increase by 100 for each increase of value of x. Is there a way I could achieve these results?




How to randomly choose column value by Id number in Python?

How can I get a random single value by ID number based on a column value? I have a data frame (large data) similar to the following

ID city
a y
b x
a z
b w

Since I need to assign a unique city to each ID number, I would like to RANDOMLY choose between y and z for a and between x and w for b.

How can I do this?




Math.random() not working as expected in for loop in React app

I'm trying to build a function for a lorem ipsum page that takes an array of words, number of paragraphs, min/max numbers of sentences per paragraph, and min/max numbers of words per sentence. It should build array of paragraphs, with each paragraph containing an array of sentences, with each sentence containing an array of words. There should be a random number of sentences in each paragraph, between the min/max sentence parameters, and a random number of words in each sentence, between the min/max words parameters. The array of words that is used in the parameter has been randomized prior to this function and has a length equal to maxWords * maxSentences * numParagraphs

Full code below, but the issue I'm having is that for some reason the random numbers that are being generated for each sentence/paragraph are outside of the min/max bounds. The code used to generate the random numbers works fine in a Javascript sandbox, but is throwing out huge numbers when inside this function. I've included console.log statements I was trying to use to test what could be going wrong, as well as a screenshot of the console output after running the code. The console output came from running the function with the following parameters: numParagraphs=3, minWords=3, maxWords=5, minSentences=2, maxSentences=6.

generateParagraphObj(numParagraphs, minSentences, maxSentences, minWords, maxWords, wordArr){
    console.log('generateParagraph ran')
    let output = [];
    let wordArrayInd = 0;
    let numSentences;
    let numWords;
    console.log(Math.floor(Math.random() * (maxSentences + 1 - minSentences)) + minSentences);
    //for every paragraph
    for(let a = 0; a < numParagraphs; a++){
        console.log('paragraph built')
        let paragraph = [];
        //determine number of sentences
        console.log(`Sentence min is ${minSentences}`);
        console.log(`Sentence max is ${maxSentences}`);
        console.log(Math.floor(Math.random() * (maxSentences + 1 - minSentences)) + minSentences);
        numSentences = Math.floor(Math.random() * (maxSentences + 1 - minSentences) + minSentences);
        //for every sentence
        for(let b = 0; b < numSentences; b++){
            //determine number of words
            console.log('sentence built');
            numWords = Math.floor(Math.random() * (maxWords + 1 - minWords) + minWords);
            let sentence = wordArr.slice(wordArrayInd, wordArrayInd + numWords + 1);
            //update index in array of words to move onto next unused word for next sentence
            wordArrayInd = wordArrayInd + numWords;
            //push sentence into paragraph
            // paragraph.push(sentence);
            paragraph.push('test sentence');
        }
        //push paragraph into output
        output.push(paragraph);
    }
    return output;
}

console output

I know that there are more efficient ways to build the arrays I want, but all I want to know is why the Math.random() lines here aren't working.

Thanks!




np.random.choice not returning correct weights when vectorized

I've got some nulls to impute in a column of a df. The weights were taken from a value_counts() of the non nulls. The following line of code works perfectly and returns the correct weights, but takes too long because of the size of the df:

dataset_2021["genero_usuario"] = dataset_2021["genero_usuario"].apply(lambda x : x if pd.isnull(x) == False else np.random.choice(a = ["M","F"], p=[0.656,0.344]))

The faster vectorized version I want to use doesn't work. 1st attempt:

dataset_2021.loc[dataset_2021.genero_usuario.isnull(), dataset_2021.genero_usuario] = np.random.choice(a = ["M","F"], p=[0.656,0.344])

This throws the error:

Cannot mask with non-boolean array containing NA / NaN values

Second attempt:

dataset_2021.fillna(value = {"genero_usuario" : np.random.choice(a = ["M","F"], p=[0.656,0.344])}, inplace = True)

This decreases the weight of the "M" and increases the weight of the "F": the value_counts() give M 0.616 and F 0.384.

  1. Why does the 1st attempt give an error
  2. Why does the difference in weights happen? with lambda it remains equal
  3. How can I solve it? I don't want to use lambda, want the code to remain speedy.

Thanks in advance




Specific Bias Random Number Generation

I need to make a function to generate a random float between 0 and the max value for a float.

It needs to have a bias towards being lower and a distribution where on average the result would be 1. I was thinking about using a uniform random into log_p(x+1) with p being max/2 meaning that on average the result would be 1 but this would mean a max value out would be very low.

Any help would be appreciated.




Copy 10 random pictures from folder to another (python)

I have folder called "pictures" that contains over 1000+ pictures and I would like to randomly pick 10 pictures from this folder and copy them to the new folder called "copy_pictures". Thanks




Change x-axis values and background colour of a plot in R

I have to make a plot of the value of the last column of the following randomly generated dataset (in R):

l<-seq(from=0.2, to=0.3, by=0.02)
output<-as.data.frame(matrix(NA,length(l)*4, 3))
colnames(output)<-c("G", "l", "Value")
output$G<-rep(2:5, each=length(l))
output$l<-rep(l, 4)
output$Value<- rnorm(nrow(output))
plot(output$Value, type="l")  

The plot looks like this now

enter image description here

But I would like, if it is possible, to have on the x-axis the values of the column "l", which is just a vector repeated four times. Regarding the backgroung I was wondering if it is possible to divide the plot into four bins corresponding to the four different values of the column G (e.g., by alternating the colours of the background and adding a legend explaining the corresponding value of G).




vendredi 21 mai 2021

How To Random Select A String From List After Tabbing Button [Flutter]

i would like to press a button and pick a random string from my list to display somewhere on the screen. Currently, the convoTopic variable within the builder is running an error. Any help is appreciated!

Below is my truncated code:


final List<String> ConvoTopics = [
'blah blah',
'black sheep',
'balh bath'
];

class ConvoPage extends StatefulWidget {

  @override
  _ConvoPageState createState() => _ConvoPageState();
}

class _ConvoPageState extends State<ConvoPage> 

  @override
  Widget build(BuildContext context) {
    void generateConvoTopic() {
      final _random = Random();
      var convoTopic = ConvoTopics[_random.nextInt(ConvoTopics.length)];
      print(convoTopic);
    }

    return Scaffold(
      backgroundColor: Color(0xff04072E),
      appBar: AppBar(
        title: Text('Convo', style: TextStyle(color: Colors.white)),
        backgroundColor: Color(0xff04072E),
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          child: Column(children: <Widget>[
            Container(
                child: Align(
                    alignment: Alignment.center,
                    child: Text(convoTopic,
                    ),
// where randomized string appears
              ),
            ),
            ElevatedButton(
            
              onPressed: () async {
                generateConvoTopic();
              },
    // button's function is to randomize convo topic
              child: Container(
                child: Text('Get Convo'),
              ),
            ),
:
:
:




MLPclassifier from sklearn shows different accuracies when executed on other machine?

It looks like running the sklearn MLPclassifier with the same input on different devices will give different accuracy results, even if a global seed is set.

MWE:

import numpy as np
from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import train_test_split

np.random.seed(1)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, stratify=y, random_state=np.random.RandomState(0))

nn = MLPClassifier(hidden_layer_sizes=(100,100),
                   activation='relu',
                   solver='adam',
                   alpha=0.001,
                   batch_size=50,
                   learning_rate_init=0.01,
                   max_iter=1000,
                   random_state=np.random.RandomState(0))

nn.fit(X_train, y_train)


y_train_pred = nn.predict(X_train)
acc_train = np.sum(y_train == y_train_pred, axis=0) / X_train.shape[0]
y_test_pred = nn.predict(X_test)
acc_test = np.sum(y_test == y_test_pred, axis=0) / X_test.shape[0]
results.append([acc_train,acc_test])

How can reproducibility be guaranteed (independent of the executing device)?




How to show title and URL from SQL

I hope someone can help me with this puzzle!

I have this code:

    <?php

$user = 'myuser';
$pass = 'mypass';

try{
    $dbh = new PDO('mysql:host=localhost;dbname=mybase', $user, $pass);
    foreach($dbh->query('SELECT title FROM ads_listing') as $title);
    foreach($dbh->query('SELECT slug FROM ads_listing') as $slug){
    print_r($slug);
    print_r($title);
    }

    $dbh = null;
} catch (PDOException $e){
    print "ERROR!:" . $e->getMessage() . "<br/>";
    die();
}
?>

It display:

Array ( [slug] => laptop-dell-e6420-in-good-condition-tj304mkn910a8 [0] => laptop-dell-e6420-in-good-condition-tj304mkn910a8 ) 1Array ( [title] => VW POLO Comfortline [0] => VW POLO Comfortline ) 1Array ( [slug] => vw-polo-comfortline-rf839h9c9d065 [0] => vw-polo-comfortline-rf839h9c9d065 ) 1Array ( [title] => VW POLO Comfortline [0] => VW POLO Comfortline )

The goal is to display from my table 10 random titles as an URL with the slug like: VW POLO Comfortline, Laptop dell e6420 in good condition,.

How can I do it please?




Generate random number with large upper bound

I am trying to generate random numbers in Python over a very large range (e.g., from 1 to $2^80$) but I am getting the following error:

enter image description here

Any ideas of why this happens or how I can get around it?