lundi 31 janvier 2022

How to embed Google Maps in form/website to get location pins from users?

I hope you are doing well.

I am part of a foundation that works with urban wildlife sightings so that human-animal conflict can be minimized. I am trying to make a form (either google form or on our website) where users can pin locations of animal sightings (not necessarily their current location) on a map which automatically saves those coords into a spreadsheet. I tried searching a lot, but couldn't find a way to embed interactive Google Maps in Google Forms or any other similarly accessible form. Any ideas how I can accomplish this?

Many thanks in advance!




How to choose a one or two-parted word(name) from file without "|" separator in python

Hello i'm looking for solution to solve my problem:

I have text file countries-and-capitals.txt with example words:

Poland | Warsaw
Sri Lanka | Colombo

and i need to write code that will pick a random name of Country or Capital.

My problem is that i can't figure out how to pick in example Sri Lanka without "|" separator and without Colombo word.

I've stuck on

import random

word = random.choice(open("countries-and-capitals.txt").readlines())

but this code picks whole line with "\n".




Getting wrong selection on an Array.sample Ruby

so I'm running into a problem where I'm trying to create a trivia game. I had a couple questions about it. Here is my current code.

  def random_question
    #Going to work a way to use a hash instead of two seperate arrays
    question_array = Array["Which state is known as the Evergreen State?", "What state is AZ?", "What state is CA?",
    'What state is known as the Last Frontier?']
    #random_question = question_array.shuffle.first
    $ind = question_array.find_index($rand)
    return $rand = question_array.sample
  end
  #If lives does not equal zero, let the game play out
  while lives != 0
    answer_array = Array["Washington", "Arizona", "California", "Alaska"]

    puts random_question()
    puts "!!!---" + $rand + "---!!!"
    puts "What is your answer?"
    #Takes answer(answer_response) and compares it to the correct answer
    answer_response = gets.chomp
    print answer_array[$ind.to_i - 1]
    if answer_response == answer_array[$ind.to_i - 1]
      puts "You're right!"
      points += 10
      puts "You have " + points.to_s + " points!"
    else
      puts "That is wrong. You lose a life!"
      lives -= 1
      puts "You have " + lives.to_s + " lives left!"
    end

Whenever I run this Ruby code in my CMD or Command Line, it spits out a totally random answer rather than the answer I would like it to display.

Does anyone have a solution? Or better yet, would anyone be able to tell me how to use a hash/dictionary where the question is linked to the answer? Please help. :)




How to fix python google form and selenium submit error?

I've been trying to test out this google form filler but keep running into an issue with the submit button. This has never happened before and I am not sure why, every time I run the code it fills in all the boxes, however, it sometimes doesn't fill out the gender question and rarely or never hits submit or submit another response. The google form link is in the code below.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
import random
from time import sleep
from random import randint
import random


s=Service('/Users) #have the current service installed here
driver = webdriver.Chrome(service=s)
url="https://forms.gle/sNCNuebKtpdF6j7t6"

driver.get(url)



datas = [

         ]



for i in range(10):
    sampleList = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

    val1 = random.choices(sampleList, weights=(5.8, 6.72, 7.5, 7.24, 6.8, 3.16, 3.5, 4.5, 1.2, 2.3), k=10)  # 25,25,50
    val2 = random.choices(sampleList, weights=(5.8, 6.7, 7.5, 7.2, 6.83, 9.1, 9.5, 8.5, 8.2, 8.3), k=10)  # 25,25,50
    val3 = random.choices(sampleList, weights=(5.8, 6.7, 7.52, 7.2, 6.8, 3.1, 4.5, 3.53, 1.2, 0.3), k=10)  # 25,25,50
    val4 = random.choices(sampleList, weights=(0.8, 2.7, 3.53, 3.2, 5.8, 4.12, 9.5, 9.5, 9.2, 9.3), k=10)  # 25,25,50
    val5 = random.choices(sampleList, weights=(1.78, 3.7, 5.5, 3.2, 6.8, 5.1, 9.51, 8.5, 8.2, 9.3), k=10)  # 25,25,50
    valx = random.randint(0,9)
    datas.append([val1[valx],val2[valx],val3[valx],val4[valx],val5[valx]]) #this list prints out alright and gets the values needed

radiobuttons = driver.find_elements(By.CLASS_NAME, "appsMaterialWizToggleRadiogroupElContainer")
print(datas)
for data in datas: #for each mini list in the big list
    print(data)


    radiolist = [0, 1, 2, 3]
    val0 = random.choices(radiolist, weights=(9.8,11.5,1.2,1.8), k=10)
    print(val0)
    rand = random.randint(0,9)
    print(rand)
    #radiobuttons[val0[rand]].click()
    radiobuttons[1].click()
    print(radiobuttons[val0[rand]])
    count = 0 #count is 0
    # contain input boxes
    textboxes = driver.find_elements(By.CLASS_NAME, 'quantumWizTextinputPaperinputInput') #these textboxes and elements seem to work and get filled out

    for value in textboxes:
        # enter value
        value.send_keys(data[count])
        print(value)
        # increment count value
        count += 1




    submit = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "span[class*='appsMaterialWizButtonPaperbuttonContent ']"))).click() #this sometimes works but if so only once

    # fill another response
    print('hi')

    another_response = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, 'Submit another response'))).click()
#this does not work at all
    #textboxes = browser.find_elements_by_class_name("quantumWizTextinputPaperinputInput")
    #radiobuttons = browser.find_elements_by_class_name("docssharedWizToggleLabeledLabelWrapper")
    #checkboxes = browser.find_elements_by_class_name("quantumWizTogglePapercheckboxInnerBox")
    #submitbutton = browser.find_element_by_class_name("appsMaterialWizButtonPaperbuttonContent")
    # close the window
driver.close()

The error either arises with the submit or submit another response button?




Same random numbers in each run in Fortran [duplicate]

I have the below Fortran code:

program Looops
  implicit none 
  
  integer, parameter:: PPPP = 3.1415     
  real*8 , Dimension(:) , allocatable  ::dkk25,dkk26,dkk27,dkk28 
  integer:: n_38
  
  Allocate(dkk25(40))
  Allocate(dkk26(40))
  Allocate(dkk27(40))
  Allocate(dkk28(40))

  call RANDOM_NUMBER(dkk25)
  call RANDOM_NUMBER(dkk26)
  dkk27(:) = sqrt(-2*log((dkk25(:))))*cos(2*pppp*(dkk26(:)))

  do n_38 = 1 , 40
    dkk28(n_38) = ((dkk27(n_38)-(sum(dkk27)/40))**2)/(40-1)
  end do
  
  print*,dkk25
end program Looops

In each run of this code I have same value of dkk25 and dkk26. I want to generate different random number in each run.




Save and load state of tf.random

I have a Tensorflow model that utilises dropout, which is controlled by the state of tf.random. At the start of my code, I set the global seed using tf.set_seed(DEFAULT_SEED). As training progresses, I want to be able to save the state of tf.random, so that if I want to stop and then resume training, I can load that state and training can continue from where it left off. For example, np.random has methods set_state() and get_state(), however I can't find an equivalent for tf.random. Am I missing something or is this not doable?

Numpy example:

np.random.set_seed(1234)

for i in range(10):
    print(np.random.randn())

x = np.random.get_state()
np.random.set_state(x)

and the state is the same as where we left it.




randomly generating pair of two people from team and scheduling the meeting every week | python

I have dataset of team member and manager. I have build a paired combination of people for meeting every week. Condition 1: team members should meet from different teams every week Condition 2: it should exclude the people which already paired from previous week.

Dataset

My Desired output should look like,

Bill + Bob Week 1

Pia + Ronnie Week 2

Any help will be much appreciated. Thank you




dimanche 30 janvier 2022

numpy randint arguments exclusive

In the official NumPy documentation (https://numpy.org/doc/stable/reference/random/generated/numpy.random.randint.html), it describes its second argument as exclusive.

random.randint(low, high=None, size=None, dtype=int)
    Return random integers from low (inclusive) to high (exclusive).

Then I though random.randint(1, 5) returns values 1, 2, 3, or 4, but it actually gives values among 1, 2, 3, 4, and 5.

What went wrong?




How to exclude values from random selection

This is independent but related to this question Randomly take wrong answers of a quiz question from dataframe column, instead of doing by hand

Using the mtcars dataset I now have managed to randomly select one value from a certain column: In this example from cyl column.

mtcars[sample(1:nrow(mtcars), 1),2]

This code will give randomly [1] 6 or [1] 8 or ...

Now I want to exclude one certain value to be chosen, in this example say cyl==8. I would store the value in a vector like:

not_select <- 8

mtcars[sample(1:nrow(mtcars), 1),2]

My question: How can I integrate not_select in mtcars[sample(1:nrow(mtcars), 1),2]

Expected Output: The random sample should not include 8

UPDATE: e.g. the output should be: 6 or 4

UPDATE II due to unclear situation:

I want to select from column cyl one value randomly. This value should not be for example 8. So the value will be 4 or 6.

Explanation: 8 is the correct answer. And I am constructing randomly false answers with the other values (e.g. 4 and 6) from cyl column.




samedi 29 janvier 2022

Generating a random number for players in a dice game

I am writing a simple dice game where two players play against each other. The winner is the one who gets the largest number when the dice is rolled. However, when I press enter to make a random number get generated for the first player, I just get new empty lines. Here is the code:

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

using namespace std;

int main()
{
    srand(time(0));
    
    int p1 = (rand() % 6) + 1;
    cout << "Player 1: Press enter to roll your dice" << endl;
    cin >> p1;

    
    int p2 = (rand() % 6) + 1;
    cout<<"Player 2: Press enter to roll your dice" << endl;
    cin >> p2; 
    

     if(p1 == p2) 
      {
          cout<<"You tied! \n";
      }
      
      else if(p1 > p2)
      {
          cout<<"You won! \n";
      }
      
      else
      {
          cout<<"You lost! \n";
      }
}



How to generate a byte string consisting of random nonzero bytes using Python?

As part of implementing the PKCS #1 v1.5 padding scheme for RSA, I need to generate an octet string of length n consisting of pseudo-randomly generated nonzero octets. I'm looking for the best way to do this using Python.

This is what my current implementation looks like:

def nonzero_random_bytes(n: int) -> bytes:
    values = [x.to_bytes(1, "big") for x in range(1, 256)]
    seq = [secrets.choice(values) for _ in range(n)]
    return b"".join(seq)

I've looked at generating the byte string with secrets.token_bytes(n), filtering the result, and generating nonzero values to backfill the string. I know I can also do something secrets.token_bytes(2 * n), filter, and trim the result but that doesn't strike me as an elegant solution.

I've also looked into how PyCryptodome and python-pkcs1 do this but I'm thinking there must be a better way (I poked around pyca/cryptography but couldn't find how they did it).

Disclaimer: I am aware that I shouldn't use PKCS1 v1.5, much less be rolling out any cryptography code myself. This purely an academic exercise. :)




Random number generator generates the same number

I am a beginner in programming, currently learning java. As a part of my practice, I have created the below code, which is simply a game asking the user to guess the number generated randomly by the Computer, if the player guesses it correctly, the score increases by 5. The problem is that my Random Number generator every time generated the same number, no randomness at all,I want to solve this problem. And also I want a more intuitive approach for my this code. the code is mentioned below:

public static void main(String... args){
 System.out.println("\nGuessNumber is a game, in which the player is required to guess the number\n" +
                       "generated randomly by the computer. If the player guesses it right his score\n" +
                       "is increased to 5, no score is cut when losing. The number will be from 1 to 6\n" +
                       "inclusive.\n");
    Scanner scan = new Scanner(System.in);
    char input;
    int randomNumber;
    int playerScore =0 ;
    //int roundCounter = 0;
    do{ System.out.print("Press 'r' to play and 'q' to quit: ");
        input = scan.next().charAt(0);
        switch (input){
            case 'r':
                System.out.print("A random number is generated for you, guess what it is: ");
                int answer = scan.nextInt();
                if(answer == (randomNumber = generateRandom())){
                    System.out.print("Congrats! that was absolutely right guess, ");
                    playerScore += 5;
                }else{
                    System.out.print("Oops!, wrong guess, right answer is "+randomNumber +", ");
                }
                break;
            case 'q':
                System.out.println("Bye Bye!");
                break;
            default:
                System.err.print("Enter a valid input: ");
                break;
        }
    }while(input != 'q');

    System.out.println("You scored "+ playerScore);
}

 private static int generateRandom(){
    Random random = new Random(1);
    return random.nextInt(7);
}

and a sample output:

enter image description here

Edit: If you can provide a better approach to write this code, please suggest me




vendredi 28 janvier 2022

Optimal way of picking a random number that's not in a container with C++

I have a container such as a std::vector<int> containing unique values. I'd like to pick a random integer number between 0 and a certain maximum MAX, that is not in the container. I'm concerned with the time complexity of such a program so I'd like to find something somewhat optimal.

So far I have basically two ideas that have both pros and cons. I can take a random number between 0 and MAX, and check if this number appears inside my container. If it is in the container, then try again.

// Values I don't want to get are stored in Vec
std::default_random_engine generator;
std::uniform_int_distribution<> distribution(0,MAX);
bool found = false;
int number;
while(!found) {
    number = distribution(generator);
    found = true;
    for(auto it : Vec) {
        if(it == number) {
            found = false;
            break;
        }
    }
}

That solution is pretty simple, but it will be excessively slow when most values inbetween 0 and MAX are already in Vec, and my program might come across this edge case.

The other solution would be to first sort Vec, and then pick a random number between 0 and MAX-Vec.size(). That way, the random number refers to a specific number not in the vector, and I'd have to iterate through the sorted container to recover the actual value, like this :

// Values I don't want to get are stored in Vec
std::sort(Vec.begin(),Vec.end());
std::default_random_engine generator;
std::uniform_int_distribution<> distribution(0,MAX-Vec.size());
int ref = distribution(generator);
int shift = 0;
int result;
for(auto it : Vec) {
    if(ref + shift >= it)
        shift++;
    else {
        result = ref + shift;
        break;
    }
}

The main disadvantage of this way of doing things, while always taking the same amount of time, is that it requires to sort the container first, which might be costly. So far, if I'm not mistaken, the first method's best case should be O(n) while the second method is O(n log(n)) since it requires a sort.

My guess is therefore to check which method should be the most efficient depending on the size of the container compared to the maximum MAX, which would basically come down to : if the container is too large, then the probability to have to guess multiple values is too high, therefore use the second method. Is there another way to make this more optimal, or am I on the right way ?




Shuffle sequential numbers without a buffer

I am looking for a shuffle algorithm to shuffle a set of sequential numbers without buffering. Another way to state this is that I’m looking for a random sequence of unique numbers that have a given period.

Your typical Fisher–Yates shuffle needs to have each element all of the elements it is going to shuffle, so that isn’t going to work.

A Linear-Feedback Shift Register (LFSR) does what I want, but only works for periods that are powers-of-two less two. Here is an example of using a 4-bit LFSR to shuffle the numbers 1-14:

1 2 3 4 5 6 7 8 9 10 11 12 13 14
8 12 14 7 4 10 5 11 6 3 2 1 9 13

The first two is the input, and the second row the output. What’s nice is that the state is very small—just the current index. You can start of any index and get a difference set of numbers (starting at 1 yields: 8, 12, 14; starting at 9: 6, 3, 2), although the sequence is always the same (5 is always followed by 11). If I want a different sequence, I can pick a different generator polynomial.

The limitations to the LFSR are that the periods are always power-of-two less two (the min and max are always the same, thus unshuffled) and there not enough enough generator polynomials to allow every possible random sequence.

A block cipher algorithm would work. Every key produces a uniquely shuffled set of numbers. However all block ciphers (that I know about) have power-of-two block sizes, and usually a fixed or limited number of block sizes. A block cipher with a arbitrary non-binary block size would be perfect if such a thing exists.

There are a couple of projects I have that could benefit from such an algorithm. One is for small embedded micros that need to produce a shuffled sequence of numbers with a period larger than the memory they have available (think Arduino Uno needing to shuffle 1 to 100,000).

Does such an algorithm exist? If not, what things might I search for to help me develop such an algorithm? Or is this simply not possible?




How do I generate a random string of 8 distinct characters in c# [closed]

I can generate a random string of 8 character with this

public static Random random = new Random();

    public static string GenerateString(int length)
    {
        const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        return new string(Enumerable.Repeat(chars, length)
            .Select(s => s[random.Next(s.Length)]).ToArray()).ToLower();
    }`

However the chars are not distinct. Any help on how can I make it distinct and generate still a string 8 chars long? I tried with distinct but then length gets affected as deletes the duplicate without taking into account the length asked.




jeudi 27 janvier 2022

Password Generator Using Multiple Strings in Swift

I'm new to coding and I'm trying to create a password generator. I've created one using a single array of strings (all lowercase or all uppercase). But I want to create using multiple arrays. I'm using Swift 5.3 (Xcode 13.2.1)

struct ContainCharacterSelection {
    var containNumbers: Bool = true
    var containLowerCharacters: Bool = true
    var containUpperCharacters: Bool = true
    var containSpecialCharacters: Bool = true
    var containComplicatedCharacters: Bool = false
}

class PasswordGenerator {
    
    let numbers = ["0","1","2","3","4","5","6","7","8","9"]
    let lowerCharacters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
    let upperCharacters = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
    let specialCharacters = ["!","\"","§","$","%","&","/","(",")","=","?","+","*","#",",",";",".",":","-","_","@","<",">"]
    let complicatedCharacters = ["^","[","]","{","}","\\","'","`","´"]

var password = ""
var passwordLenght = sliderValue
}

Thanks in advance.




mardi 25 janvier 2022

I need help making and displaying a List

I wish to program a Skateboard Trick Generator for me and some friends and I can't seem to get the List to show on the Label and randomly pick a trick.

 private void btnClick_Click(object sender, EventArgs e)
    {
        //new random
        static Random rnd = new Random();
        
        string[] words = { "Kick Flip", "Heel Flip", "Tre Flip" };

        lblTrick.Show(words[rnd.Next(0, words.Length)];

If anyone could help I would love that.

Thanks.




Fluctuation between adjacent histogram bins

I want to write a code that starts from bin size of 1 and increases the bin size by 1 until the fluctuation between the adjacent bins is greater than 5%.

Histogram code




Generating random number until they repeat in C/CPP

I have a problem with a program in C or CPP. I need to make a program that will generate a random nubers in range of 1-365, but when the program generates the same number as it allredy did, the program will write the count of numbers and repeat it self again 100 times.


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

int main()
{
    int lower = 1, upper = 365, count = 365;

    srand(time(0));

    printf("The random numbers are: ");
    for (int i = 0; i < count; i++) {
            
        int num = (rand() % (upper - lower + 1)) + lower;
        printf("%d ", num);
    }

    return 0;
}

I know how to make the generator for random numbers but i have problem with stopping it when the numbers reapeat.




Why does my random function generate the same number every time I call it in a loop?

I have my random function generating a pseudo-random number in the range:

double Utils::randomNumber(int min, int max)
{
    assert(min < max);
    srand(time(nullptr));
    return (max - min) * ((double)rand() / RAND_MAX) + min;
}

However, when I call it in a loop, I always get the very same number, although I seed the sequence:

for (int i = 0; i < m_inputs; ++i)
{
    m_weights.push_back(Utils::randomNumber(0, 1));
}

Output:

Weights: [0.787561, 0.787561, 0.787561, 0.787561, 0.787561, 0.787561, 0.787561, 0.787561, 0.787561, 0.787561, 0.787561, 0.787561]



lundi 24 janvier 2022

How to create a multiple choice question program with an external text file?

I am trying to create a multiple choice question program that will read a text file, pose 5 of the questions in a random order, receive the answer, and then display the answer if it's false. Here's what I've managed to write:

First an example of the file containing the questions:

mcq.txt:

Which of these countries is an island ? A-France B-Lithuania C-Australia D-Korea;;C
One byte is A-1bit B-4 bits C-8 bits D-32 bits;;C
What event of 1934 contributed to the creation of the Popular Front? A-The congress of Tours B-The riots of the leagues C-The Crash of Wall-Street;;B
What event is at the origin of the crisis of the Thirties? A-The Russian Revolution B-The rise of fascism C-The First World War D-The Wall Street Crash;;D
What is the color of Adam's white horse A-Green B-Red C-Grey D-White;;D
With 1 byte you can encode A-255 characters ​​B-8 characters ​​C-16 characters ​​D-256 characters;;D
What is Microsoft Windows? A-A type of computer B-An operating system C-A database management system;;B
The binary system uses the base A-2 B-10 C-8 D-16 E-None of these answers are true.;;A
In Greco-Roman mythology, the gods met on A-Mount Sinai B-Vesuvius C-Mount Olympus;;C
In Greek mythology, Pegasus is A-A winged horse B-A man with an eagle's head C-A giant;;A
When was the World War II armistice signed A-May 8, 1945 B-July 14, 1940 C-November 11, 1945 D-June 18, 1940;;A
Before 2003, the countries of Bosnia, Croatia, Slovenia, Macedonia, Montenegro and Serbia formed A-Bulgaria B-Czechoslovakia C-Kosovo D-Yugoslavia;;D
What is this infectious disease caused by Koch's bacillus called? A-Plague B-Tuberculosis C-Poliomyelitis D-Scabies;;B

the program:

import random
def mcq():
    with open("mcq.txt", "r") as f:
        i=0
        while i<5:
            line=f.readline()
            a=line.split(";;")
            print(a[0])
            answer=input("your answer?")
            if answer.upper()==a[1]:
                print("correct")
            else:
                print("false, the anwer was", a[1])
            i=i+1
mcq()

The program seems to be working but asks the questions in order, which is normal because we didn't use a random module, but when we put random.shuffle(line) we encounter the error "'str' object does not support item assignment".

To solve this I tried writing this program which is supposed to assign numbers to each line in a roundabout way and ask the questions in a random order, but it just gives numbers and is pretty much useless:

import random
with open("qcm.txt", "r") as f:
    ligne=f.read().splitlines()
    i=range(0,30)
    x=zip(ligne,i)
    for i in range(10):
        x=random.randint(0, 30)
        print(x)

The other problem with the main program is that the answer is always false. Even though I put upper() it doesn't seem to change anything.

I also thought about using dictionaries and assigning the question to the key and the answer to the value, but I don't know how to randomise it and if it's a good idea.

I would be grateful if you could help me.




How can I create a array using the random function whose sum is 1 in python using nympy?

Working on an assignment which requires me to create an array with random numbers whose sum is 1.

The actual problem statement looks something like this :

get_initial_weights

This function should have one parameter, an integer m. This function should return a matrix with 1
row and m columns containing random values, each between zero and one. The sum of these m
values should be equal to one.




dimanche 23 janvier 2022

Random number generator producing "undefined" result [duplicate]

My random number generator produces mostly what I want, however approximately 1/10 times it produces an "undefined" result. Here's my code:

    function generateID() {
        var generatedID = Math.floor(Math.random() * 99999999);
        var idTaken = false;
        userData.forEach(task => {
            if (task.id == generatedID) {
                idTaken = true;
            }
        })
        if (idTaken || generatedID < 10000000) {
            generateID();
        } else {
            return generatedID;
        }
    }
    
    console.log(generateID());



Any UUID alternate that has 8-4 formatted string?

I see some website use this canonical 8-4 format string, for example:

projects/ab80ef92-b46f-40e1-b5ca-e77d2fe31327/tags/04a29d0c-32c3

the string "ab80ef92-b46f-40e1-b5ca-e77d2fe31327" obviously as UUID generated, but I'm not sure how to generate the string "04a29d0c-32c3".

Can anyone tell me what is it and how to make it using NodeJS?




samedi 22 janvier 2022

Why am I getting an overflowerror in Python?

here's my code

J = random.randrange(400000000000000000, 800000000000000000)
K = codecs.encode(J.to_bytes(2, 'big'), "base64")

but i'm getting an overflow error when trying to run this... Basically I'm generating a number between 400000000000000000 and 800000000000000000 and converting it to base64. If anyone could help, that'd be great, thanks




Generate random time series data with increasing trend

Is there a way in Python to spread a population over a period of time with an increasing trend?

For instance, assuming I have 1000 people to distribute between 1901 and 2000, the result I expect is like:

result = {1901: 6, 1902: 4, 1903: 8, 1904: 8, ..., 1997: 20, 1998: 22, 1999: 18, 2000: 21}

The sum of the values ​​in the dictionary result (6 + 4 + 8 + 8 + ... + 20 + 22 + 18 + 21) should be 1000. It should be possible to adjust the value of the first year and that of the last (to determine how much the series should be increasing)




string replacement with random element in Python

I am trying to make a fun, randomized madlibs story for my colleagues. The idea is to have them submit adjectives, nouns, and verbs, which I will add to a separate lists. I have also added markers (e.g. "(noun)") to the story as replaceables. I am trying to figure out how to replace each marker in the string with a random, UNIQUE choice from the appropriate list of nouns, adjectives, or verbs.

My first idea has a couple of bugs:

import random

nouns = ["bee","hammer","person"]
adj = ["dazzling","punctual","dizzy","petite"]
verbs = ["sprint","blab","sniff","die"]

story = "blah blah blah (noun). Blah blah blah (adj), blah blah (verb) blah blah. Blah blah blah (noun) blah blah (noun)s blah blah (verb)."

spl_story = story.split()

for i in spl_story:
    if i == "(noun)":
        i = random.choice(nouns)
#same if statement for adjectives and verbs

new_story = " ".join(spl_story)

There are 2 main issues with this:

  1. if there is a "s" for a plural value (e.g. "(noun)s") or a special character after the marker, it doesn't split properly. I want to find a way to keep my punctuation and the s character, but make sure that the markers split properly.

I could do a long string of conditionals, such as:

    if i == "(noun)"
        i = random.choice(nouns)
    elif i == "(noun)s"
        i = random.choice(nouns) + "s"
    elif i == "(noun).":
        i = random.choice(nouns) + "."

but that's inefficient and I'd like to find a smoother solution.

Secondly: I need a UNIQUE choice from the list without replacing repetative nouns, verbs, etc.

My solution might suck from the get-go and if anyone thinks it would be good to throw it away and go a different path, I'm all ears. Thanks for any advice!




vendredi 21 janvier 2022

HTML Random Number Generator + Options off result

I'm trying to make a random number generator that gives me a random number (1-26) and then gives me a pre-assigned response depending on what number is given to me. I've got the code for the random number generator, but how do I go from here?

This is the code btw

<html>
<body>

<p id="one"></p>
<button onclick="random()">Random</button>

<script>
 function random(){

document.getElementById("one").innerHTML = Math.floor(Math.random() * 26);
}
</script>

</body>



How do I show random images from a folder on Tkinter?

So I have a couple of images in a folder and I want to do a little pack opener on tkinter where if I press on a button it randomly opens an Image of that folder and shows it. So I did this:

def pack():
    path ='C:\\Users\\matt\OneDrive\Images\cards'
    files = os.listdir(path)
    index = random.randrange(0, len(files))
    image = Image.open(files[index])
    image.show()

The problem is that this function doesn't want to work and it always tells me:

AttributeError: type object 'Image' has no attribute 'open'

Can someone please help me? And does someone know how to do a button out of an image? Thank you in advance.☺




jeudi 20 janvier 2022

Python histogram bin size fluctuations

If I want to keep my bin-to-bin fluctuations less than <= 5%, how do I find the maximum number of bins I should use?

I am using an list of 10,000 random numbers to see analyze its histogram distribution.

Here is an example: I am using the same data but with different bin sizes.

Bin of size 10

Bin of size 50

Bin of size 100

So I basically want to find the maximum number of bins for which the distribution fluctuations between adjacent bins are within 5% of each other.




How to make List random by shuffling

I want to make the quiz randomly generated by shuffling them. I created the shuffle class and call the method to shuffle the sample data. But here is the problem, it didn't display randomly as I wanted. I think I am missing something but I have no idea what did I miss. I have called the shuffle method and print them. Can anyone please enlighten me?

//this is the shuffle method and I call the method to shuffle the sample data

List shuffle(List data) {
  var random = new Random();

  // Go through all elements.
  for (var i = data.length - 1; i > 0; i--) {
    // Pick a pseudorandom number according to the list length
    var n = random.nextInt(i + 1);

    List temp = data[i];
    data[i] = data[n];
    data[n] = temp;
  }

  return data;
}

main() {
  print(shuffle(sample_data));
}

//this is the whole page

class Question {
  final int? id, answer;
  final String? question;
  final List<String>? options;
  //final List<String>? audio;

  Question({this.id, this.question, this.answer, this.options});
}

const List sample_data = [
  {
    "id": 1,
    "question": "Apakah maksud waqaf?",
    "options": ['Berhenti', 'Sambung tanpa nafas baru', 'Sambung', 'Dengung'],
    "answer_index": 2,
  },
  {
    "id": 2,
    "question": "Apakah pengertian qalqalah dari segi bahasa? ",
    "options": ['jelas ', 'lantunan ', 'nyata', 'berhenti'],
    "answer_index": 1,
  },
  {
    "id": 3,
    "question": "Qalqalah terbahagi kepada ________ jenis.",
    "options": ['1', '2', '3', '4'],
    "answer_index": 1,
  },
  {
    "id": 4,
    "question":
        "“Pertemuan antara mim sakinah dengan huruf ba dengan dengung 2 harakat”. ",
    "options": [
      'Izhar Halqi',
      'Wajibul Ghunnah',
      'Ikhfa Syafawi',
      'Idgham bila ghunnah'
    ],
    "answer_index": 2,
  },
];
List shuffle(List data) {
  var random = new Random();

  // Go through all elements.
  for (var i = data.length - 1; i > 0; i--) {
    // Pick a pseudorandom number according to the list length
    var n = random.nextInt(i + 1);

    List temp = data[i];
    data[i] = data[n];
    data[n] = temp;
  }

  return data;
}

main() {
  print(shuffle(sample_data));
}



Using an array to select a random css class from list

I am trying to have a css class selected randomly from a list.

This is wrong, I don't know how to get it to work. https://jsfiddle.net/Lke2dpv1/

How am I able to do this?

I think I have the right idea, it's just not written in the right way.

That is all I am trying to do.

Here is the array of classes: const colors = ['.play1', '.play2', '.play3'];

And then one would be selected randomly from the list.

(function randomBackground() {
  const colors = ['.play1', '.play2', '.play3'];
  const ran = colors[Math.floor(Math.random() * colors.length)];
  document.querySelector('body').classList.add('play' + ran)
}());
.play1 {
  --color-a: orange;
  --color-b: black;
  --color-c: green;
  --color-d: black;
}

.play2 {
  --color-a: purple;
  --color-b: black;
  --color-c: purple;
  --color-d: black;
}

.play3 {
  --color-a: green;
  --color-b: black;
  --color-c: green;
  --color-d: black;
}

html,
body {
  height: 100%;
  padding: 0;
  margin: 0;
}


body  {
  background-size: 165px 165px;
  background-image:
    linear-gradient(var(--color-a) 5px, #0000 5px),
    linear-gradient(90deg, var(--color-a) 5px, #0000 5px),

    linear-gradient(var(--color-b) 10px, #0000 10px 160px, var(--color-b) 160px),
    linear-gradient(90deg, var(--color-b) 10px, #0000 10px 160px, var(--color-b) 160px),

    linear-gradient(var(--color-c) 15px, #0000 15px 155px, var(--color-c) 155px),
    linear-gradient(90deg, var(--color-c) 15px, #0000 15px 155px, var(--color-c) 155px),

    linear-gradient(var(--color-d) 20px, #0000 20px 150px, var(--color-d) 150px),
    linear-gradient(90deg, var(--color-d) 20px, #0000 20px 150px, var(--color-d) 150px),

    linear-gradient(var(--color-a) 25px, #0000 25px 145px, var(--color-a) 145px),
    linear-gradient(90deg, var(--color-a) 25px, #0000 25px 145px, var(--color-a) 145px),

    linear-gradient(var(--color-b) 30px, #0000 30px 140px, var(--color-b) 140px),
    linear-gradient(90deg, var(--color-b) 30px, #0000 30px 140px, var(--color-b) 140px),

    linear-gradient(var(--color-c) 35px, #0000 35px 135px, var(--color-c) 135px),
    linear-gradient(90deg, var(--color-c) 35px, #0000 35px 135px, var(--color-c) 135px),

    linear-gradient(var(--color-d) 40px, #0000 40px 130px, var(--color-d) 130px),
    linear-gradient(90deg, var(--color-d) 40px, #0000 40px 130px, var(--color-d) 130px),

    linear-gradient(var(--color-a) 45px, #0000 45px 125px, var(--color-a) 125px),
    linear-gradient(90deg, var(--color-a) 45px, #0000 45px 125px, var(--color-a) 125px),

    linear-gradient(var(--color-b) 50px, #0000 50px 120px, var(--color-b) 120px),
    linear-gradient(90deg, var(--color-b) 50px, #0000 50px 120px, var(--color-b) 120px),

    linear-gradient(var(--color-c) 55px, #0000 55px 115px, var(--color-c) 115px),
    linear-gradient(90deg, var(--color-c) 55px, #0000 55px 115px, var(--color-c) 115px),

    linear-gradient(var(--color-d) 60px, #0000 60px 110px, var(--color-d) 110px),
    linear-gradient(90deg, var(--color-d) 60px, #0000 60px 110px, var(--color-d) 110px),

    linear-gradient(var(--color-a) 65px, #0000 65px 105px, var(--color-a) 105px),
    linear-gradient(90deg, var(--color-a) 65px, #0000 65px 105px, var(--color-a) 105px),

    linear-gradient(var(--color-b) 70px, #0000 70px 100px, var(--color-b) 100px),
    linear-gradient(90deg, var(--color-b)70px, #0000 70px 100px, var(--color-b) 100px),

    linear-gradient(var(--color-c) 75px, #0000 75px 95px, var(--color-c) 95px),
    linear-gradient(90deg, var(--color-c) 75px, #0000 75px 95px, var(--color-c) 95px),

    linear-gradient(var(--color-d) 80px, #0000 80px 90px, var(--color-d) 90px),
    linear-gradient(90deg, var(--color-d) 80px, #0000 80px 90px, var(--color-d) 90px),

    linear-gradient(var(--color-a), var(--color-a));
}



mercredi 19 janvier 2022

R: Comparing the Time for Random Searches

I am using the R programming language.

I am trying to optimize the Rastrign Function using both Random Search With Replacement and Random Search Without Replacement:

Rastrigin <- function(x1, x2)
{
  20 + x1^2 + x2^2 - 10*(cos(2*pi*x1) + cos(2*pi*x2))
}

x1 <- x2 <- seq(-5.12, 5.12, by = 0.1)
f <- outer(x1, x2, Rastrigin)

enter image description here

Part 1 : Random Search With Replacement:

To sample with replacement, I generated 100 points (I converted these points to integer format so that it's easier to see which points are duplicates for Part 2), and then evaluated the function at these 100 points. I then extracted the row of data corresponding to the smallest value of the function. I also recorded the time taken:

start.time <- Sys.time()

x1 = as.integer(rnorm(100,5,5))
x2 = as.integer(rnorm(100,5,5))
func_value = 20 + x1^2 + x2^2 - 10*(cos(2*pi*x1) + cos(2*pi*x2))

frame = data.frame(x1,x2,func_value)

sort_frame <- frame[order(func_value),]

final_answer = sort_frame[1,]

end.time <- Sys.time()
time.taken <- end.time - start.time

time.taken

Time difference of 0.01810408 secs

Part 2: Random Search Without Replacement:

Since I do not know how to write the code for the traditional way to do Random Search Without Replacement (i.e. generate random value, see if this generated value has already occurred : if not then evaluate function at this value, else generate new value until a unseen value is generated) - since I want to evaluate the function at 100 values, I decided to generate 200 values in hopes that at least 100 values in these 200 values will be unique. Then, I repeated the above procedure:

start.time <- Sys.time()

x1 = as.integer(rnorm(200,5,5))
x2 = as.integer(rnorm(200,5,5))

frame = data.frame(x1,x2)
de_duplicated = frame[!(duplicated(frame) | duplicated(frame, fromLast = TRUE)), ]

#check to make sure at least 100 values in "de_duplicated"

ifelse(nrow(de_duplicated)<100, "BAD", "GOOD")

[1] "GOOD"

#only keep 100 values in de_duplicated:

de_duplicated = de_duplicated[1:100,]

func_value = 20 + de_duplicated$x1^2 + de_duplicated$x2^2 - 10*(cos(2*pi*de_duplicated$x1) + cos(2*pi*de_duplicated$x2))

final_frame = data.frame(de_duplicated$x1,de_duplicated$x2,func_value)

sort_frame <- final_frame[order(func_value),]

final_answer = sort_frame[1,]

end.time <- Sys.time()
time.taken <- end.time - start.time

time.taken

Time difference of 0.03689885 secs

My Question: Since I am interested in comparing the times for Part 1 and Part 2 - I don't think it is fair, since I have written the code for Part 2 in a very "clumsy" way.

If you were to write the code for Part 2 in a more "traditional" way, i.e. with "while loops" - would this reduce the time required for Part 2? Can someone please show me how to do this - is writing Random Search Without Replacement (i.e. Part 2) using "while loops" in fact the traditional way to do this?

Thanks!




What am I missing in my random lowercase string generator function ? Using Swift 5.5 [duplicate]

I have a function I use to generate random strings for email addresses or passwords (for example). It was originally set like this:

static func random(length: Int) -> String {
let characters = "abcdefghijklmnopqrstuvwxyz"
return String((0..<length).map { _ in characters.randomElement()! })
}

So I changed it to this:

static func random(length: Int) -> String {
let characters = CharacterSet.lowercaseLetters
return String((0..<length).map { _ in characters.randomElement()! })
}

But I get an error saying "Value of type 'CharacterSet' has no member 'randomElement'.

I'm very new to Swift and I've done a lot of searching and so far I haven't found a good solution. I want to keep this function short and sweet. And I've been at this for a while now. Any help would be greatly appreciated! Please let me know if any more context is needed.

Edit: My question got closed because it was seen as a duplicate but, I looked at the solution page and tried to apply it to my issue and still no resolution. I'm not sure if that's because the previous answers are from 2015 and older or they were for obj-c




Python - passing random seed (generator) to `randn()`

I was reading this blog post and they suggest that rather than setting the random seed for the whole document

np.random.seed(1234)
x = np.random.randn(100)

One should use a generator, which can be created as such

rng = np.random.default_rng(1234)

In the post they use the example of rng.rand(10) which works fine. I need to use randn() however and it doesn't work if you use rng.randn(10).




How can I generate a random number in C

I want to generate a random number/character without using any libraries but <stdio.h>. Is there any possibility to do that? I mean, by doing some weird loop or something like that, I don't care, I just want to generate random stuff with the basic library.




lundi 17 janvier 2022

Create a new dataset after selection in Python

Totally newebie with Python, and I'm trying to learn "on the field". So basically I managed to open a csv file, pick only the rows that have certain values in specific columns, and then print the rows.

What I'd love to do after this is basically get a random selection of one of the found rows. I thought to do that by creating a new csv file first, which at this point will only contains the filtered rows, and then randomly select from it.

Any ideas on the simplest way to do that?

Here's the portion of the code so far:

import csv
    with open("top2018.csv") as f:
        reader = csv.reader(f)
        for row in reader:
            if (row[4] >= "0.8") and (row[6] <= "-4") and (row[12] >= "0.8"):
                print(row[2] + " -", row[1])

It will find 2 rows (I checked).

And then, for creating a new csv file:

import pandas as pd
            artist = [row[2]]
            name = [row[1]]
            dict = {'artist': artist, 'name': name}
            df = pd.DataFrame(dict)
            df.to_csv('test.csv')

But I don't know why with this method, the new csv file has only 1 entry, while I'd want to have all of the found rows in it.

Hope something I wrote make sense! Thanks guys!




Create a dataframe i nR

I would like to create a dataframe with 117 columns and 90 rows, the first ones being: ID, date1, date2, Category, DR1, DRM01, DRM02, DRM03 .... up to DRM111. For the first column, it would have values ranging from 1 to 3. In date1 it would have a fixed value, which would be "2022-01-05", in date2, it would have values between 2021-12-20 to the maximum that it gives. Category can be ABC or ERF, in DR1 would be values that would vary from 200 to 250, and finally, in DRM columns, would be values that would vary from 0 to 300. Is it possible to create a dataframe like this?




dimanche 16 janvier 2022

Big-O of while loop with an indeterminate number of iterations

I can't seem to rationalize the Big-O notation for a while loop that has an indeterminate number of iterations.

In my code for a personal project, I have a list containing all 0s. I then implement a while loop that will generate a random integer between 0 and 9. If the value in the list at the index of the random number is a 0, then the value is written to a 1 and the while loop exits. Otherwise, a random number is generated again and the process repeats.

I'm not entirely sure what the time complexity of this would be, however. For example, if after 9 iterations of the algorithm, every single value in the list except index 9 is 1, and if the random number generator just happens to not generate the number 9 for, say, 99 iterations, then it would exit after 99 + 9 iterations. Wouldn't the worst-case be O(infinity)? I don't think this is possible, but I figured I'd ask since I wasn't sure.

My textbooks and online resources don't seem to provide much insight on examples such as this. I'm sure that the best-case would be O(1), but the average and worst cases I'm a bit unsure about.


I found a similar problem that has the same premise. Here's the pseudocode, where n is some integer of arbitrary size:

sample_found = false
while(!sample_found) {
    if (rand(0,n) == 0) {
        sample_found = true
    }
}

In the worst case, this would run infinitely, right? I'm not sure about average case, either.




Random Rectangles without Overlapping some Pixels

I want to generate random rectangles. That is a pretty easy task. The issue is I need them to not overlap with any of these black dots:

dots
Inverted for ease of sight:

dots inverted

Now I can just tell it to ignore any rectangles it generates if it overlaps with any black dots, but as the dot density increases, it gets to bogosort levels of inefficiency. Is there a more efficient way to do this?




Generating random numbers without repetitions. C#

I have problem with my code. I want to generate random matrix 9x9 with digits from 1 to 9. Without repetions in rows and columns. I'm using VS in C#. My code is stopping at row 5. No errors and messeges. Please help me where is the problem.

namespace MatrixTest
{
    internal class MatrixTest
    {
        static void Main(string[] args)
        {

            int[,] wzor = new int[9, 9];

            static int losuj()
            {
                Random random = new Random();
                int wylosowanaLiczba;
                wylosowanaLiczba = random.Next(1, 10);
                return wylosowanaLiczba;
            }

            for (int wiersz = 0; wiersz < 9; wiersz++)
            {
                for (int kolumna = 0; kolumna < 9; kolumna++)
                {
                AlgorytmWiersz:

                    wzor[wiersz, kolumna] = losuj();
                    int wzorzec = wzor[wiersz, kolumna];

                    if (kolumna != 0)
                    {
                        int testKomWiersz = kolumna;
                        for (int i = 1; i < (kolumna + 1); i++)
                        {
                            testKomWiersz--;

                            int porownywanaW = wzor[wiersz, testKomWiersz];
                            if (wzorzec == porownywanaW)
                            {
                                goto AlgorytmWiersz;

                            }
                        }
                    }

                    if (wiersz != 0)
                    {
                        int testKomKolumna = wiersz;
                        for (int j = 1; j < (wiersz + 1); j++)
                        {
                            testKomKolumna--;
                            int porownywanaK = wzor[testKomKolumna, kolumna];
                            if (wzorzec == porownywanaK)
                            {
                                goto AlgorytmWiersz;

                            }
                        }
                    }   
                }
                Console.WriteLine(wzor[wiersz, 0] + "  " + wzor[wiersz, 1] + "  " + wzor[wiersz, 2] + "  " + wzor[wiersz, 3] + "  " + wzor[wiersz, 4] + "  " + wzor[wiersz, 5] + "  " + wzor[wiersz, 6] + "  " + wzor[wiersz, 7] + "  " + wzor[wiersz, 8]);
            }
        }
    }
}



Simulate randomly increasing number [closed]

Suppose we have a website that shows number of registered users but this number is simulated.

We could do this in back end by maintaining some variable and incrementing it at regular intervals. Front end service would just get this variable from backend.

I would like to do this without relying on back end. I am thinking of coming up with a non-decreasing function that maps time to number of registered users. But I do not want it to be linear or exponential function. I would like it to have a more complex shape so that it correctly simulates the randomness. Any ideas?




samedi 15 janvier 2022

Randomly Crop a Given Input Sequence in Python?

I want to create a function that takes in a input sequence/list of given length

(ex: [48083, 50118, 50118, 39631, 5868, 452, 32, 460, 15, 49, 1028, 4, 252, 32, 460, 15, 49, 1028, 55, 87, 195, 722, 10, 183, 117, 912, 479, 3684, 51, 109, 16, 2788, 124, 8, 556, 8, 95, 33, 333, 732, 2923, 15, 592, 433, 4.])

and the function will output a random seqeunce of given length say 5 from the input

(ex: [48083, 50118, 50118, 39631, 5868] or [479, 3684, 51, 109, 16])

It would basically look something like this -

def foo(x, len):
  return ...

x = [48083, 50118, 50118, 39631, 5868, 452, 32, 460, 15, 49]
output_seq = foo(x, 5) # [39631, 5868, 452, 32, 460]
output_seq = foo(x, 5) # [452, 32, 460, 15, 49]
output_seq = foo(x, 5) # [50118, 50118, 39631, 5868, 452]

Can this be done in python3x ? Any help would be appreciated ?




R sample from mixture distribution

How could I sample from this distribution:

enter image description here

given: 𝑝(𝑦) = 𝑃(𝑌 = 𝑦|𝑌~𝑃(𝜆/2)) , where 𝑃(𝜆/2) is the Poisson distribution with lamda/2 and

𝑔(𝑥|𝑦) follows the chi square distribution with df=n+2y

Many thanks!!




Using Kotlin, why does this code only work for 2 of the 3 possibilities?

When I run this on my phone, the button I tap only does 2 of the 3 possible things, and it changes depending on how I swap the order in the code. For example, usually the first option just doesn't do anything at all, but sometimes the first and last work, depending on how I rearrange the code. I have no idea what's going on. Here's my code that I'm using to do this.

    private fun changeScore() {
        when ((1..10).random()) {
            1 or 2 or 3 or 4 or 5-> win()
            6 ->  Toast.makeText(this, "neither", Toast.LENGTH_SHORT).show()
            7 or 8 or 9 or 10 -> loss()
        }
        balance.text = getString(R.string.score, coins.toString())
    }

    private fun loss() {
        coins --
        Toast.makeText(this, "loss", Toast.LENGTH_SHORT).show()
    }
    private fun win() {
        coins ++
        Toast.makeText(this, "win", Toast.LENGTH_SHORT).show()
    } 

when I tap the button, you should have a chance at loosing 1 coin or gaining 1 coin, and a 1 in 10 chance of nothing happening. Additionally, as a debug helper, all 3 options make a toast. Instead, one of the 3 options does nothing at all, no coins, and no toast. I've tried to just ignore the bug and rearrange it so the one that doesn't work is the one that only gives a toast, but I cant get that to work. How do I fix this so that all 3 are a possibility? Keep in mind, I only have less than a week of experience with Kotlin, so please explain things with that in mind because I'm relatively new to coding in general.




Reset Randomize/random number generation seed in VB.NET

So I am creating an application where the user can either input a seed, or a seed is randomly generated for them. Then, this seed is passed to the Randomize function which calls Rnd several times. The intention is that if the same seed is used - either if it's generated randomly, or if it's entered by the user - then the output list of random numbers should be the same.

The problem I ran into is that when I randomly generate the seed, this will throw off the random number generator - and I'm not sure how to reset it entirely. My code looks like this:

If UserEnteredSeed() Then
    Randomize(userSeed)
Else
    Randomize()
    userSeed = Rnd() + Rnd() ' This part is just a placeholder - but the Rnd function is called several times
End If

Randomize(userSeed)

Debug.Print(Rnd().ToString())

My problem is that when the Else clause is reached, the use of the Rnd function will (to my understanding) traverse the list of random numbers, and then when the next Randomize is called with userSeed, the list changes but the position within the list does not. This will change the output when the Else clause is not reached and Rnd is not called several times.

My question is, can I completely reset the random number generation so that regardless of whether the userSeed number is entered or generated, the same userSeed produces the same random number as output? Or if not, how can I effectively create the same intended behaviour?




vendredi 14 janvier 2022

An array that outputs number 1-5 in random, 1-5 must be output only 2 times without repeating

The code does output 1 - 5 but is there a way to make each number print only twice. (from 1-5 only) Sample Output,

It does change and is random but outputs more than twice

public class Main {

public static void main(String[] args) {
    
int num;    

int[] random = new int[5]; //this code generates numbers 1–5 

int[] array = new int[11]; //array size

for(int x = 0; x < random.length; x++)

random[x] = x; //store the index as a value

for(int x = 0; x < random.length; x++) {

num = (int)(Math.random()*5);

while(random[num] == -1)

num = (int)(Math.random()*5); 

if(random[num] != -1)

array[x] = random[num]; 

random[num] = -1; 

}

for(int x = 0; x < array.length; x++)

array[x] = array[x] + 1;

for(int x = 1; x < array.length; x++)


System.out.println("A["+x+"]: "+ array[x]);

}

}



Connecting to random points in a 2d numpy array based on distance

I have a 2d numpy array and select a random coordinate position (say 10x10 array and start at position 2,3). I want to randomly connect to 40% of the other points in the 2d array effectively generating a list of tuples [(x1, y1), (x2, y2) ...] where the list is 40% of the other coordinates.
An additional constraint, however, is the goal is to reduce connection probability the farther the points are away from one another (so point 2,3 is far more likely to connect to 2,2 than 9, 8 but yet still be random so there is a chance albeit small of connecting to 9, 8).

I believe I need to create some sort of Guassian function centered on 2,3 and use this to select the points, but any Gaussian I create will generate non-integer values - requiring additional logic as well as presents problem of needing to handle x and y dimensions separately.

Currently, I am trying to use np.meshgrid with gauss = np.exp(-(dst2 / (2.0 * sigma2)))

Is there an easier way to do this or a different approach someone might recommend?




Trying to create a list of 10 random numbers between 1-10 that do not repeat in python

This is not the whole program I want to write but right now I'm just trying to figure out this simple thing. And if you couldn't tell, I am completely new to programming.




Can't create a random list that calculates the longest distance between It's elements

I can't figure out why I'm getting this error: TypeError: 'int' object is not subscriptable*

I'm new to Python so It's difficult for me to track the mistakes I make. I've been trying to figure out what's going on the whole day

User inputs the parameters and creates a random list that calculates the longest distance among its elements.

import random

def generate_random_floats(n,m,seed):
    x = []
    if (y==0):
        random.seed()
        for i in range (n):
            x.append(random.uniform(-m,m))
    else:
        random.seed(y)
        for i in range (n):
            x.append(random.uniform(-m,m))
    return x
    pass
    # function that returns a list of n random numbers in span
    # -m, m with seed generator of random numbers (optional argument)
    
def find_max_gap(x):
    vmin <= x[0]
    dmax = 0
    for i in range (n):
        if (x[i] < vmin):
            vmin = x[i]
        elif (x[i] - vmin > dmax):
            dmax = x[i] - vmin
    return (dmax)
    
    # function that accepts a list of real numbers and returns the maximum distance between them
    pass

def present_list():
    print(" The random list is:",generate_random_floats(n,m,seed))
    # auxiliary function that prints the elements of a list
     pass

n=-1
while n < 0 or n == 0 :
    while True:
        try:
            # user input of how many random numbers
            n = int(input(">>Define the number (n) from the random numbers.\n-Positive number) :"))
            break
        except:
            continue
m=-1
while m < 0 :
    while True:
        try:
            # input user -m, m
            m = int(input(">>Define (range) from which random values will be selected.\n) :"))
            break
        except:
            continue
seed=0
b=0
x=0
s=0
while True:
    try:
        # input seed
        y = int(input("Enter the number that will set the seed value. :"))
        break
    except:
        continue
# create list of random numbers
generate_random_floats(n,m,seed)
present_list()
find_max_gap(x)   



jeudi 13 janvier 2022

RNG Distribution with multiple instances

If I need to generate random 8 bytes with RandomNumberGenerator class, I can generate all 8 bytes with a single instance and also I can use two instances of RandomNumberGenerator to generate 8 bytes - first one will generate 4 bytes and the second one will generate remaining 4 bytes. Question is - if I use two instances of RandomNumberGenerator will it make some any of 8 bytes more probable than others? Will it be a secure generator?




Make a random choice influenced by other values [closed]

How can I randomly decide weather a player will cheat or not based on their morality(higher morality means higher probability of cheating and lower means lower prob.) In other words, the random decision should be influenced by morality factor.




Looping variable RNG in a Batch file [duplicate]

I am attempting to make a simple RNG that takes two input variables to determine the number of loops as well as the range of the generated numbers in said loops. I created a file that works without the variables but I am having some issues with the Loop function and the variables. Any wrinkled Brains out there that can shed some light would be much appreciated.

@echo off 
color f0
set /p "FileName= Enter Filename (Without Extension) : "
echo @echo off >> %FileName%.txt
pause
set /p "Part= Enter TOTAL Number of vanes: "
echo %Part% Vanes total
pause
Set /p "Inspect= Enter Number of Vanes to Inspect: "
echo Out of %part% Vanes there will be %inspect% vanes randomly chosen
echo File Created!
pause
cls

set /A Range=%Part%/%inspect%
set /A Range2=%Part%/%inspect%
set /A Inc=%inspect%-%inspect%+1
set /A Bott=%Range%-%Range%+1

FOR /L %%F IN (1,1,%inspect%) DO (
    SET /A Rand_%inc%=!%RANDOM%%Inc%! %% (%range%-%Bott%+1)+%Bott%
    (echo Rand_%inc%) >>%FileName%.txt
    set /A Inc=%Inc%+1
    set /A BOTT=%range%+1
    set /A range=%range%+%range2%+1
    goto :eof
    echo %%f
    )



mercredi 12 janvier 2022

C rand(). Issue with generating random strings

Encountered issue with generating random strings.

Example below generates repeated blocks of random strings. Amount of random string in block depends on 'WORD_LENGTH'. For 1M 'COUNT' and 'WORD_LENGTH' of 20 chars each block contains 262144 (2^18) random strings and then block repeats.

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

#define WORD_LENGTH 20

//const char charset[62] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const char charset[16] = "0123456789abcdef";

int main(int argc, char** argv) {
    srand(time(NULL));
    if (argc != 2) {
        printf("Usage: program COUNT'\n\n");
        return 0;
    }
    unsigned int count = atoi(argv[1]);
    char buf[WORD_LENGTH];
    for (int c = 0; c < count; c++ ) {
        for (int i = 0; i < WORD_LENGTH; ++i) {
            buf[i] = charset[ rand() % sizeof charset];
        }
        buf[WORD_LENGTH - 1] = '\0';
        printf("%s\n", buf);
    }
    return 0;
}

Important thing. I could not reproduce "issue" when "..charset[62]..." are used with 'COUNT' up to 100M. Question: Could someone please explain why it works that way ?




Error C: subscripted value is neither array nor pointer nor vector

I'm new at programming in C language and I'm trying to do a program which adds ellipsis in every space I have in a table, which contains some text. I don't know why I get that error I told you on the title and it's imposible for me to find the problem.

Before the code I only have set this:

char string1, string2;
int ellipsis(string1, string2)
{
    int m, n, tan, blanks;
    tan=strlen(string1);
    blanks = 0;
    n=0;
    for(m=0; m<tan; m++)
        if (string1[m] != ' ')   //<-----The program says that the error is in this line.
        {
          string2[n] = string1[m];
          n++;
        }
        else
        {
            blanks++;
            string2[n] = '.';
            string2[n+1] = '.';
            string2[n+2] = '.';
            n+=2;
        }
    string2[n] = '\0';
    return blanks
}



How to create an unique and random number from an array in Javascript

i'm a super beginner in JS. I try to create a way to generate random unique number (between 0 and 10) by clicking on a button. I want that this number is delete from the array after appearing.

Thank you 🙏🏻

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

const showNumber = document.querySelector("h2");


let allNumbers = [];
for (var i =1; i <= 10; i++){  
    allNumbers.push(i);
}


const randomNumber = btn.addEventListener('click',()=> {
  let n = Math.floor(Math.random()*allNumbers.length+1);
  showNumber.innerText = n;

 });



 if(allNumbers.indexOf(n+1) === n) {  
    allNumbers.splice(n-1,1);
};



How to have a random gradient load without jQuery

I am not sure how I would ask this question.

Here are 3 gradient backgrounds:

How would I have a random one load when the page loads?

How would I do that in the code? https://jsfiddle.net/mdjno3bL/

That is all I am trying to figure out how to do.

Is there a way to do that?

How would it be written without jQuery?

.play1 {
  --color-a: orange;
  --color-b: black;
  --color-c: green;
  --color-d: black;
}

.play2 {
  --color-a: purple;
  --color-b: black;
  --color-c: purple;
  --color-d: black;
}

.play3 {
  --color-a: green;
  --color-b: black;
  --color-c: green;
  --color-d: black;
}
.play1 {
  --color-a: orange;
  --color-b: black;
  --color-c: green;
  --color-d: black;
}

.play2 {
  --color-a: purple;
  --color-b: black;
  --color-c: purple;
  --color-d: black;
}

.play3 {
  --color-a: green;
  --color-b: black;
  --color-c: green;
  --color-d: black;
}

html,
body {
  height: 100%;
  padding: 0;
  margin: 0;
}


body  .bg {
  content: "";
  position: fixed;
  /*z-index: 1;*/
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;

  background-size: 165px 165px;
  background-image:
    linear-gradient(var(--color-a) 5px, #0000 5px),
    linear-gradient(90deg, var(--color-a) 5px, #0000 5px),

    linear-gradient(var(--color-b) 10px, #0000 10px 160px, var(--color-b) 160px),
    linear-gradient(90deg, var(--color-b) 10px, #0000 10px 160px, var(--color-b) 160px),

    linear-gradient(var(--color-c) 15px, #0000 15px 155px, var(--color-c) 155px),
    linear-gradient(90deg, var(--color-c) 15px, #0000 15px 155px, var(--color-c) 155px),

    linear-gradient(var(--color-d) 20px, #0000 20px 150px, var(--color-d) 150px),
    linear-gradient(90deg, var(--color-d) 20px, #0000 20px 150px, var(--color-d) 150px),

    linear-gradient(var(--color-a) 25px, #0000 25px 145px, var(--color-a) 145px),
    linear-gradient(90deg, var(--color-a) 25px, #0000 25px 145px, var(--color-a) 145px),

    linear-gradient(var(--color-b) 30px, #0000 30px 140px, var(--color-b) 140px),
    linear-gradient(90deg, var(--color-b) 30px, #0000 30px 140px, var(--color-b) 140px),

    linear-gradient(var(--color-c) 35px, #0000 35px 135px, var(--color-c) 135px),
    linear-gradient(90deg, var(--color-c) 35px, #0000 35px 135px, var(--color-c) 135px),

    linear-gradient(var(--color-d) 40px, #0000 40px 130px, var(--color-d) 130px),
    linear-gradient(90deg, var(--color-d) 40px, #0000 40px 130px, var(--color-d) 130px),

    linear-gradient(var(--color-a) 45px, #0000 45px 125px, var(--color-a) 125px),
    linear-gradient(90deg, var(--color-a) 45px, #0000 45px 125px, var(--color-a) 125px),

    linear-gradient(var(--color-b) 50px, #0000 50px 120px, var(--color-b) 120px),
    linear-gradient(90deg, var(--color-b) 50px, #0000 50px 120px, var(--color-b) 120px),

    linear-gradient(var(--color-c) 55px, #0000 55px 115px, var(--color-c) 115px),
    linear-gradient(90deg, var(--color-c) 55px, #0000 55px 115px, var(--color-c) 115px),

    linear-gradient(var(--color-d) 60px, #0000 60px 110px, var(--color-d) 110px),
    linear-gradient(90deg, var(--color-d) 60px, #0000 60px 110px, var(--color-d) 110px),

    linear-gradient(var(--color-a) 65px, #0000 65px 105px, var(--color-a) 105px),
    linear-gradient(90deg, var(--color-a) 65px, #0000 65px 105px, var(--color-a) 105px),

    linear-gradient(var(--color-b) 70px, #0000 70px 100px, var(--color-b) 100px),
    linear-gradient(90deg, var(--color-b)70px, #0000 70px 100px, var(--color-b) 100px),

    linear-gradient(var(--color-c) 75px, #0000 75px 95px, var(--color-c) 95px),
    linear-gradient(90deg, var(--color-c) 75px, #0000 75px 95px, var(--color-c) 95px),

    linear-gradient(var(--color-d) 80px, #0000 80px 90px, var(--color-d) 90px),
    linear-gradient(90deg, var(--color-d) 80px, #0000 80px 90px, var(--color-d) 90px),

    linear-gradient(var(--color-a), var(--color-a));
}
<div class="bg play1 "></div>



Replace randomly 1000 NA Values in a dataframe column with 0s, without overwriting 1s

I am trying to randomly replace 1000 NA values in a dataframe column with 0s. The column is composed only of NAs and 1s and it looks like this:

  Column
1 NA
2 1    
3 NA    
4 NA    
5 NA    
6 1    
7 NA
...

I want it to look something like this:

  Column
1 0
2 1    
3 NA    
4 0    
5 NA    
6 1    
7 NA
...

The column I am working with has more than 1000 rows, so there will be space for 0s and NAs in the end.

I tried something like this:

is.na(df_col[sample(seq(nrow(is.na(df_col))), 1000), "Column"]) <- 0

This, however, does not work. No NA values are replaced. If I take out the is.na()s it works, but the values 1 might get replaced and I do not want that. Do you know how to solve this?




Randomize non-diagonal elements of symmetric matrix

I have a symmetric matrix that I want to randomly shuffle while keeping the diagonal elements unchanged. The rows all sum to 1 and should still sum to 1 after shuffling.

Toy example below:

A <- rbind(c(0.6,0.1,0.3),c(0.1,0.6,0.3),c(0.1,0.3,0.6))
A
#      [,1] [,2] [,3]
# [1,]  0.6  0.1  0.3
# [2,]  0.1  0.6  0.3
# [3,]  0.1  0.3  0.6

I would like a matrix B with the same diagonal elements as A and still symmetric, but with the elements randomly shuffled to generate something like

B <- rbind(c(0.6,0.3,0.1), c(0.3,0.6,0.1), c(0.3,0.1,0.6))
B
#      [,1] [,2] [,3]
# [1,]  0.6  0.3  0.1
# [2,]  0.3  0.6  0.1
# [3,]  0.3  0.1  0.6

My aim is to do that on a 24 *24 matrix, so the code can be messy and no need to have something with a low computational cost. So far, I have tried with a loop but the code quickly gets excessively complicated and I was wondering whether there was a more straightforward way to do it.




mardi 11 janvier 2022

How do you use a random element from an array, remove that element from the array, and keep using random elements until the array is empty?

This is my first stack overflow question, so if I am presenting something wrong, please let me know. I am pretty new to computer programming, so I just have a small webpage where I am just implementing things that I am learning.

I made a little quiz with random trivia multiple choice questions you can take if you press a button. I am using window prompts to ask the questions and get the answers, and I have all of the questions and answers stored as objects with question/prompt and answer pairs. All of those objects are stored in an array in a variable called shortQuizPrompts. I already have the quiz working and everything, aka., It tells you after every question if you got the answer to that question right or wrong, and it gives you a grade afterwards... I also have it set up so that if you enter an answer that is not "a", "b", "c", or "d", it lets you know that it isnt a valid answer. Those sorts of things.

As of right now, you can choose how many questions long you want the quiz to be out of the 24 total questions I have so far. It just asks the questions in the order that they are stored in the array. For example, you will never be asked the last question in the array if you do not choose for the quiz to be the full 24 questions long. However, I want to make the quiz ask the questions in a random order, while also removing those questions from the array as to not ask the same question multiple times.

I have tried increasing the iterator while looping through the array to a random number from 0 to the length of however many questions they chose. Then checking to see if the iterator was larger than the length of the number of questions they chose, it would decrease the iterator until it found a question that is still in the array that it could ask...

If anyone knows how to go about doing that, it would be great. Sorry for the long question btw. I am pretty new to coding, so this is probably a simple answer, but I digress. I'm pretty sure I did everything right. Thx.

const quizButton = document.getElementById("quiz-button");

/*  =========================
    Question and answer pairs
    =========================
*/
let shortQuizPrompts = 
   [{prompt: "10 + 10\n(a) 10\n(b) 15\n(c) 20\n(d) 25", answer: "c"},
    {prompt: "What status did astronomers downgrade Pluto to in 2006?\n(a) Dwarf Planet\n(b) White Dwarf\n(c) Black Dwarf\n(d) Dwarf Star", answer: "a"},
    {prompt: 'What tart fruit has a sweet variety called "Meyer"?\n(a) lime\n(b) lemon\n(c) grapefruit\n(d) dragonfruit', answer: "c"},
    {prompt: `What bird lays its eggs in other birds' nests?\n(a) Blue Jay\n(b) Robin\n(c) Eagle\n (d) Cuckoo`, answer: "d"},
    {prompt: `What is a female goat called?\n(a) a foe\n(b) a larp\n(c) a nanny\n(d) a maur`, answer:"c"},
    {prompt: `What is Eisoptrophobia? \n(a) the fear of mirrors\n(b) the fear of cold temperatures\n(c) the fear of farm animals\n(d) the fear of viruses`, answer: `a`},
    {prompt: `Which element of the periodic table is named after the sun?\n(a) slinerium\n(b) helium\n(c) magnesium\n(d) uranium`, answer: `b`},
    {prompt: `What color is the octopus blood?\n(a) pink\n(b) light green\n(c) violet\n(d) light blue`, answer: `d`},
    {prompt: `What value does the Roman numeral C represent?\n(a) 20\n(b) 50\n(c) 100\n(d) 200`, answer: `c`},
    {prompt: `What is measured in fathoms?\n(a) depth of water \n(b) sound \n(c) pressure \n(d) light`, answer: `a`},
    {prompt: `What is Chiroptophobia?\n(a) fear of plants \n(b) fear of insects\n(c) fear of chirogenics \n(d) fear of bats`, answer: `d`},
    {prompt: `What is the longest and heaviest bone in the human body?\n(a) tibia\n(b) skull\n(c) femur\n(d) humorous`, answer: `c`},
    {prompt: `What are the two major elements making up the sun?\n(a) hydrogen and helium\n(b) nitrogen and hydrogen\n(c) oxygen and nitrogen\n(d) oxygen and hydrogen`, answer: `a`},
    {prompt: `What is poliosis?\n(a) a disease impacting your balance\n(b) graying of hair\n(c) loss of hair\n(d) high potassium pressence in blood`, answer: `b`},
    {prompt: `When held to ultraviolet light, what animal’s urine glows in the dark?\n(a) lemur\n(b) cat\n(c) dog\n(d) lamb`, answer: ``},
    {prompt: `What year did the "ILOVEYOU" virus began infecting computers worldwide?\n(a) 2000\n(b) 2001\n(c) 2002\n(d) 2004`, answer: `a`},
    {prompt: `What planet's four largest moons are collectively known as the Galilean Moons?\n(a) neptune\n(b) jupiter\n(c) saturn\n(d) uranus`, answer: `b`},
    {prompt: `What North American mammal is also known as the prairie wolf or brush wolf?\n(a) brown bears\n(b) ocelots\n(c) coyotes\n(d) hyenas`, answer: `c`},
    {prompt: `How often are brain cells replaced?\n(a) once every few hours\n(b) once every few days\n(c) once every few weeks\n(d) never`, answer: `d`},
    {prompt: `What physical property of a diamond do carats measure?\n(a) mass\n(b) purity \n(c) color quality\n(d) mineral composition`, answer: `a`},
    {prompt: `Nosocomephobia is the fear of what?\n(a) night time\n(b) very large objects\n(c) hospitals\n(d) loud noises`, answer: `c`},
    {prompt: `In what year did the Soviet Union launch its first Sputnik satellite?\n(a) 1049\n(b) 1957\n(c) 1963\n(d)1972`, answer: `b`},
    {prompt: `What is measured in Ergs?\n(a) Work\n(b) mass\n(c) depth\n(d) emotion`, answer: `a`},
    {prompt: `What does a Scoville unit measure?\n(a) sourness\n(b) pain\n(c) spiciness\n(d) taste`, answer: `c`},];
    
    
    
    
    /*  ======================
        initiation of the quiz
        ======================
    */
   
        quizButton.onclick = () => {
        let correct = 0;
        const amountOfQuestions = prompt(`How many questions do you want? There are ${shortQuizPrompts.length} maximum`);
        alert('You are about to start the quiz. \nFor each question, enter either "a", "b", "c", or "d". \nPress enter to continue');
        for(i = 0; i< amountOfQuestions; i++) {
           const answer = prompt(shortQuizPrompts[i].prompt);
            if(answer === shortQuizPrompts[i].answer && answer !== null && answer !== undefined) {
                alert("Correct");
                correct++;
            } else if (answer !== shortQuizPrompts[i].answer && answer !==null && answer !== undefined && answer.length >= 1 && (answer === "a" || answer === "b" || answer === "c" || answer === "d")) {
                alert("Incorrect");
            } else if (answer === null) {
                alert(`Bruh, why'd you start the quiz if you didnt want to answer the questions lol`);
            } else if (answer.length == 0) {
                setInterval(alert("Trying to skip questions, I see?? Yeah, you thought you weren't gonna get caught, huh? Well think again")), 100;
            }
            console.log(answer)
            if(i === amountOfQuestions - 1 && (Math.floor(correct / amountOfQuestions * 100)) <= 33) {
                alert(`Wow, you're bad! You made a ${Math.floor((correct / amountOfQuestions) * 100).toFixed(2)}% getting ${correct} out of ${amountOfQuestions} questions correct!`);
        
            }
    
            if(i === amountOfQuestions - 1 && (Math.floor(correct / amountOfQuestions * 100)) > 33 && (Math.floor(correct / amountOfQuestions * 100)) <= 66) {
                alert(`You did ok. You made a ${Math.floor((correct / amountOfQuestions) * 100).toFixed(2)}% getting ${correct} out of ${amountOfQuestions} questions right!`);
        
            }
    
            if(i === amountOfQuestions - 1 && (Math.floor(correct / amountOfQuestions * 100)) > 66 ) {
                alert(`Congratulations! 🎉 You made a ${Math.floor((correct / amountOfQuestions) * 100).toFixed(2)}% getting ${correct} out of ${amountOfQuestions} questions right!`);
            }
            if(answer !== "a" && answer !== "b" && answer!== "c" && answer !== "d" && answer.length > 0 && answer !== null && answer !== undefined) {
                alert(`What are you doing? I told you to only enter "a", "b", "c", or "d" as answers`);
            }
        }
    
    }
* {
    box-sizing: border-box;
}

button {
    cursor: pointer;
}

#quiz-text {
    position: relative;
    left: 42vw;
    top: 25vh;
    transform: translateX(-2%) translateY(5%);
    font-size: 1.5rem;

}

#quiz-button {
    position: relative;
    left: 45vw;
    top: 25vh;
    transform: translateX(-2%) translateY(5%);
    font-size: 20px;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="game.css">
    <script src="D:/Coding/yt games/game.js" defer></script>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title> Random Stuff </title>
</head>
<body id="body">
    <p id="quiz-text">Want to take a short quiz?</p>
    <button id="quiz-button"> START</button>
    
</body>
</html>



How to run the function with multiple argparse

Hello I write my code and want to run this with multiple argparse, but when i try to do it with comma or \ it doesn't work. I'm working on wsl so I use terminal to run function like this.Another problem is when I try to run --possile-sepatators "!@#$$%%" I got the problem bash: !@#: event not found . Code:

import sys
import argparse
import csv
from random import choice
from random import randint
def read_from_csv(path):
    words = []
    with open(path, "r") as file_handle:
        reader = csv.reader(file_handle)
        for row in reader:
            for element in row:
                words.append(element)
    return words

def creating_a_password(list_of_words,args):
    new_string = ""
    if not args.words_number:
        j = 3
        max = j
    else:
        j = args.words_number
        max  = j
    if args.padding_digits:
        dopełnienie = args.padding_digits
    else:
        dopełnienie = 3
    if args.generated_passwords:
        generated_passwords = args.generated_passwords
    else:
        generated_passwords = 1
    a = randint(0, 1000)
    stringa = str(a)
    x = 0
    while x != len(stringa):
        b = randint(0, 1000)
        x = str(b)
        x = len(x)
    j = 0
    list_of_seps = []
    for l in range(generated_passwords):
        for elem in list_of_words:
            if args.possible_separators:
                for sth in args.possible_separators:
                    list_of_seps.append(sth)
                choosing1sep = choice(list_of_seps)
            else:
                choosing1sep = "^"
            if len(new_string) == 0:
                new_string += choosing1sep * dopełnienie
                new_string += str(a)
            if args.minimal_word_length and args.maximal_word_length:
                if (len(elem)>=  args.minimal_word_length) and (len(elem)<= args.maximal_word_length):
                    new_string += elem
                    new_string += choosing1sep
                    j += 1
            else:
                new_string+= elem
                new_string += choosing1sep
                j+= 1
            if j == max :
                new_string += str(b)
                new_string += choosing1sep * dopełnienie
            if j == max:
                break
        print(new_string)




def main(argument):
    parser = argparse.ArgumentParser()
    parser.add_argument("--possible_separators")
    parser.add_argument("--padding-digits")
    parser.add_argument("--padding-symbols-number")
    parser.add_argument("--possible-padding-symbols")
    parser.add_argument("--words_number")
    parser.add_argument("--minimal-word-length")
    parser.add_argument("--maximal-word-length")
    parser.add_argument("--generated-passwords")
    a = read_from_csv("data.txt")
    args = parser.parse_args(argument[1:])
    # number = args.words_number
    b = creating_a_password(a,args)


if __name__ == "__main__":
    main(sys.argv)

I tried for example python3 fileit.py --words_number 3 \ --padding-digits "@#$%". I want to write my program with every argparse argument at the same time. The code is not important, I just want to know how to do it at the same time. Commas doesn't work, spaces doesn't work.




Java Perlin Noise height map generation lacks desired randomness

I am trying to generate a height map using Perlin Noise, but am having trouble with generating truly unique maps. That is, each one is a minor variation of all the others. Two examples are below: Map 1 enter image description here

And here is my code (most was just copied and pasted from Ken Perlin's implementation, though adapted for 2D):

public class HeightMap {

    private ArrayList<Point> map = new ArrayList<>();
    private double elevationMax, elevationMin;

    private final int[] P = new int[512], PERMUTATION = { 151,160,137,91,90,15,
            131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,
            190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,
            88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,
            77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,
            102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,
            135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,
            5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,
            223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,
            129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,
            251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,
            49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,
            138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180
    };

    public HeightMap() {
        this.map = null;
        this.elevationMax = 0.0;
        this.elevationMin = 0.0;
    }

    public HeightMap(HeightMap map) {
        this.map = map.getPoints();
        this.elevationMax = map.getElevationMax();
        this.elevationMin = map.getElevationMin();
    }

    /**
     * Generates a Height Map that is, along an imaginary z-axis, centered around the median elevation, given the following parameters:
     * @param mapWidth the width [x] of the map
     * @param mapHeight the height [y] of the map
     * @param tileWidth the width [x] of each tile, or Point
     * @param tileHeight the height [y] of each tile, or Point
     * @param elevationMax the maximum elevation [z] of the map
     * @param elevationMin the minimum elevation [z] of the map
     */
    public HeightMap(int mapWidth, int mapHeight, int tileWidth, int tileHeight, double elevationMax, double elevationMin) {
        this.elevationMax = elevationMax;
        this.elevationMin = elevationMin;

        for (int i=0; i < 256 ; i++) {
            P[256+i] = P[i] = PERMUTATION[i];
        }

        int numTilesX = mapWidth / tileWidth;
        int numTilesY = mapHeight / tileHeight;

        Random r = new Random();

        for (int t = 0; t < numTilesX * numTilesY; t++) {
            double x = t % numTilesX;
            double y = (t - x) / numTilesX;
            r = new Random();
            x += r.nextDouble();
            y += r.nextDouble();

            this.map.add(new Point(x, y, lerp(noise(x, y, 13), (elevationMin + elevationMax) / 2, elevationMax), tileWidth, tileHeight));
        }
    }

    /**
     * Ken Perlin's Improved Noise Java Implementation (https://mrl.cs.nyu.edu/~perlin/noise/)
     * Adapted for 2D
     * @param x the x-coordinate on the map
     * @param y the y-coordinate on the map
     * @param stretch the factor by which adjacent points are smoothed
     * @return a value between -1.0 and 1.0 to represent the height of the terrain at (x, y)
     */
    private double noise(double x, double y, double stretch) {
        x /= stretch;
        y /= stretch;
        int X = (int)Math.floor(x) & 255, Y = (int)Math.floor(y) & 255;

        x -= Math.floor(x);
        y -= Math.floor(y);

        double u = fade(x),
               v = fade(y);

        int AA = P[P[X    ] + Y    ],
            AB = P[P[X    ] + Y + 1],
            BA = P[P[X + 1] + Y    ],
            BB = P[P[X + 1] + Y + 1];

        return lerp(v, lerp(u, grad(P[AA], x, y), grad(P[BA], x - 1, y)), lerp(u, grad(P[AB], x, y - 1), grad(P[BB], x - 1, y - 1)));
    }

    private double fade(double t) {
        return t * t * t * (t * (t * 6 - 15) + 10);
    }

    private double lerp(double t, double a, double b) {
        return a + t * (b - a);
    }

    //Riven's Optimization (http://riven8192.blogspot.com/2010/08/calculate-perlinnoise-twice-as-fast.html)
    private double grad(int hash, double x, double y) {
        switch(hash & 0xF)
        {
            case 0x0:
            case 0x8:
                return  x + y;
            case 0x1:
            case 0x9:
                return -x + y;
            case 0x2:
            case 0xA:
                return  x - y;
            case 0x3:
            case 0xB:
                return -x - y;
            case 0x4:
            case 0xC:
                return  y + x;
            case 0x5:
            case 0xD:
                return -y + x;
            case 0x6:
            case 0xE:
                return  y - x;
            case 0x7:
            case 0xF:
                return -y - x;
            default: return 0; // never happens
        }
    }
}

Is this problem inherent in Perlin Noise because the 'height' is calculated from nearly the same (x, y) coordinate each time? Is there a way to implement the noise function so that it doesn't depend on the (x, y) coordinate of each point but still looks like terrain? Any help is greatly appreciated.




Random distribution of N points with a specified average spacing?

This is probably a question of logic more than an algorithm. I want to distribute about N points in such a way that the average distance of a single point to the other N-1 points is uniformly distributed around a value d. That is, The points themselves are not be normally distributed but their spacing with respect to each other is.

Is there a logical way to implement this?

For Example :

X = np.ones(N) #1d for simplicity
d = np.ones(N)

for i in range(N):
    X[i] = ## Insert the algorithm here 
       ##

for i in range(N):
    da = 0 
    for j in range(N):
        if i != j:
            da += np.sqrt(np.abs(X[i]**2 - X[j]**2))  #Calculating distance to other points and 
                                                        summing up
            
    
    da = da / (N-1) # Taking average of all distances
    
    d[i] = da  # the average distance of point i with all other points 

A = np.mean(d) #The mean of all average distances

A is the parameter I want control over. It should be basis for how all the points are distributed.Recommendations using inbuilt Python or C modules would work as well.




Analyzing an effect as both fixed and random

I have a study that was conducted on 2 farms. This wasn't part of the initial experimental design, and wasn't a main focus of the study. I have therefore included it as a random effect in most of my analyses. However, I am also interested in whether the treatment effects were consistent across the two farms, so I have conducted another analysis with farm as a fixed effect, and included the interaction with treatment.

My advisor is arguing that the farm effect should be either fixed or random for all analyses, and not different across analyses. My question is, am I correct in thinking that it should be random if we're not interested in the effect itself, and then fixed when we are, or should it be fixed at all times? And does anyone have references I could use to support either decision?




Weird stack buffer overrun crash using std::uniform_int_distribution

I am using CMake with "Visual Studio 17 2022" Generator in my desktop to compile this code. Whenever I put this code, it works and then crashes with stack buffer overrun 0xc0000409 after the containing function returns, only in the Release build. The Debug build works well, which is similar to the situation this answer is describing.

std::random_device rd;
std::default_random_engine eng(rd());
std::uniform_int_distribution<uint64_t> dis(std::numeric_limits<uint64_t>::min(), std::numeric_limits<uint64_t>::max());
dis(eng);

The exactly same code containing this works well in Google colab(using g++ 11). How can I fix this?




NumPy equivalent to random.getrandbits()

I'm working on creating a subclass of random.Random() where the generator is actually NumPy's default Random Generator.

The reason for this is, I can leverage parallel execution using NumPy's generator via the SeedSequence object.

Overriding methods random() and seed() is fairly easy, however, I also need to override method getrandbits(), but I haven't been able to find any Numpy's equivalent function/solution. getrandbits() is used heavily by all other functions of class random.Random().




lundi 10 janvier 2022

lambda function to random color

I want generate RGB color with Lambda function. I have tried to do this code:

r = lambda: random.randint(0,255)
color=[r,r,r]

print(r)
color

Output:

<function <lambda> at 0x7f2aca8a7c20>
  
  [<function __main__.<lambda>>,
   <function __main__.<lambda>>,
   <function __main__.<lambda>>] 

I did not even get one number (r). Can anyone explain to me why this function is not good?


Update and Edit:

I realized that the lambda is a function that receives no value r() But how do you make the paint work in the same method and not permanently

If it is possible to convert a variable to a random number - that will not be in the function. That is, whenever a variable is available it will be different?




ValueError: maximum supported dimension for an ndarray

Python gives an error at the variable T. The others above do work, I do not see any differences? Anyone can identify the problem. The error is:

ValueError: maximum supported dimension for an ndarray is 32, found 10000

N = 10000
Cpl = np.random.normal(0.6, 0.1, N)    
Cs = np.random.normal(0.5, 0.1, N)
P = np.random.normal(1, 0.1, N)
Sd = np.random.normal(4, 0.1, N)
N = np.random.normal(3600, 100, N)
alpha = np.random.normal(8, 0.01, N)
Hs = np.random.normal(5, 1, N)
rho_w = np.random.normal(1025, 5, N)
rho_s = np.random.normal(2600, 50, N)
dn50 = np.random.normal(3.5, 0.1, N)
T = np.random.normal(9, 1, N)

mc = bw.MonteCarlo(Pf=2e-5,
               zfunc = 'vdmeer',
               Cpl=Cpl, 
               Cs= Cs, 
               P=P, 
               Sd=Sd, 
               N=N, 
               T=T, 
               alpha=alpha, 
               Hs=Hs, 
               rho_w=rho_w, 
               rho_s=rho_s, 
               dn50=dn50)    
 



dimanche 9 janvier 2022

Display random unique possibilities from rows from a table

I want to display random different possibilities from a specific data table. I am trying to grab random unique (cannot be used more than once) IDs from column "A" (about 100 IDs in this field), and making sure criteria is met from columns "B" and "C"(Usually only whole number or .5 decimal numbers).

Example list below, but very shortened format. I want to have total number (column "C") equal 19.5 or 20, and have:

  1. Red from column "B" to be > 5 in column "C".
  2. Green from column "B" have at least 2 in column "C"
  3. Yellow from column "C" cannot be more than 7 in column "C"

I want it so that every time I press a button, it will have another random possibility to fit specific criteria.

ID Colour Number
111 Red 1.5
112 Blue 2
113 Green 1
114 Blue 1.5
115 Yellow 2
116 Blue 1

I have been trying to freestyle with the little knowledge that I have and have the below so far. I am not sure if I am going in the right direction.

Sub RandomPossibilities()

Dim NoOfIDs As Long
Dim RandomNumber As Integer
Dim IDs(), Colour() As String 
Dim i As Byte
Dim CellsOut As Long 
Dim ArI As Byte 
Dim RedCount, BlueCount, YellowCount, GreenCount, TotalCount As Variant

Application.ScreenUpdating = False
RedCount = 0
BlueCount = 0
GreenCount = 0
YellowCount = 0
TotalCount = 0
CellsOut = 6
ReDim IDs(1 To 20) 
ReDim Colour(1 To 20)
NoOfIDs = Application.CountA(Range("A:A")) - 1 

i = 1
Do Until (TotalCount = 20 Or TotalCount = 19.5) And RedCount >= 5 And GreenCount >= 2 And YellowCount <= 7

RandomNo:
    RandomNumber = Application.RandBetween(2, NoOfIDs + 1)
    For ArI = LBound(IDs) To UBound(IDs)
        If IDs(ArI) = Cells(RandomNumber, 1).Value Then
            GoTo RandomNo
        End If
        If Cells(RandomNumber, 2).Value = "Not Available"
            GoTo RandomNo
        End If
     Next ArI
    
 IDs(i) = Cells(RandomNumber, 1).Value 
 Colour(i) = Cells(RandomNumber, 2).Value
    
 If Cells(RandomNumber, 2).Value = "Red" Then
     RedCount = RedCount + Cells(RandomNumber, 3).Value
 ElseIf Cells(RandomNumber, 2).Value = "Yellow" Then
     YellowCount = YellowCount + Cells(RandomNumber, 3).Value
 ElseIf Cells(RandomNumber, 2).Value = "Blue" Then
     BlueCount = BlueCount + Cells(RandomNumber, 3).Value
 ElseIf Cells(RandomNumber, 2).Value = "Green" Then
     GreenCount = GreenCount + Cells(RandomNumber, 3).Value
 End If
    

 If TotalCount = 20 Or TotalCount = 19.5 Then
    If RedCount >= 5 Then
       i = 0
       RedCount = 0
       BlueCount = 0
       GreenCount = 0
       YellowCount = 0
       TotalCount = 0
    End If
    If GreenCount >= 2 Then
       i = 0
       RedCount = 0
       BlueCount = 0
       GreenCount = 0
       YellowCount = 0
       TotalCount = 0
    End If
    If YellowCount <= 7 Then
       i = 0
       RedCount = 0
       BlueCount = 0
       GreenCount = 0
       YellowCount = 0
       TotalCount = 0
    End If
 End If
    
 If TotalCount >= 9 Then
    If RedCount >= 5 Then
       i = 0
       RedCount = 0
       BlueCount = 0
       GreenCount = 0
       YellowCount = 0
       TotalCount = 0
    End If
 If GreenCount >=2 Then
       i = 0
       RedCount = 0
       BlueCount = 0
       GreenCount = 0
       YellowCount = 0
       TotalCount = 0
 End If
 If YellowCount <=7 2 Then
       i = 0
       RedCount = 0
       BlueCount = 0
       GreenCount = 0
      YellowCount = 0
       TotalCount = 0
    End If
       i = 0
       RedCount = 0
       BlueCount = 0
       GreenCount = 0
       YellowCount = 0
    TotalCount = 0
 End If
    i = i + 1

TotalCount = GreenCount + BlueCount + YellowCount + RedCount
    
Loop


For ArI = LBound(IDs) To UBound(IDs)
    Cells(CellsOut + 2, 6) = IDs(ArI)
    Cells(CellsOut + 2, 7) = Colour(ArI)
    CellsOut = CellsOut + 1
Next ArI
Cells(8, 9) = YellowCount
Cells(9, 9) = BlueCount
Cells(10, 9) = GreenCount
Cells(11, 9) = RedCount
Cells(12, 9) = TotalCount
Application.ScreenUpdating = True
End Sub