示例#1
0
def generate_students(amount_of_students: int):
    """Pass a number of students and a list will be returned.
    The list will contain random students, with all fields, including
    random DataSheets with  random Courses"""
    students = []
    courses = []
    # create courses: name, classroom, teacher, ects, grade=None
    # could also have used random.sample(list,key)
    amt_of_courses = secrets.SystemRandom().randint(1, 10)
    for i in range(0, amt_of_courses):
        c_name = secrets.choice(course_names)
        c_classroom = secrets.choice(course_classrooms)
        c_teacher = secrets.choice(course_teachers)
        c_ects = secrets.choice(course_ects)
        c_grade = secrets.choice(course_grades)
        rnd_course = Course(c_name, c_classroom, c_teacher, c_ects, c_grade)
        courses.append(rnd_course)
    for student in range(0, amount_of_students):
        amt_of_courses_to_enroll = secrets.SystemRandom().randint(
            1, len(courses))
        # create datasheet: *courses
        # random.sample() returns a list, so use * to convert into required *args
        s_sheet = DataSheet(*random.sample(courses, amt_of_courses_to_enroll))
        # create student: name, gender, data_sheet, image_url
        s_name = secrets.choice(student_names)
        s_gender = secrets.choice(genders)
        s_img = secrets.choice(img_urls)
        rnd_student = Student(s_name, s_gender, s_sheet, s_img)
        students.append(rnd_student)
    return students
示例#2
0
def get_word():
    """Select a random word consisting only out of letters."""
    reg = re.compile('^[a-z]*$')
    word = secrets.SystemRandom().choice(words)
    while not reg.match(word):
        word = secrets.SystemRandom().choice(words)
    return word.upper()
示例#3
0
def get_random_groupings(
    list_of_channel_members: List[str], ) -> Generator[List[str], None, None]:
    """
    Take note that the time spent managing the memory for the big list
    of all the compositions will definitely dominate the time cost of
    generating them.

    For all shufflings, the Fisher-Yates shuffle algorithm has a time
    complexity of O(n), which is the minimum time possible to shuffle
    any list in a completely random fashion.

    For smaller channel sizes, we select and use the more random method
    because of 2 reasons:
    - It would take much less time as compared to larger channel sizes.
    For larger channel sizes, we use the much faster and balanced
    algorithm, but sacrificing some entropy. This is acceptable since
    larger channel sizes would already have more entropy in the first
    place anyway.
    - Smaller channel sizes have less entropy in the first place due to
    the very nature of less people being involved. As such, the
    tradeoff of more time taken for more entropy is acceptable.

    Do let @jamestiotio know if you are able to catch any other edge
    cases, caveats, loopholes or tricky configurations.
    """
    channel_size = len(list_of_channel_members)
    if channel_size <= 0:
        raise StopIteration("Impossible channel member size.")
    channel_members_copy = list_of_channel_members.copy()
    secrets.SystemRandom().shuffle(channel_members_copy)
    if channel_size <= settings.RANDOMIZER_CHANNEL_SIZE_THRESHOLD:
        possible_group_sizes_configurations = list(
            get_eligible_integer_compositions(
                channel_size,
                1,
                lambda x: 1,
                settings.MIN_GROUP_SIZE,
                settings.MAX_GROUP_SIZE,
            ))
        selected_group_sizes_configuration = secrets.choice(
            possible_group_sizes_configurations)
        secrets.SystemRandom().shuffle(selected_group_sizes_configuration)
        curr = 0
        for chunk_size in selected_group_sizes_configuration:
            yield channel_members_copy[curr:curr + chunk_size]
            curr += chunk_size
    else:
        group_sizes_configuration = get_balanced_grouping_allocation(
            channel_size,
            settings.MIN_GROUP_SIZE,
            settings.MAX_GROUP_SIZE,
        )
        secrets.SystemRandom().shuffle(group_sizes_configuration)
        curr = 0
        for chunk_size in group_sizes_configuration:
            yield channel_members_copy[curr:curr + chunk_size]
            curr += chunk_size
示例#4
0
def encrypt_message(plain_bit, rho, tau, pk):
    # first sample S
    s = secrets.SystemRandom().randrange(1, tau)
    # Then sample r
    r = secrets.SystemRandom().randrange(-math.pow(2, 2 * rho),
                                         math.pow(2, 2 * rho))
    # encrypt message bit
    c = (plain_bit + 2 * r + 2 * sum(pk[1:s])) % pk[0]
    return c
示例#5
0
def random_walk(n):
    x = [0]
    y = [0]

    for _ in range(n):
        xrand = secrets.SystemRandom().uniform(-0.5, 0.5)
        yrand = secrets.SystemRandom().uniform(-0.5, 0.5)

        x.append(x[-1] + xrand)
        y.append(y[-1] + yrand)

    plt.scatter(x, y)
    plt.show()
示例#6
0
def randCharLS(length):
    password = []
    password += secrets.choice(specials)
    for i in range(length - 2):
        odds = secrets.SystemRandom().randrange(0, 85)
        if odds < 40:
            password += secrets.choice(lower_letters)
        elif odds < 80:
            password += secrets.choice(upper_letters)
        else:
            password += secrets.choice(specials)
    secrets.SystemRandom().shuffle(password)
    return password
示例#7
0
 def __init__(self,
              X,
              y,
              k=4,
              epochs=200,
              loss='mse',
              metrics=['mae'],
              learning_rate=0.0005,
              layers=3,
              ending_units=256,
              optimizer=Adam,
              early_stop=None,
              seed=None):
     self.X = X
     self.y = y
     self.k = k
     self.epochs = epochs
     self.loss = loss
     self.metrics = metrics
     self.learning_rate = learning_rate
     self.layers = layers
     self.ending_units = ending_units
     self.optimizer = optimizer
     self.early_stop = early_stop
     self.generator = secrets.SystemRandom(seed)
     self._idx = self.generator.randint(0, len(X))
     self.models = []
示例#8
0
    def checkUser(self, userid):

        users = [
            {
                "uid": "leo",
                "pwd": "202cb962ac59075b964b07152d234b70"
            },
            {
                "uid": "neo",
                "pwd": "456"
            },
        ]

        for u in users:
            if u['uid'] == userid:
                # 使用用户的pwd hash为密钥生成会话密钥
                print("User {} login successfully.".format(userid))
                f = Fernet(base64.b64encode(u['pwd'].encode()))
                sessionkey = str(secrets.SystemRandom().getrandbits(128))
                token = f.encrypt(sessionkey.encode('utf-8'))
                return (str(sessionkey), token)
            else:
                print("Login failed. {} is not a legal user.".format(userid))
                return ()

        return ()
示例#9
0
def create_user(data):
    log("A new user created", "MEDIUM", "PASS")
    my_secure_rng = secrets.SystemRandom()
    val_num(data.get('privilege'))
    pincode = my_secure_rng.randrange(10000000, 99999999)
    username = pincode
    email = data.get('email')
    access = "False"
    activated = "False"
    privilege_id = 0
    # New users can only edit:read:delete
    if data.get('privilege') == 1:
        log("User triggered error creating new user", "MEDIUM", "FAIL")
        return {'message': 'User could not be created'}
    else:
        privilege_id = data.get('privilege')
    password = ""
    user = users(privilege_id, pincode, username, password, access, activated,
                 email)
    db.session.add(user)
    db.session.commit()
    result = users.query.filter(users.email == email).one()

    # Add user to default groupmember issue #422
    groupmember = groupmembers.query.order_by(desc(
        groupmembers.memberID)).first()
    groupmemberUser = groupmembers(groupmember.memberID + 1, result.userID,
                                   groupmember.groupID, groupmember.ownerID,
                                   None)
    db.session.add(groupmemberUser)
    db.session.commit()

    return result
def pass_gen(option, length):
    secretsGenerator = secrets.SystemRandom()
    if length < 5:
        print("/!\ : Weak password !")
    if option == 'A':
        if length % 2 == 1:
            length = length // 2
            length2 = length
        if length % 2 == 0:
            length = length // 2
            length2 = length - 1
        gen_pass = str(secretsGenerator.randint(0, 50))
        gen_pass = gen_pass.encode()
        hash = hashlib.sha1(gen_pass)
        gen_hash = hash.hexdigest()
        a = ''.join(
            secrets.choice(string.ascii_uppercase + string.digits)
            for i in range(length))
        b = ''.join(
            secrets.choice(gen_hash) for liste_gen_hash in range(length2))
        end = a + b + '$'
        return end
    if option == 'B':
        string_pass = ''.join(
            secrets.choice(string.ascii_uppercase) for i in range(length))
        return string_pass
    if option == 'C':
        num_pass = ''.join(
            str(secretsGenerator.randint(0, 9)) for i in range(length))
        return num_pass
示例#11
0
def kyukey(request):
    secretsgen=secrets.SystemRandom()
    otp=secretsgen.randrange(1000,9999)
    val=otp
    x = generate(key = otp)
    x.save()
    return render(request,'index.htm',{'gen':val})
示例#12
0
 def __init__(self,
              alphabet=string.digits + string.ascii_letters +
              string.punctuation + " ",
              message_length=64,
              key_number=0xffff,
              file="key.dict",
              outqueue=None):
     self.a = self.defaults_alphabet  #alphabet
     self.n = message_length
     self.MAX_KEYS = key_number
     self.file = file
     if not outqueue == None:
         outqueue.put("Starting")
     self.secure_random = secrets.SystemRandom()
     try:
         with open(self.file, 'rb') as f:
             self.key_dict = cPickle.load(f)
             print("Taking dictionary settings from file")
             settings = self.key_dict[0]
             self.a = settings[0]
             self.n = settings[1]
             self.MAX_KEYS = settings[2]
             #print("Alpha:{}\nMsgLen:{}\nMaxKeys:{}".format(self.a,self.n,self.MAX_KEYS))
     except FileNotFoundError:
         self.key_gen(outqueue)
     print("keys remaining: {}".format(len(self.key_dict) - 1))
     if not outqueue == None:
         outqueue.put("Stopped")
示例#13
0
def genRandLetters():

    secretRandom = secrets.SystemRandom()

    ascii_lowercase = string.ascii_lowercase
    ascii_uppercase = string.ascii_uppercase
    ascii_digits = string.digits
    ascii_special = string.punctuation
    uppercase_count = main.uppercase
    digits_count = main.digits
    special_count = main.special
    special_count = uppercase_count + digits_count + special_count
    lowercase_count = main.total - special_count
    x = 0
    lowercase_total = (''.join(
        secrets.choice(ascii_lowercase) for i in range(lowercase_count)))
    uppercase_total = (''.join(
        secrets.choice(ascii_uppercase) for i in range(digits_count)))
    digit_total = (''.join(
        secrets.choice(ascii_digits) for i in range(digits_count)))
    special_total = (''.join(
        secrets.choice(ascii_special) for i in range(special_count)))

    random_password = lowercase_total + uppercase_total + digit_total + special_total
    random_password_array = []
    random_password_count = len(random_password)
    for i in random_password:
        #temp = [i]
        random_password_array.append(i)

    random_password = (secretRandom.sample(random_password_array,
                                           len(random_password_array)))
    print(str("".join(map(str, random_password))))
示例#14
0
文件: zidx.py 项目: cburkert/zidx
 def blind(self, numwords: int) -> None:
     if not hasattr(self, 'num_keys'):
         raise ValueError("Cannot blind this index. "
                          "Number of keys is unknown.")
     random = secrets.SystemRandom()
     for _ in range(numwords * self.num_keys):
         self.__bf[random.randrange(self.bf_size_bits)] = 1
示例#15
0
def GeneratePaswd(size, specialChars):

    password = ""
    special = 0
    generator = secrets.SystemRandom()

    while True:

        symbol = generator.randrange(33, 126)

        if isSpecial(symbol):
            if special < specialChars:
                special += 1
            else:
                continue

        symbol = chr(symbol)

        if len(password) == 0:
            password += symbol
        elif password[-1] != symbol:
            password += symbol
        if len(password) == size:
            break
    return password
def generate_random_polynomial(n,
                               ones,
                               minus_ones,
                               secret_generator=secrets.SystemRandom()):

    poly_coeff_list = (n + 1) * [0]
    ones_filled = 0
    minus_ones_filled = 0
    degree = -1
    while ones_filled < ones:
        idx = secret_generator.randrange(0, n)
        if poly_coeff_list[idx] == 0:
            poly_coeff_list[idx] = 1
            ones_filled += 1
            if idx > degree:
                degree = idx
    while minus_ones_filled < minus_ones:
        idx = secret_generator.randrange(0, n)
        if poly_coeff_list[idx] == 0:
            poly_coeff_list[idx] = -1
            minus_ones_filled += 1
            if idx > degree:
                degree = idx

    poly = conv_poly(n)
    poly.coefflist = poly_coeff_list
    poly.degree = degree

    return poly
def msgtext_to_msgpoly(msg_text, n, p,
                       secret_generator=secrets.SystemRandom()):
    """converts a string of text, msg_text (considered in UTF-8 encoding), 
       into an array of bytes with given output_length in bits for delivery to NTRU (zero padded on the right to byte boundary),
       or throws an exception if output length is not enough to pack the message"""

    bits_per_coefficient = math.floor(math.log(p, 2))
    output_length = n * bits_per_coefficient

    # 256 is the size of the 160 sha-1 hash field, 16 bit message bit length and 80 bit mandatory padding
    HEADER_SIZE = 256
    msg_text_bytes = msg_text.encode()
    text_bitlength = len(msg_text_bytes) * 8  # text bit length field
    if HEADER_SIZE + text_bitlength > output_length:
        raise ValueError(
            'the text "%s", with %d bytes in length, is too large;'
            ' only %d bytes of payload are possible to encode with a message length of %d bits'
            % (msg_text, len(msg_text_bytes),
               (output_length - HEADER_SIZE) // 8, output_length))

    msg_bits = bytearray(20)  # sha-1 hash field
    msg_bits.append((text_bitlength & 0xFF00) >> 8)
    msg_bits.append(text_bitlength & 0xFF)
    for i in range(10):  # mandatory random padding field
        msg_bits.append(secret_generator.randrange(0, 256))
    for b in msg_text_bytes:
        msg_bits.append(b)

    bitcount = HEADER_SIZE + text_bitlength
    while bitcount < output_length:  # fill out extra random padding up to bit output length
        b = 0
        for i in range(7, -1, -1):
            b |= secret_generator.randrange(0, 2) << i
            bitcount += 1
            if bitcount >= output_length:
                break
        msg_bits.append(b)

    h = hashlib.sha1()  # fill out hash field
    h.update(msg_bits[20:])
    msg_bits[0:20] = h.digest()

    #convert a byte like object to a string of bits in a list"""
    msg_bitstring = []
    for b in msg_bits:
        for i in range(7, -1, -1):
            msg_bitstring.append((b & (1 << i)) >> i)  # copy ith bit

    # generate a polynomial from a sequence of message bits (encoded as a list of bits).
    # the first n * floor(log(p)) bits in the msg_bits are turned into coefficients, a_0, ..., a_{n - 1}"""
    bitindex = 0
    poly = conv_poly(n, p)
    for c in range(n):
        coeff_val = 0
        for bit in range(bits_per_coefficient):
            coeff_val = 2 * coeff_val + msg_bitstring[bitindex]
            bitindex += 1
        poly.coefflist[c] = coeff_val

    return poly
示例#18
0
def rand_prime(m: int,
               n: int,
               strategy: RandomStrategy = RandomStrategy.RANDOM_LIB):
    """
    Arguments:
        {m} integer -- The Starting index of Range
        {n} integer -- The Ending index of Range

    Returns:
        integer -- A random prime number between m and n.

    """
    if not isinstance(m, int):
        raise TypeError("rand_prime() expect parameter m to be int. Given: " +
                        str(type(m)) + '.')
    if not isinstance(n, int):
        raise TypeError("rand_prime() expect parameter n to be int. Given: " +
                        str(type(n)) + '.')

    found_primes = between(m, n)
    if len(found_primes) == 0:
        return -1

    if strategy is RandomStrategy.RANDOM_LIB:
        return random.choice(found_primes)
    elif strategy is RandomStrategy.SECRETS_CHOICE:
        return secrets.choice(found_primes)
    elif strategy is RandomStrategy.SECRETS_RANDOM:
        return secrets.SystemRandom().choice(found_primes)
    else:
        raise ValueError("Couldn't find the selected strategy")
示例#19
0
 def __init__(self,
              X,
              y,
              k=4,
              epochs=200,
              loss='mse',
              metrics=['mae'],
              learning_rate=0.001,
              layers=3,
              ending_units=256,
              optimizers=[Adam, Nadam, RMSprop],
              early_stop=None,
              seed=None):
     self.X = X
     self.y = y
     self.k = k
     self.epochs = epochs
     self.loss = loss
     self.metrics = metrics
     self.learning_rate = learning_rate
     self.layers = layers
     self.ending_units = ending_units
     self.optimizers = optimizers
     self.early_stop = early_stop
     self.generator = secrets.SystemRandom(seed)
     self.models = []
     self.tree = Tree()
示例#20
0
def pwgen(max_len, symbols=True):
    if (max_len < 4 and symbols == True) or (max_len < 3 and symbols == False):
        raise ValueError('Invalid password length, enter a valid length.')
    if symbols == True:
        pwStart = [
            secrets.choice(upperCaseList),
            secrets.choice(lowerCaseList),
            secrets.choice(numeralsList),
            secrets.choice(symbolsList)
        ]
    else:
        pwStart = [
            secrets.choice(upperCaseList),
            secrets.choice(lowerCaseList),
            secrets.choice(numeralsList)
        ]
    charRemain = max_len - len(pwStart)
    newAlphaNum = 0
    while newAlphaNum < charRemain:
        if symbols == True:
            pwStart += secrets.choice(alphaNum)
        else:
            pwStart += secrets.choice(anNoSymbols)
        newAlphaNum += 1
    secrets.SystemRandom().shuffle(pwStart)
    pwStart = ''.join(pwStart)
    return pwStart
示例#21
0
    def __init__(self, config):
        self.config = config
        self.ticks_left = self.config.simulation_time
        self.area = Area(height=config.area['height'],
                         width=config.area['width'])
        rand = secrets.SystemRandom()
        self.area.particles = []
        for i in range(config.atoms['number']):
            x = rand.random() * (config.area['width'] - config.atoms['radius']
                                 * 2) + config.atoms['radius']
            y = rand.random() * (config.area['height'] - config.atoms['radius']
                                 * 2) + config.atoms['radius']
            vx = rand.random(
            ) * config.atoms['max_velocity'] * 2 - config.atoms['max_velocity']
            vy = rand.random(
            ) * config.atoms['max_velocity'] * 2 - config.atoms['max_velocity']

            self.area.addParticle(
                Particle([x, y], [vx, vy], self.random_color(rand)))

        # collision_lock
        for i in range(self.config.atoms['number']):
            self.collision_lock.append([])
            for j in range(self.config.atoms['number']):
                self.collision_lock[i].append(False)
        # detektor
        self.detector = Detector(self.config)
示例#22
0
    def post(self, request):
        mobile = request.data['mobile']
        if len(mobile) < 10:
            return Response({"status": False, "message": "incorrect mobile phone"}, 400)
        mobile = "0" + mobile[-10:]
        import kavenegar
        import json
        api = kavenegar.KavenegarAPI(KAVE_NEGAR_TOKEN)
        
        secretsGenerator = secrets.SystemRandom()
        new_pass = secretsGenerator.randint(11111, 99999)

        params = {
            'receptor': mobile,
            'message': "گردش پی" + "\n" + "رمز عبور: " + str(new_pass),
        }
        api.sms_send(params)
        organization_token = request.META.get('HTTP_ORGANIZATION', None)
        if User.objects.filter(mobile=mobile):
            u = User.objects.get(mobile=mobile)
            u.set_password(new_pass)
            u.expire_pass = True
            u.save()
            if organization_token != None:
                organization = Organization.objects.get(token__exact=organization_token)
                if not Membership.objects.filter(organization=organization, user=u).exists():
                    Membership.objects.create(organization=organization, user=u)
        else:
            user = User.objects.create_user(mobile, new_pass)
            if organization_token != None:
                organization = Organization.objects.get(token__exact=organization_token)
                if not Membership.objects.filter(organization=organization, user=user).exists():
                    Membership.objects.create(organization=organization, user=user)
        content = {"status": True}
        return Response(content)
示例#23
0
def tercero_generarQR(tercero_id: int) -> Tercero:
    tercero = Tercero.objects.get(pk=tercero_id)
    now = timezone.now()
    nro_aleatorio = random.randint(1000, 9999)
    import secrets
    secure_random = secrets.SystemRandom()
    caracteres = [
        "a", "e", "i", "o", "u", "%", "&", "/", ")", "(", "=", "?", "¿", "{",
        "}", "*", "+", "¡", "!"
    ]
    random_uno = random.randint(10, 99).__str__().join(
        secure_random.sample(caracteres, 3))
    random_dos = random.choice(caracteres).join(
        secure_random.sample(caracteres, 3))
    random_tres = random.randint(100, 999).__str__().join(
        secure_random.sample(caracteres, 3))

    qr_acceso = '%s%s%s%s%s%s(%s)%s$%s%s%s' % (
        tercero.id,
        random_uno,
        nro_aleatorio,
        random_dos,
        now.month,
        nro_aleatorio,
        tercero.usuario_id,
        now.year,
        random_tres,
        now.day,
        tercero.id,
    )
    tercero.qr_acceso = qr_acceso
    tercero.save()
    return tercero
示例#24
0
def gen_shape(rank_range=None, size_range=None, dim_limit=None):
    """
    generate a shape
    :param rank_range: shape's rank range
    :param size_range: shape's size range
    :param dim_limit: shape's dim size limit
    :return: shape
    """
    if size_range is None:
        size_range = [1, 2000 - 1]
    if rank_range is None:
        rank_range = [1, 8]
    if dim_limit is None:
        dim_range = 2000000 - 1
    secret_gen = secrets.SystemRandom()
    rank = secret_gen.randint(*rank_range)
    size = secret_gen.randint(*size_range)
    p_d = np.exp(np.log(size) / rank)
    dims = np.random.normal(loc=10, scale=3.0, size=(rank, ))
    dims = np.maximum(dims, 0)
    dim_prod = np.prod(dims)
    dim_prod_norm = np.exp(np.log(dim_prod) / rank)
    prod_dims = dims / dim_prod_norm * p_d
    ceil_dims = np.ceil(prod_dims)
    maxi_dims = np.maximum(ceil_dims, 1)
    mini_dims = np.minimum(maxi_dims, dim_range)
    return [int(x) for x in list(mini_dims)]
示例#25
0
    def __init__(self,
                 steps,
                 data=None,
                 metadata=None,
                 n=10,
                 balls_number=69,
                 actions_number=5,
                 draw_length=5,
                 seed=None):
        self.seed(seed)
        self.steps = steps
        self.data = data
        self.metadata = metadata
        self.balls_number = balls_number
        self.draw_length = draw_length
        self.random = secrets.SystemRandom(seed)

        spaces_list = []
        for _ in range(balls_number):
            spaces_list.append(spaces.Discrete(n))
        self.observation_space = spaces.Tuple(spaces_list)
        spaces_list = []
        for _ in range(actions_number):
            spaces_list.append(spaces.Discrete(balls_number))
        self.action_space = spaces.Tuple(spaces_list)
        self.reset()
示例#26
0
 def PirraLaivaAuto(self):
     laivaauto = {
         1: "laiva.txt",
         2: "auto.txt",
     }
     valinta = secrets.SystemRandom().randint(1, len(laivaauto))
     self.Piirra(self.kansio + laivaauto.get(valinta))
示例#27
0
    def __init__(self, X, y, seed=None):
        self.seed(seed)
        self.X = X
        self.y = y
        self.random = secrets.SystemRandom(seed)

        self.reset()
示例#28
0
def hello(event, context):
    s3 = boto3.resource('s3')

    sec = secrets.SystemRandom()
    key = generate_key(sec)
    while is_key_exists(s3, bucket, generate_route(key)):
        key = generate_key(sec)

    link = event['body']
    if "http" not in link:
        link = "http://" + link

    s3.Object(bucket, generate_route(key)).put(Body="",
                                               ACL='public-read',
                                               ContentType='text/html',
                                               WebsiteRedirectLocation=link)

    response = {
        "statusCode": 200,
        "headers": {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Credentials": True
        },
        "body": json.dumps({"url": key})
    }

    return response
示例#29
0
    def get(self, distribution):
        """
        Returns a random value from a weighted distribution
        :param distribution: 2D array ([[x, y]...]) where x is the value and y is the weight.
        :return: Random x value
        """
        try:
            dist_list = json.loads(distribution)

            if type(dist_list) is not list:
                raise TypeError("Distribution is not a list")

            # Find the total weight of the distribution
            distribution_max = 0

            for i in range(len(dist_list)):
                distribution_max += dist_list[i][1]

            # Generate a random number between [0, distribution_max)
            random_num = secrets.SystemRandom().randrange(0, distribution_max)
            distribution_value = 0

            # Find and return the weighted value from the distribution
            for i in range(len(dist_list)):
                distribution_value += dist_list[i][1]

                if random_num < distribution_value:
                    return dist_list[i][0]

        except Exception as error:
            abort(403, "Bad Request")
            current_app.logger.exception(error, exc_info=True)
示例#30
0
    def __init__(self,
                 parent,
                 members,
                 test_mode=False,
                 interactive_drawing=False):
        """
        :param parent: The DrawingBranch that spawned this node (None == root)
        :type parent: DrawingBranch, None

        :param members: The members (branches) of this node
        :type members: collections.abc.Sequence

        :param test_mode: Generate the same (non-random) result by using
                          the same seed. (used for testing) (default: False)
        :type test_mode: bool

        :param interactive_drawing: Prompt the user when drawing
                                    (manual drawing) (default: False)
        :type interactive_drawing: bool
        """
        self._parent = parent
        # N.B. interactive_drawing is used for CLI and testing only
        self._interactive_drawing = interactive_drawing
        self._probability_factor = len(members)
        self._members = []
        for member in members:
            self._members.append(DrawingBranch(member, self))
        if test_mode:
            logger.warning("Using testing / non-random mode")
            self._rnd = random.SystemRandom(1)
        else:
            self._rnd = secrets.SystemRandom()