jeudi 31 décembre 2020

Best way of testing randomized function

Let's say I have a random number generator for 3 categories:

Prob Yield
0.1 10
0.2 5
0.7 2

The expected yield is 1 + 1 + 1.4 = 3.4

Currently I have something like this

sum = 0
N = 10000
for i in 1 to N:
    sum += getYeild()
assert(sum / N - 3.14 < some threshold)

So what is the best criterion I can use for this unit test to make an assertion?




Odd Python random.randint behavior

I wrote a program to create the appearance of a snake sliding down the screen. You can pass in a width and length for the path the snake travels down. The snake moves at random staying within the width confines given.

All works fairly well, except when testing my guard rails to keep the snake within the defined width. I noticed at times the snake position (left_side) appears to be able to go to a negative value. Given that I have a guard rail that when left_side == 0 it should only be able to move back right given that when that condition is true my only values I can add to is should be 0 or 1.

How do I fix this?

My code:

import random
import time

def path(path_width, snake_pos):
    path = ""
    for space in range(path_width + 1):
        if space == 0:
            path = path + "|"
        if space == snake_pos:
            path = path + "()"
        if space == width: 
            path = path + "|"
        else:
            path = path + " "
    return path

width = int(input("How wide is your course? "))
length = int(input("How long is your course? "))

left_side = random.randint(1, width -1)

i=1
while i < length:
    if left_side == 0:
        left_side = left_side + random.randint(0, 1)
    if left_side == width:
        left_side = left_side + random.randint(-1, 0)
    else:
        left_side = left_side + random.randint(-1, 1)
    print(path(width, left_side) + " : leftside = " + str(left_side))
    i += 1
    time.sleep(.05)



Brute Force with random and requests Library | python

I want to login with my mail address, but the password, I want to find out with my brute force python script here:

import requests
import random

s = requests.session()

here is my form data except the password:

payload = {
    "username": "maixr_p4ter@web.de",
}
password = payload["password"] = ""

here are some chars, that I converted to a list and I want that my script tries all possibilities:

chars="AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz01234567890"
chars_list = list(chars)
response = s.post("https://login.web.de/login",data=payload)

and here is my while-loop, I declared that if the password does not equal to result.status_code == 200, he should play the loop over and over. (As you know status_code returned a 200 , which means the request was successful and the server responded with the data I was requesting)

while(password != (result.status_code == 200)):

    password = random.choices(chars_list)
    print("<=="+str(guess_password)+"==>")

    if(password == list(password)):
        print("Your password is: "+ "".join(password))

but it gives me in the end: IndentationError: unexpected indent maybe you can help me to fix my problem.

all code:

import requests
import random

s = requests.session()

payload = {
    "username": "meier_peter8@web.de",
}


password = payload["password"] = "" 

chars="AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz01234567890"
chars_list = list(chars)
response = s.post("https://login.web.de/login",data=payload)

    while(password != (result.status_code == 200)):

        password = random.choices(chars_list)
        print("<=="+str(guess_password)+"==>")

        if(password == list(password)):
            print("Your password is: "+ "".join(password))



Difference between RANDOM and SRANDOM in Bash

Bash 5.1 introduces SRANDOM variable, but does it make any difference when used like this?

for i in {1..10}; do
  nbr=$((RANDOM%50))
  nbr1=$((SRANDOM%50))
  echo "$nbr -- $snbr"
done
9 -- 21
35 -- 43
27 -- 15
7 -- 24
41 -- 31
37 -- 35
23 -- 47
14 -- 23
9 -- 37
6 -- 30

From the manual:

RANDOM

Each time this parameter is referenced, it expands to a random integer between 0 and 32767. Assigning a value to this variable seeds the random number generator. If RANDOM is unset, it loses its special properties, even if it is subsequently reset

SRANDOM

This variable expands to a 32-bit pseudo-random number each time it is referenced. The random number generator is not linear on systems that support /dev/urandom or arc4random, so each returned number has no relationship to the numbers preceding it. The random number generator cannot be seeded, so assignments to this variable have no effect. If SRANDOM is unset, it loses its special properties, even if it is subsequently reset.

I don't understand what is meant by non-linear and seeding, but for my example is there a reason to use RANDOM over SRANDOM or vice-versa, or it doesn't make any difference?




How to use random function in C

In a for my personal life program (for a video game I plays), I want to write a C program witch will generate a random number between 1 and a given number.

How do I use the C random function?

(Of course I can use google random number generator, but what's the fun in that?)




How i can fill an half array random with number 1

we have an array p = [[none]*5]*6 and we want to fill it with number 1

something like this:

 [[1, none, none, 1, 1],[none, 1, none, 1, none],[none, 1, 1, 1, none], [1, none, 1, none, 1], [none, 1, none, 1, none],[1, none, 1, none, none]]



How to generate a random values periodically and publish it using MQTT protocol?

I want to repletely generate different random values for every 1 second and publish it to MQTT protocol. The code is working but it is keep sending the last value how to make it that it will send a different value every 1 second?

var mqtt = require('mqtt')

var Broker_URL = 'mqtt://localhost';
var client  = mqtt.connect(Broker_URL);

var MIN_PER_RANK =75
var MAX_PER_RANK =100

client.on('connect', function () {
    console.log("MQTT connected  "+ client.connected);
})

class virtualsensor {
    
    sendStateUpdate (newdata) {
        client.publish("testtopic", newdata)
    }
}

let vs = new virtualsensor()

let newdata = '';

for (var i=0; i<5; i++){
    newdata= String(Math.floor(Math.random() * (MAX_PER_RANK - MIN_PER_RANK  + 1) + MIN_PER_RANK));
    vs.sendStateUpdate(newdata)
}

var interval = setInterval(function(){vs.sendStateUpdate(newdata)},1000);

the output:

testtopic 81
testtopic 76
testtopic 89
testtopic 100
testtopic 96
testtopic 96
testtopic 96
testtopic 96
testtopic 96
testtopic 96
testtopic 96
testtopic 96
testtopic 96

Thanks in advance.




Simple Bubble sort program. It works flawlessly about 85% of times but in some cases it doesn't sort the list

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

main()
{
    int ctr, inner, outer, didSwap, temp;
    int nums[10];
    time_t t;

    srand(time(&t));

    for (ctr = 0; ctr < 10; ctr++)
    {
        nums[ctr] = (rand() % 99) + 1;
    }

    printf("\nHere is the list before the sort:\n");
    for (ctr = 0; ctr < 10; ctr++)
    {
        printf("%3d",nums[ctr]);
    }

    // Sorting the array

    for (outer = 0; outer < 9; outer++)
    {
        didSwap = 0;

        for (inner = outer + 1; inner < 10; inner++)
        {
            if (nums[inner] < nums[outer])
            {
                temp = nums[inner];
                nums[inner] = nums[outer];
                nums[outer] = temp;
                didSwap = 1;
            }
        }

        if (didSwap == 0)
        {
            break;
        }
    }

    printf("\n\nHere is the list after sorting:\n");
    for (ctr = 0; ctr < 10; ctr++)
    {
        printf("%3d", nums[ctr]);
    }

    printf("\n");

    return 0;
}

Sometimes it doesn't sort the list properly and sometimes doesn't sort at all. Screenshot of error




mercredi 30 décembre 2020

How do I create a table that can be filled with data from a data set randomly

I'm trying to create a random movie generator. I've already created a generator that displays a new movie after a button is clicked. But I want to create a table that will display more information about each movie that is generated i.e the director, genre, year etc. I want this information to be generated into a table each time and the correct data to be under the correct heading in the table.

Example of how the data would look

HTML so far:

<!DOCTYPE HTML>
   <html lang="en">
   <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
    <link rel="stylesheet" href="movie.css">
    <title>Movie Generator</title>
</head>
   <body><div class="container">
        <div class="row flex-top justify-content-center">
            <header class="border shadow">
                <h1>Movie Generator</h1>
            </header> 
        </div>

        <div class="row flex-top justify-content-center">
            <button id="button" class="btn-large new-movie-button" onClick="getMovie()">New Movie</button>
        </div>

        <div class="row justify-content-center">
            <main class="card">
                <p class="movie card-body center" id="newMovieSection"></p>
            </main>
        </div>
    </div>
<script src="movie.js"></script>
</body>
</html>

CSS so far:

header {
    padding: 2em;
    background-color: black;
    margin-top: 2em;
    text-align: center;
    color: white;
}

.movie {
    font-size: 2em;
}

.btn-large {
    margin: 0.5em
}
.card {
    text-align: center;
    width: 45em;
}

.new-movie-button{
    background-color: rgb(77, 87, 97);
    border-color: black;
    color: white;

}

button:hover {
    background-color: rgb(142, 155, 168);
    color: white;
}

JavaScript so far:

var movies = [
"Twilight",
"The Twilight Saga: New Moon",
"The Twilight Saga: Eclipse",
"The Twilight Saga: Breaking Dawn - Part 1",
"The Twilight Saga: Breaking Dawn - Part 2",
"Star Wars: Episode IV - A New Hope ",
"Star Wars: Episode V - The Empire Strikes Back",
"Star Wars: Episode VI - Return of the Jedi",
"Star Wars: Episode I - The Phantom Menace",
"Star Wars: Episode II - Attack of the Clones",
"Star Wars: Episode III - Revenge of the Sith",
"Star Wars: Episode VII - The Force Awakens ",
"Star Wars: Episode VIII - The Last Jedi ",
"Star Wars: The Rise of Skywalker",
"Rogue One: A Star Wars Story",
"Iron Man ",
"Iron Man 2",
"Iron Man 3",
"The Incredible Hulk",
"Thor",
"Thor: The Dark World",
"Thor: Ragnarok",
"Captian America: The First Avenger ",
"Captian America: The Winter Soldier",
"Captian America: Civil War",
"Avengers Assemble ",
"Avengers: Age of Ultron ",
"Avengers: Infinity War",
"Avengers: Endgame",
"Black Panther ",
"Doctor Strange ",
"Ant-Man",
"Ant-Man and the Wasp",
"Spider-Man: Homecoming ",
"Spider-Man: Far from Home",
"Guardians of the Galaxy ",
"Guardians of the Galaxy Vol.2",
"Harry Potter and the Philosopher's Stone ",
"Harry Potter and the Chamber of Secrets  ",
"Harry Potter and the Prisoner of Azkaban   ",
"Harry Potter and the Goblet of Fire   ",
"Harry Potter and the Order of the Phoenix   ",
"Harry Potter and the Half-Blood Prince  ",
"Harry Potter and the Deathly Hallows: Part 1  ",
"Harry Potter and the Deathly Hallows: Part 2",
"The Lord of the Rings: The Fellowship of the Ring ",
"The Lord of the Rings: The Two Towers ",
"The Lord of the Rings: The Return of the King ",
"The Hobbit: An Unexpected Journey ",
"The Hobbit: The Desolation of Smaug ",
"The Hobbit: The Battle of Five Armies ",
"Spider-Man",
"Spider-Man 2",
"Spider-Man 3",
"Mission: Impossible ",
"Mission: Impossible II",
"Mission: Impossible III",
"Mission: Impossible - Ghost Protocol",
"Mission: Impossible - Rogue Nation ",
"Mission: Impossible - Fallout ",
"Rise of the Planet of the Apes",
"Dawn of the Planet of the Apes",
"War for the Planet of the Apes",
"The Bourne Identity ",
"The Bourne Supremacy",
"The Bourne Ultimatum ",
"The Bourne Legacy",
"Jason Bourne ",
"The Amazing Spider-Man ",
"The Amazing Spider-Man 2",
"Jurassic Park",
"The Lost World: Jurassic Park",
"Jurassic Park III",
"Jurassic World",
"Jurassic World: Fallen Kingdom",
"Jumanji",
"Jumanji: Welcome to the Jungle",
"Jumanji: The Next Level",
"The Fast and the Furious ",
"2 Fast 2 Furious",
"The Fast and the Furious: Tokyo Drift ",
"Fast & Furious",
"Fast & Furious 5",
"Fast & Furious 6",
"Fast & Furious 7",
"Fast & Furious 8",
"Fast & Furious: Hobbs & Shaw",
"Transformers",
"Transformers: Revenge of the Fallen",
"Transformers: Dark of the Moon",
"Transformers: Age of Extinction",
"Transformers: The Last Knight ",
"X-Men",
"X2",
"X-Men: The Last Stand",
"X-Men Origins: Wolverine ",
"X-Men: First Class",
"The Wolverine ",
"X-Men: Days of Future Past",
"Logan",

] 

function getMovie() {
    var randomNumber = Math.floor(Math.random() * movies.length);
    document.getElementById("newMovieSection").innerHTML = movies[randomNumber];

}



Change the range of IRAND() in Fortran 77 [duplicate]

I am trying to create a list of random numbers (integers) in fortran 77 but can't quite make it work.

My problem is a want a list of N random integers, say N = 100. But also, I want the random numbers to only appear in a range between 1 and N.

So if I make:

       do 1001 j=1, N
           ar = IRAND()
           print*, j,ar
 1001 continue

That just gives me a list of integers from 0 through 2147483647.

Is there a way to change the range in IRAND()? or quick fix at least?




Create random list of size "n" containing elements from another list

I want to create random string filled with "S" and "O". For example, my desired output is like:

SSOSOOSO
OSOOSSOS
SSSOOSSO
OSOSOSOO

With my code I change randomly every line, so what is the way to change every position?

import random

rows = 4
columns = 8
char_list = ['S', 'O']

for i in range(rows):
    print(random.choice(char_list) * columns)

My current output:

SSSSSSSS
SSSSSSSS
OOOOOOOO
SSSSSSSS



Create random number and make an array from that number c# [closed]

hey guys I’m making a small project using c# for my class the program is 1- ask user to enter in Integer value between 2 and 9 This value from user gave you the maximum for random number for ex if the user write 7 the maximum will be 7 nines (9999999) and like this 2-crate a random number from 10 and the maximum depend on the value from user as I said before if 5 the random number limit will be between (10, (99999+1))

3-after crated the random number I need to create an array using that random number from before for ex if the user writes 3 The random number will be between (10, (999+1)) for ex the random number will be 271 I need to full the array using that number starting from right Like this:

    Array[0]=1
    Array[1]=7
    Array[2]=2

this how the program should be and i want the answer like this Please i want the answer without function or method Sorry about my english And thank you ♥️




How to get random item from a list in python3 without any module

I am using Python 3.9 & have a list list1 = ['a', 'b', 'c', 'd'] I want to get a random item from the list without using any module like there is a module random in Python and a function random.choice(list1) I can use this but is there another way to get a random item from a list in Python without using any module?




Generate pseudo-random list in Perl

I have a list with 79 entries that each look similar to this:

"YellowCircle1.png\tc\tColor"

That is, each entry has 3 elements (.png-file, a letter, and a category). The category can be color, number or shape.

I want to create a new list from this, pseudo-randomized. That is, I want to have all 79 entries in a random order, but with a limitation.

I have created a perl script for a completely random version using shuffle:

# !/usr/bin/perl
# Perl script to generate input list for E-Prime experiment
# with semi-randomized trials
# Date: 2020-12-30

# Open text file
$filename = 'output_shuffled.txt';
open($fh, '>', $filename) or die "Could not open file '$filename'";

# Generate headline
print $fh "Weight\tNested\tProcedure\tCardIMG1\tCardIMG3\tCardIMG4\tCardStim\tCorrectAnswer\tTrialType\n";

# Array with list of stimuli including corresponding correct response and trial type
@stimulus = (
"BlueCross1.png\tm\tColor",
"BlueCross2.png\tm\tColor",
"BlueStar1.png\tm\tColor",
"BlueStar3.png\tm\tColor",
"BlueTriangle2.png\tm\tColor",
"BlueTriangle3.png\tm\tColor",
"GreenCircle1.png\tv\tColor",
"GreenCircle3.png\tv\tColor",
"GreenCircle1.png\tv\tColor",
"GreenCircle3.png\tv\tColor",
"GreenCross1.png \tv\tColor",
"GreenCross4.png\tv\tColor",
"GreenTriangle3.png\tv\tColor",
"GreenTriangle4.png\tv\tColor",
"RedCircle2.png\tc\tColor",
"RedCircle3.png\tc\tColor",
"RedCross2.png\tc\tColor",
"RedCross4.png\tc\tColor",
"RedStar3.png\tc\tColor",
"RedStar4.png\tc\tColor",
"YellowCircle1.png\tn\tColor",
"YellowCircle2.png\tn\tColor",
"YellowStar1.png\tn\tColor",
"YellowTriangle2.png\tn\tColor",
"YellowTriangle4.png\tn\tColor",
"BlueCross1.png\tc\tNumber",
"BlueCross2.png\tv\tNumber",
"BlueStar1.png\tc\tNumber",
"BlueStar3.png\tn\tNumber",
"BlueTriangle2.png\tv\tNumber",
"GreenCircle1.png\tc\tNumber",
"GreenCircle3.png\tn\tNumber",
"BlueCross1.png\tm\tColor",
"BlueCross2.png\tm\tColor",
"BlueStar1.png\tm\tColor",
"BlueStar3.png\tm\tColor",
"BlueTriangle2.png\tv\tNumber",
"BlueTriangle3.png\tn\tNumber",
"GreenCircle1.png\tc\tNumber",
"GreenCircle3.png\tn\tNumber",
"GreenCross1.png\tc\tColor",
"GreenCross4.png\tm\tColor",
"GreenTriangle3.png\tn\tColor",
"GreenTriangle4.png\tm\tColor",
"RedCircle2.png\tv\tNumber",
"RedCircle3.png\tn\tNumber",
"RedCross2.png\tv\tNumber",
"RedCross4.png\tm\tNumber",
"RedStar3.png\tn\tColor",
"RedStar4.png\tm\tColor",
"YellowCircle1.png\tc\tColor",
"YellowCircle2.png\tv\tColor",
"YellowStar1.png\tc\tNumber",
"YellowStar4.png\tm\tNumber",
"YellowTriangle2.png\tv\tNumber",
"YellowTriangle4.png\tm\tNumber",
"BlueCross1.png\tn\tShape",
"BlueCross2.png\tn\tShape",
"BlueStar1.png\tv\tShape",
"BlueStar3.png\tv\tShape",
"BlueTriangle2.png\tc\tShape",
"BlueTriangle3.png\tc\tShape",
"GreenCircle1.png\tm\tShape",
"GreenCircle3.png\tm Shape",
"GreenCross1.png\tn\tShape",
"GreenCross4.png\tn\tShape",
"GreenTriangle3.png\tc\tShape",
"GreenTriangle4.png\tc\tShape",
"RedCircle2.png\tm\tShape",
"RedCircle3.png\tm\tShape",
"RedCross2.png\tn\tShape",
"RedCross4.png\tn\tShape",
"RedStar3.png\tv\tShape",
"RedStar4.png\tv\tShape",
"YellowCircle1.png\tm\tShape",
"YellowCircle2.png\tm\tShape",
"YellowStar1.png\tv\tShape",
"YellowStar4.png\tv\tShape",
"YellowTriangle2.png\tc\tShape",
"YellowTriangle4.png\tc\tShape",
);

# Shuffle --> Pick at random without double entries
use List::Util 'shuffle';
@shuffled = shuffle(@stimulus);

# Print each line with fixed values and shuffled stimulus entries to file
print $fh "1\t" . "\t" . "TrialProc\t" . "RedTriangle1.png\t" . "Greenstar2.png\t" . "YellowCross3.png\t" . "BlueCircle4.png\t" . "\t$_\n" for @shuffled;

# Close text file
close($fh);

# Print to terminal
print "Done\n";

However, what I eventually want is that the category does not switch more than once successively, but every 3 up to 5 times (randomly between these numbers). For example, if one line ends with "shape" and the following line with "color", the next line would have to be "color", because otherwise there would be 2 switches successively.

How would I create this? I suspect I would have to change the entries to something like hashes, so that I can create if-constructions based on the last element (that is "category") of each entry?




to print maximum and minimum sum of 4 out of 5 integers inputted using random in python

In hackerrank,this question is failing 8 out of 15 testcases,can someone please correct this and tell me what is wrong.

Also I want to use random in this question and not by other methods.

import random

inputting values in list

arr=[int(x) for x in input().split()]

assigning a randomly selected large number for minimum (mini)

mini=1000000000000

maxi=0

for x in range(len(arr)-1):
    randomsum=sum(random.sample(arr,4))
    if randomsum<mini:
       mini=randomsum
    if randomsum >maxi:
       maxi=randomsum

print(mini,maxi)



mardi 29 décembre 2020

How to generate random values that are distant from a list of values?

I have the following transparent images.

enter image description here enter image description here enter image description here enter image description here

What I want to do is to paste them on an image with a background of a specific color. The color of the background is randomized like this:

rand1, rand2, rand3 = (random.randint(0, 255),
                       random.randint(0, 255),
                       random.randint(0, 255))

background = Image.new('RGBA', png.size, (rand1, rand2, rand3))

alpha_composite = Image.alpha_composite(background, png)

Unfortunately, some of the logos don't go well with their background colors. The background color sometimes comes close to color(s) inside the logo, which makes the logo either partially or completely invisible. Here is an example where the background color is almost identical to the orange color in the Ubuntu logo:

enter image description here

What I did was to get all of the colors from each logo and save them in a list of tuples like this. This is actually a list of lists of tuples. I've just edited it now to highlight which nested list of tuples belong to which logo:

Intel = [(0, 113, 197)]
Corsair = [(4, 7, 7)]
Google = [(66, 133, 244), (234, 67, 53), (251, 188, 5), (52, 168, 83), (0, 255, 255), (255, 128, 0), (255, 255, 0)]
Riot = [(209, 54, 57), (255, 255, 255), (226, 130, 132), (0, 0, 0)]

What I want to do is to use the above ^ information to randomly choose background colours so that no part of a logo is made invisible. I'm asking for suggestions on strategies to go about this..




Random Numbers without repeat. Beginner Lvl

I've learning JS for a week so I know, it's terrible code. However I have a question. How can I randomly generate numbers without repetition in this case? Btw. sorry for my english XD

let lottoArray = [];

lottoGame()

function lottoGame () {
    do {
        let addNumber = Math.floor(Math.random()* 30);
        lottoArray.push(addNumber)
        console.log(addNumber)
    }  while(lottoArray.length <= 5 ) {
          
       }
       document.querySelector('.loti').innerHTML = lottoArray 
}



my simple rng code is not working. Why is that so?

I'm new to Javascript, as of right now I just watched a 3 hour-long tutorial and took part in a few private programming lessons. I was assigned my first project where I try to simulate a battle between two armies. Here is the code.

var myArmy = ["arcieri", "fanteria", "cavalleria", "morale"]  // <--- my Army brigades
function rng_loop() {
Math.floor(Math.random * myArmy.length)  // <---- the rng function
}

while (myArmyStrength > 0 && enemyArmyStrength > 0) {
  rng_loop()
} if (rng_loop() > 1) {
  enemyArmyStrength - 25
} else if (rng_loop() < 1) {
myArmyStrength - 20
}

/* this is what was supposed to be my loop generating random numbers and killing off both armies based on the value of said random numbers until one of the two armies got to 0. myArmyStrength and enemyArmyStrength were specified earlier on. */

if (myArmyStrength > 0 && enemyArmyStrength <= 0) {
console.log("we won the battle! Roma invicta!")
} else if (myArmyStrength <= 0 && enemyArmyStrength > 0) {
console.log("We lost the battle...")
} 
/* this if else statement was supposed to console.log a message either announcing a victory or defeat to the enemy army, but it's not console.logging anything. Why is that so? */



postgres random text in jsonb column

Following is the query I'm using to scrub some fields in the JSONB column. I'm trying to radomize the first and last name so would like to use something like md5(random()::text) as values.

update people set
data = to_jsonb(data) || '{"firstName": "random_text", "lastName": "random_text"}'
where id = 'b3c09005-7afb-4ad6-922d-76078875e59e';

I tried replacing "random_text" with md5(...) but I get an error "DETAIL: Token "md5" is invalid.". I also tried using || to concat but that didn't work either.




Generating password using Python

I have written a Python program to generate password. There is a glitch because it is not properly shuffled. Please suggest some methods to do it. Also suggest better methods for the same.

import random 
import array

digits = ['0','1','2','3','4','5','6','7','8','9']
lowercase = ['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']
uppercase = ['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']
Symbols = ['!','@','#','$','%','*','&']

mixture = digits + lowercase + uppercase + Symbols

random_digit = random.choice(digits)
random_lowercase = random.choice(lowercase)
random_uppercase = random.choice(uppercase)
random_symbol = random.choice(Symbols) 

Password = random_digit + random_lowercase + random_uppercase + random_symbol

length = random.randint(8,12)

for x in range (length) :
    Password = Password + random.choice(mixture) 

print(Password)



How do I add a 'play again' option for the following game

I have tried to add a 'while True' loop but it shows the error 'str object is not callable'. Please help me on this one. I need an extension of this already written code game.

import random
user_score = 0
computer_score = 0
user_score = 0
computer_score = 0
input = input("Choose your move, Rock, Paper or Scissors: ").upper()
comp = ["ROCK", "PAPER", "SCISSORS"]
computer_move = random.choice(comp)

if input == "ROCK":
    if computer_move == "PAPER":
        print("You lost. Better luck next time!")
        computer_score += 1
    elif computer_move == "SCISSORS":
        print("You won! Well done.")
        user_score += 1
elif input == "PAPER":
    if computer_move == "ROCK":
        print("You won! Well done.")
        user_score += 1
    elif computer_move == "SCISSORS":
        print("You lost. Better luck next time!")
        computer_score += 1
elif input == "SCISSORS":
    if computer_move == "ROCK":
        print("You lost. Better luck next time!")
        computer_score += 1
    elif computer_move == "PAPER":
        print("You won! Well done.")
        user_score += 1
elif input == computer_move:
    print("It's a tie!")
print(f"Your Score: {user_score} ; Computer Score: {computer_score} ")



How do you show a random string in Flutter

I am beginner in dart with flutter and I need to display a random string on the app screen.

I know how to get a random string but I am facing problems in trying to display it on the app screen.

So how do I display this string on the user's screen? Sorry, I am only a beginner and can't find this anywhere.

Thank you.




lundi 28 décembre 2020

Is srand a reliable source of encryption pads?

I'm looking to encrypt license keys on an audio software plugin. The biggest risk to the integrity of the license keys is small-time crackers decompiling the code and looking for the encryption key. My solution is to store an arbitrary number in the code and feed it to an algorithm that will obfuscate the encryption key while still allowing me to differ the key between projects (I'm a freelancer).

My question is - will seeding the C++ random number generator create the same psuedo-random encryption key every time, or will it differ between runs, libraries, etcetera. It's fine if it differs between operating systems, I just need it to not differ between SDKs and hosting softwares on the same computer.




How can I stop a script from shuffling the words (questions) every time I start the exercise?

I am an English teacher and I created an exercise, using Hotpotatoes, to demonstrate to my student how to make sentences from different words. The words are in alphabetical order so I can easily find the word I want to use.

But there is a code in the script that shuffles them every time I start or restart the html file. I have no experience in coding. I have been trying to change the two shuffle functions to make them stop from shuffling. Deleting them did not work, the whole exercise disappeared. By the way, the file is not a test; it's just me demonstrating to the kids over the Internet how to make sentences by dragging the words and putting them together.

The file was too big for here. Here are the two codes that I believe are doing the shuffling:

function Shuffle(InArray){
    var Num;
    var Temp = new Array();
    var Len = InArray.length;

    var j = Len;

    for (var i=0; i<Len; i++){`enter code here`
        Temp[i] = InArray[i];
    }

    for (i=0; i<Len; i++){
        Num = Math.floor(j  *  Math.random() *1);
        InArray[i] = Temp[Num];

        for (var k=Num; k < (j-1); k++) {
            Temp[k] = Temp[k+1];
        }
        j--;
    }
    return InArray;
}

Segments = Shuffle(Segments);



How can I stop a script from shuffling the words (questions) every time I start the exercise?

I am an English teacher and I created an exercise, using Hotpotatoes, to demonstrate to my student how to make sentences from different words. The words are in alphabetical order so I can easily find the word I want to use. But there is a code in the script that shuffles them every time I start or restart the html file. Please help me. I have no experience in coding whatsoever. I spent few hours trying to change the two shuffle functions to make them stop from shuffling. Deleting them did not work, the whole exercise disappeared. By the way, the file is not a test just me demonstrating to the kids over the Internet how to make sentences by dragging the words and putting them together. Thank you in advance.

The file was too big for here. Here are the two codes that I believe are doing the shuffling:

function Shuffle(InArray){
    var Num;
    var Temp = new Array();
    var Len = InArray.length;

    var j = Len;

    for (var i=0; i<Len; i++){`enter code here`
        Temp[i] = InArray[i];
    }

    for (i=0; i<Len; i++){
        Num = Math.floor(j  *  Math.random() *1);
        InArray[i] = Temp[Num];

        for (var k=Num; k < (j-1); k++) {
            Temp[k] = Temp[k+1];
        }
        j--;
    }
    return InArray;
}

Segments = Shuffle(Segments);



R: Imputing NAs with random choice of female or male

I am working in R.

I have a data frame column with female or male and some NAs.

Now, I want to randomly assign female or male to the NA values in this column. I do not want to have all NAs be male or female but every NA randomly assigned either or.

How do I do that?

Best, corkinabottle




Random for-loop in Java?

I have 25 batch jobs that are executed constantly, that is, when number 25 is finished, 1 is immediately started.

These batch jobs are started using an URL that contains the value 1 to 25. Basically, I use a for loop from 1 to 25 where I, in each round, call en URL with the current value of i, http://batchjobserver/1, http://batchjobserver/2 and so on.

The problem is that some of these batch jobs are a bit unstable and sometimes crashes which causes the for-loop to restart at 1. As a consequence, batch job 1 is run every time the loop is initiated while 25 runs much less frequently.

I like my current solution because it is so simple (in pseudo code)

for (i=1; i < 26; i++) {
   getURL ("http://batchjob/" + Integer.toString(i));
}

However, I would like I to be a random number between 1 and 25 so that, in case something crashes, all the batch jobs, in the long run, are run approximately the same number of times.

Is there some nice hack/algorithm that allows me to achieve this?

Other requirements:

  • The number 25 changes frequently
  • This is not an absolut requirement but it would be nice one batch job wasn't run again until all other all other jobs have been attempted once. This doesn't mean that they have to "wait" 25 loops before they can run again, instead - if job 8 is executed in the 25th loop (the last loop of the first "set" of loops), the 26th loop (the first loop in the second set of loops) can be 8 as well.

Randomness has another advantage: it is desirable if the execution of these jobs looks a bit manual.




Reinforcement Learning: SGD use and independence of samples in sequences

I am taking a course in RL and many times, learning policy parameters of value function weights essentially boils down to using Stochastic Gradient Descent (SGD). The agent is represented as having a sequence of states S_t, actions A_t, and reaping rewards R_t at time t of the sequence.

My understanding of SGD in general, e.g when applied using training datasets on neural nets, is that we assume the data in the mini-batches to be iid, and this makes sense because in a way we are "approximating" an expectation using an average of gradients over points that are supposedly drawn from independent but exactly similar distributions. So why is it that we use SGD in RL while incrementing through time? Is that due to the implicit assumption of conditional independence for the distribution of p(S_t | S_{t-1})?

Thanks for clarifying this point. Amine




Random generate a year within a range

Ive got this java class where I want to randomly generate a year between 2020 and 2022 using random class .I know the code below wont do the trick so can you please help me

Random random = new Random();

int year=random.nextInt(2022-2020 +1);




Get random rows from postgres more than number of rows

I'm using SQLALchemy and Postgresql.

Imagine I have a SQLAlchemy class Items,

There are 100 items in this table, I want to get for example 200 random rows(expected rows are not unique indeed).

for getting less than 100 easily I do:

items = session.query(Items)\
    .order_by(func.random())\
    .limit(80)\
    .all()

But how can I get more than 100 rows if only I have 100?




Random seed in Lua

-Read seed number and set seed -In a loop, generate a random integer between 1 and 6(inclusive of the limit), and increment a counter the number of iterations. -If the number generated is 6, exit the loop -Print the number of iterations

Sample input 0

Sample output 3 5 5 6 4




how to display Quiz randomly and without duplication in react native

everyone. I try to make Quiz app randomly and without duplication in React Native . Successfully Quiz are displayed randomly. But I don't know how to display them without duplication . I am very new to learn React Native. If you have any idea to solve this issue , please help me . I use Mac book pro , Visual Code Studio and React Native.

I write the code as below .

export function App() {

 const questions = [

  {
   questionText: "city",
  answerOptions: [
  { answerText: "canada", isCorrect: false },
  { answerText: "USA", isCorrect: false },
  { answerText: "Napoli", isCorrect: true },
  { answerText: "Brazil", isCorrect: false },
  ],

  },


 {
 questionText: "country",
 answerOptions: [
 { answerText: "Paris", isCorrect: false },
 { answerText: "London", isCorrect: false },
 { answerText: "Spain", isCorrect: true },
 { answerText: "Rome", isCorrect: false },
 ],
 },


 {
 questionText: "color",
 answerOptions: [
 { answerText: "dog", isCorrect: false },
 { answerText: "cat", isCorrect: false },
 { answerText: "blue", isCorrect: true },
 { answerText: "tiger", isCorrect: false },
 ],
 },


 {
 questionText: "currency",
 answerOptions: [
 { answerText: "cash", isCorrect: false },
 { answerText: "money", isCorrect: false },
 { answerText: "Pond", isCorrect: true },
 { answerText: "card", isCorrect: false },
 ],
 },
 ];



 const randomQuestions =
 questions[Math.floor(Math.random() * questions.length)];

 return (
 <View style={styles.container}>

<Text style={styles.question}>
{randomQuestions.questionText}
</Text>



<Text style={styles.answer}>
{randomQuestions.answerOptions[0].answerText}
</Text>

<Text style={styles.answer}>
{randomQuestions.answerOptions[1].answerText}
</Text>

<Text style={styles.answer}>
{randomQuestions.answerOptions[2].answerText}
</Text>

<Text style={styles.answer}>
{randomQuestions.answerOptions[3].answerText}
</Text>

</View>
);

};



Pythin tkinter: replace a random image from a list with another one by clicking button

my purpose is to display a random image meal among a list by cliking a button. I already succeed first steps, but what I want is to replace the previous image generated by another one when I click the button again. Currently, all images generated are overlaped (see enter image description here). I have tried many things like canvas.delete("all"), .destroy() and other stuff like that, but nothing works in my case ...

Could you help me ? Here is my code:

import os, random
from tkinter import *


# WINDOW CREATION
window = Tk()
# WINDOW's setup
window.title("Choosing meal")
window.geometry("500x500")
window.config(background = 'blue')

# FIRST BOX QUESTION: 
frame = Frame(window,bg = 'blue')

question_tilte = Label(frame, text = 'Which meal are you going to eat today ?', font = ("Arial",20), bg = 'blue', fg = "white")
question_tilte.pack()
# ADD THE BOX IN THE WINDOW 
frame.pack(expand = YES)

# SECOND BOX CREATION TO PUT THE IMAGE IN:
frame2 = Frame(window, bg = 'blue')

# RANDOM MEAL CHOOSE METHOD:
def choosing_meal():
    if os.path.exists("meals.txt"):
      with open("meals.txt","r") as file:
            meals_list = file.readlines()
            meal_random_choice = random.choice(meals_list)
            print(meal_random_choice)
            file.close()
            # LISTS 
            canvas = [canvas1,canvas2,canvas3,canvas4]
            for i in range(0,len(meals_list)):
                if meal_random_choice == meals_list[i]:
                  canvas[i].grid(row=2,column=1)
    


# MEAL BUTTON GENERATOR :
meal_generator_button = Button(frame, text = "Choose a random meal !", font = ("Helvetica",15), bg = 'white', fg = 'blue', command = choosing_meal)
meal_generator_button.pack(pady = 25, fill = X) # gère les dimensions du bouton

# Image pizza
width = 332
height = 234
image1 = PhotoImage(file = "pizza_fresca.png")
canvas1 = Canvas(frame2,width = width, height = height, bg = "blue", bd = 0,highlightthickness=0)
canvas1.create_image(width/2,height/2, image = image1)

# Image sushis
width2 = 292
height2 = 164
image2 = PhotoImage(file = "sushi.png")
canvas2 = Canvas(frame2,width = width2, height = height2, bg = "blue", bd = 0,highlightthickness=0)
canvas2.create_image(width2/2,height2/2, image = image2) 

# Image crêpes
width3 = 273
height3 = 185
image3 = PhotoImage(file = "crepes.png")
canvas3 = Canvas(frame2,width = width3, height = height3, bg = "blue", bd = 0,highlightthickness=0)
canvas3.create_image(width3/2,height3/2, image = image3)
              
# Image tacos
width4 = 279
height4 = 125
image4 = PhotoImage(file = "tacos.png")
canvas4 = Canvas(frame2,width = width4, height = height4, bg = "blue", bd = 0,highlightthickness=0)
canvas4.create_image(width4/2, height4/2, image = image4)
 
frame2.pack(expand=YES)

# DISPLAY INTERFACE:
window.mainloop()



dimanche 27 décembre 2020

Why is it showing this error: raise ValueError("Sample larger than population or is negative") ValueError: Sample larger than population

I'm trying to make two lists with random numbers with random length (they don't have to be the same). Can you tell me why I'm getting this error:

raise ValueError("Sample larger than population or is negative") ValueError: Sample larger than population or is negative

import random
size = random.randint(6,20)
a = list(random.sample(range(1,9),size))
size = random.randint(6,10)
b = list(random.sample(range(1,7),size))
#a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
#b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
c = []
for number in a:
    for num in b:
        if(number==num):
            if not number in c:
                c.append(number)
print(a)
print(b)
print(c)



Opening a random file in a directory VBScript

I have a folder with a bunch of memes in it, %AppData%\Memes And I have a file, meme.vbs in my startup folder.

How would I make meme.vbs open a random meme every set amount of minutes?




Unbiased skewness and kurtosis of continuous random variables in scipy.stats

As the answer here points out, scipy.stats gives biased estimates of skewnesss and kurtosis, which can only be corrected individually with the bias argument:

  • stats.skew(x, bias=False)
  • stats.kurtosis(x, bias=False)

Instead of the data variable x, how do I also enforce unbiasedness in the continuous random variable generators' attribute stats like norm.stats for the normal distribution, listed at the bottom of the documentation:

  • mean, var, skew, kurt = scipy.stats.norm.stats(loc=0, scale=1, moments=’mvsk’)

where arguments can be Mean(‘m’), variance(‘v’), skew(‘s’), and/or kurtosis(‘k’)




How to make mp4 random output and open in media player.? Use folders. In java

I need to create a program that offers to select a movie genre and then randomly opens one movie in the media player from the corresponding folder.




PHP else/if statement, with rand() [duplicate]

I try to solve this exercise, but Im not sure how to look for the solution. For my current knowledge my program should print out smg, but I get only error .

Error message :

     
Warning: Undefined variable $x in /in/NVFqg on line 6
Charile bit your finger!

Here is my code :

<?php 
function isBitten()
{

if ($x <= 50) { // line 6 //
   echo "Charile bit your finger!"; 
   $x = rand(0, 100);
}

else {
  echo "Charlie did not bite your finger";
}



  }

 ?>



<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Charlie</title>
  </head>
  <body>


     <?php
     isBitten();
      ?>

  </body>
</html>

Your help is much appreciated! Thank you!




samedi 26 décembre 2020

MySQL select within if statement in procedure

I have to create a procedure that inserts a row with a foreign key. This key it's a random id from another table that satisfies a condition, if there's no row that satifies it, then it will be a random id from all the ids in the table.

For example I want to create a Person and I want to assing him a car. I want his car to be a random choice from an specific color, but if there's no car from that color, then just choose a random car.

Here is my adapted current code:

DELIMITER //
DROP PROCEDURE IF EXISTS `test`;
CREATE PROCEDURE `test`( `id_color` INT )
BEGIN
    # I have auto increment id    
    INSERT INTO persons(id_color)
    VALUES ((
        SELECT IF((SELECT COUNT(*) FROM cars WHERE color = id_color) > 0, 
        SELECT car_id FROM cars WHERE color = id_color ORDER BY RAND() LIMIT 1,
        SELECT car_id FROM cars ORDER BY RAND() LIMIT 1)
    ));
    
END //
DELIMITER ; 

I am getting this error: '2014 Commands out of sync; you can't run this command now'

Don't know if it's possible to do it like that.

I use delimiter because I have to add more stuff.




How build lotto program in Python where numbers have the same chance ( **probability** ) to appear or not? [duplicate]

i want to build a program in Python designed for generating hazard numbers in lotto. For example from 1 to 45 , i want that every number between 1 and 45 ( 1 and 45 included) have the same chance to appear or not, like in real life. What is ( or what are) the appropriate random that can do that or closer to do that (approximation). EXEMPLE value= random.randint(1,46)
Does all the numbers between 1 and 45 have the same chance to appear or to not appear like in reel world ? Does chance in computer world is like chance in reel world, if no , how to make it closer? It is not about duplication. Thank you for helping




vendredi 25 décembre 2020

How do I make a numbered list?

I want to make a playlist generator, I have a list containing different songs and I want to generate a random numbered list from it containing only 10 items, and this is the code I tried:

import random

a = ['Bruised and Scarred - Mayday Parade',
     'Miracles in December - EXO',
     'All Too Well - Taylor Swift',
     'Gravity - Sara Bareilles',
     'Perfectly Perfect - Simple Plan',
     'Welcome To The Black Parade - My Chemical Romance',
     'Everything Has Changed - Taylor Swift',
     'Champagne - Taylor Swift',
     'Piece of Your Heart - Mayday Parade',
     'Blame It On The Rain - He Is We',
     'Sad Song - We The Kings',
     'Give It All - He Is We',
     ]

for x in range(1, 11):
    for y in random.sample(a, k=10):
        print(str(x) + y)

but I got this output:

1Bruised and Scarred - Mayday Parade
1All Too Well - Taylor Swift
1Blame It On The Rain - He Is We
1Everything Has Changed - Taylor Swift
1Give It All - He Is We
1Miracles in December - EXO
1Perfectly Perfect - Simple Plan
1Gravity - Sara Bareilles
1Sad Song - We The Kings
1Piece of Your Heart - Mayday Parade
2All Too Well - Taylor Swift
2Bruised and Scarred - Mayday Parade
2Blame It On The Rain - He Is We
2Perfectly Perfect - Simple Plan
2Champagne - Taylor Swift
2Everything Has Changed - Taylor Swift
2Piece of Your Heart - Mayday Parade
2Miracles in December - EXO
2Welcome To The Black Parade - My Chemical Romance
2Give It All - He Is We
3Bruised and Scarred - Mayday Parade
3Gravity - Sara Bareilles
3Welcome To The Black Parade - My Chemical Romance
3All Too Well - Taylor Swift
3Perfectly Perfect - Simple Plan
3Sad Song - We The Kings
3Champagne - Taylor Swift
3Everything Has Changed - Taylor Swift
3Piece of Your Heart - Mayday Parade
3Give It All - He Is We
4Everything Has Changed - Taylor Swift
4Blame It On The Rain - He Is We
4Piece of Your Heart - Mayday Parade
4Gravity - Sara Bareilles
4Bruised and Scarred - Mayday Parade
4Welcome To The Black Parade - My Chemical Romance
4Miracles in December - EXO
4Sad Song - We The Kings
4Give It All - He Is We
4Perfectly Perfect - Simple Plan
5Gravity - Sara Bareilles
5Blame It On The Rain - He Is We
5Perfectly Perfect - Simple Plan
5Champagne - Taylor Swift
5Everything Has Changed - Taylor Swift
5Bruised and Scarred - Mayday Parade
5Welcome To The Black Parade - My Chemical Romance
5All Too Well - Taylor Swift
5Give It All - He Is We
5Miracles in December - EXO
6Bruised and Scarred - Mayday Parade
6Champagne - Taylor Swift
6Everything Has Changed - Taylor Swift
6Miracles in December - EXO
6Welcome To The Black Parade - My Chemical Romance
6Sad Song - We The Kings
6All Too Well - Taylor Swift
6Gravity - Sara Bareilles
6Give It All - He Is We
6Perfectly Perfect - Simple Plan
7Gravity - Sara Bareilles
7Sad Song - We The Kings
7Everything Has Changed - Taylor Swift
7Welcome To The Black Parade - My Chemical Romance
7Piece of Your Heart - Mayday Parade
7Blame It On The Rain - He Is We
7Bruised and Scarred - Mayday Parade
7Give It All - He Is We
7Champagne - Taylor Swift
7All Too Well - Taylor Swift
8Sad Song - We The Kings
8Gravity - Sara Bareilles
8Champagne - Taylor Swift
8Blame It On The Rain - He Is We
8Miracles in December - EXO
8Give It All - He Is We
8Welcome To The Black Parade - My Chemical Romance
8Bruised and Scarred - Mayday Parade
8Piece of Your Heart - Mayday Parade
8Everything Has Changed - Taylor Swift
9Gravity - Sara Bareilles
9Champagne - Taylor Swift
9Bruised and Scarred - Mayday Parade
9Blame It On The Rain - He Is We
9Piece of Your Heart - Mayday Parade
9Everything Has Changed - Taylor Swift
9Sad Song - We The Kings
9Welcome To The Black Parade - My Chemical Romance
9All Too Well - Taylor Swift
9Perfectly Perfect - Simple Plan
10Champagne - Taylor Swift
10Blame It On The Rain - He Is We
10Perfectly Perfect - Simple Plan
10Miracles in December - EXO
10Give It All - He Is We
10Piece of Your Heart - Mayday Parade
10Everything Has Changed - Taylor Swift
10Welcome To The Black Parade - My Chemical Romance
10Bruised and Scarred - Mayday Parade
10Sad Song - We The Kings

I want it to contain only 10 items, but I got way too many, could please help me (Sorry for my bad english)




How to generate two distinct sets of correlated ordinal variables?

I want to generate two distinct sets of correlated ordinal variables (ranging from 1 to 7). The first set will be represented by x1, x2 and x3 whereas the second set will be represented by x4, x5 and x6. I want the first set of variables (x1, x2 and x3) to be moderately correlated (e.g., 0.4) whereas the second set of variables (x4, x5 and x6) to be strongly correlated (e.g., 0.7). At the same time, I want the correlation between these two sets of variables to be weak (e.g., 0.10) with each other.




Generating y random numbers and inserting them into a HashMap

I need to create a function that returns a random number from 1 to x and I have to generate y of them. Results must be in HashMap. At this moment the user can pass x and y values, code generates y random numbers from 1 to x but I totally don't know how to insert results in HashMap that is created.

EDIT: About HashMap, key = number from 1 to x, value = amount of generated numbers

private static BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
public static void main (String[] args) throws IOException {

    System.out.println("Insert x value: ");
    int x = Integer.parseInt(bufferedReader.readLine());

    System.out.println("Insert y value: ");
    int y = Integer.parseInt(bufferedReader.readLine());

    
    HashMap<Integer, Integer> map = new HashMap <Integer, Integer>();
    
Random random = new Random();
    for (int i = 1; i <= y; i++) {
        int value = 1 + random.nextInt(x);
        System.out.println(value);
    }


}



Make an random of ID [closed]

How do I give color red to random element with id "hello"?

<h1 id="hello">a</h1> <h1 id="hello">b</h1> <h1 id="hello">c</h1>



How do I change a specific vertex in a matrix list in python [duplicate]

import random

rows, cols = (24, 24) 
node = [[0]*cols]*rows 

def main():
    for i in range(23):
        while True:
            randx = random.randint(0,23)
            randy = random.randint(0,23)
            if node[randx][randy] == 0:
                node[randx][randy] = 1
                break
    print(node)
main()

For some reason it returns a matrix with all of the rows looking the same. for example it might produce:

[1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0], 
[1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0], 
[1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0], 
[1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0], 
[1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0], ...

the whole matrix would look like that. (I have just taken the first 5 rows to demonstrate) I am trying to make it change individual vertices in the matrix, not entire rows.




How do I change a specific vertex in a matrix list in python [duplicate]

import random

rows, cols = (24, 24) 
node = [[0]*cols]*rows 

def main():
    for i in range(23):
        while True:
            randx = random.randint(0,23)
            randy = random.randint(0,23)
            if node[randx][randy] == 0:
                node[randx][randy] = 1
                break
    print(node)
main()

For some reason it returns a matrix with all of the rows looking the same. for example it might produce:

[1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0], 
[1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0], 
[1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0], 
[1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0], 
[1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0], ...

the whole matrix would look like that. (I have just taken the first 5 rows to demonstrate) I am trying to make it change individual vertices in the matrix, not entire rows.




PostgreSQL. Select a column that correlates with value in the aggregate function

Here is the 'items' table, containing more than 10 rows:

+-----+-----------+-----------+----------+
| id  | item_name | category  | quantity |
+=====+===========+===========+==========+
| 3   | item33    | category1 | 5        |
+-----+-----------+-----------+----------+
| 2   | item52    | category5 | 1        |
+-----+-----------+-----------+----------+
| 1   | item46    | category1 | 3        |
+-----+-----------+-----------+----------+
| 4   | item11    | category3 | 2        |
+-----+-----------+-----------+----------+
| ... | ...       | ...       | ...      |
+-----+-----------+-----------+----------+

Values in the 'items' column are unique, the ones in the 'category' columnt - aren't unique.

The task is:

  1. Remove duplicates of categories: if a category contains more than 1 item, take the row with minimal 'id'.
  2. Order results by the 'quantity' (ASC).
  3. Take 10 rows: top 5 and random 5 from the rest result data output.

So, the ordering table (after #2 sub-task) should look like that:

+-----+-----------+-----------+----------+
| id  | item_name | category  | quantity |
+=====+===========+===========+==========+
| 2   | item52    | category5 | 1        |
+-----+-----------+-----------+----------+
| 4   | item11    | category3 | 2        |
+-----+-----------+-----------+----------+
| 1   | item46    | category1 | 3        |
+-----+-----------+-----------+----------+
| ... | ...       | ...       | ...      |
+-----+-----------+-----------+----------+

I know how to exclude duplicates for categories:

SELECT min(id) as id, category
FROM items
GROUP BY category

But I don't know how to order it by the quantity. If I try to add 'quantity' to the 'select' line and then make 'ORDER BY quantity', I get the error: "column "quantity" must appear in the GROUP BY clause or be used in an aggregate function".

If there is a way to add this 'quantity' column to the data output (the value in this column should correlate with the resulting 'id' value (i.e. "min(id)"))? And then do ordering and picking rows...




jeudi 24 décembre 2020

Why a wrong number of 1 is printed?

My function should randomly insert a user-chosen number of 1 into my matrix. The difficulty lies in the fact that if a cell contains a 1 the cells around it must be set to 0. Why my code print a wrong number of 1? In the code below I had thought to first set the entire matrix to 0, then randomly generate a cell to be set to 1. Then, check if the cells around it are 0, otherwise set them to 0. All this is done until the number m entered by the user becomes 0 (every time a cell is set to 1, m is decremented and every time a cell equal to 1 is reset to 0 m it is incremented). Furthermore, in order not to generate errors, the check is done considering the fact that the outermost cells cannot check on nonexistent cells.This is my (bad) code. Can anyone tell me why the print is wrong?

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


int main (void) {
    int n, m;
    
    printf("Enter square matrix size: ");
    scanf("%d",&n);
    int matrix[n][n];
    
    printf("Enter number of 1 cells: ");
    scanf("%d",&m);
    
    int a[n][n];
    
    for (int i = 0; i < n; i++){
        for (int j = 0; j < n; j++){
            a[i][j] = 0;
        }
    }
      
            while (m >= 0){
                int k = rand() % n;
                int l = rand() % n;
                a[k][l] = 1;
                if (k > 0) {
                    if (a[k-1][l] == 1){
                        a[k-1][l] = 0;
                        m++;
                    }
                    if (l > 0 && a[k-1][l-1] == 1){
                        a[k-1][l-1] = 0;
                        m++;
                    }
                    if (l < 4 && a[k-1][l+1] == 1){
                        a[k-1][l+1] = 0;
                        m++;
                    }
                }
                
                if (k < 4){
                    if (a[k+1][l] == 1){
                        a[k+1][l] = 0;
                        m++;
                        if(l<4 && a[k+1][l+1] == 1){
                            a[k+1][l+1] = 0;
                            m++;
                        }
                    }
                } 
                
                if (l > 0 && a[k][l-1] == 1){
                    a[k][l-1] = 0;
                    m++;
                }
                
                if (l<4 && a[k][l+1] == 1){
                    a[k][l+1] = 0;
                    m++;
                }
                
                m--;
                }
                        
    for (int i = 0; i < n; i++){
        for (int j = 0; j < n; j++){
            printf("\t%d", a[i][j]);
        }
        puts("");
    }
    
    
    return 0;
}



From a dictionary made of multiple lists choose one element from each

Lets say I have a dictionary of lists like this:

lists= {'pet': ["dog", "cat", "parrot"],
        'amount': [1,2,3],
        'food': ["canned", "dry"]}

And I want to pick one element from each list, randomly, so the result is like this:

{'amount': 2, 'food': 'canned', 'pet': 'cat'}

Which would the simplest way to achieve it using Python?




How to fill a matrix following this rule

I have to create a matrix with random numbers 0 or 1. The problem is that the number of 1 must be entered by the user and the 1 cells must follow a rule: if a cell is 1, the eight cells around it must necessarily be 0.

Here an example of correct output:

User entered: 8

1 0 0 1 0 0
0 0 0 0 0 1
0 1 0 0 0 0
0 0 0 0 0 1
1 0 1 0 0 0

Here an example of not correct output:

User entered: 8

1 1 0 1 0 0
0 0 0 0 0 1
0 1 0 1 0 0
0 0 0 0 0 1
1 0 1 0 0 0

This is not correct because at line 1 there are two 1 close.

My biggest problem is that I can't figure out how to insert 1s randomly since the number of 1s is entered by the user. Any advice?




How to allow a specific part of my program to write to a txt

Alright, So I've seen multiple ways to allow python programs to write to a specified txt, but none of the ones I've seen would be compatible with my program.

It's a number/password generator that can print anywhere from one line, to actual billions of lines of strings. But, the issue is that there is some dialog and options before it prints out the selected strings.

How do I make it so it only records and writes a certain part to a txt, Instead of the whole thing.

Here's a link to the github, And attached is the program. https://github.com/JasonDerulo1259/JasonsGenerator

Or alternatively, here is the raw code:

import time
import random
from random import randint
from random import choices
import sys
chars= ["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","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","$","%","&","(",")","*",",","-",".","/",":",";","<","=",">","?","@","[","]","^","_","`","{","|","}","~","0","1","2","3","4","5","6","7","8","9"]
def massprint():
  againagain = int(times)
  even=0
  odd=1
  consec=0
  rand=0
  
  while againagain >= 0:
    time.sleep(float(speed))
    againagain -= 1
    if eocr=="e":
      print(even,flush=True, end=inbetween)
      even=even+2
    elif eocr=="o":
      print(odd,flush=True, end=inbetween)
      odd=odd+2
    elif eocr=="c":
      print(consec,flush=True, end=inbetween)
      consec=consec+1
    elif eocr=="r":
      print(random.randint(int(randlowcap),int(randhighcap)),flush=True, end=inbetween)
    elif eocr=="p":
      password=random.sample(chars,letters)
      divider = ""
      password = divider.join(password) 
      print(password,flush=True, end=inbetween)
    elif eocr=="pr":
      password=choices(chars, k=letters)
      divider = ""
      password = divider.join(password) 
      print(password,flush=True, end=inbetween)
    else:
      print("Unrecognized. Type either e, o or c or r")

  if againagain<=1:
    print(" \n")
print("even, odd, consecutive, random, password or password-repeat ")
eocr=input("e/o/c/r/p/pr ")
time.sleep(0.5)
times=input("How many times/strings? ")
againagain=int(times)
time.sleep(0.5)
speed=input("What speed should it print, \nAnswer in seconds. (0.02 Is Normal-ish speed) ")
time.sleep(0.5)
inbetween=input("What should be inbetween each string (eg: space, comma, newline (/n).). \nAnswer with the string inbetween, Not the name of it \n(write ' ' , not 'space') ")
if inbetween=="/n":
  inbetween="\n"
else:
  print("")
if eocr=="e":
  print("Alright, The final number will be",str(againagain * 2))
  varcontinue=input("Is this okay? (y/n) ")
  if varcontinue=="y":
    print(" ")
    massprint()
    time.sleep(1)
    print("Done!")
  else:
    print("\n")
elif eocr=="o":
  print("Alright, The final number will be",str(againagain * 2+1))
  varcontinue=input("Is this okay? (y/n) ")
  if varcontinue=="y":
    print(" ")
    massprint()
    time.sleep(1)
    print("Done!")
  else:
    print("\n")
elif eocr=="c":
  print("Alright, The final number will be",str(againagain))
  varcontinue=input("Is this okay? (y/n) ")
  if varcontinue=="y":
    print(" ")
    massprint()
    time.sleep(1)
    print("Done!")
elif eocr=="r":
  time.sleep(0.5)
  randhighcap=input("And what do you want the highest random number to be? ")
  time.sleep(0.5)
  randlowcap=input("And what do you want the lowest random number to be? ")
  time.sleep(0.5)
  print("Alright, It will print",str(againagain),"random numbers \nWith a high cap of",randhighcap,"\nAnd a low cap of",randlowcap)
  varcontinue=input("Is this okay? (y/n) ")
  if varcontinue=="y":
    print(" ")
    massprint()
    time.sleep(1)
    print("Done!")
  else:
    print("\n")
elif eocr=="p":
  letters=int(input("Alright, How many characters should the password have? (no higher than 88) "))
  time.sleep(0.5)
  print("Okay, It will print",times,"passwords,\nEach with",letters," NON-REPEATING characters each")
  varcontinue=input("Is this okay? (y/n) ")
  if varcontinue=="y":
    print(" ")
    times=int(times)-1
    times=str(times)
    massprint()
    time.sleep(1)
    print("Done!")
elif eocr=="pr":
  letters=int(input("Alright, How many characters should the password have? "))
  time.sleep(0.5)
  print("Okay, It will print",times,"passwords,\nEach with",letters," REPEATING characters each")
  varcontinue=input("Is this okay? (y/n) ")
  if varcontinue=="y":
    print(" ")
    times=int(times)-1
    times=str(times)
    massprint()
    time.sleep(1)
    print("Done!")
else:
  print("Restart and input 'e' or 'o' or 'c' or 'r' or 'p'")
print("Press the Enter key to exit")
exit1=input(" ")
exit()



C# Why get a zero number in random number

I'm trying to create an array list using random numbers. But sometimes I get a zero in results. I do not understand why.

I'm grateful if anyone can explain.

int[] number = new int[6];
Random rnd = new Random();
for (int i = 0; i < number.Length; i++)
{
   int random = rnd.Next(1, 26);
   if (!number.Contains(random))
   {
     number[i] = random;
   }
}
foreach (int nr in number)
{
  Console.Write("|" + nr + "|");
}
//results
|6||12||0||22||25||11|



Select random line in txt file with Python

I want to use Python to output a random line from an external .txt file. In this .txt file there are several sentences. But each of them is in a different line.

My approach is to generate a random line number:

import random

line = random.randint(1, max_line)

#max_line stands for the number of lines in the .txt file.

and then to reproduce this line using print().

I've already looked around a bit, but haven't found anything yet regarding outputting the sentence of the line. Any idea how I could make this work?




mercredi 23 décembre 2020

Why is this is randrange not working/ is working and have written my code wrong?

I have made a snake game but the food sometimes generates inside the snake tail the solution I came up with was this.

def Food(snake_List, food_placed, foodX, foodY):
    while food_placed == False:
        foodX = round(random.randrange(0,display_width))
        foodY = round(random.randrange(0,display_height))
        food_pos = [foodX, foodY]
        food_placed = True
        return foodX
        return foodY
        if food_pos in snake_List:
            food_placed = False

but this doesnt work. Here is the full code

import pygame
import time
import random

pygame.init()

display_width = 600
display_height = 600
display = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Snake")

pureblue = (0,0,255)
purered = (255,0,0)
puregreen = (0,255,0)
red = (125,25,25)
green = (25,125,25)
white = (255,255,255)
black = (1,1,1)
grey = (20,20,20)
darkgrey = (15,15,15)


clock = pygame.time.Clock()

snake_block = 60
snake_speed = 5

font_style = pygame.font.SysFont(None, 50)

food_placed = False
foodX = 0
foodY = 0

def user_snake(snake_block, snake_List):
    for x in snake_List:
        pygame.draw.rect(display,green,[x[0],x[1], snake_block, snake_block])

def drawGrid(surf):
    blockSize = snake_block
    surf.fill(grey)
    for x in range(display_width):
        for y in range(display_height):
            rect = pygame.Rect(x*blockSize, y*blockSize,blockSize, blockSize)
            pygame.draw.rect(surf,darkgrey, rect, 1)

grid_surf = pygame.Surface(display.get_size())
drawGrid(grid_surf)

def Food(snake_List, food_placed, foodX, foodY):
    while food_placed == False:
        foodX = round(random.randrange(0,display_width))
        foodY = round(random.randrange(0,display_height))
        food_pos = [foodX, foodY]
        food_placed = True
        return foodX
        return foodY
        if food_pos in snake_List:
            food_placed = False

def message(msg, colour):
    text = font_style.render(msg, True, colour)
    display.blit(text, [0, display_height/4])

def SnakeGameLoop(foodX, foodY):
    game_over = False
    game_close = False
    X = display_width/2
    Y = display_height/2

    X_change = 0
    Y_change = 0
    
    snake_List = []
    Length_of_snake = 1
    Food(snake_List, food_placed, foodX, foodY)

    while not game_over:
        while game_close == True:
            message("You Lost! Press Q-Quit or C-Play Again", purered)
            pygame.display.update()
 
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        game_over = True
                        game_close = False
                    if event.key == pygame.K_c:
                        SnakeGameLoop(foodX, foodY)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    X_change = -snake_block
                    Y_change = 0
                elif event.key == pygame.K_RIGHT:
                    X_change = snake_block
                    Y_change = 0
                elif event.key == pygame.K_UP:
                    X_change = 0
                    Y_change = -snake_block
                elif event.key == pygame.K_DOWN:
                    X_change = 0
                    Y_change = snake_block

                if event.key == pygame.K_a:
                    X_change = -snake_block
                    Y_change = 0
                elif event.key == pygame.K_d:
                    X_change = snake_block
                    Y_change = 0
                elif event.key == pygame.K_w:
                    X_change = 0
                    Y_change = -snake_block
                elif event.key == pygame.K_s:
                    X_change = 0
                    Y_change = snake_block

        if X >= display_width or X < 0 or Y >= display_height or Y < 0:
            game_close = True

        X += X_change
        Y += Y_change
        snake_Head = []
        snake_Head.append(X)
        snake_Head.append(Y)
        snake_List.append(snake_Head)
        print(snake_List)
        if len(snake_List) > Length_of_snake:
            del snake_List[0]

        for x in snake_List[:-1]:
            if x == snake_Head:
                game_close = True
        display.blit(grid_surf, (0,0))
        pygame.draw.rect(display, red, [foodX, foodY, snake_block, snake_block])
        user_snake(snake_block,snake_List)
        pygame.display.update()

        if X == foodX and Y == foodY:
            foodX = round(random.randrange(0, display_width - snake_block) / snake_block) * snake_block
            foodY = round(random.randrange(0, display_height - snake_block) / snake_block) * snake_block
            Length_of_snake += 1

        clock.tick(snake_speed)


    pygame.quit()
    quit()
SnakeGameLoop(foodX, foodY)



Is there a way to use the secrets python module with a seed?

Random.seed() Is less secure than secrets, but I can't find any documentation on using a seed with secrets? or is random.seed just as fine?




How to select random characters in a non-unique way

Alright, I have a password generator, The code I have is this:

password=random.sample(chars,letters) #chars is a list of Characters (symbols,letters,numbers) and letters is how many letters are in the password
divider = ""
password = divider.join(password) 
print(password,flush=True, end=inbetween) #inbetween is where the user can choose what character seperates the passwords (it can print multiple passwords)

The issue I have is that random.sample only selects unique characters. Is there an alternative function that does the same as random.sample, but can select non-unique characters from the list.

By the way, Here is the values for the variable chars:

chars= ["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","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","$","%","&","(",")","*",",","-",".","/",":",";","<","=",">","?","@","[","]","^","_","`","{","|","}","~","0","1","2","3","4","5","6","7","8","9"]



What's the best way to pull random numbers from source array of numbers untill there is no unique values left in the source array?

I need to create a makeRandom function that accepts a range of numbers as an array, where the first number is the beginning of the range, the second is the end including this number in the range. The result of this function should be a function, and the call returns a random number from the range. The numbers returned must be unique. If I run out of unique numbers, have to return null.

It should work like this :

const getRandom = makeRandom([1, 5]);
getRandom() === 3
getRandom() === 4
getRandom() === 5
getRandom() === 2
getRandom() === 1
getRandom() === null
getRandom() === null

So I tried :

function makeRandom(numbers) {
  return () => {
    let randNumber = Math.floor(Math.random() * numbers.length);

    for (let i = 0; i < numbers.length; i++) {
      randNumber += numbers[i];

      if (randNumber === numbers[i]) {
        return true;
      }

      if (randNumber === numers[i].length) {
        return true;
      }
    }

    if (!numbers) {
      return null;
    }
  };
}

But it's not working. So what's the best way to do this?




Why is there a problem with the Gaussianity in my data, and how do I fix it?

I have two Gaussian noise generators, from MATLAB's randn() function:

noise1 = randn(1,100000)
noise2 = randn(1,100000)

I'm finding the points where they are equal. For this, I add 100 points in between each point:

mehvec = linspace(1,n,100*(n-1));
meh1 = [];
meh2 = [];
for i = 2:1:n
    meh1 = [meh1, linspace(noise1(i-1),noise1(i),100)];
    meh2 = [meh2, linspace(noise2(i-1),noise2(i),100)];
end

Now, I scan each point, to see if there's a sign change in the difference between the two noises, where the sign change occurs, and what the noise value is when they're equal:

diff = meh1 - meh2;
crossvec = [];
valuevec = [];
for i = 2:1:length(mehvec)
    if diff(i-1)>=0 && diff(i)<0 || diff(i-1)<0 && diff(i)>=0
        crossvec = [crossvec,i];
        valuevec = [valuevec,noise1(i)];
    end
end

There is a problem in the Gaussianity, in the vector where the instantaneous noises are equal. Where is it coming from?

Here's the normal-probability plot of the values where they're equal. It should be a straight line (which indicates Gaussianity), but it isn't.

Here's the normal-probability plot of the values where they're equal. It should be a straight line (which indicates Gaussianity), but it isn't.




How to stop random ranges spawning in certain areas that vary?

I am making snake using pygame for a school challenge and it is functional and working but the problem I have is that sometimes when the snake eats the food the new food spawns inside the snake's tail. The reason I'm not sure of how to change this is because the way it generates the random placement of the food is using randomrange on a grid, and I do not know of anyway to exclude the snakes tail from this range/ regenerate it if it does spawn within there. Is this a fundemental problem with using random.randrange or is there a simple fix while retaining most of the code. Highlighted code top two lines below

foodX = round(random.randrange(0,display_width-snake_block)/snake_block)*snake_block
foodY = round(random.randrange(0,display_height-snake_block)/snake_block)*snake_block

import pygame
import time
import random

pygame.init()

display_width = 600
display_height = 600
display = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Snake")

pureblue = (0,0,255)
purered = (255,0,0)
puregreen = (0,255,0)
red = (125,25,25)
green = (25,125,25)
white = (255,255,255)
black = (1,1,1)
grey = (20,20,20)
darkgrey = (15,15,15)


clock = pygame.time.Clock()

snake_block = 30
snake_speed = 10

font_style = pygame.font.SysFont(None, 50)

def user_snake(snake_block, snake_List):
    for x in snake_List:
        pygame.draw.rect(display,green,[x[0],x[1], snake_block, snake_block])

def drawGrid(surf):
    blockSize = snake_block
    surf.fill(grey)
    for x in range(display_width):
        for y in range(display_height):
            rect = pygame.Rect(x*blockSize, y*blockSize,blockSize, blockSize)
            pygame.draw.rect(surf,darkgrey, rect, 1)
grid_surf = pygame.Surface(display.get_size())
drawGrid(grid_surf)

def message(msg, colour):
    text = font_style.render(msg, True, colour)
    display.blit(text, [0, display_height/4])

def SnakeGameLoop():
    game_over = False
    game_close = False
    X = display_width/2
    Y = display_height/2

    X_change = 0
    Y_change = 0
    
    snake_List = []
    Length_of_snake = 1

    foodX = round(random.randrange(0,display_width-snake_block)/snake_block)*snake_block
    foodY = round(random.randrange(0,display_height-snake_block)/snake_block)*snake_block

    while not game_over:
        while game_close == True:
            message("You Lost! Press Q-Quit or C-Play Again", purered)
            pygame.display.update()
 
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        game_over = True
                        game_close = False
                    if event.key == pygame.K_c:
                        SnakeGameLoop()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    X_change = -snake_block
                    Y_change = 0
                elif event.key == pygame.K_RIGHT:
                    X_change = snake_block
                    Y_change = 0
                elif event.key == pygame.K_UP:
                    X_change = 0
                    Y_change = -snake_block
                elif event.key == pygame.K_DOWN:
                    X_change = 0
                    Y_change = snake_block

                if event.key == pygame.K_a:
                    X_change = -snake_block
                    Y_change = 0
                elif event.key == pygame.K_d:
                    X_change = snake_block
                    Y_change = 0
                elif event.key == pygame.K_w:
                    X_change = 0
                    Y_change = -snake_block
                elif event.key == pygame.K_s:
                    X_change = 0
                    Y_change = snake_block

        if X >= display_width or X < 0 or Y >= display_height or Y < 0:
            game_close = True

        X += X_change
        Y += Y_change
        display.blit(grid_surf, (0,0))
        pygame.draw.rect(display, red, [foodX, foodY, snake_block, snake_block])
        snake_Head = []
        snake_Head.append(X)
        snake_Head.append(Y)
        snake_List.append(snake_Head)

        if len(snake_List) > Length_of_snake:
            del snake_List[0]

        for x in snake_List[:-1]:
            if x == snake_Head:
                game_close = True

        user_snake(snake_block,snake_List)

        pygame.display.update()

        if X == foodX and Y == foodY:
            foodX = round(random.randrange(0, display_width - snake_block) / snake_block) * snake_block
            foodY = round(random.randrange(0, display_height - snake_block) / snake_block) * snake_block
            Length_of_snake += 1

        clock.tick(snake_speed)


    pygame.quit()
    quit()
SnakeGameLoop()



Using a variable both as fixed and random effect?

We want to know whether leaf length depends on the amount of nutrients in the soil or by the family it originates from. We collected 10 seeds of the parent plant (i.e. the “family”) of which 5 are raised in the lab under high levels of available nutrients (“rich”) and 5 in a nutrient poor environment (“poor”). We have data from 10 such families. It is a split-plot design.

Normally we would add family as a random factor in a mixed model, but now we are also interested in the family effect as well. Can we include family both as a fixed factor and a random factor in our model? (R in RStudio)

model1 <- lmer(length~soil + FAM + (1|FAM) + (1|FAM:soil), data)

model2 <- lmer(length~soil + FAM + (1|FAM:soil), data)

Thanks in advance!

ps: it is a statistical exercise, the design cannot be changed




Random Math Problem Generator: userAnswer and realAnswer keep returning 0

This is a random math problem generator program.

The problem is my input answer and the real answer keeps returning 0.

What's the problem here? I can't find out why.

Here's the code step by step...

import libraries

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

calling functions

int getRandNum(int i, int lower, int upper, int randNum);
int getRandOp(int i, int opSel, char randOp);
int getRealAnswer(char randOp, int randNum1, int randNum2, int realAnswer);
void showQuestion(int i, int randNum1, int randOp, int randNum2, int realAnswer, int 
userAnswer);
int getUserAnswer(int userAnswer);
void answerCompare(int realAnswer, int userAnswer);

main() function

int main(void) // main fucntion
{
    int i;
    int randNum1, randNum2;
    int userAnswer, realAnswer;
    char randOp;
    srand(time(NULL));

    for (i = 1; i <= 5; i++)
    {
        showQuestion(i, randNum1, randOp, randNum2, realAnswer, userAnswer);
        getUserAnswer(userAnswer);
        getRealAnswer(randNum1, randNum2, randOp, realAnswer);
        answerCompare(realAnswer, userAnswer);
        printf("Real Answer = %d User Answer = %d\n\n", realAnswer, userAnswer);
    }

    return 0;
}

getRandNum() function

int getRandNum(int i, int lower, int upper, int randNum) // get random number within range using rand() function
 {
    lower = (20 * (i - 1)) + 1;
    upper = 20 * I;
    randNum = (rand() % (upper - lower + 1)) + lower;

    return randNum;
}

getRandOp() function

int getRandOp(int i, int opSel, char randOp) // get random operator within list using rand() function
{
    char opList[4] = {'+', '-', '*', '/'};
    opSel = rand() % 4;
    randOp = opList[opSel];

    return randOp;
}

getRealAnser() function

int getRealAnswer(char randOp, int randNum1, int randNum2, int realAnswer) // get real answer of the problem (problematic part: always returns 0)
{
    switch (randOp)
    {
    case '+':
        realAnswer = randNum1 + randNum2;
    case '-':
        realAnswer = randNum1 - randNum2;
    case '*':
        realAnswer = randNum1 * randNum2;
    case '/':
        realAnswer = randNum1 / randNum2;
    default:
        break;
    }

    return realAnswer;
}

showQuestion() function

void showQuestion(int i, int randNum1, int randOp, int randNum2, int realAnswer, int userAnswer) // print out math question

{
    int randNum, opSel, lower, upper;

    printf("##### Question Number %d #####\n", I);
    randNum1 = getRandNum(i, lower, upper, randNum);
    randOp = getRandOp(i, opSel, randOp);
    randNum2 = getRandNum(i, lower, upper, randNum);
    realAnswer = getRealAnswer(randNum1, randNum2, randOp, realAnswer);
    printf("%d %c %d = ", randNum1, randOp, randNum2);
}

getUserAnswer() function

int getUserAnswer(int userAnswer) // user input answer of the problem (problematic part: always returns 0)
{
    userAnswer = -1;
    userAnswer = scanf("%d", &userAnswer);

    return userAnswer;
}

answerCompare() function

void answerCompare(int realAnswer, int userAnswer) // compare user answer and real answer of the problem and print result
{
    if (userAnswer == realAnswer)
    {
        printf("You are correct!\n");
    }
    else if (userAnswer != realAnswer)
    {
        printf("You are wrong!\n");
    }
    else
    {
        printf("Error! Invalid Comparison!\n");
    }
}



How can i generate a random boolean with probability (1 to 100) in C?

I need a function that generates a random boolean with a given probability from 1 to 100.

I've tried with this:

int randProb(int chance, int min, int max) { 
  int random = rand();
  if (random < (RAND_MAX) / chance / 10) 
    return -(random % (max - min + 1) + min);
  else
    return (random % (max - min + 1) + min);
}

but when I call it, passing 1 as a probability

randProb(1, 0, 1)

sometimes it returns 1, sometimes -1, and sometimes 0.

and when I call it, passing 100 as a probability

randProb(100, 0, 1)

sometimes returns 0 and sometimes 1, as it should work, with a probability of 100 it should always return 1.

Note time is initialized with this:

time_t t;
srand((unsigned) time(&t));



SQL Server : unique default values

I have a table with a column of type nchar(16) that is automatically filled with random characters generated by setting the default value of the column to dbo.randomtext((16)) (a scalar function). There will be about 1M records in the table.

I know that the likelihood of getting non-unique values is low, but is there some way to ensure that this does not happen and the column is really unique?

What will happen if I define the column as UNIQUE and the random text generated is not unique?

I am using SQL Server 2016 Standard edition.




mardi 22 décembre 2020

Command line "random"? Seedable random binary data for disk testing

I want to do a quick write test of a SSD (that I bought on ebay).

I want to write a stream of pseudo random data and then read them back and compare.

Something like ("dd" omitted for clarity) :

random $seed > /dev/nvme0n1
random $seed | cmp - /dev/nvme0n1

... with maybe some flags to control "initstate" and buffer size




Roll/Dice command?

I'm trying to make roll command that generates a random number based on user input.

For example:

user: !roll 1d100
bot: Your output is 65 (or some other random number)

I have tried a couple of different things, but none of them have worked, the output was "NaN".

My nearest code was:

const argsminus8 = message.content.slice(prefix.length).trim().split(/ +/g);
const commandminus8 = argsminus8.shift().toLowerCase();

if(message.content.startsWith (prefix + `random-number`)) {
  function getRandomIntInclusive(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }
  if (!argsminus8.length) {
    return message.channel.send(`What roll am I supposed to make?`);
  }
  const embed = new MessageEmbed()
    .setTitle('Number:')
    .setDescription( getRandomIntInclusive())
    .setColor(0x0099ff)
    .setTimestamp()
  message.channel.send({ embed });
}



Android Studio Java - How do I use a random array without repeating?

I've got an array of random messages, but I want it so that it doesn't pick a message that has already been picked and then reset once all messages have been picked.

public void showRandomMsg(){
        shuffleMsg();
        answer1.setText((messageArray[0].getmAns()));
        message2.setText((messageArray[0].getmMsg()));
        toyView1.setImageResource(messageArray[0].getmImage());
    }

Messages m01 = new Messages(R.drawable.crown1, "Mesage 0 A","Message 0 B");
Messages m02 = new Messages(R.drawable.crown2,"Mesage 1 A","Message 1 B");
Messages m03 = new Messages(R.drawable.crown3,"Mesage 2 A","Message 2 B");
Messages m04 = new Messages(R.drawable.crown4,"Mesage 3 A","Message 3 B");
Messages m05 = new Messages(R.drawable.crown5,"Mesage 4 A","Message 4 B");

Messages [] messageArray=new Messages[]{
        m01, m02, m03, m04, m05
};

public void shuffleMsg(){
    Collections.shuffle(Arrays.asList(messageArray));

}



How to create a dataframe with repeated columns created from randomly sampling another dataframe?

I am trying to repeatedly add columns to a dataframe using random sampling from another dataframe.

My first dataframe with the actual data to be sampled from looks like this

df <- data.frame(cat = c("a", "b", "c","a", "b", "c"),
                 x = c(6,23,675,1,78,543))

I have another dataframe like this:

df2 <- data.frame(obs =c(1,2,3,4,5,6,7,8,9,10),
                  cat=c("a", "a", "a", "b", "b", "b", "c","c","c", "c"))

I want to add 1000 new columns to df2 that randomly samples from df, grouped by cat. I figure out a (probably very amateurish) way of doing this once, by using slice_sample() to make a new dataframe sample1 with a random sample of df, and then merging sample1 with df2.

df <- df %>%
  group_by(cat)

df2 <- df2 %>%
  group_by(cat)

sample1 <- slice_sample(df, preserve = T, n=3, replace = T )
sample1 <- sample1 %>%
  ungroup() %>%
  mutate(obs=c(1:9)) %>%
  select(-cat)

df3 <- merge(df2,sample1, by= "obs")

Now, I want to find a way to repeat this 1000 times, to end up with df3 with 1000 columns (x1,x2,x3 etc.)

I have looked into repeat loops, but haven't been able to figure out how to make the above code work inside the loop.




Random Function in Haskell

I'm currently working on a program in Haskell (which I am very new to) where I need to randomly generate co-ordinates and use them around the program in several places, however, I don't want to be threading IO around the whole program, nor the seed. I saw this link where they use num <- randomIO :: IO Float however I keep getting - Couldn't match type `IO' with `[]' Expected type: [Float]. I in theory need the co-ordinates to be integer values, so if there is a better way of doing it that would be great! The full stack is below:

Couldn't match type `IO' with `[]'
      Expected type: [Float]
        Actual type: IO Float
    * In a stmt of a 'do' block: y <- randomIO :: IO Float

Edit - here is a minimum reproducible example! I'm using stack as well.

import Data.List
import System.Random

main :: IO ()
main = 
    do
        xt <- randomIO :: IO Float
        x <- round ((xt) * (5))
        putStrLn x



R: How to replace values in column with random numbers WITH duplicates

I have a df with data, and a name for each row. I would like the names to be replaced by a random string/number, but with the same string, when a name appears twice or more (eg. for Adam and Camille below).

df <- data.frame("name" = c("Adam", "Adam", "Billy", "Camille", "Camille", "Dennis"), "favourite food" = c("Apples", "Banana", "Oranges", "Banana", "Apples", "Oranges"), stringsAsFactors = F)

The expected output is something like this (it is not important how the random string looks or the lenght of it)

df_exp <- data.frame("name" = c("xxyz", "xxyz", "xyyz", "xyzz", "xyzz", "yyzz"), "favourite food" = c("Apples", "Banana", "Oranges", "Banana", "Apples", "Oranges"), stringsAsFactors = F)

I have tried several random replacement functions in R, however each of them creates a random string for each row in data, and not an individual one for duplicates, eg. stri_rand_strings:


library(stringi)
library(magrittr)
library(tidyr)
library(dplyr)

df <- df %>%
    mutate(UniqueID = do.call(paste0, Map(stri_rand_strings, n=6, length=c(2, 6),
                                          pattern = c('[A-Z]', '[0-9]'))))



How would I randomize the composition of an atmosphere in my game?

I am making a space game with planets that are randomly generated and I need their atmospheres to be made up of random amounts of different elements. So the thing is that I want the elements to be percentages of the complete atmosphere, an example: oxygen = 30, nitrogen = 20, carbondioxide = 50, hydrogen = 0. All these values should be completely randomized and the sum of them all has to be 100.

I basically want to fill a container to the top with random amounts of set elements, but I don't know how to randomize all of the variables and end up with a fixed sum.

This is my first time submitting anything to StackOverflow so please let me know if there is anything I need to clarify, I've been stuck on this issue for so long without finding any answers so I would appreciate any help, thanks :)

(I am using c# in unity in case that makes a difference)




How to express infinity in Prolog?

I am trying to use random/3

random(+L:int, +U:int, -R:int)

Is there any thing that can be used for representing infinity?

For Example:

random(0, Infinity, Random_Number).

Is it possible to achieve this with random? Or is there any other simple alternative?

P.S. I have made clpfd programs where I have used sup ( Supremum ), but I am not working with clpfd.




Laravel | Generate automatically invoice with laravel

i am working on very simple project for my school assignment. So it's a house rent site. Everything seems fine but i want create an automatically invoice like "INV0001" but i dont know how to do that. maybe you guys can help me fix my controller

this is my controller

public function storeSewa(Request $request){
  if ($request->edit=='false') {
  $newdata = new Sewa;
  } else {
  $newdata = Sewa::find($request->id);
  if ($newdata) {
  //
  }else {
  $newdata = new Sewa;}}
  $newdata->invoice = 'INV/'//idk, how?
  $newdata->penyewa_id = $request->penyewa_id;
  $newdata->kamar_id = $request->kamar_id;
  $newdata->tanggal_masuk = $request->tanggal_masuk;
  $newdata->tanggal_keluar = $request->tanggal_keluar;
  $newdata->durasi = $request->durasi;
  $newdata->status = 'Belum Lunas';

  $newdata->save();
  if ($newdata) {
  session()->flash('status', 'Task was successful!');
  session()->flash('type', 'success');
  return Redirect::route('account');
 }
 return 'false';
 }

well, i am very new to laravel, so is there anyone can help fix my problem with easiest way? Thanks in advance. And sorry about my bad english too




lundi 21 décembre 2020

Can I reference the result of the equation in the previous line to send an additional line of text?

I'm super new to JS and currently working on a discord bot. I'm looking for a way to reference the above result that is being generated (a number from 1-20), and have a command send an additional message if the result happens to be exactly a 20. Can anyone help me with this, any tips would be appreciated? Thanks. Examples below.

Current code:

module.exports = {
    name: 'roll',
    description: "this is a roll command!",
    execute(message, args){
        message.channel.send(`${message.author} rolled a **D20** <:d20:790654162600853535> and got***${Math.floor(Math.random() * 20) + 1}*** !`);

        }
    
    }

Current Result: @User rolled a D20 and got 20!

Alternate Current Result: @User rolled a D20 and got 5!

Wanted Result : @User rolled a D20 and got 20! !

                   @User rolled a Critical!

Alternate Wanted Result : @User rolled a D20 and got 5! !




Generate random number array without duplicates next to each other in Javascript? [duplicate]

I have a function that pushes a sequence of random numbers to an empty array. I don't mind duplicates in the array, but I really need it NOT to repeat numbers that are next to each other. So, for example [1,2,3,4,1] would be totally fine, but [1,1,2,3,4] would not. I've tried putting an if statement into the code, but I'm not quite getting it right. Here's the code I'm using to generate the array. Any help, as always, very gratefully received!

let initArray = [];

function makeCircleArray(level) {
    var i = 0;
  do {
    var val = Math.floor(Math.random() * 9)
    initArray.push(val)
    i++
  }
  while (i < level.dots)
  console.log(`${initArray}`)
  return initArray;
}



Slow shuffle for large arrays

I'm implementing the Fisher-yates shuffle in a Photoshop script. I want to create an array of n unique random elements from a maximum of about 99999. Where n is a small value but could be up to to maximum.

With maximum of under a thousand this is fine (runs in milliseconds), but considerably much slower for 10,000 (about 20 seconds).

Is there a better/faster way to do this? Bear in mind that'll it'll need to be in ECMAScript.

var maxNumber = 99; 
var numToGenerate = 5; 

var bigShuffle = shuffle(maxNumber);
var randomNumbers = bigShuffle.slice(0, numToGenerate);

alert(randomNumbers);


function shuffle(m)
{

   var temp;
   var rnd;

   // create an empy array
   var arr = new Array();
   var d = m + "";
   d = d.length;

   for(var i = 0 ; i < m; i++) 
   {
      arr.push(i);
   }

   while (m)
   {
      rnd = Math.floor(Math.random() * m-=1);
      // And swap it
      temp = arr[m];
      arr[m] = arr[rnd];
      arr[rnd] = temp;
   }

  return arr; 
}



Is there a cleaner way to write this C code?

I have to fill a matrix with random numbers 0 or 1, but if a cell contains 1, the other 8 around it must be 0. As a beginner, I tried to implement my code in this way:

for (int i = 0; i < 5; i++){
      for (int j = 0; j < 5; j++){
        a[i][j] = rand() % 2;
        if (a[i][j] == 1){
            a[i-1][j-1] = 0; 
            a[i-1][j] = 0; 
            a[i-1][j+1] = 0;
            a[i][j-1] = 0; 
            a[i][j+1] = 0;
            a[i+1][j+1] = 0; 
            a[i+1][j] = 0; 
            a[i+1][j+1] = 0;
        }
    }
}

Of course, I'm sure there is a cleaner way to write this code. Can you help me? Thanks in advance!




Displaying 4 complex random divs from array list

I am trying to make a carousel which displays 4 random posts. I came across a simple random div display from another thread

$divs = array(
'<div id="divZero">Start Div</div>',
'<div id="divFirst">First Div</div>',
'<div id="divSecond">Second Div</div>',
'<div id="divThird">Third Div</div>',
'<div id="divFourth">Fourth Div</div>',
'<div id="divFifth">Fifth Div</div>',
'<div id="divSixth">Sixth Div</div>'
);

// Array with 4 random keys from $divs
$randKeys = array_rand($divs, 4);

echo $divs[$randKeys[0]]; // First random div
echo $divs[$randKeys[1]]; // Second random div
echo $divs[$randKeys[2]]; // Third random div
echo $divs[$randKeys[3]]; // Fourth random div

The problem is I am using classes for the divs and the wrapping is not simple, and I am incorporating Google Analytics tracking code. When I try it with my div set up, I get the 417 - Expectation Failed error. Was wondering if anyone might be able to help me sort this out.

The divs use class formats since they repeat, but the link, title (and GA label names) change. Here is an example of 2

<div class="rec-wrap clearfix">
    <div class="rw-image"><a href="https://www.website.com/linkA" onclick="ga('send', 'event', { eventCategory: 'Evergreen', eventAction: 'Click', eventLabel: 'Story Title A'});"><img src="https://website.com/imageA.jpg" width="80" height="80"></a></div>
    <div class="rw-title"><a href="https://www.website.com/linkA" onclick="ga('send', 'event', { eventCategory: 'Evergreen', eventAction: 'Click', eventLabel: 'Story Title A'});">Story Title A</a></div>
</div>

<div class="rec-wrap clearfix">
    <div class="rw-image"><a href="https://www.website.com/linkB" onclick="ga('send', 'event', { eventCategory: 'Evergreen', eventAction: 'Click', eventLabel: 'Story Title B'});"><img src="https://website.com/imageB.jpg" width="80" height="80"></a></div>
    <div class="rw-title"><a href="https://www.website.com/linkB" onclick="ga('send', 'event', { eventCategory: 'Evergreen', eventAction: 'Click', eventLabel: 'Story Title B'});">Story Title B</a></div>
</div>