jeudi 31 mai 2018

JavaFx - Coloring a number of paths with different random colors

I have a JSON file of pen strokes which I need to draw in JavaFx UI. Everything is working fine, but now I need to color each stroke with a different color, and originally I used the "path" component which takes a color.

I thought of creating a path for each stroke, save them in an ArrayList and generate random colors to give one to each path. Unfortunately, all strokes are taking the last generated color. I added label beside the strokes and colored them with my generated random colors and that worked just fine with the labels but not with the paths.

How can I give a different color for each path?

Here is the code:

private void setupTimeLine() {

            long maxtime = 0;
            int strokeCount = 1;
            for (InkStroke stroke : strokes) {
                    long time = 0;

                    //get the start point of the stroke
                    double x = stroke.getX(strokeCount-1);
                    double y = stroke.getY(strokeCount-1);
                    System.out.println("Stroke number "+strokeCount+" - start x = "+x+", start y = "+y);

                    //create a path for each stroke with a random color
                    path = new Path();
                    path.setStrokeWidth(1);
                    Random rand = new Random();
                    double r = new Double (rand.nextFloat());
                    double g = new Double (rand.nextFloat());
                    double b = new Double (rand.nextFloat()); 
                    Color randomColor = new Color(r, g, b, 1);
                    System.out.println("Color = "+ randomColor.toString());
                    paths.add(path);
                    colors.add(randomColor);

                    //create a label to numerate each path with the same random color
                    Label number = new Label(Integer.toString(strokeCount));
                    number.setTextFill(randomColor);
                    pane.getChildren().add(number);
                    number.relocate(x, y-30);


                    for (int i = 0; i < stroke.getSize(); i++) {
                         final Integer final_i = new Integer(i);
                         long duration = stroke.getTimestamp(i);
                         KeyFrame frame = new 
                         KeyFrame(Duration.millis(duration + maxtime), ae -> addPoint(final_i, stroke, paths.size()));
                         timeline.getKeyFrames().add(frame);
                         time = duration;    
                     }

                    maxtime += time; 
                    strokeCount= strokeCount + 1;
           }
           // adding paths to UI and color them with random colors
           for (int i=0;i<paths.size();i++){
                paths.get(i).setStroke(colors.get(i));
                pane.getChildren().add(paths.get(i));
           }

}

And here is the result I am getting where all paths are taking the last generated color: enter image description here




My GameOver sprite is not appearing (swift)

This is my code. Is there a problem with my sprite, function or my PhisicsDelegate? I went to a few websites and according to them, this code should work. I am trying to create a breakout game and trying to create a game over sprite.

import SpriteKit import GameplayKit import AVFoundation

class GameScene: SKScene, SKPhysicsContactDelegate {

var fingerIsOnPaddle = false

let ballCategoryName = "ball"
let paddleCategoryName = "paddle"
let brickCategoryName = "brick"
let bottomCategoryName = "bottom"

let ballCategory:UInt32 = 0x1 << 0
let bottomCategory:UInt32 = 0x1 << 3
let brickCategory:UInt32 = 0x1 << 1
let paddleCategory:UInt32 = 0x1 << 2

override init(size: CGSize) {
    super.init(size: size)

    self.physicsWorld.contactDelegate = self

    let backgroundImage = SKSpriteNode(imageNamed: "bg")
    backgroundImage.position = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height / 2)
    self.addChild(backgroundImage)

    self.physicsWorld.gravity = CGVector(dx: 0, dy: -1)

    let worldBorder = SKPhysicsBody(edgeLoopFrom: self.frame)
    self.physicsBody = worldBorder
    self.physicsBody?.friction = 0
    worldBorder.restitution = 1



    let ball = SKSpriteNode(imageNamed: "ball")
    ball.name = ballCategoryName
    ball.position = CGPoint(x: self.frame.size.width / 4, y: self.frame.size.height / 4)
    self.addChild(ball)

    ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.frame.size.width / 2)
    ball.physicsBody?.friction = 0
    ball.physicsBody?.restitution = 1
    ball.physicsBody?.linearDamping = 0
    ball.physicsBody?.allowsRotation = true

    ball.physicsBody?.applyImpulse(CGVector(dx: 15, dy: -15))

    let paddle = SKSpriteNode(imageNamed: "paddle")
    paddle.name = paddleCategoryName
    paddle.position = CGPoint(x: frame.midX, y: paddle.frame.size.height * 2)

    self.addChild(paddle)

    paddle.physicsBody = SKPhysicsBody(rectangleOf: paddle.frame.size)
    paddle.physicsBody?.friction = 0
    paddle.physicsBody?.restitution = 0.1
    paddle.physicsBody?.isDynamic = false

    let bottomRect = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: self.frame.size.width, height: 0.5)
    let bottom = SKNode()
    bottom.physicsBody = SKPhysicsBody(edgeLoopFrom: bottomRect)

    self.addChild(bottom)

    bottom.physicsBody?.categoryBitMask = bottomCategory
    ball.physicsBody?.categoryBitMask = ballCategory
    paddle.physicsBody?.categoryBitMask = paddleCategory

    ball.physicsBody?.contactTestBitMask = bottomCategory | brickCategory

    let numberOfRows = 3
    let numberOfBricks = 5
    let brickWidth = SKSpriteNode(imageNamed: "brick").size.width
    let padding:Float = 20

    let xOffset:Float = (Float(self.frame.size.width) - (Float (brickWidth) * Float(numberOfBricks) + padding * (Float(numberOfBricks) - 1))) / 2

    for index in 1 ... numberOfRows{

        var yOffset:CGFloat{
            switch index {
            case 1:
                return self.frame.size.height * 0.9
            case 2:
                return self.frame.size.height * 0.7
            case 3:
                return self.frame.size.height * 0.5
            default:
                return 0.2
            }
        }

        for index in 1 ... numberOfBricks {
            let brick = SKSpriteNode(imageNamed: "brick")

            let calc1:Float = Float(index) - 0.5
            let calc2:Float = Float(index) - 1

            brick.position = CGPoint(x: CGFloat(calc1 * Float(brick.frame.size.width) + calc2*padding + xOffset), y: yOffset)

            brick.physicsBody = SKPhysicsBody(rectangleOf: brick.frame.size)
            brick.physicsBody?.allowsRotation = false
            brick.physicsBody?.friction = 0
            brick.name = brickCategoryName
            brick.physicsBody?.categoryBitMask = brickCategory
            brick.physicsBody?.isDynamic = false

            self.addChild(brick)
        }
    }
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first
    let touchLocation = touch?.location(in: self)

    let body: SKPhysicsBody? = self.physicsWorld.body(at: touchLocation!)

    if body?.node?.name == paddleCategoryName {
        fingerIsOnPaddle = true
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if fingerIsOnPaddle {
        let touch = touches.first
        let touchLoc = touch?.location(in: self)
        let prevTouchLoc = touch?.previousLocation(in: self)

        let paddle = self.childNode(withName: paddleCategoryName) as! SKSpriteNode

        var newXPos = paddle.position.x + ((touchLoc?.x)! - (prevTouchLoc?.x)!)

        newXPos = max(newXPos, paddle.size.width/2)
        newXPos = min(newXPos, self.size.width - paddle.size.width / 2)

        paddle.position = CGPoint(x: newXPos, y: paddle.position.y)
    }
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    fingerIsOnPaddle = false
}


func didBegin(_ contact: SKPhysicsContact) {
    let bodyAName = contact.bodyA.node?.name
    let bodyBName = contact.bodyB.node?.name

    if bodyAName == "ball" && bodyBName == "brick" || bodyAName == "brick" && bodyBName == "ball"{
        if bodyAName == "brick" {
            contact.bodyA.node?.removeFromParent()
        } else if bodyBName == "brick" {
            contact.bodyB.node?.removeFromParent()

            var firstBody: SKPhysicsBody
            var secondBody: SKPhysicsBody

            if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
                firstBody = contact.bodyA
                secondBody = contact.bodyB
            } else {
                firstBody = contact.bodyB
                secondBody = contact.bodyA
            }

                if firstBody.categoryBitMask == ballCategory && secondBody.categoryBitMask == bottomCategory {
                    let gameOver = SKSpriteNode (imageNamed: "gameOver")
                    gameOver.position = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height / 2)
                    self.addChild(gameOver)

            }

    }
}

}

}




Generating random numbers with predefined mean, std, min and max

For a research project I am working on, I need to generate a set of random (or pseudo-random) data (say 10,000 datum) with the following parameters:

  • Maximum value = 35;
  • Minimum Value = 1.5;
  • Mean = 9.87;
  • Standard Deviation = 3.1;

Now clearly this distribution will look somewhat like that generated with

scipy.stats.maxwell.rvs(locs=1.5,scale=3.1)

However this does not give the necessary mean or max value. Is there an a possible solution to this?




Why my random change of pixel color doesn't work ? (with PIL)

I wrote this code to change randomly the pixels colors of my image. The random change work one time, but it's all... Afet the first time, it's the same image over and over...

Can you give me a clew ?

from PIL import Image
from random import randint

picture_1 = Image.open("panda.jpg")

largeur, longueur = picture_1.size

print(largeur,"*",longueur)

picture_2 = Image.new("RGB", (largeur, longueur))

for x in range(largeur) :
   for y in range(longueur) :
       (r, g, b) = picture_1.getpixel((x,y))
       r = randint(0,25) ; v = randint(0,255) ; b = randint(0,255)
       picture_2.putpixel((x,y), (r, g, b))


picture_2.save("pandatest6.jpg")
picture_2.show()




Returning forloop to if statement

I'm making a IntegerList in Java. The list containt 6 Integers. [0,1,2,3,4,5]. I have a function getNormalList(). This list must return a list with 3 random Integers. And it may not be 3 the same Integers. The function getNormalList() is not working like I want it to work.

public class SpinResultGenerator {

    public ArrayList<Integer> getNormalList() {
        ArrayList<Integer> integerList = new ArrayList<Integer>();
        Random r = new Random();
        int Low = 0;
        int High = 6;
        for (int i = 0; i < 3; i++) {
            int number = r.nextInt(High - Low) + Low;
            integerList.add(number);
        }
        if (integerList.get(0) == integerList.get(1) && integerList.get(0) == integerList.get(2)
                && integerList.get(1) == integerList.get(2)) {
            integerList.clear();
            for (int i = 0; i < 3; i++) {
                int number = r.nextInt(High - Low) + Low;
                integerList.add(number);
            }
        }
        return integerList;
    }

    public ArrayList<Integer> getJackpotList() {
        ArrayList<Integer> integerList = new ArrayList<Integer>();
        integerList.add(5);
        integerList.add(5);
        integerList.add(5);
        return integerList;
    }
}

In this way, if the result = for example: [4,4,4]. The forloop then work again and is still able to output 3 the same Integers.




Random bytes generation in c++11

I've written a funtion to prouduce random bytes in a uint8_t type array, unless I seed this with a random_device object it works fine but when I seed there are some compiler errors.

code:

#include <algorithm>
#include <random>
#include <functional>
#include <stdint>

void generateInitVector(uint8_t IV_buff[16])
{
using bytes_randomizer = std::independent_bits_engine<std::default_random_engine, CHAR_BIT, uint8_t>;
std::random_device rd;
bytes_randomizer bytes(rd);

std::generate(std::begin(IV_buff), std::end(IV_buff), std::ref(bytes));
}

compiler errors:

  1. error: no matching function for call to 'begin(uint8_t*&)'|

  2. error: request for member 'begin' in '__cont', which is of non-class type 'unsigned char*'|

  3. error: request for member 'begin' in '__cont', which is of non-class type 'unsigned char* const'|

  4. error: no matching function for call to 'end(uint8_t*&)'|

  5. error: request for member 'begin' in '__cont', which is of non-class type 'unsigned char*'|

  6. error: request for member 'end' in '__cont', which is of non-class type 'unsigned char* const'|

  7. error: 'class std::random_device' has no member named 'generate'|

There's catch that if I define a uint8_t type array within th function

uint8_t data[16];
std::generate(std::begin(data), std::end(data), std::ref(bytes));  //and pass this array in `generate()`.

then only error 7 remains.

I'm using codeblocks 16.01

Any solutions to this.

Thanks.




Explaining a switch with random generated number within a specified range, probability of getting the range

Can someone explain how this fragment of code works?

    int rand = ThreadLocalRandom.current().nextInt(0,10);
    switch (rand)
    {
        case 0: return 2;
        case 1: return 1;
        case 2: return 1;
        default: return 0;
    }

Thanks!




mercredi 30 mai 2018

Generating random numbers while using itertools product

I am using a generator function to create ordered lists of numbers along side itertools.product in order to create every possible paring of said numbers:

def gen(lowerBound, upperBound, stepSize = 1):
    for steppedVal in np.arange(lowerBound, upperBound, stepSize):
        yield steppedVal

for vectors in it.product(gen(3,6), gen(10,30,5)):
    print(vectors)

Which as expected produces a data set like this one:

(3, 10)
(3, 15)
(3, 20)
(3, 25)
(4, 10)
(4, 15)
(4, 20)
(4, 25)
(5, 10)
(5, 15)
(5, 20)
(5, 25)

However my problem lies in the next step. I want to add a clause to generator function to use a random number within a range instead of the stepped values. When I try the following:

def gen(useRandom, lowerBound, upperBound, stepSize = 1):
    if useRandom:
        randomVal = random.uniform(lowerBound, upperBound)
        yield randomVal
    else:
        for steppedVal in np.arange(lowerBound, upperBound, stepSize):
            yield steppedVal

for vectors in itertools.product(gen(True,3,6), gen(False,10,30,5)):
    print(vectors)

I get this, which is not what I want:

(4.4163620543645585, 10)
(4.4163620543645585, 15)
(4.4163620543645585, 20)
(4.4163620543645585, 25)

How could I modify this code so that each random number in this data set is unique without having to alter the data set after the fact as that adds huge compute overhead. (The actual data set contains a dozen or so variables with 10-20 steps each).




Why do I need two functions for dice rolling simulator?

I've made a simply dice rolling simulator but afterwards, when looking at other people's examples, they've generally created two functions (Main to define the range 1 - 6, and a roll_dice function). Is it ok as I've done it? To me, the other versions seem more complex (with a while loop for example) without any extra functionality.

My code:

import random

def roll_dice():
    for x in range(1):
        print("You rolled a", (random.randint(1, 6)),"!")
        roll_again = input("Would you like to roll again? (Y or N): ")
        if roll_again.lower() == "y":
        roll_dice()
        if roll_again.lower() == "n":
            print("Thanks for rolling. See you next time")
        else:
            roll_again = input("Would you like to roll again? (Y or N): ")

Thanks!




AttributeError: 'ellipsis' object has no attribute '_jsc'

Actually, I want to generate a random double RDDs (vector RDDs). I used RandomRDDs from pyspark.mllib.random as:

from pyspark.mllib.random import RandomRDDs
sc = ... # SparkContext
u = RandomRDDs.normalRDD(sc, 10000, 10)

But I got this error:

AttributeError: 'ellipsis' object has no attribute '_jsc'

Any Idea?




randomization of treatments with placebo

I want to get a randomization of treatments with three levels; sample size for every level n = 10. There are 2 placebo and 8 treating volonteers in every level. I'm new to R.




Random number generator where the 1st and 2nd derivatives of consecutive values is relatively small

If you were to graph a list of values returned by this algorithm, it might seem smooth and wavy. This would be good for realistic terrain generation, or maybe a unique way of making white noise.




mardi 29 mai 2018

How to create numba cuda random array

Hi i try to create random array with numba cuda. For what i know this can be done by numba.cuda.random.xoroshiro128p. I need to create array like this:

minimum_bound = -5
maximum_bound = 5

variable_number = 6
row_number = 30000000

matrix_raw  = np.random.uniform(minimum_bound, maximum_bound, (row_number, variable_number))

But this is time consuming it takes over 3 sec. How to use xoroshiro to create array faster with numba kernel? Is there a way to create random matrix with cuda by simple code? Thanks for any advice :)




How to create a Fuction and Triggring in Cloud Firestore

I am new to cloud firestore , I want to create a function when a new user has been been added to firestore , it generates a unique random number and save it in a document. How I can achieve it using google cloud console?




Generate Even Amount of Runs in Left and Right Lanes for Racers

I'm working on a spreadsheet for a soap box derby type race that can automatically generate an even amount of runs in the left and right line per racer. It also will randomize who races against who. Currently, I have 6 heats and a button above each one. It pulls from a list of racers with a randomly generated number in the cell next to it using the method shown here: https://www.extendoffice.com/documents/excel/4591-excel-random-selection-no-duplicates.html

This is what the sheet looks like.
img The 'DON'T TOUCH' column is then copied to another sheet and placed in each heat when a button is pressed above that heat. The heat sheet looks like this: img

Each time a heat button is clicked, it will copy and paste from the "Randomizer" sheet and since the sheet refreshes each time, it will be randomized on each button click. The following macro runs when a heat button is clicked.

Sub btnHeat1_Click()
  On Error Resume Next
  Dim xRg As Range
  Dim WS As Worksheet
  Dim Shp As Shape
  Set xRg = Application.Selection
  Set WS = ActiveSheet
  Set Shp = WS.Shapes("btnHeat1")
  Worksheets("Randomizer").Range("E4:E62").Copy
  Worksheets("The Race is On").Range("F4:F62").PasteSpecial xlPasteValues
  xRg.Select
  Shp.Visible = False
End Sub

I need to improve the randomizer so that each racer has an even amount of runs in the left and right lane (3 times each side). I'm not sure how to go about doing this and couldn't find any examples online of a similar situation (drag race heats, golf outings, etc). I thought of recording right and left lane each time a heat button is clicked, but not sure how to implement that into the existing randomizer. Or all the heats need to be generated at once and right and left lanes can represent a 0 and 1 in the randomizer equation.

Any suggestion on how to accomplish this? Thanks!




Generate a graph with n veritces, m edges uniformly at random algorithm

Easy question, haven't found an easy answer. I want a graph with N vertices, M edges, uniformly at random. In a reasonable time complexity (I'd say quasilinear at worst). Does such algorithm exist, and if yes, what is it?




Count how many times a strings appear in random generator

I have a while loop with an string array and a simple randomize for them.

My problem however is to count how many times the same strings have appear when the loop was running.

Ex :
oc/open string has appeared 3 times
rw/read string has appeared 2 times
oc/close string has appeared 3 times

etc....

At the moment im using if else methods inside the loop, but there must be a better way to count them? Any tips?

function injection { 
COUNTER=0
countopen=0
while [ $COUNTER -lt 10 ]; do

module[0]="oc/open"
module[1]="oc/close"
module[2]="rw/read"
module[3]="rw/write"

randModule=$[$RANDOM % ${#module[@]}]
export MODULE=${module[$randModule]}
echo $MODULE

    if [ $randModule == 0 ]; then
        let countopen++
#let countclose++
#etc
#etc

    fi
let COUNTER++
done
    echo "Open $countopen"
}

injection




Mimimum range in PRNG

I was trying to implement some PRNG algorithms in C# (like LCG, Lagged Fibonacci and so on), but I'm not sure about the implementation of a range-constrainted generation. While I understood that the module at the end of the equation is used to limitate to the maximum, I've found no way other than just repeating the process until the result value is greater than the minimum. May I ask if there's a more efficient way to do that?




lundi 28 mai 2018

Pick a number check a db if its there repeat if not store

I am trying to do some code where my server picks a random number between 1 and 5. Then that is done it checks a MySQL DB to see if it is already included in the DB. If it is in the DB it repeats the process. If the number is not found then it adds it to the DB.

I am trying to write the code to do that, however, I am having some difficulty. My attempt is below

let result = 0;
con.connect(function(err) {
if (err) throw err;
while (result >= 1)
    {
        let x = Math.floor((Math.random()*5)+1);
        con.query("SELECT column1, column2 FROM users where column2 = x", function (err, result, fields) 
        {
            if (err) throw err;
            result = result.length;
        });
    }
var sql = "INSERT INTO users (column1, column2) VALUES ('a string', x)";

});




Generate random number while the generated number is on a list - ansible

I'm trying to generate random numbers in ansible while the generated number, exists in a list of numbers.

Let's suppose that my list have this values.

list = [1, 3, 5, 8, 9, 10]

I'm using the module set_fact like this.

- set_fact:
    value: ""
  until: value not in list

The value generated using the random rule always generate the number 1 or 10, I've used the module debug like the code below and it always generate different numbers.

- debug:
    msg: ""

My problem here is, how can I generate random number in a certain interval, like the one above (1,10) and how can I keep generating random numbers while the generated number exists in the list, when the generated number isn't in the list, i want to stop the loop and use this number for something.




Random Float between negative to positive range (-0.2 ... 0.2)

What is the Swifty way to random a Float between a range of negative to positive Floats? for example, random Float between -0.2 to 0.2?

Any help would be highly appreciated.

Best regards,

Roi




Feeding Network with Random Image in Keras

I try to feed network with randomly chosen images. I have two kind of training data ( Base_Train(11k images), Augmented_Train(44k images) ) . Augmented_Train contains 3-5 images which have different perspective than Base images , for each image in the Base_Train. I want to feed network with Base_Train + randomly choosen one image from Augmented_Train for each image in the Base_Train for each epoch. I try to implement with loop. However, it was very ineffective. Randomly choosen image part took about 13 hours for each epoch. Therefore, this is not applicable.

I need an idea on how to implement this in efficient way. If you give me pieces of pseudocodes, I'm gratefull.

Thanks in advance.




Random questions

I would like to ask (know) how to write in javascript random questions. I have already a code and also questions but I don't know how to do in javascript, when user is going to answer on questions, they will be random.

Thanks for help




dimanche 27 mai 2018

C++ Generate Random Amount (x) random integers (num) -- How to display the random integers?

I am stuck on this code (very beginner) and not sure what I am doing wrong. I need to display X number of random integers (num), but I am not sure how to do this.

Currently, I was able to find how to make x random, but do not know how to make it display that many random integers...not sure how or where to enter "num"

Any pointers? Really lost on this. Assignment description below too. Tried to make sure I followed the guidelines, and not sure how to search for this to see if there were duplicates first.

/*
P33: Smallest, Largest, Sum, and Average with Random Numbers
Write a program that generates X random integers Num.
Num is a random number between 20 to 50.
X is a random number between 10 to 15.
Calculate and show the Smallest, Largest, Sum, and Average of those numbers.

Sample Run:
Generating 11 random numbers (11 is a random number between 10 to 15)...

...11 Random Numbers between 20 to 50:  26, 23, 48, 32, 44, 21, 32, 20, 49, 48, 34

Sum = 377

Average = 377 / 11 = 34.3

Smallest = 21

Largest = 49
*/

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

using namespace std;

int sum = 0;
int x = 10+rand()%6;
int num = 20+rand()%31;
int max;
int largest;
int smallest;

int main(void)
{
     srand(time(NULL));
{
while (true){
        int sum = 0;
        int x = 10+rand()%6;
        int num = 20+rand()%31;
        cout<<"Generating " << x << " random numbers (" << x << " is between 10 and 15)... \n";
        int max;
        int largest;
        int smallest;
        cout << "..." << x << " Random Numbers between 20 to 50:  \n";
        largest = num;
        smallest = num;
        sum = sum + num;

        while (x < max - 1)
        {
            cout << num;
            sum = sum + num;
            x++;
            if ( num > largest)
                largest = num;
            if ( num < smallest)
                smallest = num;
        }
        cout << "Largest = " << largest << endl;
        cout << "Smallest = " << smallest << endl;
        cout << "Sum = " << sum << endl;
        cout << "Average = " << sum / max << endl;

            break;
    }
    return 0;
}
}

/*
SAMPLE RUN
==========
Generating 10 random numbers (10 is between 10 and 15)...
...10 Random Numbers between 20 to 50:
Largest = 29
Smallest = 29
Sum = 29
Average = -14

Process returned 0 (0x0)   execution time : 0.172 s
Press any key to continue.

*/




How can I make an algorithm that will randomly put 1's in a 2d array while making sure there's a path from the bottom left to the top right space?

I am trying to make a simple java game where the player cannot see the world (a 2d array) and has to enter "right," "left," "up," or "down." The player has to get from the bottom left to the top right in a certain time. The array will be full of 0's and 1's will be assigned randomly, while making sure there's a path between the start and end. This is what I have so far:

public class PathMaker {

    private int [][]arr;

    public PathMaker(int Difficulty){
        if (Difficulty == 1)
            arr = new int[5][5];
        if (Difficulty == 2)
            arr = new int[5][5];
        if (Difficulty == 3)
            arr = new int[5][5];
        Pathset(arr);
    }

    private static void Pathset(int [][]arr){
        int length = arr.length;
        int trees = (length-1)*2;
        int a, b;
        int check = 0;
        arr[0][0] = 1;
        for (int i = 0; i < trees; i++){
            a = (int)((Math.random()*length)+1);
            b = (int)((Math.random()*length)+1);
            while(check == 0){
                if (((arr[a+1][b] == 0) && (arr[a][b+1] == 0)) || a == 1 || b == 1)
                    check = 1;
                a = (int)((Math.random()*length)+1);
                b = (int)((Math.random()*length)+1);
            }
            arr[a][b] = 1;
        }
    }
}




Anyone know a good ranfom number generator for c# [duplicate]

This question already has an answer here:

So i'm trying to make a procedural cave generator in c# and so far i have the code for generating a completly random map:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;

namespace CelularAutomata
{
    class Program
    {
        static int width=512, height=512;
        Boolean[,] cellmap = new Boolean[width, height];

        static float chanceToStartAlive = 0.45f;

        public static Boolean[,] initialiseMap()
        {
            Boolean[,] map = new Boolean[width, height];

            for (int x = 0; x < width; x++)
            {
                Random rng = new Random();
                for (int y = 0; y < height; y++)
                {
                    doube random = rng.NextDouble();
                    if (random < chanceToStartAlive)
                    {
                        map[x,y] = true;
                    }
                }
            }
            return map;
        }

        public static Bitmap createImage(Boolean[,] map)
        {
            Bitmap bmp = new Bitmap(512, 512);

            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    if (map[x, y])
                    {
                        bmp.SetPixel(x, y, Color.FromArgb(255, 255, 255));
                    }
                    else {
                        bmp.SetPixel(x, y, Color.FromArgb(0, 0, 0));
                    }

                }
                Console.Write('\n');
            }

            return bmp;
        }

        static void Main(string[] args)
        {
            Boolean[,] map = initialiseMap();

            Bitmap bmp = createImage(map);
            bmp.Save("C:\\Users\\radu\\Documents\\Sync\\Licenta\\chamber.png");
        }
    }
}

The image i'm trying to obtain is something like this, except in black and white: desired image

What i'm getting is this: generated image

I believe it's because of the random number generator i'm using (i.e. just Random().NextDouble()). Anyone know a beter RNG for c#?




randomize player color listing in javascript

I have a chess pairing page at http://verlager.com/super-dev.php. The problem is that I need to randomize the player's colors because I am just listing the players in descending order by rating. The higher rated player always gets the white pieces. Not good.

I think I should take the first two players, and randomize a number. If the random number is > 0.5, then the first player has white, else the seconds player has white. List them out. Then take the next two players and do the same. Any suggestions?

for (let i = 0; i < sorted.length; i++) {
        $temp = sorted[i - 1];

//if (i % 2 !== 0) {random = Math.random();} if (random > 0.5;) {player_1 = sorted[i - 1]; player_2 = sorted[i];}


        if ($temp && $temp.length > 0) {     
            var $full = $temp.split(","); var $nick = $full[0]; 
            $name = $nick.substr( 0, 16);
            $("#I" + i).val($name + ", " + $full[1].substr(0, 1) + ". " + members.find(x => x.Name === $temp).Rating);

        }
    }
    }




Javascript in HTML code: Random numbers are not evenly distributed

I've got the following problem: I'm uploading a survey on amazon mturk using Python and the survey is done via HTML and javascript. I show one of three different versions of the survey to participants, which I select by generating a random number via javascript. I store the number in local storage to prevent refreshing the website from resetting it. The problem I find is that more people seem to get versions 1 than version 3. But I cannot recreate the problem for myself when running the code in Tryit Editor online.

Could you please help me understand (and fix) why this happens? The following is the (trimmed) HTML code that I upload. I replaced text and removed fluff, please lmk if you want to see the original. Thank you so much!

<HTMLQuestion xmlns="http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2011-11-11/HTMLQuestion.xsd">
<HTMLContent><![CDATA[
<!-- YOUR HTML BEGINS -->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/>
<script type='text/javascript' src='https://s3.amazonaws.com/mturk-public/externalHIT_v1.js'></script>
<script>
function test(){
    document.getElementById('txt-field').value = "1";
}
</script>
</head>
<body>
<form name='mturk_form' method='post' id='mturk_form' action='https://www.mturk.com/mturk/externalSubmit'><input type='hidden' value='' name='assignmentId' id='assignmentId'/>
  <span>
<INPUT TYPE="text" NAME="link_click" id='txt-field' value="0" style="display: none">    
<div><h3><a href="www.google.com" target="_blank" id='report420' onclick="test()" >link</a></h3>
Instructions</div>
<div><table border="1" style="height: 258px;" width="196"><tbody>Table</tbody></table></div>
</span>
<!--I think the relevant part starts here-->
<script> 

document.write("Miscellaneous question");

var i = localStorage.getItem('i') || Math.floor(3*Math.random());
localStorage.setItem('i',i);

if (i==0){
document.write("Version 1");
}
if (i==1){
document.write("Version 2");
}
if (i==2){
document.write("Version 3");
}
document.write("Miscellaneous question");

</script>
<p><input type='submit' id='submitButton' value='Submit' /></p></form>
<script language='Javascript'>turkSetAssignmentID();</script>
</body></html>
<!-- YOUR HTML ENDS -->
]]>
</HTMLContent>
<FrameHeight>600</FrameHeight>
</HTMLQuestion>




Rand() C after a while, generate always same values in decreasing order [duplicate]

This question already has an answer here:

I'm trying to generate random values between 0 and 3 with the following code. The problem is that after generating random values for the first 5-6 times, then it starts generating all the times in the following order: 3, 3, 3, 2, 2, 2, 1, 1, 1, 0, 0, 0 and then again 3, 3, 3, 2, 2, 2, 1, etc etc. Is there a way to avoid this and to generate COMPLETELY random this numbers?

srand(time(NULL));
i=rand()%4;
while(//condition is not verified//){

    srand(time(NULL));
    i=rand()%4;

}




Variables not passing though if statements?

Look I honestly don't know where my code is going wrong here so I've posted the whole thing. I have made this programme to generate random weather conditions for over land travel in my game of dungeons and dragons. I have tried to generate different weather patterns by making a variable thats value is between 1 and 20 and then comparing it against a range to find out what that days weather was like. The code is as follows:

import random

def day():
    temp = random.randint(1,20)
    wind = random.randint(1,20)
    percip = random.randint(1,20)
    isweird = random.randint(1,20)
    encounter = random.randint(1,12)

    #Temperature block
    if 1 <= temp <= 14:
        daystemp = ("Normal for the season")
    elif 15 <= temp <= 17:
        d4 = (random.randint(1,4))*5
        daystemp = (d4, 'degrees hotter than normal')
    elif 18 <= temp <= 20:
        d4 = (random.randint(1,4))*5
        daystemp = (d4, 'degrees colder than normal')
    else:
        temp = "Process not completed"

    #Wind block
    if 1 <= wind <= 12:
        daystemp = ("None")
    elif 13 <= wind <= 17:
        daystemp = ("Light")
    elif 18 <= wind <= 20:
        daystemp = ("Strong")

    #Precipitation block
    if 1 <= wind <= 12:
        daystemp = ("None")
    elif 13 <= wind <= 17:
        daystemp = ("Light rain or light snowfall")
    elif 18 <= wind <= 20:
        daystemp = ("Heavy rain or heavy snowfall")

    #isweird? Block
    weird = [
    'Dead magic zone (similar to an antimagicfield)',
    'Dead magic zone (similar to an antimagicfield)',
    'Wild magic zone (roll on the Wild Magic Surge table in the Players Handbook whenever a spell is cast with in the zone)',
    'Boulder carved with talking faces','Crystal cave that mystically answers questions',
    'Ancient tree containing a trapped spirit',
    'Battlefield where lingering fog occasionally assumes humanoid forms',
    'Battlefield where lingering fog occasionally assumes humanoid forms',
    'Battlefield where lingering fog occasionally assumes humanoid forms',
    'Wishingwell','Giant crystal shard protruding from the ground',
    'Wrecked ship, which might be nowhere near water',
    'Haunted hill or barrow mound',
    'Field of petrified soldiers or other creatures',
    'Floating earth mote with a tower on it'
    ]
    if 1 <= isweird <= 2:
        isweird = random.choice(weird)
    else:
        isweird = ("No weird locale")

    #Return block
    print(temp)
    print(wind)
    print(percip)
    print(isweird)


days = int(input("How many Days: "))
daybuffer = 0
daterecord = 0

while daybuffer < days:
    daybuffer += 1
    daterecord += 1
    print('\nIt is day ', daterecord)
    print(day())

This code ends up returning (for 1 day or any days)

 It is day  1
 13
 1
 11
 Floating earth mote with a tower on it
 None

So 3 problems:

  1. The Temperature wind and precipitation just shows an integer
  2. The weird locale does work for some reason even though its code is similar
  3. There is a mystery 5th item that just reads None(???)

What the heck is going on?




samedi 26 mai 2018

C++ Do/While Loops and If/Else: Dice game -- Error on Line 75: Expected "While" before "Cout" -- How to fix this?

Beginner coder -- first C++ class.

I keep getting errors at line 75 onward, and I cannot figure out where I went wrong. I know my code is pretty sticky...I need help on cleaning it up. Anyone know how I can code this correctly?

This is the assignment:

Dice (if/else, loop, random):

Using if/else, loops, and random numbers, write a Dice Game program where the user rolls 2 dice and decides whether they want to "hold" those numbers or roll again. It should let the user roll as many times as they like until they hold.

The computer then should roll 2 dice as well. The object of the game is to get a higher score than the computer.

===

Hint: use random numbers b/w 1-6, make 4 random numbers

When I tried to build the program, I get a bunch of errors and don't really know what I am doing wrong (tried to debug myself). Here are the errors:

||=== Build file: "no target" in "no project" (compiler: unknown) ===|
||In function 'int main()':|
|75|error: expected 'while' before 'cout'|
|75|error: expected '(' before 'cout'|
|75|error: expected ')' before ';' token|
|87|error: expected 'while' before 'While'|
|87|error: expected '(' before 'While'|
|87|error: 'While' was not declared in this scope|
|87|error: expected ')' before ';' token|
||=== Build failed: 7 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

Here is the code I have so far--can anyone show me the correct code?:

#include <iostream>
#include <cstdio>
#include <time.h>
#include <stdlib.h>
using namespace std;

int main()
{

srand(time(0));

int Roll1 = 1+(rand()%6);
int Roll2 = 1+(rand()%6);
int UserRoll = Roll1 + Roll2;
int Roll3 = 1+(rand()%6);
int Roll4 = 1+(rand()%6);
int ComputerRoll = Roll3 + Roll4;
string Hold;
string ThrowDice;
string Again;

do
{

do
    {
    cout << "Please enter \"throw\" (lowercase) to roll the dice: ";
    cin >> ThrowDice;
    } while(ThrowDice != "throw");

do
    {
    cout << "You rolled: " << Roll1 << " and " << Roll2 << endl;
    cout << "Would you like to hold onto these numbers or roll again? " << endl;
    cout << "Enter (lowercase) \"hold\" to keep this roll, or \"throw\" to roll again): ";
    cin >> Hold;
        if (Hold != "hold" && Hold != "throw")
        {
            cout << "Your choice isn't valid!  Please try again by typing \"hold\" or \"throw\": " << endl;
        }
    }while (Hold != "hold" && Hold != "throw");

do
    {
        if (Hold == "hold")
        {
        cout << "You chose to keep these numbers, totaling: " << UserRoll << endl;
        cout << "The computer rolled " << Roll3 << " and " << Roll4 << " totaling: " << ComputerRoll << endl;
        } break;

        if (Hold == "throw")
        {
        cout << "You chose to roll again. " << endl;
        }
    }while (Hold == "throw");

do
    {
        if (UserRoll < ComputerRoll)
        {
        cout << "Sorry. You lose. " << endl;
        } break;

        if (ComputerRoll < UserRoll)
        {
        cout << "Congratulations! You win! " << endl;
        } break;

        if (ComputerRoll == UserRoll)
        {
        cout << "It's a draw. " << endl;
        } break;
    }

cout << "Would you like to play again? [Yes/No]: " << endl;
cin >> Again;

if (Again == "Yes")
    {
        continue;
    }

else if (Again == "No")
    {
        break;
    }
}While (Again == "Yes");

return 0;

}




rejection method in python to compute area of ellipse

I am trying to calculate the area of an ellipse by using the rejection method, where (((x^2)/25)+((y^2)/36))=1.

So after reading I know I need to have the pdf which is the area under the curve. So to calculate it I need to integrate the equation above. Therefor, y = 6 - (6x)/5

f(x) = integral of (6 -(6x)/5) dx from 0 to x.




Java Mini Sudoku without backtracking

I've been working on a project on making a mini sudoku (6x6) solver without using backtracking. For this, I've made it so that the solver receives the clues from the answer sheet, make random numbers for all empty spaces, then check the conditions of the sudoku: repeat making numbers if any of them fails. Terribly inefficient, I know, but I wanted to do it this way.

Currently my codes are as follows:

public class Solver
{
    private int[][] sudokuA = new int[6][6];
    private int[][] sudokuR = new int[6][6];
    private int random;
    private int random2;

    public Solver(int[][] sudokuQ)
    {
        for (int i = 0; i<6; i++)
        {
            for (int j = 0; j<6; j++)
            {
                sudokuA[i][j] = sudokuQ[i][j];
                sudokuR[i][j] = sudokuQ[i][j];
            }
        }   
    }

    public boolean condition1(int[] array, int number)
    {
    for (int e = 0; e<6; e++)
    {
        if (array[e] == number)
        {
            return true;
        } 
    }
    return false;

    public void Loop1()
    {
        int refresh[] = new int[6];
        for (int i = 0; i<6; i++)
        {
            for (int r = 0; r<6; r++)
            {
                int input = sudokuR[i][r];
                refresh[r] = input;
            }
            for (int j = 0; j<6; j++)
            {
                if (refresh[j] == 0)
                {
                    boolean match = true;
                    while(match)
                    {
                        random = (int)(Math.random()*6+1);
                        match = condition1(refresh, random);
                    }
                    refresh[j] = random;
                    sudokuR[i][j] = random;
                }   
            }
        }
    }
}

And this code works to meet condition 1 (i.e. horizontal rows are 1 to 6) of the "guess grid". But then comes condition 2, which is to make vertical rows 1 to 6, which I can't seem to get it working for some reason....here is the code:

    public boolean condition2(int[] array, int number)
{
    int count = 0;
    for (int o = 0; o<6; o++)
    {
        if(array[o] == number)
        {
            count++;
        }
    }
    if (count > 1)
    {
        return false;
    }
    return true;
}

public void Loop2()
{
    for (int i = 0; i<6; i++)
    {
        int refresh2[] = new int[6];
        for (int r = 0; r<6; r++)
        {
            int input = sudokuR[r][i];
            refresh2[r] = input;
        }
        for (int j = 0; j<6; j++)
        {
            random2 = refresh2[j];
            if (condition2(refresh2, random2))
            {
                this.Loop1();
                i = -1;
                break;
            }
        }
    }
}

What I wanted to do was that the program checks for condition 2, and keep on making the grid that satisfies condition 1 (with Loop1) until condition 2 is also satisfied as well. However, the program just stops working as soon as I run it, and I don't know what to do;;;




NetLogo: Assign Turtles Randomly but Equally to Different Groups

I used the code below to create 50 turtles and randomly assign them to one of four different strategies (i.e. a, b, c and d):

The problem is that when I decrease the number of created turtles or when I increase the number of strategies, I face a situation where at least one of the strategies is not taken by any turtle.

turtles-own [ my_strategy ]

to setup
  ;; create 50 turtles and assign them randomly
  ;; to one of four different strategies
  create-turtles 50 [
    set my_strategy one-of [ "a" "b" "c" "d" ]
  ]
end

I need your help here to: 1. Make sure that I do not face a situation where one or more strategies are not taken by any turtle. 2. Make sure that the number of turtles assigned to each strategy is roughly equal.




Build a query in Swift 4 for Firebase to select users randomly

I'm new on Swift and Firebase and I'm trying to build a dating app. I need to select the users randomly from Firebase by gender, age and others criterias. Please, how should be the best way to do that?

Thank you very much. Best regards, Evaristo.




Return random rows only once in mysql

I am trying to retrieve random rows from mysql using RAND() function. But in result rows are repeating more than once. Is there any way to return random rows in such a way that a row is returned only once?

My query is: SELECT h.recid recid, h.name name, h.subtitle subtitle, h.pricingfrom pricingfrom FROM holydays h ORDER BY RAND()

I found this solution but I didnt understand how it works as I don't have any limits... Any answer will be appreciated.!




vendredi 25 mai 2018

Spawn blocks at random locations

I'm trying to create elements in random locations on the screen but I have run into some trouble. Creating the elements works but when I try to make them have random locations, nothing happens. Thanks for the help in advance.

Here's my code:

var newObject = document.createElement("DIV");
newObject.setAttribute("class", "object");
newObject.setAttribute("id", "powerup");
document.body.appendChild(newObject);
var powerup = document.getElementById("powerup");
var object = document.getElementsByClassName("object");
for (i = 0; i < object.length; i++) {
object[i].style.top = Math.floor(Math.random() * window.innerHeight) + 50 + "px";
object[i].style.left = Math.floor(Math.random() * window.innerWidth) + 50 + "px";
}

function createObject() {
var newObject = document.createElement("DIV");
newObject.setAttribute("class", "object");
newObject.setAttribute("id", "powerup");
document.body.appendChild(newObject);
for (i = 0; i < object.length; i++) {
object[i].style.top = Math.floor(Math.random() * window.innerHeight) + 50 + "px";
object[i].style.left = Math.floor(Math.random() * window.innerWidth) + 50 + "px";
}
}
html, body {
height: 100%;
width: 100%;
margin: 0;
}
#powerup {
background: red;
height: 10px;
width: 10px;
}
<body>
<button onclick="createObject()">Create a Block</button>
</body>



mono-energetic gamma ray mean free path

I am writing a code about a mono-energetic gamma beam which the dominated interaction is photoelectric absorption, mu=2 cm-1, and i need to generate 50000 random numbers and sample the interaction depth(which I do not know if i did it or not). I know that the mean free path=mu-1, but I need to find the mean free path from the simulation and from mu and compare them, is what I did right in the code or not?

import random
import matplotlib.pyplot as plt
import numpy as np

mu=(2)
random.seed=()
data = np.random.randn(50000)*10
bins = np.arange(data.min(), data.max()+1e-8, 0.1)
meanfreepath = 1/mu
print(meanfreepath)
plt.hist(data, bins=bins)
plt.show()




How to randomly pick a number of combinations from all the combinations efficiently

For example I have two array (first array contains first names and second array last names). I want to generate n number of unique, non-repeating combinations from this two arrays with such ordering >>> first_name + ' ' + last_name.

I don't wish to generate every possible combination beforehand, because it's too much memory-consuming.

So what I think that algorithm should do, is to iterate until combinations are not generated, during iteration, it should give some random indexes for both arrays and if those indexes are already used together try to pick another random numbers until unique indexes are not generated. But this approach might trigger deep recursion during runtime, since as many outputs are already given, a chance that new random indexes will be matched with existing ones is going higher at each step.

So what is your suggestion guys, how can I select random, unique n items from non-existing/virtual 2 array element combinations with very optimized way




Repeating values for in a random bytes generator in c++

I have made a random bytes generator for intialization vector of CBC mode AES implementation,

#include <iostream>
#include <random>
#include <climits>
#include <algorithm>
#include <functional>
#include <stdio.h>

using bytes_randomizer =    std::independent_bits_engine<std::default_random_engine, CHAR_BIT, uint8_t>;

int main()
{
bytes_randomizer br;
char x[3];
uint8_t data[100];
std::generate(std::begin(data), std::end(data), std::ref(br));

for(int i = 0; i < 100; i++)
{
    sprintf(x, "%x", data[i]);
    std::cout << x << "\n";
}
}

But the problem is it gives the same sequence over and over, I found a solution to on Stack which is to use srand() but this seems to work only for rand().

Any solutions to this, also is there a better way to generate nonce for generating an unpredictable Initialization Vector.




Threejs rotate an object around another object in 3d matrix axis

Right now I could able to set one axis to rotate.

Working code: 
https://codepen.io/itzkinnu/full/erwKzY

How to rotate an object in random axis instead of one fixed axis.

Something like this Ref image




display words at random position on click, in a container on mobile

I asked this question yesterday and was told to ask a new one to have an answer for a precision.

My code displays words on the page when the button is clicked.

It works perfectly, is it possible to contain it in a container ?

Cause i'd like this to only be displayed on mobile and when I reduce the browser page there's a huge scroll and all the words don't show in the window.

Just to try, I tried to contain it in a 300x300px box but the words appear everywhere. Is it possible either with the bootstrap grid or just any media queries, or like I did with any container ? Or is it another javascript rule ?

Thanks again !

var words = [
  'Hello',
  'No',
  'Hi',
  'Banana',
  'Apple'
];
var visible = 0;

document.querySelector("form").addEventListener("submit", function(e) {
  e.preventDefault();

  var fullWidth = window.innerWidth;
  var fullHeight = window.innerHeight;

  var elem = document.createElement("div");
  elem.textContent = words[visible];
  elem.style.position = "absolute";
  elem.style.left = Math.round(Math.random() * fullWidth) + "px";
  elem.style.top = Math.round(Math.random() * fullHeight) + "px";
  document.body.appendChild(elem);

  visible++;
});
<form>
  <input type="submit">
</form>



Generate hex string of length 32 using c++ 11

I need to randomly generate string of length 32 (RFC UUID) using C++ 11. I appreciate any help.




Python 3: Selecting random pair elements from a numpy array without repetition

I want to select random pair elements from a population array in each loop without repetition.

In my code, I create a population array then I pass it to the selection function where I will generate two random index numbers in each loop, and based on it I will select the pair elements from the population array. so if I have a population size 5, then my result size will be 10, because in each loop I will get two elements.

import random
import numpy as np
population_size = 5
dimension= 2
upper = 1
lower = 0
pair_loop = 1
pair_size = 2 

def select (pop
    parents = np.zeros((0, dimension), dtype=np.float_)

    for i in range (population_size):

        for ii in range (pair_loop): 

            random_index= np.random.randint (population_size, size=(pair_size))
            parents = np.vstack((parents, population[random_index,]))
            print (i ,"random_index", random_index)
            print (parents)

    return (parents)

population = np.random.choice(np.linspace(lower, upper, 10), size=(population_size,dimension), replace=True)    
parents = select(population)

I want to get two different elements, where I don't want to repeat the same index number,

for example, if I have: [2, 4] I don't want to see the: [2, 4] or [4,2] again

Any advice would be much appreciated




jeudi 24 mai 2018

Double Coin Toss

If we have to toss two coins.
Do we need two random variables

Random gen1 = new Random();
Random gen2 = new Random();
int firstCoinToss = gen1.nextInt(2);
int secondCoinToss = gen2.nextInt(2);

Or I can do this with one

Random gen1 = new Random();
int firstCoinToss = gen1.nextInt(2);
int secondCoinToss = gen1.nextInt(2);

I am confused because we use two coins and toss should be independent.
So if we are using how it could be independent.
If we have to use one instance, when there will be need for two instances?

[Edit:] -> the both coin should be tossed 100 times and then we have to check how many tail or head occurred.




Need help coming up with an algorithm to generate a random boolean in Java depending on count and percentages

I'm not sure if I even titled this post correctly. If I didn't, let me know and I'll edit the title.

What I am trying to do is simulate a "real-world" situation for charging batteries:

 1st charge == 100% chance of an error (a.k.a., boolean false)
 2nd charge == 90% chance of an error
 3rd charge == 80% chance of an error
 4th charge == 70% chance of an error
 5th charge == 60% chance of an error
 6th charge == 50% chance of an error
 7th charge == 40% chance of an error
 8th charge == 30% chance of an error
 9th charge == 20% chance of an error
10th charge == 10% chance of an error

So, what I need is an algorithm to generate a true or false depending on these percentages, but I have no idea how to do it. I know there is Random and ThreadLocalRandom but there is no way to input any bounds or values for nextBoolean(). I figured I could do something like this:

switch(charge){
    case 1:
        if(ThreadLocalRandom.nextInt(10,10) > 10) return ThreadLocalRandom.nextBoolean();
        break;
    case 2:
        if(ThreadLocalRandom.nextInt(9,10) > 9) return ThreadLocalRandom.nextBoolean();
        break;
    case 3:
        if(ThreadLocalRandom.nextInt(8,10) > 8) return ThreadLocalRandom.nextBoolean();
        break;
    case 4:
        if(ThreadLocalRandom.nextInt(7,10) > 7) return ThreadLocalRandom.nextBoolean();
        break;
    case 5:
        if(ThreadLocalRandom.nextInt(6,10) > 6) return ThreadLocalRandom.nextBoolean();
        break;
    case 6:
        if(ThreadLocalRandom.nextInt(5,10) > 5) return ThreadLocalRandom.nextBoolean();
        break;
    case 7:
        if(ThreadLocalRandom.nextInt(4,10) > 4) return ThreadLocalRandom.nextBoolean();
        break;
    case 8:
        if(ThreadLocalRandom.nextInt(3,10) > 3) return ThreadLocalRandom.nextBoolean();
        break;
    case 9:
        if(ThreadLocalRandom.nextInt(2,10) > 2) return ThreadLocalRandom.nextBoolean();
        break;
    case 10:
        if(ThreadLocalRandom.nextInt(1,10) > 1) return ThreadLocalRandom.nextBoolean();
        break;
}

As you can see, I have no idea what I am doing, so I need some help.

Thanks!




Trying to get multiple randomised result returned from mysql database

Hi I have spent most of the day on this and turn to you in the hope someone can help. I need to generate a random display 5-10 embedded youtube vids on a page without duplication. I can get the videos to display (but all of the same artist) when I refresh it displays a new set of videos but again all of the same artist. I know the answer is probably very simple but I just can't see it.

Any help or pointers would be most appreciated.

The initial code is:

With the output being:

<div class="ws_images"><ul>
            <iframe width="300" height="300" src="https://www.youtube.com/embed/<?       php echo $Youtube ?>" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
            <iframe width="300" height="300" src="https://www.youtube.com/embed/<?php echo $Youtube ?>" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
                    <iframe width="300" height="300" src="https://www.youtube.com/embed/<?php echo $Youtube ?>" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
                            <iframe width="300" height="300" src="https://www.youtube.com/embed/<?php echo $Youtube ?>" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
                                    <iframe width="300" height="300" src="https://www.youtube.com/embed/<?php echo $Youtube ?>" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
    </ul></div>




Exponentially Correlated Draws From Gamma Distribution

I've posted this in the math SE, but since it's algorithm related, I figured it would fit here as well.

I want to generate a series of random numbers corresponding to a given distribution, but in such a way that each draw is correlated to the previous according to some relation.

Suppose I have a correlation f=e^-lambda t and a Gaussian distribution with mean mu and standard deviation sigma. I know that the following algorithm will give me exponentially correlated draws from the Gaussian distribution (algorithm modified from here):

f = exp(-lambda * dt)
r[0] = mu

for n > 0:
    g = sigma * randn()
    r[n] = f * r[n-1] + sqrt(1 - f^2) * g + mu

An example can be seen in this figure. Here, lambda = 0.1, mu = 10, and sigma = 4.
I'm plotting with two different series, each with a different dt.

As can be seen in this figure, the resultant series of draws (after enough samples) is approximately Gaussian with the same mu and sigma.

How can I achieve this same effect with a gamma distribution?




How to call %random% same as previous in CMD?

How to call the same random number in cmd multiple times? Can I set it as variable and then call it or can I define it as !random! ?




Java random returning strange output

I belive its a trivial question, all i just have to is to make proper question, but Iam emptyminded now so: What Iam doing wrong. I try to get some random numbers - but all I get is something like this: java.util.Random@677327b6

import java.util.Random;

public class counter {

public static void main(String args[]) {
    Random random = new Random();
    int r = random.nextInt();
    System.out.println(random.toString());
}




Random Sampling From Histogram/Frequency Hash Table

I am currently trying to come up with a semi-decent (considering complexity, statistical properties and common sense) algorithm for sampling.

The data is currently contained inside a hash table, where each key is an item and the key's value is the item's frequency in the original distribution.

If one wanted to sample from such histogram, how would he go about doing that if he wanted to preserve the original probabilities of the items and transfer them into the sample?

Also, we require that there is a flag of whether duplicate items are allowed in the sample. In the case of not allowing the duplicates, the best I came up with is to apply the algorithm from the paragraph above and delete the item from the hash table once it is sampled. This way, at least the relative probabilities are preserved amongst the remaining items. However, I am unsure of whether this is an accepted practice statistically.

Is there a generally accepted algorithm for doing this? If it helps, we need to implement it in Common Lisp.




Excel Random Number Generator Without Producing Duplicates?

Example Screenshot

I have a column (D2:D49) using the code

=INT(RANDBETWEEN(0,51))

The idea is that this corresponds to playing card values from a deck.

The only issue is that numbers can appear more than once, meaning there is a chance of being dealt the exact same card (e.g. 4 of spades) twice in one hand, which is impossible - how can I amend the formula to avoid duplicates?




R Studio Randomize Date and Time

I want to anonymise a dataset by replacing the original dates and times columns with new, randomized dates (from 01.01.2012 till 31.12.2015) and new, randomized times.

  • Format of the date column: d%.m%.Y%

  • Format of the time colum: h:m

The dataframe consists of 37.094 rows.

Any ideas?




choose a random value from a inverse weigthed map

I'm using a Map with eligible words for a hangman game I'm developing. The Integer in the Map stores the times a word has been chosen, so in the beginning the Map looks like this:

alabanza 0
esperanza 0
comunal 0
aprender 0
....

After some plays, the Map would look like this

alabanza 3
esperanza 4
comunal 3
aprender 1
....

I'd like to choose the next word randomly but having the less chosen word a bigger probability of been chosen.

I've read Java - Choose a random value from a HashMap but one with the highest integer assigned but it's the opposite case.

I''ve also thought I could use a list with repeated words (the more times a word appears in the list, the more the probabilities of been chosen) but I've only managed to get to this:

int numberOfWords=wordList.size(); //The Map
List<String> repeatedWords=new ArrayList<>();
for (Map.Entry<String,Integer> entry : wordList.entrySet()) {
    for (int i = 0; i < numberOfWords-entry.getValue(); i++) {
        repeatedWords.add(entry.getKey());
    }
}
Collections.shuffle(repeatedWords);  //Should it be get(Random)?
String chosenWord=repeatedWords.get(0);

I think this fails when the amount of words chosen equals the amount of words.




How to get random value from assigned enum in c++?

I want a random color from this enum:

enum Color {
red = 10,
black = 3,
pink = 6,
rainbow=99    
};

Color my_randowm_color = ...

How can i do that?




mercredi 23 mai 2018

Python, Box-muller Gaussian random number generator & plot his

I am trying to write code in python using the Box-Muller equations, but I do not know how to start!

This is the example I am trying to solve:

{ A peak observed at 900 keV shows a FWHM of 2 keV. Using a Gaussian sampling method listed below, generate 15,000 counts corresponding to the 900 keV peak and save the sampled energies. Create and plot a histogram with a bin width of 0.2 keV and compare with the Gaussian function with the same peak area. Using a data analysis software, try a Gaussian fit to the Monte Carlo data and see the result is close enough to the peak model. Box-Muller Gaussian sampling method: [ Note, the two sampled variable y1, y2 below are for the unit Gaussian distribution (i.e. mu=0,segma=1).

y1 = (-2 ln r1 cos(2pir2))^1/2
y2 = (-2 ln r1 sin(2pi
r2))^1/2

(r1, r2: random numbers)}

Any suggestions?




display words at random position on click

It's the first time I ever post something on a forum. I'm new with javascript.

I found this : http://jsfiddle.net/6eTcD/2/ You type a word, and submit and then it appears randomly on the page.

HTML :

<form>
    <input type="text">
    <input type="submit">
</form>

JAVASCRIPT

document.querySelector("form").addEventListener("submit", function(e) {
    e.preventDefault();

    var fullWidth = window.innerWidth;
    var fullHeight = window.innerHeight;

    var text = this.querySelector("input[type='text']").value;

    var elem = document.createElement("div");
    elem.textContent = text;
    elem.style.position = "absolute";
    elem.style.left = Math.round(Math.random() * fullWidth) + "px";
    elem.style.top = Math.round(Math.random() * fullHeight) + "px";
    document.body.appendChild(elem);
});

Though I would like to choose myself the words that are gonna be displayed, and I'd like them to appear when the button is clicked. And at random positions. but not randoms words.

I tried to replace "text" with "words" and added

    function getRandomWord() {
  var words = [
    'Hello',
    'No',
    'Hi',
    'Banana',
    'Apple'
  ];

MY MODIFICATIONS :

// A $( document ).ready() block.
$( document ).ready(function() {


document.querySelector("form").addEventListener("submit", function(e) {
    e.preventDefault();

    var fullWidth = window.innerWidth;
    var fullHeight = window.innerHeight;

    function getRandomWord() {
  var words = [
    'Hello',
    'No',
    'Hi',
    'Banana',
    'Apple'
  ];

    var elem = document.createElement("div");
    elem.textContent = words;
    elem.style.position = "absolute";
    elem.style.left = Math.round(Math.random() * fullWidth) + "px";
    elem.style.top = Math.round(Math.random() * fullHeight) + "px";
    document.body.appendChild(elem);
});

    });

Anyway I don't think any of what I did could work. I'm new to this. Would any of you now?
Thank you in advance




TSQL random sample

I need to select a random sample using TSQL from a table based on ratios of 2 different variables in the table.

The random sample required is approximately 8000 records from a table with about 381,000 records. The random sample must have approximate ratios of 2 variables:

4:1 (Male/Female) - 2 category variable 4:3:2:1 (Heavy/Moderate/Light/Very Light) - 4 category variable




SAS Stratified Sampling

I have an example of PROC SURVEYSELECT where I created four groups containing five IDs in each group. I want to be able to take a random sample where the IDs in different stratifications (i.e. groups) do not overlap. How can I accomplish this? Note that each group has the same repeating ID - 1 and 2. The next three IDs are unique to the group.

Example code:

data survey;
input group $ id;
datalines;
a 1
a 2
a 3
a 4
a 5
b 1
b 2
b 6
b 7
b 8
c 1
c 2
c 9
c 10
c 11
d 1
d 2
d 12
d 13
d 14
;


proc surveyselect data=survey
method=srs n=3
out=MyStratExample;
strata group;
run;

proc print data=MyStratExample;
run;

current output:

a   1   0.6 1.6666666667
a   3   0.6 1.6666666667
a   4   0.6 1.6666666667
b   1   0.6 1.6666666667
b   2   0.6 1.6666666667
b   7   0.6 1.6666666667
c   1   0.6 1.6666666667
c   2   0.6 1.6666666667
c   11  0.6 1.6666666667
d   1   0.6 1.6666666667
d   2   0.6 1.6666666667
d   13  0.6 1.6666666667

We can observe that across the multiple groups SAS is taking samples of the same ID variable.




I came up with these two methods to get 5 unique random numbers. Which one is better/efficient? Is there any other way more efficient?

Method 1

 public int[] randIntGen() {
    int randInt[] = {0,0,0,0,0};
    Random random = new Random();
    randInt[0] = random.nextInt(52) + 1;            
    randInt[1] = random.nextInt(52) + 1;
    randInt[2] = random.nextInt(52) + 1;
    randInt[3] = random.nextInt(52) + 1;
           randInt[4] = random.nextInt(52) + 1;
    while(randInt[1] == randInt[0]) {
        randInt[1] = random.nextInt(52) + 1 ;
    }
    while(randInt[2] == randInt[0] || randInt[2] == randInt[1]) {
        randInt[2] = random.nextInt(52) + 1;
    }           
           while(randInt[3] == randInt[0] || randInt[3] == randInt[1] || randInt[3] == randInt[2]) {
        randInt[3] = random.nextInt(52) + 1;
    }           
           while(randInt[4] == randInt[0] || randInt[4] == randInt[1] || randInt[4] == randInt[2] || randInt[4] == randInt[3]) {
        randInt[4] = random.nextInt(52) + 1 ;
    }           
    return randInt;
}

Method 2

public int[] randIntGen()   {
     int randInt[] = {1,2,3,4,5};
     Random random = new Random();
            ArrayList<Integer> cl = new ArrayList<Integer>(52);
            int i = 0;
            while(i<52){
                i++;
                cl.add(i-1,i);
            }
            for(int j=0; j<5;j++) {
                randInt[j] = cl.get(random.nextInt(52));
                cl.remove(randInt[j]-1);                
            }
    return randInt;
} 




Comparing Answers (Not in Array)

How do you tell Java to print the value of matching numbers that are randomly generated. For example, if the output is 3,3,7: the system should print out, "You got two 3's".

    int roll1 = (int) (Math.random()*6) +1;
    int roll2 = (int) (Math.random()*6) +1;
    int roll3 = (int) (Math.random()*6) +1;


    System.out.print("Your numbers are " + roll1 + r2 + r3);

    if (r1 == r2 && r2 ==s3 )
        System.out.print(": You got all" + s1 + "'s");
    else if (r1 == r2 || r2 == r3 || r1 == r3)
        System.out.print(": You got two" + "'s");
    else if (r1 != r2 && sr != r3)
        System.out.print(": NO MATCHES!");
    else {

    }




Why does my if else statement fail when combined with the sample function in R

I have two vectors that can be of variable length. I want to constrain how I sample from one by using the length of the smaller one. In this case, xy is smaller so the first part should execute and the second should be ignored, but when I run the code I get an error:

Error in sample.int(length(x), size, replace, prob) : cannot take a sample larger than the population when 'replace = FALSE' In addition: Warning message: In if (xx > xy) { : the condition has length > 1 and only the first element will be used

  xy<-c(1:5)
  xx<-c(1:10)

  if(xx > xy){
    father<-xy;
    mother<-sample(xx,length(xy), replace = FALSE)
  } else {
    mother<-xx;
    father<-sample(xy,length(xx), replace = FALSE)
  }

The error makes sense on its own, if I run those lines with sample separately but I thought the if else coding should prevent that.




solr search sort by rand within same score

I am using solr 6.3 i want to sort documents by rand within the same scores

Please see the result response

"response":{"numFound":9796,"start":0,"maxScore":4.813048,"docs":[

  {
    "product_slno":"8343676",
    "product_name":"non basmati rice",
    "score":4.813048},
  {
    "product_slno":"9272399",
    "product_name":"non basmati rice",
    "score":4.813048},
  {
    "product_slno":"9117918",
    "product_name":"non basmati rice",
    "score":4.813048},
  {
    "product_slno":"11992571",
    "product_name":"non basmati rice",
    "score":4.813048},
  {
    "product_slno":"12226220",
    "product_name":"non basmati rice",
    "score":4.813048},
  {
    "product_slno":"12239015",
    "product_name":"non basmati rice",
    "score":4.813048},
  {
    "product_slno":"228513",
    "product_name":"basmati rice",
    "score":4.6070313},
  {
    "product_slno":"382382",
    "product_name":"basmati rice",
    "score":4.6070313},
  {
    "product_slno":"591419",
    "product_name":"basmati rice",
    "score":4.6070313},
  {
    "product_slno":"11992574",
    "product_name":"basmati rice",
    "score":4.6070313},
  {
    "product_slno":"12067342",
    "product_name":"basmati rice",
    "score":4.6070313},
  {
    "product_slno":"12102172",
    "product_name":"basmati rice",
    "score":4.6070313},
  {
    "product_slno":"12116777",
    "product_name":"basmati rice",
    "score":4.6070313},
  {
    "product_slno":"12125565",
    "product_name":"basmati rice",
    "score":4.6070313},
  {
    "product_slno":"4462552",
    "product_name":"non basmati rice",
    "score":4.424822},
  {
    "product_slno":"6666626",
    "product_name":"non basmati rice",
    "score":4.424822},
  {
    "product_slno":"7036941",
    "product_name":"non basmati rice",
    "score":4.424822},
  {
    "product_slno":"7833234",
    "product_name":"non basmati rice",
    "score":4.424822},
  {
    "product_slno":"7552192",
    "product_name":"non basmati rice",
    "score":4.424822},
  {
    "product_slno":"8757321",
    "product_name":"non basmati rice",
    "score":4.424822},
  {
    "product_slno":"9207159",
    "product_name":"non basmati rice",
    "score":4.424822},
  {
    "product_slno":"9978281",
    "product_name":"non basmati rice",
    "score":4.424822},
  {
    "product_slno":"11642035",
    "product_name":"non basmati rice",
    "score":4.424822},
  {
    "product_slno":"12294941",
    "product_name":"non basmati rice",
    "score":4.424822},
  {
    "product_slno":"12313470",
    "product_name":"non-basmati rice",
    "score":4.424822},
  {
    "product_slno":"5457576",
    "product_name":"basmati rice",
    "score":4.2188053},
  {
    "product_slno":"6666629",
    "product_name":"basmati rice",
    "score":4.2188053},
  {
    "product_slno":"7552189",
    "product_name":"basmati rice",
    "score":4.2188053},
  {
    "product_slno":"11476797",
    "product_name":"basmati rice",
    "score":4.2188053},
  {
    "product_slno":"11642034",
    "product_name":"basmati rice",
    "score":4.2188053},
  {
    "product_slno":"12209560",
    "product_name":"basmati rice",
    "score":4.2188053},
  {
    "product_slno":"12230206",
    "product_name":"basmati rice",
    "score":4.2188053},
  {
    "product_slno":"12233053",
    "product_name":"basmati rice",
    "score":4.2188053},
  {
    "product_slno":"182609",
    "product_name":"non basmati rice",
    "score":1.7452564},
  {
    "product_slno":"158848",
    "product_name":"non basmati parboiled rice",
    "score":1.7452564},
  {
    "product_slno":"8439880",
    "product_name":"non basmati rice",
    "score":1.7452564},
  {
    "product_slno":"10035413",
    "product_name":"non basmati rice",
    "score":1.7452564},

we have multiple documents for scores "4.813048" ,"4.6070313", "4.424822", "4.2188053", "1.7452564" i want random sort within same scores.

thanks




php - distributed randomness across array

In my Laravel 5.6 application I've got a start date (start), an end date (end) and a number (x). I must pick x random dates between start and end. Since I'm writing a small generator I want these dates as much distributed as possible.

I would like to avoid too many duplicated dates, too little distance between days, and I want a pick dates from the start to the end.

I've already found a solution. Even if it works pretty well I'm not happy with it. I would like to find a better solution with your help.

Step by step explanation on what I've done:

  1. Create an associative array containing all the days from start to end encoded as timestamps => **x** * **x**. This way every day will get a weight.

  2. Picking a $random number between 0 and the sum of all weights. Let's say $x = 8, so I will need 8 dates to be picked between $start = 01/04/18 $end = 30/04/18 for a total of 30 days. My weights sum will be $weightsSum = 240.

  3. Iterate my dates array by adding the current $weight to a $sum variable. If $sum >= $random I'll pick this date.

  4. Here becomes my idea: I'll map the dates array and I'll subtract some weight based on the distance between the picked item and the currently mapped one. For instance, let's say that $date[5] has been picked. The difference in days between date[0] and date[5] will be 5 days, so I've chosen this formula: $weight - round($weight / $diffInDays / 2 ). The new weight will be 64 - (round(64 / 5 / 2)) = 58. New weight for date[25] will be 62 and date[5] will be 32. Of course $diffInDays for date[5] will be 1. Otherwise I'll get a division by zero.

By this way, the weight of the chosen day will drastically get down, but it can be still be picked up. Also, there's less chance that a day near the previously chosen day will be picked, this is what I also need.

Let's get to the code:

__buildDatesArray()

$entriesCount = $this->entries->sum('quantity');

$base = Carbon::createFromTimestamp($this->startDate->timestamp)->startOfDay();

do {
     $this->dates->put($base->addDay()->timestamp, $entriesCount * $entriesCount);
}while($base->diffInDays($this->endDate) > 0);

__pickARandomDate()

$weightsSum = $this->dates->sum();

$random = \RNG::generateInt(0, $weightsSum);

$sum = 0;

foreach($this->dates as $timestamp => $weight)
{
    $sum += $weight;

    if ($sum >= $random)
    {
        $this->dates = $this->dates->map(function ($weight, $currentTimestamp) use ($timestamp, $weightsSum) {
            $diffInDays = ($currentTimestamp - $timestamp) / 86400;

            if ($diffInDays < 0)
                $diffInDays *= -1;

            if ($diffInDays <= 0)
                $diffInDays = 1;

            return $weight - round($weight / $diffInDays / 2);
        });

        return Carbon::createFromTimestamp($timestamp);
    }
}

Any idea on how to make this better? How can I pick dates in a well distributed fashion? I'm open to anything, thank you in advance!




Hyperparameter search: different results on different machines using the same random seed

I'm doing a bayesian parameter search (scikit-optimize gp_minimize() function) for a MLPClassifier. I noticed that I get different results (occur first at iteration 12) when I run the script on machine 2.

If I rerun the script on machine 1 or machine 2 the results are reproducible. However they differ over different machines (tried 3). The datasets are the same, I dumped them using pickle and load the same dump using pickle.

I'm not sure if this is normal to some extent or if there is another source of randomness in my code or something completely different. The one thing I checked are the library versions of numpy, scikit-learn and scikit-optimize which all are the same.

Code:

space = [
         Categorical(['constant', 'invscaling', 'adaptive'], name="learning_rate"),
         Categorical(['lbfgs', 'sgd', 'adam'], name='solver'),
         Categorical(['identity', 'logistic', 'tanh', 'relu'], name='activation'),
         Real(10 ** -7, 10 ** 1, 'log-uniform', name='alpha'),
         Real(10** -7, 10**-2, name='tol'),
         Categorical([200, 500, 1000, 1500, 2000], name='max_iter'),
         Categorical(hidden_layers, name='hidden_layer_sizes')
]

if __name__ == '__main__':
    # print log headline
    print('{:3}{:>10}{:>10}{:>12}{:>7}{:>10}{:>13}{:>11}{:>6}{:>11}'.format('#', 'max(score)',  'score', 'Arg1', 'Arg2', 'Arg3', 'Arg4', 'Arg5', 'Arg6', 'Arg7' ))

    start = time()
    res_mlp = gp_minimize(objective, space, n_calls=50, random_state=42, callback=onstep, n_jobs=-1)
    optTime = time() - start

In the objective function I do cross validation with the MLPClassifier and return the negative mean score. If the code is required I will of course add it.

First 15 iterations of the run on two different machines:

Machine 1:

#  max(score)     score        Arg1   Arg2      Arg3         Arg4      Arg5  Arg6       Arg7
        #0    0.47567   0.47567    adaptive  lbfgs      relu    0.0059539 0.0044584   200   (28, 14)
        #1    0.50947   0.50947  invscaling  lbfgs      tanh    0.0000003 0.0072200  2000      (10,)
        #2    0.53443   0.53443    adaptive    sgd      tanh    0.0000001 0.0002307  1000   (24, 45)
        #3    0.53443   0.52291    constant   adam  identity    0.0000005 0.0061839   500  (100, 36)
        #4    0.53443   0.49588  invscaling   adam      tanh    0.0004018 0.0001327  2000   (32, 26)
        #5    0.54053   0.54053  invscaling  lbfgs  identity    0.0000085 0.0068327  1500   (50, 22)
        #6    0.54053   0.27127    constant    sgd  identity    0.1103802 0.0042516   500   (32, 30)
        #7    0.54053   0.00000    constant   adam  logistic    0.0001449 0.0092666  1500   (22, 16)
        #8    0.54053   0.00699  invscaling    sgd      relu    0.5705199 0.0074732  1000   (32, 80)
        #9    0.54053   0.00000    adaptive    sgd  logistic    0.0000235 0.0016528   200   (26, 22)
        #10   0.54053   0.52548  invscaling  lbfgs  identity    0.0000001 0.0100000  1500      (10,)
        #11   0.54053   0.53284  invscaling  lbfgs  identity    0.0000001 0.0100000  1000   (50, 22)
        #12   0.54053   0.54007  invscaling  lbfgs  identity    0.0007139 0.0032280  1500   (50, 22)
        #13   0.54053   0.00339    adaptive    sgd      relu    2.7419184 0.0090097   200   (26, 36)
        #14   0.54989   0.54989    constant  lbfgs  identity   10.0000000 0.0000001   500   (50, 22)
        #15   0.54989   0.54989    constant  lbfgs  identity   10.0000000 0.0000001   500   (50, 22)

Machine 2:

#  max(score)     score        Arg1   Arg2      Arg3         Arg4       Arg5  Arg6       Arg7
#0    0.47567   0.47567    adaptive  lbfgs      relu    0.0059539  0.0044584   200   (28, 14)
#1    0.50947   0.50947  invscaling  lbfgs      tanh    0.0000003  0.0072200  2000      (10,)
#2    0.53443   0.53443    adaptive    sgd      tanh    0.0000001  0.0002307  1000   (24, 45)
#3    0.53443   0.52291    constant   adam  identity    0.0000005  0.0061839   500  (100, 36)
#4    0.53443   0.49588  invscaling   adam      tanh    0.0004018  0.0001327  2000   (32, 26)
#5    0.54053   0.54053  invscaling  lbfgs  identity    0.0000085  0.0068327  1500   (50, 22)
#6    0.54053   0.27127    constant    sgd  identity    0.1103802  0.0042516   500   (32, 30)
#7    0.54053   0.00000    constant   adam  logistic    0.0001449  0.0092666  1500   (22, 16)
#8    0.54053   0.00699  invscaling    sgd      relu    0.5705199  0.0074732  1000   (32, 80)
#9    0.54053   0.00000    adaptive    sgd  logistic    0.0000235  0.0016528   200   (26, 22)
#10   0.54053   0.52548  invscaling  lbfgs  identity    0.0000001  0.0100000  1500      (10,)
#11   0.54053   0.53284  invscaling  lbfgs  identity    0.0000001  0.0100000  1000   (50, 22)
#12   0.54053   0.53878  invscaling  lbfgs  identity    0.0006349  0.0032752  1500   (50, 22)
#13   0.54053   0.00000    adaptive    sgd  logistic    0.0566396  0.0027155   200   (24, 20)
#14   0.54053   0.50515    adaptive   adam      tanh    0.0000039  0.0000959  1000   (24, 45)
#15   0.54989   0.54989  invscaling  lbfgs  identity   10.0000000  0.0000001  1500   (50, 22)

The first difference occurs in iteartion 12 in Arg5 and Arg6




mardi 22 mai 2018

how to get random number between 5 and -5 in c++

i am trying to get random numbers using rand % (5 -5) and it gives division by zero error

#include <iostream>
using namespace std;
int main()
{
int A[20];
for (int i-0 ;i<20;i++)
 A[i]= rand() % -5;

system("pause")
return 0;
}




How to get random values with twig including same file multiple times

I'm trying to figure out, how to include one template multiple times with different random values.

I do have a template:

<div class="include-1">
  Liquid error: This liquid context does not allow includes.
</div>
<div class="include-2">
  Liquid error: This liquid context does not allow includes.
</div>
<div class="include-3">
  Liquid error: This liquid context does not allow includes.
</div>

Inside the include.twig I have:

<span>
  
</span>

Expected result (numbers in span should be random in range from 0–10):

<div class="include-1">
  <span>1</span>
</div>
<div class="include-2">
  <span>2</span>
</div>
<div class="include-3">
  <span>3</span>
</div>

Actual result (the first include get the random value, but then it is just "cached"):

<div class="include-1">
  <span>1</span>
</div>
<div class="include-2">
  <span>1</span>
</div>
<div class="include-3">
  <span>1</span>
</div>

I've tested include, embed etc. but with no avail. I'm looking for a twig based solution. Cannot touch PHP. As a fallback I can do it with JS, but was interested if such a thing can be done it Twig.

Question:

Is there a way how to force Twig to re-render the include before each include?




lundi 21 mai 2018

random.choice has an issue counting its arguments

I have an issue with random.choice in the random module. So here I have a nice looking block of code:

for trap in range(11):
    leftorright = raw_input("")
    if leftorright == "left" or "right":
        leftchoice = random.choice(True, False)
        if leftchoice:
            print "You don't feel anything on your legs, so you think you're okay."
        else:
            print "You feel a sharp pain on your %s leg." %(random.choice("left", "right"))
    else:
        print sorrycommand

So the issue here is that the two random.choice instances (leftchoice = random.choice(True, False) and print "You feel a sharp pain on your %s leg." %(random.choice("left", "right"))) are giving me this error:

Traceback (most recent call last):
  File "main.py", line 408, in <module>
    startmenuchoice() 
  File "main.py", line 404, in startmenuchoice
    room7()
  File "main.py", line 386, in room7
    leftchoice = random.choice(True, False)
TypeError: choice() takes exactly 2 arguments (3 given)

Now, going right to the real thing here: TypeError: choice() takes exactly 2 arguments (3 given)

It says in the error that there are 3 arguments given, but if you take a look at the error and the code, there are clearly only 2 arguments given (the proper amount of arguments needed). Could somebody please help me?

Side notes:

  1. I will provide any other info needed in the comments since I am not very good of thinking of every bit of needed info.
  2. I am using the site repl.it, an online IDE and compiler. Maybe that might have something to do with it?



Hoje, qual a preocupação da Taqtile com acessibilidade nas duas frentes, dev/design?

Durante o processo de desenvolvimento e design, como cuidamos das questões acerca da acessibilidade?




How to use Math.random() with questions?

So I'm making a site with questions that u need to answer and I want to use the questions in the same order. So how do I use the Math.random() function to randomize my questions, and I don't want to randomize the answers! Please help with this javascript code:

  (function() {
    const myQuestions = [{
            question: "Esimerkki kysymys1",
            answers: {
                a: "Oikein",
                b: "Väärin"
            },
            correctAnswer: "a"
        },
        {
            question: "Esimerkki kysymys2",
            answers: {
                a: "Oikein",
                b: "Väärin"
            },
            correctAnswer: "b"
        },
        {
            question: "Esimerkki kysymys3",
            answers: {
                a: "Oikein",
                b: "Väärin"
            },
            correctAnswer: "a"
        }
    ];

    function Random() {
        var display = document.getElementById("myQuestions");
        var questionAmount = 2;
        for (var i = 0; i < questionAmount; i++) {
            do {
                var randomQuestion = Math.floor(Math.random() * questions.length);
            } while (existingQuestions());

            display.innerHTML += questions[randomQuestion] + '<br>';
            questionTracker.push(randomQuestion);
        }


        function existingQuestions() {
            for (var i = 0; i < questionTracker.length; i++) {
                if (questionTracker[i] === randomQuestion) {
                    return true;
                }
            }
            return false;
        }
    }

    function buildQuiz() {
        // we'll need a place to store the HTML output
        const output = [];

        // for each question...
        myQuestions.forEach((currentQuestion, questionNumber) => {
            // we'll want to store the list of answer choices
            const answers = [];

            // and for each available answer...
            for (letter in currentQuestion.answers) {
                // ...add an HTML radio button
                answers.push(
                    `<label>
     <input type="radio" name="question${questionNumber}" value="${letter}">
      ${letter} :
      ${currentQuestion.answers[letter]}
   </label>`
                );
            }

            // add this question and its answers to the output
            output.push(
                `<div class="slide">
   <div class="question"> ${currentQuestion.question} </div>
   <div class="answers"> ${answers.join("")} </div>
 </div>`
            );
        });

        // finally combine our output list into one string of HTML and put it on the page
        quizContainer.innerHTML = output.join("");
    }

    function showResults() {
        // gather answer containers from our quiz
        const answerContainers = quizContainer.querySelectorAll(".answers");

        // keep track of user's answers
        let numCorrect = 0;

        // for each question...
        myQuestions.forEach((currentQuestion, questionNumber) => {
            // find selected answer
            const answerContainer = answerContainers[questionNumber];
            const selector = `input[name=question${questionNumber}]:checked`;
            const userAnswer = (answerContainer.querySelector(selector) || {}).value;

            // if answer is correct
            if (userAnswer === currentQuestion.correctAnswer) {
                // add to the number of correct answers
                numCorrect++;

                // color the answers green
                answerContainers[questionNumber].style.color = "lightgreen";
            } else {
                // if answer is wrong or blank
                // color the answers red
                answerContainers[questionNumber].style.color = "red";
            }
        });

        // show number of correct answers out of total
        resultsContainer.innerHTML = `${numCorrect} Oikein ${myQuestions.length}`;
    }

    function showSlide(n) {
        slides[currentSlide].classList.remove("active-slide");
        slides[n].classList.add("active-slide");
        currentSlide = n;

        if (currentSlide === 0) {
            previousButton.style.display = "none";
        } else {
            previousButton.style.display = "inline-block";
        }

        if (currentSlide === slides.length - 1) {
            nextButton.style.display = "none";
            submitButton.style.display = "inline-block";
        } else {
            nextButton.style.display = "inline-block";
            submitButton.style.display = "none";
        }
    }

    function showNextSlide() {
        showSlide(currentSlide + 1);
    }

    function showPreviousSlide() {
        showSlide(currentSlide - 1);
    }

    const quizContainer = document.getElementById("quiz");
    const resultsContainer = document.getElementById("results");
    const submitButton = document.getElementById("submit");

    // display quiz right away
    buildQuiz();

    const previousButton = document.getElementById("previous");
    const nextButton = document.getElementById("next");
    const slides = document.querySelectorAll(".slide");
    let currentSlide = 0;

    showSlide(0);

    // on submit, show results
    submitButton.addEventListener("click", showResults);
    previousButton.addEventListener("click", showPreviousSlide);
    nextButton.addEventListener("click", showNextSlide);
})();

I tried to use the Math.random function, but I could not get it to work!




Create numpy array with random integers each row with another range

i need to make fast numpy array that generates random integers in each row with a different range.

Code that works by my but is slow when i increase vectors number to 300000:

import numpy as np
import random

population_size = 4
vectors_number = population_size * 3 

add_matrix = []
for i in range(0, int(vectors_number/population_size)):
    candidates = list(range(population_size*i, population_size*(i+1))) 
    random_index = random.sample(candidates, 4)
    add_matrix.append(random_index)

winning_matrix = np.row_stack(add_matrix)
print(winning_matrix)

Each row is choose 4 random numbers from variable range.

Output:

[[ 3  0  1  2]
 [ 4  6  7  5]
 [11  9  8 10]]

Best would by create that matrix using only numpy without loops




Get random results from database and insert in columns

I'm trying to generate 6 column and 9 row long movie grid with random results from database on each user visit. I easily get random 54 results but I'm not able to separate results and insert them in 6 column as 9 row in each column. I was trying to break and continue while loop but no luck. How can I achieve this? My current code looks like this:

    <?php
    $i = 0;
    $sql = "SELECT * FROM Movies ORDER BY RAND() LIMIT 54";
    $gridmovies = $mysqli->query($sql);
    if ($gridmovies->num_rows > 0) {
        while($row = $gridmovies->fetch_assoc()) {
            $i++
    ?>
                <div class="column" style="margin-top: 0px;">
                  <a href="/similar/<?php echo $row['ImdbID']; ?>" class="item-card">
                    <div class="overlay ov-show">
                      <div class="icon"><i class="fa fa-heart"></i></div>
                    </div>
                    <img src="<?php echo $row['PosterURL']; ?>" alt="<?php echo $row['EngTitle']; ?> / <?php echo $row['GeoTitle']; ?>">
                  </a>          
                </div>
                <?php if ($i = 9) {break;} ?>
                <div class="column" style="margin-top: 40px;">
                  <?php continue; ?>
                  <a href="/similar/<?php echo $row['ImdbID']; ?>" class="item-card">
                    <div class="overlay ov-show">
                      <div class="icon"><i class="fa fa-heart"></i></div>
                    </div>
                    <img src="<?php echo $row['PosterURL']; ?>" alt="<?php echo $row['EngTitle']; ?> / <?php echo $row['GeoTitle']; ?>">
                  </a>
                </div>
                <?php if ($i = 18) {break;} ?>
                <div class="column" style="margin-top: 80px;">
                  <?php continue; ?>
                  <a href="/similar/<?php echo $row['ImdbID']; ?>" class="item-card">
                    <div class="overlay ov-show">
                      <div class="icon"><i class="fa fa-heart"></i></div>
                    </div>
                    <img src="<?php echo $row['PosterURL']; ?>" alt="<?php echo $row['EngTitle']; ?> / <?php echo $row['GeoTitle']; ?>">
                  </a>
                </div>
                 <?php if ($i = 27) {break;} ?>
                <div class="column" style="margin-top: 120px;">
                  <?php continue; ?>
                  <a href="/similar/<?php echo $row['ImdbID']; ?>" class="item-card">
                    <div class="overlay ov-show">
                      <div class="icon"><i class="fa fa-heart"></i></div>
                    </div>
                    <img src="<?php echo $row['PosterURL']; ?>" alt="<?php echo $row['EngTitle']; ?> / <?php echo $row['GeoTitle']; ?>">
                  </a>
                </div>
                <?php if ($i = 36) {break;} ?>
                <div class="column" style="margin-top: 160px;">
                  <?php continue; ?>
                  <a href="/similar/<?php echo $row['ImdbID']; ?>" class="item-card">
                    <div class="overlay ov-show">
                      <div class="icon"><i class="fa fa-heart"></i></div>
                    </div>
                    <img src="<?php echo $row['PosterURL']; ?>" alt="<?php echo $row['EngTitle']; ?> / <?php echo $row['GeoTitle']; ?>">
                  </a>
                </div>
                <?php if ($i = 45) {break;} ?>
                <div class="column" style="margin-top: 200px;">
                  <?php continue; ?>
                  <a href="/similar/<?php echo $row['ImdbID']; ?>" class="item-card">
                    <div class="overlay ov-show">
                      <div class="icon"><i class="fa fa-heart"></i></div>
                    </div>
                    <img src="<?php echo $row['PosterURL']; ?>" alt="<?php echo $row['EngTitle']; ?> / <?php echo $row['GeoTitle']; ?>">
                  </a>
                </div>
    <?php
        } $gridmovies->free();
    } else {
      echo 'error';
    }
    ?>