lundi 30 septembre 2019

MATLAB: How to generate Gamma random variables with known correlation coefficients

If I know the correlation coefficient between any two Gamma random variables Xi and Xj as rho_ij, I am wondering how I can generate the set of N Gamma distributed random numbers of X1...XN using MATLAB.

For example, my correlation coefficient matrix is

rho=[1 0.5 0.7; 0.5 1 0.4; 0.7 0.4 1]

Then, I need X1, X2, and X3.

If anyone has idea or any useful answer anywhere, please share with me.




How to generate random date in iso format for all dates in a particular month with unique values

How to generate random date in iso format in a particular month with unique values.

This code will get the date in iso format, But how to generate random date in iso format in a particular month with unique values for all the dates in that month

from datetime import datetime, timedelta
import random

def random_date(d1, d2):
    delta = d2 - d1
    seconds = delta.total_seconds()
    n = random.randrange(seconds)
    return d1 + timedelta(seconds=n)

d1 = datetime.strptime('1/1/2019 1:30 PM', '%m/%d/%Y %I:%M %p')
d2 = datetime.strptime('1/2/2019 4:50 AM', '%m/%d/%Y %I:%M %p')
print(random_date(d1, d2).isoformat(timespec='milliseconds')+'Z')



How can I generate random numbers in Haskell without IO in a range?

I would like to generate random numbers in a range and the type signature to be Int -> Int. I've read multiple other posts but none of them suggested ways to return a type Int. I used System.IO.Unsafe in my code but it is not recommended to do so. Here's my code:

import System.IO.Unsafe

-- random number generator
rng :: Int -> Int
rng upper = unsafePerformIO $ randomRIO (0,upper-1) 

Does anyone have any suggests on how to generate random Int in a range in Haskell?

Edit: It might be impossible to change IO Int -> Int so I converted my code to

-- random number generator
rng :: Int -> IO Int
rng upper = randomRIO (0,upper-1) 

The reason why I need a rng is because I want to get random numbers within the range length of the list to get an index for an element of a list.

list !! rng (length list) but I'm getting the error Couldn't match expected type ‘Int’ with actual type ‘IO Int’ which is expected.

I'm new to Haskell and I don't know how to manipulate Monads. Any help is appreciated.




Generate random date of a particular month in order using python

How to Generate random date of a particular month in this particular format.in order wise i.e., from 1 of month to 30 of that month

2011-08-12T20:17:46.384Z

Tried this but it generates in regular time date format. This code generates randomly but i need the values in order from 1 to 30/31 of that month

from datetime import datetime

d1 = datetime.strptime('1/1/2010 1:30 PM', '%m/%d/%Y %I:%M %p')
d2 = datetime.strptime('1/1/2011 4:50 AM', '%m/%d/%Y %I:%M %p')

print(random_date(d1, d2))



How to shuffle multiple iterables in same order?

I seek a plain Python function that accepts an arbitrary number of iterables (tuples, lists, dictionaries), and returns them shuffled in the same order:

a = (1, 2, {3: 4}, 5})
b = [(5,6), [7,8], [9,0], [1,2]]
c = {'arrow': 5, 'knee': 'guard', 0: ('x',2)}

x, y, z = magic(a, b, c)
print(x, y, z, sep='\n')
# ({3: 4}, 1, 2)
# [[9, 0], (5, 6), [7, 8]]
# {0: ('x', 2), 'arrow': 5, 'knee': 'guard'}

The function must:

  • Return iterables shuffled in the same order (see above)
  • Accept any number of iterables
  • Preserve iterables types
  • Support nested iterables of any depth and type
  • Return iterables with length of shortest iterable's length w/o raising error (see above)

OK if using Numpy, random, etc for the shuffle step (e.g. np.random.shuffle(magic_packing)), but cannot be a high-level library method (uses multiprocessing, encoding, etc - should be 'plain')


I've seen related SO's, but could not adapt them to such a generalized case. How can this be accomplished?


Creating and updating a Class with student information in Python

I want to design a class to store student data. Create a class named 'student' with the following attributes and methods:

Class student -- name -- GPA (0-4) -- number_of_courses (0-50) -- number_of_credits(0-120) -- init(self, name, GPA, number_of_courses, number_of_credits):

I want to add an additional definition called... -- add_course(self, grade, credits): This function will add a course to student records. To add a course I want it to add 1 to number_of_courses, add credits to the number_of_credits and calculate the new GPA.

I also want to add an additional function... -- print_student(self): that will print all attributes of a student

  • I want to create 100 students with random information and store them in a list.
  • Finally, I want to ask the user to choose one of the students to update (for example by entering a number between 1 -100). Then have them use the add_course function to add a course for that student. Finally, I want the program to print the student information before and after the update.

Here is my code thus far:

enter image description here




Is there a way to use random.choice?

Is there a way to use random.choice in a manner that it will select a random letter from a str a random number of times?

    ```def drugname(v,c): 
          con = random.choice(c)
       if con == "q":
          vowel = "u"
       else:
          vowel = random.choice(v)
       return con + vowel
    ```

I am trying to figure out how to get random.choice(c) and random.choice(v) to get selected a random number of times.




Is it acceptable to use each byte of a PRNG-generated number separately?

Say you have a PRNG that generates 64-bit output.

Assuming that bytes are 8 bits, is it acceptable to use each byte of the 64-bit output as separate 8-bit random numbers or would that possibly break the guarantees of a good PRNG? Or does it depend on the PRNG?




Random image background in HTML

I want a full background changing randomly each time the page is refresh. My page is in HTML with CSS and JS (JQuery included). I've already tried a lot of solution from this website and many others, their is a lot of tutorials I know. But I think I'm doing something wrong because nothing function.

   <!DOCTYPE html>
   <html lang="fr">
     <head>
       <meta charset="UTF-8">
       <meta http-equiv="X-UA-Compatible" content="IE=edge">
       <meta name="viewport" content="width=device-width, initial-scale=1">
       <title>index</title>
       <script src="js/jquery-3.3.1.min.js"></script>
       <script src="js/popper.min.js"></script> 
       <script src="js/bootstrap-4.3.1.js"></script>

       <!-- Bootstrap -->
       <link href="css/bootstrap-4.3.1.css" rel="stylesheet">
       <style type="text/css">
       body {
    background: url(images/BG/bg01.jpg) no-repeat center center fixed; 
     -webkit-background-size: cover;
     -moz-background-size: cover;
     -o-background-size: cover;
     background-size: cover;
   }
       a:link {
       color: #000000;
   }
   a:hover {
       color: #000000;
   }
       </style>

I've got 13 backgrounds in the same folder named, bg01.jpg bg02.jpg bg03.jpg ... I don't understand how replace my url in the css part I had, where add the JS etc... Noobie topic, I'm sorry for it but I found no tuto who worked for me




How can I move(translate) picture randomly, any position of the screen?

I want to translate image to any position in the screen? what should I do?

I want to make a project, where user asked to put an image anywhere in the screen and that should move to any place after 3 seconds, now user changed the requirement to animate picture randomly on the screen.

class ViewController: UIViewController { var timer = Timer() var imageView: UIImageView! let imageViewWidth = CGFloat(100) let imageViewHeight = CGFloat(100)

override func viewDidLoad() {
    super.viewDidLoad()

    SchedulingMethod()

}

func SchedulingMethod() {
    timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(updatePosition), userInfo: nil, repeats: true)
}
@objc func updatePosition() {

    let maxX = view.frame.maxX-imageViewWidth
    let maxY = view.frame.maxY-imageViewHeight
    let randomX = arc4random_uniform(UInt32(maxX)) + 0
    let randomY = arc4random_uniform(UInt32(maxY)) + 0

    print("chutiyaap")
    imageView = UIImageView(frame: CGRect(x: CGFloat(randomX), y: CGFloat(randomY), width: 200, height: 200))
    imageView.image = UIImage(named: "loading")
    imageView.contentMode = .scaleAspectFit
    for view in self.view.subviews {
        view.removeFromSuperview()
    }

    self.view.addSubview(imageView)
}

picture should translate randomly, actually I want this image to move randomly on the screen.




Elasticsearch sort based on multiple fields and then by random seed

[
    {
        "id": "1",
        "title": "example title 1",
        "priority": "high"
    },
    {
        "id": "2",
        "title": "example title 2",
        "priority": "high"
    },
    {
        "id": "3",
        "title": "example title 3",
        "priority": "high"
    },
    {
        "id": "4",
        "title": "example title 4",
        "priority": "low"
    },
    {
        "id": "5",
        "title": "example title 5",
        "priority": "low"
    },
    {
        "id": "6",
        "title": "example title 6",
        "priority": "low"
    }
]

I have the following items in my elasticsearch index and i can easily sort by multiple fields but i didnt find a way to sort by multiple fields and then random.

So, for example i would need to do this:

  "sort": [
    {
      "priority": "asc"
    },

    _script: {
        script: "Math.random() * 200000",
        type: "number",
        params: {},
        order: "asc"
    }

  ]

So, lets say on first query, you would get these results:

3,2,1(high priority comes first but randomized),5,4,6(low priority comes next, but also randomized)

Second query could also look like this:

2,1,3(high),6,5,4(low)




Generate Random recurring json data using python

Need to generate random json data in this format by subtracting the values

list=['20','30','50','1','200']

for n in list : 
    data= 
          {
           "total_members_present":1000    
           "count": n #(here 20) 
           "total_members_now":980 #(1000-n ,n =20),

          },
          {
           "total_members_present":980    
           "count": n #(here 30) 
           "total_members_now":950 #(1000-n ,n =30),

          },

.........

it should continue until the list ends.




Go to random frame, excluding current frame

Here is my problem.

My main timeline has 3 frames. Each frame contains different movieClip.

I created a button, and when user clicks this button, I want a random movieclip to play.

But, I don't want to play the same movieClip again. So, when user is on the frame 1 and clicks the button, either frame 2 or 3 should play. Similarly, if the user is on the frame 2, frame 1 or 3 should play.

Now, I used this code and almost achieved what I wanted:

var _this = this;
_this.Play_button.on('click', function(){
_this.gotoAndStop(0+Math.random()*2);
});

But. Many times, the click on the button goes to the same frame, and this is not what I want.

Could someone here help me to achieve this? This is a HTML5 canvas, if it makes a difference.




How do I generate random numbers with a certain interval?

I have this sample:

link

CODE JS:

for (var i=0; i < 5; i++) {
  var number = 1 + Math.floor(Math.random() * 20);
  console.log(number);
}

I want to generate numbers between 1 and 20 but with the following restrictions:

  1. The numbers should not be duplicated
  2. Exclude the first and last numbet (1,20)
  3. The difference between the generated numbers must be at least 3 (ex: 4, 7,10 etc)

Can you please give me some tips on how I could do this?

A few simple examples would help me.

Thanks




dimanche 29 septembre 2019

How can I get the information from one field in a query to use in another query?

I am still trying to finish fixing my details page and I need one more piece to fix it.

I start with this query.

NOTE:recordID actually comes in from the previous page by clicking an item. Also, name, img, item_code, and type_id are fields in my table not outside sources.

$recordID = $_GET['recordID'];
$query_master_details = "SELECT * FROM master_list WHERE master_list.master_id = $recordID";
$master_details = mysqli_query($conn, $query_master_details) or die(mysqli_error());
$row_master_details = mysqli_fetch_assoc($master_details);
$totalrows_master_details = mysqli_num_rows($master_details);

Now, I have created this to determine how to display the details about said item:

<div class="container2">
  <div class="category"><h2><?php echo $row_master_details['name']; ?></h2></div>
  <?php
  $crafted = "SELECT * FROM `master_list` WHERE `type_id` <= 3 AND `length` = $row_master_details.length ORDER BY RAND() LIMIT 1";
  $result = mysqli_query($conn, $crafted);
  $crafted = array();
  if (mysqli_num_rows($result) > 0) {
      while($row = mysqli_fetch_assoc($result)) {
          $crafted[] = $row;
      }
  }
  if ($row_master_details['type_id'] > 3) {?>
    <p><strong>Code 1</strong></p>
    <p><?php echo $crafted['name']; ?></p>
    <p><img src="img/<?php echo $crafted['img']; ?>" /></p>
    <p><?php echo $crafted['item_code']; ?></p>
    <br><br>
    <p><strong>Code 2</strong></p>
    <p><?php echo $row_master_details['name']; ?></p>
    <p><img src="img/<?php echo $row_master_details['img']; ?>" /></p>
    <p><?php echo $row_master_details['item_code']; ?></p>
    <p><?php echo $row_master_details['length']; ?> Characters</p>
  <?php }else { ?>
    <p><?php echo $row_master_details['name']; ?></p>
    <p><img src="img/<?php echo $row_master_details['img']; ?>" /></p>
    <p><?php echo $row_master_details['item_code']; ?></p>
    <p><?php echo $row_master_details['length']; ?> Characters</p>
  <?php
  mysqli_free_result($master_details);
  ?>
  <?php } ?>
<!-- end .container2 --></div>

To explain what is happening here:

This looks at the item that was clicked on the previous page and finds the information about it. If it has a type_id of 4 or higher, I need it to do the following:

  1. Look at the "length" of the current item.
  2. Select all the items from the master_list that has a type_id of 1, 2, or 3 and a matching length to the first one.
  3. Choose 1 random match.
  4. Output the "name, img, and item_code in the same fashion as the first one.

If the item selected originally has a type_id of less than 4, it just posts the original information. This part works. The part from the second query does not.

I have a feeling I need another $_GET[], but not exactly sure how to go about it. The recordID get was attached to the image used as a link.

Can anyone help me to query this so that I get what I am wanting?

Here is a pic of what I am trying to do to help make more sense:

enter image description here

This was done by manually choosing the item to match and putting them together. I want a random item to display.




How to fix this random walking program code?

I'm creating a program that generates random walking. I can't figure out why the following code is not working.

When I run it, the program doesn't proceed after asking "please enter the starting street integer: "

I tried to import Random method in my Drunkard class and then use random method in the step method. I can't figure out which part was wrong.

import java.util.Random;

public class Drunkard{
private int x;
private int y;
private int inix;
private int iniy;

public Drunkard(int avenue, int street){
    this.x = avenue;
    this.y = street; 
    this.inix = avenue;
    this.iniy = street;
}

public void fastForward(int howMany){
    int i = 0;
    while (i<howMany){
        step();
    }

}
public void step(){
    Random random = new Random();
    int ranNum = random.nextInt(4);
    if (ranNum == 0){
        this.x +=1;
    } else if (ranNum == 1){
        this.x -=1;  
    } else if (ranNum == 2){
        this.y +=1;  
    } else if (ranNum == 3){
        this.y -=1;   
    }

}
public String getLocation(){
    return x + "avenue " + y + "street";
}
public int howFar(){
    return this.x+this.y-this.inix-this.iniy;
}


}



import java.util.Scanner;

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

Scanner input = new Scanner(System.in);

System.out.println("Please enter the starting avenue integer: ");
int avenue = input.nextInt();
System.out.println("Please enter the starting street integer: ");
int street = input.nextInt();

// make the Drunkard with initial position
Drunkard ozzy = new Drunkard(avenue,street);

// have him move 100 intersections
ozzy.fastForward(100);

// get his current location
String location = ozzy.getLocation();

// get distance from start
int distance = ozzy.howFar();

System.out.println("Current location: " + location);
System.out.println("That's " + distance + " blocks from start.");

}
}



Tic Tac Toe Game Made In Python Win Conditions

This is my first ever post on here, as usually I just follow tutorials on Youtube or whatever, but I really wanted to do a project mainly by myself. I made a little Tic Tac Toe game I was pretty proud of today in Python, but there is one thing that doesn't work. The win conditions. I put in the winLoseCondition() in different spots before, but it doesn't work. Once it gets to there, it either says I lose or win. I don't know how it decides before there is enough information. One other thing, sometimes the computer overwrites one of the places the player has gone, and I don't know why. I know I probably did 100 things wrong programming this and there is a way easier way of doing it, but there are many like it but this one is mine. So, the question I really am asking here is: How do I fix my code so that my win conditions, when fulfilled correctly, actually end the game at the correct time, and not at a random time when I place the function somewhere. Also, as a bonus, why is my computer/random O placing bot overwriting some of where the player places their X's? I know I could improve the thing that places the O's, but that is for another night.

import random
import sys
winCondition = False
def winLoseCondition():
    if board[1] and board[2] and board[3] == 'X':
        print('You win!')
        sys.exit()
    if board[1] and board[2] and board[3] == 'O':
        print('You lose...')
        sys.exit()
    if board[1] and board[5] and board[9] == 'X':
        print('You win!')
        sys.exit()
    if board[1] and board[5] and board[9] == 'O':
        print('You lose...')
        sys.exit()
    if board[3] and board[5] and board[7] == 'X':
        print('You win!')
        sys.exit()
    if board[3] and board[5] and board[7] == 'O':
        print('You lose...')
        sys.exit()
    if board[1] and board[4] and board[7] == 'X':
        print('You win!')
        sys.exit()
    if board[1] and board[4] and board[7] == 'O':
        print('You lose...')
        sys.exit()
    if board[2] and board[5] and board[8] == 'X':
        print('You win!')
        sys.exit()
    if board[2] and board[5] and board[8] == 'O':
        print('You lose...')
        sys.exit()
    if board[3] and board[6] and board[9] == 'O':
        print('You lose...')
        sys.exit()
    if board[3] and board[6] and board[9] == 'X':
        print('You win!')
        sys.exit()
    if board[4] and board[5] and board[6] == 'O':
        print('You lose...')
        sys.exit()
    if board[4] and board[5] and board[6] == 'X':
        print('You win!')
        sys.exit()
    if board[7] and board[8] and board[9] == 'X':
        print('You win!')
        sys.exit()
    if board[7] and board[8] and board[9] == 'O':
        print('You lose...')
        sys.exit()

while winCondition == False:
    board = {1: ' ',2: ' ',3: ' ',
                 4: ' ',5: ' ', 6: ' ',
                 7: ' ', 8: ' ', 9: ' '}
    print('We are going to play Tic Tac Toe')
    firstPlayerMove = input('What is your first move? (Input a number 1:9. 1 is the top left box. 9 is the bottom right box.)')
    #Player's First Move
    if int(firstPlayerMove) == 1:
        board[1] = 'X'
    if int(firstPlayerMove) == 2:
        board[2] = 'X'
    if int(firstPlayerMove) == 3:
        board[3] = 'X'
    if int(firstPlayerMove) == 4:
        board[4] = 'X'
    if int(firstPlayerMove) == 5:
        board[5] = 'X'
    if int(firstPlayerMove) == 6:
        board[6] = 'X'
    if int(firstPlayerMove) == 7:
        board[7] = 'X'
    if int(firstPlayerMove) == 8:
        board[8] = 'X'
    if int(firstPlayerMove) == 9:
        board[9] = 'X'
    #Computer's First Move:
    firstComputerMove = random.randint(1,9)
    while firstComputerMove == int(firstPlayerMove):
        firstComputerMove = random.randint(1,9)
    while firstComputerMove != int(firstPlayerMove):

        if firstComputerMove == 1:
            board[1] = 'O'
            break
        if firstComputerMove == 2:
            board[2] = 'O'
            break
        if firstComputerMove == 3:
            board[3] = 'O'
            break
        if firstComputerMove == 4:
            board[4] = 'O'
            break
        if firstComputerMove == 5:
            board[5] = 'O'
            break
        if firstComputerMove == 6:
            board[6] = 'O'
            break
        if firstComputerMove == 7:
            board[7] = 'O'
            break
        if firstComputerMove == 8:
            board[8] = 'O'
            break
        if firstComputerMove == 9:
            board[9] = 'O'
            break
    #Player's Second Move
    print('This is what the board looks like:')
    print(board[1] +  '|' + board[2] + '|' + board[3])
    print('_ _ _')
    print(board[4] +  '|' + board[5] + '|' + board[6])
    print('_ _ _')
    print(board[7] +  '|' + board[8] + '|' + board[9])
    secondPlayerMove = input('What is your second move? ')
    while int(secondPlayerMove) == int(firstPlayerMove):
        secondPlayerMove = input('That space is already occupied. Please input a different number ')
    while int(secondPlayerMove) == firstComputerMove:
        secondPlayerMove = input('That space is already occupied. Please input a different number ')
    while int(secondPlayerMove) != int(firstPlayerMove) or firstComputerMove:

        if int(secondPlayerMove) == 1:
            board[1] = 'X'
            break
        if int(secondPlayerMove) == 2:
            board[2] = 'X'
            break
        if int(secondPlayerMove) == 3:
            board[3] = 'X'
            break
        if int(secondPlayerMove) == 4:
            board[4] = 'X'
            break
        if int(secondPlayerMove) == 5:
            board[5] = 'X'
            break
        if int(secondPlayerMove) == 6:
            board[6] = 'X'
            break
        if int(secondPlayerMove) == 7:
            board[7] = 'X'
            break
        if int(secondPlayerMove) == 8:
            board[8] = 'X'
            break
        if int(secondPlayerMove) == 9:
            board[9] = 'X'
            break
    #Computer's Second Move
    secondComputerMove = random.randint(1,9)
    while int(secondComputerMove) == int(firstPlayerMove):
        secondComputerMove = random.randint(1,9)
    while int(secondComputerMove) == firstComputerMove:
        secondComputerMove = random.randint(1,9)
    while int(secondComputerMove) == int(secondPlayerMove):
        secondComputerMove = random.randint(1,9)
    while int(secondComputerMove) != int(firstPlayerMove) or firstComputerMove or int(secondPlayerMove):

        if int(secondComputerMove) == 1:
            board[1] = 'O'
            break
        if int(secondComputerMove) == 2:
            board[2] = 'O'
            break
        if int(secondComputerMove) == 3:
            board[3] = 'O'
            break
        if int(secondComputerMove) == 4:
            board[4] = 'O'
            break
        if int(secondComputerMove) == 5:
            board[5] = 'O'
            break
        if int(secondComputerMove) == 6:
            board[6] = 'O'
            break
        if int(secondComputerMove) == 7:
            board[7] = 'O'
            break
        if int(secondComputerMove) == 8:
            board[8] = 'O'
            break
        if int(secondComputerMove) == 9:
            board[9] = 'O'
            break
    #Player's Third Move
    print('This is what the board looks like:')
    print(board[1] +  '|' + board[2] + '|' + board[3])
    print('_ _ _')
    print(board[4] +  '|' + board[5] + '|' + board[6])
    print('_ _ _')
    print(board[7] +  '|' + board[8] + '|' + board[9])
    thirdPlayerMove = input('Please say where you want to move.')
    while int(thirdPlayerMove) == int(firstPlayerMove):
        thirdPlayerMove = input('Sorry, that space is taken, please try again.')
    while int(thirdPlayerMove) == firstComputerMove:
        thirdPlayerMove = input('Sorry, that space is taken, please try again.')
    while int(thirdPlayerMove) == int(secondPlayerMove):
        thirdPlayerMove = input('Sorry, that space is taken, please try again.')
    while int(thirdPlayerMove) == secondComputerMove:
        thirdPlayerMove = input('Sorry, that space is taken, please try again.')
    while int(thirdPlayerMove) != int(firstPlayerMove) or firstComputerMove or int(secondPlayerMove) or secondComputerMove:

        if int(thirdPlayerMove) == 1:
            board[1] = 'X'
            break
        if int(thirdPlayerMove) == 2:
            board[2] = 'X'
            break
        if int(thirdPlayerMove) == 3:
            board[3] = 'X'
            break
        if int(thirdPlayerMove) == 4:
            board[4] = 'X'
            break
        if int(thirdPlayerMove) == 5:
            board[5] = 'X'
            break
        if int(thirdPlayerMove) == 6:
            board[6] = 'X'
            break
        if int(thirdPlayerMove) == 7:
            board[7] = 'X'
            break
        if int(thirdPlayerMove) == 8:
            board[8] = 'X'
            break
        if int(thirdPlayerMove) == 9:
            board[9] = 'X'
            break
    #Computer's Third Move
    thirdComputerMove = random.randint(1,9)
    while int(thirdComputerMove) == int(firstPlayerMove):
        thirdComputerMove = random.randint(1,9)
    while int(thirdComputerMove) == firstComputerMove:
        thirdComputerMove = random.randint(1,9)
    while int(thirdComputerMove) == int(secondPlayerMove):
        thirdComputerMove = random.randint(1,9)
    while int(thirdComputerMove) == secondComputerMove:
        thirdComputerMove = random.randint(1,9)
    while int(thirdComputerMove) == int(thirdPlayerMove):
        thirdComputerMove = random.randint(1,9)
    while int(thirdComputerMove) != int(firstPlayerMove) or firstComputerMove or int(secondPlayerMove) or secondComputerMove or int(thirdPlayerMove):

        if int(thirdComputerMove) == 1:
            board[1] = 'O'
            break
        if int(thirdComputerMove) == 2:
            board[2] = 'O'
            break
        if int(thirdComputerMove) == 3:
            board[3] = 'O'
            break
        if int(thirdComputerMove) == 4:
            board[4] = 'O'
            break
        if int(thirdComputerMove) == 5:
            board[5] = 'O'
            break
        if int(thirdComputerMove) == 6:
            board[6] = 'O'
            break
        if int(thirdComputerMove) == 7:
            board[7] = 'O'
            break
        if int(thirdComputerMove) == 8:
            board[8] = 'O'
            break
        if int(thirdComputerMove) == 9:
            board[9] = 'O'
            break
    #Player's Fourth Move
    print('This is what the board looks like:')
    print(board[1] +  '|' + board[2] + '|' + board[3])
    print('_ _ _')
    print(board[4] +  '|' + board[5] + '|' + board[6])
    print('_ _ _')
    print(board[7] +  '|' + board[8] + '|' + board[9])
    fourthPlayerMove = input('Where do you want to move?')
    while int(fourthPlayerMove) == int(firstPlayerMove):
        fourthPlayerMove = input('Sorry, that space is taken, please try again.')
    while int(fourthPlayerMove) == firstComputerMove:
        fourthPlayerMove = input('Sorry, that space is taken, please try again.')
    while int(fourthPlayerMove) == int(secondPlayerMove):
        fourthPlayerMove = input('Sorry, that space is taken, please try again.')
    while int(fourthPlayerMove) == secondComputerMove:
        fourthPlayerMove = input('Sorry, that space is taken, please try again.')
    while int(fourthPlayerMove) == int(thirdPlayerMove):
        fourthPlayerMove = input('Sorry, that space is taken, please try again.')
    while int(fourthPlayerMove) == thirdComputerMove:
        fourthPlayerMove = input('Sorry, that space is taken, please try again.')
    while int(fourthPlayerMove) != int(firstPlayerMove) or firstComputerMove or int(secondPlayerMove) or secondComputerMove or int(thirdPlayerMove) or thirdComputerMove:

        if int(fourthPlayerMove) == 1:
            board[1] = 'X'
            break
        if int(fourthPlayerMove) == 2:
            board[2] = 'X'
            break
        if int(fourthPlayerMove) == 3:
            board[3] = 'X'
            break
        if int(fourthPlayerMove) == 4:
            board[4] = 'X'
            break
        if int(fourthPlayerMove) == 5:
            board[5] = 'X'
            break
        if int(fourthPlayerMove) == 6:
            board[6] = 'X'
            break
        if int(fourthPlayerMove) == 7:
            board[7] = 'X'
            break
        if int(fourthPlayerMove) == 8:
            board[8] = 'X'
            break
        if int(fourthPlayerMove) == 9:
            board[9] = 'X'
            break
    #Computer's Fourth Move
    fourthComputerMove = random.randint(1,9)
    while int(fourthComputerMove) == int(firstPlayerMove):
        fourthComputerMove = random.randint(1,9)
    while int(fourthComputerMove) == firstComputerMove:
        fourthComputerMove = random.randint(1,9)
    while int(fourthComputerMove) == int(secondPlayerMove):
        fourthComputerMove = random.randint(1,9)
    while int(fourthComputerMove) == secondComputerMove:
        fourthComputerMove = random.randint(1,9)
    while int(fourthComputerMove) == int(thirdPlayerMove):
        fourthComputerMove = random.randint(1,9)
    while int(fourthComputerMove) == thirdComputerMove:
        fourthComputerMove = random.randint(1,9)
    while int(fourthComputerMove) == int(fourthPlayerMove):
        fourthComputerMove = random.randint(1,9)
    while int(fourthComputerMove) != int(firstPlayerMove) or firstComputerMove or int(secondPlayerMove) or secondComputerMove or int(thirdPlayerMove) or thirdComputerMove or int(fourthPlayerMove):

        if int(fourthComputerMove) == 1:
            board[1] = 'O'
            break
        if int(fourthComputerMove) == 2:
            board[2] = 'O'
            break
        if int(fourthComputerMove) == 3:
            board[3] = 'O'
            break
        if int(fourthComputerMove) == 4:
            board[4] = 'O'
            break
        if int(fourthComputerMove) == 5:
            board[5] = 'O'
            break
        if int(fourthComputerMove) == 6:
            board[6] = 'O'
            break
        if int(fourthComputerMove) == 7:
            board[7] = 'O'
            break
        if int(fourthComputerMove) == 8:
            board[8] = 'O'
            break
        if int(fourthComputerMove) == 9:
            board[9] = 'O'
            break
    #Player's Last Move
    print('This is what the board looks like:')
    print(board[1] +  '|' + board[2] + '|' + board[3])
    print('_ _ _')
    print(board[4] +  '|' + board[5] + '|' + board[6])
    print('_ _ _')
    print(board[7] +  '|' + board[8] + '|' + board[9])
    print('There is only one last spot.')
    if board[1] == ' ':
        print('You had to move to spot 1')
        board[1] = 'X'
    if board[2] == ' ':
        print('You had to move to spot 2')
        board[2] = 'X'
    if board[3] == ' ':
        print('You had to move to spot 3')
        board[3] == 'X'
    if board[4] == ' ':
        print('You had to move to spot 4')
        board[4] = 'X'
    if board[5] == ' ':
        print('You had to move to spot 5')
        board[5] = 'X'
    if board[6] == ' ':
        print('You had to move to spot 6')
        board[6] = 'X'
    if board[7] == ' ':
        print('You had to move to spot 7')
        board[7] = 'X'
    if board[8] == ' ':
        print('You had to move to spot 8')
        board[8] = 'X'
    if board[9] == ' ':
        print('You had to move to spot 9')
        board[9] = 'X'
    #Final Board
    print('The final board looks like:')
    print(board[1] +  '|' + board[2] + '|' + board[3])
    print('_ _ _')
    print(board[4] +  '|' + board[5] + '|' + board[6])
    print('_ _ _')
    print(board[7] +  '|' + board[8] + '|' + board[9])
    winCondition = True

print('The final board looks like:')
print(board[1] +  '|' + board[2] + '|' + board[3])
print('_ _ _')
print(board[4] +  '|' + board[5] + '|' + board[6])
print('_ _ _')
print(board[7] +  '|' + board[8] + '|' + board[9])




Random path generation algorithm with defined path size

I'm trying to generate a path inside a matrix with a defined count of elements inside the picked path.

I can create from point A to point B with no problems using:

step(int[] s, int[] e) //start - end
{
   int d = delta(s, e);
   if (d > 1)
   {
      //spread around
      List<int[]> pts = new List<int[]>();
      pts.Add(new int[2] { s[0] -1, s[1]    }); //left
      pts.Add(new int[2] { s[0] +1, s[1]    }); //right
      pts.Add(new int[2] { s[0]   , s[1] +1 }); //top
      pts.Add(new int[2] { s[0]   , s[1] -1 }); //bot

      //remove out of bounds points
      List<int[]> goodPoints = new List<int[]>();
      foreach (var p in pts)
      {
         if (checkValidBoundries(p))
         {
            goodPoints.Add(p);
         }
      }

      //calculate lowest deltas
      int lowestDelta = int.MaxValue;
      int[] bestFit = new int[2];
      foreach (var p in goodPoints)
      {
         int localDelta = delta(p, e);
         if (localDelta == lowestDelta) //local shuffle
         {
            if (await coinFlip())
            {
               bestFit = p;
            }
         }
         else if (localDelta < lowestDelta)
         {
            lowestDelta = localDelta;
            bestFit = p;
         }
      }

      matrix.setValue(bestFit[0], bestFit[1]);
      step(bestFit, e);
   }
}

This code will recursive iterates until the path is over. This is the way I get the shortest path.

So my question is: How can I define a number of elements in the path?

For example: from A to B this algorithm gives me 6 elements, no matter the path it will always use the lowest delta between points. But if I want this path to be 7, 8 elements long?

I tried to pick one element at a time from the path and lock it so next run it will not consider it as valid, but it keeps going wrong.

The new path can be random no problem I just want to control the number of elements inside the "best path".

Any help? Thanks in Advance




Rolling a dice in swift using a while function and printing results until the result is 1

I'm really new to Swift and I have a task asking me to create a while loop that simulates rolling a 6-sided dice repeatedly until a 1 is rolled. After each roll, print the value.

In just about every iteration I've tried over the last 2 hours I keep ending in an infinite loop that explodes Xcode.

Any help would be fantastic!

var dieRoll = Int.random(in: 1...6)

while dieRoll <= 6 { print (dieRoll) if dieRoll == 1 { print ("You win!") } }

This is about the best one I've done because when it manages to hit a one on the first roll it prints you win, otherwise if it rolls any other number first it keeps that number and crashes.




Selecting random file but then deleting it

I have some code that selects a random file from a folder then logs it, after its done logging I want it to be deleted but I can't seem to delete it.

The path to the randomly selected file is stored as a variable.

const trash = require('trash');
var fs = require('fs'),
    path = require('path'),
    files_memes = fs.readdirSync('/Users/jackb/Desktop/pup/Pictures/reddit_sub_memes')
var filename = (random_file());
var imgPATH = path.join(__dirname, '/Users/jackb/Desktop/pup/Pictures/reddit_sub_memes/' + filename);
const del = require('del');

function random_file(){
  var allFiles = (files_memes)//array
  return allFiles[Math.floor(Math.random() * allFiles.length)];
}
console.log(filename);
console.log(imgPATH);
(async () => {
    const deletedPaths = await del(['imagePATH']);

    console.log('Deleted files and directories:\n', deletedPaths.join('\n'));
})();

I expect the logged file to be deleted.




Trouble in creating a sub routine that completely randomizes a pre existing array sub routine in visual basics - excel

I need to use a VBA sub that randomly sorts a pre-existing selected array by leveraging the randbetween function in the sub.

If anyone has any suggestion it would be great, as I am a bit stuck here. Please see below what I have so far.

Option Explicit
Option Base 1

Sub shuffleArray()
Dim N As Integer, rn As Long
Dim j As Integer, i As Integer
Dim nr As Long, nc As Integer
Dim temp As Integer
Dim A()
nr = Selection.Rows.Count
nc = Selection.Rows.Count
N = Selection.Cells.Count
ReDim A(nr, nc)

rn = Application.WorksheetFunction.RandBetween(1, N - j + 1)

 For i = 1 To nr  

   For j = 1 To nc

       A(i, j) = Selection.Cells(i, j)

        temp = A(N - j + 1, i)
        A(N - j + 1, i) = A(rn)

        A(rn) = temp

   Next j
  Next I
End Sub



Apply random color to each path without new function for each

I have an SVG with a bunch of paths (rect here for simplicity)

<rect id=1 x="0" y="100" width="100" height="100"/>
<rect id=2 x="120" y="100" width="100" height="100"/>
<rect id=3 x="240" y="100" width="100" height="100"/>

I have my snippet which defines my colors:

var colors = ['red','yellow','green','blue','orange','purple','black','white'];

Then comes the snippet which randomizes the color

var random_color1 = colors[Math.floor(Math.random() * colors.length)];
var random_color2 = colors[Math.floor(Math.random() * colors.length)];
var random_color3 = colors[Math.floor(Math.random() * colors.length)];

Then I have this which applies the random color to each path (each has a unique id)

document.getElementById('1').style.fill = random_color1;
document.getElementById('2').style.fill = random_color2;
document.getElementById('3').style.fill = random_color3;

The thing is, I have a few hundred paths in this document. I need to apply the randomize to each and every path, my current process leaves hundreds of lines of code.

I'm looking for a way to;

  1. Not need a unique path id for each path
  2. Call the random_color function each time for a path without creating a new one per path and then apply it to that path.

I'm really new to javascript and I've tried whatever I know, but to no avail.




multiple random cordinates in matrix, optimization. python

the code below creates a matrix of zeros (line 06), then takes random "start points" (line 36) that move randomly in x and y (line 10), each start point have their own number(1,2,3,4,5,...,number_fo_start_points), they can't go over the path of other start_point (line 29), the list of start_points enter a while that has a limit of how many "steps" each start_poitn does (line 38) (the limit is defined by other external conditions).

My problem is that I need huge matrixes, about 1.000.000 x 1.000.000. but this code will take for ever doing that, is there a way to optimize this code?? is there a way to move all the start_points at the same time? do I need threading? can I change the same matrix with two different threads?

01    import random
02    import numpy
03    length_matrix = 1000
04    width_matrix = 1000
05    number_of_start_points = 400
06    matriz = numpy.zeros([length_matrix, width_matrix])
07    def direction(): 
08        direction = random.randint(1, 4)
09        return direction
10    def move(x, y):  
11        direction = direction()
12        if direction == 1:
13           return x + 1, y
14        if direction == 2:
15           return x - 1, y
16        if direction == 3:
17           return x, y + 1
18        if direction == 4:
19           return x, y - 1
20            
21    class start_point: 
22        def __init__(self):
23            self.xrand = random.randint(0, LARGOIMG)
24            self.yrand = random.randint(0, ANCHOIMG)
25    
26        def move(self, x, y, start_point_index): 
27            try:
28               position = move(x, y) 
29               if matrix[position] == 0 or matrix[position] == start_point_index + 1:  
30                  matrix[position] = start_point_index + 1
31                  return position 
32               return x, y  
33            except:
34               return x, y 
35    start_points = [ ]
36    for i in range(number_of_start_points):
37        nombres.append(start_point())
38    limit = (((length_matrix * width_matrix * 100000) / (360 * 540))*12)/number_of_start_points
39    while flag < limite:
40          for i in start_points:
41             new_position = (i.move(i.xrand, i.yrand, star_point.index(i)))
42             i.xrand, i.yrand = new_position
43          flag = flag + 1
44    numpy.save("matrix001",matrix)



How to fix print is not working in python with the random lib [duplicate]

This question already has an answer here:

I am creating a rock, paper, scissor game i just try the random lib but this what happens

C:\Users\Timothy\Desktop>python app1.py
2
Please choose 1=Rock, 2=Paper, 3=Siccors2

and this is the code that I create

import random
ai = (random.randint(1,3))
print(ai)
play = input("Please choose 1=Rock, 2=Paper, 3=Siccors")
if ai == play:
    print("Hello")



Generate text from a given template

For example I have a string such as

    text = '{Hello|Good morning|Hi}{. We|, we} have a {good |best }offer for you.'

How can I generate a set of all possible strings with variants of words in braces?

Hello. We have a good offer for you.

Good morning, we have a best offer for you.

etc...




samedi 28 septembre 2019

The rand() function in C++ is giving a number outside the range

So I'm trying to write a story about Jordan paying bills and stuff. I used a rand function to find a random number for his salary 3.5k - 4.5 and bills 700 -1.5k. I believe I got the formula right but usually, it generates a number outside that area. Below is the code and result.

{
    srand(time(NULL));  
    cout << fixed;
    cout << setprecision(2);
    float money = 9000;
    int minbill = 700;
    int maxbill = 1500;
    int minsal = 3500;
    int maxsal = 4500;
    float rent = 3000;

    cout << "[Jordan's Balance: Gp" << money << "]\n\n";
    cout << "Jordan's rent costs Gp" << rent <<".\n";
    float bill = (rand()%maxbill-minbill+1)+minbill;
    cout << "Jordan's bills costs Gp" << bill << ".\n";
    float totalb = rent + bill;
    cout << "Jordan needs to pay a total of Gp" << totalb << "\n\n";
    float sal = (rand()%maxsal-minsal+1)+minsal;
    cout << "Jordan received a salary of Gp" << sal << "!!\n";
    money = money + sal;
    cout << "[Jordan's Balance: Gp" << money << "]\n\n";
}

I expect Jordan's bills to be around 700-1.5k and his salary 3.5k-4.5k but it gives me a number below that.


Jordan's rent costs Gp3000.00.
Jordan's bills costs Gp133.00.
Jordan needs to pay a total of Gp3133.00

Jordan received a salary of Gp1906.00!!
[Jordan's Balance: Gp10906.00]



rand() gives almost the same number every time

I'm learning C and I want to generate a number between 0 and 6400. This is the code I came up with:

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

int main()
{
    srand(time(0));
    int i = (rand() % 6401);
    printf("Random number between 0 and 6400: %d\n", i);
    return 0;
}

When I compile and run this code from the command line I get some very weird results:

K:\C\Labo\Oefeningen 2019>a
Random number between 0 and 6400: 6282

K:\C\Labo\Oefeningen 2019>a
Random number between 0 and 6400: 6282

K:\C\Labo\Oefeningen 2019>a
Random number between 0 and 6400: 6285

K:\C\Labo\Oefeningen 2019>a
Random number between 0 and 6400: 6285

K:\C\Labo\Oefeningen 2019>a
Random number between 0 and 6400: 6289

K:\C\Labo\Oefeningen 2019>a
Random number between 0 and 6400: 6289

K:\C\Labo\Oefeningen 2019>a
Random number between 0 and 6400: 6292

K:\C\Labo\Oefeningen 2019>a
Random number between 0 and 6400: 6292

K:\C\Labo\Oefeningen 2019>a
Random number between 0 and 6400: 6295

K:\C\Labo\Oefeningen 2019>a
Random number between 0 and 6400: 6298

K:\C\Labo\Oefeningen 2019>a
Random number between 0 and 6400: 6298

K:\C\Labo\Oefeningen 2019>a
Random number between 0 and 6400: 6302

K:\C\Labo\Oefeningen 2019>a
Random number between 0 and 6400: 6302

K:\C\Labo\Oefeningen 2019>a
Random number between 0 and 6400: 6305

K:\C\Labo\Oefeningen 2019>a
Random number between 0 and 6400: 6305

K:\C\Labo\Oefeningen 2019>a
Random number between 0 and 6400: 6308

K:\C\Labo\Oefeningen 2019>a
Random number between 0 and 6400: 6308

K:\C\Labo\Oefeningen 2019>a
Random number between 0 and 6400: 6311

K:\C\Labo\Oefeningen 2019>a
Random number between 0 and 6400: 6311

K:\C\Labo\Oefeningen 2019>a
Random number between 0 and 6400: 6315

K:\C\Labo\Oefeningen 2019>a
Random number between 0 and 6400: 6315

K:\C\Labo\Oefeningen 2019>a
Random number between 0 and 6400: 6318

K:\C\Labo\Oefeningen 2019>a
Random number between 0 and 6400: 6318

K:\C\Labo\Oefeningen 2019>a
Random number between 0 and 6400: 6321

K:\C\Labo\Oefeningen 2019>

The numbers are all different but I would expect a somewhat even distribution between 0 and 6400. The weird thing is that I was using the same function without problems an hour ago? (I was using it to generate smaller numbers before.) I'm certain it's something really stupid that I'm missing but I've been stuck for an hour now.




Declaring class handle as rand type in System Verilog

Please See this for better clarification of of my codeWhat happens when we declare class handle as rand type? will it affect the randomization? I am trying to do sorting using constraint guards.

class Sorting;
    rand int unsigned n;
    rand Sorting next;
    constraint C0 { n inside {[2:20]};}

    constraint sort {if( next != null ) n < next.n;}

endclass

module random;
  Sorting s;
  initial
    begin
      s=new;
      repeat(10)
        begin
          assert(s.randomize());
          $write("%0d\t",s.n);
        end
    end
endmodule

I am getting the warning in VCS like these -> Warning-[CNST-PPRW] Constraint randomize NULL object warning

The same code is in the LRM under the constraint guard section. I am curious to know whether we can sort the random data using the constraint guard technique? I have done sorting the random data using foreach loop inside the constraint. I am just trying this way. Help me with it. Thanks!




Random color on mouse-hover

I am using the following code to change the color. I have :root{} in my CSS.

I have a random shadow color on each reload of the page, so I almost got it right. Is it possible to get a random color on each item with every 'hover'?

JS:

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

document.documentElement.style.setProperty('--shadowColor', getColor());

CSS for referencing

:root {
    --shadowColor: blue;
}

.nav a:hover {
    color: white;
    text-decoration: ;
    background-size: 1px 50px;

    text-shadow: -2px 0px var(--shadowColor);
}



Changing to a random (shadow) color on hover - using Javascript/Jquery and CSS

Currently I am using the following code to change the shadow color. I use a :root{} in my CSS, which is linked with my Javascript file.

I get a random shadow color on each reload of the page, so I almost got it right.

Is it possible to get a random color on each item with every 'hover'?

JS goes as followed

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

document.documentElement.style.setProperty('--shadowColor', getColor());

The following is a small part of my CSS for referencing

:root {
    --shadowColor: blue;
}

.nav a:hover {
    color: white;
    text-decoration: ;
    background-size: 1px 50px;

    text-shadow: -2px 0px var(--shadowColor);
}



How to generate unique random numbers from a list

I know that I should write a code to random numbers like the code below, but I don't know how to generate unique numbers, for example I want to generate 3 unique phone numbers from a list at once, how can I do it?

import random  

# last numbers of the phone numbers are in order, 1,2,3,4,5,6
myList = [60165651, 60175652, 60156523, 60135354, 60159535, 60192326]  

for x in range(5): 
    print(random.choice(myList))

-----------------------------------------------------

another problem is that if I put zero at the beginning of numbers I get an error: Token invalid!

e.g:

myPhoneList = [060165651, 60175652, 60156523, 60135354, 60159535, 60192326]



vendredi 27 septembre 2019

Why does early-userspace Linux not get enough entropy?

I have a hard time following the lines of thought in a recent LKML thread on what to do about prolonged (unbounded?) blocking of a getrandom call at system initialization.

The crux of the problem is the kernel neither getting nor creating enough entropy for an early getrandom call to succeed in a timely manner.

Linus Torvalds was, incomprehensibly to me, arguing for breaking userspace in that thread, changing the behavior of getrandom to error out with EINVAL. (Who stops Linus from breaking userspace?)

Arguably, it's the kernel that is at fault for not getting enough entropy to userspace even in early userspace.

(void *)getauxval(AT_RANDOM) in an init process already yields a pointer to 128 bits of randomness. (A C library may even make use of it to initialize things like the __stack_chk_guard value.)

Why can't the kernel take (those?) 128 bits to initialize a CSPRNG to be used by the kernel implementations of getrandom(..., 0) and /dev/urandom, enabling those interfaces to spew out whatever amount of pseudo-random values requested?

Apparently OpenBSD does not have this problem. Its arc4random_buf function always returns the randomness requested with no room for error. So I'm guessing the OpenBSD kernel can always get enough entropy to then initialize a CSPRNG either in-kernel or on the userspace side.

What were the choices that led OpenBSD to having an error-free function? And could the Linux kernel/userspace adopt those or similar choices for getrandom?




random images without repeat on click

Currently I'm working on this website and I made a random image pop up on click, but my client feels like sometimes one image keep repeating too many times so they asked me to make the it random but without repetition.

This is the website link: http://fullbleed.life/about/ (the PAST WORK section is where it should work)

Thank you!

imageString = [
  'http://fullbleed.life/wp-content/uploads/1.png',
  'http://fullbleed.life/wp-content/uploads/2.png',
  'http://fullbleed.life/wp-content/uploads/3.png',
  'http://fullbleed.life/wp-content/uploads/4.png',
  'http://fullbleed.life/wp-content/uploads/5.png',
  'http://fullbleed.life/wp-content/uploads/6.png',
  'http://fullbleed.life/wp-content/uploads/7.png',
  'http://fullbleed.life/wp-content/uploads/8.png',
  'http://fullbleed.life/wp-content/uploads/9.png',
  'http://fullbleed.life/wp-content/uploads/10.png',
]

name = [
  'Nordstrom',
  'Pylon',
  'ASP & Hand',
  'faris',
  'ARA',
  'traceme',
  'Microsoft',
  'Kozha Numbers',
  'Van Der Pop',
  'YFF',
]

function getRandom() {
  var min = 0
  var max = 10
  return Math.floor(Math.random() * max)
}

$('.past-work').bind('click', function(event) {

  var randNum = getRandom()
  var aProduct = document.getElementById('rand-images')
  var image = document.createElement('img')
  image.src = imageString[randNum]
  image.style.display = 'block'
  image.style.position = 'absolute'
  image.style.left = event.clientX - 280 + 'px'
  image.style.top = event.clientY - 280 + 'px'
  aProduct.appendChild(image)

  $(image).draggable()
      event.preventDefault()
})
<body><div class="row">
        <div class="col-md-12 past-work">
                <h1>PAST WORK</h1>
                <h4>(CLICK ANYWHERE, CLICK ANYWHERE AGAIN)</a></h4>
                <div class="picture">
                <div id="rand-images">
                </div>
        </div>
        </div>
        
        
</div>
</body>



Scale variable to be within 0-100 value range

I have created a random array :

X = np.random.random_sample(70)

How can i scale X to be within range of 0 -100 ?




HTML/CSS/JavaScript only random colored boxes play/stop animation

This is supposed to be on an exam, and i would really like to learn it but just couldn't find a way how. It should be done using only HTML / CSS and JavaScript. So the main task is:

We have 6 separate div's stacked in a row horizontally and 2 buttons under those div's ( Play & Stop buttons ) when you click the play button an animation starts playing. The animation is - the first "box" is colored by a random color, then the next "box" is again colored by a random color, while the color on the first box disappears, and so on until all the boxes were colored once and it just starts over again. When you click the Stop button, the animation pauses and continues again when pressed play.




How to find an element in a list at a random position?

I'm new to OCaml and I have this little exercise I need to do. It consists in writing a function that retrieves an element of a list at a random position. I already have a piece of code, but it has major errors, I don't know to put some parts together to make it work: the Random.int, the find-nth function.

What I would like to do is using a Random.int in my find-nth function, and being able to use the find-nth function.

Here's what I've done so far :

let choose l = 
  let rand = Random.int(List.length l) in
  let rec nth l rand = 
    match l with
    | [] -> failwith "Liste vide"
    | e1::l' -> if rand == 0 then e1 else nth l' (rand-1) in;;

For the expected results, it would return an element taken from a random position in the list. I basically have a syntax error with this code.

Thanks




How to Generate Random Damage Points for Game? - Java

I'm building a mini game in which two monsters battle each other (an opponent and the player). When the round starts, the monsters are supposed to fight and their health points decrease by 1, 2, 3, 4 or 5.

I'm using Math.random to randomize the damage dealt to each of the monsters.

How do I decrease each monster's health points when the program is run and the round starts?

Here is my code so far (Monster.java file):

import java.util.Random;

public class Monster {
    // Monster properties
    private String name;
    private int health;
    private int damage;

    // Random damage points that vary from 1 to 5
    int randomDamagePoints = (int)(Math.random() * 1 + 5);

    // Constructor
    public Monster(String name, int health, int damage) {
        this.name = "Monster";
        this.health = 50;
        this.damage = 2;
    }

    // Opponent attacks Monster 1 - Player
    public void AttackPlayer(Monster player) {
        while(health > 0) {
            // Part I need help with
        }
    }

    // Player attacks Monster 2 - Opponent
    public void AttackOpponent(Monster opponent) {
        while(health > 0) {
            // Part I need help with
        }
    }
}

Thank you for your help!




How can I remove characters from a line in a text file without renaming the file?

I want to be able to take a file in a folder and write it to a text file in batch or PowerShell.

The output in the text file should have FileName, NewFileName, DateModified.

The FileName is what the file was named before it was ingested in a program and output.

NewFileName is the name of the file that was output from the program and stored in the output folder.

The powershell script below is what I have used to get the name and date modified of the files to display in a text file.

Get-ChildItem -Path D:\Documents\Projects\Trans-Wrapping\TestOut\NewFiles\Audio\ -Recurse | Select-Object @{n='File'; e={$_.Name + "," + $_.LastWriteTime}} | Out-File "D:\Documents\Projects\Trans-Wrapping\TestOut\NewFiles\Audio\Log.txt"
Get-ChildItem -Path D:\Documents\Projects\Trans-Wrapping\TestOut\NewFiles\Video\ -Recurse | Select-Object @{n='File'; e={$_.Name + "," + $_.LastWriteTime}} | Out-File "D:\Documents\Projects\Trans-Wrapping\TestOut\NewFiles\Video\Log.txt"

However, the output I want is the original file name that was ingested.

FileName before ingested in program Some_Name_file.mxf

NewFileName after ingested random_exactly_37_characters_FileName.mxf_random_exactly_11_characters

The original file does not exist anymore, so I could have just added the path of that and said to write its name. So is there a way I can remove those 37 characters before the file name and the last 11 characters at the end of the filename and write that down on the same text file. I do not want to rename the NewFileName because it would change the date modified parameters.

Can anyone support me in this?




Rat with the randomize path in and 2-D array

The problem is similar to rat-maze problem. I have given an 2-d array MxN. each cell of an array is either 1 or 0 ,where 1 means blocked. I have given 2 points (starting point and ending point). I have to go from start index to end index. But the catch is 1) Path should be random. 2) There should be some parameter which allow me to decide how much random it can be. (i.e how crazily it should wander before reaching to its destination.) 3) Path should not intersect itself.(like a snake game).

This algorithm is needed to create population (randomly) which will used as input for genetic model for further optimize it. For now i have used bfs and created one solution. But the problem is i cannot create any no of random path with this (which i will later use as population) + i'm unable to formalize the idea of how much random it should be.

This is my code that only produces min path by using bfs

def isSafe(x,y,length):
if ((x<length) and (x>-1) and (y<length) and (y>-1)):
    return True;
return False;
def path(room,x1,y1,x2,y2,distance):
roomSize=len(room);
if ((x1==x2) and (y1==y2)):
    room[x1][y1]=distance+1
    return
queue=[[x1,y1]]
room[x1][y1]=0
start=0
end=0
while start<=end:
    x,y=queue[start]
    start+=1
    distance=room[x][y]
    for i in [-1,1]:
        if isSafe(x+i,y,roomSize):
            if room[x+i][y]=="O":
                queue.append([x+i,y])
                room[x+i][y]=distance+1
                end+=1;
    for i in [-1,1]:
        if isSafe(x,y+i,roomSize):
            if room[x][y+i]=="O":
                queue.append([x,y+i])
                room[x][y+i]=distance+1
                end+=1;
def retrace(array,x1,y1,x2,y2):
roomSize=len(array)
if not (isSafe(x2,y2,roomSize)):
    print("Wrong Traversing Point");
if type(array[x2][y2])==str:
    print("##################No Pipe been installed due to path constrained################")
    return [];
distance=array[x2][y2];
path=[[x2,y2]]
x=0
while not (array[x2][y2]==0):
    if ((isSafe(x2+1,y2,roomSize)) and type(array[x2+1][y2])==int and array[x2+1][y2]==array[x2][y2]-1):
        x2+=1;
        path.append([x2,y2]);
    elif ((isSafe(x2-1,y2,roomSize)) and type(array[x2-1][y2])==int and array[x2-1][y2]==array[x2][y2]-1):
        x2-=1;
        path.append([x2,y2])
    elif ((isSafe(x2,y2+1,roomSize)) and type(array[x2][y2+1])==int and array[x2][y2+1]==array[x2][y2]-1):
        y2+=1;
        path.append([x2,y2]);
    elif ((isSafe(x2,y2-1,roomSize)) and type(array[x2][y2-1])==int and array[x2][y2-1]==array[x2][y2]-1):
        y2-=1;
        path.append([x2,y2]);
return path;



jeudi 26 septembre 2019

How to specify a maximum value in Java's SecureRandom nextLong

In Java I wish to generate a randomly picked long number within an exclusive upper bound.

Normally if it were an Int I could do

int nextInt = new SecureRandom.nextInt(500);

Why can't I also do

long nextLong = new SecureRandom.nextLong(4294967296L);

Is there a work around to this?

Thanks




Random Num Generator (Using Java)

Anyone know how to put a random number generator within the parameters of the method? I keep getting errors whenever I try to make the random number generator object.

Ex:

public static void chooseSubstring (String text, int length, new Random()) {


    }



Trying to use

I got this error while working in Dev-C++:

#ifndef _CXX0X_WARNING_H
#define _CXX0X_WARNING_H 1

#if __cplusplus < 201103L
#error This file requires compiler and library support for the \
ISO C++ 2011 standard. This support is currently experimental, and must be \
enabled with the -std=c++11 or -std=gnu++11 compiler options.
#endif
#endif

I was trying to use the rand() function in random library. How do I fix this issue? Please be specific - I am new to programming and don't understand a lot yet. I've seen a similar question asked a couple other places but people just say "do what the error says" which is not helpful when I don't understand it or how to fix it. Do I need a different compiler? How do I do that?




Why does C not calculate the module correctly and despite this the result is correct?

I'm learning to use the random function (srand and rand) to run a dice roll simulation. The program works very well; I throw the dice 200 times and I put each result into the vettore array.

However, analyzing the calculation of the rest of the module I realized that it is not calculated correctly. For example:

1131946436 % 6 = 2 

(calculated by hand and with python and with a calculator).

the module is calculated as follows:

1131946436 / 6 = (int) 188657739
188657739 * 6 = 1131946434
1131946436 - 1131946434 = 2

while C gives me 3.

Nevertheless the program works correctly. I thought it was an int overflow problem but if you look at the results of rand() we are always under 2147483647 (the int signed limit on my 64 bit computer).

I can't understand why C doesn't calculate the module correctly and despite this the program works correctly.

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

#define MAX_SHOTS 200
#define MAX_NUMBERS 6

int main(void) {
    int a;
    int vettore[MAX_SHOTS] = {0};

    srand((unsigned) time(NULL));

    for (int i = 0; i < MAX_SHOTS; ++i) {
        a = rand() % MAX_NUMBERS;
        vettore[i] = a;
        printf("vettore[%d] = %d - %d\n", i, a, rand());
    }

    printf("Tiro di un dado: su %d tiri è uscito:\n", MAX_SHOTS);
    for (int j = 0; j < MAX_NUMBERS; ++j) {
        printf("%d)\t", j + 1);
        int num = 0;
        for (int i = 0; i < MAX_SHOTS; ++i) {
            if (vettore[i] == j) {
                ++num;
                printf("*");
            }
        }
        printf(" (%d)\n", num);
    }

    return 0;
}



How to make a method call a different randInt every time

When I call the method damagecalc and damagemagiccalc it return a Random Int, but its the same random int even when the call is in a while loop.

https://repl.it/@vismaypikachu/Adventure-Game




Why (in Python) is random.randint so much slower than random.random?

I got curious about the relative speeds of some random integer generating code. I wrote the following to check it out:

from random import random
from random import choice
from random import randint
from math import floor
import time

def main():
    times = 1000000

    startTime = time.time()
    for i in range(times):
        randint(0,9)
    print(time.time()-startTime)

    startTime = time.time()
    for i in range(times):
        choice([0,1,2,3,4,5,6,7,8,9])
    print(time.time()-startTime)

    startTime = time.time()
    for i in range(times):
        floor(10*random())##generates random integers in the same range as randint(0,9)
    print(time.time()-startTime)

main()

The results of one trial of this code were

0.9340872764587402

0.6552846431732178

0.23188304901123047

Even after executing multiplication and math.floor, the final way of generating integers was by far fastest. Messing with the size of the range from which numbers were generated didn't change anything.

So, why is random way faster than randint? and is there any reason why (besides ease of use, readability, and not inviting mistakes) that one would prefer randint to random (e.g., randint produces more random pseudo-random integers)? If floor(x*random()) feels not readable enough but you want faster code, should you go for a specialized routine?

def myrandint(low,high):   ###still about 1.6 longer than the above, but almost 2.5 times faster than random.randint
    return floor((high-low+1)*random())+low  ##returns a random integer between low and high, inclusive. Results may not be what you expect if int(low) != low, etc. But the numpty who writes 'randint(1.9,3.2)' gets what they deserve.




How to keep a randomization formula from randomizing at each change in the sheet?

I have this cute formula:

=sort(A1:A416,arrayFormula(randbetween(sign(row(A1:A416)),C1)),true)

I thought I could change the randomization event when I changed the value in C1, but now I see this is changing continuously when I update the sheet with other values.

How can I keep this from happening?

I only want the randomization to happen when I change the seed in C1.




random order quiz ِDynamic

I want my program to ask random questions and have dynamic answers But it only asks random questions and I need a dynamic answer

Button btn_1,btn_2;
TextView text;
setContentView(R.layout.activity_main);
btn_1=findViewById(R.id.btn_1);
btn_2=findViewById(R.id.btn_2);
text=findViewById(R.id.text);

int min = 1;
int max = 3;

Random r = new Random();
int rand = r.nextInt(max - min + 1) + min;
String[]question={"What is Name Color Sky ?",
      "What is Name Color Night?",
        "What is Blood Color?"
};

String[]answer={"Blue ",
        "Black",
        "White",
        "Red",
        "Green"
        ,"Purple"

};
text.setText(question[rand]); }

Screen




How do I get random values from nested dictionaries?

So, I'm fairly new to Python and trying to teach myself with the help of some books right now. I'm currently working on a personal project where I simulate a hand of playing cards. I have a dictionary with four nested dictionaries representing each suit, and for each of those dictionaries I have all cards that would be present.

I've tried searching for ways to get these values, but everything I've found has either been for Python 2.x and doesn't work anymore, or only seems to go one dictionary deep.

deck = {
    'Spades': {'Aces': 1, 'Twos': 1, 'Threes': 1, 'Fours': 1, 'Fives': 1, 'Sixes': 1, 'Sevens': 1, 'Eights': 1, 'Nines': 1, 'Tens': 1, 'Jacks': 1, 'Queens': 1, 'Kings': 1},
    'Diamonds': {'Aces': 1, 'Twos': 1, 'Threes': 1, 'Fours': 1, 'Fives': 1, 'Sixes': 1, 'Sevens': 1, 'Eights': 1, 'Nines': 1, 'Tens': 1, 'Jacks': 1, 'Queens': 1, 'Kings': 1},
    'Hearts': {'Aces': 1, 'Twos': 1, 'Threes': 1, 'Fours': 1, 'Fives': 1, 'Sixes': 1, 'Sevens': 1, 'Eights': 1, 'Nines': 1, 'Tens': 1, 'Jacks': 1, 'Queens': 1, 'Kings': 1},
    'Clubs': {'Aces': 1, 'Twos': 1, 'Threes': 1, 'Fours': 1, 'Fives': 1, 'Sixes': 1, 'Sevens': 1, 'Eights': 1, 'Nines': 1, 'Tens': 1, 'Jacks': 1, 'Queens': 1, 'Kings': 1}
}

I want to create a function that will return a random card, and I can get one random value from the deck variable, using random.choice(list(deck.keys())), but I can't get into those dictionaries, and I feel that it's really simple and I'm just being dumb.




How to get random number in forked processes?

I'm forking few processes and I need each process to perform a task on a randomly selected items. I found that the forked processes pick the exact same random numbers. I tried generating seeds and call srand(), but it didn't help much. Actually, most documentation I've read suggest to avoid srand() "unless you know exactly what you're doing".

Here is my code:

#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long qw(GetOptions);
use Time::HiRes qw(time);
use MongoDB;
#use Math::Random::Secure qw(rand);

my $num_clients = shift;
my $num_loops = 50_000_000;

sub test_forked_sub {
    my $sum=0;
    my $random_offset = rand(120);
    printf "time: %10.4f -  Random offset: %6.2f at pid: %s  \n", time(), $random_offset, $$;
    for (my $i=0; $i < $num_loops  ; $i++) {
        $sum += rand(120);
    }
}

my $nub_processes = 0;
for (my $client_id =0; $client_id < $num_clients; $client_id++ ) {
    if (my $pid = fork) {     #Parent
        $nub_processes++;
    }
    else {         # child
        die "cannot fork: $!" unless defined $pid;
        test_forked_sub();
        exit(0);
    }
}

while ($nub_processes){
    wait;
    $nub_processes--;
}

When I run it I get the exact same "random" number in each of the processes:

$ time ./test_rand_fork.pl 10
time: 1569510011.6891 -  Random offset:  46.64 at pid: 2091
time: 1569510011.6937 -  Random offset:  46.64 at pid: 2092
time: 1569510011.6987 -  Random offset:  46.64 at pid: 2093
time: 1569510011.7028 -  Random offset:  46.64 at pid: 2094
time: 1569510011.7070 -  Random offset:  46.64 at pid: 2095
time: 1569510011.7097 -  Random offset:  46.64 at pid: 2096
time: 1569510011.7144 -  Random offset:  46.64 at pid: 2097
time: 1569510011.7203 -  Random offset:  46.64 at pid: 2098
time: 1569510011.7230 -  Random offset:  46.64 at pid: 2099
time: 1569510011.7249 -  Random offset:  46.64 at pid: 2100

real    0m3.974s
user    0m32.955s
sys     0m1.444s

A possible but ugly solution, it not to fork. Instead, to run multiple instances from my shell as follows:

# shell processes
$ for i in `seq 1 10`; do  ./test_rand_fork.pl 1 &  done
time: 1569511908.7708 -  Random offset:   7.44 at pid: 4129
time: 1569511908.8070 -  Random offset:  19.50 at pid: 4131
time: 1569511908.8068 -  Random offset:  97.59 at pid: 4132
time: 1569511908.8073 -  Random offset:  14.51 at pid: 4133
time: 1569511908.8077 -  Random offset:  16.70 at pid: 4134
time: 1569511908.8080 -  Random offset: 108.63 at pid: 4138
time: 1569511908.8079 -  Random offset:  69.44 at pid: 4137
time: 1569511908.8080 -  Random offset:  83.25 at pid: 4136
time: 1569511908.8080 -  Random offset:  43.33 at pid: 4135
time: 1569511908.8203 -  Random offset:  33.82 at pid: 4139

As the "shell processes" is an ugly solution, I tried to use Math::Random::Secure. Here are the results I get randomness as needed but it is 50 times slower than the "shell processes" approach:

# using: Math::Random::Secure qw(rand);
$ time ./test_rand_fork.pl 10
time: 1569510036.9331 -  Random offset: 112.48 at pid: 2128
time: 1569510036.9470 -  Random offset:  47.15 at pid: 2129
time: 1569510036.9501 -  Random offset:  20.77 at pid: 2130
time: 1569510036.9517 -  Random offset:  40.98 at pid: 2131
time: 1569510036.9521 -  Random offset:  13.84 at pid: 2132
time: 1569510036.9538 -  Random offset:  20.43 at pid: 2133
time: 1569510036.9543 -  Random offset:  48.48 at pid: 2134
time: 1569510036.9563 -  Random offset: 109.29 at pid: 2135
time: 1569510036.9579 -  Random offset:  70.30 at pid: 2136
time: 1569510036.9601 -  Random offset:  24.31 at pid: 2137

real    3m17.251s
user    32m31.129s
sys     0m1.054s

The randomness I need is not for security purposes, I just need a good spread. Is there a way to generate a good-enough seed for the forked processes and still use the standard rand() or alternative faster way? or at least something that doesn't require installing additional library?




mercredi 25 septembre 2019

C++ Dual Stack randNum and clock() not functioning properly(HELP)

Alright so the code pretty much allocates space for a dualstack, has some structs that are pushed into the stack. Its all based on Star Wars so there are multiple ships coming in to fix, Tie Fighters, and Star Destroyers. Whether they are a TF or SD is based on a step function which is not working properly because of the rand() function not working properly. Its the same number over and over and over, and Im not sure why as it should change every loop. Also my times are very messed up as with the clock() function and im clueless about it so please help. Comment if you have any questions. I will be standing by. Thanks!

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
const int MAX = 20;
int vmr = 0;
int seed;
int upper;
int lower;
float randNum;
float randNumArr;
int dagabacount = 0;
int numberArrivals;
clock_t start;
double duration;
int fixedvehicles = 0;

//struct for vmr
struct vmr{
    char type;
    char name;
    int repairTime;
    int startTime;
    int finishTime;
};

//declaring dualstack
class repairStack
{
    private:
        int topT;
        int topS;
        int ele[MAX];

    public:
        repairStack();
        void pushTie   (struct vmr);
        void pushStar  (struct  vmr);
        int  popTie    (int *vmr); 
        int  popStar   (int *vmr);
}; 

//initializing dualstack
repairStack::repairStack()
{
    topT = -1;
    topS = MAX;
}

//pushing to tiestack
void repairStack::pushTie( struct vmr )
{
    if( topS == topT + 1 )
    {
        cout<<"\nStack Overflow tStack" << endl;
        dagabacount++;
        return;
    }

    topT++;
    ele[topT] = vmr;

    cout<<"\nInserted item in tStack : "<< vmr;    
}

//pushing to starstack
void repairStack::pushStar( struct vmr )
{
    if( topS == topT + 1 )
    {
        cout<<"\nStack Overflow sStack"<< endl;
        dagabacount++;
        return;
    }

    topS--;
    ele[topS] = vmr;

    cout<<"\nInserted item in sStack : "<< vmr;    
}

//popping to tiestack
int repairStack::popTie( int *vmr )
{
    if( topT == -1 )
    {
        cout<<"\nStack Underflow tStack"<< endl;
        return -1;
    }

    *vmr = ele[topT--];
    return 0;
}

//popping to starstack
int repairStack::popStar( int *vmr )
{
    if( topS == MAX )
    {
        cout<<"\nStack Underflow sStack"<< endl;
        return -1;
    }

    *vmr = ele[topS++];
    return 0;
}

int getNumArrivals(){
        srand((unsigned)time(NULL));
        randNumArr = float(rand()) / (float(RAND_MAX) + 1.0);
          if(randNumArr < 0.25){
             return 1;
          }
          else if(.25 <= randNumArr < .50){
              return 2;
          }
          else if(.50 <= randNumArr < .75){
              return 3;
          }
          else{
             return 4;
          }
}

int main()
{ 
    //asking user for bounds
    cout << "Please give seed value: ";
    cin >> seed;
    cout << "Please give lower bound of stack: ";
    cin >> lower;
    cout << "Please give upper bound of stack: ";
    cin >> upper;
    cout << MAX<< endl;

    //initalizing stack 's'
    repairStack s = repairStack();

    //initializing clock to 0 for first arrivals
    start = clock();
    duration = ( clock() - start ) / (double) CLOCKS_PER_SEC;
    cout<<"printf: "<< duration <<'\n';

    while(dagabacount < 5){
        //getting numberArrivals either 1,2,3,4
        numberArrivals = getNumArrivals();
        for(int i = 0; i < numberArrivals; i++){
        //getting random number between 0 and 1 to see if its T or S
          srand((unsigned)time(0));
          randNum = float(rand()) / (float(RAND_MAX) + 1.0);
          //if tie then push tie
          if(randNum < 0.75){
            struct vmr Tie_A;
            Tie_A.type='T';
            Tie_A.repairTime = 3;
            Tie_A.startTime = clock();
            Tie_A.finishTime = 0;
            Tie_A.name = 'A';
            s.pushTie(Tie_A);
          }
          //if star then push star
          else{
            struct vmr StarA;
            StarA.type='S';
            StarA.repairTime = 7;
            StarA.startTime = clock();
            StarA.finishTime = 0;
            StarA.name = 'A';
            s.pushStar(StarA);
          }
        }

        //fixing star if star stack is not empty, if so, fix a tiefighter if theres one in stack
        if(s.popStar(&vmr) == 0){
            cout << "fixed star" << endl;
            fixedvehicles++;
        }
        else{
            if(s.popTie(&vmr) == 0){
                cout << "fixed tie" << endl;
                fixedvehicles++;
            }
            else{
                cout << "Underflow" << endl;
            }
        }

    }
        cout << "5 Vehicles Rejected" << endl;
        cout << "# of Vehicles Serviced: " << fixedvehicles << endl;
        cout << "Average Time of Repair: " << endl;
    return 0;
}



Should 99 percentile of a set of two lists be the average of 99 percentile of each list?

For example, the 99 percentile value of list A is p99_a, the 99 percentile value of list B is p99_b, list C is the full set of A and B, should the 99 percentile value of list C be the 99 percentile value of p99_a and p99_b or the average value of p99_a and p99_b?

I always thought it should be the former one, however, I tried it on codes:

import numpy as np
import random
data = []
p99list = []
for i in range(10000):
    one_data = [random.randrange(10000) for x in range(1000)]
    data += one_data
    p99list.append(np.percentile(one_data, 99))

print('p99 of all data: \t' + str(np.percentile(data, 99)))
print('average of p99: \t' + str(np.average(p99list)))
print('p99 of p99 : \t' + str(np.percentile(p99list, 99)))

The results were:

p99 of all data:    9899.0
average of p99:     9889.646635999998
p99 of p99 :    9952.01

It showed that average of p99 was closer to the p99 of all data than p99 of p99. On the Contrary, if I changed the sixth line of code to as follows (on the purpose of simulating the response time of HTTP reuqests):

one_data = [random.uniform(0.2, 0.4) for x in range(1000), random.uniform(1.0, 1.2) for y in range(5)]

I ran the code again, and the results were:

p99 of all data:    0.39801099789433964
average of p99:     0.37998116766051837
p99 of p99 :    0.39904330107367425

It turned out that p99 of p99 was closer to the p99 of all data than average of p99.

So which one is more accurate?




Randomly insert 1 of 3 declared variables

I have three variables that are declared and have an integer value assigned to them.

I am trying to randomly assign the integer value to a field in an UPDATE statement, but get an error.

This is statement I am trying to execute:

FOR user_record IN (SELECT * FROM users_to_add) LOOP
    UPDATE 
        customer."user"
    SET
        primary_site_id  = ({site_GRO, site_WHS, site_SHR}[])[ceil(random()*3)],
    WHERE
        userid = (SELECT userID FROM customer.user
                  WHERE emailaddress=user_record.email_address);           
END LOOP;

I am getting:

SyntaxError: syntax error at or near "{"

This same format works if the value being randomly selected is a string but since these are variables, the inside curly brackets can't be enclosed in quotes.




Shuffle random image from array

I'm new in JS and currently working on my memory card game. The point is to open all the cells and memorise images. Each cell shows you random picture and turns back. It means you have to look through all the cards unless you match all identical ones. So far I've managed to generate a field with certain number of cells and appended each cell with one image (cards' back). How can I append one random picture from array (cards' front) with certain cell when onclick method happens?

var images = ["cards/club.png", "cards/heart.png", "cards/spade.png", "cards/star.png"];

function imgRandom(imgArr) {
    return imgArr[Math.floor(Math.random() * imgArr.length)];
}

function createTable() {
    var table = document.getElementById("gameBoard");
    var card = document.getElementById("cardBack");

    table.innerHTML = "";
    for (var i = 0; i < size; i++) {
        var row = document.createElement("tr");
        for (var j = 0; j < size; j++) {
            var cell = document.createElement("td");
            var backImg = document.createElement('img');
            backImg.className = "cardBack";
            cell.className = "square";
            cell.id = i + ',' + j;

            cell.appendChild(backImg);

            backImg.onclick = function () {
                console.log(imgRandom(images));
            }
            row.appendChild(cell);
        }
        table.appendChild(row);
    }
}



Polymorphism with Distribution in C++11

I have a problem where I want a single object to represent any distribution class (polymorphism) used in random library in c++11. Since distribution does not have a common base class as far as I know I am using factory pattern to solve my problem. Is there a better way to do so ? I am adding the code below which has some errors

#include <iostream>
#include<random>

using namespace std;

class Distribution 
{
public:
    void *distribution;
    virtual void get_distribution() = 0;
};

class normal_dist: public Distribution
{
public:
    //normal_distribution<double> *distribution;
    void get_distribution()
    {
        distribution = new normal_distribution<double>(5.0,2.0); 
    }
};

class uniform_real_dist: public Distribution
{
public:
    //uniform_real_distribution<double> *distribution;
    void get_distribution()
    {
        distribution = new uniform_real_distribution<double>(0.0,1.0);
    }
};

class Helper
{
public:
    Distribution *dist;
    default_random_engine generator;

Helper(string dist_type) 
{
    if(dist_type == "normal")
    {
        dist = new normal_dist;
        dist->get_distribution();
    }
}
};


int main() {

Helper *help = new Helper("normal");
cout<<(*(help->dist->distribution))(help->generator);


// your code goes here
return 0;
}

My questions are three fold 1) Is there a base class of distribution 2) if no, is there a way to create polymorphism 3) Whether the above code is correct approach and what is the bug and how to solve this. I would be very thankful if someone could help me on this




Random Forest Output in Rattle is Different on Different Machines

Using Rattle in R, but on different machines, I get different results when running random forest routine, although ALL settings are set the same. Any ideas why?




Excel crashing randomly

I generate over 100 reports daily in Excel, all with extensive VBA code. Unfortunately, some files are randomly corrupted for no reason that I can define. Either the file will crash immediately upon open, the user will get the "can't find project or library" error, a bad parameter warning will show, or the workbook will be completely unusable as all VBA functions are frozen. In the windows log I will usually see a faulting module for VBE7.dll. I am running Windows 10 and Excel 64bit with all updates. I've reinstalled MS Office and Windows with no help. I've tried various other fixes (registry changes) that did not help either. This is a random problem as it doesn't happen to every report but it occurs every day to some of them. All can be repaired by opening in safe mode and recompiling the code but this is not something I can expect users to do nor do they have access to the code (all pw protected). I've dealt with this issue for the last two years and nothing has worked. Microsoft has been utterly unhelpful as well. Any help would be greatly appreciated. Additionally, for any true experts out there who could dig into this and find a solution I am certainly willing to pay for your time and expertise. Thank you.




How to show two lines overlapping in turtle graphics

enter image description here

I made a random walk program using turtle and I want it show where the two turtles cross paths by changing the color.

`import turtle as T
 import random as R
 t = T.Turtle()
 u = T.Turtle()
 t.speed(0)
 u.speed(0)
 t.hideturtle()
 u.hideturtle()
 t.color("red")
 u.color("blue")
 def randWalk(num):
     for i in range(0, num):
         x = R.choice((-1,1))
         X = R.choice((-1,1))
         y = R.choice((-1,1))
         Y = R.choice((-1,1))
         t.forward(x)
         u.forward(X)
         if y == 1:
             t.left(90)
             t.forward(1)
         else:
             t.right(90)
             t.forward(1)
         if Y == 1:
             u.left(90)
             u.forward(1)
         else:
             u.right(90)
             u.forward(1)    
 randWalk(4000)`



Shuffling large memory-mapped numpy array

I have an array of dimension (20000000, 247) of size around 30 GB in a .npy file. I have 32 GB available memory. I need to shuffle the data along rows. I have opened the file in mmap_mode. However, if I try anything other than in-place modification, for example np.random.permutation or creating a random.sampled array of indices p and then returning array[p], I get MemoryError. I have also tried shuffling the in chunks and then try stacking the chunks to build the full array, but MemoryError. The only solution I have found till now is loading the file in mmap_mode = 'r+' and then doing np.random.shuffle. However, it takes forever (it has been 5 hours still it's getting shuffled).

Current code:

import numpy as np
array = np.load('data.npy',mmap_mode='r+')
np.random.seed(1)
np.random.shuffle(array)

Is there any faster method to do this without breaking the memory constraint?




Discrepancy between 2 functions [PHP]

I have 2 functions, in first I'am generation random number and setting probability. In second functions cheking the generated number is in certain range. And if its in certain range setting value to variable.

            function chance($input = array()) {
                $number  = rand(0, array_sum($input) * 10);
                $starter = 0;
                $b       = 3;
                foreach ($input as $key => $val) {
                    $starter += $val * 10;
                    if ($number <= $starter) {
                        $ret = $key;
                        break;
                    }

                }
                return $ret;
                //return $b;;
            }

            function in_range($number, $min, $max, $inclusive = FALSE) {
                if (is_int($number) && is_int($min) && is_int($max)) {
                    return $inclusive ? ($number >= $min && $number <= $max) : ($number > $min && $number < $max);
                }

                return FALSE;
            }

            $array = array(
                rand(0, 9885) => 81.9,
                rand(9886, 9985) => 15.1,
                rand(9986, 9993) => 1,
                rand(9994, 9997) => 0.09,
                rand(9998, 9999) => 0
            );
    $rolledNumber = chance($array);
                $coinsWon = 0;
if (in_range($rolledNumber, 0, 9885) == true) {
        $coinsWon = 5;
                } elseif (in_range($rolledNumber, 9886, 9985) == true) {
                    $coinsWon = 10;
                } elseif (in_range($rolledNumber, 9986, 9993) == true) {
                    $coinsWon = 50;
                }

After a few tests found that there are dismaches. For example:

Getting number 9884, and the value of coinswon is 10, but should be 5. Also I thing that the probability options its not working properly, because for 9986, 9993 numbers I've set 1% probability, but numbers in this range are generated frequently




Exploit Software Insecurity with Bash

I have an executable C program on a linux machine. The program is intended to reveal a "secret" once the password is entered. I found an exploit by using the backup function of the code which is not requiring me to enter the (correct) password. Also, I know where the backup is saved and that the backup name is generated randomly using the time as a seed. However, I have have difficulties writing a shell script which outputs the secret into the terminal.

My attempt was to make the C program create a backup. The problem however, is writing the random number generator in bash using the time as seed to get the file name of the backup. Also, using echo to output to the terminal does not seem to work.

Below is the code of the c program:

#include <stdio.h> 
#include <string.h> 
#include <unistd.h> 
#include<stdlib.h> 
#include <time.h>
// Execute any shell command
void execute(char *cmd)
{
execl("/bin/bash", "bash", "-p", "-c", cmd, NULL);
}
void sanitise(char *password)
{
int i,j;
char tmp[15];
// remove non-alphabet characters from passwords
j=0;
for(i=0; i < 15; ++i)
if(password[i] >= 'a' && password[i] <= 'z') { tmp[j]=password[I];
++j;
} else break; tmp[j] = '\0';
strcpy(password, tmp); }
int authenticate(char *str) {
char stored_password[15]="";
char pass[15];
char path[128] = "/etc/comp2700/bob/password"; int I;
FILE *fpp; int auth=0;
fpp = fopen(path, "r");
if(fpp == NULL) {
printf("Password file %s not found\n", path);
exit(1); }
fgets(stored_password, 15, fpp); sanitise(pass);
strcpy(pass, str); sanitise(pass);
if(strcmp(stored_password,pass) == 0) auth=1;
else {
 auth=0;
}
fclose(fpp);
return auth; }

int main(int argc, char* argv[], char *envp[]) {
unsigned int seed=time(0); 
// use current time as the seed for therandom number generator 
char user[16];
int r;
char command[128];
int choice=0;
if(argc < 4) {
printf("Usage: %s choice user password\n", argv[0]);
printf("To display the secret, use choice=1, e.g. \n\n %s 1 bob password\n\n", argv[0]); 
printf("To backup the secret, use choice=2, e.g., \n\n %s 2 bob password\n\n", argv[0]);
return 0; }
strcpy(user, argv[2]); printf("Welcome, %s!\n", user);
srand(seed); // change the seed for random number generator r = rand();
// generate a random number
choice = atoi(argv[1]);
if(choice == 1) { if(!authenticate(argv[3])) {
printf("Wrong password.\n");
return 0; }
execute("/bin/cat /etc/comp2700/bob/secret"); }
else if(choice == 2) {
// invoke the backup.sh script to copy the secret to the backup folder.
// the filename is randomly generated
sprintf(command, "/home/bob/Public/backup.sh f%d", r); execute(command);
}
else printf("Wrong choice.\n");
return 0; }

File: backup.sh
#!/bin/bash -p
/bin/echo "Copying secret..."
/bin/cat /etc/comp2700/bob/secret > /home/bob/Public/backup/$1

It would really help me if someone could tell me how I can get a shell script to output the secret to the terminal.

Thank you so much in advance!




Generate copula-correlated samples with specified marginals in Python

I have N random variables (X1,...,XN) each of which is distributed over a specific marginal (normal, log-normal, Poisson...) and I want to generate a sample of p joint realizations of these variables Xi, given that the variables are correlated with a given Copula, using Python 3. I know that R is a better option but i want to do it in Python.

Following this method I managed to do so with a Gaussian Copula. Now I want to adapt the method to use a Archimedean Copula (Gumbel, Frank...) or a Student Copula. Ath the beginning of the Gaussian copula method, you draw a sample of p realizations from a multivariate normal distribution. To adapt this to another copula, for instance a bivariate Gumbel, my idea is to draw a sample from the joint distribution of a bivariate Gumbel, but I am not sure on how to implement this.

I have tried using several Python 3 packages : copulae, copula and copulas all provide the noption to fit a particular copula to a dataset but do not allow to draw a random sample from a given copula.

Is there a package that does what I'm looking for, and if not, can you provide some algorithmic insight on how to draw multivariate random samples from a given Copula with uniform marginals ?

Thanks.




Display an item from a list of items

I have a sample:

link

I want the item with the "item-extra" class to be randomly displayed in the item list.

Now, the code rearranges all the elements.

I want the rest to remain fixed and only the one with the "item-extra" class will be moved to each page reload.

var ul = document.querySelector('ul');
for (var i = ul.children.length; i >= 0; i--) {
  ul.appendChild(ul.children[Math.random() * i | 0]);
}
.item-extra {
  color: red;
}
<ul>
  <li>item 1</li>
  <li>item 2</li>
  <li>item 3</li>
  <li>item 4</li>
  <li>item 5</li>
  <li class="item-extra">item extra</li>
</ul>



mardi 24 septembre 2019

Checking if theres two pairs in card hand Python

I am trying to check if there is two pairs in a hand that is random. I have it right now where it'll print one pair so it prints the number of occurrences of that card so if there are 2 twos it'll be 2 x 2 so the first number is the occurrence then the second number is the card number and then to print one pair.

How do I make it where it'll print two pairs instead so checking in a hand of 5 if there is let's say for example 2 x 2 and 2 x 5 so a pair of 2 and 5 then to print out "two pairs".

I added in numbers = cards.count(card) and for the if statement below it then numbers == 2 So that if there is one pair and one pair it prints two pairs and the probability of getting it.

def twopair():
    count = 0
    while True:
        cards = []
        for i in range(5):
            cards.append(random.choice([1,2,3,4,5,6,7,8,9,10,11,12,13]))
        stop = False
        for card in cards:
            number = cards.count(card) # Returns how many of this card is in your hand
            numbers = cards.count(card)
            print(f"{number} x {card}")
            if(number == 2 and numbers == 2):
                print("One Pair")
                stop = True
                break
        if stop:
            break
        else:
            count += 1
    print(f'Count is {count}')



Python probability of a pair

I am trying to make a poker game where it would check if it is a pair or three of a kind or four of a kind.

I am trying to figure out where to insert a while loop. if I should put it in front of the for card in set(cards): statement or the for i in range(5): I want to keep printing 5 cards until it shows either a pair, 3 of a kind, or 4 of a kind.

Then what I want to do is to print the probability of printing one of those options

import random
def poker():
    cards = []
    count = 0
    for i in range(5):
        cards.append(random.choice([1,2,3,4,5,6,7,8,9,10,11,12,13]))
        print(cards)
    for card in set(cards):
        number = cards.count(card) # Returns how many of this card is in your hand
        print(f"{number} x {card}")
        if(number == 2):
            print("One Pair")
            break
        if(number == 3):
            print("Three of a kind")
            break
        if(number == 4):
            print("Four of a kind")
            break