Python collections.abc.Collection() Examples

The following are 18 code examples of collections.abc.Collection(). 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.abc , or try the search function .
Example #1
Source File: dataset.py    From satpy with GNU General Public License v3.0 6 votes vote down vote up
def _share_metadata_key(k, values, average_times):
    """Combine metadata. Helper for combine_metadata, decide if key is shared."""
    any_arrays = any([hasattr(val, "__array__") for val in values])
    # in the real world, the `ancillary_variables` attribute may be
    # List[xarray.DataArray], this means our values are now
    # List[List[xarray.DataArray]].
    # note that this list_of_arrays check is also true for any
    # higher-dimensional ndarray, but we only use this check after we have
    # checked any_arrays so this false positive should have no impact
    list_of_arrays = any(
            [isinstance(val, Collection) and len(val) > 0 and
             all([hasattr(subval, "__array__")
                 for subval in val])
             for val in values])
    if any_arrays:
        return _share_metadata_key_array(values)
    elif list_of_arrays:
        return _share_metadata_key_list_arrays(values)
    elif 'time' in k and isinstance(values[0], datetime) and average_times:
        return True
    elif all(val == values[0] for val in values[1:]):
        return True
    return False 
Example #2
Source File: trafficarrays.py    From bluesky with GNU General Public License v3.0 6 votes vote down vote up
def delete(self, idx):
        # Remove element (aircraft) idx from all lists and arrays
        for child in self._children:
            child.delete(idx)

        for v in self._ArrVars:
            self._Vars[v] = np.delete(self._Vars[v], idx)

        if self._LstVars:
            if isinstance(idx, Collection):
                for i in reversed(idx):
                    for v in self._LstVars:
                        del self._Vars[v][i]
            else:
                for v in self._LstVars:
                    del self._Vars[v][idx] 
Example #3
Source File: traffic.py    From bluesky with GNU General Public License v3.0 6 votes vote down vote up
def delete(self, idx):
        """Delete an aircraft"""
        # If this is a multiple delete, sort first for list delete
        # (which will use list in reverse order to avoid index confusion)
        if isinstance(idx, Collection):
            idx = np.sort(idx)

        # Call the actual delete function
        super(Traffic, self).delete(idx)

        # Update conditions list
        self.cond.delac(idx)

        # Update number of aircraft
        self.ntraf = len(self.lat)
        return True 
Example #4
Source File: autopilot.py    From bluesky with GNU General Public License v3.0 6 votes vote down vote up
def selaltcmd(self, idx, alt, vspd=None):
        """ Select altitude command: ALT acid, alt, [vspd] """
        bs.traf.selalt[idx]   = alt
        bs.traf.swvnav[idx]   = False

        # Check for optional VS argument
        if vspd:
            bs.traf.selvs[idx] = vspd
        else:
            if not isinstance(idx, Collection):
                idx = np.array([idx])
            delalt        = alt - bs.traf.alt[idx]
            # Check for VS with opposite sign => use default vs
            # by setting autopilot vs to zero
            oppositevs = np.logical_and(bs.traf.selvs[idx] * delalt < 0., abs(bs.traf.selvs[idx]) > 0.01)

            bs.traf.selvs[idx[oppositevs]] = 0. 
Example #5
Source File: autopilot.py    From bluesky with GNU General Public License v3.0 5 votes vote down vote up
def setLNAV(self, idx, flag=None):
        """ Set LNAV on or off for specific or for all aircraft """
        if not isinstance(idx, Collection):
            if idx is None:
                # All aircraft are targeted
                bs.traf.swlnav = np.array(bs.traf.ntraf * [flag])
            else:
                # Prepare for the loop
                idx = np.array([idx])

        # Set LNAV for all aircraft in idx array
        output = []
        for i in idx:
            if flag is None:
                output.append(bs.traf.id[i] + ": LNAV is " + ("ON" if bs.traf.swlnav[i] else "OFF"))

            elif flag:
                route = self.route[i]
                if route.nwp <= 0:
                    return False, ("LNAV " + bs.traf.id[i] + ": no waypoints or destination specified")
                elif not bs.traf.swlnav[i]:
                   bs.traf.swlnav[i] = True
                   route.direct(i, route.wpname[route.findact(i)])
            else:
                bs.traf.swlnav[i] = False
        if flag == None:
            return True, '\n'.join(output) 
Example #6
Source File: model.py    From pandaSDMX with Apache License 2.0 5 votes vote down vote up
def __init__(self, value=None, **kwargs):
        super().__init__()

        # Handle initial values according to type
        if isinstance(value, str):
            # Bare string
            value = {DEFAULT_LOCALE: value}
        elif (isinstance(value, Collection) and len(value) == 2
              and isinstance(value[0], str)):
            # 2-tuple of str is (locale, label)
            value = {value[0]: value[1]}
        elif isinstance(value, IterableABC):
            # Iterable of 2-tuples
            value = {locale: label for (locale, label) in value}
        elif value is None:
            # Keyword arguments → dict, possibly empty
            value = dict(kwargs)
        elif isinstance(value, dict):
            # dict; use directly
            pass
        else:
            raise ValueError(value, kwargs)

        self.localizations = value

    # Convenience access 
Example #7
Source File: encoder.py    From pvl with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def encode_setseq(self, values: abc.Collection) -> str:
        """This function provides shared functionality for
        encode_sequence() and encode_set().
        """
        return ', '.join([self.encode_value(v) for v in values]) 
Example #8
Source File: metrics.py    From bluesky with GNU General Public License v3.0 5 votes vote down vote up
def delete(self, idx):
        self.delac.extend(np.array(traf.id)[idx], traf.lat[idx], traf.lon[idx], traf.distflown[idx])
        # n = len(idx) if isinstance(idx, Collection) else 1
        # print(n, 'aircraft deleted, ntraf =', traf.ntraf, 'idx =', idx, 'len(traf.lat) =', len(traf.lat)) 
Example #9
Source File: varexplorer.py    From bluesky with GNU General Public License v3.0 5 votes vote down vote up
def is_num(self):
        ''' py3 replacement of operator.isNumberType.'''
        v = getattr(self.parent, self.varname)
        return isinstance(v, Number) or \
            (isinstance(v, np.ndarray) and v.dtype.kind not in 'OSUV') or \
            (isinstance(v, Collection) and self.index and
             all([isinstance(v[i], Number) for i in self.index])) 
Example #10
Source File: varexplorer.py    From bluesky with GNU General Public License v3.0 5 votes vote down vote up
def lsvar(varname=''):
    ''' Stack function to list information on simulation variables in the
        BlueSky console. '''
    if not varname:
        # When no argument is passed, show a list of parent objects for which
        # variables can be accessed
        return True, '\n' + \
            str.join(', ', [key for key in varlist])

    # Find the variable in the variable list
    v = findvar(varname)
    if v:
        thevar = v.get()  # reference to the actual variable
        # When the variable is an object, get child attributes
        attrs = getvarsfromobj(thevar)
        vartype = v.get_type()  # Type of the variable
        if isinstance(v.parent, TrafficArrays) and v.parent.istrafarray(v.varname):
            vartype += ' (TrafficArray)'
        txt = \
            'Variable:   {}\n'.format(v.varname) + \
            'Type:       {}\n'.format(vartype)
        if isinstance(thevar, Collection):
            txt += 'Size:       {}\n'.format(len(thevar))
        txt += 'Parent:     {}'.format(v.parentname)
        if attrs:
            txt += '\nAttributes: ' + str.join(', ', attrs) + '\n'
        return True, '\n' + txt
    return False, 'Variable {} not found'.format(varname) 
Example #11
Source File: autopilot.py    From bluesky with GNU General Public License v3.0 5 votes vote down vote up
def setVNAV(self, idx, flag=None):
        """ Set VNAV on or off for specific or for all aircraft """
        if not isinstance(idx, Collection):
            if idx is None:
                # All aircraft are targeted
                bs.traf.swvnav    = np.array(bs.traf.ntraf * [flag])
                bs.traf.swvnavspd = np.array(bs.traf.ntraf * [flag])
            else:
                # Prepare for the loop                
                idx = np.array([idx])

        # Set VNAV for all aircraft in idx array
        output = []
        for i in idx:
            if flag is None:
                msg = bs.traf.id[i] + ": VNAV is " + "ON" if bs.traf.swvnav[i] else "OFF"
                if not bs.traf.swvnavspd[i]:
                    msg += " but VNAVSPD is OFF"
                output.append(bs.traf.id[i] + ": VNAV is " + "ON" if bs.traf.swvnav[i] else "OFF")

            elif flag:
                if not bs.traf.swlnav[i]:
                    return False, (bs.traf.id[i] + ": VNAV ON requires LNAV to be ON")

                route = self.route[i]
                if route.nwp > 0:
                    bs.traf.swvnav[i]    = True
                    bs.traf.swvnavspd[i] = True
                    self.route[i].calcfp()
                    actwpidx = self.route[i].iactwp
                    self.ComputeVNAV(i,self.route[i].wptoalt[actwpidx],self.route[i].wpxtoalt[actwpidx],\
                                     self.route[i].wptorta[actwpidx],self.route[i].wpxtorta[actwpidx])
                    bs.traf.actwp.nextaltco[i] = self.route[i].wptoalt[actwpidx]

                else:
                    return False, ("VNAV " + bs.traf.id[i] + ": no waypoints or destination specified")
            else:
                bs.traf.swvnav[i]    = False
                bs.traf.swvnavspd[i] = False
        if flag == None:
            return True, '\n'.join(output) 
Example #12
Source File: tfontConverter.py    From tfont with Apache License 2.0 5 votes vote down vote up
def unstructure_attrs_asdict(self, obj):
        cls = obj.__class__
        attrs = cls.__attrs_attrs__
        dispatch = self._unstructure_func.dispatch
        # add version stamp
        if cls is Font:
            rv = {".formatVersion": self.version}
        else:
            rv = {}
        override = cls is Font or cls is Layer
        for a in attrs:
            # skip internal attrs
            if not a.init:
                continue
            name = a.name
            v = getattr(obj, name)
            if not v:
                # skip attrs that have trivial default values set
                if v == a.default:
                    continue
                # skip empty collections
                if isinstance(v, Collection):
                    continue
            # force our specialized types overrides
            type_ = v.__class__
            if override:
                t = a.type
                try:
                    if issubclass(t.__origin__, dict) and t.__args__[0] is str:
                        type_ = t
                except (AttributeError, TypeError):
                    pass
            # remove underscore from private attrs
            if name[0] == "_":
                name = name[1:]
            rv[name] = dispatch(type_)(v)
        return rv 
Example #13
Source File: autopilot.py    From bluesky with GNU General Public License v3.0 5 votes vote down vote up
def selhdgcmd(self, idx, hdg):  # HDG command
        """ Select heading command: HDG acid, hdg """
        if not isinstance(idx, Collection):
            idx = np.array([idx])
        if not isinstance(hdg, Collection):
            hdg = np.array([hdg])
        # If there is wind, compute the corresponding track angle
        if bs.traf.wind.winddim > 0:
            ab50 = bs.traf.alt[idx] > 50.0 * ft
            bel50 = np.logical_not(ab50)
            iab = idx[ab50]
            ibel = idx[bel50]

            tasnorth = bs.traf.tas[iab] * np.cos(np.radians(hdg[ab50]))
            taseast = bs.traf.tas[iab] * np.sin(np.radians(hdg[ab50]))
            vnwnd, vewnd = bs.traf.wind.getdata(bs.traf.lat[iab], bs.traf.lon[iab], bs.traf.alt[iab])
            gsnorth = tasnorth + vnwnd
            gseast = taseast + vewnd
            self.trk[iab] = np.degrees(np.arctan2(gseast, gsnorth))%360.
            self.trk[ibel] = hdg
        else:
            self.trk[idx] = hdg

        bs.traf.swlnav[idx] = False
        # Everything went ok!
        return True 
Example #14
Source File: aligned_mapping.py    From anndata with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _validate_value(self, val: V, key: str) -> V:
        if (
            hasattr(val, "index")
            and isinstance(val.index, cabc.Collection)
            and not (val.index == self.dim_names).all()
        ):
            # Could probably also re-order index if it’s contained
            raise ValueError(
                f"value.index does not match parent’s axis {self.axes[0]} names"
            )
        return super()._validate_value(val, key) 
Example #15
Source File: test_md.py    From python-mbedtls with MIT License 5 votes vote down vote up
def test_algorithms():
    assert isinstance(hashlib.algorithms_guaranteed, Collection)
    assert hashlib.algorithms_guaranteed

    assert isinstance(hashlib.algorithms_available, Collection)
    assert hashlib.algorithms_available

    assert frozenset(hashlib.algorithms_guaranteed).issubset(
        hashlib.algorithms_available
    ) 
Example #16
Source File: cmd2.py    From WebPocket with GNU General Public License v3.0 5 votes vote down vote up
def flag_based_complete(self, text: str, line: str, begidx: int, endidx: int,
                            flag_dict: Dict[str, Union[Iterable, Callable]],
                            all_else: Union[None, Iterable, Callable]=None) -> List[str]:
        """
        Tab completes based on a particular flag preceding the token being completed
        :param text: the string prefix we are attempting to match (all returned matches must begin with it)
        :param line: the current input line with leading whitespace removed
        :param begidx: the beginning index of the prefix text
        :param endidx: the ending index of the prefix text
        :param flag_dict: dictionary whose structure is the following:
                          keys - flags (ex: -c, --create) that result in tab completion for the next
                                 argument in the command line
                          values - there are two types of values
                             1. iterable list of strings to match against (dictionaries, lists, etc.)
                             2. function that performs tab completion (ex: path_complete)
        :param all_else: an optional parameter for tab completing any token that isn't preceded by a flag in flag_dict
        :return: a list of possible tab completions
        """
        # Get all tokens through the one being completed
        tokens, _ = self.tokens_for_completion(line, begidx, endidx)
        if not tokens:
            return []

        completions_matches = []
        match_against = all_else

        # Must have at least 2 args for a flag to precede the token being completed
        if len(tokens) > 1:
            flag = tokens[-2]
            if flag in flag_dict:
                match_against = flag_dict[flag]

        # Perform tab completion using a Collection
        if isinstance(match_against, Collection):
            completions_matches = self.basic_complete(text, line, begidx, endidx, match_against)

        # Perform tab completion using a function
        elif callable(match_against):
            completions_matches = match_against(text, line, begidx, endidx)

        return completions_matches 
Example #17
Source File: cmd2.py    From WebPocket with GNU General Public License v3.0 5 votes vote down vote up
def __subclasshook__(cls, C):
            if cls is Collection:
                if any("__len__" in B.__dict__ for B in C.__mro__) and \
                        any("__iter__" in B.__dict__ for B in C.__mro__) and \
                        any("__contains__" in B.__dict__ for B in C.__mro__):
                    return True
            return NotImplemented

# Python 3.4 require contextlib2 for temporarily redirecting stderr and stdout 
Example #18
Source File: cmd2.py    From WebPocket with GNU General Public License v3.0 4 votes vote down vote up
def index_based_complete(self, text: str, line: str, begidx: int, endidx: int,
                             index_dict: Mapping[int, Union[Iterable, Callable]],
                             all_else: Union[None, Iterable, Callable] = None) -> List[str]:
        """
        Tab completes based on a fixed position in the input string
        :param text: the string prefix we are attempting to match (all returned matches must begin with it)
        :param line: the current input line with leading whitespace removed
        :param begidx: the beginning index of the prefix text
        :param endidx: the ending index of the prefix text
        :param index_dict: dictionary whose structure is the following:
                           keys - 0-based token indexes into command line that determine which tokens
                                  perform tab completion
                           values - there are two types of values
                              1. iterable list of strings to match against (dictionaries, lists, etc.)
                              2. function that performs tab completion (ex: path_complete)
        :param all_else: an optional parameter for tab completing any token that isn't at an index in index_dict
        :return: a list of possible tab completions
        """
        # Get all tokens through the one being completed
        tokens, _ = self.tokens_for_completion(line, begidx, endidx)
        if not tokens:
            return []

        matches = []

        # Get the index of the token being completed
        index = len(tokens) - 1

        # Check if token is at an index in the dictionary
        if index in index_dict:
            match_against = index_dict[index]
        else:
            match_against = all_else

        # Perform tab completion using a Collection
        if isinstance(match_against, Collection):
            matches = self.basic_complete(text, line, begidx, endidx, match_against)

        # Perform tab completion using a function
        elif callable(match_against):
            matches = match_against(text, line, begidx, endidx)

        return matches

    # noinspection PyUnusedLocal