Python collections.Set() Examples

The following are 30 code examples of collections.Set(). 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 collections , or try the search function .
Example #1
Source File: mailbox.py    From mochi with MIT License 7 votes vote down vote up
def encode(obj):
    if type(obj) in (list, tuple) or isinstance(obj, PVector):
        return [encode(item) for item in obj]
    if isinstance(obj, Mapping):
        encoded_obj = {}
        for key in obj.keys():
            encoded_obj[encode(key)] = encode(obj[key])
        return encoded_obj
    if isinstance(obj, _native_builtin_types):
        return obj
    if isinstance(obj, Set):
        return ExtType(TYPE_PSET, packb([encode(item) for item in obj], use_bin_type=True))
    if isinstance(obj, PList):
        return ExtType(TYPE_PLIST, packb([encode(item) for item in obj], use_bin_type=True))
    if isinstance(obj, PBag):
        return ExtType(TYPE_PBAG, packb([encode(item) for item in obj], use_bin_type=True))
    if isinstance(obj, types.FunctionType):
        return ExtType(TYPE_FUNC, encode_func(obj))
    if isinstance(obj, Receiver):
        return ExtType(TYPE_MBOX, packb(obj.encode(), use_bin_type=True))
    # assume record
    cls = obj.__class__
    return ExtType(0, packb([cls.__module__, cls.__name__] + [encode(item) for item in obj],
                            use_bin_type=True)) 
Example #2
Source File: cf.py    From stacks with MIT License 6 votes vote down vote up
def traverse_template(obj, obj_path=(), memo=None):
    def iteritems(mapping):
        return getattr(mapping, 'iteritems', mapping.items)()

    if memo is None:
        memo = set()
    iterator = None
    if isinstance(obj, Mapping):
        iterator = iteritems
    elif isinstance(obj, (Sequence, Set)) and not isinstance(obj, (str, bytes)):
        iterator = enumerate
    if iterator:
        if id(obj) not in memo:
            memo.add(id(obj))
            for path_component, value in iterator(obj):
                for result in traverse_template(value, obj_path + (path_component,), memo):
                    yield result
            memo.remove(id(obj))
    else:
        yield obj_path, obj 
Example #3
Source File: test_raw.py    From python-gssapi with ISC License 6 votes vote down vote up
def test_basic_init_default_ctx(self):
        ctx_resp = gb.init_sec_context(self.target_name)
        ctx_resp.shouldnt_be_none()

        (ctx, out_mech_type,
         out_req_flags, out_token, out_ttl, cont_needed) = ctx_resp

        ctx.shouldnt_be_none()
        ctx.should_be_a(gb.SecurityContext)

        out_mech_type.should_be(gb.MechType.kerberos)

        out_req_flags.should_be_a(Set)
        out_req_flags.should_be_at_least_length(2)

        out_token.shouldnt_be_empty()

        out_ttl.should_be_greater_than(0)

        cont_needed.should_be_a(bool)

        gb.delete_sec_context(ctx) 
Example #4
Source File: boltons_utils.py    From hyperparameter_hunter with MIT License 6 votes vote down vote up
def default_exit(path, key, old_parent, new_parent, new_items):
    # print('exit(%r, %r, %r, %r, %r)'
    #       % (path, key, old_parent, new_parent, new_items))
    ret = new_parent
    if isinstance(new_parent, Mapping):
        new_parent.update(new_items)
    elif isinstance(new_parent, Sequence):
        vals = [v for i, v in new_items]
        try:
            new_parent.extend(vals)
        except AttributeError:
            ret = new_parent.__class__(vals)  # tuples
    elif isinstance(new_parent, Set):
        vals = [v for i, v in new_items]
        try:
            new_parent.update(vals)
        except AttributeError:
            ret = new_parent.__class__(vals)  # frozensets
    else:
        raise RuntimeError("unexpected iterable type: %r" % type(new_parent))
    return ret 
Example #5
Source File: search.py    From dateparser with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def detect_language(self, text, languages):
        if isinstance(languages, (list, tuple, Set)):

            if all([language in self.available_language_map for language in languages]):
                languages = [self.available_language_map[language] for language in languages]
            else:
                unsupported_languages = set(languages) - set(self.available_language_map.keys())
                raise ValueError(
                    "Unknown language(s): %s" % ', '.join(map(repr, unsupported_languages)))
        elif languages is not None:
            raise TypeError("languages argument must be a list (%r given)" % type(languages))

        if languages:
            self.language_detector = FullTextLanguageDetector(languages=languages)
        else:
            self.language_detector = FullTextLanguageDetector(list(self.available_language_map.values()))

        return self.language_detector._best_language(text) 
Example #6
Source File: sortedset.py    From SA-ctf_scoreboard with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
def _make_cmp(self, set_op, doc):
        "Make comparator method."
        def comparer(self, that):
            "Compare method for sorted set and set-like object."
            # pylint: disable=protected-access
            if isinstance(that, SortedSet):
                return set_op(self._set, that._set)
            elif isinstance(that, Set):
                return set_op(self._set, that)
            else:
                return NotImplemented

        comparer.__name__ = '__{0}__'.format(set_op.__name__)
        doc_str = 'Return True if and only if Set is {0} `that`.'
        comparer.__doc__ = doc_str.format(doc)

        return comparer 
Example #7
Source File: fields.py    From n6 with GNU Affero General Public License v3.0 6 votes vote down vote up
def _get_main_qualifier_and_additional_info(self, arg_value):
        if (isinstance(arg_value, (collections.Set, collections.Sequence)) and
              not isinstance(arg_value, basestring)):
            # the `in_params`/`in_result` field constructor argument is
            # a set or a sequence (but not a string) -- so we expect that
            # it contains the main qualifier (one of VALID_MAIN_QUALIFIERS)
            # and possibly also other items (which we will isolate and place
            # in the `additional_info` frozenset)
            (main_qualifier,
             additional_info) = self._extract_components(arg_value)
        else:
            # otherwise we expect it to be just the main qualifier or None
            # (as in n6sdk)
            if arg_value is not None and arg_value not in VALID_MAIN_QUALIFIERS:
                raise ValueError(
                    "if not None it should be a valid main qualifier "
                    "(one of: {}) or a set/sequence containing it".format(
                        ', '.join(sorted(map(repr, VALID_MAIN_QUALIFIERS)))))
            main_qualifier = arg_value
            additional_info = frozenset()
        assert main_qualifier is None and not additional_info or (
            main_qualifier in VALID_MAIN_QUALIFIERS and
            not (additional_info & VALID_MAIN_QUALIFIERS))
        return main_qualifier, additional_info 
Example #8
Source File: hetrtransform.py    From ngraph-python with Apache License 2.0 6 votes vote down vote up
def __call__(self, *args, **kwargs):
        """
        Executes child computations in parallel.

        :arg args: list of values to the placeholders specified in __init__ *args

        :return: tuple of return values, one per return specified in __init__ returns list.
        """
        args = self.unpack_args_or_feed_dict(args, kwargs)
        for child in itervalues(self.child_computations):
            child.feed_input([args[i] for i in child.param_idx])

        return_vals = dict()
        for child in itervalues(self.child_computations):
            return_vals.update(child.get_results())

        if isinstance(self.computation_op.returns, Op):
            return return_vals[self.computation_op.returns]
        elif isinstance(self.computation_op.returns, (collections.Sequence, OrderedSet)):
            return tuple(return_vals[op] for op in self.computation_op.returns)
        elif isinstance(self.computation_op.returns, collections.Set):
            return return_vals
        else:
            return None 
Example #9
Source File: _generic_helpers.py    From n6 with GNU Affero General Public License v3.0 6 votes vote down vote up
def assertEqualIncludingTypes(self, first, second, msg=None):
        self.assertEqual(first, second)
        if first is not mock.ANY and second is not mock.ANY:
            self.assertIs(type(first), type(second),
                          'type of {!r} ({}) is not type of {!r} ({})'
                          .format(first, type(first), second, type(second)))
        if isinstance(first, collections.Sequence) and not isinstance(first, basestring):
            for val1, val2 in zip(first, second):
                self.assertEqualIncludingTypes(val1, val2)
        elif isinstance(first, collections.Set):
            for val1, val2 in zip(sorted(first, key=self._safe_sort_key),
                                  sorted(second, key=self._safe_sort_key)):
                self.assertEqualIncludingTypes(val1, val2)
        elif isinstance(first, collections.Mapping):
            for key1, key2 in zip(sorted(first.iterkeys(), key=self._safe_sort_key),
                                  sorted(second.iterkeys(), key=self._safe_sort_key)):
                self.assertEqualIncludingTypes(key1, key2)
            for key in first:
                self.assertEqualIncludingTypes(first[key], second[key]) 
Example #10
Source File: sortedset.py    From pyRevit with GNU General Public License v3.0 6 votes vote down vote up
def _make_cmp(self, set_op, doc):
        "Make comparator method."
        def comparer(self, that):
            "Compare method for sorted set and set-like object."
            # pylint: disable=protected-access
            if isinstance(that, SortedSet):
                return set_op(self._set, that._set)
            elif isinstance(that, Set):
                return set_op(self._set, that)
            else:
                return NotImplemented

        comparer.__name__ = '__{0}__'.format(set_op.__name__)
        doc_str = 'Return True if and only if Set is {0} `that`.'
        comparer.__doc__ = doc_str.format(doc)

        return comparer 
Example #11
Source File: test_dictviews.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_abc_registry(self):
        d = dict(a=1)

        self.assertIsInstance(d.viewkeys(), collections.KeysView)
        self.assertIsInstance(d.viewkeys(), collections.MappingView)
        self.assertIsInstance(d.viewkeys(), collections.Set)
        self.assertIsInstance(d.viewkeys(), collections.Sized)
        self.assertIsInstance(d.viewkeys(), collections.Iterable)
        self.assertIsInstance(d.viewkeys(), collections.Container)

        self.assertIsInstance(d.viewvalues(), collections.ValuesView)
        self.assertIsInstance(d.viewvalues(), collections.MappingView)
        self.assertIsInstance(d.viewvalues(), collections.Sized)

        self.assertIsInstance(d.viewitems(), collections.ItemsView)
        self.assertIsInstance(d.viewitems(), collections.MappingView)
        self.assertIsInstance(d.viewitems(), collections.Set)
        self.assertIsInstance(d.viewitems(), collections.Sized)
        self.assertIsInstance(d.viewitems(), collections.Iterable)
        self.assertIsInstance(d.viewitems(), collections.Container) 
Example #12
Source File: stages.py    From json-spec with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def stage(obj, parent=None, member=None):
    """
    Prepare obj to be staged.

    This is almost used for relative JSON Pointers.
    """
    obj = Staged(obj, parent, member)

    if isinstance(obj, Mapping):
        for key, value in obj.items():
            stage(value, obj, key)
    elif isinstance(obj, Sequence) and not isinstance(obj, string_types):
        for index, value in enumerate(obj):
            stage(value, obj, index)
    elif isinstance(obj, Set):
        for value in obj:
            stage(value, obj, None)

    return obj 
Example #13
Source File: configuration.py    From executing with MIT License 6 votes vote down vote up
def len_shape_watch(source, value):
    try:
        shape = value.shape
    except Exception:
        pass
    else:
        if not inspect.ismethod(shape):
            return '{}.shape'.format(source), shape

    if isinstance(value, QuerySet):
        # Getting the length of a Django queryset evaluates it
        return None

    length = len(value)
    if (
            (isinstance(value, six.string_types)
             and length < 50) or
            (isinstance(value, (Mapping, Set, Sequence))
             and length == 0)
    ):
        return None

    return 'len({})'.format(source), length 
Example #14
Source File: reportviews.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
def __init__(self, viewer, nbunch=None, data=False, default=None):
        self._viewer = viewer
        self._adjdict = viewer._adjdict
        if nbunch is None:
            self._nodes_nbrs = self._adjdict.items
        else:
            nbunch = list(viewer._graph.nbunch_iter(nbunch))
            self._nodes_nbrs = lambda: [(n, self._adjdict[n]) for n in nbunch]
        self._nbunch = nbunch
        self._data = data
        self._default = default
        # Set _report based on data and default
        if data is True:
            self._report = lambda n, nbr, dd: (n, nbr, dd)
        elif data is False:
            self._report = lambda n, nbr, dd: (n, nbr)
        else:  # data is attribute name
            self._report = lambda n, nbr, dd: \
                    (n, nbr, dd[data]) if data in dd else (n, nbr, default) 
Example #15
Source File: recipe-578039.py    From code with MIT License 6 votes vote down vote up
def objview(obj,withValues,path = str()):
    ''' That function will iterate recursivlly accross members of class
        or collections, until all primitives are found '''
    if not len(path): path = type(obj).__name__ 
    iterator = None
    if isinstance(obj, Mapping):
         iterator = iteritems
    else: 
         if isinstance(obj, (Sequence,Set,array.array,deque)) \
            and not isinstance(obj,__string_types__)  and not hasattr(obj,'_asdict'):
            iterator = enumerate
         else: 
            if not type(obj).__name__ in __primitiveTypes__:
               iterator = class__view

    if iterator:
            for path_component, value in iterator(obj):
                valuetype = type(value).__name__ 
                nextpath = path + ('[%s]' % str(path_component)) 
                if (not withValues): yield nextpath, valuetype
                for result in objview(value,withValues,nextpath):               
                    if (withValues or (valuetype not in __primitiveTypes__)):  yield result
    else:
        yield path, obj 
Example #16
Source File: test_collections.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_Set(self):
        for sample in [set, frozenset]:
            self.assertIsInstance(sample(), Set)
            self.assertTrue(issubclass(sample, Set))
        self.validate_abstract_methods(Set, '__contains__', '__iter__', '__len__')
        class MySet(Set):
            def __contains__(self, x):
                return False
            def __len__(self):
                return 0
            def __iter__(self):
                return iter([])
        self.validate_comparison(MySet()) 
Example #17
Source File: test_collections.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def test_Set(self):
        for sample in [set, frozenset]:
            self.assertIsInstance(sample(), Set)
            self.assertTrue(issubclass(sample, Set))
        self.validate_abstract_methods(Set, '__contains__', '__iter__', '__len__')
        class MySet(Set):
            def __contains__(self, x):
                return False
            def __len__(self):
                return 0
            def __iter__(self):
                return iter([])
        self.validate_comparison(MySet()) 
Example #18
Source File: reportviews.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def __getitem__(self, n):
        return self._nodes[n]

    # Set methods 
Example #19
Source File: util.py    From region with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def find_sublist_containing(el, lst, index=False):
    """

    Parameters
    ----------
    el :
        The element to search for in the sublists of `lst`.
    lst : collections.Sequence
        A sequence of sequences or sets.
    index : bool, default: False
        If False (default), the subsequence or subset containing `el` is
        returned.
        If True, the index of the subsequence or subset in `lst` is returned.

    Returns
    -------
    result : collections.Sequence, collections.Set or int
        See the `index` argument for more information.

    Raises
    ------
    exc : LookupError
        If `el` is not in any of the elements of `lst`.

    Examples
    --------
    >>> lst = [{0, 1}, {2}]
    >>> find_sublist_containing(0, lst, index=False) == {0, 1}
    True
    >>> find_sublist_containing(0, lst, index=True) == 0
    True
    >>> find_sublist_containing(2, lst, index=False) == {2}
    True
    >>> find_sublist_containing(2, lst, index=True) == 1
    True
    """
    for idx, sublst in enumerate(lst):
        if el in sublst:
            return idx if index else sublst
    raise LookupError("{} not found in any of the sublists of {}".format(el, lst)) 
Example #20
Source File: test_collections.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def test_hash_Set(self):
        class OneTwoThreeSet(Set):
            def __init__(self):
                self.contents = [1, 2, 3]
            def __contains__(self, x):
                return x in self.contents
            def __len__(self):
                return len(self.contents)
            def __iter__(self):
                return iter(self.contents)
            def __hash__(self):
                return self._hash()
        a, b = OneTwoThreeSet(), OneTwoThreeSet()
        self.assertTrue(hash(a) == hash(b)) 
Example #21
Source File: reportviews.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def __init__(self, viewer, nbunch=None,
                 data=False, keys=False, default=None):
        self._viewer = viewer
        self._adjdict = viewer._adjdict
        self.keys = keys
        if nbunch is None:
            self._nodes_nbrs = self._adjdict.items
        else:
            nbunch = list(viewer._graph.nbunch_iter(nbunch))
            self._nodes_nbrs = lambda: [(n, self._adjdict[n]) for n in nbunch]
        self._nbunch = nbunch
        self._data = data
        self._default = default
        # Set _report based on data and default
        if data is True:
            if keys is True:
                self._report = lambda n, nbr, k, dd: (n, nbr, k, dd)
            else:
                self._report = lambda n, nbr, k, dd: (n, nbr, dd)
        elif data is False:
            if keys is True:
                self._report = lambda n, nbr, k, dd: (n, nbr, k)
            else:
                self._report = lambda n, nbr, k, dd: (n, nbr)
        else:  # data is attribute name
            if keys is True:
                self._report = lambda n, nbr, k, dd: (n, nbr, k, dd[data]) \
                        if data in dd else (n, nbr, k, default)
            else:
                self._report = lambda n, nbr, k, dd: (n, nbr, dd[data]) \
                        if data in dd else (n, nbr, default) 
Example #22
Source File: sorteddict.py    From SA-ctf_scoreboard with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def __setitem__(self, key, value):
        """Set `d[key]` to *value*."""
        if key not in self:
            self._list_add(key)
        self._setitem(key, value) 
Example #23
Source File: test_collections.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_hash_Set(self):
        class OneTwoThreeSet(Set):
            def __init__(self):
                self.contents = [1, 2, 3]
            def __contains__(self, x):
                return x in self.contents
            def __len__(self):
                return len(self.contents)
            def __iter__(self):
                return iter(self.contents)
            def __hash__(self):
                return self._hash()
        a, b = OneTwoThreeSet(), OneTwoThreeSet()
        self.assertTrue(hash(a) == hash(b)) 
Example #24
Source File: meta.py    From Jacinle with MIT License 5 votes vote down vote up
def stmap(func, iterable):
    if isinstance(iterable, six.string_types):
        return func(iterable)
    elif isinstance(iterable, (collections.Sequence, collections.UserList)):
        return [stmap(func, v) for v in iterable]
    elif isinstance(iterable, collections.Set):
        return {stmap(func, v) for v in iterable}
    elif isinstance(iterable, (collections.Mapping, collections.UserDict)):
        return {k: stmap(func, v) for k, v in iterable.items()}
    else:
        return func(iterable) 
Example #25
Source File: types.py    From aws-extender with MIT License 5 votes vote down vote up
def _is_set(self, value):
        if isinstance(value, Set):
            return True
        return False 
Example #26
Source File: sorteddict.py    From pyRevit with GNU General Public License v3.0 5 votes vote down vote up
def __setitem__(self, key, value):
        """Set `d[key]` to *value*."""
        if key not in self:
            self._list_add(key)
        self._setitem(key, value) 
Example #27
Source File: annot_formats.py    From pypath with GNU General Public License v3.0 5 votes vote down vote up
def __init__(
            self,
            members,
            name = None,
            parent = None,
            aspect = 'functional',
            source = 'resource_specific',
            scope = 'specific',
            resource = None,
            transmitter = None,
            receiver = None,
            limit = None,
            avoid = None,
            enabled = True,
        ):

        collections_abc.Set.__init__(self)
        self.members = set(members)
        self.name = name or 'unnamed'
        self.parent = parent or self.name
        self.aspect = aspect
        self.source = source
        self.scope = scope
        self.resource = (
            resource or
            settings.get('annot_composite_database_name') or
            'Unknown'
        )
        self.transmitter = transmitter
        self.receiver = receiver
        self.limit = common.to_set(limit)
        self.avoid = common.to_set(avoid)
        self.enabled = enabled 
Example #28
Source File: sortedset.py    From pyRevit with GNU General Public License v3.0 5 votes vote down vote up
def __reversed__(self):
        """
        Return an iterator over the Set. Elements are iterated in their reverse
        sorted order.

        Iterating the Set while adding or deleting values may raise a
        `RuntimeError` or fail to iterate over all entries.
        """
        return reversed(self._list) 
Example #29
Source File: sortedset.py    From pyRevit with GNU General Public License v3.0 5 votes vote down vote up
def __iter__(self):
        """
        Return an iterator over the Set. Elements are iterated in their sorted
        order.

        Iterating the Set while adding or deleting values may raise a
        `RuntimeError` or fail to iterate over all entries.
        """
        return iter(self._list) 
Example #30
Source File: bird.py    From executing with MIT License 5 votes vote down vote up
def __init__(self, db_uri=None, num_samples=None):
        """
        Set db_uri to specify where the database lives, as an alternative to
        the environment variable BIRDSEYE_DB.
        """
        super(BirdsEye, self).__init__()
        self._db_uri = db_uri
        self._code_infos = {}  # type: Dict[CodeType, CodeInfo]
        self._last_call_id = None
        self._ipython_cell_value = None
        self.num_samples = num_samples or dict(
            big=dict(
                attributes=50,
                dict=50,
                list=30,
                set=30,
                pandas_rows=20,
                pandas_cols=100,
            ),
            small=dict(
                attributes=50,
                dict=10,
                list=6,
                set=6,
                pandas_rows=6,
                pandas_cols=10,
            ),
        )