def textsgetter(path: str, *, strip: bool = False) -> t.Callable[[Element], t.List[str]]: return compose(list, partial(map, str.strip) if strip else identity, partial(map, _attrgetter('text')), methodcaller('findall', path))
def guild_channels(guild_id): app._current_guild = app._guilds[guild_id] res = app._client.api_get(app._current_guild.url_channels) channels = [Channel(id="", name="", type=types.GUILD_CATEGORY)] channels.extend( sorted(map(Channel.from_dict, res.json()), key=lambda x: (x.type != types.GUILD_CATEGORY, x.position))) categories = [] children = {} for channel in channels: if channel.type == types.GUILD_CATEGORY: categories.append(channel) children[channel.id] = [] elif channel.type == types.GUILD_TEXT: parent_id = getattr(channel, 'parent_id', "") children[parent_id].append(channel) for category in categories: category.children = children[category.id] return my_render_template("guild_channels.html", categories=filter(_attrgetter('children'), categories), types=types)
def index(self, value, start=0, stop=None): "L.index(value, [start, [stop]]) -> integer -- return first index of value" if start < 0: start += len(self._reflist) start = max(0, start) return map(_attrgetter('value'), self._reflist[start:stop]).index(value) + start
def __init__(self, eltype, name): # reconstructs what are the available interfaces from file self._available_interfaces = tuple( getattr(_this_module, itf_name) for itf_name in _itf_sel_names['interfaces'][eltype]) # reconstructs from file what are the interfaces in which I have to select the element in order to get the # results that pertain it from self._available_interfaces self._selectors = [] sel_attrs_chain = tuple(_itf_sel_names['selectors'][eltype]) for ac in sel_attrs_chain: obi = _attrgetter(ac)(_this_module) self._selectors.append(obi) self._name = name # todo perform sanity checks on name self.eltype = eltype # dynamically add methods to expose for i in self._available_interfaces: # for m in _interface_methods.get(tuple(i._undobj.split('.')[-1]), []): for m in _interface_methods.get(tuple(i.__name__.split('.')[-1]), []): setattr(self, m, self._craft_member(m))
def _make_eq(current_klass, attributes): getter = _attrgetter(*attributes) def __eq__(self, other, _getter=getter) -> bool: # todo: cooperation return _getter(self) == _getter(other) # and super(current_klass, self).__eq__(other) return __eq__
def attribgetter( path: str, attname: str, *, default: T = NO_DEFAULT) -> t.Callable[[Element], t.Union[str, T]]: find = compose(_itemgetter(attname), _attrgetter('attrib'), partial(_raise_if_none, exc=LookupError(path)), methodcaller('find', path)) return (find if default is NO_DEFAULT else lookup_defaults(find, default))
def _make_lt(current_klass, attributes): getter = _attrgetter(*(name for name, attr in attributes.items() if attr.order)) def __lt__(self, other, _getter=getter): return _getter(self) < _getter(other) __lt__.__qualname__ = f"{current_klass.__qualname__}.__lt__" return __lt__
def sort(self, cmp=None, key=None, reverse=False): """ L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*; cmp(x, y) -> -1, 0, 1 """ if key is None: mykey = _attrgetter('value') else: mykey = lambda x: key(x.value) self._reflist.sort(cmp=cmp, key=mykey, reverse=reverse)
def _get_soft_next_ts(self, last_ts, interval): def taken(ts, e): """Check if `ts` has already got an item scheduled nearby.""" # TODO this function is slow and called very often. # Optimise it, maybe? for item in self._schedule_interval_items: if abs(item.next_ts - ts) <= e: return True elif item.next_ts > ts + e: return False return False # sorted list is required required to produce expected results # taken() will iterate through the heap, expecting it to be sorted # and will not always catch smallest value, so sort here. # do not remove the sort key...it is faster than relaying comparisons # NOTE: do not rewrite as popping from heap, as that is super slow! self._schedule_interval_items.sort(key=_attrgetter('next_ts')) # Binary division over interval: # # 0 interval # |--------------------------| # 5 3 6 2 7 4 8 1 Order of search # # i.e., first scheduled at interval, # then at interval/2 # then at interval/4 # then at interval*3/4 # then at ... # # Schedule is hopefully then evenly distributed for any interval, # and any number of scheduled functions. next_ts = last_ts + interval if not taken(next_ts, interval / 4): return next_ts dt = interval divs = 1 while True: next_ts = last_ts for i in range(divs - 1): next_ts += dt if not taken(next_ts, dt / 4): return next_ts dt /= 2 divs *= 2 # Avoid infinite loop in pathological case if divs > 16: return next_ts
def __imul__(self, n): "x.__imul__(n) <==> x*=n" if not isinstance(n, int): raise TypeError, "can't multiply sequence by non-int" if n < 1: for each in self._reflist: each._parent = None self._reflist = [] else: neg_old_len = -len(self._reflist) for x in xrange(n - 1): # pylint: disable-msg=W0612 self.extend(map(_attrgetter('value'), self._reflist[neg_old_len:])) return self
def flattened_requirements_graph(graph, reverse=False): flattened_requirements = [] for reqgraphinfo in sorted(_requirements_graph_reqgraphinfo(graph, depth=0), key=_attrgetter('maxdepth'), reverse=(not reverse)): intersection = requirements_intersection(*reqgraphinfo.atoms) assert len(intersection) <= 1 if len(intersection) == 0: raise _exc.IncompatibleRequirements(reqgraphinfo.atoms) flattened_requirements.append(intersection[0]) return flattened_requirements
def get_nested_attr(obj, path, default_value=None, raise_exception=False): """ Get nested object property. It uses ``operator.attrgetter`` internally. :param obj: Object (top-level) :param path: Path to property. See :param default_value: Default value returned when attribute is not present. :param raise_exception: If True, raise exception instead of returning a default value :return: Attribute value or default value, if attribute is not present """ getter = _attrgetter(path) try: return getter(obj) except AttributeError as e: if raise_exception: raise e else: return default_value
def __iter__(self): "x.__iter__() <==> iter(x)" return _imap(_attrgetter('value'), self._reflist)
def is_flush(cards): return len(set(map(_attrgetter('suit'), cards))) == 1
def __reversed__(self): "L.__reversed__() -- return a reverse iterator over the list" return _imap(_attrgetter('value'), reversed(self._reflist))
def count(self, value): "L.count(value) -> integer -- return number of occurrences of value" return map(_attrgetter('value'), self._reflist).count(value)
def get_values(cards): return tuple(map(_attrgetter('value'), cards))
def prop_fuse_multiple(mainfuse_name, subfuses_seq): return property(_attrgetter(mainfuse_name), _set_fused_multiple(mainfuse_name, subfuses_seq))
def __getitem__(self, k): "x.__getitem__(k) <==> x[k]" if isinstance(k, slice): return ListRef(map(_attrgetter('value'), self._reflist[k])) else: return self._reflist[k].value
def prop_fuse(attrname): return property(_attrgetter(attrname), _burn_fuse(attrname))
def prop_fused_bool(attrname, fusename): return property(_attrgetter(attrname), _set_fused_protected(attrname, fusename, bool))
for _i1 in _inspect_getmembers(_odr.dss): _i1_name = _i1[0] if _i1_name in _itf.keys(): setattr(_this_module, _i1_name, types.ModuleType(_this_module.__name__ + '.' + _i1_name)) else: continue for _i2 in _inspect_getmembers(_i1[1]): if _i2[0].startswith( '_'): # this vulgar hack is to avoid special methods continue try: _stack = [_i1_name, _i2[0]] _frozencall = _partial(_enh_call, stack=_stack, odrobj=_attrgetter('.'.join(_stack))( _odr.dss)) except (AttributeError, ): continue try: setattr(getattr(_this_module, _i1_name), _i2[0], _FnWrp(_frozencall)) except (TypeError, AttributeError): continue # </editor-fold> # mocks a standard selector, but for named entities def _named_selector(name, eltype): nm = (eltype.lower(), name.lower()) _this_module.Circuit.SetActiveClass(nm[0])
def prop_fused_access(attrname, fusename): return property(_attrgetter(attrname), _set_fused_protected(attrname, fusename))
# metadata __version__ = '20.7' __author__ = 'Cisco Systems Inc.' __contact__ = ['*****@*****.**', '*****@*****.**'] __copyright__ = 'Copyright (c) 2018-2019, Cisco Systems Inc.' from .main import _default_runtime as runtime, main from operator import attrgetter as _attrgetter globals().update((name.split('.')[-1], _attrgetter(name)(runtime)) for name in runtime.__all__) __all__ = ['main', 'runtime'] __all__.extend(name.split('.')[-1] for name in runtime.__all__)
def __contains__(self, value): "seq.__contains__(value) <==> value in seq" return value in _imap(_attrgetter('value'), self._reflist)