dimanche 31 octobre 2021

How to write a recursive function that will return an index from large array [closed]

I have an array of the size 5000. From that 5000 items first I have to choose random 100 items and from that 100 items, I have to choose 50 random items. Similarly, I have to select half number of items until I get only 1 item.

  def hamster(data):
    rand_100 =[] #list of 100 random indices
    rand_50=[]   #list of 50 random indices
    rand_25=[]   #list of 25 random indices
    rand_12=[]   #list of 12 random indices
    rand_6=[]    #list of 6 random indices
    rand_3=[]    #list of 3 random indices
    rand_1=[]    #list of 1 random index 
    for i in range(100):
        rand = randint(0,5000)
        rand_100.append(rand)
    for i in range(50):
        rand = randint(0,len(rand_100)-1)
        rand_50.append(rand_100[rand])
        
    for i in range(25):
         rand = randint(0,len(rand_50)-1)
         rand_25.append(rand_50[rand])
    for i in range(12):
         rand = randint(0,len(rand_25)-1)
         rand_12.append(rand_25[rand])
    for i in range(6):
         rand = randint(0,len(rand_12)-1)
         rand_6.append(rand_12[rand])
    for i in range(3):
         rand = randint(0,len(rand_6)-1)
         rand_3.append(rand_6[rand])
    for i in range(1):
         rand = randint(0,len(rand_3)-1)
         rand_1.append(rand_3[rand])
    return data[rand_1[0]]



Dice roller repeat issue in python3 [duplicate]

I'm fairly new to programming in general and have been learning python3 for the last week or so. I tried building a dice roller and ran into an issue when asking the user if they wanted to repeat the roller or end the program.

import random as dice

d100 = dice.randint(1,100)
d20 = dice.randint(1,20)
d10 = dice.randint(1,10)
d8 = dice.randint(1,8)
d6 = dice.randint(1,6)
d4 = dice.randint(1,4)
d2 = dice.randint(1,2)

repeat = 'Y'
while repeat == 'Y' or 'y' or 'yes' or 'Yes':
    roll = (input('What would you like to roll? A d100, d20,  d10, d8, d6, d4, or d2?:'))
    quantity = (input('How many would you like to roll?'))
    quantity = int(quantity)
    if roll == 'd100':
        print('You rolled a: ' + str(d100 * quantity) + '!')

    elif roll == 'd20':
        print('You rolled a: ' + str(d20 * quantity) + '!')

    elif roll == 'd10':
        print('You rolled a: ' + str(d10 * quantity) + '!')

    elif roll == 'd8':
        print('You rolled a: ' + str(d8 * quantity) + '!')

    elif roll == 'd6':
        print('You rolled a: ' + str(d6 * quantity) + '!')

    elif roll == 'd4':
        print('You rolled a: ' + str(d4 * quantity) + '!')

    elif roll == 'd2':
        print('You rolled a: ' + str(d2 * quantity) + '!')        

    else:
        print('That is not an available die! Please select a die.')

    repeat = input('Would you like to continue?: ')
    if repeat == 'yes' or 'Y' or 'y' or 'Yes':
        continue

As of right now, despite what is input for the repeat variable it always continues even if it isn't "yes", "Y", "y", or "Yes". I'm sure the answer is simple and right in front of me but I'm stumped! Thanks in advance!




Choosing random function from a list

I've defined several variables with the questions, answers and category (Prize amount) for a "who wants to be a millionaire" kind of game. Then I have this function who runs based on those Questions, answers and whatnot. I've tried to use the random function of python through shuffle, choice, choices and haven't had success.

These are the question sort of format:

question1 = "QUESTION: What is the biggest currency in Europe?"
answers1 = ["A) Crown", "B) Peso", "C) Dolar", "D) Euro"]
correct1 = "D"
amount1 = 25
cat1= 1

question2 = "QUESTION: What is the biggest mountain in the world?"
answers2 = ["A) Everest", "B) Montblanc", "C) Popocatepepl", "D) K2"]
correct2 = "A"
amount2 = 25
cat2= 2

question3 = "QUESTION: What is the capital of Brasil?"
answers3 = ["A) Rio de Janeiro", "B) Brasilia", "C) Sao Paolo", "D) Recife"]
correct3 = "B"
amount3 = 25
cat3= 3

This is what I've tried: makign a list of those functions for the first category. It always prompts me the very first question of the list no matter what. Also, it also ignores the conditions set inside the main function who, in case you retire or have a wrong answer, the game is over.

rnd.choice=([questionnaire(question1,answers1,correct1,amount1,cat1), 
questionnaire(question2,answers2,correct2,amount2,cat2), 
questionnaire(question3,answers3,correct3,amount3,cat3),questionnaire(question4,answers4,correct4,amount4,cat4), questionnaire(question5,answers5,correct5,amount5,cat5)])

Here's the code for the function questionnaire:

def questionnaire (question,answers,correct,amount, cat):
 print (question) #Shows the question
 for answer in answers: #loop through answers, print answer.
  print(answer)
  usr_input_answer= input(" What's your answer? Please select between A, B, C, D or R for Retirement. ")
  if usr_input_answer.upper() == correct:
   moneymaker(amount)
  elif usr_input_answer.upper() == "R":
   retire()
  else:
   gameover()

Both retire and gameover functions will go back and set the status variable to 0 to prevent the game from running again. I tried running this random function inside a while loop, comparing this status variable and it ignores it.

TIA.




Select n keywords from list

I need to select only a certain number of (random) keywords from the list at a time and not make an API call with all the keys as is the case now. How can I proceed?

    # Search keywords definition
keywords = ["Televisori", "Notebook", "Tablet", "Apple", "Samsung", "Smartwatch", "Auricolari Bluetooth", "Fotocamera",
            "Videocamera"]

# run bot function
def run_bot(bot, keywords):
    # shuffling keywords list
    random.shuffle(keywords)

    # start loop
    while True:
        try:
            items_full = []

            # iterate over keywords
            for el in keywords:
                # iterate over pages
                for i in range(1, 10):

                    items = search_items(el, CATEGORY, item_page=i)

                    # api time limit for another http request is 1 second
                    time.sleep(1)

                    items_full.append(items)

            # concatenate all results
            items_full = list(chain(*items_full))



What means "slowest and quickest varying" in function 'stratified' of R-package 'splitstackshape'?

To generate stratified random samples, I follow this answer on stackoverflow, which uses the stratified function of R-package splitstackshape. In the section about the group argument, the R-documentation of splitstackshape says:

The column or columns that should be used to create the groups. Can be a character vector of column names (recommended) or a numeric vector of column positions. Generally, if you are using more than one variable to create your "strata", you should list them in the order of slowest varying to quickest varying. This can be a vector of names or column indexes.

What does "you should list them in the order of slowest varying to quickest varying" mean? Since the same question asked 2 years ago at github without any answer, it would be great to have an explanation and an example as well!




Randomize index without repeating C#

I want to create a program which would show the flag in a picture box and a user would have to guess what flag it is. I have a problem that flags are repeating and I totally don't know how to fix it.

Here is a bit of my code:

private void button1_Click(object sender, EventArgs e)
{
    Random random = new Random();
    randomized = random.Next(0, 9);
//0 = Poland
//1 = France
//2 = Sweden
//3 = Germany
//4 = Portugal
//5 = Spain
//6 = Finland
//7 = Norway
//8 = Russia
//9 = Ukraine

    
    if (randomized == 0)
    {
        ptbFlag.Image = Image.FromFile("C:/Users/Kacper/Desktop/FlagiDoGeo/Poland.png");
    }

    if (randomized == 1)
    {
        ptbFlag.Image = Image.FromFile("C:/Users/Kacper/Desktop/FlagiDoGeo/France.png");
    }

    if (randomized == 2)
    {
        ptbFlag.Image = Image.FromFile("C:/Users/Kacper/Desktop/FlagiDoGeo/Sweden.jpg");
    }

    if (randomized == 3)
    {
        ptbFlag.Image = Image.FromFile("C:/Users/Kacper/Desktop/FlagiDoGeo/Germany.png");
    }

    if (randomized == 4)
    {
        ptbFlag.Image = Image.FromFile("C:/Users/Kacper/Desktop/FlagiDoGeo/Portugal.png");
    }

    if (randomized == 5)
    {
        ptbFlag.Image = Image.FromFile("C:/Users/Kacper/Desktop/FlagiDoGeo/Spain.png");
    }

    if (randomized == 6)
    {
        ptbFlag.Image = Image.FromFile("C:/Users/Kacper/Desktop/FlagiDoGeo/Finland.png");
    }

    if (randomized == 7)
    {
        ptbFlag.Image = Image.FromFile("C:/Users/Kacper/Desktop/FlagiDoGeo/Norway.png");
    }

    if (randomized == 8)
    {
        ptbFlag.Image = Image.FromFile("C:/Users/Kacper/Desktop/FlagiDoGeo/Russia.png");
    }

    if (randomized == 9)
    {
        ptbFlag.Image = Image.FromFile("C:/Users/Kacper/Desktop/FlagiDoGeo/Ukraine.png");
    }
}



Random element between -x and x in javascript

Hi I would like to generate a random number between -x and x in JavaScript. This is what I have :

function randomInt(nb){
let absoluteVal = Math.ceil(Math.random()*nb)
let sign = Math.floor(Math.random()*2)
return sign == 1 ? absoluteVal*(-1) : absoluteVal;
}
console.log(randomInt(4))

It works but it is rather inelegant. I was wondering if somebody knew a better solution. Thanks in advance.




samedi 30 octobre 2021

Java program to ask user for a 6 digit sequence of face of a die(1-6), randomly roll the dice until we get the user input sequence. Print the attempt

Ask user for a 6 digit sequence of face of a die(1-6), randomly roll the dice until we get the user input sequence in order as the user put it in. Print the number of dice roll it took to print that sequence.

Example: Enter your sequence: 436232 The sequence '436232' took 872123 dice rolls


I think we can make a testSequence 000000 and concat every random dice face with the sample string and quit the loop once the concatonated string matches the user input sequence. But i dont know how to execute this.




Getting warning: Name 'guess' can be undefined

I am getting warning for the last guess in the last if statement. Can I just ignore that and be sure, there is no case for my program to work incorrectly?

import random
print('Try to guess hidden number from 1 to 50, U have 6 tries by the way')
hidden_num = random.randint(1, 50)
tries = 6
while tries>0:
    guess = int(input(f'Guess the hidden number, tries left: {tries}\n'))
    tries-=1
    if guess == hidden_num:
        print('Great Job, You got it!')
        break
    elif guess < hidden_num:
        print('U were so close, take a bit higher')
    else:
        print('WowWo! Pick lower,Dude!')
if guess != hidden_num and tries == 0:
    print('Don\'t be upset buddy, you have whole life ahead!')



how can i select a specify index from an array to use it in switch case

hi I'm beginner and i want to make a quiz math game how can i select a specify index of the random array and use it as case value.

                Random random=new Random();
                int num1= random.nextInt(30);
                int num2= random.nextInt(30);
    
                System.out.println(num1+"+"+num2+"=");
                int result=num1+num2;
    
                System.out.println("What is the answer of this operation?");
    
              int sugg1=random.nextInt(100);
              int sugg2=random.nextInt(100);
          
                int[] array = {sugg1,sugg2,result};
        
                Random rand = new Random();
        
                for (int i = 0; i < array.length; i++) {
                    int randomIndexToSwap = rand.nextInt(array.length);
    
                    int temp = array[randomIndexToSwap];
    
                    array[randomIndexToSwap] = array[i];
    
                    array[i] = temp;
                }
                System.out.println(Arrays.toString(array));

                switch (Arrays.toString(array)) {
//I NEED HELP HERE HOW CAN I SELECT A SPECIFY INDEX OF THE RANDOM ARRAY AND USE IT AS CASE VALUE
               case array:
                
               }



Generating a random line on a 2d array in python

I've got a 2d array of zeros: 250 by 250. And I want to generate a random straight random line of a specific length (haven't yet decided). Obviously, since it's a line the values that turn from zero to one must be connected in some way, vertically, horizontally, or diagonally; and it also has to be straight. How could I do this? I'm quite stuck with this problem, any help would be appreciated.




How can I run this function when it can work on CMD

module Examples where 
   import System.Random
   import Data.List
   cars = ["Ferrari", "Audi", "Honda","McLaren","Merc"]
   cmp (x1,y1) (x2,y2) = compare y1 y2
   [car | (car, n) <- sortBy cmp(zip cars (randoms (mkStdGen 123456) :: [Int]))]

I keep getting this error:

Parse error: module header, import declaration or top-level declaration expected. | 7 | [car | (car, n) <- sortBy cmp(zip cars (randoms (mkStdGen 123456) :: [Int]))] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ :reload

Does anyone have any idea for me to fix this so this function can run




DISTINCT and RND() on joined tables

I’m really struggling with how to write a query which randomly selects 50 DISTINCT random titles from one table in my MySQL database and then selects 1 random excerpt from each title from a separate table. The first table is titles and the second is excerpts.

I’ve tried two queries nested together but this either doesn’t work or returns duplicate titles despite supposedly being DISTINCT.

Could somebody please, PLEASE help me with where I’m going wrong?!

My existing PHP:

$distincttitlequery = “SELECT DISTINCT titleid FROM titles ORDER BY rand() LIMIT 50”;
$distincttitleresult = mysql_query($cxn,$distincttitlequery);
while ($distinctqueryreturn = mysqli_fetch_assoc($distincttitlequery))
{
extract ($distinctqueryreturn);
$selectedtitle = $titleid;

$randomexcerptquery = “SELECT excerpts.titleid, excerpts.excerptid, excerpts.excerptsynopsis, title.titleid, title.title FROM excerpts INNER JOIN titles ON excerpts.titleid=title.titleid WHERE titleid = ‘$selectedtitle’ ORDER BY rand() LIMIT 1”;
$randomexcerptresults = mysql_query($cxn,$randomexcerptquery);
while ($randomexcerptreturn = mysqli_fetch_assoc($randomexcerptquery))
{

[ECHO RESULTS HERE]

}};

I’ve read in similar posts about GROUP BY but I need to create a query which deals with distinct, random and joined tables and I have absolutely no idea where to start!

My existing code uses DISTINCT on multiple columns and joins the tables but this leads to titles being repeated in returned results. I can LIVE with that but I’d love to perfect it!

Thank you in advance for your help with this.




how to discard a random number after it has been used?

I am programming a program to test my chemistry knowledge. But I want once a random number appears, it won't appear a second time. For example, when the number 1 appears (hydrogen), it will not appear twice. How to do it? ---the programming language i am using is python--- My English is not good, so there is a grammar mistake, please forgive me THANKS FOR THE HELP

'''

from random import randint

computer = randint(1,20)
loop = True

if computer == 1:
    computer = 'Hidro'
if computer == 2:
    computer = 'Heli'
if computer == 3:
    computer = 'Liti'
if computer == 4:
    computer = 'Beri'
if computer == 5:
    computer = 'Bo'
if computer == 6:
    computer = 'Cacbon'
if computer == 7:
    computer = 'Nitơ'
if computer == 8:
    computer = 'Oxi'
if computer == 9:
    computer = 'Flo'
if computer == 10:
    computer = 'Neon'
if computer == 11:
    computer = 'Natri'
if computer == 12:
    computer = 'Magie'
if computer == 13:
    computer = 'Nhôm'
if computer == 14:
    computer = 'Silic'
if computer == 15:
    computer = 'Photpho'
if computer == 16:
    computer = 'Lưu Huỳnh'
if computer == 17:
    computer = 'Clo'
if computer == 18:
    computer = 'Agon'
if computer == 19:
    computer = 'Kali'
if computer == 20:
    computer = 'Canxi'

while loop:
    print('Nguyên tố:' + computer)
    choose = input('Nguyên Tử Khối:' )
    
    if computer == 'Hidro':
        if choose == '1':
            print('Đúng!')
        else:
            print('Học lại đi mày')
    if computer == 'Heli':
        if choose == '4':
            print('Đúng!')
        else:
            print('Học lại đi mày')
    if computer == 'Liti':
        if choose == '7':
            print('Đúng!')
        else:
            print('Học lại đi mày')
    if computer == 'Beri':
        if choose == '9':
            print('Đúng!')
        else:
            print('Học lại đi mày')
    if computer == 'Bo':
        if choose == '11':
            print('Đúng!')
        else:
            print('Học lại đi mày')
    if computer == 'Cacbon':
        if choose == '12':
            print('Đúng!')
        else:
            print('Học lại đi mày')
    if computer == 'Nitơ':
        if choose == '14':
            print('Đúng!')
        else:
            print('Học lại đi mày')
    if computer == 'Oxi':   
        if choose == '16':
            print('Đúng!')
        else:
            print('Học lại đi mày')
    if computer == 'Flo':   
        if choose == '19':
            print('Đúng!')
        else:
            print('Học lại đi mày')
    if computer == 'Neon':  
        if choose == '20':
            print('Đúng!')
        else:
            print('Học lại đi mày')
    if computer == 'Natri': 
        if choose == '23':
            print('Đúng!')
        else:
            print('Học lại đi mày')
    if computer == 'Magie': 
        if choose == '24':
            print('Đúng!')
        else:
            print('Học lại đi mày')
    if computer == 'Nhôm':  
        if choose == '27':
            print('Đúng!')
        else:
            print('Học lại đi mày')
    if computer == 'Silic': 
        if choose == '28':
            print('Đúng!')
        else:
            print('Học lại đi mày')
    if computer == 'Photpho':   
        if choose == '31':
            print('Đúng!')
        else:
            print('Học lại đi mày')
    if computer == 'Lưu Huỳnh': 
        if choose == '32':
            print('Đúng!')
        else:
            print('Học lại đi mày')
    if computer == 'Clo':   
        if choose == '35,5':
            print('Đúng!')
        else:
            print('Học lại đi mày')
    if computer == 'Agon':  
        if choose == '39,9':
            print('Đúng!')
        else:
            print('Học lại đi mày')
    if computer == 'Kali':  
        if choose == '39':
            print('Đúng!')
        else:
            print('Học lại đi mày')
    if computer == 'Canxi': 
        if choose == '40':
            print('Đúng!')
        else:
            print('Học lại đi mày')
    if choose == 'End':
        exit()

'''




Create a function which accepts a size integer number and generates a random 'word' with that size. For example [closed]

Create a function that accepts a size integer number and generates a random 'word' with that size. For example:

Input size of the random word: 5

Your random word with 5 characters is: wAnBc

I did some part but its wrong and i need some help.

import string as i
import random as r

n = int(input("Entrer size of the random word: "))

  
rnd = [chr(r.randint(ord('a'), ord('z') and ord('A'), ord('Z'))) for d in range(n)]
print(rnd)




vendredi 29 octobre 2021

How can I add an error statement in a loop if the user entered letters instead of numbers but the program should continue

package sample;

import java.util.Scanner; import java.util.Random;

public class Main {

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    Random rand = new Random();
    int playerGuess;
    int randomNum = rand.nextInt(50) + 1;
    int numberOfAttempts = 0;
    while (true) {
        System.out.println("Guess a number from 1 to 50: ");
        playerGuess = scan.nextInt();
        numberOfAttempts++;

        if (playerGuess == randomNum) {
            System.out.println("Congratulations! The number was: " + randomNum);
            System.out.println("You got it in " + numberOfAttempts + " attempts.");
            break;
        }
        else if (randomNum > playerGuess) {
            System.out.println("Your guess is too low. Try again.");
        }
        else {
            System.out.println("Your guess is too high. Try again.");
        }
    }
}

}My program works fine but I forgot how to add an error statement in a loop. Can someone help me where and how to add an error statement when the user entered letters instead of numbers. Thank you in advance! :)))




PROBLEM Generate random numbers using rand() in C

I'm making program where user enters numbers and program will find MAX and MIN + position of these numbers. I want to give the user a choice for the program to fill in the numbers for him using rand(). It's working almost perfect, program will find the MAX number with the position but the problem occurs when printing MIN number with position - always prints number 8 and position 1. Where is the problem? Finding MAX number is working but program cannot find MIN number. I just can't find the solution for this problem. Thank you for your help 🙂 Here is my code:

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

typedef struct elementposition
{
    int min;
    int max;
    int positionMax;
    int positionMin;
}elementposition;

int main()
{
    struct elementposition minmax;
    srand(time(NULL));
    int a[500], i;
    int c = sizeof(a) / sizeof(a[0]);
    char y;

    printf("How many numbers you want to enter: ");
    scanf("%d", &c);
    minmax.positionMax=minmax.positionMin = 0;

    printf("Want to fill with random numbers? (Y/N)");
    scanf(" %c",&y);

    if(y == 'Y'||y == 'y')
    {
        for(i = 0; i < c; i++)
        {
            a[i] = rand() % 10000 + 1;

            if(minmax.max < a[i])
            {
                minmax.max = a[i];
                minmax.positionMax = i;
            }

            if(minmax.min > a[i])
            {
                minmax.min = a[i];
                minmax.positionMin = i;
            }
        }

        for(i = 0; i < c; i++)
        {
            printf("Number #%d: %d\n", i + 1, a[i]);
        }
    }
    else
    {

    printf("------------------------------------ \n");

    printf("Enter (%d) numbers: \n", c);
    scanf("%d",&a[0]);
    minmax.max = minmax.min = a[0];

    for(i = 1; i < c; i++)
    {
        scanf("%d", &a[i]);

        if(minmax.max < a[i])
        {
            minmax.max = a[i];
            minmax.positionMax = i;
        }

        if(minmax.min > a[i])
        {
            minmax.min = a[i];
            minmax.positionMin = i;
        }
    }
}
        printf("\nMax number is %d, number position %d. \n", minmax.max, minmax.positionMax+1);
        printf("Min number is %d, number position %d. \n", minmax.min, minmax.positionMin+1);

     printf("------------------------------------ \n");

    getch();
    return 0;
}



VBA: Select random cells based on conditions

I have 100 different clients with only 3 types (A, B or C). I would like to select (at random) 3 clients with Type A, 2 with type B and 30 with Type C - we can add 'y' in columne C.

enter image description here

Not sure how can I start here - thanks for any hints.




jeudi 28 octobre 2021

Picking rows from two NumPy arrays at random

Starting from two numpy arrays:

A = np.array([[1, 2], [2, 3], [3, 4], [4, 5]])
B = np.array([[9, 8], [8, 7], [7, 6], [6, 5]])

I would like to create a new array C picking, for each index, one row from the same index but randomly from A or B. The idea is that at each index of random_selector, if the value is higher than 0.1, then we chose the same-index row from A, otherwise, the same-index row from B.

random_selector = np.random.random(size=len(A))

C = np.where(random_selector > .1, A, B)

# example of desired result picking rows from respectively A, B, B, A:
# [[1, 2], [8, 7], [7, 6], [4, 5]]

Running the above code, however, produces the following error:

ValueError: operands could not be broadcast together with shapes (4,) (4,2) (4,2) 



In R, how can I get PRNG to give identical floating point numbers between platforms?

Running the following code in R 4.1.1 gives different results between platforms.

set.seed(1)
x <- rnorm(3)[3]
print(x, 22)

From Intel Windows:

#    1234567890123456 (digits)
# -0.83562861241004716

From M1 Mac:

#    1234567890123456 (digits)
# -0.8356286124100471557341

I know the size of difference is below .Machine$double.eps and the extra digits do not carry meaningful information.

I am not happy with the fact that extra digits exist. How can I ensure exactly consistent results? Is there an RNG library that achieves this?

round(x, 15) does not work:

print(round(x, 15), 22)
# -0.83562861241004704      (Intel Windows)
# -0.8356286124100470447118 (M1 Mac)



SQL Server CHOOSE() function behaving unexpectedly with RAND() function

I've encountered an interesting SQL server behaviour while trying to generate random values in T-sql using RAND and CHOOSE functions.

My goal was to try to return one of two given values using RAND() as rng. Pretty easy right?

For those of you who don't know it, CHOOSE function accepts in an index number(int) along with a collection of values and returns a value at specified index. Pretty straightforward.

At first attempt my SQL looked like this:

    select choose(ceiling((rand()*2)) ,'a','b')

To my surprise, this expression returned one of three values: null, 'a' or 'b'. Since I didn't expect the null value i started digging. RAND() function returns a float in range from 0(included) to 1 (excluded). Since I'm multiplying it by 2, it should return values anywhere in range from 0(included) to 2 (excluded). Therefore after use of CEILING function final value should be one of: 0,1,2. After realising that i extended the value list by 'c' to check whether that'd be perhaps returned. I also checked the docs page of CEILING and learnt that:

Return values have the same type as numeric_expression.

I assumed the CEILINGfunction returned int, but in this case would mean that the value is implicitly cast to int before being used in CHOOSE, which sure enough is stated on the docs page:

If the provided index value has a numeric data type other than int, then the value is implicitly converted to an integer.

Just in case I added an explicit cast. My SQL query looks like this now:

    select choose(cast(ceiling((rand()*2)) as int) ,'a','b','c')

However, the result set didn't change. To check which values cause the problem I tried generating the value beforehand and selecting it alongside the CHOOSE result. It looked like this:

    declare @int int = cast(ceiling((rand()*2)) as int)
    select @int,choose( @int,'a','b','c') 

Interestingly enough, now the result set changed to (1,a), (2,b) which was my original goal. After delving deeper in the CHOOSE docs page and some testing i learned that 'null' is returned in one of two cases:

  1. Given index is a null
  2. Given index is out of range

In this case that would mean that index value when generated inside the SELECT statement is either 0 or above 2/3 (I'm assuming that negative numbers are not possible here and CHOOSE function indexes from 1). As I've stated before 0 should be one of possibilities of:

    ceiling((rand()*2))

,but for some reason it's never 0 (at least when i tried it 1 million+ times like this)

    set nocount on
    
    declare @test table(ceiling_rand int)
    declare @counter int = 0
    
    while @counter<1000000
    begin
    insert into @test 
    select ceiling((rand()*2))
    
    set @counter=@counter+1
    end
    
    select distinct ceiling_rand from @test

Therefore I assume that the value generated in SELECT is greater than 2/3 or NULL. Why would it be like this only when generated in SELECT statement? Perhaps order of resolving CAST, CELING or RAND inside SELECT is different than it would seem? It's true I've only tried it a limited number of times, but at this point the chances of it being a statistical fluctuation are extremely small. Is it somehow a floating-point error? I truly am stumbled and looking forward to any explanation.

TL;DR: When generating a random number inside a SELECT statement result set of possible values is different then when it's generated before the SELECT statement.

Cheers, NFSU

EDIT: Formatting




Excel random value from a string containing substrings

I have this table that is defined as "Table1".

enter image description here

I also have a string which contains substrings inside it with delimiter ", " (comma + space)

I would like to get a formula to get one of those substrings randomly.

Excel version: Excel 365

Thanks in advance.




sklearn RandomForestClassifier.fit() not reproducible despite set random state and same input

While tuning a random forest model using Scikit-learn I noticed that its accuracy score was different after different runs, even though I used the same RandomForestClassifier instance and the same data as input. I tried googling and the stackExchange search function, but the only case I could find vaguely similar to this one is this post, but there the problem was instantiating the classifier without proper random state, which is not the case for my problem.

I'm using the following code:

clf = RandomForestClassifier( n_estimators=65, max_features = 9, max_depth= 'sqrt', random_state = np.random.RandomState(123) )

X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.3, random_state = np.random.RandomState(159) )
clf.fit(X_train, y_train)
y_pred=clf.predict(X_test)

X and y are my data and the corresponding labels, but I found the dataset didn't influence the problem. When I run the train_test_split line I get the same split every time, so no randomness there. Running predict() with the same fitted model also gives the same results every time, suggesting my problem is different from the post I linked to above. However, after every time I run fit(), predict() will give a different prediction! This happens even when I don't touch X_train and y_train. So just running these two lines

clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)

gives a different result every time. As far as I can tell from the documentation .fit() is not supposed to do anything random. Without reproducible output it is impossible to tune the model, so I'm pretty sure there is an error somewhere. What am I missing? Has anyone encountered this before, or does anyone have any clue as to why this is happening?




Random of Table Header Name of another table via INDEX MATCH

I have these 2 tables: enter image description here

On column B i'm trying to get one of the Header Names of a feature that is not empty on Table B. I want it to be selected randomly. The order of the items in Table A can be different than the order of the items in Table B, I'll need some sort of INDEX MATCH here too.

Any help will be greatly appreciated.




How do I use gshuf to randomly shuffle files in a folder on mac os?

I am trying to randomly shuffle the files in a folder on my mac. I came across a suggestion to use gshuf (part of coreutils), but I don't know exactly what command to enter.

First I tried going into the folder and typing gshuf, and that didn't seem to do anything so I hit control-c to exit. Then I tried gshuf and the folder path, and I got an error:

gshuf /Users/xxx
gshuf: read error: Is a directory

Anyone know how to make it work?




(Google Sheets Apps Script) How do I get different results with the same random function using an image click?

I am making a WTF-type random character generator. I am new to Google apps script, but I got it working via an image click. My next goal is to get multiple different results using the same method. The problem I'm running into is that it's giving the same result for each different cell. I've tried using Utilities.sleep() and waitForAllDataExecutionsCompletion() but ultimately I'm out of my depth.

How do I fix this?

function dungeonsAndDragonsChoices() {
  dND1();
  dND2();
  dND3();
  dND4();
  dND5();
  dND6();
}

function dND1() {
  ss.setActiveCell('E2').setValue(randomMood+" "+ddrandomAncestry+" "+ddrandomClass+" from "+ddrandomHome+" "+randomQuirk);
}
function dND2() {
  ss.setActiveCell('E5').setValue(randomMood+" "+ddrandomAncestry+" "+ddrandomClass+" from "+ddrandomHome+" "+randomQuirk);
}
function dND3() {
  ss.setActiveCell('E8').setValue(randomMood+" "+ddrandomAncestry+" "+ddrandomClass+" from "+ddrandomHome+" "+randomQuirk);
}
function dND4() {
  ss.setActiveCell('E11').setValue(randomMood+" "+ddrandomAncestry+" "+ddrandomClass+" from "+ddrandomHome+" "+randomQuirk);
}
function dND5() {
  ss.setActiveCell('E14').setValue(randomMood+" "+ddrandomAncestry+" "+ddrandomClass+" from "+ddrandomHome+" "+randomQuirk);
}
function dND6() {
  ss.setActiveCell('E17').setValue(randomMood+" "+ddrandomAncestry+" "+ddrandomClass+" from "+ddrandomHome+" "+randomQuirk);
}

(I'm sure this can be made prettier, but I'm new at it and I was trying to make everything easily readable)




How to randomize char symbols in c++

I just started learning C++. I want my code to print symbols in random order using array, why doesn't it work?

#include<iostream>
#include<ctime>
#include<cstdlib>

using namespace std;


int main() {
    const int rnd = 4;
    char arr[rnd] = { 'H', 'E', 'L', 'L' };
    srand(time(NULL));
    for (int i = 0; i <= arr[rnd]; i++) {
        arr[i] = rand();
        cout << arr[i];
    }
    return 0;
}



mercredi 27 octobre 2021

Moving spatial data off gird cell corners

I have a seemingly simple question that I can’t seem to figure out. I have a large dataset of millions of data points. Each data point represents a single fish with its biological information as well as when and where it was caught. I am running some statistics on these data and have been having issues which I have finally tracked down to some data points having latitude and longitude values that fall exactly on the corners of the grid cells which I am using to bin my data. When these fish with lats and long that fall exactly onto grid cell corners are grouped into their appropriate grid cell, they end up being duplicated 4 times (one for each cell that touches the grid cell corner their lats and long identify).

Needless to say this is bad and I need to force those animals to have lats and long that don’t put them exactly on a grid cell corner. I realize there are probably lots of ways to correct something like this but what I really need is a simply way to identify latitudes and longitudes that have integer values, and then to modify them by a very small amount (randomly adding or subtracting) so as to shift them into a specific cell without creating a bias by shifting them all the same way.

I hope this explanation makes sense. I have included a very simple example in order to provide a workable problem.

fish <- data.frame(fish=1:10, lat=c(25,25,25,25.01,25.2,25.1,25.5,25.7,25,25), 
                   long=c(140,140,140,140.23,140.01,140.44,140.2,140.05,140,140))

In this fish data frame there are 10 fish, each with an associated latitude and longitude. Fish 1, 2, 3, 9, and 10 have integer lat and long values that will place them exactly on the corners of my grid cells. I need some way of shifting just these values by something like plus are minus 0.01.

I can identify which lats or longs are integers easy enough with something like:

fish %>%
  near(as.integer(fish$lat))

But am struggling to find a way to then modify all the integer values by some small amount.




how to count a list of numbers which occour in a random list Python

I run 1000 times of random.choice()from a list from 0-11. how to track of the number of random selections necessary before all 12 number have been selected at least once. (Many will be selected more than once.) For instance, suppose the simulation yields the following sequence of random choices for a single trial: 2 5 6 8 2 9 11 10 6 3 1 9 7 10 0 7 0 7 4, where all 12 numbers have been selected at least once. The count for this example trial is 19. Collect the count for each trial of the simulation in a single list (ultimately consisting of 1,000 counts).




How can I generate equally distributed random numbers in a range and with decimal places in bash?

How can I generate equally distributed random numbers in a range and with p.e, 2 or 5 decimal places in bash ?

Bash usually only supports whole numbers. However, numbers with decimal places can be used in bash, e.g. with the command sleep: sleep 1.23456 # sleep time in s

Given is the following example, which can generate with bash in a range from 0 to 10, equally distributed random numbers without decimal places.

ug_rnd=0
og_rnd=10

rnd="$((0x$(dd if=/dev/urandom of=/dev/stdout bs=4 count=1 status=none | xxd -p)))"
        my_rnd=$((rnd%(og_rnd-ug_rnd+1)+ug_rnd));        
        echo "$my_rnd"



How to create a NumPy array of booleans with k% True values?

I know that we can create a NumPy array of boolean values with the following line of code:

np.random.choice(a=[False, True], size=(N,))

But what if I want to specify that I want this random array to have around 60% (or more generally k%) True values?




how to find random documents without repetition in Mongoose?

I'm working on a nodejs website in which I have Sentences database, and each time I need to randomly display a sentence that is different from the sentences already displayed till all sentences from the database are displayed.

here's some of the code I wrote:

app.get('/sentencePage', (request, response) => {
  var randID =
    request.app.locals.sentences_count[
      Math.floor(Math.random() * request.app.locals.sentences_count.length)
    ];
  Sentence.findOne({})
    .skip(randID)
    .exec(function (err, sentence_obj) {
      var index = request.app.locals.sentences_count.indexOf(randID);
      if (index > -1) {
        request.app.locals.sentences_count.splice(index, 1);
        userObj = UserDetail.findById(
          request.app.locals.user_id,
          function (err, user) {
            if (user.displayed < 20) {
              // update to db
              UserDetail.updateOne(
                { _id: user._id },
                { $inc: { displayed: 1 } },
                function (err, res) {}
              );
              request.app.locals.sentence = sentence_obj;
              response.render('sentencePage', { data: sentence_obj });
            } else {
              response.redirect('/end');
            }
          }
        );
      } else {
        response.redirect('/end');
      }
    });
});

The problem with this code is that sometimes the Sentence.findOne().skip(randID) returns null and then no sentence can be displayed.

I will truely grateful if anyone could has a clue what is the problem.

note that:

sentences_count: array that has the number from 1 to the number of sentences in the database

UserDetail : database that holds information about users

user.displayed: number of sentences already displayed to that specific user.

Thanks




mardi 26 octobre 2021

Picking a number that prevents a for loop from breaking in R

In my code below, if you keep increasing n, there is a point (in this example, n = 14) at which the sample() call inside the for loop breaks, throwing an error that n is larger than unique_study.

To prevent this automatically, can we internally (inside the for loop) change n to the nearest non-breakable number (in this example, n = 13)?

To be clear, 13 IS NOT given, user provides 14, program should find 13 and change n to 13.

library(tidyverse)

data <- expand_grid(study=1:40,group=1:2, time=0:4)

n = 14 # smaller than this will work
time_to_remove <- unique(data$time)[-(1:2)]
unique_study <- unique(data$study)

for(i in time_to_remove) {
  studies_to_remove = sample(unique_study, size = n) # change `n` to 13 HERE
  unique_study <- setdiff(unique_study, studies_to_remove)
  dat <- data %>%
    filter(
      !(   study %in% studies_to_remove &
             time >= i ))
}



Python random.choices, how to get less deviation from expected probability?

With arrays for traitname and traitWeights Using trait["traitX"] = random.choices(traitName, traitxWeights)[0] all works fine. Currently using 5 x different traits (so 5x sets of item/weight). I return a number of random combinations of all 5. All good so far.

Problem: Results for multiple traits are dumped to JSON and CSV. I open the CSV to test if distribution of traits was similar to expected - and it's not. It deviates by an average of around 6, no matter how I change weights or specify them, every test has approximately the same average deviation.

Meaning, if my weights sum to 100, and I generate 100 random picks, then for weights of [10, 20, 30, 40] I'd expect close to results of: 10 of a, 20 of b, 30 of c, 40 of d. Not exactly that amount of course. But close.

Instead I can get results like 4, 26, 28, 42. Which is a very different distribution.

This is a simplified example, in reality I have 150 options for trait a, 100 for trait b, etc. So across 150 things, the average deviation is 6. Some deviate from the expected amount by 1 or 2, OK. But then some deviate by 20. Like I said, average remains 6-ish. But the big swings are having too much effect on my intended distribution.

Desired Outcome: What would I use either different to, or in conjunction with, random.choices to generate outcomes more closely aligned with the probabilities? If I hard-code accepted deviation for traits that could work, but it will also be a ton of checks and ifs and it seems slow and unwieldy.

Thanks kindly




Generating a random matrix element by element randomly picked

I have to generate a random matrix with the following characteristics: A nxn (for the example 3x3) matrix, then pick a random element (i,j), say (2,3) and use it in the program to fill a cell in with a random number between 0 and 1 (uniform distribution works). If the sum of that column (3) is greater than 1, then that random number becomes 0, if not, it continues to be that random number. Then, I should continue with the other elements, see that (2,3) is not longer in my options:

(1, 1), (1,2), (1,3), (2,1), (2,2), …, (3,1), (3,2), (3,3)

And we now select randomly from this set, say (1,1), do the same (if the sum column of 1 is greater than 1, then (1,1) becomes 0). Then we have:

…, (1,2), (1,3), (2,1), (2,2), …, (3,1), (3,2), (3,3)

Any suggestion?




random.seed does not work in Python 3.9.7 using Spyder

very simple program given below.

import random
random.random()
random.seed(3)

Gives error message as File "C:\Users\admin\ram_stuff\Pythonprogs\random_passwd.py", line 11, in random.seed(3)

TypeError: 'int' object is not callable

I can go to cmd window in Windows10 and it runs fine.

C:\Users\admin>python
Python 3.9.7 (tags/v3.9.7:1016ef3, Aug 30 2021, 20:19:38) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

>>> import random
>>> random.random()
0.7989453624569347
>>> random.seed(3)
>>> random.random()
0.23796462709189137

Thank you.




Posting after loging in with MD5 HASH

I'm want to send some text to change the Title Text of my camera i can do that in a browser with: (I will use that later to add some variables (temperatuur info and other info from my home automation)

http://192.168.1.123/cgi-bin/configManager.cgi?action=setConfig&ChannelTitle[0].Name.CustomTitle[1].Text=TEST

and then i have to fill in my inlog credentialos i have found pythonscript that login to my camera.

A part of the script:

print "[Logging in"

query_args = {"method":"global.login",
    "session":json_obj['session'],
    "params":{
        "userName":USER_NAME,
        "password":RANDOM_HASH,
        "clientType":"Web3.0",
        "authorityType":"Default"},
    "id":10000}

URI = '/RPC2_Login'
response = HTTPconnect(self.rhost,self.proto,self.verbose,self.credentials,self.Raw).Send(URI,headers,query_args,json_obj['session'])
print response.read()

With the result:

[>] Logging in
[Verbose] Sending: http://192.168.10.185:80/RPC2_Login
[<] 200 OK
{ "id" : 10000, "params" : null, "result" : true, "session" : 1998182089 }

How can i excuted the following after the login

/cgi-bin/configManager.cgi?action=setConfig&ChannelTitle[0].Name.CustomTitle[1].Text=TEST



How to specify array indexes to be randomized?

I have an initial combination randomizer, producing a randomized binary array.

np.random.binomial(1, 0.5, 20)

The question is - is there a way to specify indexes to be randomized within the array? perhaps anything from the numpy set of tools? or would that be a specified loop?




select random indices from 2d array

I want to generate a 2d random array and select some(m) random indices to alter their values by predefined values(m).

For an example here, I want to generate 4 by 4 matrix. Then select 4 random indices and alter their values with [105,110,115,120] this values.

random_matrix = np.random.randint(0,100,(4,4))

# array([[27, 20,  2,  8],
#        [43, 88, 14, 63],
#        [ 5, 55,  4, 72],
#        [59, 49, 84, 96]])

Now, I want to randomly select 4 indices and alter their values from predefined p_array = [105,110,115,120]

I try to generate all the indices like this:

[
    (i,j)
    for i in range(len(random_matrix)) 
    for j in range(len(random_matrix[i])) 
]

But how to select 4 random indices from this and alter their values from predefined p_matrix? I couldn't think of any solution because I have to ensure 4 unique random indices where I stuck badly, as randomness haven't that guarantee.

Can we generate random matrix and selecting indices in a single shot? I need that because if the size of m getting larger and larger than it will be getting slower (current implementation). I have to ensure performance also.




Why does a randomizer act like a 'generator'

I am trying to make a simple rock paper scissors game on python

TypeError: unsupported operand type(s) for +: 'generator' and 'str'

This was the error message, that was given after I placed a randomizer in the code:

Traceback (most recent call last)

<ipython-input-4-dea4c40cfdcd> in <module>()
 49   if key == 'q':
 50     break
---> 51   player_score, comp_score = gameplay(player_score, comp_score)
 52   print('Score is: YOU ', player_score, ' - ', comp_score, ' COMPUTER')
 53   print('')

 <ipython-input-4-dea4c40cfdcd> in gameplay(player_score, comp_score)
 12 
 13   comp_move = moves[randomize]
 ---> 14   battle = key + '-' + comp_move
 15 
 16   comp_print = (word for position, word in ['rock', 'paper', 'scissors'] if position == randomize - 1)

What is this 'generator' object?? In google they say it is made from using a loop, so it is a kind of sequence, but didn't generate it with loop, rather than while loop. Is this loop the reason for the error? Moreover, I am not using the sequence of letters, but only a single letter from it, and I am calling it with its position number in the sequence?

Here is the code until the error:

 from random import randint

 player_score = 0
 comp_score = 0
 key = None

 # Setting the rules
 choices = {'r-s': 'rock breaks scissors', 'p-r': 'paper envelopes rock', 's-p': 'scissors cut paper'}
 moves = {1: 'r', 2: 'p', 3: 's'}

 def gameplay(player_score, comp_score):

   comp_move = moves[randomize]
   battle = key + '-' + comp_move

Here are more details about the code: the random number is initialized inside the while loop

while True:
  randomize = randint(1, 3)
  print('<r>ock, <p>aper or <s>cissors? Press any key to continue; <q> for exit')
  key = check_input()
  if key == 'q':
    break
  player_score, comp_score = gameplay(player_score, comp_score)
  print('Score is: YOU ', player_score, ' - ', comp_score, ' COMPUTER')
  print('')
  key = None

however, I am using a single variable not a sequence of variables here, or am I wrong?




In Tricentis Tosca, about random expressions

I am working on an website in which I have to automate it so, I created an test step, in which I used 2 "random expressions" - 1. phone number and 2. Email....But In another test step I have to verify them whether the phone number and email are displaying or not. My doubt is like how can we verify them if they change every time we run the test case??

Thank you.




Unbiased Shuffling with Large Number of Duplicates

The Fisher–Yates algorithm generates unbiased random permutations of a finite sequence. The running time is proportional to the number elements being shuffled.

I want to shuffle a few non-zero elements with a large number of zero elements.

Implementing the Fisher–Yates algorithm with a list would lead to the shuffling process taking too long and requiring too much storage. Most steps in the Fisher--Yates algorithm would simply switch the position of duplicate zero elements.

Does there exists a random shuffle (or alternative) algorithm that:

  1. Leads to unbiased permutations
  2. Does not require the shuffling and storing of all duplicate elements



Setting a condition for `sample()` in `group_by()`

Below, I'm trying to randomly select the rows of a group value in each study in my data.

First, we group_by(study), then, randomly pick one of the group's rows in each study (see below).

But there is little issue. group elements have an order. So, after sample()ing them, we can't end up with any study that only has: group = 2, or group = 3, or group = 2,3. We should only end up either with: group = 1, or group= 1,2 or group = 1,2,3.

I think the solution is that whenever sample() picks a group value that is larger than 1 (e.g., 2), then rename that to 1.

I wonder how such a condition/modification can be added to my current code below?

library(tidyverse)

(data <- expand_grid(study=1:3,group=1:3,outcome=c("A","B"), time=0:1) %>%
    as.data.frame())

return_rows <- function(x) {
  u <- unique(x)
  n <- sample(c(min(u)-1, u), 1) #If n = n[1] select all group values 
  if(n == n[1]) TRUE else x == n  # Else, select row for corresponding group
}

set.seed(0) ### For reproducibility 
data %>%
  group_by(study) %>%
  filter(return_rows(group)) %>%
  ungroup() %>% as.data.frame()



lundi 25 octobre 2021

how to use dbfaker to generate non duplicate data

when I use dbfaker to make test data, I use field definition in yml file like sample below:

org_name:
      comment: 部门
      engine: choice(['人行','工行','农行','中行','建行','交行'])

when I use choice, It comes out there are duplicate org_name in test data, How can I achive the method to get non duplicate org_name in test data

random.sample function needs k to get a list result, and neither can make non duplicate data

dbfaker




Preventing some some elements from being `sample()`ed in a for loop

My for loop below uses elements in time_to_remove to remove them randomly a study. The available elements of time to remove are: 2, 3, 4.

But there is little issue. time elements have an order. So, after sample()ing for removal, we can't end up with: time = 0,1,3 or time = 0,1,2,4 etc. We should only end up with: time = 0,1, time = 0,1,2, time=0,1,2,3 or time=0,1,2,3,4.

I wonder if such a condition can be added to my current code below?

library(tidyverse)
data <- expand_grid(study=1:4,group=1:2, time=0:4)

n = 1
time_to_remove <- unique(data$time)[-(1:2)]
unique_study <- unique(data$study)

for(i in time_to_remove) {
  studies_to_remove = sample(unique_study, size = n)
  time_to_remove = i
  unique_study <- setdiff(unique_study, studies_to_remove)
  data <- data %>%
    filter(
      !(   study %in% studies_to_remove &
            time %in% time_to_remove ))
}
data %>% as.data.frame()



Create a random BigInt for Miller-Rabin test

I'm implementing a Miller Rabin primality test using JavaScript BigInts.

The basic algorithm is no problem - I have that done, but it requires a random number in the range 0 to (number being tested-3). I can't use Math.random() and scale since I'm using BigInt.

This doesn't need to be cryptographically secure, just random enough, so I've opted for generating a string of randomly selected hex digits and converting that to a BigInt.

Here's the code:

function getRandomBigint(lower, upper) {

    // Convert to hex strings so that we know how many digits to generate
    let hexDigits = new Array(upper.toString(16).length).fill('');
    let rand;
    let newDigits;
    do {
        // Fill the array with random hex digits and convert to a BigInt
        newDigits = hexDigits.map(()=>Math.floor(Math.random()*16).toString(16));
        rand = BigInt('0x'+newDigits.join(''));
    } while (rand < lower || rand > upper);
    return rand;
}

The problem here is that the generated number could be out of range. This function handles that (badly) by iterating until it gets a number in range. Obviously, that could potentially take a very long time. In practice it has never iterated more than a couple of dozen times before delivering a number, but the nature of randomness means that the problem is 'out there' waiting to bite me!

I could scale or truncate the result to get it in range, rather than iterating, but I am concerned that this would affect the randomness. I already have some evidence that this is not as random as it might be, but that might not matter in this application.

So, two questions:

  • is this random enough for Miller Rabin?
  • how to deal with results out of range?

This is a JavaScript-only project - no libraries, please.




Example vor double precision random generator with AVX, AVX2 andAVX512

After some research I'm quite confused and not able to find a vectorized double precision random generator (uniform or normal distribution, that doesn`t matter), using AVX, AVX2 or AVX512. Is anyone able to post a minimal working example (for all AVX versions, if possible), that return n double precision random numbers?




How to generate random numbers in [0 ... 1.0] in Common Lisp

My understanding of Common Lisp pseudorandom number generation is that (random 1.0) will generate a fraction strictly less than 1. I would like to get numbers upto 1.0 inclusive. Is this possible? I guess I could decide on a degree of precision and generate integers and divide by the range but I'd like to know if there is a more widely accepted way of doing this. Thanks.




How to generate random values from a distribution with known density function in R?

I am given Zi's (i = 1,2...) form a sequence of i.i.d variables with density function:

fZ(z) = P(S1 > z)/E(S1)

Given that I know S1 follows a Pareto(1.7,70) distribution and E(S1) is equal to 100, how would i use R to obtain/generate random values of Z? Like we all know how to generate random values of a normal distribution by using rnorm(), but what if our density was custom such as above? How would I simulate values that fit that distribution?

Thank you




dimanche 24 octobre 2021

Why are my random numbers not changing accordingly in Excel?

I have some code below that generates some random numbers in Excel:

Sub Macro1()

Dim RA1 As Variant
ReDim RA1(1 To 5)

For i = 1 To 5

    Rnd (-1)
    Randomize i

    For j = 1 To 5
            
        RA1(j) = Rnd
                             
    Next j
    
    With Sheets("Sheet1")
    
        .Range(Cells(i, 1), Cells(i, 5)).Value = RA1
        
    End With
    
Next i

End Sub

This code basically generates 5 rows of 5 random numbers, but it is not running exactly as it should. When I run this code on my iMac (2021), the random numbers in each row are exactly the same. However, what this code should be generating are 5 different rows of random numbers.

Here is where things become even weirder. When I run this code on my Windows laptop, the output is as desired - that is, I do indeed get 5 different rows of random numbers. I have spoken to my professor about this and he has tried it on his Windows computer too and got 5 different rows of random numbers.

We have come to the conclusion that it is some setting in my iMac's Excel that is preventing this code from running as it should. My professor also suspects that it is not inherently an Apple issue, since he says no one has come to him with this problem before.

All in all, we basically do not know why my iMac is unable to run this code. Does anyone have any guesses as to why there is this discrepancy here? For example, are there any settings in my iMac's Excel that is preventing my code from running correctly?

Any explanations and solutions will be greatly appreciated! :)

Note: I have not changed any setting in my iMac's Excel before (well, at least, not that I know of), so everything should be default as of now.




I need my webpage to play random videos but the JS keeps repeating the same random video unless I refresh webpage

The HTML section loops but repeatedly plays the same randomly selected video selected by the JS. If I refresh the html it will play a different video. I would like it to choose a different random video after each delayms expires. I apologize, I am kind of new to programming and my terminology is off.

//HTML
{url:randvideo1, delayms:10000},

//video arrays found in JS

var videoArray1 = [
"v/video01.mp4",
"v/video02.mp4",
"v/video03.mp4",
"v/video04.mp4"
];

var randvideo1 = videoArray1[Math.floor(Math.random()*videoArray1.length)];



Making a data.frame rows to be randomly different in R

I want to randomly delete rows of my data based on given variables.

For example, if I give you the numerical variable group, then randomly delete all rows with the maximum value of group (i.e., 2) in any random study.

For example, if I give you the character variable outcome, then randomly delete all rows with any one value of outcome (either "A" or "B") in any random study.

If I give you both group and outcome, then both deletions should NOT happen to the same study because it may lead to the complete removal of that study from the data.

Is this possible in R?

m="
study group outcome
    1     1 A      
    1     1 B      
    1     2 A      
    1     2 B      
    2     1 A      
    2     1 B      
    2     2 A      
    2     2 B      
    3     1 A      
    3     1 B      
    3     2 A      
    3     2 B      
    4     1 A      
    4     1 B      
    4     2 A      
    4     2 B      
    5     1 A      
    5     1 B      
    5     2 A      
    5     2 B 
"
data <- read.table(text = m, h = T)



Two Random Numbers Without Repeating

I'm looking to make a set of two random numbers (e.g., [1,2], [3,12]) with the first number between 1-12, and the second between 1-4. I know how to sample the two numbers independently using:

sample(1:12, 1, replace = T)
sample(1:4, 1, replace = T)

but don't know how to create a system to determine if the pairing of the two numbers has already been rolled, and if so, roll again. Any tips!?

Thanks :)




Randomly replace certain words in python using a dictionary

Does anybody know how to modify this script so that it randomly changes the words when it finds them.

i.e not every instance of "Bear" becomes "Snake"

    # A program to read a file and replace words

    word_replacement = {'Bear':'Snake', 'John':'Karen', 'Bird':'Owl'}

    with open("main.txt") as main:
        words = main.read().split()

    replaced = []
    for y in words:
        replacement = word_replacement.get(y, y)
        replaced.append(replacement)
    text = ' '.join(replaced)


    print (text)

    new_main = open("main.txt", 'w')
    new_main.write(text)
    new_main.close()

Thank you in advance




How do I pass a randomized variable as an argument to a function? [closed]

I am writing a code that assigns a variable to a random value from a pandas dataframe by using the choice function from the "random" module: random.choice(df).

I am trying to pass this variable as an argument to a function; however, the code throws a disambiguation error, and I'm not sure how to solve it. I'm assuming it's not taking the unique, random value and instead passing every possible value from the series. How do I maintain the variable being random and passing the random value as a unique argument to the function? I have tried using the lambda anonymous function, which didn't work; and I've also tried a "try-except:pass" block, which also didn't work. Is there a way to possibly utilize threading?




Assigning random values to a pair of integers using rpois(2,100)

Let's say I have two integers which are (x,y). How do I assign the values of (x,y) to rpois(2,100). I need to do this because I need to change the values of (x,y) randomly all the time to test my functions if they are correct. I tried to use a =function(x,y) { (x,y)=rpois(2,100) return(x,y) } However, it appears that (x,y) is wrong because of the comma




Enabling script after the last one destroyed

I am making miner game and I want to add random generation for my mining area, I want to generate it by layer I found simple way to do it and its working, but I have a little problem, the game master has 2 of the same script the first script has 1 job is generate 200 cubes move spawn points down and destroy its self and the second script have to do the same thing but its still disabled, I want to enable the second script after the first script destroyed




samedi 23 octobre 2021

Is it possible to set seed with `RandArray` in Excel?

I need to generate a few sets of random numbers and a minimal working example of my code is as follows:

Sub Macro1()

With Sheets("Economic Assumptions")

    .Range("B10:BL10") = WorksheetFunction.RandArray(1, 63)
    .Range("B11:BL11") = WorksheetFunction.RandArray(1, 63)
    .Range("B12:BL12") = WorksheetFunction.RandArray(1, 63)
    .Range("B13:BL13") = WorksheetFunction.RandArray(1, 63)

End With

With Sheets("Simulations")

   .Range("K11:K61") = WorksheetFunction.RandArray(51, 1)
    
End With

End Sub

However, I am wondering if there is a way to set a seed, such that each time I run this, I always get the same set of random numbers. To be more precise, as one might be able to tell, I am generating five different sets of random numbers here, four sets in one worksheet and one more in another. When I mean I want the same set of random numbers, I mean that each set should always give me the same random numbers, not that I have the exact same random numbers across all sets. In fact, each set (within the same run of the macro), should be giving different random numbers, so I imagine I would need five different seeds here.

In particular, I know how to set a seed in the following context:

Sub xx()

    x = Rnd(-1)
    Randomize 10

End Sub

In this way, each time I run xx, I will get the same set of 10 random numbers, so I would like to know if this is possible with RandArray too, or otherwise, how should I go about tweaking my code if I would like to achieve what I have described above?




python - how to repeat to write numbers in mysql

Problem: please why can't I write to mysql repeatedly via -- for f in range(10):?

import mysql.connector
from mysql.connector import Error
import random 




mydb = mysql.connector.connect(
  host="localhost",
  user="db123",
  password="1111",
  database="db123"
)


mycursor = mydb.cursor()
#sql = "INSERT INTO customers (c1, c2, c3, c4, c5, d1, d2) VALUES (%s, %s, %s, %s, %s, %s, %s)"
sql = """INSERT INTO customers (c1, c2, c3, c4, c5, d1, d2) VALUES (%s, %s, %s, %s, %s, %s, %s)"""


for f in range(10):
   # int = (c1, c2, c3, c4, c5, d1, d2)
     c1 = random.randint(1, 10)
     c2 = random.randint(1, 10)
     c3 = random.randint(1, 10)
     c4 = random.randint(1, 10)
     c5 = random.randint(1, 10)
     d1 = random.randint(1, 10)
     d2 = random.randint(1, 10)
val = (c1, c2, c3, c4, c5, d1, d2)

mycursor.execute(sql, val)
#for mycursor.execute(sql, val) in range(3):

mydb.commit()

print(mycursor.rowcount, "record inserted.") 

Output: 1 record inserted.

Question: what should i do to have 10 - 100million random write to mysql?

Thx




What is the difference between `scipy.stats.expon.rvs()` and `numpy.random.exponential()`?

Simulating exponential random variables with the same mean interval time with different methods gives rise to different x axis scales

How often do we get no-hitters?

The number of games played between each no-hitter in the modern era (1901-2015) of Major League Baseball is stored in the array nohitter_times.

If you assume that no-hitters are described as a Poisson process, then the time between no-hitters is Exponentially distributed. As you have seen, the Exponential distribution has a single parameter, which we will call $τ$, the typical interval time.

The value of the parameter $τ$ that makes the exponential distribution best match the data is the mean interval time (where time is in units of number of games) between no-hitters.

# Here you go with the data
nohitter_times = np.array([ 843, 1613, 1101,  215,  684,  814,  278,  324,  161,  219,  545,
        715,  966,  624,   29,  450,  107,   20,   91, 1325,  124, 1468,
        104, 1309,  429,   62, 1878, 1104,  123,  251,   93,  188,  983,
        166,   96,  702,   23,  524,   26,  299,   59,   39,   12,    2,
        308, 1114,  813,  887,  645, 2088,   42, 2090,   11,  886, 1665,
       1084, 2900, 2432,  750, 4021, 1070, 1765, 1322,   26,  548, 1525,
         77, 2181, 2752,  127, 2147,  211,   41, 1575,  151,  479,  697,
        557, 2267,  542,  392,   73,  603,  233,  255,  528,  397, 1529,
       1023, 1194,  462,  583,   37,  943,  996,  480, 1497,  717,  224,
        219, 1531,  498,   44,  288,  267,  600,   52,  269, 1086,  386,
        176, 2199,  216,   54,  675, 1243,  463,  650,  171,  327,  110,
        774,  509,    8,  197,  136,   12, 1124,   64,  380,  811,  232,
        192,  731,  715,  226,  605,  539, 1491,  323,  240,  179,  702,
        156,   82, 1397,  354,  778,  603, 1001,  385,  986,  203,  149,
        576,  445,  180, 1403,  252,  675, 1351, 2983, 1568,   45,  899,
       3260, 1025,   31,  100, 2055, 4043,   79,  238, 3931, 2351,  595,
        110,  215,    0,  563,  206,  660,  242,  577,  179,  157,  192,
        192, 1848,  792, 1693,   55,  388,  225, 1134, 1172, 1555,   31,
       1582, 1044,  378, 1687, 2915,  280,  765, 2819,  511, 1521,  745,
       2491,  580, 2072, 6450,  578,  745, 1075, 1103, 1549, 1520,  138,
       1202,  296,  277,  351,  391,  950,  459,   62, 1056, 1128,  139,
        420,   87,   71,  814,  603, 1349,  162, 1027,  783,  326,  101,
        876,  381,  905,  156,  419,  239,  119,  129,  467])

First Approach:

import scipy.stats as stats

# computing the distribution parameter
avg_interval = np.mean(nohitter_times)

# Set the seed
np.random.seed(42)
# Simulating the distribution
rvs = stats.expon.rvs(avg_interval, size=100000)

#Plotting the distribution
#sns.histplot(rvs, kde=True, bins=100, color='skyblue', stat='density');
_ = plt.hist(rvs, bins=50, density=True, histtype="step")
_ = plt.xlabel('Games between no-hitters')
_ = plt.ylabel('PDF');

enter image description here

Second Approach:

# Seed random number generator
np.random.seed(42)

# Compute mean no-hitter time: tau
tau = np.mean(nohitter_times)

# Draw out of an exponential distribution with parameter tau: inter_nohitter_time
inter_nohitter_time = np.random.exponential(tau, 100000)

# Plot the PDF and label axes
_ = plt.hist(inter_nohitter_time, bins=50, density=True, histtype="step")
_ = plt.xlabel('Games between no-hitters')
_ = plt.ylabel('PDF')

enter image description here

As you can see, the two plots are totally different in terms of the x axis ticks. I don't know why?




Rotate self between an arc on the local axis Godot

I have a node which fires a bullet, but I want to randomly rotate it a little so that certain guns are unpredictable. Specifically, I want to rotate it on the X and Y axes between a -2.5 - 2.5 degree arc on the local axis. I've tried rotation.x = rand_range(-2.5, 2.5 * PI) and rotation.y = rand_range(-2.5, 2.5 * PI), but these seem to rotate the node on the global X and Y axes. How should I rotate the bullet emitter node locally between an arc? Thank you in advance.




What's the proper way to generate 6 characters alphanumeric code in which sum of all characters equals 9? (Voucher code generator)

My first idea was to make an array/list that has values assigned to each character. So for example:

array[0] =' 0'

array[10] = 'A'

[...]

Then code would pick a random number y between [0,x] for slot 1. For next slot [0,(x-y)] etc. When y <= 0 then fill rest of the slots with '0'.

Would that be enough for a simple voucher code generator? (It's not my decision to make encryption with this rule)

I am worried that sum of 9 is quite low for 6 character code, letters won't be used at all since they all have value over 9. To prevent situation like this: 540000, 630000, 180000 Should I make chance of '0' to appear more?

What do you guys think about it? Maybe you could also suggest some other way of doing this.




'nextDouble()' in 'java.util.Random' cannot be applied to '(double)'

import java.util.Scanner;

public class HW4

        Scanner a = new Scanner(System.in);

        int rows, cols;
        double range;

        System.out.print("2차원 배열의 ROWS 수를 입력하세요 : ");
        rows = a.nextInt();
        System.out.print("2차원 배열의 COLUMNS 수를 입력하세요 : ");
        cols = a.nextInt();
        System.out.print("2차원 배열의 요소값의 최대값 입력하세요 : ");
        range = a.nextDouble();

        Matrix m2 = new Matrix(rows, cols);


        m2.aryInit(range);
        m2.aryPrint();
        System.out.println("\n");
        m2.rowAVG();
        System.out.println("\n");
        m2.colAvg();
        System.out.println("\n");
        m2.colMax();
        System.out.println("\n");
        m2.colmin();

    }

}

import java.util.Scanner;

import java.util.Random;

public class Matrix {

private double ary[][];

Matrix() {
    ary = new double[5][5];
}

public Matrix(int r, int c) {
    ary = new double[r][c];
}

public void aryInit(double range) {
    Random r = new Random();

    for (int i = 0; i < ary.length; i++) {
        for (int j = 0; j < ary[i].length; j++) {
            ary[i][j] = r.nextDouble(range);
        }
    }
}

It is an error that a is ~. ary[i][j] = r.nextDouble(range); <~ It is an error that "range" is 'nextDouble()' in 'java.util.Random' cannot be applied to '(double)'

What should I do?




Randomizing Algorithm for a Pointillism painting in Python

NOTE: This is a school-related assignment and I am in no capacity looking for a direct answer. Looking for support on coming up with algorithms as this is my first time with such a question

Programs Intended Purpose: Take a command line provided image and scale it up by a unit of 5. Use the RGB values from the original image to re-create it in a randomized fashion.

Algorithm Attempts:

  • Test image is 250x250 scaling up to 1250x1250. I've tried to break this into sections of 50(original image side divided by 5) and then use (r + g + b)/5 number of circles to generate the color needed. Ex: Color: (100,50,5) would use 20 red circles, 10 green circles, 1 blue circle in the 50x50 space, (100+50+5)/5 = 31, 20 + 10 + 1 = 31. The x and y coordinates of these circles inside the 50x50 space should be random.

My main issue here has been putting this into code.

Code Attempt 1: Is not related to algorithm, is simply attempt to print image using pygame.draw.circle(this is what I am required to use to make the circle)

import pygame
import sys
import random


image_name = sys.argv[1]

#Import Image
src_image = pygame.image.load(image_name)

(w,h) = src_image.get_size()

window = pygame.display.set_mode((w*5,h*5))


#Nested Loop To Iterate Through Rows And Columns Of Pixels

for y in range(h):
    for x in range(w):
        (r,g,b,_) = src_image.get_at((x,y))
        print(f"{r},{g},{b},x:{x},y:{y}")
    
        pygame.draw.circle(window,(r,g,b),(x*5,y*5),2)
            
pygame.display.update()
pygame.time.delay(5000)



Using std::random_device can I set a range of floating point numbers but not include certain numbers?

As mentioned in the title I want to generate a random floating-point number between -10 and 10 but I want to make it so that it can't generate a number between -1.99 and 1.99.

My code for randomly generating numbers:

std::random_device random;
std::mt19937 gen(random());
std::uniform_real_distribution<float> dis(-10.0f, 10.0f);

for (int n = 0; n < 10; ++n)
{
    std::cout << dis(gen); << std::endl;
}



Random replace items between lists [closed]

I Have 2 Lists of data list_A = [2,3,4,5,33,42,21] and list_B = [1,11,35,48,19].I have tow types of questions. number 1: how can I replace randomly tow items form list_B with list_A for 200 iterations and 200 lists created must be unique. for example List_1 = [**2**,11,35,48,**42**] number 2: how can I replace first tow items of list_B and randomly select from list_A for example list_2 = [**5**,**33**,35,48,19]




Generate random grammar expansions in TatSu (Python)

I'm writing an interpreter for a grammar parser generated with TatSu. I'm looking for a convenient way to generate use cases for my grammar, so I can write unit tests for my interpreter. Currently, I'm generating my test cases by hand.

I wonder if the TatSu package does provide any (maybe undocumented) means to auto-generate random grammar productions so I could use them as test cases for my interpreter. In addition, it would be desirable to specify the grammar rule, for which I need the random productions.




I want to generate a list of 10 distinct random 2-digit integer numbers

I want to generate a list of 10 distinct random 2-digit integer numbers. And find the values cubes

import random as r
import math as i

ss = [r.randint(10,100) for i in range(10)]
print(i.pow(ss))


I did it wrong so i need some help.




vendredi 22 octobre 2021

How do I identify if a variable is in a list?

How do I identify if a randomly selected variable is in a list? Python 3

Example:

WarriorList = ['Achilles', 'Sun Wukong']
GuardianList = ['Ares', 'Ymir']
HunterList = ['Apollo', Artemis']
MageList = ['Anubis', 'ra']

Tank = ()

def TankPick():
    Tank = (random.choice(WarriorList))
    print (Tank)

def BalancePick():
    if (Tank) in WarriorList:
        print ('yes')
        print (random.choice(Magelist))
    else:
        print ('no')
        print (random.choice(Hunterlist))

Expected outcome:

'Sun Wukong'
'yes'
'ra'

or

'Ymir'
'no'
'Artemis'



How do you access a function name not what the function returns in python?

My question pertains specifically to the random module, in my code when i save a random number to a variable or within a list my function becomes a permanent number.

def d4(num=None):
    if num is None:
        num = random.randint(1, 4)
        return num


def d6(num=None):
    if num is None:
        num = random.randint(1, 6)
        return num 

(self explanatory for the rest of dice)

diceDict = {'d4': d4(), 'd6': d6(), 'd8': d8(), 'd10': d10(), 'd12': d12(), 'd20': d20()}
player1 = [d4(), d4()]
player2 = [d4(), d4()]

def getKey(die):
    for key, value in diceDict.items():
        if die == value:
            return key

print(f'P1 dice are: {getKey(player1[0])} and {getKey(player1[1])}')
        print(f'P2 dice are: {getKey(player2[0])} and {getKey(player2[1])}')

so what this is supposed to do is tell them what dice they have in their hand but what it does is... say the d8() in diceDict rolls a 2, then every time a dice rolls a 2 it says they have a d8. please help!




How to random numbers is a specified range? [closed]

I am trying to make a Blackjack game just for fun but I have run into the problem of not being able for the program to give out a random number such as 1-11. I have tried .random but I can't seem to get it to work.




Best road map to enter the tech field fast

Hi iam 32 years old and iam accountant…I love programming I tried to learn it before 5 years then I quit because I wasn’t have road map to what I want to do…. Can I learn programming now and make career shift or it’s over. And also what the best choice for me … I was interested in cyber security but I think it will take a lot of time….so what should I do




Is there a way to filter a fixed percentage sample from a specific categoric variable?

Say I have a population of 1000 patients with data of their sex. I'm being asked to draw a sample of size n that meets strictly that 65% of them must be male.

Some sample data (in here, the sex distribution is 50%-50%):

data <- data.frame(patient_id = 1:1000,
               sex = append(rep("male", 500),
                            rep("female", 500))
                   )

Can't really see a way to solve this task using sample_n or sample_frac in dplyr.

Result data should be something like this for n = 500, but with random patient_ids.

data.frame(patient_id = 1:500,
           sex = append(rep("male", 325),
                        rep("female", 175))
           )

Any insight is appreciated.




SQL Server get random rows depending on the column's sum

For example, I have this table in my SQL Server database :

Document NumberPageMax
First 48
Second 12
Third 4
Fourth 8
Fifth 1
Sixth 3

I need to get a random list of Document for whose the sum of NumberPageMax is equals to 50. If it's not possible to have exactly 50, it's ok to have a little more (first and sixth document for example to have 51).

Do you know if it's possible to do that in SQL and how ?

Thank you !




How to generate a Youtube ID in Go?

I'm assuming all I need to do is encode 2^64 as base64 to get a 11 character Youtube identifier. I created a Go program https://play.golang.org/p/2nuA3JxVMd0 but it has two issues:

  1. The identifier is 12 characters instead of the expected 11
  2. The encoded base64 suffix is "=" which means that it didn't have enough to encode?

So where am I going wrong?




How to randomize two times, whereas second time is disjoint with the first one

Let's say I want to randomize two times from set 1:1000. I want to sample two times 100 numbers, whereas on second time I cannot sample numbers drew in first drawing.

My work so far

import random
random.seed(42)
idx = [random.randint(0, 1000) for p in range(0, 100)]

And now I'm not sure how can I delete randomized indexes from numbers 0 up to 999. I tried to do:

without_idx = range(0, 999).remove(idx)

but I obtained error AttributeError: 'range' object has no attribute 'remove'

Could you please give me a hand with solving this problem?




jeudi 21 octobre 2021

Convert matlab to Numpy

I want to convert Matlab to Python:

a = randn(20,20);
b = randsample(100, 30, false);
c = 2.5*mean(mean(abs(a)));
d = 2*c*rand(20,10)-c;
e = d(a);

This is what I did:

a = np.random.randn(20,20)
b = np.random.randint(100, size=(100, 30))
c = 2.5 * b.mean()

I am not sure about d and e.




How to get a randomly generated string in browser by using selenium, while it can't be found in the website code?

I need to get this randomly generated string so I can finish my task, it changes every couple seconds. However, I can't find any explicit name of the string that can be retrieved from the website's code. We just learned about using selenium to grab data, so I suppose it can be down with only selenium's function?Here 's the snapshot of the question and the code




(New to python)How can I keep the randomized country for it to work in an if statement and for it to be displayed like a flag?

I was looking for an answer for an hour and nothing worked, please i need help.

This is the script




Randomly delete rows due to a variable in a dataframe

In my data below, I wonder how to delete all rows with a given value of outcome from n randomly selected studyies?

The only condition is that such a deletion should not be done if a study would be completely deleted from data.

For example, below let's say the given value of outcome is "A". Then, for a given n (say n = 1), we delete all rows with with outcome == "A" from 1 randomly selected study subject to the condition that that randomly selected study won't be completely deleted from data.

Is this possible in R?

m =
  "
  study group outcome 
1     1     1       A   
2     1     1       B    
3     1     2       A 
4     1     2       B 
5     2     1       A   
6     2     1       B    
7     2     2       A 
8     2     2       B
9     3     1       B
9     3     1       B  
"  
data <- read.table(text=m,h=T)



python quasi random number from 0 to N

Instead of just random numbers, I would like to get quasi random numbers. The purpose of this is I have 1D python list and I want to shuffle the list with quasi random numbers. Let's say if I have myList as list type then, I like to shuffle this list by generating quasi random numbers from 0 to len(myList). Is there any library or approach to achieve this goal?




ValueError: Sample larger than population or is negative when trying to randomly swap elements in a list

I am taking multiple different different sorting algos and benchmarking their times based on different sizes of arrays and different sorting of arrays. IE sorted, random, and reverse arrays ranging from 10^0 to 10^8. I am getting an error whenever I try to use a random_swap function within the main benchmarking function, and I cannot understand why.

My main code looks like this:

def benchmark (sorting_functions,
          base,
          power,
          seed,
          runs = 5):
results = pd.DataFrame(columns = ['sorting algo', 'order', 'size', 'run', 'time'])

for order in ['sorted', 'reverse', 'random', 'semi_sorted']:
    for x in range(power + 1):
 #generate random data
            rng = np.random.default_rng(seed)
            testing_data = rng.uniform(size=base**x)
            print(testing_data)
        
            #sorting of data
            if order == 'sorted':
                testing_data = sorted(testing_data)
                print(testing_data)
            
            if order == 'reverse':
                testing_data = sorted(testing_data, reverse = True)
                print(testing_data)

            #error here!!!!!    
            if order == 'semi_sorted':
                testing_data = swap_random(testing_data, 2)
            
        # Timer function
            clock = timeit.Timer(stmt='sorting_function(copy(data))',
                                 globals={
                                     'sorting_function': sorting_functions,
                                     'data': testing_data,
                                     'copy': copy.copy
                                 })
            n_ar, t_ar = clock.autorange()
            t = clock.repeat(repeat=5, number=n_ar)
            
            
            
    for run in range(runs):
        results = results.append(
            {'sorting algo': f'{sorting_functions.__name__}', 
             'order': order, 'size': base**x, 'run': run + 1, 'time': t[run] / n_ar},
            ignore_index = True)
            
print(results)

and then my function thats getting the error is:

def swap_random(seq, num_swaps):
    import random
    # looping to do as many random swaps as wanted
    # getting the index of the list
    index = range(len(seq))
    for i in range(num_swaps):
        #choosing two random values
        i1, i2 = random.sample(index, num_swaps)
        print(i1, i2)
        #swapping them
        seq[i1], seq[i2] = seq[i2], seq[i1]
    
    return seq

the error im getting is:

ValueError                                Traceback (most recent call last)
<ipython-input-22-c87ac57f742a> in <module>
     12 
     13 for title, sort in sorting_functions.items():
---> 14     benchmark(sort, base=10, power=1, seed=5)

<ipython-input-19-b03c2fcec9dc> in benchmark(sorting_functions, base, power, seed, runs)
     50 
     51                 if order == 'semi_sorted':
---> 52                     testing_data = swap_random(testing_data, 2)
     53 
     54             # Timer function

<ipython-input-18-b813edad15a9> in swap_random(seq, num_swaps)
     14     for i in range(num_swaps):
     15         #choosing two random values
---> 16         i1, i2 = random.sample(index, 2)
     17         print(i1, i2)
     18         #swapping them

~\anaconda3\lib\random.py in sample(self, population, k)
    361         n = len(population)
    362         if not 0 <= k <= n:
--> 363             raise ValueError("Sample larger than population or is negative")
    364         result = [None] * k
    365         setsize = 21        # size of a small set minus size of an empty list

ValueError: Sample larger than population or is negative

I would greatly appreciate any help with this. Thank you so much.




Is there a way to seed a cryptographically secure RNG engine int rust using a [u8; 64] array?

I am currently trying to write a library in rust - to be compiled to WASM - for working with bip39 mnemonic keys. I am currently using tiny-bip39 and RSA.

When generating a private key using RSA as per the example given on RSA I want to seed the rng based on the mnemonic passphrase I have passed into the function. I tried achieving this by simply getting the seed from the mnemonic object generated by tiny-bip39, however this seems to generate a &[u8] with a length of 64. However, Seed is defined as [u8; 32], and without having to write my own rng, I cannot figure out how to use a len 64 seed.

#[wasm_bindgen]
pub fn get_key_from_mnemonic(phrase: &str) {
    let mnemonic = Mnemonic::from_phrase(phrase, Language::English).unwrap();

    assert_eq!(phrase, mnemonic.phrase());

    let seed = Seed::new(&mnemonic, "");
    let seed_bytes = seed.as_bytes();

    let mut rng = ChaCha12Rng::from_seed(seed_bytes);

    [...]
}

Is there a cryptographically secure rng that allows for len 64 seed?

I tried simply trying into, but that did not seem to work, which makes sense.

let seed_bytes: <ChaCha12Rng as SeedableRng>::Seed = seed.as_bytes().try_into().unwrap();



random string with numbers and letters

I saw a code in a website that creates random string. I want to know what does number 17 do in this code? The code is below

<?php
echo substr(sha1(mt_rand()),17,6); //To Generate Random Numbers with Letters.
?>



sampling groups instead of rows

I want to randomly select based on group ids (ColA) instead of rows. Let's say my inital table is this:

+---------------------+
|ColA   | ColB | ColC |
+---------------------+
| AA       C        5 |      
| AA       C        8 |     
| AA       C        9 |      
| BB       D        3 |      
| BB       D        4 |    
| CC       E        1 |    
| CC       E        2 |     
| CC       E        3 |     
| CC       E        5 |    
+---------------------+

I want to get something like this:

+---------------------+
 ColA  | ColB |   ColC 
+---------------------+
| AA       C        5 |      
| AA       C        8 |     
| AA       C        9 |    
| CC       E        1 |      
| CC       E        2 |      
| CC       E        3 |     
| CC       E        5 |      
+---------------------+

So let's say i want to get whole groupings from Col A randomly. I have done this but it gives me random rows rather than groups

SELECT distinct  ColA,ColB, ColC FROM TABLE
ORDER BY  RAND()
LIMIT 20000

I'd appreciate any clues on how to implement it.




Excel issue with connection

I have a issue with one connection in Excell. I create one workbook with a lot of connections. All of them work properly. My idea is to get some concrete numbers from the worksheet , but something happen with one of the connections. Sometimes after refresh , the numbers which I extract are moved with one line below. Is there any way to prevent this?

Thank you




mercredi 20 octobre 2021

A random string generator in swift language

I'm working on some code to make a random name generator in swift/xcode. currently, it tells me that there is a problem with the override function and both of my "viewDidLoads". I'd appreciate any and all help thank you.

`````````````````````````````````````````````````````````````````````````````````````````
//  ViewController.swift
//  name gen
//
//  Created by Idrock niltag on 10/20/21.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var label : UILabel!
    
    
    
    override func ViewDidLoad() {
        super.ViewDidLoad()
    }
    @IBAction func randomWord(_ sender: Any) {
        
        let array = [ "brock", "ash", "misty", "mai","mia","edgeworth"]
        label.text = array.randomElement()
        
    }


}



CUDA curand state pointers inside C++ class

I'm currently trying to create a C++ class to use with curand. I would like to have this class hold a pointer to the curand states on the device, which I can then pass to a kernel for it to use. For example:

__global__ void setup_kernel(curandState *state, int localsites);

class cudaRNG {
  
    public:

    curandState *devStates;
    int nthreads;
    int blocksize;
    int gridsize;
    int localsites;

    cudaRNG(){
   
        localsites = 32*32*32;
        nthreads = 64;
        gridsize = (localsites + nthreads - 1) / nthreads;

        cudaMalloc((void **)&devStates,localsites*sizeof(curandState));
        setup_kernel<<<gridsize,nthreads>>>(devStates, localsites);
    }

    ~cudaRNG(){
         cudaFree(devStates);
    }
}

__global__ void setup_kernel(curandState *state, int localsites){
  
    int id = threadIdx.x + blockIdx.x * blockDim.x;
    if (id < localsites) curand_init(0,0,0,&state[id]);
}

I understand that global kernels cannot be static methods in classes, which is why I put the setup kernel outside of the class.

The code compiles fine, but when I run it and instantiate a member of this cudaRNG class, I get the following error: Caught signal 11 (Segmentation fault: address not mapped to object at address (nil)). This happens in the curand_init step. Given the error itself, I can only surmise that the issue lies in passing a host pointer to the GPU kernel, which is run on the device and thus it can't find the address requested. However, the part I am confused about is if I do the exact same process of creating a curandState object and allocating device memory and calling setup_kernel but outside this class, then it works normally. For instance, if I were to do:

__global__ void setup_kernel(curandState *state, int localsites);

int main(){

    curandState *devStates;
    int nthreads = 64;
    int gridsize = (localsites + nthreads - 1) / nthreads;
    int localsites = 32*32*32;

    cudaMalloc((void **)&devStates,localsites*sizeof(curandState));
    setup_kernel<<<gridsize,nthreads>>>(devStates, localsites);

} 

__global__ void setup_kernel(curandState *state, int localsites){
  
    int id = threadIdx.x + blockIdx.x * blockDim.x;
    if (id < localsites) curand_init(0,0,0,&state[id]);
}

Then this runs as expected. Is this a scope issue? Or is the manner in which pointers are allocated inside classes fundamentally different and thus incompatible with CUDA kernels?

Finally, is there any way of making this work? As in, having a class to initialise and contain the device RNG states so they can be passed to the relevant kernels as necessary?

Thank you very much in advance!




How to get random element from CharacterSet in Swift

I have an array of characters the user has already entered. I would like to get a random character that the user has not already entered from a combined list of all of the alphanumeric characters, the punctuation characters and the symbols. I have looked through the documentation but can't find a way to get a random element from a CharacterSet, which seems odd... I feel like I am missing something obvious.

func newRandomCharacter() -> Character {

let validCharacters: CharacterSet = .alphanumerics.union(.punctuationCharacters).union(.symbols)

var setOfUsedCharacters = CharacterSet()
// usedCharacters: [Character]
usedCharacters.forEach { setOfUsedCharacters.insert(charactersIn: String($0)) }

let setOfUnusedCharacters = validCharacters.subtracting(setOfUsedCharacters)

return setOfUnusedCharacters.randomElement() <- ???

}




Getting data from Array in order of priority

$data = array(
                    'apple' => 4,
                    'orange' => 7,
                    'banana' => 10
                );
                $muff = array_rand($data );

Is it possible to prioritize some data? For example, apples seem to be more selectable than others.




I just want a preset text to be displayed in the middle of the app after pressing a button. The problem is that I can not connect it

      Padding(
        padding: EdgeInsets.only(top: 8),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            RawMaterialButton(
              onPressed: () {},

// After pressing this Button a _random Text should be show in the center. (with the AnswerGenerator)

              child: IconButton(
                icon: new Icon(Icons.add, size: 22,),
                color: Colors.white,
                onPressed: () {},
              ),

This "AnswerGenerator" generates one of these answers (in a box), after I pressed the button, one of these answers should be displayed in the box (column).

 abstract class AnswerGenerator {
   String getQuestion();
   String getDare();
   }
  class AnswerLocalGenerator implements AnswerGenerator {
  final Random _random = Random();
  final _questions = [
   "Answer2",
   "Answer3",
   "Answer4",
   "Answer5",
   ];



Vectorised np.random.choice with varying probabilities

I've trained a machine learning model using sklearn and want to simulate the result by sampling the predictions according to the predict_proba probabilities. So I want to do something like

samples = np.random.choice(a = possible_outcomes, size = (n_data, n_samples), p = probabilities)

Where probabilities would be is an (n_data, n_possible_outcomes) array

But np.random.choice only allows 1d arrays for the p argument. I've currently gotten around this using a for-loop like the following implementation

sample_outcomes = np.zeros(len(probs)
for i in trange(len(probs)):
    sample_outcomes[i, i*n_samples : i*nsamples + n_samples] = np.random.choice(outcomes, s = n_samples, p=probs[i])

but that's relatively slow. Any suggestions to speed this up would be much appreciated !




Random effects specification in gamlss in R

I would like to use the gamlss package for fitting a model benefiting from more available distributions in that package. However, I am struggling to correctly specify my random effects or at least I think there is a mistake because if I compare the output of a lmer model with Gaussian distribution and the gamlss model with Gaussian distribution output differs. If comparing a lm model without the random effects and a gamlss model with Gaussian distribution and without random effects output is similar.

I unfortunately cannot share my data to reproduce it. Here my code:

df <- subset.data.frame(GFW_food_agg, GFW_food_agg$fourC_area_perc < 200, select = c("ISO3", "Year", "Forest_loss_annual_perc_boxcox", "fourC_area_perc", "Pop_Dens_km2", "Pop_Growth_perc", "GDP_Capita_current_USD", "GDP_Capita_growth_perc", 
                                                                                     "GDP_AgrForFis_percGDP", "Gini_2008_2018", "Arable_land_perc", "Forest_loss_annual_perc_previous_year", "Forest_extent_2000_perc"))
fourC <- lmer(Forest_loss_annual_perc_boxcox ~ fourC_area_perc + Pop_Dens_km2 + Pop_Growth_perc + GDP_Capita_current_USD + 
              GDP_Capita_growth_perc + GDP_AgrForFis_percGDP + Gini_2008_2018 + Arable_land_perc + Forest_extent_2000_perc + (1|ISO3) + (1|Year), 
            data = df)
summary(fourC)
resid_panel(fourC)


df <- subset.data.frame(GFW_food_agg, GFW_food_agg$fourC_area_perc < 200, select = c("ISO3", "Year", "Forest_loss_annual_perc_boxcox", "fourC_area_perc", "Pop_Dens_km2", "Pop_Growth_perc", "GDP_Capita_current_USD", "GDP_Capita_growth_perc", 
                                                                                     "GDP_AgrForFis_percGDP", "Gini_2008_2018", "Arable_land_perc", "Forest_loss_annual_perc_previous_year", "Forest_extent_2000_perc"))
df <- na.omit(df)
df$ISO3 <- as.factor(df$ISO3)
df$Year <- as.factor(df$Year)
fourC <- gamlss(Forest_loss_annual_perc_boxcox ~ fourC_area_perc + Pop_Dens_km2 + Pop_Growth_perc + GDP_Capita_current_USD + 
                  GDP_Capita_growth_perc + GDP_AgrForFis_percGDP + Gini_2008_2018 + Arable_land_perc + Forest_extent_2000_perc + random(ISO3) + random(Year), 
                data = df, family = NO, control = gamlss.control(n.cyc = 200))
summary(fourC)
plot(fourC)

How do the random effects need to be specified in gamlss to be similar to the random effects in lmer?

If I specify the random effects instead using

re(random = ~1|ISO3) + re(random = ~1|Year)

I get the following error: Error in model.frame.default(formula = Forest_loss_annual_perc_boxcox ~ : variable lengths differ (found for 're(random = ~1 | ISO3)')