mercredi 31 mai 2023

Generate Random Number of Jobs for Various HPC Workloads, Constrained by Resource Availability

Overview

I am trying to use Python to generate a randomized distribution of resources for various HPC workloads, constrained by the resources available on the cluster.

For example:

  • Type A = 4 cores, 8GB RAM
  • Type B = 16 cores, 32GB RAM
  • Type C = 32 cores, 128GB RAM

The cluster contains, say, 600 cores and 3000GB of RAM. Let's assume I want to have 50 concurrent users (or close to it).

Example

One feasible situation would be:

n_users = 50
n_A = 30 # 120 cores, 240GB RAM
n_B = 10 # 160 cores, 320GB RAM
n_C = 10 # 320 cores, 1280GB RAM

# 120 + 160 + 320 <= 600 cores
# 240 + 320 + 1280 <= 3000GB RAM

Questions

  1. How can I generate randomized distributions of resource allocation, per machine type (A,B,C) for n-users without violating available resources?

  2. How could I generate randomized distributions of resource allocation, per machine type, for random number of users but with fixed core-count? I.e. constraint is to use 500 cores.

Thoughts

After thinking about this for a bit, my initial thought is to use a constrained stochastic optimizer method to generate pareto-optimal solutions (non violating combinations of workloads) and using that as my random set. Unless someone has a better idea.




Re-roll next value in pseudo-random sequence without changing any other values

I would like a pseudo-random number generator which generates an effectively-infinite (i.e. very large period) sequence that can be traversed in both directions but also allows re-rolling the value under the cursor.

For example, a starting view of the state (with square brackets indicating the cursor position) might be:

... 1 7 3 [8] 4 1 6 ...

After stepping the generator forward twice, the sequence 8 4 is generated and the view is:

... 3 8 4 [1] 6 0 8 ...

Then, the application chooses to re-roll the cursor value from 1, and the generator produces 7, resulting in the view:

... 3 8 4 [7] 6 0 8 ...

From this point, even if the cursor is moved backward, the newly generated value of 7 will remain in place of the original 1. However, all other elements of the sequence will be unchanged:

... 7 3 8 [4] 7 6 0 ...

I considered using a reversible linear-feedback shift register (to allow stepping both left and right in the sequence) and writing to some set of bits in the center of the register to re-roll. However, to prevent re-rolling from affecting the rest of the sequence, only bits beyond the final tap can be re-rolled, and upon considering for a while, I realized it is probably not possible for a LFSR whose final tap is not all the way at the edge of the bit stream to be reversed.




mardi 30 mai 2023

N number of random numbers between -1 and 1 python

How to generate N number of float random numbers between -1 and +1 in python. It appears that random.choice () or random.uniform() is not working. Is there any other option lets say to produce 1000 random numbers between [-1,1]




I am trying to set an upper bounds for a random int generator independant of the maximum value set in the generator itself

The idea is that I can set the max value to 15 or 25 but if the die only has 20 sides it shouldn't roll higher than 20.

I am creating a die roller as a personal project. I created a Dice object that takes in the size of the die (how many sides) as well as the minimum and maximum values that can be rolled on the die. I was having a problem where the on a 20 sided die, if i set the maximum over 20 it would roll higher than 20. I fixed this issue by implementing a do while loop that runs until the random value produces is less than the size of the die.

This seems wildly inefficient to me as theoretically it could run for hours just getting incorrect values again and again. I am looking for a more efficient solution.

//Main.java
public class Main {

    public static void main(String[] args) {

        MinMaxDice d20 = new MinMaxDice(20, 10, 20);
        System.out.println("\nThere are " + d20.sides + " sides on this die.");
        System.out.println("The max is " + d20.max + " and the min is " + d20.min + ".");
        for (int i = 0; i < 20; i++) {
            System.out.println("It rolled a " + d20.rollDie() + ".");
        }
    }
}

//MinMaxDice.java
import java.util.concurrent.ThreadLocalRandom;

public class MinMaxDice extends Dice {
    int max;
    int min;

    MinMaxDice(int sides, int min, int max) {
        super(sides);
        this.max = max;
        this.min = min;
    }

    public int rollDie() {
        int result;
        do {
            result = this.min + ThreadLocalRandom.current().nextInt(this.max - (this.min - 1));
        } while (result > sides);
        return result;
    }
}



randomize the component values ​of the matrix in PYTHON

how to randomize the component values ​​of the matrix in PYTHON

I have a matrix (3,3) like this:[[1, 0, 1]
                                 [0, 1, 0]
                                 [1, 1, 0]]

How can i random the value of position(2,2) with the range is around its current value( for example the value of (2,2)=1 and i want it to random in range 0 and 2.




How do I call a method in an object without passing a variable that should already be in the object?

I am trying to create a dice rolling program to practice writing a program. I am creating a Dice object. I want to be able to create a die and state the number of sides when I create it. Example Dice d6 = new Dice(6). After that I want to be able to just print out the roll result without needing to specify the number of sides. in the call. Right now I have this... System.out.println(d6.rollDie(6));. I would like to be able to just do System.out.println(d6.rollDie); or System.out.println(d6.rollDie()); Having to specify the number of sides each time I call negates the point of having a sides variable in the object.

This is my current Java code.

//Main.java
public class Main {

    public static void main(String[] args) {
    
        Dice d6 = new Dice(6);
        System.out.println(d6.sides);
        System.out.println(d6.rollDie(6));
    }

}


//Dice.java
import java.util.Random;

public class Dice {
    int sides;
    int roll;

    Dice(int sides) {
        this.sides = sides;
    }


    public int rollDie(int sides) {
        this.sides = sides;
        Random random = new Random();
        int result = random.nextInt(sides + 1) + 1;
    
        return result;
    }

}



Snowflake returning 0 to N records when I expect exactly 1 record

Something that I'm not expecting is going on here. I have a table applications with 22 records with IDs 1 to 22.

I'd like to randomly select 1 record for sample data. But rather than selecting each row with equal probability, I'd like a more interesting (realistic??) distribution. I settled on the product of 2 uniform random variables. The choice of 25 below was to keep the tail from being too tiny, but I think that's not important to the issue.

My query isn't overly complicated. I added the CTE as a convenience so that anyone can run this as a self-contained query. But in my actual query I get this behavior with no CTE.

with applications as (
    select 1 + seq4() as ID, randstr(5, random()) as NAME
    from table(generator(rowcount => 22)) v
)
SELECT
    NAME
    , ID
FROM
    applications a
WHERE
    a.ID = LEAST(
        (
            SELECT 1 + round( 25 * uniform(0::float, 1::float, random()) * uniform(0::float, 1::float, random()) )
        )
        , 22
    )

It returns rows with a frequency that seems great for my purposes... but there's a catch. I do not understand why this query returns a variable number of records.

Returning 1 record appears to be the most common result. But returning 0 or 2 records happens regularly. Sometimes 3. I haven't seen 4 records... but maybe it's possible.

In the example below you can see that I got 2 records. How is it possible that ID is equal to both 4 and 7?

enter image description here

I'm quite interested in both:

  • Why do I get 0 to N records with this query?
  • What variation would produce exactly 1 record in all cases?



What modifications are needed to my VBA user defined function to allow a range or comma separated variables as input?

How to allow a UDF to accept as input, a range or comma separated variables?

Say I have this user defined function:

Function logsum(rngValues As Range) As Double With Application.WorksheetFunction Dim lSumofValues As Double Dim lAntilog As Double Dim rngLoop As Range.Select

    lSumofValues = 0
    lAntilog = 0

'For loop - add the antilogs of the values in the range
    For Each rngLoop In rngValues
        lAntilog = .Power(10, 0.1 * rngLoop.Value)
        lSumofValues = lSumofValues + lAntilog
    Next

'Perform calculation - logarithmic sum
    logsum = 10 * .Log10(lSumofValues)
End With

End Function

This returns the logarithmicn sum of a selected range of cells.

I require it to also function on selected cells, the same way as the standard "=SUM()" excel function works.

I think this will be simple for someone with the know-how to solve. Please let me know how this is done.




Why is my random feature appearing in the middle of my SHAP plot?

I have trained a model using LGBM, and used SHAP to interpret the top features. After inserting a random feature (random float) I see it appears in the middle of my SHAP plot. How do I interpret this? Does it mean all features appearing after the random are not important?




lundi 29 mai 2023

Why do the buttons on this JavaScript trivia game keep displaying an incorrect answer when the correct answer button was clicked?

I am building a trivia game using vanilla JavaScript and Bootstrap, the app gets questions from the https://opentdb.com API, displays the question and then four multiple choice answers on a separate button using Bootstrap. A simple random loop to generate numbers between 1 and 4 (without repeating) to an array is created to ensure the buttons are shuffled for the next question.

Ever since introducing the nextQuestion function to go to the next question, if I click on the correct answer, that button will not change to "Correct!" and a random "Incorrect" button will show. Before I was just refreshing the page every time to generate another question.

I have tried declaring the rand array globally and under the nextQuestion function to reset it and outputting these numbers to the console to check that are changing. I've noticed that more than often the last correct answer position for the previous question is where the "Incorrect" button is shown.

Please let me know if you need anymore information.

Here is the code:

Main.js

const api_url = 'https://opentdb.com/api.php?amount=1&category=9&type=multiple&encode=url3986';
let score = 0;
let buttonClicked = false; // Variable to track button click state
const delay = 2000; // Delay in milliseconds

// Get questions and answers from API
async function getQuestion() {
    try {
        // Fetch questions from the API
        const response = await fetch(api_url);
        const data = await response.json();
        const { results } = data;

        displayQuestion(results);

    } catch (error) {
        console.log(error);
    }
}

function displayQuestion(results) {
    const question = decodeURIComponent(results[0].question);
    const answer = decodeURIComponent(results[0].correct_answer);
    const incorrect1 = decodeURIComponent(results[0].incorrect_answers[0]);
    const incorrect2 = decodeURIComponent(results[0].incorrect_answers[1]);
    const incorrect3 = decodeURIComponent(results[0].incorrect_answers[2]);

    // Generate random number without duplicates to shuffle position of answer buttons
    randomArray = [];
    let n = [1, 2, 3, 4];
    i = n.length;
    j = 0;

    while (i--) {
        j = Math.floor(Math.random() * (i + 1));
        randomArray.push(n[j]);
        n.splice(j, 1);
    }

    // Display question and answers on separate buttons for user input
    document.getElementById('question').textContent = question;
    document.getElementById(`answer${randomArray[0]}`).textContent = answer;
    document.getElementById(`answer${randomArray[1]}`).textContent = incorrect1;
    document.getElementById(`answer${randomArray[2]}`).textContent = incorrect2;
    document.getElementById(`answer${randomArray[3]}`).textContent = incorrect3;

    // User input for button click
    document.getElementById(`answer${randomArray[0]}`).addEventListener("click", correctAnswer);
    document.getElementById(`answer${randomArray[1]}`).addEventListener("click", incorrectAnswer1);
    document.getElementById(`answer${randomArray[2]}`).addEventListener("click", incorrectAnswer2);
    document.getElementById(`answer${randomArray[3]}`).addEventListener("click", incorrectAnswer3);
}

function correctAnswer() {
    if (buttonClicked) return; // Prevent multiple clicks within the delay period
    buttonClicked = true; // Set button click state to true
    document.getElementById(`answer${randomArray[0]}`).innerHTML = "Correct!";
    document.getElementById(`answer${randomArray[0]}`).className = 'btn btn-success btn-sm';
    // Increment the score
    score++;
    // Update the score display
    updateScore();
    setTimeout(() => {
        nextQuestion();
        buttonClicked = false; // Reset button click state after the delay
      }, delay);
}

function incorrectAnswer1() {
    if (buttonClicked) return; // Prevent multiple clicks within the delay period
    buttonClicked = true; // Set button click state to true
    document.getElementById(`answer${randomArray[1]}`).innerHTML = "Incorrect!";
    document.getElementById(`answer${randomArray[1]}`).className = 'btn btn-danger btn-sm';
    setTimeout(() => {
        nextQuestion();
        buttonClicked = false; // Reset button click state after the delay
      }, delay);
}

function incorrectAnswer2() {
    if (buttonClicked) return; // Prevent multiple clicks within the delay period
    buttonClicked = true; // Set button click state to true
    document.getElementById(`answer${randomArray[2]}`).innerHTML = "Incorrect!";
    document.getElementById(`answer${randomArray[2]}`).className = 'btn btn-danger btn-sm';
    setTimeout(() => {
        nextQuestion();
        buttonClicked = false; // Reset button click state after the delay
      }, delay);
}

function incorrectAnswer3() {
    if (buttonClicked) return; // Prevent multiple clicks within the delay period
    buttonClicked = true; // Set button click state to true
    document.getElementById(`answer${randomArray[3]}`).innerHTML = "Incorrect!";
    document.getElementById(`answer${randomArray[3]}`).className = 'btn btn-danger btn-sm';
    setTimeout(() => {
        nextQuestion();
        buttonClicked = false; // Reset button click state after the delay
      }, delay);
}

// Function to update the score
function updateScore() {
    const scoreElement = document.getElementById('score');
    scoreElement.textContent = `Score: ${score}`;
}

function nextQuestion() {
    // Clear the previous question and answer buttons
    document.getElementById('question').textContent = '';

    // Clear answer buttons' styles and text content
    for (let i = 0; i < randomArray.length; i++) {
      const answerButton = document.getElementById(`answer${randomArray[i]}`);
      answerButton.classList.remove('btn-success', 'btn-danger');
      answerButton.classList.add('btn-primary');
      answerButton.textContent = '';
    }
    getQuestion();
  }

getQuestion();

game.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Trivia Game</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
    <link href="/css/style.css" rel="stylesheet">
</head>
<body>
    <div id="container">
    <div class="text-center font-weight-bold col-8 mx-auto">
        <span id="question"></span>
    </div>
    <div class="d-grid gap-2 col-4 mx-auto">
        <button type="button" class="btn btn-primary btn-sm p-1" id="answer1"></button>
        <button type="button" class="btn btn-primary btn-sm" id="answer2"></button>
        <button type="button" class="btn btn-primary btn-sm" id="answer3"></button>
        <button type="button" class="btn btn-primary btn-sm" id="answer4"></button>
        <div class="text-center" id="score">Score: 0</div>
    </div>
    </div>
    <script src="main.js"></script>
</body>
</html>



dimanche 28 mai 2023

How do you generate a list of strings with strange, bizzare, or funny capitalization? [duplicate]

When testing semi-case-insensitive languages, it is helpful to generate semi-randomly capitalized text.

How do we accept a text as input and output scrambled text (scrambled in terms of capitalization only, everything else can be fine).

inPUt Is EnGLiSH
input is english
iNPUt IS englisH
INpuT IS ENGlISH
input is English
INpUt IS EngLiSH
iNPuT iS enGlIsH
Input is English
INPUT IS ENGLISH

A semi-case insensitive language is a language L such that:
for any two x




With R, how do I get a random number from a varying vector that can be of length 1

I'm using sample(2:ncol(matrix),1) to get the number of a random collumn in my matrix, excluding column 1. The matrix increases in size as my loop iterates. It works as it should, except that when the number of columns is 2, instead of automatically returning 2 with a 100% probability, it sometimes returns 1. That's because when the length of the object from which to sample is 1, sample considers it to range from 1 to that number. How can I avoid this, or is there a better function for me to use? Thanks

I've tried sample(2:ncol(matrix),1), but when ncol(matrix)=2, it can return 1, which should not happen for my code.




VS Code showing 'random' module overriding, how to solve it?

Check This Problem Image I imported the random module in Python and tried running it. It is imported and it is running good as well, but VSCode is giving a yellow line warning and showing that it is overriding with the module in venv\Lib. It is asking me to change the name of random.py to something else, which I can't change because it will give me errors in other libraries like pandas, numpy, matplotlib, and OpenCV. How can I remove this unwanted warning?

This is the error I'm getting:

"c:\Users\Syed M Tayyab\Desktop\VS Code ML\venv\Lib\random.py" is overriding the stdlib module "random"PylancereportShadowedImports

I tried changing random.py To something else but as I mentioned earlier that changing randon.py to something else may solve this problem but will generate more problems in other libraries as random.py is also imported in them.




samedi 27 mai 2023

NodeJS: How do I generate a random hex key for password reset?

I am developing a express js end point and I need to send some random hex-decimal code

I am trying to generate a random hex key for a reset password process in nodejs. Can anyone help? Is there any library? Or shell I use some standard code
Shell I also sign the code like with jwt?




PHP 8.1 upstream timed out (110: Unknown error)

I had already a an issue when someone reached the basket on last 2023/03/29, it was a different PHP error which crashed the server. I had to manually restart the php service. Not enough memory:

PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480 bytes) in /var/www/mywebsite/prod/basket/basket_global.inc.php on line 956

So I added some memory to PHP and since yesterday I had no server crash (Nginx / PHP 8.1 / MySQL)!

memory_limit = 256M

Yesterday I had another crash of the server for which I just had to manually restart the php service:

systemctl restart php8.1-fpm.service

And once again, it happened just after someone went to the basket:

access.log:

185.230.yyyy.xxx - - [27/May/2023:02:15:09 +0000] "GET /us/basket HTTP/1.1" 200 10466 "-" "Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.133 Safari/534.16"

error.log

2023/05/27 02:15:09 [error] 3221563#3221563: *18311176 upstream timed out (110: Unknown error) while reading response header from upstream, client: 185.230.yyyy.xxxx, server: mywebsite.com, request: "GET /us/basket/ HTTP/1.1", upstream: "fastcgi://unix:/run/php/php8.1-fpm.sock", host: "mywebsite.com"

And then only upstream timed out (110: Unknown error) errors on the log file!

It happens randomly and not often, so I think it's because of this function from the basket part with an infinite while loop to generate unique working code:

function get_newMerchantReference() {
    global $config, $dataBase;

    while(1) {
        $merchantReference = mt_rand(100, 999).'-'.mt_rand(100, 999).'-'.mt_rand(100, 999);

        $sql = $dataBase->prepare('SELECT count(*) AS num
                                   FROM oo__basket_infos_hext
                                   WHERE merchant_reference LIKE :reference');
        $sql->execute(array('reference'  => $merchantReference));
        $countUniqueId = $sql->fetch();
        $sql->closeCursor();
        $sql = $dataBase->prepare('SELECT count(*) AS num
                                   FROM oo__order_infos_hext
                                   WHERE merchant_reference LIKE :reference');
        $sql->execute(array('reference'  => $merchantReference));
        $countUniqueId2 = $sql->fetch();
        $sql->closeCursor();
        if($countUniqueId['num'] == 0 && $countUniqueId2['num'] == 0) { break; }
    }
    return $merchantReference;
}

Can this while(1) loop go wrong in a random way and cause the PHP service to crash?

How to modify it to generate random number like 213-126-323 which have not been already used and is stored in oo__basket_infos_hext and oo__order_infos_hext?




vendredi 26 mai 2023

Generate initial segments of random n-dimensional infinite array in numpy

Consider the following function:

def random_matrix(rows, cols):
    rng = np.random.default_rng(0)
    return rng.random((rows, cols))

How can I make a function f that makes random matrices like random_matrix but has the property that, for all r1, r2, c1, c2, f(r1, c1)[:min(r1, r2), :min(c1, c2)] is equal to f(r2, c2)[:min(r1, r2), :min(c1, c2)]? (This is the two-dimensional case of the slightly more general question in the title. The 1-dimensional case is trivial since it is numpy's normal behavior.)




Generate Birth date based on Hire Date and grade PYTHON

In my data I have hire dates of employees and their paygrades. Paygrades are divided in categories: ( 1 = Intern , 2 : Junior , 3 : Senior ...)

Based on this data , I'm trying to generate approximate Birth Dates for these employees. Taking in account that an employee would be at least 23 years old.

This is the function I developed :

def generate_birth_date(paygrade, hire_date_str):
    if isinstance(hire_date_str, float) and math.isnan(hire_date_str):
        # Handle the case when hire_date_str is NaN
        return None
    if isinstance(hire_date_str, float):
        hire_date_str = str(int(hire_date_str))

    hire_date = datetime.strptime(hire_date_str, "%y-%m-%d").date()
    if paygrade == 'Intern':
        birth_year = random.randint(1998, 2000)
    elif paygrade == 'Junior':
        birth_year = random.randint(1996, 1998)
    elif paygrade == 'Senior':
        birth_year = random.randint(1994, 1996)
    elif paygrade == 'Manager':
        birth_year = random.randint(1992, 1994)
    elif paygrade == 'Senior Manager':
        birth_year = random.randint(1990, 1992)
    elif paygrade == 'Director':
        birth_year = random.randint(1988, 1990)
    else:
        birth_year = random.randint(1982, 1984)

    birth_month = random.randint(1, 12)
    birth_day = random.randint(1, 28)  # Assuming maximum of 28 days in a month

    birth_date = datetime(birth_year, birth_month, birth_day)

    return birth_date.date()

And this is how i'm calling it:

# Apply the function to the PAY_GRADE and HIRE_DATE columns to generate birth dates
df['BIRTH_DATE'] = df.apply(lambda row: generate_birth_date(row['PAY_GRADE'], row['HIRE_DATE']), axis=1)

The results are not 100% accurate, because II feel like sometimes he takes in account only the paygrade and sometimes the hire date only. For instance , an employee may be hired in 2006 with paygrade 2 , meaning he's a junior, meaning he was at least 23 years old by that age. Which means he would've at least almost 40 years old by now. How can I correct my function to retrieve ideal results ?




jeudi 25 mai 2023

How can I generate random strings in Rust that match a given regex pattern?

How to write a program in Rust that generates a random string that satisfies a given regular expression?

I expect the program to work for at least the following regular expressions.

"[^+*?]+"
"[^xu]"
"[^\\\\']"
"u{[0-9a-fA-F]+}"
".*"
"\\$[a-zA-Z_]\\w*"
"\\s"



show MainActivity console readout from android studio onto app screen

I have a function that works in android studio and spits out correct results to the "MainActivityKt" console window in the bottom of android studio, However I need the results to show on the main activity page on screen so the user can see the list. ive tried setting the Text(text = "$RandomQuest"), however when i do that i get the error the "unresolved reference - create local variable". When following the suggested fixes and making new variables i end with my 'random' function not working in the: val randomQuestGiver = questGiver[random.nextInt(questGiver.size)] Value. `


`package com.example.trainingapplication
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.sp
import com.example.trainingapplication.ui.theme.TrainingApplicationTheme
import java.util.Random

class MainActivity : ComponentActivity() {



override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
        TrainingApplicationTheme {
            Column(
                modifier = Modifier.fillMaxSize(),
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally
            ){
                Text(
                    text = "Quest Giver: ",
                    fontSize = 20.sp
                )
                Text(
                    text = "Quest Objective: ",
                    fontSize = 20.sp
                )
                Text(
                    text = "Quest Location: ",
                    fontSize = 20.sp
                )
                Text(
                    text = "Quest Rewards: ",
                    fontSize = 20.sp
                )
                Text(
                    text = "Potential Complications: ",
                    fontSize = 20.sp
                )
                Text(
                    text = "NPCs Involved: ",
                    fontSize = 20.sp
                )
                Text(
                    text = "Quest Hooks: ",
                    fontSize = 20.sp
                )
                Text(
                    text = "Timeline to Complete: ",
                    fontSize = 20.sp
                )
                Text(
                    text = "Consequences: ",
                    fontSize = 20.sp
                )
                Button(onClick = {
                    generateRandomQuest()

                }) {
                    Text(text = "Generate A Quest!")

                }
            }
            }

        }
    }
}


fun generateRandomQuest() {


/// Values containing list

val questGiver = arrayOf("Wandering Knight", "Village Elder")
val questObjective = arrayOf("Rescue a kidnapped individual.", "Recover a stolen item.")
val questLocation = arrayOf("Somewhere amidst an azure ocean.", "second option")
val questRewards = arrayOf("A hefty bag of gold coins", "A magical weapon")
val questHooks = arrayOf("A mysterious letter arrives", "The party stumbles")
val consequences = arrayOf("A cherished NPC dies.", "A dangerous creature is unleashed.")

/// Values that populate the list with random results
val random = Random()
val randomQuestGiver = questGiver[random.nextInt(questGiver.size)]
val randomquestObjective = questObjective[random.nextInt(questObjective.size)]
val randomquestLocation = questLocation[random.nextInt(questLocation.size)]
val randomquestRewards = questRewards[random.nextInt(questRewards.size)]
val randomNPCsInvolved = npcsInvolved[random.nextInt(npcsInvolved.size)]
val randomquestHooks = questHooks[random.nextInt(questHooks.size)]
val randomtimeline = timeline[random.nextInt(timeline.size)]
val randomconsequences = consequences[random.nextInt(consequences.size)]

/// The below lines display in the android studio console under "MainActivityKt"
/// However I need them to be used in/with the corresponding text on screen
println("hello World!")

println("Quest Giver: $randomQuestGiver")
println("Quest Objective: $randomquestObjective")
println("Quest Location: $randomquestLocation")
println("Quest Rewards: $randomquestRewards")

println("NPCs Involved: $randomNPCsInvolved")
println("Quest Hooks: $randomquestHooks")
println("Timeline: $randomtimeline")
println("Consequences: $randomconsequences.")

/// Next step is to print above results OUTSIDE this function, and onto a text page

}`






Values dissapear after use button in streamlit

I am trying to write an application to play Wheel of Fortune. Once I draw a password and want to e.g. draw points the password disappears. I know that this is caused by refreshing the application after pressing another button, but I do not know how to stop it.

This is how my code looks like.

import streamlit as st
import random

# Create a list containing the letters in a word
def lista_slowo(slowo):
    slowo = slowo.lower()
    lista_slowo = []
    for litera in slowo:
        lista_slowo.append(litera)
    return lista_slowo

# Create an empty list to display
def pusta_lista_na_tablicy(slowo):
    pusta_lista_na_tablicy = []
    for litera in slowo:
        pusta_lista_na_tablicy.append("_")
    return pusta_lista_na_tablicy

# Converting a list to a string
def zamien_na_stringa(lista_na_tablicy):
    napis = ""
    for x in lista_na_tablicy:
        napis = napis + x + " "
    return napis

st.sidebar.title("Koło fortuny")
st.sidebar.text("Witamy w grze Koło Fortuny.")
st.sidebar.text("Wybierz liczbę graczy.\nNastępnie kliknij przycisk 'Losuj kategorię'.")

slownik_kategorii = {"Zwierzęta":["Krowa","Kura","Koń"],
             "Owoce":["Mandarynka","Pomarańcza","Truskawka"],
             "Warzywa":["Ogórek","Marchewka","Sałata"],
             "Ubrania":["Spodnie","Koszulka","Koszula"],
            "Pojazdy":["Samochód","Motocykl","Samolot"]}

slownik_wartosci = [100,200,300,400,500,600,700,800,900,1000,1500,0]



ilosc_graczy = st.sidebar.selectbox("Wybierz ilość graczy",[1,2])

losuj = st.sidebar.button("Losuj kategorię")

kategoria = st.subheader("")

if losuj:
    kategoria = random.choice(list(slownik_kategorii))
    st.subheader(f"Kategoria: {kategoria}")
    slowo = random.choice(slownik_kategorii[kategoria])
    lista_na_tablicy = pusta_lista_na_tablicy(slowo)
    napis = zamien_na_stringa(lista_na_tablicy)
    st.title(napis)

    st.text("Słowo do odgadnięcia " + slowo)


odgaduj = st.sidebar.button("Odgadnij hasło")
krec = st.sidebar.button("Kręć kołem")
podaj_litere = st.sidebar.button("Podaje spółgłoskę")

if krec:
    wartosc = random.choice(slownik_wartosci)
    st.sidebar.text("Wartość spółgłoski: " + str(wartosc) + " zł")

if podaj_litere:
    podana_litera = ""
    podana_litera = st.sidebar.text_input("Wpisz spółgłoskę")
    st.sidebar.text(podana_litera)

I tried to replace the password generation button with a radio, but then every time you click another button the password draw from scratch




mercredi 24 mai 2023

Not able to create a random number [duplicate]

I need to create a random number for a game, but because I am just learning how to code I juts used examples I found on the Internet. While that was more or less always the same code, implementing it brought me 3 errors in 2 lines of code and I don't understand why.

The code I used:

  Random rnd = new Random();
  int num = rnd.Next(1, 11);

I expected it to give me a number between 1 and 10 but instead I get the errors:

Cannot declare a variable of static type 'Random'; Cannot create an instance of the static class 'Random'and 'Random' does not contain a definition for 'Next' and no accessible extension method 'Next'accepting a first argument of type 'Random' could be found (are you missing a using directive or an assembly reference?)

I'm not sure what I did wrong and I also don't know what I'm supposed to do to fix it. it would be really nice if somebody could help me




mardi 23 mai 2023

Error "attemped to compare number to string" lua, starter and probably easy to answer

What is wrong with my code? this is a really easy fix i bet but i am pretty new to lua so I cannot figure it out. The code is a random number generator that you are supposed to guess the number (its obviously not done) but it says "lua: main.lua:8: attempt to compare string with number" here is the code

local number2 = math.random(1,100)
local hi=2
repeat
print("pick a number, 1-100")
local number = io.read ()
if number == number2 then print("you got it!! congrats")
  end
if number <= number2 then print("too high!")
  end
if number >= number2 then print ("too low!")
  end
until (hi)==2

please help, thanks!




Shuffle with a constraint

I have a problem analog to:

We have 20 balls numbered from 1 to 20. The balls numbered from 1 to 5 are yellow, from 6 to 10 green, from 10 to 15 red and from 16 to 20 blue. Find a method to randomly shuffle the balls while respecting the constraint: "2 successive balls cannot have the same color".

Example:

input/output example

I have considered two methods that I am not satisfied with, and I am looking for a better one

  1. draw a ball at random, then draw a ball at random among all the others having a different color from the previous one, etc.

Problem: we can fall in cases where it is impossible to finish the drawing, if there are only remaining balls of the same color for example.

  1. divide the balls into 4 sets of 5 balls (1 per color), form 5 other sets of 4 balls by randomly drawing a ball of each color. Reassemble these 5 sets in order to respect the criterion (the first balls of the last set are permuted until the criterion is respected).

Problem some combinations are never drawn, for example red, yellow, red, yellow ... green, blue, green, blue.




lundi 22 mai 2023

How to configure Die harder test suite in Windows

I am trying to configure/run Die harder test suite for testing Random Number generator. I have downloaded the Die hard folder. This folder comprises of several .exe files. I am unable to understand which file should I execute in terminal(cygwin64) for running the test suite. Below is the snap of folder with .exe files. Any help is highly appreciated! enter image description here

I tried running individual .exe file but each one just gives its own output as mentioned in the document. However I am not able to run the test suite as a whole .




File Storage for Web Applications during production

Which form of file system SQL, NoSQL, the cloud, or a static/subdirectory inside the application should I use for my web application?

sql: I've tried to save the images as blobs, but I can't get them out and display them on the flask application.

Cloud storage: I successfully built an S3 bucket, placed a file there, and am now able to view website images. I attempted to deploy the website on ec2, with the aws id and secret key properly specified in the configure file. My s3 bucket is public, however my nginx server reports a "502 bad gateway" (in localhost it works fine).

File system: Storing an application's images within a folder and its metadata in a mysql database. This method functions without any problems, but the question is whether it will result in more photographs being kept in the folder as the application ages, say, if I want to keep the images for a longer period of time.

  1. Does it cause a server stess?
  2. Is this way of saving the images effectively?
  3. Does it slow down the application process over time as no of images increases?
  4. What additional issues can I encounter as a result of this process?



dimanche 21 mai 2023

Appwrite Random list of Documents

I am currently working on Appwrite, and as part of my work, I am facing an issue. I would like to retrieve documents randomly. Is it possible to achieve that? Thank you.

I was trying through the use of limit and offset. but not work




samedi 20 mai 2023

Getting an error when creating a create a Completely Randomized Design (CRD) layout in R

I am trying to create a Completely Randomized Design (CRD) layout in R using the agricolae package. The design involves 8 treatments, each replicated 6 times. However, I encountered an error while executing the code.

Here is my code:

# Install and load the agricolae package
install.packages("agricolae")
library(agricolae)

# Define treatments and replicates
treatments <- c("A", "B", "C", "D", "E", "F", "G", "H")
replicates <- 1:6

# Create the CRD layout
layout <- design.crd(treatments, replicates)

# Print the layout
print(layout)

# Plot the layout
plot(layout)

The error I received is: Error in data. Frame(trt, r) : arguments imply differing number of rows: 8, 6. It seems that the number of rows for treatments and replicates is not matching.

As a workaround, I was able to create the layout using the expand.grid() function, like this:

# Define treatments and replicates
treatments <- c("A", "B", "C", "D", "E", "F", "G", "H")
replicates <- 1:6

# Generate the design matrix
design <- expand.grid(Treatment = treatments, Replicate = replicates)

However, I'm unsure how to plot the expand.grid object to produce a plot like the following (it's just an example)

enter image description here

Could someone please help me resolve the issue with agricolae package OR guide me on how to plot the layout using the expand.grid object?




generate a random vector uniformly distributed

I need to construct diagonal matrix with conditional number is 997.49.45

so I need to generate a random vector uniformly distributed in (0,1) with max_value / min value approximate 997.4945.

I really confused these day. Is there any methods for problem?




vendredi 19 mai 2023

Calling random number generator ran2() available in Numerical recipes in c

I am using ran2() function in c programming codes. ran2() is known as more truly random number generator. I found that ran2() is also generates numbers in same sequence. Why is it so?

ran2 takes a long type pointer variable.

The code of ran2() is available in Numerical recipes.

Here I'm writing how I called the function:

float temp;
long *seed,seed1;
seed=&seed1;
temp=ran2(seed);

After calling this function multiple times and running multiple times I see that numbers of same sequence are generated every time. Correct me where I am doing the mistake and what modifications needed to get the truly random sequence every time.




Create a randomized function with restriction on communication size

I need to create a randomized function between two participants, 1 and 2. The two participants have both n bit sized strings, and they want to determine whatever they have the same strings. 1 and 2 can communicate using only log(n) bits. The probability of error should be at most 1/3, but the function can be run multiple time and take a "majority vote" for which conclusion appeared in most of the runs, in order to decrease the error probability.

I have tried multiple ideas - for example, using a hash function where the "random" part in the algorithm is that 1 chose a random hash method each run and communicate it to 2 using the log(n) bits. But it's either that I can't prove that the probability of error is at most 1/3 or that I need to use more then log(n) bits, do you have a general idea how to achieve it ?




Why ran2() from numerical recipes in c gives numbers in same sequence? [closed]

I am using ran2() function in c programming codes.ran2() is known as more truly random number generator.I found that ran2() is also generates numbers in same sequence.why is it so ?

How to feed time as seed in ran2()?

Ran2 takes a long type pointer variable.

The code of ran2() is available in Numerical recipes.




jeudi 18 mai 2023

How to print stuff on the same row

im writing a pyhton program that basically calculates the probability of the sum of a two dices. I'm using a print function to make a table, but apparently i can't print multiple stuff on the same row.

to get the sum of the dices i used the random libary, it looks like this:

question = int(input("How many times do you want to roll the dices: "))

def sum():
    for x in range(question):
       dice1 = random.randint(1,6)
       dice2 = random.randint(1,6)
       sum = dice1 + dice2
       print(sum)

def attempts():
      for attempts in rang(question):
             print(attempts)

Output:....

attempts        sum of the dices         probability
-----------------------------------------------------
    1
    2
    3 
                           4
                           9
                           3
                                                      100%
  • how do i make everything print in one column? thanks in advance for your help :/



picture boxes random location and collision like on vb

I'm making a game for my class and it's like a little maze. One on the forms asks for it to have random PictureBoxes around the screen and if you touch them then you die and the program ends. With the random component I used,

Dim random As New Random
Dim newLeft As Integer = Panel.Width * Rnd()
Dim newTop As Integer = Panel.Height * Rnd()

PictureBox2.Left = newLeft
PictureBox2.Top = newTop

PictureBox4.Left = newLeft
PictureBox4.Top = newTop

and the Panel.Height and Panel.Width are underlined with red. When I click on them they say

"BC30469 Reference to a non-shared member requires an object reference"

I need some help with the PictureBoxes touching first then them having random locations but within the form.

I have tried many different codes for both but nothing has worked and the panel code for BC30469 still says the same thing.




Good example for Mersenne Twister and naive parallel random number generation in R failing

It is often discouraged to generate random numbers in parallel calculation in R by simply setting sequential seeds for each parallel process like

library(parallel)
cl <- makeCluster(4)
y <- parLapply(cl, 1:10, function(i) {
  set.seed(i)
  runif(n = 5)
})
stopCluster(cl)

(code from https://www.jottr.org/2020/09/22/push-for-statistical-sound-rng/).

I could not find any example that would reproducibly demonstrate a problem with this 'naive' approach.

How can I demonstrate the potential issues with this naive approach?




mercredi 17 mai 2023

How to randomly select x number of values from a pool of values in python

For an experiment I am doing, I need to present stimuli (images) on the screen. For the same, I have divided the screen into 6*5 grid which gave me 30 coordinates. I have divided these coordinates into 4 quadrants and a set of points also aligns with the Y-axis. These coordinates based on the different quadrants are:

Q1 = [(94,-328) ,(320,-328), (548,-328), (94,-174), (320,-174), (548,-174)]

Q2 = [(134,288), (360,288), (588,288), (134,134), (360,134), (588,134)]

Q3 = [(-548,134), (-320,134), (-94,134), (-548,288), (-320,288), (-94,288)]

Q4 = [(-588,-328), (-360,-328), (-134,-328), (-588,-174), (-360,-174), (-134,-174)]

Y_axis = [(-568,0), (-340,0), (-114,0), (114,0), (340,0), (568,0)]

In the experiment, in some trials, I have to only present 4 images at 4 locations whereas in another trial I have to present 8 images and 16 images. When presenting images at 4 locations, I need to select one coordinate from each quadrant so that the images are spread across the screen and there is no bias in terms of location on the screen. I will call these 4,8 and 16 set sizes. Under each set size, there are 48 trials.

I need a code that can choose these coordinates randomly from the 30 coordinate values I already have; while ensuring that the coordinates selected by the program are randomly distributed across all 4 quadrants (or Y-axis) of the screen. So, then the code should be in such a way that there are 48 randomly selected choices with 4 coordinates, a selection of 8 coordinates (48 times), and similarly for set size 16.




can you help me correct the program which generates random dice rolls

def reject():
  print("get out!")
  quit()
import random
print("chooses random dice rolls")
maximumval=int(input("how many dice rolls do you want?"))
if maximumval<0:
   reject()
else:
    counter=1
    while counter<=maximumval:
        counter=str(counter)
        mydict={
      
         }
         
         val=random.randint(1,7)
         val=str(val)
         mydict.update({counter:val})
         val=int(val)
         counter=int(counter)
        counter+=1
    print(mydict)

it gives parseError on line 17

I was not able to solve it please help me it says parseError. Please help me fix my code please!




distribute value randomly to elements of a list

I want to randomize the elements of rand_skill = [] in a way, that the sum of all elements is always equal to the variable skill_points. Further, I'd like to be able to influence the distribution, by using tag_list = [], to make specific elements of rand_list more likely to be bigger.

def roll_talents(skill_points, tag_list):
    talents = []
    # FIGHT
    talents[0] = 0 + get_attribute_mod(attributes[3]) + get_attribute_mod(attributes[4]) + rand_skill [0]
    talents[1] = 0 + get_attribute_mod(attributes[4]) + rand_skill [1]
    talents[2] = 0 + get_attribute_mod(attributes[3]) + rand_skill [2]
    talents[3] = 0 + get_attribute_mod(attributes[0]) + rand_skill [3]
    talents[4] = 0 + get_attribute_mod(attributes[5]) + rand_skill [4]
    talents[5] = 0 + rand_skill [5]
    # COMMUNIKATION
    talents[6] = 0 + get_attribute_mod(attributes[2]) + rand_skill [6]
    talents[7] = 0 + get_attribute_mod(attributes[3]) + rand_skill [7]
    talents[8] = 0 + get_attribute_mod(attributes[6]) + rand_skill [8]
    talents[9] = 0 + get_attribute_mod(attributes[1]) + rand_skill [9]
    # [...]
    return talents

I tried to use a for loop, that adds 1 to a random element of rand_skill, until the added value equaled skill_points, but that seems very inefficient and crude.




Random selection Daml

Does anyone know how to simulate a random selection in Daml? My understanding is that I cannot make non-deterministic choices in Daml (I should call an external Oracle and ask for an index), but for testing purposes I should be able to simulate a random selection within the software.

Is that correct? Could someone please help? I cannot find any function such as "choose" "shuffle" or any other related function.

Could someone point me in the right direction please?

Any help would be very much appreciated!!!




mardi 16 mai 2023

My Python code is running in an unintended fashion

I took 10 of my codes in one line and wrote a code that outputs the next 2 lines after the 2 lines from the 0th line of the list are output. But it works like this:

Before mergeSort of L (size: 50): 12 22

6

29 30 35

3 4 48 19 49

21 32 20 42 41 14 28 2 1 5 8 36 26 33 16 23 24 37 25 18 9 44 34 39 38 15 45 27 47 43 0 40 7 13 10 46 11 31 17

what shoud i do? i can't find problem in my level.

i tried Initialization of line_num variable, rewrite a code by recommended GPT, and I checked by printing all the variables and lists.

here is full code here

import random
import random, time

def genRandList(size_L):
    L = random.sample(range(size_L), size_L)
    print(L)

    return L
    

def printListSample(L, num_elements_per_Line, num_sample_Lines):
    line_num  = 0 
    for i in range(len(L)):
        print(L[i], end=" ")
        if i != 0: 
            if (num_elements_per_Line % i) == 0:
                print("\n")
                line_num  += 1
        
    if line_num == num_sample_Lines:
                print("..............................")

                for a in range(len(L)):
                    print(L[-(num_elements_per_Line * num_sample_Lines) + a] , end=" ")


    

def mergeSort(merge_list):
    
    return merge_list

num_sample_Lines = 2
num_elements_per_Line = 10
size_L = 50
L = genRandList(size_L)
print("\nBefore mergeSort of L (size: {}):".format(size_L))
printListSample(L, num_elements_per_Line, num_sample_Lines)
t1 = time.time()
L = mergeSort(L)
t2 = time.time()



Generate n distinct random numbers in rust

I am trying to test a program which checks for correct use of brackets. To do this I want to generate Long strings of numbers with correct use of brackets (to test incorrect uses I can easily just swap around individual characters or groups of characters)

I can easily generate a vector of non-bracket characters. However, To place brackets correctly I need n unique indices. I do not know of a way to efficiently generate random indices (a list of unique random numbers in a range) so I would like either a way to do that or a way of converting random numbers into unique indices.

The two best approaches I can think of for this are:

  1. generate a vector of all indices 0-N , shuffle it and then take the first n
  2. generate a random number, test if it is in a hashset, if isn't add it and if it is regenerate until it isn't. Repeat until the hashset has n members then convert it to a vector

The first approach is efficient for N = n + $\epsilon$ but very inefficient for N >> n while the second approach is very inefficient for N = n + $\epsilon$ but efficient for N >> n.

Note:

  1. n is the number of brackets N is the number of characters
  2. for those unfamiliar with the notation $\epsilon$ is some small positive number



How to re-order and randomize DIVs using JavaScript

Long time reader, first time poster.

I was hoping someone might be able to help with this problem, which should be quite simple but unfortunately has me stumped. I'm trying to have a number of DIVs show up on page load but appear in a random order each time – but not entirely random as I'd like them to abide by some rules.

There are two different types of DIVs:

  1. Cards x5 (C)
  2. Image x4 (I)

The rules should be as follows:

  1. The first DIV must always be a C type
  2. Remaining DIVs should alternate between I and C (e.g. C, I, C, I, C, I, C, I, C)
  3. All DIVs should be randomly selected from their respective type/array

I've tried an array shuffle using jquery from the solution to another problem (below), but that just puts the DIVs in a random order, not taking into account rules 1 and 2.

var $cont = $('#content'),
  itemsArr = $cont.children().get();

$cont.append(shuffle(itemsArr))

function shuffle(a) {
    var j, x, i;
    for (i = a.length; i; i--) {
        j = Math.floor(Math.random() * i);
        x = a[i - 1];
        a[i - 1] = a[j];
        a[j] = x;
    }
    return a;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row" id="content">
  <div class="col-sm-12 col-md-6 col-lg-4" id="card1">Card #1</div>
  <div class="col-sm-12 col-md-6 col-lg-4" id="card2">Card #2</div>
  <div class="col-sm-12 col-md-6 col-lg-4" id="card3">Card #3</div>
  <div class="col-sm-12 col-md-6 col-lg-4" id="card4">Card #4</div>
  <div class="col-sm-12 col-md-6 col-lg-4" id="card5">Card #5</div>
  <div class="col-sm-12 col-md-6 col-lg-4" id="image1">Image #1</div>
  <div class="col-sm-12 col-md-6 col-lg-4" id="image2">Image #2</div>
  <div class="col-sm-12 col-md-6 col-lg-4" id="image3">Image #3</div>
  <div class="col-sm-12 col-md-6 col-lg-4" id="image4">Image #4</div>
</div>

Would be eternally grateful for any suggestions or help to point me in the right direction. Thanks in advance!




Using "Fluid Select Output" block by condition in anylogic software

How can we randomly select a path for fluids each time in AniLogic software? For instance, in 50% of cases, the fluid passes through path 1 and in the remaining 50%, it passes through path 2.

How can I fix the issue where only one output is always selected when using the randomTrue(0.5) function in the condition of "fluid select output" block? I have used this function to expect the desired output to be in 50% of cases on path 1 (output 1) and 50% on path 2 (output 2), but it seems that only one output is always selected.




lundi 15 mai 2023

How to check the same function with random returns different values each time using Pytest?

I have a function that should return a random different value every run.

Let's say

def foo_random():
    return np.random.randint(0, 1000)

I want to test that out of 10 runs, this function returned at least 2 different values using Pytest.

Is something similar supported?




Spring Boot app randomizer stops before it runs through the entire array

I have a simple quiz app in Spring Boot, that should show random questions (20 questions in total.) But the app instead stops at a random number of questions, sometimes 4/20, sometimes 15/20, etc. Not sure where the mistake is. Here's my code:

public class Quiz implements ActionListener {

List<Integer> questionIndexes = new ArrayList<>();
String[] questions = {
        // 20 different questions
};
String[][] options = {
        // Four options per question
};
char[] answers =  {
        // Answers
};

char answer;
int index;
int correctGuesses = 0;
int totalQuestions = questions.length;
int result;
int seconds = 10;

Timer timer = new Timer(1000, e -> {
    seconds--;
    secondsLeft.setText(String.valueOf(seconds));
    if (seconds <= 0) {
        displayAnswer();
    }
});

public Quiz() {

    for (int i = 0; i < totalQuestions; i++) {
        questionIndexes.add(i);
    }
    Random random = new Random();
    index = random.nextInt(totalQuestions);
    answer = answers[index];

    jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // and the rest of the code for UI

    nextQuestion();
}

public void nextQuestion() {
    if (index >= totalQuestions) {
        results();
    } else {
        index++;
        textField.setText("Question " + (index + 1));
        textArea.setText(questions[index]);
        answerLabelA.setText(options[index][0]);
        answerLabelB.setText(options[index][1]);
        answerLabelC.setText(options[index][2]);
        answerLabelD.setText(options[index][3]);
        timer.start();
    }
}

@Override
public void actionPerformed(ActionEvent e) {
    buttonA.setEnabled(false);
    buttonB.setEnabled(false);
    buttonC.setEnabled(false);
    buttonD.setEnabled(false);

    if(e.getSource() == buttonA) {
        answer = 'A';
        if(answer == answers[index]) {
            correctGuesses++;
        }
    }
    if(e.getSource() == buttonB) {
        answer = 'B';
        if(answer == answers[index]) {
            correctGuesses++;
        }
    }
    if(e.getSource() == buttonC) {
        answer = 'C';
        if(answer == answers[index]) {
            correctGuesses++;
        }
    }
    if(e.getSource() == buttonD) {
        answer = 'D';
        if(answer == answers[index]) {
            correctGuesses++;
        }
    }
    displayAnswer();
}

public void displayAnswer() {

    timer.stop();

    buttonA.setEnabled(false);
    buttonB.setEnabled(false);
    buttonC.setEnabled(false);
    buttonD.setEnabled(false);

    if(answers[index] != 'A') {
        answerLabelA.setForeground(new Color(255,0,0));
    }
    if(answers[index] != 'B') {
        answerLabelB.setForeground(new Color(255,0,0));
    }
    if(answers[index] != 'C') {
        answerLabelC.setForeground(new Color(255,0,0));
    }
    if(answers[index] != 'D') {
        answerLabelD.setForeground(new Color(255,0,0));
    }

    Timer pause = new Timer(2000, e -> {
        answerLabelA.setForeground(new Color(210,210,210));
        answerLabelB.setForeground(new Color(210,210,210));
        answerLabelC.setForeground(new Color(210,210,210));
        answerLabelD.setForeground(new Color(210,210,210));

        answer = ' ';
        seconds = 10;
        secondsLeft.setText(String.valueOf(seconds));
        buttonA.setEnabled(true);
        buttonB.setEnabled(true);
        buttonC.setEnabled(true);
        buttonD.setEnabled(true);
        questionIndexes.remove(Integer.valueOf(index));
        index++;
        nextQuestion();
    });
    pause.setRepeats(false);
    pause.start();
}

public void results() {
    buttonA.setEnabled(false);
    buttonB.setEnabled(false);
    buttonC.setEnabled(false);
    buttonD.setEnabled(false);

    result = (int)((correctGuesses/(double)totalQuestions) * 100);

    textField.setText("Your score: ");
    textArea.setText("");
    answerLabelA.setText("");
    answerLabelB.setText("");
    answerLabelC.setText("");
    answerLabelD.setText("");

    numberRight.setText("(" + correctGuesses + "/" + totalQuestions + ")");
    percentage.setText(result + "%");
    jFrame.add(numberRight);
    jFrame.add(percentage);
}

}

And every time I run the code, it randomly shows 5, 18, or 9 questions, and then the app stops, instead of running through all 20 questions randomly.




Generate standardised log-normal data in R

I want to generate data from a log-normal distribution, with mean zero and variance equal to 1, in R.

I have tried this so far:

(rlnorm(n = 100000, mean = 0, sdlog = 1) - exp(1/2))/(exp(1)*(exp(1)-1))

Using the wikipedia page, to get the mean and variance on the standard scale. I think that I have centred correctly, as when I calculate the sample mean for this generated data I get a value close to zero. However, the sample variance is not close to 1.




Uniform random integer in a range using minimum random bits

I need to generate unbiased uniformly distributed integers in an arbitrarily large range, using random bits which can be expensive to obtain, therefore I want to use as few random bits as possible on average.

The generated numbers should be between 0 and N-1, where N is the given range.

What I am doing now is:

  1. Calculate the number of bits B in N by some means; mathematically, B = ceil(log(N)/log(2)).
  2. Generate B random bits.
  3. If the random bits generated form an integer less than N, return them. Otherwise go to step 2.

The best case is when N is a power of two; then you don't reject anything. But the worst case is when N is a power of two plus one; in that case, you get asymptotically close to a probability of rejection of 1/2 on every attempt, as B grows. That strikes me as wasteful, so I wondered if there are better algorithms that need fewer bits on average.

For example, when the generated bits are >= N, if I permute bit positions in a predefined order instead of rejecting them, with the hope of finding one such permutation that is within range, and only generate a new batch if none of the permutations succeeds, would the result be uniformly distributed?




dimanche 14 mai 2023

How do I generate random strings in python? [duplicate]

I was wondering how you generate random strings in Python as opposed to random int's? How would I get around this?

I recently tried to make a random string generator using random.randint() and using if statements to print different results. When this threw an error I was wondering if there where any other ways of doing it.




Kotlin: Get x random unique elements from list using streams

I'm using the following stream() to get one random element from a list (of strings):

string.stream().filter { f -> f.contains("_reservert_") }.toList().random()

Is there a way to get x random AND uniqie elements in the same way?




samedi 13 mai 2023

Array of char of C++ [duplicate]

I have working code of int array and I try to do exactly the same code but with char. Something goes wrong, I got some huge amount of symbols instead.

char size_ch_array; // Something crazy here!!!!!!!!!!!!!!!!!!!
    cout << "Give me you size of Char Array" << endl;
    cin >> input_ch_size1;
    cin >> input_ch_size2;

    char rand_ch_array [input_ch_size1] [input_ch_size2];
            for (char m=0; m<input_ch_size1; m++)
                for (char n=0; n<input_ch_size2; n++)
                rand_ch_array [m] [n] = rand()%2;

            cout << "Your crazy array" << endl;
                for (char m=0; m<input_size1; m++)
                    for (char n=0; n<input_size2; n++)
            cout << rand_ch_array [m] [n] << " " << flush;
        cout << endl; 

I want to do func rand()%26 // where 26 letters of abc. I want to see the array of my size from 'a' to 'f', of different 26 letters or less?




Spark randomize values of a primary key column in another unique column ensuring no collisions

So I have this problem which is bugging me for a while ... I need to generate all possible values of ssn format xx-xxx-xxxx where x is any number from 0 to 9 in 1 column of a spark dataframe and then add a column which basically should contain the same values, but different than the initial column on each row.

Practical example with a small set of 0/1 possible values:

+-----------+-----------+
|ssn        |false_ssn  |
+-----------+-----------+
|00-000-0000|01-001-0000|
|00-000-0001|00-001-0001|
|00-001-0000|00-000-0001|
|00-001-0001|01-000-0000|
|01-000-0000|01-001-0001|
|01-000-0001|00-000-0000|
|01-001-0000|00-001-0000|
|01-001-0001|01-000-0001|
+-----------+-----------+

I managed to do this using this python code:

def generate_ssn_lookup_data(range_group_1: int, range_group_2: int, range_group_3: int,
                             spark: SparkSession) -> DataFrame:
    # Generate data
    sensitive_values = [f"{i:02d}-{j:03d}-{k:04d}"
                        for i in range(range_group_1)
                        for j in range(range_group_2)
                        for k in range(range_group_3)]
    mock_values = []
    used_values = set()
    for sensitive in sensitive_values:
        mock = sensitive
        while mock == sensitive or mock in used_values:
            mock = f"{random.choice(range(range_group_1)):02d}-{random.choice(range(range_group_2)):03d}-{random.choice(range(range_group_3)):04d}"
        mock_values.append(mock)
        used_values.add(mock)
    data = [(sensitive, mock) for sensitive, mock in zip(sensitive_values, mock_values)]

    df = spark.createDataFrame(data, ["ssn", "false_ssn"])
    return df

#Call 
df = generate_ssn_lookup_data(2, 2, 2, some_spark_session)

But you can imagine how this performs when trying to generate 1billion records with generate_ssn_lookup_data(100, 1000, 10000, some_spark_session)

So I also tried using spark native functions with the code below, but I can't avoid collisions where false_ssn = ssn (I added the hole debug code here, for actual values use a call like: generate_ssn_lookup_data(0, 9)) ... I'm guessing the fact that I try to ensure unique randoms is not enough, as actually the row_numbers could match for the same values... that loop though is worrying.

from pyspark.sql import DataFrame
from pyspark.sql import SparkSession
from pyspark.sql import Window
from pyspark.sql.functions import expr, rand, col, lit, concat, floor, when, row_number

spark = SparkSession.builder.master("local[*]") \
    .config("spark.driver.memory", "8g") \
    .config("spark.executor.memory", "8g") \
    .appName("App").getOrCreate()


def generate_ssn_lookup_data(start: int, end: int) -> DataFrame:
    df = spark.range(1).select(expr("null").alias("dummy"))
    ssn_characters = 9
    for _ in range(ssn_characters):
        df = df.crossJoin(spark.range(start, end + 1).select(col("id").alias("col" + str(_))))

    df = df.withColumn("ssn", concat(
        col("col0"), col("col1"), lit("-"),
        col("col2"), col("col3"), col("col4"), lit("-"),
        col("col5"), col("col6"), col("col7"), col("col8")
    )) \
        .withColumn("random", floor(rand() * pow(10, 15))) \
        .withColumn("random2", floor(rand() * pow(10, 15)))

    df = ensure_unique_random(df, random_col1="random", random_col2="random2")
    left = df.withColumn("rnd", row_number().over(Window.orderBy("random")))
    right = df.withColumnRenamed("ssn", "false_ssn").withColumn("rnd", row_number().over(Window.orderBy("random2")))
    df = left.alias("l").join(right.alias("r"), left.rnd == right.rnd).drop("rnd")

    return df.select("l.ssn", "r.false_ssn")


def ensure_unique_random(df: DataFrame, random_col1, random_col2) -> DataFrame:
    while df.where(f"{random_col1} = {random_col2}").count() != 0:
        df.where(f"{random_col1} = {random_col2}").show(truncate=False)
        df = df.withColumn(random_col2,
                           when(col(random_col1) == col(random_col2), 100).otherwise(
                               col(random_col2)))
    return df


df = generate_ssn_lookup_data(0, 1)
df.cache()
print("Generated Df ")
df.show(truncate=False)
df_count = df.count()
print(f"Generated Df Count: {df_count}")
unique_ssn_count = df.select("ssn").distinct().count()
print(f"Distinct SSN Count: {unique_ssn_count}")
false_ssn_count = df.select("false_ssn").distinct().count()
print(f"Distinct False Count: {false_ssn_count} ")
false_non_false_collisions = df.where("ssn = false_ssn")
collision_count = false_non_false_collisions.count()
print(f"False Non False Collisions: {false_non_false_collisions.count()}")
false_non_false_collisions.show(truncate=False)
assert (collision_count == 0)

Basically the problem is shuffling the values of columnA into column ensuring no duplicates appear on columnB and no columnB will equal columnA.

Thanks in advance.




vendredi 12 mai 2023

Dividing the datasets into train, valid and test based on condition

Objective: Randomly divide a data frame into train, valid and test based on condition

one sample with 60% of the rows other two samples with 20% of the rows

The data looks like here

enter image description here

Data needs to be divided based on unique ID. so that training and valid or test should not have same unique ID

Thanks




jeudi 11 mai 2023

Generate a sequence of random numbers

I am trying to generate a sequence of random numbers using the XPath 3.1 random-number-generator() function.

The specification states that the function returns a map containing three entries, and that the entry with key "next" is a zero-arity function that can be called to return another random number generator. However, there are no instructions (at least not instructions that I could understand) regarding how exactly to do that.

I was able, after some trial and error, to produce two different random numbers using:

<test>
    <xsl:value-of select="random-number-generator()?number" />
    <xsl:text> - </xsl:text>
    <xsl:value-of select="random-number-generator()?next()?number" />
</test>

However, adding a third call using the same code as the second one:

<test>
    <xsl:value-of select="random-number-generator()?number" />
    <xsl:text> - </xsl:text>
    <xsl:value-of select="random-number-generator()?next()?number" />
    <xsl:text> - </xsl:text>
    <xsl:value-of select="random-number-generator()?next()?number" />
</test>

results in the last two random numbers being equal, for example:

<test>0.8258447548324238 - 0.37162622506875487 - 0.37162622506875487</test>

(full test at https://xsltfiddle.liberty-development.net/gWmsLza).

The specification also provides an example of "a function that can be called to produce a random sequence of xs:double values in the range zero to one, of specified length". This is what I would eventually like to do, but the provided code is not in the XSLT language and I am not able to understand how it works.

Can someone please provide clear instructions how to call the function repeatedly so that it provides a new random number at each call?




mercredi 10 mai 2023

How to nullify the effect of global/operation level seed in the subsequent cells of Kaggle kernel?

Context

I am trying to write a Kaggle kernel on a topic that involves setting global/operation level seeds. For this, I am writing each case separately in a different cell. But the issue I encountered is that the seeds which I set in my previous cells were impacting the output of my subsequent cells.

For example, have a look at the following snippet that describes one of the cases:

"""
Case:
    Setup: When only operation level seed is set -
           - Since operation level seed is set, the sequence will start from same number after restarts, 
            and sequence will be same

"""

import tensorflow as tf

print(tf.random.uniform([1], seed=1))  # generates 'A1'
print(tf.random.uniform([1], seed=1))  # generates 'A2'
print(tf.random.uniform([1], seed=1))  # generates 'A3'
print(tf.random.uniform([1], seed=1))  # generates 'A4'

If I re-run the above code (as part of separate python file), I get a same sequence (as expected).

But when I re-run the same code in a separate cell of my Kaggle kernel, I got a different sequence. This might be due to the global/operation level seeds that I must have set in my previous cells.

What did I try?

To nullify the effect of previous cells on the current cell, I used some already available techniques to restart the kernel:

import IPython.display as display
import time

# Restart the cell
display.Javascript('Jupyter.notebook.kernel.restart()')

# Wait for the kernel to restart
time.sleep(20)

"""
Case:
    Setup: When only operation level seed is set -
           - Since operation level seed is set, the sequence will start from same number after restarts, 
            and sequence will be same

"""

import tensorflow as tf

print(tf.random.uniform([1], seed=1))  # generates 'A1'
print(tf.random.uniform([1], seed=1))  # generates 'A2'
print(tf.random.uniform([1], seed=1))  # generates 'A3'
print(tf.random.uniform([1], seed=1))  # generates 'A4'

or this:

from IPython.core.display import HTML
HTML("<script>Jupyter.notebook.kernel.restart()</script>")

"""
Case:
    Setup: When only operation level seed is set -
           - Since operation level seed is set, the sequence will start from same number after restarts, 
            and sequence will be same

"""

import tensorflow as tf

print(tf.random.uniform([1], seed=1))  # generates 'A1'
print(tf.random.uniform([1], seed=1))  # generates 'A2'
print(tf.random.uniform([1], seed=1))  # generates 'A3'
print(tf.random.uniform([1], seed=1))  # generates 'A4'

But I still did not get the same sequence.

My question

What else should I try or am I doing something wrong here?




Animating 2D random walk trajectory with ggplot in R

I'm trying to create an animation that shows the trajectory of a random walk on the (x,y) plane over time. Each 'step' is a move in either the vertical or horizontal direction, never both. For example, if you start at (0,0) you have only four options: (0,1), (0,-1), (1,0), (-1,0); you can never go from (0,0) to (1,1) in one step.

I've written the random walk generating function to ensure that steps can only be taken across one axis at a time. Here is a regular ggplot without animation of one of these random walks using geom_path() and geom_point():

Random walk with T=100

When I try to animate the walk, however, it shows diagonal lines connecting the points which is impossible.

Animated trajectory

I can't figure out why this is happening. I've tried using geom_line() instead but that doesn't seem to fix the issue. The code for the animation is below:

ggplot(df,aes(x=x,y=y)) + 
  geom_path() +
  geom_point() +
  transition_reveal(along=ite) + # ite: numerical ordered variable in df representing the time from 0:n
  scale_x_continuous(breaks = seq(min(df$x), max(df$x), by = 1)) +
  scale_y_continuous(breaks = seq(min(df$y), max(df$y), by = 1)) +
  coord_fixed() +
  theme(panel.grid.minor = element_blank())



How can i fetch random order from One-to-Many relationships in laravel 10

I have a One-to-Many relationship

  • The "Question" table has many Options,
  • The "Options" table belongtsTo "Question" table.

I’am trying to fetch, in the same time, random order for my question and random order for options.

I’ am getting the Questions in random order, but I don’t know how to get a random order for the options as well.

Here below you have my code :

My controller:

    public function showQ(){
        return view('my_view',[
            
            'Questions' => Question::inRandomOrder()->with('Option')->get(),
            
        ]);

In the view

    @foreach($Questions as $question)
      
       

       @foreach($Questions -> Option as $option)
           
          
       
       @endforeach

    @endforeach
    

Question model

  public function Option(): HasMany {
        return $this -> hasMany(Option::class);
    }

Option model

  public function Question(): BelongsTo {
        return $this-> belongsTo(Question::class);
    }

Is there any one to clarify the issues?




mardi 9 mai 2023

Unity Infinite Loop UnityEngine.Random

I'm trying to create a loop that outputs 9 numbers in a random order with no repeating numbers. When I run it it creates an infinite loop and I can't figure out where I went wrong.

    public void randomizer()
    {
        resetArray();
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                int randomNumber = UnityEngine.Random.Range(1, 9);
                if(!numCheck(randomNumber))
                {
                    buttons[i, j] = randomNumber;
                }
                else
                {
                    j--;
                }
                Debug.Log(randomNumber);
            }
        }
    }

    public void resetArray()
    {
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                buttons[i,j] = 0;

            }
        }
    }

    public bool numCheck(int num)
    {
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                if (buttons[i, j] == num)
                {
                    return true;
                }

            }
        }
        return false;
    }

The code loops infinitely, however when my friend mimic'd it in c# it worked fine on his end. What is causing the infinite loop?




lmer random intercept random slope model coefficients does lead to adequate regression in R

I'm trying to fit a random intercept random slope model to my data. In this data, I have different patients, all with three implanted electrodes (LAN/SAN/PAN), and I'm looking at the effect of StimRate on the response 'result'. Using lmer I'm fitting this model, but the individual coefficients per subject/electrode combination do not seem to be correct.

dataset

df<-structure(list(subject = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L), .Label = c("1", "2", "3", "5", "6", "8", "9"), class = "factor"), Electrode = c("LAN", "LAN", "LAN", "SAN", "SAN", "SAN", "PAN", "PAN", "PAN", "LAN", "LAN", "LAN", "SAN", "SAN", "SAN", "PAN", "PAN", "PAN", "LAN", "LAN", "LAN", "SAN", "SAN", "SAN", "PAN", "PAN", "PAN", "LAN", "LAN", "LAN", "SAN", "SAN", "SAN", "PAN", "PAN", "PAN", "LAN", "LAN", "LAN", "SAN", "SAN", "SAN", "PAN", "PAN", "PAN", "LAN", "LAN", "LAN", "SAN", "SAN", "SAN", "PAN", "PAN", "PAN", "LAN", "LAN", "LAN", "SAN", "SAN", "SAN", "PAN", "PAN", "PAN"), StimRate = c(170, 255, 350, 170, 255, 350, 170, 255, 350, 170, 255, 350, 170, 255, 350, 170, 255, 350, 170, 255, 350, 170, 255, 350, 170, 255, 350, 170, 255, 350, 170, 255, 350, 170, 255, 350, 170, 255, 350, 170, 255, 350, 170, 255, 350, 170, 255, 350, 170, 255, 350, 170, 255, 350, 170, 255, 350, 170, 255, 350, 170, 255, 350), result = c(6.52102722288664, 9.22019774432065, 26.5655048141819, 14.5, 20, 24.25, 1.9142135623731, 2.92080962648189, 4.30277563773199, 63.9763476887368, 88.9562197097544, 140.606864480896, 60.4829340051411, 64.0882999323977, 89.6212532523402, 9, 15.0118980208143, 25.8648808045487, 66.4275, 67.2522222222222, 111.332727272727, 90.972, 117.55, 141.881666666667, 20.255, 30.91125, 57.06, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.513333333182, 1.46499999986639, 1.60045618855114, 2.32320260275458, 2.50266082562552, 2.21762809295402, 1.92141610251248, 1.62939845265917, 2.45633949992756, 32.8, 48.51, 66.19625, 26.655, 36.3875, 39.335, 9.2425, 14.5775, 26.85125, 73.92, 58.73, 86.8066666666667, 94.4475, 100.1125, 81.7683333333333, 15.3075, 44.595, 47.395)), row.names = c(7L, 8L, 9L, 16L, 17L, 18L, 25L, 26L, 27L, 34L, 35L, 36L, 43L, 44L, 45L, 52L, 53L, 54L, 61L, 62L, 63L, 70L, 71L, 72L, 79L, 80L, 81L, 88L, 89L, 90L, 97L, 98L, 99L, 106L, 107L, 108L, 115L, 116L, 117L, 124L, 125L, 126L, 133L, 134L, 135L, 142L, 143L, 144L, 151L, 152L, 153L, 160L, 161L, 162L, 169L, 170L, 171L, 178L, 179L, 180L, 187L, 188L, 189L), class = "data.frame")

model

RISM = lmer(result ~ StimRate + (1 + StimRate | subject/Electrode), data = df) summary(RISM) cf<-coef(RISM)

when plotting the regression (intercept/slope), is does not fit well, for example for LAN/subject 2. When applying a linear regression on only this data it fits well however. What is going wrong with the random intercept random slope model?

df_subset<- df[which(df$subject==2 & df$Electrode=="LAN"),] lm(results~StimRate, data = df_subset)




lundi 8 mai 2023

How to assign a random number in Excel with conditions?

I want to assign a number between 1 to 6 in Column 2023 with the condition that each number should be equally assigned in 2023 and should not match any of the numbers assigned previously in 2020, 2021 and 2022. Excel experts are requested to extend their support, please.

Excel Table




dimanche 7 mai 2023

1B pseudo-random boolean permutations of vector set N by M

Let's say we have a set of pseudo-random boolean/binary vectors of length N, and each vector is length M.

e.g. {[0,1,0,1], [0,0,0,1]}

We need one billion unique vectors.

Now, the question is, what is the fastest way to do this?? (also please keep in mind we need to keep the vector set in memory, so that later we can use the same set to do other stuff)

For example... here are some approaches I have tried...

## where N = 10 and M = 10,000
def idx_v(idx, ivals=vector_set(N,M), ival=np.zeros(10_000)):
  divs = idx // 10
  remains = idx % 10
  a = [divs,remains]
  hv = str( abs( hash( str(a) ) ) )
  ival = ivals[remains]
  for i in hv:
    ival = np.roll(ival, int(i))
  return ival, divs, remains

for idx in range(1_000_000_000):
  ival = idx_v(idx)

that takes about 0.006 seconds per generation of 10 vectors

##where N = 100 and M = 10,000 
def idx_v(idx, ivals=vector_set(N,M), ival=np.zeros(10_000)):
  divs = idx // 100
  remains = idx % 100
  ival = np.roll(ivals[remains], divs )
  return ival, divs, remains

for idx in range(1_000_000_000):
  ival = idx_v(idx)

that takes about 0.005 seconds per generation of 10 vectors




How can I ensure that x number of mines are placed on a minesweeper board, if the mines are generated at random? [duplicate]

So I am making minesweeper in html/css/javascript. I have 3 different difficulty states that the player can choose that determine how large the board is going to be, and how many mines it will have. for the purposes of this question I'll go with the intermediate settings, 16x16 board with 40 mines on it.

board is initiated to board = []; to populate it I use

function createBoard(row,col,mines){
    let count=0;
    for(let r=0;r<row;r++){
        board[r]=[];
        for(let c=0;c<col;c++){
            if(count <= mines){
                board[r][c]=new CELL(row,col,false);
            }
            else{
                let mine = Math.round(Math.random());
                board[r][c]=new CELL(row,col,Boolean(mine)); //0 is no mine, 1 means mine
                if(mine){
                    count++;
                }
            }
        }
    }
}

so that should create the right sized board, and populate it with CELL objects, some of which are mines. The problem is that my count variable only ensures that my randomizer doesnt generate MORE THAN 40 mines. The randomizer could (theoretically) choose 0 for every single object.

so how can I make sure my board gets created with the appropriate number of mines while still being truly random?




Is ChatGPT a secure source for randomness?

Assume the attacker cannot hijack communication between ChatGPT and randomness requester, and assume ChatGPT provider is benign. Are answers from ChatGPT for questions like "give me ten integers between 0 to 4294967295" cryptographically secure?




samedi 6 mai 2023

Assigning treatments to blocks in a RCBD experiment using SPSS

I wish to use SPSS or excel (preferably SPSS) to help me randomly assign 12 treatments each to 4 blocks in a Randomized Complete Block Design experiment. I would like to receive help on how to go about this.

Thanks

I have not been able to do this on SPSS. I would like to receive directives or the code on how to go about this.




Abecedarian program on Python

I am trying to create a little program that uses a statistical approach to generate Abecedarian poems ( a poem in which the first letter of each line or stanza follows sequentially through the alphabet), but I tried two different approaches and neither seem to work. The first one just runs forever and doesn't yield any results; the second gives me an Index Error that reads "# raises IndexError if seq is empty" and "list index out of range".

The poem does not need to rhyme or have lines of any particular length.

These are the two options I have tried:

def generateAbecedarian():

  alphabet = ['a','b','c','d','e','f',
            'g','h','i','j','k','l',
            'm','n','o','p','q','r',
            's','t','u','v','w','x',
            'y','z']
        
  for i in range(1):
    line_i = model.make_sentence()
    line_i_list = line_i.split(' ')
    first_word_i = line_i_list[0]
    first_letter_i = list(first_word_i)[0]
    while first_letter_i != alphabet[i]:
      line_i = model.make_sentence()
    else:
      print(line_i)  

This first one runs and runs without ever giving any output. This is the second option I have tried:

def generateAbecedarian2():

  alphabet = ['a','b','c','d','e','f',
            'g','h','i','j','k','l',
            'm','n','o','p','q','r',
            's','t','u','v','w','x',
            'y','z']
        
  word_list_i = []      
  for i in range(26):
    word_list_i = [w
                   for w in corpus
                   if list(sentence)[0] == alphabet[i]
                  ]
    random_first_word_i = random.choice(word_list_i)
    line_i = model.make_sentence_with_start(random_first_word_i)
    print(line_i)

This one gives me the index error.

In both of these I make use of random, markovify, and a predefined corpus, as well as a Bigram model I have set up previously.




vendredi 5 mai 2023

php random numbers without duplicate

I have php code below that creates random numbers when adding static number ;100 and divides numbers with |. It works well but creates duplicate numbers, how to make it prevent creating duplicate numbers?

echo shd be 3;100|2;100 but without duplicate numbers before ;100. but this code outputs numbers like 2;100|2;100 sometimes, that are duplicates.

<?php
$kat_list=array(1,2,3,4);

$count_cat= rand(2,3);

for ($i = 1; $i <= $count_cat; $i++) {
    $rnd_cat= rand(0,count($kat_list)-1);
    $kats[]=$kat_list[$rnd_cat].'--100';

}
$line=implode('-',$kats);

 $line=str_replace('--', ';', $line);
 $line=str_replace('-', '|', $line);
 


 echo $line;



this is my football championship simulation school project where every team must play once a day and 1 match only against all the other teams randomly

so i had a problem that goes like this supposing i have 6 teams this is how the tournament would go(a,b,c,d,e,f) day 1 a-b c-d e-f day 2 a-d c-b and now the problem happens cuz only teams e and f are left and i cant form a match using these 2 teams

what i tried was making a matrix daytable[amountOfTeams/2][2] where i have to fill all the matrix before start assigning scores and points... but now the teams are playing more than one match a day this is my code

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct equipe{
    char nom[30];
    int adver[19];
    int points ;
    int ts;
}Equipe;
     void define(Equipe *league,int a){
         //defines the clubs
        int i;
        for(i=0;i<a;i++){
            printf("enter the name of the club number %d\n",i+1);
            Equipe pi;
            league[i] =  pi;
            scanf("%s",league[i].nom);
            league[i].points=0;
            printf("the %d club is %s \n",i+1,league[i].nom);}}
     bool nonplayed(Equipe *league,int kk,int first,int second){
         //to check if the teams have already played against each other
        int nc;
        for(nc=0;nc<kk;nc++){
            if(league[first].adver[nc]==second||league[second].adver[nc]==first){
                return true;
            }}
        return false;
    }
     bool checkday(int d[],int dsi,int cl){
         //to check if the teams played this day
        for(int di=0;di<dsi;di++){
            if(d[di]==cl){
                return true;
            }
        }
        return false;
    }
     void pointcount(Equipe *league,int fir,int sec){
         //counts points
      if(league[fir].ts>league[sec].ts){
        league[fir].points+=3;
      }else if(league[fir].ts==league[sec].ts){
        league[fir].points+=1;
        league[sec].points+=1;
      }else{
        league[sec].points+=3;
      }
     }
     void order(Equipe *league,int a){
         //orders the clubs depending on their points just for visuals
      Equipe mom,classement[a];
      int oi,oj;
      for(oi=0;oi<a;oi++){
        classement[oi]=league[oi];}
        oi = 1 ;
    while (oi < a){
        oj = oi;
        while (oj > 0 && classement[oj-1].points > classement[oj].points){
            mom=classement[oj];
            classement[oj]=classement[oj-1];
            classement[oj-1]=mom;
            oj = oj - 1;}
        oi = oi + 1;}
        for(oi=a-1;oi>=0;oi--){
            printf("%d:%s points:%d \n",a-oi,classement[oi].nom,classement[oi].points);
        }
     }
     void day(Equipe *league,int a,int kk,bool work){
         //simulates a day of the championship
        int f,s,j,sta,fal=0;
        int dp[a];
        int daytable[a/2][2];
        for(j=0;j<a/2;j++){
        do{
        f =rand()%a;
        s =rand()%a;
        fal++;
        if(fal>5000){
            break;
            work=false;
        }
        }while(f==s||checkday(dp,(j*2),s)||nonplayed(&league,kk,f,s)||checkday(dp,(j*2),f));
        daytable[j][1]=f;
        daytable[j][2]=s;
        dp[(j*2)]=f;
        dp[(j*2)+1]=s;}
        printf("ra7 nprinti tableau \n");
        for(j=0;j<a/2;j++){
            printf("%d %d \n",daytable[j][1],daytable[j][2]);
        }
        for(j=0;j<a/2;j++){
        league[daytable[j][1]].ts=rand()%10;
        league[daytable[j][2]].ts=rand()%10;
        printf("%s %d - %d %s\n",league[daytable[j][1]].nom,league[daytable[j][1]].ts,league[daytable[j][2]].ts,league[daytable[j][2]].nom);
        pointcount(league,daytable[j][1],daytable[j][2]);
        league[daytable[j][1]].adver[kk]=daytable[j][2];
        league[daytable[j][2]].adver[kk]=daytable[j][1];
        }
        order(league,a);
    }



int main()
{
    int a,i,kk;
    bool work;
        kk=0;
        printf("how many clubs do you want in your league\n");
        do{
        scanf("%d",&a);
        }while(a%2!=0||a>20||a<4);
        Equipe league[a];
        define(league,a);
        for(i=0;i<a-1;i++){
            matchstart:
            work=true;
            printf("press any key to continue \n");
            getch();
            printf("day %d\n",i+1);
            day(league,a,kk,work);
            if(work==false){
                goto matchstart;
            }
            kk++;}
            for(i=0;i<a-1;i++){
            printf("%s\n",league[league[0].adver[i]].nom);
            ;}
    return 0;
}



How can I randomly select values from a very large number of permutations without causing memory issues?

I am solving one machine scheduling problem and the data set is very large. I need to obtain a subset of permutations (with a pre-defined selected_number: How many numbers I want to get from the permutations) from the permutation results, and the selected permutations need to be randomized.

for example, if my machine 1 has 15 jobs, then all possible permutations would be 15! It is impossible to append all the sequences in the list for the large number of permutations, it may cause a lack of memory.

perms = list(permutations(self.machines[m]))
selected_perms = random.sample(perms, num_selected)

So I try in two ways: (1)Randomly select permutations and add to a list (select all machines), ensuring randomness: But the first way is pretty slow, I have no idea why does it happened.

selected_perms = []
                    
while selected_perms.__len__() < num_selected:
  job_perms =  random.sample((list(self.machines[m])), 15)
  if job_perms not in selected_perms:
    selected_perms.append(job_perms)    

(2) Shuffle the machine sequence first, and then select a subset of the permutations. However, this way does not perform well because the randomness is poor.

perms =  random.sample((list(self.machines[m])), job_count)
selected_perms = list(islice(permutations(perms), num_selected))

(3)I have an idea to improve method 2. First, Shuffle the machine sequence first and select smaller selection permutations. Then, repeat this process multiple times to reach the total selection number. However, I believe that this approach may only yield slightly better results than method 2.

I would appreciate any suggestions you may have!




Python portfolio weight generation

I have a problem: I need to generate weights of a portfolio of n assets, and the weight of each asset must be a multiple of 1%, and at most 25%. I use the function np.random.randint. Then I divide the weights by the sum of the generated numbers, and encounter a problem during rounding some weights become less than 1%, and some greater than 25%, which contradicts the initial conditions

I used such function:

min_weight= 1 max_weight = 25 for asset in assets_for_portfolio: weight = np.random.randint(min_weight, max_weight) portfolio_weights = weight portfolio_weights /= portfolio_weights.sum()

But I encountered the problems I described




mercredi 3 mai 2023

Reasonably unique string for a given machine

I am creating a C program. I mainly care about unix/linux systems but including windows here would be ideal. I want to find an approximately unique identifier for a networked machine. I am wondering if there is a better solution than finding a MAC address. The fact that MAC addresses can be duplicated is not necessarily a deal breaker. One might do something like this (yes, I know this is not portable; yes I know rand isn't really random, this just for demonstration):

#include <sys/socket.h>
#include <sys/ioctl.h>
#include <linux/if.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <time.h>   
#include <stdlib.h> 

int main()
{
  struct ifreq s;
  int fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
  
  srand(time(NULL)); 
  strcpy(s.ifr_name, "wlp0s20f3");
  if (0 == ioctl(fd, SIOCGIFHWADDR, &s)) {
    int i;
    for (i = 0; i < 6; ++i)
      printf("%x", (unsigned char) s.ifr_addr.sa_data[i]);
      printf("%d\n",rand() % 200);
      return 0;
  }
  return 1;
}

But is there some other mechanism that might be considered?




How to select a random word from WordNet Library C#

I am making a word quiz game in visual studio 2022. I have found a way to check if a word is a real word using WordNet database files. My question is how to select a random word from WordNet in order to make user guess it.Method like wordNet.GetAllSynsets(); does not exists. Only wordNet.AllWords; i have found that is more similar to what i want. But i dont know how to work with it.




How to make the r become 1 and stay like that [closed]

Whenever I repeat the loop, the r reverts back to 0. I want to keep it at 1 unless something else brings it back to 0.

r = 0
rand = random.randint(1,3)
if rand == 2:
   r = 1

print("r:" + str(r))



mardi 2 mai 2023

Python: random number game with play again where loop fail

This is my first code ever in Python and I'm sure many think "Ohh.. should have done this or that!". I'm aware and I'm here to learn.

I believe a lot of my errors/problems are related to indentation. But there's plenty of it. I also suspect that I'm mixing things up while in loop or if/elif's. I pasted the terminal output into notepad for reference. I'll post my code below all.

It started really simple but then I wanted to make more and when you make more and don't know what you're doing you tend to google stuff. And when googling stuff make you use different peoples thoughts and that seems to clash sometimes. So if it looks like it's a code written by multiple personalities you're not far from the truth.

What I want is:

  1. Correct action on yes/no alternatives.
  2. Warning and forced reentry when input isn't integers and/or yes/no where it's supposed to be.
  3. When new game starts the random_number must reset. This doesn't work when it starts from "Game ended after 10 trials!". It keeps the tries from last round.

My problem(s) is:

1. While reaching the end of a game the game ask you if you want to play again if you guessed the right #. I'm not sure what I changed but it worked earlier, so my guess is that it has something to do with indentation.

2. New run: Input is "no" and should exit but it start a new round. And the new round start at the "guess"-line (#45) and not at game() (#33). This action doesn't reset the random#.

# Gissa slumptal mellan 1 - 100 i Python
"""
The user must guess a number between 1-100, that the program
give by using the built-in function randint.
The user gets 10 attempts before the game ends. The user gets
an indication of how close the guess is to the correct number and another if
this one is in the range of +-3 <> random_number.

The program tells you how many times you guessed and what the number was.
"""

# Use module random and set guessed to 0.
# could have used from random import randint
import random
guessed = 0

# Declare variable and generate random number in range 1 - 100.
def get_random_number():
    random_number = random.randrange(1,100)
    return random_number


def startGame():
    answer = input("Do you want to play a game? Answer yes or no.\n")
    if answer == "yes":
        while guessed != True:
            game()
    if answer == "no":
        print("See you later!")

# Ask user to guess the number in less than 11 times(10 tries).
# The answer will be in variable "guess".
def game():
    print("\nI guessed a number between 1-100")
    print("Can you guess which in less than 10 guesses?")
    
    # Variable to how many tries and boolean on found.
    tries = 0
    found = False
    random_number = get_random_number()    
    
    while not found:
        while True:
            try:
                guess = int(input("Guess which number I'm thinking of!\n"))
                break
            except ValueError:
                print("Only integers please!")
                continue
        if guess == random_number:
                print(str(random_number) + "! It was right! You did " + str(tries) + " attempts. Good work!\n")
                found = True
                
                # Ask if user would like to try again.
                while True:
                    a = str(input("Do you want to try one more time?.\n"))
                    if a in ("yes", "no"):
                        print("Just answer yes or no, please.\n")
                        continue
                    if a=="yes":                        
                        game()
                    if a=="no": # If I answer "no", I go to startGame again, but "yes" works
                        print("Welcome back!")
                        #break
                            
                    
        # The program check if user was right and give response.
        # When in range of +-3 from randomnumber give a notice.
        elif (abs(guess - random_number) <= 3):
            print("It's really close now!")
            stillGuessing = True
        elif guess < random_number:
            print("Sorry, it was too low. Try again!\n")
            stillGuessing = True
        elif guess > random_number:
            print("Sorry, it was too high. Try again!\n")
            stillGuessing = True

        # Loopcount.
        tries += 1

            # End game after 10 tries and ask user if they want to restart.
        if tries == 10:
                print("\nThe correct answer was: " + str(random_number) + ".")
                print("Game ended after 10 tries! Do you want to play again?")           

                # Ask for Y/N. If not Y/N = errormessage and try again.
                while True:
                    b = str(input("Answer yes or no to try again.\n"))
                    if b in ("ues", "no"):
                        break
                    print("Just answer yes or no, please.\n")
                    
                    # if "yes" I return to guess without new random_number
                    if b=="yes": 
                        game()
                        
                    # if "no" I return to game() - I want the run to end with print("Welcome back!")
                    if b== "no":
                        print("Welcome back!")
                        break   
def main():
    startGame()
if __name__ == "__main__":
    main()
        
        

    
    # Hold until input.
    #print()









I've tried to change indentation, tried different valueError/string controls and rearrange the code when I understood that I've written code in the wrong place and so on.. As the code got bigger I had to start using functions etc. I started with a simple thing that outgrow me. Fast.

I expected something like this:

  1. Ask player to play

  2. If yes - start game, if no - end run.

    • check if input is "yes" or "no"
    • If not, prompt reenter yes/no
  3. Output to user about game and prompt action.

  4. Game start: 10 tries to get random#

    • check if input is int
    • If not, ask for reentry a int
    • If guess is correct: Tell "Congrats, #tries and ask for a new game".
    • check if input is "yes" or "no"
      • If not, ask for only "yes" or "no"
      • If not, reenter yes/no
    • If yes: start new game (with random# reset)
    • If no: print "Welcome back" - end run.
  5. If not right in 10 guesses: Tell user the random#, message about 10 tries and ask for a new game.

    • If yes: reset random#, go to game() and start over
    • If no: print "Welcome back" - end run.