Python itertools.cycle() Examples

The following are 30 code examples for showing how to use itertools.cycle(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module itertools , or try the search function .

Example 1
Project: flappybird-qlearning-bot   Author: chncyhn   File: learn.py    License: MIT License 6 votes vote down vote up
def showWelcomeAnimation():
    """Shows welcome screen animation of flappy bird"""
    # index of player to blit on screen
    playerIndexGen = cycle([0, 1, 2, 1])

    playery = int((SCREENHEIGHT - PLAYER[IM_HEIGTH]) / 2)

    basex = 0

    # player shm for up-down motion on welcome screen
    playerShmVals = {"val": 0, "dir": 1}

    return {
        "playery": playery + playerShmVals["val"],
        "basex": basex,
        "playerIndexGen": playerIndexGen,
    } 
Example 2
Project: bricknil   Author: virantha   File: duplo_train.py    License: Apache License 2.0 6 votes vote down vote up
def run(self):
        self.message_info("Running")

        colors = cycle([Color.red, Color.purple, Color.yellow, Color.blue, Color.white])

        snd = DuploSpeaker.sounds
        sounds = cycle([snd.brake, snd.station, snd.water, snd.horn, snd.steam])

        self.message_info('Please move the train to start the program')
        while not self.go:
            await self.led.set_color(next(colors))
            await sleep(0.3)

        for i in range(5):
            await self.led.set_color(next(colors))       # Cycle through the colors
            #await self.speaker.play_sound(next(sounds))  # cycle through the sounds
            tgt_speed = 20 + i*15                        # Keep increasing the speed
            await self.motor.ramp_speed(tgt_speed, 2000)
            self.message_info(f"Set speed to {i}")
            await sleep(3)

        self.message_info("Done") 
Example 3
Project: bricknil   Author: virantha   File: train_all.py    License: Apache License 2.0 6 votes vote down vote up
def run(self):
        self.message_info("Running")
        self.motor_speed = 0
        self.keep_running = True
        self.sensor_change = False
        self.go = False

        # Blink the color  from purple and yellow
        colors = cycle([Color.purple, Color.yellow])
        while not self.go:  # Wait until the hub button is pushed
            await self.train_led.set_color(next(colors))
            await sleep(1)

        colors = cycle([Color.green, Color.orange])
        # Ready to go, let's change the color to green!
        while self.keep_running:
            if self.sensor_change:
                await self.train_led.set_color(next(colors))
                await self.motor.ramp_speed(self.motor_speed, 900)  # Ramp to new speed in 0.9 seconds
                self.sensor_change = False
                await sleep(1)
                await self.train_led.set_color(next(colors))
            else:
                await sleep(1) 
Example 4
Project: recruit   Author: Frank-qlu   File: array.py    License: Apache License 2.0 6 votes vote down vote up
def __setitem__(self, key, value):
        if isinstance(key, numbers.Integral):
            self.data[key] = value
        else:
            if not isinstance(value, (type(self),
                                      compat.Sequence)):
                # broadcast value
                value = itertools.cycle([value])

            if isinstance(key, np.ndarray) and key.dtype == 'bool':
                # masking
                for i, (k, v) in enumerate(zip(key, value)):
                    if k:
                        assert isinstance(v, self.dtype.type)
                        self.data[i] = v
            else:
                for k, v in zip(key, value):
                    assert isinstance(v, self.dtype.type)
                    self.data[k] = v 
Example 5
Project: Pyro5   Author: irmen   File: servers.py    License: MIT License 6 votes vote down vote up
def count(self, lines):
        # use the name server's prefix lookup to get all registered wordcounters
        with locate_ns() as ns:
            all_counters = ns.list(prefix="example.dc2.wordcount.")

        # chop the text into chunks that can be distributed across the workers
        # uses futures so that it runs the counts in parallel
        # counter is selected in a round-robin fashion from list of all available counters
        with futures.ThreadPoolExecutor() as pool:
            roundrobin_counters = cycle(all_counters.values())
            tasks = []
            for chunk in grouper(200, lines):
                tasks.append(pool.submit(self.count_chunk, next(roundrobin_counters), chunk))

            # gather the results
            print("Collecting %d results (counted in parallel)..." % len(tasks))
            totals = Counter()
            for task in futures.as_completed(tasks):
                try:
                    totals.update(task.result())
                except Pyro5.errors.CommunicationError as x:
                    raise Pyro5.errors.PyroError("Something went wrong in the server when collecting the responses: "+str(x))
            return totals 
Example 6
Project: umis   Author: vals   File: umis.py    License: MIT License 6 votes vote down vote up
def read_fastq(filename):
    """
    return a stream of FASTQ entries, handling gzipped and empty files
    """
    if not filename:
        return itertools.cycle((None,))
    if filename == "-":
        filename_fh = sys.stdin
    elif filename.endswith('gz'):
        if is_python3():
            filename_fh = gzip.open(filename, mode='rt')
        else:
            filename_fh = BufferedReader(gzip.open(filename, mode='rt'))
    else:
        filename_fh = open(filename)
    return stream_fastq(filename_fh) 
Example 7
Project: bovespaStockRatings   Author: daniloaleixo   File: waitingbar.py    License: MIT License 6 votes vote down vote up
def start(self, e):
        for index in cycle(range(len(self.MESSAGE))):
            if e.is_set():
                break
            if not self.MESSAGE[index].isalpha():
                continue
            for c in self.CYCLES:
                buff = list(self.MESSAGE)
                buff.append(c)

                try:
                    if sys.stdout.encoding.upper() == 'UTF-8':
                        buff[index] = self.TABLE[buff[index]]
                    else:
                        buff[index] = buff[index].swapcase()
                except KeyError:
                    pass

                sys.stdout.write(''.join(buff))
                time.sleep(0.05)
                sys.stdout.write('\r')
                sys.stdout.flush() 
Example 8
Project: ironpython2   Author: IronLanguages   File: test_io.py    License: Apache License 2.0 6 votes vote down vote up
def test_IOBase_finalize(self):
        # Issue #12149: segmentation fault on _PyIOBase_finalize when both a
        # class which inherits IOBase and an object of this class are caught
        # in a reference cycle and close() is already in the method cache.
        class MyIO(self.IOBase):
            def close(self):
                pass

        # create an instance to populate the method cache
        MyIO()
        obj = MyIO()
        obj.obj = obj
        wr = weakref.ref(obj)
        del MyIO
        del obj
        support.gc_collect()
        self.assertIsNone(wr(), wr) 
Example 9
Project: ironpython2   Author: IronLanguages   File: test_file2k.py    License: Apache License 2.0 6 votes vote down vote up
def _test_close_open_io(self, io_func, nb_workers=5):
        def worker():
            self._create_file()
            funcs = itertools.cycle((
                lambda: io_func(),
                lambda: self._close_and_reopen_file(),
            ))
            for f in funcs:
                if not self.do_continue:
                    break
                try:
                    f()
                except (IOError, ValueError):
                    pass
        self._run_workers(worker, nb_workers)
        if test_support.verbose:
            # Useful verbose statistics when tuning this test to take
            # less time to run but still ensuring that its still useful.
            #
            # the percent of close calls that raised an error
            percent = 100. - 100.*self.close_success_count/self.close_count
            print self.close_count, ('%.4f ' % percent), 
Example 10
Project: BASS   Author: Cisco-Talos   File: bindiff.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, urls):
        """
        >>> client = Client(['http://host-1:4001', 'http://host-2:4001'])
        :param urls: List of addresses of IDA containers including the published port
        """
        if isinstance(urls, str):
            urls = [urls]
        if urls is None or not any(urls):
            raise ValueError('Invalide "urls" value')
        self._urls = itertools.cycle(urls) 
Example 11
Project: BASS   Author: Cisco-Talos   File: bindiff.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, urls):
        """
        >>> client = Client(['http://host-1:4001', 'http://host-2:4001'])
        :param urls: List of addresses of IDA containers including the published port
        """
        if isinstance(urls, str):
            urls = [urls]
        if urls is None or not any(urls):
            raise ValueError('Invalide "urls" value')
        self._urls = itertools.cycle(urls) 
Example 12
Project: twstock   Author: mlouielu   File: proxy.py    License: MIT License 5 votes vote down vote up
def __init__(self, proxies: list):
        self._proxies = proxies
        self._proxies_cycle = cycle(proxies) 
Example 13
Project: twstock   Author: mlouielu   File: proxy.py    License: MIT License 5 votes vote down vote up
def proxies(self, proxies: list):
        if not isinstance(proxies, list):
            raise ValueError('Proxies only accept list')

        self._proxies = proxies
        self._proxies_cycle = cycle(proxies) 
Example 14
Project: img2html   Author: xlzd   File: converter.py    License: Do What The F*ck You Want To Public License 5 votes vote down vote up
def __init__(self,
                 font_size=10,
                 char='䦗',
                 background='#000000',
                 title='img2html by xlzd',
                 font_family='monospace',
                 progress_callback=None):
        self.font_size = font_size
        self.background = background
        self.title = title
        self.font_family = font_family
        if isinstance(char, str):
            char = char.decode('utf-8')
        self.char = cycle(char)
        self._prg_cb = progress_callback or _progress_callback 
Example 15
Project: scanorama   Author: brianhie   File: scanorama.py    License: MIT License 5 votes vote down vote up
def plot_clusters(coords, clusters, s=1, colors=None):
    if coords.shape[0] != clusters.shape[0]:
        sys.stderr.write(
            'Error: mismatch, {} cells, {} labels\n'
            .format(coords.shape[0], clusters.shape[0])
        )
        exit(1)

    if colors is None:
        colors = np.array(
            list(islice(cycle([
                '#377eb8', '#ff7f00', '#4daf4a',
                '#f781bf', '#a65628', '#984ea3',
                '#999999', '#e41a1c', '#dede00',
                '#ffe119', '#e6194b', '#ffbea3',
                '#911eb4', '#46f0f0', '#f032e6',
                '#d2f53c', '#008080', '#e6beff',
                '#aa6e28', '#800000', '#aaffc3',
                '#808000', '#ffd8b1', '#000080',
                '#808080', '#fabebe', '#a3f4ff'
            ]), int(max(clusters) + 1)))
        )

    plt.figure()
    plt.scatter(coords[:, 0], coords[:, 1],
                c=colors[clusters], s=s)

# Put datasets into a single matrix with the intersection of all genes. 
Example 16
Project: hyper-h2   Author: python-hyper   File: coroutine_tests.py    License: MIT License 5 votes vote down vote up
def run_until_complete(self, *coroutines):
        """
        Executes a set of coroutines that communicate between each other. Each
        one is, in order, passed the output of the previous coroutine until
        one is exhausted. If a coroutine does not initially yield data (that
        is, its first action is to receive data), the calling code should prime
        it by using the 'server' decorator on this class.

        Once a coroutine is exhausted, the method performs a final check to
        ensure that all other coroutines are exhausted. This ensures that all
        assertions in those coroutines got executed.
        """
        looping_coroutines = itertools.cycle(coroutines)
        data = None

        for coro in looping_coroutines:
            try:
                data = coro.send(data)
            except StopIteration:
                break

        for coro in coroutines:
            try:
                next(coro)
            except StopIteration:
                continue
            else:
                pytest.fail("Coroutine %s not exhausted" % coro) 
Example 17
Project: razzy-spinner   Author: rafasashi   File: nemo_app.py    License: GNU General Public License v3.0 5 votes vote down vote up
def refresh(self):
        self.colorCycle = itertools.cycle(colors)
        try:
            self.substitute()
            self.img.config(image = self.image)
        except re.error:
            self.img.config(image = self.imageDimmed) 
Example 18
Project: me-ica   Author: ME-ICA   File: _tools.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def stop2(self):
        self.visited.append(4)

#_spinner = itertools.cycle((' /\b\b', ' -\b\b', ' \\\b\b', ' |\b\b')) 
Example 19
Project: FasterRCNN_KERAS   Author: akshaylamba   File: data_generators.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, class_count):
		# ignore classes that have zero samples
		self.classes = [b for b in class_count.keys() if class_count[b] > 0]
		self.class_cycle = itertools.cycle(self.classes)
		self.curr_class = self.class_cycle.next() 
Example 20
Project: brutemap   Author: brutemap-dev   File: progress.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, message, maxval=None):
        self.marker = itertools.cycle(SPINNER_CHARS)
        self.message = message
        self.curval = 0
        self.maxval = maxval or 100
        self._width = 0

        stdoutWrite(message) 
Example 21
Project: bricknil   Author: virantha   File: train_color.py    License: Apache License 2.0 5 votes vote down vote up
def run(self):
        self.message_info("Running")
        self.motor_speed = 0
        self.go = False
        slow = 40
        fast = 70

        # Blink the color  from purple and yellow
        colors = cycle([Color.purple, Color.yellow])
        while not self.go:  # Wait until the hub button is pushed
            await self.train_led.set_color(next(colors))
            await sleep(1)

        colors = cycle([Color.green, Color.orange])
        # Ready to go, let's change the color to green!
        await self.motor.ramp_speed(fast, 2000)
        self.slow = False
        while self.go:
            #speed = randint(30,30)
            #await self.motor.ramp_speed(speed, 2000)
            await self.train_led.set_color(next(colors))
            if self.slow:
                await self.motor.ramp_speed(slow, 2000)
                await self.train_led.set_color(Color.red)
                while self.slow:
                    await sleep(1)
                await self.motor.ramp_speed(fast, 2000)
            await sleep(1) 
Example 22
Project: ratcave   Author: ratcave   File: mesh_warping_demo.py    License: MIT License 5 votes vote down vote up
def animation_sequence(mesh, nframes=50):
    verts_orig = mesh.arrays[0][:, :3].copy()
    verts_normed = (verts_orig.T / np.linalg.norm(verts_orig, axis=1)).T
    norms_orig = mesh.arrays[1][:, :3].copy()
    norms_normed = verts_normed

    for t in itertools.cycle(itertools.chain(np.linspace(0, 1, nframes), np.ones(nframes), np.linspace(0, 1, nframes)[::-1], np.zeros(nframes))):
        vv = lerp(verts_orig, verts_normed, t)
        nn = lerp(norms_orig, norms_normed, t)
        mesh.arrays[0][:, :3] = vv
        mesh.arrays[1][:, :3] = nn
        yield 
Example 23
Project: yolo2-pytorch   Author: ruiminshen   File: visualize.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def __call__(self, image, yx_min, yx_max, cls=None, colors=None, debug=False):
        colors = self.colors if colors is None else [tuple(map(lambda c: c * 255, matplotlib.colors.colorConverter.to_rgb(c)[::-1])) for c in colors]
        if cls is None:
            cls = [None] * len(yx_min)
        for color, (ymin, xmin), (ymax, xmax), cls in zip(itertools.cycle(colors), yx_min, yx_max, cls):
            try:
                cv2.rectangle(image, (xmin, ymin), (xmax, ymax), color, thickness=self.thickness, lineType=self.line_type, shift=self.shift)
                if cls is not None:
                    cv2.putText(image, self.category[cls], (xmin, ymin), self.font_face, self.font_scale, color=color, thickness=self.thickness)
            except OverflowError as e:
                logging.warning(e, (xmin, ymin), (xmax, ymax))
        if debug:
            cv2.imshow('', image)
            cv2.waitKey(0)
        return image 
Example 24
Project: mquery   Author: CERT-Polska   File: yaraparse.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def xor(data: bytes, key: bytes) -> bytes:
    return bytes(x ^ y for x, y in zip(data, itertools.cycle(key))) 
Example 25
Project: AMLSim   Author: IBM   File: transaction_generator.py    License: Apache License 2.0 5 votes vote down vote up
def add_cycle_pattern(self, members, amount, date):
    """Add cycle transactions
    :param members: Transaction members
    :param amount:
    :param date:
    :return:
    """
    num = len(members)
    for i in range(num):
      src = members[i]
      dst = members[(i+1) % num]
      self.add_transaction(src, dst, amount, date) 
Example 26
Project: arches   Author: archesproject   File: activitystream.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self.types = cycle(["create", "tile create", "tile edit", "tile delete", "delete"])
        self.resources = [str(uuid4())]
        self.classids = cycle([str(uuid4()) for x in range(3)])
        self.users = cycle(
            [
                {"userid": 1, "user_username": "admin", "user_firstname": "admin", "user_lastname": "admin"},
                {"userid": 2, "user_username": "benosteen", "user_firstname": "Ben", "user_lastname": "O'Steen"},
                {"userid": 3, "user_username": "rando", "user_firstname": "ran", "user_lastname": "do"},
            ]
        )
        self.gm = GraphModel.objects.get(pk="fd0a5907-e11b-11e8-821b-a4d18cec433a") 
Example 27
Project: recruit   Author: Frank-qlu   File: ui.py    License: Apache License 2.0 5 votes vote down vote up
def next_phase(self):
        if not hasattr(self, "_phaser"):
            self._phaser = itertools.cycle(self.phases)
        return next(self._phaser) 
Example 28
Project: recruit   Author: Frank-qlu   File: ui.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, message, file=None, spin_chars="-\\|/",
                 # Empirically, 8 updates/second looks nice
                 min_update_interval_seconds=0.125):
        self._message = message
        if file is None:
            file = sys.stdout
        self._file = file
        self._rate_limiter = RateLimiter(min_update_interval_seconds)
        self._finished = False

        self._spin_cycle = itertools.cycle(spin_chars)

        self._file.write(" " * get_indentation() + self._message + " ... ")
        self._width = 0 
Example 29
Project: m00dbot   Author: dizballanze   File: tests_quiz_storage.py    License: MIT License 5 votes vote down vote up
def test_get_latest_quiz_completed_madrs(self):
        chat_id = 31337
        self._insert_chat(chat_id, lang='ru')
        quiz_id = self._insert_quiz(chat_id, question_number=10, type_='madrs')
        answers = itertools.cycle(range(0, 7))
        for question_number in range(0, 10):
            self._insert_answer(quiz_id, question_number, next(answers))
        quiz = self.storage.get_latest_quiz(chat_id)
        self.assertIsInstance(quiz, MADRSQuiz)
        self.assertDictEqual(quiz.questions, MADRS_QUESTIONS)
        self.assertEqual(quiz.lang, 'ru')
        self.assertEqual(quiz.question_number, 10)
        self.assertListEqual(quiz.answers, [0, 1, 2, 3, 4, 5, 6, 0, 1, 2])
        self.assertTrue(quiz.is_completed) 
Example 30
Project: airport   Author: cfircohen   File: image_source.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, filenames):
    self.frames = [cv2.imread(f) for f in glob.glob(filenames)]
    assert self.frames, "No image files specifed"
    self.it = itertools.cycle(self.frames)