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()
left = func(left, right)
return left | 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 = [keys]
if args:
keys.extend(args)
return keys | 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).encode('utf-8')
elif not isinstance(value, basestring):
value = str(value).encode('utf-8')
else:
value = value.encode('utf-8', 'strict')
return value | 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
if not start_inclusive:
while left < right and self._scores[left][0] == start:
left += 1
return self._scores[left:right] | 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:
self._reset() | 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 '{}'. Supported languages: {}".format(
lang, ", ".join(cls.SUPPORTED_LANGUAGES))) | 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")
iso_languages = [Language.convert_to_iso(lang) for lang in languages]
duckling_load.invoke(
clojure_hashmap.invoke(
self.clojure.read(':languages'),
clojure_list.invoke(*iso_languages)
)
)
else:
duckling_load.invoke()
self._is_loaded = True | 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_duckling_language_id(language)
duckling_parse = self.clojure.var("duckling.core", "parse")
duckling_time = self.clojure.var("duckling.time.obj", "t")
clojure_hashmap = self.clojure.var("clojure.core", "hash-map")
filter_str = '[]'
if isinstance(dim_filter, string_types):
filter_str = '[:{filter}]'.format(filter=dim_filter)
elif isinstance(dim_filter, list):
filter_str = '[{filter}]'.format(filter=' :'.join(dim_filter))
if reference_time:
duckling_result = duckling_parse.invoke(
language,
input_str,
self.clojure.read(filter_str),
clojure_hashmap.invoke(
self.clojure.read(':reference-time'),
duckling_time.invoke(
*self._parse_reference_time(reference_time))
)
)
else:
duckling_result = duckling_parse.invoke(
language, input_str, self.clojure.read(filter_str))
return self._parse_result(duckling_result) | 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,
e.g. Duckling.ENGLISH or supported ISO 639-1 Code (e.g. "en")
dim_filter: Optional parameter to specify a single filter or
list of filters for dimensions in Duckling.
reference_time: Optional reference time for Duckling.
Returns:
A list of dicts with the result from the Duckling.parse() call.
Raises:
RuntimeError: An error occurres when Duckling model is not loaded
via load(). | 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:
[
{
"dim":"time",
"end":21,
"start":11,
"value":{
"value":"2016-10-11T11:45:00.000-07:00",
"others":[
"2016-10-11T11:45:00.000-07:00",
"2016-10-12T11:45:00.000-07:00",
"2016-10-13T11:45:00.000-07:00"
]
},
"text":"at 11:45am"
}
] | 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
command supported by the peer. The :attr:`~.disco.xso.Item.node`
attribute is the identifier of the command which can be used with
:meth:`get_command_info` and :meth:`execute`. | 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 information about the command
Sends a service discovery query to the service discovery node of the
command. The returned object contains information about the command,
such as the namespaces used by its implementation (generally the
:xep:`4` data forms namespace) and possibly localisations of the
commands name.
The `command_name` can be obtained by inspecting the listing from
:meth:`get_commands` or from well-known command names as defined for
example in :xep:`133`. | 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 that a peer supports the protocol does not imply
that it offers any commands. | 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`
:return: A started command execution session.
Initialises a client session and starts execution of the command. The
session is returned.
This may raise any exception which may be raised by
:meth:`~.adhoc.service.ClientSession.start`. | 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: Coroutine function to run to get the response for a
request.
:param is_allowed: A predicate which determines whether the command is
shown and allowed for a given peer.
:type is_allowed: function or :data:`None`
:param features: Set of features to announce for the command
:type features: :class:`set` of :class:`str`
When a request for the command is received, `handler` is invoked. The
semantics of `handler` are the same as for
:meth:`~.StanzaStream.register_iq_request_handler`. It must produce a
valid :class:`~.adhoc.xso.Command` response payload.
If `is_allowed` is not :data:`None`, it is invoked whenever a command
listing is generated and whenever a command request is received. The
:class:`aioxmpp.JID` of the requester is passed as positional argument
to `is_allowed`. If `is_allowed` returns false, the command is not
included in the list and attempts to execute it are rejected with
``<forbidden/>`` without calling `handler`.
If `is_allowed` is :data:`None`, the command is always visible and
allowed.
The `features` are returned on a service discovery info request for the
command node. By default, the :xep:`4` (Data Forms) namespace is
included, but this can be overridden by passing a different set without
that feature to `features`. | 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 from self._stream.send_iq_and_wait_for_reply(
request,
)
return self._response.first_payload | 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 updated
with the newly received values. | 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(
self._command_name,
action=action,
payload=self._response.payload if payload is None else payload,
sessionid=self.sessionid,
)
request = aioxmpp.IQ(
type_=aioxmpp.IQType.SET,
to=self._peer_jid,
payload=cmd,
)
try:
self._response = \
yield from self._stream.send_iq_and_wait_for_reply(
request,
)
except (aioxmpp.errors.XMPPModifyError,
aioxmpp.errors.XMPPCancelError) as exc:
if isinstance(exc.application_defined_condition,
(adhoc_xso.BadSessionID,
adhoc_xso.SessionExpired)):
yield from self.close()
raise SessionError(exc.text)
if isinstance(exc, aioxmpp.errors.XMPPCancelError):
yield from self.close()
raise
return self._response.first_payload | 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 actions returned by
:attr:`allowed_actions`. It defaults to :attr:`~.ActionType.EXECUTE`,
which is (alongside with :attr:`~.ActionType.CANCEL`) always allowed.
`payload` may be a sequence of XSOs, a single XSO or :data:`None`. If
it is :data:`None`, the XSOs from the request are re-used. This is
useful if you modify the payload in-place (e.g. via
:attr:`first_payload`). Otherwise, the payload on the request is set to
the `payload` argument; if it is a single XSO, it is wrapped in a
sequence.
The :attr:`status`, :attr:`response` and related attributes get updated
with the newly received values. | 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
`(transport, protocol)` | 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
# XXX: retry on XMPPModifyError with RESOURCE_CONSTRAINT
yield from self.client.send(
aioxmpp.IQ(
aioxmpp.IQType.SET,
to=peer_jid,
payload=open_,
)
)
handle = self._sessions[sid, peer_jid] = IBBTransport(
self,
peer_jid,
sid,
stanza_type,
block_size,
)
protocol = protocol_factory()
handle.set_protocol(protocol)
return handle, protocol | 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 JID with which to establish the byte-stream.
:type peer_jid: :class:`aioxmpp.JID`
:param stanza_type: the stanza type to use
:type stanza_type: class:`~aioxmpp.ibb.IBBStanzaType`
:param block_size: the maximal size of blocks to transfer
:type block_size: :class:`int`
:param sid: the session id to use
:type sid: :class:`str` (must be a valid NMTOKEN)
:returns: the transport and protocol
:rtype: a tuple of :class:`aioxmpp.ibb.service.IBBTransport`
and :class:`asyncio.Protocol` | 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('index')
anchor = ''
anchorindex = target.find('#')
if anchorindex > 0:
target, anchor = target[:anchorindex], target[anchorindex:]
try:
xepnum = int(target)
except ValueError:
msg = inliner.reporter.error('invalid XEP number %s' % target,
line=lineno)
prb = inliner.problematic(rawtext, rawtext, msg)
return [prb], [msg]
target = "{:04d}".format(xepnum)
if not has_explicit_title:
title = "XEP-" + target
indexnode = addnodes.index()
targetnode = nodes.target('', '', ids=[targetid])
inliner.document.note_explicit_target(targetnode)
indexnode['entries'] = [
('single', _('XMPP Extension Protocols (XEPs); XEP %s') % target,
targetid, '')]
ref = inliner.document.settings.xep_base_url + 'xep-%04d.html' % xepnum
rn = nodes.reference(title, title, internal=False, refuri=ref+anchor,
classes=[typ])
return [indexnode, targetnode, rn], [] | 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 respective class’ constructor.
.. versionadded:: 0.10
.. deprecated:: 0.10
This function was introduced to ease the transition in 0.10 from
a unified :class:`EnumType` to split :class:`EnumCDataType` and
:class:`EnumElementType`.
It will be removed in 1.0. | 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.conversation.ConversationFeature.SEND_MESSAGE_TRACKED,
aioxmpp.im.conversation.ConversationFeature.SET_TOPIC,
aioxmpp.im.conversation.ConversationFeature.SET_NICK,
aioxmpp.im.conversation.ConversationFeature.INVITE,
aioxmpp.im.conversation.ConversationFeature.INVITE_DIRECT,
} | 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
# to a MUC.
msg.xep0045_muc_user = muc_xso.UserExt()
result = self.service.client.enqueue(msg)
return result | 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; those will be overridden by this method to conform
to the requirements of a message to the MUC. Other attributes are left
untouched (except that :meth:`~.StanzaBase.autoset_id` is called) and
can be used as desired for the message.
.. seealso::
:meth:`.AbstractConversation.send_message` for the full interface
specification. | 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
# to a MUC.
msg.xep0045_muc_user = muc_xso.UserExt()
msg.autoset_id()
tracking_svc = self.service.dependencies[
aioxmpp.tracking.BasicTrackingService
]
tracker = aioxmpp.tracking.MessageTracker()
id_key = msg.id_
body_key = _extract_one_pair(msg.body)
self._tracking_by_id[id_key] = tracker
self._tracking_metadata[tracker] = (
id_key,
body_key,
)
self._tracking_by_body.setdefault(
body_key,
[]
).append(tracker)
tracker.on_closed.connect(functools.partial(
self._tracker_closed,
tracker,
))
token = tracking_svc.send_tracked(msg, tracker)
self.on_message(
msg,
self._this_occupant,
aioxmpp.im.dispatcher.MessageSource.STREAM,
tracker=tracker,
)
return token, tracker | 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
:xep:`45` is written. It will work in many cases, probably in all
cases you test during development, but it may fail to work for some
individual messages and it may fail to work consistently for some
services. See the implementation details below for reasons.
The message is tracked and is considered
:attr:`~.MessageState.DELIVERED_TO_RECIPIENT` when it is reflected back
to us by the MUC service. The reflected message is then available in
the :attr:`~.MessageTracker.response` attribute.
.. note::
Two things:
1. The MUC service may change the contents of the message. An
example of this is the Prosody developer MUC which replaces
messages with more than a few lines with a pastebin link.
2. Reflected messages which are caught by tracking are not emitted
through :meth:`on_message`.
There is no need to set the address attributes or the type of the
message correctly; those will be overridden by this method to conform
to the requirements of a message to the MUC. Other attributes are left
untouched (except that :meth:`~.StanzaBase.autoset_id` is called) and
can be used as desired for the message.
.. warning::
Using :meth:`send_message_tracked` before :meth:`on_join` has
emitted will cause the `member` object in the resulting
:meth:`on_message` event to be :data:`None` (the message will be
delivered just fine).
Using :meth:`send_message_tracked` before history replay is over
will cause the :meth:`on_message` event to be emitted during
history replay, even though everyone else in the MUC will -- of
course -- only see the message after the history.
:meth:`send_message` is not affected by these quirks.
.. seealso::
:meth:`.AbstractConversation.send_message_tracked` for the full
interface specification.
**Implementation details:** Currently, we try to detect reflected
messages using two different criteria. First, if we see a message with
the same message ID (note that message IDs contain 120 bits of entropy)
as the message we sent, we consider it as the reflection. As some MUC
services re-write the message ID in the reflection, as a fallback, we
also consider messages which originate from the correct sender and have
the correct body a reflection.
Obviously, this fails consistently in MUCs which re-write the body and
re-write the ID and randomly if the MUC always re-writes the ID but
only sometimes the body. | 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
nickname; observe the :meth:`on_nick_change` event.
.. seealso::
:meth:`.AbstractConversation.set_nick` for the full interface
specification. | 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 server returned an error for
the kick command.
.. seealso::
:meth:`.AbstractConversation.kick` for the full interface
specification. | 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.AdminQuery(
items=[
muc_xso.AdminItem(nick=nick,
reason=reason,
role=role)
]
)
yield from self.service.client.send(iq) | 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
others).
Change the role of an occupant, identified by their `nick`, to the
given new `role`. Optionally, a `reason` for the role change can be
provided.
Setting the different roles require different privilegues of the local
user. The details can be checked in :xep:`0045` and are enforced solely
by the server, not local code.
The coroutine returns when the role change has been acknowledged by the
server. If the server returns an error, an appropriate
:class:`aioxmpp.errors.XMPPError` subclass is raised. | 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 indicating that the member should be
removed from the conversation immediately, too.
:type request_kick: :class:`bool`
`request_kick` is supported by MUC, but setting it to false has no
effect: banned members are always immediately kicked.
.. seealso::
:meth:`.AbstractConversation.ban` for the full interface
specification. | 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;
:data:`None` is a valid key. | 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
)
yield from self.service.client.send(presence)
yield from fut | 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.FieldType.HIDDEN,
var="FORM_TYPE",
values=["http://jabber.org/protocol/muc#request"],
),
)
data.fields.append(
aioxmpp.forms.Field(
type_=aioxmpp.forms.FieldType.LIST_SINGLE,
var="muc#role",
values=["participant"],
)
)
msg.xep0004_data.append(data)
yield from self.service.client.send(msg) | 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 the :meth:`on_role_change` signal.
.. versionadded:: 0.8 | 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(
type_=aioxmpp.structs.IQType.SET,
to=mucjid
)
iq.payload = muc_xso.AdminQuery(
items=[
muc_xso.AdminItem(jid=jid,
reason=reason,
affiliation=affiliation)
]
)
yield from self.client.send(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 new affiliation for the entity.
:type affiliation: :class:`str`
:param reason: Optional reason for the affiliation change.
:type reason: :class:`str` or :data:`None`
Change the affiliation of the given `jid` with the MUC identified by
the bare `mucjid` to the given new `affiliation`. Optionally, a
`reason` can be given.
If you are joined in the MUC, :meth:`Room.muc_set_affiliation` may be
more convenient, but it is possible to modify the affiliations of a MUC
without being joined, given sufficient privilegues.
Setting the different affiliations require different privilegues of the
local user. The details can be checked in :xep:`0045` and are enforced
solely by the server, not local code.
The coroutine returns when the change in affiliation has been
acknowledged by the server. If the server returns an error, an
appropriate :class:`aioxmpp.errors.XMPPError` subclass is raised. | 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)).form | 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:`~.ConfigurationForm`
for a form template to work with the returned form
.. versionadded:: 0.7 | 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`
for a form template to generate the required form
A sensible workflow to, for example, set a room to be moderated, could
be this::
form = aioxmpp.muc.ConfigurationForm.from_xso(
(await muc_service.get_room_config(mucjid))
)
form.moderatedroom = True
await muc_service.set_rooom_config(mucjid, form.render_reply())
.. versionadded:: 0.7 | 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 generate the URL.
:type filename: :class:`str`
:param size: Size of the file in bytes
:type size: :class:`int`
:param content_type: The MIME type of the file
:type content_type: :class:`str`
:return: The assigned upload slot.
:rtype: :class:`.xso.Slot`
Sends a :xep:`363` slot request to the XMPP service to obtain HTTP
PUT and GET URLs for a file upload.
The upload slot is returned as a :class:`~.xso.Slot` object. | 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 received
:raises aioxmpp.errors.XMPPError: if an XMPP error was returned instead
of a reply.
:rtype: :class:`aioxmpp.version.xso.Query`
:return: The response from the peer.
The response is returned as :class:`~aioxmpp.version.xso.Query` object. The
attributes hold the data returned by the peer. Each attribute may be
:data:`None` if the peer chose to omit that information. In an extreme
case, all attributes are :data:`None`. | 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.match_str
if match_str == range_str:
yield language
found.add(language)
continue
if len(range_str) < len(match_str):
if (match_str[:len(range_str)] == range_str and
match_str[len(range_str)] == "-"):
yield language
found.add(language)
continue | 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 ranges must be given as
:class:`LanguageRange` objects.
Return an iterator of languages which matched any of the `ranges`. The
sequence produced by the iterator is in match order and duplicate-free. The
first range to match a language yields the language into the iterator, no
other range can yield that language afterwards. | 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_range.strip_rightmost()
except ValueError:
break | 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 of :class:`LanguageRange` objects. | 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_unassigned=not strict
)
new_kwargs["localpart"] = localpart
try:
domain = kwargs.pop("domain")
except KeyError:
pass
else:
if not domain:
raise ValueError("domain must not be empty or None")
new_kwargs["domain"] = nameprep(
domain,
allow_unassigned=not strict
)
try:
resource = kwargs.pop("resource")
except KeyError:
pass
else:
if resource:
resource = resourceprep(
resource,
allow_unassigned=not strict
)
new_kwargs["resource"] = resource
if kwargs:
raise TypeError("replace() got an unexpected keyword argument"
" {!r}".format(
next(iter(kwargs))))
return super()._replace(**new_kwargs) | 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 resulting JID.
:param resource: Set the resource part of the resulting JID.
:raises: See :class:`JID`
:return: A new :class:`JID` object with the corresponding
substitutions performed.
:rtype: :class:`JID`
The attributes of parameters which are omitted are not modified and
copied down to the result. | 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 the :class:`JID` class level documentation for the semantics of
`strict`. | 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
mapping contains an entry with key :data:`None`, that entry is
returned, otherwise :class:`KeyError` is raised. | 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:`aioxmpp.JID`
:rtype: :class:`Conversation`
:return: The new or existing conversation with the peer.
`peer_jid` must be a full or bare JID. See the :class:`Service`
documentation for details.
.. versionchanged:: 0.10
In 0.9, this was a coroutine. Sorry. | 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.weight, (str(rec.target), rec.port))
for rec in answer
]
for i, (prio, weight, (host, port)) in enumerate(items):
if host == ".":
raise ValueError(
"protocol {!r} over {!r} not supported at {!r}".format(
service,
transport,
domain
)
)
items[i] = (prio, weight, (
host.rstrip(".").encode("ascii"),
port))
return items | 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 of tuples ``(prio, weight, (hostname, port))``, where
`hostname` is a IDNA-encoded :class:`bytes` object containing the hostname
obtained from the SRV record. The other fields are also as obtained from
the SRV records. The trailing dot is stripped from the `hostname`.
If the DNS query returns an empty result, :data:`None` is returned. If any
of the found SRV records has the root zone (``.``) as `hostname`, this
indicates that the service is not available at the given `domain` and
:class:`ValueError` is raised. | 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
items = [
(rec.usage, rec.selector, rec.mtype, rec.cert)
for rec in answer
]
return items | 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 :data:`True` here.
Return a list of tuples ``(usage, selector, mtype, cert)`` which contains
the information from the TLSA records.
If no data is returned by the query, :data:`None` is returned instead. | 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:
if len(records) == 1:
yield records[0][-1]
break
value = rng.randint(0, total_weight)
running_weight_sum = 0
for i, (_, weight, addr) in enumerate(records):
running_weight_sum += weight
if running_weight_sum >= value:
yield addr
del records[i]
total_weight -= weight
break | 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` implementation is used (if none is given, the
:mod:`random` module is used). | 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 function
carried in the handler spec.
:type kwargs: :class:`dict`
:raises ValueError: if the handler was registered with
different `kwargs` before
This uses a private attribute, whose exact name is an implementation
detail. The `handler_spec` is stored in a :class:`dict` bound to the
attribute.
.. versionadded:: 0.11
The `kwargs` argument. If two handlers with the same spec, but
different arguments are registered for one function, an error
will be raised. So you should always include all possible
arguments, this is the responsibility of the calling decorator. | 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_payload_class decorator)".format(
payload_cls,
)
)
def decorator(f):
add_handler_spec(
f,
HandlerSpec(
(_apply_iq_handler, (type_, payload_cls)),
require_deps=(),
),
kwargs=dict(with_send_reply=with_send_reply),
)
return f
return decorator | 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 send a reply
to the decorated callable as second argument.
:type with_send_reply: :class:`bool`
:raises ValueError: if `payload_cls` is not a registered IQ payload
If the decorated function is not a coroutine function, it must return an
awaitable instead.
.. seealso::
:meth:`~.StanzaStream.register_iq_request_handler` for more
details on the `type_`, `payload_cls` and
`with_send_reply` arguments, as well as behaviour expected
from the decorated function.
:meth:`aioxmpp.IQ.as_payload_class`
for a way to register a XSO as IQ payload
.. versionadded:: 0.11
The `with_send_reply` argument.
.. versionchanged:: 0.10
The decorator now checks if `payload_cls` is a valid, registered IQ
payload and raises :class:`ValueError` if not. | 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
:param signal_name: Attribute name of the signal to connect to
:type signal_name: :class:`str`
:param defer: Flag indicating whether deferred execution of the decorated
method is desired; see below for details.
:type defer: :class:`bool`
The signal is discovered by accessing the attribute with the name
`signal_name` on the given `class_`. In addition, the following arguments
are supported for `class_`:
1. :class:`aioxmpp.stream.StanzaStream`: the corresponding signal of the
stream of the client running the service is used.
2. :class:`aioxmpp.Client`: the corresponding signal of the client running
the service is used.
If the signal is a :class:`.callbacks.Signal` and `defer` is false, the
decorated object is connected using the default
:attr:`~.callbacks.AdHocSignal.STRONG` mode.
If the signal is a :class:`.callbacks.Signal` and `defer` is true and the
decorated object is a coroutine function, the
:attr:`~.callbacks.AdHocSignal.SPAWN_WITH_LOOP` mode with the default
asyncio event loop is used. If the decorated object is not a coroutine
function, :attr:`~.callbacks.AdHocSignal.ASYNC_WITH_LOOP` is used instead.
If the signal is a :class:`.callbacks.SyncSignal`, `defer` must be false
and the decorated object must be a coroutine function.
.. versionchanged:: 0.9
Support for :class:`aioxmpp.stream.StanzaStream` and
:class:`aioxmpp.Client` as `class_` argument was added. | 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: Flag indicating whether deferred execution of the decorated
method is desired; see below for details.
:type defer: :class:`bool`
The signal is discovered by accessing the attribute with the name
`signal_name` on the :attr:`~Descriptor.value_type` of the `descriptor`.
During instantiation of the service, the value of the descriptor is used
to obtain the signal and then the decorated method is connected to the
signal.
If the signal is a :class:`.callbacks.Signal` and `defer` is false, the
decorated object is connected using the default
:attr:`~.callbacks.AdHocSignal.STRONG` mode.
If the signal is a :class:`.callbacks.Signal` and `defer` is true and the
decorated object is a coroutine function, the
:attr:`~.callbacks.AdHocSignal.SPAWN_WITH_LOOP` mode with the default
asyncio event loop is used. If the decorated object is not a coroutine
function, :attr:`~.callbacks.AdHocSignal.ASYNC_WITH_LOOP` is used instead.
If the signal is a :class:`.callbacks.SyncSignal`, `defer` must be false
and the decorated object must be a coroutine function.
.. versionadded:: 0.9 | 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.stream.StanzaStream`
:param filter_name: Attribute name of the filter to register at
:type filter_name: :class:`str`
The filter at which the decorated method is registered is discovered by
accessing the attribute with the name `filter_name` on the instance of the
dependent class `class_`. If `class_` is
:class:`aioxmpp.stream.StanzaStream`, the filter is searched for on the
stream (and no dependendency needs to be declared).
.. versionadded:: 0.9 | 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:`contextlib.ExitStack`
:return: The object returned by the context manager on enter.
If a context manager has already been created for `instance`, it is
re-used.
On subsequent calls to :meth:`__get__` for the given `instance`, the
return value of this method will be returned, that is, the value
obtained from entering the context. | 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 other:
return True
if item.orders_after_any(other, visited=visited):
return True
return False | 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 not rely on the way how the child name
is calculated. | 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 `new_limit` is non-positive
The limit of tasks for the `group` is set to `new_limit`. If there are
currently more than `new_limit` tasks running in `group`, those tasks
will continue to run, however, the creation of new tasks is inhibited
until the group is below its limit.
If the limit is set to zero, no new tasks can be spawned in the group
at all.
If `new_limit` is negative :class:`ValueError` is raised instead.
If `new_limit` is :data:`None`, the method behaves as if
:meth:`clear_limit` was called for `group`. | 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 arguments to pass to `coro_fun`
:raise RuntimeError: if the limit on any of the groups or the total
limit is exhausted
:rtype: :class:`asyncio.Task`
:return: The task in which the coroutine runs.
Every group must have at least one free slot available for `coro` to be
spawned; if any groups capacity (or the total limit) is exhausted, the
coroutine is not accepted into the pool and :class:`RuntimeError` is
raised.
If the coroutine cannot be added due to limiting, it is not started at
all.
The coroutine is started by calling `coro_fun` with `args` and
`kwargs`.
.. note::
The first two arguments can only be passed positionally, not as
keywords. This is to prevent conflicts with keyword arguments to
`coro_fun`. | 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`
:param payload_cls: Payload class to react to (subclass of
:class:`~xso.XSO`)
:type payload_cls: :class:`~.XMLStreamClass`
:param coro: Coroutine to register
:param with_send_reply: Whether to pass a function to send the reply
early to `cb`.
:type with_send_reply: :class:`bool`
The coroutine is registered when the context is entered and unregistered
when the context is exited. Running coroutines are not affected by exiting
the context manager.
.. versionadded:: 0.11
The `with_send_reply` argument. See
:meth:`aioxmpp.stream.StanzaStream.register_iq_request_handler` for
more detail.
.. versionadded:: 0.8 | 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 type_: :class:`~.MessageType` or :data:`None`
:param from_: Sender JID to listen for, or :data:`None` for a wildcard
match.
:type from_: :class:`~aioxmpp.JID` or :data:`None`
:param cb: Callback to register
The callback is registered when the context is entered and unregistered
when the context is exited.
.. versionadded:: 0.8 | 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_: Sender JID to listen for, or :data:`None` for a wildcard
match.
:type from_: :class:`~aioxmpp.JID` or :data:`None`.
:param cb: Callback to register
The callback is registered when the context is entered and unregistered
when the context is exited.
.. versionadded:: 0.8 | 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 discarded silently. | 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._xmlstream.close()
except Exception:
pass
self.on_failure(err)
self._logger.exception("broker task failed") | 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_queue.empty():
token = self._active_queue.get_nowait()
token._set_state(StanzaState.DISCONNECTED)
if self._established:
self.on_stream_destroyed(exc)
self._established = False | 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 coroutine failed")
else:
self._send_iq_reply(request, payload) | 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.