jeudi 31 août 2023

Excel - semi-random ordered list from sample names

I have a list of employee names, and I want to extract a random pair without picking the same names too frequently. I was thinking of complex ways to add a weight metric that increases for each time a name is picked but was hoping the fine folks here might have a better suggestion of how to do this?




How do I append a dictionary with random prices from original starting point

Imagine I start with 5 stocks

dict1 = {'BA':57.0, 'QQQ':545.5, 'AAPL':150, 'SPX':245.5, 'JPM':150, }

how can I increase the dictionary to hold say 500 random prices for each asset from the original starting point?

so I get; BA: 57.0, 58.2, 59.6, 59.9 .........

Many thanks




How to display a random photo from the gallery without picking it in flutter?

I want to create a flutter app that shows me a random photo from the phone gallery, I don't want to choose it like with the image picker, I would like a button that loads me a random image.

I've tried to create a list that contains every image from the phone but i can't make it work.




mercredi 30 août 2023

Blender make hair length vary in size, but keep "origin point" to be face of object

So in blender I am making a rug/carpet without thickness, so it's only one face, and when I add hair particles (and change some settings) it looks fine, however each hair is of a certain length like so:

each hair has same length

I tried changing the random setting under Children -> Roughness, and although that does solve the same-length problem, it brings on a new one, the hairs can start from below my face.

hairs can start from bottom of face




To display random questions from selected exam

$query = mysqli_query($database, "select \* from questions where e_category='$\_SESSION\[categories\]' && question_no='$que_no' order by rand() ");

Here, the problem is that I want to display a random question from the selected exam.

Exams:-

(1) PHP (2) C language (3) Java

e.g. If the user selects PHP (exam), but cannot display random questions due to the above query, they will also verify e_category='$\_SESSION\[categories\]'

No Warring appears.

$query = mysqli_query($database, "select \* from questions where question_no='$que_no' order by rand() ");

The problem arises when e_category='$\_SESSION\[categories\]' is not used, as it displays all exam questions, not just a specific exam.




How do i detect the randomly generated number

i made code to randomly generate weighted numbers and whenever i tell it to break when it generates a certain number it doesnt do it code:

import random
while True:
    numberList = [0, 100, 250, 500, 1000, 2000, 5000, 10000, 25000, 50000, 75000, 100000, 250000, 500000, 750000, 1000000, 5000000, 10000000, 100000000, 1000000000, 10000000000, 100000000000, 1000000000000, 10000000000000, 100000000000000, 1000000000000000]
    tapped = (random.choices(numberList, weights=(1, 1/25, 1/250, 1/500, 1/1000, 1/2000, 1/5000, 1/10000, 1/25000, 1/50000, 1/75000, 1/100000, 1/250000, 1/500000, 1/750000, 1/1000000, 1/5000000, 1/10000000, 1/100000000, 1/1000000000, 1/10000000000, 1/100000000000, 1/1000000000000, 1/10000000000000, 1/100000000000000, 1/1000000000000000), k=100))
    print(tapped)
    if tapped == 500:
        break

i tried adding a while true command, i tried using

if tapped = 500:
    print('you got a 500')

and also

if tapped = 1/500
    print('you got a 500')

and both dont work (1 being from the list and the other from the weights) so im not sure what else to try




mardi 29 août 2023

randomize contents of tableview cells

I what I have below is the code that loads string from core data named title. What I would like to do is have a func that randomizes the order of the way all the names are displayed on the tableview cell every time the button is pressed. If possible also save the new order.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let song = songs[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: "songCell", for: indexPath) as UITableViewCell
        cell.textLabel?.text = song.title
        return cell
    }



algebraic operation with normal random values in Modelica

i've got such code in Modelica:\

model BioPowerSetup  
Modelica.Blocks.Interfaces.RealOutput BioPowerOutput;  
parameter Real alpha = 0.05;   
parameter Real mu1 = 7 / 25 ;   
Real Nmax = 25;   
parameter Real D = 0.2 ;   
Modelica.Blocks.Noise.TruncatedNormalNoise Noise(y_min = -0.028, y_max = 0.028, samplePeriod = 1); equation   
if BioPowerOutput < 489100 then    
 BioPowerOutput = alpha * mu1 * (Nmax * exp(mu1 * time));   
else     
BioPowerOutput = 489100 * exp(Noise.y * time);   
end if; 
end BioPowerSetup;

After compiling this program, it interrupts on the 55s with such error:

Warning: [EVENT]  Mixed block did not converge during event iteration. [b4»]   [@55.0 s] 
Error: [GENERAL] Mid-simulation event iteration didn't converge. [@55.0 s]

I will be glad of any help!

I think, that error is located in the algebraic operation with noise value, but i don't know what to do with it.




Pick n random records with same index from 2 different list column pyspark

Hi I have dataframe like this:

cc   doc_1      doc_2

4   [a, b,..]  [1, 6,..]
9   [t, s,..]  [4, 5,..]
4   [q, f,..]  [6, 7,..]

I want to pick n(1/2 of cc col) random records from both the col doc_1 doc_2 with same index value. I can use f.rand() to pick 1 record from column but I'm not sure how I'll pick multiple records with same index from different column as well

Expected Output has randomly picked value in column

doc_1  doc_2
cc  doc_1                 doc_2
4   [c, f]                [5, 3]
9   [s, g,..](4 records)  [6, 5,..](4 records)
4   [r, g]                [7, 9]



How to get non repeating random number pairs,elements can repeat

I'm currently programming a BattleShip game in Java, I randomly generate x, then y for the first cell of the ship,

public class Cell implements Comparable<Cell> {


    private final int x;
    private final int y;

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    Cell(int xc, int yc) {
        x = xc;
        y = yc;
    }


    public Cell continueWithDirection(Direction d) {
        switch (d) {
            case ROW -> {
                return new Cell(x + 1, y);
            }

            case COLUMN -> {
                return new Cell(x, y + 1);
            }
        }
        ;

        return new Cell(x, y);
    }
}

//file 2

import java.util.Random;

public enum Direction {
    ROW,
    COLUMN;

  private static final Random randomizer=new Random();
  
    static Direction random(){
        boolean b = randomizer.nextBoolean();
        if (b) {
            return Direction.ROW;
        } else {
            return Direction.COLUMN;
        }
    }
}
Cell[] cells = new Cell[size];
cells[0] = new Cell(randomizer.nextInt(getAreaWidth() - size + 1), randomizer.nextInt(getAreaHeight() - size + 1));

for (int i = 1; i < cells.length; i++) {
    cells[i] = cells[i - 1].continueWithDirection(getDirection());
}

return cells;

and then choose a random direction (either up or right) for the other 2 cells of the ship the first cell is placed from 0 to bound-shipSize + 1 x and y bound, so I guarantee that all ships will be placed in the border area, but how do I implement random coordinate generation without repeating the same x and y together. I thought to randomly generate only the first ship, then just randomly go in some direction from the ship and put a new ship, but even so I have to store an array of all ships, and detect collisions. How can I better implement this algorithm




lundi 28 août 2023

How to shuffle a list of sequence numbers in bash

I want to generate the random numbers and then use it as the "index" to get the data from other array list.

Given a number 5, and then generate 5 numbers in the sequence of [1..5], and then shuffle them into the random order.

Here are two examples output after shuffling the numbers:

1, 3, 5, 2, 4
2, 5, 1, 4, 3

Gien a number 100, then generate 100 numbers in [1...100], then shuffle them using the same method.

Now define a shuffle function in bash:

shuffle_numbers() {
    local range="$1"
    
    # Use method from "Mark Setchell"
    # numbers=( $seq 100 | shuf )
    
    # The value of numbers should be:
    # 1, 3, 5, 2, 4
    # or
    # 2, 5, 1, 4, 3
    # or
    # ..other random orders if the $range is 5.
    # or
    # ... 100 random orders if the $range is 100...
    
    sprintf "%s" "$numbers"
}

How to implement the shuffle_numbers in bash?




dimanche 27 août 2023

How use random to dict in python

Good evening! I wanted to make a program for learning English with pronunciation, but I couldn't make a random choice for the dictionary, I will be grateful if you explain how to fix it. The idea is this program will ask English word and I will input answer and the problem is English and Russian words do not match with each other and need to be synchronized.

The code here👇 https://dpaste.org/MQBeJ




Problem retrieving user data for Supabase query in Sveltekit

I'm loading in a table from Supabase of categories (id, category) that populate a select dropdown. The user selects a category, hits submit, and then it takes them to a category page with a random quote associated with what the category selected. The category page is pulling data from another table in Supabase (id, name, content, category_id) with all the quotes.

The select dropdown is working and so is the routing in the URL based on the category ID of the selection (/category/1, /category/2, etc), but I'm having trouble getting that same category ID into my query for the Category page. It seems like I'm close, but I've been stuck on this for awhile and not sure what else to try at this point.

The main pages related to this issue are /routes/category/[id]/+page.svelte, /routes/category/[id]/+page.server.js, and /routes/Quote.svelte.

Here's the /routes/category/[id]/+page.svelte code:

<script>
    import Quote from "../../Quote.svelte";
    import { page } from "$app/stores";
    
    const category = $page.params.num;
    
    export let data;
    $: ({ quotes } = data);
</script>

<Quote quotes="{quotes}" />

Here's the /routes/category/[id]/+page.server.js code:

import { supabase } from "$lib/supabaseClient";

export async function load() {
  const { data } = await supabase
    .from('quotes')
    .select('*')
    .eq('category_id', 2); // TODO: Retrieve category ID to select random quote
  
  return {
    quotes: data ?? [],
  };
}

And here's the /routes/Quote.svelte code:

<script>
    import { writable } from 'svelte/store';
    export let quotes;
    function getRandomQuote() {
      const randomIndex = Math.floor(Math.random() * quotes.length);
      return quotes[randomIndex];
    }
  
    const randomQuote = writable(getRandomQuote());
  
    function generateNewQuote() {
      randomQuote.set(getRandomQuote());
    }
</script>

{#if $randomQuote}
  <p>{$randomQuote.content}</p>
  <p>{$randomQuote.name}</p>
{/if}
<button on:click={generateNewQuote}>Get Another Quote</button>

I don't know if I'm approaching this the correct way. It feels like I'm close, but maybe I'm way off. I'm new to Sveltekit and trying to understand it better.




samedi 26 août 2023

How to make a random event in java

I want to write a java program where there 50% chance for event a to occur, 35% chance for event b to occur and 15% chance for event c to occur and finally print the event which took place. Thanks.

I tried using math.random but it ended up being too complicated for me to understand.




Avoid displaying duplicated posts on random orderby WordPress WP_Query

I'm setting up a news site on WordPress, I set up a query that shows the news by categories (for example: Brazil category, World category). The query is all right, and when the person clicks, the detailed news appears, as I want. However, at the base I have an option to view more news, where I set up another query, showing more news from the category.

How do I set up this second query without displaying the previous news?

For example, does it display news "A" and below it will appear news "B" and "C"?

Here's the code for how I'm setting up the second query:

<?php 
$args = array(
    "post_type" => array("noticias"),
    "order" => "randon",
    "category_name"=>"mundo",
    "posts_per_page" => 2,
    "paged'          => $paged
); 

$query = new WP_Query( $args );

if ( $query->have_posts() ) :
    while ( $query->have_posts() ) : $query->the_post();
?>



jeudi 24 août 2023

How would I randomly select at most one user from data frame [duplicate]

I have a pandas DataFrame that looks:

df=pd.DataFrame({'user': [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3],
                 'i': [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4],
                'value': [0.64, 0.93, 0.53, 0, 0.74, 0.61, 0.41, 0.64, 0, 0.51, 0.78, 0.21]})
df

output:

  user  i   value
0   1   1   0.64
1   2   1   0.93
2   3   1   0.53
3   1   2   0.00
4   2   2   0.74
5   3   2   0.61
6   1   3   0.41
7   2   3   0.64
8   3   3   0.00
9   1   4   0.51
10  2   4   0.78
11  3   4   0.21

For each value of (i), I want to select no value or only one random value of user (e.g. 1, 2, or 3) and check if its value is less than 0.5, then remove this user from dataframe (df).

For example: when i=1, let's say we randomly select user 2, then when we check its value 0.93 which is higher than 0.5, we keep user 2. So, df is the same.

user i value 0 1 1 0.64 1 2 1 0.93 2 3 1 0.53 3 1 2 0.00 4 2 2 0.74 5 3 2 0.61 6 1 3 0.41 7 2 3 0.64 8 3 3 0.00 9 1 4 0.51 10 2 4 0.78 11 3 4 0.21

when i= 2, let's say we randomly select user 1, then we know its value 0 is less than 0.5, so we remove it from df. Now, df contains only users 2 and 3.

      user  i   value
    1   2   1   0.93
    2   3   1   0.53
    4   2   2   0.74
    5   3   2   0.61
    7   2   3   0.64
    8   3   3   0.00
    10  2   4   0.78
    11  3   4   0.21

When i=3, let's say we select no user, we keep users 2 and 3 in df. df keep the same values.

When i=4, let's say we randomly select user 3, and when we check its value 0.21, this value is lower than 0.5. So, in the end, df contains only user 2.

the final data frame:

  user  i   value
1   2   1   0.93
4   2   2   0.74
7   2   3   0.64
10  2   4   0.78



Java Generating Random Numbers

I am creating a 2d tile map with a method called generateMap.There is an array called map which keeps what tile will be on x and y locations.There are only 4 types of tiles and they are represented in numbers,1-2-3-4.

Numbers also triggers different colors.That's why they are here.

For example : map[10][10]=1 = means there will be a tile number 1 on x10 and y10.(Green)

The thing is all four types of tiles has the same probability to show up,but somehow every time I run the method,"4"becomes much more frequent than the others.

For every tile that doesn't have a neighboring tile,which means every tile with either x0 location or y0 location,I assign them a random number.But with every tile with eight neighboring tiles at least one with same type,has a higher chance to have same type as them.

import java.awt.Dimension;
import java.awt.Toolkit;
import java.util.concurrent.ThreadLocalRandom;

public class Map {
public int tilesize=20;
public int tiletype;
public int mapx,mapy=0;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int userwidth = (int) screenSize.getWidth();
int userheight=  (int) screenSize.getHeight();
int width = tilesize/userwidth;
int height = tilesize/userheight;
public int map[][] = new int [140][80]; 

    public void generateMap() {
        
        
        for(int x=0; x<130; x++) {
            for(int y=0; y<70; y++) {
                
                if(x==0 || y==0) {
                    int randomtile=ThreadLocalRandom.current().nextInt(0, 5);
                    map[x][y]=randomtile;   
                }
                else {
                if(map[x][y-1]==1 || map[x][y+1]==1 || map[x-1][y]==1 || map[x+1][y]==1
                || map[x+1][y+1]==1 || map[x-1][y-1]==1 || map[x-1][y+1]==1 || map[x+1][y-1]==1) 
                {
                    int randomtile=ThreadLocalRandom.current().nextInt(0, 10);  
                    if(randomtile>=1 && randomtile <=7) {
                        map[x][y]=1;
                    }
                    else {
                        int randomtile2=ThreadLocalRandom.current().nextInt(0, 5);
                        map[x][y]=randomtile2;
                    }
                }
                
                
                if(map[x][y-1]==2 || map[x][y+1]==2 || map[x-1][y]==2 || map[x+1][y]==2
                || map[x+1][y+1]==2 || map[x-1][y-1]==2 || map[x-1][y+1]==2 || map[x+1][y-1]==2)
                {
                    int randomtile=ThreadLocalRandom.current().nextInt(0, 10);  
                    if(randomtile>=1 && randomtile <=7) {
                        map[x][y]=2;
                    }
                    else {
                        int randomtile2=ThreadLocalRandom.current().nextInt(0, 5);
                        map[x][y]=randomtile2;
                    }
                }
                
                
                if(map[x][y-1]==3 || map[x][y+1]==3 || map[x-1][y]==3 || map[x+1][y]==3
                || map[x+1][y+1]==3 || map[x-1][y-1]==3 || map[x-1][y+1]==3 || map[x+1][y-1]==3) 
                {
                    int randomtile=ThreadLocalRandom.current().nextInt(0, 10);  
                    if(randomtile>=1 && randomtile <=7) {
                        map[x][y]=3;
                    }
                    else {
                        int randomtile2=ThreadLocalRandom.current().nextInt(0, 5);
                        map[x][y]=randomtile2;
                    }
                }
                
                
                if(map[x][y-1]==4 || map[x][y+1]==4 || map[x-1][y]==4 || map[x+1][y]==4
                || map[x+1][y+1]==4 || map[x-1][y-1]==4 || map[x-1][y+1]==4 || map[x+1][y-1]==4) 
                {
                    int randomtile=ThreadLocalRandom.current().nextInt(0, 10);  
                    if(randomtile>=1 && randomtile <=7) {
                        map[x][y]=4;
                    }
                    else {
                        int randomtile2=ThreadLocalRandom.current().nextInt(0, 5);
                        map[x][y]=randomtile2;
                    }
                }
                    
                    
                    
                }
                
                
            }
        }
    }


}

My problem is understanding why 4 is more frequent.




mercredi 23 août 2023

Making a random image generator on Swift, but being able to modify the drop rate

I want to make a gacha system, so making a random generator of images (or 3d objects), and I'm already aware about how to do this IF all the images need to be equally rare.

But just like in a gacha game, I'd like to insert drop rate, like "common, uncommon, rare, epic" ecc.

any idea on how to do this in Swift? thanks

I didn't actually triy anything cause I had no idea.




Fill a range with random numbers and execution policy

We can fill a range [first, last) using

std::mt19937 g;
std::uniform_real_distribution<> u;
std::generate(first, last, [&]() { return u(g); });

Theoretically, it would be more performant to execute std::generate with the execution policy std::execution::par_unseq. However, we could write

std::generate(std::execution::par_unseq, first, last, [&]() { return u(g); });

but is this really safe? I think, parallal access to g might be problematic. If that's actually true, how can we fix this? I've seen strange looking code like

std::generate(std::execution::par_unseq, first, last, []()
{
    thread_local std::mt19937 g;
    thread_local std::uniform_real_distribution<> u;
    return u(g);
});

But is thread_local really sensible here? And how should g be seeded here if the generated samples are supposed to be independent?




mardi 22 août 2023

DIEHARDER test suite build is broken for Arch Linux

I've created a PRNG for an university project and I need to test it with the DIEHARDER test suit. Unfortunatelly, every way I tried to install it in my Arch Linux gets failed.

First I tried from the AUR package (dieharder, dieharder-git and dieharder-bin) and all of those gives error when downloading the files from github. When you try to enter the github address, it gives the 404 error.

Then I tried downloading from the official website. I've tried a lot of versions (3.31.1, 3.31.0, 2.6.24, 2.27.13, 2.24.7 and 2.24.1) and all of those gives error when trying to install it via ./configure and makefiles, and the errors are often based on headers and variables not properly declared in the build, just as "ckoba" commented on the official aur repository website:

For what it's worth, I spent several hours this afternoon moving variable declarations from .h files to .c files, eliminating the duplicate variable issues that broke the build. While I was at it, I updated the autoconf bits so that the build framework properly detects modern platforms. I've tested this on i686, x86_64, and aarch64 platforms, and all seem to work fine.

Does someone knows how to install it in my Arch Linux distro today in August 2023? I really need it to test my PRNG and I'm struggling for days trying to install it. Thanks in advance.




How to randomly sample 10 rows, where the 2nd row has to be at a certain distance from the 1st?

I have generated a dataframe which contains 100 rows and 3 columns: one with an x-coordinate, one with a y-coordinate, and one with "level" which is a variable I use as a constraint. I want to randomly sample 10 coordinates from these 100 at Level 1. For this, I have used the sample function in R, randomly selecting 10 rows.

However, some of the coordinates end up being too close to each other, so I want to add a second constraint that says the sample function has to skip at least 5 rows from any selected random row. How do I do this?

This is what I have now:

newdf <- df[sample(which(df$level == 1 ) , 10 ) , ]



In R, how to sample from multivariate normal given restrictions in a form of sample scheme (NOT sampling from truncated normal)?

I have written a following function to sample from multivariate normal...

library(dplyr)

rmvtnormtibble <- function(n, mu, Sigma, names) {
  (matrix(rnorm(n * length(mu)), ncol = length(mu)) %*% chol(Sigma)) %>%
    {t(.) + mu} %>%
    t %>%
    as_tibble %>%
    setNames(names)
}

...that returns a tibble having columns that correspond different variables.

The function can be called this way:

rmvtnormtibble(n = 120 + 86 + 56, mu = c(A = 24, B = 48, C = 30), Sigma = diag(3), names = c("A","B","C"))

Then I have the following sampling scheme:

A B freq
30 40 120
25 41 86
27 22 56
sample_scheme <- tibble(A = c(30,25,27), B = c(40,41,22), freq = c(120,86,56))

And now, how do we read this sample scheme table? We want exactly 120 observations having A column to be between 30 and 31 AND B column to be between 40 and 41. 86 observations A being between 25 and 26 AND B being between 41 and 42. 56 observations being A being between 27 and 28 AND B being between 22 and 23.

So any number (x), in columns A and B, defines an interval [x, x+1].

Then we can start sampling. If we set the n argument extremely high, we would most likely get what we need plus some extra observations. However, if the sampling scheme has high frequencies and/or the A and B values tend to deviate from their respective means and/or the multivariate normal has many dimensions, we might run into memory issues. Therefore n needs to be set according to these but also according to possible memory constraints of the environment.

So my question is, that how could we accrue a tibble with new observations when we loop the rmvtnormtibble function and keep adding new observations according to the sample scheme most effectively? So when we get new observations that we need, we add them, when we get observations we do not need, we omit them.




lundi 21 août 2023

Generating the Sum of 2 random numbers in Python [closed]

This code generates 2 random numbers when executed in Python. I would also like it to generate the Sum of those 2 numbers as well. Anyone know how to do this?

I am struggling to find this solution anywhere online. I've tried a few different things myself and yet no luck. Any help would be appreciated.




How to clear the clipboard everytime I add something to it?

I am working on a password generator. I have a button that generates the password and a button that copies it to the clipboard. The problem is: Every time I generate another password and then add it to the clipboard it just gets added to the other password. If I had the password 123ok and copied it to the clipboard but then generated 456ok and copied this one to the clipboard I would have 123ok456ok.

That´s my code:


import string
import random
import tkinter as tk

letters = string.ascii_letters
numbers = string.digits
symbols = string.punctuation

chars, nums, syms = True, True, True

evy = ""

if chars:
    evy += letters
if nums:
    evy += numbers
if syms:
    evy += symbols

length = 8

window = tk.Tk()
window.geometry("500x500")
window.title("Password Generator")
window.configure(background="black")


def generate():
    for x in range(1):
        global password
        password = "".join(random.sample(evy, length))
        pwd = tk.Label(text=password, foreground="green", background="black", font=16)
        pwd.pack()


genBtn = tk.Button(window, command=generate, text="Generate Password")
genBtn.pack()


def copy_clip():
    window.clipboard_append(password)
    window.clipboard_clear()


copyBtn = tk.Button(text="Copy the password", command=copy_clip)
copyBtn.pack()

window.mainloop()




How Display Random json_decode foreach

I want to display randomly in json_decode foreach. These codes are for Laravel/php.

my table:

id    url        attr
1     post-1     [{"at1":"Attr-A1","at2":"Attr-A2",.....}]

my array (attr):

[{
"at1":"Attr-A1",
"at2":"Attr-A2",
"at3":"Attr-A3",
"at4":"Attr-A4",
},
{
"at1":"Attr-B1",
"at2":"Attr-B2",
"at3":"Attr-B3",
"at4":"Attr-B4",
},
{
"at1":"Attr-C1",
"at2":"Attr-C2",
"at3":"Attr-C3",
"at4":"Attr-C4",
}]

my controller:

$post = Post::where('url',$url)->first();

my blade

@foreach ( json_decode($post->attr, true) as $arr )
    <p></p> ,
    <p></p> ,
    <p></p> ,
    <p></p>
    <br>
@endforeach

Qutput: I want the output to show randomly.

Attr-A1 , Attr-A2 , Attr-A3 , Attr-A4
Attr-C1 , Attr-C2 , Attr-C3 , Attr-C4
Attr-B1 , Attr-B4 , Attr-B3 , Attr-B4

or

Attr-C1 , Attr-C2 , Attr-C3 , Attr-C4
Attr-A1 , Attr-A2 , Attr-A3 , Attr-A4
Attr-B1 , Attr-B4 , Attr-B3 , Attr-B4

shuffle or array_random : These two do not work for me.

Does json_decode display randomly?




I'm trying to change the color of some of the blocks in my grid every 2 seconds

I'm trying to change the color of some of the blocks in my grid every 2 seconds. So far, the blocks are just a set color (yellow), but I need them to automatically and randomly change color repetitively. This is the code so far; g is the grid.

g.setColor(Color.yellow);
g.fillRect(wIncr * maxX / 2, 3 * hIncr, wIncr * (maxX / 2), hIncr * (maxY - 8));
g.setColor(Color.black);

I tried using a random generator:

private static final int MIN_STATE_COLOR = STATE_RED;
private static final int MAX_STATE_COLOR = STATE_YELLOW;

int random = new Random().nextInt(MAX_STATE_COLOR - MIN_STATE_COLOR + 1) + MIN_STATE_COLOR;

g.setColor(Color.random);
g.fillRect(wIncr * maxX / 2, 3 * hIncr, wIncr * (maxX / 2), hIncr * (maxY - 8));
g.setColor(Color.black);

And that gave me an error with MIN_STATE_COLOR and MAX_STATE_COLOR.

I then also tried creating a timer:

ActionListener timerListener = new ActionListener() {
  public void actionPerformed(ActionEvent evt) {
    g.setColor(Color.red);  // I don't know how to make it random
    g.fillRect(wIncr * maxX / 2, 3 * hIncr, wIncr * (maxX / 2), hIncr * (maxY - 8));
    g.setColor(Color.black);
  }
};
int timerDelay = 3 * 1000;
Timer timer = new Timer(timerDelay, timerListener);

But this also gave me an error.




dimanche 20 août 2023

Excel Formula. To generate random numbers based on an array of numbers and with a condition =Randomarray

Background: I have clients who get drug tested. They need to get drug tested 2x per a 7 day week. however, I don't want them finding out the pattern. So i want the pattern of numbers to change per every week. if someone gets tested monday and wednesday, then the following week they should get tested wednesday and friday.

Excel: As a result in excel I have an array of numbers lets say 1 through 65, to represent the patients. I have a formula that generates random numbers based on the array, for 10 columns. The data is present in 10 columns and 7 rows (sunday through sat (1 week)). Formula here: =RANDARRAY(A2:J8,10,1,65,TRUE). However I need each number / patient to get repeated / tested 2x per every week. I got the formula to generate 7 random numbers per day, based on the array. But what I don't know how to do is make sure the numbers are randomly generated every week with a different pattern.

Let me know if this makes sense.




How to define unequal allocation of groups in blockrand() in R

I want to design a randomized clinical trial using R v.4.0.3 and blockrand package. The following is my code:

library(blockrand)
library(writexl)
library(openxlsx)

set.seed(101)
Mos1<-blockrand(n=295, id.prefix= 'Mos -', block.prefix='B', block.sizes =1:2, stratum='XX-Y1')
set.seed(10)
Mos2<-blockrand(n=295, id.prefix= 'Mos -', block.prefix='B', block.sizes =1:2, stratum='XX-Y2')
set.seed(5)
Mos3<-blockrand(n=295, id.prefix= 'Mos -', block.prefix='B', block.sizes =1:2, stratum='XX-Y3')
set.seed(70)
Mos4<-blockrand(n=295, id.prefix= 'Mos -', block.prefix='B', block.sizes =1:2, stratum='NONXX-Y1')
set.seed(43)
Mos5<-blockrand(n=295, id.prefix= 'Mos -', block.prefix='B', block.sizes =1:2, stratum='NONXX-Y2')
set.seed(87)
Mos6<-blockrand(n=295, id.prefix= 'Mos -', block.prefix='B', block.sizes =1:2, stratum='NONXX-Y3')

dataset_names <- list('XX-Y1' = Mos1, 'XX-Y2' = Mos2,
                      'XX-Y3' = Mos3, 'NONXX-Y1' = Mos4,
                      'NONXX-Y2' = Mos5,'NONXX-Y3' = Mos6)

As you see the block.size in the function is defined as "1:2", and since the number of treatment groups is 2 (it is not written, it is default), this code produces the actual block sizes of 2 and 4 (it is multiplied). But I want the produced block sizes to be 3 and 6, while the number of groups be still 2. This means that for example in a block of 3, we will have two group A and one group B (total=3). But I could not find out how this will work out, as when I set the "block.size=3:1.5", the produced block sizes are 6 and 4. And it never goes to 6 and 3. Could anybody can help?




I have an array of points, how can I draw them in a panel? [duplicate]

I have and array full of a random number of points, I want to draw them in my panel, how can I do it? there is some methods?? I searched around the internet but nothing.... Can I do it with the graphics2d class?

Hope my question is clear enough.




samedi 19 août 2023

Javascript: Inverting randomly generated colors

I'm making a random color generator and want it to give me multiple colors coresponding to other color theories, and am so far struggling with getting a complementary color, i've tried a few ways to invert it and have either put it in wrong, or it just did not work all together.

Here's one of the color generators, only diffrence from this one is a sleep() function i put in and the rest are numbered.

function Color(){
    var bg_colour = Math.floor(Math.random() * 16777215).toString(16);
    bg_colour = "#" + ("000000" + bg_colour).slice(-6);
    document.getElementById("displayColor").innerHTML = bg_colour;
    document.getElementById("displayColor").style.color = bg_colour;
}

Here is one of the others just incase it is important.

function Color2(){
    sleep(100)
        var bg_colour2 = Math.floor(Math.random() * 16777215).toString(16);
        bg_colour2 = "#" + ("000000" + bg_colour2).slice(-6);
        document.getElementById("displayColor2").innerHTML = bg_colour2;
        document.getElementById("displayColor2").style.color = bg_colour2;
    sleep(30)
}

Thanks in advance, i'll continue working on it in my free time and post any updates on if i found out something or if someone else did.




Make a Python variable update everytime the script runs

I've got a Python script that sends requests, it sends headers and data. I'm able to send, and its working. I've got a ONE of the headers that are being sent, a variable. That variable is being appended with a new character. My problem is, it only appends everytime I start the script, I need it to append everytime it sends and not have to restart the script everytime to send a newly generated item. I've pasted my code below

`

import requests
import string
import random
from time import sleep

RequestsSent = 0
i = 1

if(i > 0):
     input_string = "guest=guest_acc8a45cdf57f7a"
     alphabet = string.ascii_lowercase
     random_character = random.choice(alphabet)
     result_string = input_string + random_character

data = "xxxxxxxxxxxxx"

headers = {'xxxxx': 'xxxxx', 'xxxxx': result_string}

while(True):
     r=requests.post(url, data=data, headers=headers)
     #print(r.text)
     RequestsSent += 1
     i += 1
     print("Requests sent: " + str(RequestsSent))
     print("Sent guess ID: " + str(result_string))
     sleep(5)

`

Output:

Requests sent: 1 Sent guess ID: guest=guest_acc8a45cdf57f7f

Requests sent: 2 Sent guess ID: guest=guest_acc8a45cdf57f7f

Requests sent: 3 Sent guess ID: guest=guest_acc8a45cdf57f7f

If I restart the script, then will it generate a new guess ID

I've tried putting the append as a infinite While loop but then that just sits on that forever and doesn't send data, the if statement doesn't work either,




vendredi 18 août 2023

How to nest if/then/else statements into random list outputs?

I'm trying to create a system which picks randomly from a list, and then, depending on which string it picked, picks another random string from a seperate group, and then another one from there.

Basically, I'm trying to give it a bunch of paths and then, depending on what choice it makes, narrow the subsequent paths down two more times.

I've got the random code going, but I can't get it to accept if/then/else statements.

Here is my code. It works for its current purpose, which is generating one of those 4 letters randomly. But because it doesn't call a variable, it won't accept if/then/else statements. If I try to make a variable, it complains about being unable to convert the variable to Boolean, but if I define it as Boolean the entire code breaks.

package randomlist;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
    
public class Randomlist {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Random generate = new Random();
           String[] name = {"A", "B", "C", "D"};

           System.out.println(name[generate.nextInt(4)]);

String nesting =(name[generate.nextInt(4)]); 
if (nesting = "A") {
               Random generate = new Random();
           String[] name = {"E", "F", "G", "H"};
           }
           else if (nesting = "B") {
               Random generate = new Random();
           String[] name = {"I", "J", "K", "L"};
           }
    

        }
    }
           
    



An elegant replacement for numpy.random.choice in Tensorflow in this context

I have been programming a machine learning pipeline in Tensorflow 2.

Below is a code snippet implementing the sampling from a replay buffer in a policy gradient algorithm. A code similar to mine can be seen here. I feel the rest of the code would be too long and unnecessary for this question.

    def sample_buffer(self, batch_size):
        max_mem = tf.math.minimum(self.mem_cntr, self.mem_size)

        batch = np.random.choice(max_mem, batch_size)
        batch = tf.convert_to_tensor(batch, dtype=tf.int32)

        states = tf.gather(self.state_memory, batch)
        states_ = tf.gather(self.new_state_memory, batch)
        actions = tf.gather(self.action_memory, batch)
        rewards = tf.gather(self.reward_memory, batch)

        return states, actions, rewards, states_

This piece of code causes this error during execution - "NotImplementedError: Cannot convert a symbolic tf.Tensor (cond/Minimum:0) to a numpy array. This error may indicate that you're trying to pass a Tensor to a NumPy call, which is not supported."

I initialised the variables mem_cntr and mem_size as Pythonic integers, and originally the tf.math.minimum was simply a min, which gave an error ("OperatorNotAllowedInGraphError: Using a symbolic tf.Tensor as a Python bool is not allowed: AutoGraph did convert this function. This might indicate you are trying to use an unsupported feature.") Hence the use of tf.math.minimum even though I never initialised these two variables as Tensors.

I tried this code suggested in another Stackoverflow post. This code works in the Python interpreter in my terminal.

def select_indices_uniform(dims, num_indices, unique=False):
    # Create a tensor of probabilities
    size = tf.reduce_prod(tf.constant(dims, dtype=tf.int32)).numpy()

    # Use the uniform_candidate_sampler function to sample indices
    samples = tf.random.log_uniform_candidate_sampler(
            true_classes=[[0]], num_true=1, num_sampled=num_indices, unique=unique, range_max=size)

    # Extract the data and return it
    indices = tf.unravel_index(samples[0], dims)
    return indices

But the problem here is that eager execution does not work with my pipeline (so I can't use .numpy()), and using the Tensorflow v1.x compatible eval to try to evaluate the tensor to a numpy array fails due to a Graph execution error.

I can not think of another way to draw a fixed number of samples from these 4 tensors without this or numpy.random.choice. tf.boolean_mask and tf.random.categorical would be good ways to draw a random number of samples.

Is there any workaround?

Please help!




mercredi 16 août 2023

Making RGB value random for game?

I play a game (silly race game called Zero Gear) And i want to get a random RGB color every match i play. I managed to do this with the kart already by setting the value to an invalid ID, that randomizes it. But it does not work the same for RGB

A part of the code is as followed:

<Parameter name="CustomWheelColor1" type="STRING" data="r g b" />
<Parameter name="CustomWheelColor2" type="STRING" data="r g b" />
<Parameter name="CustomWheelColor3" type="STRING" data="r g b" />
<Parameter name="CustomWheelColor4" type="STRING" data="r g b" />

So for example data="255 255 255" would display a white wheel color

it reads the DATA RGB part. and i have NO idea how to get this so it is random ingame.

Might be impossible, idk but i had to try and ask!




mardi 15 août 2023

Python random.seed() without system time

I am making a game for a Thumby in Python. I am using the random library to generate a random y value for a sprite. The random.seed() value, if left untouched, uses the system time. The Thumby doesn't have a system time, so how would I go about generating a random number?

So far I have tried having a value constantly go up by 0.001 in the while true loop, then setting that as the seed every time the level is reset. That is not working too well, so I need some advice.




Hello! I have an array with a random value that keep's outputting it's address instead of a number [closed]

As the title say's I have an array with it's value randomized that won't stop outputting an address instead of number or any of the content's that it should. My problem initially was I was trying to fix an error I was getting because you can't compare with pointer's and integer's so I figured I could make the value that wasn't an array into one and that allowed me to finally run the program but overall it has only led me to this problem. I'm trying to make a game of roulette within a text adventure game so I am in fact a beginner. Here is the code related to it,

int usercash2 = usercash;

  int usercash4 = usercash;


  int ball[37] = {std::rand() % 36 + 1};//I think I solved this by simply making ball an array as well and therefore when comparing to other array's,it is not a comparison between pointer's and integer's [HYPOTHISIS]

  int r1st12[12] = {1,2,3,4,5,6,7,8,9,10,11,12};

  int r2nd12[12] = {13,14,15,16,17,18,19,20,21,22,23,24};

  int r3rd12[12] = {25,26,27,28,29,30,31,32,33,34,35,36};

  int r1_18[18] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18};

  int r19_36[18] = {19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36};

  int even[18] = {2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36};

  int odd[18] = {1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35};

  int black[18] = {1,3,5,7,9,12,14,16,18,19,21,23,25,27,30,32,34,36};

  int red[18] = {2,4,6,8,10,11,13,15,17,20,22,24,26,28,29,31,33,35};

  int r1stc[12] = {1,4,7,10,13,16,19,22,25,28,31,34};

  int r2ndc[12] = {2,5,8,11,14,17,20,23,26,29,32,35};

  int r3rdc[12] = {3,6,9,12,15,18,21,24,27,30,33,36};

  int userball{1};

  int betuserball;

  
  
  
  std::cout << "WHICH NUMER WOULD YOU LIKE TO BET ON?(1-36)\n\n";


  std::cin >> userball;

  std::cout << "HOW MUCH WOULD YOU LIKE WAGER ON THAT NUMBER?\n\n";

  std::cin >> betuserball;
  

  std::cout << "HOW MUCH WOULD YOU LIKE TO WAGER ON THE FIRST 12 NUMBERS (1-12)?\n\n";

  int bet1st12;

  std::cin >> bet1st12;

  if (bet1st12 < 0 || bet1st12 > usercash){

    while(bet1st12 < 0 || bet1st12 > usercash){

      std::cout << "INVALID INPUT!\n";

      std::cin >> bet1st12;

    }

  }

  usercash4 = usercash4 - bet1st12;

  std::cout << "HOW MUCH WOULD YOU LIKE TO WAGER AND THE 2ND ROW OF 12's (13-24)\n\n";

  int bet2nd12;

  std::cin >> bet2nd12;


  if (bet2nd12 < 0 || bet2nd12 > usercash4){

    while(bet2nd12 < 0 || bet2nd12 > usercash4){

      std::cout << "INVALID INPUT!\n";

      std::cin >> bet2nd12;

    }

  } 

  usercash4 = usercash4 - bet2nd12;

  std::cout << "HOW MUCH WOULD YOU LIKE TO BET ON THE 3rd ROW OF 12'S (25-36)\n\n";

  int bet3rd12;

  std::cin >> bet3rd12;

  if (bet3rd12 < 0 || bet3rd12 > usercash4){

    while(bet3rd12 < 0 || bet3rd12 > usercash4){

      std::cout << "INVALID INPUT!\n";

      std::cin >> bet3rd12;

    }

  }

  usercash4 = usercash4 - bet3rd12;


  std::cout << "HOW MUCH WOULD YOU LIKE TO WAGER ON THE FIRST HALF OF NUMBERS?(1-18)\n\n";

  int bet1_18;

  std::cin >> bet1_18;


  if (bet1_18 < 0 || bet1_18 > usercash4){

    while(bet1_18 || bet1_18 > usercash4){

    std::cout << "INVALID INPUT!\n\n";

    std::cin >> bet1_18;

    }

  }

  usercash4 = usercash4 - bet1_18;


  std::cout << "HOW MUCH WOULD YOU LIKE TO WAGER ON THE 2ND HALF OF NUMBER'S?(19-36)\n\n";

  int bet19_36;

  std::cin >> bet19_36;

  if (bet19_36 < 0 || bet19_36 > usercash4){

    while(bet19_36 < 0 || bet19_36 > usercash4){

    std::cout << "INVALID INPUT!\n";

    std::cin >> bet19_36;

    }

  }

  usercash4 = usercash4 - bet19_36;


  std::cout << "HOW MUCH WOULD YOU LIKE TO WAGER THE BALL BEING EVEN?\n\n";

  int beteven;

  std::cin >> beteven;


  if (beteven < 0 || beteven > usercash4){

    while(beteven < 0 || beteven > usercash4){

      std::cout << "INVALID INPUT!\n";

      std::cin >> beteven;

    }

  }

  usercash4 = usercash4 - beteven;


  std::cout << "HOW MUCH WOULD YOU LIKE TO BET ON THE BALL BEING ODD?\n\n";

  int betodd;

  std::cin >> betodd;

  
  if (betodd < 0 || betodd > usercash4){

    while(betodd < 0 || betodd > usercash4){

      std::cout <<  "INVALID INPUT!\n";

      std::cin >> betodd;

    }

  }

  usercash4 = usercash4 - betodd; 


  std::cout << "HOW MUCH WOULD YOU LIKE TO WAGER ON THE BALL LANDING ON BLACK NUMBER?\n\n";

  int betblack;

  std::cin >> betblack;


  if (betblack < 0 || betblack > usercash4){

    while(betblack < 0 || betblack > usercash4){

      std::cout << "INVALID INPUT!\n";

      std::cin >> betblack;

    }

  }

  usercash4 = usercash4 - betblack;


  std::cout << "HOW MUCH WOULD YOU LIKE TO WAGER THE BALL LANDING ON RED?\n\n";

  int betred;

  std::cin >> betred;


  if (betred < 0 || betred > usercash4){

    while(betred < 0 || betred > usercash4){

      std::cout << "INVALID INPUT!\n";

      std::cin >> betred;

    }

  }

  usercash4 = usercash4 - betred;


  std::cout << "HOW MUCH WOULD YOU LIKE TO WAGER ON THE 1ST COLUMN?(please look up what that is)?\n\n";

  int bet1stc;

  std::cin >> bet1stc;


  if (bet1stc < 0 || bet1stc > usercash4){

    while(bet1stc < 0 || bet1stc > usercash4){

      std::cout << "INVALID INPUT!\n";

      std::cin >> bet1stc;

    }

  }

  usercash4 = usercash - bet1stc;


  std::cout << "HOW MUCH WOULD YOU LIKE TO WAGER ON THE 2ND COLUMN?\n\n";

  int bet2ndc;

  std::cin >> bet2ndc;


  if (bet2ndc < 0 || bet2ndc > usercash4){

    while (bet2ndc < 0 || bet2ndc > usercash4){

      std::cout << "INVALID INPUT!\n";

      std::cin >> bet2ndc;

    }

  }

  usercash4 = usercash4 - bet2ndc;

  std::cout << "HOW MUCH WOULD YOU LIKE TO WAGER ON THE 3RD COLUMN?\n\n";

  int bet3rdc;

  std::cin >> bet3rdc;


  if (bet3rdc < 0 || bet3rdc > usercash4){

    while (bet3rdc < 0 || bet3rdc > usercash4){

      std::cout << "INVALID INPUT!\n";

      std::cin >> bet3rdc;

    }

  }



  int bet6 = bet1st12 + bet2nd12 + bet3rd12 + bet1_18 + bet19_36 + beteven + betodd + bet1stc + bet2ndc + bet3rdc + betblack + betred;//jesus all that damn typing...


  std::cout << "Bartender:Finally let's roll the ball!\n\n";

  for (int i=0;i < 16;i++){

    std::cout << "TICK!\n";

  }

  std::cout << "tick\n";

  std::cout << "tick..\n";

  std::cout << "TACK!\n\n";

  std::cout << "THE BALL HAS LANDED ON " << ball << "!\n\n";

  if (ball == r1st12){

    usercash == usercash + bet1st12;

  }

  else if (r1st12 != ball){

    usercash = usercash - bet1st12;

  }


  if (ball == r2nd12){

    usercash = usercash + bet2nd12;

  }

  else if (ball != r2nd12){

    usercash = usercash - bet2nd12;

  }

  if (ball == r3rd12){

    usercash = usercash + bet3rd12;

  }

  else if (ball != r3rd12){

    usercash = usercash - bet3rd12;

  }

  if (r1_18 == ball){

    usercash = usercash + bet1_18;

  }

  else if (ball != r1_18){

    usercash = usercash - bet1_18;

  }

  if (ball == r19_36){

    usercash = usercash + bet19_36;

  }

  else if (ball != r19_36){

    usercash = usercash - bet19_36;

  }


  if (ball == black){

    usercash = usercash + betblack;

  }

  else if (ball != black){

    usercash = usercash - betblack;

  }


  if (ball == red){

    usercash = usercash + betred;

  }

  else if (ball != red){

    usercash = usercash - betred;

  }


  if (ball == even){

    usercash = usercash + beteven;

  }

  else if (ball != even){

    usercash = usercash - beteven;

  }

  if (ball == odd){

    usercash = usercash + betodd;

  }

  else if (ball != odd){

    usercash = usercash - betodd;

  }


  if (ball == r1stc){

    usercash = usercash + bet1stc;

  }

  else if (ball != r1stc){

    usercash = usercash - bet1stc;

  }


  if (ball == r2ndc){

    usercash = usercash + bet2ndc;

  }


  else if (ball != r2ndc){

    usercash = usercash - bet2ndc;

  }


  if (ball == r3rdc){

    usercash = usercash + bet3rdc;

  }


  else if (ball != r3rdc){

    usercash = usercash - bet3rdc;

  }

  int usercash3 = usercash - usercash2;

  std::cout << "$" << bet6 << " IS HOW MUCH YOU BET TOTAL!\n\n";

  std::cout << "$" << usercash2 << " IS HOW MUCH YOU HAD BEFOREHAND\n\n";

  



number baseball game in javascript

I was making the number baseball game with javascript.

I got the random 3 numbers in my console based on the code I wrote.

And I want to use the function play for comparing the randomIndexArray which shown by computer randomly and the user input value.

However, I could see any numbers in my console after I put the 3 numbers in the input box.

Also, I want to put numbers like 123 and show to the console in array like [1, 2, 3]

How can I solve this?

let inputNumber = document.getElementById("input-number");
let goButton = document.getElementById("go-button");
let userInput = document.getElementById("user-input")
let resultArea = document.getElementById("result-area");
let triesArea = document.getElementById("tries-area");
let gameOver = false;

goButton.addEventListener("click", play);

let randomIndexArray = [];
for (i = 0; i < 3; i++) {
  randomNum = Math.floor(Math.random() * 10);
  if (randomIndexArray.indexOf(randomNum) === -1) {
    randomIndexArray.push(randomNum)
  } else {
    i--
  }
};
console.log(randomIndexArray);

function play() {
  let userValue = userInput.value;
  let strike = 0;
  let ball = 0;

  for (let i = 0; i < randomIndexArray.length; i++) {
    let index = userValue.indexOf(randomIndexArray[i]);
    if (index > -1) {
      strike++;
    } else {
      ball++;
    }

  }

}
play();
<div>number baseball game</div>
<div id="tries-area">tries: 5times</div>
<div id="result-area">result: 1strike 1ball</div>
<input id="user-input" type="number" placeholder="input 3 numbers among 0 to 9">
<button id="go-button">Go!</button>



HashMap extending to random length instead of 7 with for loop

I have two arrays for a card game one of type and another of color in Java. I want to run a for loop of length 7 to assert random values to the HashMaps which would be the card list for each player. But though I run the loop 7 times some Lists fill upto 5 while some upto 6. Here's the code:

static HashMap<String, String> p1=new HashMap<>(),p2=new HashMap<>(),p3=new HashMap<>(),u=new HashMap<>();
    
    public static void ini(){
        String [] colors = {"red", "green", "blue", "yellow"};
        String [] type = {"1","2","3","4","5","6","7","8","9","+2","+4","w","r"};
        Random r = new Random();
        for (int i = 0; i < 7; i++){
            p1.put(type[r.nextInt(type.length-1)],colors[r.nextInt(colors.length-1)]);
            p2.put(type[r.nextInt(type.length-1)],colors[r.nextInt(colors.length-1)]);
            p3.put(type[r.nextInt(type.length-1)],colors[r.nextInt(colors.length-1)]);
            u.put(type[r.nextInt(type.length-1)],colors[r.nextInt(colors.length-1)]);
        }           
    }
public static void main(String[] args){
        ini();
        System.out.println(p1);
        System.out.println(p2);
        System.out.println(p3);
        System.out.println(u);
    }

Any help would be grateful!

Expectation : 7 elements / List Outcome: 4 or 5 / List




lundi 14 août 2023

How do i solve this: sqlite3.ProgrammingError: Error binding parameter 1: type 'list' is not supported

Im doing a password generator and when i try to put the data from the variable password into the db i get this error, idk why im getting this. im using pysimplegui to build the interface . Can someone help me pls? im a beginner. the code is this

lower = "abcdefghijklmnopqrstuvwxyz"
    upper = lower.upper()
    numbers = "0123456789"
    symbols = "@"

    all = lower + upper + numbers + symbols
    length = int(ipt['crt'])
    
    password ="".join(random.sample(all, length))
    pc.copy(password)
    tb = ipt['site']
    tbb = [tb]
    cur.execute("INSERT INTO senhas(site, senha) VALUES(?, ?)",( tbb, password))
    print(tb)

the ipt's are the inputs that i made.

im trying to get this error solved so i can move on to finish the project.




Sums of random number reorderings combine to recurring values

g0 = randn(1, 100);
g1 = g0;
g1(2:end) = flip(g1(2:end));
sprintf("%.15e", sum(g0) - sum(g1))
g0 = np.random.randn(100)
g1 = g0.copy()
g1[1:] = g1[1:][::-1]
print(sum(g0) - sum(g1))

In both Python and MATLAB, rerunning these commands enough times will repeat the following values (or their negatives; incomplete list):

8.881784197001252e-15
3.552713678800501e-15
2.6645352591003757e-15
4.440892098500626e-16
1.7763568394002505e-15

In fact, the first and second time I ran them - mat -> py -> mat -> py - they were exactly same, making me think they share the RNG on system level with a delay... (but ignore this happened for the question).

I'll sooner fall through the floor than this coinciding, plus across different languages.

What's happening?


Windows 11, Python 3.11.4, numpy 1.24.4, MATLAB 9.14.0.2286388 (R2023a) Update 3,




dimanche 13 août 2023

Variable with x number of strings from list in Python

Say that I had a list containing 5 strings, and I wanted to print a random number of randomly generated strings from this list. Is there a simple way to do this?

I know multiple ways to print a single random string from this list, and multiple ways to print a set number of random strings from this set. The problem comes from wanting to print a random number of random strings from the list.

To get a set number of random strings (let's say 2) I would do the following:

 import random
 my_list = ['a','b','c','d','e']
 two_rand_strings = str(my_list[random.randint(0,4)]) + " " + str(my_list[random.randint(0,4)])
 print(two_rand_strings)

I assume I need to create some sort of function to generate a random number of strings but I am new to python and scratching my head.




how to generate a unique code without twin characters next to each other in python?

thank you for helping me whoever it is..

Here's my code

import random

FullChar = 'ABCDEFGHJKLMNPQRTUVWXY123456789'
total = 1000
counts = 8
count = int(counts)
entries = []

while (0 < 1) :
    for i in range(total):
        unique_code = ''.join(random.choice(FullChar) for j in range(count)) 
        entry = (unique_code)
        entries.append(entry)
    
    print(entries)
    entries.clear()

I want to generate a unique code using python, but with the condition that there can't be the same characters side by side and there can only be a maximum of 3 of the same digits, here I use python 3 with the random.choice method

Expected Unique Code

WHQUFUN0
ABABABUF
CN1EL1X1
H2HJEKAK

Unique code that's not allowed

WHQUUFN0
RXBBBHLW
CN1EL11B
E0CCFF9N



samedi 12 août 2023

Math.random() works on localhost, but always returns 0 on Hostinger

The purpose of this code is to change my coordinates slightly before posting them, for purposes of security. When I test the code on my WAMP localhost, I find it works as I intended. When testing on a live website, it behaves as if Math.random() is always returning 0.

var latitude =  randomize($(this).attr('Tlatitude'));  //get string from mysql and randomize

function randomize(angle){
    return `${(parseFloat(angle) + ((Math.random() -0.5 )* 0.006))}`;   //change it no more than 0.2 nm.
}

Any ideas? My live website troubleshooting skills are not highly developed.

Doug




vendredi 11 août 2023

Generating numbers in log-normal distribution not giving right parameters in return?

So I am trying to implement a function to generate random number following log-normal distribution myself. (Despite I am testing it in numpy, I need it for somewhere else where out of the box function is unavailable).

Using Box-Muller transform to generate Normally distributed random number and taking exponential of it (suggested in this question), and referring to Wikipedia page I come up with this code:


import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng()

def f():
    mean = 100
    sigma = 50

    u = np.log((mean * mean) / np.sqrt(mean * mean + sigma * sigma))
    d = np.log(1 + (sigma * sigma) / (mean * mean))

    u1 = 0
    while u1 <= 0.0000001:
        u1 = rng.random()
    u2 = rng.random()

    mag = d * np.sqrt(-2 * np.log(u1))
    z0 = mag * np.cos(2 * np.pi * u2) + u
    z1 = mag * np.sin(2 * np.pi * u2) + u

    return (np.exp(z0), np.exp(z1))

iteration = 100000

data = []
for i in range(0, iteration):
    x = f()
    data.append(x[0])
    data.append(x[1])

fig, ax = plt.subplots()
ax.hist(data, bins=100) 

print('mean: ' + str(np.mean(data)))
print('median: ' + str(np.median(data)))
print('stdev: ' + str(np.std(data)))

However, the generated values does not have the right mean and stdev, even though the shape seems to be vaguely correct. Does I miss anything? Or is it just some floating point shenanigans?

matplotlib histogram plot




How can I access the buffer of CryptGenRandom?

This question is inspired by this answer on Crypto SE.

According to Niels Ferguson's Whitepaper called 'The Windows 10 random number generation infrastructure', the CryptGenRandom algorithm uses a buffer for small requests:

All PRNGs in the system are SP800-90 AES_CTR_DRBG with 256-bit security strength using the df() function for seeding and re-seeding (see SP 800-90 for details). (…) The Basic PRNGs are not used directly, but rather through a wrapping layer that adds several features.

  • A small buffer of random bytes to improve performance for small requests.
  • A lock to support multi-threading.
  • A seed version.

(…) The buffering is straightforward. There is a small buffer (currently 128 bytes). If a request for random bytes is 128 bytes or larger, it is generated directly from AES_CTR_DRGB. If it is smaller than 128 bytes it is taken from the buffer. The buffer is re-filled from the AES_CTR_DRBG whenever it runs empty. So, if the buffer contains 4 bytes and the request is for 8 bytes, the 4 bytes are taken from the buffer, the buffer is refilled with 128 bytes, and the first 4 bytes of the refilled buffer are used to complete the request, leaving 124 bytes in the buffer.

I would like to know if it is possible to access this buffer from my Windows 10 laptop, and if so how I can implement this.

I looked at the Windows page of CryptGenRandom, and this page does also mention a buffer which is given as input. However, this is a different buffer from the one in the whitepaper: in this buffer, the output bytes will be written. Therefore, the buffer has a different size and purpose than the buffer that I am interested in.




Access an application running on in minikube with istio inside an EC2 instance from outside world

I have an EC2 instance say its IP is 13.XX.XX.XX (Say IP1), I have an minikube which is running inside this EC2 instance say its IP is 10.XX.XX.XX (Say IP2) , which I came to know by doing minikube ip inside EC2 instance . I have an application running inside minikube . I am able to curl to application by doing curl http://IP2

I am using simaple istio-sample application for testing I have configured below with details ubuntu@ip:~/istio-1.18.2$ kubectl get pods --all-namespaces NAMESPACE NAME READY STATUS RESTARTS AGE default details-v1-698b5d8c98-h5tbb 2/2 Running 0 24m default productpage-v1-75875cf969-zv858 2/2 Running 0 24m default ratings-v1-5967f59c58-5wwx2 2/2 Running 0 24m default reviews-v1-9c6bb6658-tb8rp 2/2 Running 0 24m default reviews-v2-8454bb78d8-rrtl8 2/2 Running 0 24m default reviews-v3-6dc9897554-h6h5n 2/2 Running 0 24m istio-system istio-egressgateway-57f9b4cdf5-tdbj8 1/1 Running 0 74m istio-system istio-ingressgateway-54f4b997fc-grnqz 1/1 Running 0 74m istio-system istiod-5489dc5cb7-mk5gd 1/1 Running 0 75m kube-system coredns-64897985d-ffjkq 1/1 Running 0 76m kube-system etcd-ip-172-xx-xx-xxx 1/1 Running 3 77m kube-system kube-apiserver-ip-172-xx-xx-xxx 1/1 Running 3 77m kube-system kube-controller-manager-ip-172-xx-xx-xxx 1/1 Running 3 77m kube-system kube-proxy-97gr2 1/1 Running 0 76m kube-system kube-scheduler-ip-172-xx-xx-xxx 1/1 Running 3 77m kube-system storage-provisioner 1/1 Running 0 77m ubuntu@:~/istio-1.18.2$ kubectl get svc --all-namespaces NAMESPACE NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE default details ClusterIP 10.106.199.96 9080/TCP 24m default kubernetes ClusterIP 10.96.0.1 443/TCP 77m default productpage ClusterIP 10.104.163.184 9080/TCP 24m default ratings ClusterIP 10.97.82.158 9080/TCP 24m default reviews ClusterIP 10.105.167.84 9080/TCP 24m istio-system istio-egressgateway ClusterIP 10.103.41.18 80/TCP,443/TCP 75m istio-system istio-ingressgateway LoadBalancer 10.106.66.152 15021:31706/TCP,80:31892/TCP,443:30491/TCP,31400:30512/TCP,15443:31409/TCP 75m istio-system istiod ClusterIP 10.96.231.111 15010/TCP,15012/TCP,443/TCP,15014/TCP 75m kube-system kube-dns ClusterIP 10.96.0.10 53/UDP,53/TCP,9153/TCP 77m ubuntu@:~/istio-1.18.2$ kubectl get nodes --all-namespaces NAME STATUS ROLES AGE VERSION ip-172-xx-xx-xxx Ready control-plane,master 77m v1.23.3

But I want to access this application out side ec2 through any other PC . How to do this , I tried doing http://IP1 but it didnit work

I tried a lot but can't find solution.




jeudi 10 août 2023

How to return objects from array in random order on every render?

I have an array with N numbers of element. For example this one:

let i = 0;
while(i <= 40){
    console.log(i++)
}

This will always return list of numbers from 0 to 40,what I want to achieve is to order numbers in random order every time I run the function.




Can PRNG in laptop lose quality?

I have an Ideapad Gaming laptop by Lenovo, with an Intel(R) Core(TM) i5-10300H processor. On this laptop I have Windows 10 installed. Is it possible that the built-in PRNG (CryptGenRandom) loses quality after a number of years? With this I mean, that the algorithm becomes less random/a bit predictable.




mercredi 9 août 2023

Why is python random module returning smaller numbers than expected?

I am programming a twitch bot, and am trying to use the random module to select a random number for determining whether a move hits or not in a chat game I am making. The problem I am running into is that, despite the fact that I want the function to generate a number between 1 and 100, it will only ever generate numbers below 50, and I have no idea why. Yes, I've ran the code many many times to make sure I'm not just unlucky. I've looked for people with similar problems online, and haven't had any luck. Am I using the module improperly? is there some software on twitch's end interfering? I apologize if this question has been answered somewhere else, but I couldn't find it.

def Execute(data):
    if data.IsChatMessage() == False:
        return
    if data.GetParam(0).lower() == "!roll":
        DiceRoll=random.randint(1,100)
        Parent.SendStreamMessage(str(DiceRoll))

Since I am programming a streamlabs twitch chat bot, there are certain commands that streamlabs has built in, such as getting parameters from twitch chat messages and sending stream messages. The issue is that, when running this function, the bot will always respond with a number less than 50. Does anyone understand why? (As a side note, it also seems to perform exclusively floor division. For example, 13/2 and 13//2 both return 6, perhaps hinting at some error in the streamlabs chatbot software? I am new to this and really don't know tbh. I discovered this while trying to get around the bugged random module by checking for even vs odd instead of for how big the number was, but that also failed due to the weird division)

Edit: as was requested, I have added my code which returned averages of 24, 27, and 26.

def Execute(data):
    avr=0
    if data.IsChatMessage() == False:
        return
    if data.GetParam(0).lower() == "!bive":
        DiceRoll=random.randint(1,100)
        Parent.SendStreamMessage(str(DiceRoll))
        
        for i in range(100):
            avr+=random.randint(1,100)
        avr=avr/100
        Parent.SendStreamMessage(str(avr))



Resample and select a given number of rows and calculate the mean, variance and confidence intervals?

I need to select a especific number of rows per resampling from 4 to 50 rows.

So, in the first run I need that the function select 4 random rows and calculate the mean, variance and confidence intervals for a given variable and this has to be done 1000 times. The second run I need the same thing, but instead of selecting 4 rows I need that selct 5 random rows 1000 times... until 54 rows.

The example:

x1 <- matrix(rnorm(200,mean=10), nrow= 100, ncol=2)
x2 <- c(replicate(5, "AA"),replicate(15, "BB"),replicate(15, "CC"),
        replicate(10, "DD"),replicate(10, "EE"),replicate(10, "FF"),
        replicate(10, "GG"),replicate(5, "HH"),replicate(5, "II"),
        replicate(15, "JJ"))
df <- data.frame(cbind(x1,x2))
colnames(df) <- c("variable1", "variable2","group")

I'm running these code below, manually, and it is seems that is right.

samples <- vector(mode="list", length=1000)
for (i in 1:1000){
  samples[[i]]=sample(as.numeric(df$variable1),size=4,replace=F)
}

# funtionc to calculate confidence interval
conf <- function(x) {
  error <- qnorm(0.975)*sd(x)/sqrt(length(x))
  return (data.frame("lower" = mean(x)-error,
                     "upper" = mean(x)+error))
}

# calculating mean, variance and confidence interval of the simulations

mean1 <- lapply(samples,mean) # calculating the mean of these 4 select rows per simulation
mean2 <- unlist(mean1) # unlist the list of the means values
mean_4rows <- mean(mean2) # the total mean of the randomly selected rows

var1 <- lapply(samples,var) # calculating the var of these 4 select rows per simulation
var2 <- unlist(var1)
var_4rows <- var(var2) # the total variance of the randomly selected rows

conf1 <- lapply(samples,conf) # calculating the var of these 4 select rows per simulation
conf2 <- unlist(conf1)
conf_4rows <- conf(conf2) # the total conf interval of the randomly selected rows

However, I have to automate this code, to be able to run it so that I can select from 4 to 50 random rows (1000 times each number of rows selection) and calculate the mean, variance and CIs of the simulations.

In the end I would like a object with the total means, variance and CIs for the number of selected rows generated by the simulations,with the rows refering to the selection of 4 rows, and 5 selected random rows.... etc until 50 rows:

#>    rows  meanSim varianceSim  lowerCISim   upperCISim
#>    4     1.84     0.410        0.105       0.300
#>    5     1.69     0.951        1.023       2.098  
#>    6     1.99     0.714        1.234       1.987
#>   ..... 
#>    50    2.58     0.242        2.098       2.999

Any idea on how I can make this automated and save these results?

Thank you!




mardi 8 août 2023

Why does sorting my array always make the first two index values a zero?

What I am trying to get is a random number generator that will produce five lines of 5 random numbers 1 through 70 and one more number 1 through 25 like a mega millions ticket.

import java.util.Arrays;
import java.util.Collections;
import java.util.Random;

public class MegaMillions {
    
    public void play() {
        Random rand = new Random();
        int[] numbers = new int[5];
        for(int i = 0; i < 5; i++) {
            numbers[i] = rand.nextInt(69) + 1;
            Collections.shuffle(Arrays.asList(numbers));
            Arrays.sort(numbers);
            System.out.print(numbers[i] + " ");
        }
        Collections.shuffle(Arrays.asList(numbers));
        int megaBall = rand.nextInt(24) + 1;
        System.out.println("(" + megaBall + ")");
    }

}

Here is an example of what I'm getting:

0 0 21 21 35 (1)

0 0 16 26 32 (9)

0 0 39 39 53 (3)

0 0 22 37 51 (14)

0 0 18 18 60 (14)

My understanding was that Collections.shuffle should take care of any repeating integers and Arrays.sort should put in numerical order.




Get entropy for random number generator in Golang [closed]

I'm looking for a best way to provide entropy for my random number generator. As far as I understand it is secure to use /dev/random on Linux machine for the entropy source and not as much secure to use /dev/urandom.

If use "crypto/rand" Reader for entropy it can automatically use /dev/urandom. And I wasn't able to find a lib that would use only /dev/random.

Maybe someone can advise a good one or a different approach? Having entropy estimation test from NIST 800-90b included would be perfect!

|https://ift.tt/eU4cY3V

Thanks!




control is matching values of next answer on clicking submit button |php Quiz |random ques quiz| random array quiz & answer matching

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Bootstrap demo</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9" crossorigin="anonymous">
</head>

<body>
  <div class="container">

    <div class="card mt-5">
      <div>
        <h1 class="text-center alert bg-warning">let's Play Quiz</h1>
      </div>
      <div class="card-body">
        <!-- php code for quiz ques ans here -->
        <h5 class="card-title text-center">
         **<?php

          // quesionsssss
          $ques = array(
            "q1" => "Ques:What is currency of India?",
            "q2" => "Ques:Which is the most populated state in India?",
            "q3" => "Ques:Which city is financial capital of India?",
            "q4" => "Ques:Which state has the largest land area ?",
            "q5" => "Ques:Which state is most literate?"
          );
          // answersss
          $answers = array(
            "q1" => "rupee",
            "q2" => "Uttar Pradesh",
            "q3" => "Mumbai",
            "q4" => "rajasthan",
            "q5" => "Kerala"
          );
          $q = array_rand($ques);
          $questions = $ques[$q];
          echo $questions;
          //answer_key
          $ans_key = $answers[$q];
          ?>
**        </h5>
        <form action="" method="post">
          <input type="text" name="ans" required placeholder="Enter your answer here" class="mx-auto my-2 d-block">
          <br>
          <input type="submit" value="Submit Answer" name="subbtn" class="btn btn-warning btn-sm d-block mx-auto">
        </form>
      </div>
      <div class="card-footer bg-warning">
        <small class="text-dark">
        
**  <?php
if (isset($_REQUEST["subbtn"])) {
#             $user_input = $_REQUEST["ans"];
#             $f = strcasecmp($ans_key, $user_input);
if ($f == 0) {
echo "Congratulations";
else {
echo "Better luck Next Time";
#             }
#           }


#           ?>**
        </small>

      </div>
    </div>


</body>


</html>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js" integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/js/bootstrap.min.js" integrity="sha384-Rx+T1VzGupg4BHQYs2gCW9It+akI2MM/mndMCy36UVfodzcJcF0GGLxZIzObiEfa" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-HwwvtgBNo3bZJJLYd8oVXjrBZt8cqVSpeBNS5n7C8IVInixGAoxmnlMuBnhbgrkm" crossorigin="anonymous">
</script>

i am expecting to get congratulations message on correct answer and error message on wrong answer.

the ques change everytime page refreshes and same functionality every time.

everytime if enter answer the user input is matched with next answers please help to fix this.

here is how it works

The HTML structure is set up with Bootstrap classes for styling and responsiveness. PHP arrays are used to store quiz questions ($ques) and their corresponding answers ($answers). The code selects a random question from the array using array_rand() and displays it along with an input field for the user's answer. When the user submits their answer, the code compares the user's input with the correct answer ($ans_key) using strcasecmp(), which performs a case-insensitive string comparison. Based on the comparison result, a message is displayed to the user, either "Congratulations" for a correct answer or "Better luck Next Time" for an incorrect answer.




lundi 7 août 2023

x=random(0,2) TypeError: 'module' object is not callable [closed]

import random
x=random(0,2)
print (x)
TypeError: 'module' object is not callable

random module is not callable

why i am getting this error please help

Traceback (most recent call last):
  File "C:\Users\never\Desktop\python-code\demo.py", line 2, in <module>
    x=random(0,2)
TypeError: 'module' object is not callable

Process finished with exit code 1

please




Merge sort performing slower if list comes from a file

When performing a merge sort in two lists, both lists having 10000 random integers, but one of the lists have its values being read from a file, and other being randomly generated by java. My problem is, why the mergeSort() is way slower when the list values comes from a file?

First I though that the problem was with the file reading, but the list and its values are created relatively fast(10ms), the slowness begins in the mergeSort(), and I don't know why one is faster than the other.

Main.java

public class Main {

    public static void main(String[] args) throws NumberFormatException, IOException {
        ForkJoinPool pool = new ForkJoinPool();
        String filePath = "10000.txt"; 
        Vector<Integer> listFromFile = new Vector<Integer>();
        Vector<Integer> listRandom = new Vector<Integer>();
        Random rand = new Random();
        FileInputStream fis = new FileInputStream(filePath);
        BufferedReader reader = new BufferedReader(new InputStreamReader(fis));

        //10 ms
        for (int i = 0; i < 100000; i++) {
            int num = rand.nextInt();
            listRandom.add(num);
        }

        String line;
        while ((line = reader.readLine()) != null) {
            listFromFile.add(Integer.parseInt(line)); 
        }

        Instant start = Instant.now();

        //way faster 400 ms
        MergeSort sort = new MergeSort(listRandom);

        //slower 37000 ms
        MergeSort sort = new MergeSort(listFromFile);


        Vector<Integer> result = pool.invoke(sort);
        Instant end = Instant.now();
        Duration timeElapsed = Duration.between(start, end);
        System.out.println("Time taken: "+ timeElapsed.toMillis() +" milliseconds");
    }
}

MergeSort.java

public class MergeSort extends RecursiveTask<Vector<Integer>> {
    private final Vector<Integer> list;

    public MergeSort(Vector<Integer> list) {
        this.list = list;
    }
    
    
    @Override
    protected Vector<Integer> compute(){
        if (list.size() <= 1) {
            return list;
        }
        Vector<Integer> left = new Vector<Integer>();
        Vector<Integer> right = new Vector<Integer>();

        for (int i = 0; i < list.size(); i++) {
            if (i < list.size() / 2) {
                left.add(list.get(i));
            } else {
                right.add(list.get(i));
            }
        }

        MergeSort _left = new MergeSort(left);
        MergeSort _right = new MergeSort(right);

        _left.fork();
        _right.fork();

        Vector<Integer> leftSorted = _left.join();
        Vector<Integer> rightSorted = _right.join();
        
        
        return merge(leftSorted, rightSorted);
        
    }

    static Vector<Integer> merge(Vector<Integer> left, Vector<Integer> right) {
        Vector<Integer> result = new Vector<Integer>();

        while (!left.isEmpty() && !right.isEmpty()) {
            if (left.get(0) <= right.get(0)) {
                result.add(left.get(0));
                left.remove(0);
            } else {
                result.add(right.get(0));
                right.remove(0);
            }
        }
        while (!left.isEmpty()) {
            result.add(left.get(0));
            left.remove(0);

        }
        while (!right.isEmpty()) {
            result.add(right.get(0));
            right.remove(0);
        }

        return result;
    }
}




dimanche 6 août 2023

How do you code the creation of fixture lists for a sports league?

I'm trying to write a program that generates a fixture list for a sports league. If each team played each other home and away like in the English Premier League, this would be easy (expand_grid() or crossing() would be perfect), but this one is more complex.

I have a 17-team competition where each team plays 24 matches (12 at home and 12 away) for a total of 204 matches across the season. Each team will play 8 teams twice (home and away) and the other 8 teams only once (four at home and four away).

I cannot for the life of me work this out. All my attempts have basically started like this:

library(tidyverse)

# 17 team names
teams <- c(paste("Team", LETTERS[1:17]))

# Combinations of different teams
matches <- expand_grid(home = teams, away = teams) |>
  filter(home != away)

The issue now is that I don't know how to filter this down so each team will have only the 24 games. My focus on getting it to work for a given team obviously affects the number of matches the other team in the matchup is involved in. I don't know how to control this. I've tried sampling methods but this is giving me variability in how many games each team is left with.

Do any of you rstats geniuses out there know how to crack this?

Appreciate any help!




samedi 5 août 2023

getting -5200 while use wxTimer

Im making a simple program where the user can start and stop a timer to set a reminder, my issue is after the user stops the timer and restarts it the timer goes to -5200. This is not the intent. Also For my random number generator I am getting very high negative values.


void MainFrame::OnStartClicked(wxCommandEvent& evt)
{
    wxColour LightGreen(144, 238, 144);
    Start->SetBackgroundColour(LightGreen);
    Stop->SetBackgroundColour(wxNullColour); //sets stop back to default color
    SetStartProgram(true);
    if (!timer->IsRunning()) // Check if the timer is not already running
    {
        if (!optionsWindow) // Check if optionsWindow is nullptr
        {
            optionsWindow = new OptionsWindow("Time Settings");
            optionsWindow->Show(true);
            // Bind an event handler to catch when the OptionsWindow is closed.
            optionsWindow->Bind(wxEVT_CLOSE_WINDOW, &MainFrame::OnOptionsWindowClosed, this);
        }

        if (optionsWindow->GetRandomStatus() == true) {
            // Creating random number between 1 and 60
            std::random_device rd;
            std::mt19937 gen(rd());
            std::uniform_int_distribution<int> dist(1, 60);
            int randomNumber = dist(gen);

            int randomMilliseconds = randomNumber * 60000; // Convert the random number to milliseconds

            timer->Start(randomMilliseconds);
            wxLogMessage("Timer started with random interval: %d milliseconds", randomMilliseconds);
        }
        else {
            int reminderMilliseconds = optionsWindow->GetReminderTime() * 60000; // Convert the reminder time to milliseconds
            

            timer->Start(reminderMilliseconds);
            wxLogMessage("Timer started with interval: %d milliseconds", reminderMilliseconds);
        }

        Start->Disable();
    }

    evt.Skip();
}


void MainFrame::OnStopClicked(wxCommandEvent& evt)
{
    wxColour LightRed(255, 71, 71);
    Stop->SetBackgroundColour(LightRed);
    Start->SetBackgroundColour(wxNullColour); //sets start back to the default color
    SetStartProgram(false);

    if (timer->IsRunning()) {
        // If the timer is running, stop it.
        timer->Stop();
        
    }
    Start->Enable(); // Enable the "Start" button when the timer is stopped
    evt.Skip();
}



how do i assign randomly assign accounts into 3 groups that is similar by way of average spend, total spend, and frequency of spend

I have a some sample sales transactions by accounts, and would like to do a test and learn on 3 groups. I'd like the assign 3 groups to all the unique account ids and have them to be as similar as possible so the trial can be without selection bias. The bias could be in by frequency of transaction, average spend, and total spend.

I was considering using a quantile function i.e. mutate ntile for 5 bins based on sale_amount then subsequently group by and sample_n.

If i'm on the right track, is there an elegant way to parameterize this into a function to ensure i select the minimum accounts available in each stratified quantile group depending on the number of cohort required?

Appreciate your help with your methods in R.

# Load required libraries
library(dplyr)
library(lubridate)


# Set the start and end dates
start_date <- as.Date("2023-01-01")
end_date <- as.Date("2023-03-31")

# Number of accounts
num_accounts <- 90


# Function to generate random transactions and sale amounts for each day
generate_random_transactions <- function(date) {
  num_transactions <- sample(1:5, 1)  # Random number of transactions per day (1 to 5)
  sale_amounts <- runif(num_transactions, min = 10, max = 500)  # Random sale amount between 10 and 500
  transactions <- data.frame(date = date, sale_amount = sale_amounts)
  return(transactions)
}
set,seed(1)
# Generate transactions for each day within the specified date range for all accounts
all_transactions <- lapply(seq(start_date, end_date, by = "day"), generate_random_transactions)
all_transactions <- do.call(rbind, all_transactions) %>% tibble

# Assign random account numbers to each transaction
all_transactions$id <- 
  sample(1:num_accounts, nrow(all_transactions), replace = TRUE)

# Display the first few rows of the resulting transactions
all_transactions
all_transactions %>% 
  mutate(quantile = ntile(sale_amount,5)) %>% 
  group_by(quantile) %>% 
  summarise(acct_n=n_distinct(id),
            freq_n = n(),
            amt_mean=mean(sale_amount),
            amt_min=min(sale_amount),
            amt_max=max(sale_amount))
# A tibble: 5 × 6
  quantile acct_n freq_n amt_mean amt_min amt_max
     <int>  <int>  <int>    <dbl>   <dbl>   <dbl>
1        1     40     52     71.8    10.7    128.
2        2     39     52    178.    130.     230.
3        3     40     52    281.    233.     331.
4        4     37     52    376.    332.     420.
5        5     41     51    462.    421.     499.



Snail number random code# Object oriented paradigm

create method draw(int min_size,int max_size) by Figure method will be created with details It is a figure that consists of 4 sub-pictures. All sub-pictures will have the size caused by Randomize the size between min_size and max_size values. All 4 sub-figures may have the same pattern or different patterns depending on randomness. picture pattern

enter image description here

enter image description here




vendredi 4 août 2023

Argument of type "list[str]" cannot be assigned to parameter "__value" of type "str" in function "index". How do I fix this?

I have been programming a type based combat game - think of it a bit like Pokemon. In order to win a round and hit the opponent, the computer roles a virtual 6 sided dice for each player and the highest roll wins.

There are different advantages you can obtain, one being a "wizard" that increases your chances on rolling a higher number.

As I'm relatively new to python, the use of "random.choices" and the weight argument was the only way I could think to achieve the higher probability rolls. However, this has led to the issue where, when I try to return the value, it produces the error that the value has to be a string or number not in a list:

def wizardSpeed():
    dice_num = [1, 2, 3, 4, 5, 6]
    probability = [0.25, 0.45, 0.65, 0.85, 0.9, 0.85]
    dice_roll = random.choices(dice_num, probability)
    return dice_roll

I tried to fix this (with my limited knowledge :/) by obtaining the position of the value in the list, then converting the one value in that position to an integer before returning it. I then got a similar error (one in title):

def wizardSpeed():
    dice_num = ["1","2", "3", "4", "5", "6"]
    probability = [0.25, 0.45, 0.65, 0.85, 0.9, 0.85]
    dice_roll = random.choices(dice_num, probability)
    position = dice_num.index(dice_roll)
    result = int(dice_num[position])
    return result

Is there a way to fix this? I am trying to take one value from the list to be used as an integer in a variable later in the program.




Jax: generating random numbers under **JIT**

I have a setup where I need to generate some random number that is consumed by vmap and then lax.scan later on:

def generate_random(key: Array, upper_bound: int, lower_bound: int) -> int:
    ...
    return num.astype(int)

def forward(key: Array, input: Array) -> Array:
    k = generate_random(key, 1, 5)
    computation = model(.., k, ..)
    ...

# Computing the forward pass
output = jax.vmap(forward, in_axes=.....

But attempting to convert num from a jax.Array to an int32 causes the ConcretizationError.

This can be reproduced through this minimal example:

@jax.jit
def t():
  return jnp.zeros((1,)).item().astype(int)

o = t()
o

JIT requires that all the manipulations be of the Jax type.

But vmap uses JIT implicitly. And I would prefer to keep it for performance reasons.


My Attempt

This was my hacky attempt:

@partial(jax.jit, static_argnums=(1, 2))
def get_rand_num(key: Array, lower_bound: int, upper_bound: int) -> int:
  key, subkey = jax.random.split(key)
  random_number = jax.random.randint(subkey, shape=(), minval=lower_bound, maxval=upper_bound)
  return random_number.astype(int)

def react_forward(key: Array, input: Array) -> Array:
  k = get_rand_num(key, 1, MAX_ITERS)
  # forward pass the model without tracking grads
  intermediate_array = jax.lax.stop_gradient(model(input, k)) # THIS LINE ERRORS OUT
  ...
  return ...

a = jnp.zeros((300, 32)).astype(int)
rndm_keys = jax.random.split(key, a.shape[0])
jax.vmap(react_forward, in_axes=(0, 0))(rndm_keys, a).shape

Which involves creating the batch_size # of subkeys to use at every batch during vmap (a.shape[0]) thus getting random numbers.

But it doesn't work, because of the k being casted from jax.Array -> int.

But making these changes:

-  k = get_rand_num(key, 1, MAX_ITERS)
+  k = 5 # any hardcoded int

Works perfectly. Clearly, the sampling is causing the problem here...




How to generate a periodic, unpredictable, verifiable random number?

I would like a random number for a program with the following qualities:

  1. Periodic: The random number needs to be random for a certain window of time. Preferably hourly but could be more. Once the period is over, the next random number can be generated and previously generated values can be regenerated based on seed values which are publicly available.

  2. Unpredictable: The next random number cannot be easily determined. The publicly available seed must not be public yet.

  3. Verifiable: The seed for the random number should come from some publicly available source. Perhaps a scientific research organization or government body is publishing a daily or hourly number(s). For example, a group of temperatures that are recorded. Or for example, it could be as simple as a website that publishes hourly or daily random numbers.

  4. Seed should be at least a 64 bit integer. If it's too small then the random number could be guessed from a small set.

  5. Industrial-strength or exacting randomness is not required. Not interested in extreme, high-precision randomness.

I see https://avkg.com/ generates large, daily random numbers and this is actually very close and if nothing else looks better I will probably use it. Especially since it archives past results and so that satisfies the verifiable requirement. The problem is the site does not have a clean and documented API and it's not hourly. HTML scraping for this information is not ideal.

Another idea I had was to use a hash of a specific group of people's latest Tweets (X). Doing something like this would allow for verification. The problem is I don't know if they will tweet daily or hourly. Also, Elon has now made Twitter (X) non-public so you need to sign in to gather this information.

Another idea is to just create a my own version of AVKG.

Of course, a date will not work since that does not satisfy the above unpredictable requirement.

Any ideas?

Thank you so much.




How to create a function that generate a random number but following a specific distribution

I like to create data visualizations, but I often need to generate data, and i find the random normal distribution too "boring".

I would like to create a generator of random values that follows a specified distribution.

My idea is to use a graph editor such as:

https://observablehq.com/d/ac77643d0cd9422e

From this editor i have a function distribution(x) that return the y value on the graph.

And i would like to create a distributor(distribution) function that return a random value, but the value has more "chance" to be a x if the y on the graph is high.

I have no idea how to achieve that.

Does someone have any idea how I can proceed?

Thanks




jeudi 3 août 2023

How to assign array values to the n-1 location in the array

I have an array like this: [1, 2, 3, 4, 5]. I shuffle it to get this: [1, 5, 4, 2, 3].

The Goal: Assign each value in the array to the n-1 location in the array

In other words, I need the number 1 to be in 1st position, 2 in 5th, 3 in 4th, 2 in 5th, and 3 in 6th.

For example, the output of this one would be: [1, 4, 5, 3, 2].

Is there a built in function for this or a simple code that can accomplish this goal?

What I've done so far:

import numpy as np
import random
array = np.arange(1,6)
print(array)
random.shuffle(array)
print(array)



mercredi 2 août 2023

Why do I get an error In Accessing File for Bash Code

I Wanted to Make A Game To Just Spend Some Time Improving My Programming Skills.. I Got An Error, I tried Every Thing To Try To Fix It, Is There Any Solution? This is The Code

random=$((1 + $RANDOM % 10))
read -p "Enter A UserName" name
if [ -d $name ]
then
    cd $name
    if [ -d Scores ]
    then
        cd Scores
        else
                mkdir Scores
                cd Scores
                cd ../../
    fi
else
    mkdir $name
    cd $name
    mkdir Scores
    cd Scores
    cd ../../
fi
echo 'enter a random number'
read -p "Enter" r
if [ $r = $random ]
then
        echo 'great' $name
else
        echo 'nope' $name 'the number was' $random
fi

echo 'want to play again(y for play again n for dont play again)'
read m
if [ $m = y ]
then
        chmod +x AnswerDebug.sh
    bash AnswerDebug.sh
elif [ $m = n ]
then
        echo 'end of game'
else
echo 'not an input' $name
fi

The Output Was : The Output

I was programming a game where we have to find a random number. I tried to make a Scoring System but it is unfinished

I expected it to work finely but for some reason the code isn't working The code can't access AnswerDebug.sh(The Name Of The File)




I have no idea how to start this homework assignment. Can someone help guide me in a general direction?

Assignment Here

Hello everyone, Im a first year ICS 111 and we are currently on the topic of For and While loops. I attended the class and even rewatched the hour long lecture about 3 times now and have no idea where to even begin trying to work on this. So far, I've only just initialized the random numbers and Im trying to figure out how to start on my loop. I think im supposed to use a while loop since it's not specified how many times i would have to run this. The other assignments are not even close to what this one was, they were mostly straight forward from the lesson. Any sense of direction would help, I am completely lost. Thank you.

So far ive tried using a random int from -100 to 100, seeing as how north is positive and south would minus, however, I realized that since they are walking, it would only increase or decrease the X or Y coordinate one at a time, thus making that useless as it created random numbers like 50 or -11.




How to save the last RANDOM generated number in a loop

**I am trying to make the user go back to the position he was on if he gets higher than 100. So if he was on 97 and rolls a 5 on Dice1 and becomes 102 I want the variable position1 to go back to 97 I am still new so it might just be a stupid logic problem also my variable names are not industry standard so im still working on this **

     Scanner Scan = new Scanner(System.in);
     Random random = new Random();
     int Position1 = 0;
     //int position2 = 0;
    
     
     System.out.println("Type Start");
     String Input = Scan.next();

  
      if (Input.equals("start")){
         
         while(Position1!=100 ) {
            
             int Dice1 = random.nextInt(1,7);
            
 
             if (Dice1 == 6) {
                 Position1= Position1+Dice1;
                 System.out.println(Position1);
                 System.out.println("player 1 turn ");
                 Input = Scan.next();

             }
             else if (Dice1 == 5) {
                 Position1= Position1+Dice1;
                 System.out.println(Position1); 
                 System.out.println("player l turn");
                 Input = Scan.next();

             }
             else if (Dice1 == 4) {
                 Position1= Position1+Dice1;
                 System.out.println(Position1);
                 System.out.println("player 1 turn ");
                 Input = Scan.next
             }
             else if (Dice1 == 5) {
                 Position1= Position1+Dice1;
                 System.out.println(Position1); 
                 System.out.println("player l turn");
                 Input = Scan.next();

             }
             else if (Dice1 == 4) {
                 Position1= Position1+Dice1;
                 System.out.println(Position1);
                 System.out.println("player 1 turn ");
                 Input = Scan.next();

             }
             else if (Dice1 == 3) {
                 Position1= Position1+Dice1;
                 System.out.println(Position1);
                 System.out.println("Player 1 turn");
                 Input = Scan.next();

             }
             else if (Dice1 == 2) {
                 Position1= Position1+Dice1;
                 System.out.println(Position1);
                 System.out.println("player 1 turn");
                 Input = Scan.next();

             }
             else if (Dice1 == 1) {
                 Position1= Position1+Dice1;
                 System.out.println(Position1);
                 System.out.println("player 1 turn ");
                 Input = Scan.next();
             }
             if(Position1>100) {
                Position1 = Position1-Dice1;
             }
             else if(Position1==100) {
                 System.out.println("U Win"); 
                 
             }
                    
        }
        
     
    }

}

}