Python collections.deque() Examples

The following are code examples for showing how to use collections.deque(). 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: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: repr.py    Apache License 2.0 6 votes vote down vote up
def dispatch_repr(self, obj, recursive):
        if obj is helper:
            return u'<span class="help">%r</span>' % helper
        if isinstance(obj, (integer_types, float, complex)):
            return u'<span class="number">%r</span>' % obj
        if isinstance(obj, string_types):
            return self.string_repr(obj)
        if isinstance(obj, RegexType):
            return self.regex_repr(obj)
        if isinstance(obj, list):
            return self.list_repr(obj, recursive)
        if isinstance(obj, tuple):
            return self.tuple_repr(obj, recursive)
        if isinstance(obj, set):
            return self.set_repr(obj, recursive)
        if isinstance(obj, frozenset):
            return self.frozenset_repr(obj, recursive)
        if isinstance(obj, dict):
            return self.dict_repr(obj, recursive)
        if deque is not None and isinstance(obj, deque):
            return self.deque_repr(obj, recursive)
        return self.object_repr(obj) 
Example 2
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: repr.py    Apache License 2.0 6 votes vote down vote up
def dispatch_repr(self, obj, recursive):
        if obj is helper:
            return u'<span class="help">%r</span>' % helper
        if isinstance(obj, (integer_types, float, complex)):
            return u'<span class="number">%r</span>' % obj
        if isinstance(obj, string_types):
            return self.string_repr(obj)
        if isinstance(obj, RegexType):
            return self.regex_repr(obj)
        if isinstance(obj, list):
            return self.list_repr(obj, recursive)
        if isinstance(obj, tuple):
            return self.tuple_repr(obj, recursive)
        if isinstance(obj, set):
            return self.set_repr(obj, recursive)
        if isinstance(obj, frozenset):
            return self.frozenset_repr(obj, recursive)
        if isinstance(obj, dict):
            return self.dict_repr(obj, recursive)
        if deque is not None and isinstance(obj, deque):
            return self.deque_repr(obj, recursive)
        return self.object_repr(obj) 
Example 3
Project: google-tech-dev-guide   Author: alvinctk   File: deserialize_serialize_binary_tree.py    Apache License 2.0 6 votes vote down vote up
def serialize(self, root):
        """Encodes a tree to a single string.

        :type root: TreeNode
        :rtype: str
        """

        array = []
        q = deque()
        q.append(root)

        while q:
            # Breadth First Search to add all child node on this level

            node = q.popleft()
            value = str(node.val) if node else "None"
            array.append(value)
            if node:
                q.append(node.left)
                q.append(node.right)

        return ",".join(array) 
Example 4
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: pyparsing.py    MIT License 6 votes vote down vote up
def __init__(self, size):
                self.not_in_cache = not_in_cache = object()

                cache = {}
                key_fifo = collections.deque([], size)

                def get(self, key):
                    return cache.get(key, not_in_cache)

                def set(self, key, value):
                    cache[key] = value
                    if len(cache) > size:
                        cache.pop(key_fifo.popleft(), None)
                    key_fifo.append(key)

                def clear(self):
                    cache.clear()
                    key_fifo.clear()

                self.get = types.MethodType(get, self)
                self.set = types.MethodType(set, self)
                self.clear = types.MethodType(clear, self)

    # argument cache for optimizing repeated calls when backtracking through recursive expressions 
Example 5
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: util.py    MIT License 6 votes vote down vote up
def add(self, event, subscriber, append=True):
        """
        Add a subscriber for an event.

        :param event: The name of an event.
        :param subscriber: The subscriber to be added (and called when the
                           event is published).
        :param append: Whether to append or prepend the subscriber to an
                       existing subscriber list for the event.
        """
        subs = self._subscribers
        if event not in subs:
            subs[event] = deque([subscriber])
        else:
            sq = subs[event]
            if append:
                sq.append(subscriber)
            else:
                sq.appendleft(subscriber) 
Example 6
Project: flasky   Author: RoseOu   File: util.py    MIT License 6 votes vote down vote up
def unwrap_order_by(clause):
    """Break up an 'order by' expression into individual column-expressions,
    without DESC/ASC/NULLS FIRST/NULLS LAST"""

    cols = util.column_set()
    stack = deque([clause])
    while stack:
        t = stack.popleft()
        if isinstance(t, ColumnElement) and \
            (
                not isinstance(t, UnaryExpression) or
                not operators.is_ordering_modifier(t.modifier)
        ):
            cols.add(t)
        else:
            for c in t.get_children():
                stack.append(c)
    return cols 
Example 7
Project: flasky   Author: RoseOu   File: util.py    MIT License 6 votes vote down vote up
def add(self, event, subscriber, append=True):
        """
        Add a subscriber for an event.

        :param event: The name of an event.
        :param subscriber: The subscriber to be added (and called when the
                           event is published).
        :param append: Whether to append or prepend the subscriber to an
                       existing subscriber list for the event.
        """
        subs = self._subscribers
        if event not in subs:
            subs[event] = deque([subscriber])
        else:
            sq = subs[event]
            if append:
                sq.append(subscriber)
            else:
                sq.appendleft(subscriber) 
Example 8
Project: flasky   Author: RoseOu   File: repr.py    MIT License 6 votes vote down vote up
def dispatch_repr(self, obj, recursive):
        if obj is helper:
            return u'<span class="help">%r</span>' % helper
        if isinstance(obj, (integer_types, float, complex)):
            return u'<span class="number">%r</span>' % obj
        if isinstance(obj, string_types):
            return self.string_repr(obj)
        if isinstance(obj, RegexType):
            return self.regex_repr(obj)
        if isinstance(obj, list):
            return self.list_repr(obj, recursive)
        if isinstance(obj, tuple):
            return self.tuple_repr(obj, recursive)
        if isinstance(obj, set):
            return self.set_repr(obj, recursive)
        if isinstance(obj, frozenset):
            return self.frozenset_repr(obj, recursive)
        if isinstance(obj, dict):
            return self.dict_repr(obj, recursive)
        if deque is not None and isinstance(obj, deque):
            return self.deque_repr(obj, recursive)
        return self.object_repr(obj) 
Example 9
Project: Splunk_CBER_App   Author: MHaggis   File: internals.py    MIT License 6 votes vote down vote up
def _object_hook(dictionary):

        object_view = ObjectView(dictionary)
        stack = deque()
        stack.append((None, None, dictionary))

        while len(stack):
            instance, member_name, dictionary = stack.popleft()

            for name, value in dictionary.iteritems():
                if isinstance(value, dict):
                    stack.append((dictionary, name, value))

            if instance is not None:
                instance[member_name] = ObjectView(dictionary)

        return object_view 
Example 10
Project: cellulario   Author: mayfield   File: iocell.py    MIT License 6 votes vote down vote up
def __init__(self, coord='noop', debug=DEBUG):
        if isinstance(coord, coordination.AbstractCellCoordinator):
            self.coord = coord
        else:
            self.coord = self.make_coord(coord)
        self.debug = debug
        self.output_buffer = collections.deque()
        self.pending_exception = None
        self.closed = False
        self.interrupted = False
        self.tiers = []
        self.tiers_job_map = {}
        self.cleaners = []
        self.finalized = False
        self.init_event_loop()
        self.output_event = asyncio.Event(loop=self.loop) 
Example 11
Project: Gurux.DLMS.Python   Author: Gurux   File: GXXmlReader.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, filename, objects):
        """
        Constructor.
        filename: File name.
        """
        self.tree = ET.parse(filename)
        self.root = self.tree.getroot()
        self.iter = self.tree.iter()
        self.currentElement = None
        self.objects = objects
        dd = deque(self.tree.iter(), maxlen=1)
        self.last_element = dd.pop() 
Example 12
Project: fs_image   Author: facebookincubator   File: inode_id.py    MIT License 5 votes vote down vote up
def tail(n: int, iterable):
    "Return an iterator over the last n items"
    return iter(deque(iterable, maxlen=n))  # tail(3, 'ABCDEFG') --> E F G 
Example 13
Project: pyblish-win   Author: pyblish   File: ast.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def walk(node):
    """
    Recursively yield all descendant nodes in the tree starting at *node*
    (including *node* itself), in no specified order.  This is useful if you
    only want to modify nodes in place and don't care about the context.
    """
    from collections import deque
    todo = deque([node])
    while todo:
        node = todo.popleft()
        todo.extend(iter_child_nodes(node))
        yield node 
Example 14
Project: pyblish-win   Author: pyblish   File: mutex.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self):
        """Create a new mutex -- initially unlocked."""
        self.locked = False
        self.queue = deque() 
Example 15
Project: pyblish-win   Author: pyblish   File: Queue.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _init(self, maxsize):
        self.queue = deque() 
Example 16
Project: pyblish-win   Author: pyblish   File: shlex.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, instream=None, infile=None, posix=False):
        if isinstance(instream, basestring):
            instream = StringIO(instream)
        if instream is not None:
            self.instream = instream
            self.infile = infile
        else:
            self.instream = sys.stdin
            self.infile = None
        self.posix = posix
        if posix:
            self.eof = None
        else:
            self.eof = ''
        self.commenters = '#'
        self.wordchars = ('abcdfeghijklmnopqrstuvwxyz'
                          'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_')
        if self.posix:
            self.wordchars += ('��������������������������������'
                               '������������������������������')
        self.whitespace = ' \t\r\n'
        self.whitespace_split = False
        self.quotes = '\'"'
        self.escape = '\\'
        self.escapedquotes = '"'
        self.state = ' '
        self.pushback = deque()
        self.lineno = 1
        self.debug = 0
        self.token = ''
        self.filestack = deque()
        self.source = None
        if self.debug:
            print 'shlex: reading from %s, line %d' \
                  % (self.instream, self.lineno) 
Example 17
Project: pyblish-win   Author: pyblish   File: test_with.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __enter__(self):
        if self.entered is not None:
            raise RuntimeError("Context is not reentrant")
        self.entered = deque()
        vars = []
        try:
            for mgr in self.managers:
                vars.append(mgr.__enter__())
                self.entered.appendleft(mgr)
        except:
            if not self.__exit__(*sys.exc_info()):
                raise
        return vars 
Example 18
Project: pyblish-win   Author: pyblish   File: test_iterlen.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        d = deque(xrange(n))
        self.it = iter(d)
        self.mutate = d.pop 
Example 19
Project: pyblish-win   Author: pyblish   File: test_iterlen.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        d = deque(xrange(n))
        self.it = reversed(d)
        self.mutate = d.pop 
Example 20
Project: pyblish-win   Author: pyblish   File: queues.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _after_fork(self):
        debug('Queue._after_fork()')
        self._notempty = threading.Condition(threading.Lock())
        self._buffer = collections.deque()
        self._thread = None
        self._jointhread = None
        self._joincancelled = False
        self._closed = False
        self._close = None
        self._send = self._writer.send
        self._recv = self._reader.recv
        self._poll = self._reader.poll 
Example 21
Project: pyblish-win   Author: pyblish   File: pool.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, cache):
        self._cond = threading.Condition(threading.Lock())
        self._job = job_counter.next()
        self._cache = cache
        self._items = collections.deque()
        self._index = 0
        self._length = None
        self._unsorted = {}
        cache[self._job] = self 
Example 22
Project: pyblish-win   Author: pyblish   File: asynchat.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__ (self, list=None):
        if not list:
            self.list = deque()
        else:
            self.list = deque(list) 
Example 23
Project: RF-Monitor   Author: EarToEarOak   File: monitor.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self,
                 colour, enabled, alert,
                 frequency, threshold, dynamic,
                 signals, periods):

        self._colour = colour
        self._enabled = enabled
        self._alert = alert
        self._freq = frequency
        self._threshold = threshold
        self._dynamic = dynamic
        self._noise = None
        self._signals = signals
        self._levels = collections.deque(maxlen=round(LEVELS_LEN))
        self._periods = periods 
Example 24
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: lexer.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, generator, name, filename):
        self._iter = iter(generator)
        self._pushed = deque()
        self.name = name
        self.filename = filename
        self.closed = False
        self.current = Token(1, TOKEN_INITIAL, '')
        next(self) 
Example 25
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: sandbox.py    Apache License 2.0 5 votes vote down vote up
def modifies_known_mutable(obj, attr):
    """This function checks if an attribute on a builtin mutable object
    (list, dict, set or deque) would modify it if called.  It also supports
    the "user"-versions of the objects (`sets.Set`, `UserDict.*` etc.) and
    with Python 2.6 onwards the abstract base classes `MutableSet`,
    `MutableMapping`, and `MutableSequence`.

    >>> modifies_known_mutable({}, "clear")
    True
    >>> modifies_known_mutable({}, "keys")
    False
    >>> modifies_known_mutable([], "append")
    True
    >>> modifies_known_mutable([], "index")
    False

    If called with an unsupported object (such as unicode) `False` is
    returned.

    >>> modifies_known_mutable("foo", "upper")
    False
    """
    for typespec, unsafe in _mutable_spec:
        if isinstance(obj, typespec):
            return attr in unsafe
    return False 
Example 26
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: utils.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, capacity):
        self.capacity = capacity
        self._mapping = {}
        self._queue = deque()
        self._postinit() 
Example 27
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: utils.py    Apache License 2.0 5 votes vote down vote up
def copy(self):
        """Return a shallow copy of the instance."""
        rv = self.__class__(self.capacity)
        rv._mapping.update(self._mapping)
        rv._queue = deque(self._queue)
        return rv 
Example 28
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: nodes.py    Apache License 2.0 5 votes vote down vote up
def set_ctx(self, ctx):
        """Reset the context of a node and all child nodes.  Per default the
        parser will all generate nodes that have a 'load' context as it's the
        most common one.  This method is used in the parser to set assignment
        targets and other nodes to a store context.
        """
        todo = deque([self])
        while todo:
            node = todo.popleft()
            if 'ctx' in node.fields:
                node.ctx = ctx
            todo.extend(node.iter_child_nodes())
        return self 
Example 29
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: nodes.py    Apache License 2.0 5 votes vote down vote up
def set_environment(self, environment):
        """Set the environment for all nodes."""
        todo = deque([self])
        while todo:
            node = todo.popleft()
            node.environment = environment
            todo.extend(node.iter_child_nodes())
        return self 
Example 30
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: lexer.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, generator, name, filename):
        self._iter = iter(generator)
        self._pushed = deque()
        self.name = name
        self.filename = filename
        self.closed = False
        self.current = Token(1, TOKEN_INITIAL, '')
        next(self) 
Example 31
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: sandbox.py    Apache License 2.0 5 votes vote down vote up
def modifies_known_mutable(obj, attr):
    """This function checks if an attribute on a builtin mutable object
    (list, dict, set or deque) would modify it if called.  It also supports
    the "user"-versions of the objects (`sets.Set`, `UserDict.*` etc.) and
    with Python 2.6 onwards the abstract base classes `MutableSet`,
    `MutableMapping`, and `MutableSequence`.

    >>> modifies_known_mutable({}, "clear")
    True
    >>> modifies_known_mutable({}, "keys")
    False
    >>> modifies_known_mutable([], "append")
    True
    >>> modifies_known_mutable([], "index")
    False

    If called with an unsupported object (such as unicode) `False` is
    returned.

    >>> modifies_known_mutable("foo", "upper")
    False
    """
    for typespec, unsafe in _mutable_spec:
        if isinstance(obj, typespec):
            return attr in unsafe
    return False 
Example 32
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: utils.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, capacity):
        self.capacity = capacity
        self._mapping = {}
        self._queue = deque()
        self._postinit() 
Example 33
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: utils.py    Apache License 2.0 5 votes vote down vote up
def copy(self):
        """Return a shallow copy of the instance."""
        rv = self.__class__(self.capacity)
        rv._mapping.update(self._mapping)
        rv._queue = deque(self._queue)
        return rv 
Example 34
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: nodes.py    Apache License 2.0 5 votes vote down vote up
def set_lineno(self, lineno, override=False):
        """Set the line numbers of the node and children."""
        todo = deque([self])
        while todo:
            node = todo.popleft()
            if 'lineno' in node.attributes:
                if node.lineno is None or override:
                    node.lineno = lineno
            todo.extend(node.iter_child_nodes())
        return self 
Example 35
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: nodes.py    Apache License 2.0 5 votes vote down vote up
def set_environment(self, environment):
        """Set the environment for all nodes."""
        todo = deque([self])
        while todo:
            node = todo.popleft()
            node.environment = environment
            todo.extend(node.iter_child_nodes())
        return self 
Example 36
Project: AutoDL   Author: tanguofu   File: app.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, name=None, router=None, error_handler=None,
                 load_env=True, request_class=None,
                 strict_slashes=False, log_config=None,
                 configure_logging=True):

        # Get name from previous stack frame
        if name is None:
            frame_records = stack()[1]
            name = getmodulename(frame_records[1])

        # logging
        if configure_logging:
            logging.config.dictConfig(log_config or LOGGING_CONFIG_DEFAULTS)

        self.name = name
        self.router = router or Router()
        self.request_class = request_class
        self.error_handler = error_handler or ErrorHandler()
        self.config = Config(load_env=load_env)
        self.request_middleware = deque()
        self.response_middleware = deque()
        self.blueprints = {}
        self._blueprint_order = []
        self.configure_logging = configure_logging
        self.debug = None
        self.sock = None
        self.strict_slashes = strict_slashes
        self.listeners = defaultdict(list)
        self.is_running = False
        self.is_request_stream = False
        self.websocket_enabled = False
        self.websocket_tasks = set()

        # Register alternative method names
        self.go_fast = self.run 
Example 37
Project: poupool   Author: lostcontrol   File: sensor.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, maxlen):
        self.__data = collections.deque(maxlen=maxlen) 
Example 38
Project: Lane-And-Vehicle-Detection   Author: JustinHeaton   File: main.py    MIT License 5 votes vote down vote up
def __init__(self, queue_len = 10):
        # Was the line found in the previous frame?
        self.found = False

        # Remember x and y values of lanes in previous frame
        self.X = None
        self.Y = None

        # Store recent x intercepts for averaging across frames
        self.x_int = deque(maxlen=queue_len)
        self.top = deque(maxlen=queue_len)

        # Remember previous x intercept to compare against current one
        self.lastx_int = None
        self.last_top = None

        # Remember radius of curvature
        self.radii = deque(maxlen=queue_len)

        self.recent_fits = deque(maxlen=queue_len)

        # Store recent polynomial coefficients for averaging across frames
        self.fit0 = deque(maxlen=queue_len)
        self.fit1 = deque(maxlen=queue_len)
        self.fit2 = deque(maxlen=queue_len)
        self.fitx = None
        self.pts = []

        # Count the number of frames
        self.count = 0 
Example 39
Project: sandsifter   Author: Battelle   File: sifter.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, ts, injector, tests, do_tick, disassembler=disas_capstone):
        self.ts = ts;
        self.injector = injector
        self.T = tests
        self.gui_thread = None
        self.do_tick = do_tick
        self.ticks = 0

        self.last_ins_count = 0
        self.delta_log = deque(maxlen=self.RATE_Q)
        self.time_log = deque(maxlen=self.RATE_Q)

        self.disas = disassembler

        self.stdscr = curses.initscr()
        curses.start_color()

        # doesn't work
        # self.orig_colors = [curses.color_content(x) for x in xrange(256)]

        curses.use_default_colors()
        curses.noecho()
        curses.cbreak()
        curses.curs_set(0)
        self.stdscr.nodelay(1)

        self.sx = 0
        self.sy = 0

        self.init_colors()

        self.stdscr.bkgd(curses.color_pair(self.WHITE))

        self.last_time = time.time() 
Example 40
Project: google-tech-dev-guide   Author: alvinctk   File: continuous_median.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, greater=None):
        self.array = deque()
        self.greater = greater 
Example 41
Project: google-tech-dev-guide   Author: alvinctk   File: topological_sort.py    Apache License 2.0 5 votes vote down vote up
def topological_sort(self, dependencies):
        """
        Main function to retrieve topological sorted order.

        Returns a valid topological sorted order of vertices if graph
        is a DAG (Directed Acyclic Graph).

        Otherwise, returns an empty list for cyclic graph.
        """
        print("Performing topologicalSort({}))".format(dependencies))
        stack = deque()
        cyclic_stack = deque()
        visited = defaultdict(lambda: False)
        # Call the recursive helper function to store toplogical sort starting
        # from all vertices one by one
        for i in self.vertices:
            if not visited[i]:
                cyclic = self.topological_sort_util(i, visited, stack, cyclic_stack)
                if cyclic:
                    print("topologicalSort({})=[] is cyclic".format(dependencies))
                    return []

        stack = list(stack)
        # Print contents of the stack
        print("topologicalSort({})= {}".format(dependencies, stack))
        print()
        return stack 
Example 42
Project: google-tech-dev-guide   Author: alvinctk   File: river_sizes.py    Apache License 2.0 5 votes vote down vote up
def find_river(i, j, matrix, row, col, visited, sizes):
    q = deque()
    q.append((i, j))
    current_size = 0
    k = 0
    print("find_river: i={} j={}".format(i, j))
    print("q={} seen={} sizes={}".format(q, visited, sizes))
    while q:
        i, j = q.popleft()
        if visited[i][j]:
            continue
        visited[i][j] = True
        if matrix[i][j] == 0:
            continue
        current_size +=1
        print("Before getting nodes: q={} sizes={}".format(q, sizes))
        if i > 0 and not visited[i-1][j]:
            q.append((i-1, j))

        if i < row - 1 and not visited[i+1][j]:
            q.append((i+1, j))

        if j > 0 and not visited[i][j-1]:
            q.append((i, j-1))

        if j < col - 1 and not visited[i][j+1]:
            q.append((i, j+1))

        #get_node_to_vist(q, visited, i, j)
        print("After getting nodes: q={} sizes={}".format(q, sizes))
    if current_size > 0:
        sizes.append(current_size)
    for i in range(len(visited)):
        for j in range(len(visited[i])):
            print(1 if visited[i][j] else 0, end=" ")
        print(end ="\n") 
Example 43
Project: google-tech-dev-guide   Author: alvinctk   File: count_islands.py    Apache License 2.0 5 votes vote down vote up
def add_island(self, q: deque, i: int, j: int, grid: List[List[int]], visited: List[List[bool]]):
        # up
        if i - 1 >= 0 and grid[i-1][j] and not visited[i-1][j]:
            q.append((i-1, j))
        # down
        if i + 1 < len(grid) and grid[i+1][j] and not visited[i+1][j]:
            q.append((i+1, j))
        # right
        if j + 1 < len(grid[0]) and grid[i][j+1] and not visited[i][j+1]:
            q.append((i, j+1))
        # left
        if j - 1 >= 0 and grid[i][j-1] and not visited[i][j-1]:
            q.append((i, j-1)) 
Example 44
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: lexer.py    MIT License 5 votes vote down vote up
def __init__(self, generator, name, filename):
        self._iter = iter(generator)
        self._pushed = deque()
        self.name = name
        self.filename = filename
        self.closed = False
        self.current = Token(1, TOKEN_INITIAL, '')
        next(self) 
Example 45
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: sandbox.py    MIT License 5 votes vote down vote up
def modifies_known_mutable(obj, attr):
    """This function checks if an attribute on a builtin mutable object
    (list, dict, set or deque) would modify it if called.  It also supports
    the "user"-versions of the objects (`sets.Set`, `UserDict.*` etc.) and
    with Python 2.6 onwards the abstract base classes `MutableSet`,
    `MutableMapping`, and `MutableSequence`.

    >>> modifies_known_mutable({}, "clear")
    True
    >>> modifies_known_mutable({}, "keys")
    False
    >>> modifies_known_mutable([], "append")
    True
    >>> modifies_known_mutable([], "index")
    False

    If called with an unsupported object (such as unicode) `False` is
    returned.

    >>> modifies_known_mutable("foo", "upper")
    False
    """
    for typespec, unsafe in _mutable_spec:
        if isinstance(obj, typespec):
            return attr in unsafe
    return False 
Example 46
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: utils.py    MIT License 5 votes vote down vote up
def __init__(self, capacity):
        self.capacity = capacity
        self._mapping = {}
        self._queue = deque()
        self._postinit() 
Example 47
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: utils.py    MIT License 5 votes vote down vote up
def copy(self):
        """Return a shallow copy of the instance."""
        rv = self.__class__(self.capacity)
        rv._mapping.update(self._mapping)
        rv._queue = deque(self._queue)
        return rv 
Example 48
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: nodes.py    MIT License 5 votes vote down vote up
def set_ctx(self, ctx):
        """Reset the context of a node and all child nodes.  Per default the
        parser will all generate nodes that have a 'load' context as it's the
        most common one.  This method is used in the parser to set assignment
        targets and other nodes to a store context.
        """
        todo = deque([self])
        while todo:
            node = todo.popleft()
            if 'ctx' in node.fields:
                node.ctx = ctx
            todo.extend(node.iter_child_nodes())
        return self 
Example 49
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: nodes.py    MIT License 5 votes vote down vote up
def set_environment(self, environment):
        """Set the environment for all nodes."""
        todo = deque([self])
        while todo:
            node = todo.popleft()
            node.environment = environment
            todo.extend(node.iter_child_nodes())
        return self 
Example 50
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: pyparsing.py    MIT License 5 votes vote down vote up
def __init__(self, size):
                self.not_in_cache = not_in_cache = object()

                cache = {}
                key_fifo = collections.deque([], size)

                def get(self, key):
                    return cache.get(key, not_in_cache)

                def set(self, key, value):
                    cache[key] = value
                    while len(key_fifo) > size:
                        cache.pop(key_fifo.popleft(), None)
                    key_fifo.append(key)

                def clear(self):
                    cache.clear()
                    key_fifo.clear()

                def cache_len(self):
                    return len(cache)

                self.get = types.MethodType(get, self)
                self.set = types.MethodType(set, self)
                self.clear = types.MethodType(clear, self)
                self.__len__ = types.MethodType(cache_len, self)

    # argument cache for optimizing repeated calls when backtracking through recursive expressions 
Example 51
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: _tokenizer.py    MIT License 5 votes vote down vote up
def __iter__(self):
        """ This is where the magic happens.

        We do our usually processing through the states and when we have a token
        to return we yield the token which pauses processing until the next token
        is requested.
        """
        self.tokenQueue = deque([])
        # Start processing. When EOF is reached self.state will return False
        # instead of True and the loop will terminate.
        while self.state():
            while self.stream.errors:
                yield {"type": tokenTypes["ParseError"], "data": self.stream.errors.pop(0)}
            while self.tokenQueue:
                yield self.tokenQueue.popleft() 
Example 52
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: bigip_command.py    MIT License 5 votes vote down vote up
def commands(self):
        commands = self._listify(self._values['commands'])
        commands = deque(commands)
        if not is_cli(self.module):
            commands.appendleft(
                'tmsh modify cli preference pager disabled'
            )
        commands = map(self._ensure_tmsh_prefix, list(commands))
        return list(commands) 
Example 53
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: bigip_command.py    MIT License 5 votes vote down vote up
def parse_commands(self, warnings):
        results = []
        commands = list(deque(set(self.want.commands)))
        spec = dict(
            command=dict(key=True),
            output=dict(
                default='text',
                choices=['text', 'one-line']
            ),
        )

        transform = ComplexList(spec, self.module)
        commands = transform(commands)

        for index, item in enumerate(commands):
            if not self._is_valid_mode(item['command']) and is_cli(self.module):
                warnings.append(
                    'Using "write" commands is not idempotent. You should use '
                    'a module that is specifically made for that. If such a '
                    'module does not exist, then please file a bug. The command '
                    'in question is "%s..."' % item['command'][0:40]
                )
            # This needs to be removed so that the ComplexList used in to_commands
            # will work correctly.
            output = item.pop('output', None)

            if output == 'one-line' and 'one-line' not in item['command']:
                item['command'] += ' one-line'
            elif output == 'text' and 'one-line' in item['command']:
                item['command'] = item['command'].replace('one-line', '')

            results.append(item)
        return results 
Example 54
Project: Random-Erasing   Author: zhunzhong07   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.index = 0
        self.start_ts = time()
        self.avg = 0
        self._ts = self.start_ts
        self._xput = deque(maxlen=self.sma_window)
        for key, val in kwargs.items():
            setattr(self, key, val) 
Example 55
Project: flasky   Author: RoseOu   File: result.py    MIT License 5 votes vote down vote up
def __buffer_rows(self):
        size = getattr(self, '_bufsize', 1)
        self.__rowbuffer = collections.deque(self.cursor.fetchmany(size))
        self._bufsize = self.size_growth.get(size, size) 
Example 56
Project: flasky   Author: RoseOu   File: result.py    MIT License 5 votes vote down vote up
def _fetchall_impl(self):
        self.__rowbuffer.extend(self.cursor.fetchall())
        ret = self.__rowbuffer
        self.__rowbuffer = collections.deque()
        return ret 
Example 57
Project: flasky   Author: RoseOu   File: result.py    MIT License 5 votes vote down vote up
def _buffer_rows(self):
        return collections.deque(self.cursor.fetchall()) 
Example 58
Project: flasky   Author: RoseOu   File: result.py    MIT License 5 votes vote down vote up
def _fetchall_impl(self):
        ret = self.__rowbuffer
        self.__rowbuffer = collections.deque()
        return ret 
Example 59
Project: flasky   Author: RoseOu   File: zxjdbc.py    MIT License 5 votes vote down vote up
def _buffer_rows(self):
        return collections.deque([self._returning_row]) 
Example 60
Project: flasky   Author: RoseOu   File: pool.py    MIT License 5 votes vote down vote up
def __init__(self, pool):
        self.__pool = pool
        self.connection = self.__connect()
        self.finalize_callback = deque()

        pool.dispatch.first_connect.\
            for_modify(pool.dispatch).\
            exec_once(self.connection, self)
        pool.dispatch.connect(self.connection, self) 
Example 61
Project: flasky   Author: RoseOu   File: visitors.py    MIT License 5 votes vote down vote up
def iterate(obj, opts):
    """traverse the given expression structure, returning an iterator.

    traversal is configured to be breadth-first.

    """
    stack = deque([obj])
    while stack:
        t = stack.popleft()
        yield t
        for c in t.get_children(**opts):
            stack.append(c) 
Example 62
Project: flasky   Author: RoseOu   File: visitors.py    MIT License 5 votes vote down vote up
def iterate_depthfirst(obj, opts):
    """traverse the given expression structure, returning an iterator.

    traversal is configured to be depth-first.

    """
    stack = deque([obj])
    traversal = deque()
    while stack:
        t = stack.pop()
        traversal.appendleft(t)
        for c in t.get_children(**opts):
            stack.append(c)
    return iter(traversal) 
Example 63
Project: flasky   Author: RoseOu   File: queue.py    MIT License 5 votes vote down vote up
def _init(self, maxsize):
        self.maxsize = maxsize
        self.queue = deque() 
Example 64
Project: flasky   Author: RoseOu   File: mapper.py    MIT License 5 votes vote down vote up
def _acceptable_polymorphic_identities(self):
        identities = set()

        stack = deque([self])
        while stack:
            item = stack.popleft()
            if item.mapped_table is self.mapped_table:
                identities.add(item.polymorphic_identity)
                stack.extend(item._inheriting_mappers)

        return identities 
Example 65
Project: flasky   Author: RoseOu   File: mapper.py    MIT License 5 votes vote down vote up
def self_and_descendants(self):
        """The collection including this mapper and all descendant mappers.

        This includes not just the immediately inheriting mappers but
        all their inheriting mappers as well.

        """
        descendants = []
        stack = deque([self])
        while stack:
            item = stack.popleft()
            descendants.append(item)
            stack.extend(item._inheriting_mappers)
        return util.WeakSequence(descendants) 
Example 66
Project: flasky   Author: RoseOu   File: lexer.py    MIT License 5 votes vote down vote up
def __init__(self, generator, name, filename):
        self._iter = iter(generator)
        self._pushed = deque()
        self.name = name
        self.filename = filename
        self.closed = False
        self.current = Token(1, TOKEN_INITIAL, '')
        next(self) 
Example 67
Project: flasky   Author: RoseOu   File: sandbox.py    MIT License 5 votes vote down vote up
def modifies_known_mutable(obj, attr):
    """This function checks if an attribute on a builtin mutable object
    (list, dict, set or deque) would modify it if called.  It also supports
    the "user"-versions of the objects (`sets.Set`, `UserDict.*` etc.) and
    with Python 2.6 onwards the abstract base classes `MutableSet`,
    `MutableMapping`, and `MutableSequence`.

    >>> modifies_known_mutable({}, "clear")
    True
    >>> modifies_known_mutable({}, "keys")
    False
    >>> modifies_known_mutable([], "append")
    True
    >>> modifies_known_mutable([], "index")
    False

    If called with an unsupported object (such as unicode) `False` is
    returned.

    >>> modifies_known_mutable("foo", "upper")
    False
    """
    for typespec, unsafe in _mutable_spec:
        if isinstance(obj, typespec):
            return attr in unsafe
    return False 
Example 68
Project: flasky   Author: RoseOu   File: utils.py    MIT License 5 votes vote down vote up
def copy(self):
        """Return a shallow copy of the instance."""
        rv = self.__class__(self.capacity)
        rv._mapping.update(self._mapping)
        rv._queue = deque(self._queue)
        return rv 
Example 69
Project: flasky   Author: RoseOu   File: nodes.py    MIT License 5 votes vote down vote up
def set_ctx(self, ctx):
        """Reset the context of a node and all child nodes.  Per default the
        parser will all generate nodes that have a 'load' context as it's the
        most common one.  This method is used in the parser to set assignment
        targets and other nodes to a store context.
        """
        todo = deque([self])
        while todo:
            node = todo.popleft()
            if 'ctx' in node.fields:
                node.ctx = ctx
            todo.extend(node.iter_child_nodes())
        return self 
Example 70
Project: flasky   Author: RoseOu   File: nodes.py    MIT License 5 votes vote down vote up
def set_lineno(self, lineno, override=False):
        """Set the line numbers of the node and children."""
        todo = deque([self])
        while todo:
            node = todo.popleft()
            if 'lineno' in node.attributes:
                if node.lineno is None or override:
                    node.lineno = lineno
            todo.extend(node.iter_child_nodes())
        return self 
Example 71
Project: flasky   Author: RoseOu   File: nodes.py    MIT License 5 votes vote down vote up
def set_environment(self, environment):
        """Set the environment for all nodes."""
        todo = deque([self])
        while todo:
            node = todo.popleft()
            node.environment = environment
            todo.extend(node.iter_child_nodes())
        return self 
Example 72
Project: flasky   Author: RoseOu   File: util.py    MIT License 5 votes vote down vote up
def __init__(self, encoding=None, errors='strict', as_unicode=False):
        self.data = collections.deque()
        self.encoding = encoding
        if as_unicode:
            self.delim = compat.u('')
        else:
            self.delim = ''
        self.as_unicode = as_unicode
        self.errors = errors
        self.write = self.data.append 
Example 73
Project: flasky   Author: RoseOu   File: util.py    MIT License 5 votes vote down vote up
def truncate(self):
        self.data = collections.deque()
        self.write = self.data.append 
Example 74
Project: flasky   Author: RoseOu   File: _ast_util.py    MIT License 5 votes vote down vote up
def walk(node):
    """
    Iterate over all nodes.  This is useful if you only want to modify nodes in
    place and don't care about the context or the order the nodes are returned.
    """
    from collections import deque
    todo = deque([node])
    while todo:
        node = todo.popleft()
        todo.extend(iter_child_nodes(node))
        yield node 
Example 75
Project: flasky   Author: RoseOu   File: tokenizer.py    MIT License 5 votes vote down vote up
def __iter__(self):
        """ This is where the magic happens.

        We do our usually processing through the states and when we have a token
        to return we yield the token which pauses processing until the next token
        is requested.
        """
        self.tokenQueue = deque([])
        # Start processing. When EOF is reached self.state will return False
        # instead of True and the loop will terminate.
        while self.state():
            while self.stream.errors:
                yield {"type": tokenTypes["ParseError"], "data": self.stream.errors.pop(0)}
            while self.tokenQueue:
                yield self.tokenQueue.popleft() 
Example 76
Project: swaggerit   Author: dutradda   File: redis_elsearch.py    MIT License 5 votes vote down vote up
def search(cls, session, pattern, page=0, size=100):
        if cls.__use_elsearch__:
            result = await session.elsearch_bind.search(cls.__key__, pattern, page, size)
            result = result.get('hits', {}).get('hits', [])
            final_result = deque()

            while result:
                final_result.appendleft(result.pop()['_source'])

            return final_result

        else:
            return [] 
Example 77
Project: pyblish-win   Author: pyblish   File: test_io.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def test_threads(self):
        try:
            # Write out many bytes from many threads and test they were
            # all flushed.
            N = 1000
            contents = bytes(range(256)) * N
            sizes = cycle([1, 19])
            n = 0
            queue = deque()
            while n < len(contents):
                size = next(sizes)
                queue.append(contents[n:n+size])
                n += size
            del contents
            # We use a real file object because it allows us to
            # exercise situations where the GIL is released before
            # writing the buffer to the raw streams. This is in addition
            # to concurrency issues due to switching threads in the middle
            # of Python code.
            with self.open(support.TESTFN, self.write_mode, buffering=0) as raw:
                bufio = self.tp(raw, 8)
                errors = []
                def f():
                    try:
                        while True:
                            try:
                                s = queue.popleft()
                            except IndexError:
                                return
                            bufio.write(s)
                    except Exception as e:
                        errors.append(e)
                        raise
                threads = [threading.Thread(target=f) for x in range(20)]
                for t in threads:
                    t.start()
                time.sleep(0.02) # yield
                for t in threads:
                    t.join()
                self.assertFalse(errors,
                    "the following exceptions were caught: %r" % errors)
                bufio.close()
            with self.open(support.TESTFN, "rb") as f:
                s = f.read()
            for i in range(256):
                self.assertEqual(s.count(bytes([i])), N)
        finally:
            support.unlink(support.TESTFN) 
Example 78
Project: VisualNN   Author: angelhunt   File: shapes.py    GNU General Public License v3.0 4 votes vote down vote up
def get_shapes(net):
    queue = deque([])
    dataLayers = ['ImageData', 'Data', 'HDF5Data', 'Input', 'WindowData', 'MemoryData', 'DummyData']
    processedLayer = {}
    layer_indegree = {}

    # Finding the data layer
    for layerId in net:
        processedLayer[layerId] = False
        # store indegree of every layer for Topological sort
        layer_indegree[layerId] = len(net[layerId]['connection']['input'])
        net[layerId]['shape'] = {}
        if (net[layerId]['info']['type'] == 'Python'):
            if ('endPoint' not in net[layerId]['params'].keys()):
                if (not net[layerId]['connection']['input']):
                    raise Exception('Cannot determine shape of Python layer.')
            else:
                if (net[layerId]['params']['endPoint'] == "1, 0"):
                    raise Exception('Cannot determine shape of Python layer.')
        if(net[layerId]['info']['type'] in dataLayers):
            queue.append(layerId)

    while(len(queue)):
        # using deque as stack
        layerId = queue.pop()

        if(net[layerId]['info']['type'] in dataLayers):
            net[layerId]['shape']['input'], net[layerId]['shape']['output'] = get_layer_shape(net[layerId])
        else:
            net[layerId]['shape']['output'] = get_layer_shape(net[layerId])

        for outputId in net[layerId]['connection']['output']:
            if (not processedLayer[outputId]):
                # Handling Concat layer separately
                if (net[outputId]['info']['type'] == "Concat"):
                    net[outputId]['shape']['input'] = handle_concat_layer(net[outputId], net[layerId])
                else:
                    net[outputId]['shape']['input'] = net[layerId]['shape']['output'][:]

                # Decrement indegree of every output node of current layer
                layer_indegree[outputId] -= 1

                if layer_indegree[outputId] == 0:
                    queue.append(outputId)
            else:
                if (net[outputId]['info']['type'] == "Concat"):
                    net[outputId]['shape']['input'] = handle_concat_layer(net[outputId], net[layerId])

        processedLayer[layerId] = True

    return net 
Example 79
Project: google-tech-dev-guide   Author: alvinctk   File: max_sliding_window.py    Apache License 2.0 4 votes vote down vote up
def maxSlidingWindow(self, nums, k):
        dq = deque()
        debug_dq = deque()
        debug = self.print_debug

        result = []

        # initial start window
        for i in range(k):
            self.add_to_dq(dq, debug_dq, nums, i)

        self.add_to_result(dq, nums, result)

        debug = lambda x: self.print_debug(x, dq, debug_dq, result)
        debug("Initial ")
        self.print_debug("")

        n, start, end = len(nums), 1, k
        number_of_iteration = n - k
        for i in range(number_of_iteration):

            debug("Start of loop {}, ".format(i+1))
            self.print_debug("start={}, end={}, window={}".format(start, end, nums[start:end+1]))
            self.remove_elements_out_of_window(dq, debug_dq, start)
            debug("Remove elements out of window: ")

            # deque is in descending order
            self.add_to_dq(dq, debug_dq, nums, end)

            x = "push current element nums[{}]={} into ".format(end, nums[end])
            debug(x)

            # Add result = max number of this sliding window k
            # The max number is the first element
            # Add the sliding window maximum to result
            self.add_to_result(dq, nums, result)
            debug("Add result ")
            self.print_debug("")

            start += 1
            end += 1

        print("nums = {} and k = {}, result={}".format(nums, k, result))
        return result 
Example 80
Project: flasky   Author: RoseOu   File: mapper.py    MIT License 4 votes vote down vote up
def cascade_iterator(self, type_, state, halt_on=None):
        """Iterate each element and its mapper in an object graph,
        for all relationships that meet the given cascade rule.

        :param type_:
          The name of the cascade rule (i.e. save-update, delete,
          etc.)

        :param state:
          The lead InstanceState.  child items will be processed per
          the relationships defined for this object's mapper.

        the return value are object instances; this provides a strong
        reference so that they don't fall out of scope immediately.

        """
        visited_states = set()
        prp, mpp = object(), object()

        visitables = deque([(deque(self._props.values()), prp,
                             state, state.dict)])

        while visitables:
            iterator, item_type, parent_state, parent_dict = visitables[-1]
            if not iterator:
                visitables.pop()
                continue

            if item_type is prp:
                prop = iterator.popleft()
                if type_ not in prop.cascade:
                    continue
                queue = deque(prop.cascade_iterator(
                    type_, parent_state, parent_dict,
                    visited_states, halt_on))
                if queue:
                    visitables.append((queue, mpp, None, None))
            elif item_type is mpp:
                instance, instance_mapper, corresponding_state, \
                    corresponding_dict = iterator.popleft()
                yield instance, instance_mapper, \
                    corresponding_state, corresponding_dict
                visitables.append((deque(instance_mapper._props.values()),
                                   prp, corresponding_state,
                                   corresponding_dict))