buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
def standardize_weights(y,
'sample-wise weights, make sure your '
'sample_weight array is 1D.')
if sample_weight is not None and class_weight is not None:
warnings.warn('Found both `sample_weight` and `class_weight`: '
'`class_... | def standardize_weights(y,
'sample-wise weights, make sure your '
'sample_weight array is 1D.')
if sample_weight is not None:
if len(sample_weight.shape) > len(y.shape):
raise ValueError('Found a sample_weight with shape' + |
def standardize_weights(y,
' for an input with shape ' +
str(y.shape) + '. '
'sample_weight cannot be broadcast.')
return sample_weight
elif isinstance(class_weight, dict):
if len(y.shape) > 2:
raise V... | def standardize_weights(y,
' for an input with shape ' +
str(y.shape) + '. '
'sample_weight cannot be broadcast.')
class_sample_weight = None
if isinstance(class_weight, dict):
if len(y.shape) > 2:
raise ... |
def standardize_weights(y,
' The classes %s exist in the data but not in '
'`class_weight`.'
% (existing_classes - existing_class_weight))
return weights
else:
if sample_weight_mode is None:
return np.... | def standardize_weights(y,
' The classes %s exist in the data but not in '
'`class_weight`.'
% (existing_classes - existing_class_weight))
if sample_weight is not None and class_sample_weight is not None:
return sample_w... |
def test_dynamic_set_inputs():
assert preds4.shape == (1, 19)
if __name__ == '__main__':
pytest.main([__file__]) | def test_dynamic_set_inputs():
assert preds4.shape == (1, 19)
def test_sample_weights():
y = np.array([0, 1, 0, 0, 2])
sample_weights = np.array([0.5, 1., 1., 0., 2.])
class_weights = {0: 0.5, 1: 1., 2: 1.5}
# Only `sample_weights`.
weights = training_utils.standardize_weights(y, sample_weigh... |
def format(number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep='',
# sign
sign = ''
if isinstance(number, Decimal):
str_number = '{:f}'.format(number)
else:
str_number = six.text_type(number)
if str_number[0] == '-': | def format(number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep='',
# sign
sign = ''
if isinstance(number, Decimal):
# Format values with more than 200 digits (an arbitrary cutoff) using
# scientific notation to avoid high memory usage in {:f}'.format().
_, digits, exponen... |
class TestNumberFormat(TestCase):
self.assertEqual(nformat(Decimal('1234'), '.', grouping=2, thousand_sep=',', force_grouping=True), '12,34')
self.assertEqual(nformat(Decimal('-1234.33'), '.', decimal_pos=1), '-1234.3')
self.assertEqual(nformat(Decimal('0.00000001'), '.', decimal_pos=8), '0.0000... | class TestNumberFormat(TestCase):
self.assertEqual(nformat(Decimal('1234'), '.', grouping=2, thousand_sep=',', force_grouping=True), '12,34')
self.assertEqual(nformat(Decimal('-1234.33'), '.', decimal_pos=1), '-1234.3')
self.assertEqual(nformat(Decimal('0.00000001'), '.', decimal_pos=8), '0.0000... |
class Block(PandasObject):
"""
transpose = self.ndim == 2
# coerce None values, if appropriate
if value is None:
if self.is_numeric: | class Block(PandasObject):
"""
transpose = self.ndim == 2
if isinstance(indexer, np.ndarray) and indexer.ndim > self.ndim:
raise ValueError(f"Cannot set values with ndim > {self.ndim}")
# coerce None values, if appropriate
if value is None:
if self.is_nu... |
the string values returned are correct."""
missing_value = StataMissingValue(um)
loc = missing_loc[umissing_loc == j]
replacement.iloc[loc] = missing_value
else: # All replacements are identical
dtype = series.dtype | the string values returned are correct."""
missing_value = StataMissingValue(um)
loc = missing_loc[umissing_loc == j]
if loc.ndim == 2 and loc.shape[1] == 1:
# GH#31813 avoid trying to set Series values with wrong
... |
class TestFancy:
idxr = idxr(obj)
nd3 = np.random.randint(5, size=(2, 2, 2))
msg = (
r"Buffer has wrong number of dimensions \(expected 1, "
r"got 3\)|"
"'pandas._libs.interval.IntervalTree' object has no attribute "
"'get_loc'|" # AttributeError... | class TestFancy:
idxr = idxr(obj)
nd3 = np.random.randint(5, size=(2, 2, 2))
if idxr_id == "iloc":
err = ValueError
msg = f"Cannot set values with ndim > {obj.ndim}"
elif (
isinstance(index, pd.IntervalIndex)
and idxr_id == "setitem"
... |
from pipenv.patched import crayons
from pipenv.utils import (
cmd_list_to_shell, convert_deps_to_pip, create_spinner, download_file,
find_python, get_canonical_names, get_source_list, is_pinned,
is_python_command, is_required_version, is_star, is_valid_url,
parse_indexes, pep423_name, prepare_pip_source... | from pipenv.patched import crayons
from pipenv.utils import (
cmd_list_to_shell, convert_deps_to_pip, create_spinner, download_file,
find_python, get_canonical_names, get_host_and_port, get_source_list, is_pinned,
is_python_command, is_required_version, is_star, is_valid_url,
parse_indexes, pep423_name,... |
def import_requirements(project, r=None, dev=False):
if extra_index:
indexes.append(extra_index)
if trusted_host:
trusted_hosts.append(trusted_host)
indexes = sorted(set(indexes))
trusted_hosts = sorted(set(trusted_hosts))
reqs = [install_req_from_parsed_requirement(f... | def import_requirements(project, r=None, dev=False):
if extra_index:
indexes.append(extra_index)
if trusted_host:
trusted_hosts.append(get_host_and_port(trusted_host))
indexes = sorted(set(indexes))
trusted_hosts = sorted(set(trusted_hosts))
reqs = [install_req_from_p... |
def import_requirements(project, r=None, dev=False):
else:
project.add_package_to_pipfile(str(package.req), dev=dev)
for index in indexes:
trusted = index in trusted_hosts
project.add_index_to_pipfile(index, verify_ssl=trusted)
project.recase_pipfile()
| def import_requirements(project, r=None, dev=False):
else:
project.add_package_to_pipfile(str(package.req), dev=dev)
for index in indexes:
# don't require HTTPS for trusted hosts (see: https://pip.pypa.io/en/stable/cli/pip/#cmdoption-trusted-host)
host_and_port = get_host... |
def get_url_name(url):
return urllib3_util.parse_url(url).host
def get_canonical_names(packages):
"""Canonicalize a list of packages and return a set of canonical names"""
from .vendor.packaging.utils import canonicalize_name | def get_url_name(url):
return urllib3_util.parse_url(url).host
def get_host_and_port(url):
"""Get the host, or the host:port pair if port is explicitly included, for the given URL.
Examples:
>>> get_host_and_port('example.com')
'example.com'
>>> get_host_and_port('example.com:443')
'examp... |
def test_convert_deps_to_pip_unicode():
("--extra-index-url=https://example.com/simple/", (None, "https://example.com/simple/", None, [])),
("--trusted-host=example.com", (None, None, "example.com", [])),
("# -i https://example.com/simple/", (None, None, None, [])),
("requests", (None, None, None, ["req... | def test_convert_deps_to_pip_unicode():
("--extra-index-url=https://example.com/simple/", (None, "https://example.com/simple/", None, [])),
("--trusted-host=example.com", (None, None, "example.com", [])),
("# -i https://example.com/simple/", (None, None, None, [])),
("requests # -i https://example.com/s... |
class BaseGrouper:
pass
else:
raise
return self._aggregate_series_pure_python(obj, func)
def _aggregate_series_fast(self, obj, func):
func = self._is_builtin_func(func) | class BaseGrouper:
pass
else:
raise
except TypeError as err:
if "ndarray" in str(err):
# raised in libreduction if obj's values is no ndarray
pass
else:
raise
return self._aggregate_series... |
def test_array_ufunc_series_defer():
tm.assert_series_equal(r1, expected)
tm.assert_series_equal(r2, expected) | def test_array_ufunc_series_defer():
tm.assert_series_equal(r1, expected)
tm.assert_series_equal(r2, expected)
def test_groupby_agg():
# Ensure that the result of agg is inferred to be decimal dtype
# https://github.com/pandas-dev/pandas/issues/29141
data = make_data()[:5]
df = pd.DataFrame(... |
ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
<p begin="3" dur="-1">Ignored, three</p>
</div>
</body>
</tt>'''
srt_data = '''1
00:00:00,000 --> 00:00:01,000
The following line contains Chinese characters and special symbols | ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
<p begin="3" dur="-1">Ignored, three</p>
</div>
</body>
</tt>'''.encode('utf-8')
srt_data = '''1
00:00:00,000 --> 00:00:01,000
The following line contains Chinese characters and ... |
Line
<p begin="0" end="1">The first line</p>
</div>
</body>
</tt>'''
srt_data = '''1
00:00:00,000 --> 00:00:01,000
The first line | Line
<p begin="0" end="1">The first line</p>
</div>
</body>
</tt>'''.encode('utf-8')
srt_data = '''1
00:00:00,000 --> 00:00:01,000
The first line |
The first line
<p style="s1" tts:textDecoration="underline" begin="00:00:09.56" id="p2" end="00:00:12.36"><span style="s2" tts:color="lime">inner<br /> </span>style</p>
</div>
</body>
</tt>'''
srt_data = '''1
00:00:02,080 --> 00:00:05,839
<font color="white" face="sansSerif" size="16">default style<... | The first line
<p style="s1" tts:textDecoration="underline" begin="00:00:09.56" id="p2" end="00:00:12.36"><span style="s2" tts:color="lime">inner<br /> </span>style</p>
</div>
</body>
</tt>'''.encode('utf-8')
srt_data = '''1
00:00:02,080 --> 00:00:05,839
<font color="white" face="sansSerif" size="16... |
part 3</font></u>
'''
self.assertEqual(dfxp2srt(dfxp_data_with_style), srt_data)
def test_cli_option(self):
self.assertEqual(cli_option({'proxy': '127.0.0.1:3128'}, '--proxy', 'proxy'), ['--proxy', '127.0.0.1:3128'])
self.assertEqual(cli_option({'proxy': None}, '--proxy', 'proxy'), []) | part 3</font></u>
'''
self.assertEqual(dfxp2srt(dfxp_data_with_style), srt_data)
dfxp_data_non_utf8 = '''<?xml version="1.0" encoding="UTF-16"?>
<tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
<body>
<div xml:l... |
class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor):
dfxp_file = old_file
srt_file = subtitles_filename(filename, lang, 'srt')
with io.open(dfxp_file, 'rt', encoding='utf-8') as f:
srt_data = dfxp2srt(f.read())
with io.open(srt_file... | class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor):
dfxp_file = old_file
srt_file = subtitles_filename(filename, lang, 'srt')
with open(dfxp_file, 'rb') as f:
srt_data = dfxp2srt(f.read())
with io.open(srt_file, 'wt', encoding='utf... |
def srt_subtitles_timecode(seconds):
def dfxp2srt(dfxp_data):
LEGACY_NAMESPACES = (
('http://www.w3.org/ns/ttml', [
'http://www.w3.org/2004/11/ttaf1',
'http://www.w3.org/2006/04/ttaf1',
'http://www.w3.org/2006/10/ttaf1',
]),
('http://www.w3.org/ns/ttml#s... | def srt_subtitles_timecode(seconds):
def dfxp2srt(dfxp_data):
'''
@param dfxp_data A bytes-like object containing DFXP data
@returns A unicode object containing converted SRT data
'''
LEGACY_NAMESPACES = (
(b'http://www.w3.org/ns/ttml', [
b'http://www.w3.org/2004/11/ttaf1',
... |
def dfxp2srt(dfxp_data):
for ns in v:
dfxp_data = dfxp_data.replace(ns, k)
dfxp = compat_etree_fromstring(dfxp_data.encode('utf-8'))
out = []
paras = dfxp.findall(_x('.//ttml:p')) or dfxp.findall('.//p')
| def dfxp2srt(dfxp_data):
for ns in v:
dfxp_data = dfxp_data.replace(ns, k)
dfxp = compat_etree_fromstring(dfxp_data)
out = []
paras = dfxp.findall(_x('.//ttml:p')) or dfxp.findall('.//p')
|
class Task(object):
params_str = {}
params = dict(self.get_params())
for param_name, param_value in six.iteritems(self.param_kwargs):
if params[param_name].significant:
params_str[param_name] = params[param_name].serialize(param_value)
return params_str
| class Task(object):
params_str = {}
params = dict(self.get_params())
for param_name, param_value in six.iteritems(self.param_kwargs):
params_str[param_name] = params[param_name].serialize(param_value)
return params_str
|
class DummyTask(luigi.Task):
datehour_param = luigi.DateHourParameter()
timedelta_param = luigi.TimeDeltaParameter()
list_param = luigi.Parameter(is_list=True)
class TaskTest(unittest.TestCase): | class DummyTask(luigi.Task):
datehour_param = luigi.DateHourParameter()
timedelta_param = luigi.TimeDeltaParameter()
list_param = luigi.Parameter(is_list=True)
insignificant_param = luigi.Parameter(significant=False)
class TaskTest(unittest.TestCase): |
class TaskTest(unittest.TestCase):
date_param=datetime(2014, 9, 13).date(),
datehour_param=datetime(2014, 9, 13, 9),
timedelta_param=timedelta(44), # doesn't support seconds
list_param=['in', 'flames'])
original = DummyTask(**params)
other = DummyTask.fr... | class TaskTest(unittest.TestCase):
date_param=datetime(2014, 9, 13).date(),
datehour_param=datetime(2014, 9, 13, 9),
timedelta_param=timedelta(44), # doesn't support seconds
list_param=['in', 'flames'],
insignificant_param='test')
original = DummyTas... |
class SparkSubmitTask(luigi.Task):
command = []
if value and isinstance(value, dict):
for prop, value in value.items():
command += [name, '"{0}={1}"'.format(prop, value)]
return command
def _flag_arg(self, name, value): | class SparkSubmitTask(luigi.Task):
command = []
if value and isinstance(value, dict):
for prop, value in value.items():
command += [name, '{0}={1}'.format(prop, value)]
return command
def _flag_arg(self, name, value): |
class SparkSubmitTaskTest(unittest.TestCase):
self.assertEqual(proc.call_args[0][0],
['ss-stub', '--master', 'yarn-client', '--deploy-mode', 'client', '--name', 'AppName',
'--class', 'org.test.MyClass', '--jars', 'jars/my.jar', '--py-files', 'file1.py,file2.py'... | class SparkSubmitTaskTest(unittest.TestCase):
self.assertEqual(proc.call_args[0][0],
['ss-stub', '--master', 'yarn-client', '--deploy-mode', 'client', '--name', 'AppName',
'--class', 'org.test.MyClass', '--jars', 'jars/my.jar', '--py-files', 'file1.py,file2.py'... |
class SparkSubmitTaskTest(unittest.TestCase):
self.assertEqual(proc.call_args[0][0],
['ss-stub', '--master', 'spark://host:7077', '--jars', 'jar1.jar,jar2.jar',
'--py-files', 'file1.py,file2.py', '--files', 'file1,file2', '--archives', 'archive1',
... | class SparkSubmitTaskTest(unittest.TestCase):
self.assertEqual(proc.call_args[0][0],
['ss-stub', '--master', 'spark://host:7077', '--jars', 'jar1.jar,jar2.jar',
'--py-files', 'file1.py,file2.py', '--files', 'file1,file2', '--archives', 'archive1',
... |
notes:
rules. This should work out in most cases, but it is theoretically
possible to see spurious changes when target and actual values are
semantically identical but lexically distinct.
version_added: '2.3'
author:
- Jiri Tyr (@jtyr) | notes:
rules. This should work out in most cases, but it is theoretically
possible to see spurious changes when target and actual values are
semantically identical but lexically distinct.
- "The I(params) parameter is deprecated in Ansible-2.7 due to circumventing Ansible's parameter
handling. The I(... |
options:
a list of strings (see examples).
type: raw
required: true
params:
description:
- Additional module parameters.
type: dict
extends_documentation_fragment:
- ldap.documentation
''' | options:
a list of strings (see examples).
type: raw
required: true
extends_documentation_fragment:
- ldap.documentation
''' |
EXAMPLES = r'''
# server_uri: ldap://localhost/
# bind_dn: cn=admin,dc=example,dc=com
# bind_pw: password
- name: Get rid of an unneeded attribute
ldap_attr:
dn: uid=jdoe,ou=people,dc=example,dc=com
name: shadowExpire
values: []
state: exact
params: "{{ ldap_auth }}"
'''
RETURN = r''' | EXAMPLES = r'''
# server_uri: ldap://localhost/
# bind_dn: cn=admin,dc=example,dc=com
# bind_pw: password
#
# In the example below, 'args' is a task keyword, passed at the same level as the module
- name: Get rid of an unneeded attribute
ldap_attr:
dn: uid=jdoe,ou=people,dc=example,dc=com
name: shadowEx... |
modlist:
'''
import traceback
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils._text import to_native, to_bytes | modlist:
'''
import traceback
from distutils.version import LooseVersion
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils._text import to_native, to_bytes |
def main():
module.fail_json(msg=missing_required_lib('python-ldap'),
exception=LDAP_IMP_ERR)
# Update module parameters with user's parameters if defined
if 'params' in module.params and isinstance(module.params['params'], dict):
module.params.update(module.params['par... | def main():
module.fail_json(msg=missing_required_lib('python-ldap'),
exception=LDAP_IMP_ERR)
# For Ansible-2.9.x and below, allow the params module parameter with a warning
if LooseVersion(module.ansible_version) < LooseVersion('2.10'):
if module.params['params']:
... |
notes:
rule allowing root to modify the server configuration. If you need to use
a simple bind to access your server, pass the credentials in I(bind_dn)
and I(bind_pw).
version_added: '2.3'
author:
- Jiri Tyr (@jtyr) | notes:
rule allowing root to modify the server configuration. If you need to use
a simple bind to access your server, pass the credentials in I(bind_dn)
and I(bind_pw).
- "The I(params) parameter is deprecated in Ansible-2.7 due to circumventing Ansible's parameter
handling. The I(params) parameter s... |
options:
- If I(state=present), value or list of values to use when creating
the entry. It can either be a string or an actual list of
strings.
params:
description:
- List of options which allows to overwrite any of the task or the
I(attributes) options. To remove an option, se... | options:
- If I(state=present), value or list of values to use when creating
the entry. It can either be a string or an actual list of
strings.
state:
description:
- The target state of the entry. |
EXAMPLES = """
# server_uri: ldap://localhost/
# bind_dn: cn=admin,dc=example,dc=com
# bind_pw: password
- name: Get rid of an old entry
ldap_entry:
dn: ou=stuff,dc=example,dc=com
state: absent
params: "{{ ldap_auth }}"
"""
| EXAMPLES = """
# server_uri: ldap://localhost/
# bind_dn: cn=admin,dc=example,dc=com
# bind_pw: password
#
# In the example below, 'args' is a task keyword, passed at the same level as the module
- name: Get rid of an old entry
ldap_entry:
dn: ou=stuff,dc=example,dc=com
state: absent
args: "{{ ldap_au... |
RETURN = """
"""
import traceback
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.six import string_types | RETURN = """
"""
import traceback
from distutils.version import LooseVersion
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.six import string_types |
def main():
module.fail_json(msg=missing_required_lib('python-ldap'),
exception=LDAP_IMP_ERR)
state = module.params['state']
# Check if objectClass is present when needed | def main():
module.fail_json(msg=missing_required_lib('python-ldap'),
exception=LDAP_IMP_ERR)
# For Ansible-2.9.x and below, allow the params module parameter with a warning
if LooseVersion(module.ansible_version) < LooseVersion('2.10'):
if module.params['params']:
... |
def main():
isinstance(module.params['objectClass'], list))):
module.fail_json(msg="objectClass must be either a string or a list.")
# Update module parameters with user's parameters if defined
if 'params' in module.params and isinstance(module.params['params'], dict):
for key, ... | def main():
isinstance(module.params['objectClass'], list))):
module.fail_json(msg="objectClass must be either a string or a list.")
# Instantiate the LdapEntry object
ldap = LdapEntry(module)
|
def rnn(step_function, inputs, initial_states,
for o, p in zip(new_states, place_holders):
n_s.append(o.replace_placeholders({p: o.output}))
if len(n_s) > 0:
new_output = n_s[0]
return new_output, n_s
final_output, final_states = _recurrence(r... | def rnn(step_function, inputs, initial_states,
for o, p in zip(new_states, place_holders):
n_s.append(o.replace_placeholders({p: o.output}))
if len(n_s) > 0:
new_output = n_s[-1]
return new_output, n_s
final_output, final_states = _recurrence(... |
class StackedRNNCells(Layer):
'`state_size` attribute. '
'received cells:', cells)
self.cells = cells
super(StackedRNNCells, self).__init__(**kwargs)
@property
def state_size(self):
# States are a flat list
# in r... | class StackedRNNCells(Layer):
'`state_size` attribute. '
'received cells:', cells)
self.cells = cells
# reverse_state_order determines whether the state size will be in a
# reverse order of the cells' state. User might want to set... |
class StackedRNNCells(Layer):
# Format the new states as a flat list
# in reverse cell order.
states = []
for cell_states in new_nested_states[::-1]:
states += cell_states
return inputs, states
def build(self, input_shape):
if isinstance(input_shape, lis... | class StackedRNNCells(Layer):
# Format the new states as a flat list
# in reverse cell order.
new_states = []
if self.reverse_state_order:
new_nested_states = new_nested_states[::-1]
for cell_states in new_nested_states:
new_states += cell_states
... |
class StackedRNNCells(Layer):
cell.build([input_shape] + constants_shape)
else:
cell.build(input_shape)
if hasattr(cell.state_size, '__len__'):
output_dim = cell.state_size[0]
else:
output_dim = cell.state_si... | class StackedRNNCells(Layer):
cell.build([input_shape] + constants_shape)
else:
cell.build(input_shape)
if getattr(cell, 'output_size', None) is not None:
output_dim = cell.output_size
elif hasattr(cell.state_size, '__len__'... |
class RNN(Layer):
the size of the recurrent state
(which should be the same as the size of the cell output).
This can also be a list/tuple of integers
(one size per state). In this case, the first entry
(`state_size[0]`) should be the same ... | class RNN(Layer):
the size of the recurrent state
(which should be the same as the size of the cell output).
This can also be a list/tuple of integers
(one size per state).
- a `output_size` attribute. This can be a single integer or a
... |
class RNN(Layer):
state_size = self.cell.state_size
else:
state_size = [self.cell.state_size]
output_dim = state_size[0]
if self.return_sequences:
output_shape = (input_shape[0], input_shape[1], output_dim) | class RNN(Layer):
state_size = self.cell.state_size
else:
state_size = [self.cell.state_size]
if getattr(self.cell, 'output_size', None) is not None:
output_dim = self.cell.output_size
else:
output_dim = state_size[0]
if self.return_seque... |
class SimpleRNNCell(Layer):
self.dropout = min(1., max(0., dropout))
self.recurrent_dropout = min(1., max(0., recurrent_dropout))
self.state_size = self.units
self._dropout_mask = None
self._recurrent_dropout_mask = None
| class SimpleRNNCell(Layer):
self.dropout = min(1., max(0., dropout))
self.recurrent_dropout = min(1., max(0., recurrent_dropout))
self.state_size = self.units
self.output_size = self.units
self._dropout_mask = None
self._recurrent_dropout_mask = None
|
class GRUCell(Layer):
self.implementation = implementation
self.reset_after = reset_after
self.state_size = self.units
self._dropout_mask = None
self._recurrent_dropout_mask = None
| class GRUCell(Layer):
self.implementation = implementation
self.reset_after = reset_after
self.state_size = self.units
self.output_size = self.units
self._dropout_mask = None
self._recurrent_dropout_mask = None
|
class LSTMCell(Layer):
self.recurrent_dropout = min(1., max(0., recurrent_dropout))
self.implementation = implementation
self.state_size = (self.units, self.units)
self._dropout_mask = None
self._recurrent_dropout_mask = None
| class LSTMCell(Layer):
self.recurrent_dropout = min(1., max(0., recurrent_dropout))
self.implementation = implementation
self.state_size = (self.units, self.units)
self.output_size = self.units
self._dropout_mask = None
self._recurrent_dropout_mask = None
|
def test_minimal_rnn_cell_non_layer_multiple_states():
MinimalRNNCell(16, 8),
MinimalRNNCell(32, 16)]
layer = recurrent.RNN(cells)
assert layer.cell.state_size == (32, 32, 16, 16, 8, 8)
y = layer(x)
model = keras.models.Model(x, y)
model.compile(optimizer='rmsprop', loss='m... | def test_minimal_rnn_cell_non_layer_multiple_states():
MinimalRNNCell(16, 8),
MinimalRNNCell(32, 16)]
layer = recurrent.RNN(cells)
assert layer.cell.state_size == (8, 8, 16, 16, 32, 32)
y = layer(x)
model = keras.models.Model(x, y)
model.compile(optimizer='rmsprop', loss='m... |
def test_stacked_rnn_compute_output_shape():
recurrent.LSTMCell(6)]
layer = recurrent.RNN(cells, return_state=True, return_sequences=True)
output_shape = layer.compute_output_shape((None, timesteps, embedding_dim))
expected_output_shape = [(None, timesteps, 6),
(Non... | def test_stacked_rnn_compute_output_shape():
recurrent.LSTMCell(6)]
layer = recurrent.RNN(cells, return_state=True, return_sequences=True)
output_shape = layer.compute_output_shape((None, timesteps, embedding_dim))
expected_output_shape = [(None, timesteps, 6),
(Non... |
def test_rnn_cell_identity_initializer(layer_class):
np.concatenate([np.identity(units)] * num_kernels, axis=1))
if __name__ == '__main__':
pytest.main([__file__]) | def test_rnn_cell_identity_initializer(layer_class):
np.concatenate([np.identity(units)] * num_kernels, axis=1))
@keras_test
@pytest.mark.skipif(K.backend() == 'cntk', reason='Not supported.')
def test_inconsistent_output_state_size():
class PlusOneRNNCell(keras.layers.Layer):
"... |
class Field(dict):
class ItemMeta(ABCMeta):
def __new__(mcs, class_name, bases, attrs):
new_bases = tuple(base._class for base in bases if hasattr(base, '_class'))
_class = super(ItemMeta, mcs).__new__(mcs, 'x_' + class_name, new_bases, attrs)
| class Field(dict):
class ItemMeta(ABCMeta):
def __new__(mcs, class_name, bases, attrs):
classcell = attrs.pop('__classcell__', None)
new_bases = tuple(base._class for base in bases if hasattr(base, '_class'))
_class = super(ItemMeta, mcs).__new__(mcs, 'x_' + class_name, new_bases, attrs)
|
class ItemMeta(ABCMeta):
new_attrs['fields'] = fields
new_attrs['_class'] = _class
return super(ItemMeta, mcs).__new__(mcs, class_name, bases, new_attrs)
| class ItemMeta(ABCMeta):
new_attrs['fields'] = fields
new_attrs['_class'] = _class
if classcell is not None:
new_attrs['__classcell__'] = classcell
return super(ItemMeta, mcs).__new__(mcs, class_name, bases, new_attrs)
|
import unittest
from scrapy.item import Item, Field
import six
class ItemTest(unittest.TestCase):
| import sys
import unittest
import six
from scrapy.item import ABCMeta, Item, ItemMeta, Field
from tests import mock
PY36_PLUS = (sys.version_info.major >= 3) and (sys.version_info.minor >= 6)
class ItemTest(unittest.TestCase):
|
class ItemTest(unittest.TestCase):
self.assertNotEqual(item['name'], copied_item['name'])
if __name__ == "__main__":
unittest.main() | class ItemTest(unittest.TestCase):
self.assertNotEqual(item['name'], copied_item['name'])
class ItemMetaTest(unittest.TestCase):
def test_new_method_propagates_classcell(self):
new_mock = mock.Mock(side_effect=ABCMeta.__new__)
base = ItemMeta.__bases__[0]
with mock.patch.object(b... |
EXAMPLES = r'''
secured: '{{ item.secured }}'
state: present
with_items:
- { name: AWS_ACCESS_KEY, value: ABCD1234 }
- { name: AWS_SECRET, value: qwe789poi123vbn0, secured: True }
- name: Remove pipeline variable | EXAMPLES = r'''
secured: '{{ item.secured }}'
state: present
with_items:
- { name: AWS_ACCESS_KEY, value: ABCD1234, secured: False }
- { name: AWS_SECRET, value: qwe789poi123vbn0, secured: True }
- name: Remove pipeline variable |
EXAMPLES = r'''
RETURN = r''' # '''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.source_control.bitbucket import BitbucketHelper
error_messages = { | EXAMPLES = r'''
RETURN = r''' # '''
from ansible.module_utils.basic import AnsibleModule, _load_params
from ansible.module_utils.source_control.bitbucket import BitbucketHelper
error_messages = { |
def delete_pipeline_variable(module, bitbucket, variable_uuid):
))
def main():
argument_spec = BitbucketHelper.bitbucket_argument_spec()
argument_spec.update( | def delete_pipeline_variable(module, bitbucket, variable_uuid):
))
class BitBucketPipelineVariable(AnsibleModule):
def __init__(self, *args, **kwargs):
params = _load_params() or {}
if params.get('secured'):
kwargs['argument_spec']['value'].update({'no_log': True})
supe... |
def main():
secured=dict(type='bool', default=False),
state=dict(type='str', choices=['present', 'absent'], required=True),
)
module = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=True,
) | def main():
secured=dict(type='bool', default=False),
state=dict(type='str', choices=['present', 'absent'], required=True),
)
module = BitBucketPipelineVariable(
argument_spec=argument_spec,
supports_check_mode=True,
) |
class Errors(object):
E168 = ("Unknown field: {field}")
E169 = ("Can't find module: {module}")
E170 = ("Cannot apply transition {name}: invalid for the current state.")
@add_codes | class Errors(object):
E168 = ("Unknown field: {field}")
E169 = ("Can't find module: {module}")
E170 = ("Cannot apply transition {name}: invalid for the current state.")
E171 = ("Matcher.add received invalid on_match callback argument: expected "
"callable or None, but got: {arg_type}")
@ad... |
def test_matcher_schema_token_attributes(en_vocab, pattern, text):
assert len(matcher) == 1
matches = matcher(doc)
assert len(matches) == 1 | def test_matcher_schema_token_attributes(en_vocab, pattern, text):
assert len(matcher) == 1
matches = matcher(doc)
assert len(matches) == 1
def test_matcher_valid_callback(en_vocab):
"""Test that on_match can only be None or callable."""
matcher = Matcher(en_vocab)
with pytest.raises(ValueErro... |
def _make_ghost_gridspec_slots(fig, gs):
# this gridspec slot doesn't have an axis so we
# make a "ghost".
ax = fig.add_subplot(gs[nn])
ax.set_frame_on(False)
ax.set_xticks([])
ax.set_yticks([])
ax.set_facecolor((1, 0, 0, 0))
def _mak... | def _make_ghost_gridspec_slots(fig, gs):
# this gridspec slot doesn't have an axis so we
# make a "ghost".
ax = fig.add_subplot(gs[nn])
ax.set_visible(False)
def _make_layout_margins(ax, renderer, h_pad, w_pad): |
class FigureCanvasBase:
def inaxes(self, xy):
"""
Check if a point is in an axes.
Parameters
---------- | class FigureCanvasBase:
def inaxes(self, xy):
"""
Return the topmost visible `~.axes.Axes` containing the point *xy*.
Parameters
---------- |
class FigureCanvasBase:
Returns
-------
axes: topmost axes containing the point, or None if no axes.
"""
axes_list = [a for a in self.figure.get_axes()
if a.patch.contains_point(xy)]
if axes_list:
axes = cbook._topmost_artist(axes_list)... | class FigureCanvasBase:
Returns
-------
axes : `~matplotlib.axes.Axes` or None
The topmost visible axes containing the point, or None if no axes.
"""
axes_list = [a for a in self.figure.get_axes()
if a.patch.contains_point(xy) and a.get_visible()... |
def test_aspect_nonlinear_adjustable_datalim():
ax.apply_aspect()
assert ax.get_xlim() == pytest.approx([1*10**(1/2), 100/10**(1/2)])
assert ax.get_ylim() == (1 / 101, 1 / 11) | def test_aspect_nonlinear_adjustable_datalim():
ax.apply_aspect()
assert ax.get_xlim() == pytest.approx([1*10**(1/2), 100/10**(1/2)])
assert ax.get_ylim() == (1 / 101, 1 / 11)
def test_invisible_axes():
# invisible axes should not respond to events...
fig, ax = plt.subplots()
assert fig.canvas... |
import logging
from synapse.api.errors import Codes, SynapseError
from synapse.types import GroupID, RoomID, UserID, get_domain_from_id
from synapse.util.async_helpers import concurrently_execute
| import logging
from synapse.api.errors import Codes, SynapseError
from synapse.handlers.profile import MAX_AVATAR_URL_LEN, MAX_DISPLAYNAME_LEN
from synapse.types import GroupID, RoomID, UserID, get_domain_from_id
from synapse.util.async_helpers import concurrently_execute
|
# TODO: Flairs
class GroupsServerWorkerHandler:
def __init__(self, hs):
self.hs = hs | # TODO: Flairs
# Note that the maximum lengths are somewhat arbitrary.
MAX_SHORT_DESC_LEN = 1000
MAX_LONG_DESC_LEN = 10000
class GroupsServerWorkerHandler:
def __init__(self, hs):
self.hs = hs |
async def update_group_profile(self, group_id, requester_user_id, content):
)
profile = {}
for keyname in ("name", "avatar_url", "short_description", "long_description"):
if keyname in content:
value = content[keyname]
if not isinstance(value, str):
... | async def update_group_profile(self, group_id, requester_user_id, content):
)
profile = {}
for keyname, max_length in (
("name", MAX_DISPLAYNAME_LEN),
("avatar_url", MAX_AVATAR_URL_LEN),
("short_description", MAX_SHORT_DESC_LEN),
("long_descriptio... |
import logging
from functools import wraps
from synapse.api.errors import SynapseError
from synapse.http.servlet import RestServlet, parse_json_object_from_request
from synapse.types import GroupID
from ._base import client_patterns
logger = logging.getLogger(__name__)
|
import logging
from functools import wraps
from typing import TYPE_CHECKING, Tuple
from twisted.web.http import Request
from synapse.api.errors import SynapseError
from synapse.handlers.groups_local import GroupsLocalHandler
from synapse.http.servlet import (
RestServlet,
assert_params_in_dict,
parse_jso... |
def _validate_group_id(f):
"""
@wraps(f)
def wrapper(self, request, group_id, *args, **kwargs):
if not GroupID.is_valid(group_id):
raise SynapseError(400, "%s is not a legal group ID" % (group_id,))
| def _validate_group_id(f):
"""
@wraps(f)
def wrapper(self, request: Request, group_id: str, *args, **kwargs):
if not GroupID.is_valid(group_id):
raise SynapseError(400, "%s is not a legal group ID" % (group_id,))
|
class GroupServlet(RestServlet):
PATTERNS = client_patterns("/groups/(?P<group_id>[^/]*)/profile$")
def __init__(self, hs):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
@_validate_group_id
... | class GroupServlet(RestServlet):
PATTERNS = client_patterns("/groups/(?P<group_id>[^/]*)/profile$")
def __init__(self, hs: "HomeServer"):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
@_validate... |
async def on_GET(self, request, group_id):
return 200, group_description
@_validate_group_id
async def on_POST(self, request, group_id):
requester = await self.auth.get_user_by_req(request)
requester_user_id = requester.user.to_string()
content = parse_json_object_from_request(... | async def on_GET(self, request, group_id):
return 200, group_description
@_validate_group_id
async def on_POST(self, request: Request, group_id: str) -> Tuple[int, JsonDict]:
requester = await self.auth.get_user_by_req(request)
requester_user_id = requester.user.to_string()
con... |
class GroupSummaryServlet(RestServlet):
PATTERNS = client_patterns("/groups/(?P<group_id>[^/]*)/summary$")
def __init__(self, hs):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
@_validate_group_... | class GroupSummaryServlet(RestServlet):
PATTERNS = client_patterns("/groups/(?P<group_id>[^/]*)/summary$")
def __init__(self, hs: "HomeServer"):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
@_v... |
class GroupSummaryRoomsCatServlet(RestServlet):
"/rooms/(?P<room_id>[^/]*)$"
)
def __init__(self, hs):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
@_validate_group_id
async def on_P... | class GroupSummaryRoomsCatServlet(RestServlet):
"/rooms/(?P<room_id>[^/]*)$"
)
def __init__(self, hs: "HomeServer"):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
@_validate_group_id
... |
async def on_PUT(self, request, group_id, category_id, room_id):
return 200, resp
@_validate_group_id
async def on_DELETE(self, request, group_id, category_id, room_id):
requester = await self.auth.get_user_by_req(request)
requester_user_id = requester.user.to_string()
resp = a... | async def on_PUT(self, request, group_id, category_id, room_id):
return 200, resp
@_validate_group_id
async def on_DELETE(
self, request: Request, group_id: str, category_id: str, room_id: str
):
requester = await self.auth.get_user_by_req(request)
requester_user_id = reques... |
class GroupCategoryServlet(RestServlet):
"/groups/(?P<group_id>[^/]*)/categories/(?P<category_id>[^/]+)$"
)
def __init__(self, hs):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
@_validat... | class GroupCategoryServlet(RestServlet):
"/groups/(?P<group_id>[^/]*)/categories/(?P<category_id>[^/]+)$"
)
def __init__(self, hs: "HomeServer"):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
... |
async def on_GET(self, request, group_id, category_id):
return 200, category
@_validate_group_id
async def on_PUT(self, request, group_id, category_id):
requester = await self.auth.get_user_by_req(request)
requester_user_id = requester.user.to_string()
content = parse_json_obje... | async def on_GET(self, request, group_id, category_id):
return 200, category
@_validate_group_id
async def on_PUT(
self, request: Request, group_id: str, category_id: str
) -> Tuple[int, JsonDict]:
requester = await self.auth.get_user_by_req(request)
requester_user_id = requ... |
async def on_PUT(self, request, group_id, category_id):
return 200, resp
@_validate_group_id
async def on_DELETE(self, request, group_id, category_id):
requester = await self.auth.get_user_by_req(request)
requester_user_id = requester.user.to_string()
resp = await self.groups_h... | async def on_PUT(self, request, group_id, category_id):
return 200, resp
@_validate_group_id
async def on_DELETE(
self, request: Request, group_id: str, category_id: str
) -> Tuple[int, JsonDict]:
requester = await self.auth.get_user_by_req(request)
requester_user_id = reque... |
class GroupCategoriesServlet(RestServlet):
PATTERNS = client_patterns("/groups/(?P<group_id>[^/]*)/categories/$")
def __init__(self, hs):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
@_validate... | class GroupCategoriesServlet(RestServlet):
PATTERNS = client_patterns("/groups/(?P<group_id>[^/]*)/categories/$")
def __init__(self, hs: "HomeServer"):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
... |
class GroupRoleServlet(RestServlet):
PATTERNS = client_patterns("/groups/(?P<group_id>[^/]*)/roles/(?P<role_id>[^/]+)$")
def __init__(self, hs):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
@_v... | class GroupRoleServlet(RestServlet):
PATTERNS = client_patterns("/groups/(?P<group_id>[^/]*)/roles/(?P<role_id>[^/]+)$")
def __init__(self, hs: "HomeServer"):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_hand... |
async def on_GET(self, request, group_id, role_id):
return 200, category
@_validate_group_id
async def on_PUT(self, request, group_id, role_id):
requester = await self.auth.get_user_by_req(request)
requester_user_id = requester.user.to_string()
content = parse_json_object_from_... | async def on_GET(self, request, group_id, role_id):
return 200, category
@_validate_group_id
async def on_PUT(
self, request: Request, group_id: str, role_id: str
) -> Tuple[int, JsonDict]:
requester = await self.auth.get_user_by_req(request)
requester_user_id = requester.us... |
async def on_PUT(self, request, group_id, role_id):
return 200, resp
@_validate_group_id
async def on_DELETE(self, request, group_id, role_id):
requester = await self.auth.get_user_by_req(request)
requester_user_id = requester.user.to_string()
resp = await self.groups_handler.d... | async def on_PUT(self, request, group_id, role_id):
return 200, resp
@_validate_group_id
async def on_DELETE(
self, request: Request, group_id: str, role_id: str
) -> Tuple[int, JsonDict]:
requester = await self.auth.get_user_by_req(request)
requester_user_id = requester.use... |
class GroupRolesServlet(RestServlet):
PATTERNS = client_patterns("/groups/(?P<group_id>[^/]*)/roles/$")
def __init__(self, hs):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
@_validate_group_id
... | class GroupRolesServlet(RestServlet):
PATTERNS = client_patterns("/groups/(?P<group_id>[^/]*)/roles/$")
def __init__(self, hs: "HomeServer"):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
@_vali... |
class GroupSummaryUsersRoleServlet(RestServlet):
"/users/(?P<user_id>[^/]*)$"
)
def __init__(self, hs):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
@_validate_group_id
async def on_... | class GroupSummaryUsersRoleServlet(RestServlet):
"/users/(?P<user_id>[^/]*)$"
)
def __init__(self, hs: "HomeServer"):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
@_validate_group_id
... |
async def on_PUT(self, request, group_id, role_id, user_id):
return 200, resp
@_validate_group_id
async def on_DELETE(self, request, group_id, role_id, user_id):
requester = await self.auth.get_user_by_req(request)
requester_user_id = requester.user.to_string()
resp = await sel... | async def on_PUT(self, request, group_id, role_id, user_id):
return 200, resp
@_validate_group_id
async def on_DELETE(
self, request: Request, group_id: str, role_id: str, user_id: str
):
requester = await self.auth.get_user_by_req(request)
requester_user_id = requester.user... |
class GroupRoomServlet(RestServlet):
PATTERNS = client_patterns("/groups/(?P<group_id>[^/]*)/rooms$")
def __init__(self, hs):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
@_validate_group_id
... | class GroupRoomServlet(RestServlet):
PATTERNS = client_patterns("/groups/(?P<group_id>[^/]*)/rooms$")
def __init__(self, hs: "HomeServer"):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
@_valida... |
class GroupUsersServlet(RestServlet):
PATTERNS = client_patterns("/groups/(?P<group_id>[^/]*)/users$")
def __init__(self, hs):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
@_validate_group_id
... | class GroupUsersServlet(RestServlet):
PATTERNS = client_patterns("/groups/(?P<group_id>[^/]*)/users$")
def __init__(self, hs: "HomeServer"):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
@_valid... |
class GroupInvitedUsersServlet(RestServlet):
PATTERNS = client_patterns("/groups/(?P<group_id>[^/]*)/invited_users$")
def __init__(self, hs):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
@_vali... | class GroupInvitedUsersServlet(RestServlet):
PATTERNS = client_patterns("/groups/(?P<group_id>[^/]*)/invited_users$")
def __init__(self, hs: "HomeServer"):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler... |
class GroupSettingJoinPolicyServlet(RestServlet):
PATTERNS = client_patterns("/groups/(?P<group_id>[^/]*)/settings/m.join_policy$")
def __init__(self, hs):
super().__init__()
self.auth = hs.get_auth()
self.groups_handler = hs.get_groups_local_handler()
@_validate_group_id
asyn... | class GroupSettingJoinPolicyServlet(RestServlet):
PATTERNS = client_patterns("/groups/(?P<group_id>[^/]*)/settings/m.join_policy$")
def __init__(self, hs: "HomeServer"):
super().__init__()
self.auth = hs.get_auth()
self.groups_handler = hs.get_groups_local_handler()
@_validate_gro... |
class GroupCreateServlet(RestServlet):
PATTERNS = client_patterns("/create_group$")
def __init__(self, hs):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
self.server_name = hs.hostname
a... | class GroupCreateServlet(RestServlet):
PATTERNS = client_patterns("/create_group$")
def __init__(self, hs: "HomeServer"):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
self.server_name = hs.h... |
async def on_POST(self, request):
localpart = content.pop("localpart")
group_id = GroupID(localpart, self.server_name).to_string()
result = await self.groups_handler.create_group(
group_id, requester_user_id, content
) | async def on_POST(self, request):
localpart = content.pop("localpart")
group_id = GroupID(localpart, self.server_name).to_string()
assert isinstance(self.groups_handler, GroupsLocalHandler)
result = await self.groups_handler.create_group(
group_id, requester_user_id, content... |
class GroupAdminRoomsServlet(RestServlet):
"/groups/(?P<group_id>[^/]*)/admin/rooms/(?P<room_id>[^/]*)$"
)
def __init__(self, hs):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
@_validate... | class GroupAdminRoomsServlet(RestServlet):
"/groups/(?P<group_id>[^/]*)/admin/rooms/(?P<room_id>[^/]*)$"
)
def __init__(self, hs: "HomeServer"):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
... |
async def on_PUT(self, request, group_id, room_id):
return 200, result
@_validate_group_id
async def on_DELETE(self, request, group_id, room_id):
requester = await self.auth.get_user_by_req(request)
requester_user_id = requester.user.to_string()
result = await self.groups_handl... | async def on_PUT(self, request, group_id, room_id):
return 200, result
@_validate_group_id
async def on_DELETE(
self, request: Request, group_id: str, room_id: str
) -> Tuple[int, JsonDict]:
requester = await self.auth.get_user_by_req(request)
requester_user_id = requester.u... |
class GroupAdminRoomsConfigServlet(RestServlet):
"/config/(?P<config_key>[^/]*)$"
)
def __init__(self, hs):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
@_validate_group_id
async def... | class GroupAdminRoomsConfigServlet(RestServlet):
"/config/(?P<config_key>[^/]*)$"
)
def __init__(self, hs: "HomeServer"):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
@_validate_group_id... |
class GroupAdminUsersInviteServlet(RestServlet):
"/groups/(?P<group_id>[^/]*)/admin/users/invite/(?P<user_id>[^/]*)$"
)
def __init__(self, hs):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock() | class GroupAdminUsersInviteServlet(RestServlet):
"/groups/(?P<group_id>[^/]*)/admin/users/invite/(?P<user_id>[^/]*)$"
)
def __init__(self, hs: "HomeServer"):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock() |
def __init__(self, hs):
self.is_mine_id = hs.is_mine_id
@_validate_group_id
async def on_PUT(self, request, group_id, user_id):
requester = await self.auth.get_user_by_req(request)
requester_user_id = requester.user.to_string()
content = parse_json_object_from_request(request)
... | def __init__(self, hs):
self.is_mine_id = hs.is_mine_id
@_validate_group_id
async def on_PUT(self, request: Request, group_id, user_id) -> Tuple[int, JsonDict]:
requester = await self.auth.get_user_by_req(request)
requester_user_id = requester.user.to_string()
content = parse_j... |
class GroupAdminUsersKickServlet(RestServlet):
"/groups/(?P<group_id>[^/]*)/admin/users/remove/(?P<user_id>[^/]*)$"
)
def __init__(self, hs):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
... | class GroupAdminUsersKickServlet(RestServlet):
"/groups/(?P<group_id>[^/]*)/admin/users/remove/(?P<user_id>[^/]*)$"
)
def __init__(self, hs: "HomeServer"):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_... |
class GroupSelfLeaveServlet(RestServlet):
PATTERNS = client_patterns("/groups/(?P<group_id>[^/]*)/self/leave$")
def __init__(self, hs):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
@_validate_g... | class GroupSelfLeaveServlet(RestServlet):
PATTERNS = client_patterns("/groups/(?P<group_id>[^/]*)/self/leave$")
def __init__(self, hs: "HomeServer"):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
... |
class GroupSelfJoinServlet(RestServlet):
PATTERNS = client_patterns("/groups/(?P<group_id>[^/]*)/self/join$")
def __init__(self, hs):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
@_validate_gro... | class GroupSelfJoinServlet(RestServlet):
PATTERNS = client_patterns("/groups/(?P<group_id>[^/]*)/self/join$")
def __init__(self, hs: "HomeServer"):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.