Python random.choice() Examples

The following are code examples for showing how to use random.choice(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    MIT License 8 votes vote down vote up
def setUpClass(self):
        """Database setup before the CRUD tests."""
        print("Creating a temporary datatbsse...")
        engine = create_engine('sqlite:///:memory:')
        Base.metadata.create_all(engine)
        session = scoped_session(sessionmaker(bind=engine))
        self.API_NAME = "demoapi"
        self.HYDRUS_SERVER_URL = "http://hydrus.com/"
        self.session = session

        self.doc = doc_maker.create_doc(
            doc, self.HYDRUS_SERVER_URL, self.API_NAME)

        test_classes = doc_parse.get_classes(self.doc.generate())

        # Getting list of classes from APIDoc
        self.doc_collection_classes = [
            self.doc.collections[i]["collection"].class_.title for i in self.doc.collections]
        print(self.doc_collection_classes)
        print(random.choice(self.doc_collection_classes))
        test_properties = doc_parse.get_all_properties(test_classes)
        doc_parse.insert_classes(test_classes, self.session)
        doc_parse.insert_properties(test_properties, self.session)
        print("Classes and properties added successfully.")
        print("Setup done, running tests...") 
Example 2
Project: simulated-annealing-tsp   Author: chncyhn   File: anneal.py    MIT License 6 votes vote down vote up
def initial_solution(self):
        """
        Greedy algorithm to get an initial solution (closest-neighbour).
        """
        cur_node = random.choice(self.nodes)  # start from a random node
        solution = [cur_node]

        free_nodes = set(self.nodes)
        free_nodes.remove(cur_node)
        while free_nodes:
            next_node = min(free_nodes, key=lambda x: self.dist(cur_node, x))  # nearest neighbour
            free_nodes.remove(next_node)
            solution.append(next_node)
            cur_node = next_node

        cur_fit = self.fitness(solution)
        if cur_fit < self.best_fitness:  # If best found so far, update best fitness
            self.best_fitness = cur_fit
            self.best_solution = solution
        self.fitness_list.append(cur_fit)
        return solution, cur_fit 
Example 3
Project: mutatest   Author: EvanKepner   File: run.py    MIT License 6 votes vote down vote up
def colorize_output(output: str, color: str) -> str:
    """Color output for the terminal display as either red or green.

    Args:
        output: string to colorize
        color: choice of terminal color, "red" vs. "green"

    Returns:
        colorized string, or original string for bad color choice.
    """
    colors = {
        "red": f"\033[91m{output}\033[0m",  # Red text
        "green": f"\033[92m{output}\033[0m",  # Green text
        "yellow": f"\033[93m{output}\033[0m",  # Yellow text
        "blue": f"\033[94m{output}\033[0m",  # Blue text
    }

    return colors.get(color, output) 
Example 4
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    MIT License 6 votes vote down vote up
def gen_dummy_object(class_title, doc):
    """Create a dummy object based on the definitions in the API Doc.
    :param class_title: Title of the class whose object is being created.
    :param doc: ApiDoc.
    :return: A dummy object of class `class_title`.
    """
    object_ = {
        "@type": class_title
    }
    for class_path in doc.parsed_classes:
        if class_title == doc.parsed_classes[class_path]["class"].title:
            for prop in doc.parsed_classes[class_path]["class"].supportedProperty:
                if isinstance(prop.prop, HydraLink) or prop.write is False:
                    continue
                if "vocab:" in prop.prop:
                    prop_class = prop.prop.replace("vocab:", "")
                    object_[prop.title] = gen_dummy_object(prop_class, doc)
                else:
                    object_[prop.title] = ''.join(random.choice(
                        string.ascii_uppercase + string.digits) for _ in range(6))
            return object_ 
Example 5
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    MIT License 6 votes vote down vote up
def test_delete(self):
        """Test CRUD delete."""
        object_ = gen_dummy_object(random.choice(
            self.doc_collection_classes), self.doc)
        id_ = str(uuid.uuid4())
        insert_response = crud.insert(
            object_=object_, id_=id_, session=self.session)
        delete_response = crud.delete(
            id_=id_, type_=object_["@type"], session=self.session)
        assert isinstance(insert_response, str)
        response_code = None
        try:
            get_response = crud.get(
                id_=id_,
                type_=object_["@type"],
                session=self.session,
                api_name="api")
        except Exception as e:
            error = e.get_HTTP()
            response_code = error.code
        assert 404 == response_code 
Example 6
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    MIT License 6 votes vote down vote up
def test_delete_type(self):
        """Test CRUD delete when wrong/undefined class is given."""
        object_ = gen_dummy_object(random.choice(
            self.doc_collection_classes), self.doc)
        id_ = str(uuid.uuid4())
        insert_response = crud.insert(
            object_=object_, id_=id_, session=self.session)
        assert isinstance(insert_response, str)
        assert insert_response == id_
        response_code = None
        try:
            delete_response = crud.delete(
                id_=id_, type_="otherClass", session=self.session)
        except Exception as e:
            error = e.get_HTTP()
            response_code = error.code
        assert 400 == response_code 
Example 7
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    MIT License 6 votes vote down vote up
def test_delete_id(self):
        """Test CRUD delete when wrong/undefined ID is given."""
        object_ = gen_dummy_object(random.choice(
            self.doc_collection_classes), self.doc)
        id_ = str(uuid.uuid4())
        insert_response = crud.insert(
            object_=object_, id_=id_, session=self.session)
        response_code = None
        try:
            delete_response = crud.delete(
                id_=999, type_=object_["@type"], session=self.session)
        except Exception as e:
            error = e.get_HTTP()
            response_code = error.code
        assert 404 == response_code
        assert isinstance(insert_response, str)
        assert insert_response == id_ 
Example 8
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    MIT License 6 votes vote down vote up
def test_delete_ids(self):
        objects = list()
        ids = "{},{}".format(str(uuid.uuid4()), str(uuid.uuid4()))
        for index in range(len(ids.split(','))):
            object = gen_dummy_object(random.choice(
                self.doc_collection_classes), self.doc)
            objects.append(object)
        insert_response = crud.insert_multiple(objects_=objects,
                                               session=self.session, id_=ids)
        delete_response = crud.delete_multiple(
            id_=ids, type_=objects[0]["@type"], session=self.session)

        response_code = None
        id_list = ids.split(',')
        try:
            for index in range(len(id_list)):
                get_response = crud.get(
                    id_=id_list[index],
                    type_=objects[index]["@type"],
                    session=self.session,
                    api_name="api")
        except Exception as e:
            error = e.get_HTTP()
            response_code = error.code
        assert 404 == response_code 
Example 9
Project: hydrus   Author: HTTP-APIs   File: test_cli.py    MIT License 6 votes vote down vote up
def gen_dummy_object(class_title, doc):
    """Create a dummy object based on the definitions in the API Doc.
    :param class_title: Title of the class whose object is being created.
    :param doc: ApiDoc.
    :return: A dummy object of class `class_title`.
    """
    object_ = {
        "@type": class_title
    }
    for class_path in doc.parsed_classes:
        if class_title == doc.parsed_classes[class_path]["class"].title:
            for prop in doc.parsed_classes[class_path]["class"].supportedProperty:
                if isinstance(prop.prop, HydraLink) or prop.write is False:
                    continue
                if "vocab:" in prop.prop:
                    prop_class = prop.prop.replace("vocab:", "")
                    object_[prop.title] = gen_dummy_object(prop_class, doc)
                else:
                    object_[prop.title] = ''.join(random.choice(
                        string.ascii_uppercase + string.digits) for _ in range(6))
            return object_ 
Example 10
Project: pyblish-win   Author: pyblish   File: test_email.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_push_random(self):
        from email.feedparser import BufferedSubFile, NeedMoreData

        n = 10000
        chunksize = 5
        chars = 'abcd \t\r\n'

        s = ''.join(choice(chars) for i in range(n)) + '\n'
        target = s.splitlines(True)

        bsf = BufferedSubFile()
        lines = []
        for i in range(0, len(s), chunksize):
            chunk = s[i:i+chunksize]
            bsf.push(chunk)
            lines.extend(iter(bsf.readline, NeedMoreData))
        self.assertEqual(lines, target) 
Example 11
Project: pyblish-win   Author: pyblish   File: test_float.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_roundtrip(self):
        def roundtrip(x):
            return fromHex(toHex(x))

        for x in [NAN, INF, self.MAX, self.MIN, self.MIN-self.TINY, self.TINY, 0.0]:
            self.identical(x, roundtrip(x))
            self.identical(-x, roundtrip(-x))

        # fromHex(toHex(x)) should exactly recover x, for any non-NaN float x.
        import random
        for i in xrange(10000):
            e = random.randrange(-1200, 1200)
            m = random.random()
            s = random.choice([1.0, -1.0])
            try:
                x = s*ldexp(m, e)
            except OverflowError:
                pass
            else:
                self.identical(x, fromHex(toHex(x))) 
Example 12
Project: pyblish-win   Author: pyblish   File: test_dumbdbm.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_random(self):
        import random
        d = {}  # mirror the database
        for dummy in range(5):
            f = dumbdbm.open(_fname)
            for dummy in range(100):
                k = random.choice('abcdefghijklm')
                if random.random() < 0.2:
                    if k in d:
                        del d[k]
                        del f[k]
                else:
                    v = random.choice('abc') * random.randrange(10000)
                    d[k] = v
                    f[k] = v
                    self.assertEqual(f[k], v)
            f.close()

            f = dumbdbm.open(_fname)
            expected = d.items()
            expected.sort()
            got = f.items()
            got.sort()
            self.assertEqual(expected, got)
            f.close() 
Example 13
Project: RelayBot2.0   Author: nukeop   File: joke.py    GNU General Public License v3.0 6 votes vote down vote up
def get_joke(self):
        rows = self.bot.database.select("jokes", "*")
        if len(rows)<1:
            return "No jokes in the database."
        else:
            row = random.choice(rows)

            ratings = [int(x[0]) for x in self.bot.database.select(
                "jokes_ratings",
                "rating",
                "jokeid={}".format(row[0])
            )]

            rating = 0
            if len(ratings) > 0:
                rating = sum(ratings)/float(len(ratings))
            rating = util.rating_to_stars(rating)

            return ("Joke #{} by {} ({}):\n"
            "{}".format(row[0], row[2].encode('utf-8'), rating,
                        row[1].encode('utf-8'))) 
Example 14
Project: auto-base16-theme   Author: makuto   File: AutoBase16Theme.py    MIT License 6 votes vote down vote up
def pickHighContrastBrightColorUniqueOrRandom(base16Colors, currentBase16Color, colorPool):
    viableColors = []
    for color in colorPool:
        if isColorWithinContrastRange(color, base16Colors[BACKGROUND_COLOR_INDEX].color,
                                      minimumTextContrast, maximumTextContrast):
            viableColors.append(color)

    if not viableColors:
        return None

    # Prefer a color which is unique
    bestColor = None
    for color in viableColors:
        if not colorHasBeenUsed(base16Colors, color):
            bestColor = color
            break
        
    return bestColor if bestColor else random.choice(viableColors) 
Example 15
Project: nonogram-solver   Author: mprat   File: solver.py    MIT License 6 votes vote down vote up
def _pick_help_square(self, position=None):
        # randomly pick an element in the filled list
        # add that filled in thing to the puzzle solution
        print("%s squares available" % (
            len(self.filled_positions_hint_eligible)))
        if len(self.filled_positions_hint_eligible) == 0:
            raise ValueError("No more positions available")

        if position is None:
            filled_square = random.choice(self.filled_positions_hint_eligible)
        else:
            filled_square = position

        self.filled_positions_hint_eligible.remove(filled_square)
        self.prefilled_positions.append(filled_square)

        self.puzzle_state[filled_square[0], filled_square[1]] = 1 
Example 16
Project: reroils-data-legacy   Author: rero   File: cli.py    GNU General Public License v2.0 6 votes vote down vote up
def create_random_item(locations_pids, patrons_barcodes, members_pids,
                       missing, verbose=False):
    """Create items with randomised values."""
    item_types = ['standard_loan', 'short_loan', 'on_site_consultation']
    data = {
        '$schema': 'https://ils.test.rero.ch/schema/items/item-v0.0.1.json',
        'barcode': '????',
        'call_number': '????',
        'location_pid': random.choice(locations_pids),
        'item_type': random.choice(item_types)
    }
    item = Item.create(data)

    n = int(item.pid)
    data['barcode'] = str(10000000000 + n)
    data['call_number'] = str(n).zfill(5)
    item.update(data)

    if randint(0, 5) == 0 and missing > 0:
        item.lose_item()
        missing -= 1
    if verbose:
        click.echo(item.id)
    item.update(data)
    return missing, item 
Example 17
Project: google-tech-dev-guide   Author: alvinctk   File: hangman.py    Apache License 2.0 6 votes vote down vote up
def __init__(self, all_secret_word, number_of_guess):

        # To store number of guess allowed for the game
        self.number_of_guess = number_of_guess

        # To used to determine whether to print user's previous guesses
        self.start = number_of_guess

        # To store the final word to be shown
        self.random_word = random.choice(all_secret_word).lower()

        # To store user's previous guesses
        self.user_guess = set()

        # To used in determing which characters are incorrect
        self.fill_in_blank = "_"

        # Build guess word from secret word
        self.guess_word = [self.fill_in_blank] * len(self.random_word)

        # Preprocess the secret word to store the indices for a faster search
        self.secret_word = defaultdict(list)
        for i, character in enumerate(self.random_word):
            self.secret_word[character].append(i) 
Example 18
Project: programsynthesishunting   Author: flexgp   File: agent.py    GNU General Public License v3.0 6 votes vote down vote up
def sense(self, agents):
        # This part makes this GE algorithm useful for multi-agent systems. This method is responsible to sense
        # information from the environment
        # This method would be overridden by actual robots following the different logic for near by agents discovery

        import random

        # Logic that defines how a agent discovers nearby agents
        # If the random value is greater than the interaction probability parameter that denotes 
        # the agent has found some nearby agents. Higher the probability, better the chance of agent to share its 
        # gnome with other agents 
        if random.random() > self.interaction_probability:
            #Turn the flag to True
            self.agents_found = True

            # Getting values to sample agents for interaction
            range_min = int( (self.interaction_probability * len(agents) ) / 3)
            range_max = int( (self.interaction_probability * len(agents) ) / 2)
            range_avg = int( (range_min + range_max) / 2)

            # Sample the agents from the list of agents. The number of samples depend on above values
            no_agents_found = random.sample(range (len(agents) ), random.choice( [range_min,range_max,range_avg] ) )
            
            # Extract the individuals from the nearby agents and store the individuals in the class variable
            self.nearby_agents = [ agents[id].individual[0] for id in no_agents_found ] 
Example 19
Project: programsynthesishunting   Author: flexgp   File: latent_tree.py    GNU General Public License v3.0 6 votes vote down vote up
def latent_tree_crossover(g1, g2):
    """Produce a single child genome by crossover through dict
    manipulation. For each key: if present in both parents, then
    choose value randomly; if present in only one parent, then use
    that. Later, repair must make sure the offspring is valid."""

    # Put all of g1 in, to start with. FIXME The deep_copy() in
    # crossover_inds() ought to guarantee us that g1 and g2 are
    # copies, not original members of the population so we can edit
    # them in-place. However, I'm finding that c = g1 is giving
    # different results from c = g1.copy(). I've checked that
    # deep_copy() is actually running, so I don't understand this
    # problem. To be on the safe side, we'll keep the copy() here.
    # See https://github.com/PonyGE/PonyGE2/issues/89.
    c = g1.copy()   
    for k in g2.keys():
        if k in g1:
            # k is in both parents so choose randomly.
            c[k] = random.choice((g1[k], g2[k]))
        else:
            # for items in g2 only, copy them in
            c[k] = g2[k]
    return c 
Example 20
Project: programsynthesishunting   Author: flexgp   File: latent_tree.py    GNU General Public License v3.0 6 votes vote down vote up
def latent_tree_mutate(g):
    """Produce an offspring genome by mutation through dict
    manipulation. Choose a random key in the dict, and overwrite its
    value with a random int. Later, repair must make sure the
    offspring is valid, including using the mod rule to map from a
    (possibly) large int to the corresponding small one (ie the one
    giving the same production choice) in the range of possible
    choices."""
    
    # FIXME We don't rely on g being a copy, in case the search
    # algorithm sometimes mutates individuals which are original
    # members of the population.
    # See https://github.com/PonyGE/PonyGE2/issues/89.
    g = g.copy()
    k = random.choice(list(g.keys()))
    g[k] = random.randrange(1000000) # there is no true maxint on py 3
    return g 
Example 21
Project: jumpserver-python-sdk   Author: jumpserver   File: models.py    GNU General Public License v2.0 5 votes vote down vote up
def random_ssh_gateway(self):
        return random.choice([g for g in self.gateways if g.protocol == 'ssh']) 
Example 22
Project: tom-bot   Author: maartenberg   File: fortune_plugin.py    MIT License 5 votes vote down vote up
def fortune_cb(bot, *args, **kwargs):
    '''
    Return a random quote from one of the quote files.
    '''
    try:
        source = random.choice(FORTUNE_FILES)
        return fortune.get_random_fortune(source)
    except ValueError as ex:
        LOGGER.error('Fortune failed: %s', ex)
        return _('Be the quote you want to see on a wall.\n -- Error 20XX') 
Example 23
Project: f5go   Author: f5devcentral   File: go.py    MIT License 5 votes vote down vote up
def randomlink():
    return random.choice([x for x in list(g_db.linksById.values()) if not x.isGenerative() and x.usage()]) 
Example 24
Project: f5go   Author: f5devcentral   File: go.py    MIT License 5 votes vote down vote up
def getDefaultLink(self):
        if not self._url or self._url == "list":
            return None
        elif self._url == "top":
            return self.getPopularLinks()[0]
        elif self._url == "random":
            return random.choice(self.links)
        elif self._url == "freshest":
            return self.getRecentLinks()[0]
        else:
            return g_db.getLink(self._url) 
Example 25
Project: f5go   Author: f5devcentral   File: go.py    MIT License 5 votes vote down vote up
def url(self, keyword=None, args=None):
        if not self._url or self._url == "list":
            return None
        elif self._url == "top":
            return self.getPopularLinks()[0].url(keyword, args)
        elif self._url == "random":
            return random.choice(self.links).url(keyword, args)
        elif self._url == "freshest":
            return self.getRecentLinks()[0].url(keyword, args)
        else:  # should be a linkid
            return "/_link_/" + self._url 
Example 26
Project: f5go   Author: f5devcentral   File: go.py    MIT License 5 votes vote down vote up
def lucky(self):
        luckylink = random.choice(g_db.getNonFolders())
        luckylink.clicked()
        return self.redirect(deampify(luckylink.url())) 
Example 27
Project: mlbv   Author: kmac   File: mlbsession.py    GNU General Public License v3.0 5 votes vote down vote up
def gen_random_string(n):
    return ''.join(
        random.choice(
            string.ascii_uppercase + string.digits
        ) for _ in range(n)
    ) 
Example 28
Project: hydrus   Author: HTTP-APIs   File: test_app.py    MIT License 5 votes vote down vote up
def gen_dummy_object(class_title, doc):
    """Create a dummy object based on the definitions in the API Doc.
    :param class_title: Title of the class whose object is being created.
    :param doc: ApiDoc.
    :return: A dummy object of class `class_title`.
    """
    object_ = {
        "@type": class_title
    }
    for class_path in doc.parsed_classes:
        if class_title == doc.parsed_classes[class_path]["class"].title:
            for prop in doc.parsed_classes[class_path]["class"].supportedProperty:
                if isinstance(prop.prop, HydraLink) or prop.write is False:
                    continue
                if "vocab:" in prop.prop:
                    prop_class = prop.prop.replace("vocab:", "")
                    object_[prop.title] = gen_dummy_object(prop_class, doc)
                else:
                    object_[prop.title] = ''.join(random.choice(
                        string.ascii_uppercase + string.digits) for _ in range(6))
            return object_ 
Example 29
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    MIT License 5 votes vote down vote up
def test_insert(self):
        """Test CRUD insert."""
        object_ = gen_dummy_object(random.choice(
            self.doc_collection_classes), self.doc)
        id_ = str(uuid.uuid4())
        response = crud.insert(object_=object_, id_=id_, session=self.session)

        assert isinstance(response, str) 
Example 30
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    MIT License 5 votes vote down vote up
def test_get(self):
        """Test CRUD get."""
        object_ = gen_dummy_object(random.choice(
            self.doc_collection_classes), self.doc)
        id_ = str(uuid.uuid4())
        response = crud.insert(object_=object_, id_=id_, session=self.session)
        object_ = crud.get(id_=id_, type_=object_[
                           "@type"], session=self.session, api_name="api")
        assert isinstance(response, str)
        assert object_["@id"].split("/")[-1] == id_ 
Example 31
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    MIT License 5 votes vote down vote up
def test_get_id(self):
        """Test CRUD get when wrong/undefined ID is given."""
        id_ = str(uuid.uuid4())
        type_ = random.choice(self.doc_collection_classes)
        response_code = None
        try:
            get_response = crud.get(
                id_=id_, type_=type_, session=self.session, api_name="api")
        except Exception as e:
            error = e.get_HTTP()
            response_code = error.code
        assert 404 == response_code 
Example 32
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    MIT License 5 votes vote down vote up
def test_insert_type(self):
        """Test CRUD insert when wrong/undefined class is given."""
        object_ = gen_dummy_object(random.choice(
            self.doc_collection_classes), self.doc)
        id_ = str(uuid.uuid4())
        object_["@type"] = "otherClass"
        response_code = None
        try:
            insert_response = crud.insert(
                object_=object_, id_=id_, session=self.session)
        except Exception as e:
            error = e.get_HTTP()
            response_code = error.code
        assert 400 == response_code 
Example 33
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    MIT License 5 votes vote down vote up
def test_insert_ids(self):
        """Test CRUD insert when multiple ID's are given """
        objects = list()
        ids = "{},{}".format(str(uuid.uuid4()), str(uuid.uuid4()))
        ids_list = ids.split(',')
        for index in range(len(ids_list)):
            object = gen_dummy_object(random.choice(
                self.doc_collection_classes), self.doc)
            objects.append(object)
        insert_response = crud.insert_multiple(
            objects_=objects, session=self.session, id_=ids)
        for id_ in ids_list:
            assert id_ in insert_response 
Example 34
Project: pyblish-win   Author: pyblish   File: test_bisect.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_vsBuiltinSort(self, n=500):
        from random import choice
        for insorted in (list(), UserList()):
            for i in xrange(n):
                digit = choice("0123456789")
                if digit in "02468":
                    f = self.module.insort_left
                else:
                    f = self.module.insort_right
                f(insorted, digit)
            self.assertEqual(sorted(insorted), insorted) 
Example 35
Project: pyblish-win   Author: pyblish   File: test_mutants.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def fill_dict(d, candidates, numentries):
    d.clear()
    for i in xrange(numentries):
        d[Horrid(random.choice(candidates))] = \
            Horrid(random.choice(candidates))
    return d.keys()

# Test one pair of randomly generated dicts, each with n entries.
# Note that dict comparison is trivial if they don't have the same number
# of entires (then the "shorter" dict is instantly considered to be the
# smaller one, without even looking at the entries). 
Example 36
Project: pyblish-win   Author: pyblish   File: test_strtod.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_parsing(self):
        # make '0' more likely to be chosen than other digits
        digits = '000000123456789'
        signs = ('+', '-', '')

        # put together random short valid strings
        # \d*[.\d*]?e
        for i in xrange(1000):
            for j in xrange(TEST_SIZE):
                s = random.choice(signs)
                intpart_len = random.randrange(5)
                s += ''.join(random.choice(digits) for _ in xrange(intpart_len))
                if random.choice([True, False]):
                    s += '.'
                    fracpart_len = random.randrange(5)
                    s += ''.join(random.choice(digits)
                                 for _ in xrange(fracpart_len))
                else:
                    fracpart_len = 0
                if random.choice([True, False]):
                    s += random.choice(['e', 'E'])
                    s += random.choice(signs)
                    exponent_len = random.randrange(1, 4)
                    s += ''.join(random.choice(digits)
                                 for _ in xrange(exponent_len))

                if intpart_len + fracpart_len:
                    self.check_strtod(s)
                else:
                    try:
                        float(s)
                    except ValueError:
                        pass
                    else:
                        assert False, "expected ValueError" 
Example 37
Project: backtrader-cn   Author: pandalibin   File: sina.py    GNU General Public License v3.0 5 votes vote down vote up
def get_random_string(length=8, digits_only=True):
    """
    获取随机字符串长度
    :param length:
    :param digits_only:
    :return:
    """
    random_str = ""
    random_list = string.digits if digits_only else string.ascii_letters + string.digits
    for i in range(length):
        random_str += random.choice(random_list)
    return random_str 
Example 38
Project: python-samples   Author: dek-odoo   File: dek_program076.py    Apache License 2.0 5 votes vote down vote up
def main(limit):
    print random.choice([num for num in range(limit + 1) if num % 2 == 0]) 
Example 39
Project: python-samples   Author: dek-odoo   File: dek_program077.py    Apache License 2.0 5 votes vote down vote up
def main(limit):
    print random.choice([num for num in range(limit + 1)
                         if num % 5 == 0 and num % 7 == 0]) 
Example 40
Project: BASS   Author: Cisco-Talos   File: kamino.py    GNU General Public License v2.0 5 votes vote down vote up
def _translate_db(db, name = None):
    return {
        "name": name if name is not None else ("random_%s" % "".join(random.choice(string.letters + string.digits) for _ in range(32))),
        "architecture": {
            "type": db.architecture_name,
            "size": {32: "b32", 64: "b64"}[db.architecture_bits],
            "endian": {"little": "le", "big": "be"}[db.architecture_endianness],
        },
        "functions": [{
            "name": func.name,
            "id": func.entry_point,
            "call": func.calls,
            "api": func.apis,
            "sea": func.entry_point,
            "see": max(chunk.end for chunk in func.chunks),
            "blocks": [{
                "id": bb.id,
                "sea": bb.start + (1 if bb.thumb else 0),
                "eea": bb.end,
                "name": bb.name,
                "bytes": "".join("%02x" % ord(x) for x in bb.bytes),
                "dat": dict((hd.address, "".join("%02x" % ord(y) for y in db.get_bytes(hd.data_refs[0], hd.data_refs[0] + 8))) \
                        for hd in bb.code_heads if len(hd.data_refs) >= 1 and db.get_bytes(hd.data_refs[0], hd.data_refs[0] + 8) is not None),
                "src": [("0x%X" % hd.address, hd.disassembly.split()[0]) + tuple(op["opnd"] for op in hd.data["operands"]) \
                        for hd in bb.code_heads if hd.mnemonic != ""],
                "call": [succ.id for succ in bb.successors]} for bb in func.basic_blocks],
        } for func in db.functions],
    } 
Example 41
Project: RelayBot2.0   Author: nukeop   File: insult.py    GNU General Public License v3.0 5 votes vote down vote up
def get_insult(self):
        rows = self.bot.database.select("insults", "*")
        if len(rows)<1:
            return "No insults in the database."
        else:
            row = random.choice(rows)

            return row[1] 
Example 42
Project: RelayBot2.0   Author: nukeop   File: nsa.py    GNU General Public License v3.0 5 votes vote down vote up
def get_words(self, num=1):
        return ' '.join([random.choice(self.words).strip() for _ in
                         range(num)]) 
Example 43
Project: RelayBot2.0   Author: nukeop   File: eightball.py    GNU General Public License v3.0 5 votes vote down vote up
def get_answer(self):
        return random.choice(self.answers) 
Example 44
Project: RelayBot2.0   Author: nukeop   File: trivia.py    GNU General Public License v3.0 5 votes vote down vote up
def get_trivia(self):
        rows = self.bot.database.select("trivia", "*")
        if len(rows)<1:
            return "No trivia in the database."
        else:
            row = random.choice(rows)

            return ("User {} shared the following piece of"
                    " trivia:\n\n{}".format(row[2].encode('utf-8'),
                                            row[1].encode('utf-8'))) 
Example 45
Project: earlgrey   Author: icon-project   File: test_multiprocess.py    Apache License 2.0 5 votes vote down vote up
def test_credential_failure(self):
        random_length = random.randrange(5, 10)
        random_string = "".join(random.choice(string.ascii_letters) for _ in range(random_length))

        print(f"username : {random_string}")
        print(f"password : {random_string}")

        server = multiprocessing.Process(target=self._run_server, args=(random_string, random_string))
        server.daemon = True
        server.start()

        client = multiprocessing.Process(target=self._run_client, args=(random_string, random_string))
        client.daemon = True
        client.start()

        server.join()
        client.join()

        self.assertEqual(server.exitcode, 1)
        self.assertEqual(client.exitcode, 1) 
Example 46
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: filters.py    Apache License 2.0 5 votes vote down vote up
def do_random(environment, seq):
    """Return a random item from the sequence."""
    try:
        return choice(seq)
    except IndexError:
        return environment.undefined('No random item, sequence was empty.') 
Example 47
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: filters.py    Apache License 2.0 5 votes vote down vote up
def do_random(environment, seq):
    """Return a random item from the sequence."""
    try:
        return choice(seq)
    except IndexError:
        return environment.undefined('No random item, sequence was empty.') 
Example 48
Project: oeffis-paper   Author: djaffry   File: api_oebb.py    MIT License 5 votes vote down vote up
def _gen_rnd_str(length):
    return ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(length)) 
Example 49
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: timeitDecorator.py    MIT License 5 votes vote down vote up
def long_runner():
    for x in range(3):
        sleep_time = random.choice(range(1,3))
        time.sleep(sleep_time) 
Example 50
Project: auto-base16-theme   Author: makuto   File: AutoBase16Theme.py    MIT License 5 votes vote down vote up
def pickRandomColor(base16Colors, currentBase16Color, colorPool):
    return random.choice(colorPool) 
Example 51
Project: crawler   Author: fst034356   File: download.py    MIT License 5 votes vote down vote up
def get(self, url, timeout, proxy=None, num_retries=6):
        UA = random.choice(self.user_agent_list)
        headers = {'User-Agent': UA}

        if proxy is None:
            try:
                return requests.get(url, headers=headers, timeout=timeout)
            except:
                if num_retries > 0:
                    time.sleep(10)
                    print(u'获取网页出错,10S后将获取倒数第:', num_retries, u'次')
                    num_retries -= 1
                    return self.get(url, timeout, num_retries)
                else:
                    print(u'开始使用代理')
                    time.sleep(10)
                    IP = ''.join(str(random.choice(self.iplist)).strip())
                    proxy = {'http': IP}
                    return self.get(url, timeout, proxy)
        else:
            try:
                IP = ''.join(str(random.choice(self.iplist)).strip())
                print(IP)
                proxy = {'http': IP}
                print(proxy)
                return requests.get(
                    url, headers=headers, proxy=proxy, timeout=timeout)
            except:
                if num_retries > 0:
                    time.sleep(10)

                    IP = ''.join(str(random.choice(self.iplist)).strip())
                    proxy = {'http': IP}

                    print(u'正在更换代理,10S后将重新获取倒数第', num_retries, u'次')
                    print(u'当前代理是:', proxy)
                    return self.get(url, timeout, proxy, num_retries - 1)

                else:
                    print(u'代理不能使用!取消代理')
                    return self.get(url, 3) 
Example 52
Project: GeoLibs-Dator   Author: GeographicaGS   File: carto.py    MIT License 5 votes vote down vote up
def load(self, df, options=None):
        options = options or {}
        max_chunk_rows = options.get('max_chunk_rows', 10000)
        append_mode = bool(self.options['data']['append'])
        table_name = self.options['data']['table']
        table_exists = self._table_exists(table_name)

        # Uploading data to temporary tables
        temp_tables = []
        try:
            tmp_table_count = -1
            tmp_table_basename = f'{table_name}_{"".join(random.choice(string.ascii_lowercase) for i in range(10))}'
            for g, df_chunk in df.groupby(np.arange(len(df)) // max_chunk_rows):
                tmp_table_count = tmp_table_count + 1
                tmp_table_name = f'{tmp_table_basename}_{tmp_table_count}'
                self.context.write(df_chunk, tmp_table_name, overwrite=True)
            temp_tables = [f'{tmp_table_basename}_{n}' for n in range(0, (tmp_table_count+1))]
        except carto.exceptions.CartoException:
            # Clean temporary tables on import errors. i.e: 99999
            #   (https://carto.com/developers/import-api/support/import-errors/):
            temp_tables = [f'{tmp_table_basename}_{n}' for n in range(0, (tmp_table_count))]
            self._delete_temp_tables(temp_tables)
            raise

        if not table_exists:
            # Only create table (df[0:0])
            self.context.write(df[0:0], table_name)
        elif not append_mode:
            self.client.send(f'''DELETE FROM {table_name};''')

        # Insert data into 'table_name' and remove temporary tables
        self._import_from_tmp_tables(temp_tables, table_name)
        self._delete_temp_tables(temp_tables) 
Example 53
Project: auto-check-in   Author: zeekvfu   File: v2ex_copper_coin.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, logger, user_name, password):
        this_func_name = sys._getframe().f_code.co_name

        self.logger = logger
        self.user_name = user_name
        self.password = password

        session = requests.Session()
        session.headers = {
                'User-Agent': random.choice(pc_browser_ua)
                }
        self.session = session

        self.logger.debug("%s(): user_name: %s\tpassword: %s" % (this_func_name, user_name, password))
        self.logger.debug("%s(): start ..." % this_func_name) 
Example 54
Project: auto-check-in   Author: zeekvfu   File: utility.py    GNU General Public License v3.0 5 votes vote down vote up
def get_script_dir():
    return os.path.dirname(os.path.realpath(__file__))


# 从 sequence 中随机获取一个元素
# use `random.choice()` instead 
Example 55
Project: Lexeme   Author: kdelwat   File: Generator.py    MIT License 5 votes vote down vote up
def generateSyllable(categories, rule):
    '''Takes a category dictionary and a rule. Returns a
    generated syllable.
    '''
    syllable = ""
    for place in rule:
        # Choose whether to include optional category
        if place[0] == "[":
            # If the optional category begins with a number (1-9), treat that
            # as the probability of the category being included. Otherwise,
            # default to 50%.

            if isInt(place[1]):
                probability = int(place[1])
                place = place[1:]
            else:
                probability = 2

            if random.randint(1, probability) == 1:
                category = chooseRandomCategory(place)
                if category in categories:
                    syllable += random.choice(categories[category])
                else:
                    syllable += category

        # Include mandatory list
        elif place[0] == "{":
            category = chooseRandomCategory(place)
            if category in categories:
                syllable += random.choice(categories[category])
            else:
                syllable += category

        # Include single category
        else:
            if place in categories:
                syllable += random.choice(categories[place])
            else:
                syllable += place

    return syllable 
Example 56
Project: Lexeme   Author: kdelwat   File: Generator.py    MIT License 5 votes vote down vote up
def chooseRandomCategory(rule):
    rule = rule[1:-1]
    categories = rule.split("/")
    return random.choice(categories) 
Example 57
Project: sklearn2docker   Author: KhaledSharif   File: base_unit_test.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def generate_random_string(k: int):
        from random import choice
        from string import ascii_lowercase, digits
        return ''.join(choice(ascii_lowercase + digits) for _ in range(k)) 
Example 58
Project: bomb3r   Author: iMro0t   File: Provider.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, target, proxy={}, verbose=False, cc='91'):
        try:
            self.config = random.choice(
                json.load(open('config.json', 'r'))['providers'][cc])
        except:
            self.config = random.choice(
                json.load(open('config.json', 'r'))['providers']['multi'])
        self.target = target
        self.headers = self._headers()
        self.done = False
        self.proxy = proxy
        self.verbose = verbose
        self.cc = cc 
Example 59
Project: VisualNN   Author: angelhunt   File: export_prototxt.py    GNU General Public License v3.0 5 votes vote down vote up
def randomword(length):
    return ''.join(random.choice(string.lowercase) for i in range(length)) 
Example 60
Project: VisualNN   Author: angelhunt   File: export_json.py    GNU General Public License v3.0 5 votes vote down vote up
def randomword(length):
    return ''.join(random.choice(string.lowercase) for i in range(length)) 
Example 61
Project: VisualNN   Author: angelhunt   File: export_graphdef.py    GNU General Public License v3.0 5 votes vote down vote up
def randomword(length):
    return ''.join(random.choice(string.lowercase) for i in range(length)) 
Example 62
Project: VisualNN   Author: angelhunt   File: tasks.py    GNU General Public License v3.0 5 votes vote down vote up
def randomword(length):
    return ''.join(random.choice(string.lowercase) for i in range(length)) 
Example 63
Project: reroils-data-legacy   Author: rero   File: cli.py    GNU General Public License v2.0 5 votes vote down vote up
def get_one_member():
    """Find a qualified member."""
    members_pids = Member.get_all_pids()
    return random.choice(members_pids) 
Example 64
Project: schwebedraht   Author: see-base   File: main_test.py    GNU General Public License v3.0 5 votes vote down vote up
def unique_nick():
    vokal = ["a", "e", "i", "o", "u"]
    nick = ( chr(randint(97, 122)).upper()
        + choice(vokal)
        + chr(randint(97, 122))
        + choice(vokal)
        + chr(randint(97, 122))
        + choice(vokal) )

    print("Unique Nick generiert: {}".format(nick))

    return nick

# Füge die Punkte der Highscoreliste hinzu. 
Example 65
Project: sandsifter   Author: Battelle   File: mutator.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def generate_seed():
    b=""

    # prefix
    if random.randint(0,1)==1:
        b+=random.choice(prefixes)

    # opcode
    o = random.randint(1,3)
    if o==1:
        b+=rand_byte()
    elif o==2:
        b+="\x0f"
        b+=rand_byte()
    elif o==3:
        b+="\x0f\x38"
        b+=rand_byte()

    # modr/m
    b+=rand_byte()

    # sib

    # disp
    b+="".join(rand_byte() for _ in range(4))

    # imm
    b+="".join(rand_byte() for _ in range(4))

    return b 
Example 66
Project: fastai_slack   Author: JovianML   File: __init__.py    MIT License 5 votes vote down vote up
def generate_tag():
    """Create a random string to uniquely identify jobs"""
    return ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(6)) 
Example 67
Project: neural-fingerprinting   Author: StephanZheng   File: work_data.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def try_pick_piece_of_work(self, worker_id, submission_id=None):
    """Tries pick next unclaimed piece of work to do.

    Attempt to claim work piece is done using Cloud Datastore transaction, so
    only one worker can claim any work piece at a time.

    Args:
      worker_id: ID of current worker
      submission_id: if not None then this method will try to pick
        piece of work for this submission

    Returns:
      ID of the claimed work piece
    """
    client = self._datastore_client
    unclaimed_work_ids = None
    if submission_id:
      unclaimed_work_ids = [
          k for k, v in iteritems(self.work)
          if is_unclaimed(v) and (v['submission_id'] == submission_id)
      ]
    if not unclaimed_work_ids:
      unclaimed_work_ids = [k for k, v in iteritems(self.work)
                            if is_unclaimed(v)]
    if unclaimed_work_ids:
      next_work_id = random.choice(unclaimed_work_ids)
    else:
      return None
    try:
      with client.transaction() as transaction:
        work_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id,
                              KIND_WORK, next_work_id)
        work_entity = client.get(work_key, transaction=transaction)
        if not is_unclaimed(work_entity):
          return None
        work_entity['claimed_worker_id'] = worker_id
        work_entity['claimed_worker_start_time'] = get_integer_time()
        transaction.put(work_entity)
    except:
      return None
    return next_work_id 
Example 68
Project: ebay-watcher   Author: Snivyn   File: ebay-watcher.py    MIT License 5 votes vote down vote up
def get_proxy(proxy_list):
    '''
    (list) -> dict
    Given a proxy list <proxy_list>, a proxy is selected and returned.
    '''
    # Choose a random proxy
    proxy = random.choice(proxy_list)

    # Split up the proxy
    proxy_parts = proxy.split(':')

    # Set up the proxy to be used
    try:
        proxies = {
            "http": "http://" + proxy_parts[2] + ":" + proxy_parts[3] + "@" +\
            proxy_parts[0] + ":" + proxy_parts[1],
            "https": "https://" + proxy_parts[2] + ":" + proxy_parts[3] + "@" +\
            proxy_parts[0] + ":" + proxy_parts[1]
        }
    except:
        proxies = {
            "http": str(proxy),
            "https": str(proxy)
            }

    # Return the proxy
    return proxies 
Example 69
Project: docker-testnet   Author: l-n-s   File: testnet.py    MIT License 5 votes vote down vote up
def rand_string(length=8):
    """Generate lame random hexdigest string"""
    return "".join([random.choice(string.hexdigits) for _ in range(length)]) 
Example 70
Project: django-feed-reader   Author: xurble   File: utils.py    MIT License 5 votes vote down vote up
def random_user_agent():

    return choice([
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.1 Safari/605.1.15",
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36",
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393",
        "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)",
        "Mozilla/5.0 (iPad; CPU OS 8_4_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12H321 Safari/600.1.4",
        "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1",
        "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
        "Mozilla/5.0 (Linux; Android 5.0; SAMSUNG SM-N900 Build/LRX21V) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/2.1 Chrome/34.0.1847.76 Mobile Safari/537.36",
        "Mozilla/5.0 (Linux; Android 6.0.1; SAMSUNG SM-G570Y Build/MMB29K) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/4.0 Chrome/44.0.2403.133 Mobile Safari/537.36",
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:53.0) Gecko/20100101 Firefox/53.0"
    ]) 
Example 71
Project: python-drawer   Author: jshlbrd   File: ripe-ripper.py    Apache License 2.0 5 votes vote down vote up
def get_user_agent(user_agents):
    return random.choice(user_agents) 
Example 72
Project: python-drawer   Author: jshlbrd   File: ripe-ripper.py    Apache License 2.0 5 votes vote down vote up
def get_referer(referers):
    return random.choice(referers) 
Example 73
Project: programsynthesishunting   Author: flexgp   File: boolean_problem.py    GNU General Public License v3.0 5 votes vote down vote up
def make_random_boolean_fn(n):
    """Make a random Boolean function of n variables."""
    outputs = [random.choice([False, True])
               for i in range(2**n)]
    def f(x):
        return outputs[binlist2int(x)]
    return f



### Helper function 
Example 74
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: filters.py    MIT License 5 votes vote down vote up
def do_random(context, seq):
    """Return a random item from the sequence."""
    try:
        return random.choice(seq)
    except IndexError:
        return context.environment.undefined('No random item, sequence was empty.') 
Example 75
Project: pyblish-win   Author: pyblish   File: test_poll.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def test_poll1(self):
        # Basic functional test of poll object
        # Create a bunch of pipe and test that poll works with them.

        p = select.poll()

        NUM_PIPES = 12
        MSG = " This is a test."
        MSG_LEN = len(MSG)
        readers = []
        writers = []
        r2w = {}
        w2r = {}

        for i in range(NUM_PIPES):
            rd, wr = os.pipe()
            p.register(rd)
            p.modify(rd, select.POLLIN)
            p.register(wr, select.POLLOUT)
            readers.append(rd)
            writers.append(wr)
            r2w[rd] = wr
            w2r[wr] = rd

        bufs = []

        while writers:
            ready = p.poll()
            ready_writers = find_ready_matching(ready, select.POLLOUT)
            if not ready_writers:
                raise RuntimeError, "no pipes ready for writing"
            wr = random.choice(ready_writers)
            os.write(wr, MSG)

            ready = p.poll()
            ready_readers = find_ready_matching(ready, select.POLLIN)
            if not ready_readers:
                raise RuntimeError, "no pipes ready for reading"
            rd = random.choice(ready_readers)
            buf = os.read(rd, MSG_LEN)
            self.assertEqual(len(buf), MSG_LEN)
            bufs.append(buf)
            os.close(r2w[rd]) ; os.close( rd )
            p.unregister( r2w[rd] )
            p.unregister( rd )
            writers.remove(r2w[rd])

        self.assertEqual(bufs, [MSG] * NUM_PIPES) 
Example 76
Project: pyblish-win   Author: pyblish   File: test_itertools.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def test_product(self):
        for args, result in [
            ([], [()]),                     # zero iterables
            (['ab'], [('a',), ('b',)]),     # one iterable
            ([range(2), range(3)], [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2)]),     # two iterables
            ([range(0), range(2), range(3)], []),           # first iterable with zero length
            ([range(2), range(0), range(3)], []),           # middle iterable with zero length
            ([range(2), range(3), range(0)], []),           # last iterable with zero length
            ]:
            self.assertEqual(list(product(*args)), result)
            for r in range(4):
                self.assertEqual(list(product(*(args*r))),
                                 list(product(*args, **dict(repeat=r))))
        self.assertEqual(len(list(product(*[range(7)]*6))), 7**6)
        self.assertRaises(TypeError, product, range(6), None)

        def product1(*args, **kwds):
            pools = map(tuple, args) * kwds.get('repeat', 1)
            n = len(pools)
            if n == 0:
                yield ()
                return
            if any(len(pool) == 0 for pool in pools):
                return
            indices = [0] * n
            yield tuple(pool[i] for pool, i in zip(pools, indices))
            while 1:
                for i in reversed(range(n)):  # right to left
                    if indices[i] == len(pools[i]) - 1:
                        continue
                    indices[i] += 1
                    for j in range(i+1, n):
                        indices[j] = 0
                    yield tuple(pool[i] for pool, i in zip(pools, indices))
                    break
                else:
                    return

        def product2(*args, **kwds):
            'Pure python version used in docs'
            pools = map(tuple, args) * kwds.get('repeat', 1)
            result = [[]]
            for pool in pools:
                result = [x+[y] for x in result for y in pool]
            for prod in result:
                yield tuple(prod)

        argtypes = ['', 'abc', '', xrange(0), xrange(4), dict(a=1, b=2, c=3),
                    set('abcdefg'), range(11), tuple(range(13))]
        for i in range(100):
            args = [random.choice(argtypes) for j in range(random.randrange(5))]
            expected_len = prod(map(len, args))
            self.assertEqual(len(list(product(*args))), expected_len)
            self.assertEqual(list(product(*args)), list(product1(*args)))
            self.assertEqual(list(product(*args)), list(product2(*args)))
            args = map(iter, args)
            self.assertEqual(len(list(product(*args))), expected_len) 
Example 77
Project: earlgrey   Author: icon-project   File: test_basic.py    Apache License 2.0 4 votes vote down vote up
def test_mq_info(self):
        class Task:
            @message_queue_task(type_=MessageQueueType.Worker)
            async def work_async(self):
                pass

            @message_queue_task(type_=MessageQueueType.Worker)
            def work_sync(self):
                pass

        class Stub(MessageQueueStub[Task]):
            TaskType = Task

        class Service(MessageQueueService[Task]):
            TaskType = Task

        async def _run():
            route_key_length = random.randint(5, 10)
            route_key = ''.join(random.choice(string.ascii_letters) for _ in range(route_key_length))

            client = Stub('localhost', route_key)
            await client.connect()

            await client.async_task().work_async()
            client.sync_task().work_sync()
            await asyncio.sleep(1)

            info = await client.async_info().queue_info()
            self.assertEqual(info.declaration_result.message_count, 2)

            info = client.sync_info().queue_info()
            self.assertEqual(info.method.message_count, 2)

            server = Service('localhost', route_key)
            await server.connect()
            await asyncio.sleep(1)

            info = await client.async_info().queue_info()
            self.assertEqual(info.declaration_result.message_count, 0)

            info = client.sync_info().queue_info()
            self.assertEqual(info.method.message_count, 0)

        loop = asyncio.get_event_loop()
        loop.run_until_complete(_run()) 
Example 78
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: utils.py    Apache License 2.0 4 votes vote down vote up
def generate_lorem_ipsum(n=5, html=True, min=20, max=100):
    """Generate some lorem impsum for the template."""
    from jinja2.constants import LOREM_IPSUM_WORDS
    from random import choice, randrange
    words = LOREM_IPSUM_WORDS.split()
    result = []

    for _ in range(n):
        next_capitalized = True
        last_comma = last_fullstop = 0
        word = None
        last = None
        p = []

        # each paragraph contains out of 20 to 100 words.
        for idx, _ in enumerate(range(randrange(min, max))):
            while True:
                word = choice(words)
                if word != last:
                    last = word
                    break
            if next_capitalized:
                word = word.capitalize()
                next_capitalized = False
            # add commas
            if idx - randrange(3, 8) > last_comma:
                last_comma = idx
                last_fullstop += 2
                word += ','
            # add end of sentences
            if idx - randrange(10, 20) > last_fullstop:
                last_comma = last_fullstop = idx
                word += '.'
                next_capitalized = True
            p.append(word)

        # ensure that the paragraph ends with a dot.
        p = u' '.join(p)
        if p.endswith(','):
            p = p[:-1] + '.'
        elif not p.endswith('.'):
            p += '.'
        result.append(p)

    if not html:
        return u'\n\n'.join(result)
    return Markup(u'\n'.join(u'<p>%s</p>' % escape(x) for x in result)) 
Example 79
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: utils.py    Apache License 2.0 4 votes vote down vote up
def generate_lorem_ipsum(n=5, html=True, min=20, max=100):
    """Generate some lorem impsum for the template."""
    from jinja2.constants import LOREM_IPSUM_WORDS
    from random import choice, randrange
    words = LOREM_IPSUM_WORDS.split()
    result = []

    for _ in range(n):
        next_capitalized = True
        last_comma = last_fullstop = 0
        word = None
        last = None
        p = []

        # each paragraph contains out of 20 to 100 words.
        for idx, _ in enumerate(range(randrange(min, max))):
            while True:
                word = choice(words)
                if word != last:
                    last = word
                    break
            if next_capitalized:
                word = word.capitalize()
                next_capitalized = False
            # add commas
            if idx - randrange(3, 8) > last_comma:
                last_comma = idx
                last_fullstop += 2
                word += ','
            # add end of sentences
            if idx - randrange(10, 20) > last_fullstop:
                last_comma = last_fullstop = idx
                word += '.'
                next_capitalized = True
            p.append(word)

        # ensure that the paragraph ends with a dot.
        p = u' '.join(p)
        if p.endswith(','):
            p = p[:-1] + '.'
        elif not p.endswith('.'):
            p += '.'
        result.append(p)

    if not html:
        return u'\n\n'.join(result)
    return Markup(u'\n'.join(u'<p>%s</p>' % escape(x) for x in result)) 
Example 80
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: utils.py    MIT License 4 votes vote down vote up
def generate_lorem_ipsum(n=5, html=True, min=20, max=100):
    """Generate some lorem ipsum for the template."""
    from jinja2.constants import LOREM_IPSUM_WORDS
    from random import choice, randrange
    words = LOREM_IPSUM_WORDS.split()
    result = []

    for _ in range(n):
        next_capitalized = True
        last_comma = last_fullstop = 0
        word = None
        last = None
        p = []

        # each paragraph contains out of 20 to 100 words.
        for idx, _ in enumerate(range(randrange(min, max))):
            while True:
                word = choice(words)
                if word != last:
                    last = word
                    break
            if next_capitalized:
                word = word.capitalize()
                next_capitalized = False
            # add commas
            if idx - randrange(3, 8) > last_comma:
                last_comma = idx
                last_fullstop += 2
                word += ','
            # add end of sentences
            if idx - randrange(10, 20) > last_fullstop:
                last_comma = last_fullstop = idx
                word += '.'
                next_capitalized = True
            p.append(word)

        # ensure that the paragraph ends with a dot.
        p = u' '.join(p)
        if p.endswith(','):
            p = p[:-1] + '.'
        elif not p.endswith('.'):
            p += '.'
        result.append(p)

    if not html:
        return u'\n\n'.join(result)
    return Markup(u'\n'.join(u'<p>%s</p>' % escape(x) for x in result))