Пример #1
0
def _reduce(accumulator: Callable[[Any, Any], Any],
            seed: Any = NotSet) -> Callable[[Observable], Observable]:
    """Applies an accumulator function over an observable sequence,
    returning the result of the aggregation as a single element in the
    result sequence. The specified seed value is used as the initial
    accumulator value.

    For aggregation behavior with incremental intermediate results, see
    `scan()`.

    Examples:
        >>> res = reduce(lambda acc, x: acc + x)
        >>> res = reduce(lambda acc, x: acc + x, 0)

    Args:
        accumulator: An accumulator function to be
            invoked on each element.
        seed: Optional initial accumulator value.

    Returns:
        An operator function that takes an observable source and returns
        an observable sequence containing a single element with the
        final accumulator value.
    """

    if seed is not NotSet:
        initial = ops.start_with(seed)
        scanner = ops.scan(accumulator, seed=seed)

        return pipe(scanner, initial, ops.last())

    return pipe(ops.scan(accumulator), ops.last())
Пример #2
0
def _reduce(accumulator: Callable[[Any, Any], Any], seed: Any = NotSet) -> Callable[[Observable], Observable]:
    """Applies an accumulator function over an observable sequence,
    returning the result of the aggregation as a single element in the
    result sequence. The specified seed value is used as the initial
    accumulator value.

    For aggregation behavior with incremental intermediate results, see
    `scan()`.

    Examples:
        >>> res = reduce(lambda acc, x: acc + x)
        >>> res = reduce(lambda acc, x: acc + x, 0)

    Args:
        accumulator: An accumulator function to be
            invoked on each element.
        seed: Optional initial accumulator value.

    Returns:
        An operator function that takes an observable source and returns
        an observable sequence containing a single element with the
        final accumulator value.
    """


    if seed is not NotSet:
        initial = ops.start_with(seed)
        scanner = ops.scan(accumulator, seed=seed)

        return pipe(scanner, initial, ops.last())

    return pipe(ops.scan(accumulator), ops.last())
Пример #3
0
    def last(source: Observable) -> Observable:
        """Partially applied last operator.

        Returns the last element of an observable sequence that
        satisfies the condition in the predicate if specified, else
        the last element.

        Examples:
            >>> res = last(source)

        Args:
            source: Source observable to get last item from.

        Returns:
            An observable sequence containing the last element in the
            observable sequence that satisfies the condition in the
            predicate.
        """

        if predicate:
            return source.pipe(
                operators.filter(predicate),
                operators.last()
            )

        return last_or_default_async(source, False)
Пример #4
0
    def average(source: Observable) -> Observable:
        """Partially applied average operator.

        Computes the average of an observable sequence of values that
        are in the sequence or obtained by invoking a transform
        function on each element of the input sequence if present.

        Examples:
            >>> res = average(source)

        Args:
            source: Source observable to average.

        Returns:
            An observable sequence containing a single element with the
            average of the sequence of values.
        """

        if key_mapper:
            return source.pipe(operators.map(key_mapper), operators.average())

        def accumulator(prev, cur):
            return AverageValue(sum=prev.sum + cur, count=prev.count + 1)

        def mapper(s):
            if s.count == 0:
                raise Exception('The input sequence was empty')

            return s.sum / float(s.count)

        seed = AverageValue(sum=0, count=0)
        return source.pipe(operators.scan(accumulator, seed), operators.last(),
                           operators.map(mapper))
Пример #5
0
    def last(source: Observable) -> Observable:
        """Partially applied last operator.

        Returns the last element of an observable sequence that
        satisfies the condition in the predicate if specified, else
        the last element.

        Examples:
            >>> res = last(source)

        Args:
            source: Source observable to get last item from.

        Returns:
            An observable sequence containing the last element in the
            observable sequence that satisfies the condition in the
            predicate.
        """

        if predicate:
            return source.pipe(
                operators.filter(predicate),
                operators.last()
            )

        return last_or_default_async(source, False)
Пример #6
0
        def create():
            def predicate(x):
                if x < 4:
                    return x % 2 == 1
                else:
                    raise Exception(ex)

            return xs.pipe(_.last(predicate))
Пример #7
0
        def create():
            def predicate(x):
                if x < 4:
                    return x % 2 == 1
                else:
                    raise Exception(ex)

            return xs.pipe(_.last(predicate))
Пример #8
0
def file_with_path(
        credentials,
        path: str,
        retries: int = 5
) -> Observable:
    return _files_in_path(credentials, path, retries).pipe(
        last(),
        flat_map(lambda file: of(file) if file else throw(Exception('File {} does not exist.'.format(path)))),
    )
Пример #9
0
 def step(self):
     last_result = (rx.from_iterable(self.islands).pipe(
         ops.subscribe_on(NewThreadScheduler()),
         ops.flat_map(lambda island: island.epoch(self.epoch_length).pipe(
             ops.last())),
         ops.buffer_with_count(len(self.islands)),
     ).run())
     self.migration()
     self.update_cost(last_result)
Пример #10
0
def test_describe():
    source = [random.normalvariate(0.0, 1.0) for _ in range(200)]

    actual_result = []
    rx.from_(source).pipe(
        rs.math.dist.update(),
        ops.last(),
        rs.math.dist.describe(),
    ).subscribe(on_next=actual_result.append)
Пример #11
0
def delete_file_with_path(credentials, path: str, retries: int = 2):
    def delete(file):
        try:
            return delete_file(credentials, file, retries)
        except HttpError:
            logging.warning('Failed to delete file {} with path {}'.format(
                file, path))
            return empty()

    return _files_in_path(credentials, path,
                          retries).pipe(last(), filter(lambda file: file),
                                        flat_map(lambda file: delete(file)))
Пример #12
0
def create_folder_with_path(credentials, path: str):
    def create_if_missing(parent, name_file):
        name = name_file[0]
        file = name_file[1]
        if file:
            return of(file)
        else:
            return create_folder(credentials, parent, name)

    return zip(
        _path_elements(path),
        _files_in_path(credentials, path),
    ).pipe(merge_scan(create_if_missing, _root_folder), last())
Пример #13
0
def get_authorization_stream(request: OIDCRequest) -> Observable:
    response_params: Dict[str, Any] = {}

    # yapf: disable
    return just(request).pipe(
        op.flat_map(call_async(validate_redirect_uri)),
        op.flat_map(call_async(validate_response_type)),
        op.flat_map(call_async(validate_scope)),
        op.flat_map(select_flows),
        op.merge_all(),
        op.do_action(lambda x: response_params.update(asdict(x))),
        op.last(),
        op.map(lambda x: AuthorizationResponse(**response_params)))
Пример #14
0
    def open(self):
        print("WebSocket opened")
        self.write_message("connection opened")

        def _send_response(x):
            print(x)
            self.write_message(json.dumps(x))

        def _on_error(ex):
            print(ex)

        self.subject = Subject()
        self.subject.pipe(buffer(rx.interval(5.0)), last(),
                          flat_map(self.get_data)).subscribe(
                              on_next=_send_response, on_error=_on_error)
Пример #15
0
    def average(source: Observable) -> Observable:
        """Partially applied average operator.

        Computes the average of an observable sequence of values that
        are in the sequence or obtained by invoking a transform
        function on each element of the input sequence if present.

        Examples:
            >>> res = average(source)

        Args:
            source: Source observable to average.

        Returns:
            An observable sequence containing a single element with the
            average of the sequence of values.
        """

        if key_mapper:
            return source.pipe(
                operators.map(key_mapper),
                operators.average()
            )

        def accumulator(prev, cur):
            return AverageValue(sum=prev.sum+cur, count=prev.count+1)

        def mapper(s):
            if s.count == 0:
                raise Exception('The input sequence was empty')

            return s.sum / float(s.count)

        seed = AverageValue(sum=0, count=0)
        return source.pipe(
            operators.scan(accumulator, seed),
            operators.last(),
            operators.map(mapper)
        )
Пример #16
0
 def create():
     def predicate(x):
         return x % 2 == 1
     return xs.pipe(_.last(predicate))
Пример #17
0
 def create():
     return xs.pipe(_.last())
Пример #18
0
def delete_file_with_path(credentials, path: str, retries: int = 5):
    return _files_in_path(credentials, path, retries).pipe(
        last(),
        filter(lambda file: file),
        flat_map(lambda file: delete_file(credentials, file, retries=retries))
    )
"""Transformation"""
op.buffer()
op.group_by()
op.map()
op.scan()
# ...

"""Filtering"""
op.debounce()
op.distinct()
op.filter()
op.element_at()
op.first()
op.ignore_elements()
op.last()
op.skip()
op.skip_last()
op.take()
op.take_last()
# ...

"""Error Handling"""
op.catch()
op.retry()

"""Utility"""
op.delay()
op.materialize()
op.time_interval()
op.timeout()
Пример #20
0
def delete_file_with_path(credentials, path: str):
    return _files_in_path(credentials, path).pipe(
        last(), filter(lambda file: file),
        flat_map(lambda file: delete_file(credentials, file)))
Пример #21
0
        def create():
            def predicate(x):
                return x % 2 == 1

            return xs.pipe(_.last(predicate))
import rx
import rx.operators as ops

numbers = rx.from_([1, 2, 3, 4, 5, 6])
numbers.pipe(ops.last()).subscribe(
    on_next=lambda i: print("on_next {}".format(i)),
    on_error=lambda e: print("on_error: {}".format(e)),
    on_completed=lambda: print("on_completed"))
Пример #23
0
 def _last(source):
     if isinstance(source, rs.MuxObservable):
         return last_mux()(source)
     else:
         return ops.last()(source)
Пример #24
0
 def create():
     return xs.pipe(_.last())