mardi 31 mai 2022

Pick random names from different lists excel VBA

I would like to pick random names from columns in excel like this :

-In the first sheet "Inscrp" is where the lists are, and the second sheet "Tirage" is where the results of the picking.

-Column A in the sheet "Tirage" should pick random names from column A in the sheet "Inscrp" and the same for the column B, C , till the number of columns I chose I managed to do this with only the first column and here is the code :

Sub PickNamesAtRandom()
Dim HowMany As Integer
Dim NoOfNames As Long
Dim RandomNumber As Integer
Dim Names() As String 'Array to store randomly selected names
Dim i As Byte
Dim CellsOut As Long 'Variable to be used when entering names onto worksheet
Dim ArI As Byte 'Variable to increment through array indexes
Application.ScreenUpdating = False

HowMany = 5
CellsOut = 8
ReDim Names(1 To HowMany) 'Set the array size to how many names required
NoOfNames = Application.CountA(Worksheets("Inscrp").Range("A3:A100")) - 1 ' Find how many names in the list
i = 1
Do While i <= HowMany
RandomNo:
    RandomNumber = Application.RandBetween(3, NoOfNames + 1)
    'Check to see if the name has already been picked
    For ArI = LBound(Names) To UBound(Names)
        If Names(ArI) = Worksheets("Inscrp").Cells(RandomNumber, 1).Value Then
            GoTo RandomNo
        End If
    Next ArI
    Names(i) = Worksheets("Inscrp").Cells(RandomNumber, 1).Value  ' Assign random name to the array
    i = i + 1
Loop
'Loop through the array and enter names onto the worksheet
For ArI = LBound(Names) To UBound(Names)
    Worksheets("Tirage").Cells(CellsOut, 1) = Names(ArI)
    CellsOut = CellsOut + 1
Next ArI

Application.ScreenUpdating = True
End Sub



lundi 30 mai 2022

How to get rid of the negative number when generating a random number?

I'm building a program to generate random 9 digit number for students to enroll in a college/university. I have been using the random object to generate random studentID numbers for students. It works, however, I noticed that it also generates negative number. I'm wondering how to get rid of the negative number and only include positive numbers.

Random rand = new Random();
int studentID = rand.nextInt();
System.out.println("Your student ID number is: " + studentID);



Making a 1-6 random number class Java

for some reason when i call on this class it doesn't return me anything. class will need two instance properties, die1 and die2, which will be used to store the value of each die(1-6).

//define class variables here
Random rd = new Random();
int die1;
int die2;
//define class methods here

method requires no arguments. When called, the method will generate random numbers between 1-6 and assign them to die1 and die2. A different random number will be generated for each die. The return type should be void.

public void roll () {

this.die1 = 1 + rd.nextInt(6);
this.die2 = 1 + rd.nextInt(6);

}

method will return the sum of both die values as an integer when called. This should be a number between 2 and 12.

public int getTotal() {

int sum = die1 + die2;

return sum;

}

Getter method that returns the value of the first die.

public int getDice1(int dice1) {

this.die1 = dice1;

return this.die1;

}

Getter method that returns the value of the second die.

public int getDice2(int dice2) {

this.die2 = dice2;
return this.die2;
}

}




Why is sum of random.choice returning the same total when ran multiple times in Python? [closed]

I'm experimenting with a 'deck of cards', but when I try to randomly call a number from the deck, the sum is always the same, as shown below. I can't figure out why this is happening. Shouldn't random.choice(list) call a random value from the deck?

deck = [
    1, 2, 3, 4, 5, 6, 7, 8, 9,
    1, 2, 3, 4 , 5 , 6, 7, 8, 9,
    1, 2, 3, 4 , 5 , 6, 7, 8, 9,
    1, 2, 3, 4 , 5 , 6, 7, 8, 9,
    10, 10, 10, 10,
    10, 10, 10, 10,
    10, 10, 10, 10,
    10, 10, 10, 10
    ]

user_card_1 = random.choice(deck)
deck.remove(user_card_1)

dealer_card_1 = random.choice(deck)
deck.remove(dealer_card_1)

user_card_2 = random.choice(deck)
deck.remove(user_card_2)

dealer_card_2 = random.choice(deck)
deck.remove(dealer_card_2)

user_hand = user_card_1 + user_card_2
dealer_hand = dealer_card_1 + dealer_card_2

print(f"Your hand: {user_hand} ({user_card_1} and {user_card_2})")
print(f"Dealer's hand: {user_hand} ({dealer_card_1} and {dealer_card_2})")

Example output:

Your hand: 10 (4 and 6)
Dealer's hand: 10 (10 and 8)



Custom distribution is always giving the same value in Anylogic

I am using AnyLogic for a simulation, and in a function I made, I am creating a custom distribution from a list of observations (integers) which I stored in a database table (some values are 10,12,10,14,16,20,21,23,11,...).

The problem is that after creating the custom distribution programatically, it returns always the same value from the distribution (14). I thought that fixing the seed at 0 was causing the problem, so I wrote this code to compute a random seed for each execution and use it to get the random value from the custom distribution :

CustomDistribution dist = new CustomDistribution(leadtimes);
int seed = ThreadLocalRandom.current().nextInt(0, 100 + 1);
traceln("Seed : "+seed);
delay = dist.get(new Random(seed));

In this code, leadtimes is a list of integer observations, seed is generated randomly each time, dist is the custom distribution object, and delay is the random value that I would like to get.

In short :

How to generate a random value that is different each time from a custom distribution created programatically ?




dimanche 29 mai 2022

How to print a random word from a list which ends with 's'?

So I'm trying to figure out how to run a script that searches for a random word ending in 's'. the txt list I'm using is 50% words ending in 's'. I have tried a few things and I can't seem to figure it out. basically what I want it to do is run 'snoun' and tell it hits a word ending in s. I'm sure there are other ways to achieve this one thing, but the process itself is relatively important. right now I'm getting RecursionError: maximum recursion depth exceeded in comparison.

X = random.randint(1,218)
file = open('pluralnoun.txt')
content = file.readlines()
snoun = content[X]
def nouns():
    if snoun == "*s":
        print(snoun)
    else:
        nouns()

After seeing a comment I realize of course it won't work. So I tried

def run():
    X = random.randint(1,218)
    file = open('pluralnoun.txt')
    content = file.readlines()
    snoun = content[X]
    if snoun == "*s":
        print(snoun)
    else:
        run()

and I am getting IndexError: list index out of range




Only loops through twice

I am making a random number game where there are two base numbers and you must guess what the number is between them. The problem is in my for loop it is only looping through once or twice. Where am I going wrong here?

Here is my code:

import random
opening_message = "Welcome to Higher/Lower game Bella!"
print(opening_message)

higher_number = int(input("Give us a higher number! "))

lower_number = int(input('Give us a lower number! '))

if lower_number > higher_number:
    print("Lower number must be less than higher number")
    lower_number = int(input('Give us a lower number! '))
else:
    guessed_number = int(input("Great, now Guess the number between {} and {}! ".format(lower_number, higher_number)))
    print(guessed_number)



num = random.randint(lower_number, higher_number)
for number in str(num):
    if guessed_number < num:
        print('Nope, too low try again!')
        guessed_number = int(input("Guess a new number!".format(lower_number, higher_number)))
    elif guessed_number > num:
        print('Nope, too high!')
        guessed_number = int(input("Guess a new number!! "))
    else:
        if guessed_number == num:
            print('correct! The number was {}'.format(num))
    print(' You did it!')
print('Great job Bella!')



How do you display an image with a source attached to an object? The object (question) is selected randomly and images should change with them

I have an array of objects which are questions. This is for a random question quiz. Basically, when one question is randomly selected, I thought all of the attributes would go with it (if "called" correctly). I am not sure how to display the image from the object when the question text (q) displays.

const questionBank = [
{
    q: "This is question 1's text",
    options:['1','2','3','4', '5'],
    answer:4,
    imgURL: 'http://drive.google.com/uc?export=view&id=googleDriveId',
},
{
    q: "question 2 will go here",
    options:['7','6','4'],
    answer:0,
    imgURL: 'http://drive.google.com/uc?export=view&id=differentDriveId',
}

function getNewQuestion(){
    const question = document.querySelector(".question");

    //set question text
    question.innerHTML = currentQuestion.q;

    //add image to question 
    //document.querySelector('.question').appendChild(img); (attempted, did not work)
    //var img = new Image(); (attempted, did not work)
    //img = document.createElement("img");  (attempted, did not work)
    //img.src = document.querySelector('.imgUrl'); (attempted, did not work)

I think that is all the relevant code.




php function that redirects a link to a random page on my website only works once. How can I make it work every time?

First of all, this isn't my code and I've received a lot of help in getting it to this stage. My problem is this: the random redirect works perfectly once, and if you click around the site for a while or clear your browsing history, it will work again. So it's as if the rng generates a random page once but then remembers that page and links back to it each time after.

As you'll see below, a link goes to a dummy page called "random page" which then redirects to a random page on the site (excluding a number of pages listed on line 5). The issue seems to be that the seed for the rng isn't resetting. I've been working with my software engineer neighbor and we've tried all kinds of things but nothing has worked. For one thing, we tried changing array_rand on line 7 to mt_rand, but this caused a "too many redirects" error.

The original code is this:

add_action('template_redirect', 'wpsf_random_page_redirect');
function wpsf_random_page_redirect()
{
    if (is_page('random-page')) {
        $excluded_pages = array(125, 126, 508, 510, 723, 987, 995, 1079, 1109, 1121, 1135, 1146, 1159, 1177, 1188, 1418, 1433);
        $pages = get_pages(array('exclude' => $excluded_pages));
        $random_page = $pages[array_rand($pages)];
        $page_url = get_page_link($random_page);
        wp_redirect($page_url);
        exit;
    }
}

We've tried adding a second dummy page, adding srand(); into the code or various locations such as the dummy page meta description, and much more. Our closest attempt to a solution, we think, was changing array_rand to mt_rand and getting the too many redirects error.

I've looked all around the web and couldn't figure it out (partly because all this is mostly gibberish to me), but neither could my neighbor it seems, and he knows what he's doing. Any ideas would be much appreciated, thanks!




Dice simulation counting values in array with for loop

I am creating a programme that is rolling two dices at the same time using a random. The purpose of the programme is to show all the numbers that were ransomized from the two dices in two different arrays and then cound how many ones and how many sixes. the first array an loop works fins but the other one looks nestled. It is like I've somehow created a loop inside the loop because when I for example enter 2 dice rolles, the second arrray shows 4. When I enter 3 it shows 9 and so on. I can't find the problem. I want the second dice to be rolled as many times as the first one.

""when running the program"" ""code"" part 1 enter code here part 2




samedi 28 mai 2022

Fixing do-while loop problem and how to add do you want to play again?

I started C courses today and teacher assigned to do:

Guess the number and if the number is higher say it is higher but if it is lower say it is lower and count every time you guess AND if you guess it ten times already then say do you want to try again?

I don't know why my code is stop when I just play it only 1 time and how to do the "do you want to play again?"

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

int main() {
    int x;
    char name[20], result;
    int count = 0;
    int number;

    srand(time(NULL));
    x = rand() % 100 + 1;

    printf("What's your name :");
    scanf("%s", &name);
    printf("Hello!! %s\n", name);
    printf("Guess the number : ");
    scanf(" %d", &number);
    do {
        count++;
        if (x > number) {
            printf("This is your count : %d\n",count);
            printf("The number is higher\n");
        } else
        if (x < number) {
            printf("This is your count : %d\n",count);
            printf("The number is lower\n");
        } else
        if (x == number) {
            printf("\nYou're right!!, the number is %d",x);
        }
    } while (count == 10);
}



Pycharm, skips function

import time
import random

print('''What Would You Like To Do?
1) Generate New Key
2) Check Key Validation''')

question1 = int(input( ))

if question1 == 1:
    genvalues = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'


    def main():
        outfile = open('keys.txt', 'w')

        print('GENERATING NEW KEYS RESETS OLD KEYS')
        time.sleep(10)
        x = 0
        y = int(input('How Many keys would you like:   '))
        while True:
            x += 1

            keys = f'{random.choices(genvalues, k=5)}-{random.choices(genvalues, k=5)}-{random.choices(genvalues, k=5)}'
            keys2 = keys.replace("'", "")
            keys3 = keys2.replace(",", "")
            keys4 = keys3.replace("[", "")
            keys5 = keys4.replace("]", "")
            print(keys5)
            outfile.write(keys5 + '\n')

            if x == y:
                timesleep = y * 15
                print('You Have', timesleep, ' Seconds Until You Have To Create A New Key')
                time.sleep(timesleep)
                print('\n' * 100)
                outfile.close( )
                break

elif question1 == 2:

    def check():

        keys = {}
        with open('keys.txt', 'r') as file:
            for line in file:
                line = line.split( )
                keys.update({line[0]: line[1]})
        while True:
            serialkey = input('Enter Serial Key:   ')
            if serialkey not in keys:
                print('Invalid')
            else:
                print('Success')



vendredi 27 mai 2022

a Type which statisfy Object that unlimited random keyName with different value format

I need a Type which statisfy Object that has a firstName proptery , value format is string, has a lastName proptery , value format is string, other random keyName ,value format is string[ ],

const personA = {
 firstName:"Bob" //alwways exist, 
 lastName:"Tom", //alwways exist
 hobbies:["cooking","singing","dancing"] //not always exist in an object instant
 ableToSpeak:["english","japaneses"]
//...other random keyName with value of string[]
}

const personB = {
 firstName:"Jim"
 lastName:"kATE",
 food:["cake","apple","rice"]
 //...other random keyName  with value of string[]
}

The following is not working, firstName and [keyName] are conflict

type HumanType {
  [keyName: string]: string[],
  firstName:string
  lastName:string
}

Property 'firstName' of type 'string' is not assignable to 'string' index type 'string[]'.




Randomly draw a sample for 2 columns

A well known function for this in Python is random.sample()

However, my dataset consist of multiple columns, and i need the 'lat' and 'lng' coordinates to be sampled. As these two are related, i cannot use the random.sample() separately to get some random lat coordinates + some non corresponding lng coordinates.

What would be the most elegant solution for this?

Perhaps first making a third column, in which i combine lat&lng Then sample Then unmerge?

If so, how should i do this, the fact that both lat and lng values are floats with different lengts doesn't make it easier. Probably by adding a'-' in between?




jeudi 26 mai 2022

Write a for loop to create 5 randomly generated dataframes of length 100,200,500,800, and 1000, and print each of the dataframes

I've been trying to work through this small R prompt, but can't figure out what I'm doing wrong. I haven't used R in a few years, so I'm trying to get back into the flow of things. Here's my code:

y <- 5
loopValues <- c(100,200,500,800,1000)
dataframesq3 <- vector("list", y)

for (i in 1:y) {
  for (j in loopValues){
    dataframesq3[[i]] <- data.frame(replicate(10,sample(0:1,j,rep=TRUE)))
    }   
}

print(dataframesq3)

Currently, I get 5 data frames with 10 columns each and 1000 rows each instead of one of reach of the 5 above links.




How to make a random video play on a page without repeating?

I already made the video randomly play, but I need it not to repeat. Here is the code

function refreshbutton(){
var count = Math.floor(Math.random() * videos.length);
document.getElementsByTagName('source')[0].src = "./video/" + videos[count];video.load();}
var videos= ["video1.mp4","video2.mp4","video3.mp4"];



Randomly pick one cell from each column and concatenate the result

If anyone can help me with this - that would be amaze

I have 4 columns of words (A B C D) and would like to create a formula to pick a random cell from each column and concatenate the resulting 4 words into one cell

I am using this idea to create new 'nonsense' fun words by combining them randomly!

Thanks!!




Resolving potential false negative C6385 Error in C++

This question is most likely common and has been asked before. So, after spending a mind-numbing 30 minutes trying to find the solution to what I believe is a false negative, I'm resulting to posting my issue here.

I'm relatively new to C++ Coding and figured I'd create a simple random item generator. Unfortunately, when grasping a random index in my arrays, I am given a c6385 error. This error usually pertains to an invalid or overloaded buffer from the research I've found. I believe this means that the index I'm trying to access is too large thanks to rand().

I will continue looking for a solution but would like some others' opinions of the situation. I may be overlooking a small detail or am failing to grasp a concept. All help is greatly appreciated. If I come across a solution, I will lock/remove this to overpopulate the forums.

Here is my code: ItemGeneration.h

#pragma once
#include <random>
#include <iostream>
using namespace std;

class ItemGeneration
{
public:
    /*
        Creating the cosntant variables for the items main effects.
        For instance, if you were to roll the main attribute of "Item1",
        this code would dictate what possible attributes that could be chosen.

        In addition to the main attributes, the code for the avaliable sub-attributes is also created below.

        Also creating the const array that hold the rarity of items.
        For instance, an item that rolls a higher weighted value will have a lower rating.
        More rare or 'uncommon' the value, the higher rating the item will recieve.
        Item rarity dictates the value of the attributes assigned to ie, i.e the higher the
        rarity the higher the attributes multiplier in addition to the number of sub-attributes.
    */

    const char* Item1[4]
        = { "Attack %", "Health %", "Defense %", "Elemental Damage %" };

    const char* Item2[4]
        = { "Mana Regeneration", "Cooldown Reduction", "Healing Efficacy", "Elemental Resonance" };

    const char* Item3[4]
        = { "Raw Attack", "Raw Health", "Raw Defense", "Raw Elemental Damage" };

    const char* Item4[4]
        = { "Elemental Resonance", "Critical Chance", "Critical Multiplier", "Mana Regeneration" };

    const char* Item5[4]
        = { "Elemental Damage %", "Critial Chance", "Critical Multiplier", "Cooldown Reduction" };

    const char* SubAttributeList[10]
        = { "Raw Attack", "Raw Health", "Raw Defense", "Raw Elemental Damage", "Elemental Damage %",
            "Elemental Resonance", "Mana Regeneration", "Cooldown Reduction", "Critical Chance", "Critical Multiplier" };

    const char* RarityChart[6]
        = { "Common", "Uncommon", "Rare", "Unique", "Legendary", "Mythical" };

    const int InventoryLimit = 256;
    int InventorySize = 0;

    int ItemCreate(int x, int y) {

        int randNum = rand() % 4 + 1;

        if (InventorySize < InventoryLimit) {
            switch (x) {
            case 1:
                cout << "You have generated an Item1! Here are the resulting attributes:" << endl;
                cout << "Main Attribute: " << Item1[randNum] << endl;
                cout << "Sub-Atrributes: " << endl;
                break;

            case 2:
                cout << "You have generated an Item2! Here are the resulting attributes:" << endl;
                cout << "Main Attribute: " << Item2[randNum] << endl;
                cout << "Sub-Atrributes: " << endl;
                break;

            case 3:
                cout << "You have generated an Item3! Here are the resulting attributes:" << endl;
                cout << "Main Attribute: " << Item3[randNum] << endl;
                cout << "Sub-Atrributes: " << endl;
                break;

            case 4:
                cout << "You have generated an Item4! Here are the resulting attributes:" << endl;
                cout << "Main Attribute: " << Item4[randNum] << endl;
                cout << "Sub-Atrributes: " << endl;
                break;

            case 5:
                cout << "You have generated an Item5! Here are the resulting attributes:" << endl;
                cout << "Main Attribute: " << Item5[randNum] << endl;
                cout << "Sub-Atrributes: " << endl;
                break;

            default:
                cout << "They item you tried to generate doesn't seem to exist.\nPlease enter a number between 1 and 5 to generate a random item." << endl;

            }
        }
        else {
            cout << "Sorry, your inventory is too full\nPlease clear some space before attempting to create another item." << endl;
        }
    }
};

Source.cpp

#include <iostream>
#include "ItemGeneration.h"
using namespace std;

int main() {
    int x, y;

    cout << "Welcome to the random item generator!" <<
        "\nPlease enter a number between 1 and 5, " <<
        "\nfollowed by a number between 1 and 10 to select its rarity, " <<
        "\nto receive your own randomly generated item.\n" << endl;

    cin >> x;
    cin >> y;

    ItemGeneration item;
    item.ItemCreate(x, y);
    return;
}

** Update with errors **

I should have been more concise. However, I do not believe there to be an actual buffer error, a false negative. As for the error messages.

My main function is returning a c2561 error, but I believe that to be a side effect of the item generation, not functioning. MEaning it simply is returning the value as the function isn't operating. Here is my terminal readout when attempting to build the solution:

Build started...
1>------ Build started: Project: RandomItemGenerator, Configuration: Debug x64 ------
1>ItemGeneration.cpp
1>Source.cpp
1>C:\Users\Alex\source\repos\RandomItemGenerator\RandomItemGenerator\Source.cpp(18,2): error C2561: 'main': function must return a value
1>C:\Users\Alex\source\repos\RandomItemGenerator\RandomItemGenerator\Source.cpp(5): message : see declaration of 'main'
1>Generating Code...
1>Done building project "RandomItemGenerator.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

The quick solution error description:

(const char [17]) "Main Attribute: "
C6385: Reding Invalid Data from 'this->item5'.



mercredi 25 mai 2022

Forking a random number generator deterministically?

I'm using std::mt19937 to produce deterministic random numbers. I'd like to pass it to functions so I can control their source of randomness. I could do int foo(std::mt19937& rng);, but I want to call foo and bar in parallel, so that won't work. Even if I put the generation function behind a mutex (so each call to operator() did std::lock_guard lock(mutex); return rng();), calling foo and bar in parallel wouldn't be deterministic due to the race on the mutex.

I feel like conceptually I should be able to do this:

auto fooRNG = std::mt19937(rng()); // Seed a RNG with the output of `rng`.
auto barRNG = std::mt19937(rng());
parallel_invoke([&] { fooResult = foo(fooRNG); },
                [&] { barResult = bar(barRNG); });

where I "fork" rng into two new ones with different seeds. Since fooRNG and barRNG are seeded deterministically, they should be random and independent.

  1. Is this general gist viable?
  2. Is this particular implementation sufficient (I doubt it)?

Extended question: Suppose I want to call baz(int n, std::mt19937&) massively in parallel over a range of indexed values, something like

auto seed = rng();
parallel_for(range(0, 1 << 20),
             [&](int i) {
    auto thisRNG = std::mt19937(seed ^ i); // Deterministically set up RNGs in parallel?
    baz(i, thisRng);

});

something like that should work, right? That is, provided we give it enough bits of state?




How do I prevent a duplicate random number when using setInterval? (javascript)

I've been wanting to generate random numbers through a function and then use setInterval to repeat that function and give me a new number every time.

function randNum(prevNum) { 
    let randNum = Math.round(Math.random() * 12)     //choose a number between 0 and 12 
    while (randNum == prevNum){                //if the chosen number is the same as prevNum, choose another random number
        randColor = Math.round(Math.random() * 12) 
    }
    prevNum = randColor            //assign current value to parameter 
    return (prevNum);              //return parameter
}


prevNum = 0,
prevNum = setInterval (randNum, 1000, prevNum)     //assign returned parameter to current variable, then go back into the function with the new parameter value.

also using node so semicolons might be missing.




Batch script to download file with random numbers in filename

I need to make a batch script that can downloads a file with random names like this:

file_123456_2022-05-25.txt file_654321_2022-05-25.txt file_888888_2022-05-25.txt

file_159753_2022-05-26.txt file_357159_2022-05-26.txt file_147896_2022-05-26.txt

and so on...

I'm using batch file like this:

@echo off

    setlocal enableextensions disabledelayedexpansion

    for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a" 
    set "td.YY=%dt:~2,2%" 
    set "td.YYYY=%dt:~0,4%"
    set "td.MM=%dt:~4,2%"
    set "td.DD=%dt:~6,2%"

    rem Remove padding from date elements and increase day
    set /a "y=%td.YYYY%", "m=100%td.MM% %% 100", "d=(100%td.DD% %% 100)+1" 
    rem Calculate month length
    set /a "ml=30+((m+m/8) %% 2)" & if %m% equ 2 set /a "ml=ml-2+(3-y %% 4)/3-(99-y %% 100)/99+(399-y %% 400)/399"
    rem Adjust day / month / year for tomorrow date
    if %d% gtr %ml% set /a "d=1", "m=(m %% 12)+1", "y+=(%m%/12)"

    rem Pad date elements and set tomorrow variables
    set /a "m+=100", "d+=100"

    set "tm.YYYY=%y%"
    set "tm.YY=%y:~-2%"
    set "tm.MM=%m:~-2%"
    set "tm.DD=%d:~-2%"

    echo Today   : %td.YYYY%-%td.MM%-%td.DD%.txt
    echo Tomorrow: %tm.YYYY%-%tm.MM%-%tm.DD%.txt
 
echo download starting up

timeout 3
M:\Task-Scheduler\WGet\wget https://www.mywebserver.com/file_%td.YYYY%-%td.MM%-%td.DD%.txt

this code can download files with dynamic date but not with dynamic numbers! I need to download something like this: M:\Task-Scheduler\WGet\wget https://www.mywebserver.com/file_******_%td.YYYY%-%td.MM%-%td.DD%.txt

How can I solve this?

Tnx in advance




mardi 24 mai 2022

What code in c++ can shuffle and then randomly assign 10 cards [closed]

I know I need to use the srand function, but how do I connect the randomly assigned numbers to the card's type and system




How to do mysql subquery to get random records from pre-filtered list?

I searched but couldn't find a solution that works. Need a bit help here.

Let's say I have a table with more than 100 records, first, I need to find out top 20 records in certain order, then I need to pick 5 randomly from those 20 records. Here is my query,

SELECT a 
FROM tableA 
WHERE b IN (
    SELECT b 
    FROM tableA 
    WHERE c="x" 
    ORDER BY d DESC 
    LIMIT 20
) 
ORDER BY RAND() 
LIMIT 5;

Let me know how to correct it. Thanks.




I need help writing a simple code...in python [closed]

I’m needing help with python coding. Goal is for

  • Generating a random list of 26 alphabet
  • Reading the generated list and making a decision based on the position of the list.

(Checking if position 1 is A.. if not … is position 2 A? And so forth.




How to generate a random number in the entire binary64 range

I am wondering how to generate a random double number inside the entire double range in Python, so that the order of magnitude of the number (math.log10) has an equal chance to be any of the possible magnitudes (range(-307, 309)).

I tried the following code but it does not give intended result:

from random import random, uniform
from collections import Counter
import math
import sys

random_numbers = [random()/random() for i in range(2048)]

count = Counter([int(math.log10(i)) for i in random_numbers])

print(count.most_common())

uniform_numbers = [uniform(sys.float_info.min, sys.float_info.max) for i in range(2048)]

count1 = Counter([int(math.log10(i)) for i in uniform_numbers])

print(count1.most_common())
[(0, 1862), (1, 93), (-1, 68), (2, 14), (-2, 10), (3, 1)] 
[(307, 1055), (308, 888), (306, 95), (305, 10)]



Доброго времени суток, необходимо сгенерировать случайное значение

Задача проста, но я не понимаю что не так. Рандомное значение генерируется только в первый раз, потом оно не изменяется.

class MainActivity : AppCompatActivity()
{
    lateinit var binding: ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val textValueRandom = "${Random.nextInt(100)}"
        binding.randomTextView.text = textValueRandom
    }
}



lundi 23 mai 2022

how do I generate random group names using lists

I can not figure out my mistake. Can someone help me?

We are supposed to create the lists outside of the function. then create an empty list inside a function. We should return 9 different names.

    first_names = ["Gabriel", "Reinhard", "Siebren"]
    last_names = ["Colomar", "Chase", "Vaswani"]

    def name_generator(first_names, last_names):
        full_name= ()

    import random

    for _ in range(9):
        full_name=random.choice(first_names)+" "+random.choice(last_names)
        full_name.append(full_name)
    group_string = ", ".join(full_name) 



Why is python random.seed is not deterministic when passed a non-integer?

The following code on Python 3.8 always returns 18 (I've tried this on 3 different machines):

import random
random.seed(1)
random.randint(1, 100)

However, calling seed with a non-integer Python 3.8 is semi-nondeterministic:

import random
from datetime import date
random.seed(date(2022, 5, 18))
random.randint(1, 100)

I say semi-nondeterministic because if I run the code multiple times within the same Python terminal, I get the same random number. However, but if I restart the Python terminal, I get a different number.

Clearly it's not using id of the object, since that changes every time I make a new date object so I wouldn't get the same result within a Python terminal.

It's also not using hash, since the following (probably) give different results:

random.seed(date(2022, 5, 18))
random.randint(1, 100)

random.seed(hash(date(2022, 5, 18)))
random.randint(1, 100)

What, then, is going on?




Python random random function providing correct output for an integer with specific length as 3 [duplicate]

Sometimes when I try to run the below line in my code, it is provides a 2 digit integer. Any changes that I need to make in the below line for it show me the correct length integers all the time.

random_int = random.randrange(0,999,3)




dimanche 22 mai 2022

How do i generate a random question using javascript for my quiz app which doesn't repeat the same question

I am trying to generate random questions from my "questions" object which does not repeat it's self but my quiz app is repeating questions.

Please forgive me if my question is not clear enough. This is my first ever time asking a question or really using stack overfolow,

let selectedQuestions = [];
  
//creates random index between 0 and the length of any array passed into it
const getRandomIndex = (arr) => Math.floor(Math.random() * arr.length);

//uses getRandomIndex to generate select a random object from and array. Also checks to see if the random object has been selected, if not, pushes the question to the empty selectedQuestions array and if selected, loops through its own function with a recursion by calling itself until it finds a question that has not already been pushed to the selectedQuestions array.
const getRandomObject = (arr) => {
  const random = getRandomIndex(arr);
  if (selectedQuestions.includes(random)) {
    getRandomObject(arr);
  }
  selectedQuestions.push(random);
  console.log("selected questions:", selectedQuestions.length)
  return arr[random];

//renders the selected array and questions in the correct section of the quiz board.
const randomGenerator = () => {
  const data = getRandomObject(questions);
  progress.textContent = `Question ${gameState.questionCounter} of ${maxQuestion}`
  questionBoard.textContent = `Q${gameState.questionCounter}. ${data.question}`;
  currentCorrectAnswer = data.answer;
  userAnswer.forEach((answer, index) => {
    answer.innerHTML = `${alphabet[index]}. ${data.choices[index]}`;
  });
  currentUserAnswer = null;
  clearAll()

  gameState.questionCounter++
  nextBtn.disabled = true;

  setDisabledStateForQuizAnswers(false);
}



Use a random number to render that corresponding object ID's data in React

I'm trying to create an react app where you press a button and it gives you a date night option and a corresponding image. I created a small array of objects within dates.js ex:

export const dates = [
    {
        id: 0,
        name: "Comedy Club",
        image: "/assets/images/comic.jpg",   
    },
    {
        id: 1,
        name:"Piano Bar ",
        image: "/assets/images/piano-bar.jpg",
    }, 

Then I created a GetDates.js to use the random method & corresponding onclick event. Below is where I'm stuck. I've changed this code 100 times based on various previous answers and youtube tutorials but I receive errors or they are not exactly what I'm trying to render. Can you please let me know from this last update what is needed to display the dates.name & dates.image based on the randomId method used below? Again, I've altered this so much from my original attempt that I'm not sure this is the best approach. Any advice would be greatly appreciated!

class GetDates extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "",
      image: "",
    };
  }

  randomSelect() {
    const randomId = dates[Math.floor(Math.random() * dates.length)].id;
    this.setState({ ...this.props.dates[randomId] });
  }

  render() {
    return (
      <div className="results-container">
        <button className="date-btn" onclick={this.randomSelect}>
          GET DATE IDEAS!
        </button>
      </div>
    );
  }
}

export default GetDates;



Randome background for elementor

I use Elementor pro in my site. I have big Background image in top of my homepage that I have many elements in that section. I want to have one random image from a group of images (can be in gallery or in folder). but i didn't fine any solution.

I tried any addon for elementor. elementor pro background slidet, the plus row background, and etc. but they only make a slides with default order and don't have random order. I also tried some slider plugin or elementor's slider addons (smart slider,...). but the elements that should be on the image (other than text and buttons) could not be added to them.

I tried some javascripts to do it (for example: https://element.how/elementor-slider-random/#comment-12854 and this: Random background image on refresh). but it didn't work.

I like to know there is any solution to use custom php code to elementor dynamic simple background image that apply all background setting?

is there any solution?




Can I make random.choice to run only 1 option until it is False? [closed]

I want to use random.choice statement to choose 1 option and run it until it is False, but I have no idea how can i do that or if it is possible.

code:

aa = movemouse(1534,792)
bbb = movemouse(1544,800)
cc = movemouse(1556,801)

while reset:
    if a != None:
        random.choice(aa,bbb,cc)
        escape()
    if a == None:
        kibord()
    elif b != None:
        rest()
        reset = False
        if b == None:
            reset = True



Python tetris input delay gets exponentially longer

import turtle
import random

wn = turtle.Screen()
tetris = turtle.Turtle()
wn.tracer(0)
grid = []
tetriminos = ['t','l','j','i','s','z','o']

class square():
    def __init__(self, falling, block, color):
        self.falling = falling
        self.block = block
        self.color = color
for i in range(12):
    grid.append([])
for i in range(12):
    for j in range(25):
        grid[i].append(square(False, False, 'gray'))

def gridsquare(color):
    tetris.setheading(0)
    tetris.color(color)
    tetris.begin_fill()
    for i in range(4):
        tetris.forward(20)
        tetris.right(90)
    tetris.end_fill()
    tetris.color('black')

def refreshGrid():
    for i in range(12):
        for j in range(25):
            tetris.pu()
            tetris.goto(i * 20 - 120, j * 20 - 250)
            tetris.pd()
            if grid[i][j].block == True:
                gridsquare(grid[i][j].color)
            elif grid[i][j].falling == True:
                gridsquare('green')
            else:
                gridsquare('gray')
    wn.update()

def left():
    ok = True
    for i in range(12):
        for j in range(25):
            if grid[i][j].falling == True:
                if grid[i - 1][j].block == True:
                    ok = False
    if ok == True:
        for i in range(12):
            for j in range(25):
                if grid[i][j].falling == True:
                    grid[i][j].falling = False
                    grid[i - 1][j].falling = True
        refreshGrid()

def right():
    ok = True
    for i in range(12):
        for j in range(25):
            if grid[i][j].falling == True:
                if grid[i + 1][j].block == True:
                    ok = False
    if ok == True:
        for i in range(12):
            for j in range(25):
                if grid[11 - i][j].falling == True:
                    grid[11 - i][j].falling = False
                    grid[11 - i + 1][j].falling = True
        refreshGrid()

def down():
    ok = True
    for i in range(12):
        for j in range(25):
            if grid[i][j].falling == True:
                if grid[i][j - 1].block == True:
                    ok = False
    if ok == True:
        for i in range(12):
            for j in range(25):
                if grid[i][j].falling == True:
                    grid[i][j].falling = False
                    grid[i][j - 1].falling = True
        refreshGrid()
    else:
        for i in range(12):
            for j in range(25):
                if grid[i][j].falling == True:
                    grid[i][j].falling = False
                    grid[i][j].block = True
                    grid[i][j].color = 'blue'
        refreshGrid()
        newTetrimino()

def newTetrimino():
    tet = tetriminos[random.randint(0, 6)]
    #'t','l','j','i','s','z','o'
    #middle top - 5, 24
    if tet == 'z':
        grid[5][24].falling = True
        grid[5][23].falling = True
        grid[4][24].falling = True
        grid[6][23].falling = True
    elif tet == 's':
        grid[5][24].falling = True
        grid[5][23].falling = True
        grid[4][23].falling = True
        grid[6][24].falling = True
    elif tet == 't':
        grid[5][23].falling = True
        grid[4][23].falling = True
        grid[6][23].falling = True
        grid[5][24].falling = True
    elif tet == 'l':
        grid[5][23].falling = True
        grid[4][23].falling = True
        grid[6][23].falling = True
        grid[6][24].falling = True
    elif tet == 'j':
        grid[5][23].falling = True
        grid[4][23].falling = True
        grid[6][23].falling = True
        grid[4][24].falling = True
    elif tet == 'i':
        grid[5][24].falling = True
        grid[4][24].falling = True
        grid[6][24].falling = True
        grid[7][24].falling = True
    elif tet == 'o':
        grid[6][24].falling = True
        grid[7][24].falling = True
        grid[6][23].falling = True
        grid[7][23].falling = True
    refreshGrid()

grid[5][23].falling = True
grid[4][23].falling = True
grid[6][23].falling = True
grid[5][24].falling = True
for i in range(25):
    grid[0][i].block = True
    grid[0][i].color = 'black'
for i in range(25):
    grid[11][i].block = True
    grid[11][i].color = 'black'
for i in range(12):
    grid[i][0].block = True
    grid[i][0].color = 'black'

refreshGrid()
wn.listen()
wn.onkeypress(left,'a')
wn.onkeypress(right,'d')
wn.onkeypress(down,'s')
wn.mainloop()

Ok so Sorry for long code I'm trying to code tetris and i have the basics down but for some reason each tetrimino you place, it gets exponentially longer input delay I expect a little bit of input delay because of how much it has to check but i don't see why there gets more after each placement

help would be appreciated a lot

Also I am very much a beginner so please explain it as if I was an old grandma thanks




Import "pynput.keyboard" could not be resolved from source Pylance (reportMissingImports)

I am trying to write some code that essentially types a random 5 character word. I can't get pynput.keyboard to work as I keep getting the same error message (Import "pynput.keyboard" could not be resolved from source) my code:

from pynput.keyboard import Key,Controller
keyboard = Controller()
from random import randrange
import time


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 = []

for i in range(5):
    x = randrange(1,26)
    #rint(x)
    l1 = alphabet[x-1]
    #print(l1)
    word.append(l1)

y = ''.join(word)
time.wait(5)
keyboard.press(y)
keyboard.release(y)

I already did

pip3 install pynput

My problem seems to be similar to this one that I found. https://www.reddit.com/r/learnpython/comments/jqepj8/i_think_python_hates_me_import_pynputmouse_could/




samedi 21 mai 2022

Generate new order of numbers from array

I'm currently trying to generate a new order of numbers from a current array with numbers from 1 - 10.

For example, I have arrary like this:

data = [
    {
        0: 1,
        1: 2,
        2: 3,
        3: 4,
        4: 5,
        5: 6
    },
    {
        0: 1,
        1: 2,
        2: 3,
        3: 4,
        4: 5,
        5: 8
    }
]

And i'm trying to generate a new order from this array from numbers from 1 - 10.

For example: I want it to generate a new order like this:

    0: 1,
    1: 2,
    2: 3,
    3: 4,
    4: 5,
    5: 7 (The new number)

Where it checks the order of the array, and make a new order with numbers from 1 - 10




I want to add random numbers to my renaming script

Im very new to JS and node. I want to edit a bunch of files at once. This works great. But how can I change one of the lines to a random number...

My code looks like this:

const fs = require("fs");
const args = process.argv.slice(2);
const inputFolder = args[0];
const dir = `${__dirname}/${inputFolder}/`;
const inputFiles = fs.readdirSync(dir).sort();



inputFiles.forEach((file) => {
let id = file.split(".").shift();
let data = JSON.parse(fs.readFileSync(`${dir}/${file}`));

data.name = `Crypto Jackpot Golden Ticket #${id}`;
data.image = `ipfs://QmcDuio2fvEtRmukuTc6yZuh3cyfezX9DqujgduUuSfYLJ/${id}.png`;
data.description = `Hold this NFT to be included in weekly jackpots with 3 entries`;


fs.writeFileSync(`${dir}/${file}`, JSON.stringify(data, null, 2));
console.log(data);
});

Under data.descrition I want to edit a field called "DNA" so I would put: data.DNA = //BUT WHAT GOES HERE TO MAKE THIS A RANDOM NUMBER

Thanks in advance!!!




How to limit random binary generation with a for-loop? (More details in question, including code)

I am trying to make a simple C# console application that generates random binary code. The binary generation works fine, but I'm trying to limit it using a for-loop. However, this doesn't work. The application generates infinite binary code, so I don't know what I'm doing wrong. Please help! From my knowledge, the for-loop should only generate 5 random binary digits. Code:

using System;
using System.Collections.Generic;

public class BinaryGen
{
    public static void Main()
    {
        Random rnd = new Random();
        for (int i = 0; i < 5; i++)
        {
            i = rnd.Next(0, 2);
            Console.WriteLine(i);
        }
    }
}



This code I found on the internet please explain it to me? especially the def main() [closed]

import time

import pygame

import pygame.freetype

import random

Global instances

# color 
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (187, 238, 255)
PURPLE = (192, 204, 255)

# create window 
WIN = pygame.display.set_mode((640, 480))

Class Screen that shows everything that displays on the screen Why need return None


# Show the layout of screen 
class Screen: 
 
    Font = None
    def __init__(self, next_screen, *text):
        self.background = pygame.Surface((640, 480))  
        self.background.fill(BLUE)  

        y = 80
        if text:
            Screen.Font = pygame.freetype.SysFont('times', 32)  
            for line in text:
                Screen.Font.render_to(self.background, (120, y), line, BLACK)  
                y += 50  

        self.next_screen = next_screen
        self.add_text = None

    def start(self, text):
        self.add_text = text

    def draw(self):
        WIN.blit(self.background, (0, 0))  
        if self.add_text:
            y = 180
            for line in self.add_text:
                Screen.Font.render_to(WIN, (120, y), line, BLACK)
                y += 50
    
# Why need return None 
    def update(self, events):
        for event in events:
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:  
                    return self.next_screen, None

Layout of frames on the screen Create the frames to put answers inside Check the position of the mouse

class SettingScreen:  

    def __init__(self):
        self.background = pygame.Surface((640, 480))
        self.background.fill(BLUE)

        Screen.Font.render_to(self.background, (120, 50), 'Select your difficulty level', BLACK)

        self.rects = []
        x = 120
        y = 120

# Create the frames to put answers inside 
        for i in range(4):  
            rect = pygame.Rect(x, y, 80, 80)  
            self.rects.append(rect)  
            x += 100

# Is this necessary 
    def start(self, *args): 
        pass

    def draw(self):
        WIN.blit(self.background, (0, 0))
        n = 1

# Check the position of the mouse 
        for rect in self.rects:  
            if rect.collidepoint(pygame.mouse.get_pos()):  
                pygame.draw.rect(WIN, PURPLE, rect)
            pygame.draw.rect(WIN, PURPLE, rect, 5)  
            Screen.Font.render_to(WIN, (rect.x + 30, rect.y + 30), str(n), BLACK)  
            n += 1  

# 'GAME' in the main() 
    def update(self, events):
        for event in events:
            if event.type == pygame.MOUSEBUTTONDOWN:  
                for rect in self.rects:
                    if rect.collidepoint(event.pos):
                        return 'GAME', Level()

Level that changes every time player chooses answer time.sleep to make sure not to choose 2 answers continuity The screen that show your results

# Change the screen every time choose the answer 
class Level:  

    def __init__(self):
        self.questions = [
            ('Find x: (5-x) + (6+x) = 11', 3),
            ('Find x: 4(x+7) + 11(x-2) -3 = 0', 2),
            ('Find the missing number 1357986_2', 4),
            ('1 x1 = ? ', 1)
        ]
        self.current_question = None
        self.background = None
        self.right = 0
        self.wrong = 0

    def pop_question(self):
        ques = random.choice(self.questions)  
        self.questions.remove(ques)  
        self.current_question = ques  
        return ques

# time.sleep to make sure not to choose 2 answer continuity 
    def answer(self, answer):
        if answer == self.current_question[1]:  
            time.sleep(0.5)     
            self.right += 1
        else:
            time.sleep(0.5)
            self.wrong += 1

# Screen that show your results 
    def get_result(self):
        return f'{self.right} answers correct', f'{self.wrong} answers wrong', '', 'Good!' \
            if self.right > self.wrong else 'You can do better!'

Start the Game Play and stop if there are no more questions What 'GAME' and 'RESULT' doing


# start the game

class GamePlay(Level):

    def __init__(self):
        super().__init__()
        self.rects = []
        x = 120
        y = 120

        for n in range(4):  
            rect = pygame.Rect(x, y, 400, 80)
            self.rects.append(rect)
            y += 90

        self.game_level = None

    def start(self, game_level):
        self.background = pygame.Surface((640, 480))
        self.background.fill(BLUE)
        self.game_level = game_level

# Why 2 Variables 
        question, answer = game_level.pop_question()  
        Screen.Font.render_to(self.background, (120, 50), question, BLACK)

    def draw(self):
        WIN.blit(self.background, (0, 0))
        n = 1
        for rect in self.rects:
            if rect.collidepoint(pygame.mouse.get_pos()):
                pygame.draw.rect(WIN, PURPLE, rect)
            pygame.draw.rect(WIN, PURPLE, rect, 5)
            Screen.Font.render_to(WIN, (rect.x + 30, rect.y + 30), str(n), BLACK)
            n += 1

    def update(self, events):
        for event in events:
            if event.type == pygame.MOUSEBUTTONDOWN:
                n = 1
                for rect in self.rects:
                    if rect.collidepoint(event.pos):
                        self.game_level.answer(n)
                        if self.game_level.questions:

                            return 'GAME', self.game_level
                        else:
                            return 'RESULT', self.game_level.get_result()
                    n += 1
# What 'GAME' and 'RESULT' doing 


main() to run the game

def main():

    pygame.init()
    clock = pygame.time.Clock()

# this new to me 
    screens = {
        'TITLE': Screen('SETTING', 'Welcome to the game', '', '', '', 'Press [Space] to start'),
        'SETTING': SettingScreen(),
        'GAME': GamePlay(),
        'RESULT': Screen('TITLE', 'Here is your result:'),
    }  



    screen = screens['TITLE']
    while True:
        clock.tick(60)
        events = pygame.event.get()
        for event in events:
            if event.type == pygame.QUIT:
                return False

        result = screen.update(events)
        if result:
            next_screen, level = result
            if next_screen:
                screen = screens[next_screen]
                screen.start(level)

        screen.draw()
        pygame.display.update()


if __name__ == '__main__':

    main()



vendredi 20 mai 2022

Random subsetting a data frame from a larger dataframe

n=100 (n=height * width) height=10 width=10 column = [1,2,3,4,5,6,7,8,9,10]
indices = [1,2,3,4,5,6,7,8,9,10]

Rack2 = pd.DataFrame(np.random.choice(np.arange(n),size=(height, width), replace=False), index=list(indices), columns=list(column))
Rack = Rack2.sort_index(ascending=False)
a = np.repeat([True,False], Rack.size//2) 
b = np.random.shuffle(a)
a = a.reshape(Rack.shape)

SI = Rack.mask(a)
RI = Rack.where(a)

StorageSet = SI.stack() 
ss=dfStorage.index

RetrievalSet = RI.stack() 
tt=D3.index

In the python code above, there is a 10x10 Rack. Half of the rack (50 items) consists of storage items and the other half consists of retrieval items. I want to do it not half of the rack size but if I have a 10x10 rack for example 30 of that data frame are storage items. 30 of the remaining 70 items are the retrieval items. How can I do this?




python random error, do they have a fix yet

Traceback (most recent call last):
  File "/Users/milena/python/vosenbMyach.py", line 1, in <module>
    import random
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/random.py", line 49, in <module>
    from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ImportError: cannot import name 'log' from 'math' (/Users/milena/python/math.py)
milena@Stevens-MBP python % 

and the code that generated it

import random

def GetAnswer(answerNumber):
    if answerNumber == 1 :
        return 'Bet on it'
    elif answerNumber == 2 :
        return 'It is certain'
    elif answerNumber == 3 :
        return 'It is decidly so'
    elif answerNumber == 4 :
        return 'Yes!'
    elif answerNumber == 5 :
        return 'Reply hazy, try again'
    elif answerNumber == 6 :
        return 'Ask again later'
    elif answerNumber == 7 :
        return 'I need more information'
    elif answerNumber == 8 :
        return 'Concentarate!  Try Again!'
    elif answerNumber == 9 :
        return 'My reply is No!'
    elif answerNumber == 10 :
        return 'Outlook is not so goog'
    elif answerNumber == 11 :
        return 'Very Doubtful'
    elif answerNumber == 12 :
        return 'Pray'

print(GetAnswer(random.randint(1,12)))

Do I have to reinstall, did I do a screw up?




Combining the Results of Several Loops Together

I wrote the following code that generates a single random number, subtracts this random number from some constant, records this result - and then repeats this process 100 times:

# 1 random number

results <- list()
for (i in 1:100) {

    iteration = i
    number_i_1 = mean(rnorm(1,10,2))
    difference_i_1 = 10 - number_i_1
 
    results_tmp = data.frame(iteration, number_i_1, difference_i_1)

    results[[i]] <- results_tmp
}

results_df_1 <- do.call(rbind.data.frame, results)

To do this for 2 random numbers and 3 random numbers - the above code only needs to be slightly modified:

# 2 random numbers

results <- list()
for (i in 1:100) {

    iteration = i
    number_i_2 = mean(rnorm(2,10,2))
    difference_i_2 = 10 - number_i_2
 
    results_tmp = data.frame( number_i_2, difference_i_2)

    results[[i]] <- results_tmp
}
results_df_2 <- do.call(rbind.data.frame, results)

# 3 random numbers

results <- list()
for (i in 1:100) {

    iteration = i
    number_i_3 = mean(rnorm(3,10,2))
    difference_i_3 = 10 - number_i_3
 
    results_tmp = data.frame( number_i_3, difference_i_3)

    results[[i]] <- results_tmp
}
results_df_3 <- do.call(rbind.data.frame, results)

My Question: I would like to repeat this general process 20 times and store all the results in a single data frame. For example (note: the actual data frame would have 20 pairs of such columns):

final_frame = cbind(results_df_1 , results_df_2, results_df_3)

  iteration number_i_1 difference_i_1 number_i_2 difference_i_2 number_i_3 difference_i_3
1         1  12.534059     -2.5340585   9.623655      0.3763455   9.327020     0.67298023
2         2   9.893728      0.1062721  10.135650     -0.1356502  10.037904    -0.03790384
3         3   8.895232      1.1047680   9.848402      0.1515981   7.588531     2.41146943
4         4  11.648550     -1.6485504   8.509288      1.4907120  10.294153    -0.29415334
5         5   9.045034      0.9549660   9.351834      0.6481655  11.084067    -1.08406691
6         6   9.230139      0.7698612   8.163164      1.8368356   7.846356     2.15364367

And then make two mean files (note: each of these two files would also have 20 rows):

mean_numbers = data_frame(iterations = c(1:3), mean_number = c(mean(final_frame$number_i_1),mean(final_frame$number_i_2), mean(final_frame$number_i_3) ) )

mean_differences = data_frame(iterations = c(1:3), mean_differences = c(mean(final_frame$difference_i_1),mean(final_frame$difference_i_1), mean(final_frame$difference_i_1) ) )

Can someone please show me how to do this?




Choosing random items iteratively from a dataframe

I want to generate a 10x10(100 items) data frame which represents a Rack. For example, 40 items of this data frame are filled with storage items and 40 of the remaining 60 items are with retrieval items. I want to do random choosing these 40 items and say that they are stored and others are retrieval. How can I randomly choose?




Is numpy rng thread safe?

I implemented a function that uses the numpy random generator to simulate some process. Here is a minimal example of such a function:

def thread_func(cnt, gen):
    s = 0.0
    for _ in range(cnt):
        s += gen.integers(6)
    return s

Now I wrote a function that uses python's starmap to call the thread_func. If I were to write it like this (passing the same rng reference to all threads):

def evaluate(total_cnt, thread_cnt):
    gen = np.random.default_rng()
    cnt_per_thread = total_cnt // thread_cnt
    with Pool(thread_cnt) as p:
        vals = p.starmap(thread_func, [(cnt_per_thread,gen) for _ in range(thread_cnt)])
    return vals

The result of evaluate(100000, 5) is an array of 5 same values, for example:

[49870.0, 49870.0, 49870.0, 49870.0, 49870.0]

However if I pass a different rng to all threads, for example by doing:

vals = p.starmap(thread_func, [(cnt_per_thread,np.random.default_rng()) for _ in range(thread_cnt)])

I get the expected result (5 different values), for example:

[49880.0, 49474.0, 50232.0, 50038.0, 50191.0]

Why does this happen?




jeudi 19 mai 2022

print multiple random permutations

I am trying to do multiple permutations. From code:

# generate random Gaussian values
from numpy.random import seed
from numpy.random import randn
# seed random number generator
seed(1)
# generate some Gaussian values
values = randn(100)
print(values)

But now I would like to generate, for example, 20 permutations (of values). With code:

import numpy as np
import random
from itertools import permutations
result = np.random.permutation(values)
print(result)

I can only observe one permutation (or "manually" get others). I wish I had many permutations (20 or more) and so automatically calculate the Durbin-Watson statistic for each permutation (from values).

from statsmodels.stats.stattools import durbin_watson
sm.stats.durbin_watson(np.random.permutation(values))

How can I do?




Javascript Pick a random number between 4 values [closed]

I need to get a random number 3 or 5 or 7.

This is what i got so far:

let array = [3, 5, 7]
let id = Math.floor(Math.random() * 3)
console.log(array[id])

I want to know, if there are way to do this without creating an array?

Thank you.




Sample randomly within cutoff in tibble R

I have a tibble with 100 points in R, below:

preds <- tibble(x=1:100, y=seq(from=0.01,to=1,by=0.01))

And I want to randomly sample 20 observations with values less than 0.5. Currently, I can select the first 20 observations by:

number_of_likely_negatives<-20

likely_negatives <- preds %>% 
    arrange(y) %>% 
    slice(1:number_of_likely_negatives)

But how can I randomly select 20 observations with y values below 0.5?




mercredi 18 mai 2022

In Go, how do stay in a for loop, but print a different output if user guesses too high or too low

I'm trying to develop a guessing game in GO that gives the user three attempts to guess the random number correctly.

It mostly seems to work, I'm using a for loop to count the amount of lives left. If I guess the number correctly, it prints what I want:

"You guessed it!"

But the issue is, say for example, the random number is 5. If I guessed 4, it would print

"Too low"

which is correct, but in the second attempt if I was to guess 6, it would still say

"Too low"

Alternatively, if the random number was 5, and on the first attempt I guessed 6, it would print

"Too high"

If I was to guess 4 on the second attempt, it would still say

"Too high"

I think I'm getting caught in the for loop somewhere, but I don't know how to exit it without resetting the attempts count back to 3.

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    secret := getRandomNumber()
    fmt.Println(secret)

    fmt.Println("Guess the number")

    _guess := guessRandomNumber()

    for i := 3; i > 0; i-- {

        if _guess < secret {
            fmt.Println("Too low")
            fmt.Println("You have", i, "guesses left.")
        } else if _guess < secret {
            fmt.Println("Too low")
            fmt.Println("You have", i, "guesses left.")

            guessRandomNumber()
        } else if _guess > secret {
            fmt.Println("Too high")
            fmt.Println("You have", i, "guesses left.")

            guessRandomNumber()
        }

        if _guess == secret {
            fmt.Println("You guessed it!")
            i = 0
        } else if _guess < secret {
            fmt.Println("Too low")
            fmt.Println("You have", i, "guesses left.")

            guessRandomNumber()
        } else if _guess > secret {
            fmt.Println("Too high")
            fmt.Println("You have", i, "guesses left.")

            guessRandomNumber()
        }
    }

}

func getRandomNumber() int {

    rand.Seed(time.Now().UnixNano())
    return rand.Int() % 11
}

func guessRandomNumber() int {
    var guess int
    //fmt.Println("Guess again:")
    fmt.Scanf("%d", &guess)
    return guess
}

Any help would be greatly appreciated. I'm really liking GO so far.




How toMake Math.random generate number between 1 and 1000? [duplicate]

So I'm trying to figure out how to print out a random number between 1 to 1000.

I tried:

 double a = 1+ (Math.random()*1000);
            System.out.println(a);

But when I try this i get numbers with a bunch of decimals. I do not want any decimals. Anyone can help? I want to get a value like 50 or 289 or 294. I do not want to get a number like 234.5670242 or 394.220345. Help if you can. will appreciate it. Thank you.




How can I help save the planet as a programmer?

First of, I am sorry if this is an irrelevant question to ask here, but I wanted answers from real programmers !

I am studying web development in school and self teaching myself programming language such as C++ and C#.

I am questionning myself, in what field of programming will I work ? What will I do with it ?

Being in contact with people who take the planet conditions and climate change very seriously, I decided to start changing my life habits.

Now I am wondering how the programmer job could help.

So, for my question. How, as a future web developer and C++ programmer, could I help to save the planet ?




How to generate random value from enum and put it in array?

I got an enum which is filled with "items" and I want to generate one random item of the enum and put it into my inventory, which I made out of an array. The array only has room for 10 ints.

public class InventoryEnums {
    public static void main (String[] args){

    int[] inventar = new int[9] // int array mit 10 Plätzen

    enum items {
        KARTE, MONSTERBALL, MONSTERDEX, FAHRRAD, VM03, HYPERHEILER, AMRENABEERE, TOPGENESUNG, ANGEL, TOPSCHUTZ
    }



How to generate a random expiry date for a credit card?

I'm trying to make a program that generates random credit card details. I don't know how to generate a random expiry date for the card and the expiry date should be expiry>current year.

Any help is appreciated.




mardi 17 mai 2022

How to fix a random value in the rest of the codes?

I have multiple functions, the first one generates a random number, the others use the value of the first one. But I want to fix the return value of the first function and use it in the rest of my code

how can I do this without the random changes every time I call the other functions?

import random

def list():
    return [i for i in range(1, 11)]


def fun1():
    return random.choice(list())


def fun2():
    return 2 + fun1()

def fun3():
    return 4 + fun1()


print(fun2(), fun3())



SQLITE select random N rows in sql [duplicate]

I've got two tables which both have hundreds of millions of rows.

One is PAPER. Each row is unique with a column called "paper_id" as its key. The other is PFOS. Each row has two columns, "paper_id" and "field_id".

One paepr may belong to several fields.

I need to select N rows in each group grouped by field_id in PFOS then get papers in PAPER by selected paper_id.

This is my sql: select paper_id in PFOS where field_id in/= xxx order by random limit N. If possible, I could also process data with python cause I'm using sqlite3 package.

Questions

  1. How could I make it faster?
  2. When I use LIMIT(), the rows I got are less than N.Did I make a mistake in sql?

PAPER

paper_id*,title...

PFOS

paper_id,field_id

I would apprecaite it if I got you suggestions.




lundi 16 mai 2022

SQLITE select random N rows

I've got two tables which both have hundreds of millions of rows.

One is PAPER. Each row is unique with a column called "paper_id" as its key. The other is PFOS. Each row has two columns, "paper_id" and "field_id".

One paepr may belong to several fields.

I need to select N rows in each group grouped by field_id in PFOS then get papers in PAPER by selected paper_id.

This is my sql:

select paper_id in PFOS where field_id in/= xxx order by random limit N

Questions

  1. How could I make it faster?
  2. When I use LIMIT(), the rows I got are less than N.Did I make a mistake in sql?

PAPER

paper_id*,title...

PFOS

paper_id,field_id

I would apprecaite it if I got you suggestions.




Why is random.choice not giving a random answer? [closed]

I am relatively new to Python ( 3 days old ) and I was trying out a challange as per my instructor. He instructed us to prepare a game called Snake, Water and Gun ( It's basically like rock, paper, scissors ) but when I was generating a random computer choice, I was getting water everytime. Why am I getting same choice everytime and how do I fix this ? Here is the complete code.

import random
print("*****Snake Water Gun*****")
print(f"Enter the following:\n- s for Snake\n- w for Water\n- g for Gun")
hoice = ["s", "w", "g"]
cc = "Computer chose"
c = 0
u = 0
for i in range(10):
    inp = input("Enter your choice : ").lower()
    choice = random.choice(hoice)
    if inp == "s":
        if choice == "s":
            print("Computer chose Snake. Draw ! ")
        elif choice == "w":
            u += 1
            print(f"{cc} Water. You Won ! ")
        else:
            c += 1
            print(f"{cc} Gun. Computer Won ! ")
    elif inp == "w":
        if choice == "s":
            c += 1
            print(f"{cc} Snake. Computer Won ! ")
        elif choice == "w":

            print(f"{cc} Water. Draw ! ")
        else:
            u += 1
            print(f"{cc} Gun. You Won ! ")
    elif inp == "g":
        if choice == "s":
            u += 1
            print(f"{cc} Snake. You Won ! ")
        elif choice == "w":
            c += 1
            print(f"{cc} Water. Computer Won ! ")
        else:
            print(f"{cc} Gun. Draw ! ")
    else:
        print("Please enter a valid move")
        i -= 1

print(f"{u}-{c}. You won") if u > c else print(f"{u}-{c}. Computer won")



dimanche 15 mai 2022

Making the Appropriate method call?

So I'm not sure how to make the appropriate method call. I created all the following code below according to some of the stuff that I know and according to what I was asked for of the assignment. I did another assignment on assigning method calls to a main method but it was with integers not with scanner class or most of the content in this assignment. I was able to figure out most of what I needed except this. If there is anything else wrong with my code please tell me. Any help would be appreciated. This is for a class assignment. Thank you for your help. I tried this:

import java.util.*;
import java.util.Scanner;
public class Dba    {
    public static void printTicket (String name, String id, double price)
    {
        Random num = new Random();
        Scanner input = new Scanner(System.in);
          int x = 1000;
      int age;
      String space="";
      String firstResponder;
      String veteran;        
        
        System.out.println("Please enter your first name and last name, separated by a space:");
        name=input.nextLine();

        System.out.println("Are you a first responder?");
        firstResponder=input.nextLine();
        
        System.out.println("Are you a veteran?");
        veteran=input.nextLine();
        
        int randomNumber=num.nextInt(x)+1;
        
        space += name.charAt(0);
    int index=0;
    
          for(int i=0;i<name.length();i++)
      {
          if(name.charAt(i)==' ')
          {
              index=i;
              break;
          }
      }
      
        for(int i=index+1;i<name.length();i++)
      {
          space+=name.charAt(i);
      }
      
      
    
    System.out.println("Please Enter your Age: ");
    age=input.nextInt();
        if (age<3) 
        {
            price=2;
        }
        else if(age>=3 && age<=5)
        {            
            price=9;
        }
        else if(age>=6 && age<=18)
        {
            price=11;
        }
        else
        {
            price=12;
        }
        
        if(firstResponder.equals("yes") && age>18)
        {
            price=price*0.5;
            System.out.println("Because you are a first responder with over 18 years of age you get a 50% discount");
        }
        
        if(veteran.equals("yes") && age>18)
        {
            price=price*0.5;
            System.out.println("Because you are a veteran with over 18 years of age you get a 50% discount");
        }
            
        System.out.println("Welcome to APCS Carnival, " + name +"!");
        System.out.println("Your User ID is " + id);
        System.out.println("The cost of your ticket is $" + price + ".");
        System.out.println("Have a great time at the APCS Carnival today!");
   }
    
        public static void main(String[] args)
        {
        printTicket();
            

    }
}



Random videos followed by selected videos from array

I've been making a site that plays 60 random videos (without duplicates) one after the other. However, I'd like it to play certain videos after a certain amount of videos have been played. Once the selected video has been played, it then returns back to stepping through the random shuffled of videos. For example, '1,40,32,21,45,(chosen video), 59, 11,18,27,(chosen video) etc etc. It's important that the selected video's are not then included in the 60 shuffled videos. Hope that makes sense...I'm very much a beginner so any help would be much appreciated!

Thanks a lot :)

var clip = document.querySelector("#OracleVidSRC");
var video = document.querySelector("#OracleVid");
var oracleVidArray = [
"mp4s/1-£2000.mp4",
"mp4s/2-1-2.mp4",
"mp4s/3-I_love_you.mp4",
"mp4s/4-Anger.mp4",
"mp4s/5-ASMR.mp4",
"mp4s/6-Implementation.mp4",
"mp4s/7-Bird_Aria.mp4",
"mp4s/8-Birth.mp4",
"mp4s/9-Participation.mp4",
"mp4s/10-The_cafe.mp4",
"mp4s/11-Contrabasso.mp4",
"mp4s/12-A_new_friend.mp4",
"mp4s/13-Dream.mp4",
"mp4s/14-Farewell_steven.mp4",
"mp4s/15-Feldman.mp4",
"mp4s/16-Unfortunate.mp4",
"mp4s/17-Game_show.mp4",
"mp4s/18-Perseverance.mp4",
"mp4s/19-We're_going_down_to_the_river.mp4",
"mp4s/20-Hallelujah.mp4",
"mp4s/21-Help.mp4",
"mp4s/22-How_am_I_gonna_walk away_from_this.mp4",
"mp4s/23-A_lovely_way_of_putting_it.mp4",
"mp4s/24-I_am_a_conductor.mp4",
"mp4s/25-I_am_alive_and_shall_go_on.mp4",
"mp4s/26-I_need_a_man.mp4",
"mp4s/27-Introduce_the_band.mp4",
"mp4s/28-Is_it_too_late.mp4",
"mp4s/29-Let's_rock.mp4",
"mp4s/30-Positive_influence.mp4",
"mp4s/31-Misplacement.mp4",
"mp4s/32-The_opening.mp4",
"mp4s/33-One_eye_the_other_the_other_of_a_doll.mp4",
"mp4s/34-Please_let's_have_a_chat_mister_boss.mp4",
"mp4s/35-Using_initiative.mp4",
"mp4s/36-Schubert.mp4",
"mp4s/37-Slow_dance.mp4",
"mp4s/38-Stockhausen.mp4",
"mp4s/39-Stop.mp4",
"mp4s/40-The_ball.mp4",
"mp4s/41-The_concert.mp4",
"mp4s/42-The_desert.mp4",
"mp4s/43-I'm_sorry.mp4",
"mp4s/44-The_mountain.mp4",
"mp4s/45-Try.mp4",
"mp4s/46-Upon_who's_silence_stands.mp4",
"mp4s/47-We_have_to_face_it.mp4",
"mp4s/48-Webern.mp4",
"mp4s/49-The_walk_that_turned_into_a_dance.mp4",
"mp4s/50-Decision.mp4",
"mp4s/50-Individual_responsibility.mp4",
"mp4s/51-What_is_modular_synthesis?.mp4",
"mp4s/52-William_s_burroughs.mp4",
"mp4s/53-Wolf_tune.mp4",
"mp4s/54-Worlds.mp4",
"mp4s/55-Seeking_knowledge.mp4",
"mp4s/56-Anticipation.mp4",
"mp4s/57-Puccini_giacomo.mp4",
"mp4s/59-Phil.mp4",
"mp4s/60-Motivation.mp4",
"mp4s/Angel_clip.mp4",
"mp4s/Chicken_clip.mp4"


 ];



 var count = 0;


function oracleClicked() {
  let sortedRandom = ranNums[count];
  console.log (ranNums);
clip.src = oracleVidArray[sortedRandom];
count += 1;
video.style = "display: block";
video.load();





}

function shuffle(array) {
    var i = array.length,
        j = 0,
        temp;

    while (i--) {

        j = Math.floor(Math.random() * (i+1));

        // swap randomly chosen element with current element
        temp = array[i];
        array[i] = array[j];
        array[j] = temp;


    }

    return array;
}

var ranNums = shuffle([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60]);





video.addEventListener('ended', oracleClicked)



How to tune random.choice probability - python -

I made a function that randomly selects one from a list of texts.

def ttc(*arg):
    a = random.choice([*arg])
    return ''.join(a)

print(ttc("Price", "Condition", "Loan"))
print(ttc("entertainment", "geese", "Uruguay", "comedy", "butterfly"))

But I found it necessary to make certain words have a higher probability of being selected.

For example, can we change the probability of being selected sequentially from the front of the list by 50% 30% 20% like this?




samedi 14 mai 2022

Receiving same output from Math.random() function in game I'm creating [closed]

If I console.log my generateOutcome() function I get a randomized output however every time I click on a door in my web game I'm trying to create I never get the monster ('you die') option...I'm sure it has to do with my selectDoor() function -- what am I missing?code




Unique Random Integers [duplicate]

I Can't figure out how I'm supposed to return the Unique values since I'm unable to add more integers to nums which I think is an integer array of sorts but im unfamiliar with it and how im meant to update or change it, Anything helps.

The current output is just a set amount of 0's set by the first number given, the second number given sets the maximum value that can be rolled randomly

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

public class LabProgram {

    // Print the numbers in array separated by a space
    public static void printNums(int[] nums) {
        for (int i = 0; i < nums.length; ++i) {
            System.out.printf("%d ", nums[i]);
        }
    }

    // Used in uniqueRandomInt(), printed in main()
    public static int retries;

    // Generate howMany unique random ints from 0 to maxNum using randGen
    public static int[] uniqueRandomInts(int howMany, int maxNum) {
        int i = 0;
        int nextRand;
        retries = 0;                                  // Initialize static variable
        Random randGen = new Random(29);              // Random number generator with seed 29

        int[] nums = new int[howMany];
        HashSet<Integer> alreadySeen = new HashSet<Integer>();

        /* Enter your code here */
        nextRand = randGen.nextInt(maxNum);
        while(alreadySeen.contains(nextRand)){
            nextRand = randGen.nextInt();
            retries++;
        }
        nums = nextRand;
        
        
        return nums;
    }

    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);
        int howMany = scnr.nextInt();
        int maxNum = scnr.nextInt();
    
        int[] uniqueInts = uniqueRandomInts(howMany, maxNum);
        printNums(uniqueInts);
        System.out.printf("  [%d retries]\n", retries); // Print static variable here
    }
}



Sorting Arrays in Java returning gibberish

Every time I run the code, it returns the array of the two randomly generated numbers as complete and utter gibberish. I am using JDK 18.0.0 and windows 10.

import java.util.concurrent.ThreadLocalRandom;
import java.util.*;
import java.util.Arrays;

public class Mäxchen {

    public static void main(String[] args) {

//beginning of user input for amount of players
        Scanner playerAmountInput = new Scanner(System.in);
            System.out.println("Enter amount of players \n");

            String a = playerAmountInput.nextLine();
            System.out.println("Amount of players are: " + a);
                //end of user input for amount of players

        int playerAmount=2;
        int playerResult=0;
        int die1=ThreadLocalRandom.current().nextInt(1, 6 + 1); //random die 1
        int die2=ThreadLocalRandom.current().nextInt(1, 6 + 1); //random die 2
        int actualResult=0;

        System.out.println(die1+" "+die2);

        int[] arr = { die1, die2 };

         Arrays.sort(arr);


              System.out.println(arr);

    }

}

I am trying to build the german drinking game "Mäxchen" which is similar to Yahtzee. I need to sort the two dice is descending order, and for some reason the output i get is:

[I@7cc355be

All I want, is for the two dice to be displayed in descending order. Any help is greatly appreciated.




vendredi 13 mai 2022

Random.Choice always the same result

Some pretext that's maybe useful idk. I use mixer and am trying to do a random music choice but the random.choice always take the last one (song 5). This is my code

if Mamp=='1':
vad=input("[1] Bakground music")
#Mixer shit
mixer.init()
pygame.mixer.get_init
if vad=='1':
    commands=[mixer.music.load("song1.mp3"), mixer.music.load("song2.mp3"),mixer.music.load("song3.mp3"),mixer.music.load("song4.mp3"),mixer.music.load("song5.mp3")]
    current_command=random.choice(commands)
    current_command
    mixer.music.play(0)

I looked at many answers for the same problem but all wer're just fixing thier (the uploader's) code and uploaded it so I couldn't use it for my code. And since i'm trying to learn python it would be great if you could also explain what went wrong?




jeudi 12 mai 2022

Testing randomness function without intended mean

I have a program that tests a randomness function for how truly random it is:

function testRandom(randomF, tests, intendedMean){
  
  let total = 0;
  
  for(let t = 0; t < tests; t++){
    
    total+=randomF();
    
  }
  
  return Math.abs((total/tests) - intendedMean);
  
}

const randomFunc = () => { return ~~(Math.random() * 2) + 1 }
//returns a randomly choosen 1 or 2.

console.log(testRandom(randomFunc, 100, 1.5));

But is their a way to take out the intended mean and still have a relatively accurate output? My ideas so far are to create a standard deviation set up, but I'm not sure that's the right idea.




Scraping SofaScore votes using Xpath and google sheets

I'm trying to scrape the votes from SofaScore with google sheets using the importxml function.

I'm running into an issue because the class name has a random string at the end of it.

Example "class="sc-5b0433e1-5 koUsvm"

Lets use https://www.sofascore.com/washington-nationals-new-york-mets/ExbsFtc as an example link.

Typically I would just use something similar to the code below.

//div[contains(@class= 'sc-5b0433e1-5')]

Does anyone know how to go about this.




MySQL insert at random position

I want to build a poll where the answers are not assignable to the voters. But I need to keep track of who already voted. So I have two different MySQL tables, one for answers and one for voters. But by the order of the elements as they are inserted in both tables, one could figure out from whom which answer is. So is it somehow possible to change the order in which the items are stored, randomly?




rand() % (int) in a loop causing seg fault [closed]

I'm trying to make a Qlearning function for a basic automatic learning project. pseudo code for Qlearning function here When using rand() % 4; in espi_greed (which aim is to sometimes choose a random action, other times chose the best action derived from Q) function it causes seg fault (when I replace it by action_choisie = 2; for instance I get no seg fault, so I guess the modulo operation is causing this error).

#include "functions.h"
#include <time.h>
#include <stdlib.h>


double alpha = 0.5;
double gamma_temp =1;
double epsilon=0.15;

double max_Q(double*** Q, int ligne, int colonne){
 double max=-100;
 for (int i=0;i<4;++i){
     if (Q[ligne][colonne][i]>max){
         max = Q[ligne][colonne][i];
     }
 }
 return (max);
}

action epsi_greed(double*** Q, int ligne, int colonne){
 float ran_nb = rand()/RAND_MAX;
enum action action_choisie;
if (ran_nb<epsilon) {
 action_choisie = rand() % 4; 
} 
else {
 double max=-100;
 int ind_max = 0;
   for (int i=0;i<4;++i){
       if (Q[ligne][colonne][i]>max){
           max = Q[ligne][colonne][i];
     ind_max = i;
       }
   }
action_choisie = ind_max;
} 
return(action_choisie);
}
                                
 

void Q() {
 
double*** Q = (double***)malloc(rows * sizeof(double**));

 if (Q == NULL)
 {
     fprintf(stderr, "Out of memory");
     exit(0);
 }

 for (int i = 0; i < rows; i++)
 {
     Q[i] = (double**)malloc(cols * sizeof(double*));

     if (Q[i] == NULL)
     {
         fprintf(stderr, "Out of memory");
         exit(0);
     }

     for (int j = 0; j < cols; j++)
     {
         Q[i][j] = (double*)malloc(4 * sizeof(double));
         if (Q[i][j] == NULL)
         {
             fprintf(stderr, "Out of memory");
             exit(0);
         }
     }
 }

 // assign values to the allocated memory
 for (int i = 0; i < rows; i++)
 {
     for (int j = 0; j < cols; j++)
     {
         for (int k = 0; k < 4; k++) {
             Q[i][j][k] = 0;
         }
     }
 }   


     int etat_ligne=start_row;
     int etat_col=start_col;
     int ancienne_ligne;
     int ancienne_col;
     action prochaine_action;
     envOutput nouvel_etat;
     srand(time(NULL));

 for (int u=0;u<30;++u) { 
     int i =0;
     nouvel_etat.done=0;
     while (nouvel_etat.done!=1 && i<1000) {
         

         prochaine_action=epsi_greed(Q,etat_ligne,etat_col); 
     
         nouvel_etat = maze_step(prochaine_action);
         
         /* on update les anciennes valeurs */
         ancienne_ligne=etat_ligne;
         ancienne_col=etat_col;
         
         /* on update les nouvelles valeurs */
         etat_ligne=nouvel_etat.new_row;
         etat_col=nouvel_etat.new_col;

         /* on update Q */
         Q[ancienne_ligne][ancienne_col][prochaine_action] = Q[ancienne_ligne][ancienne_col][prochaine_action] + alpha*(nouvel_etat.reward + gamma_temp*max_Q(Q,etat_ligne,etat_col) - Q[ancienne_ligne][ancienne_col][prochaine_action]);
         i=i+1;
     }
     if (nouvel_etat.done==1) {
         printf("success",i);
     }
     else {
         printf("échec");
     }
 }
 }

(mazestep function is from the teacher so it should not be a problem)

One thing I found is that putting very small numbers for i and u (100 and 2 for instance) in the loops for Q() function avoids segment fault but the code will not be functional this way

How to solve or avoid this problem ?




Sample from groups, but n varies per group in R

I am trying to randomly sample n times a given grouped variable, but the n varies by the group. For example:

library(dplyr)
iris <- iris %>% mutate(len_bin=cut(Sepal.Length,seq(0,8,by=1))

I have these factors, which are my grouped variable:

table(iris$len_bin)

(4,5] (5,6] (6,7] (7,8] 
   32    57    49    12 

Is there a way to randomly sample only these groups n times, n being the number of times each element is present in this vector:

x <- c("(4,5]","(5,6]","(5,6]","(5,6]","(6,7]")

The result should look like:

# Groups:   len_bin [4]
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species    len_bin
         <dbl>       <dbl>        <dbl>       <dbl> <fct>      <fct>  
1          5           2            3.5         1   versicolor (4,5]  
2          5.3         3.7          1.5         0.2 setosa     (5,6]  
2          5.3         3.7          1.5         0.2 setosa     (5,6]  
2          5.3         3.7          1.5         0.2 setosa     (5,6]  
3          6.5         3            5.8         2.2 virginica  (6,7]  

I managed to do this with a for loop and using sample_n() based on the vector. I am assuming there must be a faster way. Can I define n within sample_n() for example?




Random div from csv list or from HTML

I have a recipe on this page: http://limitlesshoops.com/teams/tigers/recipes.html that I want to display as a random selection instead. I have a list of over 13,000 recipes in a csv that includes image URLs, but I'm using Google Spreadsheets to just turn those into HTML because that might be easier for me. Any help would be fantastic because I've worked on this for hours and can't figure it out. Thanks a ton.

Here's the file: https://docs.google.com/spreadsheets/d/e/2PACX-1vRrLLrhwJtPrbWLF38RlGtPNA0PlCkuWXpULqCFi-9AhTtMBTfOCTnhdr8ax-elZRWJVIE3zhVVXBxO/pubhtml?gid=1400250095&single=true




Create new rows that are conditional on earlier rows

I want to create output_df, which adds two rows to the bottom.

The new rows are:

  • assigned NA for column z, and
  • percentage is calculated such that sum(output_df$x == "Y" & output_df$y == "A") == 1 and sum(output_df$x == "N" & output_df$y == "B") == 1
original_df <- data.frame(x = c("Y","N","Y","N"),
                          y = c("A","B","A","B"),
                          z = c("a","b","c","d"),
                          percentage = c(0.1, 0.2, 0.5, 0.5)) 

output_df <- data.frame(x = c("Y","N","Y","N","Y","N"),
                        y = c("A","B","A","B","A","B"),
                        z = c("a","b","c","d",NA , NA),
                        percentage = c(0.1, 0.2, 0.5, 0.5, 0.4, 0.3)) 

For context, my intent is to use output_df to feed into the sample function, where replace = T.




mercredi 11 mai 2022

Display A Random Quote and Author from Array List in a New activity On Button Click

I'm trying to create a mood checker application. Where when the user clicks on a mood, it would display a quote in a new activity. My application runs but the quote is not displayed. I think there might be a problem with my try catch method, but I don't really know how to resolve this.

public class MainActivity extends AppCompatActivity {
public ImageButton awesome, good, neutral,sad, awful;
public int index;
public ArrayList<Quote> awesome_List;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // DECLARE MOOD BUTTONS//
    awesome=(ImageButton) findViewById(R.id.btn_awesome);
    good=(ImageButton) findViewById(R.id.btn_good);
    neutral=(ImageButton) findViewById(R.id.btn_neutral);
    sad=(ImageButton)findViewById(R.id.btn_sad);
    awful=(ImageButton)findViewById(R.id.btn_awful);

    //Create Array List for each mood quote and author


    //AWESOME MOOD//
    String[] awesomeQuoteArray = {
            "“Happy people don\\'t have the best of everything, they make the best of everything",
            "“Most people are about as happy as they make up their minds to be”.",
            "“A happy person is happy, not because everything is right in their life but because their attitude towards everything in life is right”.",
            "“Make someone happy. Make just one someone happy and you will be happy too”",
            "“The beauty of life does not depend on how happy you are, but how happy others are because of you”."
    };

    String[] awesomeAuthorArray={
            "Marcel Proust",
            "Eckhart Tolle",
            "Adi Shankara",
            "Marcus Tullius Cicero",
            "Marcus Aurellius"
    };
    awesome_List=new ArrayList<>();
    addAwesomeToQuoteList(awesomeQuoteArray,awesomeAuthorArray);

    // generate awesome random quotes
    final int awesomeQuoteLength = awesome_List.size();
    index=getRandomQuote(awesomeQuoteLength-1);
    addAwesomeToQuoteList(awesomeQuoteArray,awesomeAuthorArray);

    awesome.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            sendAwesomeData(); 

    }
    });
   }
   
public void sendAwesomeData(){
    String AwesomeText="";
    try {
        System.out.println(AwesomeText.charAt(awesome_List.size()));

        String hello ="hello";

        AwesomeText= awesome_List.get(index).toString();


    }catch (StringIndexOutOfBoundsException e){
        System.out.println("String index out of bounds. String length:" + AwesomeText.length());
    }
    String AwesomeOutputText = AwesomeText;
    Intent awesomeIntent= new Intent(MainActivity.this, awesome_mood_quotes.class);

    awesomeIntent.putExtra(awesome_mood_quotes.QUOTE,AwesomeOutputText );
    startActivity(awesomeIntent);
}


public int getRandomQuote(int length){
    return(int) (Math.random()*length)+1;
}

}


Second Activity Code

public class awesome_mood_quotes extends AppCompatActivity {
public static final String QUOTE= "QUOTE";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_awesome_mood_quotes);

    TextView awesomeQuote=(TextView) findViewById(R.id.awesome_quote_text);

    Intent intent= getIntent();
    String AwesomeText=intent.getStringExtra(QUOTE);
    awesomeQuote.setText(AwesomeText);



}

}




How do i make the background a Random hex color? Also so there are no duplicates

My PNG is a transparent background. when i run the script, it gives me the same 10 colors. When I set the brightness to 0% then no colors generate. Trying to make it so a random hex # is generated for each image and there are no repeats.

const gif = {
  export: false,
  repeat: 0,
  quality: 100,
  delay: 500,
};

const text = {
  only: false,
  color: getRandomColor(),
  size: 20,
  xGap: 40,
  yGap: 40,
  align: "left",
  baseline: "top",
  weight: "regular",
  family: "Courier",
  spacer: " => ",
};

function getRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}


'#'+(Math.random() * 0xFFFFFF << 0).toString(16).padStart(6, '0');



function setRandomColor() {
  $("#colorpad").css("background-color", getRandomColor());
}

const pixelFormat = {
  ratio: 2 / 128,
};

const background = {
  generate: true,
  brightness: "50%",
  static: false,
  default: getRandomColor(),
};



button displays random quotes in new activity (Android Studio)

My application works however, when clicking the button, it doesn't show any quotes in the 2nd activity. It's just blank.

This is the second activity code




A single global variable that is always a random number each time it's referenced

I'd like to use one global variable that is random every time it's used. My current method creates a random number once and that number stays the same. I don't need the number to be unique, just always random.

var randomNumber = Math.floor(Math.random() * 100);
$('something').css('width', randomNumber)
$('something-else').css('width', randomNumber) // want a different random number
$('a-totally-different-thing').css('width', randomNumber) // want another different random number

Is there a way to do this, or do I have to use a different var each time? My main reason for wanting this is to keep the code clean and readable and not have to put Math.floor(Math.random() * 100) in over and over again everywhere. I'm experimenting with generative art so it's going to be used a LOT. I'd like it to be global so I can reference it from anywhere.

Answer: Use a function instead of a variable. Much Thanks to VLAZ and CherryDT




random number generator function returns a nested tuple in haskell

I am trying to understand why my haskell function returns a nested tuple, and I cannot seem to wrap my head around the problem.

I have this function that generates a random binary Int

test :: StdGen -> (Int, StdGen)
test g = do
  let (i, g') = randomR (0, 1) g
  return (i, g')

However, I cannot compile this unless I change the function to return a nested tuple, like so:

test :: StdGen -> (Int, (Int, StdGen))

If I do so, I have to get the snd element in the returned tuple, to get the desired result:

g = mkStdGen 5
(i, g') = snd test g

How do I make my test function return a single tuple with the random binary and a new generator (i, g)? What am I missing?




mardi 10 mai 2022

unity2d move a game object towards a random position

i have a satellite which i let spawn randomly in a different script by just using the method Satellite() and i want it move towards the bottom of the screen but not towards the middle but again a random position of the ground. the problem is that satellitedirection is always 0. also, if i somehow would manage to get the problem solved, wouldn´t every satellite on the screen move towards the same position?

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

public class SatelliteBehaviour : MonoBehaviour
{
    [SerializeField] Rigidbody2D satelliteRB;
    [SerializeField] Transform satelliteFirePoint;
    [SerializeField] GameObject satellitePrefab;
    float satellitedirection;

    void Start()
    {
        

    }

    
    void Update()
    {
        transform.Rotate(0,0,80*Time.deltaTime);
        //satelliteRB.velocity = -transform.up * 5;
        transform.position = Vector2.MoveTowards(transform.position, new Vector2(satellitedirection, -15), 1 * Time.deltaTime);

        Debug.Log(satellitedirection);
        
    }

    public void Satellite()
    {
        Instantiate(satellitePrefab, new Vector2(Random.Range(-18,18),10), Quaternion.identity);
        satellitedirection = Random.Range(-18, 18);
    }
}



How to generate integers based on a string seed

I'm quite new to Postgres, and I've been trying to create a DB function which would produce a positive seeded integer in a given range based on a string seed.

I've actually managed to make it work, however, I don't believe my solution is really all that great and would appreciate, if you could suggest a better solution, provided there is one.

So far I have this:

CREATE OR REPLACE FUNCTION seeded_int(p_low integer, p_high integer, p_seed text)
    RETURNS integer
    LANGUAGE 'plpgsql'
AS $BODY$
DECLARE
    v_num integer;
BEGIN
    SELECT ('x' || SUBSTR(MD5(p_seed), 1, 8))::bit(32)::int INTO v_num;
    PERFORM SETSEED(v_num / 2147483647.0); -- 2^31 - 1
    RETURN FLOOR(RANDOM() * (p_high - p_low + 1) + p_low);
END;
$BODY$;

As you can see, my function consists of three steps:

  1. Generating integer from seed by using MD5 hash function (borrowed from this SO answer)
  2. Dividing the integer so that it fits between -1 and 1 and could be used as seed (value taken from the documentation of SEED parameter)
  3. Generating seeded integer in a given range

The problem:

My biggest problem is with the second step where I literally divide the number v_num, which I want to use as seed, by the exact same value 2^31-1 which would then be used to multiply the seed again, as described in the documentation:

SEED

Sets the internal seed for the random number generator (the function random). Allowed values are floating-point numbers between -1 and 1, which are then multiplied by 2^31-1.

Is it possible to set the seed without redundant operations?

Is there a better way how to approach generating seeded integers?

EDIT: I just realized I didn't actually need SETSEED() and RANDOM() functions at all. The integer generated in the 1st step is already seeded, and all I have to do is recalculate it so that it fits the given range. I believe that, in order to do so, I just need to fit the value between 0 and 1 and use it instead of RANDOM() in the 3rd step. I'm kind of disappointed in myself for not seeing this immediately...