jeudi 24 janvier 2019

Randomize item from Array with exclude specific item in JavaScript

I wonder if there is any option to randomize an item from array and exclude specific item.

e.g: array=["a","-","b","c","d"] I want randomize letter from this array but not "-" char.

I know I can do a while loop and check if its the unwanted item. but its not a robust code, and may cause a lot of bugs.

I know I can put them into a new array but its wont help me for my needs.

Maybe its not possible but I just want to be sure. I will be grateful for any help Thank!




mercredi 23 janvier 2019

How can I set my variable in C++ to 0 and prevent it from getting random?

I am a beginner in programming. I was doing some simple applications. I was already done with my programme when I realised that my variable is getting random, even if I set it to 0. I was trying to figure it out why. My goal is to add 1 to the "cor" variable when the answer is matching the random generated number, the "else" section is working as it has to be. Maybe someone more experienced can help me.

`

#include <iostream>
#include <string>
#include <time.h>
#include <Windows.h>

using namespace std;

int number;
int ynumber[5];
int cor = 0;
int falsed = 0;

int main()
{
    cout << "Welcome to our lottery!" << endl; 

    cout << "We start in ..." << endl;
    Sleep(2000);


    for (int i = 3; i >= 0; i--)
    {
        system("cls");
        cout << i << endl;
        Sleep(1000);
    }

    system("cls");
    srand(time(NULL));

    for (int i = 0; i < 6; i++)
    {
        cout << "Type your " << i+1 << " number below" << endl;
        cin >> ynumber[i];

        number = rand() % 50 + 1;
        cout << "The picked number is: " << number << endl;
        Sleep(1000);

        if (ynumber[i] == number)
        {
            cout << "Same same!" << endl;
            cor = cor + 1;
        }
        else
        {
            cout << "Hope for better luck next time ;)" << endl;
            falsed = falsed + 1; 
        }
    }

    system("cls");

    cout << "Thank you for participating!" << endl << "Correct picked numbers: " << cor << endl << "Wrong picked numbers: " << falsed << endl << endl;

    system("pause");

    return 0;
}

`




Running Keras model.fit() with identical setting returns different results

I have a trained model saved in model_path, and I want to continue its training on a fixed set of data, multiple times, each time starting from the state in which it was saved. If I run the same optimization on the same fixed set of data, with explicit definition of the random seed generators for both Numpy and Tensorflow, I expect the same loss at the end of the training. I followed the instructions on the Keras FAQ on reproducible results and it does not seem to help.

My model is a stack of relus and a linear layer on top. No batch normalization or dropout. The only source of randomness may be the He weight initialization, but it doesn't really come to place since the model I load is already trained.

for i in range(3): 
    tf.set_random_seed(42)
    np.random.seed(42)
    random.seed(42)
    X = scaler.transform(df.iloc[0:150,0:12].values)
    Y = df.iloc[0:150,12].values
    model = load_model('model.h5')
    model.compile(loss='mae', optimizer='adam')
    _ = model.fit(X, Y, batch_size=150, epochs=20, verbose=0, shuffle=False)
    x_test = scaler.transform(df.iloc[150:350,0:12].values)
    y_test = df.iloc[150:350,12].values
    mae = model.evaluate(x=x_test, y=y_test, steps=test_amount//50, verbose=0)
    print('MAE: ', mae)
    K.clear_session()
    tf.reset_default_graph()

Which results in:

MAE:  12.2394380569458
MAE:  12.65652847290039
MAE:  9.243626594543457

Also, I am not running on GPU. What is cousing these differences?




Problem with random package code in Python

I have the following simple "random walk" code:

import random

def random_walk(n):
    """Return coordinates after 'n' block random walk."""
    x = 0
    y = 0
    for i in range(n):
        step = random.choice(['N', 'S', 'E', 'W'])
        if step == 'N':
            y = y + 1
        elif step == 'S':
            y == y - 1
        elif step == 'W':
            x = x + 1
        else:
            x = x - 1
        return (x,y)

for i in range(25):
    walk = random_walk(10)
    print(walk, "Distance from home = ", abs(walk[0]) + abs(walk[1]))

I have two problems:

(A) When I run this in Visual Studio Code it tells me that variable i is not used. It gets "underlined" giving me the following error:

[pylint] Unused variable 'i' [W0612] (10,6)
[pylint] Unused variable 'i' [W0101] (22,3)

Note that Sublime and Jupyter have no problem running it.

(B) For some reason I never am able to move more than one step in x direction and one in y direction. As a result my distance from home is always 0,1 or But the code above clearly states that we walk for n blocks and not just 0, 1, or 2 blocks.

(0, 1) Distance from home = 1
(1, 0) Distance from home = 1
(1, 0) Distance from home = 1
(1, 0) Distance from home = 1
(1, 0) Distance from home = 1
(1, 0) Distance from home = 1
(1, 0) Distance from home = 1
(0, 1) Distance from home = 1
(1, 0) Distance from home = 1
(1, 0) Distance from home = 1
(1, 0) Distance from home = 1
(1, 0) Distance from home = 1
(0, 0) Distance from home = 0
(1, 0) Distance from home = 1
(1, 0) Distance from home = 1
(0, 0) Distance from home = 0
(1, 0) Distance from home = 1
(1, 0) Distance from home = 1
(0, 0) Distance from home = 0
(0, 1) Distance from home = 1
(1, 0) Distance from home = 1
(0, 0) Distance from home = 0
(1, 0) Distance from home = 1
(0, 0) Distance from home = 0
(0, 0) Distance from home = 0

What is the problem?




mardi 22 janvier 2019

Fastest way to sample from multidimensional random normal in python

At each iteration of a for loop, I would like to get a batch of samples from a multidimensional random normal distribution in python. What is the most efficient function to use when running the script on CPUs and GPUs? From my experiments so far it seems that tensorflow's tf.random.normal seem to be the fastest option. Pytorch's MultivariateNormal seems to be too slow. Ideally I would like to integrate it with a pytorch nn (so cast the samples to pytorch tensors after generation).




How to fix SKPhysicsContactDelegate not being called

My sprites are supposed to contact each other and print to console, however, one goes behind the other and they do not actually touch. Needless to say, nothing is being printed to console.

I've tried using many different "types" of if statements in the function, however, none of them have worked. For example, I've tried using:

if bodyA.categoryBitMask == 1 && bodyB.categoryBitMask == 2 || bodyA.categoryBitMask == 2 && bodyB.categoryBitMask == 1

as well as:

if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask

Help would be much appreciated! :)

import SpriteKit
import GameplayKit

class GameScene: SKScene, SKPhysicsContactDelegate {

var e = SKSpriteNode()
var square = SKSpriteNode()

var timer:Timer!

let squareCategory:UInt32 = 0x1 << 1
let eCategory:UInt32 = 0x1 << 2

override func didMove(to view: SKView) {

    self.physicsWorld.contactDelegate = self

    square = SKSpriteNode(imageNamed: "square")
    square.size = CGSize(width: 100, height: 100)
    square.physicsBody = SKPhysicsBody(rectangleOf: square.size)
    square.position = CGPoint(x: 0, y: -590)
    square.physicsBody = SKPhysicsBody(rectangleOf: e.size)
    square.name = "square"

    square.physicsBody?.categoryBitMask = squareCategory
    square.physicsBody?.contactTestBitMask = eCategory
    square.physicsBody?.usesPreciseCollisionDetection = true

    self.addChild(square)

    let swipeRight: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(GameScene.swipedRight(sender:)))
    swipeRight.direction = .right
    view.addGestureRecognizer(swipeRight)

    let swipeLeft: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector (GameScene.swipedLeft(sender:)))
    swipeLeft.direction = .left
    view.addGestureRecognizer(swipeLeft)

    timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(self.adde), userInfo: nil, repeats: true)

  }

@objc func swipedRight(sender: UISwipeGestureRecognizer) {

    //middle
    if square.position == CGPoint(x: 0, y: -590) {

        square.position = CGPoint(x: 200, y: -590)

    }

    //left
    if square.position == CGPoint(x: -200, y: -590) {

        square.position = CGPoint(x: 0, y: -590)

    }

}

@objc func swipedLeft(sender: UISwipeGestureRecognizer) {

    //middle
    if square.position == CGPoint(x: 0, y: -590) {

        square.position = CGPoint(x: -200, y: -590)

    }

    //right
    if square.position == CGPoint(x: 200, y: -590) {

        square.position = CGPoint(x: 0, y: -590)

    }

}

@objc func adde() {

    e = SKSpriteNode(imageNamed: "e")

    let ePosition = GKRandomDistribution(lowestValue: -414, highestValue: 414)
    let position = CGFloat(ePosition.nextInt())

    e.size = CGSize(width: 75, height: 75)
    e.position = CGPoint(x: position, y: 640)
    e.physicsBody = SKPhysicsBody(rectangleOf: e.size)
    e.name = "e"

    e.physicsBody?.categoryBitMask = eCategory
    e.physicsBody?.contactTestBitMask = squareCategory

    e.physicsBody?.isDynamic = true

    self.addChild(e)

    let animationDuration:TimeInterval = 6

    var actionArray = [SKAction]()

    actionArray.append(SKAction.move(to: CGPoint(x: position, y: -705), duration: animationDuration))
    actionArray.append(SKAction.removeFromParent())

    e.run(SKAction.sequence(actionArray))

}

func didBegin(_ contact: SKPhysicsContact) {

    let bodyAName = contact.bodyA.node?.name
    let bodyBName = contact.bodyB.node?.name

    if bodyAName == "square" && bodyBName == "e" || bodyAName == "e" && bodyBName == "square"{
        if bodyAName == "square" {
            contact.bodyA.node?.removeFromParent()
        } else if bodyBName == "e" {
            contact.bodyB.node?.removeFromParent()
        }


    }

}

override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered
}
}

I am supposed to get the message, but the "e" goes behind the "square" and I don't get any message.




Empty variable in for-loop

I have this one-liner which works entirely fine.

import random
from string import ascii_letters, digits

def pwd_generator(pwd):

    password = "".join([random.choice(ascii_letters + digits) for i in range(pwd)])
    print(password)

I wanted to translate that now into a 'normal' for-loop.

def pwd_generator(pwd):
    password = ''
    for i in range(pwd):
        password.join([random.choice(ascii_letters + digits)])

    print(password)

In this scenario however, password is empty.

Why is the variable empty when I try to write it in a 'proper' for-loop?