vendredi 31 mai 2019

Random number generator not random in a batch file

Trying to generate a random number and use it for variable value in Windows batch script file. Maybe I am missing something very basic, but something is not working here for me.

Created a batch file named random_test.bat with the following content.

SET rnumber=%random%
echo %random%
pause

Running the file consecutively three times produces the following set of outputs:

One

C:\Users\user\Desktop>SET rnumber=28955

C:\Users\user\Desktop>echo 20160
20160

C:\Users\user\Desktop>pause
Press any key to continue . . .

Two

C:\Users\user\Desktop>SET rnumber=29072

C:\Users\user\Desktop>echo 13887
13887

C:\Users\user\Desktop>pause
Press any key to continue . . .

Three

C:\Users\user\Desktop>SET rnumber=29183

C:\Users\user\Desktop>echo 18885
18885

C:\Users\user\Desktop>pause
Press any key to continue . . .

As you can see the command echo %random% keeps producing relatively random numbers between 0 and 32,767 as expected.

At the same time using %random% to set a value for variable rnumber does not. It produces a not-so random number (possibly too between 0 and 32,767) but it is not random. If I were to guess right now it seems to be slowly growing in the 0 to 32,767 direction.

To clarify the script keeps producing a random number with line 2 on each execution (20160, 13887, 18885...), but line 1 seems to produce a number that keeps increasing with each execution of the batch file (28955, 29072, 29183, and so on in my multiple tests).

I already tried it on two different computers, Windows 7 x64 and Windows 2012 R2 respectively, running this 3 line script multiple times in row.

Next thing to try will be on a computer from a completely different network, I'm wondering if this has anything to do with domain policies, network, software..

What is going on here?

UPDATE:

When running the commands in sequence from the same CMD window it works as expected, but it does not when executing the same batch file multiple times.

  • The line in the script echo %random% works as expected.
  • The line SET rnumber=%random% does not.

(When executing the same script multiple times)




Creating a file of max length characters, with a word inserted at random locations x amount of times

I am able to create the random data file but when trying to insert the word at random locations x amount of times, the length of the file becomes greater than the max length passed in.

I have tried creating a file with random characters - length of word*amount of times it needs to be inserted and then adding it to the random locations but that just led to it being appended to the end of the file.

def gen_file(word:str, frequency:int, maxlength:int):
    contents = ''
    i = 0

    while i < frequency:
        for x in range(0, maxlength):
            ran_num = random.randint(0, maxlength-1)
            if x == ran_num:
                contents = contents + word
                i = i+1
            else:
                contents = contents + random.choice(string.ascii_letters)

    file = open("new.txt","w")
    file.write(file_contents)
    file.close()

If I call the function as gen_file('hello', 3, 5000). I expect the output file to be 5000 characters long with 'hello' inserted at 3 random locations but I get an output file that ranges anywhere from 10,000 - 20,000 characters.




How can I add a code like "if I type 4, it gives me 4 numbers random, (1485),if I type lets say 6 it then it gives me 6 numbers random (178398)

How can I write a code for this problem? IF I type in the textbox any number, how can I get a random number which its length value is the same number I entered in the textbox? like: if I type 4, label1`d show me 4 numbered random. type in the textbox 4, label lets say 4598,9637 like this




Math.Random always setting random number to 0

Creating a program where a random number is generated using math.random which i have put into a function and called this function in the program to make things tidier but the random number that gets outputted is always what the integer secret_number is set to, and i am not sure how to fix this to create a random number. I would like to keep the math.random in the function and use parameters

package guessinggame3;
import java.util.Scanner; //imports scanner to read from keyboard
import java.util.ArrayList;


public class GuessingGame3 { //start of public class

static Scanner kboard = new Scanner(System.in); //calls scanner 


public static void main(String args[]) //start of main 
{

System.out.println("Welcome to the guessing game, the computer will 
generate a random number that you have to guess, good luck!"); //opening 
message explaining how to play 

int secret_number = 0;
int number_of_guesses = 0;
int user_guess ;
ArrayList<Integer> entered_numbers = new ArrayList<Integer>();


generate_random_number(secret_number); //calls he function 
generate_random_number to say the random number has been generated 




for(int i=0; i<20;i++) { // start of for loop sets user attempts to 20


System.out.println("Please make your guess"); //asks user to enter make 
their guess             
user_guess = kboard.nextInt();
number_of_guesses++; // adds on to the counter after each user guess


if(entered_numbers.contains(user_guess)) //checks if entered number = 
number stored in array
{
System.out.println("You have already entered this number"); //displays 
error message if user enters same number again
continue;
}

else 
{
entered_numbers.add(user_guess);
if (user_guess == secret_number)
System.out.println("Your guess is corret you win!");
}

if (user_guess < secret_number)
{
System.out.println("Guess is too low");
}

if (user_guess > secret_number) 
{
System.out.println("Your guess is too high");
}


System.out.println (20 - number_of_guesses + " Guesses remaining"); 
//Tells the user how many guesses they have remaining 


} //end of for loop

} //end of main

static void generate_random_number(int secret_number)  //start of function 
generate_random_number function passing secret_number as a parameter
{       
secret_number = (int)(Math.random()*100) + 1; //generates random number 
between 0 and 100
System.out.println("The computer has generated it's number"); //lets the 
user know that the random number has been generated
} //end of function generate_random_number

} //end of public class




How can I move the characters in the string randomly in C#? [duplicate]

This question already has an answer here:

How can I move the characters in the string randomly in C#?

For example:

string test = "ABCDEFG"; 

Change to DCGFAEB




How to insert a random string into the sed 's//' replace string for each line actioned?

This:

echo " " | tr ' ' '\n' | sed "s|.*|$RANDOM|"

Or this:

echo " " | tr ' ' '\n' | sed "s|.*|$(echo $RANDOM)|"

Will print a list of 5 numbers (space is replaced by newline, sed replaces each line with $RANDOM), and those 5 numbers will all be the same:

$ echo "    " | tr ' ' '\n' | sed "s|.*|$(echo $RANDOM)|"
21590
21590
21590
21590
21590

This is because the replace of $RANDOM to a random value happens only once.

What is the easiest and shortest way, preferably by only using sed, to actually print a different random number for each line. i.e. to provide some "secondary input stream" which differs for each line that sed handles?

I could do it with xargs, but I wonder if there is a way to do it with sed only.




Compare Mixed Effects Model to Fixed Effects in R

I would like to test the significance of my random intercept. So I would like to compare my mixed model: fm1 <- glmer (BinaryOutcome ~ Age + (1|Center), family='binomial', data=DF1) to my random effects model: fm2 <- glm (BinaryOutcome ~ Age, family='binomial', data=DF1)

I tried the following code: lr.test (fm1, fm2)

which gives me some errors.

Anyone any idea how to solve this issue?




jeudi 30 mai 2019

If statement always returns true [duplicate]

This question already has an answer here:

I am new to javascript and am playing around with random numbers. I made a function that should check a generated number against user input and say if it's the same or not, but it always says "correct" even though in the console it shows that the numbers are different. Below is my code. Can someone see what I am doing wrong?

 <!DOCTYPE html>
 <html>

 <head>
         <meta charset="UTF-8">
         <title>title</title>
 </head>

 <body>
         <input id="inp" value="5">
         <button id="btn">Click me!</button>
         <script>
                 function myfunc() {
                         var comp = Math.floor((Math.random() * 10) + 1);
                         var guess = document.getElementById("inp").value * 1;
                         console.log(comp, guess);
                         if (guess = comp) {
                                 alert("Correct!");
                         } else {
                                 alert("Wrong! The computer's number was " + comp);
                         }
                 }
                 document.getElementById("btn").onclick = myfunc;
         </script>
 </body>

 </html>



same numbers, different input methods, different outputs

While bubble sorting an array, it will give different outputs depending on the method of input, manually it sorts correctly, random it won't. Any ideas?

I've already tried doing the same inputs manually as it does at random but it still didn't work for random.

    valores =["20", "78", "48", "55", "4"] 

(same input in both functions)

let valores = []

function randomVals() {
    let cantidad
    valores = []

    if (rCantidad.value != '') {
        cantidad = Number(rCantidad.value)
    } else {
        cantidad = 15
    }

    for (let k = 0; k < cantidad; k++) {
        valores.push(((Math.random()) * 100).toFixed(0))
    }
    console.log(valores)
}


function agregarValor() {

    let val = Number(valor.value)

    valores.push(val)

    console.log(valores)

}

expected sorted output:

     valores=[4, 20, 48, 55, 78]

sorted output given while using

      randomVals() valores=["20", "4", "48", "55", "78"]




How do I generate a predictable random stream in heirachy in c#?

I am making a procedural game with heirachy.

So object A will have 10 children. Each child will have 10 children and so on.

Now suppose I want to give each child a random colour, and a random position (assume these are given by integers).

Therefor let X be the "ID" of an object. Let COLOUR and POSITION be enums of type PROPERTY.

Then I want to generate random integers:

int GenerateRandomInteger(PROPERTY P, int childNumber);

So I can use:

int N = parentObject.GenerateRandomInteger(COLOUR, 7);

for example.

Any ideas how to go about this?




Known differences in boost random output from 1.58 to 1.67?

I am working with some legacy code I didn't write that generates random data. The output has changed after it was updated to 1.67 boost from 1.58. Normally reproducible output happens by a fixed seed key. But they are now different between new and old versions.

The boost random distributions used include uniform_int, uniform_real, exponential_distribution and normal_distribution. Does anyone have specific knowledge that one of those or more is now different wrt the boost versions I've mentioned?

I may have to write a simple test prog to ascertain this for sure.




Attacking weak PRNG Math.round(Math.random() * 30D)

Is it possible for an attacker to predict, following a random generator of the form Math.round(Math.random() * 30D), with a sufficient number of values? I know that the Math.random is a weak PRNG, but does rounding up the value not prevent brute force attack or analysis (as there are many on this PRNG)? And if that does not stop, how could the attacker proceed? Thank you in advance for your answer.




Generate a random fake email body with HTML text [on hold]

I need to generate a ton of fake emails for some testing. I'm using Bogus for most of the message properties, but I can't seem to find a library that can help me generate a random fake HTML-formatted email body. Bogus can handle plenty of lorem-ipsum text, but I need it to have HTML formatting. Anyone know of a library or public API that can do this?




How to Determine typical rate of progression with haphazardly collected data?

We are studying visual acuity (VA) in extant patient records. Some patients were tested once. Some patients many times. All at different ages. All have the same disease.

We would like to use these age vs. VA data to determine the typical course of progressive loss of VA in the population. What is the right approach to doing this, mindful that individuals may progress at different rates, but also that there must be some "typical" course.

SPSS preferred (could do MATLAB or something else in a pinch).

Thanks!

Random effects mixed linear modeling seems right, but how to frame it?




Simple method to reverse engineer a PRNG?

I have a pseudo random binary sequence that I'd like to reverse engineer. It's being generated by a radio IC that I need to communicate with so is almost certainly an LFSR of some description. I'd like to work out the seed and polynomial used.

Is there a simple method?

The sequence is 8-bit numbers and it repeats every 127 bytes.

Here's the full 127 byte sequence:

0x32,0x20,0x49,0xA7,0xB8,0x7F,0x1D,0x8A,0x5F,0x54,0x2D,0xE7,0x2B,0x30,0x6D,0x74,0x64,0x40,0x93,0x4F,0x70,0xFE,0x3B,0x14,0xBE,0xA8,0x5B,0xCE,0x56,0x60,0xDA,0xE8,0xC8,0x81,0x26,0x9E,0xE1,0xFC,0x76,0x29,0x7D,0x50,0xB7,0x9C,0xAC,0xC1,0xB5,0xD1,0x91,0x02,0x4D,0x3D,0xC3,0xF8,0xEC,0x52,0xFA,0xA1,0x6F,0x39,0x59,0x83,0x6B,0xA3,0x22,0x04,0x9A,0x7B,0x87,0xF1,0xD8,0xA5,0xF5,0x42,0xDE,0x72,0xB3,0x06,0xD7,0x46,0x44,0x09,0x34,0xF7,0x0F,0xE3,0xB1,0x4B,0xEA,0x85,0xBC,0xE5,0x66,0x0D,0xAE,0x8C,0x88,0x12,0x69,0xEE,0x1F,0xC7,0x62,0x97,0xD5,0x0B,0x79,0xCA,0xCC,0x1B,0x5D,0x19,0x10,0x24,0xD3,0xDC,0x3F,0x8E,0xC5,0x2F,0xAA,0x16,0xF3,0x95,0x98,0x36,0xBA




Android Studio program was working, and now it doesnt

I am facing an error on android studio. I have been working on an assignment and for the past week, with everything going according to plan. Today I added some small code and the build executes, however, it force closes the app. I tried running a previous version (which I am SURE that worked) and it's giving me the same error in logcat. The error is:

2019-05-30 13:10:01.626 28770-28770/? E/Zygote: isWhitelistProcess - 
Process is Whitelisted
2019-05-30 13:10:01.629 28770-28770/? E/Zygote: accessInfo : 1
2019-05-30 13:10:02.768 28770-28770/com.example.myapplication 
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 28770
    java.lang.RuntimeException: Unable to start activity 

ComponentInfo{com.example.myapplication/ 
com.example.myapplication.fingerprint}: 
    android.view.InflateException: Binary XML file line #70: Binary XML 
file 
    line #70: Error inflating class Button
        at 
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3115)
        at 
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3258)
        at     

android.app.servertransaction.LaunchActivityItem.execute         
(LaunchActivityItem.ja    va:78)
        at 

android.app.servertransaction.TransactionExecutor. 
executeCallbacks(TransactionExecutor.java:108)
        at 
android.app.servertransaction.TransactionExecutor. 
execute(TransactionExecutor.java:68)
        at 
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1955)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7073)
        at java.lang.reflect.Method.invoke(Native Method)
        at 
com.android.internal.os.RuntimeInit$MethodAndArgsCaller 
.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)
     Caused by: android.view.InflateException: Binary XML file line #70: 
Binary XML file line #70: Error inflating class Button
     Caused by: android.view.InflateException: Binary XML file line #70: 
Error inflating class Button
     Caused by: android.content.res.Resources$NotFoundException: Drawable 
android:color/tertiary_text_light with resource ID #0x1060011
      Caused by: android.content.res.Resources$NotFoundException: File 
res/color/tertiary_text_light.xml from drawable resource ID #0x1060011
        at android.content.res.ResourcesImpl.loadDrawableForCookie 
        (ResourcesImpl.java:898)
         at 
android.content.res.ResourcesImpl.loadDrawable(ResourcesImpl.java:677)
        at android.content.res.Resources.loadDrawable(Resources.java:912)
        at 
android.content.res.TypedArray.getDrawableForDensity(TypedArray.java:955)
        at android.content.res.TypedArray.getDrawable(TypedArray.java:930)
        at android.view.View.<init>(View.java:5442)
        at android.widget.TextView.<init>(TextView.java:1118)
        at android.widget.Button.<init>(Button.java:181)
        at android.widget.Button.<init>(Button.java:156)
        at android.support.v7.widget.AppCompatButton.<init>        
        (AppCompatButton.java:71)
        at android.support.v7.widget.AppCompatButton.<init>        
        (AppCompatButton.java:67)
        at android.support.v7.app.AppCompatViewInflater.createButton 
        (AppCompatViewInflater.java:187)
        at android.support.v7.app.AppCompatViewInflater.createView 
        (AppCompatViewInflater.java:110)
        at android.support.v7.app.AppCompatDelegateImpl.createView 
        (AppCompatDelegateImpl.java:1266)
        at android.support.v7.app.AppCompatDelegateImpl.onCreateView 
        (AppCompatDelegateImpl.java:1316)
        at 
android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:811)
        at 
android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:769)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:902)
        at     
android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:863)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:554)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:461)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:383)
        at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
    at android.support.v7.app.AppCompatActivity.setContentView 
    (AppCompatActivity.java:140)
        at com.example.myapplication.fingerprint.onCreate 
        (fingerprint.java:58)
        at android.app.Activity.performCreate(Activity.java:7327)
        at android.app.Activity.performCreate(Activity.java:7318)
        at android.app.Instrumentation.callActivityOnCreate 
        (Instrumentation.java:1275)
        at android.app.ActivityThread.performLaunchActivity             
        (ActivityThread.java:3095)
        at 
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3258)
        at android.app.servertransaction.LaunchActivityItem.execute 
        (LaunchActivityItem.java:78)
2019-05-30 13:10:02.773 28770-28770/com.example.myapplication 
E/AndroidRuntime:     at 
android.app.servertransaction.TransactionExecutor.executeCallbacks 
(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute 
(TransactionExecutor.java:68)
        at 
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1955)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7073)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run 
        (RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)
     Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file 
     line #18: <item> tag requires a 'drawable' attribute or child tag 
     defining a drawable
        at 

     android.graphics.drawable.StateListDrawable.inflateChildElements 
    (StateListDrawable.java:190)
     at 
    android.graphics.drawable.StateListDrawable.inflate 
    (StateListDrawable.java:122)
        at 
android.graphics.drawable.DrawableInflater.inflateFromXmlForDensity 
(DrawableInflater.java:146)
        at android.graphics.drawable.Drawable.createFromXmlInnerForDensity 
(Drawable.java:1359)
        at android.graphics.drawable.Drawable.createFromXmlForDensity 
(Drawable.java:1318)
        at android.content.res.ResourcesImpl.loadDrawableForCooki 
e(ResourcesImpl.java:879)

This is my layout

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout         
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/coordinatorLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/darker_gray"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBarLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:theme="@style/AppTheme.AppBarOverlay"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="427dp"
            android:layout_height="wrap_content"
            android:background="@android:color/background_dark"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <TextView
        android:id="@+id/txt_name"
        android:layout_width="169dp"
        android:layout_height="22dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="76dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:text="Enter Name"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.513"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/appBarLayout" />

    <EditText
        android:id="@+id/eT_name"
        android:layout_width="212dp"
        android:layout_height="37dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="12dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.601"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/txt_name" />

    <TextView
        android:id="@+id/txt_surname"
        android:layout_width="169dp"
        android:layout_height="21dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="64dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:text="Enter Surname"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/txt_name" />

    <EditText
        android:id="@+id/eT_surname"
        android:layout_width="212dp"
        android:layout_height="37dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="12dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.601"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/txt_surname" />

    <Button
        android:id="@+id/btn_loadData"
        android:layout_width="172dp"
        android:layout_height="43dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="64dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:text="Load Data"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.506"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/eT_surname" />

    <TextView
        android:id="@+id/txt_savedData"
        android:layout_width="219dp"
        android:layout_height="102dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="132dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />


</android.support.constraint.ConstraintLayout>




Is PHP gmp_random_range function from GMP extension cryptographically secure?

This is my first question, so excuse my clumsyness (and I am not a programmer - so even more excuses). It's not a problem but a question. I use PHP to write a software that generates random combinations of characters. For this I need arbitrary length integers random generation. So I use GMP extension and especially gmp_random_range(). But I need to prove with a link for example that it is cryptographically secure. Or at least it is enough random. GMP random functions use seed (gmp_random_seed ), and if I don't set a seed everything looks random enough. So, I suppose when I don't set the seed explicitly it takes it from some reliable random source. I could not find something clearly stating such thing. Any help is appreciated, thank you in advance.




mercredi 29 mai 2019

Assign an individual in a dataset to a particular state based on predetermined probabilities in R

I have data which looks like this

df <- data.frame(
age_grp10 = rep(c("00-09", "10-19", "20-29", "30-39", "40-49", "50-59", "60-    69", "70-79", "80-89"), 2),
sex = c(rep("M", 9), rep("F", 9)),
prob_arr = round((runif(18, min = 0.11, max = 2.50)), digits = 2),
prob_dep = round((runif(18, min = 0.11, max = 2.50)), digits = 2)
)

This dataset gives the probability of a person, by age and gender, arriving or departing in a calendar year.

Then I have population level data, which looks like this

  pop_df <- data.frame(
  uniq_ID = c("AFG1234", "WED1234", "POJ1234", "DER234", "QWE1234", "BGR1234", "ABC1234", "DSE1234", "UHJ1234", "POI234",
          "EDC1234", "BGT1234", "MJI1234", "WEX1234", "FGH1234", "UJN1234", "LOK1234", "DRT1234", "URD1234", "MVR1234"),
  age_grp10 = c("50-59", "40-49", "20-29", "40-49", "00-09",  "50-59", "30-39", "70-79",  "60-69", "40-49",
            "80-89", "10-19", "30-39", "30-39", "50-59", "70-79", "00-09", "70-79", "20-29", "20-29"),
  sex = c("M", "M", "F", "M", "F", "F", "F", "M", "F", "M", "F", "F", "M", "M", "M", "M", "M", "F", "M", "F"))

In this population dataset, each row is an individual, for about 5 million people. It shows their age and gender, and unique ID number. Based on the probabilities in the first dataframe (df), I would like to assign arrival and departure status to the individuals in the population dataframe (pop_df).

My desired output would look like

pop_df <- pop_df %>%
left_join(df) %>%
mutate(Arrived = c(0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0),
     Departed = c(1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))

In this last dataset, the values of Arrived and Departed are dependent on the probabilities in the df dataframe. So XX% of males aged 0-9 years would be assigned arrival status, based on the value of prob_arr in the df dataframe.

Thanks for your help




How to choose random value from array, then choose randomly again excluding the value just chosen? (Python)

I am trying to create a combination of unique phrases to make a sentence and want to randomly select a phrase length from S (only needs to happen 1 time), and then randomly select first a J value, and then a random Q value, but I do not want the same value selected from J or S selected. How can I do this?

Here is what some of the sample outputs look like:

I3 and I1 I4 not I5 I5 or I4 and I3 not I3

Q=("but","why","okay")
J=("J1","J2","J3","J4","J5")
S=[(J), (J,Q,J), (J,Q,J,Q,J),(J,Q,J,Q,J,Q,J)]

' '.join([random.choice(i) for i in random.choice(S)])




Verifying PRBS 7 sequence using only 2 bits of the data

I have a 8 bit PRBS 7 Generator, I need to use only 2 bits from LSB from the generated PRBS 7 data, in my checker side to verify if the pattern is following prbs sequence or not.

There are Two Components; 1 PRBS Generator and 1 PRBS Checker

PRBS Generator is going to generate 8 bits of PRBS 7 Sequence data_gen[7:0];

PRBS CHECKER is going take data_gen[1:0] and check if the sequence follows prbs 7 or not.




How to speed up drawing plots in Matplotlib?

I'm playing with random walk, I have two points. First one is walking randomly, second one is trying to escape from his area, which is given by formula e^(-t), where t is the distance between the two points. In my opinion it is not a difficult program, but it takes about a minute to run it with hundred points to calculate, so I'm asking you to help me find some way to speed it up and explain it to me.

import numpy as np
import matplotlib.pyplot as plt


def f(x, y, zx, zy):
    return np.exp(-np.sqrt((x-zx)**2+(y-zy)**2))


x = y = np.linspace(-100, 100, 1000)
X, Y = np.meshgrid(x, y)

fig, ax = plt.subplots(1, 1, figsize=(12, 6))
#random picking first location for two points
loksx = [np.random.randn(), ]
loksy = [np.random.randn(), ]
lokzx = [np.random.randn(), ]
lokzy = [np.random.randn(), ]
for i in range(100):
    lokzx.append(np.random.randn()+lokzx[-1])
    lokzy.append(np.random.randn()+lokzy[-1])
    nsx = np.random.randn()
    nsy = np.random.randn()
    #checking if the next step has smaller value than the last one 
    if f(loksx[-1]+nsx, loksy[-1]+nsy, lokzx[-1], lokzy[-1]) < f(loksx[-1], loksy[-1], lokzx[-1], lokzy[-1]):
        loksx.append(nsx+loksx[-1])
        loksy.append(nsy+loksy[-1])
Z = []
for i in range(len(lokzx)):
    Z.append(f(X, Y, lokzx[i], lokzy[i]))
ax.plot(lokzx[0], lokzy[0], 'y,',markersize=1)
ax.plot(loksx[0], loksy[0], 'w,', markersize=1)
ax.plot(lokzx[1:-1], lokzy[1:-1], 'g,',markersize=1)
ax.plot(loksx[1:-1], loksy[1:-1], 'b,', markersize=1)

ax.plot(loksx[-1], loksy[-1], 'k,', markersize=1)
ax.plot(lokzx[-1], lokzy[-1], 'r,',markersize=1)
for i in range(len(Z)):
    ax.contourf(X, Y, Z[i], 20, cmap='RdGy', alpha=0.01)
ax.plot()
ax.set_aspect('equal')
plt.show()




How to randomly fill the rows of the matrix?

I have a matrix with n-rows and n-columns. I need to make sure that the numbers in each row are unique.

let matrix = [];
let matrixRows = 3;
let matrixColumns = 5;

for ( let i = 0; i < matrixRows; i++ ) {
    matrix[ i ] = [];
    let j = 0;
    while (j < matrixColumns) {
        matrix[ i ][ j ] = Math.floor(Math.random() * 5) + 1;
        j++;
    }
}

console.log( matrix.join('\n') );

It should look something like this

"1,2,3,4,5 \\ here is line break (new row)
1,4,2,5,3 \\ here is line break (new row)
5,4,2,3,1"




A teacher turned coder - need help generating random sheets that include strings, images and hopefully equations

The purpose of the workbook will be to randomly generate 5-10 questions for school children to attempt.

It will need a questions sheet and an answer sheet, I have already managed to find an appropriate one that randomly generates strings but as math questions get more complicated we need images and/or equations.

You will be seriously helping the education sector is you help us with this!

The code below is the closest thing I have found that will generate random images but means each question has to be screenshotted and put into the same folder.

An added complication is that this needs to work on school computers that has security that refrains from showing the file/folder directory so the directory needs to be defined as the folder the workbook is in.

Public Function PictureLookup(Value As String, Location As Range, Index As Integer)

Application.Volatile

Dim lookupPicture As Shape Dim sheetName As String Dim picTop As Double Dim picLeft As Double

sheetName = Location.Parent.Name

'Delete current picture with the same Index if exists For Each lookupPicture In Sheets(sheetName).Shapes If lookupPicture.Name = "PictureLookup" & Index Then lookupPicture.Delete End If Next lookupPicture

'Get position of cell calling the UDF picTop = Location.Top picLeft = Location.Left

'Add the picture in the right location Set lookupPicture = Sheets(sheetName).Shapes.AddPicture _ ("C:\Users\marks\Documents\Flags\" & Value & ".png", msoFalse, msoTrue, picLeft, picTop, -1, -1)

'change the picture name lookupPicture.Name = "PictureLookup" & Index

PictureLookup = ""

End Function




How can I pick random value in matrix using conditions

Hi I have to extract some data from my matrix whitout looping using numpy

here is a given matrix at the end of my code:

[[1 3][1 --][2 3][3 --][1 --][3 --][2 --][1 --][1 --][1 3]]

At the end I must get one matrix like this :

[[1 ] [1 ] [3 ] [3 ] [1 ] [3 ] [2 ] [1 ] [1 ] [3 ]]

I would like to select random value when there is no value: -- (exemple [1 3]) and pick the only value available when there is -- value (exemple [1 --]).

I must avoid using loop and all the result are randomly generated between 1 and 3.

Thank you for your help! np.count_nonzero(Resultat, axis=1)




How to get successive random subsamples?

I'm aiming to randomly take a sample of items from a list and then take a sample from that new list until only one item is left in the list.

Code:

from random import sample

exampleList = ["Gary","Kerry","Larry","Bob","Frank","Joshua"]

def reduce(List):
    newList = sample(List, random.randint(1, len(List)))
    return newList

reduce(reduce(reduce(reduce(exampleList)))) #<-- I want to avoid doing this#




Random number generator doesn't produce expected numbers within a given range using values from input fields [duplicate]

This question already has an answer here:

I'm trying to generate a random number between two given values. I'm able to produce this with a pretty standard little function, however when I try to set the maximum and minimum values through an input field, I get some unexpected results.

This is using jQuery, which isn't necessary for this particular function but is needed for the larger project.

Here's an example of what I'm finding:

https://jsfiddle.net/u2k41hzd/

function randomNumber(min, max) {
    points = Math.floor(Math.random() * (max - min + 1) + min);
}

$( "button" ).on( "click", function ( event ) {
    minPoints = $( ".min-points" ).val();
    maxPoints = $( ".max-points" ).val();
    randomNumber(minPoints, maxPoints);
    $(".random").html(points);
});

In the case of the minimum number being 1 and the maximum being 6, I would expect to get numbers between 1 and 6. However, I get numbers between 0 and 5.

If the minimum number is 2 and the maximum 6, I would expect to get numbers between 2 and 6, but get numbers between 0 and 4. Passing in 3 and 6 gives numbers between 0 and 3, and so on.

Ignoring the input values and hard coding them instead seems produce expected results with no issue. Essentially I'm just unsure as to why the input values are behaving as they are. I'm sure I've just misunderstood something or made a mistake somewhere, but I've not been able to determine the reason!




Writing a Factory method for STL random number generators

I'm trying to provide an interface — through a config file — for my users to choose a distribution for some of the parameters that they are using. I would like to use STL random number generator algorithms for this purpose.

Let's assume that my program reads a JSON from a command line. For the JSON provided below, the program needs to realize that it should generate a random number from the normal distribution with given mean and standard variation. (I'm using the same parameter names as STL library for clearance.)

{
    "dist": "normal_distribution",
    "mean": 0.1,
    "stddev": 0.5
}

So far, I can parse the JSON easily, and use each distribution's param_type to initialize the distribution. I use the name to decide which distribution to decide the param_type and the distribution.

What I don't know is how to implement this nicely. I know that I should provide some sort of factory method for this, pass the JSON, and spit out a function or a class. If I want to return an instance of a class, let's say a unique_ptr of the generator, I need to define an abstract class, e.g., RandDist and write some sort of adaptor to incorporate my input, .... I generally don't need a lot from the class, just a gen() method should be enough.

I'm wondering if anyone have thoughts on this. Or, if anyone knows a library that can do this.

P.S. Input doesn't have to be a JSON object, any hash table would work per se.




How to randomly permutate string without adjacent equal elements

So, I have an example string like "aaabbbc", i would like to shuffle it randomly but no two consecutive letters should be same in the result. The output should be "abababc" or "cbababa" or "abacbab" etc.

I've tried a code using PriorityQueue, its solve the problem, but only one way not randomly generate many ways to shuffle my string with no two consecutive. Below is code that i've used.

    int n = str.length();
    int[] count = new int[MAX_CHAR];

    for (int i = 0; i < n; i++) {
        count[str.charAt(i) - 'a']++;
    }

    PriorityQueue<Key> pq = new PriorityQueue<>(new KeyComparator());
    for (char c = 'a'; c <= 'z'; c++) {
        int val = c - 'a';
        if (count[val] > 0) {
            pq.add(new Key(count[val], c));
        }
    }
    str = "";

    Key prev = new Key(-1, '#');
    while (pq.size() != 0) {
        Key k = pq.peek();
        pq.poll();
        str = str + k.ch;

        if (prev.freq > 0) {
            pq.add(prev);
        }

        (k.freq)--;
        prev = k;
    }

    if (n != str.length()) {
        return "";
    } else {
        return str;
    }

I am stuck when trying to make it randomly by that algorithm. The result i wanted is dynamic output like i described above. Thanks




Different sample results using set.seed command?

I want to use the sample function after setting set.seed with a fixed number. Unfortunately I obtain different results from a edx website. I'm wondering why I get different results. In the website they obtain 0.2706222. On my computer I obtain 0.3293778

I realized that the problem came from my sample function which do not returns me the same sample. Setting set.seed(1) and using sample(seq(1:5000), 3). My computer returns 1017 4775 2177 whereas it "should be" 1328 1861 2864

library(downloader) 
url <- "https://raw.githubusercontent.com/genomicsclass/dagdata/master/inst/extdata/femaleControlsPopulation.csv"
input_file <- basename(url)
download(url, destfile=input_file)
x <- unlist( read.csv(input_file) )
set.seed(1)
my_sample <- sample(x,5)
abs(mean(my_sample)-mean(x))

The expected output of the code computing the mean should be 0.2706222.




mardi 28 mai 2019

crypto/rand generate the same results when running go test multiple times

In go, crypto/rand is cryptographically secure. So why does it generate the same result when I run go test for the same code for multiple times?

Associated code: readLen, err := io.ReadAtLeast(rand.Reader, buff, buffLen) fmt.Println(buff)




Trying to toggle random LEDs with a XOR and bit shift operator

For a model railroad project, I am trying to toggle LEDs by using a random number generator (rand()) which produces x and then shifting 1 to the left by x on the LATC register on a PIC16F15325. (I am an enthusiastic hobbyist, but still with so much to learn, completely self-taught.) I am using XC8 and PICkit 3.

I am using the 16F15325 pic, and, in my mind, the following code should (A) generate a random number (pseudo is ok) between 0 and 5 (this is x) and (B) toggle bits C0 through C5 (each connected to an LED in the LATC register) by shifting 1 by x bits (i.e., 0 to 5) and by applying an XOR to that pin. Given that this is in an infinite loop, then each time the code loops, it should toggle at least one LED. This works about 90% of the time, but sometimes it doesn't result in a toggle, and it's driving me nuts.

#include <xc.h>
#include <stdint.h>         /* For uint8_t definition */
#include <stdbool.h>        /* For true/false definition */
#include "configs.c"

void main(void) {

InitProgram();   // THIS SETS UP THE TRIS AND SETS THE C PORT TO OUTPUT

//  DECLARE AND SET VARIABLES

int x;             //  GENERAL PURPOSE VARIABLE TO USE ON THE FLY

LATC = 0b00111111;

while(1)
{
    x = rand() % 6;   //  SHOULD GENERATE 0 THROUGH 5 B/C NO "+ 1"

    LATC = LATC ^ 1 << x;

    //  I HAVE ALSO TRIED LATC = LATC ^ 1 << (char) x;

    //  THERE IS A ONE SECOND DELAY HERE

 }
}

As noted, this very often works on each run through the loop, but about 10% of the time, no LED will toggle. 90% of the time, one of the LEDs toggles.




How to run a simulation to find the average value of a portfolio

Having run my np.random numbers through a Cholesky decomposition, I'm having a problem using those numbers in a loop find the value of the assets

I have used a for loop, but it continuously gives an error. I want the initial value "s0" to continually multiply for 12 times. (Finding the 12-month return) and get the average of those 10000 simulations of the portfolio.

import numpy as np
import pandas as pd

    def cholesky(rho):
     L = [[0.0] * len(rho) for b in range(len(rho))]
    for i in range(len(rho)):
       for j in range(i+1):
        s = sum(L[i][k] * L[j][k] for k in range(j))
        L[i][j] = ((rho[i][i] - s)**(1/2)) if (i == j) else \
                  (1.0 / L[j][j] * (rho[i][j] - s))
return L

rho = [[1],[0.5, 1],[0.1, 0.8,1]] 
a = cholesky(rho)

np.random.seed(42)
normalrands=np.random.normal(0,1,[10000,3])

corrnormalrands=[]
for i in range(0,len(rho)):
    corrrow=[]
    for j in range (0,10000):
        if i ==0:
             corrrow.append(a[0][0]*normalrands[j,0])
        elif i==1:
             corrrow.append(a[1][0]*normalrands[j,0]+a[1][1]*normalrands[j,1])
        else:
             corrrow.append(a[2][0]*normalrands[j,0]+a[2] [1]*normalrands[j,1]+a[2][2]*normalrands[j,2])

     corrnormalrands.append(corrrow)


def portfoliostock(s0,mu,sigma,months):
 x = corrnormalrands
 price=[]
 for i in range [0,10000]:
     stockvalue=s0
     for j in range (0,months):
         stockvalue=stockvalue*np.exp(mu+sigma*x(i,j))
         price.append(stockvalue)

         return price


stocks =portfoliostock(50000,0.005833,0.057733,12)

print ("stock value =" , np.mean(stocks))


 for i in range corrnormalrands[0,10000]:
                             ^
 SyntaxError: invalid syntax




Function for finding ROC score of a feature after randomly shuffling training target data is not acting random

I am trying to write a function that will give the average ROC score of 10 logistic regression classifiers that are each trained on a different random shuffling of the training target data for one feature at a time. (for the purpose of comparing against the non shuffled roc score) But I am getting very strange and non random results for each roc score.

I have tried using np.random.shuffle instead of pd.sample and got the same result

from sklearn import metrics
from sklearn.linear_model import LogisticRegression

def shuffled_roc(df, feature):
    df = df.sample(frac=1, random_state=0)
    x = df[feature][np.isfinite(df[feature])].copy()
    y = df['target'][np.isfinite(df[feature])].copy()

    x_train = x.iloc[:int(0.8*len(x))]
    y_train = y.iloc[:int(0.8*len(x))]

    x_test = x.iloc[int(0.8*len(x)):]
    y_test = y.iloc[int(0.8*len(x)):]

    y_train_shuffled = y_train.sample(frac=1).reset_index(drop=True)

    rocs = []
    for i in range(10):
        y_train_shuffled = y_train_shuffled.sample(frac=1).reset_index(drop=True)
        lr = LogisticRegression(solver = 'lbfgs').fit(x_train.values.reshape(-1,1), y_train_shuffled)

        roc = metrics.roc_auc_score(y_test, lr.predict_proba(x_test.values.reshape(-1,1))[:,1])
        rocs.append(roc)
    print(rocs)
    return np.mean(rocs)
shuffled_roc(df_accident, 'target_suspension_count')

I expect 10 different values for the 10 roc scores but instead I get

[0.7572317596566523, 0.24276824034334765, 0.24276824034334765, 0.7572317596566523, 0.7572317596566523, 0.7572317596566523, 0.24276824034334765, 0.7572317596566523, 0.7572317596566523, 0.24276824034334765]




How to store a variable for each iteration of a loop?

Currently, I'm trying to store my latitude matrix for each iteration of a loop in my code.

Currently, I'm trying to store the variable as follows:

 latitude[p] <- lat

with latitude being the variable I'm trying to store in, p being the loop number, and lat being the randomly generated latitude matrix.

The following is my reproducible code:

 p=0
 latitude = 0
 while(p<5) 
   {

   p = p + 1

   lat <- round(rnorm(n=50, m = 55, sd = 8),0)
   lon <- round(rnorm(n=50, m = 76, sd = 20),0)
   no2 <- round(rnorm(n=100, m = .3, sd = .1),2)

   partial_data <- data.frame(lat,lon,no2)
   coordinates(partial_data) = ~lat+lon
   spplot(partial_data,'no2')

   latitude[p] <- lat
 }

Currently, I'm getting the error:

 In latitude[p] <- lat :
   number of items to replace is not a multiple of replacement length

and when I call "latitude[1]" I get a single number as output. I would like a full random matrix generated for the loop as output.

Thank you!




Generating random sparse matrix R

I am dealing with large matrices - on the order of 10^8 columns and 10^3-10^4 rows. Since these matrices are only ones and zeros, I think the sparse construction in the Matrix package is appropriate. However, I don't see a way to generate a random matrix like in the example below. Note that non-zero entries are defined by the column probabilities col_prob.

set.seed(1)#For reproducibility
ncols <- 20
nrows <- 10
col_prob <- runif(ncols,0.1,0.2)
rmat <- matrix(rbinom(nrows*ncols,1,col_prob),
       ncol=ncols,byrow=T)

Certainly I can convert rmat into a sparse matrix:

rmat_sparse <- Matrix(rmat,sparse=T)

However, I would like to generate the sparse matrix in one step. I'm not sure that the function Matrix::rsparsematrix can accomplish this.

Any thoughts?




i have a problem with a function using random

am working on a project of minesweeper but the problem is when i use this code to fill the array but when i use it it gives me error on the line of checking (if)

i've been trying to fix it for a while but for some reason it is not working

   int i, random,random2;
 srand(time(NULL));
        for (i = 0; i < minenum; i++)
    {
        random = rand() % (size);
                printf(" %d \n",random);
        random2=rand()%(size);
                printf(" %d \n",random2);
        if(board[random][random2]=='X') i--;
        printf("qwewqewqe");
        board[(int)random][(int)random2] = 'X';
                printf("%d \n",i);

    }
}

i expect it working without crashing!




How would I put a String of numbers Separated by commas into an Integer array?

I'm working on a project for my computer science course and in short need to turn a String that looks like this "13,24,5,25,17,10,24,20,23,6,25,18,16,21," to an Integer Array. Thanks for Any comments in advance. I'm using JAVA




Boost Random Number Not Change

I have some problem when generating random number with boost library in CPP. When I try printout random number, the value return same value. Here is my code.

for(int i = 0; i < TOTAL_PARTICLES; i++) {
            boost::random::mt19937 engine(static_cast<unsigned int>(std::time(0)));                    
            randn = boost::bind(boost::random::uniform_real_distribution<>(-2.5, 2.5), engine);                            
            cout << "Random : " << randn() << endl;
        }




Random number generator in VHDL

I'm designing a test bench and I need to create a random sequence of bits for one of the system's inputs which is normally controlled by the user. I also want this sequence of bits not being in the same order every time I run the simulation.

I cannot use a PRNG since its initial state will be predefined meaning it while produce the same numbers every time. I also used the uniform function but I had the same issue.

RAND_GEN : process(clk) is
    variable seed1, seed2 : positive := 1;
    variable re           : real;
begin
    if rising_edge(clk) then
        uniform(seed1, seed2, re);
        if (re < 0.5) then
            rand_bit <= '0';
        else
            rand_bit <= '1';
        end if;
    end if;
end process;

Is there any alternatives for this problem?




Does std::discrete_distribution() allow zero weights?

Can std::discrete_distribution be used with some zero weights, assuming that at least one positive weight was given? The items with zero weights should simply never be sampled.

The fact that it appears to work on my machine does not give me confidence that it will work on all systems.

Example:

std::discrete_distribution<> dd({1.0, 2.0, 0.0, 3.0});




Hello, can someone help me to add fisher yates shuffle on my code?

this is my code , i don't know where to put the fisher yates shuffle algorithm in my code. can you help me?

i'm using firebase for my database. the button actually is 4 button not 2 button, but i cut it because it's to long to post in here.

public class AlfabetQuizActivity extends AppCompatActivity {

Button c1,c2;
TextView question, score;
private String answer;
private int skor=0, count=0;
private DatabaseReference qref, aref, c1ref, c2ref;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_alfabet_quiz);

    c1 = (Button) findViewById(R.id.choice1Button);
    c2 = (Button) findViewById(R.id.choice2Button);

    question = (TextView) findViewById(R.id.questionTxt);
    score = (TextView) findViewById(R.id.scoreTxt);

    updateQuestion();

    c1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(c1.getText().toString().equals(answer)){
                Toast.makeText(getApplicationContext(), "Jawaban Benar", Toast.LENGTH_SHORT).show();
                c1.setBackgroundColor(Color.GREEN);
                skor = skor +1;
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        c1.setBackgroundColor(Color.parseColor("#F9CDAD"));
                        updateQuestion();
                        updateScore(skor);
                    }
                },1500);
            }
            else {
                Toast.makeText(getApplicationContext(), "Jawaban Salah", Toast.LENGTH_SHORT).show();
                c1.setBackgroundColor(Color.RED);

                if(c2.getText().toString().equals(answer)){
                    c2.setBackgroundColor(Color.GREEN);
                }

                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        c1.setBackgroundColor(Color.parseColor("#F9CDAD"));
                        c2.setBackgroundColor(Color.parseColor("#F9CDAD"));
                    }
                },1500);
            }
        }
    });

    c2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(c2.getText().toString().equals(answer)){
                Toast.makeText(getApplicationContext(), "Jawaban Benar", Toast.LENGTH_SHORT).show();
                c2.setBackgroundColor(Color.GREEN);
                skor = skor +1;
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        c2.setBackgroundColor(Color.parseColor("#F9CDAD"));
                        updateQuestion();
                        updateScore(skor);
                    }
                },1500);
            }
            else {
                Toast.makeText(getApplicationContext(), "Jawaban Salah", Toast.LENGTH_SHORT).show();
                c2.setBackgroundColor(Color.RED);

                if(c1.getText().toString().equals(answer)){
                    c1.setBackgroundColor(Color.GREEN);
                }

                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        c1.setBackgroundColor(Color.parseColor("#F9CDAD"));
                        c2.setBackgroundColor(Color.parseColor("#F9CDAD"));
                    }
                },1500);
            }
        }
    });
}

private void updateScore(int skorr){
    score.setText(""+ skor);
}

private void updateQuestion(){

    qref = FirebaseDatabase.getInstance("https://learnhangul-ed611.firebaseio.com/").getReference("AlfabetQuiz/");
    qref.child(count+"/question").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            String q = dataSnapshot.getValue(String.class);
            question.setText(q);
        }
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

    c1ref = FirebaseDatabase.getInstance("https://learnhangul-ed611.firebaseio.com/").getReference("AlfabetQuiz/");
    c1ref.child(count+"/choice1").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            String ch1 = dataSnapshot.getValue(String.class);
            c1.setText(ch1);
        }
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

    c2ref = FirebaseDatabase.getInstance("https://learnhangul-ed611.firebaseio.com/").getReference("AlfabetQuiz/");
    c2ref.child(count+"/choice2").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            String ch2 = dataSnapshot.getValue(String.class);
            c2.setText(ch2);
        }
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

    aref = FirebaseDatabase.getInstance("https://learnhangul-ed611.firebaseio.com/").getReference("AlfabetQuiz/");
    aref.child(count+"/answer").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            answer = dataSnapshot.getValue(String.class);

        }
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
    count = count +1;

}

}

thankyou for helping me.




lundi 27 mai 2019

C++: How can I generate random non-zero intergers in close interval?

I need to create randoms edges in a weighted graph with int non-zero weight. I can't find any solution to create the random generator in c++ able to me return an int with some non-zero value in a range.

my following function can be illustrate better my problem:

/* Non-zero random integer numbers generator in closed interval */
#include <cstdlib>
#include <ctime>

int randomize(int upper_limit, int lower_limit){
    srand(time(NULL));
    int x = 0;
    do
    { 
        x = rand() ...what I need to do?
    }
    while(resp == 0);

    return x;
}




How to create a publicly visible, provably random seed ahead of time?

Imagine that you are hosting a debate with n participants and you wish to split them in half in a completely random fashion.

One might do so by creating a list of participants, randomly shuffling that list, then forcing the first n/2 participants to debate as a team.

If this debate was particularly important, however, we would want to ensure that the teams we have created are provably random in a way that is publicly visible. We want to be able to show that the teams we have created are not the direct result of any human's decisions. Would there be a way to do this?

I believe this problem boils down to the issue of creating a seed for a random number generator that is based on the state of the world at a particular time, but I'm not sure. Is this a problem software engineers have tackled before, and is there an API out there for this?




How to write a random group generator in java using else-if statements?

I have to code a program that allows the user to choose between two task: a random group generator, and a task that parses and counts an input sentence by word. I am really confused on how to go about it. The instructions are: Team Maker: If 1 is entered, the application prompts the user to enter the desired number of teams to make. If 0 is entered, nothing happens and the application continues on prompting the user to enter 1 or 2. See Fig-3. If the number of teams is 1 or greater, the application displays the team number, beginning from 1, followed by three full names randomly selected from the 49 students provided in COP2510.txt. See also Fig-3, where 1 and 3 are entered for making one team and three teams, respectively. Hint: Use the Random class as seen in GetRandom1.java or GR.zip of Quiz 3 to implement this random selection.
All names of each team must be displayed beginning with a 'tab'. It's very important in this application that no student appears in the same or different teams more than once. Hint: there are more than one way to "map" a random number (integer) to a specific student name. Using if....else if....else if....else if.... is one possible approach and is recommended here. Storing all names in an array is another way but is not introduced until Chapter 10 . Counting Words: If 2 is entered, the application prompts the user to enter one or more sentences. See Fig-4. The application uses the space character, " ", to separate and count words in the input. If there are two or more consecutive spaces, they are treated as just one. That is, "AA BB" and "AA BB" both contains two words. See Fig-5. All leading and trailing spaces in the input would be ignored. Hint: use 'trim()' method of String. The application display two lines of dashes, i.e., "-------------------" to enclose every word it finds. Each word must be displayed together with its length. For example, if "Hi, John!" is entered, the two lines between dashes should be "Hi, (3)" and "John!(5)". After the 2nd dashes line, the total number of words is displayed to end the task. If no words or sentences are entered, a message of "Nothing or only space(s) is entered." is displayed between the two dashes lines and the count is zero. See the last input in Fig-5. Hint: You may use trim(), indexOf(), length(), substring(), and equals() methods of String to implement the above word count task. Even the same methods are used, there are different approaches to get this task completed.

I got the first part where the program welcomes the user, and shows what the program does. However I don't know how to code the random team generator. I can only use else if statements. Someone told me to assign a random number to each name and then use the else if statements, however I have no idea how to do that. And as for the word counter I just have no clue. If anyone could help that would be great.

   import java.util.Scanner;
   import java.util.Random;
   public class asssignment3 {
   public static void main (String args[]){
   Scanner sc = new Scanner(System.in);
    //print out a task prompt 
    System.out.println("Assignment-3 can perform the following two task:");
    System.out.println();
    System.out.println("\t1-Making 3-member tems from class of COP2510");
    System.out.println("\t2-Parsing and counting an input sentence by word");
    System.out.println();
    System.out.print("Enter 1 or 2 to begin your task or anything else to quit:   ");
    String choiceNumber = sc.nextLine (); 

  if (choiceNumber.equalsIgnoreCase("0")) {
      System.out.println("Enter 1 or 2 to begin your task or anything else to quit:  ");
      String optionNumber = sc.nextLine ();
  }
  Random r = new Random();    
 if (choiceNumber.equalsIgnoreCase ("1")) {
     String studentName = "";`




How to compute P values for increasing sample size using a loop?

I am having trouble creating a for loop. I want to increase my sample size from 1 to 200 and calculate a p value after each newly added observation. So that first I sample 1 observation - calculate first p value, then sample 2 observations - calculate second p value, then 3... up to 200 observations so that I get 200 p-values.
The observations will all be sampled from one column of a data frame (with replacing).

Lets say the column of the data frame is called data$column1. The sample size increases by one in each "round" from 1:200.

How do I create a for loop so that for each "round", one more observation is being sampled and a new p value is being computed? Finally I want to plot all p values.

n <- 1:200

for i in length(n) {
sample(data$column1,n, replace = TRUE)
pvalue <- t.test(data$column1, alternative = "greater")
}




How to generate one random value, and its result from a list

My situation seems to be easy but I can't get it to work...

What I want is, generate a random value displayed in a h tag, and also, display the good value relative to the random one, in an other tag.

var first = ['1+2', '10+20', '100+200'];
var second = ['3', '30', '300'];

var first_value = first[Math.floor(Math.random()*first.length)];
var second_value = second[Math.floor(Math.random()*second.length)];

document.getElementById('first_value').innerHTML = first_value;
document.getElementById('second_value').innerHTML = second_value;

At the moment, everything is generated randomly, there is no relation between the 2 values generated.

If "10+20" is randomly selected, I want to display "30" in the second html tag.

Thanks for your help guys :-)




dimanche 26 mai 2019

mvrnorm (from MASS) vs rmvnorm (from mvtnorm)

I am generating a large volume of data from the multivariate Normal distribution for simulation. I wonder if anyone is aware of which command is most efficient for this. If it is the mvrnorm (from the "MASS" package) or the rmvnorm (from the "mvtnorm" package).




c# How do you choose a number and its neighbours that form a 2x2 matrix , from a 4x4 matrix?

I have a 4x4 matrix , filled with double numbers (its a homogenic matrix), and i have to choose a number randomly , and 3 of its neighbours (so they form a 2x2 matrix).

The point is to keep the matrix stochastic after substracting a random number out 2 numbers , and adding the same random number to the other two numbers (1000 cycles)




function that will return a random number according to input

i'm having trouble writing a function that will get a number and will return a random number in the range between the input and a const number, for example: I enter 5, and the cost is 100, so the function should return a number between 5-100, and when I enter 50, it should return between 50-100: this is my function so far:

public double stopPoint(double d) {
    Random rand = new Random();
    if(d>0) {
        return Math.random() * ((this.finish.getX()-50) - d  );
    }
}

this.finish.getX is the constant number for example 100, and d is the input, but it doesnt seem to work, anybody knows why?




Why do we multiply calls to numpy.random.random by numbers and subtract numbers?

I found this snippet of code in an article about backpropagation and I got confused on how exactly it works. The article says the following

"This is our weight matrix for this neural network. It's called "syn0" to imply "synapse zero". Since we only have 2 layers (input and output), we only need one matrix of weights to connect them. Its dimension is (3,1) because we have 3 inputs and 1 output."

I want to specify that by input the author is referring to array "X" and output refers to array "Y".

My first question is why does the article claim we have only 3 inputs. A glance at the code reveals that our array, X, has size 4. Am I just misunderstanding something?

My second question is why are multiplying the call to np.random.random() by 2?

Thanks for the help!

import numpy as np    

X = np.array([ [0,0,1],
               [0,1,1],
               [1,0,1],
               [1,1,1] ])

y = np.array([[0,0,1,1]]).T  

# initialize weights randomly with mean 0
syn0 = 2*np.random.random((3,1)) - 1




Discard some dictionaty items in list during random.choice

I want to get random item from a list, also I don't want some items to be consider while random.choice(). Below is my data structure

x=[
  { 'id': 1, 'version':0.1, 'ready': True  }
  { 'id': 6, 'version':0.2, 'ready': True }
  { 'id': 4, 'version':0.1, 'ready': False }
  { 'id': 35, 'version':0.1, 'ready': False  }
  { 'id': 45, 'version':0.1, 'ready': False  }
  { 'id': 63, 'version':0.1, 'ready': True   }
  { 'id': 34, 'version':0.1, 'ready': True   }
  { 'id': 33, 'version':0.1, 'ready': True   }
]

I can get the random item by using random.choice(x). But is there any way, consider 'ready': True attribute of item while random.choice().

Or any SIMPLE trick to achieve this?

NOTE: I want to use python in-built modules to avoid dependencies like numpy, etc.




create a fixed length random byte array between range

I need to generate an array of random 20 bytes between given range of arrays..

I want to do something like:

use rand::prelude::*;

fn main() {
    let low = [0u8; 20];
    let high = [2u8; 20];
    let value = rand::thread_rng().gen_range(low, high);
    println!("{:?}", value);
}

but I get following error:

error[E0277]: the trait bound `[u8; 20]: rand::distributions::uniform::SampleUniform` is not satisfied
 --> src\main.rs:6:36
  |
6 |     let value = rand::thread_rng().gen_range(low, high);
  |                                    ^^^^^^^^^ the trait `rand::distributions::uniform::SampleUniform` is not implemented for `[u8; 20]`

error: aborting due to previous error

I tried implementing SampleUniform and UniformSampler without much success.

Is there a simple way to implement this?




Why is this function sometimes producing returns outside its supposed restrictions?

As an exercise I'm building a clone of the classic Nibbles/Snake game.

The game area consists of a two-dimensional array (rows and columns), and the player snake consists of another two-dimensional array containing coordinates for each cell in the game area that the snake is currently occupying.

I then have a function to create the apples that the snake is supposed to eat. This function returns a simple array containing an x- and a y-coordinate specifying the game area cell to put the apple. This cell should of course never be one of the cells that the player snake is occupying at the moment when the apple is created.

However, the function I've constructed sometimes creates an apple in a cell that the player snake IS currently occupying.

Can anyone spot the bug?

This is the relevant code:

const rows = 20;
const cols = 26;

const cells = createCells(rows, cols);
let player = [[1,1], [1,2], [1,3], [1,4]];
let apple = createApple(cells, player);

function createCells(rows, cols) {
    let cells = new Array(rows);
    for (let r = 0; r < cells.length; r++) {
        cells[r] = new Array(cols);
    }
    return cells;
}

function createApple(cells, player) {
    let positions = new Array();
    for (let r = 0; r < cells.length; r++) {
        for (let c = 0; c < cells[r].length; c++) {
            for (let p = 0; p < player.length; p++) {
                if (!(player[p][0] === r && player[p][1] === c)) {
                    positions.push([r, c]);
                }
            }
        }
    }
    let random = Math.floor(Math.random() * positions.length - 1);
    let apple = positions[random];
    return apple;
}




How do I generate random string array urls without repeating?

I am trying to generate random string array urls in picasso, everything is working fine but it repeats, like i had 28 string array items when i start app some items are repeating but i want only 1 item at one time when random start

This is my code

     ImageView imageView = itemView.findViewById(R.id.imageview);
        random = new Random(); 
        int p=  random.nextInt(icons.length);
        Picasso.get().load(icons[p]).into(imageView);




samedi 25 mai 2019

System.Random producing the same random number

Despite the Random generator only being created once, the output is always the same random result (for all three test outputs).

A test snippet from a slightly larger script:

   let myRandGen = System.Random()
   let getRandomObject = 
      let options = [|"Bob"; "Jim"; "Jane"|]
      let randIndex  = myRandGen.Next(options.Length) 
      options.[randIndex] 

   printfn "New one: %s" getRandomObject
   printfn "New two: %s" getRandomObject
   printfn "New three: %s" getRandomObject

I need the output to be random for each call, which it currently isn't.

Example output:

New one: Jane
New two: Jane
New three: Jane




Reversing LCG in java

I'm trying to get the original value that produces this random number.

Random rand = new Random(295);
int nextInt = 0;
for (int n = 0; n < 78801 + 1; n++) {
    nextInt = rand.nextInt(500000);
}
System.out.println(nextInt);//499429

The value (499429) was produced by seed (295) and it's the 78801th nextInt. I have done lots of research, according to the attached links, LCG is reversible. How can I reverse it in java such that using only the seed value and the output I will get back the nth value?

Making a customizable LCG that travels backward and forward

Reversible pseudo-random sequence generator

pseudo random distribution which guarantees all possible permutations of value sequence - C++

Reversible Linear Congruential Generator

Cracking a linear congruential generator

Cracking Random Number Generators - Part 1

Reverse engineering the seed of a linear congruential generator

Predicting the next Math.random() in Java

Inverse function of Java's Random function




what is the fastest way to get the nth nextInt value?

I have to find the nth nextInt of each array element. The code below is really slow as the array elements are over 40k, and each array element is over a million.

int[] numbers ={1000000,1004300,2204000,1306000...40k+};
for (int i = 0; i <numbers.length; n++) {
Random ran = new Random(1234);
    int nex = 0;
    for (int n = 0; n <numbers[i]; n++) {
        nex = ran.nextInt();
    }
    System.out.println("Next int value: " + nex);
}

Is there a faster way to get the 1 millionth nextInt? if yes please how?




gameObject out of screen edge

I have this piece of code from my 2D game character. It's working fine on respawning my character on random Screen positions, but the problem is that this code works with my game caharacter Center, I mean it generates the center position to a Random Range and there on the edge of the screen my chracter is going half out of the screen... I need this code working on any Android device and i dont know how i can solve this. Anyone a simple solution?

Sorry for my beginner english.

//Generate Random X
    float generateX()
    {
        float x = Random.Range(Camera.main.ScreenToWorldPoint(new Vector2(0, 0)).x, Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, 0)).x);
        return x;
    }

    //Generate Random Y
    float generateY()
    {
        float y = Random.Range(2.0f, Camera.main.ScreenToWorldPoint(new Vector2(0, Screen.height)).y);
        return y;
    }

void generateCoordinates()
    {
        transform.position = new Vector2(generateX(), generateY());
    }




Are seeded random numbers not consistent between python versions?

Question:

Why are seeded random outputs seemingly different across python versions? Have I missed something obvious, is it a documented behavior (I could not find it)

Observed results:

An attempt to reproduce seeded random numbers across python versions produces different results:

# python 3.7
rachel = sorted(Random('rachel').sample(range(57), 6))
larry = sorted(Random('larry').sample(range(57), 6))
armin = sorted(Random('armin').sample(range(57), 6))
laura = sorted(Random('laura').sample(range(57), 6))
rachel, larry, armin, laura

output:

([8, 22, 27, 35, 45, 47],
 [10, 18, 20, 29, 45, 47],
 [4, 7, 15, 22, 47, 52],
 [5, 8, 37, 40, 50, 55])

Comparison point:

Whereas a screenshot from Raymond Hettinger's advanced python at Europycon 2011 is showing a different output - probably python 2.6 or 2.7: (the image quality is poor, but the results are clearly different)

enter image description here




vendredi 24 mai 2019

Replace a certain group in a pyspark dataframe column with a random item from a list

Let's say the dataframe looks like this:

ls = [
    ['1', -9.78],
    ['2', 5.38],
    ['1', 8.86],
    ['2', -0.47],
    ['1', -0.19],
    ['1', 4.78],
    ['1', -9.23],
    ['2', -89.32]
]
test = spark.createDataFrame(pd.DataFrame(ls, columns=['col1', 'col2']))
test.show()

output:

+----+------+
|col1|  col2|
+----+------+
|   1| -9.78|
|   2|  5.38|
|   1|  8.86|
|   2| -0.47|
|   1| -0.19|
|   1|  4.78|
|   1| -9.23|
|   2|-89.32|
+----+------+

I want to replace all row where the value in col1 == 1 with random pick from a list of items: ['a', 'b', 'c'] (with replacement).

For example, the result would look like this:

+----+------+
|col1|  col2|
+----+------+
|   a| -9.78|
|   2|  5.38|
|   a|  8.86|
|   2| -0.47|
|   c| -0.19|
|   b|  4.78|
|   a| -9.23|
|   2|-89.32|
+----+------+

How can I do this in pyspark?




I have a function to generate random string,and a program to repeat that function. I want it to generate more than 1 line of random string

I have a Function to generate random string ,and funtion to repeat it .but how to make it generating more than 1 or according to the written in parameter?

    function generatorstring($length = 7){

    $karakter = '0123456789abcdefghijklmnopqrstuvwxyz';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $karakter[rand(0, strlen($karakter) - 1)];
        }
    return $randomString;
    }
    function repeat($rpt){
        for ($i = 0; $i < $rpt; $i++){
        $res = generatorstring();
        }
    return $res;
    }
    echo repeat(3);

I expected result like this

'As6s8Xs',
'zE71jnM', 
'ak9a71b', 

But, its only produce 1 line of random string.




Is there a good aggregate equivalent for Google Sheets with the large funktion?

I try to write an easy randomizer based on a database for randomly combining data. This works fine in Excel, but not in GoogleSheets, because there is no aggregat

I've already tried LARGE and MAX but then its not randomizing, and with SUBTOTAL its not working. I thought it also could be based on ROW, but maybe i have a wrong concept.

The code in excel is like this (i use the german version of excel, but this should be the english equivalent)

=TEXTJOIN(" ";TRUE;INDIRECT("A"&ROUNDUP(RAND()*AGGREGAT(14;4;(A:A<>"")*ROW(A:A);1);0));INDIRECT("B"&ROUNDUP(RAND()*AGGREGAT(14;4;(B:B<>"")*ROW(B:B);1);0));INDIRECT("C"&ROUNDUP(RAND()*AGGREGAT(14;4;(C:C<>"")*ROW(C:C);1);0)))

As i mentioned there is no aggregat, and the other solutions i looked up didnt work for me.




jeudi 23 mai 2019

How to use random.choice() with functions? [duplicate]

This question already has an answer here:

I have 18 multiple choice questions listed as functions in one file, and I want to call 10 of those questions randomly from a main file. If I use random.choice() with a list of integers or strings it works fine, but if I pass it a list of functions it runs all of the functions in order, ignoring the range I set. I've read a lot of documentation, help files and similar cases on forums, but I'm still scratching my head over it. At this point I think random.choice just won't do what I need it to. Does anyone see my mistake or know an alternative?

I've tried random.choice(), .choices(), .shuffle() I've tried passing the functions in a list and a dictionary, entering the list name or the entire list of options directly into the .choice(), printing(random.choice(list)) but I get the same result every time.

import random

def Q1():
    print('Question 1')
def Q2():
    print('Question 2')
def Q3():
    print('Question 3')    

list = [Q1(),Q2(),Q3()]
for i in range(5):
    random.choice(list)
    i+=i




Calculating probability using simulation

Let Xi~U(0,30) be random variables. If one takes a sample of n=12, then we are interested in knowing the probability of the proportion to be greater than 18 i.e. $P(\overline X_{12}>18)$

Without using simulation and applied the CLT, the answer is .1150

Here is my approach to implement this in R using simulation:

SimProb<-function(N)
{
n=12

M<-matrix(runif(1,0,30),N,n)
rowMeann<-rowMeans(M)

for(i in 1:N)
{
  if(rowMeann[i]>18)
    c=cumsum(rowMeann[i])
    c

}
prob<-1-c
return(prob)
}

The code does not show any error but does not work properly.

When I was checking, it turns out c= 6.083532 which can't be.

For different values of N, SimProb returns only negative values, I don't understand why.

Could someone please help me ?

Thank you




Using my own template parameters for std::mersenne_twister_engine when switching between different floating point precisions

std::mt19937 is a typedef of std::mersenne_twister_engine. Should I be using my own template parameters for the latter if I'm switching between different floating point precisions in my sampling? If so, how?

Right now I have something like this

#include <random>
#include <iostream>

int main()
{
    using float_type = double;

    std::random_device rd;  
    std::mt19937 gen(rd()); 
    std::uniform_real_distribution<float_type> dis(1.0, 2.0);
    for (int n = 0; n < 1e6; ++n) {
        std::cout << dis(gen) << ' ';
    }
    std::cout << '\n';
}

but when I switch using float_type = double; to using float_type = float; there isn't much of a speedup. Actually, in some other code I have, using float is actually much slower!

Here's a makefile if it helps. I used time ./prog after I compile with make as a rough timer, and I am running Ubuntu 18.04.2 LTS and my processor is a Intel® Xeon(R) CPU E3-1241 v3 @ 3.50GHz × 8 .

PROG = prog
SRCS = main.cpp
OBJS = main.o
CXX = g++
CXXFLAGS = -std=c++11 -O3 $(INCLUDES) -pg


all: $(PROG)

$(PROG): $(OBJS)
        $(CXX) -o $@ $(OBJS) 

main.cpp :
        $(CXX) $(CXXFLAGS) -c 

main.o : main.cpp
        $(CXX) $(CXXFLAGS) -c main.cpp

.PHONY: clean
clean:
        rm -f $(PROG) $(OBJS) 




Art idea generator

Can't print a single item from my list. The items in my list are phrases.

.shuffle()

.split()

print('[%s]' % ', '.join(map(str, mylist)))

def getWord(wordList): wordIndex=random.randint(0,len(wordList)-1) return wordList[wordIndex] print('%s' %(words))

ideas='stack of books, pile of rocks, pine cone' print ('%s' %(ideas))

I expect the output to be "stack of books", "pile of rocks", or "pine cone"




How do i generate 2 random numbers, once within the range of 50 and 259, and once within 50 and 159? [duplicate]

This question already has an answer here:

I'm working on an assembly 8086 project for class and needed a way to generate 2 random numbers, once within 50 and 259 and once within 50 and 159.




Adding Random Proxy to requests.get()

I'm new to Python and web scraping. I found these 2 programs on the internet. I'm trying to figure out how to add random proxy generating from def get_proxies() to def webParser() method. So each url request will get random proxy address. Is this possible? Please help.

from lxml import html
import csv, os, json
import requests
from lxml.html import fromstring
from itertools import cycle
#from exceptions import ValueError
import sys
from time import sleep

def get_proxies():
    url = 'https://free-proxy-list.net/'
    response = requests.get(url)
    parser = fromstring(response.text)
    proxies = set()
    for i in parser.xpath('//tbody/tr')[:10]:
        if i.xpath('.//td[7][contains(text(),"yes")]'):
            # Grabbing IP and corresponding PORT
            proxy = ":".join([i.xpath('.//td[1]/text()')[0], i.xpath('.//td[2]/text()')[0]])

            proxies.add(proxy)

    return proxies

proxies = get_proxies()
proxy_pool = cycle(proxies)

url = 'https://httpbin.org/ip'
for i in range(1,11):
    #Get a proxy from the pool
    proxy = next(proxy_pool)
    print("Request #%d"%i)
    try:
        response = requests.get(url,proxies={"http": proxy, "https": proxy})
        print(response.json())
    except:
        #Most free proxies will often get connection errors. You will have retry the entire request using another proxy to work.
        #We will just skip retries as its beyond the scope of this tutorial and we are only downloading a single url
        print("Skipping. Connnection error")


def webParser(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36'}
    page = requests.get(url, headers=headers)
    while True:
        sleep(3)
        try:
            doc = html.fromstring(page.content)
            XPATH_NAME = '//h1[@id="title"]//text()'
            XPATH_SALE_PRICE = '//span[contains(@id,"ourprice") or contains(@id,"saleprice")]/text()'
            XPATH_ORIGINAL_PRICE = '//td[contains(text(),"List Price") or contains(text(),"M.R.P") or contains(text(),"Price")]/following-sibling::td/text()'
            XPATH_CATEGORY = '//a[@class="a-link-normal a-color-tertiary"]//text()'
            XPATH_AVAILABILITY = '//div[@id="availability"]//text()'

            RAW_NAME = doc.xpath(XPATH_NAME)
            RAW_SALE_PRICE = doc.xpath(XPATH_SALE_PRICE)
            RAW_CATEGORY = doc.xpath(XPATH_CATEGORY)
            RAW_ORIGINAL_PRICE = doc.xpath(XPATH_ORIGINAL_PRICE)
            RAw_AVAILABILITY = doc.xpath(XPATH_AVAILABILITY)

            NAME = ' '.join(''.join(RAW_NAME).split()) if RAW_NAME else None
            SALE_PRICE = ' '.join(''.join(RAW_SALE_PRICE).split()).strip() if RAW_SALE_PRICE else None
            CATEGORY = ' > '.join([i.strip() for i in RAW_CATEGORY]) if RAW_CATEGORY else None
            ORIGINAL_PRICE = ''.join(RAW_ORIGINAL_PRICE).strip() if RAW_ORIGINAL_PRICE else None
            AVAILABILITY = ''.join(RAw_AVAILABILITY).strip() if RAw_AVAILABILITY else None

            if not ORIGINAL_PRICE:
                ORIGINAL_PRICE = SALE_PRICE

            if page.status_code != 200:
                raise ValueError('captha')
            data = {
                'NAME': NAME,
                'SALE_PRICE': SALE_PRICE,
                'CATEGORY': CATEGORY,
                'ORIGINAL_PRICE': ORIGINAL_PRICE,
                'AVAILABILITY': AVAILABILITY,
                'URL': url,
            }

            return data
        except Exception as e:
            print(e)



def ReadAsin():
    # AsinList = csv.DictReader(open(os.path.join(os.path.dirname(__file__),"Asinfeed.csv")))
    AsinList = ['ITM001',
                'ITM002',
                'ITM003',
                'ITM004',
                'ITM005'
                ]
    extracted_data = []
    for i in AsinList:
        url = "http://www.ecomsite.com/item/" + i
        print
        "Processing: " + url
        extracted_data.append(webParser(url))
        sleep(5)
    f = open('data.json', 'w')
    json.dump(extracted_data, f, indent=4)


if __name__ == "__main__":
    ReadAsin()




Get errors with rand and rand_r when multithreading

I am creating many threads and each one should output a random number.

I know that srand() with rand is not thread-safe and indeed all the output numbers are the same.

So I tried to use rand_r but I get the following error on my Windows terminal

main.c:47:16: warning: implicit declaration of function 'rand_r'; did you mean 'rand'? [-Wimplicit-function-declaration]
 result= ( (rand_r(&seed) % (high+1-low) ) + low);
            ^~~~~~
            rand
main.c: In function 'customerServe':
main.c:333:1: warning: control reaches end of non-void function [-Wreturn-type]
}

c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: 
C:\Users\allys\AppData\Local\Temp\ccSslADA.o:main.c:(.text+0xe): undefined 
reference to `rand_r'
c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: 
C:\Users\allys\AppData\Local\Temp\ccSslADA.o:main.c:(.text+0x41c): 
undefined reference to `rand_r'
collect2.exe: error: ld returned 1 exit status

Thank you




Cannot create an instance of an abstract class (Random)

I am trying to learn Kotlin so I was following a tutorial on internet where instructor wrote a code which worked fine in with them but it gives error to me.

This is the error

Error:(26, 17) Kotlin: Cannot create an instance of an abstract class

import kotlin.random.Random

fun main(args: Array<String>) {
    feedTheFish()
}

fun feedTheFish() {
    val day = randomDay()
    val food = "pellets"
    print("Today is ${day} and the fish eat ${food}")
}


fun randomDay():String {
    val week = listOf ("Monday", "Tuesday", "wednesday", "thursday", "friday", "saturday", "sunday")
    return week[ Random().nextInt(7)]
}

I am getting error from return statement, I think from Random. Please help me to understand this and fix this code.




Understanding Tensorflow initialize_all_variables

Why the following code prints 4 different numbers?

# Random seed for reproducibility
tf.set_random_seed(1234)
# Random variable
foo = tf.Variable(tf.random_uniform(shape=(1,1)),name = 'foo')
# Operation to initialize variables
init = tf.initialize_all_variables()
# Run Operations in session
with tf.Session() as sess:
    # Loop 
    for i in range(1,5):
        # Initialize variables
        sess.run(init)
        # Print foo value
        print(sess.run(foo))

I was expecting it to print the same random value 4 times since I am running the initializer at the start of each of the four iterations.




mercredi 22 mai 2019

Is there any way to get random from enum class in c++?

I want to fill a variable with random element from enum class.

So I tried set enum class type to int and pass last enum from enum class to rand:

enum class Enumerator: int
{
    en1=0,
    en2,
    en3,
    ensCount
};

int main()
{
    srand(time(NULL));
    auto a=static_cast<Enumerator>(rand()%Enumerator::ensCount);
    return 0;
}

Result is "no match for «operator%» (operand types are «int» and «Enumerator»)" error.




SImulating Random numbers that are weibull distributed in Netlogo

I have been trying to get Netlogo to output random numbers according to a weibull distribution, given a scale and a shape as inputs. E.g, in R, the command rweibull does the trick, e.g, rweibull(1, shape=16, scale = 2500) outputs numbers like 2333.438, etc. However, the existing code that outputs a weibull distributed random variable in Netlogo (see code below) only produces numbers around 1, independently of the shape and scale that is entered. How can I get Netlogo to output a weibull distributed random variable as R does?

The existing Netlogo code I have tried is below(it is available on many sites)

If one tries to get the reporter to output a realization of the Weibull R.V using the same parameter as above, one only gets, e.g, 1.001021732652175, 1.000377358845726, and so on.

P.S: I have tried to use the rserve extension and use the r:get rweibull(n, shape, scale), but unfortunately the extension does not seem to be available for Netlogo 6.0 and above.

to-report random-weibull [#shape #scale] ; goes scale then shape
      let xWei random-float 1
      let yWei (1 / #scale)
      let zWei (#shape * (-1 * ln(1 - xWei)))^ yWei
      report zwei
    end

I expect the actual outcome of the reporter to be numbers around the scale that is used as input for the weibull reporter, and not a random float around 1 as it's doing now... Maybe another parameterization?




What is going on here?!? I am about to lose my mind

I am running this python code mentioned below and the console says things like this:

sim is: [1 0 1 1 1 1 1 0 1 0]

counter_one is 3

counter_zero is 7

But which makes things even stranger is that when I run the code again every once in a while the counters are correct.

import numpy as np

from fractions import Fraction

elements = np.array([1, 0])

prob_of_functioning = Fraction(2, 3)
prob_of_failing = Fraction(1, 3)
probabilities = [prob_of_functioning, prob_of_failing]

sim = np.random.choice(elements, 10, p=probabilities)

print("sim is:")
print(sim)

counter_one = 0
counter_zero = 0

for k in sim:
    if sim[k] == 1:
        counter_one = (counter_one + 1)
    if sim[k] == 0:
        counter_zero = (counter_zero + 1)


print("counter_one is")
print(counter_one)

print("counter_zero is")
print(counter_zero)




Reading a CSV file line by line and producing streams with some lines sent with a random delay

I am reading concurrently 3 CSV file line by line and sending them to a message queue (Apache Kafka). The data rows are ordered by increasing timestamp values. I am simulating the streams by looking at the last timestamp and at the new timestamp and make a thread sleep for the difference of the two timestamps. I do this in order to simulate the production of the messages.

Now I want to have some of those messages delayed by a random amount of time and have prepared a function that put the thread to sleep for a random amount of time and chooses randomly when to perform this operation.

When I do that I put to sleep the entire reading of the CSV file by delaying all the subsequent messages that have to be produced.

Probably I am lacking experience in doing this stuff, but I don't know how to randomly put to sleep and of the messages that I am producing without delaying all the messages that have to come?




How can I create random emails for each customer? [on hold]

How can I create random emails for each customer so external companies can send them mail without knowing the real address?

I need this because I have to share some email address with external companies for every customer that uses a service of the company. Because of GPDR I cannot just share the real email address of the customer and have to use a randomly generated alias. This should be the same as Amazon does when they transmit email addresses of their customers to 3rd party sellers. Of course the external company will send a few emails to this random address and they should be redirected to the real email, but the random address will not send any email (only an alias to receive them).

What kind of infrastructure and logic will I need to do something like this? Which services may already be able to do this for me?

Thanks for helping!




Random grid of elements using Haskell

Having absolutely zero experience with Haskell, I need to come up with a code equivalent to this Python one:

from random import choice, sample

def random_subset():
    return tuple(sample(('N', 'S', 'W', 'E'), choice((1, 2, 3, 4))))

def form_grid(n):
    return [[random_subset() for _ in range(n)] for _ in range(n)]

form_grid(10)

which produces something like this:

N     ESWN  SNEW  NSE   EWSN  E     ENSW  N     NSWE  WES   
NE    WNS   SWEN  EWN   ENWS  WEN   WS    W     ENSW  NW    
WENS  NWE   SNEW  ES    E     S     ES    SENW  EW    WEN   
NSE   NE    WNE   NEWS  SNE   W     SWNE  NSWE  SNEW  EN    
S     SNW   WNES  S     WESN  E     ES    N     ESN   ES    
SWEN  S     WSNE  NEWS  WESN  E     S     SE    E     N     
NEW   S     NEW   WS    W     EN    N     NWS   E     WENS  
WN    NWE   S     SEW   NESW  EWSN  WENS  ES    NWS   WN    
W     NWE   N     N     ES    E     E     WN    SWNE  NES   
WENS  NWE   NW    WESN  SW    NES   ENWS  SE    N     SWNE 

I, for the love of god, can't wrap my head around Haskell's concept of IO (randomness in particular). The best I could come up with is this:

import Data.Random hiding (shuffle, sample)
import Data.Random.Source.Std
import Data.Random.Extras

randSubset :: IO [Char]
randSubset = do
    len <- runRVar (choice [1..4]) StdRandom :: IO Int
    subset <- runRVar (sample len ['N', 'S', 'W', 'E']) StdRandom :: IO [Char]
    return subset

formGrid :: Int -> [[IO [Char]]]
formGrid n = [[subset | _ <- [0..(n - 1)], subset <- randSubset] | _ <- [0..(n - 1)]]

which still didn't do it:

error:
    * Couldn't match expected type `[IO [Char]]'
                  with actual type `IO [Char]'
    * In the expression: randSubset
      In a stmt of a list comprehension: subset <- randSubset
      In the expression:
        [subset | _ <- [0 .. (n - 1)], subset <- randSubset]
   |
12 | formGrid n = [[subset | _ <- [0..(n - 1)], subset <- randSubset] | _ <- [0..(n - 1)]]
   |                                                      ^^^^^^^^^^

Quick googling didn't help much - I probably didn't use the most accurate keywords for this problem I'm facing. Making random changes and hoping for the best is getting pretty frustrating, but I really have neither time, nor energy to dive into Haskell properly (even though it's a shame), so for now, I'd love someone to just point me to what's wrong with this code.




R caret: fully reproducible results with parallel rfe on different machines

I have the following code using random forest as method which is fully reproducible if you run it in parallel mode on the same machine:

library(doParallel)
library(caret)

recursive_feature_elimination <- function(dat){

  all_preds <- dat[,which(names(dat) %in% c("Time", "Chick", "Diet"))]
  response <- dat[,which(names(dat) == "weight")]

  sizes <- c(1:(ncol(all_preds)-1))

  # set seeds manually
  set.seed(42, kind = "Mersenne-Twister", normal.kind = "Inversion")
  # an optional vector of integers for the size. The vector should have length of length(sizes)+1
  # length is n_repeats*nresampling+1
  seeds <- vector(mode = "list", length = 16)
  for(i in 1:15) seeds[[i]]<- sample.int(n=1000, size = length(sizes)+1)
  # for the last model
  seeds[[16]]<-sample.int(1000, 1)
  seeds_list <- list(rfe_seeds = seeds,
                     train_seeds = NA)

  # specify rfeControl
  contr <- caret::rfeControl(functions=rfFuncs, method="repeatedcv", number=3, repeats=5, 
                             saveDetails = TRUE, seeds = seeds, allowParallel = TRUE)

  # recursive feature elimination caret 
  results <- caret::rfe(x = all_preds, 
                        y = response,
                        sizes = sizes, 
                        method ="rf",
                        ntree = 250, 
                        metric= "RMSE", 
                        rfeControl=contr )


 return(results)


}

dat <- as.data.frame(ChickWeight)

cores <- detectCores()
cl <- makePSOCKcluster(cores, outfile="")
registerDoParallel(cl)
results <- recursive_feature_elimination(dat)
stopCluster(cl)
registerDoSEQ()

The outcome on my machine is:

 Variables  RMSE Rsquared   MAE RMSESD RsquaredSD MAESD Selected
         1 39.14   0.6978 24.60  2.755    0.02908 1.697         
         2 23.12   0.8998 13.90  2.675    0.02273 1.361        *
         3 28.18   0.8997 20.32  2.243    0.01915 1.225         

The top 2 variables (out of 2):
   Time, Chick

I am using a Windows OS with one CPU and 4 cores. If the code is run on a UNIX OS using multiple CPUs with multiple cores, the outcome is different. I think this behaviour shows up because of the random number generation, which obviously differs between my system and the multi-CPU system.

How can I produce fully reproducible results independent of the OS and independent of how many CPUs and cores used for parallelization?

How can I assure that the same random numbers are used for each internal process of rfe and randomForest no matter in which sequence during the parallel computing the process is run?

How are the random numbers generated for each parallel process?