Ejemplo n.º 1
0
 def __init__(self, frames):
     Sequence.__init__(self)
     # frames is a tuple of frame tuples: see Frame constructor for the
     # format of a frame tuple; it is reversed, because _tracemalloc
     # returns frames sorted from most recent to oldest, but the
     # Python API expects oldest to most recent
     self._frames = tuple(reversed(frames))
    def __init__(self, fname='', dat=None):
        """
        Initialization for SpectralImage can be from a filename or metadata
        dictionary.

        hdf5 filename is checked against list of supported file types.
        Dictionary supercedes loading from a file.

        Parameters
        ----------
            fname : str
                filename of hdf5 file to open
            dat : DictionaryTreeBrowser
                metadata dictionary

        """
        if dat is not None:
            assert isinstance(dat, DictionaryTreeBrowser)
            self.dat = dat.copy()
        elif self.is_supported(fname):
            self.load_h5_data(fname)
        else:
            raise Exception('No valid dictionary or filename supplied.')
            return

        self.load_from_metadata()
        Sequence.__init__(self)

        if self.is_supported(fname):
            print('Load from %s complete.' % fname)
            print('%d x %d x %d spatial x %d spectral points' %
                  (len(self.z_array), len(self.x_array), len(
                      self.y_array), len(self.spec_x_array)))
Ejemplo n.º 3
0
 def __init__(self, frames):
     Sequence.__init__(self)
     # frames is a tuple of frame tuples: see Frame constructor for the
     # format of a frame tuple; it is reversed, because _tracemalloc
     # returns frames sorted from most recent to oldest, but the
     # Python API expects oldest to most recent
     self._frames = tuple(reversed(frames))
Ejemplo n.º 4
0
def patch_spaces_tuple_Tuple():
    # Sequence: `__getitem__`
    #   Reversible:  `__reversed__`*
    #   Collection:
    #     Sized: `__len__`
    #     Iterable: `__iter__`*
    #     Container: `__contains__`*
    # * [optional] Based on `__len__` and `__getitem__` (which should raise
    #   IndexError), Sequence provides generic slow-ish implementations of
    #   `__iter__`, `__contains__` and `__reversed__`.

    spaces_tuple = importlib.import_module('gym.spaces.tuple')

    # patch the missing methods into the class prototype
    spaces_tuple.Tuple.__len__ = __len__
    spaces_tuple.Tuple.__iter__ = __iter__

    # declare Sequence as a virtual base class of Tuple
    Sequence.register(spaces_tuple.Tuple)
Ejemplo n.º 5
0
 def __init__(self, traces):
     Sequence.__init__(self)
     # traces is a tuple of trace tuples: see Trace constructor
     self._traces = traces
Ejemplo n.º 6
0
    def __reversed__(self):
        # type: () -> Iterable
        return reversed(self.data)

    def __getitem__(self, index):
        # type: (Any) -> Any
        return self.data[index]

    @property
    def _evictcount(self):
        # type: () -> int
        return len(self)


Sequence.register(Messagebuffer)


class BufferMap(OrderedDict, Evictable):
    """Map of buffers."""

    Buffer = Messagebuffer
    Empty = Empty

    maxsize = None
    total = 0
    bufmaxsize = None

    def __init__(self, maxsize, iterable=None, bufmaxsize=1000):
        # type: (int, Iterable, int) -> None
        super().__init__()
Ejemplo n.º 7
0
    def __init__(self, path):
        Sequence.__init__(self)

        self._path = unicodedata.normalize('NFC', str(path))
        self._instance = None
Ejemplo n.º 8
0
 def __init__(self, traces):
     Sequence.__init__(self)
     # traces is a tuple of trace tuples: see Trace constructor
     self._traces = traces
Ejemplo n.º 9
0
else:
    from collections import Iterable, Sequence
# Register extension classes that look like a sequence, ie. have a
# length and adressable elements, as a Sequence. Same for Iterable.
for entry in ext.__dict__.values():
    # Only consider types (=classes), not object instances
    if not isinstance(entry, type): continue
    # The Iterable interface means the type contains retrievable items.
    # If the type fulfills this but is not already a known Iterable then
    # register it as such.
    if hasattr(entry, "__getitem__") and not issubclass(entry, Iterable):
        Iterable.register(entry)
    # A Sequence is an Iterable that also has a determinable length.
    if hasattr(entry, "__getitem__") and hasattr(entry, "__len__") \
        and not issubclass(entry, Sequence):
        Sequence.register(entry)


def bool_md5(self):
    return hashlib.md5(self.__getstate__()[1])


bool.md5 = bool_md5


@boost.python.inject_into(grid)
class _():
    def show_summary(self, f=None):
        if (f is None): f = sys.stdout
        print("origin:", self.origin(), file=f)
        print("last:", self.last(), file=f)
Ejemplo n.º 10
0
 def __init__(self, frames):
     Sequence.__init__(self)
     # frames is a tuple of frame tuples: see Frame constructor for the
     # format of a frame tuple
     self._frames = frames
    def remove(self, value):
        """
        Remove the first occurrence of a value from the vector.

        >>> v1 = v(1, 2, 3, 2, 1)
        >>> v2 = v1.remove(1)
        >>> v2
        pvector([2, 3, 2, 1])
        >>> v2.remove(1)
        pvector([2, 3, 2])
        """


_EMPTY_PVECTOR = PythonPVector(0, SHIFT, [], [])
PVector.register(PythonPVector)
Sequence.register(PVector)
Hashable.register(PVector)


def python_pvector(iterable=()):
    """
    Create a new persistent vector containing the elements in iterable.

    >>> v1 = pvector([1, 2, 3])
    >>> v1
    pvector([1, 2, 3])
    """
    return _EMPTY_PVECTOR.extend(iterable)


try:
Ejemplo n.º 12
0
 def __init__(self, traces):
     Sequence.__init__(self)
     self._traces = traces
Ejemplo n.º 13
0
KeysView.register(EmptySet)
ItemsView.register(EmptySet)
ValuesView.register(EmptyCollection)
assert issubclass(EmptySet, KeysView)
assert issubclass(EmptySet, ItemsView)
assert issubclass(EmptySet, Set)
assert issubclass(EmptySet, MappingView)
assert issubclass(EmptyCollection, ValuesView)
assert issubclass(EmptyCollection, Collection)
assert issubclass(EmptyCollection, MappingView)



Mapping.register(EmptyMapping)
Set.register(EmptySet)
Sequence.register(EmptySequence)
assert issubclass(EmptyMapping, Mapping)
assert issubclass(EmptySet, Set)
assert issubclass(EmptySequence, Sequence)

if 0:
    Mapping.register(EmptyThree)
    Set.register(EmptyThree)
    Sequence.register(EmptyThree)
assert issubclass(EmptyThree, Mapping)
assert issubclass(EmptyThree, Set)
assert issubclass(EmptyThree, Sequence)



Ejemplo n.º 14
0
    def __reversed__(self):
        # type: () -> Iterable
        return reversed(self.data)

    def __getitem__(self, index):
        # type: (Any) -> Any
        return self.data[index]

    @property
    def _evictcount(self):
        # type: () -> int
        return len(self)


Sequence.register(Messagebuffer)  # noqa: E305


@python_2_unicode_compatible
class BufferMap(OrderedDict, Evictable):
    """Map of buffers."""

    Buffer = Messagebuffer
    Empty = Empty

    maxsize = None
    total = 0
    bufmaxsize = None

    def __init__(self, maxsize, iterable=None, bufmaxsize=1000):
        # type: (int, Iterable, int) -> None
Ejemplo n.º 15
0
    @classmethod
    def from_sequence_range(cls, seq, range_or_slice):
        return cls(seq, range_or_slice)

    def __len__(self):
        return len(self.__rng)

    def __iter__(self):
        return map(self.__seq.__getitem__, self.__rng)

    def __reversed__(self):
        return map(self.__seq.__getitem__, reversed(self.__rng))


'''
Sequence.register(int)
Sequence.register(range)
assert not isinstance(int, Sequence)
assert isinstance(range, Sequence) ??????? why fail????
'''


def t():
    ls = SeqSliceView([1, 2, 3, 4, 5, 6, 7], range(1, 6, 2))
    ls2 = SeqSliceView(ls, slice(-1, None, -1))
    assert repr(ls2) == 'SeqSliceView([1, 2, 3, 4, 5, 6, 7], range(5, -1, -2))'


if __name__ == "__main__":
    t()
Ejemplo n.º 16
0
    """
    __slots__ = ('first', 'rest')

    def __new__(cls, first, rest):
        instance = super(PList, cls).__new__(cls)
        instance.first = first
        instance.rest = rest
        return instance

    def __bool__(self):
        return True

    __nonzero__ = __bool__


Sequence.register(PList)
Hashable.register(PList)


class _EmptyPList(_PListBase):
    __slots__ = ()

    def __bool__(self):
        return False

    __nonzero__ = __bool__

    @property
    def first(self):
        raise AttributeError("Empty PList has no first")
Ejemplo n.º 17
0
 def __init__(self, elements: t.Sequence[t.Any], root: "NodeTree",
              tree: tuple):
     Sequence.__init__(self)
     Node.__init__(self, root, tree)
     self._elements: t.Sequence[t.Any] = elements
Ejemplo n.º 18
0
    def __init__(self, file_path):
        File.__init__(self, file_path)
        Sequence.__init__(self)

        self._instance = None
Ejemplo n.º 19
0
 def __init__(self, frames):
     Sequence.__init__(self)
     # frames is a tuple of frame tuples: see Frame constructor for the
     # format of a frame tuple
     self._frames = frames
            raise TypeError("'%s' object cannot be interpreted as an index" %
                            type(index).__name__)

        if index >= 0:
            return self.popleft(index).left

        shifted = len(self) + index
        if shifted < 0:
            raise IndexError(
                "pdeque index {0} out of range {1}".format(index, len(self)), )
        return self.popleft(shifted).left

    index = Sequence.index


Sequence.register(PDeque)
Hashable.register(PDeque)


def pdeque(iterable=(), maxlen=None):
    """
    Return deque containing the elements of iterable. If maxlen is specified then
    len(iterable) - maxlen elements are discarded from the left to if len(iterable) > maxlen.

    >>> pdeque([1, 2, 3])
    pdeque([1, 2, 3])
    >>> pdeque([1, 2, 3, 4], maxlen=2)
    pdeque([3, 4], maxlen=2)
    """
    t = tuple(iterable)
    if maxlen is not None:
Ejemplo n.º 21
0
 def __init__(self, frames):
     Sequence.__init__(self)
     self._frames = tuple(reversed(frames))
Ejemplo n.º 22
0
    def __reversed__(self):
        # type: () -> Iterable
        return reversed(self.data)

    def __getitem__(self, index):
        # type: (Any) -> Any
        return self.data[index]

    @property
    def _evictcount(self):
        # type: () -> int
        return len(self)


Sequence.register(Messagebuffer)  # noqa: E305


@python_2_unicode_compatible
class BufferMap(OrderedDict, Evictable):
    """Map of buffers."""

    Buffer = Messagebuffer
    Empty = Empty

    maxsize = None
    total = 0
    bufmaxsize = None

    def __init__(self, maxsize, iterable=None, bufmaxsize=1000):
        # type: (int, Iterable, int) -> None
Ejemplo n.º 23
0
from collections.abc import Sequence as _Sequence

from . import _pyrodigal
from ._pyrodigal import Gene, Genes, Pyrodigal

__all__ = ["Gene", "Genes", "Pyrodigal"]
__doc__ = _pyrodigal.__doc__

__author__ = "Martin Larralde <*****@*****.**>"
__license__ = "GPLv3"
__version__ = "0.3.2"

_Sequence.register(Genes)
Ejemplo n.º 24
0
 def __jclass_init__(self):
     Sequence.register(self)
     MutableSequence.register(self)
Ejemplo n.º 25
0
    def truncate(self: VectorOrSub, max_length: Realish) -> VectorOrSub:
        if self.length > max_length:
            return self.scale_to(max_length)
        return self

    def scale_to(self: VectorOrSub, length: Realish) -> VectorOrSub:
        """
        Scale the vector to the given length
        """
        try:
            scale = length / self.length
        except ZeroDivisionError:
            scale = 1
        return self.scale_by(scale)

    scale = scale_to

    def reflect(self: VectorOrSub, surface_normal: VectorLike) -> VectorOrSub:
        """
        Calculate the reflection of the vector against a given surface normal
        """
        surface_normal = Vector2.convert(surface_normal)
        if not isclose(surface_normal.length, 1):
            raise ValueError("Reflection requires a normalized vector.")

        return self - (2 * (self * surface_normal) * surface_normal)


Sequence.register(Vector2)