dimanche 28 février 2021

Python insert output into new row of existing excel file

I have this simple code to print random numbers. Each time i run this code, the values are being replaced. How do I make it write from the next available row within the same excel file? Thanks.

import pandas as pd
import random
import time
from xlsxwriter import*
from time import time, sleep


numberList = [0, 40, 43, 45, 48, 50, 53, 55, 58, 60]
my_list = []
my_list = (random.choices(numberList, weights=(2, 1, 3, 6, 3, 2, 2, 1, 1, 1), k=100))


df = pd.DataFrame.from_dict({'Random No':my_list})
df.to_excel('dataset5.xlsx', header=True, index=False)



Random shuffling of tags in react

I am building a quiz program in react and pulling my questions from a mysql db into an array and then displaying the different parts in html rows. Right now I'm always pulling the correct answer into button 1 and three incorrect answers into buttons 2-4. Is there a way for me to shuffle the rows randomly so that I don't have to create a separate array and then shuffle?

<div className='answers'>
    <Row><button onClick={correctAnswer}>}</button></Row>
    <Row><button onClick={incorrectAnswer1}></button></Row>
    <Row><button onClick={incorrectAnswer2}></button></Row>
    <Row><button onClick={incorrectAnswer3}></button></Row>
</div>



How to use slice notation in this case?

I am solving a problem in which I am using two large matrices A and B. Matrix A is formed by ones and zeros and matrix B is formed by positive integers.

At some point, I have to update the components of A such that, if the component is 1 it stays at 1. If the component is 0, it can stay at 0 with probability p or change to 1 with probability 1-p. The parameters p are functions of the same component of matrix B, i.e., I have a list of probabilities such that, if I update A[i,j], then p equals the component B[i,j] of the vector probabilities

I can do the updating with the following code:

for i in range(n):
  for j in range(n):
    if A[i,j]==0:
        pass
    else:
        A[i,j]=np.random.choice([0,1],p=[probabilities[B[i,j]],1-probabilities[B[i,j]]])
        

I think that there should be a faster way to update matrix A using slice notation. Any advice?




random - adding bias to incorrect answers in a quiz (javascript)

I wanted to make a relatively simple algorithm, that isn't just randomly choosing a question. So for each question I have a value called numOfCorrect, when the user gets the answer correct it adds 1, if the user gets it wrong it subtracts 1. like this:

const questions = [
    {question: "what is 9 + 10?", numOfCorrect: -5 ...},
    {question: "what is the meaning of life?", numOfCorrect: -5 ...},
    {question: "how do I get a bias for the incorrect?", numOfCorrect: 0 ...},
    {question: "1 + 1 = 4?", numOfCorrect: 10 ...}

]

so if each numOfCorrect is 0, I would want each question to have an even chance of getting picked, so that's just picking a random question normally.

The questions will be sorted from the least numOfCorrect to the most. I don't want to just decrease the range to bias the first indexes. Instead I want the probability for the questions to increase or decrease based on the numOfCorrect value, so there should be a non zero chance for any of the questions to be picked.

I was thinking something like:

  • for a question with a negative numOfCorrect => 1 / questions.length * ( 1 + ( (1/question.numOfCorrect) * -1)), so for a value -5 it would be 0.25 * 1.2 which would be 0.3. So instead of 25% chance it would be 30%.

  • for a question with positive numOfCorrect. If numOfCorrect was 1, then it would be 0.25 * 0.9, 2 would be 0.25 * 0.8...

Problem is they won't add to 1 (obviously). I don't know what I'm doing, I'm no mathematician.

So main question. How can pick a random question and bias the ones with a lower numOfCorrect, that will preferably exponentially increase/decrease their probability of being picked as the value numOfCorrect increases/decreases??




How to show random team member name from list or range using VBA?

Excel sheet

Hi experts,

I have a list of members in an excel sheet as shown in the image (from A2 to A21). I want a VBA code that randomly select a name from this range and displays it in cell E2. My requirement is that all the members must be covered and when we click and no member name should repeat. That is, I need to click the macro button exactly 20 times which should show random member name in E2 cell without repeating. I got so many codes to generate unique random number but I couldn't find any to link it with my requirement. Any help please?




samedi 27 février 2021

Using JavaScript to randomly select variables that format the webpage (background color, etc.) [closed]

Sorry, this question is a bit different. I want the webpage formatting to be randomly assigned.

So something like this: $color1 = {document.body.style.backgroundColor = "#AA0000"}. I'd do this for five different colors, etc.

Then, JavaScript could randomly choose which format (color) to implement.

I'm a real beginner. Sorry. I hope to learn a lot from the replies.




How do I remove multiple random characters from a string in python

I have come up with the following code but unfortunately its only removing 1 character from my string.

import random
string = 'HelloWorld!'
def remove_random_character(phrase):
        character_number = random.randint(0, len(phrase))
        remover = f'{phrase[:character_number - 1]}_{phrase[character_number:]}'
        for _ in range(8):
            sliced_phrase = remover
        print(sliced_phrase)
remove_random_character(string)```

 I thought that the for loop will take care of this but unfortunately it did not. but every time it loops it just refreshes the *sliced_phrase* variable. but I do not know how to store the last version of the loop, for that to be edited. So how can I can I remove multiple random characters from a string?



Generating solid spheres in python

I'd like to generate random uniform samples from n-dimensional solid spheres.

My current method is this

def sample_sphere(d, npoints):
    points = np.zeros((npoints, d))
    for i in range(npoints):
        r = np.random.rand() #random radius
        v = np.random.uniform(low= -1, high=1, size = d) #random direction
        v = v/np.linalg.norm(v)
        points[i] = r*v
    return points

But unsurpringly, this method gives a higher concentration of points near 0, (see image) since the sampling density is not proportional to the volume. How can I sample uniformly?




Why is my JS not reading my correctly? [duplicate]

This is my code:

<!DOCTYPE html>
<html>
  <head>
    <title>Random Number Generator</title>
  </head>
  <body>
    <h1>
      Random Number Generator
    </h1>
    <p>
      Minimum:
      <input type="number" id="min" />
    </p>
    <p>
      Maximum:
      <input type="number" id="max" />
    </p>
    <button onclick="go()">
      Go
    </button>
    <p id="ran"></p>
    <script>var min, max;
function go() {
  min = document.getElementById("min").value;
  max = document.getElementById("max").value;
  document.getElementById("ran").innerHTML = Math.floor(
    Math.random() * (max - min + 1) + min
  );
}
</script>
  </body>
</html>

It is a random number generator. My problem is that the result is less than the minimum. I'm positive that the problem is with the input because one time I replaced max and min with numbers and it came up with a number between them.




Generating random dots within an outer circle that have a certain distance

I'm currently really stuck with some of my code and I can't seem to find the issue. Here is what I am trying to do: I have a big outer circle in which I want to display smaller dots. These dots should be randomly distributed but should not overlap, thus they should have a minimum distance to each other. What I have tried is to first randomly generate a point, check wether it is in the outer circle and if it is, append it to the final list of dot positions. Then another point is created, checked if in circle and then it should be checked if the dot has a minimum distance to the other dot(s) in the final list. However, I seem to have some issues with my code as it will not run through whenever I set the required distances higher than 1. I have changed multiple things, but I cannot make it work.

If anyone has an idea about what the problem might be or how I could better code this, I would be very very grateful (it is driving me nuts at this point).

Thank you so much in advance!

Here's what I have been trying:

import random
import numpy as np
import math

#Variables
radiusOC = 57
size_obj = 7
required_dist = 5
no_stimuli = 3


def CreatePos(radiusOC, size_obj, required_dist, no_stimuli):
    final_list = []
    def GenRandPos(radiusOC,size_obj):
        """
        Takes the radius of the outer circle and generates random dots within this radius. Then checks if the the dots are located 
        within the outer circle.
        """
        while True:
            xPos = random.randint(-radiusOC,radiusOC)
            yPos = random.randint(-radiusOC,radiusOC)
        
            # check if in Circle 
            on_circle = (xPos- 0)**2 + (yPos-0)**2
            if (radiusOC-size_obj)**2 >= on_circle:
                print("Still in circle",on_circle, xPos, yPos )
                position = [xPos, yPos]
                break
            else:
                print("Not in circle",on_circle, xPos, yPos )
                continue
                
        return position


    def CheckSurrounding(position, final_list, required_dist): 
        """
        Takes dot positions that are in the visual field, the list of positions, and the distances dots are required to have from each other. 
        It is checked if there are dots close by or not.  
        """
        X1 = position[0]
        Y1 = position[1]
        dist_list = []
        for elem in final_list:
            for i in elem: 
                X2 = elem[0]
                Y2 = elem[1]
                dist = math.sqrt((X1-X2)**2 + (Y1-Y2)**2)
                dist_list.append(dist)
                
        if all(dist_list) >= required_dist: 
            return position
            
        else:
            return None

    # append the first dot to the list
    position = GenRandPos(radiusOC, size_obj)
    final_list.append(position)

    # now append the rest of the dots if they have a certain distance to each other
    while len(final_list) < no_stimuli: 
        position = GenRandPos(radiusOC, size_obj)

        if CheckSurrounding(position, final_list, required_dist)  != None: 
            position = CheckSurrounding(position, final_list, required_dist)
            final_list.append(position)

        else: 
            continue
    
    return final_list


´´´



Why is generating a higher amount of random data much slower?

I want to generate a high amount of random numbers. I wrote the following bash command (note that I am using cat here for demonstrational purposes; in my real use case, I am piping the numbers into a process):

for i in {1..99999999}; do echo -e "$(cat /dev/urandom | tr -dc '0-9' | fold -w 5 | head -n 1)"; done | cat

The numbers are printed at a very low rate. However, if I generate a smaller amount, it is much faster:

for i in {1..9999}; do echo -e "$(cat /dev/urandom | tr -dc '0-9' | fold -w 5 | head -n 1)"; done | cat

Note that the only difference is 9999 instead of 99999999.

Why is this? Is the data buffered somewhere? Is there a way to optimize this, so that the random numbers are piped/streamed into cat immediately?




Doesn't store entered value when runs second time

I made rock,paper,scissor game. It works fine, as I wanted to, but it doesn't store entered value when runs second time, how do I fix that.

import random

tools =["Rock","Scissors","Paper"]
r="".join(tools[0])
s="".join(tools[1])
p="".join(tools[-1])
def computer_predicion():
    computer_pred = random.choice(tools)
    return computer_pred
computer=computer_predicion()
def my_predicion():
my_predicion = input("Choose (R)Rock,(S)Scissors,(P)Paper:")
    if my_predicion=="R" or my_predicion =="r":
       my_predicion = r
       return my_predicion
    elif my_predicion=="S" or my_predicion =="s":
       my_predicion = s
       return my_predicion
    elif my_predicion=="P" or my_predicion =="p":
       my_predicion = p
       return my_predicion
    else:
         print("Debils ir?")
human=my_predicion()
def game():
    message_win = ("You won!")
    message_lose = ("You lost!")
    message = "Computer:%s\nUser:%s"%(computer,human)
    if computer ==r and human==r :
       print(message+"\nIt's draw")
    elif computer == p and human == p:
       print(message + "\nIt's draw")
    elif computer == s and human == s:
       print(message + "\nIt's draw")
    elif computer == r and human==p:
       print(message+'\n'+message_win)
    elif computer == p and human==r:
       print(message+'\n'+message_lose)
    elif computer == r and human==s:
       print(message+'\n'+message_lose)
    elif computer == s and human==r:
       print(message+'\n'+message_win)
    elif computer == p and human == s:
       print(message+'\n'+message_win)
    elif computer == s and human==p:
       print(message+'\n'+message_lose)
    else:
        pass
 c=True
 while c :      //Here code runs second time if user inputs Y or y.
      game()
      h = input("Continue?(Y/N):")
      if h=="Y" or h=="y":
         my_predicion()
         computer_predicion()
         pass
      elif h=="N" or h=="n":
          c=False
      else:
           print("Wrong symbol!")

If you have any further suggestions on how to make code better I would love to hear them out. Thank you!




Inserting parentheses at random place?

stackoverflow community! I am once again asking for your help...

I have made a random equation generator that generates a string like this:

def strmaker():
    picker = random.randint(2, 5)
    if picker == 5:
        return "1" + random.choice(RandomSymbols) + "2" + random.choice(RandomSymbols) + "3" + random.choice(
            RandomSymbols) + "4" + random.choice(RandomSymbols) + "5"
    elif picker == 4:
        return "1" + random.choice(RandomSymbols) + "2" + random.choice(RandomSymbols) + "3" + random.choice(
            RandomSymbols) + "4"
    elif picker == 3:
        return "1" + random.choice(RandomSymbols) + "2" + random.choice(RandomSymbols) + "3"
    else: return "1" + random.choice(RandomSymbols) + "2"

The typical outcome of this would look like this:

1-2*3-4

So basically what i wanna do is: Make some code/function that inserts one or multiple sets of parentheses at a random spot.

Like this!

(1-2)*3-4

Or this!

(1-2)*(3-4)

Or...

(1-2*3)-4

I think you get it at this point. What would be the simplest way to do this?




Shuffling a list returns None

I have a nested list whose each element contains 5 elements two of which are string, 2 others are arrays and the other one is an integer. This is an example of one of the elements:

print(data[0])

['string1', 'string2', array([ 8.3815563e-01, -3.5425583e-01,  2.1343436e+00,  9.6825659e-02,
       -9.0467620e-01,  2.3725919e-01, -1.1198132e+00, -1.4628445e+00,
       -9.7618866e-01,  3.4088433e-01, -8.1933931e-02,  5.3724372e-01,
       -9.3491834e-01, -1.7797737e-01, -2.3983700e+00,  2.8213045e-01,
       -2.6180375e+00, -1.3855113e+00,  5.4659176e-01,  9.1559738e-01,
       -9.5645869e-01,  1.1714146e+00, -1.5016689e+00, -6.0279185e-01,
       -2.7174740e+00, -8.4398395e-01, -1.4227449e+00, -3.3634397e-01,
       -1.1180943e-01,  2.0590048e+00, -8.1385499e-01,  3.3400309e-01,
        1.5486939e+00,  7.1667129e-01, -5.3015262e-01,  2.9040620e-01,
       -1.7378879e+00,  1.8073572e+00,  2.0475891e+00, -3.7024517e-02,
       -2.4894023e+00,  8.1641458e-02, -1.0466967e+00, -9.3819243e-01,
        2.2070546e+00, -7.8535575e-01,  1.8938659e+00,  6.1495984e-01,
        1.3074586e+00,  1.7998766e+00,  4.2521158e-01, -1.0011816e+00,
        3.9505896e-01,  1.9510569e-01,  5.4488051e-01, -2.4220757e+00,
       -2.0812688e+00,  7.4905115e-01,  2.5282860e+00,  3.6349185e+00,
       -1.5371487e-02, -1.4186651e+00, -3.0352873e-01,  1.1874241e+00,
       -7.4466765e-01, -5.5792803e-01,  2.0802140e+00, -1.0457656e+00,
       -1.6084572e+00,  7.6335722e-01,  6.1364901e-01, -8.8677669e-01,
        1.8135322e+00, -9.9430311e-01,  1.1136630e+00,  1.7036382e+00,
        1.2363054e+00, -1.0278525e+00, -1.4202880e+00,  3.4898412e+00,
        3.2176024e-01, -3.3177676e+00, -1.5177081e+00, -3.3506298e+00,
        8.9109224e-01, -9.2560369e-01, -1.3482516e-01,  1.8940198e+00,
       -2.4911180e+00,  1.7098404e+00,  1.0733328e+00, -6.8110102e-01,
        7.5147294e-02,  2.0663846e+00, -6.3406414e-01, -8.0714762e-01,
       -3.9137515e-01,  1.6869707e+00,  1.8897502e+00, -1.0949643e+00,
        8.3844274e-02, -3.1892413e-01,  1.0630800e+00, -2.1269834e-02,
        3.3197129e+00, -1.1836429e+00,  1.2935223e-01,  1.2349771e+00,
       -1.7768501e-01, -8.5823111e-02,  9.8761206e-04, -3.3543497e-01,
        1.2038582e-01,  1.0106378e+00, -6.1783981e-01,  6.3571078e-01,
        3.6776218e+00, -1.0869727e+00,  4.0498915e-01, -1.3616250e+00,
       -1.9101478e+00, -1.4676404e+00,  5.2525636e-02, -9.4835764e-01,
       -2.2515597e+00, -1.4384656e+00,  2.7463729e+00, -1.1626251e+00,
        5.0647104e-01, -1.0085446e+00, -3.4135873e+00,  2.8761895e+00,
       -7.5525141e-01,  1.9556025e-01,  1.8816977e+00, -2.1862485e+00,
        5.3653735e-01,  1.0174786e+00, -3.5168248e-01,  1.4792174e+00,
       -1.9718715e+00,  3.5284543e-01, -1.3289005e+00,  9.2077084e-02,
       -1.5259730e+00, -1.2676430e-01,  6.3915849e-02,  5.7076526e-01,
       -1.4283143e+00,  3.4811370e+00, -7.5676990e-01,  1.5901275e-01,
        3.0968320e-01, -2.0210378e+00,  1.5994365e+00, -1.8184477e+00,
       -1.7792468e+00, -3.8709867e+00, -8.5106057e-01,  7.5884897e-01,
        3.2979882e-01, -1.5201263e-01, -1.9805571e+00, -2.2941742e+00,
       -4.1824151e-02, -2.1928535e+00, -1.8360862e-01,  9.7463828e-01,
        6.0613501e-01,  1.4130658e+00,  1.2847931e+00, -1.3037770e+00,
       -9.3676001e-01,  1.6299471e+00,  2.8797865e+00,  7.8968775e-01,
       -4.1697282e-01, -7.7608454e-01, -8.9482792e-02, -1.5818343e-01,
        6.1421517e-02,  1.3762995e+00, -1.6491550e+00,  3.0861428e-01,
        4.6627381e-01,  1.6797400e+00,  7.4473983e-01, -2.0260219e-01,
       -1.2619594e+00, -9.3980944e-01,  1.4026953e+00,  4.5976865e-01,
       -1.7153995e+00, -1.5826430e+00,  4.1946498e-01, -2.3856725e-01,
       -7.2106045e-01, -4.1541594e-01,  2.0517633e+00,  1.4137658e+00],
      dtype=float32), array([ 0.76214266, -1.1080794 ,  0.62450695, -0.03991625, -1.0332664 ,
        0.4477847 , -1.5307423 , -0.46780497, -0.65694493,  0.4017106 ,
        1.046495  ,  0.89560634, -0.02834422,  0.25185633, -1.722349  ,
        0.47461596,  0.43950516,  0.47719032,  1.231193  , -0.2833851 ,
       -0.95124   ,  1.9791093 , -2.199751  , -0.31563753, -0.15620655,
        0.08995419, -1.0236559 , -0.09124855,  1.3184121 ,  1.3093723 ,
        1.5500983 , -1.138387  ,  1.825099  ,  0.54720974, -0.4497883 ,
       -1.019564  , -0.4743175 ,  1.5091532 ,  2.434069  , -0.51617134,
       -1.3287805 , -0.9675629 ,  1.0409877 ,  0.24908057,  1.448763  ,
        0.75647604,  0.25115636,  1.0880857 ,  0.44079414,  2.5577083 ,
        0.13774393, -0.7663842 ,  0.39448643,  1.6326874 ,  1.7713975 ,
       -1.0623255 , -0.27031946, -2.0021632 ,  1.4890292 ,  0.4731933 ,
       -0.30264556,  1.0804956 , -1.607742  ,  0.9306975 ,  0.12114237,
       -0.62948585,  0.52928966, -0.93153584,  1.3739216 ,  0.5499291 ,
        1.8106089 , -0.83994585,  0.287617  ,  1.7036526 ,  1.045847  ,
        1.971305  ,  0.94189185,  0.37291932, -1.2711267 ,  1.4045115 ,
        0.6248116 , -1.5587406 , -0.43730614, -2.5828342 , -0.5555636 ,
       -0.8796892 , -1.9538026 , -0.03389208,  0.3284353 , -0.12875274,
        0.65289074, -0.6155094 ,  0.28595057,  0.68420696, -0.5966044 ,
        0.5173465 , -0.76814157,  0.5442661 , -0.7675229 , -0.5273055 ,
        0.6800498 , -0.51253283, -0.7812486 , -0.38429317,  0.7641112 ,
       -0.01918199, -0.6239758 ,  1.5667789 ,  1.4919078 , -0.65991163,
       -1.4864634 , -1.0146723 ,  0.6918642 ,  0.44775197, -0.14802925,
        1.762855  ,  1.1468196 , -0.37504146, -0.32759622, -2.2596357 ,
       -1.1980705 , -1.4669111 , -0.09373622, -0.34457773, -1.4592841 ,
       -0.06391117,  0.6223186 , -0.321511  ,  0.30783862, -1.0348482 ,
       -0.70685714,  1.2692565 ,  0.21873838,  1.0072349 , -0.5244955 ,
       -0.8728946 , -0.03604483,  1.4866482 , -0.7006194 ,  2.59386   ,
        0.04309946,  0.8236084 , -1.192761  ,  0.91982   , -0.2588019 ,
        0.46571994,  1.0871515 , -1.3756664 , -1.5655178 ,  0.45953277,
        0.74666524,  0.38552722,  1.7726213 , -0.3308338 ,  0.5287637 ,
       -1.8667183 ,  0.65863764,  0.18299544,  0.6244534 , -0.5654262 ,
        0.3377428 , -0.91572076, -1.8910241 , -1.1871653 ,  0.94825065,
       -1.4711756 , -0.8371643 , -1.0536038 ,  0.02091897, -0.8702738 ,
        0.95009375, -0.9187259 , -1.8877221 ,  0.59374857,  0.6501635 ,
       -0.3254898 , -1.3754797 , -1.2943144 ,  1.3063593 ,  1.6203603 ,
        1.9170743 ,  2.1614845 , -0.9923637 ,  0.616638  , -1.8561238 ,
       -0.897864  ,  0.63119555, -0.3960814 ,  0.23239917, -1.5750691 ,
        0.16524327,  1.8257805 , -0.02598399, -1.0150673 ,  0.64206785,
       -0.62078387, -0.08855089, -0.1757602 ,  1.0424634 ,  0.78948444],
      dtype=float32), 2]

I want to shuffle the original list so that the order of these nested elements changes. This is what I have written:

import random
shuffled_data = random.shuffle(data)

However, when I print "shuffled_data", it returns "None". How can I solve this problem?




vendredi 26 février 2021

call php function on form submition

Hi im trying to generate this a code from this php function

         <?php function generateRandomString($length = 6) {
    return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
}

echo  generateRandomString(); ?>

when this <button>Submit</button> is clicked. It is a submition button for a form in HTML

Many Thanks in advance :)




Import random - randint not working? Python [closed]

Error:

line 50, in <module>
    random.randinit(1, sh-1),
AttributeError: module 'random' has no attribute 'randinit'

Randint is not being recognized as a module of Random.

I do NOT have anything named random.py or pyc

My file is NOT named random.py

I HAVE pip installed random2 (random on windows wont install?)

I don't think the code is relevant but if it is, here's the code:

import random
import curses
from curses import textpad

s = curses.initscr()
curses.curs_set(0)
sh, sw = s.getmaxyx()
w = curses.newwin(sh, sw, 0, 0)
w.keypad(1)
w.timeout(100)

snk_x = sw/4
snk_y = sh/2
snake = [
    [snk_y, snk_x],
    [snk_y, snk_x-1],
    [snk_y, snk_x-2]
]

food = [sh/2, sw/2]
w.addch(int(food[0]), int(food[1]), curses.ACS_PI)

key = curses.KEY_RIGHT

while True:
    next_key = w.getch()
    key = key if next_key == -1 else next_key

    if snake[0][0] in [0, sh] or snake[0][1] in [0, sw] or snake[0] in snake[1:]:
        curses.endwin()
        quit()

    new_head = [snake[0][0], snake[0][1]]

    if key == curses.KEY_DOWN:
        new_head[0] += 1
    if key == curses.KEY_UP:
        new_head[0] -= 1
    if key == curses.KEY_RIGHT:
        new_head[1] += 1
    if key == curses.KEY_LEFT:
        new_head[1] -= 1
    
    snake.insert(0, new_head)

    if snake[0] == food:
        food = None
        while food is None:
            nf = [
                random.randinit(1, sh-1),
                random.randinit(1, sw-1)
            ]
            food = nf if nf not in snake else None
        w.addch(int(food[0], food[1], curses.ACS_PI))
    else:
        tail = snake.pop()
        w.addch(int(tail[0]), int(tail[1]), ' ')
    
    w.addch(int(snake[0][0]), int(snake[0][1]), curses.ACS_CKBOARD)

This is just me meeting the text:code ratio requirments.

Can I be any more descriptive than this?

I'm not sure but if you have any questions let me know.




How generate multiple random distribution from a vector of mean and st.dev in octave/matlab?

So I have a vector V of values with dimension [5,1]. For each value in this vector V[i] I would like to generate let's say 5 numbers normally distribuited with mean V[i] and a fixed st deviation. So in the end I will have a matrix [5,5] which on the i-row has 5 values normally distributed with mean V[i]. How can i do this with octave/matlab without using for loop ? Practically I would like to pass to the normrnd function a vector of means V and get a set of n normally distributed number for each mean in the vector V.




How do I select random rows without using df.sample()?

If I wanted to select rows randomly from a data frame without using df.sample(), would something like

import random
peopleCount = people.iloc[[random.randint(1, 101)]], :]

work? Or am I approaching this the wrong way?




Why is rand() giving me negative numbers?

I'm trying to make it so that rand_draw holds a random positive number between 0-8. But this code keeps giving negative numbers on some iterations. What's happening?

srand(time(0));
int draw_count = 8;
int rand_draw = (2 * rand()) % draw_count;
cout << rand_draw << endl;



select random images from a folder for webdriver

I want to uplaod an Image to twitter, I am using selenium
I have a folder where all images are located but I need to choose a random images in that folder Thanks for your help

path_image = ('C:/Users/92/Desktop/python/V2/images/')

    element = driver.find_element_by_xpath("//input[@type='file']")
    driver.execute_script("arguments[0].style.display = 'block';", element)
    
    element.send_keys(random.choice(path_image))

the ERROR that I am getting

selenium.common.exceptions.InvalidArgumentException: Message: invalid argument: File not found : D
  (Session info: chrome=88.0.4324.190)



My random replace-system replaces the wrong items

I want to build a program that replaces 12345 with one of each item from the shuflo list, but if the shuflo list contains a number from 1 to 5 it will replace them too.

Here is my code:

shuflo = [1, 2, 3, 4, 5]

def build(x):
    random.shuffle(shuflo)
    lock = shuflo
    lack = str(x)
    lack = lack.replace("1", str(lock[0]))
    lack = lack.replace("2", str(lock[1]))
    lack = lack.replace("3", str(lock[2]))
    lack = lack.replace("4", str(lock[3]))
    lack = lack.replace("5", str(lock[4]))
    Ponf = [lack, eval(lack)]
    return Ponf

print(build("(1)+(2)+(3)+(4)+(5)"))

The typical outcome would be:

['(3)+(1)+(2)+(3)+(5)', 14]

In the list shuflo there is only one of 3, but some of the elements get replaced twice so it doesn't work.

How can i fix this???




SelectKBest for regression `f_regression` behaves weird when changing the random_state parameter when splitting

I am working on a regression project using the Audi dataset from Kaggle.

I have looked at other notebooks and i saw that people use SelectKbest. I tried using the same thing, but when I was splitting my data to train-test I used random_state = 42 and when I tried using the SelectKBest I had a lot of warnings:

minmax_scaler = MinMaxScaler()

#cars_df_with_dummies -> this is a dataframe I created with pd.get_dummies(cars_df)
cars_scaled = minmax_scaler.fit_transform(cars_df_with_dummies)
cars_scaled = pd.DataFrame(cars_scaled, columns = cars_df_with_dummies.columns)


scaled_price_label = cars_scaled['price']
scaled_cars_without_price = cars_scaled.drop(['price'],axis=1)

X_train,X_test,y_train,y_test = train_test_split(scaled_cars_without_price,scaled_price_label,test_size=0.2,random_state=42)

The code to select the best features (was taken from the top rated notebook):

column_names = cars_df_with_dummies.drop(columns = ['price']).columns

no_of_features = []
r_squared_train = []
r_squared_test = []


for k in range(3, 35, 2): # From 3 to 35 variables (every single one)
    selector = SelectKBest(f_regression, k = k)
    X_train_transformed = selector.fit_transform(X_train, y_train)
    X_test_transformed = selector.transform(X_test)
    regressor = LinearRegression()
    regressor.fit(X_train_transformed, y_train)
    no_of_features.append(k)
    r_squared_train.append(regressor.score(X_train_transformed, y_train))
    r_squared_test.append(regressor.score(X_test_transformed, y_test))
    
sns.lineplot(x = no_of_features, y = r_squared_train, legend = 'full')
sns.lineplot(x = no_of_features, y = r_squared_test, legend = 'full')
plt.show()

/anaconda3/lib/python3.8/site-packages/sklearn/feature_selection/_univariate_selection.py:302: RuntimeWarning: invalid value encountered in true_divide
  corr /= X_norms
/anaconda3/lib/python3.8/site-packages/scipy/stats/_distn_infrastructure.py:1932: RuntimeWarning: invalid value encountered in less_equal
  cond2 = cond0 & (x <= _a)

As soon as I changed to random_state=0 in the code above it worked!, but I have no idea why. I have read about the random_state parameter and people said it doesn't matter which value is assigned to it.

From the Docs:

An integer

Use a new random number generator seeded by the given integer. Using an int will produce the same results across different calls. However, it may be worthwhile checking that your results are stable across a number of different distinct random seeds. Popular integer random seeds are 0 and 42.

why did the random_state parameter affect the SelectKbest ?




Why we get error from choice attribute but i don't use choice

Why we get error from choice attribute but I don't use choice !! This is my python code:

from random import randint
User , Computer = 0 , randint(0,11)
# check process
while Computer != User :
   User = int(input('Enter Your number :'))
   print('Very good')

Error : in print(random.choice(a))
AttributeError: partially initialized module 'random' has no attribute 'choice' (most likely due to a circular import) i dont know why i take this error sorry i am Beginner thanks




how to remove text added in a modal from an object after closing it

I'm a beginner and I'm trying to add random jokes to a modal from an object. Until now everything works. What I want now is to clear the modal after I click the close button so that every time I click "lets have a laugh..." a new joke will appear without having to refresh the page.

Other suggestions to make the code cleaner are welcome.

const JokesObject = {
joke1: {
    question: "what is the ultimate paradox",
    answer: "There is no absolute truth"
},
joke2: {
    question: "what turns coffee into code",
    answer: "A programmer"
  }
};

function jokie () {

const ListJokes = Object.keys(JokesObject);
let randomJoke = ListJokes[Math.floor(Math.random() * ListJokes.length)];   
const joke = JokesObject[randomJoke];

const jokeModalQuestion = document.getElementById('joke');
const jokeModalAnswer = document.getElementById('answer');
const addJoke = document.createTextNode(joke.question);
const addAnswer = document.createTextNode(joke.answer);

jokeModalQuestion.appendChild(addJoke);

function answer () {
    jokeModalAnswer.appendChild(addAnswer);
 };

document.getElementById('giveAnswer').addEventListener('click', answer)
};

jokie();

const toggleModal = () => {
document.querySelector('.modal').classList.toggle('modal-hidden');
};

document.querySelector('.show-modal').addEventListener('click', toggleModal);

document.querySelector('.modal__close-bar').addEventListener('click', toggleModal);



Generate random numbers with given expected number of repetitions

Given n and r. Generate n random numbers between [0,1] with the expected number of repetitions r.
The method that is recommended for this is to choose a random number between [0,1] and
chose it's a number of repetitions between [1,2r]. Not sure how choosing repetitions between
[1,2r] will lead to a total expected number of repetitions to r.
To generate a random value it seems one could use Math.random() function in JAVA.

Also choosing when we are choosing the repetitions between [1,2r]. suppose the repetition is 3
Then does one choose the next n-1 numbers or n-3 numbers so that the expected number of repetitions
remain r.




How to make a random matrix without numpy

I came across this problem: create a random matrix without numpy.

I searched a bit for the term, but I didn't get it. Do u have to re-seed everytime I'm searching for a random number? My solution to this was:

import random

def matrix_random_number(n_filas, n_columnas, num_decimals=2):
    blank = [0]
    row = blank*n_filas
    array = [row]*n_columnas
    
    for j in range(n_columnas):
        for i in range(n_filas):
            array[j][i] = random.randint(0,100*10**num_decimals)/10**num_decimals
    return array

But my output was:

[[80.91, 47.46, 15.86, 77.16, 92.47, 54.92, 2.76, 97.42, 14.99, 15.97],
 [80.91, 47.46, 15.86, 77.16, 92.47, 54.92, 2.76, 97.42, 14.99, 15.97],
 [80.91, 47.46, 15.86, 77.16, 92.47, 54.92, 2.76, 97.42, 14.99, 15.97],
 [80.91, 47.46, 15.86, 77.16, 92.47, 54.92, 2.76, 97.42, 14.99, 15.97],
 [80.91, 47.46, 15.86, 77.16, 92.47, 54.92, 2.76, 97.42, 14.99, 15.97],
 [80.91, 47.46, 15.86, 77.16, 92.47, 54.92, 2.76, 97.42, 14.99, 15.97],
 [80.91, 47.46, 15.86, 77.16, 92.47, 54.92, 2.76, 97.42, 14.99, 15.97]]

So that this is clearly not random. How to improve? Why is this bad code? Thanks in advance




jeudi 25 février 2021

Generate custum number of lorem ipsum words in html

With lorem+TAB I am able to generate some random words.

<body>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmodtempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodoconsequat. Duis aute irure dolor in reprehenderit in voluptate velit essecillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.</body>

Now I want to generate more number of words, say 100 sentences of lorem text. Is there any way to do it in sublime text 3?




SQLite recalculates random() multiple times in subquery or CTE

If I run the following query:

WITH cte AS(SELECT random() AS rand)
SELECT rand,rand FROM cte;

the value rand is calculated once, and the same value appears twice in in the result.

If I run that with a table:

DROP TABLE IF EXISTS data;
CREATE TABLE data(n int);
INSERT INTO data(n) VALUES(1),(2),(3),(4),(5);
WITH cte AS(SELECT random() AS rand FROM data)
SELECT rand,rand FROM cte;

… the value for rand is recalculated for every instance, and so each row in the result set has two different values. See http://sqlfiddle.com/#!5/73fd4/1

I expected random() to be recalculated for each row, but I didn’t expect expect that the rand value be recalculated after the CTE.

I don’t think this is standard behaviour, and it certainly isn’t how PostgreSQL, SQL Server and MySQL work.

How do I get SQLite to calculate the rand value only once per iteration?




Python Script for generating random numbers within a given range every 5 minutes interval with timestamp

I'm looking for a script that loops forever and keep generating random numbers every 5 minutes with timestamp(e.g. the excel file will have two columns [timestamp = jan 5 14:00][value = 120]) and insert it into an excel file. This program will run forever and keep populating the excel file, and when re-run, it continues to populate from the last stopped row. I have a program to generate a random number for a certain number of times and store them into excel. But the value is always replaced. I'm not sure how to do the rest. Please help. Thank you.

import pandas as pd
import random
from xlsxwriter import*


def Rand(start, end, num): 
    result = [] 
  
    for j in range(num): 
        result.append(random.randint(start, end)) 
  
    return result 
  
num = 100
start = 100
end = 151
random = (Rand(start, end, num))



df = pd.DataFrame.from_dict({'Random No':random})
df.to_excel('test2.xlsx', header=True, index=False)

enter image description here




Why sort() using Math.random() is different from using a number?

I have two different results using the same range of numbers. Sorry if it is obvius, I am a total beginner and couldn't find the answer for this.

This below shuffles the array.

(function(array) {
    array.sort(() => 0.5 - Math.random());
    console.log(array);
})([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
// Output: [Shuffled array]

However, if I manually write a random number between -0.5 and 0.5, I can't shuffle it. Why??

(function(array) {
    array.sort(() => 0.2145467);
    console.log(array);
})([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
// Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]



Do-While loop breaks despite not fulfilling conditions

This is probably a simple fix but when I run the loop below r1 and r2 sometimes don't fulfill the conditions to break the loop but the loop still breaks and returns the values. For example the loop breaks even if Math.abs(r1-r2)<3

  let r1
  let r2
  do{
    r1 = Math.round(Math.random()*(elementsToSwap.length-1))
    r2 = Math.round(Math.random()*(elementsToSwap.length-1))
  }while(
    (Math.abs(r1-r2)<3)
    &&prev.includes(r1)
    &&prev.includes(r2)
  )

What am I doing wrong?

elementsToSwap and prev are both arrays.




How do I fix this problem with openpyxl and random integers?

so i am coding in python using the openpyxl module, which I am using to find cells in my excel worksheet. Now the code i am using goes as follows:

#Create a function for the NEXT QUESTION button

def next():

#This part will make the selection random

random_question = randint(column_a, 1000)

Now in order for randint to funciton, it has to have 2 components, as far as I have understood it, which is why the (column_a, 1000) is like it is (column_a is defined as a variable elsewhere in the code).

My problem is that I only need it to return 1 cell from the collum A, but it should not be looking for the 1000th value, is there a way to change the 1000 out with something else, so it will look to the end of where there is nothing more written?

thank you in advance




Keep getting None value after calling string from list chosen by using random [duplicate]

So Im making game Rock,paper,Scissors and my problem is I keep getting None value after calling variable that contains randomly chosen string from list ''tools''.

import random

tools =["Rock","Scissors","Paper"]
def computer_predicion():
    computer_pred = random.choice(tools)
print(computer_predicion())



sample from more than one column

I have a df of numeric character values which looks like this -

set.seed(89)
a <- sample(1:30, 25, replace = T) 
b <- sample(1:30, 25, replace = T) 
d <- cbind(a,b)

I now want to sample into two new columns V1 and V2 for the length as d, from those distinct character values, with replacement, but I keep getting replicated columns (V1 = V2).

This feels like I am missing something obvious ?




Random Quiz App without duplication in Swift [duplicate]

I try to make quiz app in Swift and want to display the quiz randomly without repeating .

I think the first thing I have to do is to make quiz random and the second is to display without duplication .

But I haven't been able to do the first thing . I'm very beginner with programming . Please help my code !

This code below is to make quiz random .


【Question.swift】  

import Foundation

struct Question {
    let text: String
    let answers: [String]
    let rightAnswer: String
    init(q: String, a: [String], correctAnswer: String) {
        text = q
        answers = a
        rightAnswer = correctAnswer
    }
}


【QuizBrain.swift】 

import Foundation

struct QuizBrain {

var randomNumber = Int.random(in: 0..<11) 
var questionNumber = 0

let quiz = [
        Question(q: "Which is C ?", a: ["B", "C", "D"], correctAnswer: "C"),
        Question(q: "Which is F?", a: ["F", "G", "H"], correctAnswer: "F"),
        Question(q: "Which is J ?", a: ["H", "I", "J"], correctAnswer: "J"),
        Question(q: "Which is L ?", a: ["L", "M", "N"], correctAnswer: "L"),
        Question(q: "Which is P ?", a: ["P", "Q", "R"], correctAnswer: "P"),
]


func randomQuiz() ->  Question {
        let random = quiz.shuffled() 
        let randomQuiz = random[randomNumber] 
        return randomQuiz
    }

mutating func nextQuestion() {
        if questionNumber + 1  < quiz.count {
            questionNumber += 1
        } else {
            questionNumber = 0
        }
    }

mutating func getText() -> String {
        return randomQuiz().text
}

mutating func getAnswers() -> [String] {
        return randomQuiz().answers
}

mutating func checkBeginnerAnswer(userAnswer: String) -> Bool {
        if userAnswer == beginnerQuiz[questionNumber].rightAnswer {
            return true
        } else {
            return false
        }
    }
}


【VocabularyController.swift】 

import UIKit
import AVFoundation

class VocabularyController: UIViewController {

    @IBOutlet weak var questionLabel: UILabel!
    @IBOutlet weak var choice1: UIButton!
    @IBOutlet weak var choice2: UIButton!
    @IBOutlet weak var choice3: UIButton!

    var quizBrain = QuizBrain() 
    override func viewDidLoad() {
        super.viewDidLoad()
        updateUI()
    }

  @IBAction func answerButtonPressed(_ sender: UIButton) {
        let userAnswer = sender.currentTitle!
        let userGotItRight = quizBrain.checkAnswer(userAnswer: userAnswer)

        quizBrain.nextQuestion() 

        Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(updateUI), userInfo: nil, repeats: false)
  }

@objc func updateUI() {
        questionLabel.text = quizBrain.getText()   
        let answerChoices = quizBrain.getAnswers() 

        choice1.setTitle(answerChoices[0], for: .normal) 
        choice2.setTitle(answerChoices[1], for: .normal)
        choice3.setTitle(answerChoices[2], for: .normal) 
   }
}



There is no error with this code . And the quiz is randomized. But I can't display the question with the answer which I want to display .

For example when the q in Question is "Which is F? , the a in Question should be ["F", "G", "H"] . But sometimes the a is ["P", "Q", "R"] or sometimes ["L", "M", "N"]... The answers don't correspond the text which be corresponded .

So please tell me how I can display the quiz randomly and correctly . And I would like to know how I can display it without duplication in this code !

Thank you in advance !




How to generate 8 digit unique identifier to replace the existing one in python pandas

Let us say I have the following simple data frame. But in reality, I have hundreds thousands of rows like this.

df

ID              Sales
倀굖곾ꆹ譋῾理     100
倀굖곾ꆹ         50
倀굖곾ꆹ譋῾理     70
곾ꆹ텊躥㫆        60

My idea is that I want to replace the Chinese digit with randomly generated 8 digits something looks like below.

ID              Sales
13434535        100
67894335         50
13434535         70
10986467         60

The digits are randomly generated but they should keep uniqueness as well. For example, row 0 and 2 are same and when it replaced by a random unique ID, it should be the same as well.

Can anyone help on this in Python pandas? Any solution that is already done before is also welcome.




Increase drop chances based on the number

Good day, there is a task. Take the number N (from 1 to 1000)

From a random function, we need a number R from 1 to 1,000,000

Moreover, if R = 950,000-990000. Then we get a unique item And if 990000-1000000 then a legendary item falls to us

Problem. Come up with math so that with an increase in N, the chance of dropping unique and legendary items increases.

I would like to hear your solutions, because I did not think of mine. Thank!




mercredi 24 février 2021

MGID Ads are not visible on Google AMP Cached Pages

I am using MGID and Google AdSense for monetization. On AMP Pages like below both Ad Network are working fine.


https://example.com/post1/amp/

But on Google AMP Cached Pages like below, MGID Ads are not visible.

https://example-com.cdn.ampproject.org/c/s/example.com/post1/amp/

MGID provides different Ad codes for AMP Pages. Yet, that code is only working on AMP pages, not on Google AMP Cached Pages.




I want to make a random number guessing game in tkinter

I want a higher or lower game using tkinter in the def tookawhile(): from 0 too 1000 and I want it to go for 3 rounds. When round 3 is over I want it to say "Well done now go user as there is No game" where the text box is locked as the person cant edit it

import tkinter as tk
import random
import time
from tkinter import *
playing_game = False
def to_make_video():
    global btn1
    text_widget.configure(state='normal')
    msg = "People who are watching go hit that subscribe button and"+\
          " hit that like button also hit that little bell to turn on"+\
          " notifcations"
    text_widget.delete("0.0", "end")
    text_widget.insert("end", msg)
    text_widget.configure(width=25, height=6)
    text_widget.configure(state='disabled')
    btn1.destroy()
    start_game()

def tookawhile():
 text_widget.configure(state='normal',height=4)
 text_widget.delete("0.0","end")
 text_widget.insert("end", "User lets play a game if you arent going to leave\nI have a number between 0 and 1000 in my memory chip can you guess it?")


def whyisthereanapp():
  text_widget.configure(state='normal',width=29,height=2)
  text_widget.delete("0.0","end")
  text_widget.insert("end","Well the creator released it by accident")
  text_widget.configure(state='disabled')
  btn.destroy()
  time.sleep(10)
  tookawhile()
def game_won():
    # When the button is pressed:
    global playing_game
    text_widget.configure(state='normal')
    playing_game = False
    text_widget.delete("0.0", "end")
    text_widget.insert("end", "Why aren't you leaving?")
    text_widget.configure(width=23, height=1)
    text_widget.configure(state='disabled')
    btn.destroy()
    #btn2 = Button(title="I want to play")
    #btn2.pack()

def move_button():
    global playing_game
    # If the game is over stop moving the button
    if not playing_game:
        return None
    # Pick the next random position for the button
    numberx = random.randint(1, 600)
    numbery = random.randint(1, 470)
    btn.place(x=numberx, y=numbery)
    # After 500 milliseconds call `move_button` again
    # You can change the value to make it faster/slower
    root.after(200, move_button)

def start_game():
    # Start the game
    global playing_game
    btn.config(command=game_won)
    playing_game = True
    # Start the loop that keeps moving it to new random positions
    move_button()

def toplayagame():
  text_widget.configure(state='normal')
  text_widget.delete("0.0", "end")
  text_widget.insert("end", "Well there is no game")
  text_widget.configure(width=21)
  text_widget.configure(state='disabled')
  btn1.destroy()
  btn.configure(text='Then why is there an application?',width=25,command=whyisthereanapp,background='Blue',foreground='Yellow',activebackground='Black')
  btn.place(x=349, y=470)
  
def pressed():
    global btn1
    # Ask the user why they are here
    text_widget.configure(state='normal')
    text_widget.delete("0.0", "end")
    text_widget.insert("end", "Why are you here?")
    text_widget.configure(width=17)
    text_widget.configure(state='disabled')
    btn.place(x=190, y=470)
    btn.configure(text="To play a game", width=12, command=toplayagame)

    btn1 = tk.Button(root, bd=10, text="To make a video", bg="grey", fg="white",
                     activebackground="white", activeforeground="black",
                     height=1, width=15, command=to_make_video)
    btn1.place(x=1, y=470)

# Create a window
root = tk.Tk()
root.title("There is no game")
root.geometry("1050x1400")

text_widget = tk.Text(root, height=1, width=10)
text_widget.pack()
text_widget.insert(tk.END, "Hello user")
text_widget.configure(state='disabled')

btn = tk.Button(root, bd=10, text="Hello", activebackground="black",
                activeforeground="white", bg="grey", fg="white", height=1,
                width=4, command=pressed)
btn.place(x=455, y=470)

# Run tkinter's mainloop
root.mainloop()



Python random number program

I'm trying to write a program that has a function that takes in three arguments and prints one integer.

Specific details:

  • Argument #1 should correspond to the size of a np.randint that has values from 0 to 10.
  • Argument #2 is an integer that you will multiply the randint by.
  • Argument #3 is a value you will index the result of the multiplication by.

Random seed set to 42.

You will print the integer that was indexed as ‘Your random value is x’ where x = the result of the indexing.

python3 reallyrandom.py 59 2 7  

Should generate the following:

Your random value is 12 

I can make the program work if I write it like this:

import numpy as np
import pandas as pd
import random

def reallyrandom(arg1, arg2, arg3):
    
    int1=int(arg1)
    int2=int(arg2)
    int3=int(arg3)

    np.random.seed(42)

    x=np.random.randint(0,10, size=int1)
    y=x*int2
    z=y[int3]

    print("Your random value is {}".format(z))

reallyrandom(59,2,7)

It also works if I write it like this:

import numpy as np
import pandas as pd
import random

def reallyrandom():
    arg1=input()
    arg2=input()
    arg3=input()
    int1=int(arg1)
    int2=int(arg2)
    int3=int(arg3)

    np.random.seed(42)

    x=np.random.randint(0,10, size=int1)
    y=x*int2
    z=y[int3]

    print("Your random value is {}".format(z))

reallyrandom()

But when I try to switch it to this style, it gives no output. I'm confused by the whole sys thing. Please help me understand it.

import numpy as np
import pandas as pd
import random
import sys

def reallyrandom():
    arg1=sys.argv[1]
    arg2=sys.argv[2]
    arg3=sys.argv[3]
    int1=int(arg1)
    int2=int(arg2)
    int3=int(arg3)

    np.random.seed(42)

    x=np.random.randint(0,10, size=int1)
    y=x*int2
    z=y[int3]

    print("Your random value is {}".format(z))



reallyrandom()

I also tried like this unsuccesfully:

import numpy as np
import pandas as pd
import random
import sys

def reallyrandom():

    int1=int(arg1)
    int2=int(arg2)
    int3=int(arg3)

    np.random.seed(42)

    x=np.random.randint(0,10, size=int1)
    y=x*int2
    z=y[int3]

    print("Your random value is {}".format(z))


if __name__ == '__main__':
    arg1=sys.argv[1]
    arg2=sys.argv[2]
    arg3=sys.argv[3]
    reallyrandom()



Randomize the order of an html list [duplicate]

I was was wondering if it would be possible to randomize the order of a list in HTML,css, and javascript? Basically just the order would be randomized each time. Here is some very simple code just as a starting point:

<ul>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>  



How to reorder the results of wordpress shortcode?

I'm currently working on a website that used the DynamicUserDirectory plugin, and it's shortcode displays a search bar followed by several divs containing the user information.

What I want to do is randomize the order of the users, and editing the plugin itself probably isn't the best way because it would get overwritten during an update.

Is there any way to write my own shortcode function that stores the results of the user directory shortcode, reorders it, then returns the new content? I'm open to all suggestions.




Why does my page fall into the infinite loop?

function randomNumber(){
    var value;
    var flag = false;
    var tds = document.querySelectorAll('td');
    do{
        value = Math.round(Math.random() * (26 - 1) + 1);
        for(var t = 0; t < tds.length; t++){
            if(tds[t].innerHTML == value)
                flag = true;
        }
        if(!flag){
            return value;
        }
    }while(flag == true)
}

This function returns a random number for innerHTML of a new td. In case there are other tds with the same number as this code generates, the loop starts once again. If the generated number is unique, I add it to the innerHTML of a new td. But I can't even load the page since I run into an infinite loop, but no matter how hard I tried, I couldn't notice the problem in logic of this code.




bash, How to do a given function more random by adding a seed?

How to do given random function, more random by adding a seed ?

The question is related on Linux like Debian or Ubuntu, bash and a given function which use RANDOM.

Given function which should be more random:

getRND(){
    min="${1:-1}"   ## min is the first parameter, or 1 if no parameter is given           
    max="${2:-100}" ## max is the second parameter, or 100 if no parameter is given
    rnd_count=$((RANDOM%(max-min+1)+min));
    echo "$rnd_count"
}

var=$(getRND -10 10) # Call the function
echo $var # output

Ideas for a seed:

  • use actual date and time (the time in ms if possible) and doing a shuff with this and use it as seed
  • if one other seed create a more random random, use the better one



Trouble with storing random number and Yes No loop

I have written a c code to generate random numbers(each time generate a different set of random numbers) and need to ask the user if want to generate another random number. If the user reply yes, the program need to generate another random number; if the user replies No, the program needs to calculate the total and average of the random numbers.

My problem is I don't know how to store the random number and there is a problem with my loops.

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

main() 
{
    int sum=0, i, num[100], arr[100];
    float avg;
    char choice;
    
    srand(time(0));

        for(i=0; i<100; i++)
        {
            arr[i] = rand();
            printf("Random number generated: %d", arr[i]);
            fflush(stdin);
            printf("\nGenerate another random number(y/n)? ");
            scanf("%c", &choice);
            if(choice == 'n' || choice == 'N')
            {
                sum += arr[i];
                avg = sum / i;
        
                printf("\n::TOTAL     : %d", sum);
                printf("\n::AVERAGE   : %.2f", avg); 
            }
        }    
    system("PAUSE");
}

The correct output should be like this: Correct output




mardi 23 février 2021

Using random.choice based on condition

I have a file with like this with 10000 rows:

         Col1   Col2        
1        G1     h5
2        G2     t5
3        JG     d2
4        G2     d2
5        G1     D5
6        GG     d2

I want to replace the string in col2 based on the outcome of random.choice each time it finds the pattern. for example if I find d2 in col2 I would want to use random.choice("a2","b2","g2") and want something like below:

        Col1   Col2        
1        G1     h5
2        G2     t5
3        JG     a2
4        G2     b2
5        G1     D5
6        GG     g2

So each time a pattern match occurs it has to print a random choice.

I have tried using for loop followed by if condition. but for some reason, I am getting it wrong.




How to properly add gradually increasing/decreasing space between objects?

I've trying to implement transition from an amount of space to another which is similar to acceleration and deceleration, except i failed and the only thing that i got from this was this infinite stack of mess, here is a screenshot showing this in action:

enter image description here

you can see a very black circle here, which are in reality something like 100 or 200 circles stacked on top of each other

and i reached this result using this piece of code:

def Place_circles(curve, circle_space, cs, draw=True, screen=None):
    curve_acceleration = []
    if type(curve) == tuple:
        curve_acceleration = curve[1][0]
        curve_intensity = curve[1][1]
        curve = curve[0]
        #print(curve_intensity)
        #print(curve_acceleration)
    Circle_list = []
    idx = [0,0]
    for c in reversed(range(0,len(curve))):
        for p in reversed(range(0,len(curve[c]))):
            user_dist = circle_space[curve_intensity[c]] + curve_acceleration[c] * p
            dist = math.sqrt(math.pow(curve[c][p][0] - curve[idx[0]][idx[1]][0],2)+math.pow(curve [c][p][1] - curve[idx[0]][idx[1]][1],2))
            if dist > user_dist:
                idx = [c,p]
                Circle_list.append(circles.circles(round(curve[c][p][0]), round(curve[c][p][1]), cs, draw, screen))

This place circles depending on the intensity (a number between 0 and 2, random) of the current curve, which equal to an amount of space (let's say between 20 and 30 here, 20 being index 0, 30 being index 2 and a number between these 2 being index 1).

This create the stack you see above and isn't what i want, i also came to the conclusion that i cannot use acceleration since the amount of time to move between 2 points depend on the amount of circles i need to click on, knowing that there are multiple circles between each points, but not being able to determine how many lead to me being unable to the the classic acceleration formula.

So I'm running out of options here and ideas on how to transition from an amount of space to another. any idea?

PS: i scrapped the idea above and switched back to my master branch but the code for this is still available in the branch i created here https://github.com/Mrcubix/Osu-StreamGenerator/tree/acceleration . So now I'm back with my normal code that don't possess acceleration or deceleration.

TL:DR i can't use acceleration since i don't know the amount of circles that are going to be placed between the 2 points and make the time of travel vary (i need for exemple to click circles at 180 bpm of one circle every 0.333s) so I'm looking for another way to generate gradually changing space.




C++ 2D int array randomly shuffle

I am trying to make a program that simulates a game of dominoes. For this I have to randomly shuffle the pile of dominoes but I cannot figure out how. I have searched this but everything I have tried has failed. Is there a way to do this? Here is what I was attempting, the problem with this though is that it says that Seed and Time are not declared in this scope:

#include <iostream>
#include <vector>
#include <ctime>
#include <algorithm>
#include <cstdlib>


using namespace std;

class CRandom {
   public:
      vector<int>* shufflePile(){
      
         vector<int>* pile = new vector<int>;
         
         for(int i=0; i<=27; i++){
            pile->push_back(i);
         }
         srand( _Seed; unsigned (time( _Time 0)));
         random_shuffle(pile->begin(), pile->end());
         
   }

};

class CDominoes {
   int pieces [28][3] =
      {
         {0,0,1}, //1
         {1,1,1}, {1,0,1}, //2,3
         {2,2,1}, {2,1,1}, {2,0,1}, //4, 5, 6
         {3,3,1}, {3,2,1}, {3,1,1}, {3,0,1}, //7, 8, 9, 10
         {4,4,1}, {4,3,1}, {4,2,1}, {4,1,1}, {4,0,1}, //11, 12, 13, 14, 15
         {5,5,1}, {5,4,1}, {5,3,1}, {5,2,1}, {5,1,1}, {5,0,1}, //16, 17,18, 19, 20, 21
         {6,6,1}, {6,5,1}, {6,4,1}, {6,3,1}, {6,2,1}, {6,1,1}, {6,0,1} //22, 23, 24, 25, 26, 27, 28 
      };
};

class CPlayer {
};

class CTable {
};

int main() {
}



Numpy error in file "mtrand.pyx" while fitting a keras model

I am using:

  • keras-rl2 : 1.0.4
  • tensorflow : 2.4.1
  • numpy : 1.19.5
  • gym 0.18.0

For the training of a DQN model for a reinforcement learning project.

My action space contains 60 dicrete values:

self.action_space = Discrete(60)

and I am getting this error after x steps:

1901/10000 [====>.........................] - ETA: 1:02 - reward: 6.1348Traceback (most recent call last):
  File "D:/GitHub/networth-simulation/rebalancing_simple_discrete.py", line 203, in <module>
    dqn.fit(env, nb_steps=5000, visualize=False, verbose=1)
  File "D:\GitHub\networth-simulation\venv\lib\site-packages\rl\core.py", line 169, in fit
    action = self.forward(observation)
  File "D:\GitHub\networth-simulation\venv\lib\site-packages\rl\agents\dqn.py", line 227, in forward
    action = self.policy.select_action(q_values=q_values)
  File "D:\GitHub\networth-simulation\venv\lib\site-packages\rl\policy.py", line 227, in select_action
    action = np.random.choice(range(nb_actions), p=probs)
  File "mtrand.pyx", line 928, in numpy.random.mtrand.RandomState.choice
ValueError: probabilities contain NaN

When I use a lower number of discrete actions (<10) it doesn't happen every time.

I found that fix but I don't understand how to apply it. I can't find any file "numpy/random/mtrand/mtrand.pyx"

Has anyone found a way to fix that error?




How to randomly allocate a set of IDs digitally, one ID per person, such that everyone knows that the particular allocations are kept private?

I have a set of UUIDs that I want to assign to a set of people. I want to deliver these UUIDs to people in a secure manner, such that everyone knows that I do not know which UUID corresponds to which person. I.e., I want it to be publicly verifiable that the assignment process was random and that the delivery process was private, and that no record is kept of the assignments and deliveries. I am having a lot of trouble figuring out how to implement this digitally.

The purpose here is to allow people to prove that they received a legitimate ID for authentication purposes, without revealing who they are in particular when they submit said ID. A real life analogy would be to have people one at a time pick a random slip of paper with their ID written on it from a jar, where everyone can see that the jar owner does not know which ID was picked by each person, and also everyone knows that every person only received one ID.

I toyed with the idea of sending a link to a private webpage via email, where people could then click one of a set of links on said webpage to claim a particular ID, but then I have no way of ensuring that each person claims only one ID without recording some kind of credential to keep track of who has already claimed an ID.




Can't figure out how to draw a maze using a minimum spanning tree in Java

So far I've been able to create an adjacency matrix so every node is connected to its neighbor and all the edges are randomly weighted. Then I have a method for finding the minimum spanning tree using the matrix, which outputs which nodes are connected. Now I need to use the MST to draw the maze, but I can't figure it out while keeping the maze 5x5.




How to solve cannot assign to function call in python?

I am supposed to write function randomWorld. It takes in two integers width and height which represent the width and height of the world and returns a dict that represents the world. I have been following the teacher algorithm idea but I am getting this SyntaxError cannot assign to function call and this is what I have done

def randomWorld(width, height):
    """Return a random world"""
    world={}
    for x in range(width):        
      for y in range(height):
        if random.randint(0,10) < 3:
         world.Cell(x,y)=True
    return world



Random maze generator in Java programming language [closed]

What are my alternative options on graphing a random maze since I cant upload an image? I think it would be a good idea to use panels and change the size of the borders to make it look like there are walls there but i think it would be hard to code. Any other suggestions?




why is the random variable I decleared not changing even though I have created an object for it using randint function

import random
ran = random.randint(000,999)

n = int(input("Enter Any Number = "))

list=[]

for i in range(n):
    list.append(ran)
    print(i,"----",list)

print(list)



getting Python 3.9 to recognize parameters and act accordingly (Interactive storytelling)

I'll try to keep it short and sweet.

I'm writing an interactive story that changes based on the "roll" of a d20 dice. I've managed to figure out getting started, but I've hit a point where I don't think Python is actually listening to the parameters I'm giving it, because it kind of just does whatever.

Essentially, here's what's supposed to happen:

Player agrees that they want to play the game -> Player Rolls dice -> Game uses the randomly rolled number to determine which start that the player will have.

What's currently happening is, all goes well until it's supposed to spit out the start that the player has. It doesn't seem to actually decide based on my parameters. For example, you're supposed to have the "human" start if the player rolls 5 or less, and an "elf" start for anything between 6 and 18. Here's what happened yesterday:

    venv\Scripts\python.exe C:/Users/drago/PycharmProjects/D20/venv/main.py

Hello! Would you like to go on an adventure? y/n >> y
Great! Roll the dice.
Press R to roll the D20.
You rolled a 15!
You start as a human.
As a human, you don't have any special characteristics except your ability to learn.

The related code is below:

    def NewGame():
    inp = input("Hello! Would you like to go on an adventure? y/n >> ")
    if inp == "y" or inp == "yes":
        print("Great! Roll the dice.")
        input("Press R to roll the D20.")
        print("You rolled a " + str(RollD20()) + "!")
        PostGen()
    else:
        input("Okay, bye! Press any key to exit.")
        sys.exit()


    def PostGen():
    if RollD20() <= 5:
        print("You start as a human.")
        PostStartHum()
    elif RollD20() >= 6:
        print("You start as an elf.")
        PostStartElf()
    elif RollD20() >= 19:
        print("You lucked out, and can start as a demigod!")
        PostStartDemi()


 def RollD20():
    n = random.randint(1, 20)
    return n

def PostStartHum():
    print("As a human, you don't have any special characteristics except your ability to learn.")
def PostStartElf():
    print("As an elf, you have a high intelligence and a deep respect for tradition.")
def PostStartDemi():
    print("As a demigod, you are the hand of the gods themselves; raw power incarnated in a human form...")
    print("However, even mighty decendants of gods have a weakness. Be careful."

Thanks for all your help.




script #auto random register python

I'm trying to make python script that able to auto generated randomly register at same time But i don't know how to do it or how to start I'm beginner at python so if someone could help or have such script to modify it




PHP: Equally random shuffle records for users [closed]

I'm looking for algorithm that could randomly shuffle stuff from 2 arrays. One array is array of objects. Objects should be randomly shuffled for users (2nd arr) and every user should have similar amount of objects.

ex: Let's say I have: 5 objects

{
    "id" => 1,                                                              
    "foreign_key" => 100001,  
    "some_data" => 'some_data',  
    'user' => null  
},

3 users

$users[] = {101,222,777}

INPUT:

$objects[] = [
    {
        "id" => 1,                                                              
        "foreign_key" => 100001,  
        "some_data" => 'some_data',  
        'user' => null  
    },
    {  
        "id" => 2,  
        "foreign_key" => 100002,  
        "some_data" => 'some_data2',  
        'user' => null  
    },
    {  
        "id" => 3,  
        "foreign_key" => 100002,  
        "some_data" => 'some_data3',  
        'user' => null  
    },
    {  
        "id" => 4,  
        "foreign_key" => 100003,  
        "some_data" => 'some_data4',  
        'user' => null  
    },
    {
        "id" => 5,  
        "foreign_key" => 100004,  
        "some_data" => 'some_data5',  
        'user' => null  
    }           
];  

Every object have foreign key. If some objects have the same foreign key they should go to the same user.

OUTPUT:

$objects[] = [
    {
        "id" => 1,                                                              
        "foreign_key" => 100001,  
        "some_data" => 'some_data',  
        'user' => 101  
    },  
    {  
        "id" => 2,  
        "foreign_key" => 100002,  
        "some_data" => 'some_data2',  
        'user' => 222  
    },
    {  
        "id" => 3,  
        "foreign_key" => 100002,  
        "some_data" => 'some_data3',  
        'user' => 222 
    },
    {  
        "id" => 4,  
        "foreign_key" => 100003,  
        "some_data" => 'some_data4',  
        'user' => 777  
    },
    {  
        "id" => 5,  
        "foreign_key" => 100004,  
        "some_data" => 'some_data5',  
        'user' => 101  
    }          
];  

Could sb help me?

php 5.4




Generate a list of 100 elements, with each element having a 50% chance of being 0, and a 50% chance of being a random number between 0 and 1

I am quite new in this and I am trying to learn on my own. As I said in the title, I am trying to create a list of 100 numbers whose elements are either 50% chance of being 0's or 50% change being a number between 0 and 1. I made it like the one below. It works but it is a very tedious and not well coded program. Any hints of how to make to make it better?

import random
import numpy as np

#define a list of 100 random numbers between 0 and 1
randomlist = []
for i in range(0,100):
    n = random.uniform(0,1)
    randomlist.append(n)
print(randomlist)


#create a list of 100 numbers of 0's and 1's
def random_binary_string(length):
    
    sample_values = '01' # pool of strings
    result_str = ''.join((random.choice(sample_values) for i in range(length)))
    return (result_str)

l=100
x=random_binary_string(l)
x1=np.array(list(map(int, x)))
print(x1)


#combine both lists. Keep value if of the binary list if it is equal to zero. Else, substitute it by the value of randomlist
#corresponding to the index position
finalist=[]
for i in range(len(x1)):
    if x1[i]==0:
        finalist.append(x1[i])
    else:
        finalist.append(randomlist[i])
        
print(finalist)    

Thanks a lot!




Jupyter Notebook - Random Module Flip a coin

I'm very new to this website and I am a novice at Python, I've just started. This may have been asked many times now, but I'm not sure why the following code is not running:

import random

output={"Heads":0, "Tails":0}
coin=list(output.keys())

for a in range(10000):
    output[random.choice(coin)]+=1
    
print("Heads:", output["Heads"])
print("Tails:", output["Tails"])

Expected Result : It should randomly give you the total of how many times it was heads and tails whilst flipping the coin 10,000 times.

Actual Result: TypeError: 'list' object is not callable

I've googled this problem and it seems you have to use a square bracket but I'm not sure where to amend this. This code works for Python IDLE but not for Jupyter Notebook.

Any help would be much appreciated, thank you.

Peter.




How to set random value from a set of strings in Batch file?

How to set a random value from a set of strings in a Batch file?

I have some strings in my file like "You failed!", "Game over!", "OOF!!" etc.

Is there a way to put them in an array/list and get a random string from that list?




Random item in array by ratio PHP

I am having problems getting items in arrays by rate
I have total record : 50
Array:

$array = ['banana' => 30, 'apple' => 50, 'orange' => 20]

I want in 50 records there will be 30% of banana, 50% of apple and 20% of orange. This is my code:

public function randomArray(){
    $total = 50;
    $array = ['banana' => 30, 'apple' => 50, 'orange' => 20]; //ratio total must be 100%

    $result = [];
    for($i = 1; $i <= $total; $i++){
        $rand = $array[array_rand($array)];
        $result[] = $rand;
    }

    dd($result);
}

I don't know how to apply ratio yet.
Thanks for any help.




lundi 22 février 2021

randint method returns the same value on each execution

in the below code i am trying to learn how to use threads with synchronization. as shown below in the code i generate a thread every 3 seconds an a random number is passed to the method isNumPrime(...) to check if the generated number is prime or not. the problems i am facing are

1-the output i receive every time i run the code is the same. please have a look at the output below. the same random numbers are generated every time i press ctrl+f5 is

        thread_1 = threading.Thread(group = None, target = self.isNumPrime, 
        name='Thread_1', args = (), kwargs=dict(targetNum=randint(0,100)), 
        daemon = None)

indeed generates random nmbers`?? because what i am getting is not randomly generated numbers. i expect to receive differently generated numbers each time i press ctrl+f5

2-given the output belwo, why i am receiving repeated output of "in loop: targetNum: xx"?? it must be displayed once for each single iteration with a number from range of (3,targetNum)

code:

import threading
import logging
import time
from random import seed
from random import randint

class ThreadsWithSync(threading.Thread):

    def __new__(cls):
    """
    For object creation
    """
    print("cls: %s"%(cls))
    #cls.onCreateObject()
    instance = super(ThreadsWithSync, cls).__new__(cls)
    #print("instace: %s"%(instance.__repr__)) #activate this line whenever an informative and descriprtive text about the instance is needed to be displayed
    return instance
    
    def __init__(self):
    """
    For object initialization
    """
    #print("self: %s"%(self)) 
    threading.Thread.__init__(self) #to initialize the super class
    print("self: %s"%(self))
    seed(1)

    @classmethod
    def onCreateObject(cls):
    """
    This will be invoked once the creation procedure of the object begins.
    """

    def __repr__(self):
    """
    similar to toString in Java
    """
    return "\n__class__: " + repr(self.__class__) +"\n__new__:" + repr(self.__new__) + "\n__str__: " + repr(self.__str__) + "\n__sizeof__: " + repr(self.__sizeof__)
    
    def isNumPrime(self, targetNum):
    
    if targetNum == 0 or targetNum == 1:
        print("targetNum passed to method, will return false: %s"%(targetNum))
        return False

    if targetNum == 2:
        print("targetNum passed to method will return true: %s"%(targetNum))
        return True

    isPrim = True
    for i in range(3,targetNum):
        print("in loop: targetNum: %s"%(targetNum)) 
        if targetNum % i == 0:
            isPrim = False
            break
    print("is %s a prime : %s"%(targetNum, isPrim)) 
    return isPrim

    def spawnThread(self):
    if __name__ == "__main__":
        self.main()

    def main(self):
    while True:
        thread_1 = threading.Thread(group = None, target = self.isNumPrime, name='Thread_1', args = (), kwargs=dict(targetNum=randint(0,100)), daemon = None)
        #thread_2 = threading.Thread(group = None, target = self.isNumPrime, name='Thread_2', args = (), kwargs=dict(targetNum=randint(0,100)), daemon = None)
        thread_1.start()
        #thread_2.start()
        time.sleep(3)

t1 = ThreadsWithSync()
t1.spawnThread()

output:

in loop: targetNum: 17
in loop: targetNum: 17
in loop: targetNum: 17
in loop: targetNum: 17
in loop: targetNum: 17
in loop: targetNum: 17
in loop: targetNum: 17
in loop: targetNum: 17
in loop: targetNum: 17
in loop: targetNum: 17
in loop: targetNum: 17
in loop: targetNum: 17
in loop: targetNum: 17
in loop: targetNum: 17
is 17 a prime : True
in loop: targetNum: 72
is 72 a prime : False
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
is 97 a prime : True
in loop: targetNum: 8
in loop: targetNum: 8
is 8 a prime : False
in loop: targetNum: 32
in loop: targetNum: 32
is 32 a prime : False
in loop: targetNum: 15
is 15 a prime : False
in loop: targetNum: 63
is 63 a prime : False
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
...
...
... 
...
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
in loop: targetNum: 97
is 97 a prime : True
in loop: targetNum: 57



In SwiftUI can I create two actions from one button? I want two random colors

I want a single button to change two color swatches to random colors. I have found code for changing one swatch. https://www.youtube.com/watch?v=iMr4rv4rk98&feature=emb_logo @State private var randomColor1 = UIColor(red: 0.8, green: 0.1, blue: 0.5, alpha: 1)

But get an error when I try to make two random colors "consecutive statements on a line must be separated by ';'"

Searching for two actions from one button, this seems to imply it's not possible but instead just "execute the closure": Is there a way to have a button run multiple functions in SwiftUI?

And here is my code:

    @State private var randomColor1 = UIColor(red: 0.8, green: 0.1, blue: 0.5, alpha: 1)
@State private var randomColor2 = UIColor(red: 0.4, green: 0.0, blue: 0.8, alpha: 1)

var body: some View {
    ZStack {
        VStack{
            HStack {
               Rectangle()
                   .frame(width: 100, height: 200)
                   .foregroundColor(Color(randomColor1))
               Rectangle()
                   .frame(width: 100, height: 200)
                   .foregroundColor(Color(randomColor2))
           }
            Button(action: {
                self.randomColor1 = UIColor(
                    red:.random(in: 0...1),
                    green: .random(in: 0...1),
                    blue: .random(in: 0...1),
                    alpha: 1))
            
                self.randomColor2 = UIColor(
                    red:.random(in: 0...1),
                    green: .random(in: 0...1),
                    blue: .random(in: 0...1),
                    alpha: 1)
                )
            }, label: {
               Text("Make 2 Random colors")
            })
        }
    



Python get random value when using min() when there is more than one match

I have the following code:

dict = {'a': 1, 'b': 2, 'c': 5, 'd':1, 'e': 5, 'f': 1}
get_min = min(dict, key=dict.get)

As you can see here there is actually three min() matches "a", "d" and "f" with the value of 1.

This will return "a" 100% of the time as that is what min() is designed to do from what I am reading. However, I have a need where I would like to randomly get back "a", "d" or "f" instead of just "a".

Is there a way I can do this using min() or some other way (maybe lambda, I am not very good at it)? I thought this would be pretty simple but it turns out it is not :P. I can get this working with some for loops and creating lists but I was looking for the shortest way possible.

Your thoughts would be appreciated!

Thanks,

jAC




Replace pairs in the list with other possible pairs randomly

I am working on a problem where I have to calculate how many times a specific element in EB pairs with an element in EA by a fair random choice with a little twist. But before that I used random.sample, to get all the possible pairs from both lists. Then, I multiplied the pairs (repeated) to reach the sample number 100000 and selected 1% of the pairs randomly in the list.

import random
import itertools
EA=["A1","A2","A3","A4"]
EB=["B1","B6","B8","B2","B4","B89","B42","B28","B7","B96","B34","B5","B100","B55","B56","B95","B96","B20"]
EAB=random.sample(set(itertools.product(EA, EB)),72 )
First_Event=EAB*100000
percent_1 = random.sample(First_Event, 1000)
percent_1[1] #this gives for example [('A1', 'B2')] 

Now I want to replace for every pair in the percent_1 list, an element from the EA list eg: A1 in this case by either of its downstream elements randomly ("A2", "A3", "A4"), and element from EB list eg: B2 in this case, can be replaced with ant of the upstream entries ("B1","B6","B8") in EB list. Likewise I want to replace all pairs randomly with their respective EA(Downstream) and EB(Upstream) partners in percent_1 list. If it is (A4,B1) I would retain it as such in the list.




Python: Randomly Select One Key From All Keys in a Dictionary

Let's say I have accessed my dictionary keys using print (hamdict.keys())

Below is a sample output:

enter image description here

I know my dictionary list has a length of 552 elements. I want to randomly select one "key" word from my list and assign it to the variable "starter". I tried to do this with the code below (note: I have a dictionary called hamdict):

random_num = random.randint(0, len(hamdict.keys())-1)
print (random_num)
print (hamdict.keys()[random_num])

I'm able to get a value for random_num so that seems to work. But the second print returns the following error:

enter image description here

How can I fix my code?




How to store items for a single user discord.py

This is my first question so sorry if its a duplicate i did not know how to word it.

What i'm trying to do is lets say i have a >mine command it will generate random amount of coins from 100 to 500 and when i check >balance it shows that amount but I want it to be just for me so when someone else does >bal it will show only the amount they mined if that makes sense

here is the original code

from discord import *
from discord.ext import *
import random
from discord.ext import commands

bot = commands.Bot(command_prefix='>')
coinbalance = 0






@bot.command()
async def mine(ctx):
    coinsget = random.randint(100,500)
    coinstr = str(coinsget)


    global coinbalance
    await ctx.send(":pick: you went mining and collected "+coinstr+" coins!  :moneybag:")
    coinbalance = coinsget + coinbalance

@bot.command()
async def bal(ctx):
    balstr = str(coinbalance)



    await ctx.send("your balance = "+balstr)



bot.run('my token')

this was the original one I tried to use something with ctx.author but I could not come up with anything I could do.




How do I make btn01 or btn go to a random spot every 4 milliseconds and when you click on it it will stop and do something else?

I want to make any btn go to a random spot every 3 milisecounds, and when you click the random button it will do something else like print Hi and stop the button from moving. Here is the code:

I tried while a == True: but it keeps frezzing when i press the "To make a video" button and just frezzes for a while

import time
import os
import tkinter as tk
import random
from tkinter import *
from tkinter import messagebox
from tkinter import Button
import math
from tkinter import Text
from tkinter import Grid
from tkinter import Place
#from tkinter import place
window = tk.Tk()
window.title("There is no game")
window.geometry("494x300")
numberx = random.randint(1,200)
numbery = random.randint(1,200)
##def clickedrandom():
##  a = False
def toplayagame():
  print("Hi")
a = True
def tomakeavideo():
  T.delete('1.0', END)
  T.insert(tk.END, "People who are watching go hit that subscribe button and hit that like button also hit that little bell to turn on notifcations")
  T.configure(width = 25, height=6)
  while a == True:
    numberx = random.randint(1,200)
    numbery = random.randint(1,200)
    int(numberx)
    int(numbery)
    time.sleep(0.3)
    btn.place(x = numberx, y = numbery)

def pressed():
  T.delete('1.0', END)
  T.insert(tk.END, "Why are you here?")
  btn.place(x=190, y=200)
  T.configure(width = 17, height=1)
  btn.configure(text = "To play a game", width=12,command=toplayagame)
  btn1= Button(window, bd=10,text="To make a video",activebackground='White',activeforeground='Black',bg='Grey',fg='White',height=1,width=15,state=ACTIVE,command=tomakeavideo)
  btn1.pack()
  btn1.place(x=1,y=200)

T = tk.Text(window, height=1, width=10)
T.pack()
T.insert(tk.END, "Hello user")

btn = Button(window, bd=10,text="Hello",activebackground='Black',activeforeground='White',bg='Grey',fg='White',height=1,width=4,state=ACTIVE,command=pressed)
btn.pack()

btn.place(x=215, y=200)


window.mainloop()



How many codes can RandomStringGenerator generate for a length of 6?

I am using this code to generate random codes of length 6

RandomStringGenerator generator = new RandomStringGenerator.Builder()
                 .withinRange('0', 'z')
                 .filteredBy(CharacterPredicates.LETTERS, CharacterPredicates.DIGITS)
                 .build();
             String randomLetters = generator.generate(6);

RandomStringGenerator is from apache commons commons-text. I would like to understand how many codes can be generated with this code? 100K codes? 1 Million codes? How can I calculate that?




Twofold Question; Calling a random integer in a range through a function in Python 3.9

This is really a twofold question, since I know there are two errors with the same couple blocks of code.

I'm essentially making an interactive story that changes based on "rolling a d20." For instance, the player is presented with a scenario, and prompted to roll a d20. The computer generates a number between 1 and 20, and, depending on the roll, the story will pan out a certain way. The roadblock I'm having is that I've defined a function, "RollD20()," that stores the value of variable "n" as a random integer between 1 and 20 and then prints the value rolled. When I call the function, it crashes with an error saying "n is not defined."

The other part to this question, in the same block of code, is that I'm trying to get to a point where the game will ask the user essentially, do you want to play? and if the answer constitutes a yes, then the rest of it plays out. If not, the process ends. But thus far, regardless of what key I press, y or yes, n or no, or even enter, it doesn't end the process like it's supposed to, it just moves forward. Is there an easy way to fix this?

Thanks, and the code is below.


import sys
import random

while True:

    def NewGame():
        print(input("Hello! Would you like to go on an adventure? y/n >> "))
        if input == "y" or "yes":
            print("Great! Roll the dice.")
            print(input("Press R to roll the D20."))
            print("You rolled a " + RollD20(n) + "!")
        else:
            print(input("Okay, bye! Press any key to exit."))
            sys.exit()


    def RollD20():
        n = random.randint(1, 20)
        print(n)


    NewGame()

Traceback (most recent call last):
\venv\main.py", line 22, in <module>
    NewGame()
\venv\main.py", line 11, in NewGame
    print("You rolled a " + RollD20(n) + "!")
NameError: name 'n' is not defined

Process finished with exit code 1



Python get random value from comma seperated list

I have the following example string:

"jkbgr-ouuerg-uzge8-rgub, uirib-eioh-34fn-zdfe"

Now I want to choose a random key from this comma seperated list and further process it in a for loop, how can I split the list and choose a random value from it?

Kind regards




Uniform_real_distribution between 0.0 and 1.0 generates extremely low numbers in C++ always close to 0

Inside a class, I am trying to implement a method that generates a random number which would end up being a property of the class. I am calling the method randomPropertyGenerator inside the object constructor.

My minimum code for reproducing the issue looks like this

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <random>
using namespace std;

class Object {
    public:
        double randomProp;
        double randomPropGen(double a, double b);
        Object() {
            double randomProp = randomPropGen(0.0, 1.0);
        }
};

double Object::randomPropGen(double min, double max){
    std::uniform_real_distribution<double> distribution(min, max);
    std::random_device rd;
    std::default_random_engine generator(rd());
    return distribution(generator);
}

int main(int argc, char *argv[]){
    std::uniform_real_distribution<double> distribution(0.0, 1.0);
    std::random_device rd;
    std::default_random_engine generator(rd());
    
    Object o = Object();
    for (int i = 0; i < 10; i++){
        double randomProp2 = distribution(generator);
        cout << "This is randomProp from object " << o.randomProp << endl;
        cout << "This is randomProp2 inside main " << randomProp2 << endl;
        cout << "\n" << endl;
    }
    return 0;
}

When I compile the code and run it, I am getting the following results:

This is randomProp from object 8.35785e-318
This is randomProp2 inside main 0.688014


This is randomProp from object 8.35785e-318
This is randomProp2 inside main 0.263372


This is randomProp from object 8.35785e-318
This is randomProp2 inside main 0.689736


This is randomProp from object 8.35785e-318
This is randomProp2 inside main 0.392283


This is randomProp from object 8.35785e-318
This is randomProp2 inside main 0.96836


This is randomProp from object 8.35785e-318
This is randomProp2 inside main 0.401998


This is randomProp from object 8.35785e-318
This is randomProp2 inside main 0.91537


This is randomProp from object 8.35785e-318
This is randomProp2 inside main 0.608586


This is randomProp from object 8.35785e-318
This is randomProp2 inside main 0.168815


This is randomProp from object 8.35785e-318
This is randomProp2 inside main 0.631994

As you can see the randomProp when generated inside the method of my class is always the same and seems to be always extremely close to 0, whereas the randomProp generated in the main class makes more sense. Can someone tell me what I am doing wrong and how I can fix the method? Thanks for your help!




coin flipping simulator in java [duplicate]

/I want to simulate a coin flipping in java 50 times. However, the output always is "tail". Is there any problem with my code/

package chapter2;

import java.util.Random;

public class E7_coinflipping {
    public static void main (String[] args) {
        Random rand = new Random(50);
        boolean flip = rand.nextBoolean();
        System.out.print("outcome: ");
        System.out.println(flip? "tail" : "head");
    }
}
//output:

outcome: tail



random.choice() takes 2 positional arguments but 3 were given

When I type this:

rand_num = random.choice(1, 101)

It shows:

TypeError: choice() takes 2 positional arguments but 3 were given

These are all put in functions and I don't get why it says this.




Circle spacing abnormally low with acceleration

I'm going to define some terms so it's easier to understand what I'm talking about.

  • Stream: a curve or a line or a polyline of multiple circles
  • Curve intensity: a value in [0 ; 2] which will be used to call circle_space (ex:circle_space[curve_intensity[c]]) (we will see what circle_space is later)

What I'm trying to make is a stream which contain accelerations and deceleration. to make this possible, I need to either gradually increase or decrease the space between 2 circles. for this I need the speed associated with the curve composing the polyline. let's say circle_space = [20,25,30] meaning the index 0 is the minimum speed, index 2 is the maximum.

Now let's say the first curve is decelerating (by either 1 or 2), it need to gradually go from a speed to another right? And speed is defined by spacing.

here is the distance formula I'm using right now user_dist = circle_space[curve_intensity[c]] + curve_acceleration[c] * p where c is the index of one of the actual curves I'm looping through and p is the point contained in the active curve that's I'm looping through. curve in the next example is the polyline (fusion of curves and lines) curve = [curve_0, curve_1, curve_2] and curve_0 = [[0,0], [1,0], [1,1]] same format for other curves but with different coordinates.

the issue is that right now, this isn't working, causing things such as this

enter image description here

enter image description here

in this situation, curve_intensity = [2, 0, 0, 0, 1, 0] and curve_acceleration = [-0.030000000000000002, 0.0, 0.015000000000000001, -0.015000000000000001] so we can see that the first stream (between 0 and 2 on the first image) is decelerating, but we can also see that the spacing isn't equal to the minimum defined, same goes for accelerating streams. (it should gradually go from a spacing to another) how can I fix this spacing issue?

this is the code that place the circles depending on circle_space:

def Place_circles(curve, circle_space, cs, resolution, draw=True, screen=None):
    curve_acceleration = []
    if type(curve) == tuple:
        curve_acceleration = curve[1][0]
        curve_intensity = curve[1][1]
        curve = curve[0]
        print(curve_intensity)
        print(curve_acceleration)
    Circle_list = []
    idx = [0,0]
    for c in reversed(range(0,len(curve))):
        for p in reversed(range(0,len(curve[c]))):
            if not curve_acceleration and type(circle_space) == int:
                user_dist = circle_space
                dist = math.sqrt(math.pow(curve[c][p][0] - curve[idx[0]][idx[1]][0],2)+math.pow(curve [c][p][1] - curve[idx[0]][idx[1]][1],2))
                if dist > user_dist:
                    idx = [c,p]
                    Circle_list.append(circles.circles(round(curve[c][p][0]), round(curve[c][p][1]), cs, resolution, draw, screen))
            else:
                user_dist = circle_space[curve_intensity[c]] + curve_acceleration[c] * p
                dist = math.sqrt(math.pow(curve[c][p][0] - curve[idx[0]][idx[1]][0],2)+math.pow(curve [c][p][1] - curve[idx[0]][idx[1]][1],2))
                if dist > user_dist:
                    idx = [c,p]
                    Circle_list.append(circles.circles(round(curve[c][p][0]), round(curve[c][p][1]), cs, resolution, draw, screen))

code of my generator including this acceleration feature: https://github.com/Mrcubix/Osu-StreamGenerator/tree/acceleration




Repeat Text X Amount with New Numbers Each Time

I am looking for way to write a script that allows you to print a certain text 100 times and have randomize a certain value in it within a range.For example:

The text could be:

“r”: randomNumber,

“g”: randomNumber,

“b”: randomNumber

randomNumber could be a range of decimals between 0 and 1, by .01

I’m trying to find a more efficient way to duplicate a text a lot of times while having a different number in a range within the repeating text every time. So I do not need to copy a text several hundred times and rewrite the number manually. That’s very inefficient!

Any help is greatly appreciated! Thank you!




R: How do I store the outputs of 1000 die rolls, 6 times into a matrix?

How do I repeat a function n times and bind the vector outputs into a matrix? Or rather, how do I improve my function to get the intended result?

So far I have:


sample(1:6, 1000, rep = TRUE)

Have tried making into a function, but am stuck here.

droll_func = function(t){
    sample(1:6, 1000, rep = TRUE)
}