def scan(source: Observable) -> Observable: """Partially applied scan operator. Applies an accumulator function over an observable sequence and returns each intermediate result. Examples: >>> scanned = scan(source) Args: source: The observable source to scan. Returns: An observable sequence containing the accumulated values. """ def factory(scheduler): nonlocal source has_accumulation = [False] accumulation = [None] def projection(x): if has_accumulation[0]: accumulation[0] = accumulator(accumulation[0], x) else: accumulation[0] = accumulator(seed, x) if has_seed else x has_accumulation[0] = True return accumulation[0] return source.pipe(ops.map(projection)) return defer(factory)
def execute(self, channel_value: str, profile_data: List[Tuple[int, int]]) -> Observable: _LOG.debug("SetSpeedProfileInteractor.execute()") # pylint: disable=not-callable return rx.defer(lambda _: rx.just( self._kraken_repository.set_speed_profile(channel_value, profile_data)))
def set_led_status(self, driver: X52Driver, led_status: Union[X52ColoredLedStatus, X52LedStatus], attr_name: str) -> Observable: _LOG.debug("X52DriverInteractor.set_led_status()") return rx.defer(lambda _: rx.just( self._x52_repository.set_led_status(driver, led_status, attr_name)) )
def create(): def defer(scheduler): invoked[0] += 1 xs[0] = scheduler.create_cold_observable( on_next(100, scheduler.clock), on_error(200, ex)) return xs[0] return rx.defer(defer)
def _if_then(condition: Callable[[], bool], then_source: Observable, else_source: Observable = None) -> Observable: """Determines whether an observable collection contains values. Example: 1 - res = rx.if_then(condition, obs1) 2 - res = rx.if_then(condition, obs1, obs2) Args: condition: The condition which determines if the then_source or else_source will be run. then_source: The observable sequence or Promise that will be run if the condition function returns true. else_source: [Optional] The observable sequence or Promise that will be run if the condition function returns False. If this is not provided, it defaults to rx.empty Returns: An observable sequence which is either the then_source or else_source. """ else_source = else_source or rx.empty() then_source = rx.from_future(then_source) if is_future(then_source) else then_source else_source = rx.from_future(else_source) if is_future(else_source) else else_source def factory(_: abc.Scheduler): return then_source if condition() else else_source return rx.defer(factory)
def export_geometry(geometry, i, geometry_count): geometry_description = str(i + 1).zfill(len(str(geometry_count))) return defer( lambda _: _export_geometry( geometry, geometry_description=geometry_description ) )
def set_band_names(band_names: list, files: Union[str, list]) -> Observable: def action(): set_band_metadata('BAND_NAME', band_names, files) return defer(lambda _: gdal_queue.enqueue( from_callable(action), retries=3, description='set_band_names({}, {})'.format(band_names, files)))
def set_mfd_profile_name_line(self, driver: X52Driver, name: str, clear_mfd: bool = False) -> Observable: _LOG.debug("X52DriverInteractor.set_mfd_line3()") return rx.defer(lambda _: rx.just( self._x52_repository.set_mfd_line3(driver, name[:_X52_MFD_LINE_SIZE ], clear_mfd)))
def set_date_time(self, driver: X52Driver, use_local_time: bool, use_24h: Tuple[bool, bool, bool], clock2_offset: datetime.timedelta, clock3_offset: datetime.timedelta, date_format: X52DateFormat) -> Observable: _LOG.debug("X52DriverInteractor.set_date_time()") return rx.defer(lambda _: rx.just( self._x52_repository. set_date_time(driver, use_local_time, use_24h, clock2_offset, clock3_offset, date_format)))
def enqueue(credentials, queue: WorkQueue, mapper: Mapper, description: str = None, retries: int = 0): return rx.pipe( flat_map(lambda value: queue.enqueue(observable=defer(lambda _: mapper( value)), group=str(credentials), description=description, retries=retries)))
def _case(mapper, sources, default_source=None) -> Observable: default_source = default_source or empty() def factory(_) -> Observable: try: result = sources[mapper()] except KeyError: result = default_source result = from_future(result) if is_future(result) else result return result return defer(factory)
def build_vrt(destination: str, files: Union[str, list]) -> Observable: def action(): if isinstance(files, str): files_ = glob(files) else: files_ = files gdal.SetConfigOption('VRT_SHARED_SOURCE', '0') vrt = gdal.BuildVRT(destination, files_) if vrt: vrt.FlushCache() return defer(lambda _: gdal_queue.enqueue(from_callable(action), retries=3, description='build_vrt({}, {})'. format(destination, files)))
def on_next(value): def accumulate(): has_accumulator_value = accumulator_value[0] is not NotSet if has_accumulator_value: acc_source = accumulator(accumulator_value[0], value) return from_future(acc_source) if is_future( acc_source) else acc_source else: return of(value) accumulator_source = defer(lambda _: accumulate()) if not active[0]: active[0] = True subscribe(accumulator_source) else: queue.append(accumulator_source)
def enqueue(credentials, queue: WorkQueue, mapper: Mapper, description: str = None, retries: int = 0): def mapper_to_observable(value): ee.InitializeThread(credentials) return mapper(value) return rx.pipe( flat_map(lambda value: queue.enqueue(observable=defer( lambda _: mapper_to_observable(value)), group=str(credentials), description=description, retries=0)), retry(credentials, retries, description))
def _case( mapper: Callable[[], Any], sources: Mapping, default_source: Optional[Union[Observable, Future]] = None) -> Observable: default_source = default_source or empty() def factory(_) -> Observable: try: result = sources[mapper()] except KeyError: result = default_source result = from_future(result) if is_future(result) else result return result return defer(factory)
def set_band_names(band_names: list, files: Union[str, list]) -> Observable: def action(): if isinstance(files, str): files_ = [files] else: files_ = files globbed_files = [] for f in files_: globbed_files += glob(f) for f in globbed_files: ds = gdal.Open(f, GA_Update) for i in range(0, len(band_names)): band = ds.GetRasterBand(i + 1) band.SetMetadata({'BAND_NAME': band_names[i]}) ds.FlushCache() return defer(lambda _: gdal_queue.enqueue( from_callable(action), retries=3, description='set_band_names({}, {})'.format(band_names, files)))
def timestamp(source: Observable) -> Observable: """Records the timestamp for each value in an observable sequence. Examples: >>> timestamp(source) Produces objects with attributes `value` and `timestamp`, where value is the original value. Args: source: Observable source to timestamp. Returns: An observable sequence with timestamp information on values. """ def factory(scheduler_=None): _scheduler = scheduler or scheduler_ or TimeoutScheduler.singleton() mapper = operators.map(lambda value: Timestamp(value=value, timestamp=_scheduler.now)) return source.pipe(mapper) return defer(factory)
def test_ref_count_notconnected(self): disconnected = [False] count = [0] def factory(scheduler): count[0] += 1 def create(obs, scheduler=None): def func(): disconnected[0] = True return func return rx.create(create) xs = rx.defer(factory) subject = MySubject() conn = ConnectableObservable(xs, subject) refd = conn.pipe(ops.ref_count()) dis1 = refd.subscribe() self.assertEqual(1, count[0]) self.assertEqual(1, subject.subscribe_count) assert not disconnected[0] dis2 = refd.subscribe() self.assertEqual(1, count[0]) self.assertEqual(2, subject.subscribe_count) assert not disconnected[0] dis1.dispose() assert not disconnected[0] dis2.dispose() assert disconnected[0] disconnected[0] = False dis3 = refd.subscribe() self.assertEqual(2, count[0]) self.assertEqual(3, subject.subscribe_count) assert not disconnected[0] dis3.dispose() assert disconnected[0]
def timestamp(source: Observable) -> Observable: """Records the timestamp for each value in an observable sequence. Examples: >>> timestamp(source) Produces objects with attributes `value` and `timestamp`, where value is the original value. Args: source: Observable source to timestamp. Returns: An observable sequence with timestamp information on values. """ def factory(scheduler_=None): _scheduler = scheduler or scheduler_ or timeout_scheduler mapper = operators.map(lambda value: Timestamp(value=value, timestamp=_scheduler.now)) return source.pipe(mapper) return defer(factory)
def repeat(source: Observable) -> Observable: """Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. Examples: >>> repeated = source.repeat() >>> repeated = source.repeat(42) Args: source: The observable source to repeat. Returns: The observable sequence producing the elements of the given sequence repeatedly. """ if repeat_count is None: gen = infinite() else: gen = range(repeat_count) return rx.defer(lambda _: rx.concat_with_iterable(source for _ in gen))
def create(): def defer(scheduler): invoked[0] += 1 raise Exception(ex) return rx.defer(defer)
def execute(self) -> Observable: _LOG.debug("GetStatusInteractor.execute()") return rx.defer( lambda _: rx.just(self._kraken_repository.has_supported_kraken()))
def execute(self) -> Observable: _LOG.debug("GetLightingModesInteractor.execute()") # pylint: disable=not-callable return rx.defer(lambda _: rx.just(self._kraken_repository.get_lighting_modes()))
def execute(self) -> Observable: return rx.defer(lambda _: rx.just(self._check_new_version()))
def execute(self, system_info: SystemInfo) -> Observable: return rx.defer(lambda _: rx.just( self._dmi_decode_repository.refresh(system_info)))
def execute(self) -> Observable: _LOG.debug("CheckNewVersionInteractor.execute()") return rx.defer(lambda _: rx.just(self._check_new_version()))
def execute(self, lighting_settings: LightingSettings) -> Observable: _LOG.debug("SetLightingInteractor.execute()") # pylint: disable=not-callable return rx.defer(lambda _: rx.just( self._kraken_repository.set_lighting_mode(lighting_settings)))
def execute(self, system_info: SystemInfo) -> Observable: return rx.defer(lambda _: rx.just( self._sys_devices_cache_repository.refresh(system_info)))
def execute(self) -> Observable: LOG.debug("GetStatusInteractor.execute()") return rx.defer(lambda _: rx.just(self._kraken_repository.get_status()))
def execute(self) -> Observable: _LOG.debug("HasSupportedKrakenInteractor.execute()") # pylint: disable=not-callable return rx.defer( lambda _: rx.just(self._kraken_repository.has_supported_kraken()))
import rx x = 1 y = 5 integers = rx.defer(lambda i: rx.range(x, y)) integers.subscribe(lambda i: print(i)) print("\nSetting y = 10\n") y = 10 integers.subscribe(lambda i: print(i))