mercredi 30 septembre 2020

Random float number for different scenarios

Is it possible to generate a random float number that is (a,b],(a,b)? for example, (0,100], it will never be 0, but it can be 100.




How to cast random numbers in an array?

I'm currently trying to create 20 random numbers in an array and set these values to either 0 or 1. The problem I'm having after this is when I try to do a bit of casting to try and get these numbers to doubles. From what I understand (Not much), this should work, but it just outputs 0's and 1's again. I'd really appreciate any help or advice, or even any links to tutorials that might help! Thank you in advance!

#include <iostream>

using namespace std;

int main()
{
   int array[20] = { 0 };

   for (int j = 0; j < 20; j++)
   {
      array[j] = rand() % 2;

      cout << (double)array[j] << endl;
  }

}




Not showing the "print('yes')" statement

def subtract1(a, b):
    return a - b
    if random.randint(0,100) < 99:
        print("Yes")
print(subtract(20, 10)

I have tried many different ways of using a random number gen but can't seem to find one that works. I am now quite sure that it has to do something with the other code but I'm not sure what.




Repeatable random numbers using dorng package

I am trying to generate a repeatable set of random numbers in R using foreach and dorng packages. My expectation is that I should get the same random numbers in both the cases below. However, that is not what I see.

Here is a brief overview of what I am trying to do.

  1. Set the seed
  2. In a loop, sleep for a random duration and get a list of 20 random numbers
  3. Save the first list of random numbers
  4. Repeat the process in steps 1 and 2 one more time with different random sleep duration.
  5. Save the second list of random numbers
  6. Compare the first and second lists of random numbers.

I was expecting that the first set of random numbers and the second set of random numbers to be the same. The order might be different because each parallel process could be sleeping for a random duration and might impact the overall order of random numbers picked. However, In the case below, I see that only 122 of the 200 numbers match. If I change the random sleep duration from 8 and 10 seconds to 8 and 12 seconds, the number of common random numbers goes down even more. I am using sleep as a proxy for computation and other processing that happens within the foreach loop.

Any help with what could be wrong here is greatly appreciated.

library(doParallel)
library(doRNG)
library(foreach)

# Make 10 clusters and set them to run in parallel
cl <- makeCluster(10)
registerDoParallel(cl)

## COLLECT THE FIRST SET OF RANDOM NUMBERS 
set.seed(123)
# Sleep duration for first sample collection
x <- 0:10

# Generate 10 random numbers after a random amount of sleep
rp1 <- foreach(i=1:20, .combine = 'c', .options.RNG=123) %dorng%{ 
  # Sleep for random duration
  Sys.sleep(sample(x))
  return(rnorm(10,0,1))
}

## RESET THE SEED AND COLLECT SECOND SET OF RANDOM NUMBERS
set.seed(123)
# Sleep duration for second sample collection
x <- 0:8

# Generate 10 random numbers after a random amount of sleep
rp2 <- foreach(i=1:20, .combine = 'c', .options.RNG=123) %dorng%{ 
  # Sleep for random duration
  Sys.sleep(sample(x))
  return(rnorm(10,0,1))
}

stopCluster(cl)

# Do a diff between the two sets of random numbers
common <- intersect(rp1,rp2)
print(length(common))



How to generate n random numbers from negative binomial distribution?

I am trying to make a function in order to generate n random numbers from negative binomial distribution. To generate it, I first made a function to generate n random variables from geometric distribution. My function for generating n random numbers from geometric distribution as follows:

rGE<-function(n,p){
  I<-rep(NA,n)
  for (j in 1:n){
  x<-rBer(1,p)
  i<-1 # number of trials
  while(x==0){
    x<-rBer(1,p)
    i<-i+1
  }
  I[j]<- i
  }
  return(I)
}

I tested this function (rGE), for example for rGE(10,0.5), which is generating 10 random numbers from a geometric distribution with probability of success 0.5, a random result was:

[1] 2 4 2 1 1 3 4 2 3 3

In rGE function I used a function named rBer which is:

rBer<-function(n,p){
  sample(0:1,n,replace = TRUE,prob=c(1-p,p))
}

Now, I want to improve my above function (rGE) in order to make a function for generating n random numbers from a negative binomial function. I made the following function:

rNB<-function(n,r,p){
  I<-seq(n)
  for (j in 1:n){
    x<-0
    x<-rBer(1,p)
    i<-1 # number of trials
    while(x==0 & I[j]!=r){
      x<-rBer(1,p)
      i<-i+1
    }
    I[j]<- i
  }
  return(I)
}

I tested it for rNB(3,2,0.1), which generates 3 random numbers from a negative binomial distribution with parametrs r=2 and p=0.1 for several times:

> rNB(3,2,0.1)
[1] 2 1 7
> rNB(3,2,0.1)
[1] 3 1 4
> rNB(3,2,0.1)
[1] 3 1 2
> rNB(3,2,0.1)
[1] 3 1 3
> rNB(3,2,0.1)
[1] 46  1 13 

As you can see, I think my function (rNB) does not work correctly, because the results always generat 1 for the second random number. Could anyone help me to correct my function (rNB) in order to generate n random numbers from a negative binomial distribution with parametrs n, r, and p. Where r is the number of successes and p is the probability of success?

[[Hint: Explanations regarding geometric distribution and negative binomial distribution: Geometric distribution: In probability theory and statistics, the geometric distribution is either of two discrete probability distributions:

  1. The probability distribution of the number X of Bernoulli trials needed to get one success, supported on the set { 1, 2, 3, ... }.
  2. The probability distribution of the number Y = X − 1 of failures before the first success, supported on the set { 0, 1, 2, 3, ... }

Negative binomial distribution:A negative binomial experiment is a statistical experiment that has the following properties: The experiment consists of x repeated trials. Each trial can result in just two possible outcomes. We call one of these outcomes a success and the other, a failure. The probability of success, denoted by P, is the same on every trial. The trials are independent; that is, the outcome on one trial does not affect the outcome on other trials. The experiment continues until r successes are observed, where r is specified in advance. ]]




Randomly select 40 files from a folder which has 100 files [closed]

I'm trying to select certain amount of files randomly from a folder. For example if a folder has 100 files, I want to select 40 files randomly rather than the first 40.

            string sourceFolder = //unc path;
            var dir = new DirectoryInfo(sourceFolder );
            var allFiles = dir.GetFiles("*.pdf");
            int fileCount = allFiles.Length; // 100 files
            int folderOne = 60;
            int folderTwo = 40;

            if (fileCount > 0)
            {
                // select 60 files randomly and move them to folderOne
            }

I tried using Random function in C# but I cannot get my head around it.

             var random = new Random();
             int index = random.Next(0, fileCount - 1);
             var file = allFiles[index].FullName;

Any help would be greatly appreciated. Thanks




How to insert random values in an array with max lenght and max array sum

So, i need to make an array with lets say $n = 100 (max array length) and $target = 50 (max array values sum) with random numbers between 0-20.

I've tried with the below code but it gets - values when y<x.

$target = 50;
$n = 100;
while ($n) {
    if (0 < $n--) {
        $addend = rand(0, $target - ($n - 1));
        $target -= $addend;
        $addends[] = $addend;
    } else {
        $addends[] = $target;
    }
}



The different options for accessing random elements in an array using JavaScript/P5.js

I am new to using JavaScript and the P5.js library. However, I have many years of experience in Processing and some understanding of Java.

I have worked out 3 ways that I can randomly access an element in an array. All appear to work however I was wondering what would be best practice. `

var cars = ["Saab", "Volvo", "BMW"];

var rm = Math.floor(Math.random() * cars.length); 
var ri = int(random(cars.length));
var words = random(cars);

The first 2 methods are familiar however the 3rd is a new concept, is this somthing that is unique to javaSript.

Thanks in advance




How do I unit test my random generator function?

I wrote the following 4-liner in C as a helper function, but I now find it useful beyond what I had anticipated and would like to cover it in my tests.

double random_double_in_range(double min, double max) {
    // This cannot overflow, no matter the values of min, max and x.
    // It will return an uniformly distributed double
    // between min and max, inclusive.
    int n = rand();
    if (n==0) return min;
    double x = (double) n;
    return x * (max / RAND_MAX - min / RAND_MAX + min / x);
}

I wrote the comment and believe it to be true, but how can I really without tests?

I can easily test that the returned value is within the bounds, but how can I write a test that determines whether it is actually uniformly distributed? If I simply run it one million times and check that it fits a uniform distribution within some tolerance, eventually it will exceed that tolerance and fail spuriously.

I know that probably there exist libraries that do this already; this is more of a personal exercise (how do they do their testing?)




numpy implementing a custom RNG

I'm trying to get numpy to use my own implementation of an RNG in for consistency reasons. My understanding, based on the little documentation I could find, from the numpy docs here and here is that I need to provide a custom BitGenerator class that implements the random_raw method and then initialise using np.random.Generator, so I tried this:

import numpy as np

class TestBitGenerator(np.random.BitGenerator):
  def __init__(self):
    super().__init__(0)
    self.counter = 0
  def random_raw(self, size=None):
    self.counter += 1
    if size is None:
      return self.counter
    return np.full(n, self.counter)  

mc_adapter = TestBitGenerator() 
npgen = np.random.Generator(mc_adapter)

print(npgen.random())

which results in a segfault:

$ python bitgen.py 
Segmentation fault (core dumped)

I assume I'm missing something (from TestBitGenerator?) here, can anyone point me in the right direction? I tried not subclassing np.random.BitGenerator.

I using numpy 1.19.2 and python 3.8.2




Modules and numpy.random seeds

I have two modules, the first of which which is:

# module.py

import numpy
import myrandom

class A():
    def __init__(self,n1,n2):
        A.rng_set1 = myrandom.generate_random(n1)
        A.rng_set2 = myrandom.generate_random(n2)
        A.data = np.concatenate((A.rng_set1,A.rng_set2))

The module myrandom is something like:

# myrandom.py

import numpy as np

    def generate_random(n):
        return np.random.rand(n)

Given a seed I want A.data to be predictable. I don't want rng_set1 and rng_set2 to share the same numbers if n1 equals n2. I don't understand how to seed this thing.

I've tried putting np.random.seed(constant) into generate_random, into A's init, at module.py top level and before import module.py. I can't seem to get the desired result.

How am i supposed to do this? Thank you.




How to generate a random number based on fixed character set in javascript

I'm generating a number based on a fixed character set.

function generator()
{
     var text = "";
     var char_list = "LEDGJR", number_list = "0123456789";
     for(var i=0; i < 2; i++ )
     {  
          text += char_list.charAt(Math.floor(Math.random() * char_list.length));
     }

     for(var j=0; j < 2; j++ )
     {  
          text += number_list.charAt(Math.floor(Math.random() *             
                              number_list.length));
     }

     return text;
}

Result : RE39, JE12 etc...

Once all the permutation related to the above sequence is done, then the generator should generate string as RE391, JE125 means adding one more number to the complete number.

How can I get the permutation count of sequence?




Speed up random weighted choice without replacement in python

I want to sample ~10⁷ times from a population of ~10⁷ integers without replacements and with weights, each time picking 10 elements. After each sampling I change the weights. I have timed two approaches (python3 and numpy) in the following script. Both approaches seem painfully slow to me, do you see a way of speeding it up?

import numpy as np
import random

@profile
def test_choices():
    population = list(range(10**7))
    weights = np.random.uniform(size=10**7)
    np_weights = np.array(weights)

    def numpy_choice():
        np_w = np_weights / sum(np_weights)
        c = np.random.choice(population, size=10, replace=False, p=np_w)

    def python_choice():
        c = []
        while len(c) < 10:
            c += random.choices(population=population, weights=weights, k=10 - len(c))
            c = list(set(c))

    for i in range(10**1):

        numpy_choice()
        python_choice()

        add_weight = np.random.uniform()
        random_element = random.randint(0, 10**7)
        weights[random_element] += add_weight
        np_weights[random_element] += add_weight


test_choices()

With the timer result:

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
    24        10   20720062.0 2072006.2     56.6          numpy_choice()
    25        10   15593925.0 1559392.5     42.6          python_choice()



Speed up random weighted choice without replacement in python

I want to sample ~10⁷ times from a population of ~10⁷ integers without replacements and weights, each time picking 10 elements. I have timed two approaches (python3 and numpy) in the following script. Both approaches seem painfully slow to me, do you see a way of speeding it up?

import numpy as np
import random

@profile
def test_choices():
    population = list(range(10**7))
    weights = np.random.uniform(size=10**7)
    np_weights = np.array(weights)

    def numpy_choice():
        np_w = np_weights / sum(np_weights)
        c = np.random.choice(population, size=10, replace=False, p=np_w)

    def python_choice():
        c = []
        while len(c) < 10:
            c += random.choices(population=population, weights=weights, k=10 - len(c))
            c = list(set(c))

    for i in range(10**1):

        numpy_choice()
        python_choice()

        add_weight = np.random.uniform()
        random_element = random.randint(0, 10**7)
        weights[random_element] += add_weight
        np_weights[random_element] += add_weight


test_choices()

With the timer result:

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
    24        10   20720062.0 2072006.2     56.6          numpy_choice()
    25        10   15593925.0 1559392.5     42.6          python_choice()



mardi 29 septembre 2020

How to reference a randomly generated filename with flask

I am creating a program that generates a chart, and then displays the chart on the webpage. I want each chart generated to have a unique filename. However, once that unique filename is generated, I don't know how to refer to it within the html file.

I use this to create a random filename starting with "chart" in the "images" folder. This parts works fine.

basename = "images/chart"
suffix = str(uuid.uuid4())
filename = "_".join([basename, suffix])
plt.savefig(filename)

I then have this in the html file, but don't know how to modify to add the random suffix part of the name that was just generated.

<img src="">



How do I make a random int into a variable I can use and compare in Java?

its not great code I know but I need help at line 30 with if (guess == roll) im trying to make it if you guess the number right it will say you win and if not it will not say you win.

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

public class diceGame 
{
 public static void main(String[] args) 
 {
    Scanner scan = new Scanner(System.in);
    diceGame test = new diceGame();
     
    System.out.println("Number of rolls?: ");
    int numRoll = scan.nextInt();
    
    System.out.println("Gues the number/most common number: ");
    int guess = scan.nextInt();
     
     Random rand = new Random();
    
            for(int i = 0; i < roll.length; i++)
            {
            roll[i] = rand.nextInt(6)+1;
            }
            
        for(int i = 0; i < roll.length; i++)
        {
        System.out.print(roll[i] + ", ");
        }
 
        
        if (guess == roll)
        {
            System.out.println("Good job you guess correct");
        }
        else
        {
            System.out.println("You did not guess correct");
        }
 } 
    
 }



How to specify variables with random in Python

I am creating a password generator the takes the length of the desired password, number of letters, as well as the number of numbers. The password needs to contain uppercase letters as well as numbers and special characters. I am having trouble figuring out how to specify the number of letters and numbers in the password. This is what I have so far:

import random

charslet ="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
charsnum = "1234567890"
charssym = "!@#$%^&*"

def password():
    pwd = ""

    passlen = int(input("How long do you want the password to be?: "))
    passlet = int(input("How many letters do you want in your password?: "))
    passnum = int(input("How many numbers do you want in your password?: "))
    passsym = int(passlen - (passlet + passnum))
    chars = ""

    for let in range(passlet):
        chars += random.choice(charslet)
    for num in range(passnum):
        chars += random.choice(charsnum)
    for sym in range(passsym):
        chars += random.choice(charssym)



    for p in range(passlen):
        pwd += random.choice(chars)

    print(pwd)

password()




How to end program with while loop in Python

Started learning python today and was working on a program that picks a random number and prompts the user to guess the number. I don't know how to get the program to stop running after the user guesses the number right the first time. Any help would be appreciated.

import random

def Guess():
    number = random.randint(0, 100)
    state = False
    tries = 0

    while state == False:
        print("Guess a number between 0 and 99")
        guess = int(input("What is your guess?: "))
        if guess == number:
            print("\nCorrect, the number was: " + str(number))
            print("\nThat took you " + str(tries) + " tries")
            return True
        elif guess > number:
            print("Wrong, Try a lower number\n")
            tries += 1
        elif guess < number:
            print("Wrong, Try a higher number\n")
            tries +=1 
Guess()



How to randomly select quote from txt file Python

I have a .txt file that looks like this:

Better three hours too soon than a minute too late
Love all, trust a few, do wrong to none
A fool thinks himself to be wise, but a wise man knows himself to be a fool
There is nothing either good or bad but thinking makes it so
One touch of nature makes the whole world kin
We know what we are, but know not what we may be
It is not in the stars to hold our destiny but in ourselves
Love sought is good, but given unsought, is better
Some are born great, some achieve greatness and some have greatness thrust upon them
No legacy, is so reach, as honesty
Bieber is barber

I want to make the the code to select random quotes from txt and fill it on interface below :(The hide quote then reveal quote)

               ..:: C.O.V.I.D ::..
+----------------------------------------------------+
| _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _            |
| _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _     _  _       |
| _ _ _                                  _ _ _ _ _ _ |
+----------------------------------------------------+

Here is my code. I tried for few hours:

quotes = psphelper.readQuotesFromFile("quotes.txt");
#print("List of quotes");
no = 1;
for q in quotes:
 #   print("{0}. {1}" .format(no, q));
    no += 1;

guess_quote = quotes
guess_quote_answer = guess_quote

guess_quote_list = list(guess_quote)

for i in range(len(guess_quote_list)):
    if guess_quote_list[i] != ' ':
        guess_quote_list[i] = '_'
guess_quote = ''.join(guess_quote_list)

guess = 'a'
for i in range(len(guess_quote_answer)):
    if guess_quote_answer[i] == guess:
        guess_quote_list[i] = guess

title = "..:: C.O.V.I.D ::..";
width = 50;
print(title.center(width));

guess_quote = ''.join(guess_quote_list)    
psphelper.showQuoteScreen(guess_quote, 50)



How do i change this number to a random number within a set time?

I know almost nothing about C, so I need a hand with this. So, I have a title and I want the numbers to change to a random number within a min# and a max#(for instance, 1-10) and I want it to change randomly within a given set time (for instance, randomly between 20-60 seconds it will change). As I said, im very new so im not sure where to look or anything. Thank you.

What i want to change as said above




Scramble each digit of the int a and print out the biggest possible integer

I’m stuck here. Do I just keep making new strings and turn them to int or us there a faster better way?

public void biggest(int a){
       int random;
       String aS = String.valueOf(a);
       int ah=9;
       if (a<10)
             System.out.println(a);
       for(int i= 0;i<aS.length();i++){
            String firstNum = aS.substring(i,i+1);
            for (int j = ah; j > Integer.parseInt(firstNum); j--){
                System.out.println(ah);
            
            }
            }
    } ```



Is there a shorter version, biased probability?

import random as rd
def prob(times):
    h,t=0,0
    for _ in range(times):
        if rd.randrange(1,11)<=7:h+=1
        else:t+=1
    return h

To return the results of biased coin flipping 70% head




How to start an animation on the position it last ended on

I have a 3D cube that completes one of 2 animations depending on what number is selected by math.random. The animation holds its end position after it has ended (due to "forwards") but if the cube is clicked, to run the animation again, it returns back to its original position. How to I make the cube complete the animation starting from the last time's ending position?

            @keyframes one {
                0% {transform: translateZ(-5em) rotateY(0deg) rotateX(0deg);}
                100% {transform: translateZ(-5em) rotateY(0deg) rotateX(360deg);}
            }
            @keyframes two {
                0% {transform: translateZ(-5em) rotateY(0deg) rotateX(0deg);}
                100% {transform: translateZ(-5em) rotateY(-90deg) rotateX(360deg);}
            }
function spinDie() {
                var num = Math.floor(Math.random() * 1) + 1;
                if (num === 1) {
                   document.getElementById("die").style.animation="one 2s forwards"
                }
                if(num === 2) {
                    document.getElementById("die").style.animation="two 2s forwards"
                }
}



Create a method to scramble the characters inside a string and print out the scrambled string [duplicate]

I can not use arrays or random. Only Math.random and simple java

int ran = (int)(Math.random()*10000)%100;



Program output varies for unknown reason [duplicate]

Disclaimer: I know the code is wrong and horrible, but that isn't the point.
I was trying to solve Project Euler Problem 11, and i came up with this code

template<size_t N>
long long GridGP(long long (&grid)[N]) //Stands for Grid Greatest Product;
{
    long long gridSize = sizeof(grid) / sizeof(*grid);
    long long digitProd = 1; //Digit Product
    long long potDigProd = 1; //Potential Digit Product
    for (long long numLocation = 0; numLocation <= gridSize - 31; numLocation++) //-31 so that it doesn't continue onto the last 3 rows
    {
        potDigProd = 1;
        if (numLocation - 3 >= ((numLocation / 10) * 10)) //Left Diagonal
        {
            for (long long i = 0; i <= 4; i++) //Times 4 not 3, so that it includes the first number in the series of 4 adjacent numbers
            {
                potDigProd *= grid[numLocation - ((i * 10) - i)];
            }
            if (potDigProd > digitProd) digitProd = potDigProd;
            potDigProd = 1;
        }
        if (numLocation - 3 < ((numLocation / 10) * 10) + 7) //Right Diagonal
        {
            for (long long i = 0; i <= 4; i++)
            {
                potDigProd *= grid[numLocation + ((i * 10) + i)];
            }
            if (potDigProd > digitProd) digitProd = potDigProd;
            potDigProd = 1;
        }
        for (long long i = 0; i <= 4; i++) //Down, doesn't requre an if statement to check if it's beyond the last 4th row because the for loop doesn't go beyond the last 4th row
        {
            potDigProd *= grid[numLocation + (i * 10)];
        }
        if (potDigProd > digitProd) digitProd = potDigProd;
        potDigProd = 1;
        if (numLocation >= 40) //Up
        {
            for (long long i = 0; i <= 4; i++)
            {
                potDigProd *= grid[numLocation - (i * 10)];
            }
            if (potDigProd > digitProd) digitProd = potDigProd;
            potDigProd = 1;
        }
    }
    return digitProd;
}

The main method just has the grid from problem 11 as an int array grid20x20 and then cout << GridGP(grid20x20);

Can someone explain why?
Note: It is possible that you'll have it give the same answer everytime, if that happens rebuild the project and you should start getting a different answer each time. very weird.
I also use the Visual Studio C++ Compiler

The post i was linked to does not answer my question




lundi 28 septembre 2020

Three.js 3D random Vectors with random rotation have a strange directional bias

I have been experimenting with Three.js. I'm new to working with libs like this, but I created a short script that takes a random source Vector, generates a random direction in all 3 dimensions, and then clones and translates that vector many times over with a random angle adjustment (simulating e.g. a random space flight cycle)

The following js-bin shows a set of 100 examples of flight cycles (which in turn have 300 "movements" each) visualized in 2 dimensions only. Each color represents a unique flight cycle.

https://jsbin.com/tiwoweyolo/edit?js,output

If I remove the X and Y axis from the random quaternion rotation that occurs on every move, and apply only to Z (which I believe would be a true 2D simulation) the random cycles seem truly random. Try it yourself. Change the setFromAxisAngle() call to only rotate round Z like so:

q.setFromAxisAngle(new THREE.Vector3(0, 0, 1), range(-cone, cone));

The cone angle is my way of ensuring each new vector is generally aimed away from the previous and away from the origin. I don't mind a few loop backs here and there.

Making this change and running the JS and viewing the output window you really see a random set of "flights".

BUT if you noticed, the original js-bin which rotates as follows:

q.setFromAxisAngle(new THREE.Vector3(1, 1, 1), range(-cone, cone));

...there is incredible bias from top left to bottom right. In fact you see very few flights at all travelling bottom left and top right.

Originally I thought this was just an artifact of trying to visualize 3 dimensional coordinates in 2D. However, surely anything that was X,Y in the emptier quadrants would not be affected by Z.

Why is this bias occurring, is it occurring at all, or is it an artifact of rendering 3d vectors in 2D?

If there is a bias, how do I make this more random?




Next Page Iteration in Selenium/BeautfulSoup for Scraping E-Commerce Website

I'm scraping an E-Commerce website, Lazada using Selenium and bs4, I manage to scrape on the 1st page but I unable to iterate to the next page. What I'm tyring to achieve is to scrape the whole pages based on the categories I've selected.

Here what I've tried :

Run the argument with incognito

option = webdriver.ChromeOptions()

option.add_argument(' — incognito')

driver = webdriver.Chrome(executable_path='chromedriver', chrome_options=option)

driver.get('https://www.lazada.com.my/')

driver.maximize_window()
```
# Select category item #


element = driver.find_elements_by_class_name('card-categories-li-content')[0]

webdriver.ActionChains(driver).move_to_element(element).click(element).perform()

t = 10

try:
    
WebDriverWait(driver,t).until(EC.visibility_of_element_located((By.ID,"a2o4k.searchlistcategory.0.i0.460b6883jV3Y0q")))
except TimeoutException:

    print('Page Refresh!')

    driver.refresh()

element = driver.find_elements_by_class_name('card-categories-li-content')[0]

webdriver.ActionChains(driver).move_to_element(element).click(element).perform()

print('Page Load!')

#Soup and select element

def getData(np):

soup = bs(driver.page_source, "lxml")

product_containers = soup.findAll("div", class_='c2prKC')

for p in product_containers:

    title = (p.find(class_='c16H9d').text)#title

    selling_price = (p.find(class_='c13VH6').text)#selling price

    try:

        original_price=(p.find("del", class_='c13VH6').text)#original price 

    except:

        original_price = "-1"

    if p.find("i", class_='ic-dynamic-badge ic-dynamic-badge-freeShipping ic-dynamic-group-2'):
        freeShipping = 1
    else:
        freeShipping = 0
    try:
        discount = (p.find("span", class_='c1hkC1').text)
    except:
        discount ="-1"
    if p.find(("div", {'class':['c16H9d']})):
        url = "https:"+(p.find("a").get("href"))
    else:
        url = "-1"
    nextpage_elements = driver.find_elements_by_class_name('ant-pagination-next')[0]
 

np=webdriver.ActionChains(driver).move_to_element(nextpage_elements).click(nextpage_elements).perform()

    print("- -"*30)
    toSave = [title,selling_price,original_price,freeShipping,discount,url]
    print(toSave)
    writerows(toSave,filename)

getData(np)

``````````````````````````




Hive: random select different size of samples from group by

Is it possible to random select different sizes of samples from group by in Hive? For instance, I have a table like this

|-----------------|----------------|
|     ID          |     Value      |
|-----------------|----------------|
|    IKJ12        |    5           |
|-----------------|----------------|
|    IKJ12        |    9           |
|-----------------|----------------|
|    IKJ12        |    10          |
|-----------------|----------------|
|    IKJ09        |    7           |
|-----------------|----------------|
|    IKJ09        |    14          |
|-----------------|----------------|

I would like to randomly select two samples from ID = IKJ12 and one sample from ID = IKJ09. One possibility is like this.

|-----------------|----------------|
|     ID          |     Value      |
|-----------------|----------------|
|    IKJ12        |    5           |
|-----------------|----------------|
|    IKJ12        |    10          |
|-----------------|----------------|
|    IKJ09        |    14          |
|-----------------|----------------|



Pygame, how do I get a random output to repeat the same value twice?

I'm coding a game and I want to have damage that is random per say. Lets say I did this for the first half of the code enemy_hp == enemy_hp - random.choice(damage) And damage = [1, 2, 3, 4, 5] When I run the code, it outputs a value 4, I want to get the same value a second time to print it on the screen for the player to see how much damage they dealt.

What would the second half of the code be? I've been stuck on this for a few hours now.

I don't know how confusing this is to read, so I'm going to give a 'quick' summary. I want to get the same value twice from a list using random.choice(). The second time I get that value it will be used in a line of code similar to this: print('random text here' + str(value))




Applying function to which element in a list?

So i wrote this code:

def bool_gen(p):
   p = float(p)
   if p > 100 or p < 0:
     p = 0.5
   elif 1 <= p <= 100:
     p = p / 100

   return random.random() < p

def apply_discount(v, b):

    if b == True:
       v = v * 0.5
       return v
    elif b == False:
       return v


p = int(random.randint(0,200))
b = bool_gen(p)       
purchases_prices = [20,30,40,50]
have_discount = []
no_discount = []
for each_price in purchases_prices: 
   if b == True    
      have_discount.append(apply_discount(each_price,b))
        
   elif b == False:   
       no_discount.append(apply_discount(each_price,b))

What i want is to bool_gen is applied to each element in purchases_prices and not to the whole list. This is what i get:

have_discount = [10, 15, 20] and no_discount = []

What i wanted to happen(so apply_discount to be applied in each of the element in purchases_prices):

have_discount = [10,20]  and no_discount = [30]

Ty in advance!




How do I set a random seed, randomly?

I am running a process which is massively parallelized that depends on randomness. The trouble is that each of the workers in the parallel process shares the same random seed as the parent process, thereby ruining my attempts to run distinct random simulations.

Thus, I have the problem of how to set a distinct random seed on each worker at inception. My current solution is to take the microseconds part off of time.time() and convert it to an integer before passing it to random.seed(). It looks like the following. Is there a better way?

import re
import random
import time
def set_random_seed():
    seed = int(re.sub(r'[^0-9]', '', str(time.time())[-7:]))
    random.seed(seed)



Trying to randomly select an class from an array and apply to body (JS NOOB)

Trying to randomly select on of the color classes once the color span is clicked then apply it to the body, not sure how to randomize the array selection and apply per click.

Test site located here: http://alexcoven.com/type/

<script type="text/javascript">
    // Select the element
    var body = document.querySelector('body');

    // Array of color Classes
    var classColorArray = ['tan-red', 'orange-green', 'deep-green-orange'];

    // Apply the new classes
    var cl = body.classList;

    document.querySelector('span.reverse').addEventListener('click', (e) => {
        body.className = ''; // Clear
        cl.add('reverse'); // Add
          event.preventDefault();
    });
    document.querySelector('span.default').addEventListener('click', (e) => {
        body.className = ''; // Clear
          event.preventDefault();
    });
    document.querySelector('span.color').addEventListener('click', (e) => {
        body.className = ''; // Clear
        cl.add.apply(cl, classColorArray);
          event.preventDefault();
    });
</script>



How to store a Scanner input and have it correspond with an array? Then pick a random element from that array

Working on a beginner java project.

The idea of the program is to take in user's favorite genre and return a random recommendation based on a top 10 (starting with 3 now) list of books in each genre.

My main question is how could I take in their input, make it correspond to the right array and print out a random element from that array in the getRecommendation() method.

Code below (left out imports and public class):

public WhatBook() {
    
    System.out.println("Hello, what genre of book are you in the mood for?");
        System.out.println("Please enter: \n1 for Horror\n2 for Adventure\n3 for Crime\n4 for War\n5 for Scifi");
        while (true) {
        Scanner scanGenre = new Scanner(System.in);
        int bookGenre = scanGenre.nextInt();
        
        if (bookGenre < 1 || bookGenre > 5) {
            System.out.println("Please choose from the genres from 1 to 5.");
        } else {
            System.out.println(bookGenre + "? Great choice! Let's get some recommendations for you.");
            break;
        }
        
    }


public static String getRecommendation() {

    // pick random element of the entered genre array
    // create random object
    int rnd = new Random().nextInt(array.length);
    return array(rnd);

}

// public arrays
String[] horror = { "The Shining", "The Stand", "The Haunting of Hill House" };
String[] adventure = { "Into Thin Air", "Hatchet", "The Call of the Wild" };
String[] crime = { "In Cold Blood", "Devil in the White City", "Helter Skelter" };
String[] war = { "The Things They Carried", "All Quiet on the Western Front", "Catch-22" };
String[] scifi = { "Dune", "1984", "Ender's Game" };

public static void main(String[] args) {

    WhatBook user1 = new WhatBook();

}

I tried using a switch loop in the constructor to set each int value to its corresponding array. Like:

switch (bookGenre) {

case 1: bookGenre = horror[0]; break; etc...

but this doesn't work.

Any ideas how to store the bookGenre int value to match its array?




Differences in simulation outputs using random

I'm trying to find the expected number of time steps for an share price to fall from $25 to $18 by generating simulations. Analytically, it can be shown that the expected number of time steps required is 129.

The following 3 codes appear fundamentally the same to me, but gives different results.

The first returns an average of 100 time steps:

target = 18
support_level = 20
I = []
n = 50000

for i in range(n):
    stock_price = 25
    t = 0
    
    while stock_price != target:

        t += 1

        if stock_price < support_level:
            stock_price += random.choices([-1, 1], weights=[1/3, 2/3])[0]

        if stock_price == support_level:
            stock_price += random.choices([-1, 1], weights=[0.1, 0.9])[0]

        if stock_price > support_level:
            stock_price += random.choices([-1, 1], weights=[2/3, 1/3])[0]
    
    I.append(t)
sum(I) / len(I)

The second returns an average of 114:

for i in range(n):
    stock_price = 25
    t = 0
    
    while stock_price != target:
        x = random.uniform(0, 1)
        t += 1

        if stock_price < support_level:
            if x <= 2/3:
               stock_price += 1
            else:
               stock_price -= 1

        if stock_price == support_level:
            if x <= 0.9:
               stock_price += 1
            else:
               stock_price -= 1

        if stock_price > support_level:
            if x <= 1/3:
               stock_price += 1
            else:
               stock_price -= 1
    
    I.append(t)

The third returns an average of 129:

for i in range(n):
    p=25
    t=0

    while p != 18:
        if(p==20):
            dist = [0.1, 0.9]
        elif(p>20):
            dist = [2/3, 1/3]
        else:
            dist = [1/3, 2/3]

        p=p+random.choices(direction, dist)[0]
        t+=1
        
    I.append(t)
    
sum(I)/len(I)

What is the difference?




How do I use a list to store operators that I can use in a function? [duplicate]

I am very new to python and I would really appreciate the help.

If I write the eval statement where I input the values in manually it works no problem

x = input("Enter a number: ")
y = input("Enter another number: ")
o = input("Enter calculation symbols for calculation you want to perform: ")

result = eval(x + o + y)
print("result is: %s" %result)

But when I try to write the eval statement pulling variables from a list I get an “unsupported operand type(s) for +: 'int' and 'str'” error import random

x = [1, 2, 3, 4, 5, 6, 7, 8, 9];
y = [1, 2, 3, 4, 5, 6, 7, 8, 9];
o = ['+', '-', '*', '/'];

rx = random.choice(x)
ry = random.choice(y)
ro = random.choice(o)

result = eval(rx + ro + ry)
print("The result is: %s" %result)

I have tried changing the variable type but it seems at least to me that the issue is with the operator variable type and I have no idea how to correct that.

Thanks for the help!




How do I program a spatially dependend random number distribution?

I wrote a routine that distributes circles randomly (uniformly) with an arbitrary diameter in my study area.

def no_nearby_dots(new_dot, dots_sim, min_distance):
    for dot in dots_sim:
        if np.sqrt((dot[0] - new_dot[0]) ** 2 + (dot[1] - new_dot[1]) ** 2) <= min_distance:
            return False
    return True

while realizations < simulations:
    dots_sim = []
    new_dot = True
    dots_sim.append((np.random.uniform(xmin, xmax), np.random.uniform(ymin, ymax)))
    failed_attempts = 0
    while new_dot:
        xp = np.random.uniform(xmin, xmax)
        yp = np.random.uniform(ymin, ymax)
        if no_nearby_dots((xp, yp), dots_sim, diameter):
            dots_sim.append((xp, yp))
            failed_attempts = 0
        else:
            failed_attempts += 1
        if len(dots_sim) == n_sim:
            new_dot = False
        if failed_attempts > 2000:
            new_dot = False
            print('ERROR...exit loop')
            break

    x_sim = [dot[0] for dot in dots_sim]
    y_sim = [dot[1] for dot in dots_sim]

I want to introduce a second circle around the initial ones where the possibility of distributing points reduces exponentially towards the inner border -> I want to prevent a "hard" border, the points are allowed to occur anywhere on the plane but not closer than diameter, additionally they can only occur to a certain degree between diameter and diameter2.

Are there any ideas how to do that?




Optimize randomization of a number excluding a list of values in Python

I need to generate a random number between a min and a max. This number should be a multiple of 10. This is the solution I have come to.

import random
BLOCK = 10

def random_excluding_values(_min, _max, exclude_list):
while True:
    random_number = round(random.randrange(_min, _max - BLOCK) / BLOCK) * BLOCK
    if random_number not in exclude_list:
        return random_number

There is a way to obtain the same result using list list comprehension or something else?




dimanche 27 septembre 2020

RandomRegex, I want to use the Dropdown menus options and select randomly one of them

I once worked it out before, which was years ago, and now i'm having trouble figuring out the syntax required to choose one option from the many given.




On the full double range std::uniform_real_distribution always returns inf

Consider the following minimal example:

#include <random>
#include <iostream>

int main (const int argC, char* argV[] ) {
    std::uniform_real_distribution<double> dist(std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max());
    std::random_device gen;
    std::cout << dist(gen) << std::endl;
    return 0;
}

I would expect the program to print basically any number in the range of double. However on my machine the output is always inf. The same is true if I replace double by float.

I can easily imagine how this can happen by a faulty implementation of std::uniform_real_distribution, as e.g. the length of the interval from which the numbers are drawn is not representable as a double. However my question is, is this indeed a bug in my standard library implementation, or did I miss some some restriction on the interval allowed by the C++ standard?




Using list instead of dictionary for organized results

I'm trying to get my code below working to have the results organized rather than random.

This is what's happening now.

sum = 9 count = 117
sum = 6 count = 142
sum = 3 count = 58
sum = 7 count = 172
sum = 8 count = 129
sum = 5 count = 109
sum = 4 count = 87
sum = 11 count = 53
sum = 12 count = 31
sum = 10 count = 72

And what I'm trying to achieve is

    sum = 1 count = 117
    sum = 2 count = 142
    sum = 3 count = 58
    sum = 4 count = 172
    sum = 5 count = 129
    sum = 6 count = 109
    sum = 7 count = 87
    sum = 8 count = 53
    sum = 12 count = 31

etc. While omitting any number that hasn't been rolled. I'd ideally like to use a list instead of a dictionary but any time I try it I get varying errors. Currently this outputs the amount but not in order.

    import random
    
    print("results")
    occurrences = []
    for i in range(1000):
        die1 = random.randint(1, 6)
        die2 = random.randint(1, 6)
        roll = die1 + die2
        current = occurrences[roll, ]
        occurrences[roll] = current + 1
    
    for roll, count in occurrences[]
        print(f"sum = {roll} count = {count}")



How to assign an argument to the probabilty of returning that arg?

So what i want to do it's to assign an argument(x p.e) to the probabilty of returning it. Example : if x is 0.22, i will have a 22% probabilty of return True; if x is below 0 or higher than 1, then assign x = 0.5 p.e idk what to write in return part...so i tried this solution but without sucess

def gen_true(x):
    for x in range(0,1):
       x = float(x)
    if x > 100 or x < 0:
       p = 0.5
    elif 1 < x < 100:
       x = x / 100

    return random.randrange(100) < x
gen_true(0.70)



Puppeteer Random user-agent args

Recently I asked this random useragents from .json file but the thing is that after I added "capture screen" of puppeteer it keeps showing headless chrome, so I copied the previous topic answer into wrong place.

Now the real useragent js page came from this page:

const browser = await puppeteer.launch({
headless: false,
args: ['--headless', '--disable-infobars', '--user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36', '--no-sandbox', `--proxy-server=socks5://127.0.0.1:${port}`] : ['--no-sandbox'],

});

So how do I create rnadom list inside the arguments? My previous help which doesnt worked for me as the random useragents code was not in correct place is here: Puppeteer browser useragent list

But adding that code inside this wont work.

So after --user-agent= I want to add "random" function but how?




Numpy repeat random choice

Imagine a 2D Boolean field. Suppose it is a a x b = 3x3 field

F= [[0 1 0] [0 1 0] [1 1 1]]

without_zeros(range(9)*F) = (1 4 6 7 8 ) this is the list of idices where F = True.

Now I need N = e.g.1M possibilities to randomly make m (e.g. 3) selections from this number range without repetitions

e.g.

1 7 4
4 6 8
8 6 1
1 6 4
... 

My approach with vectorized functions failed.

My best result so far is with a = 3, b = 3, N = 5E6, m = 3 ~ 84s. on an i3 7250.

My question: Are there better methods with prevent the for-loop and work in parallel / vectorized?

compiled - start timer
Time: 84.47356009483337
finish

working example:

import numpy as np
from numba import jit, prange
import time as t

@jit
def startzellen_zufall(mask, m, N):
    b = mask.reshape(mask.size)
    a = np.arange(1, len(b) + 1, dtype=np.int16)
    c = a * b
    clean = np.array(c[c != 0], dtype=np.int16)

    l = []
    for i in prange(0, N):
        l.append(np.random.choice(clean, m, replace=False))
    return np.stack(l)

##############
N = 5000000
m = 3
mask = np.array([[True, False, False], [False, True, True], [True, False, True]])

startzellen_zufall(mask, m, N)
print("compiled - start timer")
t1 = t.time()
startzellen_zufall(mask, m, N)
t2 = t.time()
print("Time: %s" % (t2 - t1))
print("finish")




Button to change background color randomly

const btn = document.getElementById('btn');

btn.addEventListener('click', () => {
    document.body.style.backgroundColor = changeC()
});

var x = Math.floor(Math.random() *256);
    y = Math.floor(Math.random() * 256);
    z = Math.floor(Math.random() * 256);

function changeC() { 
    return  "rgb(" + x + "," + y + "," + z + ")";
};

First click changes the background color.
Consecutive clicks don't.
How to modify code so that consecutive clicks will also change the background color randomly?




Python Dice Program, Random integer not changing

I am trying to write a small bit of code, that makes a number of throws of a dice and then records the number of 6's rolled. As you can imagine i'm using random.randint(1,6). However the random integer is simply repeated for each consecutive throw. I am guessing it could be the structure of the while loop I have, i'm a total newbie to this so any help would be much appreciated.

#import random module
import random

#introduce the program
print("a program to count the number of 6's thrown in a simulation of a dice being thrown 6000 times")

#declare the variables
max = int(6) #need to declare max number for the dice
min = int(1) #need to declare min number for the dice
throw = random.randint(1,6) #each throw of the dice generates a number
countThrow = 0 #count the number of throws
maxThrow = int(6) #max throw
sixRolled = 0 #count the number of 6's thrown

#while loop

while countThrow != maxThrow:
    countThrow = countThrow + 1
    print(throw)
    print("Number of rolls ", countThrow)

    if throw == 6:
        sixRolled = sixRolled + 1
        print("You have thrown a", throw)

    else:
        print("you have rolled a", throw, "roll again.")
        

print("You have rolled ", sixRolled, "6's in 6 throws")

Many thanks




samedi 26 septembre 2020

Generate random images from user checkboxed selections

Hi I have two sets of code. The first one was made by a nice person on this site, and generates a random letter based on the selections checkboxed by the user.

The second is one I found online. It allows you to turn image links into checkboxes that can be checked and unchecked.

I am trying to combine these two codes so that I can have the program generate a random image (instead of a letter) based on an array of images (again instead of letters) that the user checkboxes. In short, I'm trying to get something like the first set of code that uses images instead of letters.

Then, the final thing I'm trying to do is add a range slider like so (https://www.w3schools.com/code/tryit.asp?filename=GJ5U82DC2JX9) underneath each image. I want the user to be able to use the slider to "weight" the frequency of each checked image in the final randomization (with a range of 0 to 10).

Here is the first program in running form:

https://www.w3schools.com/code/tryit.asp?filename=GJ5TXX8V9B7L

Here is the second program in running form:

https://www.w3schools.com/code/tryit.asp?filename=GJ5TXEQM6HVI

I have tried intuitively copying and pasting from one set to the other, but I cant seem to get it even close to working the way I'd like. As for the weighting part, I am at a loss.

Thank you for any and all help, and if this is beyond the scope of help for this site I apologize.




IndexOutOfBounds Exception for Card Shuffler

I am trying to create a card shuffler method and I am currently having trouble with an IndexOutOfBounds exception. I can't seem to understand why it is erroring out even after working through the code.

public static ArrayList<Card> shuffle(ArrayList<Card> currDeck) {
        var newDeck = new ArrayList<Card>();
        int length = currDeck.size();
        Random rand = new Random();
        int counter = 0;

        while (length != 0) {
            int index = rand.nextInt(length - 1);
            newDeck.set(counter, currDeck.get(index));
            currDeck.remove(currDeck.get(index));
            length --;
            counter ++;
        }


        return newDeck;
    }

Thanks!




Need to add a loop [closed]

I have this JavaScript which displays x random numbers of which sum is a given number y. (120 splitted to 5 random parts currently)

I want to make it display all possible combinations of number like a list, but allow only numbers from 1-50.

import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
public class Demo {
    public static Random randNum = new Random();
    public static int[] DemoFunc(int number, int parts) {
        HashSet<Integer>set = new HashSet<Integer>();
        set.add(0);
        set.add(0);
        set.add(0);
        set.add(number);
        int arrSize = parts + 1;
        while (set.size() < arrSize) {
            set.add(1 + randNum.nextInt(number - 1));
        }
        Integer[] dividers = set.toArray(new Integer[arrSize]);
        Arrays.sort(dividers);
        int[] res = new int[parts];
        for(int i = 1, j = 0; i<dividers.length; ++i, ++j) {
            res[j] = dividers[i] - dividers[j];
        }
        return res;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(DemoFunc(120, 5)));
    }
}



Initialize a np array randomly with a determined quantity of 1's and 0's

I want to initialize an array randomly with a certain quantity of 1's and 0's. The following code is all I've got. I just managed to initialize it with a random quantity of 1's and 0's, but I'd like to do it, for example (knowing that the matrix is 10x10) with 25 1's and 75 0's.

matrix = np.random.randint(2, size=(10,10))



Finding the multiple in while loop

The return type is int and the input parameters are also int.

I am generating random integers in the while loop and I am checking if that int is the multiple of the input parameter int and the return the number of tries it took to get that matched one.

And I want to do it in a while loop and not in a for loop.

public int findMul(int v){
    double random = Math.random();
    int numoftries = 0;

    while(v % random == 0){
        numoftries++;
    }
    return numoftries;
}

For some reason when I call it in the main method then execute it, it always shows the number 0 no matter what number and I don't know how to fix.




How do i loop a random int that changes in each loop

I want to create a loop that prints out a diffrent random number 10 times. I tried creating a random int in the variable num and then used a for-loop that printed out the variable num 10 times:

Random rnd = new Random();

int num = rnd.Next(10);

for (int i = 0; i < 10; i++) 
    {
       Console.WriteLine(num)
    }

This obviously doesn't work since it prints out the same random number 10 times. How do I get it to output a diffrent number in each loop?




Instagram Random Comment Picker

I plan to make a random comment picker website for Instagram. For instance an user wants to use these web site and s/he will paste an URL which contains comments of his/her own Instagram account and the web site will pick randomly any of them maybe one or two, maybe more.

I thought primary to get a class name (using DOM object) that contains user account name but I couldn't.

So I realized that I should use some API to get data. But surely I don't know what I have to do. If I use Graph API, can I reach to these comments (not my own Instagram accounts users' comments)?




Calling generator and expecting random results but the same result repeats

My function is like this:

    def func(word1):
       for x in index
    #  lots of stuff
            yield from ''.join(word3)

Then I call it later like this:

input3 = next(iter(''.join(func(input2[-x:])) for x in range(len(input1))))

But the results are being sent repeatedly instead of a new random one as it should. The function does not seem to be executed for a while after getting the results. But - after about 5 or so loops (from outside the generator which call the generator as above), an additional randomized result is retrieved from the generator. This was being stacked onto my input in a way like RandWord1RandWord2. This is why I added input2[-x:] to make sure I'm only getting the latest result. But the problem is that I want the results to to vary every single time, not after ~5 tries.

I previously had the for loop that now occurs in the generator as part of my loops from outside of it, and everything worked as I expected. But I had a lot of repeating code because of it so I wanted to define it as a function that could be called instead. I tried searching and I figured next would be what I needed, but it doesn't force cause the generator to to be executed every time it appears.

Anyone know what could be the problem?




Why does random.seed( ) does not work in generating dataset?

I'm creating dataset for testing with

import random
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split

random.seed(10)
X, y = make_regression(n_samples = 1000, n_features = 10)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 0)
X[0:2]

Could you please explain why I get a different dataset after each running? For example, 2 runs return

array([[-0.28058959, -0.00570283,  0.31728106,  0.52745066,  1.69651572,
        -0.37038286,  0.67825801, -0.71782482, -0.29886242,  0.07891646],
       [ 0.73872413, -0.27472164, -1.70298606, -0.59211593,  0.04060707,
         1.39661574, -1.25656819, -0.79698442, -0.38533316,  0.65484856]])

and

array([[ 0.12493586,  1.01388974,  1.2390685 , -0.13797227,  0.60029193,
        -1.39268898, -0.49804303,  1.31267837,  0.11774784,  0.56224193],
       [ 0.47067323,  0.3845262 ,  1.22959284, -0.02913909, -1.56481745,
        -1.56479078,  2.04082295, -0.22561445, -0.37150552,  0.91750366]])



vendredi 25 septembre 2020

How can I determine the number of points in sliced 27 cubes of a big cube

I have coded for 100 points randomly and uniformly distributed in a big cube of dimensions 100x100x100. Then I divided the big cube of 100x100x100 into small 27 equal cubic slices. I wish to compute the number of points in each cube and their distances from each other.

Please help




Adding adjustable random noise to a matrix in R

I have a matrix generating function that produces lower-triangle of 1s and upper-triangle of 0s.

I was wondering if it might be possible to add some adjustable random noise (from some distribution that gives random 0 and 1) to the outputted matrix such that the random 0s randomly replace some of the bottom 1s, and random 1s randomly replace some of the top 0s?

lower_mat <- function(r, c) {
  m <- matrix(0, nrow=r,ncol=c)
  m[lower.tri(m)] <- 1
  m
}


lower_mat(5,4)
#      [,1] [,2] [,3] [,4]
# [1,]    0    0    0    0
# [2,]    1    0    0    0
# [3,]    1    1    0    0
# [4,]    1    1    1    0
# [5,]    1    1    1    1



Order of operation and How does the random() play in this scenario

Just started learning loops and I'm having trouble understanding the order of operation here in the let value, along with how the random() works in this scenario.

From what it looks like: Math.floor() prevents decimals and Math.random() selects a random number between 0 and 36. Does random() select a random value for both MAX and MIN? Does random() also generate a random for its self to be multiplied by whatever the value of MAX and MIN equal after being subtracted, then adding the MIN back?

const MIN = 0;
const MAX = 36;
var testNumber = 15;
var i = 1;

while (MAX) {
    let randomValue = Math.floor(Math.random() * (MAX - MIN)) + MIN;

    if (randomValue == testNumber) {
        break;
    }



How to get reproducible samples from Tensorflow Probability: tfp.mcmc.sample_chain?

Running a simple Bayesian regression model, I am not able to replicate the results with multiple runs on GPU. I am wondering how I can set tfp.mcmc.sample_chain to generate reproducible results on GPU? Seeding the sample_chain didn't work for me.

The test code snippet:


import os
import random
from pprint import pprint
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import pandas as pd

import tensorflow.compat.v2 as tf
tf.enable_v2_behavior()

import tensorflow_probability as tfp

sns.reset_defaults()
#sns.set_style('whitegrid')
#sns.set_context('talk')
sns.set_context(context='talk',font_scale=0.7)

%config InlineBackend.figure_format = 'retina'
%matplotlib inline

tfd = tfp.distributions
tfb = tfp.bijectors

dtype = tf.float64
dfhogg = pd.DataFrame(np.array([[1, 201, 592, 61, 9, -0.84],
                                 [2, 244, 401, 25, 4, 0.31],
                                 [3, 47, 583, 38, 11, 0.64],
                                 [4, 287, 402, 15, 7, -0.27],
                                 [5, 203, 495, 21, 5, -0.33],
                                 [6, 58, 173, 15, 9, 0.67],
                                 [7, 210, 479, 27, 4, -0.02],
                                 [8, 202, 504, 14, 4, -0.05],
                                 [9, 198, 510, 30, 11, -0.84],
                                 [10, 158, 416, 16, 7, -0.69],
                                 [11, 165, 393, 14, 5, 0.30],
                                 [12, 201, 442, 25, 5, -0.46],
                                 [13, 157, 317, 52, 5, -0.03],
                                 [14, 131, 311, 16, 6, 0.50],
                                 [15, 166, 400, 34, 6, 0.73],
                                 [16, 160, 337, 31, 5, -0.52],
                                 [17, 186, 423, 42, 9, 0.90],
                                 [18, 125, 334, 26, 8, 0.40],
                                 [19, 218, 533, 16, 6, -0.78],
                                 [20, 146, 344, 22, 5, -0.56]]),
                   columns=['id','x','y','sigma_y','sigma_x','rho_xy'])


## for convenience zero-base the 'id' and use as index
dfhogg['id'] = dfhogg['id'] - 1
dfhogg.set_index('id', inplace=True)

## standardize (mean center and divide by 1 sd)
dfhoggs = (dfhogg[['x','y']] - dfhogg[['x','y']].mean(0)) / dfhogg[['x','y']].std(0)
dfhoggs['sigma_y'] = dfhogg['sigma_y'] / dfhogg['y'].std(0)
dfhoggs['sigma_x'] = dfhogg['sigma_x'] / dfhogg['x'].std(0)

X_np = dfhoggs['x'].values
sigma_y_np = dfhoggs['sigma_y'].values
Y_np = dfhoggs['y'].values

def sample(seed):

  mdl_ols_batch = tfd.JointDistributionSequential([
      # b0
      tfd.Normal(loc=tf.cast(0, dtype), scale=1.),
      # b1
      tfd.Normal(loc=tf.cast(0, dtype), scale=1.),
      # likelihood
      #   Using Independent to ensure the log_prob is not incorrectly broadcasted
      lambda b1, b0: tfd.Independent(
          tfd.Normal(
              # Parameter transformation
              loc=b0[..., tf.newaxis] + b1[..., tf.newaxis]*X_np[tf.newaxis, ...],
              scale=sigma_y_np[tf.newaxis, ...]),
          reinterpreted_batch_ndims=1
      ),
  ])
  
  
  @tf.function(autograph=False, experimental_compile=True)
  def run_chain(init_state, 
                step_size,
                target_log_prob_fn,
                unconstraining_bijectors,
                num_steps=500, 
                burnin=50):

    def trace_fn(_, pkr):
      return (
          pkr.inner_results.inner_results.target_log_prob,
          pkr.inner_results.inner_results.leapfrogs_taken,
          pkr.inner_results.inner_results.has_divergence,
          pkr.inner_results.inner_results.energy,
          pkr.inner_results.inner_results.log_accept_ratio
      )

    kernel = tfp.mcmc.TransformedTransitionKernel(
      inner_kernel=tfp.mcmc.NoUTurnSampler(
        target_log_prob_fn,
        step_size=step_size),
      bijector=unconstraining_bijectors)

    hmc = tfp.mcmc.DualAveragingStepSizeAdaptation(
      inner_kernel=kernel,
      num_adaptation_steps=burnin,
      step_size_setter_fn=lambda pkr, new_step_size: pkr._replace(
          inner_results=pkr.inner_results._replace(step_size=new_step_size)),
      step_size_getter_fn=lambda pkr: pkr.inner_results.step_size,
      log_accept_prob_getter_fn=lambda pkr: pkr.inner_results.log_accept_ratio
    )

    # Sampling from the chain.
    chain_state, sampler_stat = tfp.mcmc.sample_chain(
        num_results=num_steps,
        num_burnin_steps=burnin,
        current_state=init_state,
        kernel=hmc,
        trace_fn=trace_fn,
        seed=seed
    )
    return chain_state, sampler_stat

  nchain = 4
  b0, b1, _ = mdl_ols_batch.sample(nchain)
  init_state = [b0, b1]
  step_size = [tf.cast(i, dtype=dtype) for i in [.1, .1]]
  target_log_prob_fn = lambda *x: mdl_ols_batch.log_prob(x + (Y_np, ))

  # bijector to map contrained parameters to real
  unconstraining_bijectors = [
      tfb.Identity(),
      tfb.Identity(),
  ]

  samples, sampler_stat = run_chain(
      init_state, step_size, target_log_prob_fn, unconstraining_bijectors)
  print(tf.reduce_sum(samples))
  

seed = 24
  
os.environ['TF_DETERMINISTIC_OPS'] = 'true'
os.environ['PYTHONHASHSEED'] = f'{seed}'
np.random.seed(seed)
random.seed(seed)
tf.random.set_seed(seed)
sample(seed)

os.environ['TF_DETERMINISTIC_OPS'] = 'true'
os.environ['PYTHONHASHSEED'] = f'{seed}'
np.random.seed(seed)
random.seed(seed)
tf.random.set_seed(seed)
sample(seed)




iunity c# script random 2d level creation

Hello i got this code that generates level parts randomly but i need to remove already appeared level parts from the game ,the ones that my character already past but i want to store them somewhere to be able to get back on my 2d level by recreating same parts.What would be best approach to this? Some guy told me about seed generation and other something about storing information in a list or something.


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LevelGenerator : MonoBehaviour
{
    private const float PlayerDistanceSpawnLevelPart = 50f;
    [SerializeField] private Transform LevelPartStart;
    [SerializeField] private List<Transform> LevelPartList;
    public GameObject player;
    private Vector3 lastEndPosition;

    private void Awake()
    {
        lastEndPosition = LevelPartStart.Find("EndPosition").position;
        
        int StartingSpawnLevelParts = 5;
        for (int i = 0; i < StartingSpawnLevelParts; i++)
        {
            SpawnLevelPart();
        }
    }

    void Update()
    {

        if (Vector3.Distance(player.transform.position, lastEndPosition) < PlayerDistanceSpawnLevelPart)
        {
            //spawn another level part
            SpawnLevelPart();
        }
    }

    private void SpawnLevelPart()
    {
        Transform chosenLevelPart = LevelPartList[Random.Range(0, LevelPartList.Count)];
        Transform lastLevelPartTransform = SpawnLevelPart(chosenLevelPart,lastEndPosition);
        lastEndPosition = lastLevelPartTransform.Find("EndPosition").position;
    }
    private Transform SpawnLevelPart(Transform levelPart,Vector3 spawnPossition)
    {
        Transform levelPartTransform = Instantiate(levelPart, spawnPossition, Quaternion.identity);
        return levelPartTransform;
    }

}




numpy.random.rand() generating values greater than 1

I'm trying to create two numpy arrays (a, b) filled with random values between 0-1 using numpy.random.rand(). While the following code doesn't cause any problems for a, the seceond array b is filled with values between 1-10.

import numpy

a = numpy.random.rand(100,784)
b = numpy.random.rand(10,100)

print(b)

Any ideas?




Hive: randomly select N values from distinct values of one column

Suppose I have a dataset like this

|-----------------|----------------|
|    ID           |     Values     |
|-----------------|----------------|
|     123         |     aaaa       |
|-----------------|----------------|
|    234          |    bbb         |
|-----------------|----------------|
|     123         |     ab3d       |
|-----------------|----------------|
|    264          |     34g3ff     |
|-----------------|----------------|
|     783         |     341g5h     |
|-----------------|----------------|
|    921          |     7jdfew     |
|-----------------|----------------|
|     264         |     53fj       |
|-----------------|----------------|

I would like to randomly select, say, 3 values from the distinct ID values. One possibility is to get a table like this

|-----------------|----------------|
|    ID           |     Values     |
|-----------------|----------------|
|     123         |     aaaa       |
|-----------------|----------------|
|     123         |     ab3d       |
|-----------------|----------------|
|     783         |     341g5h     |
|-----------------|----------------|
|    921          |     7jdfew     |
|-----------------|----------------|

How shall I do that in Hive?




Given a exponential probability density function, how to generate random values using the random generator in Excel?

Based on a set of experiments, a probability density function (PDF) for an exponentially distributed variable was generated. Now the goal is to use this function in a Monte carlo simulation. I am vaguely familiar with PDF's and random generator, especially for normal and log-normal distributions. However, I am not quite able to figure this out. Would be great if someone can help.

Here's the function:

f = γ/2R * exp⁡(-γl/2R) (1-exp⁡(-γ) )^(-1) H (2R-l)

  • f is the probability density function,
  • 1/γ is the mean of the distribution,
  • R is a known fixed variable,
  • H is the heaviside step function,
  • l is the variable that is exponentially distributed



Randomly change position of letters in a string in c++

I have a program that creates a password with upper letters, lower letters, symbols and numbers in this order, but I want to make a subprogram that changes the order of letters in the string, making it completely random, but with out changing the letters, only the order.

Example: "ORVkgr<>74" -> ">Vr7>kgO4R<" or "Ogk4r7<RV>".




Taking random samples from a python generator

I'm using the function for pair in itertools.combinations(bug_map.keys(), 2): to generate all pairs of elements in my db. The problem is that the amount of element is around 6.6 K and so the number of combinations is 21.7 M. Also, combinations are emitted in lexicographic sort order.

Supposing that I would take random pairs from the generator without "yielding" all of them (just a subset of n dimension), what can I do?




jeudi 24 septembre 2020

unsupported operand type(s) for +: 'float' and 'list'

i was starting with pygame recently and tried making a snake game, in which i came up with this error . plzz help.

here is my code!!

import pygame
import random
import time

pygame.init()

print("SELECT LEVEL:\n"
      "EASY\n"
      "MEDIUM\n"
      "HARD\n"
      "DIFFICULT\n")
level=input()
if level =="easy" or "EASY":
    fps=35
elif level =="medium" or "MEDIUM":
    fps=50
elif level =="hard" or "HARD":
    fps=80
elif level =="difficult" or "DIFFICULT":
    fps=110

win=pygame.display.set_mode((600,600))
pygame.display.set_caption("SNAKE GAME")
clock=pygame.time.Clock()
x=10
y=10
dim=10
vel=5
snake_pos=[]

def snake(dim,snake_pos):
    for x in snake_pos:
        pygame.draw.rect(win, (255, 0, 0), [x[0], x[1], dim, dim])
def snakegame():
    gameover=False
    gameend=False

    x1=600/2
    y1=600/2

    x1_change=0
    y1_change=0

    snakelist=[]
    length_of_snake=1

    foodx=round(random.randrange(0,600-dim)/10.0)*10.0
    foody=round(random.randrange(0,600-dim)/10.0)*10.0


    while not gameover:
        while gameend==True:
            score=length_of_snake-1
            score_font=pygame.font.SysFont("comimsansms",45)
            value=score_font.render("Your score is:"+str(score),True,(0,0,255))
            win.blit(value,[600/3,600/5])
            pygame.display.update()

            for event in pygame.event.get():
                if event.type==pygame.QUIT:
                    gameend=False
                    gameover=True

        #win.fill((0,0,0))


        for event in pygame.event.get():
            if event.type==pygame.QUIT:
                gameover=True

            if event.type==pygame.KEYDOWN:
                if event.key==pygame.K_LEFT:
                    x1_change=-snake_pos
                    y1_change=0
                if event.key == pygame.K_RIGHT:
                    x1_change = snake_pos
                    y1_change = 0
                if event.key==pygame.K_UP:
                    y1_change=-snake_pos
                    x1_change=0
                if event.key==pygame.K_DOWN:
                    y1_change=snake_pos
                    x1_change=0

        if x1>=600 or x1<0 or y1>=600 or y1<0:
            gameend=True
        x1=x1+x1_change
        y1=y1+y1_change
        win.fill((0,0,0))
        pygame.draw.rect(win,(255,255,0),[foodx,foody,dim,dim])
        snake_head=[]
        snake_head.append(x1)
        snake_head.append(y1)
        snake_pos.append(snake_head)

        if len(snake_pos)>length_of_snake:
            del snake_pos[0]

        for x in snake_pos[:-1]:
            if x==snake_head:
                gameend=True
        snake(dim,snake_pos)
        pygame.display.update()
        if x1==foodx and y1==foody:
            foodx = round(random.randrange(0, 600 - dim) / 10.0) * 10.0
            foody = round(random.randrange(0, 600 - dim) / 10.0) * 10.0
            length_of_snake=length_of_snake+1
        clock.tick(fps)
    pygame.quit()


snakegame()

after running its showing the screen ...but when i try to move it..its giving this error message. tried everything but nothing is working

Traceback (most recent call last):
  File "C:/pypy/projects/snakeGame.py", line 112, in <module>
    snakegame()
  File "C:/pypy/projects/snakeGame.py", line 87, in snakegame
    x1=x1+x1_change
TypeError: unsupported operand type(s) for +: 'float' and 'list'

i am using pycharm anaconda 3.7 , will be glad if someone can help




How to randomly change the signs of some of the elements in a numpy array?

Given a numpy array

import numpy as np
from numpy.random import random
N = 5
x = random(N)

How to randomly multiply a subset of (some of the elements in) x by -1 in order to change the sign of some of the elements in the array?




shuffle every value in a String[]

so i have a large amount of strings in a string array but for this case lets just say this:

String s = 
"abc," +
"bac," +
"cba," +
"cab," +
"bca,";

//split s of all characters behind a comma and place them in a array

String[] sArray = s.split(",");  

//assign a number to each index in sArray and assign a random index to desiredString

Random stringSelector = new Random();
int range = stringSelector.nextInt(sArray.length);
desiredString = sArray[stringSelector];

//print

System.out.println(desiredString);

the real problem here is that there will be too many occurrences of a certain index if you place this program in a loop

cab
cab
abc
cab
bac
cab
bca
cab 

and adding more values to s doesnt help the case because i am really working with a array with 81 strings

i was wondering if there is a way to shuffle every value in sArray before having a number assigned to each index

or basically just creating a more "random" sequence than Random()




I can't replicate my results even after setting the random.seed

I have a class Simulation(theta), in which two of its methods draw a random number from an exponential distribution (numpy.random.exponential(theta[i]]), i=[0,1]).

numpy.random.seed(42)

n_sim = 1000

ss_syn = numpy.zeros((n_sim, 4))

for i in range(n_sim):

    theta = [numpy.random.uniform(3, 7), numpy.random.uniform(7, 14)]
    
    s = Simulation(theta)

    while s.num_departs < 200:
        s.advance_time()
        
    ss_syn[i, 0] = theta[0]
    ss_syn[i, 1] = theta[1]
    ss_syn[i, 2] = s.total_wait / 200

ss_syn = pandas.DataFrame(ss_syn, columns=['arrival_avg', 'serving_avg', 'total_wait_avg'])

print(ss_syn)

The output is:

enter image description here

The problem lies when I try to replicate the result, for instance:

s = Simulation([6.026572, 11.560237])
# I've also tried Simulation([ss_syn.iloc[0, 0], ss_syn.iloc[0, 1])

while s.num_departs < 200:
        s.advance_time()

print(s.total_wait / 200)

which gives me an output of 96.1220525219869 (totally different from the one I expected: 151.143088)

Notice that I do set the random seed. I've even tried switching IDE (from JupyterLab to Pycharm) and the result is still the same. Does the fact that I am drawing a random number inside the class have something to do with this replication problem? If so, how could I replicate my results then?




How do I save the random generated string to a variable and compute the distance?

I am taking a Java class and was tasked to create a code with these parameters:

(Get String 1 –from user) Prompt the user to enter a string consisting of 5 uppercase characters and save this string in a variable.2.

(Get String 2 –randomly generated) Generate a string with 5 randomly generated characters and save it in a variable.

(Calculate Distance) Compute the distance between the two strings and display it to the user

I think I have cracked the first one and part of the second but am having trouble saving string2 to a variable and I can't seem to wrap my head around calculating distance.

Any help would be appreciated.

This is what I have so far:

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

public class StringDiff {

    public static void main(String[] args) {
        
        Scanner scan = new Scanner(System.in);
        
        System.out.println ("Please enter 5 Capital letters.");
        int userString = scan.nextInt();
        
        Math.random().toString(255).substr(2, 5);           
    }
}



Placing objects at random places in pygame

Hi I am writing a simple Snake game in python using pygame. There is one thing I cannot quite figure out, that is: how to put an object at a random place on the screen, without it flickering.

Here is a bit of my code:

class Food(object):

    def __init__(self):
        self.eaten = False

    def food_spawn(self):
        self.food_x = random.randrange(0, 800, 1)
        self.food_y = random.randrange(0, 800, 1)

    def food_drawing(self):
        self.food_spawn()
        pygame.draw.circle(win, (0, 255, 0), (self.food_x, self.food_y), 15)


def window_drawing():
    # Filling the window with the background color to make the block move and not to draw longer and longer stripes
    win.fill((0,0,0))


    # Drawing the Food and the snake
    player.snake_drawing()
    apple.food_drawing()

    pygame.display.update()



player = Snake(300, 50)
apple = Food()

I know that the issue is that I call random.randrange(0,800,1) every time I call apple.food_drawing(), and hence the new position with every iteration. However, I cannot find a way how to make the food position random without using randrange.

Do You have any idea how to make this work?

This is my entire code if you want to try it out:

import pygame
import random

pygame.init()
screen_widht = 800
screen_height = 800

pygame.display.set_caption('Snake Game')
win = pygame.display.set_mode((screen_widht, screen_height))

clock = pygame.time.Clock()

snake_vel = 5
mainLoop = True
snake_moving = True




class Snake(object):

    def __init__(self, snake_x, snake_y):
        # self.colour = colour
        self.snake_x = snake_x
        self.snake_y = snake_y
        self.snake_widht = 25
        self.snake_height = 25

    def snake_drawing(self):
        pygame.draw.rect(win, (255,0,0),(self.snake_x, self.snake_y, self.snake_widht, self.snake_height))


    def move_snake(self):
        pass


class Food(object):

    def __init__(self):
        self.eaten = False

    def food_spawn(self):
        self.food_x = random.randrange(0, 800, 1)
        self.food_y = random.randrange(0, 800, 1)

    def food_drawing(self):
        self.food_spawn()
        pygame.draw.circle(win, (0, 255, 0), (self.food_x, self.food_y), 15)


def window_drawing():
    # Filling the window with the background color to make the block move and not to draw longer and longer stripes
    win.fill((0,0,0))


    # Drawing the Food and the snake
    player.snake_drawing()
    apple.food_drawing()

    pygame.display.update()



player = Snake(300, 50)
apple = Food()

snake_dir_x = False
snake_dir_y = False
snake_dir_neg_x = False
snake_dir_neg_y = False


while mainLoop:
    clock.tick(30)

    # creates a list of pressed keys
    keys = pygame.key.get_pressed()


    # creates a list of events, ex: mouse click events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            mainLoop = False

    # Pauses the game(more accureatly the snakes movment)
    if keys[pygame.K_p]:
        snake_dir_x = False
        snake_dir_y = False
        snake_dir_neg_x = False
        snake_dir_neg_y = False


    # Control of the snake: the for loop and the break statments are so that the snake can not move side ways
    for _ in range(1):

        if keys [pygame.K_RIGHT] and player.snake_x < screen_widht - player.snake_widht:
            player.snake_x += snake_vel
            snake_dir_x = True
            snake_dir_y = False
            snake_dir_neg_x = False
            snake_dir_neg_y = False
            break

        if keys[pygame.K_LEFT] and player.snake_x > 0:
            player.snake_x -= snake_vel
            snake_dir_x = False
            snake_dir_y = False
            snake_dir_neg_x = True
            snake_dir_neg_y = False
            break

        if keys[pygame.K_DOWN] and player.snake_y < screen_height - player.snake_height:
            player.snake_y += snake_vel
            snake_dir_x = False
            snake_dir_y = False
            snake_dir_neg_x = False
            snake_dir_neg_y = True
            break

        if keys[pygame.K_UP] and player.snake_y > 0:
            player.snake_y -= snake_vel
            snake_dir_x = False
            snake_dir_y = True
            snake_dir_neg_x = False
            snake_dir_neg_y = False
            break

        else:
            if snake_dir_x and player.snake_x < screen_widht - player.snake_widht:
                player.snake_x += snake_vel
            if snake_dir_neg_x and player.snake_x > 0:
                player.snake_x -= snake_vel
            if snake_dir_neg_y and player.snake_y < screen_height - player.snake_height:
                player.snake_y += snake_vel
            if snake_dir_y and player.snake_y > 0:
                player.snake_y -= snake_vel


    window_drawing()

All help is appreciated thank You.




Im trying to print the sum in the main diagonal in a random array but my code wont work

int[][] arr = new int[rows][cols];

System.out.print("6. Output the sum of the elements in the main diagonal");

         for(i=0;i<rows;i++)
         { 
             for( j = 0; j < cols; j++)
          { 
              arr[i][j] = g.nextInt();
         }
     }
             for( i = 0; i < rows; i++)
         { 
              for( j = 0; j < cols; j++)
          { 
        if(i == j) 
     {
     sum = sum + arr[i][j];
     }
         }
        }
        System.out.print("SUM of DIAGONAL elements of the matrix = " + sum) ;



Randomly generate a specific amount of strings from a List c#

I may not know how to search for a solution properly yet but I could not find anything related to the thing I got stuck on below:

I have a List of strings containing 21 words

public static List<string> LevelOneWords = new List<string> { "As", "If", "Go", "Do", "So", "No", "Up", "Hi", "Me", "Be", "Ah", "An", "Aw", "Is", "Ok", "At", "We", "Am", "Ab", "Ex", "It"};

How do I go on about generating a specific amount of these following a user decision?

Because rand.Next(LevelOneWords.Count) only lets you generate random words from the amount available in the list.

But say I wanted to generate 50 instances?

To put you in the picture, this is a Typer Shark kind of game and in the training session, I want the user to have the freedom to choose how much words should be generated.

Thanking you in advance since I am new to programming and I find StackOverFlow's community very helpful!




How do i select a random cell in a csv

I have a CSV file that is random words only. No header.

For example:

"dawn","go","test","these","swung" "joy","frequently","seven","congress"

My code does not select a random cell and returns the error: 'TypeError: '_csv.reader' object is not subscriptable'

My code is:

    def random_select(self):

        csv_reader = csv.reader("randomwords.csv")       
        words = list(csv_reader)
        random_names = random.choice(words)
        readcsv = csv_reader[random_names][random_names]

        print(''.join(readcsv))



using Pipes create N child and send message to parent

I'm trying to create n child with the same parent, and send the random number from child -> parent. For now, I have a problem to send random 0/1 from child -> parent.

#include<stdio.h> 
#include<stdlib.h> 
#include<unistd.h> 
#include<sys/types.h> 
#include<string.h> 
#include<sys/wait.h> 

int main() 
{ 
pid_t pids[10];
int i;
int n = 10;

/* Start children. */
for (i = 0; i < n; ++i) {
     if ((pids[i] = fork()) < 0) {
     perror("fork");
         abort();
  } else if (pids[i] == 0) {
   // printf("I am a child with id %d and my parent %d\n",getpid(),getppid());
    int random = rand() % 2;
    printf("\nChild send random: %d\n",random);
    write(pids[1], &random, sizeof(random));    
    exit(0);
    }
   else{
    int ran;
    read(pids[0], &ran, sizeof(ran)); // read from child
    printf("\nParent Received: %d\n", ran);
    }
  
}

wait(NULL);

 }
 



mercredi 23 septembre 2020

replace increasing digits of an array

I have generated a random binary number in the form of an array of char with a fixed length

    public char[] biNum(int length) {

        char[] biStr = new char[length];
        for (int i=0; i<length; i++) {
            biStr[i] = (char)r.nextInt(1);
        }
        return biStr;
    }

how do I get multiple such arrays with increment number of '*' at random positions in it? example: if the length is 8, then

100*10*1 has 2 '*'
10*01*** has 4 '*'
0******1 has 6 '*'

I'm not trying to get a 2 dimension array here. But if that was easier then I am ok with that too

    for (i = 2; i < length; i+2){
        biNum(20);
        //some method that adds i '*' in biStr
        System.out.println(biStr);
    }

what I was thinking was, in the for loop add another loop

for (j = 0; j < i; j++)
    generate j random numbers
    for every random number
        biStr[random number] = '*'

but then I need to make sure there's no duplicate random number. I am not sure how to do it.




Can't I call rand() multy times in a line?

for (int i = 0; i < 12; i++) {
        Vertex v;
        v.pos = (glm::vec3)((GLfloat)(rand() % 100) / 50 - 1, (GLfloat)(rand() % 100) / 50 - 1, (GLfloat)(rand() % 100) / 50 - 1);
        v.col = (glm::vec3)((GLfloat)(rand() % 100) / 100, (GLfloat)(rand() % 100) / 100, (GLfloat)(rand() % 100) / 100);
        tri4.objData.vertices.push_back(v);
        std::cout << tri4.objData.vertices.at(i).pos.x <<"\t" <<i4.objData.vertices.at(i).pos.y<<"\t"<< tri4.objData.vertices.at(i).pos.z << "\n\n";
        std::cout << tri4.objData.vertices.at(i).col.x << "\t" << tri4.objData.vertices.at(i).col.y << "\t" << tri4.objData.vertices.at(i).col.z << "\n\n";

        tri4.objData.indices.push_back(i);
        std::cout << tri4.objData.indices.at(i) << '\n';
    }

this is my GL codes in tihis case, pos.x and pos.y are same.. those three rand()s are return same at 'v.pos=' line or 'v.col=' line.. I did't use srand(time) or something. does rand()s return same values on one line? or vec3 has problem with it?




Generate 128 bit Poisson distributed numbers in cpp

I try to measure probabilities in the order of 1e-25 or even lower. I run a cpp code which is basically an ODE solver numerically (with simple Euler steps). I have long long ints for storing the cell numbers (every step I roll a dice and I update the cell numbers using a 64 bit precision Mersenne Twister random num generator and I choose numbers from a poisson distribution with the mersenne engine). As long long int and 64 bit mersenne and poisson dist is only enough until approx. 1e19, I would need to have 128 bit precision. I am searching for a reliable method to generate 128 bit pseudo random numbers and also to store them like uint_128 and so, and generate especially 128bit random poisson distributed numbers.

I have searched in the topic but did not find anything helpful, maybe I could have puzzle the pieces together, but I could not...

Thank you in advance!




Randomise an ID variable, but maintain uniqueness of ID for grouping purposes

I have a bunch of different participant ID variables that I need to randomise for privacy purposes. However, I need the ID variables for grouping purposes in my analyses. So, I need new, 'random' IDs that are still unique to each participant.

An example of the result I want:

ids = c('A4579', 'A5219', 'A7832', 'A1650', 'A5219', 'A7832') would become random_ids = c('5d6y8', 'u537h', '0v65j', 'o4g4h', 'u537h', '0v65j')

Notice that in both the ids list and the new random_ids list, the third and sixth and second and fifth IDs match.

What is the best (i.e., 'most random') way of creating these new 'randomised' IDs? I scare quote randomised because I am not sure how random these could really be...

Thanks in advance!




Pulling a random value out of a table is returning a null value

I have a stored procedure that I've used to 'de-identify' client information when I want to use it in a test environment. I am replacing actual names and addresses with random values. I have database tables in a database called dict (for dictionary) for female names, male names, last names, and addresses.

Each of these has a field called f_row_id that is a sequential number from 1 to x, one for each record in the table.

We recently upgraded to mySQL 8 and the stored procedure quit working. I ended up with NULL for every field where I tried filling in a random value out of the other table. In trying to find what will now work, I'm unable to get the following query to work as I expect:

SELECT
    f_enroll_id,
    (SELECT f_name FROM dict.dummy_female_first_name fn WHERE fn.f_row_id = (FLOOR(RAND() * 850)  + 1) LIMIT 1)
FROM
    t_enroll

My data table (that I eventually want to have contain random names) is called t_enroll. There is an ID field in that (f_enroll_id) I want to get a list of each ID and a random first name for each record in that table.

There are 850 records in the table of random first names (dummy_female_first_name) (in my stored procedure this is a session variable that I compute at the start of the procedure).

When I first tried running this I got an error that my sub-query returned more than one value. I don't understand why it would do that since (FLOOR(RAND() * 850) + 1) should return a single integer. So I added the LIMIT 1. But when I run this, about half of the returned rows have NULL for the first name.

I have verified that all the rows in my first name table have a row ID, that the row ID is unique, and there not any gaps in the numbers.

What do you think is causing this?

Thanks in advance!




How to shuffle a list of lists in javascript [duplicate]

Let's say I have a list of lists in Javascript like so:

var list_of_list = [["N", "B"], ["E", "B"], ["Y", "R"], ["R", "R"], ["A", "B"], ["U", "R"]]

I'd like to randomize the first-level ordering of the lists without randomizing inside the lists. So, for example,

shuffle(list_of_lists) 
> [["E", "B"], ["R", "R"], ["Y", "R"], ["N", "B"], ["U", "R"], ["A", "B"]]

Is one possible random shuffle since it preserves the ordering of the nested lists while randomizing the top-level lists.

I've tried a number of different approaches, but can't seem to get shuffling to occur. For example, none of these standard approaches to shuffling work:

var list_of_list = [["N", "B"], ["E", "B"], ["Y", "R"], ["R", "R"], ["A", "B"], ["U", "R"]]
      function shuffle(a) {
                var j, x, i;
                for (i = a.length - 1; i > 0; i--) {
                    j = Math.floor(Math.random() * (i + 1));
                    x = a[i];
                    a[i] = a[j];
                    a[j] = x;
                }
                return a;
            }
      
        function shuffle_2(array) {
            var currentIndex = array.length, temporaryValue, randomIndex;

            // While there remain elements to shuffle...
            while (0 !== currentIndex) {

                // Pick a remaining element...
                randomIndex = Math.floor(Math.random() * currentIndex);
                currentIndex -= 1;

                // And swap it with the current element.
                temporaryValue = array[currentIndex];
                array[currentIndex] = array[randomIndex];
                array[randomIndex] = temporaryValue;
            }

            return array;
        }

     list_of_list2 = list_of_list.sort(func);  
     function func(a, b) {  
                return 0.5 - Math.random();
            } 
            
            
console.log(list_of_list2.join("|"));
console.log(shuffle(list_of_list).join("|"));
console.log(shuffle_2(list_of_list).join("|"));

What is the right way to do this?




Looping over a set of number generating commands in R

Below, I'm showing a block of code to generate some set of item scores in R. However, there seems to be a fair amount of unnecessary repetition to get to the final data.

I was wondering if there might be a more compact way of achieving the same data in R?

set.seed(8649)     
N      = 10        
latent = rnorm(N)  

##### generate latent responses to items
item1 = latent + rnorm(N, mean=0, sd=0.2)  
item2 = latent + rnorm(N, mean=0, sd=0.3)
item3 = latent + rnorm(N, mean=0, sd=0.5)
item4 = latent + rnorm(N, mean=0, sd=1.0)
item5 = latent + rnorm(N, mean=0, sd=1.2)  

##### convert latent responses to ordered categories
item1 = findInterval(item1, vec=c(-Inf,-2.5,-1, 1,2.5,Inf)) 
item2 = findInterval(item2, vec=c(-Inf,-2.5,-1, 1,2.5,Inf))
item3 = findInterval(item3, vec=c(-Inf,-3,  -2, 2,3,  Inf))  
item4 = findInterval(item4, vec=c(-Inf,-3,  -2, 2,3,  Inf))
item5 = findInterval(item5, vec=c(-Inf,-3.5,-3,-1,0.5,Inf))

data = cbind(item1, item2, item3, item4, item5)



randomly replacing percentage of values per group with NA in R dataframe

I have a dataframe with different groups (ID) of varying size. Within each group, I would like to randomly replace a specific percentage of values in the "value" column (let's say 30%) with NA's. Here is a simplified version of my data:

ID<-rep(c("X1","X2"),times=c(3,6)
value<-c(1,2,3,1,2,3,4,5,6)
data.frame(ID,value)
ID value
X1     1
X1     2
X1     3
X2     1
X2     2
X2     3
X2     4
X2     5
X2     6

Here is what I would like to have:

ID value
X1     1
X1     NA
X1     3
X2     1
X2     2
X2     NA
X2     4
X2     5
X2     NA

Any idea how I could do this? I have a preference for using tidyverse but if you have other options, that would also be appreciated!




This code is not working properly and it doesn't make any sense why it isn't to me. Does anyone have a guess what the problem might be? [closed]

This is the link to the hangman game in C++ I am making. It works perfectly fine on repl, but it doesn't work when I try to build and run it. It shoes letters have been guessed at the very start of the game, when which, obviously you haven't guessed any. The letters are also rather random having nothing to do with the game or anything, at least I think. Can someone else at least run this on their computer and see if it is just me? Thanks! It starts with:

WELCOME TO HANGMAN!!


----------------------------------------------------------------------------------------------------------

Here are the rules:
* you must enter one letter
* that letter cannot be a symbol
* you have ten guesses
* correct guesses won't count against you
* you cannot guess the same letter twice
* and finally, if you need to give up enter any numeral



You have 10 incorrect guesses left
The word so far is

_ _ _ _ _


You have guessed: A, B, I, J, K, Q, R, T,
What is your guess?

This is what is does give when first opened, however, I want it to show that you haven't guessed anything yet, because you haven't.

cout << "You have " << guesses << " incorrect guesses left" << endl;
    cout << "The word so far is\n\n";
    for (int i = 0; i < word.length(); i++)
    {
      if (i == word.length() - 1)
      {
        cout << guessedWord[i] << endl;
      }
      else
      {
        cout << guessedWord[i] << " ";
      }
    }
    cout << "\n\nYou have guessed: ";
    for (int i = 0; i < guessed.size(); ++i)
    {
      if (guessed[i])
      {
        cout << static_cast<char>(i + 'A') << ", ";
      }
    }
    cout << "\nWhat is your guess?" << endl;
    cin >> myGuess;
    istringstream myGuess2(myGuess);
    char guess = toupper(myGuess2.peek());
    if (isalpha(guess) == false)
    {
      if (isdigit(guess) == true)
      {
        break;
      }
      else
      {
        cout << "That is not a letter, please try again" << endl;
        continue;
      }
    }
    else if (guessed[guess - 'A'])
    {
      cout << "You have already guessed this." << endl;
      continue;
    }

This is what that part of it looks like, if none of the conditions by which you want to give up (if you enter a number) or if you do not enter an actual alphabetical character, then it goes on to take the ascii value of you guess, subtract the ascii value of 'A' to get the place of the letter in the array of bools, then it sets that letter's value to true. After it just checks if your guess is correct and everything, but that works fine for now.