def test_oneshot_timer_timespan_observer_throws(self): scheduler1 = TestScheduler() xs = rx.timer(11) xs.subscribe(lambda x: _raise("ex"), scheduler=scheduler1) self.assertRaises(RxException, scheduler1.start) scheduler2 = TestScheduler() ys = rx.timer(1, period=None) ys.subscribe(on_completed=lambda: _raise("ex"), scheduler=scheduler2) self.assertRaises(RxException, scheduler2.start)
def create(): def mapper(xy): x, y = xy return "{}{}".format(x.value, y.value) return xs.pipe( ops.join( ys, lambda x: rx.timer(x.interval), lambda y: rx.timer(y.interval), ), ops.map(mapper), )
def create(): def mapper(xy): x, y = xy return "{}{}".format(x.value, y.value) return xs.pipe( ops.join( ys, lambda x: rx.timer(x.interval), lambda y: rx.timer(y.interval).pipe(ops.flat_map(rx.throw(ex) if y.value == "tin" else rx.empty())), ), ops.map(mapper), )
def create(): def mapper(xy): x, y = xy return "{}{}".format(x.value, y.value) return xs.pipe( ops.join( ys, lambda x: rx.timer(x.interval), lambda y: rx.timer(y.interval), ), ops.map(mapper), )
def create(): def mapper(x_yy): x, yy = x_yy return yy.pipe(ops.map(lambda y: '{}{}'.format(x.value, y.value))) return xs.pipe( ops.group_join( ys, lambda x: rx.timer(x.interval), lambda y: rx.timer(y.interval), ), ops.flat_map(mapper), )
def create(): def mapper(x_yy): x, yy = x_yy return yy.pipe(ops.map(lambda y: '{}{}'.format(x.value, y.value))) return xs.pipe( ops.group_join( ys, lambda x: rx.timer(x.interval), lambda y: rx.timer(y.interval).pipe( ops.flat_map(rx.throw(ex) if y.value == "tin" else rx.empty())), ), ops.flat_map(mapper), )
def create(): def mapper(x_yy): x, yy = x_yy return yy.pipe( ops.map(lambda y: '{}{}'.format(x.value, y.value))) return xs.pipe( ops.group_join( ys, lambda x: rx.timer(x.interval), lambda y: rx.timer(y.interval), ), ops.flat_map(mapper), )
def init_buttons(self): self.buttons = {} colStream = rx.create(self.observeColPins(COL_PINS)) rowStream = rx.create(self.observeRowPins(ROW_PINS)) keyStream = rowStream.pipe( ops.join( colStream, lambda l: rx.timer(.01), lambda r: rx.timer(.01) ), ops.map(self.findKey), ) keyStream.subscribe(on_next=lambda i: self.on_compose(i))
def create(): def mapper(xy): x, y = xy return "{}{}".format(x.value, y.value) return xs.pipe( ops.join( ys, lambda x: rx.timer(x.interval), lambda y: rx.timer(y.interval).pipe( ops.flat_map( rx.throw(ex) if y.value == "tin" else rx.empty())), ), ops.map(mapper), )
def create(): def mapper(x_yy): x, yy = x_yy return yy.pipe( ops.map(lambda y: '{}{}'.format(x.value, y.value))) return xs.pipe( ops.group_join( ys, lambda x: rx.timer(x.interval), lambda y: rx.timer(y.interval).pipe( ops.flat_map( rx.throw(ex) if y.value == "tin" else rx.empty())), ), ops.flat_map(mapper), )
def timeout_check(process: subprocess.Popen, timeout: float, ct: CancellationToken) -> rx.Observable: """Kills the given process after timeout has passed. Args: process: process to be killed timeout: termination time in seconds ct: CancellationToken Return: rx.Observable that fires only a single dictionary after the timeout has passed. """ return rx.timer(timeout).pipe( ops.do_action( # Request cancellation so all simulation processes that # share the same cancellation_token are also stopped. # TODO not working as intended if simulation is short enough # to stop before max_time has elapsed. Maybe let caller # implement its own timeout check when multiple processes # are being run. on_next=lambda _: ct.request_cancellation()), ops.map( lambda _: { # sutils.kill_process returns None, which can be casted to bool MCERD.IS_RUNNING: bool(sutils.kill_process(process)), MCERD.MSG: MCERD.SIM_TIMEOUT }), ops.first())
def test_oneshot_timer_date_observer_throws(self): scheduler = TestScheduler() date = scheduler.to_datetime(250.0) xs = rx.timer(date) xs.subscribe(lambda x: _raise("ex"), scheduler=scheduler) self.assertRaises(RxException, scheduler.start)
def test_spot_instance_checker_through_404(requests_mock): requests_mock.get(INSTANCE_ACTION_URL, text="test", status_code=404) o = spot_instance_check_observable(0.1).pipe(ops.merge(rx.timer(0.5)), ops.first()) def on_next(x): assert x == 0 o.subscribe(on_next=on_next, scheduler=CurrentThreadScheduler())
def run(self): '''Polls the Twitch API periodically.''' logger.info('Starting Twitch poller...') logger.info('polling_interval: %d' % (self.polling_interval)) def poll(it): streams = self.get_streams() self.merge_streams(streams) self.disposer = timer(0, self.polling_interval).subscribe(on_next=poll)
def test_spot_instance_checker_terminate(requests_mock): body = {"action": "terminate", "time": "2017-09-18T08:22:00Z"} requests_mock.get(INSTANCE_ACTION_URL, json=body) o = spot_instance_check_observable(0.1).pipe(ops.merge(rx.timer(0.5)), ops.first()) def on_next(x): assert isinstance(x, CheckerMessage) assert x.checker_type == "spot_instance" assert x.body == f'"spot/instance-action": {body}' o.subscribe(on_next=on_next, scheduler=CurrentThreadScheduler())
def test_spot_instance_checker_observer(requests_mock): with mock.patch("igata.checkers.aws.observers.logger.info") as mock_method: requests_mock.get(INSTANCE_ACTION_URL, json={ "action": "terminate", "time": "2017-09-18T08:22:00Z" }) o = spot_instance_check_observable(0.1).pipe( ops.merge(rx.timer(0.3)), ops.take(2), ops.filter(lambda x: isinstance(x, CheckerMessage))) o.subscribe(CheckersObserver(), scheduler=CurrentThreadScheduler()) mock_method.assert_called_once()
def run(self): #On Each Minute async def on_minute(bar): symbol = bar.symbol print("Close: ", bar.close) print("Open: ", bar.open) print("Low: ", bar.low) print(symbol) #Check for Doji if bar.close > bar.open and bar.open - bar.low > 0.1: print('Buying on Doji!') respSO = [] self.submitMarketOrder(1, symbol, 'buy', respSO) # check position and take profit, # Get the rate at which the market order was filled # place a limit order at 1% higher than market order deal rate positions = self.alpaca.list_positions() for position in positions: if(position.side == 'long'): self.submitLimitOrder(position.qty, symbol, 'sell', position.avg_entry_price + (position.avg_entry_price * 0.1), respSO) # Use rx timer to get prices every 5 minutes # Subscribe to Microsoft Stock rx.timer(5.0).subscribe(lambda t: on_minute(self.alpaca.get_barset('MSFT', 'minute', 1)))
def delay_subscription(source: Observable) -> Observable: """Time shifts the observable sequence by delaying the subscription. Exampeles. >>> res = source.delay_subscription(5) Args: source: Source subscription to delay. Returns: Time-shifted sequence. """ def mapper(_) -> Observable: return rx.empty() return source.pipe( ops.delay_with_mapper(rx.timer(duetime, scheduler=scheduler), mapper))
def create(): def right_duration_mapper(y): if len(y.value) >= 0: raise Exception(ex) else: return rx.empty() def mapper(x_yy): x, yy = x_yy return yy.pipe(ops.map(lambda y: '{}{}'.format(x.value, y.value))) return xs.pipe( ops.group_join( ys, lambda x: rx.timer(x.interval), right_duration_mapper, ), ops.flat_map(mapper), )
def create(): def right_duration_mapper(y): if len(y.value) >= 0: raise Exception(ex) else: return rx.empty() def mapper(xy): x, y = xy return "{}{}".format(x.value, y.value) return xs.pipe( ops.join( ys, lambda x: rx.timer(x.interval), right_duration_mapper, ), ops.map(mapper), )
def delay_subscription(source: Observable) -> Observable: """Time shifts the observable sequence by delaying the subscription. Exampeles. >>> res = source.delay_subscription(5) Args: source: Source subscription to delay. Returns: Time-shifted sequence. """ def mapper(_) -> Observable: return rx.empty() return source.pipe( ops.delay_with_mapper(rx.timer(duetime, scheduler=scheduler), mapper) )
def create(): def right_duration_mapper(y): if len(y.value) >= 0: raise Exception(ex) else: return rx.empty() def mapper(xy): x, y = xy return "{}{}".format(x.value, y.value) return xs.pipe( ops.join( ys, lambda x: rx.timer(x.interval), right_duration_mapper, ), ops.map(mapper), )
def create(): def right_duration_mapper(y): if len(y.value) >= 0: raise Exception(ex) else: return rx.empty() def mapper(x_yy): x, yy = x_yy return yy.pipe( ops.map(lambda y: '{}{}'.format(x.value, y.value))) return xs.pipe( ops.group_join( ys, lambda x: rx.timer(x.interval), right_duration_mapper, ), ops.flat_map(mapper), )
def running_check(process: subprocess.Popen, first_check: float, interval: float) -> rx.Observable: """Periodically checks if the given process is running. Args: process: process to be monitored first_check: seconds until the first check interval: interval between each check Return: rx.Observable that fires dictionaries after each check """ return rx.timer(first_check, interval).pipe( # TODO change this to run at an increasing interval, i.e: # - first check after 0.0 seconds, # - second check after 0.2 seconds, # - third after 1.0, ... etc. # MCERD is likely to crash early (?) so it makes sense to # run the check more frequently at the beginning. ops.map(lambda _: {MCERD.IS_RUNNING: MCERD.is_running(process)}), ops.take_while(lambda x: x[MCERD.IS_RUNNING], inclusive=True))
def doRx(): def subscribe(a: Observer, scheduler=None): print(threading.current_thread().name) a.on_next(1) a.on_completed() def mapper(value): print("立即执行") return value + 1 create = rx.timer(5) # create = rx.create(subscribe) pipe = create.pipe( ops.map(mapper) ) def on_next(value): print(threading.current_thread().name) print(value) pipe.subscribe(on_next)
def cancellation_check(process: subprocess.Popen, interval: float, ct: CancellationToken) -> rx.Observable: """Kills the given process if cancellation is requested from the CancellationToken. Args: process: process that will killed if cancellation is requested interval: cancellation check interval in seconds ct: CancellationToken that is being checked Return: rx.Observable that fires a single dictionary after cancellation is requested """ return rx.timer(0, interval).pipe( ops.map(lambda _: MCERD._stop_if_cancelled(process, ct)), ops.first(lambda x: not x), ops.map(lambda _: { MCERD.IS_RUNNING: False, MCERD.MSG: MCERD.SIM_STOPPED }), )
def closing(x): return rx.timer(x)
def _interval(period, scheduler: typing.Scheduler = None) -> Observable: return timer(period, period, scheduler)
import time import rx from rx import operators as ops # https://www.youtube.com/watch?v=HLtZek0OhQA&list=PL1A418Fn3fORAnrEIwMiP04vsLzzusEjK&index=6 rx.from_(['abc', 'def', 'ghi']).subscribe(print) # abc # def # ghi print() # 1초마다 인터벌 발생 (시간의 단위는 초이다.) rx.interval(1).pipe( # 30 초가 될때까지 동작 ops.take_until(rx.timer(30)), # 3초마다 이벤트 출력 ops.sample(3)).subscribe(print) # 1 # 4 # 7 # 10 # 13 # 16 # 19 # 22 # 25 # 28 time.sleep(40)
def closing(): curr = window[0] window[0] += 1 return rx.timer(curr * 100)
def closing(x): return rx.timer(x)
def closings(): w = window[0] window[0] += 1 return rx.timer(w * 100)
def create(): return rx.timer(duetime=300)
def create(): return rx.timer(-1)
def create(): return rx.timer(1000)
# 위와 다른 점: args 로 생성한다. print('--') # 마블에서 옵저버블 생성 하기 # 타이밍을 제어 할 수 있다. from rx.testing import marbles, TestScheduler scheduler = TestScheduler() ts = 0.1 rx.from_marbles('--(a1)-(b2)---(c3)|', timespan=ts).subscribe(print_value) rx.from_marbles('(a6)---(b5)(c4)|', timespan=ts).subscribe(print_value) time.sleep(2) print('--') # Interval 을 이용한 옵저버블 생성 rx.interval(0.3).pipe(ops.take_until(rx.timer(3))).subscribe(print_value) time.sleep(4) print('--') # 버퍼 print('-- buffer') rx.from_(range(2000)).pipe(ops.buffer( rx.interval(0.001))).subscribe(on_next=lambda buffer: print( '# of items in buffer {}'.format(len(buffer)))) time.sleep(2) print('-- buffer with count') rx.from_(range(10)).pipe(ops.buffer_with_count(3)).subscribe(print_value) print('-- buffer with time') rx.interval(1).pipe(
def _interval(period, scheduler: Optional[typing.Scheduler] = None) -> Observable: return timer(period, period, scheduler)
).subscribe(print_count) groups = rx.from_(range(3)).pipe( ops.group_by(key_selector) ) groups.subscribe(subscribe_group_observable) # Sample: A way to grab items and emit latest values at certain points print('-- Sample') # 10 ms 마다 인터벌 발생 (시간의 단위는 초이다.) rx.interval(0.01).pipe( # 1초 동안 동작 ops.take_until(rx.timer(1)), # 100ms 마다 이벤트 출력 (현재 받은 최신값) ops.sample(0.1) ).subscribe(print) time.sleep(2) # Max print('-- Max') rx.from_([1, 2, 3, 4, 12, 3, 3, -10]).pipe( ops.max(lambda x, y: x - y) ).subscribe(print)
def closing(): curr = window[0] window[0] += 1 return rx.timer(curr * 100)
from datetime import datetime from rx import timer, operators as op """this method will emit the values in sequence after the timout is done. :parameter duetime: time after witch it should emit the first value. :return it will return an observable with values emitted after duetime. """ timer(5.0, 10).pipe(op.map(lambda i: i * i)).subscribe(lambda x: print( "value is {}, current time is {}".format(x, datetime.now().time()))) print("start time is {}".format(datetime.now().time())) input("press any key to exit\n") # result # start time is 19:55:42.269061 # press any key to exit # value is 0, current time is 19:55:47.278135 # value is 1, current time is 19:55:57.273175 # value is 4, current time is 19:56:07.286588 # value is 9, current time is 19:56:17.273586 # value is 16, current time is 19:56:27.285112
def create(): return rx.timer(duetime=300, period=300)
class __Timer: ticks_per_second = 50 ticks = rx.subject.Subject( ) # Subscribe to this subject to receive the globally synchronized tick updates timer = rx.timer(0, 1.0 / ticks_per_second)
def closings(): w = window[0] window[0] += 1 return rx.timer(w * 100)