def setInterval(self, begin, end): """Set both the start time and the end time.""" self._begin = assertIsInstance(begin, datetime.datetime) \ if begin is not None else datetime.datetime.min self._end = assertIsInstance(end, datetime.datetime) \ if end is not None else datetime.datetime.max self._updateView()
def addTargetURI(self, uri): assertIsInstance(uri, str) l = lambda action: action.text() if uri not in map(l, self.playto.menu().actions()): shortcut = "Ctrl+%s"%str(len(self.playto.menu().actions())+1) \ if len(self.playto.menu().actions())<9 else "" self.playto.menu().addAction(uri, self._playToSlot, shortcut) self.bufferview.graph.playto.menu().addAction( uri, self._playToSlot, shortcut)
def slice(self, starttime=None, endtime=None): """Return a slice of the buffer's elements. *starttime* and *endtime* must be datetime.datetime or None and they can be used to slice the buffer.""" assertIsInstance(starttime, datetime.datetime, None) assertIsInstance(endtime, datetime.datetime, None) start = 0 if starttime is None else self.index(starttime) end = len(self._buffer) if endtime is None else self.index(endtime, start) return collections.deque(self._buffer[start:end])
def __init__(self, *decoders): super().__init__() self._sequence = list() for decoder in decoders: assertIsInstance(decoder, Decoder) if isinstance(decoder, _CompositeDecoder): self._sequence.extend(decoder.sequence()) else: self._sequence.append(decoder)
def islice(self, starttime=None, endtime=None): """Returns an iterator over the stored records {'timetag': ... , 'products': ...}. *starttime* and *endtime* must be datetime.datetime or None and they can be used to slice the buffer.""" assertIsInstance(starttime, datetime.datetime, None) assertIsInstance(endtime, datetime.datetime, None) for record in self._buffer: if starttime is not None and record.timetag<starttime: continue if endtime is not None and record.timetag>endtime: break yield record
def __init__(self, request=Request.ANY, mode="items", separator="\n", src=False, dest=False, depth=None, parent=None): super().__init__(request, Offer(quickdict(str=str())), Functor.RESULTONLY, parent=parent) self.dumpsrc = assertIsInstance(src, bool) self.dumpdest = assertIsInstance(dest, bool) self.depth = None if depth is None else int(depth) if mode not in ("items", "values", "keys"): raise ValueError( "mode must be 'items' or 'values' or 'keys', not '%s'"%mode) else: self._mode = mode self.separator = assertIsInstance(separator, str, None) if self.separator is None: self.separator = ""
def addObserver(self, observer, mode=QtCore.Qt.QueuedConnection): """Subscribe *observer* as a new observer. Return whether *observer* has been correctly added.""" assertIsInstance(observer, Observer) if observer in self.observers(): rvalue = False else: observer._Observer__addObservable(self) self.__observers[weakref.ref(observer)] = \ Observable._ObserverRecord(observer, mode) self.observerAdded.emit(observer) rvalue = True return rvalue
def __init__(self, parser, sender, speed=1.0, loop=False, interval=1000, offer=Offer(Offer.UNDEFINED), parent=None): super().__init__(offer, parent=parent) self._parser = assertIsInstance(parser, Player.Parser) self._sender = assertIsInstance(sender, Player.Sender) self._loop = assertIsInstance(loop, bool) self._speed = float(speed) # speed factor self._interval = int(interval) # in ms self._queue = collections.deque() self._waittimer = QtCore.QTimer(timeout=self._parseSendOutAndWait) self._waittimer.setSingleShot(True) self._running = False self._date = None # Datetime when the next item should be sent. self.playcnt = 0
def __init__(self, react=None, hz=None, parent=None): """:class:`Observer` objects can be subscribed to many :class:`Observable` instances in order to listen to their notifications. The argument *react* can be set to the handler function (it must accept one argument) that will be called as consequence of an observable notification. If *react* is None, the member method :meth:`_react` will be called. *hz* defines the rate at which the observer will react to notifications. Available values are: * None --- immediately; * 0 --- never; * <float> --- at the selected frequency (in hz). *parent* defines the observers parent. .. note:: The list of the subscribed observables is composed by weak references, so it is necessary to keep both observables and observers alive. """ if not sip.ispycreated(self): QtCore.QObject.__init__(self, parent) Node.__init__(self) self._internal = self._InternalQObject() self.__observed = set() self.__queue = set() self.__timer = QtCore.QTimer(timeout=self._update) self.__hz = None if hz is None else float(hz) if self.__hz: self.__timer.start(1000/float(hz)) self.__react = assertIsInstance(react, None, collections.Callable)
def __init__(self, buffer, begin=None, end=None, fps=None, graph=None, parent=None): super().__init__(parent) # Setup GUI self.setFocusPolicy(QtCore.Qt.StrongFocus) self.setLayout(QtGui.QVBoxLayout()) self.layout().setSpacing(4) self.graph = BufferView.Graph(weakref.proxy(self)) \ if graph is None else graph(weakref.proxy(self)) self.layout().addWidget(self.graph) self.scroll = QtGui.QScrollBar(QtCore.Qt.Horizontal, valueChanged=self._scrollTo) self.scroll.setPageStep(50) QtGui.QShortcut("Left", self.scroll, self._scrollLeft) QtGui.QShortcut("Right", self.scroll, self._scrollRight) QtGui.QShortcut("Alt+Left", self.scroll, self._scrollPageLeft) QtGui.QShortcut("Alt+Right", self.scroll, self._scrollPageRight) QtGui.QShortcut(QtCore.Qt.Key_PageUp, self.scroll, self._scrollPageLeft) QtGui.QShortcut(QtCore.Qt.Key_PageDown, self.scroll, self._scrollPageRight) QtGui.QShortcut("Ctrl+Up", self.scroll, self.zoomIn) QtGui.QShortcut("Ctrl+Down", self.scroll, self.zoomOut) QtGui.QShortcut("Home", self.scroll, self._scrollBegin) QtGui.QShortcut("End", self.scroll, self._scrollEnd) self.layout().addWidget(self.scroll) # Model self._buffer = buffer self._begin = assertIsInstance(begin, datetime.datetime) \ if begin is not None else datetime.datetime.min self._end = assertIsInstance(end, datetime.datetime) \ if end is not None else datetime.datetime.max # Zooming self._zoom = None self._zoomdelta = datetime.timedelta() self._viewbegin = self.begin() self._viewend = self.end() self._viewinterval = None self.zoomOriginal() # Selection self._selbegin = self._selend = self.begin() # Refresh timer self._refresher = QtCore.QTimer(timeout=self._refresherTimeout) if fps is not None and fps!=0: self._toupdate = False self._buffer.changed.connect(self._bufferChanged) self._refresher.start(1000/fps)
def __init__(self, request=QRequest("diff.*.contacts|source|timetag"), blender=Functor.RESULTONLY, rawsource=False, hz=None, parent=None): super().__init__(request, Offer(quickdict(osc=osc.Packet)), blender, hz=hz, parent=parent) # self._tuiostate[observable-ref][source][profile] = [fseq, {s_id: TuioDescriptor}] self._tuiostate = {} self.observableRemoved.connect(self.__removeRecord) self._rawsource = assertIsInstance(rawsource, bool)
def __init__(self, timetag, elements): """:class:`Packet` object representing an OSC Bundle. The argument *timetag* must be a :class:`datetime.datetime` instance or ``None``, while *elements* should be the list of :class:`Packet` objects contained in the bundle. """ self.timetag = assertIsInstance(timetag, None, datetime.datetime) self.elements = elements self.source = None # source is not encoded
def __init__(self, rt=False, blender=Functor.MERGECOPY, parent=None): timetag = datetime.datetime.now() super().__init__( QRequest("data"), Offer(quickdict( osc=osc.Bundle(timetag, (osc.Bundle(timetag, (Offer.UNDEFINED, )), osc.Message(str(), str(), Offer.UNDEFINED), Offer.UNDEFINED)), timetag=timetag)), blender, parent=parent) self._receipttime = assertIsInstance(rt, bool)
def __init__(self, sizelimit=10000, oversizecut=100, parent=None, **kwargs): super().__init__(parent) """Product buffer.""" self._buffer = [] """Number of products stored in buffer.""" self._sum = 0 """Maximum number of stored products.""" self._sizelimit = None \ if sizelimit is None or sizelimit==float("inf") \ else assertIsInstance(sizelimit, int) """When stored products exceed 'sizelimit', instead of keeping 'sizelimit' products, it keeps 'sizelimit'-'oversizecut' products, so that productDrop is not invoked anytime a new product is obtained.""" self.oversizecut = assertIsInstance(oversizecut, int) # Connect argument slot for key, value in kwargs.items(): if key=="changed": self.changed.connect(value) elif key=="productDrop": self.productDrop.connect(value) else: raise TypeError( "'%s' is an invalid keyword argument for this function"%key)
def _normalize(path): assertIsInstance(path, str) if not path or path=="$": rvalue = ("", ) else: sub = [] def encode(match): m = match.group() sub.append(match.group()[1:-1] if m[0]=="[" and m[-1]=="]" \ else match.group()) return "[#%d]"%(len(sub)-1) def decode(match): return sub.pop(0) path = _re0.sub(encode, path) path = _re1.sub(";", path) path = _re2.sub(";..;", path) path = _re3.sub("", path) path = _re4.sub(decode, path) path = _re5.sub("", path) path = _re6.sub("|", path) rvalue = tuple(_re7.split(path)) return rvalue
def addrToString(addr): """Return a string representing the QHostAddress *addr*.""" assertIsInstance(addr, QHostAddress) if addr.protocol()==QAbstractSocket.IPv4Protocol: return addr.toString() elif addr.protocol()==QAbstractSocket.IPv6Protocol: addr = addr.toIPv6Address() s = "" ; zeros = False for i in range(0,16,2): c = (addr[i]<<8)+addr[i+1] if c==0: if i==0: s += ":" if not zeros: s += ":" zeros = True else: s += hex(c)[2:] if i<14: s += ":" if zeros: zeros = False return s else: return ""
def __init__(self, blender=Functor.MERGECOPY, rawsource=False, parent=None): super().__init__(QRequest("osc"), Offer(TuioDecoder.getTemplate()), blender, parent=parent) """Alive TUIO items.""" # self.__alive[source][profile] = set of session_ids self.__alive = {} """Association between the TUIO Session ID and the gesture event ID. This is necessary because different TUIO sources may use the same Session ID.""" # self.__idpairs[source][session_id] = event_id self.__idpairs = {} self.__idcount = 0 self._rawsource = assertIsInstance(rawsource, bool)
def __init__(self, address, typetags="", *arguments): """:class:`Packet` object representing an OSC Message. The argument *address* must be a string begginning with the character ``/`` (forward slash). The argument *typetags* must be a string composed by sequence of characters corresponding exactly to the sequence of OSC arguments in the given message. *arguments* is the list of object contained in the OSC Message. """ self.address = assertIsInstance(address, str) self.typetags = typetags self.arguments = arguments self.source = None # source is not encoded
def __init__(self, outputdevice, writeend=True, hz=None, parent=None): """:class:`Consumer <boing.core.Consumer>` node that anytime it receives some data, it writes the data to the device *outputdevice*. The :class:`DataWriter` requires the products ``str`` if the output device is text enabled (see method :meth:`isTextModeEnabled <boing.utils.fileutils.IODevice.isTextModeEnabled>`) otherwise it requires the product ``data``. If the argument *writeend* is set to ``True``, the :class:`DataWriter` will never write an empty string; this can be useful in order to prevent a socket to close. *parent* defines the parent of the node. """ self._textmode = outputdevice.isTextModeEnabled() super().__init__(request=QRequest("str" if self._textmode else "data"), hz=hz, parent=parent) self.__output = outputdevice self.writeend = assertIsInstance(writeend, bool)
def __init__(self, node, antialiasing=False, parent=None): QtGui.QWidget.__init__(self, parent) self.node = node # Setup GUI self.antialiasing = assertIsInstance(antialiasing, bool) self.sizehint = QtCore.QSize(320,240) self.setFocusPolicy(QtCore.Qt.StrongFocus) # Context menu self.menu = QtGui.QMenu() self.menu.addAction("Toggle debug level", self.toggleDebug, QtCore.Qt.Key_Space) self.menu.addAction("Clear tracks", self.node.clearTracks, 'Ctrl+C') '''self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.connect(self, QtCore.SIGNAL("customContextMenuRequested(const QPoint &)"), self.__contextmenu) self.connect(QtGui.QShortcut('Alt+C', self), QtCore.SIGNAL("activated()"), self.__configpanel)''' """position circle size""" self.phi = 4 self.__fps_count = 0 self.__fps_previous = 0 self.__fps_timer = QtCore.QTimer() self.__fps_timer.timeout.connect(self._fpsTimeout) self.debuglevel = 0 self.oldest = None
def __init__(self, inputdevice, postend=True, parent=None): """:class:`Producer <boing.core.Producer>` node that anytime the device *inputdevice* send the signal :attr:`readyRead <boing.utils.fileutils.CommunicationDevice.readyRead>` it reads the device and it produces a message containing the data. The provided products is a dictionary ``{"str": data}`` if ``data`` is a string, otherwise the product will be a dictionary like ``{"data": data}``. If the argument *postend* is set to ``True``, the :class:`DataReader` will never produce an empty product, like ``{"str": ""}`` or ``{"data": b""}``. *parent* defines the parent of the node. """ self._textmode = inputdevice.isTextModeEnabled() if self._textmode: offer = Offer(quickdict(str=str())) tags = dict(str=QRequest("str")) else: offer = Offer(quickdict(data=bytearray())) tags = dict(data=QRequest("data")) super().__init__(offer, tags=tags, parent=parent) self.__input = inputdevice self.__input.readyRead.connect(self._postData) self.postend = assertIsInstance(postend, bool)
def __init__(self, request=Request.ANY, timelimit=30000, sizelimit=10000, timewarping=True, oversizecut=100, fps=20, guiparent=None, parent=None): super().__init__(request, parent=parent) if fps<=0: raise ValueError( "fps must be a value greater than zero, not %s"%str(fps)) self.fps = fps self._active = False self._buffer= TimedProductBuffer(timelimit, sizelimit, oversizecut=oversizecut) # Deactivate the timed buffer eraser and use the refresher # timer instead. self._buffer.setEraserActive(False) """Determines whether the time when the buffer is stopped does not reduce the products timelife.""" self.timewarping = assertIsInstance(timewarping, bool) """time when the recorder was stopped or None if the recorder is running.""" self._stoptime = None self._refresher = QtCore.QTimer(timeout=self._refreshtime) # Player self._player = BufferPlayer(sender=Player.PostSender()) self._player.stopped.connect(self._playerStopped) self._targets = {} # Setup GUI self._gui = Recorder.RecorderWindow(weakref.proxy(self), guiparent) self._gui.start.connect(self.start) self._gui.stop.connect(self.stop) self._gui.stop.connect(self._player.stop) self._gui.toggle.connect(self._toggle) self._gui.clearBuffer.connect(self.clearBuffer) self._gui.playTo.connect(self.playTo) self._gui.writeTo.connect(self.writeTo) self._gui.toggleKeepAlive.connect(self._toggleKeepAlive) self._gui.closed.connect(self.clear) self._toggledBusy.connect(self._gui._toggled)
def __init__(self, wrap=False, rt=False, blender=Functor.RESULTONLY, parent=None): super().__init__(QRequest("osc"), Offer(quickdict(data=bytearray())), blender, parent=parent) self.wrap = assertIsInstance(wrap, bool) self.rt = assertIsInstance(rt, bool)
def __add__(self, other): assertIsInstance(other, Decoder, None) return self if other is None else _CompositeDecoder(self, other)
def __init__(self, wrap=False, protocol=None, request=QRequest.ANY, blender=Functor.MERGECOPY, parent=None): super().__init__(request, Offer(quickdict(data=bytes())), blender, parent=parent) self.wrap = assertIsInstance(wrap, bool) self.protocol = assertIsInstance(protocol, None, int)
def __init__(self, encoding="utf-8", blender=Functor.MERGECOPY, parent=None): super().__init__(QRequest("data"), Offer(quickdict(str=str())), blender, parent=parent) self.encoding = assertIsInstance(encoding, str) self.errors = "replace"
def __init__(self, encoding="utf-8", blender=Functor.MERGECOPY, parent=None): super().__init__(QRequest("str"), Offer(quickdict(data=bytearray())), blender, parent=parent) self.encoding = assertIsInstance(encoding, str)
def subscribeTo(self, observable, mode=QtCore.Qt.QueuedConnection): """Subscribe to *observable*. Return whether *observer* has been successfully subscribed to.""" assertIsInstance(observable, Observable) rvalue = observable.addObserver(self, mode) return rvalue
def __init__(self, wrap=False, request=QRequest.ANY, blender=Functor.MERGECOPY, parent=None): super().__init__(request, Offer(quickdict(str=str())), blender, parent=parent) self.wrap = assertIsInstance(wrap, bool)
def __init__(self, request=Request.ANY): self.request = assertIsInstance(request, Request)