def test_range_double_subscribe(self): scheduler = TestScheduler() obs = rx.range(1, 4) results = scheduler.start(lambda: obs.pipe(ops.concat(obs))) assert results.messages == [on_next(200, 1), on_next(200, 2), on_next(200, 3), on_next(200, 1), on_next(200, 2), on_next(200, 3), on_completed(200)]
def _solve(print: t_print = print) -> bool: limit = 1000 total = rx.range(limit) \ .pipe( ops.filter(lambda n: n % 3 == 0 or n % 5 == 0), ops.sum(), ).run() print(total) return True
def _solve_rx(print=print): """Benchmark: 15/1_000_000 takes 30s """ print(f'\n\n\n***************') turns = 15 game_count = 1_000_000 #scheduler=rx.scheduler.CurrentThreadScheduler() scheduler = rx.scheduler.ThreadPoolScheduler(4) wins = rx.range(0,game_count,scheduler=scheduler)\ .pipe( ops.filter(lambda i: play_w(turns)), ops.count() ).run() print(f' Max prize: {math.floor(game_count/wins)}') print(f"Not done") return False
# then create a ThreadPoolScheduler with that number of threads optimal_thread_count = multiprocessing.cpu_count() + 1 pool_scheduler = ThreadPoolScheduler(optimal_thread_count) # Create TASK 1 rx.from_(["Alpha", "Beta", "Gamma", "Delta", "Epsilon" ]).pipe(ops.map(lambda s: intense_calculation(s)), ops.subscribe_on(pool_scheduler)).subscribe( on_next=lambda s: print("TASK 1: {0} {1}".format( current_thread().name, s)), on_error=lambda e: print(e), on_completed=lambda: print("TASK 1 done!")) # Create TASK 2 rx.range(1, 10).pipe(ops.map(lambda s: intense_calculation(s)), ops.subscribe_on(pool_scheduler)).subscribe( on_next=lambda i: print("TASK 2: {0} {1}".format( current_thread().name, i)), on_error=lambda e: print(e), on_completed=lambda: print("TASK 2 done!")) # Create TASK 3, which is infinite rx.interval(1.0).pipe(ops.map(lambda i: i * 100), ops.observe_on(pool_scheduler), ops.map(lambda s: intense_calculation(s))).subscribe( on_next=lambda i: print("TASK 3: {0} {1}".format( current_thread().name, i)), on_error=lambda e: print(e)) input("Press any key to exit\n")
def test_run_range(self): result = rx.range(42).run() assert result == 41
from rx import from_, range, operators as ops from threading import current_thread import multiprocessing import time import random def intense_calculation(value): # sleep for a random short duration between 0.5 to 2.0 seconds to simulate a long-running calculation time.sleep(random.randint(5,20) * .1) return value # Create Process 1 from_(["Alpha","Beta","Gamma","Delta","Epsilon"]).pipe( ops.map(lambda s: intense_calculation(s)) ).subscribe(on_next=lambda s: print("PROCESS 1: {0} {1}".format(current_thread().name, s)), on_error=lambda e: print(e), on_completed=lambda: print("PROCESS 1 done!")) # Create Process 2 range(1,10).pipe( ops.map(lambda s: intense_calculation(s)) ).subscribe(on_next=lambda i: print("PROCESS 2: {0} {1}".format(current_thread().name, i)), on_error=lambda e: print(e), on_completed=lambda: print("PROCESS 2 done!")) input("Press any key to exit\n")
from configs.config import GlobalConfig GlobalConfig.initialize_global_configuration() from sink.save_data_sink import SaveDataSink import pandas as pd import rx from rx import operators from rx import scheduler sink = SaveDataSink("test_save", "value", None) rx.range(1, 100, 1, scheduler=scheduler.ImmediateScheduler()).pipe( operators.do_action(lambda x: print(x)), operators.map(lambda x: pd.DataFrame([{"value": x}])), ).subscribe(sink) print("Done")
import rx from rx import operators as ops from random import randint three_emissions = rx.range(0, 3).pipe(ops.publish()) three_emissions_ints = three_emissions.pipe( ops.map(lambda i: randint(1, 10000)) ) three_emissions_ints.subscribe(lambda s: print("Subscriber 1: {0}".format(s))) three_emissions_ints.subscribe(lambda s: print("Subscriber 2: {0}".format(s))) three_emissions.connect() # Subscriber 1 과 2 가 다른 랜덤 숫자를 받는다. # 같은 랜덤 숫자를 받을 수 없는가?
def create(): return rx.range(0, 10, 2)
async def go(loop): scheduler = AsyncIOScheduler(loop) ai = rx.range(0, 10, scheduler=scheduler).pipe(to_async_iterable()) async for x in ai: print("got %s" % x)
# This method is used to create an observable. rx.create() # observable 을 생성할 때 사용 # This observable will not output anything and directly emit the complete state. rx.empty() # 해당 observable 은 아무것도 output 하지 않고 즉시 완료 상태를 발생시킨다. # This method creates an observable that will never reach the complete state. rx.never() # 완료 상태에 도달할 수 없는 observable 을 생성한다. rx.throw() rx.interval() rx.from_() rx.interval() rx.just() rx.range() rx.repeat_value() rx.start() rx.timer() """Mathematical""" op.average() op.concat() op.count() op.max() op.min() op.reduce() op.sum() """Transformation""" op.buffer()
def test_run_range_to_iterable(self): result = rx.range(42).pipe(ops.to_iterable()).run() assert list(result) == list(range(42))
def test_run_range(self): result = rx.range(42).run() assert result == 41
time.sleep(random.randint(5, 20) * .1) return value # calculate number of CPU's, then create a ThreadPoolScheduler with that number of threads optimal_thread_count = multiprocessing.cpu_count() pool_scheduler = ThreadPoolScheduler(optimal_thread_count) # Create Process 1 rx.of("Alpha", "Beta", "Gamma", "Delta", "Epsilon").pipe(ops.map(lambda s: intense_calculation(s)), ops.subscribe_on(pool_scheduler)).subscribe( on_next=lambda s: logging.info(f"PROCESS 1: {s}"), on_error=lambda e: logging.error(e), on_completed=lambda: logging.info("PROCESS 1 done!"), scheduler=pool_scheduler) # Create Process 2 rx.range(1, 10).pipe(ops.map(lambda s: intense_calculation(s)), ops.subscribe_on(pool_scheduler)).subscribe( on_next=lambda i: logging.info(f"PROCESS 2: {i}"), on_error=lambda e: logging.error(e), on_completed=lambda: logging.info("PROCESS 2 done!")) # Create Process 3, which is infinite rx.interval(1).pipe(ops.map(lambda i: i * 100), ops.observe_on(pool_scheduler), ops.map(lambda s: intense_calculation(s))).subscribe( on_next=lambda i: logging.info(f"PROCESS 3: {i}"), on_error=lambda e: logging.error(e)) input("Press any key to exit\n")
import rx from rx import operators as ops from random import randint three_emissions = rx.range(0, 3) three_emissions_ints = three_emissions.pipe( ops.map(lambda i: randint(1, 10000)), ops.publish() ) three_emissions_ints.subscribe(lambda s: print("Subscriber 1: {0}".format(s))) three_emissions_ints.subscribe(lambda s: print("Subscriber 2: {0}".format(s))) three_emissions_ints.connect() # publish 이전에 랜덤 숫자를 생성하고 두 Subscriber 에 공유 한다.
import rx from rx import operators as ops pipe = rx.range(1, 11) \ .pipe(ops.filter(lambda i: i % 2 == 0), ops.filter(lambda i: i < 3), ops.map(lambda i: i + i), ops.map(lambda i: i ** i), ops.average(lambda x: x + x), ops.sum()) pipe.subscribe(lambda x: print("value is {0}".format(x)))
def create(): return rx.range(-10, 5)
from rx import range test = range(0, 11) test.subscribe(lambda x: print("The value is {0}".format(x)), on_error=lambda e: print("Error : {0}".format(e)), on_completed=lambda: print("Job Done!"))
def create(): return rx.range(5)
from rx import range """ this method will give range of integers based on the input given. :parameters start: the first value from which the range will start stop: optional, the last value of the range to stop. :return this will return an observable with integer value based on the input given. """ my_range = range(0, 10) my_range.subscribe(lambda i: print("value is {}".format(i)), lambda e: print("error : {}".format(e)), lambda: print("onComplete")) # result # value is 0 # value is 1 # value is 2 # value is 3 # value is 4 # value is 5 # value is 6 # value is 7 # value is 8 # value is 9 # onComplete # # Process finished with exit code 0
from rx import range, operators as op test = range(1, 11) sub1 = test.pipe( op.filter(lambda s: s % 2 == 0), # next x -> 2, 4, 6, 8, 10 op.reduce(lambda acc, x: acc + x, 3) # acc: 3, x: 2 -> 5 # acc: 5, x: 4 -> 9 # acc: 9, x: 6 -> 15 # acc: 15, x: 8 -> 23 # acc: 23, x: 10 -> 33 ) sub1.subscribe(lambda x: print("This value {}".format(x)))
from rx import of, range, operators as op class MyObserver(Observer): def on_next(self, x): print("Got: %s" % x) def on_error(self, e): print("Got error: %s" % e) def on_completed(self): print("Sequence completed") print("------ observer ------") range(5).subscribe(MyObserver()) print("------ of ------") of(7, 8).pipe(op.map(lambda x: x * 3)).subscribe(print) of([7, 8]).pipe(op.map(lambda x: x * 3)).subscribe(print) print("------ map ------") range(10).pipe(op.map(lambda x: x * 2)).subscribe(print) print("------ map ------") range(10, 20, 2).pipe(op.map(lambda x: "%d" % (x * 2))).subscribe(print) print("------ merge ------") s1 = range(1, 5) s2 = of("abcde", "def") s1.pipe(op.merge(s2)).subscribe(print)
from rx import range, just # Using Observable.range() letters = range(1, 10) letters.subscribe(lambda value: print(value)) # Using Observable.just() greeting = just("Hello World!") greeting.subscribe(lambda value: print(value))
from threading import current_thread import rx from rx.scheduler import ThreadPoolScheduler from rx import operators as ops def intense_calculation(value): time.sleep(random.randint(5, 20) * 0.1) return value optimal_thread_count = multiprocessing.cpu_count() pool_scheduler = ThreadPoolScheduler(optimal_thread_count) rx.range(1, 10).pipe( ops.map(lambda i: i*100), ops.subscribe_on(pool_scheduler) ).subscribe( on_next=lambda i: print("PROCESS 1: {0}".format(i)), on_error=lambda e: print(e), on_completed=lambda: print("PROCESS 1 done!"), ) rx.of('Yeyy', 'uhuu', 'teste').pipe( ops.map(lambda s: len(s)), ops.subscribe_on(pool_scheduler) ).subscribe( on_next=lambda s: print("PROCESS 2: {0}".format(s)), on_error=lambda e: print(e), on_completed=lambda: print("PROCESS 2 done!"), )
# Example of a 'cold' Observable import rx from rx.concurrency import NewThreadScheduler import time def observer_function(value): time.sleep(1) print(value * value) rx.range(1, 100000, scheduler=NewThreadScheduler())\ .subscribe(observer_function) # As the observable runs in a separate thread need # ensure that the main thread does not terminate input('Press enter to finish')
# intenção de criar 3 processos # 1 processo rx.of("Alpha", "Beta", "Gamma", "Delta", "Epsilon").pipe( ops.map(lambda s: intense_calculation(s)), ops.subscribe_on(pool_scheduler)).subscribe( on_next=lambda i: print("processo 1: {} {}".format( current_thread().name, i)), on_error=lambda e: print("Erro identificado: {}".format(e)), on_completed=lambda: print("Fim do processo 1!")) # processo 2 rx.range(1, 10).pipe( ops.map(lambda s: intense_calculation(s)), ops.subscribe_on(pool_scheduler)).subscribe( on_next=lambda i: print("processo 2: {} {}".format( current_thread().name, i)), on_error=lambda e: print("Erro identificado: {}".format(e)), on_completed=lambda: print("Fim do processo 2!")) # processo 3 rx.interval(1).pipe( ops.map(lambda i: i * 100), ops.observe_on(pool_scheduler), ops.map(lambda s: intense_calculation(s))).subscribe( on_next=lambda i: print("processo 3: {} {}".format( current_thread().name, i)), on_error=lambda e: print("Erro identificado: {}".format(e))) input("Pressione alguma tecla para sair\n")
import rx from rx import operators as ops letters = rx.from_(["A", "B", "C", "D", "E", "F"]) numbers = rx.range(1, 5) letters.pipe(ops.zip(numbers), ops.map( lambda z: "{0}-{1}".format(z[0], z[1]))).subscribe(lambda i: print(i))
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))
def test_run_range_to_iterable(self): result = rx.range(42).pipe(ops.to_iterable()).run() assert list(result) == list(range(42))
import rx from rx import operators as ops import operator a = rx.of(1, 2, 3, 4) b = rx.of(2, 2, 4, 4) a.pipe( ops.zip(b), # returns a tuple with the items of a and b ops.map(lambda z: operator.mul(z[0], z[1])), ops.flat_map(lambda x: rx.range(0, x))).subscribe(print)
def create_job(self, driver: Driver): return rx.range(0, self.steps).pipe(ops.map(lambda _: driver.next_step()))
def create(): return rx.range(10, 15)