code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if withscores:
return lambda score_member: (score_member[1], score_cast_func(self._encode(score_member[0]))) # noqa
else:
return lambda score_member: score_member[1] | def _range_func(self, withscores, score_cast_func) | Return a suitable function from (score, member) | 3.629094 | 2.811326 | 1.290883 |
funcs = {"sum": add, "min": min, "max": max}
func_name = aggregate.lower() if aggregate else 'sum'
try:
return funcs[func_name]
except KeyError:
raise TypeError("Unsupported aggregate: {}".format(aggregate)) | def _aggregate_func(self, aggregate) | Return a suitable aggregate score function. | 3.746104 | 3.479634 | 1.07658 |
keys = self._list_or_args(keys, args)
if not keys:
raise TypeError("{} takes at least two arguments".format(operation.lower()))
left = self._get_set(keys[0], operation) or set()
for key in keys[1:]:
right = self._get_set(key, operation) or set()
... | def _apply_to_sets(self, func, operation, keys, *args) | Helper function for sdiff, sinter, and sunion | 3.199545 | 2.965375 | 1.078968 |
# returns a single list combining keys and args
try:
iter(keys)
# a string can be iterated, but indicates
# keys wasn't passed as a list
if isinstance(keys, basestring):
keys = [keys]
except TypeError:
keys = [k... | def _list_or_args(self, keys, args) | Shamelessly copied from redis-py. | 5.368233 | 4.603047 | 1.166235 |
"Return a bytestring representation of the value. Taken from redis-py connection.py"
if isinstance(value, bytes):
return value
elif isinstance(value, (int, long)):
value = str(value).encode('utf-8')
elif isinstance(value, float):
value = repr(value).en... | def _encode(self, value) | Return a bytestring representation of the value. Taken from redis-py connection.py | 2.696125 | 1.919639 | 1.404496 |
found = self.remove(member)
index = bisect_left(self._scores, (score, member))
self._scores.insert(index, (score, member))
self._members[member] = score
return not found | def insert(self, member, score) | Identical to __setitem__, but returns whether a member was
inserted (True) or updated (False) | 3.789286 | 3.607689 | 1.050336 |
if member not in self:
return False
score = self._members[member]
score_index = bisect_left(self._scores, (score, member))
del self._scores[score_index]
del self._members[member]
return True | def remove(self, member) | Identical to __delitem__, but returns whether a member was removed. | 3.282494 | 2.978641 | 1.10201 |
score = self._members.get(member)
if score is None:
return None
return bisect_left(self._scores, (score, member)) | def rank(self, member) | Get the rank (index of a member). | 5.077169 | 4.516196 | 1.124214 |
if not self:
return []
if desc:
return reversed(self._scores[len(self) - end - 1:len(self) - start])
else:
return self._scores[start:end + 1] | def range(self, start, end, desc=False) | Return (score, member) pairs between min and max ranks. | 3.621255 | 3.040587 | 1.190973 |
if not self:
return []
left = bisect_left(self._scores, (start,))
right = bisect_right(self._scores, (end,))
if end_inclusive:
# end is inclusive
while right < len(self) and self._scores[right][0] == end:
right += 1
... | def scorerange(self, start, end, start_inclusive=True, end_inclusive=True) | Return (score, member) pairs between min and max scores. | 2.474243 | 2.379439 | 1.039843 |
if self.explicit_transaction:
raise RedisError("Cannot issue a WATCH after a MULTI")
self.watching = True
for key in keys:
self._watched_keys[key] = deepcopy(self.mock_redis.redis.get(self.mock_redis._encode(key))) | def watch(self, *keys) | Put the pipeline into immediate execution mode.
Does not actually watch any keys. | 6.423331 | 5.838642 | 1.100141 |
if self.explicit_transaction:
raise RedisError("Cannot issue nested calls to MULTI")
if self.commands:
raise RedisError("Commands without an initial WATCH have already been issued")
self.explicit_transaction = True | def multi(self) | Start a transactional block of the pipeline after WATCH commands
are issued. End the transactional block with `execute`. | 11.818885 | 7.1537 | 1.652136 |
try:
for key, value in self._watched_keys.items():
if self.mock_redis.redis.get(self.mock_redis._encode(key)) != value:
raise WatchError("Watched variable changed.")
return [command() for command in self.commands]
finally:
... | def execute(self) | Execute all of the saved commands and return results. | 6.834313 | 6.171624 | 1.107377 |
self.commands = []
self.watching = False
self._watched_keys = {}
self.explicit_transaction = False | def _reset(self) | Reset instance variables. | 12.943377 | 10.943843 | 1.182709 |
if lang is not None and cls.is_supported(lang):
return lang
elif lang is not None and cls.is_supported(lang + "$core"): # Support ISO 639-1 Language Codes (e.g. "en")
return lang + "$core"
else:
raise ValueError("Unsupported language '{}'. Supporte... | def convert_to_duckling_language_id(cls, lang) | Ensure a language identifier has the correct duckling format and is supported. | 3.828284 | 3.540059 | 1.081418 |
duckling_load = self.clojure.var("duckling.core", "load!")
clojure_hashmap = self.clojure.var("clojure.core", "hash-map")
clojure_list = self.clojure.var("clojure.core", "list")
if languages:
# Duckling's load function expects ISO 639-1 Language Codes (e.g. "en")
... | def load(self, languages=[]) | Loads the Duckling corpus.
Languages can be specified, defaults to all.
Args:
languages: Optional parameter to specify languages,
e.g. [Duckling.ENGLISH, Duckling.FRENCH] or supported ISO 639-1 Codes (e.g. ["en", "fr"]) | 3.979913 | 3.90054 | 1.020349 |
if self._is_loaded is False:
raise RuntimeError(
'Please load the model first by calling load()')
if threading.activeCount() > 1:
if not jpype.isThreadAttachedToJVM():
jpype.attachThreadToJVM()
language = Language.convert_to_duckli... | def parse(self, input_str, language=Language.ENGLISH, dim_filter=None, reference_time='') | Parses datetime information out of string input.
It invokes the Duckling.parse() function in Clojure.
A language can be specified, default is English.
Args:
input_str: The input as string that has to be parsed.
language: Optional parameter to specify language,
... | 3.013802 | 2.79211 | 1.079399 |
return self._parse(input_str, dim=Dim.TIME,
reference_time=reference_time) | def parse_time(self, input_str, reference_time='') | Parses input with Duckling for occurences of times.
Args:
input_str: An input string, e.g. 'Let's meet at 11:45am'.
reference_time: Optional reference time for Duckling.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
... | 7.400003 | 9.187276 | 0.805462 |
disco = self.dependencies[aioxmpp.disco.DiscoClient]
response = yield from disco.query_items(
peer_jid,
node=namespaces.xep0050_commands,
)
return response.items | def get_commands(self, peer_jid) | Return the list of commands offered by the peer.
:param peer_jid: JID of the peer to query
:type peer_jid: :class:`~aioxmpp.JID`
:rtype: :class:`list` of :class:`~.disco.xso.Item`
:return: List of command items
In the returned list, each :class:`~.disco.xso.Item` represents one... | 11.374937 | 9.39618 | 1.210592 |
disco = self.dependencies[aioxmpp.disco.DiscoClient]
response = yield from disco.query_info(
peer_jid,
node=command_name,
)
return response | def get_command_info(self, peer_jid, command_name) | Obtain information about a command.
:param peer_jid: JID of the peer to query
:type peer_jid: :class:`~aioxmpp.JID`
:param command_name: Node name of the command
:type command_name: :class:`str`
:rtype: :class:`~.disco.xso.InfoQuery`
:return: Service discovery informatio... | 7.537507 | 6.99184 | 1.078043 |
disco = self.dependencies[aioxmpp.disco.DiscoClient]
response = yield from disco.query_info(
peer_jid,
)
return namespaces.xep0050_commands in response.features | def supports_commands(self, peer_jid) | Detect whether a peer supports :xep:`50` Ad-Hoc commands.
:param peer_jid: JID of the peer to query
:type peer_jid: :class:`aioxmpp.JID`
:rtype: :class:`bool`
:return: True if the peer supports the Ad-Hoc commands protocol, false
otherwise.
Note that the fact t... | 12.254194 | 9.169634 | 1.336389 |
session = ClientSession(
self.client.stream,
peer_jid,
command_name,
)
yield from session.start()
return session | def execute(self, peer_jid, command_name) | Start execution of a command with a peer.
:param peer_jid: JID of the peer to start the command at.
:type peer_jid: :class:`~aioxmpp.JID`
:param command_name: Node name of the command to execute.
:type command_name: :class:`str`
:rtype: :class:`~.adhoc.service.ClientSession`
... | 7.074183 | 6.131322 | 1.153778 |
info = CommandEntry(
name,
handler,
is_allowed=is_allowed,
features=features,
)
self._commands[node] = info
self._disco.mount_node(
node,
info,
) | def register_stateless_command(self, node, name, handler, *,
is_allowed=None,
features={namespaces.xep0004_data}) | Register a handler for a stateless command.
:param node: Name of the command (``node`` in the service discovery
list).
:type node: :class:`str`
:param name: Human-readable name of the command
:type name: :class:`str` or :class:`~.LanguageMap`
:param handler:... | 4.57979 | 5.565627 | 0.82287 |
if self._response is not None and self._response.actions is not None:
return self._response.actions.allowed_actions
return {adhoc_xso.ActionType.EXECUTE,
adhoc_xso.ActionType.CANCEL} | def allowed_actions(self) | Shorthand to access :attr:`~.xso.Actions.allowed_actions` of the
:attr:`response`.
If no response has been received yet or if the response specifies no
set of valid actions, this is the minimal set of allowed actions (
:attr:`~.ActionType.EXECUTE` and :attr:`~.ActionType.CANCEL`). | 9.182693 | 3.666879 | 2.504226 |
if self._response is not None:
raise RuntimeError("command execution already started")
request = aioxmpp.IQ(
type_=aioxmpp.IQType.SET,
to=self._peer_jid,
payload=adhoc_xso.Command(self._command_name),
)
self._response = yield fr... | def start(self) | Initiate the session by starting to execute the command with the peer.
:return: The :attr:`~.xso.Command.first_payload` of the response
This sends an empty command IQ request with the
:attr:`~.ActionType.EXECUTE` action.
The :attr:`status`, :attr:`response` and related attributes get ... | 6.721424 | 4.330876 | 1.551978 |
if self._response is None:
raise RuntimeError("command execution not started yet")
if action not in self.allowed_actions:
raise ValueError("action {} not allowed in this stage".format(
action
))
cmd = adhoc_xso.Command(
... | def proceed(self, *,
action=adhoc_xso.ActionType.EXECUTE,
payload=None) | Proceed command execution to the next stage.
:param action: Action type for proceeding
:type action: :class:`~.ActionTyp`
:param payload: Payload for the request, or :data:`None`
:return: The :attr:`~.xso.Command.first_payload` of the response
`action` must be one of the action... | 3.803394 | 3.529254 | 1.077676 |
if self.is_closing():
return
self._write_buffer += data
if len(self._write_buffer) >= self._output_buffer_limit_high:
self._protocol.pause_writing()
if self._write_buffer:
self._can_write.set() | def write(self, data) | Send `data` over the IBB. If `data` is larger than the block size
is is chunked and sent in chunks.
Chunks from one call of :meth:`write` will always be sent in
series. | 4.960526 | 5.164382 | 0.960527 |
if self.is_closing():
return
self._closing = True
# make sure the writer wakes up
self._can_write.set() | def close(self) | Close the session. | 9.190988 | 8.187459 | 1.122569 |
def on_done(fut):
del self._expected_sessions[sid, peer_jid]
_, fut = self._expected_sessions[sid, peer_jid] = (
protocol_factory, asyncio.Future()
)
fut.add_done_callback(on_done)
return fut | def expect_session(self, protocol_factory, peer_jid, sid) | Whitelist the session with `peer_jid` and the session id `sid` and
return it when it is established. This is meant to be used
with signalling protocols like Jingle and is the counterpart
to :meth:`open_session`.
:returns: an awaitable object, whose result is the tuple
... | 3.945036 | 5.183469 | 0.76108 |
if block_size > MAX_BLOCK_SIZE:
raise ValueError("block_size too large")
if sid is None:
sid = utils.to_nmtoken(random.getrandbits(8*8))
open_ = ibb_xso.Open()
open_.stanza = stanza_type
open_.sid = sid
open_.block_size = block_size
... | def open_session(self, protocol_factory, peer_jid, *,
stanza_type=ibb_xso.IBBStanzaType.IQ,
block_size=4096, sid=None) | Establish an in-band bytestream session with `peer_jid` and
return the transport and protocol.
:param protocol_factory: the protocol factory
:type protocol_factory: a nullary callable returning an
:class:`asyncio.Protocol` instance
:param peer_jid: the JI... | 4.166193 | 3.910228 | 1.06546 |
env = inliner.document.settings.env
if not typ:
typ = env.config.default_role
else:
typ = typ.lower()
has_explicit_title, title, target = split_explicit_title(text)
title = utils.unescape(title)
target = utils.unescape(target)
targetid = 'index-%s' % env.new_serialno('in... | def xep_role(typ, rawtext, text, lineno, inliner,
options={}, content=[]) | Role for PEP/RFC references that generate an index entry. | 2.775357 | 2.749447 | 1.009424 |
if nested_type is _Undefined:
return EnumCDataType(enum_class, **kwargs)
if isinstance(nested_type, AbstractCDataType):
return EnumCDataType(enum_class, nested_type, **kwargs)
else:
return EnumElementType(enum_class, nested_type, **kwargs) | def EnumType(enum_class, nested_type=_Undefined, **kwargs) | Create and return a :class:`EnumCDataType` or :class:`EnumElementType`,
depending on the type of `nested_type`.
If `nested_type` is a :class:`AbstractCDataType` or omitted, a
:class:`EnumCDataType` is constructed. Otherwise, :class:`EnumElementType`
is used.
The arguments are forwarded to the resp... | 2.8883 | 1.848134 | 1.562819 |
if not body:
return None, None
try:
return None, body[None]
except KeyError:
return min(body.items(), key=lambda x: x[0]) | def _extract_one_pair(body) | Extract one language-text pair from a :class:`~.LanguageMap`.
This is used for tracking. | 6.506819 | 6.571814 | 0.99011 |
if self._this_occupant is not None:
items = [self._this_occupant]
else:
items = []
items += list(self._occupant_info.values())
return items | def members(self) | A copy of the list of occupants. The local user is always the first
item in the list, unless the :meth:`on_enter` has not fired yet. | 6.388441 | 3.987495 | 1.602119 |
return {
aioxmpp.im.conversation.ConversationFeature.BAN,
aioxmpp.im.conversation.ConversationFeature.BAN_WITH_KICK,
aioxmpp.im.conversation.ConversationFeature.KICK,
aioxmpp.im.conversation.ConversationFeature.SEND_MESSAGE,
aioxmpp.im.conver... | def features(self) | The set of features supported by this MUC. This may vary depending on
features exported by the MUC service, so be sure to check this for each
individual MUC. | 2.918832 | 2.596995 | 1.123927 |
msg.type_ = aioxmpp.MessageType.GROUPCHAT
msg.to = self._mucjid
# see https://mail.jabber.org/pipermail/standards/2017-January/032048.html # NOQA
# for a full discussion on the rationale for this.
# TL;DR: we want to help entities to discover that a message is related
... | def send_message(self, msg) | Send a message to the MUC.
:param msg: The message to send.
:type msg: :class:`aioxmpp.Message`
:return: The stanza token of the message.
:rtype: :class:`~aioxmpp.stream.StanzaToken`
There is no need to set the address attributes or the type of the
message correctly; th... | 11.420049 | 11.322397 | 1.008625 |
msg.type_ = aioxmpp.MessageType.GROUPCHAT
msg.to = self._mucjid
# see https://mail.jabber.org/pipermail/standards/2017-January/032048.html # NOQA
# for a full discussion on the rationale for this.
# TL;DR: we want to help entities to discover that a message is related
... | def send_message_tracked(self, msg) | Send a message to the MUC with tracking.
:param msg: The message to send.
:type msg: :class:`aioxmpp.Message`
.. warning::
Please read :ref:`api-tracking-memory`. This is especially relevant
for MUCs because tracking is not guaranteed to work due to how
:xe... | 7.124003 | 6.525127 | 1.09178 |
stanza = aioxmpp.Presence(
type_=aioxmpp.PresenceType.AVAILABLE,
to=self._mucjid.replace(resource=new_nick),
)
yield from self._service.client.send(
stanza
) | def set_nick(self, new_nick) | Change the nick name of the occupant.
:param new_nick: New nickname to use
:type new_nick: :class:`str`
This sends the request to change the nickname and waits for the request
to be sent over the stream.
The nick change may or may not happen, or the service may modify the
... | 7.320051 | 8.176021 | 0.895307 |
yield from self.muc_set_role(
member.nick,
"none",
reason=reason
) | def kick(self, member, reason=None) | Kick an occupant from the MUC.
:param member: The member to kick.
:type member: :class:`Occupant`
:param reason: A reason to show to the members of the conversation
including the kicked member.
:type reason: :class:`str`
:raises aioxmpp.errors.XMPPError: if the serve... | 9.857779 | 12.616263 | 0.781355 |
if nick is None:
raise ValueError("nick must not be None")
if role is None:
raise ValueError("role must not be None")
iq = aioxmpp.stanza.IQ(
type_=aioxmpp.structs.IQType.SET,
to=self._mucjid
)
iq.payload = muc_xso.Admi... | def muc_set_role(self, nick, role, *, reason=None) | Change the role of an occupant.
:param nick: The nickname of the occupant whose role shall be changed.
:type nick: :class:`str`
:param role: The new role for the occupant.
:type role: :class:`str`
:param reason: An optional reason to show to the occupant (and all
oth... | 4.187337 | 4.141542 | 1.011057 |
if member.direct_jid is None:
raise ValueError(
"cannot ban members whose direct JID is not "
"known")
yield from self.muc_set_affiliation(
member.direct_jid,
"outcast",
reason=reason
) | def ban(self, member, reason=None, *, request_kick=True) | Ban an occupant from re-joining the MUC.
:param member: The occupant to ban.
:type member: :class:`Occupant`
:param reason: A reason to show to the members of the conversation
including the banned member.
:type reason: :class:`str`
:param request_kick: A flag indicat... | 6.51258 | 7.237935 | 0.899784 |
return (yield from self.service.set_affiliation(
self._mucjid,
jid, affiliation,
reason=reason)) | def muc_set_affiliation(self, jid, affiliation, *, reason=None) | Convenience wrapper around :meth:`.MUCClient.set_affiliation`. See
there for details, and consider its `mucjid` argument to be set to
:attr:`mucjid`. | 6.523455 | 5.856114 | 1.113956 |
msg = aioxmpp.stanza.Message(
type_=aioxmpp.structs.MessageType.GROUPCHAT,
to=self._mucjid
)
msg.subject.update(new_topic)
yield from self.service.client.send(msg) | def set_topic(self, new_topic) | Change the (possibly publicly) visible topic of the conversation.
:param new_topic: The new topic for the conversation.
:type new_topic: :class:`str`
Request to set the subject to `new_topic`. `new_topic` must be a
mapping which maps :class:`~.structs.LanguageTag` tags to strings;
... | 7.659992 | 7.134893 | 1.073596 |
fut = self.on_exit.future()
def cb(**kwargs):
fut.set_result(None)
return True # disconnect
self.on_exit.connect(cb)
presence = aioxmpp.stanza.Presence(
type_=aioxmpp.structs.PresenceType.UNAVAILABLE,
to=self._mucjid
)
... | def leave(self) | Leave the MUC. | 6.263037 | 5.818974 | 1.076313 |
msg = aioxmpp.Message(
to=self._mucjid,
type_=aioxmpp.MessageType.NORMAL
)
data = aioxmpp.forms.Data(
aioxmpp.forms.DataType.SUBMIT,
)
data.fields.append(
aioxmpp.forms.Field(
type_=aioxmpp.forms.FieldTyp... | def muc_request_voice(self) | Request voice (participant role) in the room and wait for the request
to be sent.
The participant role allows occupants to send messages while the room
is in moderated mode.
There is no guarantee that the request will be granted. To detect that
voice has been granted, observe t... | 3.173853 | 3.324632 | 0.954648 |
if mucjid is None or not mucjid.is_bare:
raise ValueError("mucjid must be bare JID")
if jid is None:
raise ValueError("jid must not be None")
if affiliation is None:
raise ValueError("affiliation must not be None")
iq = aioxmpp.stanza.IQ(
... | def set_affiliation(self, mucjid, jid, affiliation, *, reason=None) | Change the affiliation of an entity with a MUC.
:param mucjid: The bare JID identifying the MUC.
:type mucjid: :class:`~aioxmpp.JID`
:param jid: The bare JID of the entity whose affiliation shall be
changed.
:type jid: :class:`~aioxmpp.JID`
:param affiliation: The ne... | 3.230462 | 3.194954 | 1.011114 |
if mucjid is None or not mucjid.is_bare:
raise ValueError("mucjid must be bare JID")
iq = aioxmpp.stanza.IQ(
type_=aioxmpp.structs.IQType.GET,
to=mucjid,
payload=muc_xso.OwnerQuery(),
)
return (yield from self.client.send(iq)).f... | def get_room_config(self, mucjid) | Query and return the room configuration form for the given MUC.
:param mucjid: JID of the room to query
:type mucjid: bare :class:`~.JID`
:return: data form template for the room configuration
:rtype: :class:`aioxmpp.forms.Data`
.. seealso::
:class:`~.ConfigurationF... | 6.239069 | 5.724701 | 1.089851 |
iq = aioxmpp.stanza.IQ(
type_=aioxmpp.structs.IQType.SET,
to=mucjid,
payload=muc_xso.OwnerQuery(form=data),
)
yield from self.client.send(iq) | def set_room_config(self, mucjid, data) | Set the room configuration using a :xep:`4` data form.
:param mucjid: JID of the room to query
:type mucjid: bare :class:`~.JID`
:param data: Filled-out configuration form
:type data: :class:`aioxmpp.forms.Data`
.. seealso::
:class:`~.ConfigurationForm`
... | 8.478289 | 8.085757 | 1.048546 |
payload = Request(filename, size, content_type)
return (yield from client.send(IQ(
type_=IQType.GET,
to=service,
payload=payload
))) | def request_slot(client,
service: JID,
filename: str,
size: int,
content_type: str) | Request an HTTP upload slot.
:param client: The client to request the slot with.
:type client: :class:`aioxmpp.Client`
:param service: Address of the HTTP upload service.
:type service: :class:`~aioxmpp.JID`
:param filename: Name of the file (without path), may be used by the server
to gene... | 6.590498 | 5.909135 | 1.115307 |
return (yield from stream.send(
aioxmpp.IQ(
type_=aioxmpp.IQType.GET,
to=target,
payload=version_xso.Query(),
)
)) | def query_version(stream: aioxmpp.stream.StanzaStream,
target: aioxmpp.JID) -> version_xso.Query | Query the software version of an entity.
:param stream: A stanza stream to send the query on.
:type stream: :class:`aioxmpp.stream.StanzaStream`
:param target: The address of the entity to query.
:type target: :class:`aioxmpp.JID`
:raises OSError: if a connection issue occured before a reply was re... | 4.20289 | 4.278303 | 0.982373 |
if not issubclass(xso_class, Bookmark):
raise TypeError(
"Classes registered as bookmark types must be Bookmark subclasses"
)
Storage.register_child(
Storage.bookmarks,
xso_class
)
return xso_class | def as_bookmark_class(xso_class) | Decorator to register `xso_class` as a custom bookmark class.
This is necessary to store and retrieve such bookmarks.
The registered class must be a subclass of the abstract base class
:class:`Bookmark`.
:raises TypeError: if `xso_class` is not a subclass of :class:`Bookmark`. | 6.279486 | 6.555037 | 0.957963 |
if LanguageRange.WILDCARD in ranges:
yield from languages
return
found = set()
for language_range in ranges:
range_str = language_range.match_str
for language in languages:
if language in found:
continue
match_str = language.ma... | def basic_filter_languages(languages, ranges) | Filter languages using the string-based basic filter algorithm described in
RFC4647.
`languages` must be a sequence of :class:`LanguageTag` instances which are
to be filtered.
`ranges` must be an iterable which represent the basic language ranges to
filter with, in priority order. The language ran... | 2.729719 | 2.758753 | 0.989476 |
for language_range in ranges:
while True:
try:
return next(iter(basic_filter_languages(
languages,
[language_range])))
except StopIteration:
pass
try:
language_range = language_... | def lookup_language(languages, ranges) | Look up a single language in the sequence `languages` using the lookup
mechansim described in RFC4647. If no match is found, :data:`None` is
returned. Otherwise, the first matching language is returned.
`languages` must be a sequence of :class:`LanguageTag` objects, while
`ranges` must be an iterable o... | 6.218601 | 6.307017 | 0.985981 |
new_kwargs = {}
strict = kwargs.pop("strict", True)
try:
localpart = kwargs.pop("localpart")
except KeyError:
pass
else:
if localpart:
localpart = nodeprep(
localpart,
allow_un... | def replace(self, **kwargs) | Construct a new :class:`JID` object, using the values of the current
JID. Use the arguments to override specific attributes on the new
object.
All arguments are keyword arguments.
:param localpart: Set the local part of the resulting JID.
:param domain: Set the domain of the re... | 2.315255 | 2.187667 | 1.058321 |
nodedomain, sep, resource = s.partition("/")
if not sep:
resource = None
localpart, sep, domain = nodedomain.partition("@")
if not sep:
domain = localpart
localpart = None
return cls(localpart, domain, resource, strict=strict) | def fromstr(cls, s, *, strict=True) | Construct a JID out of a string containing it.
:param s: The string to parse.
:type s: :class:`str`
:param strict: Whether to enable strict parsing.
:type strict: :class:`bool`
:raises: See :class:`JID`
:return: The parsed JID
:rtype: :class:`JID`
See th... | 4.939662 | 5.080535 | 0.972272 |
parts = self.print_str.split("-")
parts.pop()
if parts and len(parts[-1]) == 1:
parts.pop()
return type(self).fromstr("-".join(parts)) | def strip_rightmost(self) | Strip the rightmost part of the language range. If the new rightmost
part is a singleton or ``x`` (i.e. starts an extension or private use
part), it is also stripped.
Return the newly created :class:`LanguageRange`. | 6.97068 | 6.389811 | 1.090906 |
keys = list(self.keys())
try:
keys.remove(None)
except ValueError:
pass
keys.sort()
key = lookup_language(keys, language_ranges)
return self[key] | def lookup(self, language_ranges) | Perform an RFC4647 language range lookup on the keys in the
dictionary. `language_ranges` must be a sequence of
:class:`LanguageRange` instances.
Return the entry in the dictionary with a key as produced by
`lookup_language`. If `lookup_language` does not find a match and the
ma... | 3.510848 | 3.125103 | 1.123434 |
try:
return self._conversationmap[peer_jid]
except KeyError:
pass
return self._make_conversation(peer_jid, False) | def get_conversation(self, peer_jid, *, current_jid=None) | Get or create a new one-to-one conversation with a peer.
:param peer_jid: The JID of the peer to converse with.
:type peer_jid: :class:`aioxmpp.JID`
:param current_jid: The current JID to lock the conversation to (see
:rfc:`6121`).
:type current_jid: :class:`... | 6.408445 | 7.29185 | 0.87885 |
global _state
_state.resolver = dns.resolver.Resolver()
_state.overridden_resolver = False | def reconfigure_resolver() | Reset the resolver configured for this thread to a fresh instance. This
essentially re-reads the system-wide resolver configuration.
If a custom resolver has been set using :func:`set_resolver`, the flag
indicating that no automatic re-configuration shall take place is cleared. | 11.435909 | 11.030612 | 1.036743 |
record = b".".join([
b"_" + service.encode("ascii"),
b"_" + transport.encode("ascii"),
domain])
answer = yield from repeated_query(
record,
dns.rdatatype.SRV,
**kwargs)
if answer is None:
return None
items = [
(rec.priority, rec.we... | def lookup_srv(
domain: bytes,
service: str,
transport: str = "tcp",
**kwargs) | Query the DNS for SRV records describing how the given `service` over the
given `transport` is implemented for the given `domain`. `domain` must be
an IDNA-encoded :class:`bytes` object; `service` must be a normal
:class:`str`.
Keyword arguments are passed to :func:`repeated_query`.
Return a list ... | 3.632017 | 2.949542 | 1.231384 |
record = b".".join([
b"_" + str(port).encode("ascii"),
b"_" + transport.encode("ascii"),
hostname
])
answer = yield from repeated_query(
record,
dns.rdatatype.TLSA,
require_ad=require_ad,
**kwargs)
if answer is None:
return None
... | def lookup_tlsa(hostname, port, transport="tcp", require_ad=True, **kwargs) | Query the DNS for TLSA records describing the certificates and/or keys to
expect when contacting `hostname` at the given `port` over the given
`transport`. `hostname` must be an IDNA-encoded :class:`bytes` object.
The keyword arguments are passed to :func:`repeated_query`; `require_ad`
defaults to :dat... | 4.397869 | 3.582686 | 1.227534 |
rng = rng or random
all_records.sort(key=lambda x: x[:2])
for priority, records in itertools.groupby(
all_records,
lambda x: x[0]):
records = list(records)
total_weight = sum(
weight
for _, weight, _ in records)
while records:
... | def group_and_order_srv_records(all_records, rng=None) | Order a list of SRV record information (as returned by :func:`lookup_srv`)
and group and order them as specified by the RFC.
Return an iterable, yielding each ``(hostname, port)`` tuple inside the
SRV records in the order specified by the RFC. For hosts with the same
priority, the given `rng` implement... | 2.743078 | 3.126072 | 0.877484 |
handler_dict = automake_magic_attr(f)
if kwargs is None:
kwargs = {}
if kwargs != handler_dict.setdefault(handler_spec, kwargs):
raise ValueError(
"The additional keyword arguments to the handler are incompatible") | def add_handler_spec(f, handler_spec, *, kwargs=None) | Attach a handler specification (see :class:`HandlerSpec`) to a function.
:param f: Function to attach the handler specification to.
:param handler_spec: Handler specification to attach to the function.
:type handler_spec: :class:`HandlerSpec`
:param kwargs: additional keyword arguments passed to the fu... | 9.555371 | 9.223416 | 1.03599 |
if (not hasattr(payload_cls, "TAG") or
(aioxmpp.IQ.CHILD_MAP.get(payload_cls.TAG) is not
aioxmpp.IQ.payload.xq_descriptor) or
payload_cls not in aioxmpp.IQ.payload._classes):
raise ValueError(
"{!r} is not a valid IQ payload "
"(use IQ.as_pa... | def iq_handler(type_, payload_cls, *, with_send_reply=False) | Register the decorated function or coroutine function as IQ request
handler.
:param type_: IQ type to listen for
:type type_: :class:`~.IQType`
:param payload_cls: Payload XSO class to listen for
:type payload_cls: :class:`~.XSO` subclass
:param with_send_reply: Whether to pass a function to se... | 6.120206 | 5.401021 | 1.133157 |
import aioxmpp.dispatcher
return aioxmpp.dispatcher.message_handler(type_, from_) | def message_handler(type_, from_) | Deprecated alias of :func:`.dispatcher.message_handler`.
.. deprecated:: 0.9 | 8.281068 | 7.552603 | 1.096452 |
import aioxmpp.dispatcher
return aioxmpp.dispatcher.presence_handler(type_, from_) | def presence_handler(type_, from_) | Deprecated alias of :func:`.dispatcher.presence_handler`.
.. deprecated:: 0.9 | 7.855809 | 6.570952 | 1.195536 |
if asyncio.iscoroutinefunction(f):
raise TypeError(
"inbound_message_filter must not be a coroutine function"
)
add_handler_spec(
f,
HandlerSpec(
(_apply_inbound_message_filter, ())
),
)
return f | def inbound_message_filter(f) | Register the decorated function as a service-level inbound message filter.
:raise TypeError: if the decorated object is a coroutine function
.. seealso::
:class:`StanzaStream`
for important remarks regarding the use of stanza filters. | 6.008538 | 6.597514 | 0.910728 |
if asyncio.iscoroutinefunction(f):
raise TypeError(
"inbound_presence_filter must not be a coroutine function"
)
add_handler_spec(
f,
HandlerSpec(
(_apply_inbound_presence_filter, ())
),
)
return f | def inbound_presence_filter(f) | Register the decorated function as a service-level inbound presence filter.
:raise TypeError: if the decorated object is a coroutine function
.. seealso::
:class:`StanzaStream`
for important remarks regarding the use of stanza filters. | 6.268516 | 6.681534 | 0.938185 |
if asyncio.iscoroutinefunction(f):
raise TypeError(
"outbound_message_filter must not be a coroutine function"
)
add_handler_spec(
f,
HandlerSpec(
(_apply_outbound_message_filter, ())
),
)
return f | def outbound_message_filter(f) | Register the decorated function as a service-level outbound message filter.
:raise TypeError: if the decorated object is a coroutine function
.. seealso::
:class:`StanzaStream`
for important remarks regarding the use of stanza filters. | 6.303801 | 6.77992 | 0.929775 |
if asyncio.iscoroutinefunction(f):
raise TypeError(
"outbound_presence_filter must not be a coroutine function"
)
add_handler_spec(
f,
HandlerSpec(
(_apply_outbound_presence_filter, ())
),
)
return f | def outbound_presence_filter(f) | Register the decorated function as a service-level outbound presence
filter.
:raise TypeError: if the decorated object is a coroutine function
.. seealso::
:class:`StanzaStream`
for important remarks regarding the use of stanza filters. | 6.569033 | 7.150326 | 0.918704 |
def decorator(f):
add_handler_spec(
f,
_depsignal_spec(class_, signal_name, f, defer)
)
return f
return decorator | def depsignal(class_, signal_name, *, defer=False) | Connect the decorated method or coroutine method to the addressed signal on
a class on which the service depends.
:param class_: A service class which is listed in the
:attr:`~.Meta.ORDER_AFTER` relationship.
:type class_: :class:`Service` class or one of the special cases below
:par... | 6.354403 | 8.273564 | 0.768037 |
def decorator(f):
add_handler_spec(
f,
_attrsignal_spec(descriptor, signal_name, f, defer)
)
return f
return decorator | def attrsignal(descriptor, signal_name, *, defer=False) | Connect the decorated method or coroutine method to the addressed signal on
a descriptor.
:param descriptor: The descriptor to connect to.
:type descriptor: :class:`Descriptor` subclass.
:param signal_name: Attribute name of the signal to connect to
:type signal_name: :class:`str`
:param defer:... | 5.782239 | 8.179076 | 0.706955 |
spec = _depfilter_spec(class_, filter_name)
def decorator(f):
add_handler_spec(
f,
spec,
)
return f
return decorator | def depfilter(class_, filter_name) | Register the decorated method at the addressed :class:`~.callbacks.Filter`
on a class on which the service depends.
:param class_: A service class which is listed in the
:attr:`~.Meta.ORDER_AFTER` relationship.
:type class_: :class:`Service` class or
:class:`aioxmpp.str... | 5.564195 | 11.606251 | 0.479414 |
try:
handlers = get_magic_attr(coro)
except AttributeError:
return False
hs = HandlerSpec(
(_apply_iq_handler, (type_, payload_cls)),
)
try:
return handlers[hs] == dict(with_send_reply=with_send_reply)
except KeyError:
return False | def is_iq_handler(type_, payload_cls, coro, *, with_send_reply=False) | Return true if `coro` has been decorated with :func:`iq_handler` for the
given `type_` and `payload_cls` and the specified keyword arguments. | 6.183093 | 5.639149 | 1.096459 |
import aioxmpp.dispatcher
return aioxmpp.dispatcher.is_message_handler(type_, from_, cb) | def is_message_handler(type_, from_, cb) | Deprecated alias of :func:`.dispatcher.is_message_handler`.
.. deprecated:: 0.9 | 5.233892 | 4.774216 | 1.096283 |
import aioxmpp.dispatcher
return aioxmpp.dispatcher.is_presence_handler(type_, from_, cb) | def is_presence_handler(type_, from_, cb) | Deprecated alias of :func:`.dispatcher.is_presence_handler`.
.. deprecated:: 0.9 | 5.248188 | 4.44095 | 1.181771 |
try:
handlers = get_magic_attr(cb)
except AttributeError:
return False
hs = HandlerSpec(
(_apply_inbound_message_filter, ())
)
return hs in handlers | def is_inbound_message_filter(cb) | Return true if `cb` has been decorated with :func:`inbound_message_filter`. | 13.963622 | 11.919786 | 1.171466 |
try:
handlers = get_magic_attr(cb)
except AttributeError:
return False
hs = HandlerSpec(
(_apply_inbound_presence_filter, ())
)
return hs in handlers | def is_inbound_presence_filter(cb) | Return true if `cb` has been decorated with
:func:`inbound_presence_filter`. | 14.364151 | 12.713708 | 1.129816 |
try:
handlers = get_magic_attr(cb)
except AttributeError:
return False
hs = HandlerSpec(
(_apply_outbound_message_filter, ())
)
return hs in handlers | def is_outbound_message_filter(cb) | Return true if `cb` has been decorated with
:func:`outbound_message_filter`. | 14.654874 | 13.204512 | 1.109838 |
try:
handlers = get_magic_attr(cb)
except AttributeError:
return False
hs = HandlerSpec(
(_apply_outbound_presence_filter, ())
)
return hs in handlers | def is_outbound_presence_filter(cb) | Return true if `cb` has been decorated with
:func:`outbound_presence_filter`. | 15.324961 | 13.441648 | 1.14011 |
try:
handlers = get_magic_attr(cb)
except AttributeError:
return False
return _depsignal_spec(class_, signal_name, cb, defer) in handlers | def is_depsignal_handler(class_, signal_name, cb, *, defer=False) | Return true if `cb` has been decorated with :func:`depsignal` for the given
signal, class and connection mode. | 7.454049 | 6.806217 | 1.095182 |
try:
handlers = get_magic_attr(filter_)
except AttributeError:
return False
return _depfilter_spec(class_, filter_name) in handlers | def is_depfilter_handler(class_, filter_name, filter_) | Return true if `filter_` has been decorated with :func:`depfilter` for the
given filter and class. | 8.481392 | 7.955227 | 1.066141 |
try:
handlers = get_magic_attr(cb)
except AttributeError:
return False
return _attrsignal_spec(descriptor, signal_name, cb, defer) in handlers | def is_attrsignal_handler(descriptor, signal_name, cb, *, defer=False) | Return true if `cb` has been decorated with :func:`attrsignal` for the
given signal, descriptor and connection mode. | 7.480339 | 6.918456 | 1.081215 |
cm = self.init_cm(instance)
obj = stack.enter_context(cm)
self._data[instance] = cm, obj
return obj | def add_to_stack(self, instance, stack) | Get the context manager for the service `instance` and push it to the
context manager `stack`.
:param instance: The service to get the context manager for.
:type instance: :class:`Service`
:param stack: The context manager stack to push the CM onto.
:type stack: :class:`contextl... | 8.886434 | 7.889509 | 1.126361 |
return self.orders_after_any(frozenset([other]), visited=visited) | def orders_after(self, other, *, visited=None) | Return whether `self` depends on `other` and will be instanciated
later.
:param other: Another service.
:type other: :class:`aioxmpp.service.Service`
.. versionadded:: 0.11 | 12.743287 | 19.353472 | 0.65845 |
if not other:
return False
if visited is None:
visited = set()
elif self in visited:
return False
visited.add(self)
for item in self.PATCHED_ORDER_AFTER:
if item in visited:
continue
if item in o... | def orders_after_any(self, other, *, visited=None) | Return whether `self` orders after any of the services in the set
`other`.
:param other: Another service.
:type other: A :class:`set` of
:class:`aioxmpp.service.Service` instances
.. versionadded:: 0.11 | 2.656586 | 2.711071 | 0.979903 |
if self is other:
return False
return not self.orders_after(other) and not other.orders_after(self) | def independent_from(self, other) | Return whether the services are independent (neither depends on
the other).
:param other: Another service.
:type other: :class:`aioxmpp.service.Service`
.. versionadded:: 0.11 | 5.852176 | 8.042613 | 0.727646 |
parts = type(self).__module__.split(".")[1:]
if parts[-1] == "service" and len(parts) > 1:
del parts[-1]
return logger.getChild(".".join(
parts+[type(self).__qualname__]
)) | def derive_logger(self, logger) | Return a child of `logger` specific for this instance. This is called
after :attr:`client` has been set, from the constructor.
The child name is calculated by the default implementation in a way
specific for aioxmpp services; it is not meant to be used by
non-:mod:`aioxmpp` classes; do ... | 4.594657 | 4.308733 | 1.066359 |
if new_limit is None:
self._group_limits.pop(group, None)
return
self._group_limits[group] = new_limit | def set_limit(self, group, new_limit) | Set a new limit on the number of tasks in the `group`.
:param group: Group key of the group to modify.
:type group: hashable
:param new_limit: New limit for the number of tasks running in `group`.
:type new_limit: non-negative :class:`int` or :data:`None`
:raise ValueError: if `... | 2.862204 | 3.12317 | 0.916442 |
# ensure the implicit group is included
__groups = set(__groups) | {()}
return asyncio.ensure_future(__coro_fun(*args, **kwargs)) | def spawn(self, __groups, __coro_fun, *args, **kwargs) | Start a new coroutine and add it to the pool atomically.
:param groups: The groups the coroutine belongs to.
:type groups: :class:`set` of group keys
:param coro_fun: Coroutine function to run
:param args: Positional arguments to pass to `coro_fun`
:param kwargs: Keyword argumen... | 8.051038 | 12.854109 | 0.62634 |
yield from self._check_for_feature()
iq = aioxmpp.IQ(
type_=aioxmpp.IQType.SET,
payload=carbons_xso.Enable()
)
yield from self.client.send(iq) | def enable(self) | Enable message carbons.
:raises RuntimeError: if the server does not support message carbons.
:raises aioxmpp.XMPPError: if the server responded with an error to the
request.
:raises: as specified in :meth:`aioxmpp.Client.send` | 11.424978 | 8.727576 | 1.309067 |
yield from self._check_for_feature()
iq = aioxmpp.IQ(
type_=aioxmpp.IQType.SET,
payload=carbons_xso.Disable()
)
yield from self.client.send(iq) | def disable(self) | Disable message carbons.
:raises RuntimeError: if the server does not support message carbons.
:raises aioxmpp.XMPPError: if the server responded with an error to the
request.
:raises: as specified in :meth:`aioxmpp.Client.send` | 11.973628 | 9.07863 | 1.31888 |
stream.register_iq_request_handler(
type_,
payload_cls,
coro,
with_send_reply=with_send_reply,
)
try:
yield
finally:
stream.unregister_iq_request_handler(type_, payload_cls) | def iq_handler(stream, type_, payload_cls, coro, *, with_send_reply=False) | Context manager to temporarily register a coroutine to handle IQ requests
on a :class:`StanzaStream`.
:param stream: Stanza stream to register the coroutine at
:type stream: :class:`StanzaStream`
:param type_: IQ type to react to (must be a request type).
:type type_: :class:`~aioxmpp.IQType`
:... | 2.223537 | 2.72191 | 0.816903 |
stream.register_message_callback(
type_,
from_,
cb,
)
try:
yield
finally:
stream.unregister_message_callback(
type_,
from_,
) | def message_handler(stream, type_, from_, cb) | Context manager to temporarily register a callback to handle messages on a
:class:`StanzaStream`.
:param stream: Stanza stream to register the coroutine at
:type stream: :class:`StanzaStream`
:param type_: Message type to listen for, or :data:`None` for a wildcard
match.
:type typ... | 3.250539 | 4.648345 | 0.699289 |
stream.register_presence_callback(
type_,
from_,
cb,
)
try:
yield
finally:
stream.unregister_presence_callback(
type_,
from_,
) | def presence_handler(stream, type_, from_, cb) | Context manager to temporarily register a callback to handle presence
stanzas on a :class:`StanzaStream`.
:param stream: Stanza stream to register the coroutine at
:type stream: :class:`StanzaStream`
:param type_: Presence type to listen for.
:type type_: :class:`~.PresenceType`
:param from_: S... | 3.37786 | 4.382294 | 0.770797 |
if order is not _Undefined:
return filter_.context_register(func, order)
else:
return filter_.context_register(func) | def stanza_filter(filter_, func, order=_Undefined) | This is a deprecated alias of
:meth:`aioxmpp.callbacks.Filter.context_register`.
.. versionadded:: 0.8
.. deprecated:: 0.9 | 4.434865 | 3.336831 | 1.329065 |
if (self._state != StanzaState.ACTIVE and
self._state != StanzaState.ABORTED):
raise RuntimeError("cannot abort stanza (already sent)")
self._set_state(StanzaState.ABORTED) | def abort(self) | Abort the stanza. Attempting to call this when the stanza is in any
non-:class:`~StanzaState.ACTIVE`, non-:class:`~StanzaState.ABORTED`
state results in a :class:`RuntimeError`.
When a stanza is aborted, it will reside in the active queue of the
stream, not will be sent and instead disc... | 6.066006 | 3.740972 | 1.621505 |
try:
task.result()
except asyncio.CancelledError:
# normal termination
pass
except Exception as err:
try:
if self._sm_enabled:
self._xmlstream.abort()
else:
self._xmls... | def _done_handler(self, task) | Called when the main task (:meth:`_run`, :attr:`_task`) returns. | 5.65799 | 5.763775 | 0.981646 |
self._logger.debug("destroying stream state (exc=%r)", exc)
self._iq_response_map.close_all(exc)
for task in self._iq_request_tasks:
# we don’t need to remove, that’s handled by their
# add_done_callback
task.cancel()
while not self._active_qu... | def _destroy_stream_state(self, exc) | Destroy all state which does not make sense to keep after a disconnect
(without stream management). | 5.999207 | 5.546409 | 1.081638 |
try:
payload = task.result()
except errors.XMPPError as err:
self._send_iq_reply(request, err)
except Exception:
response = self._compose_undefined_condition(request)
self._enqueue(response)
self._logger.exception("IQ request c... | def _iq_request_coro_done_send_reply(self, request, task) | Called when an IQ request handler coroutine returns. `request` holds
the IQ request which triggered the excecution of the coroutine and
`task` is the :class:`asyncio.Task` which tracks the running coroutine.
Compose a response and send that response. | 4.817651 | 4.539435 | 1.061289 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.