def flat_map_thrice(self) -> None: v = 13 w = 29 x = 17 y = 11 t = (IO.now(v).flat_map(L(IO.now)(_ + w)).flat_map(L( IO.now)(_ + x)).flat_map(L(IO.now)(_ + y))) t.attempt.should.contain(v + w + x + y)
def _process_results(self, monitor, results: SearchResults): ''' returns True if a result was found to stop the find() in *_clean_done* ''' return ( results.choose(monitor) .map(L(self._add_link)(results.query, _)) .replace(True) .get_or_else(L(self._no_result)(results)) )
def window_state(ui_window: Ident, twindow: Window, layout: ViewTree) -> Do: window_id = yield TS.from_maybe(twindow.id, 'window_state: `{twindow}` has no id') native_window_e = yield TS.lift(window(window_id)) native_window = yield TS.from_either(native_window_e) panes = yield TS.lift(window_panes(window_id)) native_pane, tail = yield TS.from_maybe(panes.detach_head, 'no panes in window') reference_pane = yield pane_by_id(native_pane.id) state = ( reference_pane .map(L(TrackedWindow)(native_window, ui_window, layout, native_pane, _)) | L(PristineWindow)(native_window, ui_window, layout, native_pane) ) yield TS.pure(state)
def object_from_module(mod: ModuleType, pred: Callable[[Any], bool], desc: str) -> Do: all = yield Maybe.getattr(mod, '__all__').to_either( f'module `{mod.__name__}` does not define `__all__`') yield (Lists.wrap(all).flat_map(L(Maybe.getattr)( mod, _)).find(pred).to_either(f'no {desc} in `{mod.__name__}.__all__`'))
def search(self, monitor): return ( LazyList(self._queries(monitor)) .filter(_.valid) .apzip(self._safe_search) .map2(L(SearchResults)(_, _, self.min_seeders, self.max_size)) )
def flat_map_delay(self) -> None: v = 13 w = 29 x = 17 f = _ + x t = IO.delay(f, v).flat_map(L(IO.now)(_ + w)) t.attempt.should.contain(v + w + x)
def lift(self, key: Key) -> 'SubTree': def err() -> 'SubTree': keys = ', '.join(self.data.keys()) return SubTreeInvalid( key, f'MapNode({self.rule}) invalid key ({keys})') return (self.data.lift(key) / L(SubTree.cons)(_, key) | err)
def _path_lens(a: A, sub: Callable[[A], List[A]], f: Callable[[A], Maybe[UnboundLens]]) -> Maybe[UnboundLens]: def go_sub(): l, s = sub(lens), sub(a) g = lambda b: _path_lens(b, sub, f) return _path_lens_list(s, g) / _add(l).cons(lens) return (f(a) / L(List)(lens, _)).or_else(go_sub)
def layout_node(self, node: MeasuredLayoutNode, reference: P) -> Do: vertical = node.data.view.vertical layout_reference = yield reference_pane(node) new_reference = layout_reference | reference yield node.sub.traverse(position_view(vertical, new_reference), TS) yield node.sub.traverse(L(self)(_, new_reference), TS) yield node.sub.traverse(resize_view(vertical, new_reference.ident), TS) yield TS.unit
def choose(self, monitor): available = ( self.results.filter(lambda a: a.seeders is not None).filter( _.seeders >= self.min_seeders)) matching = (available.filter( L(match_title)(monitor, _.title, self.query.res)).filter( _.magnet_link).filter_not( lambda a: monitor.contains_torrent(a.magnet_link))) return (matching.filter(_.size < self.max_bytes).head.o(matching.head))
def handle_show(show): season = List.wrap(self.tvdb.season(show.etvdb_id, num)) if season: now = datetime.now().strftime('%F') aired = (season.filter(_['date'] < now).map(_['episode']).max) aired % L(self._releases.add_season)( show.canonical_name, num, _, search_name=show.search_name) return 'Done' else: return 'No such season: {} s{}'.format(show, num)
def location(self): files = List('io', 'anon', 'instances/io', 'tc/base') def filt(entry, name): return entry.filename.endswith('/amino/{}.py'.format(name)) stack = self.stack.filter_not(lambda a: files.exists(L(filt)(a, _))) pred = (lambda a: not IOException.remove_pkgs.exists( lambda b: '/{}/'.format(b) in a.filename)) return stack.find(pred)
def truncated_trace_lines(self) -> List[str]: try: tb = Lists.wrap(traceback.walk_tb(self.cause.__traceback__)) / _[0] error_loc = (tb.filter( L(non_internal_frame)(_, self._internal_packages_arg)).flat_map( frame_traceback_entry)) return self.trace_lines_with((error_loc) + format_exception_error(self.cause)) except Exception as e: return self.trace_error()
def location(self) -> None: IO.debug = True IOException.remove_pkgs = List('fn') def fail(a: int) -> None: raise Exception(str(a)) f = lambda a: a + 2 g = lambda a, b: IO.now(a + b) t = IO.delay(f, 1).flat_map(L(g)(_, 3)) t2 = t.map(fail) exc = t2._attempt().value code = (exc.location / _.code_context) | '' code[0].should.contain('t.map(fail)')
def lift(self, key: Key) -> 'SubTree': return (SubTreeInvalid(key, 'ListNode index must be int') if isinstance( key, str) else self.sub.lift(key) / L(SubTree.cons)(_, key) | (lambda: SubTreeInvalid(key, 'ListNode index oob')))
def execute_read(writes: List[TmuxCmd], read: TmuxCmd) -> Do: results = yield execute_cmds(writes, Just(read)) yield TmuxIO.from_either( results.last.map(read_result) | L(Left)(f'no output for {read}'))
def objects_from_module(mod: ModuleType, pred: Callable[[Any], bool]) -> Do: all = yield Maybe.getattr(mod, '__all__').to_either( f'module `{mod.__name__}` does not define `__all__`') return (Lists.wrap(all).flat_map(L(Maybe.getattr)(mod, _)).filter(pred))
def assemble(path): return (cb(self.rest).io('invalid arguments') / L(self.client.post)('{}{}'.format(path, sub), _))
def assemble(i, a): return cb(a).io('invalid arguments') // L(io)(i, _)
def delay(f: Callable[..., A], *a: Any, **kw: Any) -> 'IO[A]': return Suspend(L(f)(*a, **kw) >> Pure, safe_fmt(f, a, kw))
class ScalarEncoder(Encoder[Union[Number, str, None]], pred=L(issubclass)(_, (Number, str, type(None)))): def encode(self, a: Union[Number, str, None]) -> Either[JsonError, Json]: return Right(JsonScalar(a))
def format_logger_tree(tree: 'amino.Map[Logger, Any]', fmt_logger: Callable[[Logger], str], level: int=0 ) -> 'amino.List[str]': from amino import _, L sub_f = L(format_logger_tree)(_, fmt_logger, level=level + 1) formatted = tree.bimap(fmt_logger, sub_f) return indent(formatted.flat_map2(lambda a, b: b.cons(a)), level)
def encode_json(data: A) -> Do: enc = yield Encoder.e_for(data).lmap(L(JsonError)(data, _)) yield enc.encode(data)
def _clean_done(self, a): p = a.proc if p.done.value: monitor = self._releases.find_by_id(p.monitor.id) a.proc.result % __.find(L(self._process_results)(monitor, _)) return True
def sub_loggers(loggers, root): from amino import Map, _, L children = loggers.keyfilter(L(re.match)('{}\.[^.]+$'.format(root), _)) sub = (children.k / L(sub_loggers)(loggers, _)).fold_left(Map())(operator.pow) return Map({loggers[root]: sub})
def suspend(f: Callable[..., 'IO[A]'], *a: Any, **kw: Any) -> 'IO[A]': return Suspend(L(f)(*a, **kw), safe_fmt(f, a, kw))
def decode_field(field: Field) -> Do: value = yield data.field(field.name) dec = yield Decoder.e(field.tpe).lmap(L(JsonError)(data, _)) yield dec.decode(field.tpe, value)
def _flat_map(self, f: Callable[[A], IO[B]], ts: Eval[str], fs: Eval[str]) -> IO[B]: bs = L(BindSuspend)( self.thunk, lambda a: self.f(a).flat_map(f, Just(ts), Just(fs)), ts, fs) return Suspend(bs, (ts & fs).map2('{}.{}'.format))
class ListEncoder(Encoder[List], pred=L(issubclass)(_, Collection)): def encode(self, a: Collection) -> Either[JsonError, Json]: return Lists.wrap(a).traverse(encode_json, Either) / JsonArray
def _flat_map(self, f: Callable[[A], IO[B]], ts: Eval[str], fs: Eval[str]) -> IO[B]: return Suspend(L(f)(self.value), (ts & fs).map2('{}.{}'.format))