def __init__(self, context: BlenderContext) -> None: super().__init__(context) self._position = Subject() self._activeInputs = Subject() # noinspection PyTypeChecker self.position = self._position.pipe( ops.distinct_until_changed(), ops.map(lambda v: tuple( p * s for p, s in zip(v, context.window_size.tuple))), ops.map(Point.from_tuple), ops.share()) codes = { MouseButton.LEFT: bge.events.LEFTMOUSE, MouseButton.MIDDLE: bge.events.MIDDLEMOUSE, MouseButton.RIGHT: bge.events.RIGHTMOUSE } def pressed(e: SCA_InputEvent) -> bool: return KX_INPUT_ACTIVE in e.status or KX_INPUT_JUST_ACTIVATED in e.status def value_for(button: MouseButton) -> Observable: code = codes[button] return self._activeInputs.pipe( ops.start_with({}), ops.map(lambda i: code in i and pressed(i[code])), ops.map(lambda v: button if v else 0)) # noinspection PyTypeChecker self.buttons = rx.combine_latest( *[value_for(b) for b in MouseButton]).pipe( ops.map(lambda v: reduce(lambda a, b: a | b, v)), ops.distinct_until_changed(), ops.share())
def select(self, selectors: List): if len(selectors) == 1 and callable(selectors[0]): return self._state.pipe(rxop.map(selectors[0]), rxop.distinct_until_changed()) else: return self._state.pipe( rxop.map(lambda data: safe_get(data, selectors)), rxop.distinct_until_changed())
def open(self): scheduler = AsyncIOScheduler() print("WebSocket opened") # A Subject is both an observable and observer, so we can both subscribe # to it and also feed (send) it with new values self.subject = Subject() # Get all distinct key up events from the input and only fire if long enough and distinct searcher = self.subject.pipe( ops.map(lambda x: x["term"]), ops.filter(lambda text: len(text) > 2), # Only if the text is longer than 2 characters ops.debounce(0.750), # Pause for 750ms ops.distinct_until_changed(), # Only if the value has changed ops.flat_map_latest(search_wikipedia) ) def send_response(x): self.write_message(x.body) def on_error(ex): print(ex) searcher.subscribe(send_response, on_error, scheduler=scheduler)
def __init__(self, source_map, crypto="BTC", currency="USD", debounce_interval=2): """ :param source_map: (dict) that maps the details of an API :param crypto: cryptocurrency code :param currency: fiat currency code """ self.crypto = crypto.upper() self.currency = currency.upper() self.source = source_map[self.get_exchange()] self.websocket_msg = self.source["{}{}".format( self.crypto, self.currency)]["message"] self.url = self.source["url"] self.subject = Subject() filtered_data = self.subject.pipe(rx_ops.debounce(debounce_interval), rx_ops.distinct_until_changed()) def on_error(err): self.log(msg=f"subject error: {err}") filtered_data.subscribe(on_next=self.get_on_next(), on_error=on_error)
def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._subject = Subject() self.subscribe = self._subject.pipe( ops.distinct_until_changed(json.dumps)).subscribe # type: ignore self._observables: dict[Disposable, Any] = {} self._update_observables()
def __init__(self, error_handler: ErrorHandler) -> None: if error_handler is None: raise ValueError("Argument 'error_handler' is required.") super().__init__() self._error_handler = error_handler self._added_window = Subject() self._removed_window = Subject() changed_window = rx.merge( self._added_window.pipe(ops.map(lambda v: (v, True))), self._removed_window.pipe(ops.map(lambda v: (v, False)))) def on_window_change(windows: Tuple[Window, ...], event: Tuple[Window, bool]): (window, added) = event if added and window not in windows: return windows + (window,) elif not added and window in windows: return tuple(c for c in windows if c is not window) # noinspection PyTypeChecker self.windows = changed_window.pipe( ops.scan(on_window_change, ()), ops.start_with(()), ops.distinct_until_changed())
def __init__(self, toolkit: BlenderToolkit, look_and_feel: Optional[LookAndFeel] = None, font_options: Optional[FontOptions] = None, window_manager: Optional[WindowManager] = None, error_handler: Optional[ErrorHandler] = None) -> None: super().__init__(toolkit, look_and_feel, font_options, window_manager, error_handler) resolution = Dimension(bge.render.getWindowWidth(), bge.render.getWindowHeight()) self._resolution = BehaviorSubject(resolution) # noinspection PyTypeChecker self.window_size = self._resolution.pipe(ops.distinct_until_changed()) self._shader = cast(GPUShader, gpu.shader.from_builtin("2D_IMAGE")) if use_viewport_render: # noinspection PyArgumentList self._draw_handler = SpaceView3D.draw_handler_add( self.process, (), "WINDOW", "POST_PIXEL") else: self._draw_handler = None bge.logic.getCurrentScene().post_draw.append(self.process) # noinspection PyTypeChecker self._texture = Buffer(bgl.GL_INT, 1) bgl.glGenTextures(1, self.texture)
def open(self): scheduler = AsyncIOScheduler(asyncio.get_event_loop()) print("WebSocket opened") # A Subject is both an observable and observer, so we can both subscribe # to it and also feed (send) it with new values self.subject = Subject() # Get all distinct key up events from the input and only fire if long enough and distinct searcher = self.subject.pipe( ops.map(lambda x: x["term"]), ops.filter(lambda text: len(text) > 2), # Only if the text is longer than 2 characters ops.debounce(0.750), # Pause for 750ms ops.distinct_until_changed(), # Only if the value has changed ops.flat_map_latest(search_wikipedia) ) def send_response(x): self.write_message(x.body) def on_error(ex): print(ex) searcher.subscribe(send_response, on_error, scheduler=scheduler)
def on_change(path: str = ''): """Applies `distinct_until_changed` to an observable stream. If `path` is provided, emitted items must be JSON-like objects, and `path` is a JSON pointer to the observed value. `None` is returned if the pointer cannot be resolved. Args: path (str, optional): [description]. Defaults to ''. Returns: [type]: [description] """ if path: return ops.distinct_until_changed( partial(jp.resolve_pointer, pointer=path, default=None)) return ops.distinct_until_changed()
def __init__(self, graph: Graph, context: Any = None) -> None: self._graph = graph self._context = context or {} super().__init__(tuple(self._graph)[0], self.transition) self._updates = to_observable(self).pipe(on_change()) self._updates.subscribe(self._on_enter) self.views = self._updates.pipe( ops.filter(lambda s: isinstance(s, DlgText)), ops.map(self.view), ops.distinct_until_changed())
def spot_instance_check_observable(interval_seconds: float = 1.0) -> rx.Observable: """ スポットインスタンスのステータスをinterval秒ごとにurlを叩いてチェックしに行くobservableを返す関数 :param interval_seconds: interval seconds """ return rx.interval(interval_seconds).pipe( ops.map(access_spot_instance_state), ops.filter(lambda resp: resp.status_code != 404), ops.map(spot_instance_state_response_to_checker_message), ops.distinct_until_changed(), )
def __init__(self, store: EcsStore) -> None: self.log: Optional[Callable[[str], None]] = None self._store = store self.get_entity = self._store.get_entity self.select_entities = self._store.select_entities self._systems = {} self._actions = Subject() self._queue = [] self.events = to_observable(self._store).pipe( ops.distinct_until_changed())
def monitor(): def is_running(state): return state in [Task.State.UNSUBMITTED, Task.State.READY, Task.State.RUNNING] return interval(_MONITORING_FREQUENCY).pipe( flat_map(lambda _: execute( action=load_status, description='monitor task ' + str(task)) ), flat_map(extract_state), distinct_until_changed(), take_while(is_running, inclusive=True) )
def heartbeat(liveliness): """ Projects a source observable sequence to a boolean. The resulting value is True when there is an observable emitted within the liveliness factor and False otherwise. Args: liveliness: The amount of time (in seconds) between each event for the observable to be considered alive. Note that an observable may stay alive for up to 2x liveliness between each event as this operator checks for items emitted between this window. """ return rx.pipe( buffer_with_time_or_count(liveliness, 1), rx_map(lambda items: len(items) > 0), distinct_until_changed(), )
def _add_obs(self, name, default=None): subject = BehaviorSubject(default) uniq_subject = subject.pipe(ops.distinct_until_changed()) def getobs(self): return getattr(self, f"_obs_{name}").value def setobs(self, v): getattr(self, f"_obs_{name}").on_next(v) setattr(self, f"_obs_{name}", subject) setattr(self, f"obs_{name}", uniq_subject) setattr(self.__class__, name, property(getobs, setobs)) self._data_fields.append(name)
def __init__(self, host, port): self.socket = QtNetwork.QTcpSocket() self.socket.stateChanged.connect(self._on_socket_state_change) self.socket.readyRead.connect(self.read) self.socket.error.connect(self._on_error) self.socket.setSocketOption(QtNetwork.QTcpSocket.KeepAliveOption, 1) self._host = host self._port = port self.block_size = 0 self._obs_state = BehaviorSubject(ConnectionState.DISCONNECTED) self.obs_state = self._obs_state.pipe(ops.distinct_until_changed()) self.message_stream = Subject()
def __init__(self): super(globalPluginHandler.GlobalPlugin, self).__init__() nvdaMonitor = startMonitoringNvda({ "speechViewer": speechViewer, "wx": wx }) outputServer = startOutputServer() nvdaMonitor.speechViewerStateStream.pipe( map(lambda status: {OutputKeys.SPEECH_VIEWER_STATE: status}), distinct_until_changed(), map(lambda msgDict: dehydrateMessage(msgDict)), ).subscribe( on_next=lambda picklableMsg: outputServer.send(picklableMsg))
def select(selector: Mapper[T1, T2] ) -> Callable[[Observable], Observable]: """ Reactive operator that applies a selector and shares the result across multiple subscribers Args: selector: the selector function Returns: The reactive operator """ return pipe( op.map(selector), op.distinct_until_changed(comparer=is_), op.multicast(subject=ReplaySubject(1)), op.ref_count(), )
def __init__(self, source_map, crypto="BTC", currency="USD", debounce_interval=2): self.crypto = crypto.upper() self.currency = currency.upper() self.url = source_map[self.get_exchange()] self.subject = Subject() filtered_data = self.subject.pipe(rx_ops.debounce(debounce_interval), rx_ops.distinct_until_changed()) def on_error(err): self.log(msg=f"subject error: {err}") filtered_data.subscribe(on_next=self.get_on_next(), on_error=on_error)
def open(self): print("WebSocket opened") self.stream = Subject() searcher = self.stream.pipe(ops.map(lambda x: x["term"]), ops.filter(lambda text: len(text) > 2), ops.debounce(0.750), ops.distinct_until_changed(), ops.flat_map_latest(search_wikipedia)) def send_response(x): self.write_message(x.body) def on_error(ex): print(ex) searcher.subscribe(send_response, on_error, scheduler=scheduler)
def __init__(self, context: Context, layout: Optional[Layout] = None, visible: bool = True): from .layout import AbsoluteLayout self._layout = Maybe.from_optional(layout).or_else_call(AbsoluteLayout) self._layout_pending = True self._layout_running = False # noinspection PyTypeChecker self.children = self.layout.observe("children").pipe( ops.map( lambda children: tuple(map(lambda c: c.component, children)))) super().__init__(context, visible) self.observe("size") \ .pipe(ops.filter(lambda _: self.visible), ops.distinct_until_changed()) \ .subscribe(lambda _: self.request_layout(), on_error=self.error_handler)
def __init__(self, scheduler=None): self._observerable = rx.interval( ObserveConfig.interval, scheduler).pipe(ops.map(lambda dummy: get_merge_requests()), ops.retry(), ops.publish(), ops.ref_count()) self._ready_to_merge = self._observerable.pipe( ops.map(lambda requests: next((request for request in requests if is_ready_to_merge(request)), None)), ops.start_with(None), ops.distinct_until_changed()) self._ready_to_merge.subscribe(lambda ready_to_merge: logging.info( 'Ready to merge: ' + str(ready_to_merge))) voted_merge_requests = self._observerable.pipe( ops.map(_to_voted_merge_requests_set)) self._new_votes_merge_requests = voted_merge_requests.pipe( ops.skip(1), ops.zip(voted_merge_requests), ops.map(lambda zipped: zipped[0] - zipped[1]), ops.filter(len), ops.map(_to_merge_requests)) self._new_votes_merge_requests.pipe( ops.map(lambda diff_set: [merge_request.get_iid() for merge_request in diff_set]) ).subscribe( lambda ids: logging.info(f'New votes for merge requests: {ids}')) awards = self._new_votes_merge_requests.pipe(ops.map(_to_awards_set), ops.publish(), ops.ref_count(), ops.start_with(set())) self._new_awards = awards.pipe( ops.skip(1), ops.zip(awards), ops.map(lambda zipped: zipped[0] - zipped[1]), ops.filter(len), ops.flat_map(lambda diff_set: rx.from_iterable(diff_set)), ops.map(lambda award_key: award_key.award)) self._new_awards.subscribe( lambda new_award: logging.info('New award: ' + str(new_award)))
def create(): return xs.pipe(ops.distinct_until_changed())
:param temperature: the sensor temperature :return: Line protocol to write into InfluxDB """ import socket return 'iot_sensor,hostname={},type=temperature value={}'.format( socket.gethostname(), temperature) """ Read temperature every minute; distinct_until_changed - produce only if temperature change """ data = rx \ .interval(period=timedelta(seconds=60)) \ .pipe(ops.map(lambda t: sensor_temperature()), ops.distinct_until_changed(), ops.map(lambda temperature: line_protocol(temperature))) _db_client = InfluxDBClient(url="http://localhost:9999", token="my-token", org="my-org", debug=True) """ Create client that writes data into InfluxDB """ _write_api = _db_client.write_api(write_options=WriteOptions(batch_size=1)) _write_api.write(org="my-org", bucket="my-bucket", record=data) """ Call after terminate a script """ atexit.register(on_exit, _db_client, _write_api)
import rx from rx import operators as ops rx.from_(["Alpha", "Theta", "Kappa", "Beta", "Gamma", "Delta", "Epsilon" ]).pipe(ops.map(lambda s: len(s)), ops.distinct_until_changed()).subscribe(lambda i: print(i)) print() print('-' * 20) rx.from_([ "Alpha", "Theta", "Kappa", "Beta", "Gamma", "Delta", "Epsilon" ]).pipe( ops.distinct_until_changed(lambda s: len(s))).subscribe(lambda i: print(i))
def create(): return xs.pipe(ops.distinct_until_changed(lambda x: _raise(ex)))
def create(): return rx.never().pipe(ops.distinct_until_changed())
def on_mouse_move(self) -> Observable: return self.observe("position").pipe( ops.distinct_until_changed(), ops.map(lambda p: MouseMoveEvent(self.context, p)))
def create(): return xs.pipe( ops.distinct_until_changed(comparer=lambda x, y: False) )
def create(): return xs.pipe(ops.distinct_until_changed(lambda x: x % 2))
def on_button_release(self, button: MouseButton) -> Observable: return self.observe("buttons").pipe( ops.map(lambda b: b & button), ops.distinct_until_changed(), ops.pairwise(), ops.filter(lambda b: b[0] == button and b[1] != button))
def on_style_change(self) -> Observable: return self._on_style_change.pipe(ops.distinct_until_changed())
def create(): return xs.pipe( ops.distinct_until_changed(comparer=lambda x, y: _raise(ex)), )