python类seed()的实例源码

agents.py 文件源码 项目:deeppavlov 作者: deepmipt 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def add_cmdline_args(argparser):
        """Parameters of agent and default values"""
        group = argparser.add_argument_group('Coreference Teacher')
        group.add_argument('--language', type=str, default='ru')
        group.add_argument('--predictions_folder', type=str, default='predicts',
                           help='folder where to dump conll predictions, scorer will use this folder')
        group.add_argument('--scorer_path', type=str, default='scorer/reference-coreference-scorers/v8.01/scorer.pl',
                           help='path to CoNLL scorer perl script')
        group.add_argument('--valid_ratio', type=float,
                           default=0.2, help='valid_set ratio')
        group.add_argument('--test_ratio', type=float,
                           default=0.2, help='test_set ratio')
        group.add_argument('--teacher_seed', type=int, default=42, help='seed')
        group.add_argument('--raw-dataset-path', type=str, default=None,
                             help='Path to folder with two subfolders: dataset and scorer. '
                                  'These two folders are extracted rucoref_29.10.2015.zip and '
                                  'reference-coreference-scorers.v8.01.tar.gz')
agents.py 文件源码 项目:deeppavlov 作者: deepmipt 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def __init__(self, opt, shared=None):
        """Initialize the parameters of the DefaultTeacher"""
        assert opt['train_part'] + opt['test_part'] + opt['valid_part'] == 1
        self.parts = [opt['train_part'], opt['valid_part'], opt['test_part']]
        # store datatype
        self.dt = opt['datatype'].split(':')[0]
        self.opt = opt
        opt['datafile'] = _path(opt)

        # store identifier for the teacher in the dialog
        self.id = 'ner_teacher'

        random_state = random.getstate()
        random.seed(opt.get('teacher_seed'))
        self.random_state = random.getstate()
        random.setstate(random_state)

        if shared and shared.get('metrics'):
            self.metrics = shared['metrics']
        else:
            self.metrics = CoNLLClassificationMetrics(opt['model_file'])

        # define standard question, since it doesn't change for this task
        super().__init__(opt, shared)
service.py 文件源码 项目:iotronic 作者: openstack 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def _child_process(self, service):
        self._child_process_handle_signal()

        # Reopen the eventlet hub to make sure we don't share an epoll
        # fd with parent and/or siblings, which would be bad
        eventlet.hubs.use_hub()

        # Close write to ensure only parent has it open
        os.close(self.writepipe)
        # Create greenthread to watch for parent to close pipe
        eventlet.spawn_n(self._pipe_watcher)

        # Reseed random number generator
        random.seed()

        launcher = Launcher()
        launcher.launch_service(service)
        return launcher
crypto.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def get_random_string(length=12,
                      allowed_chars='abcdefghijklmnopqrstuvwxyz'
                                    'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
    """
    Returns a securely generated random string.

    The default length of 12 with the a-z, A-Z, 0-9 character set returns
    a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
    """
    if not using_sysrandom:
        # This is ugly, and a hack, but it makes things better than
        # the alternative of predictability. This re-seeds the PRNG
        # using a value that is hard for an attacker to predict, every
        # time a random string is required. This may change the
        # properties of the chosen random sequence slightly, but this
        # is better than absolute predictability.
        random.seed(
            hashlib.sha256(
                ("%s%s%s" % (
                    random.getstate(),
                    time.time(),
                    settings.SECRET_KEY)).encode('utf-8')
            ).digest())
    return ''.join(random.choice(allowed_chars) for i in range(length))
chunk_vacuum.py 文件源码 项目:cpsc415 作者: WheezePuppet 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def run(self, vacuum_class, max_steps=10000):
        scores = []

        for seed in seeds:
            logging.debug('Running seed {}...'.format(seed))
            random.seed(seed)
            dve = RandomDirtyVacuumEnvironment()
            dve.add_to_random_empty_square(vacuum_class())
            step = 0
            steps_to_clean = 0
            while step < max_steps:
                dve.step()
                step += 1
                if not dve.is_clean():
                    steps_to_clean += 1
            scores.append(Result(seed, dve.agents[0].performance,
                steps_to_clean))
        return scores
concept_test.py 文件源码 项目:ConceptualSpaces 作者: lbechberger 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_sample_two_dimensions_one_cuboid_property(self):
        random.seed(42)
        doms = {0:[0], 1:[1]}
        dom = {0:[0]}
        cs.init(2, doms)
        s = Core([Cuboid([0.5, float("-inf")],[0.7, float("inf")],dom)], dom)
        w = Weights({0:1}, {0:{0:1}})
        f = Concept(s, 1.0, 10.0, w)    

        expected_samples = [[0.671077246097072, -1.1182375118372132], [0.7223363669989505, 0.8182873448596939], 
                            [0.8341255198319808, 0.43652402266795276], [0.4349365229310276, 1.658190358962174], 
                            [0.6150663198218392, -1.6363623513048244], [0.47689201330881126, -1.7458891753921715], 
                            [0.5268116788866108, 1.8152637100843205], [0.8197557203077108, 0.43588084575268926], 
                            [0.6480058823075816, -1.997712415488226], [0.5778432024671717, -1.7231499261264656], 
                            [0.6787669258743846, -0.9397734842397636], [0.47843872817402455, -1.1528071782316718], 
                            [0.6277970899463485, -1.5159832165269371], [0.7123582792556478, -0.10931589475282344], 
                            [0.4909539247388911, -0.3056855079203169], [0.5187297023218571, -0.31247344066238325], 
                            [0.5772907067965353, -1.1450108032032733], [0.6882004507621521, 0.873633101185304], 
                            [0.6667338652830263, 0.9919022415162564], [0.4722500795674033, 0.3346891571648989]]
        samples = f.sample(20)
        self.assertEqual(samples, expected_samples)
mesh_maze.py 文件源码 项目:mesh_maze 作者: elfnor 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def generate_maze(bm, maze_params):
    """
    generate the maze on the bm bmesh
    """
    bm.verts.ensure_lookup_table()
    bm.edges.ensure_lookup_table()
    sel_geom, inner_edges = get_inner_edges(bm, maze_params['boundary_type'])
    if maze_params['maze_update']:
        all_edges = sorted(bm.edges, key=lambda edge: edge.index)
        full_mesh = inner_edges == all_edges
        random.seed(maze_params['rseed'])
        maze_path, maze_verts = recursive_back_tracker_maze(inner_edges, full_mesh)
        if maze_params['braid'] > 0.0:
            maze_path = do_braid(maze_path, maze_verts, maze_params['braid'])

        link_centers, vert_centers = get_maze_centers(maze_path, maze_verts)
    else:
        link_centers = maze_params['link_centers']
        vert_centers = maze_params['vert_centers']

    bevel_extrude(bm, sel_geom, maze_params, link_centers, vert_centers)
    return bm, link_centers, vert_centers
hashing.py 文件源码 项目:coralillo 作者: getfleety 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def get_random_string(length=12,
                      allowed_chars='abcdefghijklmnopqrstuvwxyz'
                                    'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
    """
    Return a securely generated random string.
    The default length of 12 with the a-z, A-Z, 0-9 character set returns
    a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
    """
    if not using_sysrandom:
        # This is ugly, and a hack, but it makes things better than
        # the alternative of predictability. This re-seeds the PRNG
        # using a value that is hard for an attacker to predict, every
        # time a random string is required. This may change the
        # properties of the chosen random sequence slightly, but this
        # is better than absolute predictability.
        random.seed(
            hashlib.sha256(
                ('%s%s%s' % (random.getstate(), time.time(), settings.SECRET_KEY)).encode()
            ).digest()
        )
        return ''.join(random.choice(allowed_chars) for i in range(length))
Functions.py 文件源码 项目:turtle 作者: icse-turtle 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def __init__(self):
        Module.__init__(self)
        self.add_method('+', self.addition)
        self.add_method('-', self.subtraction)
        self.add_method('*', self.multiplication)
        self.add_method('/', self.division)
        self.add_method('%', self.module)
        self.add_method('**', self.power)
        self.add_method('abs', self.abs)
        self.add_method('min', self.minimum)
        self.add_method('max', self.maximum)
        self.add_method('strcat', self.strcat)
        self.add_method('substr', self.substr)
        self.add_method('strlen', self.strlen)
        self.add_method('strindex', self.strindex)
        self.add_method('symcat', self.symcat)
        self.add_method('randint', self.randint)

        random.seed(time.time())
Steganography.py 文件源码 项目:Steganography 作者: Ludisposed 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def retrieve_lsb(data, magic):
    '''
    A method that retrieves the least significant bits of the picture

    Args:
        data     (list): The list representation of the image
        magic    (str) : The password

    Returns:
        The list representation of the image with retrieved text from random lsb's
    '''
    print '[*] Retrieving message from image'

    retrieve_range = range(data.size)
    if not magic is None:
        random.seed(generate_seed(magic))
        retrieve_range = random_ints(data.size)

    return retrieve(data, retrieve_range)
name_gen.py 文件源码 项目:Maps 作者: DarkPurple141 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def __init__(self,location = None):
        random.seed()
        self.name = generate_name()
        self.location = location
        self.cities = []
voronoi.py 文件源码 项目:Maps 作者: DarkPurple141 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def __init__(self,seed):
        random.seed(seed)
        self.ISLAND_FACTOR = 1.13 # 1.0 means no small islands; 2.0 leads to a lot
        self.bumps = random.randrange(1,7)
        self.startAngle = random.uniform(0,2*math.pi)
        self.dipAngle = random.uniform(0,2*math.pi)
        self.dipWidth = random.uniform(0.2,0.7)
plsr2.py 文件源码 项目:pylspm 作者: lseman 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def HOCcat(data_, mvmodel, seed):
    response = data_.ix[:, 10:25]
    preditors = []
    preditors.append(data_.ix[:, 10:15])
    preditors.append(data_.ix[:, 15:20])
    preditors.append(data_.ix[:, 20:25])

    plsr_ = None
    for i in range(3):
        res_ = plsr2(preditors[i], response, seed=seed)[0]
        plsr_ = res_ if plsr_ is None else np.hstack((plsr_, res_))

    plsr_ = pd.DataFrame(plsr_)
    plsr_.index = range(len(plsr_))

    cols = list(plsr_.columns)
    for s in range(len(cols)):
        cols[cols.index(s)] = 'T' + str(s)
    plsr_.columns = cols

    data_ = pd.concat([data_, plsr_], axis=1)

    Variables = pd.read_csv(mvmodel)
    Variables = Variables[
        Variables.latent.str.contains("Humanização") == False]

    for i in range(len(cols)):
        df_ = pd.DataFrame([['Humanização', cols[i], 'A']],
                           columns=Variables.columns)
        Variables = Variables.append(df_)

    Variables.index = range(len(Variables))
    mvmodel = Variables

    return[data_, mvmodel]
gen.py 文件源码 项目:tree-gen 作者: friggog 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def construct(params, seed=0, render=False, out_path=None):
    """Construct the tree"""
    if seed == 0:
        seed = int(random.random() * 9999999)
        # print('Seed: ', seed)
    random.seed(seed)
    Tree(TreeParam(params)).make()
    if render:
        bpy.data.scenes['Scene'].render.filepath = out_path
        bpy.ops.render.render(write_still=True)

#mod = __import__('ch_trees.parametric.tree_params.quaking_aspen', fromlist=[''])
#reload(mod)
#construct(mod.params)
test_stream_counter_readers_writers.py 文件源码 项目:nidaqmx-python 作者: ni 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def test_one_sample_uint32(self, x_series_device, seed):
        # Reset the pseudorandom number generator with seed.
        random.seed(seed)

        number_of_pulses = random.randint(2, 50)
        frequency = random.uniform(1000, 10000)

        # Select random counters from the device.
        counters = random.sample(self._get_device_counters(x_series_device), 2)

        with nidaqmx.Task() as write_task, nidaqmx.Task() as read_task:
            write_task.co_channels.add_co_pulse_chan_freq(
                counters[0], freq=frequency)
            write_task.timing.cfg_implicit_timing(
                samps_per_chan=number_of_pulses)

            read_task.ci_channels.add_ci_count_edges_chan(counters[1])
            read_task.ci_channels.all.ci_count_edges_term = (
                '/{0}InternalOutput'.format(counters[0]))

            reader = CounterReader(read_task.in_stream)

            read_task.start()
            write_task.start()

            write_task.wait_until_done(timeout=2)

            value_read = reader.read_one_sample_uint32()
            assert value_read == number_of_pulses
test_stream_counter_readers_writers.py 文件源码 项目:nidaqmx-python 作者: ni 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def test_one_sample_double(self, x_series_device, seed):
        # Reset the pseudorandom number generator with seed.
        random.seed(seed)

        frequency = random.uniform(1000, 10000)

        # Select random counters from the device.
        counters = random.sample(
            self._get_device_counters(x_series_device), 2)

        with nidaqmx.Task() as write_task, nidaqmx.Task() as read_task:
            write_task.co_channels.add_co_pulse_chan_freq(
                counters[0], freq=frequency)
            write_task.timing.cfg_implicit_timing(
                sample_mode=AcquisitionType.CONTINUOUS)
            actual_frequency = write_task.co_channels.all.co_pulse_freq

            read_task.ci_channels.add_ci_freq_chan(
                counters[1], min_val=1000, max_val=10000)
            read_task.ci_channels.all.ci_freq_term = (
                '/{0}InternalOutput'.format(counters[0]))

            reader = CounterReader(read_task.in_stream)

            read_task.start()
            write_task.start()

            value_read = reader.read_one_sample_double()

            numpy.testing.assert_allclose(
                [value_read], [actual_frequency], rtol=0.05)
test_stream_counter_readers_writers.py 文件源码 项目:nidaqmx-python 作者: ni 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def test_multi_sample_double(self, x_series_device, seed):
        # Reset the pseudorandom number generator with seed.
        random.seed(seed)

        number_of_samples = random.randint(2, 50)
        frequency = random.uniform(1000, 10000)

        # Select random counters from the device.
        counters = random.sample(
            self._get_device_counters(x_series_device), 3)

        with nidaqmx.Task() as write_task, nidaqmx.Task() as read_task:
            write_task.co_channels.add_co_pulse_chan_freq(
                counters[1], freq=frequency)
            write_task.timing.cfg_implicit_timing(
                samps_per_chan=number_of_samples + 1)

            read_task.ci_channels.add_ci_freq_chan(
                counters[2], min_val=1000, max_val=10000, edge=Edge.RISING)
            read_task.ci_channels.all.ci_freq_term = (
                '/{0}InternalOutput'.format(counters[1]))
            read_task.timing.cfg_implicit_timing(
                samps_per_chan=number_of_samples)

            read_task.start()
            write_task.start()
            write_task.wait_until_done(timeout=2)

            reader = CounterReader(read_task.in_stream)

            values_read = numpy.zeros(number_of_samples, dtype=numpy.float64)
            reader.read_many_sample_double(
                values_read, number_of_samples_per_channel=number_of_samples,
                timeout=2)

            expected_values = [frequency for _ in range(number_of_samples)]

            numpy.testing.assert_allclose(
                values_read, expected_values, rtol=0.05)
test_stream_counter_readers_writers.py 文件源码 项目:nidaqmx-python 作者: ni 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def test_one_sample_pulse_freq(self, x_series_device, seed):
        # Reset the pseudorandom number generator with seed.
        random.seed(seed)

        frequency = random.uniform(1000, 10000)
        duty_cycle = random.uniform(0.2, 0.8)

        # Select random counters from the device.
        counters = random.sample(self._get_device_counters(x_series_device), 2)

        with nidaqmx.Task() as write_task, nidaqmx.Task() as read_task:
            write_task.co_channels.add_co_pulse_chan_freq(
                counters[0], freq=frequency, duty_cycle=duty_cycle)
            write_task.timing.cfg_implicit_timing(
                sample_mode=AcquisitionType.CONTINUOUS)

            read_task.ci_channels.add_ci_pulse_chan_freq(
                counters[1], min_val=1000, max_val=10000)
            read_task.ci_channels.all.ci_pulse_freq_term = (
                '/{0}InternalOutput'.format(counters[0]))

            read_task.start()
            write_task.start()

            reader = CounterReader(read_task.in_stream)

            value_read = reader.read_one_sample_pulse_frequency()
            write_task.stop()

            assert numpy.isclose(value_read.freq, frequency, rtol=0.05)
            assert numpy.isclose(value_read.duty_cycle, duty_cycle, rtol=0.05)
test_stream_counter_readers_writers.py 文件源码 项目:nidaqmx-python 作者: ni 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def test_one_sample_pulse_time(self, x_series_device, seed):
        # Reset the pseudorandom number generator with seed.
        random.seed(seed)

        high_time = random.uniform(0.0001, 0.001)
        low_time = random.uniform(0.0001, 0.001)

        # Select random counters from the device.
        counters = random.sample(self._get_device_counters(x_series_device), 2)

        with nidaqmx.Task() as write_task, nidaqmx.Task() as read_task:
            write_task.co_channels.add_co_pulse_chan_time(
                counters[0], high_time=high_time, low_time=low_time)
            write_task.timing.cfg_implicit_timing(
                sample_mode=AcquisitionType.CONTINUOUS)

            read_task.ci_channels.add_ci_pulse_chan_time(
                counters[1], min_val=0.0001, max_val=0.001)
            read_task.ci_channels.all.ci_pulse_time_term = (
                '/{0}InternalOutput'.format(counters[0]))

            read_task.start()
            write_task.start()

            reader = CounterReader(read_task.in_stream)
            value_read = reader.read_one_sample_pulse_time()
            write_task.stop()

            assert numpy.isclose(value_read.high_time, high_time, rtol=0.05)
            assert numpy.isclose(value_read.low_time, low_time, rtol=0.05)


问题


面经


文章

微信
公众号

扫码关注公众号