mardi 31 juillet 2018

java.lang.IllegalArgumentException: bound must be positive

Based on the mentioned range value (for eg: range value is 3 - 50)I have a requirement to generate random range values For instance i have a range value 3-50.

So my intention is to pick a random range in between 3-50 it may be any value like 4-48, 10-30 or vice versa.

Code Iam using

 int firstRangeNo = 0;
int secondRangeNo = 0;

String rangeValues = "1-100"
String[] ranges = rangeValues.split("_");
int minRange = Integer.parseInt(ranges[0]);
int maxRange = Integer.parseInt(ranges[1]);
// Generate random range values based on the minimum and maximum values 
do {
    firstRangeNo = random.nextInt((maxRange - minRange) + 1) + minRange;
    secondRangeNo = random.nextInt((maxRange - minRange) + 1) + minRange;
} while (firstRangeNo > secondRangeNo || firstRangeNo == secondRangeNo);

while executing this code randomly am getting below message

java.lang.IllegalArgumentException: bound must be positive
    at java.util.Random.nextInt(Random.java:388)    




How does the function add_disk_randomness work?

I am trying to understand the add_disk_randomness function from the linux kernel. I read a few papers, but they don't describe it very well. This code is from /drivers/char/random.c:

add_timer_randomness(disk->random, 0x100 + disk_devt(disk));

disk_devt(disk) holds the variable disk->devt. I understand it as a unique block device number. But what are the major and minor device number?

Then the block device number and the hex 0x100 are added together.

Then we collect also the time value disk->random. Is this the seek time for each block?

These two values will be passed to the function add_timer_randomness. It would be nice to get an example with values.




How to select a random row from a Pervasive PSQL table

In Pervasive PSQL (specifically), using a sql select statement, how can you select a random row from a table that has no numeric IDs?




Generate random point positons on a torus

I'm working on a code to simulate propagation of particles on a torus surface. Initially, particles are gather on a "local" space, as shown on the following pic :

Initial particles on torus

Blue points are initial particles. The problem is, when I zoom in, particles don't seem to be spread randomly :

Zoom in

First, I see they form like raws. Moreover, I'm working with N = 5 particles, but there seems to be 25 particles here (5 raws of 5). I suppose it comes from meshgrid() since 25 = 5^2, but I don't really understand how this function works to be honest.

Here is my code :

Creating the red torus :

angle = np.linspace(0, 2*np.pi, 32)
theta, phi = np.meshgrid(angle, angle)
X = (R + r * np.cos(phi)) * np.cos(theta)
Y = (R + r * np.cos(phi)) * np.sin(theta)  
Z = r * np.sin(phi)

Placing initial points :

thetaInit = ((np.random.rand(N)-0.5)*np.pi/16)
phiInit = ((np.random.rand(N)-0.5)*np.pi/32)
theta2, phi2 = np.meshgrid(phiInit, thetaInit)
Xinit = (R + r * np.cos(phi2)) * np.cos(theta2)
Yinit = (R + r * np.cos(phi2)) * np.sin(theta2) 
Zinit = r *  np.sin(phi2)

Where N is the number of particles, and r, R are respectively minor and major radius of the torus.




How to make array of 30 different unique random numbers?

I want to use arc4random to generate array of 30 different numbers, so that there is no repeating in it. How can I do it?




Python- If statements with random numbers not working

I'm very new to programming and I'm trying to write a program in python 3.6 that generates a random number as an "answer" and then the computer has to guess that answer for x number of questions. To keep track of how many questions the computer guesses right, I created a variable called 'right' and if the computer's answer equals the guess, then add one to that variable. However, it does it everytime even if it's wrong. Sorry if this seems stupid, but thank you for your help

import random
def total(x, t):
        for i in range(t):
                cor = 0
                gue = 0
                n = 0
                right = 0
                def ans():
                         cor = random.randint(1,4)
                         print(cor, 'answer')
                def guess():
                         gue = random.randint(1,4)
                         print(gue, 'guess')
                while n <= x:
                         ans()
                         guess()
                         if cor == gue:
                                 right += 1
                         n += 1 
                print(right, n)




Rotating Proxy Use Using Random String Selection

I'm wondering if it would be possible to randomize proxy usage using the code below. All of the proxies I plan to use have the same port, same login, but of course different IPs. How can I then test this to ensure functionality?

My other question is, how can I use this inside another main program I'm working with? I need a file named RandomIP.java. Do I need to link these? Or can I set this up inside my existing .java project? I'm not too familiar with Java yet, but I'm getting there!

Here's the code I'm trying to work with:

public class RandomIP {

public static void main (String [] args) {

    String [] proxyIP = {"123", "213", "314", "415"};
    Random random = new Random();

    int select = random.nextInt(proxyIP.length);

    System.out.println("Proxy selected: " + proxyIP[select]);
}

Of course in my main project, I will be using the proxy which requires an IP entry. But can I replace that IP with the random if the program loops? So it should use a different proxy each time?




Java, random operator; call the same method into the method

I am trying to learn Java. I have tried to solve a little problem. at this point I dont know what to try anymore. I want to generate 2 random numbers and 2 random operator (+/-). If the result of these is between 0-20 print something, otherwise start over again until the result is in the range. I am getting an error when I recall the method: randomQuestion(); Thanks in advance!

private int randomQuestion(){

    static Random random = new Random();

    //generate 2 random numbers 
    int number = random.nextInt(15)+1;
    int number2 = random.nextInt(15)+1;
    //initiate result 
    int res = 0;
    //operator
    String operator =  randomOperator();

    //if operator is "+" do sum
    //otherwise do subtraction
    if (operator.equals("+")) {
        res = num1+num2;
        return res;
    }
    //if(operator.equals("-")) {
    else {
        res = num1-num2;
        return res;
    }

}

private void checkResult() {
    int res = randomQuestion();
    //if the result is between 0 and 20 (inclusive)
            if (res > 0 && res <= 20) {
                System.out.println(res + " is between 0-20"); 
            }
            else {
                //start over again with new numbers
                randomQuestion();
            }




Sample row of dataframe R until reach value

I try to sample randomly rows from a dataframe until to reach a value. and the number of row can differ depending of the values ramdomly selected. I try with the sample function but i dont know how to place condiction and how to have a non fixe length for row selected

Thks




How can i use ' ++ i ' inside this situation?

I want to draw a random name for an event where users can win items specified by their ID (1,2,3 etc.). The random name part is ok by now but how can i display the result like: The ID : 1 winner is: 'the random name' The ID : 2 winner is: 'the random name' etc... till ID : 27

static void Main(string[] args)
    {
        string[] Names = { "Erik", "Levente", "Noel", "Áron", "Krisztián", "Kristóf", "Bence", "Roland", "Máté", "László", "Bálint" ,
        "Regina", "Brigitta", "Gréta", "Hédi", "Hanna", "Boglárka", "Jázmin", "Réka", "Alexandra", "Rebeka", "Lili", "Luca", "Zsófi"};



        List<string> alreadyUsed = new List<string>();
        Random r = new Random();
        while (alreadyUsed.Count < Names.Length)
        {
            int index = r.Next(0, Names.Length);
            if (!alreadyUsed.Contains(Names[index]))
            {
             alreadyUsed.Add(Names[index]);

             Console.WriteLine("The ID : 1  winner is:  " + Names[index]);


            }
        }


        Console.ReadKey(true);
    }




How do you save the value of a randomly generated number for recalling in a different function? [duplicate]

This question already has an answer here:

How do you save the output of a random number generator function to be recalled in a different function?

For example, in the code below, I would be using the function randNum() to roll the dice and return the value of w to the saveDiceNumber() function as a variable.

Then I would save the first value received from the randNum() function into the new variable x located in the saveDiceNumber() function. Then I would like to repeat the process for variables y and z, without losing the newly created value of x.

So in essence, I would like to create a single function that uses the same random number generator to create 3 different variables and then recall the value of those variables without having to re-generate/re-roll random numbers.


The random number generator function:

function randNum(){
    var w = Math.floor(Math.random()*Math.floor(6)); 
    return w;
}

Function where RNG output should be saved:

function saveDiceNumber(){
    var w = randNum(); //roll the dice

    var x = w; //first output of w
    var y = w; //second output of w
    var z = w; //third output of w
}




Python, random based code [on hold]

While writing the code encounter some problem, so I'm here again. Hope someone assists me a little. My problem right now, is that I want to buttons that show Chinese characters to shuffle or change places at random when button with pinyin (text) is pressed. I don't really need work done for me, mainly I am looking for suggestions and points for me.

#========== Imports ===========#

from tkinter import *
import random

#========== Parameters ==========#

CN = Tk()
CN.title("Chinese Test")
CNW = ["ài","bā","bàba","bēizi","Běijīng","běn","búkèqi","bù","cài","chá","chī","chūzūchē"]
CNI = ["爱","八","爸爸","杯子","北京","本","不客气","不","菜","茶","吃","出租车",
       "打电话","大","的","点","电脑","电视","电影","东西","都","读","对不起",
       "多","多少","儿子","二","饭店","飞机","分钟","高兴","个","工作","汉语",
       "好","号","喝","和","很","后面","回","会","几","家","叫","今天"]

#=========== Functions ==========#

def ButRandom():
    B0['text'] = random.choice(CNW)
    if (B0['text']=="ài"):
        B1['text'] = "爱"
        B2['text'] = random.choice(CNI)
        B3['text'] = random.choice(CNI)
        B4['text'] = random.choice(CNI)
    elif (B0['text']=="bā"):
        B1['text'] = "八"
        B2['text'] = random.choice(CNI)
        B3['text'] = random.choice(CNI)
        B4['text'] = random.choice(CNI)
    elif (B0['text']=="bàba"):
        B1['text'] = "爸爸"
        B2['text'] = random.choice(CNI)
        B3['text'] = random.choice(CNI)
        B4['text'] = random.choice(CNI)
    elif (B0['text']=="bēizi"):
        B1['text'] = "杯子"
        B2['text'] = random.choice(CNI)
        B3['text'] = random.choice(CNI)
        B4['text'] = random.choice(CNI)

# Test parameters

def ButCheck():
    B0['text'] = "Correct. Again?"
def ButCheck1():
    B0['text'] = "Incorrect"
def ButCheck2():
    B0['text'] = "Incorrect"
def ButCheck3():
    B0['text'] = "Incorrect"

#=========== Buttons ==========#

B0 = Button(CN, text = "Click to start", command = ButRandom, bd = 3)
B0.grid(row = 0, column = 1)

B1 = Button(CN, text = 1, command = ButCheck, bd = 3, width = 3, height = 2)
B1.grid(row = 2, column = 0)
B2 = Button(CN, text = 2, command = ButCheck1, bd = 3, width = 3, height = 2)
B2.grid(row = 2, column = 1)
B3 = Button(CN, text = 3, command = ButCheck2, bd = 3, width = 3, height = 2)
B3.grid(row = 2, column = 2)
B4 = Button(CN, text = 4, command = ButCheck3, bd = 3, width = 3, height = 2)
B4.grid(row = 2, column = 3)

#========== Pack ==========#

CN.mainloop(  )

I'm lack in basic knowledge, so it a little hard to me to find my possible mistake or optimized code.




In this situation how can i display the results without duplicatin ?:)

Describe it on a baby level im so beginner...

static void Main(string[] args)
{
    string[] Names = { "Erik", "Levente", "Noel", "Áron", "Krisztián", "Kristóf", "Bence", "Roland", "Máté", "László", "Bálint" ,
    "Regina", "Brigitta", "Gréta", "Hédi", "Hanna", "Boglárka", "Jázmin", "Réka", "Alexandra", "Rebeka", "Lili", "Luca", "Zsófi"};          

    List<string> alreadyUsed = new List<string>();
    Random r = new Random();
    while (alreadyUsed.Count < Names.Length)
    {
        int index = r.Next(0, Names.Length);
        if (!alreadyUsed.Contains(Names[index]))
            alreadyUsed.Add(Names[index]);
        Console.WriteLine("The 1st Winner is:  " + Names[r.Next(0, Names.Length - 1)]);
    }

    Console.ReadKey(true);
}




Selcting Random queries from foreign table

Am trying to select specific number of Random questions from the table

Something like 3 random questions from questions table which are tagged as group_1 and two from group_3

This is my Sql command

SELECT
    questions.qid,
    tags.tag
FROM
    tag_dir tag_dir
JOIN questions ON questions.qid = tag_dir.qid
JOIN tags ON tags.id = tag_dir.tag_id
WHERE tags.id having 1 and 2
LIMIT 0,10

But i don't know how to get specific number of Random results

Here is my table structure




PRNG namespace Python

x = 0
a = 81
c = 337
m = 1000
def rand():
    global x
    x = (a * x + c) % m
    return x
def reset(mult, inc, mod):
    global x, a, c, m
    x = 0
    a = mult
    c = inc
    m = mod 

def roll(pup):
    newl = []
    for i in range(10):
        newl.append(rand() % pup + 1 )
    return newl

print(roll(6))

An outline of this code was given to me in my textbook but I do not understand how the rand function gives me a sequence of random numbers. Specifically, the first 3 numbers are

[2, 5, 2]

however, when I manually followed the code with pen and paper, every time there is a call to rand(), it should always be giving me 2 since

x = (a * x + c) % 6 + 1

which is essentially

x = (0 + 337) % 6 + 1

I even tried keeping the value of x to the last appended value of roll() so for instance, after the first iteration, rand() gives two, and so the next call to rand() is

x = (81 * 2 + 337) % 6 + 1

which still gives 2. What am I missing?




Random name picker without duplication?

Im just creating the most simple name picker from a specified list. How should i modify it to dont duplicate the already "picked" names?

static void Main(string[] args) {

        string[] Names = { "Erik", "Levente", "Noel", "Áron", "Krisztián", "Kristóf", "Bence", "Roland", "Máté", "László", "Bálint" ,
        "Regina", "Brigitta", "Gréta", "Hédi", "Hanna", "Boglárka", "Jázmin", "Réka", "Alexandra", "Rebeka", "Lili", "Luca", "Zsófi"};

        Random rnd2 = new Random();
        Console.WriteLine("Az ID : '1' eszköz nyertese: " + Names[rnd2.Next(0, Names.Length - 1)]);

        Random rnd3 = new Random();
        Console.WriteLine("Az ID : '2' eszköz nyertese: " + Names[rnd2.Next(0, Names.Length - 1)]);

        Random rnd4 = new Random();
        Console.WriteLine("Az ID : '3' eszköz nyertese: " + Names[rnd2.Next(0, Names.Length - 1)]);

        Random rnd5 = new Random();
        Console.WriteLine("Az ID : '4' eszköz nyertese: " + Names[rnd2.Next(0, Names.Length - 1)]);

        Random rnd6 = new Random();
        Console.WriteLine("Az ID : '5' eszköz nyertese: " + Names[rnd2.Next(0, Names.Length - 1)]);

        Random rnd7 = new Random();
        Console.WriteLine("Az ID : '6' eszköz nyertese: " + Names[rnd2.Next(0, Names.Length - 1)]);


        Console.ReadKey(true);
    }




lundi 30 juillet 2018

Android Studio Cryptographically Safe Random Password Generator

I'm interested in building an Android random password generation app. I am not very familiar with true randomness in Android but I have a vague impression I could use entropy? Or how could I achieve true randomness in an android device?

I've tried to use SecureRandom() but I have no idea how to propely use it.




random numbers between 1 and 50; 50 times

I´m almost got it, but it still not working out like I want it -- I got s var a = generates an integer between 1 and 50

the integer (result) is output in a textare id("tt4")

but I can't get it done 50 times, I tried to use a for loop // but like I said, I´m hanging here...

function add() {
  var a = Math.floor(Math.random() * 50) + 1;
  for (var i = 0; i < 49; i++) {
    document.getElementById("tt4").innerHTML = a + ('\n');
  }
}
<!DOCTYPE html>
<html>

<head>
  <title></title>
  <link rel="stylesheet" type="text/css" href="style.css" media="screen" />
</head>

<body>
  <button onclick="add()">OK</button>
  <br><br>
  <textarea id="tt4" name="t4"></textarea>
</body>

</html>

I know that the problem is in the for-loop, because 'nothing' hapens with the var i inside the loop // but I can't figure it out




Selenium Java random select username for saucelabs cross browser execution

Project info: java, selenium, testng, maven. Running from Jenkins on saucelabs.

I have the method to select randomly the users name from the string of users:

public class RandomDataSelect {

public static String selectRandomUser(){

    String[] users = {"user1", "user2"};
    return users[(int) (Math.random()* users.length)];
}

and pass each username to each browser while the cross browser and parallel execution in saucelabs. The idea that each browser: chrome and FF should take one username from the list and perform the login.

Currently the issue is that one browser takes 2 usernames, placed them into login field and trying to login with them. For example: login "user1user2". Must be "user1" or "user2".

In the same time , chrome browser didn't get any command to enter the input.

Please, help me to figure out what is the issue.

The code of the main test:

 public class Login extends TestBase{


 @Test(dataProvider = "browsers")
 public void Login(String browser, String version, String os, Method method) throws Exception {

 this.createRemoteDriver(browser, version, os, method.getName());
 WebDriver driver = getWebDriver();

 System.out.println("Driver: " + driver.toString());

 app = new Application(driver);
 configRead = new ConfigFileReader();

        VisitPage page = VisitPage.getURL(driver);
        this.annotate("Visiting page...");

        app.loginPage().Login_as(RandomDataSelect.selectRandomUser(), configRead.getPassword());
        this.annotate("Submit login");

        driver.close();
        this.annotate("Driver close");
}

}

The code of the TestBase class:

 public class TestBase {

private WebDriver driver;

protected Application app;
RandomDataSelect randomuser;
ConfigFileReader configRead;
private static String baseUrl;
private PropertyLoader propertyRead;

private static final String SAUCE_ACCESS_KEY=System.getenv("SAUCE_ACCESS_KEY"
);
private static final String SAUCE_USERNAME = System.getenv("SAUCE_USERNAME");

private ThreadLocal<WebDriver> webDriver = new ThreadLocal<WebDriver>();
private ThreadLocal<String> sessionId = new ThreadLocal<String>();



public  WebDriver getWebDriver() {
    return webDriver.get();
}

private void setWebDriver(WebDriver driver) {
    webDriver.set(driver);
}

public String getSessionId() {
    return sessionId.get();
}

@DataProvider(name = "browsers", parallel = true)
public static Object[][] sauceBrowserDataProvider(Method testMethod) throws 
JSONException {

    String browsersJSONArrayString  = 
    System.getenv("SAUCE_ONDEMAND_BROWSERS");
    System.out.println(browsersJSONArrayString);
    JSONArray browsersJSONArrayObj = new JSONArray(browsersJSONArrayString);

    Object[][] browserObjArray = new Object[browsersJSONArrayObj.length()] 
    [3];
    for (int i=0; i < browsersJSONArrayObj.length(); i++) {
        JSONObject browserObj = 
    (JSONObject)browsersJSONArrayObj.getJSONObject(i);
        browserObjArray[i] = new Object[]{browserObj.getString("browser"), 
    browserObj.getString("browser-version"), browserObj.getString("os")};
    }
    return browserObjArray;
   }


void createRemoteDriver(String browser, String version, String os, String 
methodName) throws Exception {


    DesiredCapabilities capabilities = new DesiredCapabilities();

    Class<? extends RemoteSauceOnDemandBrowser> SLclass = this.getClass();

    capabilities.setCapability("browserName", browser);
    if (version != null) {
        capabilities.setCapability("browser-version", version);
    }
    capabilities.setCapability("platform", os);
    capabilities.setCapability("name", SLclass.getSimpleName());
    capabilities.setCapability("tunnelIdentifier", "hdsupply");

    capabilities.setCapability("idleTimeout",100);


    this.webDriver.set(new RemoteWebDriver(new URL
            ("http://" + SAUCE_USERNAME + ":" + SAUCE_ACCESS_KEY + 
"@ondemand.saucelabs.com:80/wd/hub"), capabilities));


   String jobName = methodName + '_' + os + '_' + browser + '_' + version;
   capabilities.setCapability("name", jobName);

    // set current sessionId
    String id = ((RemoteWebDriver) getWebDriver()).getSessionId().toString();
    sessionId.set(id);


    randomuser = new RandomDataSelect();
    configRead = new ConfigFileReader();
}

private void printSessionId() {

    String message = String.format("SauceOnDemandSessionID=%1$s job- 
name=%2$s",
            (((RemoteWebDriver) driver).getSessionId()).toString(), "some job 
name");
    System.out.println(message);
}



@AfterMethod(description = "Throw the test execution results into saucelabs")

public void tearDown(ITestResult result) {
    ((JavascriptExecutor) webDriver.get()).executeScript("sauce:job-result=" 
+ (result.isSuccess() ? "passed" : "failed"));
    printSessionId();
    webDriver.get().quit();
}

void annotate(String text) {
    ((JavascriptExecutor) webDriver.get()).executeScript("sauce:context=" + 
text);
  }
}




Generate random numbers in range given a mean

How would one generate random numbers between a min and max with a supplied mean?

For example, if the min was 4 and max was 25 with an average of 7, generate random numbers in that range that bias the resulting mean (i.e. the mean of all the generate numbers would be close to 7).

I already know how to generate numbers in a range, but the mean is a new thought to me. Is there perhaps something in the <random> library that is built for this?




GAMS decimal numbers

I have the following code:

loop (d,
 rnd(d)=uniformInt(1,nd)
 );

I am going to use the integer numbers rnd(d) as an index of another set s(i). But for example when rnd(d)=34.000 however, it is integer, but s(34.000) has no valid index since, 34.000 is not 34 !! and GAMS shows a error message.




is there a generator, which changes csv files?

can somebody help me please? knows somebody an csv changer which changes automatically like this?

From this:

the before times!

to

change to blank cells




dimanche 29 juillet 2018

Beginner getting ValueError

I'm a beginner coder on python trying to make a "die roller" where you can choose the size of die and it returns this error on my 20th line of my code

import sys
import random
import getopt


def main(argv):
    dsize = ''
    try:
        opts, args = getopt.getopt(argv, "hi:o:", ["dsize="])
        except getopt.GetoptError:
        print("Roll.py -d <dsize>")
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print('Roll.py -d <dsize>')
            sys.exit()
            # elif opt in ("-d", "--dsize"):
            #  dsize = arg
    print('Die size is ', dsize)
    print('roll is: '(random.randrange(1, dsize)))


if __name__ == "__main__":
    main(sys.argv[1:])

also if i uncomment the "elif opt in", and "dsize" i get this

 File "h:\Projects\Roll.py", line 17
   elif opt in ("-d", "--dsize"):
      ^
SyntaxError: invalid syntax




How to make a cell show the text of another random cell?

In Google Sheets, I have a spreadsheet list, which includes a cell (E1) that chooses a random number like so: =RANDBETWEEN(1,99)

I would like to make another cell show the text in column C, row of random number from E1. How can I accomplish this?




Random Position Spawning

I am currently using the unity tanks game tutorial and have been working on improving it and I am working on having a random tank spawn. It works by choosing a random spawn point for tank 1 and then for tank 2 adds one to the generator to choose the next spawn point so to get rid of the chance of having the same spawn point for both tanks yet both tanks occasionally get the same spawn point. So I was wondering on how to fix this and make the tanks spawn at a random place instead of spawning at the same one

using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class GameManager : MonoBehaviour
{
    public int m_NumRoundsToWin = 5;        
    public float m_StartDelay = 3f;         
    public float m_EndDelay = 3f;           
    public CameraControl m_CameraControl;   
    public Text m_MessageText;              
    public GameObject m_TankPrefab;         
    public TankManager[] m_Tanks;
    public Transform[] m_SpawnPoints;           


    private int m_RoundNumber;              
    private WaitForSeconds m_StartWait;     
    private WaitForSeconds m_EndWait;       
    private TankManager m_RoundWinner;
    private TankManager m_GameWinner; 

private void SpawnAllTanks()
{
int spawn = Random.Range(0, 666);
    for (int i = 0; i < m_Tanks.Length; i++)
    {
        m_Tanks[i].m_SpawnPoint.rotation) as GameObject;
           m_Tanks[i].m_Instance =
                    Instantiate(m_TankPrefab, m_SpawnPoints[(spawn + i) % 6].position, m_Tanks[i].m_SpawnPoint.rotation) as GameObject;
                    print("Choosing Spawn"+(spawn + i) % 6);
        m_Tanks[i].m_PlayerNumber = i + 1;
        m_Tanks[i].m_SpawnPoint.position =m_SpawnPoints[(spawn + i) % 6].position;
        m_Tanks[i].Setup();

    }
}




Random generic tree java

I want to create a tree that has these characteristics. Example scheme

All elements (files and directories) must be generated randomly. As input I have to have the depth level and a number of elements to create.




Generating a random number in C++

How can I generate random numbers between two numbers provided that the random numbers will never ever repeat themselves, if the computer has generated all random numbers between the 2 numbers , then it should return null value. I tried using rand() and random() but the numbers were repeatin after certain interval. I tried using Google too but Unfortunately couldn't get anything relevant.




Random row selection based on a column value and probability

Here is the dummy set

df <- data.frame(matrix(rnorm(80), nrow=40))
df$color <-  rep(c("blue", "red", "yellow", "pink"), each=10)


1                   -1.22049503   blue
2                    1.61641224   blue
3                    0.09079087   blue
4                    0.32325956   blue
5                   -0.62733486    red
6                    0.43102051    red
7                    0.61619844    red
8                   -0.17718356    red
9                    1.18737562 yellow
10                  -0.19035444 yellow
11                  -0.49158052 yellow
12                  -1.47425432 yellow
13                   0.22942192   pink
14                   0.76779548   pink
15                   0.97631652   pink
16                  -0.33513712   pink

what I am trying to get is like if the df$color is blue then those rows will be selected, but if the df$color is blue then it got higher probability of getting that row selected, if df$color is yellow then it got lesser probability of getting that row selected, and if df$color is pink then it got very less probability of getting that row selected

This is what I came up with

my.data.frame <- df[(df$color == 'pink') | (df$color == 'blue') & runif(1) < .6 | (df$color == 'red') & runif(1) < .6|(df$color == 'yellow') & runif(1) < .3, ]

But here is the output in 2 runs

1                   -1.22049503  blue
2                    1.61641224  blue
3                    0.09079087  blue
4                    0.32325956  blue
13                   0.22942192  pink
14                   0.76779548  pink
15                   0.97631652  pink
16                  -0.33513712  pink

In second run

1                   -1.22049503  blue
2                    1.61641224  blue
3                    0.09079087  blue
4                    0.32325956  blue
5                   -0.62733486   red
6                    0.43102051   red
7                    0.61619844   red
8                   -0.17718356   red
13                   0.22942192  pink
14                   0.76779548  pink
15                   0.97631652  pink
16                  -0.33513712  pink

So here the blue rows are always getting selected as expected, but the other rows say all the red rows are selected in first run, in second run all the pink and all the red rows are selected - instead of some in red and even less in pink.

What am I missing? or any better way of doing this?




Javascript random text generate randomly

I want create javascript random script which makes random text which every text has assigned random integer to it. and everything will be separated by , i.e es45d4dw 2, Every item should be generated at random different time from range. How can i do that?

var myVar = setInterval(myFunction, getRndInteger(1000, 10000));

    function getRndInteger(min, max) {
        return Math.floor(Math.random() * (max - min + 1) ) + min;
    }

    function myFunction() {
        var para = document.createElement("t");
        var t = document.createTextNode(makeid());
        para.appendChild(t);
        document.body.appendChild(para);
    }

    function makeid() {
      var text = "";
      var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

      for (var i = 0; i < 10; i++)
        text += possible.charAt(Math.floor(Math.random() * possible.length));

      return text;
    }




Passing Values One-Way between Python Scripts

I'm writing a program which involves the use of randomised numbers (r1, r2, r3), with these randomised numbers changing every 3 seconds for 1000 cycles.

I have a script that generates the randomised numbers (random.py), however I'm struggling in being able to have the other script (read.py) being able to access the values of r1, r2 and r3.

e.g. at time 't' r1 is generated by random.py = 56 and at the same time 't' read.py wants to access the value of r1.

As the values of r1, r2 and r3 change over time, read.py wants to be able to access whatever the 'current' value is.

I have tried importing random.py as a module but this executes random.py leading to the script being executed in its entirety (1000 cycles * 3secs) and doesn't achieve my goal.

random.py:

import time
import random

for i in range (1000):
  r1 = random.randinit(1,100)
  r2 = random.randinit(1,100)
  r3 = random.randinit(1,100)
  time.sleep(3)

Any help or advice greatly appreciated.




samedi 28 juillet 2018

PHP Split int into random values

I have a int called v_cnt which im using a maximum value for a voting system, them im using mt_rand to generate a random number of 'votes' (used for gaming purposes not a rigged system)

// vote 1
$vote_limit = $v_cnt;
$vote_1 = mt_rand(0, $vote_limit); 
// vote 2
$vote_limit = $v_cnt - $vote_1; if($vote_limit < 0){ $vote_limit = 0;}
$vote_2 = mt_rand(0, $vote_limit);
// vote 3
$vote_limit = $v_cnt - ($vote_1 + $vote_2); if($vote_limit < 0){ $vote_limit = 0;}
$vote_3 = mt_rand(0, $vote_limit);

This gives me vote_1, vote_2 and vote_3 which is ideal. But, since mt_rand is a random value up to the limit, im not getting quite the result i need as i need it to calculate like this;

(vote_1 + vote_2 + vote_3) = $v_cnt

So essentially i need to split an int into 3 random values which must add up to equal the starting number. I hope this makes sense.

Thank you.




if statement for random string and int

I have this if statement working well but the code DqJUXRcx may change. How to make it == random code?

@IBAction func btnPlusPressed(_ sender: UIButton) {
    var strURLl = url.text!

    if (url.text == "DqJUXRcx" as String ){
        strURLl = "https://pastebin.com/raw/\(url.text!)"
    } else {
        strURLl = "\(url.text!)"
    }
}




vendredi 27 juillet 2018

How can a random number be used as a Double in a Haskell function?

I am trying to write a function that uses a random number as a condition to compare to a list (which is created by mapping a function over a range of integers). I'm doing it interactively, and if I do it by defining each term separately it works:

import System.Random.MWC (create)
import Statistics.Distribution (genContVar)
import Statistics.Distribution.Uniform (uniformDistr)

rng <- create
rd <- (genContVar (uniformDistr 0 1)) rng

f x = takeWhile (<rd) $ fmap (*x) [1..10]

alternatively, I can use a non-random Double with a let expression and also have no problem

f x = let rd = 0.4 in takeWhile (<rd) $ fmap (*x) [1..10]

however, if I try to put it all together I get an error

f x = let rand <- (genContVar (uniformDistr 0 1) g) in takeWhile (<rand) $ fmap (*x) [1..10]

<interactive>:39:16: error:
parse error on input ‘<-’
Perhaps this statement should be within a 'do' block?

I understand that having different variable types prevents so much as adding up and Int and a Double, and that monads are very particular, but being new to Haskell I'm hoping to avoid the broader philosophy about that for now and instead try to find a practical way of using random numbers in general functions.




True Random number of an integer through a byte generator (BlueRand)

I'm trying to create a Java application that receives a string and uses that string to determine how many integers should be randomly selected from a range from 1 - x where x is an integer value. I understand that "True" random generation is difficult/impossible using modern computing technology, but a github repository gained my interest that uses jpeg images as a source of random number generation (https://github.com/prgpascal/bluerand).

The generator seems to create a random amount of bytes, however, and so I was wondering if any of you may have any indication of how one might use this to somehow generate integers within a range.

Of course, if any of you know any other generators without a quota limit, be it from a website with an api or a library that works on a local computer that can do this task and I've missed it, I would be happy to learn of it and move my attention to it!

Thank you for your time.




Am I using random.shuffle wrong or is this a bug?

So I'm shuffling a list before I split it. it's a list of numbers read from a file so the list is actually a list of strings, but they're numbers:

streams = ['0','1','2','3','4','5','6','7','8','9']

now, the code I run, simply shuffles the list:

print(streams, type(streams[0]))
import random
random.shuffle(streams)

I'm using Python 3.6.4 by the way. Here's the error I get:

C:\src>python cli.py
0,1,2,3,4,5,6,7,8,9
 <class 'str'>
Traceback (most recent call last):
...
  File "....py", line 3, in split_randomized_list
    random.shuffle(streams)
  File "C:\ProgramData\Anaconda3\lib\random.py", line 275, in shuffle
    x[i], x[j] = x[j], x[i]
TypeError: 'str' object does not support item assignment

This says to me that it can't shuffle lists made up of numbers in string format? Is that right? Is that a bug or am I doing it wrong?




randomly rearrange lines in a huge ndjson file (45 GB)

I have an ndjson file (every line a valid json) with information that I want to run through a topic model. As it happens, this data is sorted a) by user, and b) by time, so the structure of the overall ndjson file is far from random. However, for the purpose of pushing this file (which I will later chunk into n smaller ndjsons with 50k lines each) through the topic model, I need the features that appear in the data to all have the same probability of being in any given line. My idea to achieve this is to randomly re-order all the lines in the file. The file I'm working with has 11502106 lines and has an overall file size of 45 GB. I also have a gzipped version of the file, which is approximately 4 GB large.

My idea for solving this problem was to use Ubuntu's built-in shuf function, to extract the same number of lines as in the original file, and to direct the output to a new file. I did this like this:

nohup shuf -n 11502106 original_file.json > new_file_randomorder.json &

However, this process gets killed by the system after running for approx. 5 minutes. I'm guessing that I'm running out of memory (16 GB memory is available in my machine). I'm running Ubuntu 16.04.

I realise that this could be a very complicated task, given the fact that file size > available memory.

If anyone has any ideas or potential solutions to this problem, that would be greatly appreciated! Thanks a lot in advance!




Select Random Rows in MySQL for JOIN with another table

I am migrating millions of row from table1 to table2. After the migration, I am trying to spot check certain rows to see if they are migrated properly. Here is a sample SQL query [not the exact one]:

SELECT     tbl1.name,
           tbl1.address,
           tbl2.name,
           tbl2.new_address
FROM       
          (SELECT * 
           FROM table1
           ORDER BY   RAND() limit 10) tbl1
INNER JOIN table2 tbl2
ON         tbl1.name = tbl2.name;

I am trying to select 10 rows from table 1 to join with table2 for checking. If I ran this query with an explain, it does a full table scan i.e., all rows in table 1 (which is > 130 million). How to optimize this query in MySQL?




Random Brush Generator - How to get a new color every time? [duplicate]

This question already has an answer here:

I have a foreach loop, calling the below method. When I step through my code, it is generating a random color. I don't care about the color, just need visual seperation. When I just run the program and don't step through the code, everything is the same color.

I know that a while back I did read a post where someone had the same issue, if you find it please direct me to it. Thanks!

foreach (var opt in OptionList.GroupBy(p => p.PropertyDescription))
    {
      var rndColor = Get_Color();

      foreach (var option in opt)
      {
        option.Foreground = rndColor;
      }
    }

private Brush Get_Color()
{
  Brush retVal = Brushes.Black;

  Random r = new Random();
  int red = r.Next(0, 200);
  int green = r.Next(0, 200);
  int blue = r.Next(0, 200);
  SolidColorBrush brush = new SolidColorBrush(Color.FromRgb((byte)red, 
  (byte)green, (byte)blue));
  retVal = brush;

  return retVal;
}




C++ RNG example from S.O. prints nonrandom numbers (on my machine)

I've been having trouble generating random integers with the example provided by user @Cubbi on this question. I've set up the program as follows:

rand_test.cpp

#include <iostream>
#include <random>

int main()
{
    std::random_device rd;
    std::mt19937 eng(rd());
    std::uniform_int_distribution<> distr(25, 63);

    for(int n = 0; n < 40; ++n)
        std::cout << distr(eng) << ' ';
}

...and compiled it with g++ rand_test.cpp -std=c++11


I executed the program four times in the span of about a minute and received the exact same sequence of numbers:
46 53 38 60 25 48 59 45 62 63 31 50 37 45 52 55 34 27 ...
I then executed it again after researching the issue and beginning this question (10-15 minutes) and again, the same output. Then I recompiled, and the output was the same as before. What's the cause and how do I fix this?
  • Compiler: TDM-GCC-64
  • OS: Windows 10 Home (64 bit)



Creating a function that generates pseudo random numbers

I need to create a function in JavaScript that generates a pseudo random number between a minimum and maximum value, I also need this function to receive an integer value as a parameter, and that the number generated by the function is always the same according to the value used .

function random(seed, min, max)

random(5, 0, 500) => 354
random(184, 0, 500) => 412
random(5, 0, 500) => 354

Is it possible to create a function that does as described and has a good variation of results?




What are periods in pseudo random number generator?

I am reading a text from a book. But since pseudo random number generation is a complex topic, I just was expecting a very basic answer for beginniers. What is the signifigance of period in pseudo number generators. Why is a higher period better? Also what are states? Is having more states better?

Of the three pseudo-random number engines, the Mersenne twister generates the highest quality of random numbers. The period of a Mersenne twister depends on an algorithmic parameter but is much bigger than the period of a linear congruential engine. The memory required to store the state of a Mersenne twister also depends on its parameters but is much larger than the single integer state of the linear congruential engine. For example, the predefined Mersenne twister mt19937 has a period of 2^19937−1, while the state contains 625 integers or 2.5 kilobytes. It is also one of the fastest engines.




Cryptographically secure pseudo-random number generator (CSPRNG) in Java

I'm looking for a CSPRNG algorithm, I would love to see a Java implementation but if it's not too complicated and I can "translate it" myself in Java it would already be great to see it in another language. I do not care how fast is-it but I want to be able to initialize it (ie by generating a list of x random numbers with another computer at another time I get the same suite if I initialized the generator with the same number).

Thomas!




Haskell: Efficiency iterative map with added noise

I am wondering how to improve the time performance of the white noise addition to the logistic map? The noise is only allowed to be added after calculating the values (as it is an iterative map.)

 module Generating

import System.Random (Random,randomR,random,mkStdGen,StdGen)
import Data.Random.Normal (mkNormals,normal)
import qualified Data.Vector.Unboxed as U 
import Control.Monad.State

genR :: (Random a, Fractional a) => Int -> (a, StdGen)
genR x = randomR (0,1.0) (mkStdGen x)


new ::Double-> Double ->Int -> (Double,Int) -> U.Vector (Double,Int)
new skal r n = U.unfoldrN n go
  where  
   go (x0,g0)  = let  !eins= (1.0-x0)
                      !x=x0 `seq` eins `seq` r*x0*eins
                      !g=g0+1
                      !noise= skal*(fst $ genR g)
             in Just ((x0+noise,g0),(x,g))

fs :: (t, t1) -> t
fs (x,y)=x

first :: U.Vector (Double,Int)->U.Vector Double
first  =U.map (\(x,y)->x)  

As you can see, I actually only want the first value of the tuple, but the generator needs to be updated.

Any suggestions? Maybe State Monads?




Perl: Comparing two lines at once while reading in a file

I have a perl script that reads text file line by line and splits the line into different columns. It randomly generates hex colors for each distinct number before the decimal point (format: $cols[2].$cols[3] #random_hex_color). The number after the decimal is not considered. I am trying to compare $cols[2] for line X with $cols[2] for the next line. If the numbers are equal, the #random_hex_color should be the same.

So far, I am randomly generating a new #random_hex_color for every line.

Desired output: 22.1 #9139491 66.3 #D465671 66.5 #D465671 31.8 #C18D961




Script to pick random directory in bash

I have a directory full of directories containing exam subjects I would like to work on randomly to simulate the real exam.

They are classified by difficulty level:

0-0, 0-1 .. 1-0, 1-1 .. 2-0, 2-1 ..

I am trying to write a shell script allowing me to pick one subject (directory) randomly based on the parameter I pass when executing the script (0, 1, 2 ..).

I can't quite figure it, here is my progress so far:

ls | find . -name "1$~" | sort -r | head -n 1

What am I missing here?




sample without replacement with pymongo

I recently started using mongodb and pymongo, and am aware of using $sample to sample. There are multiple questions on stackoverflow regarding sampling from a mongo db, and in some of those questions there are comments warning that the sample is with replacement, but did not address how to sample without replacement.

But I would to sample without replacement! Any solutions that are efficient and non-hacky?




if statement in for loop (random number generator

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

int main()
{
unsigned seed;
cout << "Input a whole number between 0 and 65535 to\n initialize the random number generator: ";
cin >> seed;
srand(seed);

int number;
number = rand();

int count;
for (count = 1; count <= 20; count++)
{

    if (number >= 1 && number <= 100)
    {
        cout << number << endl;
        number = rand();
    }
    else
    {
        number = rand();
        --count;
    }

}
return 0;
}

I was trying to code a random number generator that prints out 20 random numbers between 1 and 100 including 1 and 100. Everything is working fine now after i decremented "count" in the else statement (--count). without that "--count" the program outputs only one or no numbers at all. Why would it output only one number if the if-statement initializes the rand() function to generate a new number after every loop? Can anyone explain to me why I had to put --count in this else statement? It was more of a guess to decrement "count" than knowing why. Even if it would generate a number over 100 it has to generate it again and again until it fits the case or not?




How to specify the number of odd and even numbers from a random generator in R?

I need to generate a random selection of 9 whole numbers from 1 to 40 with the following condition: the output must contain 5 even numbers and 4 odd numbers.

I have the following code to generate 9 random numbers:

x1<- sample(1:40, 9, replace=F)
> x1
  [1]  2 36  6 10 39 17 14 11 25

I now need to add the odd and even numbers condition in the equation. How can I do this?




Why all variables are zeros after initialization. (using random_normal() )

My friend has random values with same code, i think that is tensorflow's problem.

here is my code:

import tensorflow as tf

w1 = tf.random_normal([2,3], stddev=1, seed=1)
w2 = tf.random_normal([3,1], stddev=1, seed=1)

sess = tf.Session()

init=tf.global_variables_initializer()
sess.run(init)

print(sess.run(w1))
print(sess.run(w2))

sess.close()

output:

[[ 0.  0.  0.]
 [ 0.  0.  0.]]
[[ 0.]
 [ 0.]
 [ 0.]]

I using anaconda3 ,python3.6.5 ,tensorflow is gpu ver. someone can told me how to fix it? thank u




Get index of Shuffle Range on 2D Array php

I want to random 80*13 digits for genetic algorithm where 80 is popsize and 13 is dna size. And I trying to get index of range value on 2d array. To make a random int from 1 - 13 without duplicate where i mean 2d for 80 rows and 13 column. like this

$arr = [0][0]; //this is output will be same with the table value in row1 col1
$arr = [0][1]; //this is output will be same with the table value in row1 col2
...
$arr = [0][12]; //this is output will be same with the table value in row2 col1
$arr = [1][1]; //this is output will be same with the table value in row2 col2
..

i have a code like this.

<?php
function randomGen($min, $max) {
    $numbers = range($min, $max);
    shuffle($numbers);
    return array_slice($numbers, 0);
}
?>

<table>
    <tr>
        <th rowspan="2">Kromosom ke-</th>
        <th colspan="13">Stasiun Kerja</th>
    </tr>
    <tr>
        <?php
        for ($i=1; $i <= 13; $i++) { 
        ?>
            <th>
                <?php echo $i;?>
            </th>
        <?php
        }
        ?>
    </tr>
    <tr>
<?php
    for($i = 0; $i < 80; $i++) {
        $no = 1;
        echo "<td> v".$no."</td>";
        $arr[$i] = randomGen(1,13);
        for ($j=0; $j <= 12; $j++) {
            $arr[$j] = randomGen(1,13);
            echo "<td>";
            echo $arr[$i][$j];
            echo "</td>";
        }
            echo "</td><tr>";
            $no++;

    }
    // print_r($arr[0][0].' '); // for see the value is same or not
    ?>

when i try to printout $arr[0][0], thats value is not same with the table in row1 col1.

Any ideas?




How to generate a random number in Crystal?

In Crystal, how can I generate a random number?


Using Python, I can simply do the following to generate a random integer between 0 and 10:

from random import randint
nb = randint(0, 10)




trying to +1 to random.seed() for every loop

I'm working on a casino program that gets a bet ($1-$50) from the user, then pulls a slot machine to display a three-string combination of "7", "cherries", "bar", or "(space)". Certain combinations will trigger a bet multiplier, and the user will win back this amount. The run should look like this: ask user for bet, show user the pull and their winnings, then ask user for a new bet, display a new pull, and so on.

Right now, I have everything down except for a couple problems - I cannot make it so that the program generates a new random combination for each pull. Secondly, the main loop continues forever, printing the user's pull and winnings forever. Below is the method that generates either "7", "cherries", etc.

def rand_string(self):
    random.seed(0)
    # produces a number between 0 and 999
    test_num = random.randrange(1000)

    # precompute cutoffs
    bar_cutoff = 10 * TripleString.BAR_PCT
    cherries_cutoff = bar_cutoff + 10 * TripleString.CHERRIES_PCT
    space_cutoff = cherries_cutoff + 10 * TripleString.SPACE_PCT

    # bar = 38%, cherries = 40%, space = 7%, seven = 15%
    if test_num < bar_cutoff:
        return TripleString.BAR
    elif test_num < cherries_cutoff:
        return TripleString.CHERRIES
    elif test_num < space_cutoff:
        return TripleString.SPACE
    else:
        return TripleString.SEVEN

And here is the loop in main:

while(True):
if bet == 0: #a bet of $0 ends the program
    print("Please come again!")
    break
else:
    print("whirrr...and your pull is " +\
          object.pull())
    object.display(None)

I thought I could solve this by somehow adding 1 to random.seed() for each loop (we begin with random.seed(0), but for each new pull 1 is added so that random.seed(1) and so on), but I don't know how to go about doing this and I'm not even sure if it's doable. If someone could point out my mistakes here, that'd be great. (sorry if this makes no sense, I'm very new to Python).




jeudi 26 juillet 2018

Efficiently convert random bytes to string without much loss of entropy

I need a cryptographically random string to serve as the session identifier in my Web app. Here is my current implementation with libsodium:

char session_id[81];
sprintf(session_id, "%"
        PRIx32
        "%"
        PRIx32
        "%"
        PRIx32
        "%"
        PRIx32
        "%"
        PRIx32
        "%"
        PRIx32
        "%"
        PRIx32
        "%"
        PRIx32,
        randombytes_random(), randombytes_random(), randombytes_random(), randombytes_random(),
        randombytes_random(), randombytes_random(), randombytes_random(), randombytes_random());

Which is the most obvious way. This problem is that most of the key space is unused: there are 36 alphanumeric characters even if we ignore case sensitivity, but only 16 of which (0-9, A-E, and maybe X from the 0X prefix) would appear in the resulting string. I'd like to know if there is a way to improve the current approach by making use of more of the key space.

The convert should be as efficient as possible, but on the other hand I hope most of the randomness is preserved. Please note that I don't expect ALL entropy to be preserved if that operation would be too expansive. Instead, I'm seeking a balance between the length of the resulting string, performance, and the amount of entropy.

I'm already using libsodium for other functionalities in my project, and I'd like to stick to it. Please avoid suggesting another library unless you have a really good reason. Thanks in advance.




How to generate random increasing or decreasing strings in python?

I need to make sequence of random strings, which increase(decrease) for alphabetic oder. For example: "ajikfk45kJDk", "bFJIPH7CDd", "c".




C# Generate and execute random delay between tasks

I have this code here:

                        #region BunnyHop

                    bool bLocalIsOnGround = pLocal.IsOnGround();

                    if (bMouseEnabled && Config.MiscEnabled && Config.bBunnyHopEnabled && IsKeyState(Config.iBunnyHopKey) && pLocal.GetVelocity() > 45f)
                    {
                        if (bLocalIsOnGround)

                        g_pEngineClient.PlusJump();
                        else if (g_pEngineClient.GetJumpState() == 5)
                            g_pEngineClient.MinusJump();
                    }
                    #endregion

And I am looking to add a randomly generated delay like this:

                    {
                        if (bLocalIsOnGround)
                        //RANDOM DELAY HERE BETWEEN 0 AND 10  MS
                        g_pEngineClient.PlusJump();
                        else if (g_pEngineClient.GetJumpState() == 5)
                            g_pEngineClient.MinusJump();
                    }
                    #endregion

I have tried thread.delay and rest, neither are working properly. And help is appreciated.




how to know the seed for a random dataset in python

I have a simple random test code in python-3, where I generate a few random numbers, and do some processing with them, something like this:

random.seed(9001)
while True:
    x = numpy.random.rand((10, 10))
    do_some_processing(x)

My problem is that when I fix the seed, ie it becomes a deterministic run, then the code works fine. But when I delete the seed line, then sometimes the code reports errors. So I need to know for what seed value were the random numbers generated which created the failures.

So, how can I know and print the seed value, so that I can replicate the failure test?




Is there a way to generate just random "times"?

I know that you can use as.POSIXct to generate dates and times. But I want to generate just the times ex) 05:16 (min:sec) Does anyone know how to do it? I could not find any package for just time.




How to select a random member of a javascript array with n members such that every selection is as far as possible from the previous 3 selections?

Suppose there is an array with 50 elements. Every time a random element is selected (all selected elements are still eligible for re-election in the subsequent iterations), is there a way to make sure that these new selections are as "far" as possible from the three items that were selected before it? Of course, this won't matter for the first three iterations.

By "far" I mean as distant (neighbour-wise) as possible from the previous 3 selections.

I am not sure if I make sense so feel free to correct any misconception I may display.




Maintain Order of Output with RandomTimeOut ( Javascript )

This code will output 1 to 5 in random order. However, we want this code to output in the sequential manner (1,2,3,4,5). I do have a solution which may not be the right way to approach this question. Need Thoughts or right solution.

'use strict';
const callback = function( result ){
    console.log(result);
};
const print = function( num ){
    for(let i =0 ; i < num ; i++){
        randomTimeout(i , callback);
    }
};
const randomTimeout = function( i , callback ) {
    setTimeout(function(){
        callback('Processing '+ i);
    }, Math.random()*1000 );
};
print(5);

Solution:

'use strict';
const callback = function( result ){
    console.log(result);
    print(5);
};
let i = 1;
const print = function( num ){
    if(i<=num)
        randomTimeout( i++ , callback );
};
const randomTimeout = function( i , callback ) {
    setTimeout(function(){
        callback('Processing '+ i);
    }, Math.random()*1000 );
};
print(5);

Thanks in advance!




mercredi 25 juillet 2018

How to get the remaining sample after using random.sample() in Python?

I have a large list of elements (in this example I'll assume it's filled with numbers). For example: l = [1,2,3,4,5,6,7,8,9,10] Now I want to take 2 samples from that list, one with the 80% of the elements (randomly chosen of course), and the other one with the remaining elements (the 20%), so I can use the bigger one to train a machine-learning tool, and the rest to test that training. The function I used is from random and I used it this way:

sz = len(l) #Size of the original list
per = int((80 * sz) / 100) #This will be the length of the sample list with the 80% of the elements (I guess)
random.seed(1) # As I want to obtain the same results every time I run it.
l2 = random.sample(l, per)

I'm not totally sure, but I believe that with that code I'm getting a random sample with the 80% of the numbers.

l2 = [3,4,7,2,9,5,1,8]

Nonetheless, I can't seem to find the way to get the other sample list with the remaining elements l3 = [6,10] (the sample() function does not remove the elements it takes from the original list). Can you please help me? Thank you in advance.




Unable to add two strings(random hash and normal string) php

So i have this short code

<?php 
$random = substr(md5(uniqid(rand(), true)), 
16, 16);
$name="Tito";



$both= $random+$name;
echo $both;
?>

The result is meant to be something like fdgd3644333d2672Tito(random+"Tito")

But instead,I keep getting numbers such as 0,344 etc or strings IFF

Please help.How do I concatenate these strings as a whole word??

Thanks in advance




I need to random shuffle rows of two pandas DataFrames in the same random way

I have two dataframes, A and B , with dimension MxN which rows I want to random shuffle. A and B have the same column names and indexes. I know how to shuffle data inside each column with df.apply(np.random.shuffle) method, but it permutate differently each column. I want that if the first row of A becames the second row after shuffle, the first row of B becames the second row too, etc. How can I do what I want?




How to get unique random values in Dynamic Add / Remove input Fields

I have created Dynamic Add/Remove fields. Everything is working perfectly. The only problem is that there is a hidden field having name="auth_key[]".

For that I want random values. So I use value="<?php echo rand(); ?>". How ever it creates same random values for all the fields that are added. I want unique random values for all the fields that are added.

Following is my code:

<div class="panel panel-default">

  <div class="panel-heading"><center><b>Team Members</b></center></div>

  <div class="panel-body">

    <div class="row">

      <div class="col-md-5"><label>Member's Registered Email</label></div>
      <div class="col-md-5"><label>Role in Project</label></div>
      <div class="col-md-2"></div>

    </div>

    <div class="row">

      <div class="col-md-5">

        <div class="form-group">

          <input type="text" class="form-control" name="user_email[]" placeholder="">

        </div>

      </div>

      <div class="col-md-5">

        <div class="form-group">

          <input type="text" class="form-control" name="user_role[]" placeholder="">
          <input type="hidden" class="form-control" name="user_status[]" value="Verified" placeholder="">
          <input type="hidden" class="form-control" name="auth_key[]" value="<?php echo rand(); ?>" placeholder="">

        </div>

      </div>

      <div class="col-md-2">

        <button type="button" class="btn btn-success" id="add-member-fields"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Add</button>

      </div>

    </div>

    <div id="member-fields">

    </div>

<p class="help-block"><i>To add member please register new User, if already not registered.</i></p>

  </div>

</div>

<?php

$user = wp_get_current_user();
$args = array(
  'role'         => 'backer',
  'exclude'      => array( $user->ID ),
 );

$users = get_users( $args );
$get_user_emails = wp_list_pluck( $users, 'user_email' );

?>

<script type='text/javascript'>

jQuery(document).ready(function($) {
  var wrapper = $("#member-fields");
  var add_button = $("#add-member-fields");

  var x = 1;
  var availableAttributes = <?php echo json_encode($get_user_emails); ?>;
  var previousValue="";

  add_button.click(function(e) {
    e.preventDefault();
    x++;
    var element = $('<div id="user-fields"><div class="row"><div class="col-md-5"><div class="form-group"><input type="text" class="form-control" id="user_email" name="user_email[]" placeholder=""></div></div><div class="col-md-5"><div class="form-group"><input type="text" class="form-control" name="user_role[]" placeholder=""><input type="hidden" class="form-control" name="user_status[]" value="Unverified" placeholder=""><input type="hidden" class="form-control" name="auth_key[]" value="<?php echo rand(); ?>" placeholder=""></div></div><div class="col-md-2"><button type="button" class="btn btn-danger" id="remove_member_field"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span> Remove</button></div></div><div class="clear"></div></div>');

    element.fadeIn("slow").find("input[name^='user_email']").autocomplete({
    autoFocus: true,
      source: availableAttributes,
    });
    wrapper.append(element);
  });

  wrapper.on("keyup","#user_email",function() {
    var isValid = false;
    for (i in availableAttributes) {
        if (availableAttributes[i].toLowerCase().match(this.value.toLowerCase())) {
            isValid = true;
        }
    }
    if (!isValid) {
        this.value = previousValue
    } else {
        previousValue = this.value;
    }

});

  wrapper.on("click", "#remove_member_field", function(e) {
    e.preventDefault();
    $(this).parent().fadeOut(300, function() {
      $(this).closest('#user-fields').remove();
      x--;
    });
  });
});

</script>

Please help me. Thanks in advance.




mardi 24 juillet 2018

Loop a function every random seconds, with a random delay and more (specific, read)

Sorry for being a burden but I am very new to Java and programming in general. I have attempted to solve my problem by using the searchbar but that has only brought more confusion. I only know the bare minimum to use Java, so this is taking way longer than it should.

To get to the point: Basically what I want to be accomplished is a function that will generate a random integer within the range 85-10. Then after a random amount of time (1-25 seconds), that number will get subtracted by another random integer in the range of 0-3 and call another function. Once the first random integer is less than 4, wait a random amount of time and then restart the loop

here is my psuedocode: (my java is ugly and doesn't work yet lol)

loop() {                                                       //main loop
    int count = 85+(int)(Math.random()*((100-85)+1));           //randint range 85-100
    for count in range(4, 101) {                               //loop until count is too low
        int lossage = (int)(Math.random()*3);                  //randint to determine lossage
        Sleep(1000+(int)(Math.random()*((25000-1000)+1)));     //wait 1-25 seconds
        int result = count - lossage;                          //calculate count after loss
        OtherFunction();                                       //call other function
        Sleep(1000+(int)(Math.random()*((5000-1000)+1)));      //wait 1-5 seconds 
    }                                                          //loop again
    else {                                                     //case if count is too low
        Sleep((1+(int)(Math.random()*((20000-10000)+1)));      //wait 10-20 seconds to restart
}

If somebody can convert this to working Java and explain how it works I would be infinitely grateful. I have been trying for an hour to get this too work. Conditional loops confuse me, maybe I am missing something obvious. Thanks




Random Enum returns null

Hello i am trying to get random ENUM, but it returns null, someone can help me what's wrong in my code ? I was trying to repair it alone but i give up.

public class LotteryMachine {

protected enum Sings {
    ONE,
    TWO,
    THREE
}

private static final List<Sings> SINGS_LIST = Collections.unmodifiableList(Arrays.asList(Sings.values()));
private static final int SIZE = SINGS_LIST.size();
private static final Random RANDOM = new Random();

Sings randomSing() {
    return SINGS_LIST.get(RANDOM.nextInt(SIZE));

}
}



public class Game {

private LotteryMachine lotteryMachine = new LotteryMachine();

private LotteryMachine.Sings singOne;
private LotteryMachine.Sings singTwo;
private LotteryMachine.Sings singThree;

private void Lottery(){
    this.singOne = lotteryMachine.randomSing();
    this.singTwo = lotteryMachine.randomSing();
    this.singThree = lotteryMachine.randomSing();
}

public void viewLottery(){
    System.out.print(singOne + " " + singTwo + " " + singThree);
}

}




passing two input files to a function leads to bad results

First of all sorry for my english. I am not native english speaker. In general I am trying to retrieve indices of variable sample size for each input file. Afterwards I want to compare the values between the two input files. Thus, I have two input files as arguments. The first function selects randomly values in a certain range. The second function takes the output of the first function and calculates an Index for each sample.

For this aim, I firstly passed two input files as arguments to my script.

file_name1 = sys.argv[1]
file_name2 = sys.argv[2]

I picked the values of each input file and saved them to a list, as following:

data1 = [2, 6, 4, 8, 9, 8, 6, 6, 6,, 7, 7, 4, 2, 2, 2, ......] #sample size 835
data2 = [7, 7, 5, 3,4, 2, 8, 6, 5, 1, 1, 9, 7 ......] #sample size 2010

I wrote a function, which picks randomly numbers from the list within a certain range (0, 200, 400, n). After that I grouped same values and saved the value, and the number of values as key values in a dictionary.

def subsamples(list_object):

   val = np.array(list_object)
   n = len(val)
   count = 0
   while (count < n ):
       count += 200
     if (count > n):
        break
     subsample = np.random.choice(val, count, replace=False)
     unique, counts = np.unique(subsample, return_counts=True)
     group_cat = dict(zip(unique, counts))
     pois_group.append(group_cat)

     return pois_group

Additionally I have a second function that calculates an Index for each sample size.

def list_sample_size(object):
   data = subsamples(object)
   def p(n, N):
        if n is 0:
            #return 0
        else:
            return (float(n)/N) * ln(float(n)/N)
    for i in data:
        N = sum(i.values())
        #calculate the Index
        sh = -sum(p(n,N) for n in i.values() if n is not 0)
        index = round(math.exp(sh),2)
        print("Index: %f, sample size: %s" % (index, N))
        y.append(index)
        x.append(N)
    return x,y

x_1, y_1= list_sample_size(data1)
print "--------------------"
x_2, y_2 = list_sample_size(data2)

but I got following ouput when I call the function for each input file. It outputs the first Input correctly but the second output prints the first input1 and then its own, does anyone now what am I doing wrong?

Input1 has 835 pois
Index: 37.720000 , sample size: 200
Index: 43.590000 , sample size: 400
Index: 46.010000 , sample size: 600
Index: 48.770000 , sample size: 800
---------------------------
Input1 has 2010 pois
Index: 37.720000 , sample size: 200
Index: 43.590000 , sample size: 400
Index: 46.010000 , sample size: 600
Index: 48.770000 , sample size: 800
Index: 22.610000 , sample size: 200
Index: 21.110000 , sample size: 400
Index: 25.920000 , sample size: 600
Index: 27.670000 , sample size: 800
Index: 28.630000 , sample size: 1000
Index: 28.110000 , sample size: 1200
Index: 28.380000 , sample size: 1400
Index: 28.610000 , sample size: 1600
Index: 28.910000 , sample size: 1800
Index: 29.120000 , sample size: 2000

Does anyone know waht am I doing wrong?




Is sample_n really a random sample when used with sparklyr?

I have 500 million rows in a spark dataframe. I'm interested in using sample_n from dplyr because it will allow me to explicitly specify the sample size I want. If I were to use sparklyr::sdf_sample(), I would first have to calculate the sdf_nrow(), then create the specified fraction of data sample_size / nrow, then pass this fraction to sdf_sample. This isn't a big deal, but the sdf_nrow() can take a while to complete.

So, it would be ideal to use dplyr::sample_n() directly. However, after some testing, it doesn't look like sample_n() is random. In fact, the results are identical to head()! It would be a major issue if instead of sampling rows at random, the function were just returning the first n rows.

Can anyone else confirm this? Is sdf_sample() my best option?

# install.packages("gapminder")

library(gapminder)
library(sparklyr)
library(purrr)

sc <- spark_connect(master = "yarn-client")

spark_data <- sdf_import(gapminder, sc, "gapminder")


> # Appears to be random
> spark_data %>% sdf_sample(fraction = 0.20, replace = FALSE) %>% summarise(sample_mean = mean(lifeExp))
# Source:   lazy query [?? x 1]
# Database: spark_connection
  sample_mean
        <dbl>
1    58.83397


> spark_data %>% sdf_sample(fraction = 0.20, replace = FALSE) %>% summarise(sample_mean = mean(lifeExp))
# Source:   lazy query [?? x 1]
# Database: spark_connection
  sample_mean
        <dbl>
1    60.31693


> spark_data %>% sdf_sample(fraction = 0.20, replace = FALSE) %>% summarise(sample_mean = mean(lifeExp))
# Source:   lazy query [?? x 1]
# Database: spark_connection
  sample_mean
        <dbl>
1    59.38692
> 
> 
> # Appears to be random
> spark_data %>% sample_frac(0.20) %>% summarise(sample_mean = mean(lifeExp))
# Source:   lazy query [?? x 1]
# Database: spark_connection
  sample_mean
        <dbl>
1    60.48903


> spark_data %>% sample_frac(0.20) %>% summarise(sample_mean = mean(lifeExp))
# Source:   lazy query [?? x 1]
# Database: spark_connection
  sample_mean
        <dbl>
1    59.44187


> spark_data %>% sample_frac(0.20) %>% summarise(sample_mean = mean(lifeExp))
# Source:   lazy query [?? x 1]
# Database: spark_connection
  sample_mean
        <dbl>
1    59.27986
> 
> 
> # Does not appear to be random
> spark_data %>% sample_n(300) %>% summarise(sample_mean = mean(lifeExp))
# Source:   lazy query [?? x 1]
# Database: spark_connection
  sample_mean
        <dbl>
1    57.78434


> spark_data %>% sample_n(300) %>% summarise(sample_mean = mean(lifeExp))
# Source:   lazy query [?? x 1]
# Database: spark_connection
  sample_mean
        <dbl>
1    57.78434


> spark_data %>% sample_n(300) %>% summarise(sample_mean = mean(lifeExp))
# Source:   lazy query [?? x 1]
# Database: spark_connection
  sample_mean
        <dbl>
1    57.78434
> 
> 
> 
> # === Test sample_n() ===
> sample_mean <- list()
> 
> for(i in 1:20){
+   
+   sample_mean[i] <- spark_data %>% sample_n(300) %>% summarise(sample_mean = mean(lifeExp)) %>% collect() %>% pull()
+   
+ }
> 
> 
> sample_mean %>% flatten_dbl() %>% mean()
[1] 57.78434
> sample_mean %>% flatten_dbl() %>% sd()
[1] 0
> 
> 
> # === Test head() ===
> spark_data %>% 
+   head(300) %>% 
+   pull(lifeExp) %>% 
+   mean()
[1] 57.78434




How to find SHA1 output having 'zero' in first 8 places

I have to find SHA1 output having 'zero' in first 8 places.

Output[40] = SHA1( Data[64] + Random[??] )

I cant figureout equation for generating random string to find required SHA1 in minimum iterations.

Random Generator

String GenRand()
{
    String possibleCharacters("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"); // change if require
    int randomStringLength = 12; //8 // change if require 

   String randomString;
   for(int i=0; i<randomStringLength; ++i)
   {
       int index = rand() % possibleCharacters.length();
       Char nextChar = possibleCharacters.at(index);
       randomString.append(nextChar);
   }
   return randomString;
}

Data[64]:

HOPETDtHmRghhwLNEdYJNKYSRdUIkoKAxfhaQQTtcSrKrlgjpQBRKAXyANYqtFFP

Random[??]:

awtVstgafWfa

Required Output[40]:

000000006259aa374ab4e1bb03074b6ec672cf99




randomly initialized embeddings with Tensorflow

I am making an embedding layer with randomly initialized embeddings. I proceeded this way

vocab_size = 10
embed_dim = 4

mapping_strings = tf.constant(["hello", "lake", "palmer"])  # input tokens

table = tf.contrib.lookup.string_to_index_table_from_tensor(
mapping=mapping_strings, num_oov_buckets=1, default_value=-1)

ids = table.lookup(mapping_strings)           # ids for each  oken 

embedding_matrix = tf.random_normal(name="embedding_matrix",
                                        dtype=tf.float32,
                                        shape=[vocab_size,embed_dim])
#embedding for each id 
embedded_inputs = tf.nn.embedding_lookup(embedding_matrix, ids)



with tf.Session() as sess:

table.init.run()
print(sess.run(embedded_inputs))

This works and gives me the expected output , but i want these randomly initialized embeddings to be trained later, where are the weights and biases set ? and how will backpropagation be performed in order for the embeddings to be learned? also is tf.random_normal giving me a random variable for the embedding_matrix ?




How to select a random string from a list of strings in SQL Server

Im trying to generate some dummy data and need to re-apply the logic on every new row.

For Example, The words are 'Comm' and 'Resi'.

The query I am using is as follows;

    SELECT SubSkill = (
    SELECT TOP 1 Name
    FROM (
        SELECT RandomGUID = cast(round(RAND(CHECKSUM(NEWID())) * (1 - 10) + 10, 2) AS INT) 
            ,'Comm' AS Name 
    UNION ALL   
        SELECT cast(round(RAND(CHECKSUM(NEWID())) * (1 - 10) + 10, 2) AS INT)
            ,'Resi'
        ) NAMES
    ORDER BY RandomGUID
    )
,* FROM Sales2

However this gives me either 'Comm' for every record, or 'Resi' for every record on execution. I need it to be randomly selected on each row.

Any ideas?




R - random drawings from a custom probability distribution derived from a dataset

I have an R data frame my_measurements (which is a subsample of a much larger 10k+-row data frame) that looks like this:

> glimpse(my_measurements)
Observations: 300
Variables: 2
$ measurement_id <int> 2, 27, 36, 39, 41, 44, 118, 121, 125, 127, 132, 134, 148...
$ value          <dbl> 0.9746835, 1.0000000, 1.0000000, 1.0000000, 1.0000000, 0...

Here is the dput(my_measurements) output:

structure(list(measurement_id = c(2L, 27L, 36L, 39L, 41L, 44L, 
118L, 121L, 125L, 127L, 132L, 134L, 148L, 149L, 179L, 182L, 194L, 
203L, 204L, 210L, 227L, 241L, 246L, 249L, 278L, 298L, 324L, 328L, 
364L, 370L, 380L, 383L, 397L, 405L, 427L, 443L, 450L, 453L, 454L, 
476L, 479L, 493L, 512L, 524L, 566L, 582L, 586L, 592L, 600L, 604L, 
619L, 633L, 638L, 641L, 650L, 657L, 659L, 661L, 663L, 674L, 676L, 
683L, 686L, 689L, 693L, 719L, 720L, 723L, 726L, 728L, 732L, 746L, 
748L, 752L, 757L, 762L, 768L, 769L, 783L, 785L, 789L, 795L, 811L, 
829L, 839L, 846L, 847L, 860L, 878L, 890L, 892L, 915L, 918L, 933L, 
948L, 976L, 986L, 987L, 1034L, 1040L, 1055L, 1061L, 1072L, 1081L, 
1085L, 1088L, 1091L, 1107L, 1113L, 1114L, 1115L, 1125L, 1135L, 
1140L, 1143L, 1144L, 1148L, 1155L, 1159L, 1161L, 1166L, 1168L, 
1175L, 1179L, 1186L, 1201L, 1222L, 1232L, 1234L, 1238L, 1241L, 
1249L, 1256L, 1262L, 1269L, 1378L, 1403L, 1417L, 1446L, 1447L, 
1489L, 1493L, 1498L, 1501L, 1504L, 1515L, 1521L, 1534L, 1545L, 
1563L, 1566L, 1587L, 1596L, 1597L, 1599L, 1600L, 1608L, 1618L, 
1631L, 1641L, 1653L, 1678L, 1690L, 1696L, 1700L, 1711L, 1718L, 
1737L, 1774L, 1778L, 1792L, 1793L, 1795L, 1806L, 1807L, 1811L, 
1820L, 1821L, 1822L, 1831L, 1835L, 1837L, 1846L, 1853L, 1854L, 
1875L, 1883L, 1884L, 1889L, 1895L, 1902L, 1907L, 1916L, 1920L, 
1927L, 1933L, 1939L, 1941L, 1957L, 1965L, 1973L, 1974L, 1977L, 
1991L, 2005L, 2032L, 2035L, 2048L, 2051L, 2062L, 2072L, 2103L, 
2113L, 2124L, 2126L, 2132L, 2150L, 2151L, 2173L, 2188L, 2195L, 
2202L, 2207L, 2210L, 2217L, 2218L, 2221L, 2224L, 2229L, 2240L, 
2244L, 2248L, 2259L, 2265L, 2301L, 2324L, 2333L, 2339L, 2340L, 
2352L, 2353L, 2358L, 2372L, 2376L, 2381L, 2384L, 2392L, 2413L, 
2426L, 2445L, 2451L, 2454L, 2455L, 2459L, 2460L, 2472L, 2478L, 
2484L, 2486L, 2490L, 2498L, 2515L, 2518L, 2525L, 2528L, 2532L, 
2551L, 2558L, 2568L, 2587L, 2608L, 2609L, 2618L, 2620L, 2621L, 
2630L, 2633L, 2670L, 2673L, 2683L, 2690L, 2696L, 2703L, 2705L, 
2712L, 2715L, 2718L, 2738L, 2740L, 2748L, 2749L, 2750L, 2768L, 
2772L, 2779L, 2794L, 2818L, 2826L, 2829L, 2838L), value = c(0.974683544303797, 
1, 1, 1, 1, 0.666666666666667, 1, 0.852941176470588, 1, 1, 1, 
0.928571428571429, 0.957446808510638, 0.952380952380952, 0.939024390243902, 
1, 1, 1, 1, 0.9375, 1, 0.75, 1, 0.932432432432432, 0.914893617021277, 
0.75, 0.883333333333333, 0.945098039215686, 0.911111111111111, 
1, 0.955223880597015, 0.972222222222222, 1, 1, 1, 0.692307692307692, 
0.932203389830508, 0.333333333333333, 1, 1, 0.882352941176471, 
0.818181818181818, 0.882352941176471, 1, 1, 1, 0.850574712643678, 
0.878787878787879, 1, 0.866666666666667, 1, 0.824742268041237, 
0.748148148148148, 1, 1, 1, 0.931034482758621, 0.96875, 1, 1, 
0.875, 1, 1, 1, 1, 0.666666666666667, 1, 1, 0.739130434782609, 
0.642857142857143, 0, 1, 1, 0.96875, 0.76, 0.747899159663866, 
0.888888888888889, 1, 0.948979591836735, 0.888888888888889, 1, 
1, 1, 1, 0.975609756097561, 1, 0.6875, 0.788235294117647, 0.9375, 
0.888888888888889, 1, 0.666666666666667, 1, 0.875, 1, 0.991111111111111, 
0.928571428571429, 1, 0.923076923076923, 1, 0.689922480620155, 
1, 0.684210526315789, 1, 0.779661016949153, 1, 1, 0.704545454545455, 
0.703703703703704, 1, 1, 1, 0, 0.655172413793103, 0.875, 1, 1, 
1, 0.7, 0.857142857142857, 1, 1, 0.686274509803922, 1, 1, 1, 
1, 0, 0.5, 1, 1, 0.995412844036697, 0.857142857142857, 0.75, 
0.75, 0.75, 0.5, 0.96, 0.693227091633466, 1, 0.5, 1, 1, 1, 1, 
1, 0.627906976744186, 0.666666666666667, 0.888888888888889, 0, 
0.75, 0.714285714285714, 0.8, 0.6, 0.444444444444444, 0.666666666666667, 
0.666666666666667, 0.416666666666667, 0.4, 0, 1, 1, 1, 0.975, 
1, 1, 1, 1, 0.994871794871795, 0.615384615384615, 1, 1, 0.538461538461538, 
0.714285714285714, 0.5, 1, 1, 1, 1, 1, 0.589285714285714, 0.384615384615385, 
1, 0.75, 1, 1, 0.5, 1, 1, 0.4, 1, 1, 1, 1, 0.578947368421053, 
1, 0.842105263157895, 0.714285714285714, 0.53125, 0.5, 0, 0.636363636363636, 
0.6, 0, 1, 1, 1, 1, 1, 0.888888888888889, 1, 1, 1, 1, 1, 0.888888888888889, 
0.24390243902439, 0.933333333333333, 0.5, 0.3125, 0.904761904761905, 
0.368421052631579, 0.307692307692308, 0.5, 0.5, 0.285714285714286, 
0.209302325581395, 0.857142857142857, 0.466666666666667, 0.5, 
1, 1, 0.216867469879518, 1, 0.147058823529412, 0.846153846153846, 
0.888888888888889, 1, 1, 1, 0.947368421052632, 1, 1, 0.9, 1, 
1, 1, 0.9375, 1, 1, 0.125, 1, 1, 0.454545454545455, 1, 0.111111111111111, 
1, 1, 1, 0.125, 0.230769230769231, 0.375, 1, 0, 0.333333333333333, 
0, 0, 0.142857142857143, 0.0697674418604651, 0.230769230769231, 
1, 1, 0.110497237569061, 0.142857142857143, 0.0714285714285714, 
0.166666666666667, 1, 0.051948051948052, 0.0888888888888889, 
0, 1, 0, 1, 1, 0.0833333333333333, 1, 1, 0.125, 0, 0.96875, 1, 
0.986111111111111, 1, 0.0909090909090909, 0, 0.888888888888889, 
0, 0, 0.608695652173913, 0)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -300L))

Where measurement_id is just a unique identifier for each measurement, and value is the measurement itself (which happens to be between 0 and 1, but doesn't imply a probabilistic meaning and in other scenarios can be any number).

I made a ggplot() of the density distribution of the values like this:

ggplot(data = my_measurements) + 
    geom_density(mapping = aes(x = value, ..density..))

Which looks like this:

enter image description here

As you can see, values range from 0 to 1, but a lot of them are close to 1.

My question is: How can I use the curve in the plot as a probability density function (I hope I am using the right term, if not please correct me!) to draw random samples from???

Ideally, I'd like to create a function that gives me a random number between 0 and 1 where the probability is a function of that curve. In one possible embodiment, the function would take two arguments: one is a vector containing, in this case, all the values from my_measurements; the second being the number of random numbers to pick. The return value would be a vector of the numbers drawn from that distribution.

So, when I run this function against the my_measurements dataset, there is a high chance that it will return numbers close to 1, and a very low chance of returning 0.25 (the lowest point in the curve).

Hope this makes sense, thank you very much for your help.




Random quote generator repeats the same quotes (Ruby)

Good day to everyone! There is a quote generator made with Shoes.

    @think.click do
        @noun_nominative.shuffle
        @base.shuffle
        @thought.replace(@base.sample)
    end

    @noun_nominative = 
        [
            "враг", "удар", "цель", "твой батя",
            "смерть", "друг", "любовь", "ненависть"
        ]
    @noun_accusative = 
        [
            "цель", "друга", "кормилку для лошадей"
        ]
    @base =
        [
        @noun_nominative.sample.capitalize + " - это всякий, кто стремится убить тебя, неважно на чьей он стороне.",
        "Иногда " + @noun_nominative.sample + " не попадает в " + @noun_accusative.sample + ", но " + @noun_nominative.sample + " не может промахнуться.",
        "Нет ничего труднее, чем гибнуть, не платя смертью за " + @noun_accusative.sample + ".",
        "Индивидуумы могут составлять " + @noun_accusative.sample + ", но только институты могут создать " + @noun_accusative.sample + ".",
        @noun_nominative.sample.capitalize + " - это тот человек, который знает о вас все и не перестает при этом любить вас.",
        "Трудно себе представить, что сталось бы с человеком, живи он в государстве, населенном литературными героями."
        ]       

It simply replaces phrases in base array with random words from noun_nominative and noun_accusative, showing a new quote every time button "think" is clicked.

The program should make a brand new quote with every click, however, it keeps showing the same phrases which were generated once. How could I make it regenerate the quotes without reopening the program?

Thank you for answering!




Rounding a number to 10^ form JAVA

I have a random number such as 35 127 3658 45782 etc... I want to round them to 10^ form like 10 100 1000 10000. I can do it with this code:

Math.pow(10, (int)(Math.log10(number)) + 1);

But this code seems to me a bit complex and long for basic operation like that. Is there a better way to do it?




Is the numpy random generator biased?

The numpy.random.choice method can generate a random sample without replacement if different elements should have different probabilities. However, when I test it with

import numpy

a = [0, 1, 2, 3, 4, 5]
p = [0.1, 0.3, 0.3, 0.1, 0.1, 0.1]
result = [0, 0, 0, 0, 0, 0]
N = 1000000
k = 3

for i in range(0, N):
    temp = numpy.random.choice(a, k, False, p)
    for j in temp:
        result[j] += 1
for i in range(0, 6):
    result[i] /= (N * k)
print(result)

the second and third elements only show up 25% of the time which is off by a lot. I tried different probability distributions (e.g., [0.1, 0.2, 0.3, 0.1, 0.1, 0.2]) and every time the result didn't match the expectation. Is there an issue with my code or is numpy really that inaccurate?




How to get random objects from a stream and return it

I have List with some users from google and now in stream I say for every google user make new HRVacationUser ( witch is model ) and give me ( their email, some random date, some random date ) which random date is for random holiday. But in that case i set each user is on vacantion. How can I take random user from google users and set random date for holiday, so I can make a request in the database - give me this user which is in holiday?

public List<HRVacationUser> listVacationGoogleUsers(List<GoogleUser> allGoogleUsers){
        LocalDate date = LocalDate.now();
        List<HRVacationUser> collectHRUser = allGoogleUsers.stream()
                .map(user ->
                        new HRVacationUser(user.getPrimaryEmail(), date.minusDays(ThreadLocalRandom.current().nextInt(1,5)), date.plusDays(ThreadLocalRandom.current().nextInt(1, 5))))
                .collect(toList());
        return collectHRUser;
    }




lundi 23 juillet 2018

How can I efficiently populate a data frame with an index variable and two random variables?

I have written a dataframe with 3 variables: x,y and z with the following characteristics:

1) The dataframe contains 10 sets of x and y variables drawn at random from a standard normal distribution. 2) Each set, denoted as z, has 10 observations of x, y pairs.

df1<-data.frame(x=rnorm(10),y=rnorm(10),z=1)
df2<-data.frame(x=rnorm(10),y=rnorm(10),z=2)
df3<-data.frame(x=rnorm(10),y=rnorm(10),z=3)
df4<-data.frame(x=rnorm(10),y=rnorm(10),z=4)
df5<-data.frame(x=rnorm(10),y=rnorm(10),z=5)
df6<-data.frame(x=rnorm(10),y=rnorm(10),z=6)
df7<-data.frame(x=rnorm(10),y=rnorm(10),z=7)
df8<-data.frame(x=rnorm(10),y=rnorm(10),z=8)
df9<-data.frame(x=rnorm(10),y=rnorm(10),z=9)
df10<-data.frame(x=rnorm(10),y=rnorm(10),z=10)

then I bind the rows in one dataframe

df<bind_rows(df1,df2,df3,df4,df5,df6,df7,df8,df9,df10)

I have tried to do this using the following for loop:

for (i in seq(1,10,1)) {
  df<-data.frame(x="",y="",z="")
  df<-rbind(data.frame(x=rnorm(10),y=rnorm(10),z=i))
}

but I am unable to make the z-index variable to increase each 10 rows and bind the data generated 10 times. The z variable remains constant and equal to 10

Is there anything I have to modify in the loop or other options to do this?




How do I print the value of button?

I can't output the value of button for example I have a button the value are (1, 2, 3, 4.....12). When I clicked 6 buttons example the value are (1,2,3,4,5,6) and clicked the generate button the value of button will be output on the page. And clicked another 6 button output in the newline. And Do not repeat the same number.

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <p id = "demo"></p>
    <input type = "button" name = "btn" value = "1">
    <input type = "button" name = "btn" value = "2">
    <input type = "button" name = "btn" value = "3">
    <input type = "button" name = "btn" value = "4">
    <input type = "button" name = "btn" value = "5">
    <input type = "button" name = "btn" value = "6"><br>
    <input type = "button" name = "btn" value = "7">
    <input type = "button" name = "btn" value = "8">
    <input type = "button" name = "btn" value = "9">
    <input type = "button" name = "btn" value = "10">
    <input type = "button" name = "btn" value = "11">
    <input type = "button" name = "btn" value = "12"><br><br>
    <button onclick = "document.getElementById("demo").innerHTML = Print()">Generate</button>
 <script>
    function Print(num1) {
        btn.value = btn.value + num1;
 }
 </script>
</body>
</html>




create random string in Python3

I have a string like "Mississippi" and I want to create a random string with the length of the string like "Aqwertyuiop".

How can I achieve this in Python3?




dimanche 22 juillet 2018

List index out of range using randint

I'm currently playing around with trying to append a random item (using randint) from a list to another list before adding the next item. Well, that's probably a weird way of putting it but I'm not sure how else to describe it - I apologize. So instead, here's my current code in question and the output I desire:

Code:

import random

lineIDPart3 = []
lineIDSpace6 = []
lineIDSpace6Poss = ["4", "0", "C", "8"]
lineIDSpace6Num = random.randint(0, 3)
while len(lineIDPart3) < 34:
    lineIDPart3.append(lineIDSpace6Poss[lineIDSpace6Num])
    if lineIDSpace6Num < 4:
        lineIDSpace6Num += 1
    else:
        lineIDSpace6Num = 0
print(lineIDPart3)

Example of the output I want:

["C", "8", "4", "0", "C", "8"...]

I'm pretty stumped on this one so any and all help is appreciated!




Display random image with specific audio on page load

Im trying to re purpose some code. I have a program that displays a random image on page load. Im trying to re build it so that it loads a random image WITH a specified sound effect for each image. Im trying to achieve that by having the page load a random div with all the relevant content, but I think ive made some huge missteps and am chasing my tail. Any help setting this up would be amazing please and thanks!

=========================================================================

<script type="text/javascript">
var lastIndex = 0;

function randomCard() {
var theCard = document.getElementById('myCard');
var divArray = new Array

(
'<div id=card><Image id="Image1" src="MyImages/image1.gif"></image><audio 
src="MyAudio/Audio1.mp3" autoplay="autoplay"></audio></div>',
'<div id=card><Image id="Image2" src="MyImages/image2.gif"></image><audio 
src="MyAudio/Audio1.mp3" autoplay="autoplay"></audio></div>',
'<div id=card><Image id="Image2" src="MyImages/image3.gif"></image><audio 
src="MyAudio/Audio1.mp3" autoplay="autoplay"></audio></div>'
);

var divIndex = 0;

if(divArray.length > 1) {
while(divIndex == lastIndex) {
divIndex = Math.floor(Math.random() * divArray.length);
}
lastIndex = divIndex;


}
else {
return false;
}
}
</script>

</head>
<body onload="randomCard()">

<div id=card></div>




[Help-SQL]: i don't want the same number in cell when i am updating table column next time using Random function

I have the following query to update random number in [SetID] column.

" UPDATE Employee SET SetID = CAST(RAND(CHECKSUM(NEWID())) * 5 as INT) + 1 " Update Random Number query

But sometimes i am getting same number on a few rows after executing query. i don't want to repeat the previous number again on that row. Thanks in advance. :)




itertools combinations in tandem with looping

I have the following Python code. Because random is being used, it generates a new answer every time:

import random

import numpy as np

N = 64 # Given

T = 5 # Given

FinalLengths = []

for i in range(T):

    c = range(1, N)
    x = random.sample(c, 2) # Choose 2 random numbers between 1 and N-1
    LrgstNode = max(x)
    SmlstNode = min(x)
    RopeLengths = [SmlstNode, LrgstNode - SmlstNode, N - LrgstNode] 
    S = max(RopeLengths)
    N = S
    FinalLengths.append(S)

avgS = np.mean(FinalLengths) # Find average

print("The mean of S is {}".format(avgS))

My research has led me to possibly using itertools in order to produce all possible combinations within the range and get the avg to converge. If so, how?

Thank you.




How to count the output of the steps needed to complete the program

Hi i have this program and i want to count and print the total steps that needed to complete the program when i'm running it 10 times. (count the total console lines)

Any advice is appreciated

The code of the Hash Table:

public class HashFunction {

String[] theArray;
int arraySize;
int itemsInArray = 0;
    int K = 0;

/**
 *
 * @param args
 */
public static void main(String[] args) {


HashFunction theFunc = new HashFunction(101);

String[] elementsToAdd2 = new String[101];

for (int i = 0; i <= 100; i++) {
elementsToAdd2[i] = Integer.toString(RandomNumbers.getRandomNumberInRange(0, 15024267));
}



    theFunc.hashFunction2(elementsToAdd2, theFunc.theArray);

}


public void hashFunction2(String[] stringsForArray, String[] theArray) {

    for (int n = 0; n < stringsForArray.length; n++) {

        String newElementVal = stringsForArray[n];

        // Create an index to store the value in by taking
        // the modulus

        int arrayIndex = Integer.parseInt(newElementVal) % 101;

        System.out.println("P" + arrayIndex + " " + "I" + newElementVal + "@" + arrayIndex );

        // Cycle through the array until we find an empty space

        while (theArray[arrayIndex] != "-1") {

            ++arrayIndex;

            System.out.println( "P" + arrayIndex);

            // If we get to the end of the bucket go back to index 0

            arrayIndex %= arraySize;

        }

        theArray[arrayIndex] = newElementVal;

    }

}

HashFunction(int size) {

    arraySize = size;

    theArray = new String[size];

    Arrays.fill(theArray, "-1");

}

}

Program to run the class 10 times:

public class RunTenTimes
    {
public static void main(String[] args)
  {
      for(int i=1; i<=10; i++)
          HashFunction.main(args); 
  }
}

Should i add the code in the main class or in the RunTenTimes Class?




What better way to design the built-in stats of a random generator?

Context : a random sentence generator

1) the function generateSentence() generates random sentences returned as strings (works fine)

2) the function calculateStats() outputs the number of unique strings the above function can theoretically generate (works fine also in this mockup, so be sure to read the disclaimer, I don't want to waste your time)

3) the function generateStructure() and the words lists in Dictionnary.lists are constantly growing as time passes

Quick mockup of the main generator function :

function generateSentence() {
  var words = [];
  var structure = generateStructure();

  structure.forEach(function(element) {
    words.push(Dictionnary.getElement(element));
  });

  var fullText = words.join(" ");
  fullText = fullText.substring(0, 1).toUpperCase() + fullText.substring(1);
  fullText += ".";
  return fullText;
}

var Dictionnary = {
  getElement: function(listCode) {
    return randomPick(Dictionnary.lists[listCode]);
  },
  lists: {
    _location: ["here,", "at my cousin's,", "in Antarctica,"],
    _subject: ["some guy", "the teacher", "Godzilla"],
    _vTransitive: ["is eating", "is scolding", "is seeing"],
    _vIntransitive: ["is working", "is sitting", "is yawning"],
    _adverb: ["slowly", "very carfully", "with a passion"],
    _object: ["this chair", "an egg", "the statue of Liberty"],
  }
}

// returns an array of strings symbolizing types of sentence elements
// example : ["_location", "_subject", "_vIntransitive"]
function generateStructure() {
  var str = [];

  if (dice(6) > 5) {// the structure can begin with a location or not
    str.push("_location");
  }

  str.push("_subject");// the subject is mandatory

  // verb can be of either types
  var verbType = randomPick(["_vTransitive", "_vIntransitive"]);
  str.push(verbType);

  if (dice(6) > 5) {// adverb is optional
    str.push("_adverb");
  }

  // the structure needs an object if the verb is transitive
  if (verbType == "_vTransitive") {
    str.push("_object");
  }

  return str;
}

// off-topic warning! don't mind the implementation here,
// just know it's a random pick in the array
function randomPick(sourceArray) {
  return sourceArray[dice(sourceArray.length) - 1];
}

// Same as above, not the point, just know it's a die roll (random integer from 1 to max)
function dice(max) {
  if (max < 1) { return 0; }
  return Math.round((Math.random() * max) + .5);
}

At some point I wanted to know how many different unique strings it could output and I wrote something like (again, very simplified) :

function calculateStats() {// the "broken leg" function I'm trying to improve/replace
  var total = 0;
  // lines above : +1 to account for 'no location' or 'no adverb'
  var nbOfLocations = Dictionnary.lists._location.length + 1;
  var nbOfAdverbs = Dictionnary.lists._adverb.length + 1;

  var nbOfTransitiveSentences = 
    nbOfLocations *
    Dictionnary.lists._vTransitive.length *
    nbOfAdverbs *
    Dictionnary.lists._object.length;
  var nbOfIntransitiveSentences =
    nbOfLocations *
    Dictionnary.lists._vIntransitive.length *
    nbOfAdverbs;

  total = nbOfTransitiveSentences + nbOfIntransitiveSentences;
  return total;
}

(Side note : don't worry about namespace pollution, type checks on input parameters, or these sort of things, this is assumed to be in a bubble for the sake of example clarity.)

Important disclaimer : This is not about fixing the code I posted. This is a mock-up and it works as it is. The real question is "As the complexity of possible structures grow in the future, as well as the size and diversity of the lists, what would be a better strategy to calculate stats for these types of random constructions, rather than my clumsy calculateStats() function, which is hard to maintain, likely to handle astronomically big numbers*, and prone to errors?"

* in real context, the total number has exceeded (10 power 80) for some time already...