Python six.moves.filterfalse() Examples

The following are 17 code examples of six.moves.filterfalse(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module six.moves , or try the search function .
Example #1
Source File: msvc.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _unique_everseen(self, iterable, key=None):
        """
        List unique elements, preserving order.
        Remember all elements ever seen.

        _unique_everseen('AAAABBBCCDAABBB') --> A B C D

        _unique_everseen('ABBCcAD', str.lower) --> A B C D
        """
        seen = set()
        seen_add = seen.add
        if key is None:
            for element in filterfalse(seen.__contains__, iterable):
                seen_add(element)
                yield element
        else:
            for element in iterable:
                k = key(element)
                if k not in seen:
                    seen_add(k)
                    yield element 
Example #2
Source File: recipes.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def partition(pred, iterable):
    """
    Returns a 2-tuple of iterables derived from the input iterable.
    The first yields the items that have ``pred(item) == False``.
    The second yields the items that have ``pred(item) == True``.

        >>> is_odd = lambda x: x % 2 != 0
        >>> iterable = range(10)
        >>> even_items, odd_items = partition(is_odd, iterable)
        >>> list(even_items), list(odd_items)
        ([0, 2, 4, 6, 8], [1, 3, 5, 7, 9])

    """
    # partition(is_odd, range(10)) --> 0 2 4 6 8   and  1 3 5 7 9
    t1, t2 = tee(iterable)
    return filterfalse(pred, t1), filter(pred, t2) 
Example #3
Source File: msvc.py    From PhonePi_SampleServer with MIT License 6 votes vote down vote up
def _unique_everseen(self, iterable, key=None):
        """
        List unique elements, preserving order.
        Remember all elements ever seen.

        _unique_everseen('AAAABBBCCDAABBB') --> A B C D

        _unique_everseen('ABBCcAD', str.lower) --> A B C D
        """
        seen = set()
        seen_add = seen.add
        if key is None:
            for element in filterfalse(seen.__contains__, iterable):
                seen_add(element)
                yield element
        else:
            for element in iterable:
                k = key(element)
                if k not in seen:
                    seen_add(k)
                    yield element 
Example #4
Source File: build_py.py    From PhonePi_SampleServer with MIT License 6 votes vote down vote up
def _unique_everseen(iterable, key=None):
    "List unique elements, preserving order. Remember all elements ever seen."
    # unique_everseen('AAAABBBCCDAABBB') --> A B C D
    # unique_everseen('ABBCcAD', str.lower) --> A B C D
    seen = set()
    seen_add = seen.add
    if key is None:
        for element in filterfalse(seen.__contains__, iterable):
            seen_add(element)
            yield element
    else:
        for element in iterable:
            k = key(element)
            if k not in seen:
                seen_add(k)
                yield element 
Example #5
Source File: pip.py    From stash with MIT License 6 votes vote down vote up
def find(cls, where='.', exclude=(), include=('*', )):
        """Return a list all Python packages found within directory 'where'

        'where' should be supplied as a "cross-platform" (i.e. URL-style)
        path; it will be converted to the appropriate local path syntax.
        'exclude' is a sequence of package names to exclude; '*' can be used
        as a wildcard in the names, such that 'foo.*' will exclude all
        subpackages of 'foo' (but not 'foo' itself).

        'include' is a sequence of package names to include.  If it's
        specified, only the named packages will be included.  If it's not
        specified, all found packages will be included.  'include' can contain
        shell style wildcard patterns just like 'exclude'.

        The list of included packages is built up first and then any
        explicitly excluded packages are removed from it.
        """
        out = cls._find_packages_iter(convert_path(where))
        out = cls.require_parents(out)
        includes = cls._build_filter(*include)
        excludes = cls._build_filter('ez_setup', '*__pycache__', *exclude)
        out = filter(includes, out)
        out = filterfalse(excludes, out)
        return list(out) 
Example #6
Source File: recipes.py    From pipenv with MIT License 6 votes vote down vote up
def partition(pred, iterable):
    """
    Returns a 2-tuple of iterables derived from the input iterable.
    The first yields the items that have ``pred(item) == False``.
    The second yields the items that have ``pred(item) == True``.

        >>> is_odd = lambda x: x % 2 != 0
        >>> iterable = range(10)
        >>> even_items, odd_items = partition(is_odd, iterable)
        >>> list(even_items), list(odd_items)
        ([0, 2, 4, 6, 8], [1, 3, 5, 7, 9])

    """
    # partition(is_odd, range(10)) --> 0 2 4 6 8   and  1 3 5 7 9
    t1, t2 = tee(iterable)
    return filterfalse(pred, t1), filter(pred, t2) 
Example #7
Source File: build_py.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _unique_everseen(iterable, key=None):
    "List unique elements, preserving order. Remember all elements ever seen."
    # unique_everseen('AAAABBBCCDAABBB') --> A B C D
    # unique_everseen('ABBCcAD', str.lower) --> A B C D
    seen = set()
    seen_add = seen.add
    if key is None:
        for element in filterfalse(seen.__contains__, iterable):
            seen_add(element)
            yield element
    else:
        for element in iterable:
            k = key(element)
            if k not in seen:
                seen_add(k)
                yield element 
Example #8
Source File: utils.py    From pysaliency with MIT License 5 votes vote down vote up
def __iter__(self):
        if self.cache_location is not None:
            filenames = iglob(self.filename('*'))
            keys = map(lambda f: os.path.splitext(os.path.basename(f))[0], filenames)
            new_keys = filterfalse(lambda key: key in self._cache.keys(), keys)
            return chain(iterkeys(self._cache), new_keys)
        else:
            return iterkeys(self._cache) 
Example #9
Source File: pip.py    From stash with MIT License 5 votes vote down vote up
def _candidate_dirs(base_path):
        """
        Return all dirs in base_path that might be packages.
        """
        has_dot = lambda name: '.' in name
        for root, dirs, files in os.walk(base_path, followlinks=True):
            # Exclude directories that contain a period, as they cannot be
            #  packages. Mutate the list to avoid traversal.
            dirs[:] = filterfalse(has_dot, dirs)
            for dir in dirs:
                yield os.path.relpath(os.path.join(root, dir), base_path) 
Example #10
Source File: utils.py    From dist-dqn with MIT License 5 votes vote down vote up
def partition(pred, iterable):
  """
  Partition the iterable into two disjoint entries based
  on the predicate.

  @return: Tuple (iterable1, iterable2)
  """
  iter1, iter2 = itertools.tee(iterable)
  return filterfalse(pred, iter1), filter(pred, iter2) 
Example #11
Source File: test_six.py    From six with MIT License 5 votes vote down vote up
def test_filter_false():
    from six.moves import filterfalse
    f = filterfalse(lambda x: x % 3, range(10))
    assert six.advance_iterator(f) == 0
    assert six.advance_iterator(f) == 3
    assert six.advance_iterator(f) == 6 
Example #12
Source File: iterables.py    From armi with Apache License 2.0 5 votes vote down vote up
def drop(self, pred):
        """Drop items for which pred(item) evaluates to True.

        Note: returns self so it can be chained with other filters, e.g.,

                newseq = seq.select(...).drop(...).transform(...)
        """
        # self._iter = (i for i in self if not pred(i))
        self._iter = filterfalse(pred, self._iter)
        return self 
Example #13
Source File: test_six.py    From c4ddev with MIT License 5 votes vote down vote up
def test_filter_false():
    from six.moves import filterfalse
    f = filterfalse(lambda x: x % 3, range(10))
    assert six.advance_iterator(f) == 0
    assert six.advance_iterator(f) == 3
    assert six.advance_iterator(f) == 6 
Example #14
Source File: fntools.py    From meza with MIT License 5 votes vote down vote up
def dfilter(content, blacklist=None, inverse=False):
    """ Filters content

    Args:
        content (dict): The content to filter
        blacklist (Seq[str]): The fields to remove (default: None)
        inverse (bool): Keep fields instead of removing them (default: False)

    See also:
        `meza.process.cut`

    Returns:
        dict: The filtered content

    Examples:
        >>> content = {'keep': 'Hello', 'strip': 'World'}
        >>> dfilter(content) == {'keep': 'Hello', 'strip': 'World'}
        True
        >>> dfilter(content, ['strip']) == {'keep': 'Hello'}
        True
        >>> dfilter(content, ['strip'], True) == {'strip': 'World'}
        True
    """
    blackset = set(blacklist or [])
    func = filterfalse if inverse else filter
    return dict(func(lambda x: x[0] not in blackset, content.items())) 
Example #15
Source File: test_six.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def test_filter_false():
    from six.moves import filterfalse
    f = filterfalse(lambda x: x % 3, range(10))
    assert six.advance_iterator(f) == 0
    assert six.advance_iterator(f) == 3
    assert six.advance_iterator(f) == 6 
Example #16
Source File: test_six.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def test_filter_false():
    from six.moves import filterfalse
    f = filterfalse(lambda x: x % 3, range(10))
    assert six.advance_iterator(f) == 0
    assert six.advance_iterator(f) == 3
    assert six.advance_iterator(f) == 6 
Example #17
Source File: convert.py    From meza with MIT License 4 votes vote down vote up
def to_datetime(content, dt_format=None, warn=False):
    """Parses and formats strings into datetimes.

    Args:
        content (str): The string to parse.

        dt_format (str): Date format passed to `strftime()`
            (default: None).

        warn (bool): raise error if content can't be safely converted
            (default: False)

    Returns:
        obj: The datetime object or formatted datetime string.

    See also:
        `meza.process.type_cast`

    Examples:
        >>> fmt = '%Y-%m-%d %H:%M:%S'
        >>> to_datetime('5/4/82 2:00 pm')
        datetime.datetime(1982, 5, 4, 14, 0)
        >>> to_datetime('5/4/82 10:00', fmt) == '1982-05-04 10:00:00'
        True
        >>> to_datetime('2/32/82 12:15', fmt) == '1982-02-28 12:15:00'
        True
        >>> to_datetime('spam')
        datetime.datetime(9999, 12, 31, 0, 0)
        >>> to_datetime('spam', warn=True)
        Traceback (most recent call last):
        ValueError: Invalid datetime value: `spam`.

    Returns:
        datetime
    """
    bad_nums = map(str, range(29, 33))
    good_nums = map(str, range(31, 27, -1))

    try:
        bad_num = next(x for x in bad_nums if x in content)
    except StopIteration:
        options = [content]
    else:
        possibilities = (content.replace(bad_num, x) for x in good_nums)
        options = it.chain([content], possibilities)

    # Fix impossible dates, e.g., 2/31/15
    results = filterfalse(lambda x: x[1], map(_to_datetime, options))
    value = next(results)[0]

    if warn and value == DEFAULT_DATETIME:
        raise ValueError('Invalid datetime value: `{}`.'.format(content))
    else:
        datetime = value.strftime(dt_format) if dt_format else value

    return datetime