Python random.choices() Examples

The following are 30 code examples of random.choices(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module random , or try the search function .
Example #1
Source File: tests_views.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_process_multiple_tag_query_params(self):
        """Test that grouping by multiple tag keys returns a valid response."""
        with tenant_context(self.tenant):
            labels = (
                OCPAWSCostLineItemDailySummary.objects.filter(usage_start__gte=self.ten_days_ago)
                .values(*["tags"])
                .first()
            )
            self.assertIsNotNone(labels)
            tags = labels.get("tags")

        qstr = "filter[limit]=2"

        # pick a random subset of tags
        kval = len(tags.keys())
        if kval > 2:
            kval = random.randint(2, len(tags.keys()))
        selected_tags = random.choices(list(tags.keys()), k=kval)
        for tag in selected_tags:
            qstr += f"&group_by[tag:{tag}]=*"

        url = reverse("reports-openshift-aws-costs") + "?" + qstr
        client = APIClient()
        response = client.get(url, **self.headers)
        self.assertEqual(response.status_code, status.HTTP_200_OK) 
Example #2
Source File: client_auth.py    From maubot with GNU Affero General Public License v3.0 6 votes vote down vote up
def login(request: web.Request) -> web.Response:
    info, err = await read_client_auth_request(request)
    if err is not None:
        return err
    api, _, username, password, _ = info
    device_id = ''.join(random.choices(string.ascii_uppercase + string.digits, k=8))
    try:
        return web.json_response(await api.request(Method.POST, Path.login, content={
            "type": "m.login.password",
            "identifier": {
                "type": "m.id.user",
                "user": username,
            },
            "password": password,
            "device_id": f"maubot_{device_id}",
        }))
    except MatrixRequestError as e:
        return web.json_response({
            "errcode": e.errcode,
            "error": e.message,
        }, status=e.http_status) 
Example #3
Source File: Dataloader.py    From Text_Segmentation_Image_Inpainting with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, image_folder, max_images=False, image_size=(512, 512), add_random_masks=False):
        super(TestDataset, self).__init__()
        if isinstance(image_folder, str):
            self.images = glob.glob(os.path.join(image_folder, "clean/*"))
        else:
            self.images = list(chain.from_iterable([glob.glob(os.path.join(i, "clean/*")) for i in image_folder]))
        assert len(self.images) > 0

        if max_images:
            self.images = random.choices(self.images, k=max_images)
        print(f"Find {len(self.images)} images.")

        self.img_size = image_size

        self.transformer = Compose([  # RandomGrayscale(p=0.4),
            # ColorJitter(brightness=0.2, contrast=0.2, saturation=0, hue=0),
            ToTensor(),
            # Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
        ])
        self.add_random_masks = add_random_masks 
Example #4
Source File: Dataloader.py    From Text_Segmentation_Image_Inpainting with GNU General Public License v3.0 6 votes vote down vote up
def random_masks(pil_img, size=512, offset=10):
    draw = ImageDraw.Draw(pil_img)
    # draw liens
    # can't use np.random because its not forkable under PyTorch's dataloader with multiprocessing
    reps = random.randint(1, 5)

    for i in range(reps):
        cords = np.array(random.choices(range(offset, size), k=4)).reshape(2, 2)
        cords[1] = np.clip(cords[1], a_min=cords[0] - 75, a_max=cords[0] + 75)

        width = random.randint(15, 20)
        draw.line(cords.reshape(-1).tolist(), width=width, fill=255)
    # # draw circles
    reps = random.randint(1, 5)
    for i in range(reps):
        cords = np.array(random.choices(range(offset, size - offset), k=2))
        cords.sort()
        ex = np.array(random.choices(range(20, 70), k=2)) + cords
        ex = np.clip(ex, a_min=offset, a_max=size - offset)
        draw.ellipse(np.concatenate([cords, ex]).tolist(), fill=255)
    return pil_img 
Example #5
Source File: Table.py    From TIES_DataGeneration with MIT License 6 votes vote down vote up
def create(self):
        '''This will create the complete table'''
        self.define_col_types()                                             #define the data types for each column
        self.generate_missing_cells()                                       #generate missing cells


        local_span_flag=False                                               #no span initially
        if(self.assigned_category==3):                                      #if assigned category is 3, then it should have spanned rows or columns
            local_span_flag=True
        elif(self.assigned_category==4):                                    #if assigned category is 4, spanning/not spanning doesn't matter
            local_span_flag=random.choices([True,False],weights=[0.5,0.5])[0]   #randomly choose if to span columns and rows for headers or not
        #local_span_flag=True
        if(local_span_flag):
            self.make_header_col_spans()

        html=self.create_html()                                             #create equivalent html

        #create same row, col and cell matrices
        cells_matrix,cols_matrix,rows_matrix=self.create_same_cell_matrix(),\
                                             self.create_same_col_matrix(),\
                                             self.create_same_row_matrix()
        tablecategory=self.select_table_category()                      #select table category of the table
        return cells_matrix,cols_matrix,rows_matrix,self.idcounter,html,tablecategory 
Example #6
Source File: Dataloader.py    From Text_Segmentation_Image_Inpainting with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, image_folder, max_images=False, image_size=(512, 512), add_random_masks=False):
        super(ImageInpaintingData, self).__init__()

        if isinstance(image_folder, str):
            self.images = glob.glob(os.path.join(image_folder, "clean/*"))
        else:
            self.images = list(chain.from_iterable([glob.glob(os.path.join(i, "clean/*")) for i in image_folder]))
        assert len(self.images) > 0

        if max_images:
            self.images = random.choices(self.images, k=max_images)
        print(f"Find {len(self.images)} images.")

        self.img_size = image_size

        self.transformer = Compose([RandomGrayscale(p=0.4),
                                    # ColorJitter(brightness=0.2, contrast=0.2, saturation=0, hue=0),
                                    ToTensor(),
                                    # Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
                                    ])
        self.add_random_masks = add_random_masks 
Example #7
Source File: lambda_function.py    From aws-batch-example with MIT License 6 votes vote down vote up
def lambda_handler(event,context):
    # Grab data from environment
    jobqueue = os.environ['JobQueue']
    jobdef = os.environ['JobDefinition']

    # Create unique name for the job (this does not need to be unique)
    job1Name = 'job1' + ''.join(random.choices(string.ascii_uppercase + string.digits, k=4))

    # Set up a batch client 
    session = boto3.session.Session()
    client = session.client('batch')

    # Submit the job
    job1 = client.submit_job(
        jobName=job1Name,
        jobQueue=jobqueue,
        jobDefinition=jobdef
    )
    print("Started Job: {}".format(job1['jobName'])) 
Example #8
Source File: my_utils.py    From ICDAR-2019-SROIE with MIT License 6 votes vote down vote up
def random_string(n):
    if n == 0:
        return ""

    x = random.random()
    if x > 0.5:
        pad = " " * n
    elif x > 0.3:
        pad = "".join(random.choices(digits + " \t\n", k=n))
    elif x > 0.2:
        pad = "".join(random.choices(ascii_uppercase + " \t\n", k=n))
    elif x > 0.1:
        pad = "".join(random.choices(ascii_uppercase + digits + " \t\n", k=n))
    else:
        pad = "".join(
            random.choices(ascii_uppercase + digits + punctuation + " \t\n", k=n)
        )

    return pad 
Example #9
Source File: recording.py    From ReolinkCameraAPI with GNU General Public License v3.0 6 votes vote down vote up
def get_snap(self, timeout: int = 3) -> Image or None:
        """
        Gets a "snap" of the current camera video data and returns a Pillow Image or None
        :param timeout: Request timeout to camera in seconds
        :return: Image or None
        """
        randomstr = ''.join(random.choices(string.ascii_uppercase + string.digits, k=10))
        snap = self.url + "?cmd=Snap&channel=0&rs=" \
               + randomstr \
               + "&user=" + self.username \
               + "&password=" + self.password
        try:
            req = request.Request(snap)
            req.set_proxy(Request.proxies, 'http')
            reader = request.urlopen(req, timeout)
            if reader.status == 200:
                b = bytearray(reader.read())
                return Image.open(io.BytesIO(b))
            print("Could not retrieve data from camera successfully. Status:", reader.status)
            return None

        except Exception as e:
            print("Could not get Image data\n", e)
            raise 
Example #10
Source File: transaction_graph_generator.py    From AMLSim with Apache License 2.0 6 votes vote down vote up
def add_normal_sar_edges(self, ratio=1.0):
        """Add extra edges from normal accounts to SAR accounts to adjust transaction graph features
        :param ratio: Ratio of the number of edges to be added from normal accounts to SAR accounts
        compared to the number of total SAR accounts
        """
        sar_flags = nx.get_node_attributes(self.g, IS_SAR_KEY)
        orig_candidates = [n for n in self.hubs if not sar_flags.get(n, False)]  # Normal
        bene_candidates = [n for n, sar in sar_flags.items() if sar]  # SAR
        num = int(len(bene_candidates) * ratio)
        if num <= 0:
            return

        num_origs = len(orig_candidates)
        print("Number of orig/bene candidates: %d/%d" % (num_origs, len(bene_candidates)))
        orig_list = random.choices(orig_candidates, k=num)
        bene_list = random.choices(bene_candidates, k=num)
        for i in range(num):
            _orig = orig_list[i]
            _bene = bene_list[i]
            self.add_transaction(_orig, _bene)
        logger.info("Added %d edges from normal accounts to sar accounts" % num) 
Example #11
Source File: test_subview.py    From audiomate with MIT License 6 votes vote down vote up
def test_subview(benchmark):
    corpus = resources.generate_corpus(
        200,
        (5, 10),
        (1, 5),
        (0, 6),
        (1, 20),
        random.Random(x=234)
    )

    random.seed(200)
    filtered_utts = random.choices(list(corpus.utterances.keys()), k=20000)
    filters = [
        subset.MatchingUtteranceIdxFilter(filtered_utts)
    ]

    benchmark(run, corpus, filters) 
Example #12
Source File: ducks.py    From DHV3 with GNU Affero General Public License v3.0 6 votes vote down vote up
def _bushes(self, ctx):
        if random.randint(0, 5) == 1:
            choosen = random.choices(bushes_objects, bushes_weights)[0]()
            result = await choosen.give(ctx.bot, ctx)

            ctx.logger.info("Found in bushes : " + choosen.name)

            if choosen.db:
                db_name = choosen.db
                if not result:
                    db_name += '_not_taken'

                await ctx.bot.db.add_to_stat(ctx.message.channel, ctx.message.author, db_name, 1)

            _ = self.bot._
            language = await self.bot.db.get_pref(ctx.channel, "language")

            if result:
                await self.bot.send_message(ctx=ctx, message=(_("Searching the bushes around the duck, you found...", language) + "**" + _(choosen.name, language) + "**"))
            else:
                await self.bot.send_message(ctx=ctx, message=(
                        _("Searching the bushes around the duck, you found...", language) + "**" + _(choosen.name, language) + "**, " + _("that you unfortunately couldn't take, because your backpack is full.",
                                                                                                                             language))) 
Example #13
Source File: GenerateData.py    From AIX360 with Apache License 2.0 6 votes vote down vote up
def chooseRangeValue(thresholds, rangeList):
    """  Generate a random value based on the probability weights (thresholds) and list of ranges passed
    Args: 
        thresholds : list of probabilities for each choice
        rangeList: a list of pair lists giving the lower and upper bounds to choose value from 
    """

    # pick a number 1..3 from weights
    rangeVal = choices(Index3Population, thresholds)

    # get the appropriate range given rangeVal
    interval = rangeList[rangeVal[0]]

    # construct a population list from the result
    intervalPopulation = list(range(interval[0], interval[1]))

    # construct a equally prob weights list
    numElements = interval[1] - interval[0]
    probVal = 1.0 / numElements
    probList = [probVal] * numElements

    # now choose the value from the population based on the weights
    val = choices(intervalPopulation, probList)
    return val[0] 
Example #14
Source File: randAug.py    From Tricks-of-Semi-supervisedDeepLeanring-Pytorch with MIT License 5 votes vote down vote up
def __call__(self, img):
        ops = random.choices(self.augment_pool, k=self.n)
        for op, max_v, bias in ops:
            prob = np.random.uniform(0.2, 0.8)
            if random.random() + prob >= 1:
                img = op(img, v=self.m, max_v=max_v, bias=bias)
        img = CutoutAbs(img, 16)
        return img 
Example #15
Source File: data.py    From Sorting_Visualization with MIT License 5 votes vote down vote up
def __init__(self, Length, time_interval=1, 
                                sort_title="Figure", 
                                is_resampling=False, 
                                is_sparse=False, 
                                record=False, 
                                sound=False, sound_interval=16,
                                fps=25):
        self.data = [x for x in range(Length)]
        if is_resampling:
            self.data = random.choices(self.data, k=Length)
        else:
            self.Shuffle()
        if is_sparse:
            self.data = [x if random.random() < 0.3 else 0 for x in self.data]

        self.length = Length

        self.SetTimeInterval(time_interval)
        self.SetSortType(sort_title)
        self.Getfigure()
        self.InitTime()

        self.record = record
        if record:
            fourcc = cv2.VideoWriter_fourcc(*'XVID')
            self.vdo_wtr = cv2.VideoWriter("%s.avi"%self.sort_title, fourcc, fps, (self.im_size, self.im_size), True)
        
        self.sound = sound
        if sound and pygame is not None:
            self.SetSoundInterval(sound_interval)
            self.GetSoundArray()

        self.Visualize() 
Example #16
Source File: autoaug.py    From PyTorch-Encoding with MIT License 5 votes vote down vote up
def __call__(self, img):
        ops = random.choices(self.augment_list, k=self.n)
        for op, minval, maxval in ops:
            if random.random() > random.uniform(0.2, 0.8):
                continue
            val = (float(self.m) / 30) * float(maxval - minval) + minval
            img = op(img, val)
        return img 
Example #17
Source File: test_tfidf.py    From redshells with MIT License 5 votes vote down vote up
def test_apply_with_empty(self):
        texts = [random.choices(string.ascii_letters, k=100) for _ in range(100)]
        dictionary = gensim.corpora.Dictionary(texts)
        model = Tfidf(dictionary, texts)
        results = model.apply(texts + [[]])
        self.assertEqual([], results[-1]) 
Example #18
Source File: Table.py    From TIES_DataGeneration with MIT License 5 votes vote down vote up
def define_col_types(self):
        '''
        We define the data type that will go in each column. We categorize data in three types:
        1. 'n': Numbers
        2. 'w': word
        3. 'r': other types (containing special characters)

        '''

        len_all_words=len(self.all_words)
        len_all_numbers=len(self.all_numbers)
        len_all_others=len(self.all_others)

        total = len_all_words+len_all_numbers+len_all_others

        prob_words = len_all_words / total
        prob_numbers = len_all_numbers / total
        prob_others=len_all_others/total

        for i,type in enumerate(random.choices(['n','w','r'], weights=[prob_numbers,prob_words,prob_others], k=self.no_of_cols)):
            self.cell_types[:,i]=type

        '''The headers should be of type word'''
        self.cell_types[0:2,:]='w'

        '''All cells should have simple text but the headers'''
        self.headers[:] = 's'
        self.headers[0:2, :] = 'h' 
Example #19
Source File: fiat_ramp.py    From SempoBlockchain with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, **kwargs):
        super(FiatRamp, self).__init__(**kwargs)

        def random_string(length):
            return ''.join(random.choices(string.ascii_letters, k=length))

        self.payment_reference = random_string(5) + '-' + random_string(5) 
Example #20
Source File: randAug.py    From Tricks-of-Semi-supervisedDeepLeanring-Pytorch with MIT License 5 votes vote down vote up
def __call__(self, img):
        ops = random.choices(self.augment_pool, k=self.n)
        for op, max_v, bias in ops:
            v = np.random.randint(1, self.m)
            if random.random() < 0.5:
                img = op(img, v=v, max_v=max_v, bias=bias)
        img = CutoutAbs(img, 16)
        return img 
Example #21
Source File: dummy_multitask_box_env.py    From garage with MIT License 5 votes vote down vote up
def sample_tasks(self, n):
        """Sample a list of `num_tasks` tasks.

        Args:
            n (int): Number of tasks to sample.

        Returns:
            list[str]: A list of tasks.

        """
        return choices(self.all_task_names, k=n) 
Example #22
Source File: invitations.py    From cride-platzi with MIT License 5 votes vote down vote up
def create(self, **kwargs):
        """Handle code creation."""
        pool = ascii_uppercase + digits + '.-'
        code = kwargs.get('code', ''.join(random.choices(pool, k=self.CODE_LENGTH)))
        while self.filter(code=code).exists():
            code = ''.join(random.choices(pool, k=self.CODE_LENGTH))
        kwargs['code'] = code
        return super(InvitationManager, self).create(**kwargs) 
Example #23
Source File: email_whitelist.py    From SempoBlockchain with GNU General Public License v3.0 5 votes vote down vote up
def set_referral_code(self):
        self.referral_code = ''.join(random.choices(
            string.ascii_letters + string.digits, k=16)) 
Example #24
Source File: pool.py    From cwcf with MIT License 5 votes vote down vote up
def sample_steps(self, size):
        avg_len = self.sum_len / self.size
        eps_to_fetch = int(size / avg_len)

        return random.choices(self.data, k=eps_to_fetch) 
Example #25
Source File: user.py    From SempoBlockchain with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, blockchain_address=None, **kwargs):
        super(User, self).__init__(**kwargs)

        self.secret = ''.join(random.choices(
            string.ascii_letters + string.digits, k=16))

        self.primary_blockchain_address = blockchain_address or bt.create_blockchain_wallet() 
Example #26
Source File: evil_ssdp.py    From evil-ssdp with MIT License 5 votes vote down vote up
def gen_random(length):
        """Generates random hex strings"""
        chars = 'abcdef'
        digits = '0123456789'
        value = ''.join(random.choices(chars + digits, k=length))
        return value 
Example #27
Source File: sentiment.py    From TaobaoAnalysis with MIT License 5 votes vote down vote up
def create_train_test(train_pos_path=TRAIN_POS_PATH, train_neg_path=TRAIN_NEG_PATH,
                      test_pos_path=TEST_POS_PATH, test_neg_path=TEST_NEG_PATH):
    """
    用数据库中所有非默认评论创建训练和测试样本,保证正负样本数一样
    """

    pos, neg = [], []
    for content, rate in Review.filter_default(
        session.query(Review.content, Review.rate)
        .filter(Review.content != '')
    ):
        if Rate(rate).is_good:
            pos.append(content)
        else:
            neg.append(content)

    size = min(len(pos), len(neg))
    size_train = int(size * 0.8)
    pos = choices(pos, k=size)
    neg = choices(neg, k=size)

    for data, path in ((pos[:size_train], train_pos_path),
                       (neg[:size_train], train_neg_path),
                       (pos[size_train:], test_pos_path),
                       (neg[size_train:], test_neg_path)):
        with codecs.open(path, 'w', 'utf-8') as file:
            file.writelines(data) 
Example #28
Source File: functional.py    From clevr-graph with The Unlicense 5 votes vote down vote up
def op(self, graph, l:List, n:int):
		if len(l) < n:
			raise ValueError(f"Cannot sample {n} items from list of length {len(l)}")
		else:
			return random.choices(l, k=n) 
Example #29
Source File: test_pool.py    From airflow with Apache License 2.0 5 votes vote down vote up
def test_create_pool_name_too_long(self):
        long_name = ''.join(random.choices(string.ascii_lowercase, k=300))
        column_length = models.Pool.pool.property.columns[0].type.length
        self.assertRaisesRegex(AirflowBadRequest,
                               "^Pool name can't be more than %d characters$" % column_length,
                               pool_api.create_pool,
                               name=long_name,
                               slots=5,
                               description='') 
Example #30
Source File: slotmachine.py    From pajbot with MIT License 5 votes vote down vote up
def pull_lol(low_tier_emotes, high_tier_emotes, bet, house_edge, ltsw, htsw, ltbw, htbw):
    slot_options = []
    for e in low_tier_emotes:
        slot_options += [e] * 3
    for e in high_tier_emotes:
        slot_options += [e]

    randomized_emotes = random.choices(slot_options, k=3)

    # figure out results of these randomized emotes xd
    bet_return = 0.0

    emote_counts = Counter(randomized_emotes)

    for emote_name in emote_counts:
        emote_count = emote_counts[emote_name]

        if emote_count <= 1:
            continue

        if emote_count == 2:
            # small win
            if emote_name in low_tier_emotes:
                bet_return += ltsw
            else:
                bet_return += htsw

        if emote_count == 3:
            # big win
            if emote_name in low_tier_emotes:
                bet_return += ltbw
            else:
                bet_return += htbw

    return bet_return, randomized_emotes