samedi 30 juin 2018

convert random.uniform call from python2 to python3

I have some python2 code like this

self.rng.uniform(0, cutoffs[-1])

where self.rng is mtrand.RandomState, and cutoffs[-1] is map object.

when upgraded to python3, I am getting

TypeError: float() argument must be a string or a number, not 'map'

Can someone instruct how to convert this to be python3 compatible




Shuffle rows of a dataframe in pandas python brings about different regression results?

I am trying to randomise my rows in the dataframe - data before applying linear regression, but i realised the regression results differs after the rows are randomised which shouldn't be the case? Codes which i have tried using:

Without row randomisation: 
data 
X = data[feature_col]
y = data['median_price']
lr = LinearRegression()
lr.fit(X, y)

With row randomisation: 
Method 1: 
data = data.sample(frac=1)

Method 2:
data = data.sample(frac=1, axis=1)

Method 3: 
from sklearn.utils import shuffle
data = shuffle(data)

Method 4: 
data = data.sample(frac=1, axis=1)

Out of the 4 row randomisation methods i have tried, only Method 4 gives the same results as the one where no randomisation is applied. I thought row randomisation does not affects the regression results in any case?




Why does this playlist code work fine on only about half the browsers/platforms/html test sites?

I have tested this code on three different test sites using three different browsers on two different MacOS versions. It works perfect on some and not at all on the others. I even tried an alternate manual playlist code wizard using SCM Player at https://scmplayer.co/ but the embed code that produced works nowhere. Anyway, here is the code that works half the time (placed within the tags). Any help would be greatly appreciated!

<script type="text/javascript">
var numberOfSongs = 26
var sound = new Array(numberOfSongs+1)
sound[0]= "http://rvratptcavailability.x10host.com/afhsclassof1986/highschoolflashbacksongs/Rio.mp3"
sound[1]= "http://rvratptcavailability.x10host.com/afhsclassof1986/highschoolflashbacksongs/Alive%20And%20Kicking.mp3"
sound[2]= "http://rvratptcavailability.x10host.com/afhsclassof1986/highschoolflashbacksongs/Key%20Largo.mp3"
sound[3]= "http://rvratptcavailability.x10host.com/afhsclassof1986/highschoolflashbacksongs/Come%20On%20Eileen.mp3"
sound[4]= "http://rvratptcavailability.x10host.com/afhsclassof1986/highschoolflashbacksongs/Tainted%20Love.mp3"
sound[5]= "http://rvratptcavailability.x10host.com/afhsclassof1986/highschoolflashbacksongs/Everybody%20Wants%20You.mp3"
sound[6]= "http://rvratptcavailability.x10host.com/afhsclassof1986/highschoolflashbacksongs/Eyes%20Without%20A%20Face.mp3"
sound[7]= "http://rvratptcavailability.x10host.com/afhsclassof1986/highschoolflashbacksongs/Hungry%20Like%20The%20Wolf.mp3"
sound[8]= "http://rvratptcavailability.x10host.com/afhsclassof1986/highschoolflashbacksongs/I%20Ran%20%28So%20Far%20Away%29.mp3"
sound[9]= "http://rvratptcavailability.x10host.com/afhsclassof1986/highschoolflashbacksongs/If%20I%27d%20Been%20The%20One.m4a"
sound[10]= "http://rvratptcavailability.x10host.com/afhsclassof1986/highschoolflashbacksongs/It%27s%20My%20Life%20%5BTalk%20Talk%5D.mp3"
sound[11]= "http://rvratptcavailability.x10host.com/afhsclassof1986/highschoolflashbacksongs/Let%27s%20Go%20%5BWang%20Chung%5D.mp3"
sound[12]= "http://rvratptcavailability.x10host.com/afhsclassof1986/highschoolflashbacksongs/Obsession.mp3"
sound[13]= "http://rvratptcavailability.x10host.com/afhsclassof1986/highschoolflashbacksongs/On%20The%20Dark%20Side.mp3"
sound[14]= "http://rvratptcavailability.x10host.com/afhsclassof1986/highschoolflashbacksongs/The%20Other%20Guy.mp3"
sound[15]= "http://rvratptcavailability.x10host.com/afhsclassof1986/highschoolflashbacksongs/Promises%20Promises.mp3"
sound[16]= "http://rvratptcavailability.x10host.com/afhsclassof1986/highschoolflashbacksongs/Rock%20Me%20Amadeus.mp3"
sound[17]= "http://rvratptcavailability.x10host.com/afhsclassof1986/highschoolflashbacksongs/The%20Safety%20Dance.mp3"
sound[18]= "http://rvratptcavailability.x10host.com/afhsclassof1986/highschoolflashbacksongs/She%27s%20A%20Beauty.mp3"
sound[19]= "http://rvratptcavailability.x10host.com/afhsclassof1986/highschoolflashbacksongs/Somebody%27s%20Baby.m4a"
sound[20]= "http://rvratptcavailability.x10host.com/afhsclassof1986/highschoolflashbacksongs/Someday%20%5BGlass%20Tiger%5D.mp3"
sound[21]= "http://rvratptcavailability.x10host.com/afhsclassof1986/highschoolflashbacksongs/Vacation.m4a"
sound[22]= "http://rvratptcavailability.x10host.com/afhsclassof1986/highschoolflashbacksongs/Whisper%20To%20A%20Scream%20%28Birds%20Fly%29.mp3"
sound[23]= "http://rvratptcavailability.x10host.com/afhsclassof1986/highschoolflashbacksongs/What%20Is%20Love_.mp3"
sound[24]= "http://rvratptcavailability.x10host.com/afhsclassof1986/highschoolflashbacksongs/Take%20It%20Easy%20On%20Me.mp3"
sound[25]= "http://rvratptcavailability.x10host.com/afhsclassof1986/highschoolflashbacksongs/The%20Old%20Man%20Down%20The%20Road.mp3"
function randomNumber(){
var randomLooper = -1
while (randomLooper < 0 || randomLooper > numberOfSongs ||isNaN(randomLooper)){    randomLooper = parseInt(Math.random()*(numberOfSongs+1))
}
return randomLooper
}
var randomsub = randomNumber()
var soundFile = sound[randomsub]
document.write ('<EMBED src= "' + soundFile + '" hidden=true  type="audio/mpeg" autostart=true loop=true>')
</script>

Here is a link to the web page to see if works (plays music) on your browser or platform; maybe you can extract the code from there if necessary: http://rvratptcavailability.x10host.com/afhsclassof1986/




Is it faster, using coin flips, to generate random ints from 1 to 9, w/ single factor solving algorithms, or is it faster w/ multi-factor algorithms?

Is it faster, using coin flips, to generate random ints from 1 to 9, with single factor solving algorithms, or is it computationally faster with multi-factor solving algorithms?

Solving using one factorization, one would process solving attempts with four instances of f(2), for a four bit/process return, that has a function range of 2^4=16. For generating an int from 1 to 9 with f(2) per that method, 9 of the 16 results would be valid, & 7 possible returns per solving attempts would be solving attempt fail/retries. Hence, this single factorization method of generating rand ints from 1 to 9 has a 7/16=%44 solving attempt fail/retry rate for a four process function.

Using instead multiple factors algorithmmically, the solving attempt fail/retry rate may be reduced, comparatively?

First, two instances of f(2) could generate a random int from 1 to 4, accepting only returns from 1 to 3, with a %25 solving attempt fail/retry rate for a two process solving attempt function.

Next, another two instances of f(2) could generate another random int from 1 to 4, accepting only returns from 1 to 3, with another %25 solving attempt fail/retry rate for its two process solving attempt function.

The first rand int from 1 to 3 may be added to {3* ((the second rand int from 1 to 3 result)-1)} to yield a rand int from 1 to 9, that has a %25 fail/retry rate for solving attempts of its first two processes, followed by a %25 fail/retry rate for solving attempts of its next two processes.

The f(2) -> f(9) solving efficiency of the second proposed algorithm may be more efficient, because it uses multiple factors, instead of a single factor?

For discussion of creating a random number generator from a coin toss, see Creating a random number generator from a coin toss




JS: Forward to a site with random parts in the URL

by opening a HTML-site, I want to redirect to the following page:

https://ift.tt/2Mx9zmLOPTION1&f2=OPTION2&f3=OPTION3&f4=OPTION4&f5=OPTION5&... etc.

The value for the "OPTIONS" should be randomly selected from a list (array) for every OPTION (1,2,3,4,5,..).

How can I do this with Javascript?

kind regards




Index error when drawing elements by index from list using random.randint()'s

fruits = ['Apple','Mango','Banana','Grapes','Guava']
random.seed(500)
low =0
high = len(fruits)
random_fruits = [fruits[random.randint(low,high)] for i in range(1000)]

This is my code and following is the error what I am getting?

IndexError: list index out of range




vendredi 29 juin 2018

How to generate a random number on the interval (0.8 ; 1)? (JAVA)

Math.random() give a pseudorandom number on the interval (0 ; 1]. But I wanted to generate in other intervals, such as, (0.5 ; 0.6) or (0.7; 1] or (0.8 ; 1) etc.




p5.js – Smoothly morphing random shape

first of all, i am a beginner on js and p5.js. My aim on this program is a smoothly morphing random shape. I was satisfied with the calculateShape()-function and the drawShape()-function, but when it comes to morphing (updateShape()) it gets really ugly. I thought it might be a good idea to save my current array into a temporary array, then loop over the array and add a random number to each x and y of each index and then replace the old x and y at this index. The main problem is, that it is always adding new shapes on the screen instead of changing the values of the vertices of the existing shape. Can anybody of you please give me a hint or point out my mistake(s)? THANK YOU IN ADVANCE!

var c1;
var c2;
var c3;
var centerX;
var centerY;
var fb;
var radius;
var angle;
var shape = [];
var temp;


/*function to calculate the inital shape*/
function calculateShape() {
    //calculate coordinates and save into array
    for (var i = 0; i < fb; i++) {
        var x = cos(angle * i) * radius + random(-77,77);
        var y = sin(angle * i) * radius + random(-77,77);
        var v = createVector(x, y);
        shape.push(v);
    }
}

/*function for morphing the shape*/
function updateShape() {
    var temp = shape;
    for (var i = 0; i < shape.length - 1; i++) {
        var x = temp[i].x + random(-1, 1);
        var y = temp[i].y + random(-1, 1);
        var p = temp[i];
        var v = createVector(x, y);
        shape.splice(p,1);
        shape.push(v);    
    }
}


/*function for drawing the shape on the screen*/
function createShape(){
    beginShape();
    curveVertex(shape[shape.length-1].x, shape[shape.length-1].y);
    for (var i = 0; i < shape.length; i++){
        curveVertex(shape[i].x, shape[i].y);
    }
    curveVertex(shape[0].x, shape[0].y);
    endShape(CLOSE);
}




function setup() {
    createCanvas(windowWidth, windowHeight);
    smooth();
    background(250);
    //frameRate(2);

    // defining possible colors
    c1 = color(0, 196, 181, 235); 
    c2 = color(50, 227, 232, 235);
    c3 = color(248, 49, 62, 255);
    var colors = [c1, c2, c3];


    //center of the window
    centerX = windowWidth/2;
    centerY = windowHeight/2;

    //defining all variables
    fb = 8; 
    angle = radians(360 / fb);
    radius = random(120, 140);

    //calling thefunction that initalises the shape
    calculateShape();
}


function draw() {
    translate(centerX, centerY);


    blendMode(BLEND);
    fill(c3);
    noStroke();


    createShape();
    updateShape();    
}




c# random numbers in abstract properties

How do I create an abstract property that can be a random number?

Parent.cs:

public abstract float ageInYears{get;}

Child.cs:

public override float ageInYears{
     get{
          return Random.Range(0, 10);
     }
}

How do I ensure the stagnation of the random number whenever it is accessed?




VBA get random string from array

I am trying to be able to return a string from an array that will be put into a label in a userform. I've seen a lot of things for this, but none of them seem to work. I have an array named Compliments that I want to pull one of the strings for that array and pass it through to my label6 but because this is a userform that only shows up when the sheet is opened and is opened momentarily I want to be able to make it random. Each time someone opens the sheet they will get a different compliment to help start their day. My code for everything is below:

Private Sub UserForm_Activate()
    TextBox1.Value = Date
    TextBox2.Value = Time
    TextBox3.Value = MainMenu.TextBox1.Value
    Label6.Caption = "RANDOM ARRAY GOES HERE"

    Application.Wait (Now + TimeValue("00:00:05"))

    Welcome.Hide
End Sub

Private Sub UserForm_Initialize()
    Me.StartUpPosition = 0
    Me.Top = (Application.Height / 2) - Me.Height / 2
    Me.Left = (Application.Width / 2) - Me.Width / 2

    Compliments = Array("Good Morning, You are Beautiful Today", _
        "I think you're pretty awesome", "That outfit looks great on you", _
        "You're a great engineer", "You rock Dude", "Nobody can get you down", _
        "Your makeup is spot on")
End Sub




why is the output in lottery code isn't working?

I'm supposed to make a code in c# (microsoft visual studio 2017) that lets the user input six numbers, and then compare them to an array of six randomly generated numbers(with no duplicates).

If the user has one match, he's supposed to get a message saying he had one match, and different messages for two or three matches, and so on.

This is what I got so far:

static bool isValueInArray(int value, int[] a)
    {
        for (int i = 0; i < a.Length; i++)
        {
            if (a[i] == value)
            {
                return true;
            }
        }

        return false;
    }

  static void Main(string[] args)
    {
        int min = 0;
        int max = 6;
        Random randnum = new Random();//random number generator
        int[] numbers = new int[6];// generates six numbers
        for (int i = 0; i < numbers.Length; i++)
        {
            numbers[i] = randnum.Next(min, max);//sets the numbers between 0 to 6
            if(isValueInArray( i, numbers))
            {
                numbers[i] = randnum.Next(min, max);
            }
        }

        try
        {
            Console.WriteLine("Hello and Welcome to our little game of lottery! lets see just how much luck you got!"); // greetings and instructions
            Console.WriteLine("You'll now get to choose 6 different numbers between 0 to 6 to play with.");
            Console.WriteLine("Go ahead and type them in.");

            int[] lottery = new int[6];

            for (int i = 0; i < lottery.Length; i++)
            {
                lottery[i] = int.Parse(Console.ReadLine()); // array to catch six numbers input
                if (lottery[i] > 6)//checking if the numbers fit between 0 and 6
                {
                    Console.WriteLine("whoops! the number you enetered isn't in range! please try again ^^");
                    break;
                }

                int x = 6;
                for (int a = 0; a < lottery.Length; a++)
                {
                    for (int b = 0; b < numbers.Length; b++)
                    {
                        if (lottery[a] == numbers[b])
                        {
                            a++;
                            x--;
                            if (x == 6)
                            {
                                Console.WriteLine("six match");
                                break;
                            }
                            else if (x == 5)
                            {
                                Console.WriteLine("five match");
                                break;
                            }
                            else if (x == 4)
                            {
                                Console.WriteLine("four match");
                                break;
                            }
                            else if (x == 3)
                            {
                                Console.WriteLine("three match");
                                break;
                            }
                            else if (x == 2)
                            {
                                Console.WriteLine("two match");
                                break;
                            }
                            else if (x == 1)
                            {
                                Console.WriteLine("one match");
                                break;
                            }

                        }
                    }
                }
            }
        }

        catch (FormatException)// checking if the input is in char format
        {
            Console.WriteLine("only numbers please!");
        }
    }

My problem is with the output. The program seems to go over all of the "else if" options and print all of them, instead of picking and printing just one of them.




Pandas: Filling random empty rows with data

I have a dataframe with several currently-empty columns. I want a fraction of these filled with data drawn from a normal distribution, while all the rest are left blank. So, for example, if 60% of the elements should be blank, then 60% would be, while the other 40% would be filled. I already have the normal distribution, via numpy, but I'm trying to figure out how to choose random rows to fill. Currently, the only way I can think of involves FOR loops, and I would rather avoid that.

Does anyone have any ideas for how I could fill empty elements of a dataframe at random? I have a bit of the code below, for the random numbers.

data.loc[data['ColumnA'] == 'B', 'ColumnC'] = np.random.normal(1000, 500, rowsB).astype('int64')




Speed of a PRNG

Is there a specific algorithm or method of calculating the speed of a pseudo random number generator? I've recently made a PRNG, and for my last question here I learned that the Big-O analysis is not suitable in my situation. I want to compare my program's speed to a well known pseudo random number generator, but I can't find any valuable information related to it.




Fast random string

I'm trying to generate random string ID for a program (the ID has to be unique only during the execution of the program). I first did it in Python without any issue :

class RandomIdGenerator:
    _base_62_chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

    @classmethod
    def get_base_62(cls, length):
        return "".join([random.choice(RandomIdGenerator._base_62_chars) for _ in range(length)])

But as I need my program to be in C++, I'm trying to generate the same string with it. This is what I do now :

void Node::setId()
{
    QString allow_symbols("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
    qsrand(QTime::currentTime().msec());

    for (int i = 0; i < ID_LENGTH; ++i) {
        id_.append(allow_symbols.at(qrand() % (allow_symbols.length())));
    }
}

I have two main issues with it. First it doesn't use C++11 (I don't know how Qt works but I don't think it's C++11) and the ID generated are all the same. If I generate four of them I get :

"R4NDM1xM"
"R4NDM1xM"
"R4NDM1xM"
"R4NDM1xM"

I tried using the C++11 method but I got the same result, even worse, at each execution, I got the exact same result :

void Node::setId()
{
    id_ = "";

    const std::string str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    std::random_device rd;
    std::mt19937 generator(rd);
    std::uniform_int_distribution<int> dist(0, str.size() - 1);

    for (int i = 0; i < Node::ID_LENGTH; ++i)
        id_ += str[dist(generator)];
}

How can I generate random string ID at each call of a method?




jeudi 28 juin 2018

How to start java swing timer?

Right now, the object moves a certain increment each time I manually click a button, but its actually suppose to move on its own across the screen on its own once a button is clicked. I tried calling timer.start(); various times in my code. As well as, setting up an 'if' statement in the actionPerformed method that checks for a button being pressed and then calls timer.start() as a result. But, it didn't get the object to move on its own.

Can anyone lead me in the right direction? Am I not writing the code right? Or is does this problem have something to do with java swing timer.

PS. I am new to java,

This is what I have imported in the beginning :

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Random;

And this is part of my code :

 public void actionPerformed(ActionEvent e){

    if (e.getSource() == rightBtn) {    
        objXpos += objMoveIncrement;
        direction = "right";
        direction.equals("Right");

    }
    if (e.getSource() == leftBtn) {
        direction = "left";
        direction.equals("Left");
        objXpos -= objMoveIncrement;
    }

    repaint();

} } **edit the timer is suppose to start once a button is clicked, and the timer is what allows the object to move across the screen




TypeError: 'tuple' object cannot be interpreted as an integer

I have x0 which is a float64 (64,64) array. Whenever I try this:

    delta = np.random.randn(x0.shape)

It gives the captioned error. This is so basic that I'm wrapping my heads around it. What am I missing out? Thanks

The complete traceback is as follows:

Traceback (most recent call last):

  File "<ipython-input-31-dcd2365ed519>", line 1, in <module>
    delta = np.random.randn(x0.shape)

  File "mtrand.pyx", line 1420, in mtrand.RandomState.randn

  File "mtrand.pyx", line 1550, in mtrand.RandomState.standard_normal

  File "mtrand.pyx", line 167, in mtrand.cont0_array

TypeError: 'tuple' object cannot be interpreted as an integer




Why is stratifiedkfold generating the same splits in spite of using different random_state values?

I am trying to generate different stratified splits of my data set using stratifiedkfold split and random_state parameter. However, when I use different random_state values, I still get the same splits. My understanding is that by using different random_state values, you will be able to generate different splits. Please let me know what I am doing incorrectly. Here is the code.

import numpy as np
X_train=np.ones(10)
Y_train=np.ones(10)

from sklearn.model_selection import StratifiedKFold
skf = StratifiedKFold(n_splits=5,random_state=0)
skf1 = StratifiedKFold(n_splits=5,random_state=100)


trn1=[]
cv1=[]
for train, cv in skf.split(X_train, Y_train):
    trn1=trn1+[train]
    cv1=cv1+[cv]

trn2=[]
cv2=[]
for train, cv in skf1.split(X_train, Y_train):
    trn2=trn2+[train]
    cv2=cv2+[cv]


for c in list(range(0,5)):
    print('Fold:'+str(c+1))
    print(trn1[c])
    print(trn2[c])
    print(cv1[c])
    print(cv2[c])

Here is the output

Fold:1
[2 3 4 5 6 7 8 9]
[2 3 4 5 6 7 8 9]
[0 1]
[0 1]
Fold:2
[0 1 4 5 6 7 8 9]
[0 1 4 5 6 7 8 9]
[2 3]
[2 3]
Fold:3
[0 1 2 3 6 7 8 9]
[0 1 2 3 6 7 8 9]
[4 5]
[4 5]
Fold:4
[0 1 2 3 4 5 8 9]
[0 1 2 3 4 5 8 9]
[6 7]
[6 7]
Fold:5
[0 1 2 3 4 5 6 7]
[0 1 2 3 4 5 6 7]
[8 9]
[8 9]




What is the best recomendation for a random num. gen. for windows (using dev CPP)?

In linux I use drand48 and srand48. It works GREAT. Now I am trying to run my code (for simplicity, say it is c, not c++) on Dev-CPP in windows 7, and apparently this doesn't work (yes - I remember to include stdlib.h). See code segment below.

There is an infinite number OLD discussions (that I've found) about this problem online. My simple question is:

What is the best alternative for drand48, for me to use on my system. I need good accuracy since I have to select 10^8 random numbers (in a loop). For the same reason, I also need it to be fast. This is 2018: What do we have now for this purpose? How to use it?

Thanks!

Code segment:

#include <omp.h> 
#include <stdio.h> 
#include <stdlib.h>
#include <math.h> 
#include <time.h>
double Gaussian(void)   
{ 
double X1,X2,Y1,w=0.0; 
do { X1=2.0*(drand48())-1.0; 
 X2=2.0*(drand48())-1.0; 
 w=X1*X1+X2*X2; } while (w>=1.0); 
w=sqrt((-2.0*log(w))/w); 
static int q=0;  
if (q==0) Y1=X1*w; else { Y1=X2*w; q=1-q; } 
return Y1;
}

int main (void) /* Main program */ 
{ 
long int iseed=time(0);
srand48(iseed); 
int n=0; 
double X=0.0;


    for (n=0;n<10;n+=1) 
        {
            X=X+Gaussian();
        }
return (0);  
}  

This returns: [Error] 'drand48' was not declared in this scope. Also: [Error] 'srand48' was not declared in this scope.




Javascript - onClick random image [duplicate]

This question already has an answer here:

I need some help with a small exercise I am doing using Javascript. I must create a small page with a menu generated from Javascript, and an image source that, when the image is clicked, the image is changed to a random image. If the next random image is same as the one before, I must generate another random image. How can this be done please?

HTML:

<!DOCTYPE html>
<html>
    <head>
        <title>Revision</title>
    </head>

    <body>
        <nav id="menu"></nav>
        <img id="image" width="300px" height="200px"/>
        <script src="js/mainScript.js"></script> 
        <script src="js/script.js"></script> 
    </body>
</html>

Javascript:

var imgArray = ["js/images/bmw1.JPG", "js/images/bmw2.jpg", 
"js/images/bmw3.jpg"];
var image = document.getElementById("image");
image.src = imgArray[0];

function changeImage()
{
    var i = imgArray.indexOf(this.getAttribute("src"));

    if(i < (imgArray.length-1))
        {
            i++;
            this.src = imgArray[i];
        }
    else
        {
            this.src = imgArray[0];
        }
}

image.addEventListener('click', changeImage);

As is, the code will show the first image, which is BMW1.jpg, and after I click on the image, it goes to the next image, BMW2.jpg, then on BMW3.jpg, and then it starts over.

Thanks!

EDIT: This is not a duplicated question as this needs image sources to be random, not numbers.




How to create simple random array using CUDA xoroshiro128p

I need to get simple example for creating random array using CUDA xoroshiro128p. For example final array shell by size(2,4). Link for numba doc here

Pseudo code:

minimum = -2
maximum = 2

out_array = random(minimum, maximum, shape(2,4))

Output:
[[ 1.87569628  2.85881711  3.6009965   1.49224129]
 [-3.27321953  1.59090995 -4.66912864 -3.43071647]]




mercredi 27 juin 2018

How to assign random interior color of cells as I add names to a list?

This is my first time posting so please have mercy! I have tried to assign random colors to a name list so I can later recall and populate another list of a staffing sheet.

This is my code so far but it doesn't work for some odd reason. I'm not sure if someone already asked this question but my search has turned up empty handed.

Thanks!

Private Sub Worksheet_Change(ByVal Target As Range)
    Set WF = Application.WorksheetFunction
    If Target.Cells.Column = 1 Then
        If Target.Column = 3 Then
            x = 0
            On Error Resume Next
            x = WF.Match(Target.Value, _
                Range("C1").Resize(Target.Row - 1), _
                0)
            On Error GoTo 0
            If x > 0 Then
                ' duplicate value...copy the old color
                Target.Interior.Color = Cells(x, 3).Interior.Color
            Else
                ' choose a new color
                Target.Interior.Color = RGB( _
                    WF.RandBetween(0, 255), _
                    WF.RandBetween(0, 255), _
                    WF.RandBetween(0, 255))
            End If
        End If
    End If
End Sub




Pick random values from c# array and make sure you don't use the same one again [duplicate]

This question already has an answer here:

I wanted to pick random values from a c# array of strings in a foreach loop and make sure that i don't pick the same value twice...

I know how to build the array and loop through it, but I don't know how to randomly pick a value from the array or keep track of the values I've already picked, can someone enlighten me please?

So far I have;

//create an array of strings
string[] stringArray = { "string 1", "string 2", "string 3"};

//loop through the array using the strings in a foreach loop
foreach (string randomStringSelected in stringArray)
{
//do stuff here with randomly selecting value from array HERE
}

....pretty standard, but it would be nice to randomly pick "string 2" first, keep a track of the fact I've used it, on the next loop around in the foreach pick either "string 1" or "string 3"...but I don't know how. I've seen something about using a List or Dictionary and the Random function but (if I'm being honest) I didn't understand how to get those things worked.

Many thanks in advance for any help!




Rounding to two decimal places is not working

I am trying to reduce the decimal places of my number to two. Unfortunately is not possible. For this reason I added some of my code, maybe you will see the mistake...

Update [dbo].[company$Line] SET Amount = ROUND((SELECT RAND(1) * Amount),2), ... SELECT * FROM [dbo].[company$Line]

Amount in db which I want to change:

0.00000000000000000000 1914.65000000000010000000 376.81999999999999000000 289.23000000000002000000

Result I get after executing the code:

0.00000000000000000000 1366.28000000000000000000 268.89999999999998000000 206.38999999999999000000

Result I want to get (or something like this):

0.00 1914.70 376.82 289.23




mardi 26 juin 2018

error with random.sample: raise NotImplementedError(" >= and <= don't work with 0.") NotImplementedError: >= and <= don't work with 0

I have a problem with this code, I really dont understand why it cannot reach the second cycle of the most internal for:

def remove_random_links(A,E):
    rs = random.sample(A.edges, E)
    A.remove_edges_from(rs)

N = 30
L = [0,60,30,40,30,30,20,40]
rep = 15
d = []
g = []

for j in range(rep):
    R = nx.grid_graph(dim=[N,N])  
    _deg = []
    _gap = [] 
    for i in L:
        remove_random_links(R,i)
        A = nx.adj_matrix(R)
        L = nx.laplacian_matrix(R) 
        eigwd, eigv = LA.eigh(L.todense())
        eigw = np.sort(eigwd)
        eigw0 = eigw[0]
        eigw1 = eigw[1]
        eigw2 = eigw[2]
        eigw3 = eigw[3]
        gap = eigw2 - eigw1
        deg = eigw3 - eigw2
        _deg.append(deg)
        _gap.append(gap)
        print("meow")    
    d.append(_deg)
    g.append(_gap)
    print("M")

It goes on its first for cycle (the one in j) and then into its first for cycle in i, it completes it and then it is not able to do the second one because of this error with the function remove_random_links(), which gives me the following error:

File "/Users/Sofia/Desktop/delta.py", line 23, in remove_random_links(R,i)

File "/Users/Sofia/Desktop/delta.py", line 9, in remove_random_links rs = random.sample(A.edges, E)

File "/anaconda3/lib/python3.6/random.py", line 317, in sample if not 0 <= k <= n:

File "/anaconda3/lib/python3.6/site-packages/scipy/sparse/compressed.py", line 322, in ge "Comparing a sparse matrix with a scalar "

File "/anaconda3/lib/python3.6/site-packages/scipy/sparse/compressed.py", line 272, in _inequality raise NotImplementedError(" >= and <= don't work with 0.")

NotImplementedError: >= and <= don't work with 0.




Visual Basic Randomize() vs New Random

It seems that Randomize() Rnd()Randomize() Rnd() aren't used anymore. Instead people make something like:

Dim rng as New Random() Dim randomNo as Integer = rng.Next(10) ‘ this is a random number between 0 and 10. Dim anotherRandomNo as Integer = rng.Next(10) ‘ a different random number.

Dim rng as New Random() Dim randomNo as Integer = rng.Next(10) ‘ this is a random number between 0 and 10. Dim anotherRandomNo as Integer = rng.Next(10) ‘ a different random number.

Could someone tell me why this is considered 'better' in most circumstances?

Thanks

Zima




I find a bug in Leetcode 215. Kth Largest Element in an Array

I write code for leetcode 215 Kth Largest Element in an Array

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

int partition(vector<int>& nums, int start, int end)
{
    uniform_int_distribution<int> distribution(start, end);
    default_random_engine generator;
    int pivotIdx = distribution(generator);
    int pivot = nums[pivotIdx];
    std::swap(nums[pivotIdx], nums[end - 1]);

    int i = start;
    for (int j = start; j < end; ++j)
    {
        if (nums[j] < pivot)
        {
            std::swap(nums[i], nums[j]);
            ++i;
        }
    }

    std::swap(nums[i], nums[end - 1]);

    return i;
}


int findKthLargest(vector<int>& nums, int k)
{
    int size = (int)nums.size();

    int tempIdx = size - k;

    int start = 0;
    int end = size;
    while (start < end)
    {
        int pivotIdx = partition(nums, start, end);

        if (tempIdx < pivotIdx)
        {
            end = pivotIdx;
        }
        else if (tempIdx > pivotIdx)
        {
            start = pivotIdx + 1;
        }
        else
        {
            return nums[tempIdx];
        }
    }

    return -1;
}

nums = { 3, 2, 1, 5, 6, 4 }, k = 2,

in my computer, return 6, is wrong!

but online, return 5, is correct, is Accepted! Why?




lundi 25 juin 2018

Write a function that randomly picks a string from array in C++

I am in a C++ beginning programming class and we are currently studying classes and constructors. I have been stuck on an assignment where we must write a function to randomly pick a color from our color array. Below is what I have so far. I think I am close but I am getting a compiler error and not sure how to fix it.

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;

class ColorClass {
    public:
        ColorClass(string colors) {
            setColors(colors);
        }
        void setColors(string x) {
            colors[7] = x;
        }
        const string getColors() {
            return colors[7];
        }
        string randomizeColor(string x) {
            srand (time(NULL)); //initialize the random seed
            string word = x[rand() % 7]; //**get a compiler error here**
            return word;
        }
    private:
        string colors[7];
};

int main() {
    ColorClass colorClassInstance("Red, Orange, Yellow, Green, Blue, Purple, Indigo");

    cout << colorClassInstance.getColors() << endl;
    cout << colorClassInstance.randomizeColor(colorClassInstance.getColors()) << endl;

    return 0;
}

The compiler error is something like

no viable conversion from std::__1::basic_string...std::_1::allocator

(too long to type out, but hoping someone understands this on first glance).




Lagged Fibonacci RNG Returning negative

I have this code for a lagged fibonacci RNG in c-sharp. Some of the results i'm getting from this code are negative and or duplicates. Do you know the issue with this please?

    int[] initialSetofKStates;
    //Declare Values for j, k and m
    int n = 0;
    int k = 89;
    int j = 38;
    double M = Math.Pow(2,32);

    public LaggedFibonacciRNG()
    {
        //Set n equal to k
        n = k;
        //Initialize the initial set of K to hold k Random Numbers
        initialSetofKStates = new int[k];
        //Fill the initial set of K states with Random Numbers
        Random r = new Random();
        for (int i = 0; i < initialSetofKStates.Length;i++)
        {
            initialSetofKStates[i] = r.Next();
        }
    }

    public decimal generateRandomNumber(int max)
    {

        if (k <= 1) k = 89; else k--;
        if (j <= 1) j = 38; else j--;

        int rand1 = initialSetofKStates[n - k];
        int rand2 = initialSetofKStates[n - j];
        long Random = (long)((rand1 + rand2) % M);
        initialSetofKStates[n-k] = (int)Random;

        return (decimal) Math.Floor((Random * max) / M);
    }




Finding a source of entropy in an embedded system?

For a small embedded device (TI MSP430F2274), I am trying to create a PRNG, but am having difficulty identifying a potential source of entropy to use as a seed. Unfortunately, the device does not have enough available memory space to include time.h and incorporate the function srand(time(0)). Has anyone had experience with this family of devices, or has incorporated a PRNG in an embedded device that is constrained by its memory space? Thank you.




Random selection in SQL Server

I have two sets and for each value in the first set I want to apply a number of random values from the second. The approach I have chosen uses a select from the first with a cross apply from the second. A simplified MWE is as follows:

DROP TABLE IF EXISTS #S;
CREATE TABLE #S (c CHAR(1));
INSERT INTO #S VALUES ('A'), ('B');
DROP TABLE IF EXISTS #T;
WITH idGen(id) AS (
    SELECT 1 
    UNION ALL 
    SELECT id + 1 FROM idGen WHERE id < 1000
) 
SELECT id INTO #T FROM idGen OPTION(MAXRECURSION 0);
DROP TABLE IF EXISTS #R;
SELECT c, id INTO #R FROM #S
CROSS APPLY (
    SELECT id, ROW_NUMBER() OVER (
        /* 
        -- this gives 100% overlap
        PARTITION BY c
        ORDER BY RAND(CHECKSUM(NEWID()))
        */
        -- this gives the expected ~10% overlap
        ORDER BY RAND(CHECKSUM(NEWID()) + CHECKSUM(c))
    ) AS R
    FROM #T 
) t
WHERE t.R <= 100;
SELECT COUNT(*) AS PercentOverlap -- ~10%
FROM #R rA JOIN #R rB
ON rB.id = rA.id AND rB.c = 'B'
WHERE rA.c = 'A';

While this solution works, I am wondering why changing to the (commented) partitioning method does not? Also, are there any caveats using this solution, seeing as it feels sort of dirty to add two checksums?

In the actual problem there is also a count in the first set containing the number of random values to select from the second set, which replaces the static 100 in the example above. However, using the fixed 100 made it easy to verify the expected overlap.




How to generate random Int in Haskell?

i'm trying to generate a random index (Int), with this code: randomRIO (0, 2 :: Int). But its generate a IO Int, so i cant do something like this: [1,2,3] !! randomIndex. What does it have to be done to convert the IO Int to Int? Thanks.




How do you not get repeating numbers from math.floor?

My goal is to make these gems all have different values from 1-10

If you could help me out while still using mathfloor I would appreciate that as well

//Variables
var emGem = 0;
var ruGem = 0;
var diGem = 0;
var saGem = 0;
var possibleGem = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

//Initiate scores
emGem = possibleGem[Math.floor(Math.random() * possibleGem.length)];
ruGem = possibleGem[Math.floor(Math.random() * possibleGem.length)];
diGem = possibleGem[Math.floor(Math.random() * possibleGem.length)];
saGem = possibleGem[Math.floor(Math.random() * possibleGem.length)];

//Debug
console.log(emGem);
console.log(ruGem);
console.log(diGem);
console.log(saGem);
console.log(randomNumber);



Java - how to divide an integer into 5 random parts

I'm working on an android graphics app, and at some point in the code, I need to divide lets say, a rectangle's width into 5 random sizes.

I have my randomintegerfunction(int min, int max) in my activity, but that can help me divide it into 2 parts.

How do I go about dividing an integer, lets say 100, into 5 random parts, so that the first one or two parts arent always the biggest, then I subdivide for the third, fourth and fifth parts?

Right now, I am know I can try to implememt it using my random integer generator,but the issue, I think is that I'd have to use some forced divisions, like dividing the first 70% of the integer into 2 parts, then dividing the remaining 20% into two parts, to make a total of 5 parts, but such a method would always make the first part be bigger than the fifth part, which I'd like to avoid...to make it truly random.

What I'd like, for example...

the first part to potentially be 7, second part 25, third part 5, fourth part 40, fifth/last/remaining part 23. To add up to 100 (or any integer).

I am not sure about how to write the logic of such a function...so please if you have any ideas of how to implement a function that randomly divides an integer into 3 or 4 or 5 or 6 truly random sizes/parts, please enlighten me!

Thanks for your time!




Why would you increment a RNG seed?

I've seen code of the following kind (in a unit test) and I was wondering what could be the motivation behind it:

int seed = GetMySeed()
Something(seed++)
SomethingElse(seed++)
YetSomethingElse(seed++)

Now, if the three functions called were the same, I could image scenarios where you want this, e.g. creating multiple instances of an object with a different seed. However, in my mind, the direct modification of a seed feels like bad practice. Even if I had reasons to modify the seed, it would seem more natural to me to write:

int seed = GetMySeed()
TheSameThing(seed)
TheSameThing(seed + 1)
TheSameThing(seed + 2)

What might be the reason you would increment the seed?




dimanche 24 juin 2018

What's the difference between nextDouble and nextFloat in the random class?

To my knowledge, they both do the same thing, which is generate a value between 0.0 and 1.0, right?




How to generate random sampling in python . with integers. with sum and size given

Is there a direct function or any another way in python where I can generate random integers for my given size and I want to specify sum of those numbers as well.

For example. I want to generate 7 numbers whose sum is 341.

Can I also specify mean for this. Like 7 numbers with mean 165 and sum 341. (optional)




LibGDX internal calls to MathUtils.random() interfere with the sequence of random numbers generated

While using a random number generator (RNG) with a given seed several times (ie. each time calling setSeed() with the same seed to start over), I have encountered some deviation in the sequence of numbers generated on each pass. After banging my head against the wall a few times I found the reason to be this:

box2d's World.createBody() calls LongMap.put(), which calls LongMap.push(), which calls MathUtils.random() inside a while loop.

To my knowledge particle effects call MathUtils.random() too.

So how can I trust a sequence of numbers to always repeat itself if LibGDX internally uses the same static RNG instance and therefor could mess up the sequence?

How am I supposed to know exactly where and when MathUtils.random() is called outside my code?




How to withdraw unique images?

How to withdraw unique images?

int[] resimler ={R.drawable.yesil,R.drawable.mavi,R.drawable.kare,R.drawable.soru};

    int[] secilen=new int[resimler.length];

    for (int i=0;i<resimler.length;++i) {


        int resim=resimler[new Random().nextInt(resimler.length)];

        secilen[i]=resim;


    }



    img1.setImageResource(secilen[0]);
    img2.setImageResource(secilen[1]);
    img3.setImageResource(secilen[2]);
    img4.setImageResource(secilen[3]);




Efficient random sampling

My problem is simple: I've an array with 20 million floats. In that array, every float has a probability p of being randomly altered.

The simples way to do so is to move through the array, doing if (rand(0,1) < p) then modify.

However, even paralelizing, its slow as hell, and I was thinking if there's a faster way to randomly obtain some indexes to modify.

My first thought was to pick up p * n random numbers, where n is the total number of floats in the array, however, that doesnt exactly represent the probability distribution, as nothing in the first case guarantees that only p*n floats will be modified.

Ideas?

PD: I'm using python for the implementation, probably someone had this problem before and implemented something in the libraries, but I cannot find it.




Why is the first and second image of the spin slot cant never be the same?

i have a project in assembly that i have written, its a spin slot with 3 picture option. i dont know why' ive been sitting hours and couldn't find why the first and second image slot can't never be the same and that's causes the win condition can never be achived.

this is the code:

IDEAL
MODEL small
STACK 100h
DATASEG
; --------------------------
; your variables here
    ; name of image file
    va db 1,2,3,4   
    filename db 'pic2.bmp',0      
    smallpic1 db 'sppic1.bmp',0   
    smallpic2 db 'sppic2.bmp',0     
    smallpic3 db 'sppic3.bmp',0     
    smallpic4 db 'sppic4.bmp',0     
    smallpic5 db 'sppic5.bmp',0    
    ; x and y ccordinates of imag left down corner
    x_coord dw 0
    y_coord dw 200
    image_height dw 140   
    ; must be an 8 multiplication
    image_width dw 320 

    ; image file handle - received 
    ; when opening a file
    filehandle dw ?                 

    ; image file header
    Header db 54 dup (0)

    ; color table
    Palette db 256*4 dup (0)

    ; a buffer holding one image line 
    ; must be an 8 multiplication
    ScrLine db 320 dup (0)

    ; printed when we fail to open file
    ErrorMsg db 'Error', 13, 10,'$'

    diff dw ?  
forstars db ' for start press s',10,13,'$'    
instruction db ' to roll the spin slot press on enter',10,13,' and see what you get, if the three',10,13,' picture are the same you win, for',10,13,' rolling it again press on enter',10,13,' and for exit press e$'

MAX_TICKS db 20 
lastTick db 0   
TickCounter db 0  
adda db '   to roll the spin slot press enter$'
; --------------------------
CODESEG
proc OpenFile
; Open image file file
    mov ah, 3Dh
    xor al, al

    int 21h
    jc openerror
    mov [filehandle], ax
    ret
openerror:
    mov dx, offset ErrorMsg
    mov ah, 9h
    int 21h
    ret
endp OpenFile

; close file at end of use
proc CloseFile
    push bx
    push ax
    mov bx, [filehandle]
    mov ah, 3Eh
    int 21h
    pop ax
    pop bx
    ret
endp CloseFile
proc ReadHeader
; Read BMP file header, 54 bytes
    mov ah,3fh
    mov bx, [filehandle]
    mov cx,54
    mov dx,offset Header
    int 21h
    ret
endp ReadHeader

proc ReadPalette
; Read BMP file color palette, 256 colors * 4 bytes (400h)
    mov ah,3fh
    mov cx,400h
    mov dx,offset Palette
    int 21h
    ret
endp ReadPalette

proc CopyPal
; Copy the colors palette to the video memory
; The number of the first color should be sent to port 3C8h
; The palette is sent to port 3C9h
    mov si,offset Palette
    mov cx,256
    mov dx,3C8h
    mov al,0
    ; Copy starting color to port 3C8h
    out dx,al
    ; Copy palette itself to port 3C9h
    inc dx
PalLoop:
    ; Note: Colors in a BMP file are saved as BGR values 
    ; rather than RGB.
    mov al,[si+2] ; Get red value.
    shr al,2 ; Max. is 255, but video palette maximal
    ; value is 63. Therefore dividing by 4.
    out dx,al ; Send it.
    mov al,[si+1] ; Get green value.
    shr al,2
    out dx,al ; Send it.
    mov al,[si] ; Get blue value.
    shr al,2
    out dx,al ; Send it.
    add si,4 ; Point to next color.
    ; (There is a null chr. after every color.)

    loop PalLoop
    ret
endp CopyPal


proc CopyBitmap
; BMP graphics are saved upside-down.
; Read the graphic line by line (200 lines in VGA format),
; displaying the lines from bottom to top.
    mov ax, 0A000h
    mov es, ax

    ; calculate gap between screen buttom and down corner
    mov ax, [y_coord]
    sub ax, [image_height]
    mov [diff], ax

    ;number of lines - loop iterations 
    mov cx,[image_height]  
PrintBMPLoop:
    push cx ; keep cx - because it is used in loop

    ; di = cx*320, point to the correct screen line
    add cx, [diff]
    mov di,cx
    shl cx,6
    shl di,8
    add di,cx
    add di, [x_coord]

    ; Read one line
    mov ah,3fh
    mov cx,[image_width]
    mov dx,offset ScrLine
    int 21h

    ; Copy one line into video memory
    cld ; Clear direction flag, for movsb
    mov cx,[image_width]
    mov si,offset ScrLine

    rep movsb ; Copy line to the screen
     ;rep movsb is same as the following code:
     ;mov es:di, ds:si
     ;inc si
     ;inc di
     ;dec cx
     ;loop until cx=0
    pop cx
    loop PrintBMPLoop
    ret
endp CopyBitmap

proc startphoto
; Process BMP  file
    call OpenFile
    call ReadHeader
    call ReadPalette
    call CopyPal
    call CopyBitmap
    call CloseFile
    ret
endp startphoto

proc clean
;taxt mood  
    push ax
    mov ax, 2 
    int 10h
; Graphic mod
    mov ax, 13h
    int 10h
    pop ax
    ret
endp clean

proc randomnumber
random1:
; put segment number in 
; register es
    mov ax, 40h
    mov es, ax

; move random number to ax
    mov ax, [es:6Ch]
    xor ax, [bx]
    inc bx
    and ax, 15
    cmp ax, 4
    ja random1
    ret 
endp randomnumber

proc sfphoto
;small first pic
    mov [x_coord], 50
    mov [y_coord], 100
    mov [image_height],40
    mov [image_width],  40
    mov dx, offset smallpic1
    call startphoto
    ret 
endp sfphoto

proc sfphoto1
;small first pic
    mov [x_coord], 140
    mov [y_coord], 100
    mov [image_height],40
    mov [image_width],  40
    mov dx, offset smallpic1
    call startphoto
    ret 
endp sfphoto1

proc sfphoto2
;small first pic
    mov [x_coord], 230
    mov [y_coord], 100
    mov [image_height],40
    mov [image_width],  40
    mov dx, offset smallpic1
    call startphoto
    ret 
endp sfphoto2


proc ssphoto
;small second pic
    mov [x_coord], 50
    mov [y_coord], 100
    mov [image_height],40
    mov [image_width],  40
    mov dx, offset smallpic2
    call startphoto
    ret 
endp ssphoto

proc ssphoto1
;small second pic
    mov [x_coord], 140
    mov [y_coord], 100
    mov [image_height],40
    mov [image_width],  40
    mov dx, offset smallpic2
    call startphoto
    ret 
endp ssphoto1

proc ssphoto2
;small second pic
    mov [x_coord], 230
    mov [y_coord], 100
    mov [image_height],40
    mov [image_width],  40
    mov dx, offset smallpic2
    call startphoto
    ret 
endp ssphoto2


proc sthphoto
;small therd pic
    mov [x_coord], 50
    mov [y_coord], 100
    mov [image_height],40
    mov [image_width],  40
    mov dx, offset smallpic3
    call startphoto
    ret 
endp sthphoto

proc sthphoto1
;small therd pic
    mov [x_coord], 140
    mov [y_coord], 100
    mov [image_height],40
    mov [image_width],  40
    mov dx, offset smallpic3
    call startphoto
    ret 
endp sthphoto1

proc sthphoto2
;small therd pic
    mov [x_coord], 230
    mov [y_coord], 100
    mov [image_height],40
    mov [image_width],  40
    mov dx, offset smallpic3
    call startphoto
    ret 
endp sthphoto2

proc sfophoto
;small four pic
    mov [x_coord], 50
    mov [y_coord], 100
    mov [image_height],40
    mov [image_width],  40
    mov dx, offset smallpic4
    call startphoto
    ret 
endp sfophoto

proc sfophoto1
;small four pic
    mov [x_coord], 140
    mov [y_coord], 100
    mov [image_height],40
    mov [image_width],  40
    mov dx, offset smallpic4
    call startphoto
    ret 
endp sfophoto1

proc sfophoto2
;small four pic
    mov [x_coord], 230
    mov [y_coord], 100
    mov [image_height],40
    mov [image_width],  40
    mov dx, offset smallpic4
    call startphoto
    ret 
endp sfophoto2

proc sfiphoto
;small five pic
    mov [x_coord], 50
    mov [y_coord], 100
    mov [image_height],40
    mov [image_width],  40
    mov dx, offset smallpic5
    call startphoto
    ret 
endp sfiphoto

proc sfiphoto1
;small five pic
    mov [x_coord], 140
    mov [y_coord], 100
    mov [image_height],40
    mov [image_width],  40
    mov dx, offset smallpic5
    call startphoto
    ret 
endp sfiphoto1

proc sfiphoto2
;small five pic
    mov [x_coord], 230
    mov [y_coord], 100
    mov [image_height],40
    mov [image_width],  40
    mov dx, offset smallpic5
    call startphoto
    ret 
endp sfiphoto2


; read_clock - A pocedure for clock reading
; when done clock values ar in cx and dx
proc read_clock
    push    ax
    mov     ah, 2ch
    int     21h     ; clock interrupt
    pop     ax
    ret
endp read_clock

;FIRST CLOCK
; wait_ticks - the below procedure waits for 
; MAX_TICKS clock ticks  -  this is done by reading the clock
; and counting tick changes in dl
proc wait_ticks
    ; keep registers
    push    dx
    push    cx
    push    ax

    mov al, [MAX_TICKS]
    ; read clock to initiate lastTick
    call    read_clock
    mov     [lastTick], dl
    mov     [tickCounter], 0

ticksLoop:
    ;read the clock and check if it was changed
    call    read_clock
    cmp     [lastTick], dl
    je      ticksLoop       ; no tick - do nothing - jump back to ticksLoop

    ; clock was changed - a new tick
    inc     [tickCounter]
    cmp     [tickCounter], al
    je      timeover

    ; MAX_TICK was not reached
    mov     [lastTick], dl
    jmp     ticksLoop
timeover:
    pop     ax
    pop     cx
    pop     dx
    ret
endp wait_ticks



proc game 
    call randomnumber
;compering
    cmp ax, 00
    je one 
    cmp ax, 01
    je two
    cmp ax, 02
    je three
    cmp ax, 03 
    je four
    cmp ax, 04
    je five
one:
;small first pic
    call sfphoto
    jmp ffph
two:
;small second pic
    call ssphoto
    jmp ffph
three:
;small therd pic
    call sthphoto
    jmp ffph
four:
;small four pic
    call sfophoto
    jmp ffph
five:
;small five pic
    call sfiphoto
    jmp ffph
ffph:
;start printing second picture
    call wait_ticks
    call randomnumber
;compering
    cmp ax, 00
    je one1
    cmp ax, 01
    je two1
    cmp ax, 02
    je three1
    cmp ax, 03 
    je four1
    cmp ax, 04
    je five1
one1:
;small first pic
    call sfphoto1
    jmp fsph
two1:
;small second pic
    call ssphoto1
    jmp fsph
three1:
;small therd pic
    call sthphoto1
    jmp fsph
four1:
;small four pic
    call sfophoto1
    jmp fsph
five1:
;small five pic
    call sfiphoto1
    jmp fsph
fsph:
;start printing therd picture
    mov [MAX_TICKS], 20
    call wait_tickS
    call randomnumber
    ;compering
    cmp ax, 00
    je one2
    cmp ax, 01
    je two2
    cmp ax, 02
    je three2
    cmp ax, 03 
    je four2
    cmp ax, 04
    je five2
one2:
;small first pic
    call sfphoto2
    jmp fthph
two2:
;small second pic
    call ssphoto2
    jmp fthph
three2:
;small therd pic
    call sthphoto2
    jmp fthph
four2:
;small four pic
    call sfophoto2
    jmp fthph
five2:
;small five pic
    call sfiphoto2
    jmp fthph
fthph:
    ret
endp game


proc afterClean
    mov [MAX_TICKS], 20
    call wait_ticks
    ret 
endp afterClean


proc music
    mov     al, 182         ; Prepare the speaker for the
        out     43h, al         ;  note.
        mov     ax, 4560       ; Frequency number (in decimal)
                                ;  for middle C.
        out     42h, al         ; Output low byte.
        mov     al, ah          ; Output high byte.
        out     42h, al 
        in      al, 61h         ; Turn on note (get value from
                                ;  port 61h).
        or      al, 00000011b   ; Set bits 1 and 0.
        out     61h, al         ; Send new value.
        mov     bx, 25          ; Pause for duration of note.
pause1:
        mov     cx, 65535
pause2:
        dec     cx
        jne     pause2
        dec     bx
        jne     pause1


        in      al, 61h         ; Turn off note (get value from
                                ;  port 61h).
        and     al, 11111100b   ; Reset bits 1 and 0.
        out     61h, al         ; Send new value.

        ret 
endp music


start:
    mov ax, @data
    mov ds, ax
; --------------------------
    mov bx, 0
; Your code here
s:
; Graphic mode
    mov ax, 13h
    int 10h
;printing string
    mov  dx, offset forstars 
    mov  ah, 9h 
    int  21h
;printing string
    mov  dx, offset instruction 
    mov  ah, 9h 
    int  21h
; first pic 
    mov dx, offset filename
    call startphoto
; קריאת תו ופעולה בהתאם
    mov ah, 0h
    int 16h 
    cmp al, 's'
    jne a1
    call music
    call clean
    je startrall
a1: 
    cmp al, 'e'
    jne s
    call music
    je exit1
startrall:  
;printing string
    mov  dx, offset adda 
    mov  ah, 9h 
    int  21h
;קריאת תו ופעולה בהתאם 
    mov ah, 0h
    int 16h 
    cmp al, 13
    jne f1
    call music
    je startgame
f1: 
    cmp al, 'e'
    jne startrall
    call music
    je exit1
startgame:
    call clean
    call afterClean
    call game
;קריאת תו ופעולה בהתאם
tav1:
    mov ah, 0h
    int 16h 
    cmp al, 13
    jne tav2 
    call music
    call clean 
    call afterClean
    je startgame    
;קריאת תו ופעולה בהתאם
tav2:
    cmp al, 'e'
    jne tav1
    call music
    je exit1
exit1:
    call clean

; --------------------------

exit:
    mov ax, 4c00h
    int 21h
END start

the first and second slot will always be the same picture, i cant find why the random can never be the same.




How to random position from UIButtons has created by storyboard?[swift Xcode]

I created 12 UIButtons by storyboard, in my program, these buttons represent cards,I want to random the buttons' position for shuffling the cards.please do me a favor, give a way or idea to achieve it.




samedi 23 juin 2018

Generate random char/digit

I`m trying to found fastest way to generate random digit/char array.

char *randomGet(int num) {
    srand(time(NULL));
    const char ab[37] = { "0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZ" };//Alphabet&Digit
    char *targ = new char[num];
    for (int i = 0; i < num; i++) {
        strcat(targ, ab[rand() % 38]);
    }
    return targ;
}

So far I've come up with this, but it does not work (argument of type char is incompatible with parameter of type const char *). Help me find the best solution to my problem. Ty.




How to limit the stepsize using python's scipy.stats.levy?

I am trying to model a Levy walk using scipy.stats.levy. It works fine except for the fact that there are a few steps which are VERY large and I would like to know if there is a proper way to limit the stepsize.

Here is the code I am using:

import numpy as np 
from scipy.stats import uniform
from scipy.stats import levy
import matplotlib.pyplot as plt

def levy_walk( n ):

    # uniformly distributed angles
    angle = uniform.rvs( size=(n,), loc=.0, scale=2.*np.pi )

    # levy distributed step length
    r = levy.rvs( size=n )

    # x and y coordinates (position added to previous coordinate --> cum. sum)
    x = np.cumsum( r * np.cos(angle) )
    y = np.cumsum( r * np.sin(angle) )

    return np.array( (x, y, r, angle) )

# number of steps to simulate
n = 500

# get levy walk (strictly speaking, it seems to be a flight)
foo = levy_walk( n )

# initialize figure
fig = plt.figure( figsize=(14,6) )

# plot 2D random walk with Levy stepsize
ax1 = fig.add_subplot( 1,2,1 )
ax1.plot( foo[0,:], foo[1,:] )
ax1.set_xlabel( 'x' )
ax1.set_ylabel( 'y' )
ax1.set_title( '2D Levy flight' )

# plot histogram
ax2 = fig.add_subplot( 1,2,2 )
num_bins = n/10
ax2.hist( foo[2,:], bins=n/10 )
ax2.set_yscale( 'log' )
ax2.set_xlabel( 'stepsize' )
ax2.set_title( 'histogram' )

plt.show()

And this is an example output figure where you can clearly see the occurrence of very few but VERY large steps:

2D Lévy flight (walk)

So, my question is what is the proper way to limit the step size ? (Using the scale option does not really help as it only scales everything down)




plot shuffled array numpy

I am writting a very simple script, one that plot a sin using jupyter notebook (python 3). when I put:

import numpy
import matplotlib.pyplot as plt
x=np.arange(0.0,5*np.pi,0.001)
y = np.sin(x)
plt.plot(x,y)

The plot is fine.

However if :

import numpy
import matplotlib.pyplot as plt
x=np.arange(0.0,5*np.pi,0.001)
np.random.shuffle(x)
y = np.sin(x)
plt.plot(x,y)

the image is enter image description here

I don't understand why shuffling the x BEFORE I ran sin does it.
thank you




Random Function

So, I am a beginner in Python and I wanted to try something out. I want to make a for loop with random strings in it. I want the names not to repeat themselves and the prices can occur twice (we were with 5 people and there were 2 drill-motor and 2 Dc-motors to give away). So, 4 people would get a price, 2 people get the drill-motors and 2 people get the DC-motors. How can I do this? Because when I run, the random.sample repeats itself every time it runs a part of the loop and some names and prices occur to often. Thus, I want the names to occur once and each price twice.

Thanks for your help.

This is the code:

import random

price=["You have won the drill-motor" , "You have won the DC motor"]

Names = ["Hilmi", "Joris", "Isa", "Dennis", "Jasper"]

for i in range (len(Names)-1): print(*random.sample(Names,1), *random.sample(price,1))




vendredi 22 juin 2018

Testing postgres "RANDOM()" in minitest

Introduction

I have a hierarchy parent-children in my RoR project and I wrote a new feature to our ruby on rails project, that shows two random children records from a parent.

class Article < ActiveRecord::Base
  has_many :reviews

  def to_json
    {
      ...
      reviews: reviews.n_random.as_json
      ...
    }
  end
end

and

class Review < ActiveRecord::Base
  belongs_to :article

  scope :n_random, ->(n=2) { order("RANDOM()").limit(n) }
end

Now, the problem that I have is even though the randomness works correctly, even in tests, I have problems with few tests that actually test this feature indirectly.

Let's say that I have an ArticlesControllerTest test suite, that contains a method

test 'show renders correct article' do
    # given
  params = { format: :json, id: 1 } 
  article = Article.find(params[:id])

    # when
  post :get, params
  response_article = JSON.parse(response.body, symbolize_names: true)


    #then
  assert_response 200
  assert_equal response_article, article.to_json
end

Problem

The last assert_equal fails, because for example:

  • response_article contains ids 1, 2
  • article.to_json contains ids 1, 3

Question

Is it possible to write some kind of a filter, that makes postgres's RANDOM() return always constant value? I know that I can use SELECT setseed(0.5); to set seed, so that next SELECT RANDOM(); returns the same value (although the next RANDOM() will change), but what I would like to achieve is to do something like setseed(0.5) before every possible select from active records.

I'll gladly take any other responses that will help me with this problem, because I know that RoR and Postgres are two different servers and I have no idea how to test this randomness from postgres's side.

inb4: I don't want to modify tests in a huge way.




Change the value of variables that occur 80% of the times in each row, R

In my data, I have 74 observations (rows) and 128 variables (columns), where each variable takes either 0 or 1 as value. In R, I am trying to write a code, where I can find in each row, the variables that has 1 as value and calculate 80% of the times 1 appears in each row. Pick those variables that has 80% of the times value as 1 and change the value from 1 to 0. I could write code, where I can calculate the 80% of times, 1 appears in each row, but I am not able to pick these variables in each row and change their value from 1 to 0.

data# data frame with 74 observations and 128 variables

row1 <- data[1,]

count1 <- length(which(data[1,] == 1)) # #number of 1 in row 1

print(count1)

perform <- 80/100*count1# 80% of count1

Any suggestions

Thank you

Priya




repeat random generation in parallel in c++, avoiding duplication over multiple runs

This is probably a really simple question but I'm pretty new to random number generation on c++ and want to make sure I'm getting it correct.

I have a stochastic function that I want to run in parallel, multiple times, so each parallel run of the function needs to be different from the other and different from previous runs, from my understanding, one way I could do this would be to have random_device as the seed for each. e.g.

for (int i= 0; i< runs; i++){
//do something
#pragma omp parallel for schedule(static)
for (int j = 0; j < std::size(iters); j++){
    std::mt19937 mrandThread(std::random_device{}());
    iters.at(j) = stochFunction(parameters, mrandThread);
}
//do something
}

However, this seems like it would be computationally expensive, as you would be initiating random_device many times, especially if the above loop is repeated a lot. Another problem would be that runs may be duplicated, as the random_device is just setting a seed, which may come up again? However, currently passing the engine from outside the loops e.g.

std::mt19937 mrandThread(std::random_device{}());
for (int i= 0; i< runs; i++){
//do something
#pragma omp parallel for schedule(static)
for (int j = 0; j < std::size(iters); j++){
    iters.at(j) = stochFunction(parameters, mrandThread);
}
//do something
}

means that each thread gives the same result, as they are just running duplicates of the mersenne twister from the point they were sent out in parallel? Another option I've seen is to use rand_r(), but could this again potentially have a problem similar to seed duplication, or does this act more like a branching off of the current random trajectory set outside the loop?

Any advice on how best to implement this would be much appreciated.




Discretization size and Recurrence period of numpy uniform

My queries are regarding the generation of the uniform random number generator using numpy.random.uniform on [0,1).

a) Does this implementation involve a uniform step-size, i.e. are the universe of possibilities {0,a,2a,...,Na} where (N+1)a = 1 and a is constant?

b) If the above is true, then what's the value of this step-size? I noticed that the value of numpy.nextafter(x,y) keeps on changing depending upon x. Hence my question regarding whether a uniform step-size was used to implement numpy.random.uniform.

c) If the step-size is not uniform, then what would be the best way to figure out the number of unique values that numpy.random.uniform(low=0, high=1) can take?

d) What's the recurrence period of numpy.random.uniform, i.e. after how many samplings will I see my original number again? For maximum efficiency, this should be equal to the number of unique values.

I tried looking up the source code at Github but didn't find anything directly interpretable there.




jeudi 21 juin 2018

Microsoft Access query to retrieve random transactions with seemingly impossible criteria

I was asked to assist with developing a report to retrieve a 25% sample of random transactions within a specific date range. I am not a programmer but I was able to devise the following fairly quickly:

SELECT TOP 25 PERCENT account.CID, account.ACCT, account.NAME, log.DATE, log.action_txt, log.field_nm, log.from_data, log.to_data, log.tran_id, log.init 
FROM account INNER JOIN log ON account.ACCT = log.ACCT
GROUP BY account.CID, account.ACCT, account.NAME, log.DATE, log.action_txt, log.field_nm, log.from_data, log.to_data, log.tran_id, log.init
HAVING (((log.DATE) Between #2/7/2018# And #6/15/2018#) AND ((log.action_txt)="mod" Or (log.action_txt)="del") AND ((log.init)="J1X" 
ORDER BY log.tran_dt

This returns 25% of the records within the date range. Each record row is unique but each account number potentially has multiple records on each day. In some cases the records have the same date and tran_id as well.

Upon further discussion with the requester, he actually wants to see all of the transactions for 25% of the accounts that have activity on each day within the date range. Thus if there were 100 accounts on 3/1/2018 with records in this table, he wants to see all of the transactions for 25 of those accounts; if there were 60 accounts on 3/2/2018 with records in this table, he wants to see all of the transactions for 15 of those accounts; and so on.

I was thinking that an Access module would work best in this scenario as I believe there are multiple parts to this. I figured that I need a function to loop through the date range and for each day: 1. Count the account numbers only one time 2. Return all of the transactions for 25% of the total accounts

But as I mentioned, I am not a programmer and I am exhausted from searching possible solutions for the many parts.




AVR Atmega128 random number generator from range

I'm building project for studies on ATmega128 with my friend and we have a problem with random number generator (from 0 to 5), because the function always show the same result. We can't add time.h, because AVR Studio didn't accept this.

Code below:

uint8_t randomNumber(uint8_t r){
r = rand()%5;
return r;
}

other try

uint8_t randomNumber(uint8_t min, uint8_t max){
uint8_t = result;
result = min + rand() % (max+1 - min);
return result;
}

Any ideas? Thanks, Sebastian




How can I find a subarray with arbitrary elements randomly?

I have an array with 100 elements. Array elements are a set of ones and zeros. For example, Array[100] = {0,0,1,0,1,0,1,1,1,0,0,0,0,0,1,1,0,1,0,0,1,0,0,0,1,1,....,1}

If we assume that variable needed has the value of 2, then the "find_gap_randomly" function selects 2 contiguous zero elements (A subarray with 2 zero elements means that there is a gap in my program).

Now, I am curious to know how I can write this program in a more readable code with or without using random library, preferably for OPNET network simulator.Do you have another suggestions for implementing the "find_gap_randomly" function in C ?

static void find_gap_randomly(int needed)
        {
FIN(find_rr_gap());

         int logic=0;
         int first_f=0;
         int s=1;

         for ( int i=1 ; i<=100 ; i++)
             {
                if ( array[i]==0)
                    {
                      if (logic==0)
                          {
                            first_f=i;
                            logic= logic+1;
                          }
                       else
                           {
                            logic= logic+1;
                           }

                       if (i==100)
                           {
                             if (logic >= needed-1)
                                 {
                                     ary_rr[s].first= first_f;
                                     ary_rr[s].last=i;
                                     ary_rr[101].first=ary_rr[101].first+1;
                                 }
                           }
                    }
                else
                    {
                      if (logic >= needed && logic!=0)
                          {
                                ary_rr[s].first= first_f;
                                ary_rr[s].last=i-1;
                                ary_rr[101].first=ary_rr[101].first+1;
                                s=s+1;
                          }
                      logic=0;
                      first_f=0;
                    }
             }

            return;
            FOUT;
        }




Is there a scope for numpy random seeds?

My question is related to What is the scope of a random seed in Python? . In the case of above question, it is clarified that there is a (hidden) global Random() instance in the module for random.

1) I would like to clarify, whether setting the random seed in one module will cause this to be the random seed in other modules and whether there are certain things to be aware of.

For instance: Given: moduleA.py, moduleB.py

moduleA.py:

import random 
import moduleB
random.seed(my_seed)
moduleB.randomfct()

moduleB.py:

import random 
def randomfct():
    #do_things_using_random

Does moduleB also use my_seed, or do I have to pass the seed to moduleB.py and set it again?

2) Does the order of setting the random seed / importing play any role? moduleA.py:

import random 
random.seed(my_seed)
import moduleB

3) Is this also the case for setting numpy random seeds, e.g. np.random.seed(42)?




R: replacing values in the randomly selected fractions of observations

I am relatively new to R and probably the solution to this problem is rather simple.

Let's imagine that i have nest dataset of bird two species (a and b) like this:

df
year nestid sp  egg chick
2013    a1  a   2   1
2013    a2  a   NA  1
2013    a3  a   NA  0
2013    a4  a   NA  1
2013    a5  a   NA  0
2013    b1  b   2   0
2013    b2  b   NA  1
2013    b3  b   NA  2
2013    b4  b   NA  1
2014    a1  a   NA  1
2014    a2  a   NA  1
2014    a3  a   1   1
2014    a4  a   NA  1
2014    a5  a   NA  1
2014    b1  b   NA  1
2014    b2  b   NA  2
2014    b3  b   NA  2
2014    b4  b   NA  1

I want to infer number of eggs for those 'NAs' from number of chicks. It makes sense to replace "NA" by 2 if there were "2" chicks as they lay 2 eggs max.

But i want to replace NAs by "2" for randomly selected 80% of nests with 1 chick and replace by "1" for remaining 20% of the nests with 1 chick for species "a" in year 2013. But this ratio would be 40% and 60% for clutch sizes of 2 and 1 respectively for species "a" in 2014.

I tried like this but could not work out how to code properly.

df%>% mutate(egg=ifelse(egg==0 & chick==2, 2, egg))

df%>% 
mutate(egg=ifelse(egg==0 & chick==1 & year==2013, sample_frac(.8)==2, egg))

Any help would be greatly appreciated!

Many thanks




sampling from discrete distribution without replacement where the probabilities change each draw

having a sequence S = (s1,s2,...sk) with probability weights for each sequence site P = (p1,p2,...pk) where the sum of P = 1 maximum length of S may be around 10^9 By Simulation a site k is picked and modified after each draw , as reason the pk also changes each run through.

Question 1: How would you suggest to draw site? Actually I implemented this logic which seems to be ok itself as going along literature see e.g. here:

    counter = 0
    random_number = draw_random()  #<= float in range 0,1
    while P_sum <  random_number
        P_sum += P[counter]
        counter++
    return counter

By testing the simulation I observed a strong bias which seems to rebuilt random generators distribution ( see_here ) Three different generators generate 3 different results... which is fairly ok but none of them is correct at all states Walkers and Knuth's methods with lookup table seem to be too time expensive for me as the lookup tables have to be recalculated each time.

Question 2 How can I reduce bias from randomness? Actual built in 3 different generators (only one used per simulation) which are uniform distributed in kindness to their chances. Knowing this is a heavy question when not knowing a line of simulation code

Question 3 Library for the thing ? As it's not to much code I don't have problem to write on my own, but is there a another library for it which may not BOOST? Asking as this question may be outdated... Not Boost as I don't want to built in a fourth random generator and use that large thing

Question 4 Faster alternative?

I know that this topic was answered may thousands of time before - but none of the answers satisfies me enough nor gave me a wise alternative e.g. here seems to have the same problem but I don't understand which heap is where built and why in addition it seems very complicated for such a "easy" thing

Thank you for your support!




mercredi 20 juin 2018

write a bat file with %xxx% content with by using a bat file

I want to use my batch file which I converted to an exe file to create another batch file that has the content %key% in it. When I try to execute the exe file, the %key% is ignored/deleted. same happens when using %random%.... how can I prevent my 1st batch file with which i create the 2nd one to delete %xxx% expressions? I want the the 1st batch just ignores the %xxx% expression and just copy it into the 2nd bat file without executing anything




VBA MSWord Checklist with shuffled text

I'm currently working on an MSWORD Checklist which contains a table with three columns, 1st describes the check, 2nd has 18 checkboxes and acts as the initial check, 3rd has 8 checkboxes and act as the crosscheck.

I'm looking to shuffle the checkboxes in column 3 among the different listed values in column 1

For example: Table 2: The 3 checkboxes should be shuffled randomly across rows 3-9

I currently have a piece of code which somewhat works. It can shuffle text in a table but only using column 1, instead of column 3. It also doesn't recognize headers from the range its actually supposed to use, which are the rows with the values.


Sub Shuffleboxes()


Dim numberOfRows As Integer Dim currentRowText As String Dim I As Integer Dim doc As Document


Set doc = ActiveDocument


'Find the number of rows in the first table of the document numberOfRows = doc.Tables(1).Rows.Count 'Initialise (seed) the random number generator Randomize 'For each row in the table For I = 1 To numberOfRows 'Find a new row number (any row in the table) newRow = Int(numberOfRows * Rnd + 1) 'Unless we're not moving to a new row If newRow <> I Then 'Get the current row text currentRowText = CleanUp(doc.Tables(1).Cell(I, 1).Range.Text) 'Overwrite the current row text with the new row text doc.Tables(1).Cell(I, 1).Range.Text = CleanUp(doc.Tables(1).Cell(newRow, 1).Range.Text) 'Put the current row text into the new row doc.Tables(1).Cell(newRow, 1).Range.Text = currentRowText End If Next I


End Sub

I've added a screen shot of my word document in order to illustrate everything better.

CHECKLIST PREVIEW

Thanks in advance for your help.

much appreciated.

Florian




JMeter: After installing Blazemeter plugin for Random CSV, Jmeter is not allowing to right click on "Test Plan"

I just installed bzm plugin for Random CSV but now Jmeter is not allowing to right click on "Test Plan".

Even, "edit" menu looks diabled, have restrated JMeter multile times, still no solution. Please help. Also, this is not the first time I have faced this issue after adding and installing plugins.

enter image description here enter image description here




Store a random value in a for loop in arduino ide

My project is a LED "wheel of fortune", when the button is not pressed the LEDs light up randomly but when I press the button the LEDs are supposed to light up in a circle and then stop at a random point. I'm using a altered example code for arrays from the arduino sites and almost got it working.

Whats missing is: hold the last lit up LED (the one where it stops randomly after a few times going round in circles). I know I should store the last used LED and then tell it to delay for a bit. I got it working in the else-loop but don't know how to put that same code in the for-loop.

Code follows here. I hope I made the question clear, if not please ask!

/*
Arrays

Demonstrates the use of an array to hold pin numbers in order to iterate over
the pins in a sequence. Lights multiple LEDs in sequence, then in reverse.

Unlike the For Loop tutorial, where the pins have to be contiguous, here the
pins can be in any random order.

The circuit:
- LEDs from pins 2 through 7 to ground

created 2006
by David A. Mellis
modified 30 Aug 2011
by Tom Igoe

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/Array

*/
int taster = 8;
int tasterstatus = 0;
int timer = 100;           // The higher the number, the slower the timing.
int ledPins[] = {
    // 2, 7, 4, 6, 5, 3
    2,3,4,5,6
};       // an array of pin numbers to which LEDs are attached
int pinCount = 5;           // the number of pins (i.e. the length of the array)



void setup() {
    // the array elements are numbered from 0 to (pinCount - 1).
    // use a for loop to initialize each pin as an output:
    pinMode(taster, INPUT);
    for (int thisPin = 0; thisPin < pinCount; thisPin++) {
        pinMode(ledPins[thisPin], OUTPUT);
    }
}

void loop()
{
    tasterstatus = digitalRead(taster);
    if (tasterstatus == HIGH)
    {
        for (int kreisrund = 0; kreisrund < 5; kreisrund++)
        {
            // loop from the lowest pin to the highest:
            for (int thisPin = 0; thisPin < pinCount; thisPin++)
            {
                // turn the pin on:
                digitalWrite(ledPins[thisPin], HIGH);
                delay(timer / 2);
                // turn the pin off:
                digitalWrite(ledPins[thisPin], LOW);
            }
        }

        for (int kreisrund = 0; kreisrund < 1; kreisrund++)
        {
            // loop from the lowest pin to the highest:
            for (int thisPin = 0; thisPin < pinCount; thisPin++)
            {
                // turn the pin on:
                digitalWrite(ledPins[thisPin], HIGH);
                delay(timer * 3);
                // turn the pin off:
                digitalWrite(ledPins[thisPin], LOW);
            }

            // WHERE TO PUT THE INDEX?! 
            for (int thisPin = 0; thisPin < random(0, 5); thisPin++)
            {
                // turn the pin on:
                digitalWrite(ledPins[thisPin], HIGH);
                delay(timer * 5);
                // turn the pin off:
                digitalWrite(ledPins[thisPin], LOW);
            }
        }
    }
    else
    {
        int index;
        index = random(5);

        digitalWrite(ledPins[index], HIGH);
        delay(timer);
        digitalWrite(ledPins[index], LOW);

        /*// loop from the lowest pin to the highest:
        //for (int thisPin = 0; thisPin < pinCount; thisPin++) {
        // turn the pin on:
        digitalWrite(ledPins[random(0,5)], HIGH);
        delay(timer/2);
        // turn the pin off:
        digitalWrite(ledPins[random(0,5)], LOW);
        */
    }
}




mardi 19 juin 2018

MySQL lookup based on round(1 + rand() * x) produces NULL and multiple results

I'm trying to select first names from a lookup table at random in MySQL to build a test dataset. I have a table with 200 first names, genders and a row id going from 1 to 200. Something like this:

id   firstname   gender
1    Aaron       m
2    Adam        m
3    Alan        m
etc...

I'm selecting from this table using a random generator with the following query:

SELECT id, firstname FROM firstname WHERE id = round(1 + (rand() * 199));

I am expecting the random number to tally up with exactly one id from the lookup table, thus producing a single results like

id   firstname
43   Jason

Running the code again and again instead gives me a selection of

  • single rows (as above)
  • or multiple rows like

id firstname 29 Ethan 147 Jean

  • or no results (just NULL in both fields).

If I run the random generator on its own, it will always generate a number between 1 and 200. As you can see below, the id field is INT, and the query behaves the same way if I cast the result as SIGNED. I have also tried to use FLOOR instead of ROUND, just to see if that worked any differently - alas, no.

Can anyone tell my why the anomaly? What am I missing?

Here is some code to create the first 20 rows of the original table for testing purposes:

-- First Name --
drop table if exists firstname;

  CREATE TABLE firstname (
  id INT NOT NULL,
  firstname VARCHAR(20) NOT NULL,
  gender VARCHAR(1) NOT NULL,
  PRIMARY KEY (id),
  UNIQUE (firstname)
  );

  INSERT INTO firstname
  (id,firstname,gender)
  VALUES
  (1,"Aaron","m"),
(2,"Adam","m"),
(3,"Alan","m"),
(4,"Albert","m"),
(5,"Alexander","m"),
(6,"Andrew","m"),
(7,"Anthony","m"),
(8,"Arthur","m"),
(9,"Austin","m"),
(10,"Benjamin","m"),
(11,"Billy","m"),
(12,"Bobby","m"),
(13,"Brandon","m"),
(14,"Brian","m"),
(15,"Bruce","m"),
(16,"Bryan","m"),
(17,"Carl","m"),
(18,"Charles","m"),
(19,"Christian","m"),
(20,"Christopher","m");




Random Numbers without ascending and descending orders [duplicate]

This question already has an answer here:

I have a problem with a method that generates numbers that do not repeat. Everything goes fine, but I would never want to get a result like: 1,2,3,4 or 4,3,2,1 . The idea is not to receive the numbers in ascending order or in descending order.

Below is the method implemented if someone can help me. Thank you!

public static List<int> GenerateNumbers(int mn, int mx)
{
    List<int> source = new List<int>();
    for (int i = mn; i <= mx; i++)
        source.Add(i);
    List<int> randomNumbers = new List<int>();
    while (source.Count != 0)
    {
        int randomIndex = UnityEngine.Random.Range(0, source.Count - 1);
        randomNumbers.Add(source[randomIndex]);
        source.RemoveAt(randomIndex);
    }
    return randomNumbers;
}




Generating random vectors C++

I am working on a programme which takes an initial vector as an inpit.This vector is vector of size 20.The programme then generates 10 random vectors from this vector.For this purpose I choose 2 ransom indices in the initial vector and swap them with each other to generate a new vector.This is done to generate all the 10 new vectors. The 10 new vectors generated should be stored in the following 2 dimensional vector

vector<vector<int>> allparents

I have been able to generate 2 random indice numbers using the srand() function and then swap the elements at these indices for the initial vector.However I am unable to generate 10 of such random parents and then store them in the allparents 2D vector.My code is as follows :

#include<vector>
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<ctime>
using namespace std;
int main () {
srand(time(NULL));
int i1=(rand()%19+1);
int i2=(rand()%19+1);
cout<<i1<<endl;
cout<<i2<<endl; 
vector<int> initial= {71,127,428,475,164,253,229,395,92,189,41,110,443,490,278,305,28,58,371,560};
vector<vector<int>> allparents[10][20];
for(int r=0;r<10;r++){
for(int c=0;c<20;c++){
swap(initial[i1],initial[i2]);
allparents[r][c]=myvector[c];
cout << "myvector contains:";
cout<<allparents[r][c]<" "<<endl;
}}
return 0;
}

As I am new to vectors,I would request your help in this programme.Thanks.




Body does not spawn randomly despite code previously working

In my game objects are meant to spawn randomly along the y-axis of the camera's view, and come across the screen in an infinite runner style. It took me a while to learn to do this and upon running it worked. Later I made a new method (Respawn) and ever since the body always spawns in the exact same place even though I haven't changed ANY code with the random, any idea why? I've obviously changed something without realising but I have no idea what I did, any help would be greatly appreciated.

(Pigeoncam is my OrthographicCamera) (Only relevant code is below)

Code: `

Vector3 cameraPosition = pigeoncam.position;

float effectiveViewportHeight = pigeoncam.viewportHeight * pigeoncam.zoom;

float minWorldY = cameraPosition.y - effectiveViewportHeight/2f;
float maxWorldY = cameraPosition.x + effectiveViewportHeight/2f;

float randomYPos = MathUtils.random(minWorldY, maxWorldY);


public ObstacleOne(GameScreen screen){
    this.world = screen.getWorld();
    defineObstacleOne();
}

public void update() {

  b2body.setLinearVelocity(-4f, 0);
  Respawn();

}

public void Respawn(){
    if(b2body.getPosition().x <= 10 / RadiationPigeon.PPM){
        b2body.setTransform(6.5f, randomYPos, 0);
    }
}
public void defineObstacleOne(){
    BodyDef bdef = new BodyDef();
    Vector2 set = bdef.position.set(6.5f, randomYPos);

At first, I thought I messed something up when I added the Respawn() method but even when I get rid of it the body won't stop spawning at the same place every time. This is where it respawns (It's the blue rectangle)




lundi 18 juin 2018

Is it possible to get the sum of these random generated doubles in an array?

Is there a way to get the average of these randomly populated doubles in this array? I want to make an array that is filled with randomly generated doubles based on the user inputs length.

import java.util.Scanner; 
    import java.util.Random;
    import java.util.Arrays;
        public class GarageTest {

        public static void main(String[] args){

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter a number");
        //create an array with the size entered by the user
        double[] array = new double[scanner.nextInt()];
        //populate the array with doubles
        for(int i =0; i < array.length; i++) {
            Random rand = new Random();
            array[i] = rand.nextDouble();
        }
        System.out.println(Arrays.toString(array));
        }

        }




How do I generate random doubles in an Array?

My goal is to ask the user for an array length and generate a list of random doubles to fill that array out. I don't understand how to get Math.random into my array. I started with a different approach and scrapped it. Why does double random = Math.random() * array; not import a random generator into my array?

import java.util.Scanner;
import java.util.Arrays;
import java.util.Random;

public class Average
{
  public static void main(String[] args)
  {
    /*Scanner in = new Scanner (System.in);

    System.out.println("Please enter your array size: ");
    int size = in.nextInt();
    int[] awnser = new int[size]; */
    Scanner scanner = new Scanner(System.in);

    System.out.println("Enter a number");

    double[] array = new double[scanner.nextDdouble()];
    double random = Math.random() * array;
    System.out.println(array.length);

    }
  }




Unexpected behavior of set.seed() in conjunction with .Random.seed in R?

I stumbled across this unexpected behavior (to me), which is likely due to my misuse and/or misunderstanding of .Random.seed.

set.seed(1234)  # This is for reproducibility
s1 <- .Random.seed
set.seed(s1)
s2 <- .Random.seed
runif(1)
s3 <- .Random.seed
set.seed(s3)
s4 <- .Random.seed
all(s2==s4)  # TRUE

The part I don't understand is the last line. How can the seed set have "returned" to s2, that is, to the set before runif(1) was called?

I understand that .Random.seed saves the seed set for the uniform random-number generator, but it was my understanding that I could also use it as an input for the set.seed() function.

I would like to store a bunch of such seed sets for later use. A workaround is to store integers instead (for instance 1234, 1235, etc...) but I somehow liked the idea to let the RNG decide what the next sate should be.




Sampling from multivariate customised cumulative distribution function in Matlab

Consider a 5-variate cumulative distribution function (cdf) which I call F.

I want to sample random 5x1 vectors from this cdf in Matlab. F is not a cdf that has been already implemented in Matlab (such as normal, t-student, etc.). Specifically, it is defined as

enter image description here

I have read several question/answers in this and other forums on how to sample from customised probability distribution functions in Matlab. However,

1) Most of them are for univariate cdf, e.g. here. The idea is to apply inverse transform sampling. My problem is a bit more complicated because I would need to "invert"a 5-variate function.

2) Another option could be to use slicesample as suggested here but I don't know how to write the analytical expression of the probability density function in my case.

3) Here's another idea but specific for the bivariate case.

Could you kindly help me to understand how I can proceed?




Java: How do I set the nonce when using DRBG SecureRandom?

Java 9 introduced a new SecureRandom called DRBG. I want to use it to deterministically generate random numbers. The problem is that it uses a nonce internally which it always changes, so I don't get the same numbers for the same seeds. It does have an option internally to set that nonce, but I can't find any public methods that can accomplish that. How can I change that nonce?




java- how to generate a 6 digit random hexadecimal value

I have a scenario in a Android app, where a random hexadecimal value has to be generated with 6 digits. (The range of values can be hexadecimal or integer values).

What is the most efficient way to do this? Do I have to generate a random decimal number, and then convert it to hexadecimal? Or can a value be directly generated?




C# Generate unique secure random strings gradually

I want to generate unique and secure strings randomly and I want to do it over time. I want to choose the shortest possible length for my use (Big enough so that random tries fail with good chance). I Also want the process to be fast. Using the following code and testing it for uniqueness, duplicates occur sooner than I expected. I'm not sure if there is any problem. P.S.: Is it secure to use a pool for generated numbers? P.P.S: I prefer not to add '-' and '_' to the alphabet. Is it worth removing it?

string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
string Random(int length,string alphabet)
    {
        StringBuilder result = new StringBuilder();
        using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
        {
            for (int i = 0; i < lenght; i++)
            {
                byte[] buffer = new byte[sizeof(uint)];
                rng.GetBytes(buffer);
                uint num = BitConverter.ToUInt32(buffer, 0);
                result.Append(alphabet[(int)(num % (uint)alphabet.Length)]);
            }
        }

        return result.ToString();
    }




dimanche 17 juin 2018

array of Weighted random numbers with constant sum

Is there any well-known algorithm which can generate an array of weighted random numbers having the same constant sum?

This problem can be stated in another way: Say, I have a total value of 20. Which should be distributed into 3 parts each of them has a weight of 2,4,3 respectively. So, I need 3 random numbers which will have a sum of 20 but the distribution will follow the weight.




How to insert value (random value from List) to sqlite?

I have int values into List<Integer>

I created new random - Random rand = new Random();

And i can get my random value from this

int random_one = givenList.get(rand.nextInt(givenList.size()));

But i need to insert random_one to the DataBase

As result, i was converted my random_one to String

String random = Integer.toString(random_one);

But it doesn't work again!

I left my code of my MainActivity Class and my DataBase in this order below

public class MainActivity extends AppCompatActivity {

    DataBaseHelper myDb;
    EditText name_edittext,age_edittext,weight_edittext,height_edittext;
    Spinner gender_spinner,trauma_spinner,illnesses_spinner;
    Button save;
    String name;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        /*DataBase*/
        myDb = new DataBaseHelper(this);
        /*Spinners*/
        gender_spinner = (Spinner) findViewById(R.id.spinner_gender);
        trauma_spinner = (Spinner) findViewById(R.id.spinner_trauma);
        illnesses_spinner = (Spinner) findViewById(R.id.spinner_illnesses);

        String [] gender={"Male","Female"};
        ArrayAdapter<String> gender_adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,gender);
        gender_spinner.setAdapter(gender_adapter);
        String [] trauma={"Back","Hand","Leg","None"};
        ArrayAdapter<String> trauma_adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,trauma);
        trauma_spinner.setAdapter(trauma_adapter);
        String [] illnesses={"Heart problems","Scoliosis","Others","None"};
        ArrayAdapter<String> illnesses_adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,illnesses);
        illnesses_spinner.setAdapter(illnesses_adapter);
        /*EditTexts*/
        name_edittext = (EditText) findViewById(R.id.name);
        age_edittext = (EditText) findViewById(R.id.age);
        weight_edittext = (EditText) findViewById(R.id.weight);
        height_edittext = (EditText) findViewById(R.id.height);
        /*Button*/
        save = (Button) findViewById(R.id.save_button);
        /*Save*/
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ClickMe();
            }
        });
    }

    private void ClickMe(){
        String name = name_edittext.getText().toString();
        String age = age_edittext.getText().toString();
        String weight = weight_edittext.getText().toString();
        String height = weight_edittext.getText().toString();
        String gender = gender_spinner.getSelectedItem().toString();
        String trauma = trauma_spinner.getSelectedItem().toString();
        String illnesses = illnesses_spinner.getSelectedItem().toString();
        //Random
        List<Integer> givenList = Arrays.asList(1, 2, 3);
        Random rand = new Random();
        int random_one = givenList.get(rand.nextInt(givenList.size()));
        String random = Integer.toString(random_one);

        Boolean result = myDb.insertData(name,age,weight,height,gender,trauma,illnesses,random);
        if (result == true){
            Toast.makeText(this,"Data is added successfully",Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(this,"Data is not added",Toast.LENGTH_SHORT).show();
        }

        Intent i = new Intent(this,MenuActivity.class);
        startActivity(i);
    }
}

&&&

public class DataBaseHelper extends SQLiteOpenHelper{
    public static final String DATABASE_NAME = "Schedule.dp";
    public static final String TABLE_NAME = "Schedule_table";
    /*Col*/
    public static final String COL_1 = "ID";
    public static final String COL_2 = "NAME";
    public static final String COL_3 = "AGE";
    public static final String COL_4 = "WEIGHT";
    public static final String COL_5 = "HEIGHT";
    public static final String COL_6 = "GENDER";
    public static final String COL_7 = "TRAUMA";
    public static final String COL_8 = "ILLNESSES";
    public static final String COL_9 = "RANDOM";

    public DataBaseHelper(Context context) {
        super(context,DATABASE_NAME,null,1);
    }

    @Override
    public void onCreate(SQLiteDatabase db){
        db.execSQL("CREATE TABLE "+TABLE_NAME+" (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,AGE INTEGER,WEIGHT INTEGER,HEIGHT INTEGER,GENDER TEXT,TRAUMA TEXT,ILLNESSES TEXT,RANDOM TEXT)");
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
        db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
    }

    public boolean updataData(String id,String name,String age,String weight,String height,String gender,String trauma,String illnesses,String random){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_2,name);
        contentValues.put(COL_3,age);
        contentValues.put(COL_4,weight);
        contentValues.put(COL_5,height);
        contentValues.put(COL_6,gender);
        contentValues.put(COL_7,trauma);
        contentValues.put(COL_8,illnesses);
        contentValues.put(COL_9,random);
        int result = db.update(TABLE_NAME,contentValues,"ID =?",new String[]{id});
        if (result>0){
            return true;
        }else{
            return false;
        }

    }
    public boolean insertData(String name,String age,String weight,String height,String gender,String trauma,String illnesses,String random){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_2,name);
        contentValues.put(COL_3,age);
        contentValues.put(COL_4,weight);
        contentValues.put(COL_5,height);
        contentValues.put(COL_6,gender);
        contentValues.put(COL_7,trauma);
        contentValues.put(COL_8,illnesses);
        contentValues.put(COL_9,random);
        long result = db.insert(TABLE_NAME,null,contentValues);
        db.close();
        if (result==-1){
            return false;
        }else{
            return true;
        }

    }
    public Cursor getAllData(){
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor res = db.rawQuery("Select * from "+ TABLE_NAME,null);
        return res;
    }
    public void deleteAll(){
        SQLiteDatabase db = this.getWritableDatabase();
        db.execSQL("delete from "+ TABLE_NAME);
        db.close();
    }
}