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

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

项目:Cortex-Analyzers    作者:CERT-BDF    | 项目源码 | 文件源码
def save(self):
        # Use long filename as first preference
        filename = self.longFilename

        # Otherwise use the short filename
        if filename is None:
            filename = self.shortFilename
        # Otherwise just make something up!
        if filename is None:
            import random
            import string
            filename = 'UnknownFilename ' + \
                       ''.join(random.choice(string.ascii_uppercase + string.digits)
                               for _ in range(5)) + ".bin"
            #f = open("/tmp/" + filename, 'wb')
            # if self.data is None:
            #f.write(("Pas de PJ"))
            # f.close()
            # else:
            # f.write((self.data))
            # f.close()
            # return filename
项目:Maps    作者:DarkPurple141    | 项目源码 | 文件源码
def render(self,PolygonList):
        a = self.get_neighbours(PolygonList)
        land = [i.terrain for i in a if i.terrain >= 0]
        salt = [i for i in self.get_neighbours(PolygonList) if i.terrain < 0]

        if len([i for i in self.vertices if i.river == True])/len(self.vertices) > 0.88:
            if not salt:
                self.terrain = 0
                self.color = color_palettes.shallows[2]
        if self.terrain < 0 and land:
            self.terrain = -1
            #self.color = color_palettes.shallows[0]
        elif self.terrain > 0 and len(land) != len(a):
            #coast = [i for i in self.vertices if i.coast]
            #if len(coast) > 1:
            #    render_coast(coast)
            if self.terrain > 2:
                self.color = random.choice(color_palettes.cliff)
            else:
                self.terrain = 1
                #self.color = random.choice(color_palettes.sand)
项目:robot-arena    作者:kenganong    | 项目源码 | 文件源码
def move():
  hits_robot = []
  hits_non_robot = []
  for move in MOVES:
    target = shooting(move)
    if target and target[TYPE] == ROBOT:
      hits_robot.append(move)
    elif target:
      hits_non_robot.append(move)
  if LASER in hits_robot:
    return LASER
  elif hits_robot:
    return random.choice(hits_robot)
  elif hits_non_robot:
    return random.choice(hits_non_robot)
  else:
    return FORWARD # Find something to shoot!
项目:DREAM    作者:LaceyChen17    | 项目源码 | 文件源码
def reorder_bpr_loss(re_x, his_x, dynamic_user, item_embedding, config):
    '''
        loss function for reorder prediction
        re_x padded reorder baskets
        his_x padded history bought items
    '''
    nll = 0
    ub_seqs = []
    for u, h, du in zip(re_x, his_x, dynamic_user):
        du_p_product = torch.mm(du, item_embedding.t()) # shape: max_len, num_item
        nll_u = [] # nll for user
        for t, basket_t in enumerate(u):
            if basket_t[0] != 0:
                pos_idx = torch.cuda.LongTensor(basket_t) if config.cuda else torch.LongTensor(basket_t)                               
                # Sample negative products
                neg = [random.choice(h[t]) for _ in range(len(basket_t))] # replacement
                # neg = random.sample(range(1, config.num_product), len(basket_t)) # without replacement
                neg_idx = torch.cuda.LongTensor(neg) if config.cuda else torch.LongTensor(neg)
                # Score p(u, t, v > v')
                score = du_p_product[t - 1][pos_idx] - du_p_product[t - 1][neg_idx]
                # Average Negative log likelihood for basket_t
                nll_u.append(- torch.mean(torch.nn.LogSigmoid()(score)))
        nll += torch.mean(torch.cat(nll_u))
    return nll
项目:graph    作者:noxern    | 项目源码 | 文件源码
def slack(text: hug.types.text):
    """Returns JSON containing an attachment with an image url for the Slack integration"""
    title = text

    if text == 'top250':
        top250_res = requests.get(IMDB_URL + '/chart/toptv', headers={'Accept-Language': 'en'})
        top250_page = html.fromstring(top250_res.text)
        candidates = top250_page.xpath('//*[@data-caller-name="chart-top250tv"]//tr/td[2]/a')

        title = random.choice(candidates).text

    return dict(
        response_type='in_channel',
        attachments=[
            dict(image_url=GRAPH_URL + f'/graph?title={quote(title)}&uuid={uuid.uuid4()}')
        ]
    )
项目:variational-text-tensorflow    作者:carpedm20    | 项目源码 | 文件源码
def get_neighbors(words, word, window_size=2):
  if type(word) == str:
    idx = words.index(word)
  elif type(word) == int:
    idx = word
  else:
    raise Exception(" [!] Invalid type for word: %s" % type(word))

  if idx < window_size:
    ans = words[-(window_size - idx):] + words[:idx + window_size + 1]
  elif idx >= len(words) - window_size:
    ans = words[idx-window_size:] + words[:window_size + idx - len(words) + 1]
  else:
    ans = words[idx-window_size:idx+window_size+1]

  for _ in xrange(15):
    if random.random() < 0.1:
      ans.append(random.choice(ans))

  random.shuffle(ans)
  return ans
项目:nidaqmx-python    作者:ni    | 项目源码 | 文件源码
def test_one_sample_one_line(self, x_series_device, seed):
        # Reset the pseudorandom number generator with seed.
        random.seed(seed)

        do_line = random.choice(x_series_device.do_lines).name

        with nidaqmx.Task() as task:
            task.do_channels.add_do_chan(
                do_line, line_grouping=LineGrouping.CHAN_PER_LINE)

            writer = DigitalSingleChannelWriter(task.out_stream)
            reader = DigitalSingleChannelReader(task.in_stream)

            # Generate random values to test.
            values_to_test = [bool(random.getrandbits(1)) for _ in range(10)]

            values_read = []
            for value_to_test in values_to_test:
                writer.write_one_sample_one_line(value_to_test)
                time.sleep(0.001)
                values_read.append(reader.read_one_sample_one_line())

            numpy.testing.assert_array_equal(values_read, values_to_test)
项目:nidaqmx-python    作者:ni    | 项目源码 | 文件源码
def test_one_sample_port_byte(self, x_series_device, seed):
        # Reset the pseudorandom number generator with seed.
        random.seed(seed)

        do_port = random.choice(
            [d for d in x_series_device.do_ports if d.do_port_width <= 8])

        with nidaqmx.Task() as task:
            task.do_channels.add_do_chan(
                do_port.name, line_grouping=LineGrouping.CHAN_FOR_ALL_LINES)

            # Generate random values to test.
            values_to_test = [int(random.getrandbits(do_port.do_port_width))
                              for _ in range(10)]

            writer = DigitalSingleChannelWriter(task.out_stream)
            reader = DigitalSingleChannelReader(task.in_stream)

            values_read = []
            for value_to_test in values_to_test:
                writer.write_one_sample_port_byte(value_to_test)
                time.sleep(0.001)
                values_read.append(reader.read_one_sample_port_byte())

            numpy.testing.assert_array_equal(values_read, values_to_test)
项目:nidaqmx-python    作者:ni    | 项目源码 | 文件源码
def test_one_sample_port_uint16(self, x_series_device, seed):
        # Reset the pseudorandom number generator with seed.
        random.seed(seed)

        do_port = random.choice(
            [do for do in x_series_device.do_ports if do.do_port_width <= 16])

        with nidaqmx.Task() as task:
            task.do_channels.add_do_chan(
                do_port.name, line_grouping=LineGrouping.CHAN_FOR_ALL_LINES)

            # Generate random values to test.
            values_to_test = [int(random.getrandbits(do_port.do_port_width))
                              for _ in range(10)]

            writer = DigitalSingleChannelWriter(task.out_stream)
            reader = DigitalSingleChannelReader(task.in_stream)

            values_read = []
            for value_to_test in values_to_test:
                writer.write_one_sample_port_uint16(value_to_test)
                time.sleep(0.001)
                values_read.append(reader.read_one_sample_port_uint16())

            numpy.testing.assert_array_equal(values_read, values_to_test)
项目:nidaqmx-python    作者:ni    | 项目源码 | 文件源码
def test_create_ai_voltage_chan(self, x_series_device, seed):
        # Reset the pseudorandom number generator with seed.
        random.seed(seed)

        ai_phys_chan = random.choice(x_series_device.ai_physical_chans).name

        with nidaqmx.Task() as task:
            ai_channel = task.ai_channels.add_ai_voltage_chan(
                ai_phys_chan, name_to_assign_to_channel="VoltageChannel",
                terminal_config=TerminalConfiguration.NRSE, min_val=-20.0,
                max_val=20.0, units=VoltageUnits.FROM_CUSTOM_SCALE,
                custom_scale_name="double_gain_scale")

            assert ai_channel.physical_channel.name == ai_phys_chan
            assert ai_channel.name == "VoltageChannel"
            assert ai_channel.ai_term_cfg == TerminalConfiguration.NRSE
            assert ai_channel.ai_min == -20.0
            assert ai_channel.ai_max == 20.0
            assert (ai_channel.ai_voltage_units ==
                    VoltageUnits.FROM_CUSTOM_SCALE)
            assert (ai_channel.ai_custom_scale.name ==
                    "double_gain_scale")
项目:nidaqmx-python    作者:ni    | 项目源码 | 文件源码
def test_create_ai_resistance_chan(self, x_series_device, seed):
        # Reset the pseudorandom number generator with seed.
        random.seed(seed)

        ai_phys_chan = random.choice(x_series_device.ai_physical_chans).name

        with nidaqmx.Task() as task:
            ai_channel = task.ai_channels.add_ai_resistance_chan(
                ai_phys_chan, name_to_assign_to_channel="ResistanceChannel",
                min_val=-1000.0, max_val=1000.0, units=ResistanceUnits.OHMS,
                resistance_config=ResistanceConfiguration.TWO_WIRE,
                current_excit_source=ExcitationSource.EXTERNAL,
                current_excit_val=0.002, custom_scale_name="")

            assert ai_channel.physical_channel.name == ai_phys_chan
            assert ai_channel.name == "ResistanceChannel"
            assert numpy.isclose(ai_channel.ai_min, -1000.0, atol=1)
            assert numpy.isclose(ai_channel.ai_max, 1000.0, atol=1)
            assert ai_channel.ai_resistance_units == ResistanceUnits.OHMS
            assert (ai_channel.ai_resistance_cfg ==
                    ResistanceConfiguration.TWO_WIRE)
            assert ai_channel.ai_excit_src == ExcitationSource.EXTERNAL
            assert ai_channel.ai_excit_val == 0.002
项目:nidaqmx-python    作者:ni    | 项目源码 | 文件源码
def test_watchdog_expir_state(self, x_series_device, seed):
        # Reset the pseudorandom number generator with seed.
        random.seed(seed)

        do_line = random.choice(x_series_device.do_lines)

        with nidaqmx.system.WatchdogTask(
                x_series_device.name, timeout=0.1) as task:
            expir_states = [DOExpirationState(
                physical_channel=do_line.name,
                expiration_state=Level.TRISTATE)]

            task.cfg_watchdog_do_expir_states(expir_states)

            expir_state_obj = task.expiration_states[do_line.name]
            assert expir_state_obj.expir_states_do_state == Level.TRISTATE

            expir_state_obj.expir_states_do_state = Level.LOW
            assert expir_state_obj.expir_states_do_state == Level.LOW
项目:nidaqmx-python    作者:ni    | 项目源码 | 文件源码
def test_arm_start_trigger(self, x_series_device, seed):
        # Reset the pseudorandom number generator with seed.
        random.seed(seed)

        counter = random.choice(self._get_device_counters(x_series_device))

        with nidaqmx.Task() as task:
            task.co_channels.add_co_pulse_chan_freq(counter)
            task.triggers.arm_start_trigger.trig_type = (
                TriggerType.DIGITAL_EDGE)
            assert (task.triggers.arm_start_trigger.trig_type ==
                    TriggerType.DIGITAL_EDGE)

            task.triggers.arm_start_trigger.trig_type = (
                TriggerType.NONE)
            assert (task.triggers.arm_start_trigger.trig_type ==
                    TriggerType.NONE)
项目:nidaqmx-python    作者:ni    | 项目源码 | 文件源码
def test_pause_trigger(self, x_series_device, seed):
        # Reset the pseudorandom number generator with seed.
        random.seed(seed)

        counter = random.choice(self._get_device_counters(x_series_device))

        with nidaqmx.Task() as task:
            task.co_channels.add_co_pulse_chan_freq(counter)
            task.timing.cfg_implicit_timing(
                sample_mode=AcquisitionType.CONTINUOUS)

            task.triggers.pause_trigger.trig_type = (
                TriggerType.DIGITAL_LEVEL)
            assert (task.triggers.pause_trigger.trig_type ==
                    TriggerType.DIGITAL_LEVEL)

            task.triggers.pause_trigger.trig_type = (
                TriggerType.NONE)
            assert (task.triggers.pause_trigger.trig_type ==
                    TriggerType.NONE)
项目:snips-skill-fakeweather    作者:snipsco    | 项目源码 | 文件源码
def generate_random_forecast(use_celcius=True):
        """ Generate a random weather forecast.

        :param use_celcius: If true, phrase should use degrees celcius,
                            otherwise use Fahrenheit.
        :return: A phrase describing a random weather forecast.
        """
        degrees = random.choice([12, 15, 18, 21, 23])
        conditions = random.choice([_("cloudy"), _("rainy"), _(
            "thunder storms"), _("windy"), _("clear sky"), _("light wind")])
        if use_celcius:
            degrees_sentence = _("{} degrees celcius").format(degrees)
        else:
            degrees = int(degrees * 9 / 5 + 32)
            degrees_sentence = _("{} degrees Fahrenheit").format(degrees)
        return _("{}, {}").format(conditions, degrees_sentence)
项目:PyPlanet    作者:PyPlanet    | 项目源码 | 文件源码
def test_map_juke(self):
        if len(self.instance.map_manager.maps) <= 1:
            raise Exception('Test server should contain more than 1 map!')
        while True:
            next_map = random.choice(list(self.instance.map_manager.maps))
            if next_map.uid != self.instance.map_manager.current_map.uid:
                break

        # Set next map
        await self.instance.map_manager.set_next_map(next_map)
        assert self.instance.map_manager.next_map == next_map
        map_info = await self.instance.gbx.execute('GetNextMapInfo')
        assert map_info['UId'] == next_map.uid
    #
    # async def test_map_jump(self):
    #   if len(self.instance.map_manager.maps) <= 1:
    #       raise Exception('Test server should contain more than 1 map!')
    #   while True:
    #       jump_map = random.choice(self.instance.map_manager.maps)
    #       if jump_map.uid != self.instance.map_manager.current_map.uid:
    #           break
    #
    #   # Skip to next map.
    #   await self.instance.map_manager.set_current_map(jump_map)
    #   assert self.instance.map_manager.next_map == jump_map
项目:zipline-chinese    作者:zhanghan1990    | 项目源码 | 文件源码
def minutes_for_days():
    """
    500 randomly selected days.
    This is used to make sure our test coverage is unbaised towards any rules.
    We use a random sample because testing on all the trading days took
    around 180 seconds on my laptop, which is far too much for normal unit
    testing.

    We manually set the seed so that this will be deterministic.
    Results of multiple runs were compared to make sure that this is actually
    true.

    This returns a generator of tuples each wrapping a single generator.
    Iterating over this yeilds a single day, iterating over the day yields
    the minutes for that day.
    """
    env = TradingEnvironment()
    random.seed('deterministic')
    return ((env.market_minutes_for_day(random.choice(env.trading_days)),)
            for _ in range(500))
项目:sappho    作者:lily-mayfield    | 项目源码 | 文件源码
def add_if_below_threshold(cls, player, asteroid_list, at_least_x_existing):

        if len(asteroid_list) < at_least_x_existing:
            plus_or_minus_x = random.choice([1, -1])
            new_asteroid_x = player.sprite.rect.top - (cls.SPAWN_DISTANCE_FROM_PLAYER * plus_or_minus_x)

            if new_asteroid_x > player.sprite.rect.left:
                x_speed = -1
            else:
                x_speed = 1

            plus_or_minus_y = random.choice([1, -1])
            new_asteroid_y = player.sprite.rect.left - (cls.SPAWN_DISTANCE_FROM_PLAYER * plus_or_minus_y)

            if new_asteroid_y > player.sprite.rect.top:
                y_speed = -1
            else:
                y_speed = 1

            another_asteroid = Asteroid((new_asteroid_x, new_asteroid_y), 10, x_speed, y_speed)
            asteroid_list.add(another_asteroid)
项目:board-games-app    作者:sampathweb    | 项目源码 | 文件源码
def generate_bot_move(self):
        """Returns the computer selected row, col
        """
        selections = defaultdict(list)
        if self.bot_level == 1:  # Easy - Pick any one from valid_choices list
            selected_item = random.choice(self.game_choices)
        elif self.bot_level == 2:  # Hard - Try to block the player from winning
            for win_set in self.winning_combos:
                rem_items = list(win_set - self.player_a_choices - self.player_b_choices)
                selections[len(rem_items)].append(rem_items)
            if selections.get(1):
                selected_item = random.choice(random.choice(selections[1]))
            elif selections.get(2):
                selected_item = random.choice(random.choice(selections[2]))
            else:
                selected_item = random.choice(random.choice(selections[3]))
        return selected_item
项目:freeradius    作者:epiphyte    | 项目源码 | 文件源码
def gen_pass(dump, key):
    """Generate password for a user account."""
    if key is None:
        print("no key available")
        exit(1)
    rands = ''.join(random.choice(CHARS) for _ in range(64))
    encoded = wrapper.encrypt(rands, key)
    raw = wrapper.decrypt(encoded, key)
    if rands != raw:
        print("encrypt/decrypt problem")
        exit(1)
    if dump:
        print("password:")
        print(raw)
        print("config file encoded")
        print(encoded)
    else:
        return (raw, encoded)
项目:Bahubali---DDOS-Toolkit    作者:navanchauhan    | 项目源码 | 文件源码
def _send_http_post(self, pause=10):
        global stop_now

        self.socks.send("POST / HTTP/1.1\r\n"
                        "Host: %s\r\n"
                        "User-Agent: %s\r\n"
                        "Connection: keep-alive\r\n"
                        "Keep-Alive: 900\r\n"
                        "Content-Length: 10000\r\n"
                        "Content-Type: application/x-www-form-urlencoded\r\n\r\n" % 
                        (self.host, random.choice(useragents)))

        for i in range(0, 9999):
            if stop_now:
                self.running = False
                break
            p = random.choice(string.letters+string.digits)
            print term.BOL+term.UP+term.CLEAR_EOL+"Posting: %s" % p+term.NORMAL
            self.socks.send(p)
            time.sleep(random.uniform(0.1, 3))

        self.socks.close()
项目:plugin.video.exodus    作者:lastship    | 项目源码 | 文件源码
def randomagent():
    BR_VERS = [
        ['%s.0' % i for i in xrange(18, 50)],
        ['37.0.2062.103', '37.0.2062.120', '37.0.2062.124', '38.0.2125.101', '38.0.2125.104', '38.0.2125.111', '39.0.2171.71', '39.0.2171.95', '39.0.2171.99',
         '40.0.2214.93', '40.0.2214.111',
         '40.0.2214.115', '42.0.2311.90', '42.0.2311.135', '42.0.2311.152', '43.0.2357.81', '43.0.2357.124', '44.0.2403.155', '44.0.2403.157', '45.0.2454.101',
         '45.0.2454.85', '46.0.2490.71',
         '46.0.2490.80', '46.0.2490.86', '47.0.2526.73', '47.0.2526.80', '48.0.2564.116', '49.0.2623.112', '50.0.2661.86', '51.0.2704.103', '52.0.2743.116',
         '53.0.2785.143', '54.0.2840.71'],
        ['11.0'],
        ['8.0', '9.0', '10.0', '10.6']]
    WIN_VERS = ['Windows NT 10.0', 'Windows NT 7.0', 'Windows NT 6.3', 'Windows NT 6.2', 'Windows NT 6.1', 'Windows NT 6.0', 'Windows NT 5.1', 'Windows NT 5.0']
    FEATURES = ['; WOW64', '; Win64; IA64', '; Win64; x64', '']
    RAND_UAS = ['Mozilla/5.0 ({win_ver}{feature}; rv:{br_ver}) Gecko/20100101 Firefox/{br_ver}',
                'Mozilla/5.0 ({win_ver}{feature}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{br_ver} Safari/537.36',
                'Mozilla/5.0 ({win_ver}{feature}; Trident/7.0; rv:{br_ver}) like Gecko',
                'Mozilla/5.0 (compatible; MSIE {br_ver}; {win_ver}{feature}; Trident/6.0)']
    index = random.randrange(len(RAND_UAS))
    return RAND_UAS[index].format(win_ver=random.choice(WIN_VERS), feature=random.choice(FEATURES), br_ver=random.choice(BR_VERS[index]))
项目:encore.ai    作者:dyelax    | 项目源码 | 文件源码
def get_seq(self, seq_len):
        """
        Gets a single pair of sequences (input, target) from a random song.

        @param seq_len: The number of words in a sequence.

        @return: A tuple of sequences, (input, target) offset from each other by one word.
        """
        # Pick a random song. Must be longer than seq_len
        for i in xrange(1000):  # cap at 1000 tries
            song = random.choice(self.lyric_indices)
            if len(song) > seq_len: break

        # Take a sequence of (seq_len) from the song lyrics
        i = random.randint(0, len(song) - (seq_len + 1))
        inp= np.array(song[i:i+seq_len], dtype=int)
        target =  np.array(song[i+1:i+seq_len+1], dtype=int)
        return inp, target
项目:simple_rl    作者:david-abel    | 项目源码 | 文件源码
def epsilon_greedy_q_policy(self, state):
        '''
        Args:
            state (State)

        Returns:
            (str): action.
        '''
        # Policy: Epsilon of the time explore, otherwise, greedyQ.
        if numpy.random.random() > self.epsilon:
            # Exploit.
            action = self.get_max_q_action(state)
        else:
            # Explore
            action = numpy.random.choice(self.actions)

        return action
项目:simple_rl    作者:david-abel    | 项目源码 | 文件源码
def _compute_max_qval_action_pair(self, state):
        '''
        Args:
            state (State)

        Returns:
            (tuple) --> (float, str): where the float is the Qval, str is the action.
        '''
        # Grab random initial action in case all equal
        best_action = random.choice(self.actions)
        max_q_val = float("-inf")
        shuffled_action_list = self.actions[:]
        random.shuffle(shuffled_action_list)

        # Find best action (action w/ current max predicted Q value)
        for action in shuffled_action_list:
            q_s_a = self.get_q_value(state, action)
            if q_s_a > max_q_val:
                max_q_val = q_s_a
                best_action = action

        return max_q_val, best_action
项目:simple_rl    作者:david-abel    | 项目源码 | 文件源码
def _compute_max_qval_action_pair(self, state, q_func_id=None):
        '''
        Args:
            state (State)
            q_func_id (str): either "A", "B", or None. If None, computes avg of A and B.

        Returns:
            (tuple) --> (float, str): where the float is the Qval, str is the action.
        '''
        # Grab random initial action in case all equal
        best_action = random.choice(self.actions)
        max_q_val = float("-inf")
        shuffled_action_list = self.actions[:]
        random.shuffle(shuffled_action_list)

        # Find best action (action w/ current max predicted Q value)
        for action in shuffled_action_list:
            q_s_a = self.get_q_value(state, action, q_func_id)
            if q_s_a > max_q_val:
                max_q_val = q_s_a
                best_action = action

        return max_q_val, best_action
项目:simple_rl    作者:david-abel    | 项目源码 | 文件源码
def _compute_max_qval_action_pair(self, state, horizon=None):
        '''
        Args:
            state (State)
            horizon (int): Indicates the level of recursion depth for computing Q.

        Returns:
            (tuple) --> (float, str): where the float is the Qval, str is the action.
        '''
        # If this is the first call, use the default horizon.
        if horizon is None:
            horizon = self.horizon

        # Grab random initial action in case all equal
        best_action = random.choice(self.actions)
        max_q_val = self.get_q_value(state, best_action, horizon)

        # Find best action (action w/ current max predicted Q value)
        for action in self.actions:
            q_s_a = self.get_q_value(state, action, horizon)
            if q_s_a > max_q_val:
                max_q_val = q_s_a
                best_action = action

        return max_q_val, best_action
项目:simple_rl    作者:david-abel    | 项目源码 | 文件源码
def _transition_func(self, state, action):
        '''
        Args:
            state (State)
            action (str)

        Returns
            (State)
        '''
        if self.num_states == 1:
            return state

        if (state, action) not in self._transitions:
            # Chooses @self.num_rand_trans from range(self.num_states)
            self._transitions[state][action] = np.random.choice(self.num_states, self.num_rand_trans, replace=False)

        state_id = np.random.choice(self._transitions[state][action])
        return RandomState(state_id)
项目:ptm    作者:GrivIN    | 项目源码 | 文件源码
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" % (random.getstate(), time.time())).encode('utf-8')
            ).digest())
    return ''.join(random.choice(allowed_chars) for i in range(length))
项目:AntiRansom    作者:YJesus    | 项目源码 | 文件源码
def randompdf (path) :

    numpdf = (randint(1500,2000))

    for i in range(10):

        name = path + ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(randint(5,15))]) + ".pdf"

        numwords = (randint(200,1000))

        pdf = FPDF()
        pdf.add_page()
        pdf.set_font("Arial", size=12)

        words =[]

        for i in range(numwords):

            randomword  = ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(randint(5,15))])
            words.append(randomword)

        wordsinstring = ''.join(words)

        pdf.cell(200, 10, txt=wordsinstring, align="C")

        pdf.output(name)

        for i in range(numpdf):

            dupli = path + ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(randint(5,15))]) + ".pdf"

            copyfile(name, dupli)
项目:pogom-linux    作者:PokeHunterProject    | 项目源码 | 文件源码
def read_config(scan_config):
    config_path = os.path.join(
        os.path.dirname(os.path.realpath(sys.argv[0])), "config.json")

    if os.path.isfile(config_path):
        config['CONFIG_PATH'] = config_path

    try:
        with open(config_path, "r") as f:
            c = json.loads(f.read())
    except:
        c = {}

    config['LOCALE'] = c.get('LOCALE', 'en')
    config['GOOGLEMAPS_KEY'] = c.get('GOOGLEMAPS_KEY', None)
    config['CONFIG_PASSWORD'] = c.get('CONFIG_PASSWORD', None)
    config['ACCOUNTS'] = c.get('ACCOUNTS', [])
    scan_config.update_scan_locations(c.get('SCAN_LOCATIONS', {}))

    if config.get('CONFIG_PASSWORD', None):
        config['AUTH_KEY'] = ''.join(random.choice(string.lowercase) for _ in range(32))
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def random_user(self, settings, author, server):
        filter_users = [server.get_member(x) for x in settings["Players"]
                        if hasattr(server.get_member(x), "name")]
        legit_users = [x for x in filter_users if x.id != author.id and x is not x.bot]

        users = [x for x in legit_users if settings["Players"][x.id]["Cookies"] > 0]

        if not users:
            user = "Fail"
        else:
            user = random.choice(users)
            if user == user.bot:
                users.remove(user.bot)
                settings["Players"].pop(user.bot)
                dataIO.save_json(self.file_path, self.system)
                user = random.choice(users)
            self.account_check(settings, user)
        return user
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def _clear_shop(self, ctx):
        """Wipes the entire shop list"""
        user = ctx.message.author
        settings = self.check_server_settings(user.server)
        shop_name = settings["Config"]["Shop Name"]
        await self.bot.say("Do you want to wipe the entire shop list? "
                           "You cannot undue this action.")
        choice = await self.bot.wait_for_message(timeout=15, author=user)
        if choice is None:
            msg = "Cancelling shop wipe."
        elif choice.content.title() == "No":
            msg = "Cancelling shop wipe."
        elif choice.content.title() == "Yes":
            settings["Shop List"] = {}
            dataIO.save_json(self.file_path, self.system)
            msg = "The shop list has been cleared from the {} Shop".format(shop_name)
        else:
            msg = "Improper response. Cancelling shop wipe."
        await self.bot.say(msg)
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def _sort_setshop(self, ctx, choice: str):
        """Changes the sorting method for shop listings. Alphabetical, Lowest, Highest"""
        server = ctx.message.server
        settings = self.check_server_settings(server)
        choice = choice.title()
        if choice == "Alphabetical":
            settings["Config"]["Sort Method"] = "Alphabet"
            dataIO.save_json(self.file_path, self.system)
            msg = "Changing sorting method to Alphabetical."
        elif choice == "Lowest":
            settings["Config"]["Sort Method"] = "Lowest"
            dataIO.save_json(self.file_path, self.system)
            msg = "Setting sorting method to Lowest."
        elif choice == "Highest":
            settings["Config"]["Sort Method"] = "Highest"
            dataIO.save_json(self.file_path, self.system)
            msg = "Setting sorting method to Highest."
        else:
            msg = "Please choose Alphabet, Lowest, or Highest."
        await self.bot.say(msg)
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def end(self, ctx):
        """Ends a raffle"""
        if self.raffle["Config"]["Active"]:
            if len(self.raffle["Players"]) > 0:
                self.raffle["Config"]["Active"] = False
                tickets = self.raffle["Config"]["Tickets"]
                winning_ticket = random.choice(tickets)
                winner = []
                for subdict in self.raffle["Players"]:
                    if winning_ticket in self.raffle["Players"][subdict]["Tickets"]:
                        winner.append(subdict)
                mention = "<@" + winner[0] + ">"
                await self.bot.say("The winner of the raffle is...")
                await asyncio.sleep(3)
                await self.bot.say(mention + "! Congratulations, you have won!")
                self.raffle["Config"]["Tickets"] = []
                self.raffle["Players"] = {}
            else:
                self.raffle["Config"]["Active"] = False
                await self.bot.say("Oh no! No one joined the raffle. Cancelling the raffle.")
            dataIO.save_json(self.file_path, self.raffle)
        else:
            await self.bot.say("You need to start a raffle for me to end one!")
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def game_outcomes(self, settings, players, target):
        success_rate = self.calculate_success(settings, target)
        good_out, bad_out = self.get_theme(settings)
        results = []
        for player in players:
            chance = random.randint(1, 100)
            if chance <= success_rate:
                good_thing = random.choice(good_out)
                good_out.remove(good_thing)
                settings["Crew"][player.id] = {"Name": player.name, "Bonus": good_thing[1]}
                settings["Players"][player.id]["Spree"] += 1
                results.append(good_thing[0].format(player.name))
            else:
                bad_thing = random.choice(bad_out)
                dropout_msg = bad_thing[0] + "```\n{0} dropped out of the game.```"
                self.failure_handler(settings, player, bad_thing[1])
                settings["Crew"].pop(player.id)
                bad_out.remove(bad_thing)
                results.append(dropout_msg.format(player.name))
        self.save_system()
        return results
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def game_setup(self, author, data, mode):

        racers = []

        if mode == 'zoo':
            if len(data['Players']) == 1:
                bot_set = random.choice(animals)
                racers = [Racer(bot_set[0], bot_set[1], self.bot.user)]

            for user in data['Players']:
                mobj = author.server.get_member(user)
                animal_set = random.choice(animals)
                racers.append(Racer(animal_set[0], animal_set[1], mobj))
        else:
            animal_set = (":turtle:", "slow")
            if len(data['Players']) == 1:
                racers = [Racer(animal_set[0], animal_set[1], self.bot.user)]

            for user in data['Players']:
                mobj = author.server.get_member(user)
                racers.append(Racer(animal_set[0], animal_set[1], mobj))

        return racers
项目:prov2bigchaindb    作者:DLR-SC    | 项目源码 | 文件源码
def is_block_to_tx_valid(tx_id: str, bdb_connection: BigchainDB) -> bool:
    """
    Checks if block with transaction is valid

    :param tx_id: Id of transaction which should be included in the
    :type tx_id: str
    :param bdb_connection: Connection object for BigchainDB
    :type bdb_connection: BigchainDB
    :return: True if transactions is in block and block is valid
    :rtype: bool
    """
    node = random.choice(bdb_connection.nodes)
    res = requests.get(node + bdb_connection.blocks.path + '?transaction_id=' + tx_id)
    block_id = res.json()
    if len(block_id) < 1 or len(block_id) > 1:
        raise exceptions.TransactionIdNotFound(tx_id)
    res = requests.get(node + bdb_connection.api_prefix + '/statuses?block_id=' + block_id[0])
    if res.status_code != 200:
        raise exceptions.BlockIdNotFound(block_id[0])
    status = res.json()['status']
    if status == 'valid':
        return True
    return False
项目:robocup-soccer    作者:kengz    | 项目源码 | 文件源码
def median(values):
    """Return the middle value, when the values are sorted.
    If there are an odd number of elements, try to average the middle two.
    If they can't be averaged (e.g. they are strings), choose one at random.
    >>> median([10, 100, 11])
    11
    >>> median([1, 2, 3, 4])
    2.5
    """
    n = len(values)
    values = sorted(values)
    if n % 2 == 1:
        return values[n/2]
    else:
        middle2 = values[(n/2)-1:(n/2)+1]
        try:
            return mean(middle2)
        except TypeError:
            return random.choice(middle2)
项目:MIT-CS-lectures    作者:William-Python-King    | 项目源码 | 文件源码
def main():
    answer=random.choice(list(queens(10)))
    prettyPrint(answer)
项目:MIT-CS-lectures    作者:William-Python-King    | 项目源码 | 文件源码
def  move(self,field,time=1):
        if  field.getDrunk()!=self:
            raise ValueError('Drunk.move called with drunk not in field')           
        for i  in range(time):
            pt=CompassPt(random.choice(CompassPt.possibles))
            field.move(pt,1) # Drunk?????
项目:charm-plumgrid-gateway    作者:openstack    | 项目源码 | 文件源码
def pwgen(length=None):
    """Generate a random pasword."""
    if length is None:
        # A random length is ok to use a weak PRNG
        length = random.choice(range(35, 45))
    alphanumeric_chars = [
        l for l in (string.ascii_letters + string.digits)
        if l not in 'l0QD1vAEIOUaeiou']
    # Use a crypto-friendly PRNG (e.g. /dev/urandom) for making the
    # actual password
    random_generator = random.SystemRandom()
    random_chars = [
        random_generator.choice(alphanumeric_chars) for _ in range(length)]
    return(''.join(random_chars))
项目:Maps    作者:DarkPurple141    | 项目源码 | 文件源码
def generate_name():
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    wordlist = []

    with open ("words", 'r') as fo:
        for word in fo:
            if len(word) < 5:
                continue
            else:
                wordlist.append(word.strip())

    namelength = random.randrange(4)
    pref = random.choice(wordlist)[0:3]
    pref = pref[0].upper() + pref[1:3]

    if random.random() > 0.5:
        suff = random.choice(wordlist)[-3:]
    else:
        suff = random.choice(wordlist)[:3]

    for i in range(namelength):
        pref = pref + random.choice(alphabet)

    name = pref + suff

    return name
项目:Maps    作者:DarkPurple141    | 项目源码 | 文件源码
def _make_river(river_source,centre):
    seen = set()
    start = random.choice(river_source.vertices)
    seen.add(start)
    start.river = True
    river_list = []
    river_list.append(start)
    q = queue.Queue()
    q.put(start)

    exceptions = []

    while not q.empty():
        curr = q.get()
        next_item = None
        for v in curr.v_neighbours:
            if v in seen:
                continue
            seen.add(v)
            if v and ((v.elevation <= curr.elevation or ((curr.elevation<2) and v.elevation>4)) and __centre_dist_inc(curr,v,centre)) and (v.elevation >= 0):
                next_item = v

        if next_item:
            if len([i.terrain for i in next_item.neighbours if i.terrain <0]) > 1:
                break
            else:
                q.put(next_item)
                if next_item.river:
                    exceptions.append(next_item)
                next_item.river = True
                river_list.append(next_item)

    if len(river_list) < 11:
        for i in river_list:
            if i not in exceptions:
                i.river = False
        return


    return river_list
项目:Maps    作者:DarkPurple141    | 项目源码 | 文件源码
def sea_or_land(self,centre,max_dist,island):

        x, y = self.centre.get_cords()
        point = (x - centre[0])/max_dist,(y - centre[1])/max_dist

        land = island.inside(point)

        if not land:
            self.terrain = -2
            self.color = random.choice(color_palettes.ocean)
        else:
            self.terrain = 2
            self.color = (50,150,0)
项目:Maps    作者:DarkPurple141    | 项目源码 | 文件源码
def make_mountain(self,polyList):
        self.terrain = min(self.terrain+5, 11)
        self.color = random.choice(color_palettes.terrain[11-self.terrain])
        n = self.get_neighbours(polyList)
        for i in n:
            i.terrain = min(i.terrain+4,11)
            i.color = random.choice(color_palettes.terrain[11-i.terrain])
项目:RandTerrainPy    作者:jackromo    | 项目源码 | 文件源码
def _init_gradients(self, vec_magnitude):
        """Initialize all gradient vectors to be in random directions with the same magnitude.

        Args:
            vec_magnitude (float): Magnitude of all gradient vectors.

        """
        self._grad_vecs = [[(0, 0) for _ in range(self._width_in_squares+1)] for _ in range(self._length_in_squares+1)]
        """list[list[tuple(float, float)]]: Grid of gradient vectors."""
        for x in range(self._width_in_squares+1):
            for y in range(self._length_in_squares+1):
                x_val = (random.random() - 0.5) * 2 * vec_magnitude
                y_val = math.sqrt(vec_magnitude**2 - x_val**2) * random.choice([1, -1])
                self._grad_vecs[y][x] = (x_val, y_val)
项目:cs114    作者:justinglobal    | 项目源码 | 文件源码
def random_question():
    question = random.choice(list(bools.keys()))
    answer = bools[question]

    return question, answer
项目:flora    作者:Lamden    | 项目源码 | 文件源码
def random_string(length):
    pool = string.ascii_letters + string.digits
    return ''.join(random.choice(pool) for i in range(length))