lundi 30 avril 2018

How do I randomise specific colours on Processing

I am looking for some help to randomise specific colours on Processing using the Array Function. For example I only want the colours to be a specific red, blue, yellow and green. How to I ensure that when each single letter bounces off the wall, one of the colours appears on that specific letter?

Below is my code, really appreciate the help.

String word = "bounce";
char[] letters;
ArrayList<Letter> letterObjects;
boolean ballFall = false;
PFont font;
color randColour = color (0);
Letter l;

void setup () {
    size (500, 500);
    pixelDensity(displayDensity());
    textAlign(CENTER);
    textSize(30);
    letters = word.toCharArray();
    letterObjects = new ArrayList<Letter>();
    font = createFont("AvenirNext-Medium", 50);
    textFont(font);

    //iterate over the letter array
    //for each letter create a new object
    //add this object to an ArrayLost
    for (int i = 0; i<letters.length; i++) {
        char currentLetter = letters[i];
        float currentPosition = i * 30;
        letterObjects.add(new Letter(currentLetter, 180 + currentPosition, height/2));
    }
}

void draw () {
    background(255);

    for (Letter l : letterObjects) {
        l.display();
    }

    if (ballFall == true) {
        for (Letter l : letterObjects) {
            l.move();
            l.bounce();
        }
    }
}

void mouseClicked() {
    ballFall = true;
}

Letter class

class Letter {
    char character;
    float x, y;
    float xSpeed, ySpeed;
    float distance;

    Letter(char _c, float _x, float _y) {
        character = _c;
        x = _x;
        y = _y;

        //x = random(width);
        //y = random(height);
        xSpeed = random(1, 3);
        ySpeed = random(1, 3);
    }

    void move () {
        x += xSpeed*2;
        y += ySpeed*2;
    }

    void bounce () {
        if (x<0 || x>width) {
            xSpeed *=-1;
            randColour = color (random(255), random (255), random(255));
        }

        if (y<0 || y>height) {
            ySpeed *=-1;
            randColour = color (random(255), random (255), random(255));
        }
    }

    void display () {
        fill(randColour);
        text(character, x, y);
    }
}




Random pattern generator?

I am currently developing an app that will need to recognize and distinguish different patterns, and I currently need 54 unique, easily distinguishable patterns that are not too intricate for a normal mobile camera to read. The patterns can use any means possible to distinguish themselves, but I would like for each pattern to follow the same style. The goal is for the app to distinguish each pattern without it being too easy to distinguish them with the naked eye. I have considered using a simple 3x3 or 2x2 square sporting 4-9 different coloured squares for each pattern, but I've also seen images where there is a mash of colours with waves going through, used for similar puproses, but I am afraid this pattern will be too difficult for the app to distinguish between. Especially if there are 54 of them. Is there any application that I can use to generate these patterns while guaranteeing that no two patterns look too much alike? The best I've found so far is a knitting-pattern generator, but that makes a random sheet of pattern with no regards for uniqueness.

I hope I'm not asking for too much, but I can't seem to find a good algorithm to work this out anywhere. If no such program exists I will have to make these patterns myself, but I would like to avoid that at any cost, as it's likely to cause a lot of similar patterns.

Thank you all in advance.




how can i create random number generator that follows t distribution? in python

how can i create random number generator that follows t distribution? with given mu, variance, and degrees of freedom

import math 
import random

def student_t(nu): # nu equals number of degrees of freedom
    x = random.gauss(0.0, 1.0)
    y = 2.0*random.gammavariate(0.5*nu, 2.0)
    return x / (math.sqrt(y/nu))

I found this from here https://www.johndcook.com/python_student_t_rng.html. but shouldn't the sixth line be like

y = random.gammavariate(0.5*nu, 2.0)

why is there 2.0* ?




How to include the max value of uniform_real_distribution

I am a beginner in C++ and I am trying to explore C++11 features. Here I am trying to get familiar with the new randomness generating engines.

I summarized the following code from a tutorial on this subject and I noticed two things:

1- The uniform_real_distribution doe not include the max value.
2- The commented line produce an error although it seems to work fine on the tutorial.

#include <iostream>
#include <chrono>

using namespace std;

int main(){
    unsigned seed = 201;
    //seed = chrono::steady_clock()::now().time_since_epoch().count();
    default_random_engine e(seed);
    uniform_real_distribution<double> u(0,9);
    vector<double> v(10);
    int num;
    for(int i = 0; i < 400; ++i){
        num = u(e);
        ++v[num];
    }
    for (int i = 0; i < 10; ++i)
        cout << i << ":  " << string(v[i],'*') << "\n";
}

I tried to find the reasons of these two things with no luck.

So, my questions:

1- How to include the max value?
2- Why I am getting the error when uncomment the chrono line ?

cannot convert 'std::chrono::_V2::steady_clock' to 'unsigned int' in initialization

Note: I am using MinGW64 g++ with c++14.




Preventing array_rand string duplicate in PHP

I am randomizing php templates to include them in the web page. Each time the user reloads the web page, a new randomized template will appear.

Problem with array_rand it returns one random string each time the user reloads the web page, and the same template may be displayed again and again.

For example, let's say the user reloads the page 3 times. He may get the following templates: template1.php, template1.php, template2.php

I want the user to see all the templates in a random order. For example, template3.php,template2.php,template1.php

$items = array("template1.php","template2.php","template3.php"); #templates array
$a = $items[array_rand($items,1)]; #randomize templates

include $a; #including randomized template




dimanche 29 avril 2018

Keeping random numbers the same after refresh, Rails

I am creating a multiple choice generator that can generate multiple choice answers based on input data. The random number generators are in the page's controller. The controller gets called during a refresh and as such, the random numbers change.

I thought of storing the random numbers in sessions. But this would cause all the random numbers to stay the same even when I do want to change my input data (such as loading a new page).

Is there a way to block the controller action during page refreshes? Or another easy way to have the random numbers stay the same on page refresh, but change when loading new page?




Python Select random film from json by film type

import random
import json

# user_input = input('')

with open('robot.json') as f:
    data = json.load(f)

for film in data['films']:
    print(film["title"], film["category"])

In the code above, I want to add a user input that allows a user to specify the genre of film and using that response, retrieve a random selection from its respective category that is contained within the 'robot.json' file.

I can't seem to get random.choice to work, but that program will print all the entries in the json.

I am new to this, so I keep getting stuck in the weeds. Any help would be great.




Python - Random Sample Generator

so my first question on Stackoverflow. Please be kind:) I'm very new to Python - but each day I'm trying to get better.

I'm trying to address this questions: "Generate 1,000 random samples of size 50 from population. Calculate the mean of each of these samples (so you should have 1,000 means) and put them in a list norm_samples_50"

My guess is I have to use the randn function - but I can't quite guess on how to form the syntax based on the question above. I've done the research and cant' quite find an answer that fits. Would appreciate any help.




How would i generate a random number in python without duplicating numbers

I was wondering how to generate a random 4 digit number that has no duplicates in python 3.6 I could generate 0000-9999 but that would give me a number with a duplicate like 3445, Anyone have any ideas thanks in advance




How to populate array with characters from another array using math.random

I'm trying to populate a new array with four random characters from an array containing seven characters. Is this possible? I can't seem to find the correct way to do it.

This is what I have tried but I get an error,

char charactersAllowed[] = {'a','b','c','d','e','f','g'};
char currentCharacters[] = charactersAllowed[ (int) 
(Math.random() * 4) ];

error : incompatible types: char cannot be converted to char[ ]




how to show product randomly in woo-commerce slider

how to show product randomly in woo-commerce slider. now I use this code in function.php and some of my page work random but slider not working.

this is webpage : fidarabzar.ir

 [fusion_products_slider picture_size="auto" cat_slug="مته" number_posts="30" carousel_layout="title_on_rollover" autoplay="yes" columns="5" column_spacing="" scroll_items="" show_nav="yes" mouse_scroll="no" show_cats="yes"show_price="yes" show_buttons="yes" hide_on_mobile="small-visibility,medium-visibility,large-visibility" class="" id=""][/fusion_products_slider ]

php code

add_filter( 'woocommerce_get_catalog_ordering_args', 
'custom_woocommerce_get_catalog_ordering_args' );

function custom_woocommerce_get_catalog_ordering_args( $args ) {
$orderby_value = isset( $_GET['orderby'] ) ? woocommerce_clean( 
$_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', 
get_option( 'woocommerce_default_catalog_orderby' ) );

if ( 'random_list' == $orderby_value ) {
    $args['orderby'] = 'rand';
    $args['order'] = '';
    $args['meta_key'] = '';
}
return $args;
}

add_filter( 'woocommerce_default_catalog_orderby_options', 
'custom_woocommerce_catalog_orderby' );
add_filter( 'woocommerce_catalog_orderby', 
'custom_woocommerce_catalog_orderby' );

function custom_woocommerce_catalog_orderby( $sortby ) {
$sortby['random_list'] = 'Random';
return $sortby;
}




I'm Trying to Modify Values in a List Matrix and I Keep Getting an Index Error

I can't figure out why I'm getting an index error. I have check the indexes of the list matrix I'm modifying and I shouldn't be trying to modify non-existent values. I am using a list matrix to represent square tiles on a game map. I want each tile that has the forest value of 1, to be surrounded on all eight sides by tiles of the same value.

I feel like it would be too lengthy and unnecessary to show you all of my code. The parameter mapMatrix is a list matrix of ints. It's got 200 lists as elements inside and, initially, each list has 100 int elements of 0. Though I used a for-loop to create it, I am absolutely sure I am not wrong about its elements and values. I have used print() and len() statements to check before calling the function I've included. genPoint is a tuple of ints representing a point. It is (50, 75). I assigned this manually in the function that calls this one.

The error I get (if I remove the try/except statements):

file destination address\python.exe file destination address/map_main.py Traceback (most recent call last): File "file destination address", line 56, in main() File "file destination address/Last_Map/map_main.py", line 28, in main mapMatrix = forest_gen(mapMatrix, GEN_POINT) # add Deep Forest File "file destination address\forest_gen.py", line 64, in forest_gen mapMatrix[p[y + 1]][p[x]] = 1 IndexError: tuple index out of range

"""
Generates a forest on map matrix.
"""

__author__ = "LuminousNutria"
__Date__ = "4-28-18"

import random as r


def forest_gen(mapMatrix, genPoint):
    """
    Adds int values of 1 to mapMatrix. This represents forested tiles.

    Preconditions:
        First parameter, mapMatrix, should only have zeroes.

    Algorithm:
        One point is taken from the genPoints parameter.
        Ten points are generated within 7 tiles of this.
        Each tile surrounding the ten tiles is converted to 1 from 0.
        Roughly half of the tiles surrounding those tiles are turned to 1.
        Roughly one-quarter of the previous tiles are turned to 1.
        All points surrounded by at least 6 points of 1, are turned to 1.

    :param genPoint: tuple of ints
        A two value tuple representing an (x, y) point.

    :param mapMatrix: list matrix of ints
        A matrix representing the map.

    :return: list matrix of ints
        Returns mapMatrix
    """
    pointList = []

    # The point indicated from genPoint is forest.
    genX = genPoint[0]
    genY = genPoint[1]
    mapMatrix[genY][genX] = 1

    height = len(mapMatrix)
    width = len(mapMatrix[0])

    # Find ten points within 7 tiles of genPoint.
    xPos = r.randint(0, width)
    yPos = r.randint(0, height)
    distance = abs((genX - xPos) + (genY - yPos))
    for i in range(10):
        while distance > 7:
            xPos = r.randint(0, width)
            yPos = r.randint(0, height)
            distance = abs((genX - xPos) + (genY - yPos))
        pointList.append((xPos, yPos))

    # Make all points in pointList forest.
    for p in pointList:
        mapMatrix[p[1]][p[0]] = 1

    # Surround each forest tile with forest tiles.
    for y in range(height):
        for x in range(width):
            if mapMatrix[y][x] == 1:
                try:
                    mapMatrix[p[y + 1]][p[x]] = 1
                    mapMatrix[p[y - 1]][p[x]] = 1
                    mapMatrix[p[y]][p[x + 1]] = 1
                    mapMatrix[p[y]][p[x - 1]] = 1
                    mapMatrix[p[y + 1]][p[x + 1]] = 1
                    mapMatrix[p[y - 1]][p[x - 1]] = 1
                    mapMatrix[p[y + 1]][p[x - 1]] = 1
                    mapMatrix[p[y - 1]][p[x + 1]] = 1
                except IndexError:
                    print("ERROR1 forest_gen function:")
                    print("\tForest is off the edge of the map.")
                    print("\tAt point:", (x, y))
                    return False




Random integer generating

I've faced with the curious question. Maybe someone could guide me to relevant literature.

So, in Python, I've created this method, which appends random integers to set until repeated value occurs. When a generated integer is not unique for particularly set, method brakes:

import random

def count_no_repeat(i,j):
    random_set = set()
    while True:
        new_number = random.randint(i,j)
        if new_number in random_set:
            break
        random_set.add(new_number)
    return len(random_set) + 1

Then, I've repeated this method thousand times to count: how much steps it needs to generate non-been-before value

stats = []
for _ in range(1000):
    stats.append(count_no_repeat(1,n))

n - there is upper bound for integer generator.

And got such results: for n = 100: distplot for n equals 100

for n = 1000: distplot for n equals 1000

for n = 10000: distplot for n equals 10000

for n = 100000: distplot for n equals 100000

So, for this experiment median:

  • grows relatively slow;
  • stays on the place on the plot (that also true for a 10'000-times experiment);

Who can help, and say, why this is so? Thanks!




How can your generate a decimal between a specific range using Swift? [duplicate]

This question already has an answer here:

How can you generate a random decimal between 0.0 and 0.25 using Swift in Xcode.

This is the closest thing I could find, but it doesn't do what I desired:

let percent = drand48()

It generates a random number between 0.0 and 1.0.




Rails - passing randomly generated instance variable between routes

I'm creating an app which randomly displays a "flashcard" for language practice, which the user needs to provide a translation to. I have two tables: Flashcards (containing the flashcard data) and Practices (for managing the practice sessions and storing the responses provided).

I have managed to get a flashcard to randomly display when the user starts a practice session but what I can't work out is how to set the code so that when a user provides the response, the program remembers/knows which random card has been displayed so it can correctly POST to Practices. My current code generates a new card between showing the card and saving it to the database as @flashcard doesn't persist between routes.

# practices_controller.rb

def index
  call_random
end

def create
  call_random
  @practice = Practice.create(practice_params.merge(session_id: @session_id, flashcard_id: @flashcard.id))
  if @practice.save
    redirect_to @practice
  else
    render 'index'
  end
end

def show
end

private

def find_practice
  @practice = Practice.find(params[:id])
end

def random_flashcard
  @flashcard = Flashcard.order("RANDOM()").first
end

def call_random
  @flashcard ||= random_flashcard
end

I've tried setting and reading class attributes and other private methods to try and save the randomly generated flashcard (either the whole object or the ID) but no solution has worked for me. One methods which I thought might get me close was this, but it still failed as @flashcards was still nil in the create route.

# practice_controller.rb

def index
  random_flashcard(:generate)
end

def create
  random_flashcard(:recall)
  @practice = Practice.create(practice_params.merge(session_id: @session_id, flashcard_id: @flashcard.id))
  if @practice.save
    redirect_to @practice
  else
    render 'index'
  end
end

private

def random_flashcard(action = :generate)
  if action == :generate
    @flashcard = Flashcard.order("RANDOM()").first
  elsif action == :recall
    @flashcard
  end
end




my arch is loaded for a long time

Laptop: thinkpad t430s with ssd ocz vertex 450

My laptop with arch and ssd is loaded for a very long time. I think the problem is in [91.357306] random: crng init done But I do not know how to fix it.

dmesg after boot:

[    4.637977] psmouse serio1: synaptics: serio: Synaptics pass-through port at isa0060/serio1/input0
[    4.677750] input: SynPS/2 Synaptics TouchPad as /devices/platform/i8042/serio1/input/input8
[    4.684802] mousedev: PS/2 mouse device common for all mice
[    4.709830] IPv6: ADDRCONF(NETDEV_UP): wlp3s0: link is not ready
[    4.736908] iwlwifi 0000:03:00.0: Radio type=0x1-0x2-0x0
[    5.044248] iwlwifi 0000:03:00.0: Radio type=0x1-0x2-0x0
[    5.128889] IPv6: ADDRCONF(NETDEV_UP): wlp3s0: link is not ready
[    5.130531] IPv6: ADDRCONF(NETDEV_UP): enp0s25: link is not ready
[    5.321973] psmouse serio2: trackpoint: IBM TrackPoint firmware: 0x0e, buttons: 3/3
[    5.373820] IPv6: ADDRCONF(NETDEV_UP): enp0s25: link is not ready
[    5.444014] IPv6: ADDRCONF(NETDEV_UP): wlp3s0: link is not ready
[    5.522477] input: TPPS/2 IBM TrackPoint as /devices/platform/i8042/serio1/serio2/input/input18
[   91.357306] random: crng init done
[  193.815456] iwlwifi 0000:03:00.0: Radio type=0x1-0x2-0x0
[  194.113579] iwlwifi 0000:03:00.0: Radio type=0x1-0x2-0x0
[  194.195389] IPv6: ADDRCONF(NETDEV_UP): wlp3s0: link is not ready
[  194.201243] IPv6: ADDRCONF(NETDEV_UP): wlp3s0: link is not ready
[  194.228926] iwlwifi 0000:03:00.0: Radio type=0x1-0x2-0x0
[  194.526766] iwlwifi 0000:03:00.0: Radio type=0x1-0x2-0x0
[  194.606418] IPv6: ADDRCONF(NETDEV_UP): wlp3s0: link is not ready
[  197.789590] iwlwifi 0000:03:00.0: Radio type=0x1-0x2-0x0
[  198.088463] iwlwifi 0000:03:00.0: Radio type=0x1-0x2-0x0
[  198.171724] IPv6: ADDRCONF(NETDEV_UP): wlp3s0: link is not ready
[  201.423446] wlp3s0: authenticate with 00:37:b7:c5:08:b4
[  201.426336] wlp3s0: send auth to 00:37:b7:c5:08:b4 (try 1/3)
[  201.430707] wlp3s0: authenticated
[  201.433318] wlp3s0: associate with 00:37:b7:c5:08:b4 (try 1/3)
[  201.437528] wlp3s0: RX AssocResp from 00:37:b7:c5:08:b4 (capab=0x411 status=0 aid=4)
[  201.457272] wlp3s0: associated
[  202.521227] IPv6: ADDRCONF(NETDEV_CHANGE): wlp3s0: link becomes ready




how to pick first machine random out of three in shell?

I have three remote machines (machineA, machineB, machineC) from where I can copy files. If for whatever reason I can't copy from machineA, then I should copy from machineB and if for whatever reason I can't copy from machineB then start copying from machineC.

Below is the single shell command I have and I need to run it on many machines but then it means on all those machines, it will copy from machineA only.

(ssh goldy@machineA 'ls -1 /process/snap/20180418/*' | parallel -j5 'scp goldy@machineA:{} /data/files/') || (ssh goldy@machineB 'ls -1 /process/snap/20180418/*' | parallel -j5 'scp goldy@machineB:{} /data/files/') || (ssh goldy@machineC 'ls -1 /process/snap/20180418/*' | parallel -j5 'scp goldy@machineC:{} /data/files/')

Now is there any way by which I can pick first machine randomly (out of those three) instead of keeping machineA as first always. So pick first machine randomly and keep other two as the backup incase first machine is down? Is this possible to do?




samedi 28 avril 2018

Javascript: play a random song from an array (list)

I want to play a random song in a website. The tunes are short (max a few seconds, they don't need preload or buffering).

This part works, the number of songs may be unlimited, because tunes.length automatically counts all songs.

document.write displays the URL of a random song URL on the screen

tunes = new Array(
'"http://example.net/abcd.ogg"',
'"http://example.net/efgh.ogg"',
'"http://example.net/ijkl.ogg"'
)
var audiopath = (tunes[Math.floor(Math.random() * tunes.length)])
document.write (audiopath)

This part works too, when the URL is defined as a constant.

var song = new audio('http://example.net/abcd.ogg');
song.play();

When I try to replace the constant URL with the variable audiopath, it fails to play.
May it be anything wrong with the syntax? I tried to run it with and without single quotes in the URL '"http://example.net/ijkl.ogg"' or "http://example.net/ijkl.ogg"

var song = new audio(audiopath);
song.play();




how to generate a String random

the client will enter information(String) in edittext that i already hold it in an arraylist called options , how I can make a random that take the information and pick one of it randomly. I hope someone answer , thanks anyway.




Why random number generator not giving random repeated output

So I have written this function for random number generator and then shuffle them , I was wondering it will give us a random number so I was expecting a count of few numbers more than one so I wrote a hashmap so keep track of the count, but after running this code the output is 1 corresponding to each key that means no repetition, but then does it solve the purpose of being random when its not repeating its own value. Please a little explanation would be appreciated here " I know this function is creating the random, why we are subtracting the "i" here --> int r = i + rand.nextInt(100-i)

package interview.java.crack;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class ShuffleDeckCards {

// Function which shuffle and print the array
public static void shuffle(int card[], int n) {



    Random rand = new Random();

    for (int i = 0; i < n ; i++) {
        // Random for remaining positions.
        int r = i + rand.nextInt(100-i);

        // swapping the elements
        int temp = card[r];
        card[r] = card[i];
        card[i] = temp;

    }
}

// Driver code
public static void main(String[] args) {
    // Array from 0 to 51
    int a[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99};
    shuffle(a, 100);

    Map<Integer,Integer> mp = new HashMap<Integer,Integer>();




    int count = 0;
    // Printing all shuffled elements of cards
    for (int i = 0; i < 100; i++){
    //  System.out.print(a[i] + " ");

    if(mp.containsKey(a[i])){
        count = mp.get(a[i]) +1;
        mp.put(a[i], count);
    }

    else{
        mp.put(a[i], 1);
    }
    }

    for(Map.Entry<Integer, Integer> hm : mp.entrySet()){
        int value = hm.getValue();
        int key = hm.getKey();
        System.out.println(" key is " + key + " value "+ value);
    }

}

}




Is there a way to generate a matrix of multiple random variables on SPSS?

I need to generate 10 million values (Bernoulli and Poisson) for my end of year project and since the .csv file I use as a support is limited at 32K values per column, that makes it incredibly tedious to generate 10M values since that would take me 300 variables, which, while not impossible to make (that would take what, 20 minutes ?), must not be the only to procede. Is there any way I could generate 300 variables at once ?




Segmentation fault when generating doubles with rand() in c

Accoring to gdb this line causes a segmentation fault

((double) rand()/(double) (RAND_MAX)) * (r*2)

but this is completely fine

((float) rand()/(float) (RAND_MAX)) * (r*2)

I can make do with floats, but this bugs me. Am I doing something wrong or is rand() incapable of dealing with doubles.

Notice that in the context of upper example all floats are doubles

struct cord {

    float x;
    float y;
};

int main() {

   float r = 3.0;
   int amount = 1000000;

   srand(time(NULL));

   struct cord cords[amount];

   for (int i = 0; i < amount; i++) {

     cords[i] = (struct cord) {
  ->     ((float) rand()/(float) (RAND_MAX)) * (r*2),
         ((float) rand()/(float) (RAND_MAX)) * (r*2)
     };
   }
 ...




My if statement always does the not equal, even if the answer is equal

It always turn out to print out "Sorry", even if the number is the same. Why doesn't this if statement work?

    import random

    high_number = input("What is the maximum number?\nExample(20): ")  
    print('0-{}'.format(high_number))  

    guess = input("Guess the number: ")  
    high_number = int(high_number)  

    value = random.randint(0, high_number)  

    if value != guess:  
       print("Sorry.")  
    elif value == guess:  
       print("Hurray!")  




On Excel, is generating 1000 samples of 10k values equivalent to generating 100 samples of 100k, and any other 10 million values combination?

I need to generate 100 100k samples for my End of year project, but since every column is limited at 32k values, I was wondering if generating 1000 10k samples was going to give me the same results if I then rearrange them into 100 samples of 10K in Matlab to apply the Chi-squared test. My projectmate told me there'd be a problem when it comes to seeds that would skew the results since each 100k sample wouldn't be coming from the same seed.




Generate random subsample of fixed size of numpy array

I have searched for this and couldn't find it. Imagine I have a numpy array of size N. Now I want to generate it's subsample of size M. Basically I want M randomly chosen elements from this array. N >= M. How can I do it ?




vendredi 27 avril 2018

Variable Importance R

I am running into trouble with variable importance in R. It prints the importance but does not include the variable name. I cannot figure out where it is getting the index in the left column. Below is the code and the output.

#Random Forest training 
set.seed(7)
rf_train <- train(Output~., data=training, method = "rf",
                  trControl = trainControl(method="cv",number=4,classProbs = T,summaryFunction = twoClassSummary),metric="ROC")

#Plot of variable importance 
varImp(rf_train)
plot(varImp(rf_train))
print(rf)
 Overall

8 100.00, 23 99.80, 21 98.19, 2 94.17, 634 92.06, 7 91.75, 1010 81.26, 636 69.02, 9 56.88, 630 49.90, 1 42.60, 4 36.95, 16 29.34, 15 29.10, 1008 28.83, 17 28.54, 18 27.50, 22 27.04, 3 26.78, 14 26.36,




Linux using file for random sort not working sort --random_source=FILE

I am playing around with the sort command for Linux.

I have file1:

one
two
three
four
five

I tried:

sort -R file

The output of that command is always sorted randomly as expected

I then tried:

sort --random-source=/dev/urandom file1

and the command always has this output:

five
four
one
three
two

Why is the last sort command output always the same? Shouldn't it always be sorted randomly with this command?

Can I get an explanation on why this is occurring? Thanks.

Erik W.




Randomly replace elements in a dictionary lists based on another list

It looks like a game but I need this to evaluate a model I'm working on. Need some help... I have a dictionary with lists as values. I need to replace only one element in each list at a random position with an element in my_list but which is not present in the list. Then I need to print which letters were swapped preferably as a list of tuples showing each key from the original dictionary. My code so far, which doesn't work as needed...:

my_list=[['a','b','c','d','e','q'],['f','j','k','l','m','n'],['o','p','r','s','t','k'], ['e','s','w','x','h','z']]
my_dict = {0:['a','d','f'], 1:['o','t','e'], 2:['m', 'j', 'k'],3:['d','z','f']}
all_letters = set(itertools.chain.from_iterable(my_list))

replace_index = np.random.randint(0,3,4)
print(replace_index)
dict_out = my_dict.copy()
replacements = []
for key, terms in enumerate(my_list):
    print(key)
    print(terms)
    other_letters = all_words.difference(terms)
    print(other_letters)
    replacement = np.random.choice(list(other_letters))
    print(replacement)
    replacements.append((terms[replace_index[key]], replacement))
    print(replacements)
    dict_out[replace_index[key]] = replacement
    print(dict_out)
print(replacements) # [(o,('a','c')...]




Javascript random number generator in range, going below and above the given range

I have been trying to make a random number generator, with a given range, thought it would be easy and then without any logical reason the random number isnt in any way affected by the given maximum and minimum range. Please help. Here is the code:

<!DOCTYPE html>
          <html>
           <head>
             <style>
                .elements {
                text-align: center;
                 }

           .random {
                margin-top: 100px;
                width: 275px;
                height: 200px;
                font-size: 50px;
                text-align: center;
            }

            .range {
                margin: 35px 25px;
                width: 100px;
                height: 100px;
                text-align: center;
                font-size: 30px;
            }

            .generate {
                margin-top: 50px;
                width: 250px;
                height: 35px;
                font-size: 20px;
            }
        </style>

        <script language="javascript" type="text/javascript">
            function rand()
            {
                var max = document.getElementById("max").value;
                var min = document.getElementById("min").value;

                var output = document.getElementById("output");

                var random = Math.floor(Math.random() * max + min);

                output.value = random;
            }
        </script>

    </head>
    <body>
        <div class="elements">

        <input type="text" class="random" id="output">
        <br>
        <input type="button" class="generate" value="Generate random number" onclick="rand();">
        <br>
        <h1>Maximum Number</h1>
        <input type="text" class="range" id="max">
        <h1>Minimal Number</h1>
        <input type="text" class="range" id="min">

        </div>
    </body>
</html>




constant memory reservoir sampling, O(k) possible?

I have an input stream, of size n, and I want to produce an output stream of size k that contains distinct random elements of the input stream, without requiring any additional memory for elements selected by the sample.

The algorithm I am currently using is basically as follows:

for each element in input stream
    if random()<k/n
        decrement k
        output element
        if k = 0
            halt
        end if
    end if
    decrement n
end for

The function random() generates a number from [0..1) on a random distribution, and I trust its principle of operation is straightforward.

Although this algorithm can terminate early when it selects the last element, in general the algorithm is still approximately O(n). It seems to work as intended (outputting roughly uniformly distributed but still random elements from the input stream), but I'm wondering if a faster algorithm exists. Obviously, since k elements must be generated, the algorithm cannot be any faster than O(k). I would still like to keep the requirement of not requiring any additional memory, however.




cant get a variable equal in a loop

So I'm just trying to learn programming/coding. and I'm trying to make a loop where the computer guesses at random a number that I put in (the variable), I mostly the loop with the "while" and "if/else" loops down but like...idk how to put the variable in. I'm sure there are other things wrong with the code. Its just a simple one since I actually just started 2 days ago. here is the code

input = var
x = 0
counter = 0

while x == 0:
    from random import *
    print randint(1, 3)

    if randint == var:
        x = 1
        count = counter + 1
        print (counter)
        print "Good Bye!"
    else:
        x == 0
        counter = counter + 1
        print (counter)




jeudi 26 avril 2018

how to stop / freeze / pause volatile NOW / TODAY / RAND / RANDBETWEEN?

is there a easy way (without heavy scripting) how to disable automatic re-calculations of volatile functions like =NOW() =TODAY() =RAND() =RANDBETWEEN() in google spreadsheet?

in case of building a key generator, where I need to work with multiple RANDBETWEEN outputs, a re-calculation takes a place on every cell change, and those RANDBETWEEN numbers cant stay for example a week in my sheet, which I constantly edit.

most of my google searching told me that this cant be done because those functions are volatile and this can be done only in MS Excel by setting calculations on "manual". also most of those answers suuggested copy/pasting of such volatiles, but this can be bothersome if there are too many of them...




Pulling 5 different values in C# from an image list of cards

I have 5 separate image lists that all need to pull 5 values different from each other. I have been trying several different ways but haven't found one that works. The program is supposed to be a poker hand so they all need to be different cards.

This is what I have. (deleted some due to not working). What do I need to do to achieve these 5 different cards?

namespace Random_Card
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void getCardButton_Click(object sender, EventArgs e)
        {
            Random rand = new Random();

            int index = rand.Next(cardImageList.Images.Count);
            int index1 = rand.Next(cardImageList.Images.Count);
            int index2 = rand.Next(cardImageList.Images.Count);
            int index3 = rand.Next(cardImageList.Images.Count);
            int index4 = rand.Next(cardImageList.Images.Count);

            cardPictureBox.Image = cardImageList.Images[index];
            cardPictureBox1.Image = cardImageList.Images[index1];
            cardPictureBox2.Image = cardImageList.Images[index2];
            cardPictureBox3.Image = cardImageList.Images[index3];
            cardPictureBox4.Image = cardImageList.Images[index4];



            while (index == index1)
            {
                new Random();
            }
        }
    }
}




How to select a random child element from XML & show sub-child elements; using JS?

I want to take data from an XML file to display in an html page that is obtained by clicking a button. When the button is clicked, I'd like it to select a random child, and display the sub-child data. I made an XML file that looks like this:

<?xml version="1.0" encoding="UTF-8"?>
 <kdramas>
  <kdrama>
    <title lang="en">A Gentleman's Dignity</title>
    <genre>Comedy, Romance, Drama</genre>
    <year>2012</year>
    <episodes>20</episodes>
    <about>This drama will tell the story of four men in their forties as they go through love, breakup, success and failure. </about>
</kdrama>
<kdrama>
    <title lang="en">Boys Over Flowers</title>
    <genre>Comedy, Romance, Drama, School</genre>
    <year>2009</year>
    <episodes>25</episodes>
    <about>about text</about>
</kdrama>
<kdrama>
    <title lang="en">Goblin</title>
    <genre>Comedy, Romance, Melodrama, Supernatural</genre>
    <year>2016</year>
    <episodes>16</episodes>
    <about>about text</about>
</kdrama>

I am able to display the XML data when the button is clicked, but it shows all of the data (except for the titles). I have looked around to see if it is possible to select a random child then display its sub-child elements, but so far, I am not having any luck finding anything. The JS code I have to display the XML data is:

function getDrama(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    document.getElementById("content").innerHTML =
    this.responseText;
    document.getElementById("content").style.display = "block";
  }
};
xhttp.open("GET", "https://raw.githubusercontent.com/npellow/npellow.github.io/master/kdramaList.xml", true);
xhttp.send();
}

Any ideas on how to do this? Or even just pointing me to a place where I can read on how to do it myself would be great?




"Color Game" - calling random from array C++

hey guys so we are doing our project in c++ class. It is called "Color Game" there is an imaginary die with 6 sides and with diff colors. I don't know how to call randomly a string array. So for example I declared:

int color[] = {"Blue", "Red", "Green", "White", "Orange", "Yellow"};

I want 1 random name of the color from the array to be the output. I just don't know what code I will use. I'm just an amateur in c++.

Also, we need to display different color name when we have for example:

char answer;

cout<<"The first color is: " <<color1;
cout<<"want to play again (y/n)? ";
cin>>answer;

if (answer = 'y')
{
cout<<"The second color is: " <<color2;
}

and when we run the program, the 2 colors are randomly picked from the array.

This is just a sample of how will be the output should be. please help me in random calling arrays. thanks!




Generating random values from a set of values according to the percentage distribution

So I'm trying to randomly assign a single value from a array of values to a variable but the values should be assigned according to a defined percentage distribution. For example, If we have the values ["cat", "dog", "mouse"] with their percentage distribution as [30,50,20] respectively. Now suppose I need to generate 10 values from the above array randomly. I want the values like: 1. dog 2. dog 3. mouse 4. cat 5. dog 6. cat 7. mouse 8. dog 9. cat 10. dog So, even though the values have been generated randomly, the percentage distribution from the list is intact(cat-3 times, dog-5 times, mouse-2 times). How can I implement this?




How to make a Docker environment variable value to get a random id

I am looking to pass an environment variable which should get a random id.

Something like below.

ENV SERVICE_TAG= $uuid

In short, every time I run the container, I should get a random id for this environment variable inside the container.

Can anyone please suggest the way forward?

Thanks and regards, Prasanth.




Matlab - collecting grain for random number generation

I'm in a difficult position as I'm currently using Matlab which is not really the tool for the job in question - I can't find other grain for pseudorandomness other than cputime. I need at least three numbers as a grain for my polynomial congruential pseudorandom number generator. Please help and thank you for your time.




How to randomly divide files of a folder into sub folders?

I have a folder of approximately 1000 images, and I want to divide the folder into two subfolders, of 800 and 200 images each. I also want the division to be random, not ordered by file-names, file size, date created... etc

An idea how I could do that on Windows machine?

Thank you!




I get undefined many times from random array

I am doing a random generator in Javascript.

What doesen't work? I get the "undefined" value very often (~80% of all time) as the first value here in this script. If I make the array bigger, the error occures less often.

When will it work? If I make the both arrays with the same amount of entries, I don't get the error.

And if I swap the order in the code of * two.length); with one.length); it also works.

Can you spot the error? Its driving me crazy and its very strange.

var one = 
['Abashed',
'Abhorrent',
'Party',
'Zing',
'Zip',
'Zippy'];

var two =
['Account',
'Wives',
'Wills',
'Wins',
'Wounds',
'Wrecks',
'Wrists',
'Writings',
'Wrongs',
'Years',
'Yellows',
'Young',
'Youths',
'Zings',
'Zips'];

function showrandom() {
  var rand = Math.floor(Math.random() * one.length);
  var rand = Math.floor(Math.random() * two.length);


  document.getElementById('random').innerHTML = one[rand] + ' ' + two[rand];
}

showrandom();




mercredi 25 avril 2018

How to select the first record with a random not null value for a specific column

I was involved with the following problem and finally got the answer. Wanted to share with anyone who may need that.

I needed to select the first record with a random but not null value for id column from my table. The values of id column were not subsequent so I needed to select a random id that existed.

For example for the following table:

CREATE TABLE randomValue
(id int)

INSERT INTO randomValue 
VALUES (generate_series(1, 10))

SELECT * FROM randomValue

DELETE FROM randomValue WHERE id IN 
(SELECT id FROM randomValue WHERE id IN (2, 5, 7))

I needed a query that selected a random record with an existing id value.




Why are serialized numpy random_state objects different when are loaded?

I'm trying to figure out why certain cross-validations using a defined set of indices, the same input data, and the same random_state in sklearn gives different results using the same LogisticRegression model hyperparameters. My first thought was that the initial random_state may be different on subsequent runs. Then I realized when I pickle the random_state it says the objects are different when I compare the 2 objects directly but the values in the get_state method are the same. Why is this?

random_state = np.random.RandomState(0)
print(random_state)
# <mtrand.RandomState object at 0x12424e480>

with open("./rs.pkl", "wb") as f:
    pickle.dump(random_state, f, protocol=pickle.HIGHEST_PROTOCOL)
with open("./rs.pkl", "rb") as f:
    random_state_copy = pickle.load(f)
    print(random_state_copy)
# <mtrand.RandomState object at 0x126465240>
print(random_state == random_state_copy)
# False
print(str(random_state.get_state()) == str(random_state_copy.get_state()))
# True

Versions:

numpy= '1.13.3',

Python='3.6.4 |Anaconda, Inc.| (default, Jan 16 2018, 12:04:33) \n[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)]')




R generate random data frames

I want to create random data in R. I know that I can generate simple random data with e.g. rnorm(2000, mean=0, sd=10). With this I can create a data distribution like the most left violin in the image. But I don't know how to create more complex random data distributions like the other three in the image.

enter image description here




Checking if two strings are the same, if they are, need to redo loop

firstRound = (i + "&" + partnerOne);
secondRound = (i + "&" + partnerTwo);

while (firstRound.Equals(secondRound))
{
    myCount = myCount + 1;
    spotTwo = rnd.Next(heelerEntries.Count);
    partnerTwo = heelerEntriesTwo[spotTwo];
    secondRound = (i + "&" + partnerTwo);
    if (myCount == 5)
    {
        MessageBox.Show("Messed up 5 times!");
        break;
    }

As seen in the code above, i am trying to see if the strings firstRound and secondRound are the same. If they are, i want it to redo the entire second round loop. The code is for randomizing teams from a list so i cannot have the same team for the different rounds. If anyone is able to help, or give me other ideas on ways to do this, i appreciate it.




Array not being randomized as it should and values coming in negative

so I'm trying to store random numbers using the srand function to store values in a 2D Array using a loop. When I print out the array it has the same values everytime and the numbers are often in negative values which is strange and also they remain the same even if srand function is there.

#include <stdio.h>
#include <math.h>
#include <time.h>

#define NROW 13
#define NCOL 11


int main()

{

void disp_array(int a[NROW][NCOL]);

int ar[NROW][NCOL];
int i,j;




for (i=0;i<NROW;i++){

for(j=0;j<NCOL;j++){

    ar[NROW][NCOL]= (rand()%101);

    }

}

 disp_array(ar);

return 0;

}

void disp_array(int a[NROW][NCOL]){

int i;
int j;



for(i=0;i<7;i++){


for(j=0;j<5;j++){

printf("Value at row %d column %d is %d \n",i,j,a[i][j]);

        }
}



}

`




Stuck inside nextGaussian() method

i have a break point directly after a call to nextGaussian() method in eclipse. the code takes forever to run and when i paused it it shows that it's in the StrictMath.log(double) inside of RandomPlus(Random).nextGaussian() which is inside of RandomPLus.normalRand(double mean, double std). below is my random plus code:

public class RandomPlus extends Random{
    private static final long serialVersionUID = 1L;

    public double NormalRand(double mean, double standardDeviation) {
        return mean + (this.nextGaussian() * standardDeviation);
    }

    public boolean draw(double probability) {
        return this.nextDouble() < probability;
    }
}

The only thing i can think of is that i call this medthod ~ 100.000 times with everytime creating a new instance of it.




Unable to reproduce randomness with tensorflow and numpy combined?

I have a project in which I cannot reproduce random numbers when I use numpy in combination with tensorflow. In the beginning of all my tests, I set

tf.set_random_seed(seed)
np.random.seed(seed)

I have been debugging, and when I use numpy and no TF, all results are reproducible. When I add the TF code, the random numbers stop being reproducible. When I use both TF and numpy, I get the following results:

  1. TF variables are initialized to the same value every time (OK)
  2. When I use np.random.RandomState() with a set seed instead of direct calls to np.random.uniform(), np.random.normal(), etc, results are reproducible (OK)
  3. When I use direct calls to np.random.uniform(), np.random.normal(), etc, results are not reproducible (NOT OK)

The difference between 2 and 3 makes me think that TF must be using numpy internally somewhere in order to generate random numbers. This sounds a bit strange and unexpected. I have only 1 main thread, so the difference is definitely not caused because of race conditions. Furthermore, even if TF uses np.random, this should not change the random numbers that I observe between runs in my project since the sequence of querying the random number generation is always the same.

What is even more strange is that the particular piece of TF code which makes results non-reproducible is computing and applying gradients, where I would not expect any random number generation to be needed. Note that I am comparing only the sampled random numbers rather than results from the network (since TF has some non-deterministic operations) and these random numbers are not affected in any way by results produced from training the net.

Sorry I am unable to post my code, but it is just too big and reducing it to a smaller sample will likely make the problem go away. Thus any suggestions how to debug further are welcome.




When i run this code snippet several times which generates a random even number in python it prints "None" for some times. Why is this happening?

When i run this code several times it prints "None" for some times. Why is this happening

import random
def randomeven():
    n=int(r.random()*100)
    if n%2==0:
       return n
    else:
       randomeven()

print(randomeven())




Python script to make every combination of a string with placed characters

I'm looking for help in creating a script to add periods to a string in every place but first and last, using as many periods as needed to create as many combinations as possible:

The output for the string "1234" would be:

["1234","1.234","12.34","123.4","1.2.34","1.23.4" etc. ]

And obviously this needs to work for all lengths of string.




Guessing game outputting hot/cold with regards to how close the guess is too the answer

The goal of the game is to guess a number between 1 and 50. If the user enters a guess that is within 10 of the actual answer, the program tells them that they are HOT. If they enter a number that is within 3 of the answer, it tells them that they are VERY HOT. If they input anything else, they are COLD. Here is an example of the program running (the correct answer is 17):

Guess a number between 1 and 50: 40 You’re COLD, guess again: 10 You’re HOT, guess again: 20 You’re VERY HOT, guess again: 17 Correct, the number was 17.

This is expanding on a previous code that had guesses between 1-10 and simply had a "you're correct or a "you're incorrect, try again" code. Does anyone know where I should start to modify this code:

 import java.util.Scanner;
 import java.util.Random;
 public class Problem2 {

public static void main(String[] args) {

    // TODO, add your application code
    Random rand = new Random();
    Scanner keyboard = new Scanner(System.in);
    int numberToGuess = rand.nextInt(10);
    System.out.println("Guess a number between 1 and 10: ");
    int guess = keyboard.nextInt();

    if (guess==numberToGuess)
        System.out.println("Correct, the number was " + numberToGuess);
    else
        System.out.println("Incorrect, guess again: ");
        int guess2 = keyboard.nextInt();
    if (guess2==numberToGuess)
        System.out.println("Correct, the number was " + numberToGuess);
    else 
        System.out.println("Incorrect, guess again: ");
        int guess3 = keyboard.nextInt();
    if (guess3==numberToGuess)
        System.out.println("Correct, the number was " + numberToGuess);
    else 
        System.out.println("Incorrect, guess again: ");
        int guess4 = keyboard.nextInt();
    if (guess4==numberToGuess)
        System.out.println("Correct, the number was " + numberToGuess);
    else 
        System.out.println("Incorrect, guess again: ");
        int guess5 = keyboard.nextInt();
    if (guess5==numberToGuess)
        System.out.println("Correct, the number was " + numberToGuess);
    else 
        System.out.println("Incorrect, guess again: ");
        int guess6 = keyboard.nextInt();
    if (guess6==numberToGuess)
        System.out.println("Correct, the number was " + numberToGuess);
    else 
        System.out.println("Incorrect, guess again: ");
        int guess7 = keyboard.nextInt();
    if (guess7==numberToGuess)
        System.out.println("Correct, the number was " + numberToGuess);
    else 
        System.out.println("Incorrect, guess again: ");
        int guess8 = keyboard.nextInt();
    if (guess8==numberToGuess)
        System.out.println("Correct, the number was " + numberToGuess);
    else 
        System.out.println("Incorrect, guess again: ");
        int guess9 = keyboard.nextInt();
    if (guess9==numberToGuess)
        System.out.println("Correct, the number was " + numberToGuess);
    else 
        System.out.println("Incorrect, guess again: ");
        int guess10 = keyboard.nextInt();
    if (guess10==numberToGuess)
        System.out.println("Correct, the number was " + numberToGuess);
    else 
        System.out.println("Incorrect, guess again: ");



}

to work with the new problem?




how to make my random gaussiana distribution over one day

I would like to simulate a random normal distribution using python but in the x-axis, I would like that the distribution was centered in the 14:00 hs, for example. I have some idea where my distribution will be centered.

My function will receive a timestamp and return a value which belongs to the Gaussian function. Using this




random.shuffle in python prints nothing

I am having a problem with Python 3. I just want to shuffle an array list in a new function. The following is my code:

    def otherorder(array, if_randomized=True):
        pivot = random.shuffle(array)
        print(pivot)

If I do the following in my shell: otherorder([2, 32, 1, 44, 27])

There is no Output. Can anybody help me please?




Generate save activation key as product key

I am trying to create a function which creates a random String. This String should consist of letters (only caps) and numbers. It will be used to activate a product. So the user has to type it into a text field. So far I found the following function:

function random_str($length, $keyspace =  '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'){

  $pieces = [];
  $max = mb_strlen($keyspace, '8bit') - 1;
  for ($i = 0; $i < $length; ++$i) {
      $pieces []= $keyspace[random_int(0, $max)];
  }
  return implode('', $pieces);
}

I do not have that much experience with random functions. So is there anything to improve or would you suggest a different function?




Best way to pick random elements from an array with at least a min diff in R

I would like to randomly choose from an array a certain number of elements in a way that those respect always a limit in their reciprocal distance. For example, having a vector a <- seq(1,1000), how can I pick 20 elements with a minimum distance of 15 between each other?

For now, I am using a simple iteration for which I reject the choice whenever is too next to any element, but it is cumbersome and tends to be long if the number of elements to pick is high. Is there a best-practice/function for this?




SQL server - Masking / changing value uniqueidentifier before inserting

So the main goal is to mask or randomly change value of uniqueidentifier before inserting.

For example: I have a table

Create table Student
(
Student_ID masked WITH (FUNCTION='default()') DEFAULT NEWID()
Student_Name varchar(100),
)

Im inserting new data:

insert into DDM_Student_Sample values ('B9BC5E61-0F3C-498F-AF2C-1AC16446A846','Stuart Little Joe')

The result is the same output as it was inserted, i.e. uniqueidentifier = 'B9BC5E61-0F3C-498F-AF2C-1AC16446A846'

I have created a user with login:

CREATE USER MAIN_USER FOR LOGIN MAIN_USER; 
EXEC sp_addrolemember 'db_owner', 'MAIN_USER';

By toturial (http://www.sqlservercentral.com/articles/Security/149689/) it says you must create user without login. Maybe thats the problem why Student_ID does not change randomly.

In the end, maybe there is another way before inserting data to table change it value randomly. Or I should just change value from front-end? And write something like :

model.StudentId = Guid.NewGuid();
model.SaveToDatabase();




mardi 24 avril 2018

Random Numbers in Java and frequency

How do I convert a list of random numbers into an array form in java. Example:

1 5 3 8 9 1 5 7 8 4 2 1

How do I put this in an array and count the frequency for the number of times each number occurs?




Random Color to SVG rect

How can I make this possible? It's not working. I would like that the color of the rect changes after reload to one of the colors in the array.

This method isn't working. Can anybody help?

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 72 72">
<defs>
    <style>
        .cls-1 {
            fill: #ff0000;
        }

        .cls-2 {
            fill: #fff;
        }
    </style>
</defs>
<title>Logo MC</title>
<g id="Ebene_2" data-name="Ebene 2">
    <g id="Ebene_1-2" data-name="Ebene 1">
        <rect class="cls-1" width="72" height="72" />
        <path class="cls-2" d="M12,20.41h4.62l7.61,13.17h.28l7.61-13.17h4.66V45.29H32.15V33l.28-4.17h-.28L25.83,40H23L16.65,28.85h-.28L16.65,33V45.29H12Z" />
        <path class="cls-2" d="M63.22,41.29a12.21,12.21,0,0,1-4.34,3.39,13.84,13.84,0,0,1-10.76.16,13.18,13.18,0,0,1-6.86-17.12,12.54,12.54,0,0,1,6.86-6.86,13.15,13.15,0,0,1,5.16-1,11.75,11.75,0,0,1,9.32,4.07l-3.31,3.19a8.93,8.93,0,0,0-2.55-2.05,7.19,7.19,0,0,0-3.42-.76,8.68,8.68,0,0,0-3.27.61,7.82,7.82,0,0,0-2.66,1.72,8.17,8.17,0,0,0-1.79,2.69,9.77,9.77,0,0,0,0,7.06,8.17,8.17,0,0,0,1.79,2.69,8,8,0,0,0,2.66,1.72,8.88,8.88,0,0,0,3.27.61,7.92,7.92,0,0,0,3.7-.85,9.09,9.09,0,0,0,2.86-2.42Z" />
        <path class="cls-2" d="M14,53.11h0a1.33,1.33,0,0,1-.14.19,1,1,0,0,1-.2.16,1.23,1.23,0,0,1-.26.12,1.65,1.65,0,0,1-.32,0,1,1,0,0,1-.45-.1,1,1,0,0,1-.36-.27,1.13,1.13,0,0,1-.25-.41,1.32,1.32,0,0,1-.1-.53,1.27,1.27,0,0,1,.1-.52,1.13,1.13,0,0,1,.25-.41,1,1,0,0,1,.36-.27A1,1,0,0,1,13,51a1.06,1.06,0,0,1,.58.15,1,1,0,0,1,.34.35h0l0-.34V50h.32v3.58H14Zm-.89.22a.8.8,0,0,0,.34-.07.69.69,0,0,0,.28-.2.87.87,0,0,0,.2-.32,1.14,1.14,0,0,0,.07-.43,1.18,1.18,0,0,0-.07-.43,1,1,0,0,0-.2-.32.77.77,0,0,0-.28-.19.8.8,0,0,0-.34-.07.83.83,0,0,0-.34.07.9.9,0,0,0-.28.2,1.16,1.16,0,0,0-.2.32,1.33,1.33,0,0,0,0,.85,1,1,0,0,0,.2.32.9.9,0,0,0,.28.2A.83.83,0,0,0,13.08,53.33Z" />
        <path class="cls-2" d="M18.49,53a1.38,1.38,0,0,1-.17.25.93.93,0,0,1-.23.21,1.4,1.4,0,0,1-.3.15,1.52,1.52,0,0,1-.38,0,1.16,1.16,0,0,1-.49-.1.94.94,0,0,1-.38-.27,1.25,1.25,0,0,1-.26-.41,1.51,1.51,0,0,1-.09-.53,1.69,1.69,0,0,1,.08-.5,1.38,1.38,0,0,1,.24-.41,1.2,1.2,0,0,1,.38-.29,1.1,1.1,0,0,1,.49-.1,1.21,1.21,0,0,1,.48.09,1,1,0,0,1,.36.26,1.13,1.13,0,0,1,.23.4,1.46,1.46,0,0,1,.09.52v0a0,0,0,0,0,0,0v0h-2a1,1,0,0,0,.3.73.79.79,0,0,0,.29.17.89.89,0,0,0,.31.06.79.79,0,0,0,.49-.14,1.22,1.22,0,0,0,.3-.37Zm-.29-.86a.85.85,0,0,0-.05-.26.73.73,0,0,0-.14-.26.71.71,0,0,0-.25-.2.9.9,0,0,0-.39-.08,1,1,0,0,0-.29.05,1,1,0,0,0-.25.15.79.79,0,0,0-.19.25,1,1,0,0,0-.1.35Z" />
        <path class="cls-2" d="M21.36,53.62a1.15,1.15,0,0,1-.37-.06,1.32,1.32,0,0,1-.29-.15,1.2,1.2,0,0,1-.22-.23.87.87,0,0,1-.14-.27l.28-.12a.92.92,0,0,0,.3.41.8.8,0,0,0,.44.13.75.75,0,0,0,.47-.13.38.38,0,0,0,.17-.3.37.37,0,0,0,0-.15.24.24,0,0,0-.09-.12.55.55,0,0,0-.17-.1l-.28-.09-.34-.08-.24-.08a.78.78,0,0,1-.22-.12,1,1,0,0,1-.17-.19.53.53,0,0,1-.06-.26.61.61,0,0,1,.08-.3.73.73,0,0,1,.21-.22,1,1,0,0,1,.3-.13,1.41,1.41,0,0,1,.35-.05,1,1,0,0,1,.3,0,1.08,1.08,0,0,1,.27.1,1.24,1.24,0,0,1,.22.18,1,1,0,0,1,.15.25l-.28.11a.63.63,0,0,0-.28-.3.81.81,0,0,0-.39-.1.78.78,0,0,0-.22,0l-.19.08a.44.44,0,0,0-.14.13.26.26,0,0,0-.05.17.25.25,0,0,0,.13.24,1.18,1.18,0,0,0,.37.15l.36.09a1.09,1.09,0,0,1,.55.27.58.58,0,0,1,.18.42.59.59,0,0,1-.07.29.72.72,0,0,1-.19.24,1,1,0,0,1-.31.16A1.14,1.14,0,0,1,21.36,53.62Z" />
        <path class="cls-2" d="M24.41,50.45a.21.21,0,0,1-.17-.07.23.23,0,0,1-.08-.17.25.25,0,0,1,.08-.18.21.21,0,0,1,.17-.07.24.24,0,0,1,.18.07.29.29,0,0,1,.07.18.26.26,0,0,1-.07.17A.24.24,0,0,1,24.41,50.45Zm-.16,3.09V51.09h.32v2.45Z" />
        <path class="cls-2" d="M27.71,54.7a1.09,1.09,0,0,1-.42-.07,1,1,0,0,1-.31-.16,1,1,0,0,1-.22-.23,1.49,1.49,0,0,1-.13-.25l.3-.12a.72.72,0,0,0,.29.39.84.84,0,0,0,.49.15.84.84,0,0,0,.67-.26,1,1,0,0,0,.22-.71v-.32h0a1.06,1.06,0,0,1-.35.35,1,1,0,0,1-.55.15,1,1,0,0,1-.45-.1,1,1,0,0,1-.36-.27,1.48,1.48,0,0,1-.35-.94,1.3,1.3,0,0,1,.1-.52,1.22,1.22,0,0,1,.25-.41,1,1,0,0,1,.36-.27,1,1,0,0,1,.45-.1,1,1,0,0,1,.55.15,1,1,0,0,1,.35.34h0v-.41h.31v2.37a1.45,1.45,0,0,1-.09.54,1,1,0,0,1-.26.39,1,1,0,0,1-.38.23A1.4,1.4,0,0,1,27.71,54.7Zm0-1.37a.8.8,0,0,0,.34-.07.76.76,0,0,0,.28-.2,1,1,0,0,0,.2-.31,1.2,1.2,0,0,0,.07-.44,1.18,1.18,0,0,0-.07-.43,1.16,1.16,0,0,0-.2-.32.87.87,0,0,0-.28-.19.8.8,0,0,0-.34-.07.78.78,0,0,0-.33.07,1,1,0,0,0-.47.52,1.08,1.08,0,0,0-.08.42,1.18,1.18,0,0,0,.08.43,1,1,0,0,0,.47.52A.78.78,0,0,0,27.72,53.33Z" />
        <path class="cls-2" d="M31.31,51.55h0l.14-.21.2-.17a1,1,0,0,1,.25-.12.88.88,0,0,1,.29,0,.94.94,0,0,1,.39.07.78.78,0,0,1,.29.21.83.83,0,0,1,.16.31,1.29,1.29,0,0,1,.06.4v1.54h-.32V52.06a.81.81,0,0,0-.18-.58.64.64,0,0,0-.49-.18.72.72,0,0,0-.32.08.82.82,0,0,0-.25.21,1.08,1.08,0,0,0-.16.3,1,1,0,0,0-.06.35v1.3H31V51.09h.3Z" />
        <path class="cls-2" d="M37.86,51.09h.3v.46h0a1.2,1.2,0,0,1,.13-.21,1.54,1.54,0,0,1,.19-.17,1.34,1.34,0,0,1,.24-.12A.78.78,0,0,1,39,51a.73.73,0,0,1,.5.16.84.84,0,0,1,.27.4,1.09,1.09,0,0,1,.34-.4.89.89,0,0,1,.54-.16.86.86,0,0,1,.38.07.75.75,0,0,1,.26.2.81.81,0,0,1,.15.31,1.6,1.6,0,0,1,.05.39v1.56h-.32V52a.93.93,0,0,0-.14-.55.54.54,0,0,0-.46-.19.61.61,0,0,0-.3.08.74.74,0,0,0-.23.2.85.85,0,0,0-.15.3,1,1,0,0,0-.06.34v1.32h-.32V52.05a.87.87,0,0,0-.14-.56.52.52,0,0,0-.45-.19.61.61,0,0,0-.3.08.69.69,0,0,0-.24.21.89.89,0,0,0-.15.31,1.49,1.49,0,0,0,0,.36v1.28h-.32Z" />
        <path class="cls-2" d="M45.2,53.1h0a1,1,0,0,1-.35.37.88.88,0,0,1-.51.15,1.06,1.06,0,0,1-.37-.06,1,1,0,0,1-.3-.17.79.79,0,0,1-.19-.26.72.72,0,0,1-.07-.33.67.67,0,0,1,.08-.35.78.78,0,0,1,.22-.26A1.26,1.26,0,0,1,44,52a1.75,1.75,0,0,1,.4-.05,1.53,1.53,0,0,1,.45.06,1.33,1.33,0,0,1,.33.13V52a.73.73,0,0,0-.06-.3.63.63,0,0,0-.16-.23.7.7,0,0,0-.24-.15.87.87,0,0,0-.28-.05.85.85,0,0,0-.4.1.78.78,0,0,0-.29.28l-.28-.17a1,1,0,0,1,.39-.36,1.2,1.2,0,0,1,.57-.13,1.23,1.23,0,0,1,.44.07.93.93,0,0,1,.33.21.84.84,0,0,1,.22.31,1.07,1.07,0,0,1,.07.41v1.53H45.2Zm0-.65a1.66,1.66,0,0,0-.33-.15,1.2,1.2,0,0,0-.4-.06,1.36,1.36,0,0,0-.3,0,.9.9,0,0,0-.24.12.52.52,0,0,0-.16.17.5.5,0,0,0-.06.24.54.54,0,0,0,0,.22.57.57,0,0,0,.15.16.64.64,0,0,0,.2.11.85.85,0,0,0,.23,0,.71.71,0,0,0,.32-.07.77.77,0,0,0,.28-.19.92.92,0,0,0,.19-.28A.8.8,0,0,0,45.2,52.45Z" />
        <path class="cls-2" d="M48.11,52.85a.43.43,0,0,0,.11.32.28.28,0,0,0,.24.11h.12l.12,0,.1.27a.49.49,0,0,1-.17.06l-.21,0a.64.64,0,0,1-.44-.17.6.6,0,0,1-.14-.2.85.85,0,0,1-.05-.3V51.38h-.44v-.29h.44v-.75h.32v.75h1.12v-.75h.32v.75h.61v.29h-.61v1.47a.43.43,0,0,0,.11.32.28.28,0,0,0,.24.11H50l.12,0,.1.27a.49.49,0,0,1-.17.06l-.21,0a.64.64,0,0,1-.44-.17.6.6,0,0,1-.14-.2.85.85,0,0,1-.05-.3V51.38H48.11Z" />
        <path class="cls-2" d="M54.27,53a1.38,1.38,0,0,1-.17.25.93.93,0,0,1-.23.21,1.4,1.4,0,0,1-.3.15,1.52,1.52,0,0,1-.38,0,1.16,1.16,0,0,1-.49-.1,1.05,1.05,0,0,1-.39-.27,1.41,1.41,0,0,1-.25-.41,1.51,1.51,0,0,1-.09-.53,1.69,1.69,0,0,1,.08-.5,1.38,1.38,0,0,1,.24-.41,1.2,1.2,0,0,1,.38-.29,1.1,1.1,0,0,1,.49-.1,1.21,1.21,0,0,1,.48.09,1,1,0,0,1,.36.26,1.13,1.13,0,0,1,.23.4,1.46,1.46,0,0,1,.09.52v0a0,0,0,0,0,0,0v0h-2a1,1,0,0,0,.3.73.79.79,0,0,0,.29.17.89.89,0,0,0,.31.06.79.79,0,0,0,.49-.14,1.22,1.22,0,0,0,.3-.37ZM54,52.1a.85.85,0,0,0,0-.26.73.73,0,0,0-.14-.26.71.71,0,0,0-.25-.2.9.9,0,0,0-.39-.08,1,1,0,0,0-.29.05,1,1,0,0,0-.25.15.79.79,0,0,0-.19.25,1,1,0,0,0-.1.35Z" />
        <path class="cls-2" d="M56.26,53.54V51.09h.3v.43h0a.78.78,0,0,1,.11-.2.9.9,0,0,1,.18-.16.7.7,0,0,1,.21-.11.51.51,0,0,1,.2,0l.19,0,.15,0-.1.29a.7.7,0,0,0-.28,0,.59.59,0,0,0-.25.07.68.68,0,0,0-.21.17.72.72,0,0,0-.14.26,1,1,0,0,0-.06.34v1.38Z" />
        <path class="cls-2" d="M60.19,53.62a1,1,0,0,1-.36-.06,1,1,0,0,1-.52-.38.87.87,0,0,1-.14-.27l.28-.12a.92.92,0,0,0,.3.41.8.8,0,0,0,.44.13.75.75,0,0,0,.47-.13.38.38,0,0,0,.17-.3.37.37,0,0,0,0-.15.24.24,0,0,0-.09-.12.55.55,0,0,0-.17-.1l-.28-.09-.34-.08-.24-.08a.78.78,0,0,1-.22-.12,1,1,0,0,1-.17-.19.53.53,0,0,1-.06-.26.61.61,0,0,1,.08-.3.73.73,0,0,1,.21-.22,1,1,0,0,1,.3-.13,1.41,1.41,0,0,1,.35-.05,1,1,0,0,1,.3,0,1.08,1.08,0,0,1,.27.1,1.24,1.24,0,0,1,.22.18,1,1,0,0,1,.15.25l-.28.11a.67.67,0,0,0-.27-.3.88.88,0,0,0-.4-.1.78.78,0,0,0-.22,0l-.19.08a.58.58,0,0,0-.14.13.34.34,0,0,0,0,.17.25.25,0,0,0,.13.24,1.18,1.18,0,0,0,.37.15l.36.09a1.17,1.17,0,0,1,.56.27.61.61,0,0,1,.17.42.59.59,0,0,1-.07.29.61.61,0,0,1-.19.24.91.91,0,0,1-.31.16A1.14,1.14,0,0,1,60.19,53.62Z" />
    </g>
</g>
<script type="text/javascript">
    var colors = ['#ff0000', '#00ff00', '#0000ff'];
    var random_color = colors[Math.floor(Math.random() * colors.length)];
    document.getElementsByClassName('cls-1').fill = random_color;
</script>




math.floor and math.radom are one index off

I'm building a small tic tac toe game.

When it is the computer turn to play, I make him pick a random number to pick an element from an array.

My problem is that the random number will be 3 for example, but the element picked from the array won't be arr[3], but arr[4].

it is a problem because if the number picked is the end of the array, it will return undefined.

here is the javascript code:

var grid = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9'];
var choice = 9;

function myFunction(clicked_id){
  $('#' + clicked_id).html('X');
  grid.splice(grid.indexOf(clicked_id), 1);
  choice -+ 1;
    setTimeout(computer, 1000);
  player.push(clicked_id);
  findElement(player);
  console.log(player);
  console.log(grid);
  console.log(grid.length)

}

function computer(){
  var ran = Math.floor(Math.random() * choice);
  var res = grid[ran - 1];
    $('#' + res).html('O');
    grid.splice(grid.indexOf(res), 1);
  cpu.push(grid[ran]);
  findElement(cpu);
  choice -= 1;
  console.log(ran);
  console.log(cpu);
} 

Here is what will be logged in the console log: ["item1"] -> What I clicked on

["item2", "item3", "item4", "item5", "item6", "item7", "item8", "item9"] -> new modified array after using splice.

8 -> new array length

5 - random number picked by computer

["item8"] -> element picked by the computer in the array (arr[6])

'item6' is the box checked on the tic tac toe game.

Here is a link to my codepen to see the code in action.

https://codepen.io/nico3d911/pen/odvmPR?editors=0001

Thanks for your help!




C++, How to add random char to a existing string?

Im trying to add a random char (A-Z,a-z) to a existing string. (The string is char *)

I can only use:

iostream, time.h, assert.h.

I saw some tutorials but it dosnt help because they using string class.




Is it possible to set a step with random.uniform?

I'm making a game in python that has user set variables, but to get the correct coords for certain elements within the game I need float values. I used the random.uniform function but you cannot set a step and this is something I need. is it possible and if not is there another way I can achieve what I need.

I have provided what I'm doing below, thank you in advance.

coord = (uniform(self.Player_Movement, (600 - self.Player_Movement), self.Grid_Rectangle), uniform((50 + self.Player_Movement), (600 - self.Player_Movement), self.Grid_Rectangle))




Spark sample is too slow

I'm trying to execute a simple random sample wth Scala from an existing table, possibly ~100e6 records.

import org.apache.spark.sql.SaveMode

val nSamples = 3e5.toInt
val frac = 1e-5
val table = spark.table("db_name.table_name").sample(false, frac).limit(nSamples)
(table
  .write
  .mode(SaveMode.Overwrite)
  .saveAsTable("db_name.new_name")
)

But it is taking too long (~5h by my estimates).

Useful information:

  1. I have ~6 workers. By analyzing the number of partitions of the table I get: 11433.

  2. I'm not sure if the partitions/workers ratio is reasonable.

  3. I'm running Spark 2.1.0 using Scala.

I have tried:

  1. Removing the .limit() part.

  2. Changing frac to 1.0, 0.1, etc.

Best,




Generating random numbers with Only integers, not floats

I have created a python script where I have 4 empty lists, and the code creates a random numbers on those lists, and in the end, it saves it as an Excel file. The issue is there that it creates numbers with floats, and I only want integers! Could somebody help me?

Here is my code:

import numpy as np
import openpyxl
import random

from openpyxl import Workbook

# Create workbook object
wb = openpyxl.Workbook()
sheet = wb.get_active_sheet()

sheet.title = 'Sheet #1'



# Generate data

Timestamp = [0, 1, 2, 3, 4, 5, 6, 7,8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]

Subtotal_vest = []

Subtotal_NorthEast = []

Subtotal_south = []

Others = []



for i in Timestamp:
    Subtotal_vest.append(random.gauss(3640, 25)),
    Subtotal_NorthEast.append(random.gauss(3832, 25)),
    Subtotal_south.append(random.gauss(2592, 25)),
    Others.append(random.gauss(1216, 25)),







#y = x * x

# Add titles in the first row of each column
sheet.cell(row=1, column=1).value = 'Timestamp'
sheet.cell(row=1, column=2).value = 'Vest'
sheet.cell(row=1, column=3).value = 'North east'
sheet.cell(row=1, column=4).value = 'South'
sheet.cell(row=1, column=5).value = 'Others'

#sheet.cell(row=1, column=2).value = 'Y values'

# Loop to set the value of each cell

for inputs in range(0, len(Timestamp)):
    sheet.cell(row=inputs + 2, column=1).value = Timestamp[inputs]
    sheet.cell(row=inputs + 2, column=2).value = Subtotal_vest[inputs]
    sheet.cell(row=inputs + 2, column=3).value = Subtotal_NorthEast[inputs]
    sheet.cell(row=inputs + 2, column=4).value = Subtotal_south[inputs]
    sheet.cell(row=inputs + 2, column=5).value = Others[inputs]



# Finally, save the file and give it a name
wb.save('Excel/Matrix.xlsx')




function that should Generate random matrix with sums of rows/columns defined as input lists

I've a task to make fuction that generates random matrix from non negative integers in range (0-8)

  • Input of the function are 2 lists :
    • sumForEveryCol
    • sumForEveryRow
  • Each list contains sum of the values for every rows/columns
  • Example: sumForEveryRow should contain sums for every row by it's index ( sumForEveryRow[0] = sum of the first row ... etc.)
  • sumForEveryColumn[0] = sum of the first column .. sumForEveryColumn[1] - second column .. etc.)
  • Sum of every row or column is constant value of 40
  • Value of any cell should be in range 0, 8

I've strange ideas (code below) but there is no chance to work at all.. because of the algorithm... What is the algorithm in general to generate such matrix and what is the best way to implement it in python

Example:

sumsForEveryRow = [4,20,8,8] = constant 40
sumsForEveryCol = [8,8,8,8,8] = constant 40

gen_random_matrix(sumForEveryRow, sumForEveryCol) should produce random matrix like:

[ 0 , 2 , 0 , 0 , 2 ],  - sum of row 1 should be 4
[ 1 , 2 , 8 , 5 , 4 ],  - sum of row 2 should be 20
[ 3 , 2 , 0 , 3 , 0 ],  - sum of row 3 should be 8
[ 4 , 2 , 0 , 0 , 2 ],  - sum of row 4 should be 8
sum for every column should be
  8   8   8   8   8



import random
import numpy

sumsForEveryCol = [8,8,8,8,8]
sumsForEveryRow = [4,20,8,8]
def gen_random_matrix(sumForEveryCol, sumForEveryRow):
    sum = 40
    max_value_cell = 8
    num_of_rows = len(sumsForEveryRow)
    num_of_cols = len(sumsForEveryCol)
    matrix = numpy.zeros((num_of_rows, num_of_cols), dtype=numpy.int)

    for i in range(0, num_of_rows - 1):
        cur_row_sum = sumsForEveryRow[i]
        for j in range(0, num_of_cols - 1):
            if max_value_cell >= cur_row_sum:
                if cur_row_sum == 0:
                    matrix[i][j] = 0
                else:
                    # Dont generate 0 values ????
                    rand_digit = random.randint(1, cur_row_sum)
                    cur_row_sum = cur_row_sum - rand_digit
                    matrix[i][j] = rand_digit
            else:
                rand_digit = random.randint(0, max_value_cell)
                matrix[i][j] = rand_digit
                cur_row_sum = cur_row_sum - rand_digit


    return matrix




WordPress: Show random 4 categories with 3 last posts

I am busy to build a row that will show randomly 4 categories with the category title and the 3 latest posts under it. But i am stuck how i can get the categories in random order because the 'orderby' is not working...

Can somewone help me with that?

The code i am using:

 <?php
    //for each category, show all posts
    $cat_args   = array(
        'orderby' => 'rand',
        'order' => 'ASC'
    );
    $limit      = 4;
    $counter    = 0;
    $categories = get_categories($cat_args);

    foreach ($categories as $category):
        if ($counter < $limit) {
            $args  = array(
                'showposts' => 3,
                'category__in' => array(
                $category->term_id
            ),
            'caller_get_posts' => 1
        );
        $posts = get_posts($args);
        if ($posts) {
            echo '<h3><a href="' . get_category_link($category->term_id) . '" title="' . sprintf(__("View all posts in %s"), $category->name) . '" ' . '>' . $category->name . '</a> </h3>';
            foreach ($posts as $post) {
                setup_postdata($post);
?>

<p><a href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>

<?php
            } // foreach($posts
        } // if ($posts
    } // foreach($categories
?>

<?php
    $counter++;
    endforeach;
?>




lundi 23 avril 2018

How to add image links to random slideshow in Javascript

I am (very) novice and trying to help a friend with a website. I came across the javascript code below, but i'm struggling to make the images link to a separate webpage when clicked. I would appreaciate any help!

<script language="javascript">

var delay=1000 //set delay in miliseconds
var curindex=0

var randomimages=new Array()

randomimages[0]="1.jpg"
randomimages[1]="5.jpg"
randomimages[2]="2.jpg"
randomimages[3]="4.jpg"
randomimages[4]="3.jpg"
randomimages[5]="6.jpg"

var preload=new Array()

for (n=0;n<randomimages.length;n++)
{
preload[n]=new Image()
preload[n].src=randomimages[n]
}

document.write('<img name="defaultimage" 
src="'+randomimages[Math.floor(Math.random()*(randomimages.length))]+'">')

function rotateimage()
{

if (curindex==(tempindex=Math.floor(Math.random()*(randomimages.length)))){
curindex=curindex==0? 1 : curindex-1
}
else
curindex=tempindex

document.images.defaultimage.src=randomimages[curindex]
}

setInterval("rotateimage()",delay)

</script>




Hibernate + MySQL - How can I get not guessable generated ID?

How can I get entity ID (primary key) to be hard to guess?

Ideal would be 8 or 16 digit random unique number or String.

I tried UUID but it fails with my H2 tests because of reported bug (https://github.com/h2database/h2database/issues/345).

Or if it's hard with ID... how can I get another column to be auto generated with random unique number while creating ?

I need random, hard to guess, unique ID per user for external API.

Thanks for any suggestions. :)




Randomly shuffle the pages of a PDF file using pyPDF or PyPDF2

I'm not very experienced in programming. What I'm trying to do is to randomly shuffle the pages of a pdf and output it to another pdf.

Searching online I found the following two solutions (source 1, source 2):

#!/usr/bin/env python2
import random, sys

from PyPDF2 import PdfFileWriter, PdfFileReader
input = PdfFileReader(sys.stdin)
output = PdfFileWriter()
pages = range(input.getNumPages())
random.shuffle(pages)
for i in pages:
     output.addPage(input.getPage(i))
output.write(sys.stdout)

And this one:

#!/usr/bin/python

import sys
import random

from pyPdf import PdfFileWriter, PdfFileReader


# read input pdf and instantiate output pdf
output = PdfFileWriter()
input1 = PdfFileReader(file(sys.argv[1],"rb"))

# construct and shuffle page number list
pages = list(range(input1.getNumPages()))
random.shuffle(pages)

# display new sequence
print 'Reordering pages according to sequence:'
print pages

# add the new sequence of pages to output pdf
for page in pages:
    output.addPage(input1.getPage(page))

# write the output pdf to file
outputStream = file(sys.argv[1]+'-mixed.pdf','wb')
output.write(outputStream)
outputStream.close()

I tried both (and both with PyPDF2 and pyPdf) and both indeed create a new pdf file, but this file is simply empty (and has 0KB) (when I enter, let's say "shuffle.py new.pdf").

I'm using PyCharm and one problem I encounter (and not really understand) is that it says: "Cannot find reference 'PdfFileWriter'".

PyCharm tells me that it cannot find the reference

I would appreciate any help understanding what I'm doing wrong :)




Make an image appear at the X,Y position of a random generator

I have a RNG set up to spawn "ocs" in a small game, I have an image source set up for how I want the orc to look but I cannot get the orc image to appear at the points of randomYposition and orcXposition.

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>17013455_assignment_2</title>
</head>
<body>
<canvas id="canvas"></canvas>
<script src="17013455_ass2_task1.js"></script>
</body>
</html>

Here is my code:

    window.onload=function () {
    var canvas = document.getElementById("canvas");
    var gc = canvas.getContext("2d");
    canvas.width = 640;
    canvas.height = 448;
    gc.clearRect(0, 0, canvas.width, canvas.height);
    var orc = new Image();
    orc.src = "https://imgur.com/MIWLkHT";
    var background = new Image();
    background.src = "https://i.imgur.com/9mPYXqC.png";
    background.onload = function () {
        gc.drawImage(background, 0, 0)
    };


    //sword dimentions
    var swordHeight = 50;
    var swordWidth = 25;
    var swordX = 50;
    var swordY = 220;

    //orc dimentions
    var orcWidth = 5;
    var orcHeight = 10;

    //controls for player
    var upPressed = false;
    var downPressed = false;

    function keyUpHandler(e) {
        if (e.keyCode === 38) {
            upPressed = false;
        }
        else if (e.keyCode === 40) {
            downPressed = false;
        }
    }

    function drawSword() {
        /*Make a box to represent a sword until sprites are used*/
        gc.beginPath();
        gc.rect(swordX, swordY, swordWidth, swordHeight);
        gc.fillStyle = "#000000";
        gc.fill();
        gc.closePath();
    }

    var orcs = [];
    function spawnorc() {
        drawOrc();
        console.log('spawn an orc');
        var randomYposition = Math.floor(Math.random() * (canvas.height - 
    orcHeight));
        var orcXposition = canvas.width - 20;
        var newOrc = {
            x: orcXposition,
            y: randomYposition
        };
        function drawOrc() {
            orc.onload = function () {
                gc.drawImage(orc, randomYposition, orcXposition, orcWidth, 
    orcHeight);
            }
        }
        orcs.push(newOrc);
        console.log(newOrc);
    }

    function keyDownHandler(e) {
        if (e.keyCode === 38) {
            upPressed = true;
        }
        else if (e.keyCode === 40) {
            downPressed = true;
        }
    }

    function render() {
        if (downPressed && swordY < canvas.height - swordHeight) {
            swordY += 3;
        }
        else if (upPressed && swordY > 0) {
            swordY -= 3;
        }
        gc.drawImage(background, 0, 0);
        drawSword();
    }

    document.addEventListener("keydown", keyDownHandler, "false");
    document.addEventListener("keyup", keyUpHandler, "false");

    render();
    spawnorc();
    setInterval(spawnorc, 3000);
    setInterval(render, 10);

    };

The log shows that the number generator is working and spawning an "orc" however if I try and put "spawn orc" in the render function they spawn far too quickly, but I'm not sure how to get the orc to appear at the points without having it render.




How to get n random "paragraphs" (groups of ordered lines) from a file

I have a file with a known structure - each 4%1=1 line starts with the character "@" and defines an ordered group of 4 lines. I want to select randomly n groups (half) of lines in the most efficient way (preferably in bash/another Unix tool).

My suggestion in python is:

path = "origin.txt"
new_path = "subset.txt"
import random
with open(path) as f:
  subset_size = round((len(lines)/4) * 0.5)
  lines = f.readlines()
  l = random.sample(list(range(0, len(lines), 4)),subset_size)
  selected_lines = [line for i in l for line in list(range(i,i+4))]
  with open(new_path,'w+') as f2:
    f2.writelines(new_lines)

Can you help me find another (and faster) way to do it?




dimanche 22 avril 2018

"Segmentation fault 11" crashing in for loop

I'm super new to C programming, only taking it for a required course in uni and finally getting done with my final project this week.

Problem is every time I run this code I get an error message that says "segmentation fault: 11" and I'm not sure what that means.

The code is supposed to run two-player race. Each player has a pre-determined "speed modifier", aka a number from 0-9. A random number from 1-10 is generated; if the speed modifier + the random number doesn't exceed 10, then the speed modifier is added and the car moves that total amount of "spaces". The whole race track is 90 "spaces".

Every time I run this code it works somewhat fine (more on that later) for one or two iterations, then gives out that error message. I normally don't ask for homework help online but I'm honestly so confused. Any help at all would be super appreciated.

Here is the relevant code:

Race (main) function:

int race(struct car cars[4], int mode)
{
/* Define variables. */
int endgame, i, x, y, first=-1, second=-1, randnum, spaces[]={};
char input[100];
/* Declare pointer. */
int *spacesptr=spaces;

for (i=0; i<mode; i++)
{
    /* Array spaces will keep track of how many spaces a car has moved. Start each car at 0. */
    spaces[i]=0;
}

/* Clear screen before race. */
system("cls");

/* Print message to indicate race has started. */
printf("\n3...\n2...\n1...\nGO!\n\n");

/* Open do while loop to keep race running until it is over. */
do
{
    /* Conditions for two player mode. */
    if (mode==2)
    {
        /* Run the next block of code once for each player. */
        for (i=0; i<mode; i++)
        {
            /* Generate random integer from 1-10 to determine how many spaces the car moves. */
            x=10, y=1;
            randnum=(getrandom(x, y));
            spaces[i]=spaces[i]+randnum;

            /* Call function speedmod to determine if speedmodifier should be added. */
            speedmod(cars, spaces, randnum);

            /* Rank players. */
            if (spaces[i]>89)
            {
                if (first==-1)
                {
                    first=i;
                }

                else if (second==-1)
                {
                    second=i;
                }

            }

        }
    }

    ...

    /* Call function displayrace to display the race. */
    displayrace(cars, spaces, mode);

    /* Call function endgame to determine if the race is still going. */
    endgame=fendgame(mode, spaces);

    if (endgame==0)
    {
        /* Ask for player input. */
        printf("Enter any key to continue the race:\n");
        scanf("%s", input);

        /* Clear screen before loop restarts. */
        system("cls");
    }

} while (endgame==0);
}

Random number function:

int getrandom(int x, int y)
{
/* Define variable. */
int randnum;

/* Use time seed. */
srand(time(0));

/* Generate random numbers. */
randnum=(rand()+y) % (x+1);

return randnum;
}

Add speed modifier function:

void speedmod(struct car cars[4], int spaces [], int go)
{
/* Declare pointer. */
int *spacesptr=spaces;

/* If the number of spaces plus the speed modifier is less than or equal to ten... */
if (spaces[go]+cars[go].speedmod<=10)
{
    /* ...add the speed modifier to the number of spaces moved. */
    spaces[go]=spaces[go]+cars[go].speedmod;
}
}

Display race function:

void displayrace(struct car cars[4], int spaces[], int mode)
{
/* Define variables. */
int i, j;

/* Declare pointers. */
int *spacesptr=spaces;
struct car *carsptr=cars;

/* Open for loop. */
for (i=0; i<mode; i++)
{
    /* Print racecar number. */
    printf("#%d\t", cars[i].carnumber);

    /* For every space the car has moved... */
    for (j=0; j<spaces[i]; j++)
    {
        if (j<=90)
        {
            /* ...print one asterisk. */
            printf("*");
        }
    }

    /* New line. */
    printf("\n");
}
}

End game function:

int fendgame(int mode, int spaces[])
{
/* Define variables. */
int racers=0, endgame=0, i;
/* Declare pointer. */
int *spacesptr=spaces;

/* Open for loop. */
for (i=0; i<mode; i++)
{
    /* If any of the racers have not yet crossed the finish line (90 spaces)... */
    if (spaces[i]<=90)
    {
        /* ...then add to the number of racers still in the game. */
        racers++;
    }
}

/* If all the racers have crossed the finish line... */
if (racers==0)
{
    /* ...then end the game. */
    endgame=1;
}

return endgame;
}

Now to be more specific on the issue...it's messing up somewhere on the "for" loop in the race function. For some reason it doesn't actually go through each iteration of "i", specifically in this line:

spaces[i]=spaces[i]+randnum;

I know this because I put in printf statements to display the value of spaces[i] before and after; the first iteration of i works fine...but the second iteration actually uses spaces[i-1] instead and adds the randnum to that value?

And then, like I said, it crashes after one or two times of this...:-(

I know it's a lot but I'm hoping someone more experienced than I could spot the error(s) in this code for me! Please help!




show random image on Processing

I'm really noob on processing and programing and I can't figure it out how to show my images at random.

I'm loading the images in setup with the PImage name img0, img1, img2 and then

image("img" + random(3), 0, 0); 

But it does't work, coz processing wait for a PImage argument, and the string plus a number isn't.

And I know for shure there must be some better way than:

int randomNumber = random(3);

if(randomNumber == 0 ){ 
   image(img0,0,0);
} 
if(randomNumber == 1 ){ 
    image(img1,0,0);
} 
if(randomNumber == 2 ){
    image(img2,0,0);
} 

But I haven't found it.

Any thoughts? thanks!




update sql with two values in several times

I want to update my table based on 2 values (a, b), .. a: is the number that needs to stored and b: is the repeated times.. as examples (1, 17); (4, 5); (8, 7) .. so here needs to be store “1” in 17 times or 17 records, then go next to store value “4” in next 5 records then go next store “8” in next 7 records.. and so on till finish all (a,b) values .. total table records are 500, so here I will use allot of (a,b)

for($i = 1; $i<=$b; $i++) {

$sql = "UPDATE tbl_ AAA SET goals = '$a' WHERE goal_id = '$i' ";

Is there any simple solution that I paste my all (a,b) around 240 (a, b)




Blank text when using random package

I'm making a dice program and whenever I try to type "D4" (Since that's the only thing I have right now) I get the random numbers I coded in, then blank text.

I'm using:
Windows 10 Home
Python 3.6

This is my code:

from random import *
import os
import time
os.system('cls')

print("What dice would you like to roll?")

print("D4, D6, D10, D12, D20")

D4 = int(randint(1, 4))

D6 = int(randint(1, 6))

D10 = int(randint(1, 10))

D12 = int(randint(1, 12))

D20 = int(randint(1, 20))

age = int(D4)

diceI = input("Name: ")

if (diceI == D4):
    print("lol")

else:
    os.system('cls')
    time.sleep(.1)
    print("4")
    os.system('cls')
    time.sleep(.1)
    print("2")
    os.system('cls')
    time.sleep(.1)
    print("3")
    os.system('cls')
    time.sleep(.1)
    print("4")
    os.system('cls')
    time.sleep(.1)
    print("1")
    os.system('cls')
    time.sleep(.1)
    print("3")
    os.system('cls')
    time.sleep(.1)
    print("2")
    os.system('cls')
    time.sleep(.1)
    print(random.randint(1,4))

I understand that this is very messy code so I'll try and explain why I have certain things the way they are.

First of all, this: https://i.stack.imgur.com/6cvmD.png

The reason why I have this is because if I just try to have the "if" statement in the general the code, nothing shows up. That's why I just have it show up with the actual code in the else statement.

Second of all, this: https://i.stack.imgur.com/QBoj0.png

I know this can be very easily simplified, but the thing I'm trying to do is to show random numbers before the actual result comes in, giving the effect that it is actually a die that you're rolling.

I really hope somebody sees this, because I've been trying to fix it for around 5 days now.




Random word generator using python

I would like to generate random words from ascii codes. I have tried like that:

 import random

 liste = [random.randint(33, 127) for i in range(8)]
 osman=', '.join(str(x) for x in liste)
 a=bytes.fromhex(hex(liste[0])[2:]).decode()
 b=bytes.fromhex(hex(liste[1])[2:]).decode()
 c=bytes.fromhex(hex(liste[2])[2:]).decode()
 d=bytes.fromhex(hex(liste[3])[2:]).decode()
 e=bytes.fromhex(hex(liste[4])[2:]).decode()
 f=bytes.fromhex(hex(liste[5])[2:]).decode()
 g=bytes.fromhex(hex(liste[6])[2:]).decode()
 h=bytes.fromhex(hex(liste[7])[2:]).decode()

 print(a,b,c,d,e,f,g,h,sep="")

Is there an easier way and how can i develop for more words?




want the code to only print out quotes 1, 3 and 5 odd numbers

displayRandomQuote = function () {
    var quotes = {
        0: "All computers wait at the same speed.",
        1: "A good programmer looks both ways before crossing a one-way street.",
        2: "Computers do not solve problems, they execute solutions.",
        3: "The best thing about a boolean is even if you are wrong, you are only off by a bit",
        4: "Ubuntu is an ancient African word, meaning 'can’t configure Debian'",
        5: "Without requirements or design, programming is the art of adding bugs to an empty 'text' file."

    }
    var rand = Math.floor(Math.random() * Object.keys(quotes).length);
    console.log(quotes[rand]);
}
displayRandomQuote();




how to generate random and limited 128bit SUID key?

I'm doing some random generation of 128bit ID's in range between 0x00 and 0xff and I'm wondering which one of my 3 samples is superior (if any) aka if I will run each method x-times, which one of those will give me more unique ID's in a long run, and/or also which one will be less faulty in case of repeatings.

D2 ? D3 ? or D4?

I'm including my sheet because my formulas are very long: https://docs.google.com/spreadsheets/d/1O1B8R5MkKr9QNF2F3qskUVmAMQGhXOQBm7O8VifFFiM/edit?usp=sharing

my guess is that the weakest is D2

also... is it worth to do D3 over D4 in the name of more randomnes/originality? or is there even difference if I use RAND() in a first place. (I cant really tell if I probably dont see something what isnt there...)

??




Python programming language

I want to create a matrix of 100000x100000 and fill it with random integers in python. The output is "Memory error". Is it really memory problem? Can I allocate memory? Help, please!




samedi 21 avril 2018

How many random requests do I need to make to a set of records to get 80% of the records?

Suppose I have an array of 100_000 records ( this is Ruby code, but any language will do)

ary = ['apple','orange','dog','tomato', 12, 17,'cat','tiger' .... ]
results = []

I can only make random calls to the array ( I cannot traverse it in any way)

results << ary.sample 
# in ruby this will pull a random record from the array, and 
# push into results array

How many random calls like that, do I need to make, to get least 80% of records from ary. Or expressed another way - what should be the size of results so that results.uniq will contain around 80_000 records from ary.

From my rusty memory of Stats class in college, I think it's needs to be 2*result set size = or around 160_000 requests ( assuming random function is random, and there is no some other underling issue) . My testing seems to confirm this.

ary = [*1..100_000];
result = [];  
160_000.times{result << ary.sample}; 
result.uniq.size # ~ 80k

This is stats, so we are talking about probabilities, not guaranteed results. I just need a reasonable guess.

So the question really, what's the formula to confirm this?




Unicode entities not showing up in ReactNative app while testing through Android Expo client

I added Unicode entities and they are not showing up through Expo client in Android. I can see the characters through iOS Expo client.

This is my first test through react native. Not sure if i am missing any includes.

See the five unicode entries below "&#x0710..." enter image description here

Here is a screenshot from my Nexus 4 phone

enter image description here




Generating random numbers in a file, and calling them from the file, then printing them out

I'm trying to create a file that generates random numbers, then I want the program to call those random numbers and print them out. 1st; the srand (time(NULL)) function is giving me an error, 2nd; i want to check wether the loop and the formula i used to get random numbers are correct.

thanks.

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

using namespace std;
int rand(int x);

int main() {


ofstream outputFile;
outputFile.open("fileTest.txt");
// unsigned seed = time(0);

// srand(time(NULL));
int i;
for (i =0; i<23; i++){
outputFile << rand(i) <<endl;
}

ifstream inputFile;
inputFile.open ("fileTest.txt");

      int ranNum[i];

    for (int i = 190; i <= 270; i++)
    {
        ranNum[i] = (rand() % (270-190+1)+ 190);
        inputFile>> ranNum[i];
        cout<<ranNum [i]<<" "<<endl;
    }

  system("pause");

  return 0;
}




Execute code from non .py file in python

I am trying to make python execute a random line of code from a given file. Let's say I have a file called "code_lines". This file contains random pieces of python code, ex.

print("This is a random message")
print("This is another message")
print("This is getting boring")

Is it possible for python to select a random line from that file and run it as code?




c# delete previous random generated string

I have a program where it randomly generates a new password and then writes it on a text file.

The issue is that when I try to generate a new password, it writes the new password plus the previously generated password.

I want to just write down the newly generated password, excluding the previous one

This is the code for the string password:

        string password = "";
        string pathUserPass = @"C:\Users\Name\Desktop\test\UserPass.txt";
        string pathXD = @"C:\Users\Name\Desktop\test";
        var fileUserPass = new FileInfo(pathUserPass);
        string Response;

        int r, k;
        Random Rand = new Random();
        for (int i = 0; i < 10; i++)
        {
            r = Rand.Next(3);
            if (r == 0)
            {
                k = Rand.Next(0, 25);
                password += charPassword[k];
            }

            else if (r == 1)
            {
                k = Rand.Next(0, 25);
                password += charPassword[k];
            }

            else if (r == 2)
            {
                k = Rand.Next(0, 9);
                password += charPassword[k];
            }
        }

This is my code that writes a newly generated password:

        else if (File.Exists(pathUserPass) && fileUserPass.Length > 0)
        {
            while(true)
            {
                try
                {
                    using (var tw = new StreamWriter(pathUserPass, true))
                    {
                        while (password == password)
                        {
                            for (int i = 0; i < 10; i++)
                            {
                                r = Rand.Next(3);
                                if (r == 0)
                                {
                                    k = Rand.Next(0, 25);
                                    password += charPassword[k];
                                }

                                else if (r == 1)
                                {
                                    k = Rand.Next(0, 25);
                                    password += charPassword[k];
                                }

                                else if (r == 2)
                                {
                                    k = Rand.Next(0, 9);
                                    password += charPassword[k];
                                }
                            }
                            tw.WriteLine(password);
                            Console.WriteLine("Wrote {0}", password);
                        }
                    }
                    Console.Read();
                }
                catch (UnauthorizedAccessException e)
                {
                    Console.WriteLine(e);
                    Console.Read();
                }
                catch (IOException e)
                {
                    Console.WriteLine(e);
                    Console.Read();
                }
            }

OutPut:

awbicsoatfibutdbqgrf

awbicsoatfibutdbqgrfkabeokksnd

awbicsoatfibutdbqgrfkabeokksndedmmscajpd

awbicsoatfibutdbqgrfkabeokksndedmmscajpdjdcqsepbcg

awbicsoatfibutdbqgrfkabeokksndedmmscajpdjdcqsepbcgyidlctlcpk

awbicsoatfibutdbqgrfkabeokksndedmmscajpdjdcqsepbcgyidlctlcpkiidjfcbiih

awbicsoatfibutdbqgrfkabeokksndedmmscajpdjdcqsepbcgyidlctlcpkiidjfcbiihbccqhuxpgg

Any ideas of taking out the previous generated string? I appreciate anyone reading this. Thx :)