Python random 模块,Random() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用random.Random()

项目:sharedbuffers    作者:jampp    | 项目源码 | 文件源码
def gen_values(self, n, reversed = False, shuffled = False, gen_dupes = False):
        if reversed:
            keys = xrange(n-1,-1,-1)
        else:
            keys = xrange(n)
        if shuffled:
            keys = list(keys)
            r = random.Random(1234827)
            r.shuffle(keys)
        if gen_dupes:
            return itertools.chain(
                itertools.izip(keys, xrange(0, 2*n, 2)),
                itertools.islice(itertools.izip(keys, xrange(0, 2*n, 2)), 10, None),
            )
        else:
            return itertools.izip(keys, xrange(0, 2*n, 2))
项目:CyberScan    作者:medbenali    | 项目源码 | 文件源码
def __init__(self, inf, sup, seed=None, forever=1, renewkeys=0):
        self.forever = forever
        self.renewkeys = renewkeys
        self.inf = inf
        self.rnd = random.Random(seed)
        self.sbox_size = 256

        self.top = sup-inf+1

        n=0
        while (1<<n) < self.top:
            n += 1
        self.n =n

        self.fs = min(3,(n+1)/2)
        self.fsmask = 2**self.fs-1
        self.rounds = max(self.n,3)
        self.turns = 0
        self.i = 0
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def __init__(self, inf, sup, seed=None, forever=1, renewkeys=0):
        self.forever = forever
        self.renewkeys = renewkeys
        self.inf = inf
        self.rnd = random.Random(seed)
        self.sbox_size = 256

        self.top = sup-inf+1

        n=0
        while (1<<n) < self.top:
            n += 1
        self.n =n

        self.fs = min(3,(n+1)/2)
        self.fsmask = 2**self.fs-1
        self.rounds = max(self.n,3)
        self.turns = 0
        self.i = 0
项目:jarvis    作者:anqxyr    | 项目源码 | 文件源码
def show_page(page, rating=True):
    attribution = page.build_attribution_string(
        templates=dict(
            author='written {hdate} by {user}',
            rewrite='rewritten {hdate} by {user}',
            translator='translated {hdate} by {user}',
            maintainer='maintained {hdate} by {user}'),
        group_templates=dict(
            author='co-written {hdate} by {users} and {last_user}',
            rewrite='rewritten {hdate} by {users} and {last_user}',
            translator='translated {hdate} by {users} and {last_user}',
            maintainer='maintained {hdate} by {users} and {last_user}'))
    out = lex.page_lookup.summary if rating else lex.page_lookup.nr_summary
    if page.name == 'scp-1848':
        r = rand.Random(int(arrow.now().format('YYYYMMDDHH')))
        rating = r.randrange(-160, -140)
    else:
        rating = page.rating
    return out(page=page, rating=rating, attribution=attribution)
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def run_with_fixed_seeds(count=128, master_seed=0x243F6A8885A308D3):
    """
    decorator run test method w/ multiple fixed seeds.
    """
    def builder(func):
        @wraps(func)
        def wrapper(*args, **kwds):
            rng = random.Random(master_seed)
            for _ in irange(count):
                kwds['seed'] = rng.getrandbits(32)
                func(*args, **kwds)
        return wrapper
    return builder

#=============================================================================
# custom test harness
#=============================================================================
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def getrandbytes(rng, count):
    """return byte-string containing *count* number of randomly generated bytes, using specified rng"""
    # NOTE: would be nice if this was present in stdlib Random class

    ###just in case rng provides this...
    ##meth = getattr(rng, "getrandbytes", None)
    ##if meth:
    ##    return meth(count)

    if not count:
        return _BEMPTY
    def helper():
        # XXX: break into chunks for large number of bits?
        value = rng.getrandbits(count<<3)
        i = 0
        while i < count:
            yield value & 0xff
            value >>= 3
            i += 1
    return join_byte_values(helper())
项目:jack    作者:uclmr    | 项目源码 | 文件源码
def shuffle_and_batch(items: List[T], batch_size: int,
                      rng: Optional[random.Random] = None) \
        -> Iterator[List[T]]:
    """Optionally shuffles and batches items in a list.

    Args:
        - items: List of items to shuffle & batch.
        - batch_size: size of batches.
        - rng: random number generator if items should be shuffles, else None.

    Returns: Batch iterator
    """

    todo = list(range(len(items)))
    if rng is not None:
        rng.shuffle(todo)
    while todo:
        indices = todo[:batch_size]
        todo = todo[batch_size:]
        items_batch = [items[i] for i in indices]
        yield items_batch
项目:CVE-2016-6366    作者:RiskSense-Ops    | 项目源码 | 文件源码
def __init__(self, inf, sup, seed=None, forever=1, renewkeys=0):
        self.forever = forever
        self.renewkeys = renewkeys
        self.inf = inf
        self.rnd = random.Random(seed)
        self.sbox_size = 256

        self.top = sup-inf+1

        n=0
        while (1<<n) < self.top:
            n += 1
        self.n =n

        self.fs = min(3,(n+1)/2)
        self.fsmask = 2**self.fs-1
        self.rounds = max(self.n,3)
        self.turns = 0
        self.i = 0
项目:deep_stack    作者:lyn716    | 项目源码 | 文件源码
def random_str(randomlength=8,
               just_number=False):
    """????????????

    :param      randomlength: ?????????
    :param      just_number: ?????
    :return:
    """

    string = ""

    if just_number:
        chars = '0123456789'
    else:
        chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'

    length = len(chars) - 1
    random = Random()

    for i in range(randomlength):
        string += chars[random.randint(0, length)]

    return string
项目:NLP    作者:Deamon5550    | 项目源码 | 文件源码
def generate_hold_out_split (dataset, training = 0.8, base_dir="splits"):
    r = random.Random()
    r.seed(1489215)

    article_ids = list(dataset.articles.keys())  # get a list of article ids
    r.shuffle(article_ids)  # and shuffle that list


    training_ids = article_ids[:int(training * len(article_ids))]
    hold_out_ids = article_ids[int(training * len(article_ids)):]

    # write the split body ids out to files for future use
    with open(base_dir+ "/"+ "training_ids.txt", "w+") as f:
        f.write("\n".join([str(id) for id in training_ids]))

    with open(base_dir+ "/"+ "hold_out_ids.txt", "w+") as f:
        f.write("\n".join([str(id) for id in hold_out_ids]))
项目:SFBIStats    作者:royludo    | 项目源码 | 文件源码
def my_color_func(word=None, font_size=None, position=None, orientation=None, font_path=None, random_state=None):
    """
    custom colors for wordcloud, derived from wordcloud source

    Parameters
    ----------
    word
    font_size
    position
    orientation
    font_path
    random_state

    Returns
    -------

    """

    if random_state is None:
        random_state = Random()
    return "hsl(%d, 70%%, 40%%)" % random_state.randint(0, 255)
项目:sidekick    作者:fabiommendes    | 项目源码 | 文件源码
def test_random_sample(self):
        alist = list(range(100))

        assert list(
            random_sample(1, alist, random_state=2016)) == alist

        mk_rsample = lambda rs=1: \
            list(random_sample(0.1, alist, random_state=rs))
        rsample1 = mk_rsample()
        assert rsample1 == mk_rsample()

        rsample2 = mk_rsample(1984)
        randobj = Random(1984)
        assert rsample2 == mk_rsample(randobj)

        assert rsample1 != rsample2

        assert mk_rsample(object) == mk_rsample(object)
        assert mk_rsample(object) != mk_rsample(object())
        assert mk_rsample(b"a") == mk_rsample(u"a")

        assert raises(TypeError, lambda: mk_rsample([]))
项目:hakkuframework    作者:4shadoww    | 项目源码 | 文件源码
def __init__(self, inf, sup, seed=None, forever=1, renewkeys=0):
        self.forever = forever
        self.renewkeys = renewkeys
        self.inf = inf
        self.rnd = random.Random(seed)
        self.sbox_size = 256

        self.top = sup-inf+1

        n=0
        while (1<<n) < self.top:
            n += 1
        self.n =n

        self.fs = min(3,(n+1)//2)
        self.fsmask = 2**self.fs-1
        self.rounds = max(self.n,3)
        self.turns = 0
        self.i = 0
项目:hnmt    作者:robertostling    | 项目源码 | 文件源码
def __init__(self, f, block_size=0x40000, max_blocks=512,
                 encoding='utf-8', seed=123):
        assert 'b' in f.mode
        self.random = Random(seed)
        self.block_size = block_size
        self.max_blocks = max_blocks
        self.lines = None
        self.f = f
        self.encoding = encoding

        f.seek(0, 2)
        file_size = f.tell()
        f.seek(0, 0)

        if file_size <= block_size*max_blocks:
            # For sufficiently small files, read the whole one into RAM
            self.lines = [str(line.rstrip(b'\n'), encoding) for line in f]
            shuffle(self.lines, self.random.random)
        else:
            # For large files, only store a list of block offsets
            self.offsets = list(range(0, file_size, block_size))
项目:fnc-1-baseline    作者:FakeNewsChallenge    | 项目源码 | 文件源码
def generate_hold_out_split (dataset, training = 0.8, base_dir="splits"):
    r = random.Random()
    r.seed(1489215)

    article_ids = list(dataset.articles.keys())  # get a list of article ids
    r.shuffle(article_ids)  # and shuffle that list


    training_ids = article_ids[:int(training * len(article_ids))]
    hold_out_ids = article_ids[int(training * len(article_ids)):]

    # write the split body ids out to files for future use
    with open(base_dir+ "/"+ "training_ids.txt", "w+") as f:
        f.write("\n".join([str(id) for id in training_ids]))

    with open(base_dir+ "/"+ "hold_out_ids.txt", "w+") as f:
        f.write("\n".join([str(id) for id in hold_out_ids]))
项目:uci-statnlp    作者:sameersingh    | 项目源码 | 文件源码
def file_splitter(filename, seed = 0, train_prop = 0.7, dev_prop = 0.15,
    test_prop = 0.15):
    """Splits the lines of a file into 3 output files."""
    import random
    rnd = random.Random(seed)
    basename = filename[:-4]
    train_file = open(basename + ".train.txt", "w")
    test_file = open(basename + ".test.txt", "w")
    dev_file = open(basename + ".dev.txt", "w")
    with open(filename, 'r') as f:
        for l in f.readlines():
            p = rnd.random()
            if p < train_prop:
                train_file.write(l)
            elif p < train_prop + dev_prop:
                dev_file.write(l)
            else:
                test_file.write(l)
    train_file.close()
    test_file.close()
    dev_file.close()
项目:uci-statnlp    作者:sameersingh    | 项目源码 | 文件源码
def file_splitter(all_file, train_file, dev_file):
    """Splits the labeled data into train and dev, sentence-wise."""
    import random
    all_sents, all_labels = read_file(all_file)
    train_f = open(train_file, "w")
    dev_f = open(dev_file, "w")
    seed = 0
    dev_prop = 0.25
    rnd = random.Random(seed)
    for i in xrange(len(all_sents)):
        if rnd.random() < dev_prop:
            write_sent(dev_f, all_sents[i], all_labels[i])
        else:
            write_sent(train_f, all_sents[i], all_labels[i])
    train_f.close()
    dev_f.close()
项目:DeepLearn    作者:GauravBh1010tt    | 项目源码 | 文件源码
def generate_hold_out_split (dataset, training = 0.8, base_dir="splits"):
    r = random.Random()
    r.seed(1489215)

    article_ids = list(dataset.articles.keys())  # get a list of article ids
    r.shuffle(article_ids)  # and shuffle that list


    training_ids = article_ids[:int(training * len(article_ids))]
    hold_out_ids = article_ids[int(training * len(article_ids)):]

    # write the split body ids out to files for future use
    with open(base_dir+ "/"+ "training_ids.txt", "w+") as f:
        f.write("\n".join([str(id) for id in training_ids]))

    with open(base_dir+ "/"+ "hold_out_ids.txt", "w+") as f:
        f.write("\n".join([str(id) for id in hold_out_ids]))
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_zeroinputs(self):
        # Verify that distributions can handle a series of zero inputs'
        g = random.Random()
        x = [g.random() for i in range(50)] + [0.0]*5
        g.random = x[:].pop; g.uniform(1,10)
        g.random = x[:].pop; g.paretovariate(1.0)
        g.random = x[:].pop; g.expovariate(1.0)
        g.random = x[:].pop; g.weibullvariate(1.0, 1.0)
        g.random = x[:].pop; g.normalvariate(0.0, 1.0)
        g.random = x[:].pop; g.gauss(0.0, 1.0)
        g.random = x[:].pop; g.lognormvariate(0.0, 1.0)
        g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0)
        g.random = x[:].pop; g.gammavariate(0.01, 1.0)
        g.random = x[:].pop; g.gammavariate(1.0, 1.0)
        g.random = x[:].pop; g.gammavariate(200.0, 1.0)
        g.random = x[:].pop; g.betavariate(3.0, 3.0)
        g.random = x[:].pop; g.triangular(0.0, 1.0, 1.0/3.0)
项目:DecInt    作者:casevh    | 项目源码 | 文件源码
def Random(self, randlength):
        '''Return a random integer with randlength digits.

        The actual number of digits may be less than randlength because
        leading zeroes are stripped from the result.'''

        result = DecInt()
        result.radix = self.radix
        result.sign = 1
        result.terms = []
        power, base = self.radix

        full, partial = divmod(randlength, power)
        for i in range(full):
            result.terms.append(mp(_rr.randrange(long(Radix2Value(self.radix)))))
        result.terms.append(mp(_rr.randrange(long(Radix2Value((partial, base))))))
        while len(result.terms) > 1 and result.terms[-1] == ZERO:
            result.terms.pop()
        return result
项目:sockeye    作者:awslabs    | 项目源码 | 文件源码
def generate_digits_file(source_path: str,
                         target_path: str,
                         line_count: int = 100,
                         line_length: int = 9,
                         sort_target: bool = False,
                         line_count_empty: int = 0,
                         seed=13):
    assert line_count_empty <= line_count
    random_gen = random.Random(seed)
    with open(source_path, "w") as source_out, open(target_path, "w") as target_out:
        all_digits = []
        for _ in range(line_count - line_count_empty):
            digits = [random_gen.choice(_DIGITS) for _ in range(random_gen.randint(1, line_length))]
            all_digits.append(digits)
        for _ in range(line_count_empty):
            all_digits.append([])
        random_gen.shuffle(all_digits)
        for digits in all_digits:
            print(" ".join(digits), file=source_out)
            if sort_target:
                digits.sort()
            print(" ".join(digits), file=target_out)
项目:trex-http-proxy    作者:alwye    | 项目源码 | 文件源码
def __init__(self, inf, sup, seed=None, forever=1, renewkeys=0):
        self.forever = forever
        self.renewkeys = renewkeys
        self.inf = inf
        self.rnd = random.Random(seed)
        self.sbox_size = 256

        self.top = sup-inf+1

        n=0
        while (1<<n) < self.top:
            n += 1
        self.n =n

        self.fs = min(3,(n+1)/2)
        self.fsmask = 2**self.fs-1
        self.rounds = max(self.n,3)
        self.turns = 0
        self.i = 0
项目:trex-http-proxy    作者:alwye    | 项目源码 | 文件源码
def __init__(self, inf, sup, seed=None, forever=1, renewkeys=0):
        self.forever = forever
        self.renewkeys = renewkeys
        self.inf = inf
        self.rnd = random.Random(seed)
        self.sbox_size = 256

        self.top = sup-inf+1

        n=0
        while (1<<n) < self.top:
            n += 1
        self.n =n

        self.fs = min(3,(n+1)//2)
        self.fsmask = 2**self.fs-1
        self.rounds = max(self.n,3)
        self.turns = 0
        self.i = 0
项目:Price-Comparator    作者:Thejas-1    | 项目源码 | 文件源码
def demo_bw():
    # demo Baum Welch by generating some sequences and then performing
    # unsupervised training on them

    print()
    print("Baum-Welch demo for market example")
    print()

    model, states, symbols = _market_hmm_example()

    # generate some random sequences
    training = []
    import random
    rng = random.Random()
    rng.seed(0)
    for i in range(10):
        item = model.random_sample(rng, 5)
        training.append([(i[0], None) for i in item])

    # train on those examples, starting with the model that generated them
    trainer = HiddenMarkovModelTrainer(states, symbols)
    hmm = trainer.train_unsupervised(training, model=model,
                                     max_iterations=1000)
项目:kitty    作者:cisco-sas    | 项目源码 | 文件源码
def __init__(self, name, selection_strategy='1', seed=None):
        '''
        :param name: name of the Stage
        :param selection_strategy: strategy for selecting amount of template in each mutation
        :param seed: RNG seed (default: None)
        '''
        super(Stage, self).__init__('Stage[%s]' % name)
        self._templates = []
        self._strategy = selection_strategy
        self._min_sequence = None
        self._max_sequence = None
        self._r = random.Random()
        self._seed = seed
        if seed:
            self._r.seed(seed)
        self._current_sequence_templates = None
        self._default_sequence_templates = None
        self._ready = False
        self._validate_strategy(selection_strategy)
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def test_zeroinputs(self):
        # Verify that distributions can handle a series of zero inputs'
        g = random.Random()
        x = [g.random() for i in xrange(50)] + [0.0]*5
        g.random = x[:].pop; g.uniform(1,10)
        g.random = x[:].pop; g.paretovariate(1.0)
        g.random = x[:].pop; g.expovariate(1.0)
        g.random = x[:].pop; g.weibullvariate(1.0, 1.0)
        g.random = x[:].pop; g.vonmisesvariate(1.0, 1.0)
        g.random = x[:].pop; g.normalvariate(0.0, 1.0)
        g.random = x[:].pop; g.gauss(0.0, 1.0)
        g.random = x[:].pop; g.lognormvariate(0.0, 1.0)
        g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0)
        g.random = x[:].pop; g.gammavariate(0.01, 1.0)
        g.random = x[:].pop; g.gammavariate(1.0, 1.0)
        g.random = x[:].pop; g.gammavariate(200.0, 1.0)
        g.random = x[:].pop; g.betavariate(3.0, 3.0)
        g.random = x[:].pop; g.triangular(0.0, 1.0, 1.0/3.0)
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def test_constant(self):
        g = random.Random()
        N = 100
        for variate, args, expected in [
                (g.uniform, (10.0, 10.0), 10.0),
                (g.triangular, (10.0, 10.0), 10.0),
                (g.triangular, (10.0, 10.0, 10.0), 10.0),
                (g.expovariate, (float('inf'),), 0.0),
                (g.vonmisesvariate, (3.0, float('inf')), 3.0),
                (g.gauss, (10.0, 0.0), 10.0),
                (g.lognormvariate, (0.0, 0.0), 1.0),
                (g.lognormvariate, (-float('inf'), 0.0), 0.0),
                (g.normalvariate, (10.0, 0.0), 10.0),
                (g.paretovariate, (float('inf'),), 1.0),
                (g.weibullvariate, (10.0, float('inf')), 10.0),
                (g.weibullvariate, (0.0, 10.0), 0.0),
            ]:
            for i in range(N):
                self.assertEqual(variate(*args), expected)
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def test_zeroinputs(self):
        # Verify that distributions can handle a series of zero inputs'
        g = random.Random()
        x = [g.random() for i in xrange(50)] + [0.0]*5
        g.random = x[:].pop; g.uniform(1,10)
        g.random = x[:].pop; g.paretovariate(1.0)
        g.random = x[:].pop; g.expovariate(1.0)
        g.random = x[:].pop; g.weibullvariate(1.0, 1.0)
        g.random = x[:].pop; g.vonmisesvariate(1.0, 1.0)
        g.random = x[:].pop; g.normalvariate(0.0, 1.0)
        g.random = x[:].pop; g.gauss(0.0, 1.0)
        g.random = x[:].pop; g.lognormvariate(0.0, 1.0)
        g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0)
        g.random = x[:].pop; g.gammavariate(0.01, 1.0)
        g.random = x[:].pop; g.gammavariate(1.0, 1.0)
        g.random = x[:].pop; g.gammavariate(200.0, 1.0)
        g.random = x[:].pop; g.betavariate(3.0, 3.0)
        g.random = x[:].pop; g.triangular(0.0, 1.0, 1.0/3.0)
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def test_constant(self):
        g = random.Random()
        N = 100
        for variate, args, expected in [
                (g.uniform, (10.0, 10.0), 10.0),
                (g.triangular, (10.0, 10.0), 10.0),
                (g.triangular, (10.0, 10.0, 10.0), 10.0),
                (g.expovariate, (float('inf'),), 0.0),
                (g.vonmisesvariate, (3.0, float('inf')), 3.0),
                (g.gauss, (10.0, 0.0), 10.0),
                (g.lognormvariate, (0.0, 0.0), 1.0),
                (g.lognormvariate, (-float('inf'), 0.0), 0.0),
                (g.normalvariate, (10.0, 0.0), 10.0),
                (g.paretovariate, (float('inf'),), 1.0),
                (g.weibullvariate, (10.0, float('inf')), 10.0),
                (g.weibullvariate, (0.0, 10.0), 0.0),
            ]:
            for i in range(N):
                self.assertEqual(variate(*args), expected)
项目:scapy-bpf    作者:guedou    | 项目源码 | 文件源码
def __init__(self, inf, sup, seed=None, forever=1, renewkeys=0):
        self.forever = forever
        self.renewkeys = renewkeys
        self.inf = inf
        self.rnd = random.Random(seed)
        self.sbox_size = 256

        self.top = sup-inf+1

        n=0
        while (1<<n) < self.top:
            n += 1
        self.n =n

        self.fs = min(3,(n+1)/2)
        self.fsmask = 2**self.fs-1
        self.rounds = max(self.n,3)
        self.turns = 0
        self.i = 0
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def __init__(self, inf, sup, seed=None, forever=1, renewkeys=0):
        self.forever = forever
        self.renewkeys = renewkeys
        self.inf = inf
        self.rnd = random.Random(seed)
        self.sbox_size = 256

        self.top = sup-inf+1

        n=0
        while (1<<n) < self.top:
            n += 1
        self.n =n

        self.fs = min(3,(n+1)/2)
        self.fsmask = 2**self.fs-1
        self.rounds = max(self.n,3)
        self.turns = 0
        self.i = 0
项目:scapy-radio    作者:BastilleResearch    | 项目源码 | 文件源码
def __init__(self, inf, sup, seed=None, forever=1, renewkeys=0):
        self.forever = forever
        self.renewkeys = renewkeys
        self.inf = inf
        self.rnd = random.Random(seed)
        self.sbox_size = 256

        self.top = sup-inf+1

        n=0
        while (1<<n) < self.top:
            n += 1
        self.n =n

        self.fs = min(3,(n+1)/2)
        self.fsmask = 2**self.fs-1
        self.rounds = max(self.n,3)
        self.turns = 0
        self.i = 0
项目:Callandtext    作者:iaora    | 项目源码 | 文件源码
def getrandbytes(rng, count):
    """return byte-string containing *count* number of randomly generated bytes, using specified rng"""
    # NOTE: would be nice if this was present in stdlib Random class

    ###just in case rng provides this...
    ##meth = getattr(rng, "getrandbytes", None)
    ##if meth:
    ##    return meth(count)

    if not count:
        return _BEMPTY
    def helper():
        # XXX: break into chunks for large number of bits?
        value = rng.getrandbits(count<<3)
        i = 0
        while i < count:
            yield value & 0xff
            value >>= 3
            i += 1
    return join_byte_values(helper())
项目:isf    作者:w3h    | 项目源码 | 文件源码
def __init__(self, inf, sup, seed=None, forever=1, renewkeys=0):
        self.forever = forever
        self.renewkeys = renewkeys
        self.inf = inf
        self.rnd = random.Random(seed)
        self.sbox_size = 256

        self.top = sup-inf+1

        n=0
        while (1<<n) < self.top:
            n += 1
        self.n =n

        self.fs = min(3,(n+1)/2)
        self.fsmask = 2**self.fs-1
        self.rounds = max(self.n,3)
        self.turns = 0
        self.i = 0
项目:isf    作者:w3h    | 项目源码 | 文件源码
def __init__(self, name, selection_strategy='1', seed=None):
        '''
        :param name: name of the Stage
        :param selection_strategy: strategy for selecting amount of template in each mutation
        :param seed: RNG seed (default: None)
        '''
        super(Stage, self).__init__('Stage[%s]' % name)
        self._templates = []
        self._strategy = selection_strategy
        self._min_sequence = None
        self._max_sequence = None
        self._r = random.Random()
        self._seed = seed
        if seed:
            self._r.seed(seed)
        self._current_sequence_templates = None
        self._default_sequence_templates = None
        self._ready = False
        self._validate_strategy(selection_strategy)
项目:isf    作者:w3h    | 项目源码 | 文件源码
def __init__(self, name=None, fuzzable=True):
        namer = NameGen()
        fields = []
        r = Random()
        for tag in opcodes:
            for i in range(4):
                opcode = tag | i
                current = chr(opcode)
                for j in range(i):
                    current += chr(r.randint(0, 255))
                fields.append(Static(name=namer.gen(opcode), value=current))
        super(RandomHidReport, self).__init__(
            fields=fields,
            min_elements=10,
            max_elements=40,
            fuzzable=fuzzable,
            name=name
        )
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_zeroinputs(self):
        # Verify that distributions can handle a series of zero inputs'
        g = random.Random()
        x = [g.random() for i in range(50)] + [0.0]*5
        g.random = x[:].pop; g.uniform(1,10)
        g.random = x[:].pop; g.paretovariate(1.0)
        g.random = x[:].pop; g.expovariate(1.0)
        g.random = x[:].pop; g.weibullvariate(1.0, 1.0)
        g.random = x[:].pop; g.vonmisesvariate(1.0, 1.0)
        g.random = x[:].pop; g.normalvariate(0.0, 1.0)
        g.random = x[:].pop; g.gauss(0.0, 1.0)
        g.random = x[:].pop; g.lognormvariate(0.0, 1.0)
        g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0)
        g.random = x[:].pop; g.gammavariate(0.01, 1.0)
        g.random = x[:].pop; g.gammavariate(1.0, 1.0)
        g.random = x[:].pop; g.gammavariate(200.0, 1.0)
        g.random = x[:].pop; g.betavariate(3.0, 3.0)
        g.random = x[:].pop; g.triangular(0.0, 1.0, 1.0/3.0)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_constant(self):
        g = random.Random()
        N = 100
        for variate, args, expected in [
                (g.uniform, (10.0, 10.0), 10.0),
                (g.triangular, (10.0, 10.0), 10.0),
                #(g.triangular, (10.0, 10.0, 10.0), 10.0),
                (g.expovariate, (float('inf'),), 0.0),
                (g.vonmisesvariate, (3.0, float('inf')), 3.0),
                (g.gauss, (10.0, 0.0), 10.0),
                (g.lognormvariate, (0.0, 0.0), 1.0),
                (g.lognormvariate, (-float('inf'), 0.0), 0.0),
                (g.normalvariate, (10.0, 0.0), 10.0),
                (g.paretovariate, (float('inf'),), 1.0),
                (g.weibullvariate, (10.0, float('inf')), 10.0),
                (g.weibullvariate, (0.0, 10.0), 0.0),
            ]:
            for i in range(N):
                self.assertEqual(variate(*args), expected)
项目:litevideo    作者:enjoy-digital    | 项目源码 | 文件源码
def sink_generator(sink, rand_threshold=100):
    prng = random.Random(42)
    for i in range(len(sink_cb_cr)):
        valid = 0
        while True:
            valid = (prng.randrange(100) < rand_threshold)
            if valid:
                yield sink.valid.eq(1)
                yield sink.y.eq(sink_y[i])
                yield sink.cb_cr.eq(sink_cb_cr[i])
                yield
                while not (yield sink.ready):
                    yield
                yield sink.valid.eq(0)
                break
            else:
                yield sink.valid.eq(0)
                yield
    # yield for processing latency
    for i in range(128):
        yield
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def demo_bw():
    # demo Baum Welch by generating some sequences and then performing
    # unsupervised training on them

    print()
    print("Baum-Welch demo for market example")
    print()

    model, states, symbols = _market_hmm_example()

    # generate some random sequences
    training = []
    import random
    rng = random.Random()
    rng.seed(0)
    for i in range(10):
        item = model.random_sample(rng, 5)
        training.append([(i[0], None) for i in item])

    # train on those examples, starting with the model that generated them
    trainer = HiddenMarkovModelTrainer(states, symbols)
    hmm = trainer.train_unsupervised(training, model=model,
                                     max_iterations=1000)
项目:Dumb-Cogs    作者:irdumbs    | 项目源码 | 文件源码
def __init__(self, seed=None):
        Data.__init__(self)
        self.output = ''
        self.yesno_callback = False
        self.yesno_casual = False       # whether to insist they answer

        self.clock1 = 30                # counts down from finding last treasure
        self.clock2 = 50                # counts down until cave closes
        self.is_closing = False         # is the cave closing?
        self.panic = False              # they tried to leave during closing?
        self.is_closed = False          # is the cave closed?
        self.is_done = False            # caller can check for "game over"
        self.could_fall_in_pit = False  # could the player fall into a pit?

        self.random_generator = random.Random()
        if seed is not None:
            self.random_generator.seed(seed)
项目:python-    作者:secondtonone1    | 项目源码 | 文件源码
def rng(self):
        cur_pid = _os.getpid()
        if cur_pid != getattr(self, '_rng_pid', None):
            self._rng = _Random()
            self._rng_pid = cur_pid
        return self._rng
项目:picoCTF    作者:picoCTF    | 项目源码 | 文件源码
def give_port():
    """
    Returns a random port and registers it.
    """

    global port_random

    context = get_deploy_context()

    # default behavior
    if context["config"] is None:
        return randint(1000, 65000)

    if "banned_ports_parsed" not in context["config"]:
        banned_ports_result = []
        for port_range in context["config"].banned_ports:
            banned_ports_result.extend(list(range(port_range["start"], port_range["end"] + 1)))

        context["config"]["banned_ports_parsed"] = banned_ports_result

    # during real deployment, let's register a port
    if port_random is None:
        port_random = Random(context["config"].deploy_secret)

    # if this instance already has a port, reuse it
    if (context["problem"], context["instance"]) in inv_port_map:
        return inv_port_map[(context["problem"], context["instance"])]

    if len(context["port_map"].items()) + len(context["config"].banned_ports_parsed) == 65536:
        raise Exception("All usable ports are taken. Cannot deploy any more instances.")

    while True:
        port = port_random.randint(0, 65535)
        if port not in context["config"].banned_ports_parsed:
            owner, instance = context["port_map"].get(port, (None, None))
            if owner is None or (owner == context["problem"] and instance == context["instance"]):
                context["port_map"][port] = (context["problem"], context["instance"])
                return port
项目:picoCTF    作者:picoCTF    | 项目源码 | 文件源码
def update_problem_class(Class, problem_object, seed, user, instance_directory):
    """
    Changes the metaclass of the given class to introduce necessary fields before
    object instantiation.

    Args:
        Class: The problem class to be updated
        problem_name: The problem name
        seed: The seed for the Random object
        user: The linux username for this challenge instance
        instance_directory: The deployment directory for this instance

    Returns:
        The updated class described above
    """

    random = Random(seed)
    attributes = deepcopy(problem_object)

    # pass configuration options in as class fields
    attributes.update(dict(deploy_config))

    attributes.update({"random": random, "user": user, "directory": instance_directory,
                       "server": deploy_config.hostname})

    return challenge_meta(attributes)(Class.__name__, Class.__bases__, Class.__dict__)
项目:8-Queens    作者:miguelarauj1o    | 项目源码 | 文件源码
def initial_state(self):
        r = Random()
        return [r.randint(1, 8) for y in range(8)]
项目:8-Queens    作者:miguelarauj1o    | 项目源码 | 文件源码
def crossover(self, p1, p2):
        r = Random()
        crossover_index = r.randint(0, 8)
        left = p1.state[0:crossover_index]
        right = p2.state[crossover_index:8]
        left.extend(right)
        return left
项目:8-Queens    作者:miguelarauj1o    | 项目源码 | 文件源码
def mutate(self):
        r = Random()
        for i in range(len(self.state)):
            if random() < self._mutation_rate:
                self.state[i] = r.randint(1,8)
项目:8-Queens    作者:miguelarauj1o    | 项目源码 | 文件源码
def mutate(self):
        r = Random()

        if random() < self._mutation_rate:
            ix1 = r.randint(0,len(self.state)-1)
            ix2 = r.randint(0,len(self.state)-1)
            temp = self.state[ix1]
            self.state[ix1] = self.state[ix2]
            self.state[ix2] = temp
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def __init__(self):
        self.mutex = _allocate_lock()
        self.rng = _Random()
        self.normcase = _os.path.normcase
项目:abe-bootstrap    作者:TryCoin-Team    | 项目源码 | 文件源码
def __init__(gen, rng=1, chain=None, **kwargs):
        if not hasattr(rng, 'randrange'):
            import random
            rng = random.Random(rng)
        if chain is None:
            chain = Abe.Chain.create("Testnet")

        gen._rng = rng
        gen.chain = chain

        for attr, val in kwargs.items():
            setattr(gen, attr, val)