id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
sequencelengths 20
707
| docstring
stringlengths 3
17.3k
| docstring_tokens
sequencelengths 3
222
| sha
stringlengths 40
40
| url
stringlengths 87
242
| docstring_summary
stringclasses 1
value | parameters
stringclasses 1
value | return_statement
stringclasses 1
value | argument_list
stringclasses 1
value | identifier
stringclasses 1
value | nwo
stringclasses 1
value | score
float32 -1
-1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
600 | locationlabs/mockredis | mockredis/client.py | MockRedis._hincrby | def _hincrby(self, hashkey, attribute, command, type_, increment):
"""Shared hincrby and hincrbyfloat routine"""
redis_hash = self._get_hash(hashkey, command, create=True)
attribute = self._encode(attribute)
previous_value = type_(redis_hash.get(attribute, '0'))
redis_hash[attribute] = self._encode(previous_value + increment)
return type_(redis_hash[attribute]) | python | def _hincrby(self, hashkey, attribute, command, type_, increment):
"""Shared hincrby and hincrbyfloat routine"""
redis_hash = self._get_hash(hashkey, command, create=True)
attribute = self._encode(attribute)
previous_value = type_(redis_hash.get(attribute, '0'))
redis_hash[attribute] = self._encode(previous_value + increment)
return type_(redis_hash[attribute]) | [
"def",
"_hincrby",
"(",
"self",
",",
"hashkey",
",",
"attribute",
",",
"command",
",",
"type_",
",",
"increment",
")",
":",
"redis_hash",
"=",
"self",
".",
"_get_hash",
"(",
"hashkey",
",",
"command",
",",
"create",
"=",
"True",
")",
"attribute",
"=",
"self",
".",
"_encode",
"(",
"attribute",
")",
"previous_value",
"=",
"type_",
"(",
"redis_hash",
".",
"get",
"(",
"attribute",
",",
"'0'",
")",
")",
"redis_hash",
"[",
"attribute",
"]",
"=",
"self",
".",
"_encode",
"(",
"previous_value",
"+",
"increment",
")",
"return",
"type_",
"(",
"redis_hash",
"[",
"attribute",
"]",
")"
] | Shared hincrby and hincrbyfloat routine | [
"Shared",
"hincrby",
"and",
"hincrbyfloat",
"routine"
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L589-L595 | -1 |
||||||
601 | locationlabs/mockredis | mockredis/client.py | MockRedis.lrange | def lrange(self, key, start, stop):
"""Emulate lrange."""
redis_list = self._get_list(key, 'LRANGE')
start, stop = self._translate_range(len(redis_list), start, stop)
return redis_list[start:stop + 1] | python | def lrange(self, key, start, stop):
"""Emulate lrange."""
redis_list = self._get_list(key, 'LRANGE')
start, stop = self._translate_range(len(redis_list), start, stop)
return redis_list[start:stop + 1] | [
"def",
"lrange",
"(",
"self",
",",
"key",
",",
"start",
",",
"stop",
")",
":",
"redis_list",
"=",
"self",
".",
"_get_list",
"(",
"key",
",",
"'LRANGE'",
")",
"start",
",",
"stop",
"=",
"self",
".",
"_translate_range",
"(",
"len",
"(",
"redis_list",
")",
",",
"start",
",",
"stop",
")",
"return",
"redis_list",
"[",
"start",
":",
"stop",
"+",
"1",
"]"
] | Emulate lrange. | [
"Emulate",
"lrange",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L611-L615 | -1 |
||||||
602 | locationlabs/mockredis | mockredis/client.py | MockRedis.lindex | def lindex(self, key, index):
"""Emulate lindex."""
redis_list = self._get_list(key, 'LINDEX')
if self._encode(key) not in self.redis:
return None
try:
return redis_list[index]
except (IndexError):
# Redis returns nil if the index doesn't exist
return None | python | def lindex(self, key, index):
"""Emulate lindex."""
redis_list = self._get_list(key, 'LINDEX')
if self._encode(key) not in self.redis:
return None
try:
return redis_list[index]
except (IndexError):
# Redis returns nil if the index doesn't exist
return None | [
"def",
"lindex",
"(",
"self",
",",
"key",
",",
"index",
")",
":",
"redis_list",
"=",
"self",
".",
"_get_list",
"(",
"key",
",",
"'LINDEX'",
")",
"if",
"self",
".",
"_encode",
"(",
"key",
")",
"not",
"in",
"self",
".",
"redis",
":",
"return",
"None",
"try",
":",
"return",
"redis_list",
"[",
"index",
"]",
"except",
"(",
"IndexError",
")",
":",
"# Redis returns nil if the index doesn't exist",
"return",
"None"
] | Emulate lindex. | [
"Emulate",
"lindex",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L617-L629 | -1 |
||||||
603 | locationlabs/mockredis | mockredis/client.py | MockRedis._blocking_pop | def _blocking_pop(self, pop_func, keys, timeout):
"""Emulate blocking pop functionality"""
if not isinstance(timeout, (int, long)):
raise RuntimeError('timeout is not an integer or out of range')
if timeout is None or timeout == 0:
timeout = self.blocking_timeout
if isinstance(keys, basestring):
keys = [keys]
else:
keys = list(keys)
elapsed_time = 0
start = time.time()
while elapsed_time < timeout:
key, val = self._pop_first_available(pop_func, keys)
if val:
return key, val
# small delay to avoid high cpu utilization
time.sleep(self.blocking_sleep_interval)
elapsed_time = time.time() - start
return None | python | def _blocking_pop(self, pop_func, keys, timeout):
"""Emulate blocking pop functionality"""
if not isinstance(timeout, (int, long)):
raise RuntimeError('timeout is not an integer or out of range')
if timeout is None or timeout == 0:
timeout = self.blocking_timeout
if isinstance(keys, basestring):
keys = [keys]
else:
keys = list(keys)
elapsed_time = 0
start = time.time()
while elapsed_time < timeout:
key, val = self._pop_first_available(pop_func, keys)
if val:
return key, val
# small delay to avoid high cpu utilization
time.sleep(self.blocking_sleep_interval)
elapsed_time = time.time() - start
return None | [
"def",
"_blocking_pop",
"(",
"self",
",",
"pop_func",
",",
"keys",
",",
"timeout",
")",
":",
"if",
"not",
"isinstance",
"(",
"timeout",
",",
"(",
"int",
",",
"long",
")",
")",
":",
"raise",
"RuntimeError",
"(",
"'timeout is not an integer or out of range'",
")",
"if",
"timeout",
"is",
"None",
"or",
"timeout",
"==",
"0",
":",
"timeout",
"=",
"self",
".",
"blocking_timeout",
"if",
"isinstance",
"(",
"keys",
",",
"basestring",
")",
":",
"keys",
"=",
"[",
"keys",
"]",
"else",
":",
"keys",
"=",
"list",
"(",
"keys",
")",
"elapsed_time",
"=",
"0",
"start",
"=",
"time",
".",
"time",
"(",
")",
"while",
"elapsed_time",
"<",
"timeout",
":",
"key",
",",
"val",
"=",
"self",
".",
"_pop_first_available",
"(",
"pop_func",
",",
"keys",
")",
"if",
"val",
":",
"return",
"key",
",",
"val",
"# small delay to avoid high cpu utilization",
"time",
".",
"sleep",
"(",
"self",
".",
"blocking_sleep_interval",
")",
"elapsed_time",
"=",
"time",
".",
"time",
"(",
")",
"-",
"start",
"return",
"None"
] | Emulate blocking pop functionality | [
"Emulate",
"blocking",
"pop",
"functionality"
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L638-L660 | -1 |
||||||
604 | locationlabs/mockredis | mockredis/client.py | MockRedis.lpush | def lpush(self, key, *args):
"""Emulate lpush."""
redis_list = self._get_list(key, 'LPUSH', create=True)
# Creates the list at this key if it doesn't exist, and appends args to its beginning
args_reversed = [self._encode(arg) for arg in args]
args_reversed.reverse()
updated_list = args_reversed + redis_list
self.redis[self._encode(key)] = updated_list
# Return the length of the list after the push operation
return len(updated_list) | python | def lpush(self, key, *args):
"""Emulate lpush."""
redis_list = self._get_list(key, 'LPUSH', create=True)
# Creates the list at this key if it doesn't exist, and appends args to its beginning
args_reversed = [self._encode(arg) for arg in args]
args_reversed.reverse()
updated_list = args_reversed + redis_list
self.redis[self._encode(key)] = updated_list
# Return the length of the list after the push operation
return len(updated_list) | [
"def",
"lpush",
"(",
"self",
",",
"key",
",",
"*",
"args",
")",
":",
"redis_list",
"=",
"self",
".",
"_get_list",
"(",
"key",
",",
"'LPUSH'",
",",
"create",
"=",
"True",
")",
"# Creates the list at this key if it doesn't exist, and appends args to its beginning",
"args_reversed",
"=",
"[",
"self",
".",
"_encode",
"(",
"arg",
")",
"for",
"arg",
"in",
"args",
"]",
"args_reversed",
".",
"reverse",
"(",
")",
"updated_list",
"=",
"args_reversed",
"+",
"redis_list",
"self",
".",
"redis",
"[",
"self",
".",
"_encode",
"(",
"key",
")",
"]",
"=",
"updated_list",
"# Return the length of the list after the push operation",
"return",
"len",
"(",
"updated_list",
")"
] | Emulate lpush. | [
"Emulate",
"lpush",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L693-L704 | -1 |
||||||
605 | locationlabs/mockredis | mockredis/client.py | MockRedis.rpop | def rpop(self, key):
"""Emulate lpop."""
redis_list = self._get_list(key, 'RPOP')
if self._encode(key) not in self.redis:
return None
try:
value = redis_list.pop()
if len(redis_list) == 0:
self.delete(key)
return value
except (IndexError):
# Redis returns nil if popping from an empty list
return None | python | def rpop(self, key):
"""Emulate lpop."""
redis_list = self._get_list(key, 'RPOP')
if self._encode(key) not in self.redis:
return None
try:
value = redis_list.pop()
if len(redis_list) == 0:
self.delete(key)
return value
except (IndexError):
# Redis returns nil if popping from an empty list
return None | [
"def",
"rpop",
"(",
"self",
",",
"key",
")",
":",
"redis_list",
"=",
"self",
".",
"_get_list",
"(",
"key",
",",
"'RPOP'",
")",
"if",
"self",
".",
"_encode",
"(",
"key",
")",
"not",
"in",
"self",
".",
"redis",
":",
"return",
"None",
"try",
":",
"value",
"=",
"redis_list",
".",
"pop",
"(",
")",
"if",
"len",
"(",
"redis_list",
")",
"==",
"0",
":",
"self",
".",
"delete",
"(",
"key",
")",
"return",
"value",
"except",
"(",
"IndexError",
")",
":",
"# Redis returns nil if popping from an empty list",
"return",
"None"
] | Emulate lpop. | [
"Emulate",
"lpop",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L706-L720 | -1 |
||||||
606 | locationlabs/mockredis | mockredis/client.py | MockRedis.rpush | def rpush(self, key, *args):
"""Emulate rpush."""
redis_list = self._get_list(key, 'RPUSH', create=True)
# Creates the list at this key if it doesn't exist, and appends args to it
redis_list.extend(map(self._encode, args))
# Return the length of the list after the push operation
return len(redis_list) | python | def rpush(self, key, *args):
"""Emulate rpush."""
redis_list = self._get_list(key, 'RPUSH', create=True)
# Creates the list at this key if it doesn't exist, and appends args to it
redis_list.extend(map(self._encode, args))
# Return the length of the list after the push operation
return len(redis_list) | [
"def",
"rpush",
"(",
"self",
",",
"key",
",",
"*",
"args",
")",
":",
"redis_list",
"=",
"self",
".",
"_get_list",
"(",
"key",
",",
"'RPUSH'",
",",
"create",
"=",
"True",
")",
"# Creates the list at this key if it doesn't exist, and appends args to it",
"redis_list",
".",
"extend",
"(",
"map",
"(",
"self",
".",
"_encode",
",",
"args",
")",
")",
"# Return the length of the list after the push operation",
"return",
"len",
"(",
"redis_list",
")"
] | Emulate rpush. | [
"Emulate",
"rpush",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L722-L730 | -1 |
||||||
607 | locationlabs/mockredis | mockredis/client.py | MockRedis.lrem | def lrem(self, key, value, count=0):
"""Emulate lrem."""
value = self._encode(value)
redis_list = self._get_list(key, 'LREM')
removed_count = 0
if self._encode(key) in self.redis:
if count == 0:
# Remove all ocurrences
while redis_list.count(value):
redis_list.remove(value)
removed_count += 1
elif count > 0:
counter = 0
# remove first 'count' ocurrences
while redis_list.count(value):
redis_list.remove(value)
counter += 1
removed_count += 1
if counter >= count:
break
elif count < 0:
# remove last 'count' ocurrences
counter = -count
new_list = []
for v in reversed(redis_list):
if v == value and counter > 0:
counter -= 1
removed_count += 1
else:
new_list.append(v)
redis_list[:] = list(reversed(new_list))
if removed_count > 0 and len(redis_list) == 0:
self.delete(key)
return removed_count | python | def lrem(self, key, value, count=0):
"""Emulate lrem."""
value = self._encode(value)
redis_list = self._get_list(key, 'LREM')
removed_count = 0
if self._encode(key) in self.redis:
if count == 0:
# Remove all ocurrences
while redis_list.count(value):
redis_list.remove(value)
removed_count += 1
elif count > 0:
counter = 0
# remove first 'count' ocurrences
while redis_list.count(value):
redis_list.remove(value)
counter += 1
removed_count += 1
if counter >= count:
break
elif count < 0:
# remove last 'count' ocurrences
counter = -count
new_list = []
for v in reversed(redis_list):
if v == value and counter > 0:
counter -= 1
removed_count += 1
else:
new_list.append(v)
redis_list[:] = list(reversed(new_list))
if removed_count > 0 and len(redis_list) == 0:
self.delete(key)
return removed_count | [
"def",
"lrem",
"(",
"self",
",",
"key",
",",
"value",
",",
"count",
"=",
"0",
")",
":",
"value",
"=",
"self",
".",
"_encode",
"(",
"value",
")",
"redis_list",
"=",
"self",
".",
"_get_list",
"(",
"key",
",",
"'LREM'",
")",
"removed_count",
"=",
"0",
"if",
"self",
".",
"_encode",
"(",
"key",
")",
"in",
"self",
".",
"redis",
":",
"if",
"count",
"==",
"0",
":",
"# Remove all ocurrences",
"while",
"redis_list",
".",
"count",
"(",
"value",
")",
":",
"redis_list",
".",
"remove",
"(",
"value",
")",
"removed_count",
"+=",
"1",
"elif",
"count",
">",
"0",
":",
"counter",
"=",
"0",
"# remove first 'count' ocurrences",
"while",
"redis_list",
".",
"count",
"(",
"value",
")",
":",
"redis_list",
".",
"remove",
"(",
"value",
")",
"counter",
"+=",
"1",
"removed_count",
"+=",
"1",
"if",
"counter",
">=",
"count",
":",
"break",
"elif",
"count",
"<",
"0",
":",
"# remove last 'count' ocurrences",
"counter",
"=",
"-",
"count",
"new_list",
"=",
"[",
"]",
"for",
"v",
"in",
"reversed",
"(",
"redis_list",
")",
":",
"if",
"v",
"==",
"value",
"and",
"counter",
">",
"0",
":",
"counter",
"-=",
"1",
"removed_count",
"+=",
"1",
"else",
":",
"new_list",
".",
"append",
"(",
"v",
")",
"redis_list",
"[",
":",
"]",
"=",
"list",
"(",
"reversed",
"(",
"new_list",
")",
")",
"if",
"removed_count",
">",
"0",
"and",
"len",
"(",
"redis_list",
")",
"==",
"0",
":",
"self",
".",
"delete",
"(",
"key",
")",
"return",
"removed_count"
] | Emulate lrem. | [
"Emulate",
"lrem",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L732-L765 | -1 |
||||||
608 | locationlabs/mockredis | mockredis/client.py | MockRedis.ltrim | def ltrim(self, key, start, stop):
"""Emulate ltrim."""
redis_list = self._get_list(key, 'LTRIM')
if redis_list:
start, stop = self._translate_range(len(redis_list), start, stop)
self.redis[self._encode(key)] = redis_list[start:stop + 1]
return True | python | def ltrim(self, key, start, stop):
"""Emulate ltrim."""
redis_list = self._get_list(key, 'LTRIM')
if redis_list:
start, stop = self._translate_range(len(redis_list), start, stop)
self.redis[self._encode(key)] = redis_list[start:stop + 1]
return True | [
"def",
"ltrim",
"(",
"self",
",",
"key",
",",
"start",
",",
"stop",
")",
":",
"redis_list",
"=",
"self",
".",
"_get_list",
"(",
"key",
",",
"'LTRIM'",
")",
"if",
"redis_list",
":",
"start",
",",
"stop",
"=",
"self",
".",
"_translate_range",
"(",
"len",
"(",
"redis_list",
")",
",",
"start",
",",
"stop",
")",
"self",
".",
"redis",
"[",
"self",
".",
"_encode",
"(",
"key",
")",
"]",
"=",
"redis_list",
"[",
"start",
":",
"stop",
"+",
"1",
"]",
"return",
"True"
] | Emulate ltrim. | [
"Emulate",
"ltrim",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L767-L773 | -1 |
||||||
609 | locationlabs/mockredis | mockredis/client.py | MockRedis.lset | def lset(self, key, index, value):
"""Emulate lset."""
redis_list = self._get_list(key, 'LSET')
if redis_list is None:
raise ResponseError("no such key")
try:
redis_list[index] = self._encode(value)
except IndexError:
raise ResponseError("index out of range") | python | def lset(self, key, index, value):
"""Emulate lset."""
redis_list = self._get_list(key, 'LSET')
if redis_list is None:
raise ResponseError("no such key")
try:
redis_list[index] = self._encode(value)
except IndexError:
raise ResponseError("index out of range") | [
"def",
"lset",
"(",
"self",
",",
"key",
",",
"index",
",",
"value",
")",
":",
"redis_list",
"=",
"self",
".",
"_get_list",
"(",
"key",
",",
"'LSET'",
")",
"if",
"redis_list",
"is",
"None",
":",
"raise",
"ResponseError",
"(",
"\"no such key\"",
")",
"try",
":",
"redis_list",
"[",
"index",
"]",
"=",
"self",
".",
"_encode",
"(",
"value",
")",
"except",
"IndexError",
":",
"raise",
"ResponseError",
"(",
"\"index out of range\"",
")"
] | Emulate lset. | [
"Emulate",
"lset",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L792-L800 | -1 |
||||||
610 | locationlabs/mockredis | mockredis/client.py | MockRedis._common_scan | def _common_scan(self, values_function, cursor='0', match=None, count=10, key=None):
"""
Common scanning skeleton.
:param key: optional function used to identify what 'match' is applied to
"""
if count is None:
count = 10
cursor = int(cursor)
count = int(count)
if not count:
raise ValueError('if specified, count must be > 0: %s' % count)
values = values_function()
if cursor + count >= len(values):
# we reached the end, back to zero
result_cursor = 0
else:
result_cursor = cursor + count
values = values[cursor:cursor+count]
if match is not None:
regex = re.compile(b'^' + re.escape(self._encode(match)).replace(b'\\*', b'.*') + b'$')
if not key:
key = lambda v: v
values = [v for v in values if regex.match(key(v))]
return [result_cursor, values] | python | def _common_scan(self, values_function, cursor='0', match=None, count=10, key=None):
"""
Common scanning skeleton.
:param key: optional function used to identify what 'match' is applied to
"""
if count is None:
count = 10
cursor = int(cursor)
count = int(count)
if not count:
raise ValueError('if specified, count must be > 0: %s' % count)
values = values_function()
if cursor + count >= len(values):
# we reached the end, back to zero
result_cursor = 0
else:
result_cursor = cursor + count
values = values[cursor:cursor+count]
if match is not None:
regex = re.compile(b'^' + re.escape(self._encode(match)).replace(b'\\*', b'.*') + b'$')
if not key:
key = lambda v: v
values = [v for v in values if regex.match(key(v))]
return [result_cursor, values] | [
"def",
"_common_scan",
"(",
"self",
",",
"values_function",
",",
"cursor",
"=",
"'0'",
",",
"match",
"=",
"None",
",",
"count",
"=",
"10",
",",
"key",
"=",
"None",
")",
":",
"if",
"count",
"is",
"None",
":",
"count",
"=",
"10",
"cursor",
"=",
"int",
"(",
"cursor",
")",
"count",
"=",
"int",
"(",
"count",
")",
"if",
"not",
"count",
":",
"raise",
"ValueError",
"(",
"'if specified, count must be > 0: %s'",
"%",
"count",
")",
"values",
"=",
"values_function",
"(",
")",
"if",
"cursor",
"+",
"count",
">=",
"len",
"(",
"values",
")",
":",
"# we reached the end, back to zero",
"result_cursor",
"=",
"0",
"else",
":",
"result_cursor",
"=",
"cursor",
"+",
"count",
"values",
"=",
"values",
"[",
"cursor",
":",
"cursor",
"+",
"count",
"]",
"if",
"match",
"is",
"not",
"None",
":",
"regex",
"=",
"re",
".",
"compile",
"(",
"b'^'",
"+",
"re",
".",
"escape",
"(",
"self",
".",
"_encode",
"(",
"match",
")",
")",
".",
"replace",
"(",
"b'\\\\*'",
",",
"b'.*'",
")",
"+",
"b'$'",
")",
"if",
"not",
"key",
":",
"key",
"=",
"lambda",
"v",
":",
"v",
"values",
"=",
"[",
"v",
"for",
"v",
"in",
"values",
"if",
"regex",
".",
"match",
"(",
"key",
"(",
"v",
")",
")",
"]",
"return",
"[",
"result_cursor",
",",
"values",
"]"
] | Common scanning skeleton.
:param key: optional function used to identify what 'match' is applied to | [
"Common",
"scanning",
"skeleton",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L882-L910 | -1 |
||||||
611 | locationlabs/mockredis | mockredis/client.py | MockRedis.scan | def scan(self, cursor='0', match=None, count=10):
"""Emulate scan."""
def value_function():
return sorted(self.redis.keys()) # sorted list for consistent order
return self._common_scan(value_function, cursor=cursor, match=match, count=count) | python | def scan(self, cursor='0', match=None, count=10):
"""Emulate scan."""
def value_function():
return sorted(self.redis.keys()) # sorted list for consistent order
return self._common_scan(value_function, cursor=cursor, match=match, count=count) | [
"def",
"scan",
"(",
"self",
",",
"cursor",
"=",
"'0'",
",",
"match",
"=",
"None",
",",
"count",
"=",
"10",
")",
":",
"def",
"value_function",
"(",
")",
":",
"return",
"sorted",
"(",
"self",
".",
"redis",
".",
"keys",
"(",
")",
")",
"# sorted list for consistent order",
"return",
"self",
".",
"_common_scan",
"(",
"value_function",
",",
"cursor",
"=",
"cursor",
",",
"match",
"=",
"match",
",",
"count",
"=",
"count",
")"
] | Emulate scan. | [
"Emulate",
"scan",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L912-L916 | -1 |
||||||
612 | locationlabs/mockredis | mockredis/client.py | MockRedis.sscan | def sscan(self, name, cursor='0', match=None, count=10):
"""Emulate sscan."""
def value_function():
members = list(self.smembers(name))
members.sort() # sort for consistent order
return members
return self._common_scan(value_function, cursor=cursor, match=match, count=count) | python | def sscan(self, name, cursor='0', match=None, count=10):
"""Emulate sscan."""
def value_function():
members = list(self.smembers(name))
members.sort() # sort for consistent order
return members
return self._common_scan(value_function, cursor=cursor, match=match, count=count) | [
"def",
"sscan",
"(",
"self",
",",
"name",
",",
"cursor",
"=",
"'0'",
",",
"match",
"=",
"None",
",",
"count",
"=",
"10",
")",
":",
"def",
"value_function",
"(",
")",
":",
"members",
"=",
"list",
"(",
"self",
".",
"smembers",
"(",
"name",
")",
")",
"members",
".",
"sort",
"(",
")",
"# sort for consistent order",
"return",
"members",
"return",
"self",
".",
"_common_scan",
"(",
"value_function",
",",
"cursor",
"=",
"cursor",
",",
"match",
"=",
"match",
",",
"count",
"=",
"count",
")"
] | Emulate sscan. | [
"Emulate",
"sscan",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L926-L932 | -1 |
||||||
613 | locationlabs/mockredis | mockredis/client.py | MockRedis.zscan | def zscan(self, name, cursor='0', match=None, count=10):
"""Emulate zscan."""
def value_function():
values = self.zrange(name, 0, -1, withscores=True)
values.sort(key=lambda x: x[1]) # sort for consistent order
return values
return self._common_scan(value_function, cursor=cursor, match=match, count=count, key=lambda v: v[0]) | python | def zscan(self, name, cursor='0', match=None, count=10):
"""Emulate zscan."""
def value_function():
values = self.zrange(name, 0, -1, withscores=True)
values.sort(key=lambda x: x[1]) # sort for consistent order
return values
return self._common_scan(value_function, cursor=cursor, match=match, count=count, key=lambda v: v[0]) | [
"def",
"zscan",
"(",
"self",
",",
"name",
",",
"cursor",
"=",
"'0'",
",",
"match",
"=",
"None",
",",
"count",
"=",
"10",
")",
":",
"def",
"value_function",
"(",
")",
":",
"values",
"=",
"self",
".",
"zrange",
"(",
"name",
",",
"0",
",",
"-",
"1",
",",
"withscores",
"=",
"True",
")",
"values",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"1",
"]",
")",
"# sort for consistent order",
"return",
"values",
"return",
"self",
".",
"_common_scan",
"(",
"value_function",
",",
"cursor",
"=",
"cursor",
",",
"match",
"=",
"match",
",",
"count",
"=",
"count",
",",
"key",
"=",
"lambda",
"v",
":",
"v",
"[",
"0",
"]",
")"
] | Emulate zscan. | [
"Emulate",
"zscan",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L943-L949 | -1 |
||||||
614 | locationlabs/mockredis | mockredis/client.py | MockRedis.hscan | def hscan(self, name, cursor='0', match=None, count=10):
"""Emulate hscan."""
def value_function():
values = self.hgetall(name)
values = list(values.items()) # list of tuples for sorting and matching
values.sort(key=lambda x: x[0]) # sort for consistent order
return values
scanned = self._common_scan(value_function, cursor=cursor, match=match, count=count, key=lambda v: v[0]) # noqa
scanned[1] = dict(scanned[1]) # from list of tuples back to dict
return scanned | python | def hscan(self, name, cursor='0', match=None, count=10):
"""Emulate hscan."""
def value_function():
values = self.hgetall(name)
values = list(values.items()) # list of tuples for sorting and matching
values.sort(key=lambda x: x[0]) # sort for consistent order
return values
scanned = self._common_scan(value_function, cursor=cursor, match=match, count=count, key=lambda v: v[0]) # noqa
scanned[1] = dict(scanned[1]) # from list of tuples back to dict
return scanned | [
"def",
"hscan",
"(",
"self",
",",
"name",
",",
"cursor",
"=",
"'0'",
",",
"match",
"=",
"None",
",",
"count",
"=",
"10",
")",
":",
"def",
"value_function",
"(",
")",
":",
"values",
"=",
"self",
".",
"hgetall",
"(",
"name",
")",
"values",
"=",
"list",
"(",
"values",
".",
"items",
"(",
")",
")",
"# list of tuples for sorting and matching",
"values",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
")",
"# sort for consistent order",
"return",
"values",
"scanned",
"=",
"self",
".",
"_common_scan",
"(",
"value_function",
",",
"cursor",
"=",
"cursor",
",",
"match",
"=",
"match",
",",
"count",
"=",
"count",
",",
"key",
"=",
"lambda",
"v",
":",
"v",
"[",
"0",
"]",
")",
"# noqa",
"scanned",
"[",
"1",
"]",
"=",
"dict",
"(",
"scanned",
"[",
"1",
"]",
")",
"# from list of tuples back to dict",
"return",
"scanned"
] | Emulate hscan. | [
"Emulate",
"hscan",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L960-L969 | -1 |
||||||
615 | locationlabs/mockredis | mockredis/client.py | MockRedis.hscan_iter | def hscan_iter(self, name, match=None, count=10):
"""Emulate hscan_iter."""
cursor = '0'
while cursor != 0:
cursor, data = self.hscan(name, cursor=cursor,
match=match, count=count)
for item in data.items():
yield item | python | def hscan_iter(self, name, match=None, count=10):
"""Emulate hscan_iter."""
cursor = '0'
while cursor != 0:
cursor, data = self.hscan(name, cursor=cursor,
match=match, count=count)
for item in data.items():
yield item | [
"def",
"hscan_iter",
"(",
"self",
",",
"name",
",",
"match",
"=",
"None",
",",
"count",
"=",
"10",
")",
":",
"cursor",
"=",
"'0'",
"while",
"cursor",
"!=",
"0",
":",
"cursor",
",",
"data",
"=",
"self",
".",
"hscan",
"(",
"name",
",",
"cursor",
"=",
"cursor",
",",
"match",
"=",
"match",
",",
"count",
"=",
"count",
")",
"for",
"item",
"in",
"data",
".",
"items",
"(",
")",
":",
"yield",
"item"
] | Emulate hscan_iter. | [
"Emulate",
"hscan_iter",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L971-L978 | -1 |
||||||
616 | locationlabs/mockredis | mockredis/client.py | MockRedis.sadd | def sadd(self, key, *values):
"""Emulate sadd."""
if len(values) == 0:
raise ResponseError("wrong number of arguments for 'sadd' command")
redis_set = self._get_set(key, 'SADD', create=True)
before_count = len(redis_set)
redis_set.update(map(self._encode, values))
after_count = len(redis_set)
return after_count - before_count | python | def sadd(self, key, *values):
"""Emulate sadd."""
if len(values) == 0:
raise ResponseError("wrong number of arguments for 'sadd' command")
redis_set = self._get_set(key, 'SADD', create=True)
before_count = len(redis_set)
redis_set.update(map(self._encode, values))
after_count = len(redis_set)
return after_count - before_count | [
"def",
"sadd",
"(",
"self",
",",
"key",
",",
"*",
"values",
")",
":",
"if",
"len",
"(",
"values",
")",
"==",
"0",
":",
"raise",
"ResponseError",
"(",
"\"wrong number of arguments for 'sadd' command\"",
")",
"redis_set",
"=",
"self",
".",
"_get_set",
"(",
"key",
",",
"'SADD'",
",",
"create",
"=",
"True",
")",
"before_count",
"=",
"len",
"(",
"redis_set",
")",
"redis_set",
".",
"update",
"(",
"map",
"(",
"self",
".",
"_encode",
",",
"values",
")",
")",
"after_count",
"=",
"len",
"(",
"redis_set",
")",
"return",
"after_count",
"-",
"before_count"
] | Emulate sadd. | [
"Emulate",
"sadd",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L982-L990 | -1 |
||||||
617 | locationlabs/mockredis | mockredis/client.py | MockRedis.sdiff | def sdiff(self, keys, *args):
"""Emulate sdiff."""
func = lambda left, right: left.difference(right)
return self._apply_to_sets(func, "SDIFF", keys, *args) | python | def sdiff(self, keys, *args):
"""Emulate sdiff."""
func = lambda left, right: left.difference(right)
return self._apply_to_sets(func, "SDIFF", keys, *args) | [
"def",
"sdiff",
"(",
"self",
",",
"keys",
",",
"*",
"args",
")",
":",
"func",
"=",
"lambda",
"left",
",",
"right",
":",
"left",
".",
"difference",
"(",
"right",
")",
"return",
"self",
".",
"_apply_to_sets",
"(",
"func",
",",
"\"SDIFF\"",
",",
"keys",
",",
"*",
"args",
")"
] | Emulate sdiff. | [
"Emulate",
"sdiff",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L997-L1000 | -1 |
||||||
618 | locationlabs/mockredis | mockredis/client.py | MockRedis.sdiffstore | def sdiffstore(self, dest, keys, *args):
"""Emulate sdiffstore."""
result = self.sdiff(keys, *args)
self.redis[self._encode(dest)] = result
return len(result) | python | def sdiffstore(self, dest, keys, *args):
"""Emulate sdiffstore."""
result = self.sdiff(keys, *args)
self.redis[self._encode(dest)] = result
return len(result) | [
"def",
"sdiffstore",
"(",
"self",
",",
"dest",
",",
"keys",
",",
"*",
"args",
")",
":",
"result",
"=",
"self",
".",
"sdiff",
"(",
"keys",
",",
"*",
"args",
")",
"self",
".",
"redis",
"[",
"self",
".",
"_encode",
"(",
"dest",
")",
"]",
"=",
"result",
"return",
"len",
"(",
"result",
")"
] | Emulate sdiffstore. | [
"Emulate",
"sdiffstore",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1002-L1006 | -1 |
||||||
619 | locationlabs/mockredis | mockredis/client.py | MockRedis.sinter | def sinter(self, keys, *args):
"""Emulate sinter."""
func = lambda left, right: left.intersection(right)
return self._apply_to_sets(func, "SINTER", keys, *args) | python | def sinter(self, keys, *args):
"""Emulate sinter."""
func = lambda left, right: left.intersection(right)
return self._apply_to_sets(func, "SINTER", keys, *args) | [
"def",
"sinter",
"(",
"self",
",",
"keys",
",",
"*",
"args",
")",
":",
"func",
"=",
"lambda",
"left",
",",
"right",
":",
"left",
".",
"intersection",
"(",
"right",
")",
"return",
"self",
".",
"_apply_to_sets",
"(",
"func",
",",
"\"SINTER\"",
",",
"keys",
",",
"*",
"args",
")"
] | Emulate sinter. | [
"Emulate",
"sinter",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1008-L1011 | -1 |
||||||
620 | locationlabs/mockredis | mockredis/client.py | MockRedis.sinterstore | def sinterstore(self, dest, keys, *args):
"""Emulate sinterstore."""
result = self.sinter(keys, *args)
self.redis[self._encode(dest)] = result
return len(result) | python | def sinterstore(self, dest, keys, *args):
"""Emulate sinterstore."""
result = self.sinter(keys, *args)
self.redis[self._encode(dest)] = result
return len(result) | [
"def",
"sinterstore",
"(",
"self",
",",
"dest",
",",
"keys",
",",
"*",
"args",
")",
":",
"result",
"=",
"self",
".",
"sinter",
"(",
"keys",
",",
"*",
"args",
")",
"self",
".",
"redis",
"[",
"self",
".",
"_encode",
"(",
"dest",
")",
"]",
"=",
"result",
"return",
"len",
"(",
"result",
")"
] | Emulate sinterstore. | [
"Emulate",
"sinterstore",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1013-L1017 | -1 |
||||||
621 | locationlabs/mockredis | mockredis/client.py | MockRedis.sismember | def sismember(self, name, value):
"""Emulate sismember."""
redis_set = self._get_set(name, 'SISMEMBER')
if not redis_set:
return 0
result = self._encode(value) in redis_set
return 1 if result else 0 | python | def sismember(self, name, value):
"""Emulate sismember."""
redis_set = self._get_set(name, 'SISMEMBER')
if not redis_set:
return 0
result = self._encode(value) in redis_set
return 1 if result else 0 | [
"def",
"sismember",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"redis_set",
"=",
"self",
".",
"_get_set",
"(",
"name",
",",
"'SISMEMBER'",
")",
"if",
"not",
"redis_set",
":",
"return",
"0",
"result",
"=",
"self",
".",
"_encode",
"(",
"value",
")",
"in",
"redis_set",
"return",
"1",
"if",
"result",
"else",
"0"
] | Emulate sismember. | [
"Emulate",
"sismember",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1019-L1026 | -1 |
||||||
622 | locationlabs/mockredis | mockredis/client.py | MockRedis.smove | def smove(self, src, dst, value):
"""Emulate smove."""
src_set = self._get_set(src, 'SMOVE')
dst_set = self._get_set(dst, 'SMOVE')
value = self._encode(value)
if value not in src_set:
return False
src_set.discard(value)
dst_set.add(value)
self.redis[self._encode(src)], self.redis[self._encode(dst)] = src_set, dst_set
return True | python | def smove(self, src, dst, value):
"""Emulate smove."""
src_set = self._get_set(src, 'SMOVE')
dst_set = self._get_set(dst, 'SMOVE')
value = self._encode(value)
if value not in src_set:
return False
src_set.discard(value)
dst_set.add(value)
self.redis[self._encode(src)], self.redis[self._encode(dst)] = src_set, dst_set
return True | [
"def",
"smove",
"(",
"self",
",",
"src",
",",
"dst",
",",
"value",
")",
":",
"src_set",
"=",
"self",
".",
"_get_set",
"(",
"src",
",",
"'SMOVE'",
")",
"dst_set",
"=",
"self",
".",
"_get_set",
"(",
"dst",
",",
"'SMOVE'",
")",
"value",
"=",
"self",
".",
"_encode",
"(",
"value",
")",
"if",
"value",
"not",
"in",
"src_set",
":",
"return",
"False",
"src_set",
".",
"discard",
"(",
"value",
")",
"dst_set",
".",
"add",
"(",
"value",
")",
"self",
".",
"redis",
"[",
"self",
".",
"_encode",
"(",
"src",
")",
"]",
",",
"self",
".",
"redis",
"[",
"self",
".",
"_encode",
"(",
"dst",
")",
"]",
"=",
"src_set",
",",
"dst_set",
"return",
"True"
] | Emulate smove. | [
"Emulate",
"smove",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1032-L1044 | -1 |
||||||
623 | locationlabs/mockredis | mockredis/client.py | MockRedis.spop | def spop(self, name):
"""Emulate spop."""
redis_set = self._get_set(name, 'SPOP')
if not redis_set:
return None
member = choice(list(redis_set))
redis_set.remove(member)
if len(redis_set) == 0:
self.delete(name)
return member | python | def spop(self, name):
"""Emulate spop."""
redis_set = self._get_set(name, 'SPOP')
if not redis_set:
return None
member = choice(list(redis_set))
redis_set.remove(member)
if len(redis_set) == 0:
self.delete(name)
return member | [
"def",
"spop",
"(",
"self",
",",
"name",
")",
":",
"redis_set",
"=",
"self",
".",
"_get_set",
"(",
"name",
",",
"'SPOP'",
")",
"if",
"not",
"redis_set",
":",
"return",
"None",
"member",
"=",
"choice",
"(",
"list",
"(",
"redis_set",
")",
")",
"redis_set",
".",
"remove",
"(",
"member",
")",
"if",
"len",
"(",
"redis_set",
")",
"==",
"0",
":",
"self",
".",
"delete",
"(",
"name",
")",
"return",
"member"
] | Emulate spop. | [
"Emulate",
"spop",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1046-L1055 | -1 |
||||||
624 | locationlabs/mockredis | mockredis/client.py | MockRedis.srandmember | def srandmember(self, name, number=None):
"""Emulate srandmember."""
redis_set = self._get_set(name, 'SRANDMEMBER')
if not redis_set:
return None if number is None else []
if number is None:
return choice(list(redis_set))
elif number > 0:
return sample(list(redis_set), min(number, len(redis_set)))
else:
return [choice(list(redis_set)) for _ in xrange(abs(number))] | python | def srandmember(self, name, number=None):
"""Emulate srandmember."""
redis_set = self._get_set(name, 'SRANDMEMBER')
if not redis_set:
return None if number is None else []
if number is None:
return choice(list(redis_set))
elif number > 0:
return sample(list(redis_set), min(number, len(redis_set)))
else:
return [choice(list(redis_set)) for _ in xrange(abs(number))] | [
"def",
"srandmember",
"(",
"self",
",",
"name",
",",
"number",
"=",
"None",
")",
":",
"redis_set",
"=",
"self",
".",
"_get_set",
"(",
"name",
",",
"'SRANDMEMBER'",
")",
"if",
"not",
"redis_set",
":",
"return",
"None",
"if",
"number",
"is",
"None",
"else",
"[",
"]",
"if",
"number",
"is",
"None",
":",
"return",
"choice",
"(",
"list",
"(",
"redis_set",
")",
")",
"elif",
"number",
">",
"0",
":",
"return",
"sample",
"(",
"list",
"(",
"redis_set",
")",
",",
"min",
"(",
"number",
",",
"len",
"(",
"redis_set",
")",
")",
")",
"else",
":",
"return",
"[",
"choice",
"(",
"list",
"(",
"redis_set",
")",
")",
"for",
"_",
"in",
"xrange",
"(",
"abs",
"(",
"number",
")",
")",
"]"
] | Emulate srandmember. | [
"Emulate",
"srandmember",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1057-L1067 | -1 |
||||||
625 | locationlabs/mockredis | mockredis/client.py | MockRedis.srem | def srem(self, key, *values):
"""Emulate srem."""
redis_set = self._get_set(key, 'SREM')
if not redis_set:
return 0
before_count = len(redis_set)
for value in values:
redis_set.discard(self._encode(value))
after_count = len(redis_set)
if before_count > 0 and len(redis_set) == 0:
self.delete(key)
return before_count - after_count | python | def srem(self, key, *values):
"""Emulate srem."""
redis_set = self._get_set(key, 'SREM')
if not redis_set:
return 0
before_count = len(redis_set)
for value in values:
redis_set.discard(self._encode(value))
after_count = len(redis_set)
if before_count > 0 and len(redis_set) == 0:
self.delete(key)
return before_count - after_count | [
"def",
"srem",
"(",
"self",
",",
"key",
",",
"*",
"values",
")",
":",
"redis_set",
"=",
"self",
".",
"_get_set",
"(",
"key",
",",
"'SREM'",
")",
"if",
"not",
"redis_set",
":",
"return",
"0",
"before_count",
"=",
"len",
"(",
"redis_set",
")",
"for",
"value",
"in",
"values",
":",
"redis_set",
".",
"discard",
"(",
"self",
".",
"_encode",
"(",
"value",
")",
")",
"after_count",
"=",
"len",
"(",
"redis_set",
")",
"if",
"before_count",
">",
"0",
"and",
"len",
"(",
"redis_set",
")",
"==",
"0",
":",
"self",
".",
"delete",
"(",
"key",
")",
"return",
"before_count",
"-",
"after_count"
] | Emulate srem. | [
"Emulate",
"srem",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1069-L1080 | -1 |
||||||
626 | locationlabs/mockredis | mockredis/client.py | MockRedis.sunion | def sunion(self, keys, *args):
"""Emulate sunion."""
func = lambda left, right: left.union(right)
return self._apply_to_sets(func, "SUNION", keys, *args) | python | def sunion(self, keys, *args):
"""Emulate sunion."""
func = lambda left, right: left.union(right)
return self._apply_to_sets(func, "SUNION", keys, *args) | [
"def",
"sunion",
"(",
"self",
",",
"keys",
",",
"*",
"args",
")",
":",
"func",
"=",
"lambda",
"left",
",",
"right",
":",
"left",
".",
"union",
"(",
"right",
")",
"return",
"self",
".",
"_apply_to_sets",
"(",
"func",
",",
"\"SUNION\"",
",",
"keys",
",",
"*",
"args",
")"
] | Emulate sunion. | [
"Emulate",
"sunion",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1082-L1085 | -1 |
||||||
627 | locationlabs/mockredis | mockredis/client.py | MockRedis.sunionstore | def sunionstore(self, dest, keys, *args):
"""Emulate sunionstore."""
result = self.sunion(keys, *args)
self.redis[self._encode(dest)] = result
return len(result) | python | def sunionstore(self, dest, keys, *args):
"""Emulate sunionstore."""
result = self.sunion(keys, *args)
self.redis[self._encode(dest)] = result
return len(result) | [
"def",
"sunionstore",
"(",
"self",
",",
"dest",
",",
"keys",
",",
"*",
"args",
")",
":",
"result",
"=",
"self",
".",
"sunion",
"(",
"keys",
",",
"*",
"args",
")",
"self",
".",
"redis",
"[",
"self",
".",
"_encode",
"(",
"dest",
")",
"]",
"=",
"result",
"return",
"len",
"(",
"result",
")"
] | Emulate sunionstore. | [
"Emulate",
"sunionstore",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1087-L1091 | -1 |
||||||
628 | locationlabs/mockredis | mockredis/client.py | MockRedis.call | def call(self, command, *args):
"""
Sends call to the function, whose name is specified by command.
Used by Script invocations and normalizes calls using standard
Redis arguments to use the expected redis-py arguments.
"""
command = self._normalize_command_name(command)
args = self._normalize_command_args(command, *args)
redis_function = getattr(self, command)
value = redis_function(*args)
return self._normalize_command_response(command, value) | python | def call(self, command, *args):
"""
Sends call to the function, whose name is specified by command.
Used by Script invocations and normalizes calls using standard
Redis arguments to use the expected redis-py arguments.
"""
command = self._normalize_command_name(command)
args = self._normalize_command_args(command, *args)
redis_function = getattr(self, command)
value = redis_function(*args)
return self._normalize_command_response(command, value) | [
"def",
"call",
"(",
"self",
",",
"command",
",",
"*",
"args",
")",
":",
"command",
"=",
"self",
".",
"_normalize_command_name",
"(",
"command",
")",
"args",
"=",
"self",
".",
"_normalize_command_args",
"(",
"command",
",",
"*",
"args",
")",
"redis_function",
"=",
"getattr",
"(",
"self",
",",
"command",
")",
"value",
"=",
"redis_function",
"(",
"*",
"args",
")",
"return",
"self",
".",
"_normalize_command_response",
"(",
"command",
",",
"value",
")"
] | Sends call to the function, whose name is specified by command.
Used by Script invocations and normalizes calls using standard
Redis arguments to use the expected redis-py arguments. | [
"Sends",
"call",
"to",
"the",
"function",
"whose",
"name",
"is",
"specified",
"by",
"command",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1344-L1356 | -1 |
||||||
629 | locationlabs/mockredis | mockredis/client.py | MockRedis._normalize_command_args | def _normalize_command_args(self, command, *args):
"""
Modifies the command arguments to match the
strictness of the redis client.
"""
if command == 'zadd' and not self.strict and len(args) >= 3:
# Reorder score and name
zadd_args = [x for tup in zip(args[2::2], args[1::2]) for x in tup]
return [args[0]] + zadd_args
if command in ('zrangebyscore', 'zrevrangebyscore'):
# expected format is: <command> name min max start num with_scores score_cast_func
if len(args) <= 3:
# just plain min/max
return args
start, num = None, None
withscores = False
for i, arg in enumerate(args[3:], 3):
# keywords are case-insensitive
lower_arg = self._encode(arg).lower()
# handle "limit"
if lower_arg == b"limit" and i + 2 < len(args):
start, num = args[i + 1], args[i + 2]
# handle "withscores"
if lower_arg == b"withscores":
withscores = True
# do not expect to set score_cast_func
return args[:3] + (start, num, withscores)
return args | python | def _normalize_command_args(self, command, *args):
"""
Modifies the command arguments to match the
strictness of the redis client.
"""
if command == 'zadd' and not self.strict and len(args) >= 3:
# Reorder score and name
zadd_args = [x for tup in zip(args[2::2], args[1::2]) for x in tup]
return [args[0]] + zadd_args
if command in ('zrangebyscore', 'zrevrangebyscore'):
# expected format is: <command> name min max start num with_scores score_cast_func
if len(args) <= 3:
# just plain min/max
return args
start, num = None, None
withscores = False
for i, arg in enumerate(args[3:], 3):
# keywords are case-insensitive
lower_arg = self._encode(arg).lower()
# handle "limit"
if lower_arg == b"limit" and i + 2 < len(args):
start, num = args[i + 1], args[i + 2]
# handle "withscores"
if lower_arg == b"withscores":
withscores = True
# do not expect to set score_cast_func
return args[:3] + (start, num, withscores)
return args | [
"def",
"_normalize_command_args",
"(",
"self",
",",
"command",
",",
"*",
"args",
")",
":",
"if",
"command",
"==",
"'zadd'",
"and",
"not",
"self",
".",
"strict",
"and",
"len",
"(",
"args",
")",
">=",
"3",
":",
"# Reorder score and name",
"zadd_args",
"=",
"[",
"x",
"for",
"tup",
"in",
"zip",
"(",
"args",
"[",
"2",
":",
":",
"2",
"]",
",",
"args",
"[",
"1",
":",
":",
"2",
"]",
")",
"for",
"x",
"in",
"tup",
"]",
"return",
"[",
"args",
"[",
"0",
"]",
"]",
"+",
"zadd_args",
"if",
"command",
"in",
"(",
"'zrangebyscore'",
",",
"'zrevrangebyscore'",
")",
":",
"# expected format is: <command> name min max start num with_scores score_cast_func",
"if",
"len",
"(",
"args",
")",
"<=",
"3",
":",
"# just plain min/max",
"return",
"args",
"start",
",",
"num",
"=",
"None",
",",
"None",
"withscores",
"=",
"False",
"for",
"i",
",",
"arg",
"in",
"enumerate",
"(",
"args",
"[",
"3",
":",
"]",
",",
"3",
")",
":",
"# keywords are case-insensitive",
"lower_arg",
"=",
"self",
".",
"_encode",
"(",
"arg",
")",
".",
"lower",
"(",
")",
"# handle \"limit\"",
"if",
"lower_arg",
"==",
"b\"limit\"",
"and",
"i",
"+",
"2",
"<",
"len",
"(",
"args",
")",
":",
"start",
",",
"num",
"=",
"args",
"[",
"i",
"+",
"1",
"]",
",",
"args",
"[",
"i",
"+",
"2",
"]",
"# handle \"withscores\"",
"if",
"lower_arg",
"==",
"b\"withscores\"",
":",
"withscores",
"=",
"True",
"# do not expect to set score_cast_func",
"return",
"args",
"[",
":",
"3",
"]",
"+",
"(",
"start",
",",
"num",
",",
"withscores",
")",
"return",
"args"
] | Modifies the command arguments to match the
strictness of the redis client. | [
"Modifies",
"the",
"command",
"arguments",
"to",
"match",
"the",
"strictness",
"of",
"the",
"redis",
"client",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1369-L1404 | -1 |
||||||
630 | locationlabs/mockredis | mockredis/client.py | MockRedis.config_get | def config_get(self, pattern='*'):
"""
Get one or more configuration parameters.
"""
result = {}
for name, value in self.redis_config.items():
if fnmatch.fnmatch(name, pattern):
try:
result[name] = int(value)
except ValueError:
result[name] = value
return result | python | def config_get(self, pattern='*'):
"""
Get one or more configuration parameters.
"""
result = {}
for name, value in self.redis_config.items():
if fnmatch.fnmatch(name, pattern):
try:
result[name] = int(value)
except ValueError:
result[name] = value
return result | [
"def",
"config_get",
"(",
"self",
",",
"pattern",
"=",
"'*'",
")",
":",
"result",
"=",
"{",
"}",
"for",
"name",
",",
"value",
"in",
"self",
".",
"redis_config",
".",
"items",
"(",
")",
":",
"if",
"fnmatch",
".",
"fnmatch",
"(",
"name",
",",
"pattern",
")",
":",
"try",
":",
"result",
"[",
"name",
"]",
"=",
"int",
"(",
"value",
")",
"except",
"ValueError",
":",
"result",
"[",
"name",
"]",
"=",
"value",
"return",
"result"
] | Get one or more configuration parameters. | [
"Get",
"one",
"or",
"more",
"configuration",
"parameters",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1421-L1432 | -1 |
||||||
631 | locationlabs/mockredis | mockredis/client.py | MockRedis._translate_range | def _translate_range(self, len_, start, end):
"""
Translate range to valid bounds.
"""
if start < 0:
start += len_
start = max(0, min(start, len_))
if end < 0:
end += len_
end = max(-1, min(end, len_ - 1))
return start, end | python | def _translate_range(self, len_, start, end):
"""
Translate range to valid bounds.
"""
if start < 0:
start += len_
start = max(0, min(start, len_))
if end < 0:
end += len_
end = max(-1, min(end, len_ - 1))
return start, end | [
"def",
"_translate_range",
"(",
"self",
",",
"len_",
",",
"start",
",",
"end",
")",
":",
"if",
"start",
"<",
"0",
":",
"start",
"+=",
"len_",
"start",
"=",
"max",
"(",
"0",
",",
"min",
"(",
"start",
",",
"len_",
")",
")",
"if",
"end",
"<",
"0",
":",
"end",
"+=",
"len_",
"end",
"=",
"max",
"(",
"-",
"1",
",",
"min",
"(",
"end",
",",
"len_",
"-",
"1",
")",
")",
"return",
"start",
",",
"end"
] | Translate range to valid bounds. | [
"Translate",
"range",
"to",
"valid",
"bounds",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1478-L1488 | -1 |
||||||
632 | locationlabs/mockredis | mockredis/client.py | MockRedis._translate_limit | def _translate_limit(self, len_, start, num):
"""
Translate limit to valid bounds.
"""
if start > len_ or num <= 0:
return 0, 0
return min(start, len_), num | python | def _translate_limit(self, len_, start, num):
"""
Translate limit to valid bounds.
"""
if start > len_ or num <= 0:
return 0, 0
return min(start, len_), num | [
"def",
"_translate_limit",
"(",
"self",
",",
"len_",
",",
"start",
",",
"num",
")",
":",
"if",
"start",
">",
"len_",
"or",
"num",
"<=",
"0",
":",
"return",
"0",
",",
"0",
"return",
"min",
"(",
"start",
",",
"len_",
")",
",",
"num"
] | Translate limit to valid bounds. | [
"Translate",
"limit",
"to",
"valid",
"bounds",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1490-L1496 | -1 |
||||||
633 | locationlabs/mockredis | mockredis/client.py | MockRedis._aggregate_func | def _aggregate_func(self, aggregate):
"""
Return a suitable aggregate score function.
"""
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)) | python | def _aggregate_func(self, aggregate):
"""
Return a suitable aggregate score function.
"""
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",
")",
":",
"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",
")",
")"
] | Return a suitable aggregate score function. | [
"Return",
"a",
"suitable",
"aggregate",
"score",
"function",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1507-L1516 | -1 |
||||||
634 | locationlabs/mockredis | mockredis/client.py | MockRedis._apply_to_sets | def _apply_to_sets(self, func, operation, keys, *args):
"""Helper function for sdiff, sinter, and sunion"""
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 | python | def _apply_to_sets(self, func, operation, keys, *args):
"""Helper function for sdiff, sinter, and sunion"""
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",
")",
":",
"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"
] | Helper function for sdiff, sinter, and sunion | [
"Helper",
"function",
"for",
"sdiff",
"sinter",
"and",
"sunion"
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1518-L1527 | -1 |
||||||
635 | locationlabs/mockredis | mockredis/client.py | MockRedis._list_or_args | def _list_or_args(self, keys, args):
"""
Shamelessly copied from redis-py.
"""
# 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 | python | def _list_or_args(self, keys, args):
"""
Shamelessly copied from redis-py.
"""
# 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",
")",
":",
"# 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"
] | Shamelessly copied from redis-py. | [
"Shamelessly",
"copied",
"from",
"redis",
"-",
"py",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1529-L1544 | -1 |
||||||
636 | locationlabs/mockredis | mockredis/client.py | MockRedis._encode | def _encode(self, value):
"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 | python | def _encode(self, value):
"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",
")",
":",
"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"
] | Return a bytestring representation of the value. Taken from redis-py connection.py | [
"Return",
"a",
"bytestring",
"representation",
"of",
"the",
"value",
".",
"Taken",
"from",
"redis",
"-",
"py",
"connection",
".",
"py"
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1551-L1563 | -1 |
||||||
637 | locationlabs/mockredis | mockredis/pipeline.py | MockRedisPipeline.watch | def watch(self, *keys):
"""
Put the pipeline into immediate execution mode.
Does not actually watch any keys.
"""
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))) | python | def watch(self, *keys):
"""
Put the pipeline into immediate execution mode.
Does not actually watch any keys.
"""
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",
")",
":",
"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",
")",
")",
")"
] | Put the pipeline into immediate execution mode.
Does not actually watch any keys. | [
"Put",
"the",
"pipeline",
"into",
"immediate",
"execution",
"mode",
".",
"Does",
"not",
"actually",
"watch",
"any",
"keys",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/pipeline.py#L33-L42 | -1 |
||||||
638 | locationlabs/mockredis | mockredis/pipeline.py | MockRedisPipeline.execute | def execute(self):
"""
Execute all of the saved commands and return results.
"""
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() | python | def execute(self):
"""
Execute all of the saved commands and return results.
"""
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",
")",
":",
"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",
"(",
")"
] | Execute all of the saved commands and return results. | [
"Execute",
"all",
"of",
"the",
"saved",
"commands",
"and",
"return",
"results",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/pipeline.py#L55-L65 | -1 |
||||||
639 | locationlabs/mockredis | mockredis/pipeline.py | MockRedisPipeline._reset | def _reset(self):
"""
Reset instance variables.
"""
self.commands = []
self.watching = False
self._watched_keys = {}
self.explicit_transaction = False | python | def _reset(self):
"""
Reset instance variables.
"""
self.commands = []
self.watching = False
self._watched_keys = {}
self.explicit_transaction = False | [
"def",
"_reset",
"(",
"self",
")",
":",
"self",
".",
"commands",
"=",
"[",
"]",
"self",
".",
"watching",
"=",
"False",
"self",
".",
"_watched_keys",
"=",
"{",
"}",
"self",
".",
"explicit_transaction",
"=",
"False"
] | Reset instance variables. | [
"Reset",
"instance",
"variables",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/pipeline.py#L67-L74 | -1 |
||||||
640 | FraBle/python-duckling | duckling/language.py | Language.convert_to_duckling_language_id | def convert_to_duckling_language_id(cls, lang):
"""Ensure a language identifier has the correct duckling format and is supported."""
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))) | python | def convert_to_duckling_language_id(cls, lang):
"""Ensure a language identifier has the correct duckling format and is supported."""
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",
")",
":",
"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",
")",
")",
")"
] | Ensure a language identifier has the correct duckling format and is supported. | [
"Ensure",
"a",
"language",
"identifier",
"has",
"the",
"correct",
"duckling",
"format",
"and",
"is",
"supported",
"."
] | e6a34192e35fd4fc287b4bc93c938fcd5c2d9024 | https://github.com/FraBle/python-duckling/blob/e6a34192e35fd4fc287b4bc93c938fcd5c2d9024/duckling/language.py#L51-L60 | -1 |
||||||
641 | FraBle/python-duckling | duckling/duckling.py | Duckling.load | 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"])
"""
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 | python | 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"])
"""
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",
"=",
"[",
"]",
")",
":",
"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"
] | 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"]) | [
"Loads",
"the",
"Duckling",
"corpus",
"."
] | e6a34192e35fd4fc287b4bc93c938fcd5c2d9024 | https://github.com/FraBle/python-duckling/blob/e6a34192e35fd4fc287b4bc93c938fcd5c2d9024/duckling/duckling.py#L81-L107 | -1 |
||||||
642 | FraBle/python-duckling | duckling/wrapper.py | DucklingWrapper.parse_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"
}
]
"""
return self._parse(input_str, dim=Dim.TIME,
reference_time=reference_time) | python | 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"
}
]
"""
return self._parse(input_str, dim=Dim.TIME,
reference_time=reference_time) | [
"def",
"parse_time",
"(",
"self",
",",
"input_str",
",",
"reference_time",
"=",
"''",
")",
":",
"return",
"self",
".",
"_parse",
"(",
"input_str",
",",
"dim",
"=",
"Dim",
".",
"TIME",
",",
"reference_time",
"=",
"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"
}
] | [
"Parses",
"input",
"with",
"Duckling",
"for",
"occurences",
"of",
"times",
"."
] | e6a34192e35fd4fc287b4bc93c938fcd5c2d9024 | https://github.com/FraBle/python-duckling/blob/e6a34192e35fd4fc287b4bc93c938fcd5c2d9024/duckling/wrapper.py#L258-L287 | -1 |
||||||
643 | horazont/aioxmpp | aioxmpp/adhoc/service.py | AdHocClient.get_commands | 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`.
"""
disco = self.dependencies[aioxmpp.disco.DiscoClient]
response = yield from disco.query_items(
peer_jid,
node=namespaces.xep0050_commands,
)
return response.items | python | 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`.
"""
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",
")",
":",
"disco",
"=",
"self",
".",
"dependencies",
"[",
"aioxmpp",
".",
"disco",
".",
"DiscoClient",
"]",
"response",
"=",
"yield",
"from",
"disco",
".",
"query_items",
"(",
"peer_jid",
",",
"node",
"=",
"namespaces",
".",
"xep0050_commands",
",",
")",
"return",
"response",
".",
"items"
] | 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`. | [
"Return",
"the",
"list",
"of",
"commands",
"offered",
"by",
"the",
"peer",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/adhoc/service.py#L72-L92 | -1 |
||||||
644 | horazont/aioxmpp | aioxmpp/adhoc/service.py | AdHocClient.get_command_info | 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`.
"""
disco = self.dependencies[aioxmpp.disco.DiscoClient]
response = yield from disco.query_info(
peer_jid,
node=command_name,
)
return response | python | 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`.
"""
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",
")",
":",
"disco",
"=",
"self",
".",
"dependencies",
"[",
"aioxmpp",
".",
"disco",
".",
"DiscoClient",
"]",
"response",
"=",
"yield",
"from",
"disco",
".",
"query_info",
"(",
"peer_jid",
",",
"node",
"=",
"command_name",
",",
")",
"return",
"response"
] | 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`. | [
"Obtain",
"information",
"about",
"a",
"command",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/adhoc/service.py#L95-L122 | -1 |
||||||
645 | horazont/aioxmpp | aioxmpp/adhoc/service.py | AdHocClient.execute | 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`.
"""
session = ClientSession(
self.client.stream,
peer_jid,
command_name,
)
yield from session.start()
return session | python | 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`.
"""
session = ClientSession(
self.client.stream,
peer_jid,
command_name,
)
yield from session.start()
return session | [
"def",
"execute",
"(",
"self",
",",
"peer_jid",
",",
"command_name",
")",
":",
"session",
"=",
"ClientSession",
"(",
"self",
".",
"client",
".",
"stream",
",",
"peer_jid",
",",
"command_name",
",",
")",
"yield",
"from",
"session",
".",
"start",
"(",
")",
"return",
"session"
] | 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`. | [
"Start",
"execution",
"of",
"a",
"command",
"with",
"a",
"peer",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/adhoc/service.py#L147-L171 | -1 |
||||||
646 | horazont/aioxmpp | aioxmpp/adhoc/service.py | AdHocServer.register_stateless_command | 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`.
"""
info = CommandEntry(
name,
handler,
is_allowed=is_allowed,
features=features,
)
self._commands[node] = info
self._disco.mount_node(
node,
info,
) | python | 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`.
"""
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",
"}",
")",
":",
"info",
"=",
"CommandEntry",
"(",
"name",
",",
"handler",
",",
"is_allowed",
"=",
"is_allowed",
",",
"features",
"=",
"features",
",",
")",
"self",
".",
"_commands",
"[",
"node",
"]",
"=",
"info",
"self",
".",
"_disco",
".",
"mount_node",
"(",
"node",
",",
"info",
",",
")"
] | 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`. | [
"Register",
"a",
"handler",
"for",
"a",
"stateless",
"command",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/adhoc/service.py#L299-L349 | -1 |
||||||
647 | horazont/aioxmpp | aioxmpp/adhoc/service.py | ClientSession.start | 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.
"""
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 | python | 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.
"""
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",
")",
":",
"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"
] | 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. | [
"Initiate",
"the",
"session",
"by",
"starting",
"to",
"execute",
"the",
"command",
"with",
"the",
"peer",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/adhoc/service.py#L480-L506 | -1 |
||||||
648 | horazont/aioxmpp | aioxmpp/adhoc/service.py | ClientSession.proceed | 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.
"""
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 | python | 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.
"""
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",
")",
":",
"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"
] | 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. | [
"Proceed",
"command",
"execution",
"to",
"the",
"next",
"stage",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/adhoc/service.py#L509-L572 | -1 |
||||||
649 | horazont/aioxmpp | aioxmpp/ibb/service.py | IBBTransport.write | 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.
"""
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() | python | 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.
"""
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",
")",
":",
"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",
"(",
")"
] | 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. | [
"Send",
"data",
"over",
"the",
"IBB",
".",
"If",
"data",
"is",
"larger",
"than",
"the",
"block",
"size",
"is",
"is",
"chunked",
"and",
"sent",
"in",
"chunks",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/ibb/service.py#L232-L250 | -1 |
||||||
650 | horazont/aioxmpp | aioxmpp/ibb/service.py | IBBTransport.close | def close(self):
"""
Close the session.
"""
if self.is_closing():
return
self._closing = True
# make sure the writer wakes up
self._can_write.set() | python | def close(self):
"""
Close the session.
"""
if self.is_closing():
return
self._closing = True
# make sure the writer wakes up
self._can_write.set() | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_closing",
"(",
")",
":",
"return",
"self",
".",
"_closing",
"=",
"True",
"# make sure the writer wakes up",
"self",
".",
"_can_write",
".",
"set",
"(",
")"
] | Close the session. | [
"Close",
"the",
"session",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/ibb/service.py#L265-L274 | -1 |
||||||
651 | horazont/aioxmpp | aioxmpp/ibb/service.py | IBBService.open_session | 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`
"""
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 | python | 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`
"""
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",
")",
":",
"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"
] | 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` | [
"Establish",
"an",
"in",
"-",
"band",
"bytestream",
"session",
"with",
"peer_jid",
"and",
"return",
"the",
"transport",
"and",
"protocol",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/ibb/service.py#L419-L471 | -1 |
||||||
652 | horazont/aioxmpp | aioxmpp/muc/service.py | Room.features | 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.
"""
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,
} | python | 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.
"""
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",
")",
":",
"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",
",",
"}"
] | 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. | [
"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",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/muc/service.py#L1018-L1035 | -1 |
||||||
653 | horazont/aioxmpp | aioxmpp/muc/service.py | Room.send_message | 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.
"""
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 | python | 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.
"""
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",
")",
":",
"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"
] | 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. | [
"Send",
"a",
"message",
"to",
"the",
"MUC",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/muc/service.py#L1470-L1498 | -1 |
||||||
654 | horazont/aioxmpp | aioxmpp/muc/service.py | Room.send_message_tracked | 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.
"""
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 | python | 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.
"""
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",
")",
":",
"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"
] | 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. | [
"Send",
"a",
"message",
"to",
"the",
"MUC",
"with",
"tracking",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/muc/service.py#L1508-L1610 | -1 |
||||||
655 | horazont/aioxmpp | aioxmpp/muc/service.py | Room.set_nick | 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.
"""
stanza = aioxmpp.Presence(
type_=aioxmpp.PresenceType.AVAILABLE,
to=self._mucjid.replace(resource=new_nick),
)
yield from self._service.client.send(
stanza
) | python | 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.
"""
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",
")",
":",
"stanza",
"=",
"aioxmpp",
".",
"Presence",
"(",
"type_",
"=",
"aioxmpp",
".",
"PresenceType",
".",
"AVAILABLE",
",",
"to",
"=",
"self",
".",
"_mucjid",
".",
"replace",
"(",
"resource",
"=",
"new_nick",
")",
",",
")",
"yield",
"from",
"self",
".",
"_service",
".",
"client",
".",
"send",
"(",
"stanza",
")"
] | 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. | [
"Change",
"the",
"nick",
"name",
"of",
"the",
"occupant",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/muc/service.py#L1613-L1638 | -1 |
||||||
656 | horazont/aioxmpp | aioxmpp/muc/service.py | Room.kick | 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.
"""
yield from self.muc_set_role(
member.nick,
"none",
reason=reason
) | python | 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.
"""
yield from self.muc_set_role(
member.nick,
"none",
reason=reason
) | [
"def",
"kick",
"(",
"self",
",",
"member",
",",
"reason",
"=",
"None",
")",
":",
"yield",
"from",
"self",
".",
"muc_set_role",
"(",
"member",
".",
"nick",
",",
"\"none\"",
",",
"reason",
"=",
"reason",
")"
] | 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. | [
"Kick",
"an",
"occupant",
"from",
"the",
"MUC",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/muc/service.py#L1641-L1662 | -1 |
||||||
657 | horazont/aioxmpp | aioxmpp/muc/service.py | Room.muc_set_role | 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.
"""
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) | python | 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.
"""
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",
")",
":",
"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",
")"
] | 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. | [
"Change",
"the",
"role",
"of",
"an",
"occupant",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/muc/service.py#L1665-L1708 | -1 |
||||||
658 | horazont/aioxmpp | aioxmpp/muc/service.py | Room.ban | 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.
"""
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
) | python | 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.
"""
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",
")",
":",
"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",
")"
] | 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. | [
"Ban",
"an",
"occupant",
"from",
"re",
"-",
"joining",
"the",
"MUC",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/muc/service.py#L1711-L1741 | -1 |
||||||
659 | horazont/aioxmpp | aioxmpp/muc/service.py | Room.leave | def leave(self):
"""
Leave the MUC.
"""
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 | python | def leave(self):
"""
Leave the MUC.
"""
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",
")",
":",
"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"
] | Leave the MUC. | [
"Leave",
"the",
"MUC",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/muc/service.py#L1777-L1795 | -1 |
||||||
660 | horazont/aioxmpp | aioxmpp/muc/service.py | MUCClient.set_affiliation | 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.
"""
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) | python | 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.
"""
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",
")",
":",
"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",
")"
] | 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. | [
"Change",
"the",
"affiliation",
"of",
"an",
"entity",
"with",
"a",
"MUC",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/muc/service.py#L2382-L2435 | -1 |
||||||
661 | horazont/aioxmpp | aioxmpp/muc/service.py | MUCClient.get_room_config | 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
"""
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 | python | 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
"""
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",
")",
":",
"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"
] | 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 | [
"Query",
"and",
"return",
"the",
"room",
"configuration",
"form",
"for",
"the",
"given",
"MUC",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/muc/service.py#L2438-L2464 | -1 |
||||||
662 | horazont/aioxmpp | aioxmpp/httpupload/__init__.py | request_slot | 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.
"""
payload = Request(filename, size, content_type)
return (yield from client.send(IQ(
type_=IQType.GET,
to=service,
payload=payload
))) | python | 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.
"""
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",
")",
":",
"payload",
"=",
"Request",
"(",
"filename",
",",
"size",
",",
"content_type",
")",
"return",
"(",
"yield",
"from",
"client",
".",
"send",
"(",
"IQ",
"(",
"type_",
"=",
"IQType",
".",
"GET",
",",
"to",
"=",
"service",
",",
"payload",
"=",
"payload",
")",
")",
")"
] | 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. | [
"Request",
"an",
"HTTP",
"upload",
"slot",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/httpupload/__init__.py#L76-L109 | -1 |
||||||
663 | horazont/aioxmpp | aioxmpp/version/service.py | query_version | 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`.
"""
return (yield from stream.send(
aioxmpp.IQ(
type_=aioxmpp.IQType.GET,
to=target,
payload=version_xso.Query(),
)
)) | python | 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`.
"""
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",
":",
"return",
"(",
"yield",
"from",
"stream",
".",
"send",
"(",
"aioxmpp",
".",
"IQ",
"(",
"type_",
"=",
"aioxmpp",
".",
"IQType",
".",
"GET",
",",
"to",
"=",
"target",
",",
"payload",
"=",
"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`. | [
"Query",
"the",
"software",
"version",
"of",
"an",
"entity",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/version/service.py#L185-L212 | -1 |
||||||
664 | horazont/aioxmpp | aioxmpp/bookmarks/xso.py | as_bookmark_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`.
"""
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 | python | 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`.
"""
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",
")",
":",
"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"
] | 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`. | [
"Decorator",
"to",
"register",
"xso_class",
"as",
"a",
"custom",
"bookmark",
"class",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/bookmarks/xso.py#L241-L262 | -1 |
||||||
665 | horazont/aioxmpp | aioxmpp/structs.py | basic_filter_languages | 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.
"""
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 | python | 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.
"""
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",
")",
":",
"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"
] | 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. | [
"Filter",
"languages",
"using",
"the",
"string",
"-",
"based",
"basic",
"filter",
"algorithm",
"described",
"in",
"RFC4647",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/structs.py#L1228-L1269 | -1 |
||||||
666 | horazont/aioxmpp | aioxmpp/structs.py | JID.fromstr | 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`.
"""
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) | python | 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`.
"""
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",
")",
":",
"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",
")"
] | 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`. | [
"Construct",
"a",
"JID",
"out",
"of",
"a",
"string",
"containing",
"it",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/structs.py#L792-L815 | -1 |
||||||
667 | horazont/aioxmpp | aioxmpp/im/p2p.py | Service.get_conversation | 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.
"""
try:
return self._conversationmap[peer_jid]
except KeyError:
pass
return self._make_conversation(peer_jid, False) | python | 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.
"""
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",
")",
":",
"try",
":",
"return",
"self",
".",
"_conversationmap",
"[",
"peer_jid",
"]",
"except",
"KeyError",
":",
"pass",
"return",
"self",
".",
"_make_conversation",
"(",
"peer_jid",
",",
"False",
")"
] | 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. | [
"Get",
"or",
"create",
"a",
"new",
"one",
"-",
"to",
"-",
"one",
"conversation",
"with",
"a",
"peer",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/im/p2p.py#L204-L228 | -1 |
||||||
668 | horazont/aioxmpp | aioxmpp/network.py | reconfigure_resolver | 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.
"""
global _state
_state.resolver = dns.resolver.Resolver()
_state.overridden_resolver = False | python | 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.
"""
global _state
_state.resolver = dns.resolver.Resolver()
_state.overridden_resolver = False | [
"def",
"reconfigure_resolver",
"(",
")",
":",
"global",
"_state",
"_state",
".",
"resolver",
"=",
"dns",
".",
"resolver",
".",
"Resolver",
"(",
")",
"_state",
".",
"overridden_resolver",
"=",
"False"
] | 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. | [
"Reset",
"the",
"resolver",
"configured",
"for",
"this",
"thread",
"to",
"a",
"fresh",
"instance",
".",
"This",
"essentially",
"re",
"-",
"reads",
"the",
"system",
"-",
"wide",
"resolver",
"configuration",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/network.py#L116-L127 | -1 |
||||||
669 | horazont/aioxmpp | aioxmpp/service.py | iq_handler | 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.
"""
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 | python | 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.
"""
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",
")",
":",
"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"
] | 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. | [
"Register",
"the",
"decorated",
"function",
"or",
"coroutine",
"function",
"as",
"IQ",
"request",
"handler",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L1001-L1060 | -1 |
||||||
670 | horazont/aioxmpp | aioxmpp/service.py | inbound_message_filter | 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.
"""
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 | python | 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.
"""
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",
")",
":",
"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"
] | 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. | [
"Register",
"the",
"decorated",
"function",
"as",
"a",
"service",
"-",
"level",
"inbound",
"message",
"filter",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L1083-L1107 | -1 |
||||||
671 | horazont/aioxmpp | aioxmpp/service.py | inbound_presence_filter | 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.
"""
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 | python | 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.
"""
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",
")",
":",
"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"
] | 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. | [
"Register",
"the",
"decorated",
"function",
"as",
"a",
"service",
"-",
"level",
"inbound",
"presence",
"filter",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L1110-L1134 | -1 |
||||||
672 | horazont/aioxmpp | aioxmpp/service.py | outbound_message_filter | 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.
"""
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 | python | 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.
"""
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",
")",
":",
"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"
] | 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. | [
"Register",
"the",
"decorated",
"function",
"as",
"a",
"service",
"-",
"level",
"outbound",
"message",
"filter",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L1137-L1161 | -1 |
||||||
673 | horazont/aioxmpp | aioxmpp/service.py | outbound_presence_filter | 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.
"""
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 | python | 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.
"""
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",
")",
":",
"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"
] | 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. | [
"Register",
"the",
"decorated",
"function",
"as",
"a",
"service",
"-",
"level",
"outbound",
"presence",
"filter",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L1164-L1189 | -1 |
||||||
674 | horazont/aioxmpp | aioxmpp/service.py | depsignal | 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.
"""
def decorator(f):
add_handler_spec(
f,
_depsignal_spec(class_, signal_name, f, defer)
)
return f
return decorator | python | 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.
"""
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",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"add_handler_spec",
"(",
"f",
",",
"_depsignal_spec",
"(",
"class_",
",",
"signal_name",
",",
"f",
",",
"defer",
")",
")",
"return",
"f",
"return",
"decorator"
] | 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. | [
"Connect",
"the",
"decorated",
"method",
"or",
"coroutine",
"method",
"to",
"the",
"addressed",
"signal",
"on",
"a",
"class",
"on",
"which",
"the",
"service",
"depends",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L1244-L1293 | -1 |
||||||
675 | horazont/aioxmpp | aioxmpp/service.py | attrsignal | 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
"""
def decorator(f):
add_handler_spec(
f,
_attrsignal_spec(descriptor, signal_name, f, defer)
)
return f
return decorator | python | 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
"""
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",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"add_handler_spec",
"(",
"f",
",",
"_attrsignal_spec",
"(",
"descriptor",
",",
"signal_name",
",",
"f",
",",
"defer",
")",
")",
"return",
"f",
"return",
"decorator"
] | 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 | [
"Connect",
"the",
"decorated",
"method",
"or",
"coroutine",
"method",
"to",
"the",
"addressed",
"signal",
"on",
"a",
"descriptor",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L1314-L1355 | -1 |
||||||
676 | horazont/aioxmpp | aioxmpp/service.py | Descriptor.add_to_stack | 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.
"""
cm = self.init_cm(instance)
obj = stack.enter_context(cm)
self._data[instance] = cm, obj
return obj | python | 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.
"""
cm = self.init_cm(instance)
obj = stack.enter_context(cm)
self._data[instance] = cm, obj
return obj | [
"def",
"add_to_stack",
"(",
"self",
",",
"instance",
",",
"stack",
")",
":",
"cm",
"=",
"self",
".",
"init_cm",
"(",
"instance",
")",
"obj",
"=",
"stack",
".",
"enter_context",
"(",
"cm",
")",
"self",
".",
"_data",
"[",
"instance",
"]",
"=",
"cm",
",",
"obj",
"return",
"obj"
] | 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. | [
"Get",
"the",
"context",
"manager",
"for",
"the",
"service",
"instance",
"and",
"push",
"it",
"to",
"the",
"context",
"manager",
"stack",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L284-L306 | -1 |
||||||
677 | horazont/aioxmpp | aioxmpp/service.py | Meta.orders_after | 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
"""
return self.orders_after_any(frozenset([other]), visited=visited) | python | 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
"""
return self.orders_after_any(frozenset([other]), visited=visited) | [
"def",
"orders_after",
"(",
"self",
",",
"other",
",",
"*",
",",
"visited",
"=",
"None",
")",
":",
"return",
"self",
".",
"orders_after_any",
"(",
"frozenset",
"(",
"[",
"other",
"]",
")",
",",
"visited",
"=",
"visited",
")"
] | Return whether `self` depends on `other` and will be instanciated
later.
:param other: Another service.
:type other: :class:`aioxmpp.service.Service`
.. versionadded:: 0.11 | [
"Return",
"whether",
"self",
"depends",
"on",
"other",
"and",
"will",
"be",
"instanciated",
"later",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L595-L605 | -1 |
||||||
678 | horazont/aioxmpp | aioxmpp/service.py | Meta.orders_after_any | 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
"""
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 | python | 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
"""
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",
")",
":",
"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"
] | 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 | [
"Return",
"whether",
"self",
"orders",
"after",
"any",
"of",
"the",
"services",
"in",
"the",
"set",
"other",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L607-L632 | -1 |
||||||
679 | horazont/aioxmpp | aioxmpp/tasks.py | TaskPool.set_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`.
"""
if new_limit is None:
self._group_limits.pop(group, None)
return
self._group_limits[group] = new_limit | python | 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`.
"""
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",
")",
":",
"if",
"new_limit",
"is",
"None",
":",
"self",
".",
"_group_limits",
".",
"pop",
"(",
"group",
",",
"None",
")",
"return",
"self",
".",
"_group_limits",
"[",
"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`. | [
"Set",
"a",
"new",
"limit",
"on",
"the",
"number",
"of",
"tasks",
"in",
"the",
"group",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/tasks.py#L80-L107 | -1 |
||||||
680 | horazont/aioxmpp | aioxmpp/tasks.py | TaskPool.spawn | 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`.
"""
# ensure the implicit group is included
__groups = set(__groups) | {()}
return asyncio.ensure_future(__coro_fun(*args, **kwargs)) | python | 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`.
"""
# 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",
")",
":",
"# ensure the implicit group is included",
"__groups",
"=",
"set",
"(",
"__groups",
")",
"|",
"{",
"(",
")",
"}",
"return",
"asyncio",
".",
"ensure_future",
"(",
"__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`. | [
"Start",
"a",
"new",
"coroutine",
"and",
"add",
"it",
"to",
"the",
"pool",
"atomically",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/tasks.py#L165-L200 | -1 |
||||||
681 | horazont/aioxmpp | aioxmpp/carbons/service.py | CarbonsClient.enable | 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`
"""
yield from self._check_for_feature()
iq = aioxmpp.IQ(
type_=aioxmpp.IQType.SET,
payload=carbons_xso.Enable()
)
yield from self.client.send(iq) | python | 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`
"""
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",
")",
":",
"yield",
"from",
"self",
".",
"_check_for_feature",
"(",
")",
"iq",
"=",
"aioxmpp",
".",
"IQ",
"(",
"type_",
"=",
"aioxmpp",
".",
"IQType",
".",
"SET",
",",
"payload",
"=",
"carbons_xso",
".",
"Enable",
"(",
")",
")",
"yield",
"from",
"self",
".",
"client",
".",
"send",
"(",
"iq",
")"
] | 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` | [
"Enable",
"message",
"carbons",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/carbons/service.py#L74-L90 | -1 |
||||||
682 | horazont/aioxmpp | aioxmpp/carbons/service.py | CarbonsClient.disable | 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`
"""
yield from self._check_for_feature()
iq = aioxmpp.IQ(
type_=aioxmpp.IQType.SET,
payload=carbons_xso.Disable()
)
yield from self.client.send(iq) | python | 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`
"""
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",
")",
":",
"yield",
"from",
"self",
".",
"_check_for_feature",
"(",
")",
"iq",
"=",
"aioxmpp",
".",
"IQ",
"(",
"type_",
"=",
"aioxmpp",
".",
"IQType",
".",
"SET",
",",
"payload",
"=",
"carbons_xso",
".",
"Disable",
"(",
")",
")",
"yield",
"from",
"self",
".",
"client",
".",
"send",
"(",
"iq",
")"
] | 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` | [
"Disable",
"message",
"carbons",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/carbons/service.py#L93-L109 | -1 |
||||||
683 | horazont/aioxmpp | aioxmpp/stream.py | StanzaStream._process_incoming_iq | def _process_incoming_iq(self, stanza_obj):
"""
Process an incoming IQ stanza `stanza_obj`. Calls the response handler,
spawns a request handler coroutine or drops the stanza while logging a
warning if no handler can be found.
"""
self._logger.debug("incoming iq: %r", stanza_obj)
if stanza_obj.type_.is_response:
# iq response
self._logger.debug("iq is response")
keys = [(stanza_obj.from_, stanza_obj.id_)]
if self._local_jid is not None:
# needed for some servers
if keys[0][0] == self._local_jid:
keys.append((None, keys[0][1]))
elif keys[0][0] is None:
keys.append((self._local_jid, keys[0][1]))
for key in keys:
try:
self._iq_response_map.unicast(key, stanza_obj)
self._logger.debug("iq response delivered to key %r", key)
break
except KeyError:
pass
else:
self._logger.warning(
"unexpected IQ response: from=%r, id=%r",
*key)
else:
# iq request
self._logger.debug("iq is request")
key = (stanza_obj.type_, type(stanza_obj.payload))
try:
coro, with_send_reply = self._iq_request_map[key]
except KeyError:
self._logger.warning(
"unhandleable IQ request: from=%r, type_=%r, payload=%r",
stanza_obj.from_,
stanza_obj.type_,
stanza_obj.payload
)
response = stanza_obj.make_reply(type_=structs.IQType.ERROR)
response.error = stanza.Error(
condition=errors.ErrorCondition.SERVICE_UNAVAILABLE,
)
self._enqueue(response)
return
args = [stanza_obj]
if with_send_reply:
def send_reply(result=None):
nonlocal task, stanza_obj, send_reply_callback
if task.done():
raise RuntimeError(
"send_reply called after the handler is done")
if task.remove_done_callback(send_reply_callback) == 0:
raise RuntimeError(
"send_reply called more than once")
task.add_done_callback(self._iq_request_coro_done_check)
self._send_iq_reply(stanza_obj, result)
args.append(send_reply)
try:
awaitable = coro(*args)
except Exception as exc:
awaitable = asyncio.Future()
awaitable.set_exception(exc)
task = asyncio.ensure_future(awaitable)
send_reply_callback = functools.partial(
self._iq_request_coro_done_send_reply,
stanza_obj)
task.add_done_callback(self._iq_request_coro_done_remove_task)
task.add_done_callback(send_reply_callback)
self._iq_request_tasks.append(task)
self._logger.debug("started task to handle request: %r", task) | python | def _process_incoming_iq(self, stanza_obj):
"""
Process an incoming IQ stanza `stanza_obj`. Calls the response handler,
spawns a request handler coroutine or drops the stanza while logging a
warning if no handler can be found.
"""
self._logger.debug("incoming iq: %r", stanza_obj)
if stanza_obj.type_.is_response:
# iq response
self._logger.debug("iq is response")
keys = [(stanza_obj.from_, stanza_obj.id_)]
if self._local_jid is not None:
# needed for some servers
if keys[0][0] == self._local_jid:
keys.append((None, keys[0][1]))
elif keys[0][0] is None:
keys.append((self._local_jid, keys[0][1]))
for key in keys:
try:
self._iq_response_map.unicast(key, stanza_obj)
self._logger.debug("iq response delivered to key %r", key)
break
except KeyError:
pass
else:
self._logger.warning(
"unexpected IQ response: from=%r, id=%r",
*key)
else:
# iq request
self._logger.debug("iq is request")
key = (stanza_obj.type_, type(stanza_obj.payload))
try:
coro, with_send_reply = self._iq_request_map[key]
except KeyError:
self._logger.warning(
"unhandleable IQ request: from=%r, type_=%r, payload=%r",
stanza_obj.from_,
stanza_obj.type_,
stanza_obj.payload
)
response = stanza_obj.make_reply(type_=structs.IQType.ERROR)
response.error = stanza.Error(
condition=errors.ErrorCondition.SERVICE_UNAVAILABLE,
)
self._enqueue(response)
return
args = [stanza_obj]
if with_send_reply:
def send_reply(result=None):
nonlocal task, stanza_obj, send_reply_callback
if task.done():
raise RuntimeError(
"send_reply called after the handler is done")
if task.remove_done_callback(send_reply_callback) == 0:
raise RuntimeError(
"send_reply called more than once")
task.add_done_callback(self._iq_request_coro_done_check)
self._send_iq_reply(stanza_obj, result)
args.append(send_reply)
try:
awaitable = coro(*args)
except Exception as exc:
awaitable = asyncio.Future()
awaitable.set_exception(exc)
task = asyncio.ensure_future(awaitable)
send_reply_callback = functools.partial(
self._iq_request_coro_done_send_reply,
stanza_obj)
task.add_done_callback(self._iq_request_coro_done_remove_task)
task.add_done_callback(send_reply_callback)
self._iq_request_tasks.append(task)
self._logger.debug("started task to handle request: %r", task) | [
"def",
"_process_incoming_iq",
"(",
"self",
",",
"stanza_obj",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"incoming iq: %r\"",
",",
"stanza_obj",
")",
"if",
"stanza_obj",
".",
"type_",
".",
"is_response",
":",
"# iq response",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"iq is response\"",
")",
"keys",
"=",
"[",
"(",
"stanza_obj",
".",
"from_",
",",
"stanza_obj",
".",
"id_",
")",
"]",
"if",
"self",
".",
"_local_jid",
"is",
"not",
"None",
":",
"# needed for some servers",
"if",
"keys",
"[",
"0",
"]",
"[",
"0",
"]",
"==",
"self",
".",
"_local_jid",
":",
"keys",
".",
"append",
"(",
"(",
"None",
",",
"keys",
"[",
"0",
"]",
"[",
"1",
"]",
")",
")",
"elif",
"keys",
"[",
"0",
"]",
"[",
"0",
"]",
"is",
"None",
":",
"keys",
".",
"append",
"(",
"(",
"self",
".",
"_local_jid",
",",
"keys",
"[",
"0",
"]",
"[",
"1",
"]",
")",
")",
"for",
"key",
"in",
"keys",
":",
"try",
":",
"self",
".",
"_iq_response_map",
".",
"unicast",
"(",
"key",
",",
"stanza_obj",
")",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"iq response delivered to key %r\"",
",",
"key",
")",
"break",
"except",
"KeyError",
":",
"pass",
"else",
":",
"self",
".",
"_logger",
".",
"warning",
"(",
"\"unexpected IQ response: from=%r, id=%r\"",
",",
"*",
"key",
")",
"else",
":",
"# iq request",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"iq is request\"",
")",
"key",
"=",
"(",
"stanza_obj",
".",
"type_",
",",
"type",
"(",
"stanza_obj",
".",
"payload",
")",
")",
"try",
":",
"coro",
",",
"with_send_reply",
"=",
"self",
".",
"_iq_request_map",
"[",
"key",
"]",
"except",
"KeyError",
":",
"self",
".",
"_logger",
".",
"warning",
"(",
"\"unhandleable IQ request: from=%r, type_=%r, payload=%r\"",
",",
"stanza_obj",
".",
"from_",
",",
"stanza_obj",
".",
"type_",
",",
"stanza_obj",
".",
"payload",
")",
"response",
"=",
"stanza_obj",
".",
"make_reply",
"(",
"type_",
"=",
"structs",
".",
"IQType",
".",
"ERROR",
")",
"response",
".",
"error",
"=",
"stanza",
".",
"Error",
"(",
"condition",
"=",
"errors",
".",
"ErrorCondition",
".",
"SERVICE_UNAVAILABLE",
",",
")",
"self",
".",
"_enqueue",
"(",
"response",
")",
"return",
"args",
"=",
"[",
"stanza_obj",
"]",
"if",
"with_send_reply",
":",
"def",
"send_reply",
"(",
"result",
"=",
"None",
")",
":",
"nonlocal",
"task",
",",
"stanza_obj",
",",
"send_reply_callback",
"if",
"task",
".",
"done",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"send_reply called after the handler is done\"",
")",
"if",
"task",
".",
"remove_done_callback",
"(",
"send_reply_callback",
")",
"==",
"0",
":",
"raise",
"RuntimeError",
"(",
"\"send_reply called more than once\"",
")",
"task",
".",
"add_done_callback",
"(",
"self",
".",
"_iq_request_coro_done_check",
")",
"self",
".",
"_send_iq_reply",
"(",
"stanza_obj",
",",
"result",
")",
"args",
".",
"append",
"(",
"send_reply",
")",
"try",
":",
"awaitable",
"=",
"coro",
"(",
"*",
"args",
")",
"except",
"Exception",
"as",
"exc",
":",
"awaitable",
"=",
"asyncio",
".",
"Future",
"(",
")",
"awaitable",
".",
"set_exception",
"(",
"exc",
")",
"task",
"=",
"asyncio",
".",
"ensure_future",
"(",
"awaitable",
")",
"send_reply_callback",
"=",
"functools",
".",
"partial",
"(",
"self",
".",
"_iq_request_coro_done_send_reply",
",",
"stanza_obj",
")",
"task",
".",
"add_done_callback",
"(",
"self",
".",
"_iq_request_coro_done_remove_task",
")",
"task",
".",
"add_done_callback",
"(",
"send_reply_callback",
")",
"self",
".",
"_iq_request_tasks",
".",
"append",
"(",
"task",
")",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"started task to handle request: %r\"",
",",
"task",
")"
] | Process an incoming IQ stanza `stanza_obj`. Calls the response handler,
spawns a request handler coroutine or drops the stanza while logging a
warning if no handler can be found. | [
"Process",
"an",
"incoming",
"IQ",
"stanza",
"stanza_obj",
".",
"Calls",
"the",
"response",
"handler",
"spawns",
"a",
"request",
"handler",
"coroutine",
"or",
"drops",
"the",
"stanza",
"while",
"logging",
"a",
"warning",
"if",
"no",
"handler",
"can",
"be",
"found",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L978-L1055 | -1 |
||||||
684 | horazont/aioxmpp | aioxmpp/stream.py | StanzaStream._process_incoming_message | def _process_incoming_message(self, stanza_obj):
"""
Process an incoming message stanza `stanza_obj`.
"""
self._logger.debug("incoming message: %r", stanza_obj)
stanza_obj = self.service_inbound_message_filter.filter(stanza_obj)
if stanza_obj is None:
self._logger.debug("incoming message dropped by service "
"filter chain")
return
stanza_obj = self.app_inbound_message_filter.filter(stanza_obj)
if stanza_obj is None:
self._logger.debug("incoming message dropped by application "
"filter chain")
return
self.on_message_received(stanza_obj) | python | def _process_incoming_message(self, stanza_obj):
"""
Process an incoming message stanza `stanza_obj`.
"""
self._logger.debug("incoming message: %r", stanza_obj)
stanza_obj = self.service_inbound_message_filter.filter(stanza_obj)
if stanza_obj is None:
self._logger.debug("incoming message dropped by service "
"filter chain")
return
stanza_obj = self.app_inbound_message_filter.filter(stanza_obj)
if stanza_obj is None:
self._logger.debug("incoming message dropped by application "
"filter chain")
return
self.on_message_received(stanza_obj) | [
"def",
"_process_incoming_message",
"(",
"self",
",",
"stanza_obj",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"incoming message: %r\"",
",",
"stanza_obj",
")",
"stanza_obj",
"=",
"self",
".",
"service_inbound_message_filter",
".",
"filter",
"(",
"stanza_obj",
")",
"if",
"stanza_obj",
"is",
"None",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"incoming message dropped by service \"",
"\"filter chain\"",
")",
"return",
"stanza_obj",
"=",
"self",
".",
"app_inbound_message_filter",
".",
"filter",
"(",
"stanza_obj",
")",
"if",
"stanza_obj",
"is",
"None",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"incoming message dropped by application \"",
"\"filter chain\"",
")",
"return",
"self",
".",
"on_message_received",
"(",
"stanza_obj",
")"
] | Process an incoming message stanza `stanza_obj`. | [
"Process",
"an",
"incoming",
"message",
"stanza",
"stanza_obj",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L1057-L1075 | -1 |
||||||
685 | horazont/aioxmpp | aioxmpp/stream.py | StanzaStream._process_incoming_presence | def _process_incoming_presence(self, stanza_obj):
"""
Process an incoming presence stanza `stanza_obj`.
"""
self._logger.debug("incoming presence: %r", stanza_obj)
stanza_obj = self.service_inbound_presence_filter.filter(stanza_obj)
if stanza_obj is None:
self._logger.debug("incoming presence dropped by service filter"
" chain")
return
stanza_obj = self.app_inbound_presence_filter.filter(stanza_obj)
if stanza_obj is None:
self._logger.debug("incoming presence dropped by application "
"filter chain")
return
self.on_presence_received(stanza_obj) | python | def _process_incoming_presence(self, stanza_obj):
"""
Process an incoming presence stanza `stanza_obj`.
"""
self._logger.debug("incoming presence: %r", stanza_obj)
stanza_obj = self.service_inbound_presence_filter.filter(stanza_obj)
if stanza_obj is None:
self._logger.debug("incoming presence dropped by service filter"
" chain")
return
stanza_obj = self.app_inbound_presence_filter.filter(stanza_obj)
if stanza_obj is None:
self._logger.debug("incoming presence dropped by application "
"filter chain")
return
self.on_presence_received(stanza_obj) | [
"def",
"_process_incoming_presence",
"(",
"self",
",",
"stanza_obj",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"incoming presence: %r\"",
",",
"stanza_obj",
")",
"stanza_obj",
"=",
"self",
".",
"service_inbound_presence_filter",
".",
"filter",
"(",
"stanza_obj",
")",
"if",
"stanza_obj",
"is",
"None",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"incoming presence dropped by service filter\"",
"\" chain\"",
")",
"return",
"stanza_obj",
"=",
"self",
".",
"app_inbound_presence_filter",
".",
"filter",
"(",
"stanza_obj",
")",
"if",
"stanza_obj",
"is",
"None",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"incoming presence dropped by application \"",
"\"filter chain\"",
")",
"return",
"self",
".",
"on_presence_received",
"(",
"stanza_obj",
")"
] | Process an incoming presence stanza `stanza_obj`. | [
"Process",
"an",
"incoming",
"presence",
"stanza",
"stanza_obj",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L1077-L1095 | -1 |
||||||
686 | horazont/aioxmpp | aioxmpp/stream.py | StanzaStream._process_incoming | def _process_incoming(self, xmlstream, queue_entry):
"""
Dispatch to the different methods responsible for the different stanza
types or handle a non-stanza stream-level element from `stanza_obj`,
which has arrived over the given `xmlstream`.
"""
stanza_obj, exc = queue_entry
# first, handle SM stream objects
if isinstance(stanza_obj, nonza.SMAcknowledgement):
self._logger.debug("received SM ack: %r", stanza_obj)
if not self._sm_enabled:
self._logger.warning("received SM ack, but SM not enabled")
return
self.sm_ack(stanza_obj.counter)
return
elif isinstance(stanza_obj, nonza.SMRequest):
self._logger.debug("received SM request: %r", stanza_obj)
if not self._sm_enabled:
self._logger.warning("received SM request, but SM not enabled")
return
response = nonza.SMAcknowledgement()
response.counter = self._sm_inbound_ctr
self._logger.debug("sending SM ack: %r", response)
xmlstream.send_xso(response)
return
# raise if it is not a stanza
if not isinstance(stanza_obj, stanza.StanzaBase):
raise RuntimeError(
"unexpected stanza class: {}".format(stanza_obj))
# now handle stanzas, these always increment the SM counter
if self._sm_enabled:
self._sm_inbound_ctr += 1
self._sm_inbound_ctr &= 0xffffffff
# check if the stanza has errors
if exc is not None:
self._process_incoming_erroneous_stanza(stanza_obj, exc)
return
if isinstance(stanza_obj, stanza.IQ):
self._process_incoming_iq(stanza_obj)
elif isinstance(stanza_obj, stanza.Message):
self._process_incoming_message(stanza_obj)
elif isinstance(stanza_obj, stanza.Presence):
self._process_incoming_presence(stanza_obj) | python | def _process_incoming(self, xmlstream, queue_entry):
"""
Dispatch to the different methods responsible for the different stanza
types or handle a non-stanza stream-level element from `stanza_obj`,
which has arrived over the given `xmlstream`.
"""
stanza_obj, exc = queue_entry
# first, handle SM stream objects
if isinstance(stanza_obj, nonza.SMAcknowledgement):
self._logger.debug("received SM ack: %r", stanza_obj)
if not self._sm_enabled:
self._logger.warning("received SM ack, but SM not enabled")
return
self.sm_ack(stanza_obj.counter)
return
elif isinstance(stanza_obj, nonza.SMRequest):
self._logger.debug("received SM request: %r", stanza_obj)
if not self._sm_enabled:
self._logger.warning("received SM request, but SM not enabled")
return
response = nonza.SMAcknowledgement()
response.counter = self._sm_inbound_ctr
self._logger.debug("sending SM ack: %r", response)
xmlstream.send_xso(response)
return
# raise if it is not a stanza
if not isinstance(stanza_obj, stanza.StanzaBase):
raise RuntimeError(
"unexpected stanza class: {}".format(stanza_obj))
# now handle stanzas, these always increment the SM counter
if self._sm_enabled:
self._sm_inbound_ctr += 1
self._sm_inbound_ctr &= 0xffffffff
# check if the stanza has errors
if exc is not None:
self._process_incoming_erroneous_stanza(stanza_obj, exc)
return
if isinstance(stanza_obj, stanza.IQ):
self._process_incoming_iq(stanza_obj)
elif isinstance(stanza_obj, stanza.Message):
self._process_incoming_message(stanza_obj)
elif isinstance(stanza_obj, stanza.Presence):
self._process_incoming_presence(stanza_obj) | [
"def",
"_process_incoming",
"(",
"self",
",",
"xmlstream",
",",
"queue_entry",
")",
":",
"stanza_obj",
",",
"exc",
"=",
"queue_entry",
"# first, handle SM stream objects",
"if",
"isinstance",
"(",
"stanza_obj",
",",
"nonza",
".",
"SMAcknowledgement",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"received SM ack: %r\"",
",",
"stanza_obj",
")",
"if",
"not",
"self",
".",
"_sm_enabled",
":",
"self",
".",
"_logger",
".",
"warning",
"(",
"\"received SM ack, but SM not enabled\"",
")",
"return",
"self",
".",
"sm_ack",
"(",
"stanza_obj",
".",
"counter",
")",
"return",
"elif",
"isinstance",
"(",
"stanza_obj",
",",
"nonza",
".",
"SMRequest",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"received SM request: %r\"",
",",
"stanza_obj",
")",
"if",
"not",
"self",
".",
"_sm_enabled",
":",
"self",
".",
"_logger",
".",
"warning",
"(",
"\"received SM request, but SM not enabled\"",
")",
"return",
"response",
"=",
"nonza",
".",
"SMAcknowledgement",
"(",
")",
"response",
".",
"counter",
"=",
"self",
".",
"_sm_inbound_ctr",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"sending SM ack: %r\"",
",",
"response",
")",
"xmlstream",
".",
"send_xso",
"(",
"response",
")",
"return",
"# raise if it is not a stanza",
"if",
"not",
"isinstance",
"(",
"stanza_obj",
",",
"stanza",
".",
"StanzaBase",
")",
":",
"raise",
"RuntimeError",
"(",
"\"unexpected stanza class: {}\"",
".",
"format",
"(",
"stanza_obj",
")",
")",
"# now handle stanzas, these always increment the SM counter",
"if",
"self",
".",
"_sm_enabled",
":",
"self",
".",
"_sm_inbound_ctr",
"+=",
"1",
"self",
".",
"_sm_inbound_ctr",
"&=",
"0xffffffff",
"# check if the stanza has errors",
"if",
"exc",
"is",
"not",
"None",
":",
"self",
".",
"_process_incoming_erroneous_stanza",
"(",
"stanza_obj",
",",
"exc",
")",
"return",
"if",
"isinstance",
"(",
"stanza_obj",
",",
"stanza",
".",
"IQ",
")",
":",
"self",
".",
"_process_incoming_iq",
"(",
"stanza_obj",
")",
"elif",
"isinstance",
"(",
"stanza_obj",
",",
"stanza",
".",
"Message",
")",
":",
"self",
".",
"_process_incoming_message",
"(",
"stanza_obj",
")",
"elif",
"isinstance",
"(",
"stanza_obj",
",",
"stanza",
".",
"Presence",
")",
":",
"self",
".",
"_process_incoming_presence",
"(",
"stanza_obj",
")"
] | Dispatch to the different methods responsible for the different stanza
types or handle a non-stanza stream-level element from `stanza_obj`,
which has arrived over the given `xmlstream`. | [
"Dispatch",
"to",
"the",
"different",
"methods",
"responsible",
"for",
"the",
"different",
"stanza",
"types",
"or",
"handle",
"a",
"non",
"-",
"stanza",
"stream",
"-",
"level",
"element",
"from",
"stanza_obj",
"which",
"has",
"arrived",
"over",
"the",
"given",
"xmlstream",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L1145-L1193 | -1 |
||||||
687 | horazont/aioxmpp | aioxmpp/stream.py | StanzaStream.flush_incoming | def flush_incoming(self):
"""
Flush all incoming queues to the respective processing methods. The
handlers are called as usual, thus it may require at least one
iteration through the asyncio event loop before effects can be seen.
The incoming queues are empty after a call to this method.
It is legal (but pretty useless) to call this method while the stream
is :attr:`running`.
"""
while True:
try:
stanza_obj = self._incoming_queue.get_nowait()
except asyncio.QueueEmpty:
break
self._process_incoming(None, stanza_obj) | python | def flush_incoming(self):
"""
Flush all incoming queues to the respective processing methods. The
handlers are called as usual, thus it may require at least one
iteration through the asyncio event loop before effects can be seen.
The incoming queues are empty after a call to this method.
It is legal (but pretty useless) to call this method while the stream
is :attr:`running`.
"""
while True:
try:
stanza_obj = self._incoming_queue.get_nowait()
except asyncio.QueueEmpty:
break
self._process_incoming(None, stanza_obj) | [
"def",
"flush_incoming",
"(",
"self",
")",
":",
"while",
"True",
":",
"try",
":",
"stanza_obj",
"=",
"self",
".",
"_incoming_queue",
".",
"get_nowait",
"(",
")",
"except",
"asyncio",
".",
"QueueEmpty",
":",
"break",
"self",
".",
"_process_incoming",
"(",
"None",
",",
"stanza_obj",
")"
] | Flush all incoming queues to the respective processing methods. The
handlers are called as usual, thus it may require at least one
iteration through the asyncio event loop before effects can be seen.
The incoming queues are empty after a call to this method.
It is legal (but pretty useless) to call this method while the stream
is :attr:`running`. | [
"Flush",
"all",
"incoming",
"queues",
"to",
"the",
"respective",
"processing",
"methods",
".",
"The",
"handlers",
"are",
"called",
"as",
"usual",
"thus",
"it",
"may",
"require",
"at",
"least",
"one",
"iteration",
"through",
"the",
"asyncio",
"event",
"loop",
"before",
"effects",
"can",
"be",
"seen",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L1195-L1211 | -1 |
||||||
688 | horazont/aioxmpp | aioxmpp/stream.py | StanzaStream._send_stanza | def _send_stanza(self, xmlstream, token):
"""
Send a stanza token `token` over the given `xmlstream`.
Only sends if the `token` has not been aborted (see
:meth:`StanzaToken.abort`). Sends the state of the token acoording to
:attr:`sm_enabled`.
"""
if token.state == StanzaState.ABORTED:
return
stanza_obj = token.stanza
if isinstance(stanza_obj, stanza.Presence):
stanza_obj = self.app_outbound_presence_filter.filter(
stanza_obj
)
if stanza_obj is not None:
stanza_obj = self.service_outbound_presence_filter.filter(
stanza_obj
)
elif isinstance(stanza_obj, stanza.Message):
stanza_obj = self.app_outbound_message_filter.filter(
stanza_obj
)
if stanza_obj is not None:
stanza_obj = self.service_outbound_message_filter.filter(
stanza_obj
)
if stanza_obj is None:
token._set_state(StanzaState.DROPPED)
self._logger.debug("outgoing stanza %r dropped by filter chain",
token.stanza)
return
self._logger.debug("forwarding stanza to xmlstream: %r",
stanza_obj)
try:
xmlstream.send_xso(stanza_obj)
except Exception as exc:
self._logger.warning("failed to send stanza", exc_info=True)
token._set_state(StanzaState.FAILED, exc)
return
if self._sm_enabled:
token._set_state(StanzaState.SENT)
self._sm_unacked_list.append(token)
else:
token._set_state(StanzaState.SENT_WITHOUT_SM) | python | def _send_stanza(self, xmlstream, token):
"""
Send a stanza token `token` over the given `xmlstream`.
Only sends if the `token` has not been aborted (see
:meth:`StanzaToken.abort`). Sends the state of the token acoording to
:attr:`sm_enabled`.
"""
if token.state == StanzaState.ABORTED:
return
stanza_obj = token.stanza
if isinstance(stanza_obj, stanza.Presence):
stanza_obj = self.app_outbound_presence_filter.filter(
stanza_obj
)
if stanza_obj is not None:
stanza_obj = self.service_outbound_presence_filter.filter(
stanza_obj
)
elif isinstance(stanza_obj, stanza.Message):
stanza_obj = self.app_outbound_message_filter.filter(
stanza_obj
)
if stanza_obj is not None:
stanza_obj = self.service_outbound_message_filter.filter(
stanza_obj
)
if stanza_obj is None:
token._set_state(StanzaState.DROPPED)
self._logger.debug("outgoing stanza %r dropped by filter chain",
token.stanza)
return
self._logger.debug("forwarding stanza to xmlstream: %r",
stanza_obj)
try:
xmlstream.send_xso(stanza_obj)
except Exception as exc:
self._logger.warning("failed to send stanza", exc_info=True)
token._set_state(StanzaState.FAILED, exc)
return
if self._sm_enabled:
token._set_state(StanzaState.SENT)
self._sm_unacked_list.append(token)
else:
token._set_state(StanzaState.SENT_WITHOUT_SM) | [
"def",
"_send_stanza",
"(",
"self",
",",
"xmlstream",
",",
"token",
")",
":",
"if",
"token",
".",
"state",
"==",
"StanzaState",
".",
"ABORTED",
":",
"return",
"stanza_obj",
"=",
"token",
".",
"stanza",
"if",
"isinstance",
"(",
"stanza_obj",
",",
"stanza",
".",
"Presence",
")",
":",
"stanza_obj",
"=",
"self",
".",
"app_outbound_presence_filter",
".",
"filter",
"(",
"stanza_obj",
")",
"if",
"stanza_obj",
"is",
"not",
"None",
":",
"stanza_obj",
"=",
"self",
".",
"service_outbound_presence_filter",
".",
"filter",
"(",
"stanza_obj",
")",
"elif",
"isinstance",
"(",
"stanza_obj",
",",
"stanza",
".",
"Message",
")",
":",
"stanza_obj",
"=",
"self",
".",
"app_outbound_message_filter",
".",
"filter",
"(",
"stanza_obj",
")",
"if",
"stanza_obj",
"is",
"not",
"None",
":",
"stanza_obj",
"=",
"self",
".",
"service_outbound_message_filter",
".",
"filter",
"(",
"stanza_obj",
")",
"if",
"stanza_obj",
"is",
"None",
":",
"token",
".",
"_set_state",
"(",
"StanzaState",
".",
"DROPPED",
")",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"outgoing stanza %r dropped by filter chain\"",
",",
"token",
".",
"stanza",
")",
"return",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"forwarding stanza to xmlstream: %r\"",
",",
"stanza_obj",
")",
"try",
":",
"xmlstream",
".",
"send_xso",
"(",
"stanza_obj",
")",
"except",
"Exception",
"as",
"exc",
":",
"self",
".",
"_logger",
".",
"warning",
"(",
"\"failed to send stanza\"",
",",
"exc_info",
"=",
"True",
")",
"token",
".",
"_set_state",
"(",
"StanzaState",
".",
"FAILED",
",",
"exc",
")",
"return",
"if",
"self",
".",
"_sm_enabled",
":",
"token",
".",
"_set_state",
"(",
"StanzaState",
".",
"SENT",
")",
"self",
".",
"_sm_unacked_list",
".",
"append",
"(",
"token",
")",
"else",
":",
"token",
".",
"_set_state",
"(",
"StanzaState",
".",
"SENT_WITHOUT_SM",
")"
] | Send a stanza token `token` over the given `xmlstream`.
Only sends if the `token` has not been aborted (see
:meth:`StanzaToken.abort`). Sends the state of the token acoording to
:attr:`sm_enabled`. | [
"Send",
"a",
"stanza",
"token",
"token",
"over",
"the",
"given",
"xmlstream",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L1213-L1263 | -1 |
||||||
689 | horazont/aioxmpp | aioxmpp/stream.py | StanzaStream.register_iq_request_handler | def register_iq_request_handler(self, type_, payload_cls, cb, *,
with_send_reply=False):
"""
Register a coroutine function or a function returning an awaitable to
run when an IQ request is received.
: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 cb: Function or coroutine function to invoke
:param with_send_reply: Whether to pass a function to send a reply
to `cb` as second argument.
:type with_send_reply: :class:`bool`
:raises ValueError: if there is already a coroutine registered for this
target
:raises ValueError: if `type_` is not a request IQ type
:raises ValueError: if `type_` is not a valid
:class:`~.IQType` (and cannot be cast to a
:class:`~.IQType`)
The callback `cb` will be called whenever an IQ stanza with the given
`type_` and payload being an instance of the `payload_cls` is received.
The callback must either be a coroutine function or otherwise return an
awaitable. The awaitable must evaluate to a valid value for the
:attr:`.IQ.payload` attribute. That value will be set as the payload
attribute value of an IQ response (with type :attr:`~.IQType.RESULT`)
which is generated and sent by the stream.
If the awaitable or the function raises an exception, it will be
converted to a :class:`~.stanza.Error` object. That error object is
then used as payload for an IQ response (with type
:attr:`~.IQType.ERROR`) which is generated and sent by the stream.
If the exception is a subclass of :class:`aioxmpp.errors.XMPPError`, it
is converted to an :class:`~.stanza.Error` instance directly.
Otherwise, it is wrapped in a :class:`aioxmpp.XMPPCancelError`
with ``undefined-condition``.
For this to work, `payload_cls` *must* be registered using
:meth:`~.IQ.as_payload_class`. Otherwise, the payload will
not be recognised by the stream parser and the IQ is automatically
responded to with a ``feature-not-implemented`` error.
.. warning::
When using a coroutine function for `cb`, there is no guarantee
that concurrent IQ handlers and other coroutines will execute in
any defined order. This implies that the strong ordering guarantees
normally provided by XMPP XML Streams are lost when using coroutine
functions for `cb`. For this reason, the use of non-coroutine
functions is allowed.
.. note::
Using a non-coroutine function for `cb` will generally lead to
less readable code. For the sake of readability, it is recommended
to prefer coroutine functions when strong ordering guarantees are
not needed.
.. versionadded:: 0.11
When the argument `with_send_reply` is true `cb` will be
called with two arguments: the IQ stanza to handle and a
unary function `send_reply(result=None)` that sends a
response to the IQ request and prevents that an automatic
response is sent. If `result` is an instance of
:class:`~aioxmpp.XMPPError` an error result is generated.
This is useful when the handler function needs to execute
actions which happen after the IQ result has been sent,
for example, sending other stanzas.
.. versionchanged:: 0.10
Accepts an awaitable as last argument in addition to coroutine
functions.
Renamed from :meth:`register_iq_request_coro`.
.. versionadded:: 0.6
If the stream is :meth:`stop`\\ -ped (only if SM is not enabled) or
:meth:`close`\\ ed, running IQ response coroutines are
:meth:`asyncio.Task.cancel`\\ -led.
To protect against that, fork from your coroutine using
:func:`asyncio.ensure_future`.
.. versionchanged:: 0.7
The `type_` argument is now supposed to be a :class:`~.IQType`
member.
.. deprecated:: 0.7
Passing a :class:`str` as `type_` argument is deprecated and will
raise a :class:`TypeError` as of the 1.0 release. See the Changelog
for :ref:`api-changelog-0.7` for further details on how to upgrade
your code efficiently.
"""
type_ = self._coerce_enum(type_, structs.IQType)
if not type_.is_request:
raise ValueError(
"{!r} is not a request IQType".format(type_)
)
key = type_, payload_cls
if key in self._iq_request_map:
raise ValueError("only one listener is allowed per tag")
self._iq_request_map[key] = cb, with_send_reply
self._logger.debug(
"iq request coroutine registered: type=%r, payload=%r",
type_, payload_cls) | python | def register_iq_request_handler(self, type_, payload_cls, cb, *,
with_send_reply=False):
"""
Register a coroutine function or a function returning an awaitable to
run when an IQ request is received.
: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 cb: Function or coroutine function to invoke
:param with_send_reply: Whether to pass a function to send a reply
to `cb` as second argument.
:type with_send_reply: :class:`bool`
:raises ValueError: if there is already a coroutine registered for this
target
:raises ValueError: if `type_` is not a request IQ type
:raises ValueError: if `type_` is not a valid
:class:`~.IQType` (and cannot be cast to a
:class:`~.IQType`)
The callback `cb` will be called whenever an IQ stanza with the given
`type_` and payload being an instance of the `payload_cls` is received.
The callback must either be a coroutine function or otherwise return an
awaitable. The awaitable must evaluate to a valid value for the
:attr:`.IQ.payload` attribute. That value will be set as the payload
attribute value of an IQ response (with type :attr:`~.IQType.RESULT`)
which is generated and sent by the stream.
If the awaitable or the function raises an exception, it will be
converted to a :class:`~.stanza.Error` object. That error object is
then used as payload for an IQ response (with type
:attr:`~.IQType.ERROR`) which is generated and sent by the stream.
If the exception is a subclass of :class:`aioxmpp.errors.XMPPError`, it
is converted to an :class:`~.stanza.Error` instance directly.
Otherwise, it is wrapped in a :class:`aioxmpp.XMPPCancelError`
with ``undefined-condition``.
For this to work, `payload_cls` *must* be registered using
:meth:`~.IQ.as_payload_class`. Otherwise, the payload will
not be recognised by the stream parser and the IQ is automatically
responded to with a ``feature-not-implemented`` error.
.. warning::
When using a coroutine function for `cb`, there is no guarantee
that concurrent IQ handlers and other coroutines will execute in
any defined order. This implies that the strong ordering guarantees
normally provided by XMPP XML Streams are lost when using coroutine
functions for `cb`. For this reason, the use of non-coroutine
functions is allowed.
.. note::
Using a non-coroutine function for `cb` will generally lead to
less readable code. For the sake of readability, it is recommended
to prefer coroutine functions when strong ordering guarantees are
not needed.
.. versionadded:: 0.11
When the argument `with_send_reply` is true `cb` will be
called with two arguments: the IQ stanza to handle and a
unary function `send_reply(result=None)` that sends a
response to the IQ request and prevents that an automatic
response is sent. If `result` is an instance of
:class:`~aioxmpp.XMPPError` an error result is generated.
This is useful when the handler function needs to execute
actions which happen after the IQ result has been sent,
for example, sending other stanzas.
.. versionchanged:: 0.10
Accepts an awaitable as last argument in addition to coroutine
functions.
Renamed from :meth:`register_iq_request_coro`.
.. versionadded:: 0.6
If the stream is :meth:`stop`\\ -ped (only if SM is not enabled) or
:meth:`close`\\ ed, running IQ response coroutines are
:meth:`asyncio.Task.cancel`\\ -led.
To protect against that, fork from your coroutine using
:func:`asyncio.ensure_future`.
.. versionchanged:: 0.7
The `type_` argument is now supposed to be a :class:`~.IQType`
member.
.. deprecated:: 0.7
Passing a :class:`str` as `type_` argument is deprecated and will
raise a :class:`TypeError` as of the 1.0 release. See the Changelog
for :ref:`api-changelog-0.7` for further details on how to upgrade
your code efficiently.
"""
type_ = self._coerce_enum(type_, structs.IQType)
if not type_.is_request:
raise ValueError(
"{!r} is not a request IQType".format(type_)
)
key = type_, payload_cls
if key in self._iq_request_map:
raise ValueError("only one listener is allowed per tag")
self._iq_request_map[key] = cb, with_send_reply
self._logger.debug(
"iq request coroutine registered: type=%r, payload=%r",
type_, payload_cls) | [
"def",
"register_iq_request_handler",
"(",
"self",
",",
"type_",
",",
"payload_cls",
",",
"cb",
",",
"*",
",",
"with_send_reply",
"=",
"False",
")",
":",
"type_",
"=",
"self",
".",
"_coerce_enum",
"(",
"type_",
",",
"structs",
".",
"IQType",
")",
"if",
"not",
"type_",
".",
"is_request",
":",
"raise",
"ValueError",
"(",
"\"{!r} is not a request IQType\"",
".",
"format",
"(",
"type_",
")",
")",
"key",
"=",
"type_",
",",
"payload_cls",
"if",
"key",
"in",
"self",
".",
"_iq_request_map",
":",
"raise",
"ValueError",
"(",
"\"only one listener is allowed per tag\"",
")",
"self",
".",
"_iq_request_map",
"[",
"key",
"]",
"=",
"cb",
",",
"with_send_reply",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"iq request coroutine registered: type=%r, payload=%r\"",
",",
"type_",
",",
"payload_cls",
")"
] | Register a coroutine function or a function returning an awaitable to
run when an IQ request is received.
: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 cb: Function or coroutine function to invoke
:param with_send_reply: Whether to pass a function to send a reply
to `cb` as second argument.
:type with_send_reply: :class:`bool`
:raises ValueError: if there is already a coroutine registered for this
target
:raises ValueError: if `type_` is not a request IQ type
:raises ValueError: if `type_` is not a valid
:class:`~.IQType` (and cannot be cast to a
:class:`~.IQType`)
The callback `cb` will be called whenever an IQ stanza with the given
`type_` and payload being an instance of the `payload_cls` is received.
The callback must either be a coroutine function or otherwise return an
awaitable. The awaitable must evaluate to a valid value for the
:attr:`.IQ.payload` attribute. That value will be set as the payload
attribute value of an IQ response (with type :attr:`~.IQType.RESULT`)
which is generated and sent by the stream.
If the awaitable or the function raises an exception, it will be
converted to a :class:`~.stanza.Error` object. That error object is
then used as payload for an IQ response (with type
:attr:`~.IQType.ERROR`) which is generated and sent by the stream.
If the exception is a subclass of :class:`aioxmpp.errors.XMPPError`, it
is converted to an :class:`~.stanza.Error` instance directly.
Otherwise, it is wrapped in a :class:`aioxmpp.XMPPCancelError`
with ``undefined-condition``.
For this to work, `payload_cls` *must* be registered using
:meth:`~.IQ.as_payload_class`. Otherwise, the payload will
not be recognised by the stream parser and the IQ is automatically
responded to with a ``feature-not-implemented`` error.
.. warning::
When using a coroutine function for `cb`, there is no guarantee
that concurrent IQ handlers and other coroutines will execute in
any defined order. This implies that the strong ordering guarantees
normally provided by XMPP XML Streams are lost when using coroutine
functions for `cb`. For this reason, the use of non-coroutine
functions is allowed.
.. note::
Using a non-coroutine function for `cb` will generally lead to
less readable code. For the sake of readability, it is recommended
to prefer coroutine functions when strong ordering guarantees are
not needed.
.. versionadded:: 0.11
When the argument `with_send_reply` is true `cb` will be
called with two arguments: the IQ stanza to handle and a
unary function `send_reply(result=None)` that sends a
response to the IQ request and prevents that an automatic
response is sent. If `result` is an instance of
:class:`~aioxmpp.XMPPError` an error result is generated.
This is useful when the handler function needs to execute
actions which happen after the IQ result has been sent,
for example, sending other stanzas.
.. versionchanged:: 0.10
Accepts an awaitable as last argument in addition to coroutine
functions.
Renamed from :meth:`register_iq_request_coro`.
.. versionadded:: 0.6
If the stream is :meth:`stop`\\ -ped (only if SM is not enabled) or
:meth:`close`\\ ed, running IQ response coroutines are
:meth:`asyncio.Task.cancel`\\ -led.
To protect against that, fork from your coroutine using
:func:`asyncio.ensure_future`.
.. versionchanged:: 0.7
The `type_` argument is now supposed to be a :class:`~.IQType`
member.
.. deprecated:: 0.7
Passing a :class:`str` as `type_` argument is deprecated and will
raise a :class:`TypeError` as of the 1.0 release. See the Changelog
for :ref:`api-changelog-0.7` for further details on how to upgrade
your code efficiently. | [
"Register",
"a",
"coroutine",
"function",
"or",
"a",
"function",
"returning",
"an",
"awaitable",
"to",
"run",
"when",
"an",
"IQ",
"request",
"is",
"received",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L1394-L1511 | -1 |
||||||
690 | horazont/aioxmpp | aioxmpp/stream.py | StanzaStream.register_message_callback | def register_message_callback(self, type_, from_, cb):
"""
Register a callback to be called when a message is received.
: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 function to call
:raises ValueError: if another function is already registered for the
same ``(type_, from_)`` pair.
:raises ValueError: if `type_` is not a valid
:class:`~.MessageType` (and cannot be cast
to a :class:`~.MessageType`)
`cb` will be called whenever a message stanza matching the `type_` and
`from_` is received, according to the wildcarding rules below. More
specific callbacks win over less specific callbacks, and the match on
the `from_` address takes precedence over the match on the `type_`.
See :meth:`.SimpleStanzaDispatcher.register_callback` for the exact
wildcarding rules.
.. versionchanged:: 0.7
The `type_` argument is now supposed to be a
:class:`~.MessageType` member.
.. deprecated:: 0.7
Passing a :class:`str` as `type_` argument is deprecated and will
raise a :class:`TypeError` as of the 1.0 release. See the Changelog
for :ref:`api-changelog-0.7` for further details on how to upgrade
your code efficiently.
.. deprecated:: 0.9
This method has been deprecated in favour of and is now implemented
in terms of the :class:`aioxmpp.dispatcher.SimpleMessageDispatcher`
service.
It is equivalent to call
:meth:`~.SimpleStanzaDispatcher.register_callback`, except that the
latter is not deprecated.
"""
if type_ is not None:
type_ = self._coerce_enum(type_, structs.MessageType)
warnings.warn(
"register_message_callback is deprecated; use "
"aioxmpp.dispatcher.SimpleMessageDispatcher instead",
DeprecationWarning,
stacklevel=2
)
self._xxx_message_dispatcher.register_callback(
type_,
from_,
cb,
) | python | def register_message_callback(self, type_, from_, cb):
"""
Register a callback to be called when a message is received.
: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 function to call
:raises ValueError: if another function is already registered for the
same ``(type_, from_)`` pair.
:raises ValueError: if `type_` is not a valid
:class:`~.MessageType` (and cannot be cast
to a :class:`~.MessageType`)
`cb` will be called whenever a message stanza matching the `type_` and
`from_` is received, according to the wildcarding rules below. More
specific callbacks win over less specific callbacks, and the match on
the `from_` address takes precedence over the match on the `type_`.
See :meth:`.SimpleStanzaDispatcher.register_callback` for the exact
wildcarding rules.
.. versionchanged:: 0.7
The `type_` argument is now supposed to be a
:class:`~.MessageType` member.
.. deprecated:: 0.7
Passing a :class:`str` as `type_` argument is deprecated and will
raise a :class:`TypeError` as of the 1.0 release. See the Changelog
for :ref:`api-changelog-0.7` for further details on how to upgrade
your code efficiently.
.. deprecated:: 0.9
This method has been deprecated in favour of and is now implemented
in terms of the :class:`aioxmpp.dispatcher.SimpleMessageDispatcher`
service.
It is equivalent to call
:meth:`~.SimpleStanzaDispatcher.register_callback`, except that the
latter is not deprecated.
"""
if type_ is not None:
type_ = self._coerce_enum(type_, structs.MessageType)
warnings.warn(
"register_message_callback is deprecated; use "
"aioxmpp.dispatcher.SimpleMessageDispatcher instead",
DeprecationWarning,
stacklevel=2
)
self._xxx_message_dispatcher.register_callback(
type_,
from_,
cb,
) | [
"def",
"register_message_callback",
"(",
"self",
",",
"type_",
",",
"from_",
",",
"cb",
")",
":",
"if",
"type_",
"is",
"not",
"None",
":",
"type_",
"=",
"self",
".",
"_coerce_enum",
"(",
"type_",
",",
"structs",
".",
"MessageType",
")",
"warnings",
".",
"warn",
"(",
"\"register_message_callback is deprecated; use \"",
"\"aioxmpp.dispatcher.SimpleMessageDispatcher instead\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"self",
".",
"_xxx_message_dispatcher",
".",
"register_callback",
"(",
"type_",
",",
"from_",
",",
"cb",
",",
")"
] | Register a callback to be called when a message is received.
: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 function to call
:raises ValueError: if another function is already registered for the
same ``(type_, from_)`` pair.
:raises ValueError: if `type_` is not a valid
:class:`~.MessageType` (and cannot be cast
to a :class:`~.MessageType`)
`cb` will be called whenever a message stanza matching the `type_` and
`from_` is received, according to the wildcarding rules below. More
specific callbacks win over less specific callbacks, and the match on
the `from_` address takes precedence over the match on the `type_`.
See :meth:`.SimpleStanzaDispatcher.register_callback` for the exact
wildcarding rules.
.. versionchanged:: 0.7
The `type_` argument is now supposed to be a
:class:`~.MessageType` member.
.. deprecated:: 0.7
Passing a :class:`str` as `type_` argument is deprecated and will
raise a :class:`TypeError` as of the 1.0 release. See the Changelog
for :ref:`api-changelog-0.7` for further details on how to upgrade
your code efficiently.
.. deprecated:: 0.9
This method has been deprecated in favour of and is now implemented
in terms of the :class:`aioxmpp.dispatcher.SimpleMessageDispatcher`
service.
It is equivalent to call
:meth:`~.SimpleStanzaDispatcher.register_callback`, except that the
latter is not deprecated. | [
"Register",
"a",
"callback",
"to",
"be",
"called",
"when",
"a",
"message",
"is",
"received",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L1563-L1622 | -1 |
||||||
691 | horazont/aioxmpp | aioxmpp/stream.py | StanzaStream.register_presence_callback | def register_presence_callback(self, type_, from_, cb):
"""
Register a callback to be called when a presence stanza is received.
: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 function
:raises ValueError: if another listener with the same ``(type_,
from_)`` pair is already registered
:raises ValueError: if `type_` is not a valid
:class:`~.PresenceType` (and cannot be cast
to a :class:`~.PresenceType`)
`cb` will be called whenever a presence stanza matching the `type_` is
received from the specified sender. `from_` may be :data:`None` to
indicate a wildcard. Like with :meth:`register_message_callback`, more
specific callbacks win over less specific callbacks. The fallback order
is identical, except that the ``type_=None`` entries described there do
not apply for presence stanzas and are thus omitted.
See :meth:`.SimpleStanzaDispatcher.register_callback` for the exact
wildcarding rules.
.. versionchanged:: 0.7
The `type_` argument is now supposed to be a
:class:`~.PresenceType` member.
.. deprecated:: 0.7
Passing a :class:`str` as `type_` argument is deprecated and will
raise a :class:`TypeError` as of the 1.0 release. See the Changelog
for :ref:`api-changelog-0.7` for further details on how to upgrade
your code efficiently.
.. deprecated:: 0.9
This method has been deprecated. It is recommended to use
:class:`aioxmpp.PresenceClient` instead.
"""
type_ = self._coerce_enum(type_, structs.PresenceType)
warnings.warn(
"register_presence_callback is deprecated; use "
"aioxmpp.dispatcher.SimplePresenceDispatcher or "
"aioxmpp.PresenceClient instead",
DeprecationWarning,
stacklevel=2
)
self._xxx_presence_dispatcher.register_callback(
type_,
from_,
cb,
) | python | def register_presence_callback(self, type_, from_, cb):
"""
Register a callback to be called when a presence stanza is received.
: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 function
:raises ValueError: if another listener with the same ``(type_,
from_)`` pair is already registered
:raises ValueError: if `type_` is not a valid
:class:`~.PresenceType` (and cannot be cast
to a :class:`~.PresenceType`)
`cb` will be called whenever a presence stanza matching the `type_` is
received from the specified sender. `from_` may be :data:`None` to
indicate a wildcard. Like with :meth:`register_message_callback`, more
specific callbacks win over less specific callbacks. The fallback order
is identical, except that the ``type_=None`` entries described there do
not apply for presence stanzas and are thus omitted.
See :meth:`.SimpleStanzaDispatcher.register_callback` for the exact
wildcarding rules.
.. versionchanged:: 0.7
The `type_` argument is now supposed to be a
:class:`~.PresenceType` member.
.. deprecated:: 0.7
Passing a :class:`str` as `type_` argument is deprecated and will
raise a :class:`TypeError` as of the 1.0 release. See the Changelog
for :ref:`api-changelog-0.7` for further details on how to upgrade
your code efficiently.
.. deprecated:: 0.9
This method has been deprecated. It is recommended to use
:class:`aioxmpp.PresenceClient` instead.
"""
type_ = self._coerce_enum(type_, structs.PresenceType)
warnings.warn(
"register_presence_callback is deprecated; use "
"aioxmpp.dispatcher.SimplePresenceDispatcher or "
"aioxmpp.PresenceClient instead",
DeprecationWarning,
stacklevel=2
)
self._xxx_presence_dispatcher.register_callback(
type_,
from_,
cb,
) | [
"def",
"register_presence_callback",
"(",
"self",
",",
"type_",
",",
"from_",
",",
"cb",
")",
":",
"type_",
"=",
"self",
".",
"_coerce_enum",
"(",
"type_",
",",
"structs",
".",
"PresenceType",
")",
"warnings",
".",
"warn",
"(",
"\"register_presence_callback is deprecated; use \"",
"\"aioxmpp.dispatcher.SimplePresenceDispatcher or \"",
"\"aioxmpp.PresenceClient instead\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"self",
".",
"_xxx_presence_dispatcher",
".",
"register_callback",
"(",
"type_",
",",
"from_",
",",
"cb",
",",
")"
] | Register a callback to be called when a presence stanza is received.
: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 function
:raises ValueError: if another listener with the same ``(type_,
from_)`` pair is already registered
:raises ValueError: if `type_` is not a valid
:class:`~.PresenceType` (and cannot be cast
to a :class:`~.PresenceType`)
`cb` will be called whenever a presence stanza matching the `type_` is
received from the specified sender. `from_` may be :data:`None` to
indicate a wildcard. Like with :meth:`register_message_callback`, more
specific callbacks win over less specific callbacks. The fallback order
is identical, except that the ``type_=None`` entries described there do
not apply for presence stanzas and are thus omitted.
See :meth:`.SimpleStanzaDispatcher.register_callback` for the exact
wildcarding rules.
.. versionchanged:: 0.7
The `type_` argument is now supposed to be a
:class:`~.PresenceType` member.
.. deprecated:: 0.7
Passing a :class:`str` as `type_` argument is deprecated and will
raise a :class:`TypeError` as of the 1.0 release. See the Changelog
for :ref:`api-changelog-0.7` for further details on how to upgrade
your code efficiently.
.. deprecated:: 0.9
This method has been deprecated. It is recommended to use
:class:`aioxmpp.PresenceClient` instead. | [
"Register",
"a",
"callback",
"to",
"be",
"called",
"when",
"a",
"presence",
"stanza",
"is",
"received",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L1680-L1736 | -1 |
||||||
692 | horazont/aioxmpp | aioxmpp/stream.py | StanzaStream.wait_stop | def wait_stop(self):
"""
Stop the stream and wait for it to stop.
See :meth:`stop` for the general stopping conditions. You can assume
that :meth:`stop` is the first thing this coroutine calls.
"""
if not self.running:
return
self.stop()
try:
yield from self._task
except asyncio.CancelledError:
pass | python | def wait_stop(self):
"""
Stop the stream and wait for it to stop.
See :meth:`stop` for the general stopping conditions. You can assume
that :meth:`stop` is the first thing this coroutine calls.
"""
if not self.running:
return
self.stop()
try:
yield from self._task
except asyncio.CancelledError:
pass | [
"def",
"wait_stop",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"running",
":",
"return",
"self",
".",
"stop",
"(",
")",
"try",
":",
"yield",
"from",
"self",
".",
"_task",
"except",
"asyncio",
".",
"CancelledError",
":",
"pass"
] | Stop the stream and wait for it to stop.
See :meth:`stop` for the general stopping conditions. You can assume
that :meth:`stop` is the first thing this coroutine calls. | [
"Stop",
"the",
"stream",
"and",
"wait",
"for",
"it",
"to",
"stop",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L1912-L1925 | -1 |
||||||
693 | horazont/aioxmpp | aioxmpp/stream.py | StanzaStream.resume_sm | def resume_sm(self, xmlstream):
"""
Resume an SM-enabled stream using the given `xmlstream`.
If the server rejects the attempt to resume stream management, a
:class:`.errors.StreamNegotiationFailure` is raised. The stream is then
in stopped state and stream management has been stopped.
.. warning::
This method cannot and does not check whether the server advertised
support for stream management. Attempting to negotiate stream
management without server support might lead to termination of the
stream.
If the XML stream dies at any point during the negotiation, the SM
state is left unchanged. If no response has been received yet, the
exception which caused the stream to die is re-raised. The state of the
stream depends on whether the main task already noticed the dead
stream.
If negotiation succeeds, this coroutine resumes the stream management
session and initiates the retransmission of any unacked stanzas. The
stream is then in running state.
.. versionchanged:: 0.11
Support for using the counter value provided some servers on a
failed resumption was added. Stanzas which are covered by the
counter will be marked as :attr:`~StanzaState.ACKED`; other stanzas
will be marked as :attr:`~StanzaState.DISCONNECTED`.
This is in contrast to the behaviour when resumption fails
*without* a counter given. In that case, stanzas which have not
been acked are marked as :attr:`~StanzaState.SENT_WITHOUT_SM`.
"""
if self.running:
raise RuntimeError("Cannot resume Stream Management while"
" StanzaStream is running")
self._start_prepare(xmlstream, self.recv_stanza)
try:
response = yield from protocol.send_and_wait_for(
xmlstream,
[
nonza.SMResume(previd=self.sm_id,
counter=self._sm_inbound_ctr)
],
[
nonza.SMResumed,
nonza.SMFailed
]
)
if isinstance(response, nonza.SMFailed):
exc = errors.StreamNegotiationFailure(
"Server rejected SM resumption"
)
if response.counter is not None:
self.sm_ack(response.counter)
self._clear_unacked(StanzaState.DISCONNECTED)
xmlstream.stanza_parser.remove_class(
nonza.SMRequest)
xmlstream.stanza_parser.remove_class(
nonza.SMAcknowledgement)
self.stop_sm()
raise exc
self._resume_sm(response.counter)
except: # NOQA
self._start_rollback(xmlstream)
raise
self._start_commit(xmlstream) | python | def resume_sm(self, xmlstream):
"""
Resume an SM-enabled stream using the given `xmlstream`.
If the server rejects the attempt to resume stream management, a
:class:`.errors.StreamNegotiationFailure` is raised. The stream is then
in stopped state and stream management has been stopped.
.. warning::
This method cannot and does not check whether the server advertised
support for stream management. Attempting to negotiate stream
management without server support might lead to termination of the
stream.
If the XML stream dies at any point during the negotiation, the SM
state is left unchanged. If no response has been received yet, the
exception which caused the stream to die is re-raised. The state of the
stream depends on whether the main task already noticed the dead
stream.
If negotiation succeeds, this coroutine resumes the stream management
session and initiates the retransmission of any unacked stanzas. The
stream is then in running state.
.. versionchanged:: 0.11
Support for using the counter value provided some servers on a
failed resumption was added. Stanzas which are covered by the
counter will be marked as :attr:`~StanzaState.ACKED`; other stanzas
will be marked as :attr:`~StanzaState.DISCONNECTED`.
This is in contrast to the behaviour when resumption fails
*without* a counter given. In that case, stanzas which have not
been acked are marked as :attr:`~StanzaState.SENT_WITHOUT_SM`.
"""
if self.running:
raise RuntimeError("Cannot resume Stream Management while"
" StanzaStream is running")
self._start_prepare(xmlstream, self.recv_stanza)
try:
response = yield from protocol.send_and_wait_for(
xmlstream,
[
nonza.SMResume(previd=self.sm_id,
counter=self._sm_inbound_ctr)
],
[
nonza.SMResumed,
nonza.SMFailed
]
)
if isinstance(response, nonza.SMFailed):
exc = errors.StreamNegotiationFailure(
"Server rejected SM resumption"
)
if response.counter is not None:
self.sm_ack(response.counter)
self._clear_unacked(StanzaState.DISCONNECTED)
xmlstream.stanza_parser.remove_class(
nonza.SMRequest)
xmlstream.stanza_parser.remove_class(
nonza.SMAcknowledgement)
self.stop_sm()
raise exc
self._resume_sm(response.counter)
except: # NOQA
self._start_rollback(xmlstream)
raise
self._start_commit(xmlstream) | [
"def",
"resume_sm",
"(",
"self",
",",
"xmlstream",
")",
":",
"if",
"self",
".",
"running",
":",
"raise",
"RuntimeError",
"(",
"\"Cannot resume Stream Management while\"",
"\" StanzaStream is running\"",
")",
"self",
".",
"_start_prepare",
"(",
"xmlstream",
",",
"self",
".",
"recv_stanza",
")",
"try",
":",
"response",
"=",
"yield",
"from",
"protocol",
".",
"send_and_wait_for",
"(",
"xmlstream",
",",
"[",
"nonza",
".",
"SMResume",
"(",
"previd",
"=",
"self",
".",
"sm_id",
",",
"counter",
"=",
"self",
".",
"_sm_inbound_ctr",
")",
"]",
",",
"[",
"nonza",
".",
"SMResumed",
",",
"nonza",
".",
"SMFailed",
"]",
")",
"if",
"isinstance",
"(",
"response",
",",
"nonza",
".",
"SMFailed",
")",
":",
"exc",
"=",
"errors",
".",
"StreamNegotiationFailure",
"(",
"\"Server rejected SM resumption\"",
")",
"if",
"response",
".",
"counter",
"is",
"not",
"None",
":",
"self",
".",
"sm_ack",
"(",
"response",
".",
"counter",
")",
"self",
".",
"_clear_unacked",
"(",
"StanzaState",
".",
"DISCONNECTED",
")",
"xmlstream",
".",
"stanza_parser",
".",
"remove_class",
"(",
"nonza",
".",
"SMRequest",
")",
"xmlstream",
".",
"stanza_parser",
".",
"remove_class",
"(",
"nonza",
".",
"SMAcknowledgement",
")",
"self",
".",
"stop_sm",
"(",
")",
"raise",
"exc",
"self",
".",
"_resume_sm",
"(",
"response",
".",
"counter",
")",
"except",
":",
"# NOQA",
"self",
".",
"_start_rollback",
"(",
"xmlstream",
")",
"raise",
"self",
".",
"_start_commit",
"(",
"xmlstream",
")"
] | Resume an SM-enabled stream using the given `xmlstream`.
If the server rejects the attempt to resume stream management, a
:class:`.errors.StreamNegotiationFailure` is raised. The stream is then
in stopped state and stream management has been stopped.
.. warning::
This method cannot and does not check whether the server advertised
support for stream management. Attempting to negotiate stream
management without server support might lead to termination of the
stream.
If the XML stream dies at any point during the negotiation, the SM
state is left unchanged. If no response has been received yet, the
exception which caused the stream to die is re-raised. The state of the
stream depends on whether the main task already noticed the dead
stream.
If negotiation succeeds, this coroutine resumes the stream management
session and initiates the retransmission of any unacked stanzas. The
stream is then in running state.
.. versionchanged:: 0.11
Support for using the counter value provided some servers on a
failed resumption was added. Stanzas which are covered by the
counter will be marked as :attr:`~StanzaState.ACKED`; other stanzas
will be marked as :attr:`~StanzaState.DISCONNECTED`.
This is in contrast to the behaviour when resumption fails
*without* a counter given. In that case, stanzas which have not
been acked are marked as :attr:`~StanzaState.SENT_WITHOUT_SM`. | [
"Resume",
"an",
"SM",
"-",
"enabled",
"stream",
"using",
"the",
"given",
"xmlstream",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L2359-L2434 | -1 |
||||||
694 | horazont/aioxmpp | aioxmpp/stream.py | StanzaStream._send_immediately | def _send_immediately(self, stanza, *, timeout=None, cb=None):
"""
Send a stanza without waiting for the stream to be ready to send
stanzas.
This is only useful from within :class:`aioxmpp.node.Client` before
the stream is fully established.
"""
stanza.autoset_id()
self._logger.debug("sending %r and waiting for it to be sent",
stanza)
if not isinstance(stanza, stanza_.IQ) or stanza.type_.is_response:
if cb is not None:
raise ValueError(
"cb not supported with non-IQ non-request stanzas"
)
yield from self._enqueue(stanza)
return
# we use the long way with a custom listener instead of a future here
# to ensure that the callback is called synchronously from within the
# queue handling loop.
# we need that to ensure that the strong ordering guarantees reach the
# `cb` function.
fut = asyncio.Future()
def nested_cb(task):
"""
This callback is used to handle awaitables returned by the `cb`.
"""
nonlocal fut
if task.exception() is None:
fut.set_result(task.result())
else:
fut.set_exception(task.exception())
def handler_ok(stanza):
"""
This handler is invoked synchronously by
:meth:`_process_incoming_iq` (via
:class:`aioxmpp.callbacks.TagDispatcher`) for response stanzas
(including error stanzas).
"""
nonlocal fut
if fut.cancelled():
return
if cb is not None:
try:
nested_fut = cb(stanza)
except Exception as exc:
fut.set_exception(exc)
else:
if nested_fut is not None:
nested_fut.add_done_callback(nested_cb)
return
# we can’t even use StanzaErrorAwareListener because we want to
# forward error stanzas to the cb too...
if stanza.type_.is_error:
fut.set_exception(stanza.error.to_exception())
else:
fut.set_result(stanza.payload)
def handler_error(exc):
"""
This handler is invoked synchronously by
:meth:`_process_incoming_iq` (via
:class:`aioxmpp.callbacks.TagDispatcher`) for response errors (
such as parsing errors, connection errors, etc.).
"""
nonlocal fut
if fut.cancelled():
return
fut.set_exception(exc)
listener = callbacks.OneshotTagListener(
handler_ok,
handler_error,
)
listener_tag = (stanza.to, stanza.id_)
self._iq_response_map.add_listener(
listener_tag,
listener,
)
try:
yield from self._enqueue(stanza)
except Exception:
listener.cancel()
raise
try:
if not timeout:
reply = yield from fut
else:
try:
reply = yield from asyncio.wait_for(
fut,
timeout=timeout
)
except asyncio.TimeoutError:
raise TimeoutError
finally:
try:
self._iq_response_map.remove_listener(listener_tag)
except KeyError:
pass
return reply | python | def _send_immediately(self, stanza, *, timeout=None, cb=None):
"""
Send a stanza without waiting for the stream to be ready to send
stanzas.
This is only useful from within :class:`aioxmpp.node.Client` before
the stream is fully established.
"""
stanza.autoset_id()
self._logger.debug("sending %r and waiting for it to be sent",
stanza)
if not isinstance(stanza, stanza_.IQ) or stanza.type_.is_response:
if cb is not None:
raise ValueError(
"cb not supported with non-IQ non-request stanzas"
)
yield from self._enqueue(stanza)
return
# we use the long way with a custom listener instead of a future here
# to ensure that the callback is called synchronously from within the
# queue handling loop.
# we need that to ensure that the strong ordering guarantees reach the
# `cb` function.
fut = asyncio.Future()
def nested_cb(task):
"""
This callback is used to handle awaitables returned by the `cb`.
"""
nonlocal fut
if task.exception() is None:
fut.set_result(task.result())
else:
fut.set_exception(task.exception())
def handler_ok(stanza):
"""
This handler is invoked synchronously by
:meth:`_process_incoming_iq` (via
:class:`aioxmpp.callbacks.TagDispatcher`) for response stanzas
(including error stanzas).
"""
nonlocal fut
if fut.cancelled():
return
if cb is not None:
try:
nested_fut = cb(stanza)
except Exception as exc:
fut.set_exception(exc)
else:
if nested_fut is not None:
nested_fut.add_done_callback(nested_cb)
return
# we can’t even use StanzaErrorAwareListener because we want to
# forward error stanzas to the cb too...
if stanza.type_.is_error:
fut.set_exception(stanza.error.to_exception())
else:
fut.set_result(stanza.payload)
def handler_error(exc):
"""
This handler is invoked synchronously by
:meth:`_process_incoming_iq` (via
:class:`aioxmpp.callbacks.TagDispatcher`) for response errors (
such as parsing errors, connection errors, etc.).
"""
nonlocal fut
if fut.cancelled():
return
fut.set_exception(exc)
listener = callbacks.OneshotTagListener(
handler_ok,
handler_error,
)
listener_tag = (stanza.to, stanza.id_)
self._iq_response_map.add_listener(
listener_tag,
listener,
)
try:
yield from self._enqueue(stanza)
except Exception:
listener.cancel()
raise
try:
if not timeout:
reply = yield from fut
else:
try:
reply = yield from asyncio.wait_for(
fut,
timeout=timeout
)
except asyncio.TimeoutError:
raise TimeoutError
finally:
try:
self._iq_response_map.remove_listener(listener_tag)
except KeyError:
pass
return reply | [
"def",
"_send_immediately",
"(",
"self",
",",
"stanza",
",",
"*",
",",
"timeout",
"=",
"None",
",",
"cb",
"=",
"None",
")",
":",
"stanza",
".",
"autoset_id",
"(",
")",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"sending %r and waiting for it to be sent\"",
",",
"stanza",
")",
"if",
"not",
"isinstance",
"(",
"stanza",
",",
"stanza_",
".",
"IQ",
")",
"or",
"stanza",
".",
"type_",
".",
"is_response",
":",
"if",
"cb",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"cb not supported with non-IQ non-request stanzas\"",
")",
"yield",
"from",
"self",
".",
"_enqueue",
"(",
"stanza",
")",
"return",
"# we use the long way with a custom listener instead of a future here",
"# to ensure that the callback is called synchronously from within the",
"# queue handling loop.",
"# we need that to ensure that the strong ordering guarantees reach the",
"# `cb` function.",
"fut",
"=",
"asyncio",
".",
"Future",
"(",
")",
"def",
"nested_cb",
"(",
"task",
")",
":",
"\"\"\"\n This callback is used to handle awaitables returned by the `cb`.\n \"\"\"",
"nonlocal",
"fut",
"if",
"task",
".",
"exception",
"(",
")",
"is",
"None",
":",
"fut",
".",
"set_result",
"(",
"task",
".",
"result",
"(",
")",
")",
"else",
":",
"fut",
".",
"set_exception",
"(",
"task",
".",
"exception",
"(",
")",
")",
"def",
"handler_ok",
"(",
"stanza",
")",
":",
"\"\"\"\n This handler is invoked synchronously by\n :meth:`_process_incoming_iq` (via\n :class:`aioxmpp.callbacks.TagDispatcher`) for response stanzas\n (including error stanzas).\n \"\"\"",
"nonlocal",
"fut",
"if",
"fut",
".",
"cancelled",
"(",
")",
":",
"return",
"if",
"cb",
"is",
"not",
"None",
":",
"try",
":",
"nested_fut",
"=",
"cb",
"(",
"stanza",
")",
"except",
"Exception",
"as",
"exc",
":",
"fut",
".",
"set_exception",
"(",
"exc",
")",
"else",
":",
"if",
"nested_fut",
"is",
"not",
"None",
":",
"nested_fut",
".",
"add_done_callback",
"(",
"nested_cb",
")",
"return",
"# we can’t even use StanzaErrorAwareListener because we want to",
"# forward error stanzas to the cb too...",
"if",
"stanza",
".",
"type_",
".",
"is_error",
":",
"fut",
".",
"set_exception",
"(",
"stanza",
".",
"error",
".",
"to_exception",
"(",
")",
")",
"else",
":",
"fut",
".",
"set_result",
"(",
"stanza",
".",
"payload",
")",
"def",
"handler_error",
"(",
"exc",
")",
":",
"\"\"\"\n This handler is invoked synchronously by\n :meth:`_process_incoming_iq` (via\n :class:`aioxmpp.callbacks.TagDispatcher`) for response errors (\n such as parsing errors, connection errors, etc.).\n \"\"\"",
"nonlocal",
"fut",
"if",
"fut",
".",
"cancelled",
"(",
")",
":",
"return",
"fut",
".",
"set_exception",
"(",
"exc",
")",
"listener",
"=",
"callbacks",
".",
"OneshotTagListener",
"(",
"handler_ok",
",",
"handler_error",
",",
")",
"listener_tag",
"=",
"(",
"stanza",
".",
"to",
",",
"stanza",
".",
"id_",
")",
"self",
".",
"_iq_response_map",
".",
"add_listener",
"(",
"listener_tag",
",",
"listener",
",",
")",
"try",
":",
"yield",
"from",
"self",
".",
"_enqueue",
"(",
"stanza",
")",
"except",
"Exception",
":",
"listener",
".",
"cancel",
"(",
")",
"raise",
"try",
":",
"if",
"not",
"timeout",
":",
"reply",
"=",
"yield",
"from",
"fut",
"else",
":",
"try",
":",
"reply",
"=",
"yield",
"from",
"asyncio",
".",
"wait_for",
"(",
"fut",
",",
"timeout",
"=",
"timeout",
")",
"except",
"asyncio",
".",
"TimeoutError",
":",
"raise",
"TimeoutError",
"finally",
":",
"try",
":",
"self",
".",
"_iq_response_map",
".",
"remove_listener",
"(",
"listener_tag",
")",
"except",
"KeyError",
":",
"pass",
"return",
"reply"
] | Send a stanza without waiting for the stream to be ready to send
stanzas.
This is only useful from within :class:`aioxmpp.node.Client` before
the stream is fully established. | [
"Send",
"a",
"stanza",
"without",
"waiting",
"for",
"the",
"stream",
"to",
"be",
"ready",
"to",
"send",
"stanzas",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L2561-L2673 | -1 |
||||||
695 | horazont/aioxmpp | aioxmpp/entitycaps/caps390.py | _process_features | def _process_features(features):
"""
Generate the `Features String` from an iterable of features.
:param features: The features to generate the features string from.
:type features: :class:`~collections.abc.Iterable` of :class:`str`
:return: The `Features String`
:rtype: :class:`bytes`
Generate the `Features String` from the given `features` as specified in
:xep:`390`.
"""
parts = [
feature.encode("utf-8")+b"\x1f"
for feature in features
]
parts.sort()
return b"".join(parts)+b"\x1c" | python | def _process_features(features):
"""
Generate the `Features String` from an iterable of features.
:param features: The features to generate the features string from.
:type features: :class:`~collections.abc.Iterable` of :class:`str`
:return: The `Features String`
:rtype: :class:`bytes`
Generate the `Features String` from the given `features` as specified in
:xep:`390`.
"""
parts = [
feature.encode("utf-8")+b"\x1f"
for feature in features
]
parts.sort()
return b"".join(parts)+b"\x1c" | [
"def",
"_process_features",
"(",
"features",
")",
":",
"parts",
"=",
"[",
"feature",
".",
"encode",
"(",
"\"utf-8\"",
")",
"+",
"b\"\\x1f\"",
"for",
"feature",
"in",
"features",
"]",
"parts",
".",
"sort",
"(",
")",
"return",
"b\"\"",
".",
"join",
"(",
"parts",
")",
"+",
"b\"\\x1c\""
] | Generate the `Features String` from an iterable of features.
:param features: The features to generate the features string from.
:type features: :class:`~collections.abc.Iterable` of :class:`str`
:return: The `Features String`
:rtype: :class:`bytes`
Generate the `Features String` from the given `features` as specified in
:xep:`390`. | [
"Generate",
"the",
"Features",
"String",
"from",
"an",
"iterable",
"of",
"features",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/entitycaps/caps390.py#L33-L50 | -1 |
||||||
696 | horazont/aioxmpp | aioxmpp/entitycaps/caps390.py | _process_identities | def _process_identities(identities):
"""
Generate the `Identities String` from an iterable of identities.
:param identities: The identities to generate the features string from.
:type identities: :class:`~collections.abc.Iterable` of
:class:`~.disco.xso.Identity`
:return: The `Identities String`
:rtype: :class:`bytes`
Generate the `Identities String` from the given `identities` as specified
in :xep:`390`.
"""
parts = [
_process_identity(identity)
for identity in identities
]
parts.sort()
return b"".join(parts)+b"\x1c" | python | def _process_identities(identities):
"""
Generate the `Identities String` from an iterable of identities.
:param identities: The identities to generate the features string from.
:type identities: :class:`~collections.abc.Iterable` of
:class:`~.disco.xso.Identity`
:return: The `Identities String`
:rtype: :class:`bytes`
Generate the `Identities String` from the given `identities` as specified
in :xep:`390`.
"""
parts = [
_process_identity(identity)
for identity in identities
]
parts.sort()
return b"".join(parts)+b"\x1c" | [
"def",
"_process_identities",
"(",
"identities",
")",
":",
"parts",
"=",
"[",
"_process_identity",
"(",
"identity",
")",
"for",
"identity",
"in",
"identities",
"]",
"parts",
".",
"sort",
"(",
")",
"return",
"b\"\"",
".",
"join",
"(",
"parts",
")",
"+",
"b\"\\x1c\""
] | Generate the `Identities String` from an iterable of identities.
:param identities: The identities to generate the features string from.
:type identities: :class:`~collections.abc.Iterable` of
:class:`~.disco.xso.Identity`
:return: The `Identities String`
:rtype: :class:`bytes`
Generate the `Identities String` from the given `identities` as specified
in :xep:`390`. | [
"Generate",
"the",
"Identities",
"String",
"from",
"an",
"iterable",
"of",
"identities",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/entitycaps/caps390.py#L62-L80 | -1 |
||||||
697 | horazont/aioxmpp | aioxmpp/entitycaps/caps390.py | _process_extensions | def _process_extensions(exts):
"""
Generate the `Extensions String` from an iterable of data forms.
:param exts: The data forms to generate the extensions string from.
:type exts: :class:`~collections.abc.Iterable` of
:class:`~.forms.xso.Data`
:return: The `Extensions String`
:rtype: :class:`bytes`
Generate the `Extensions String` from the given `exts` as specified
in :xep:`390`.
"""
parts = [
_process_form(form)
for form in exts
]
parts.sort()
return b"".join(parts)+b"\x1c" | python | def _process_extensions(exts):
"""
Generate the `Extensions String` from an iterable of data forms.
:param exts: The data forms to generate the extensions string from.
:type exts: :class:`~collections.abc.Iterable` of
:class:`~.forms.xso.Data`
:return: The `Extensions String`
:rtype: :class:`bytes`
Generate the `Extensions String` from the given `exts` as specified
in :xep:`390`.
"""
parts = [
_process_form(form)
for form in exts
]
parts.sort()
return b"".join(parts)+b"\x1c" | [
"def",
"_process_extensions",
"(",
"exts",
")",
":",
"parts",
"=",
"[",
"_process_form",
"(",
"form",
")",
"for",
"form",
"in",
"exts",
"]",
"parts",
".",
"sort",
"(",
")",
"return",
"b\"\"",
".",
"join",
"(",
"parts",
")",
"+",
"b\"\\x1c\""
] | Generate the `Extensions String` from an iterable of data forms.
:param exts: The data forms to generate the extensions string from.
:type exts: :class:`~collections.abc.Iterable` of
:class:`~.forms.xso.Data`
:return: The `Extensions String`
:rtype: :class:`bytes`
Generate the `Extensions String` from the given `exts` as specified
in :xep:`390`. | [
"Generate",
"the",
"Extensions",
"String",
"from",
"an",
"iterable",
"of",
"data",
"forms",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/entitycaps/caps390.py#L103-L121 | -1 |
||||||
698 | horazont/aioxmpp | aioxmpp/statemachine.py | OrderedStateMachine.wait_for | def wait_for(self, new_state):
"""
Wait for an exact state `new_state` to be reached by the state
machine.
If the state is skipped, that is, if a state which is greater than
`new_state` is written to :attr:`state`, the coroutine raises
:class:`OrderedStateSkipped` exception as it is not possible anymore
that it can return successfully (see :attr:`state`).
"""
if self._state == new_state:
return
if self._state > new_state:
raise OrderedStateSkipped(new_state)
fut = asyncio.Future(loop=self.loop)
self._exact_waiters.append((new_state, fut))
yield from fut | python | def wait_for(self, new_state):
"""
Wait for an exact state `new_state` to be reached by the state
machine.
If the state is skipped, that is, if a state which is greater than
`new_state` is written to :attr:`state`, the coroutine raises
:class:`OrderedStateSkipped` exception as it is not possible anymore
that it can return successfully (see :attr:`state`).
"""
if self._state == new_state:
return
if self._state > new_state:
raise OrderedStateSkipped(new_state)
fut = asyncio.Future(loop=self.loop)
self._exact_waiters.append((new_state, fut))
yield from fut | [
"def",
"wait_for",
"(",
"self",
",",
"new_state",
")",
":",
"if",
"self",
".",
"_state",
"==",
"new_state",
":",
"return",
"if",
"self",
".",
"_state",
">",
"new_state",
":",
"raise",
"OrderedStateSkipped",
"(",
"new_state",
")",
"fut",
"=",
"asyncio",
".",
"Future",
"(",
"loop",
"=",
"self",
".",
"loop",
")",
"self",
".",
"_exact_waiters",
".",
"append",
"(",
"(",
"new_state",
",",
"fut",
")",
")",
"yield",
"from",
"fut"
] | Wait for an exact state `new_state` to be reached by the state
machine.
If the state is skipped, that is, if a state which is greater than
`new_state` is written to :attr:`state`, the coroutine raises
:class:`OrderedStateSkipped` exception as it is not possible anymore
that it can return successfully (see :attr:`state`). | [
"Wait",
"for",
"an",
"exact",
"state",
"new_state",
"to",
"be",
"reached",
"by",
"the",
"state",
"machine",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/statemachine.py#L152-L170 | -1 |
||||||
699 | horazont/aioxmpp | aioxmpp/statemachine.py | OrderedStateMachine.wait_for_at_least | def wait_for_at_least(self, new_state):
"""
Wait for a state to be entered which is greater than or equal to
`new_state` and return.
"""
if not (self._state < new_state):
return
fut = asyncio.Future(loop=self.loop)
self._least_waiters.append((new_state, fut))
yield from fut | python | def wait_for_at_least(self, new_state):
"""
Wait for a state to be entered which is greater than or equal to
`new_state` and return.
"""
if not (self._state < new_state):
return
fut = asyncio.Future(loop=self.loop)
self._least_waiters.append((new_state, fut))
yield from fut | [
"def",
"wait_for_at_least",
"(",
"self",
",",
"new_state",
")",
":",
"if",
"not",
"(",
"self",
".",
"_state",
"<",
"new_state",
")",
":",
"return",
"fut",
"=",
"asyncio",
".",
"Future",
"(",
"loop",
"=",
"self",
".",
"loop",
")",
"self",
".",
"_least_waiters",
".",
"append",
"(",
"(",
"new_state",
",",
"fut",
")",
")",
"yield",
"from",
"fut"
] | Wait for a state to be entered which is greater than or equal to
`new_state` and return. | [
"Wait",
"for",
"a",
"state",
"to",
"be",
"entered",
"which",
"is",
"greater",
"than",
"or",
"equal",
"to",
"new_state",
"and",
"return",
"."
] | 22a68e5e1d23f2a4dee470092adbd4672f9ef061 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/statemachine.py#L173-L183 | -1 |