buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
def diff(arr, n: int, axis: int = 0):
elif is_bool_dtype(dtype):
dtype = np.object_
elif is_integer_dtype(dtype):
dtype = np.float64 | def diff(arr, n: int, axis: int = 0):
elif is_bool_dtype(dtype):
dtype = np.object_
is_bool = True
elif is_integer_dtype(dtype):
dtype = np.float64 |
def diff(arr, n: int, axis: int = 0):
result = res - lag
result[mask] = na
out_arr[res_indexer] = result
else:
out_arr[res_indexer] = arr[res_indexer] - arr[lag_indexer]
| def diff(arr, n: int, axis: int = 0):
result = res - lag
result[mask] = na
out_arr[res_indexer] = result
elif is_bool:
out_arr[res_indexer] = arr[res_indexer] ^ arr[lag_indexer]
else:
out_arr[res_indexer] = arr[res_indexer] - arr[lag_indexer]
|
from pandas import (
from pandas.api.types import is_scalar
from pandas.core.index import MultiIndex
from pandas.core.indexes.datetimes import Timestamp
import pandas.util.testing as tm
from pandas.util.testing import (
assert_almost_equal, | from pandas import (
from pandas.api.types import is_scalar
from pandas.core.index import MultiIndex
from pandas.core.indexes.datetimes import Timestamp
from pandas.core.indexes.timedeltas import TimedeltaIndex
import pandas.util.testing as tm
from pandas.util.testing import (
assert_almost_equal, |
class TestSeriesAnalytics:
result = s.cummax(skipna=False)
tm.assert_series_equal(expected, result)
def test_npdiff(self):
pytest.skip("skipping due to Series no longer being an ndarray")
# no longer works as the return type of np.diff is now nd.array | class TestSeriesAnalytics:
result = s.cummax(skipna=False)
tm.assert_series_equal(expected, result)
def test_np_diff(self):
pytest.skip("skipping due to Series no longer being an ndarray")
# no longer works as the return type of np.diff is now nd.array |
class TestSeriesAnalytics:
r = np.diff(s)
assert_series_equal(Series([nan, 0, 0, 0, nan]), r)
def _check_accum_op(self, name, datetime_series_, check_dtype=True):
func = getattr(np, name)
tm.assert_numpy_array_equal( | class TestSeriesAnalytics:
r = np.diff(s)
assert_series_equal(Series([nan, 0, 0, 0, nan]), r)
def test_int_diff(self):
# int dtype
a = 10000000000000000
b = a + 1
s = Series([a, b])
result = s.diff()
assert result[1] == 1
def test_tz_diff(self):... |
class TestTimeSeries(TestData):
)
tm.assert_index_equal(expected.index, result.index)
def test_diff(self):
# Just run the function
self.ts.diff()
# int dtype
a = 10000000000000000
b = a + 1
s = Series([a, b])
rs = s.diff()
assert rs[... | class TestTimeSeries(TestData):
)
tm.assert_index_equal(expected.index, result.index)
def test_pct_change(self):
rs = self.ts.pct_change(fill_method=None)
assert_series_equal(rs, self.ts / self.ts.shift(1) - 1) |
INTERNAL_RESULT_KEYS = ('add_host', 'add_group')
LOCALHOST = ('127.0.0.1', 'localhost', '::1')
MODULE_REQUIRE_ARGS = ('command', 'win_command', 'shell', 'win_shell', 'raw', 'script')
MODULE_NO_JSON = ('command', 'win_command', 'shell', 'win_shell', 'raw')
RESTRICTED_RESULT_KEYS = ('ansible_rsync_path', 'ansible_playboo... | INTERNAL_RESULT_KEYS = ('add_host', 'add_group')
LOCALHOST = ('127.0.0.1', 'localhost', '::1')
MODULE_REQUIRE_ARGS = ('command', 'win_command', 'shell', 'win_shell', 'raw', 'script')
MODULE_NO_JSON = ('command', 'win_command', 'shell', 'win_shell', 'raw')
RESTRICTED_RESULT_KEYS = ('ansible_rsync_path', 'ansible_playboo... |
def namespace_facts(facts):
''' return all facts inside 'ansible_facts' w/o an ansible_ prefix '''
deprefixed = {}
for k in facts:
if k in ('ansible_local',):
# exceptions to 'deprefixing'
deprefixed[k] = module_response_deepcopy(facts[k])
else:
deprefixed... | def namespace_facts(facts):
''' return all facts inside 'ansible_facts' w/o an ansible_ prefix '''
deprefixed = {}
for k in facts:
if k.startswith('ansible_') and k not in ('ansible_local',):
deprefixed[k[8:]] = module_response_deepcopy(facts[k])
else:
deprefixed[k] =... |
def main():
'test/integration/targets/win_module_utils/library/legacy_only_new_way_win_line_ending.ps1',
'test/integration/targets/win_module_utils/library/legacy_only_old_way_win_line_ending.ps1',
'test/utils/shippable/timing.py',
])
for path in sys.argv[1:] or sys.stdin.read().splitli... | def main():
'test/integration/targets/win_module_utils/library/legacy_only_new_way_win_line_ending.ps1',
'test/integration/targets/win_module_utils/library/legacy_only_old_way_win_line_ending.ps1',
'test/utils/shippable/timing.py',
'test/integration/targets/gathering_facts/library/bogus_... |
class URLValidator(RegexValidator):
ul = '\u00a1-\uffff' # Unicode letters range (must not be a raw string).
# IP patterns
ipv4_re = r'(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}'
ipv6_re = r'\[[0-9a-f:.]+\]' # (simple regex, validated later)
# Host patterns | class URLValidator(RegexValidator):
ul = '\u00a1-\uffff' # Unicode letters range (must not be a raw string).
# IP patterns
ipv4_re = r'(?:0|25[0-5]|2[0-4]\d|1\d?\d?|[1-9]\d?)(?:\.(?:0|25[0-5]|2[0-4]\d|1\d?\d?|[1-9]\d?)){3}'
ipv6_re = r'\[[0-9a-f:.]+\]' # (simple regex, validated later)
# Host pa... |
def validate_ipv4_address(value):
ipaddress.IPv4Address(value)
except ValueError:
raise ValidationError(_('Enter a valid IPv4 address.'), code='invalid')
def validate_ipv6_address(value): | def validate_ipv4_address(value):
ipaddress.IPv4Address(value)
except ValueError:
raise ValidationError(_('Enter a valid IPv4 address.'), code='invalid')
else:
# Leading zeros are forbidden to avoid ambiguity with the octal
# notation. This restriction is included in Python 3.9.5... |
TEST_DATA = [
(validate_ipv4_address, '1.1.1.1\n', ValidationError),
(validate_ipv4_address, '٧.2٥.3٣.243', ValidationError),
# validate_ipv6_address uses django.utils.ipv6, which
# is tested in much greater detail in its own testcase
(validate_ipv6_address, 'fe80::1', None), | TEST_DATA = [
(validate_ipv4_address, '1.1.1.1\n', ValidationError),
(validate_ipv4_address, '٧.2٥.3٣.243', ValidationError),
# Leading zeros are forbidden to avoid ambiguity with the octal notation.
(validate_ipv4_address, '000.000.000.000', ValidationError),
(validate_ipv4_address, '016.016.016.0... |
TEST_DATA = [
(validate_ipv46_address, '::zzz', ValidationError),
(validate_ipv46_address, '12345::', ValidationError),
(validate_comma_separated_integer_list, '1', None),
(validate_comma_separated_integer_list, '12', None),
(validate_comma_separated_integer_list, '1,2', None), | TEST_DATA = [
(validate_ipv46_address, '::zzz', ValidationError),
(validate_ipv46_address, '12345::', ValidationError),
# Leading zeros are forbidden to avoid ambiguity with the octal notation.
(validate_ipv46_address, '000.000.000.000', ValidationError),
(validate_ipv46_address, '016.016.016.016',... |
class Sanic:
if _rn not in self.named_response_middleware:
self.named_response_middleware[_rn] = deque()
if middleware not in self.named_response_middleware[_rn]:
self.named_response_middleware[_rn].append(middleware)
# Decorator
def middl... | class Sanic:
if _rn not in self.named_response_middleware:
self.named_response_middleware[_rn] = deque()
if middleware not in self.named_response_middleware[_rn]:
self.named_response_middleware[_rn].appendleft(middleware)
# Decorator
def m... |
def test_several_bp_with_host(app):
def test_bp_middleware(app):
blueprint = Blueprint("test_middleware")
@blueprint.middleware("response")
async def process_response(request, response): | def test_several_bp_with_host(app):
def test_bp_middleware(app):
blueprint = Blueprint("test_bp_middleware")
@blueprint.middleware("response")
async def process_response(request, response): |
def test_bp_middleware(app):
assert response.status == 200
assert response.text == "FAIL"
def test_bp_exception_handler(app):
blueprint = Blueprint("test_middleware") | def test_bp_middleware(app):
assert response.status == 200
assert response.text == "FAIL"
def test_bp_middleware_order(app):
blueprint = Blueprint("test_bp_middleware_order")
order = list()
@blueprint.middleware("request")
def mw_1(request):
order.append(1)
@blueprint.middleware("re... |
capfirst = allow_lazy(capfirst, six.text_type)
# Set up regular expressions
re_words = re.compile(r'<.*?>|((?:\w[-\w]*|&.*?;)+)', re.U | re.S)
re_chars = re.compile(r'<.*?>|(.)', re.U | re.S)
re_tag = re.compile(r'<(/)?([^ ]+?)(?:(\s*/)| .*?)?>', re.S)
re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines
... | capfirst = allow_lazy(capfirst, six.text_type)
# Set up regular expressions
re_words = re.compile(r'<.*?>|((?:\w[-\w]*|&.*?;)+)', re.U | re.S)
re_chars = re.compile(r'<.*?>|(.)', re.U | re.S)
re_tag = re.compile(r'<(/)?(\S+?)(?:(\s*/)|\s.*?)?>', re.S)
re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines
r... |
class TestUtilsText(SimpleTestCase):
self.assertEqual('<p>I <3 python...</p>',
truncator.words(3, '...', html=True))
def test_wrap(self):
digits = '1234 67 9'
self.assertEqual(text.wrap(digits, 100), '1234 67 9') | class TestUtilsText(SimpleTestCase):
self.assertEqual('<p>I <3 python...</p>',
truncator.words(3, '...', html=True))
re_tag_catastrophic_test = ('</a' + '\t' * 50000) + '//>'
truncator = text.Truncator(re_tag_catastrophic_test)
self.assertEqual(re_tag_catastrophic_test, t... |
def test_not_match(command):
@pytest.mark.parametrize('command, new_command', [
(Command(script='vagrant ssh', stderr='VM must be running to open SSH connection. Run `vagrant up`\nto start the virtual machine.'), 'vagrant up && vagrant ssh'),
(Command(script='vagrant ssh devbox', stderr='VM must be running t... | def test_not_match(command):
@pytest.mark.parametrize('command, new_command', [
(Command(script='vagrant ssh', stderr='VM must be running to open SSH connection. Run `vagrant up`\nto start the virtual machine.'), 'vagrant up && vagrant ssh'),
(Command(script='vagrant ssh devbox', stderr='VM must be running to... |
def match(command, settings):
def get_new_command(command, settings):
cmds = command.script.split(' ')
machine = ""
if len(cmds) >= 3:
machine = cmds[2]
return shells.and_("vagrant up " + machine, command.script) | def match(command, settings):
def get_new_command(command, settings):
cmds = command.script.split(' ')
machine = None
if len(cmds) >= 3:
machine = cmds[2]
startAllInstances = shells.and_("vagrant up", command.script)
if machine is None:
return startAllInstances
else:
r... |
def array_equivalent(left, right, strict_nan=False):
if not isinstance(right_value, float) or not np.isnan(right_value):
return False
else:
if np.any(left_value != right_value):
return False
return True
# NaNs can occur in ... | def array_equivalent(left, right, strict_nan=False):
if not isinstance(right_value, float) or not np.isnan(right_value):
return False
else:
try:
if np.any(left_value != right_value):
return False
... |
class Index(IndexOpsMixin, PandasObject):
# if other is not object, use other's logic for coercion
return other.equals(self)
try:
return array_equivalent(
com.values_from_object(self), com.values_from_object(other)
)
except Exception:
... | class Index(IndexOpsMixin, PandasObject):
# if other is not object, use other's logic for coercion
return other.equals(self)
return array_equivalent(
com.values_from_object(self), com.values_from_object(other)
)
def identical(self, other):
""" |
import pandas as pd
from pandas import DatetimeIndex, Float64Index, NaT, Series, TimedeltaIndex, date_range
from pandas.util import testing as tm
@pytest.mark.parametrize("notna_f", [notna, notnull])
def test_notna_notnull(notna_f): | import pandas as pd
from pandas import DatetimeIndex, Float64Index, NaT, Series, TimedeltaIndex, date_range
from pandas.util import testing as tm
now = pd.Timestamp.now()
utcnow = pd.Timestamp.now("UTC")
@pytest.mark.parametrize("notna_f", [notna, notnull])
def test_notna_notnull(notna_f): |
def test_array_equivalent():
assert not array_equivalent(DatetimeIndex([0, np.nan]), TimedeltaIndex([0, np.nan]))
def test_array_equivalent_compat():
# see gh-13388
m = np.array([(1, 2), (3, 4)], dtype=[("a", int), ("b", float)]) | def test_array_equivalent():
assert not array_equivalent(DatetimeIndex([0, np.nan]), TimedeltaIndex([0, np.nan]))
@pytest.mark.parametrize(
"lvalue, rvalue",
[
# There are 3 variants for each of lvalue and rvalue. We include all
# three for the tz-naive `now` and exclude the datetim64 var... |
def capfirst(x):
# Set up regular expressions
re_words = re.compile(r'<.*?>|((?:\w[-\w]*|&.*?;)+)', re.U | re.S)
re_chars = re.compile(r'<.*?>|(.)', re.U | re.S)
re_tag = re.compile(r'<(/)?([^ ]+?)(?:(\s*/)| .*?)?>', re.S)
re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines
re_camel_case = re.compile(r'(... | def capfirst(x):
# Set up regular expressions
re_words = re.compile(r'<.*?>|((?:\w[-\w]*|&.*?;)+)', re.U | re.S)
re_chars = re.compile(r'<.*?>|(.)', re.U | re.S)
re_tag = re.compile(r'<(/)?(\S+?)(?:(\s*/)|\s.*?)?>', re.S)
re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines
re_camel_case = re.compile(r'((... |
class TestUtilsText(SimpleTestCase):
truncator = text.Truncator('<p>I <3 python, what about you?</p>')
self.assertEqual('<p>I <3 python...</p>', truncator.words(3, '...', html=True))
def test_wrap(self):
digits = '1234 67 9'
self.assertEqual(text.wrap(digits, 100), '1234 67 9'... | class TestUtilsText(SimpleTestCase):
truncator = text.Truncator('<p>I <3 python, what about you?</p>')
self.assertEqual('<p>I <3 python...</p>', truncator.words(3, '...', html=True))
re_tag_catastrophic_test = ('</a' + '\t' * 50000) + '//>'
truncator = text.Truncator(re_tag_catast... |
def test_overflowing_header_limit_after_100(self):
'r\n' * 32768
)
resp = client.HTTPResponse(FakeSocket(body))
self.assertRaises(client.HTTPException, resp.begin)
def test_overflowing_chunked_line(self):
body = ( | def test_overflowing_header_limit_after_100(self):
'r\n' * 32768
)
resp = client.HTTPResponse(FakeSocket(body))
with self.assertRaises(client.HTTPException) as cm:
resp.begin()
# We must assert more because other reasonable errors that we
# do not want can... |
class HttpRequest(object):
if server_port != ('443' if self.is_secure() else '80'):
host = '%s:%s' % (host, server_port)
# There is no hostname validation when DEBUG=True
if settings.DEBUG:
return host
domain, port = split_domain_port(host)
if do... | class HttpRequest(object):
if server_port != ('443' if self.is_secure() else '80'):
host = '%s:%s' % (host, server_port)
# Allow variants of localhost if ALLOWED_HOSTS is empty and DEBUG=True.
allowed_hosts = settings.ALLOWED_HOSTS
if settings.DEBUG and not allowed_h... |
class HostValidationTests(SimpleTestCase):
request.get_host()
@override_settings(DEBUG=True, ALLOWED_HOSTS=[])
def test_host_validation_disabled_in_debug_mode(self):
"""If ALLOWED_HOSTS is empty and DEBUG is True, all hosts pass."""
request = HttpRequest()
request.META =... | class HostValidationTests(SimpleTestCase):
request.get_host()
@override_settings(DEBUG=True, ALLOWED_HOSTS=[])
def test_host_validation_in_debug_mode(self):
"""
If ALLOWED_HOSTS is empty and DEBUG is True, variants of localhost are
allowed.
"""
valid_host... |
def parse(validator_string, validators=None):
validators = validators or val.DefaultValidators
try:
tree = ast.parse(validator_string, mode='eval')
# evaluate with access to a limited global scope only |
def parse(validator_string, validators=None):
validators = validators or val.DefaultValidators
if validator_string:
for validator in validators.keys():
if validator_string.startswith(validator):
break
else:
raise SyntaxError(
'Invalid sch... |
except ImportError:
from gzip import GzipFile
import six
# - Python>=3.5 GzipFile's read() has issues returning leftover
# uncompressed data when input is corrupted | except ImportError:
from gzip import GzipFile
import six
import re
# - Python>=3.5 GzipFile's read() has issues returning leftover
# uncompressed data when input is corrupted |
def gunzip(data):
raise
return output
def is_gzipped(response):
"""Return True if the response is gzipped, or False otherwise"""
ctype = response.headers.get('Content-Type', b'')
return ctype in (b'application/x-gzip', b'application/gzip') | def gunzip(data):
raise
return output
_is_gzipped_re = re.compile(br'^application/(x-)?gzip\b', re.I)
def is_gzipped(response):
"""Return True if the response is gzipped, or False otherwise"""
ctype = response.headers.get('Content-Type', b'')
return _is_gzipped_re.search(ctype) is not ... |
import unittest
from os.path import join
from scrapy.utils.gz import gunzip
from tests import tests_datadir
SAMPLEDIR = join(tests_datadir, 'compressed') | import unittest
from os.path import join
from scrapy.utils.gz import gunzip, is_gzipped
from scrapy.http import Response, Headers
from tests import tests_datadir
SAMPLEDIR = join(tests_datadir, 'compressed') |
class GunzipTest(unittest.TestCase):
with open(join(SAMPLEDIR, 'truncated-crc-error-short.gz'), 'rb') as f:
text = gunzip(f.read())
assert text.endswith(b'</html>') | class GunzipTest(unittest.TestCase):
with open(join(SAMPLEDIR, 'truncated-crc-error-short.gz'), 'rb') as f:
text = gunzip(f.read())
assert text.endswith(b'</html>')
def test_is_x_gzipped_right(self):
hdrs = Headers({"Content-Type": "application/x-gzip"})
r1 = Respons... |
import warnings
import numpy as np
from pandas._libs import NaT, algos as libalgos, lib, tslib, writers
from pandas._libs.index import convert_scalar
import pandas._libs.internals as libinternals
from pandas._libs.tslibs import Timedelta, conversion | import warnings
import numpy as np
from pandas._libs import NaT, Timestamp, algos as libalgos, lib, tslib, writers
from pandas._libs.index import convert_scalar
import pandas._libs.internals as libinternals
from pandas._libs.tslibs import Timedelta, conversion |
class DatetimeLikeBlockMixin:
# Override to return DatetimeArray and TimedeltaArray
return self.array_values()
class DatetimeBlock(DatetimeLikeBlockMixin, Block):
__slots__ = () | class DatetimeLikeBlockMixin:
# Override to return DatetimeArray and TimedeltaArray
return self.array_values()
def iget(self, key):
# GH#31649 we need to wrap scalars in Timestamp/Timedelta
# TODO: this can be removed if we ever have 2D EA
result = super().iget(key)
... |
class TestDataFrameIndexingUInt64:
df = result.set_index("foo")
tm.assert_index_equal(df.index, idx) | class TestDataFrameIndexingUInt64:
df = result.set_index("foo")
tm.assert_index_equal(df.index, idx)
def test_object_casting_indexing_wraps_datetimelike():
# GH#31649, check the indexing methods all the way down the stack
df = pd.DataFrame(
{
"A": [1, 2],
"B": ... |
from asyncio.base_events import BaseEventLoop
from concurrent.futures import Executor, ProcessPoolExecutor
from enum import Enum, Flag
from functools import partial, wraps
import keyword
import logging
from multiprocessing import Manager | from asyncio.base_events import BaseEventLoop
from concurrent.futures import Executor, ProcessPoolExecutor
from enum import Enum, Flag
from functools import partial, wraps
import io
import keyword
import logging
from multiprocessing import Manager |
def format_file_in_place(
"""
if src.suffix == ".pyi":
mode |= FileMode.PYI
with tokenize.open(src) as src_buffer:
src_contents = src_buffer.read()
try:
dst_contents = format_file_contents(
src_contents, line_length=line_length, fast=fast, mode=mode | def format_file_in_place(
"""
if src.suffix == ".pyi":
mode |= FileMode.PYI
with open(src, "rb") as buf:
newline, encoding, src_contents = prepare_input(buf.read())
try:
dst_contents = format_file_contents(
src_contents, line_length=line_length, fast=fast, mode=mode |
def format_file_in_place(
return False
if write_back == write_back.YES:
with open(src, "w", encoding=src_buffer.encoding) as f:
f.write(dst_contents)
elif write_back == write_back.DIFF:
src_name = f"{src} (original)" | def format_file_in_place(
return False
if write_back == write_back.YES:
with open(src, "w", encoding=encoding, newline=newline) as f:
f.write(dst_contents)
elif write_back == write_back.DIFF:
src_name = f"{src} (original)" |
def format_file_in_place(
if lock:
lock.acquire()
try:
sys.stdout.write(diff_contents)
finally:
if lock:
lock.release() | def format_file_in_place(
if lock:
lock.acquire()
try:
f = io.TextIOWrapper(
sys.stdout.buffer,
encoding=encoding,
newline=newline,
write_through=True,
)
f.write(diff_contents)
f.d... |
def format_stdin_to_stdout(
`line_length`, `fast`, `is_pyi`, and `force_py36` arguments are passed to
:func:`format_file_contents`.
"""
src = sys.stdin.read()
dst = src
try:
dst = format_file_contents(src, line_length=line_length, fast=fast, mode=mode) | def format_stdin_to_stdout(
`line_length`, `fast`, `is_pyi`, and `force_py36` arguments are passed to
:func:`format_file_contents`.
"""
newline, encoding, src = prepare_input(sys.stdin.buffer.read())
dst = src
try:
dst = format_file_contents(src, line_length=line_length, fast=fast, mode=... |
def format_stdin_to_stdout(
finally:
if write_back == WriteBack.YES:
sys.stdout.write(dst)
elif write_back == WriteBack.DIFF:
src_name = "<stdin> (original)"
dst_name = "<stdin> (formatted)"
sys.stdout.write(diff(src, dst, src_name, dst_name))
def... | def format_stdin_to_stdout(
finally:
if write_back == WriteBack.YES:
f = io.TextIOWrapper(
sys.stdout.buffer,
encoding=encoding,
newline=newline,
write_through=True,
)
f.write(dst)
f.detach()
... |
def format_str(
return dst_contents
GRAMMARS = [
pygram.python_grammar_no_print_statement_no_exec_statement,
pygram.python_grammar_no_print_statement, | def format_str(
return dst_contents
def prepare_input(src: bytes) -> Tuple[str, str, str]:
"""Analyze `src` and return a tuple of (newline, encoding, decoded_contents)
Where `newline` is either CRLF or LF, and `decoded_contents` is decoded with
universal newlines (i.e. only LF).
"""
srcbuf = ... |
def lib2to3_parse(src_txt: str) -> Node:
"""Given a string with source, return the lib2to3 Node."""
grammar = pygram.python_grammar_no_print_statement
if src_txt[-1] != "\n":
nl = "\r\n" if "\r\n" in src_txt[:1024] else "\n"
src_txt += nl
for grammar in GRAMMARS:
drv = driver.Dri... | def lib2to3_parse(src_txt: str) -> Node:
"""Given a string with source, return the lib2to3 Node."""
grammar = pygram.python_grammar_no_print_statement
if src_txt[-1] != "\n":
src_txt += "\n"
for grammar in GRAMMARS:
drv = driver.Driver(grammar, pytree.convert)
try: |
import asyncio
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from functools import partial
from io import StringIO
import os
from pathlib import Path
import sys | import asyncio
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from functools import partial
from io import BytesIO, TextIOWrapper
import os
from pathlib import Path
import sys |
class BlackTestCase(unittest.TestCase):
source, expected = read_data("../black")
hold_stdin, hold_stdout = sys.stdin, sys.stdout
try:
sys.stdin, sys.stdout = StringIO(source), StringIO()
sys.stdin.name = "<stdin>"
black.format_stdin_to_stdout(
... | class BlackTestCase(unittest.TestCase):
source, expected = read_data("../black")
hold_stdin, hold_stdout = sys.stdin, sys.stdout
try:
sys.stdin = TextIOWrapper(BytesIO(source.encode("utf8")), encoding="utf8")
sys.stdout = TextIOWrapper(BytesIO(), encoding="utf8")
... |
class BlackTestCase(unittest.TestCase):
expected, _ = read_data("expression.diff")
hold_stdin, hold_stdout = sys.stdin, sys.stdout
try:
sys.stdin, sys.stdout = StringIO(source), StringIO()
sys.stdin.name = "<stdin>"
black.format_stdin_to_stdout(
... | class BlackTestCase(unittest.TestCase):
expected, _ = read_data("expression.diff")
hold_stdin, hold_stdout = sys.stdin, sys.stdout
try:
sys.stdin = TextIOWrapper(BytesIO(source.encode("utf8")), encoding="utf8")
sys.stdout = TextIOWrapper(BytesIO(), encoding="utf8")
... |
class BlackTestCase(unittest.TestCase):
tmp_file = Path(black.dump_to_file(source))
hold_stdout = sys.stdout
try:
sys.stdout = StringIO()
self.assertTrue(ff(tmp_file, write_back=black.WriteBack.DIFF))
sys.stdout.seek(0)
actual = sys.stdout.read() | class BlackTestCase(unittest.TestCase):
tmp_file = Path(black.dump_to_file(source))
hold_stdout = sys.stdout
try:
sys.stdout = TextIOWrapper(BytesIO(), encoding="utf8")
self.assertTrue(ff(tmp_file, write_back=black.WriteBack.DIFF))
sys.stdout.seek(0)
... |
class BlackTestCase(unittest.TestCase):
result = CliRunner().invoke(black.main, ["-", option, "**()(!!*)"])
self.assertEqual(result.exit_code, 2)
if __name__ == "__main__":
unittest.main() | class BlackTestCase(unittest.TestCase):
result = CliRunner().invoke(black.main, ["-", option, "**()(!!*)"])
self.assertEqual(result.exit_code, 2)
def test_preserves_line_endings(self) -> None:
with TemporaryDirectory() as workspace:
test_file = Path(workspace) / "test.py... |
class TestUtil(unittest.TestCase):
self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
def test_strip_jsonp(self):
stripped... | class TestUtil(unittest.TestCase):
self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
self.assertEqual(parse_iso8601('2014-03-2... |
from __future__ import unicode_literals
import re
from .subtitles import SubtitlesInfoExtractor
from .common import ExtractorError
from ..utils import parse_iso8601 | from __future__ import unicode_literals
from .subtitles import SubtitlesInfoExtractor
from .common import ExtractorError
from ..utils import parse_iso8601 |
class DRTVIE(SubtitlesInfoExtractor):
}
def _real_extract(self, url):
mobj = re.match(self._VALID_URL, url)
video_id = mobj.group('id')
programcard = self._download_json(
'http://www.dr.dk/mu/programcard/expanded/%s' % video_id, video_id, 'Downloading video JSON') | class DRTVIE(SubtitlesInfoExtractor):
}
def _real_extract(self, url):
video_id = self._match_id(url)
programcard = self._download_json(
'http://www.dr.dk/mu/programcard/expanded/%s' % video_id, video_id, 'Downloading video JSON') |
class DRTVIE(SubtitlesInfoExtractor):
title = data['Title']
description = data['Description']
timestamp = parse_iso8601(data['CreatedTime'][:-5])
thumbnail = None
duration = None | class DRTVIE(SubtitlesInfoExtractor):
title = data['Title']
description = data['Description']
timestamp = parse_iso8601(data['CreatedTime'])
thumbnail = None
duration = None |
def parse_iso8601(date_str, delimiter='T'):
return None
m = re.search(
r'Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$',
date_str)
if not m:
timezone = datetime.timedelta() | def parse_iso8601(date_str, delimiter='T'):
return None
m = re.search(
r'(\.[0-9]+)?(?:Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$)',
date_str)
if not m:
timezone = datetime.timedelta() |
def parse_iso8601(date_str, delimiter='T'):
timezone = datetime.timedelta(
hours=sign * int(m.group('hours')),
minutes=sign * int(m.group('minutes')))
date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
dt = datetime.datetime.strptime(date_str, date_format) - timez... | def parse_iso8601(date_str, delimiter='T'):
timezone = datetime.timedelta(
hours=sign * int(m.group('hours')),
minutes=sign * int(m.group('minutes')))
date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
dt = datetime.datetime.strptime(date_str, date_format) - timezo... |
def test_seek():
im.seek(50)
assert_image_equal_tofile(im, "Tests/images/a_fli.png") | def test_seek():
im.seek(50)
assert_image_equal_tofile(im, "Tests/images/a_fli.png")
@pytest.mark.parametrize(
"test_file",
[
"Tests/images/timeout-9139147ce93e20eb14088fe238e541443ffd64b3.fli",
"Tests/images/timeout-bff0a9dc7243a8e6ede2408d2ffa6a9964698b87.fli",
],
)
@pyt... |
install_requires = [
"docker >= 3.4.1, < 3.5",
"mypy_extensions >= 0.3.0, < 0.4",
"python-dateutil >= 2.7.3, < 3.0",
"requests >= 2.19.1, < 3.0",
"toml >= 0.9.4, < 1.0",
"typing >= 3.6.4, < 4.0",
"typing_extensions >= 3.6.4, < 4.0", | install_requires = [
"docker >= 3.4.1, < 3.5",
"mypy_extensions >= 0.3.0, < 0.4",
"python-dateutil >= 2.7.3, < 3.0",
"requests >= 2.20, < 3.0",
"toml >= 0.9.4, < 1.0",
"typing >= 3.6.4, < 4.0",
"typing_extensions >= 3.6.4, < 4.0", |
def _make_getset_interval(method_name, lim_name, attr_name):
setter(self, min(vmin, vmax, oldmin), max(vmin, vmax, oldmax),
ignore=True)
else:
setter(self, max(vmin, vmax, oldmax), min(vmin, vmax, oldmin),
ignore=True)
sel... | def _make_getset_interval(method_name, lim_name, attr_name):
setter(self, min(vmin, vmax, oldmin), max(vmin, vmax, oldmax),
ignore=True)
else:
setter(self, max(vmin, vmax, oldmin), min(vmin, vmax, oldmax),
ignore=True)
sel... |
def test_bar_errbar_zorder():
assert capline.zorder > bar.zorder
for barlinecol in barlinecols:
assert barlinecol.zorder > bar.zorder | def test_bar_errbar_zorder():
assert capline.zorder > bar.zorder
for barlinecol in barlinecols:
assert barlinecol.zorder > bar.zorder
def test_set_ticks_inverted():
fig, ax = plt.subplots()
ax.invert_xaxis()
ax.set_xticks([.3, .7])
assert ax.get_xlim() == (1, 0) |
import stat
import tarfile
import zipfile
class ArchiveException(Exception):
""" | import stat
import tarfile
import zipfile
from django.core.exceptions import SuspiciousOperation
class ArchiveException(Exception):
""" |
class BaseArchive:
return False
return True
def extract(self):
raise NotImplementedError('subclasses of BaseArchive must provide an extract() method')
| class BaseArchive:
return False
return True
def target_filename(self, to_path, name):
target_path = os.path.abspath(to_path)
filename = os.path.abspath(os.path.join(target_path, name))
if not filename.startswith(target_path):
raise SuspiciousOperation("Ar... |
class TarArchive(BaseArchive):
name = member.name
if leading:
name = self.split_leading_dir(name)[1]
filename = os.path.join(to_path, name)
if member.isdir():
if filename and not os.path.exists(filename):
os.makedirs(fil... | class TarArchive(BaseArchive):
name = member.name
if leading:
name = self.split_leading_dir(name)[1]
filename = self.target_filename(to_path, name)
if member.isdir():
if filename and not os.path.exists(filename):
os.make... |
class ZipArchive(BaseArchive):
info = self._archive.getinfo(name)
if leading:
name = self.split_leading_dir(name)[1]
filename = os.path.join(to_path, name)
dirname = os.path.dirname(filename)
if dirname and not os.path.exists(dirname):
... | class ZipArchive(BaseArchive):
info = self._archive.getinfo(name)
if leading:
name = self.split_leading_dir(name)[1]
if not name:
continue
filename = self.target_filename(to_path, name)
dirname = os.path.dirname(filename)
... |
import sys
import tempfile
import unittest
from django.utils.archive import Archive, extract
TEST_DIR = os.path.join(os.path.dirname(__file__), 'archives') | import sys
import tempfile
import unittest
from django.core.exceptions import SuspiciousOperation
from django.test import SimpleTestCase
from django.utils.archive import Archive, extract
TEST_DIR = os.path.join(os.path.dirname(__file__), 'archives') |
class TestGzipTar(ArchiveTester, unittest.TestCase):
class TestBzip2Tar(ArchiveTester, unittest.TestCase):
archive = 'foobar.tar.bz2' | class TestGzipTar(ArchiveTester, unittest.TestCase):
class TestBzip2Tar(ArchiveTester, unittest.TestCase):
archive = 'foobar.tar.bz2'
class TestArchiveInvalid(SimpleTestCase):
def test_extract_function_traversal(self):
archives_dir = os.path.join(os.path.dirname(__file__), 'traversal_archives')
... |
class HTTPBearer(HTTPBase):
else:
return None
if scheme.lower() != "bearer":
raise HTTPException(
status_code=HTTP_403_FORBIDDEN,
detail="Invalid authentication credentials",
)
return HTTPAuthorizationCredentials(scheme=... | class HTTPBearer(HTTPBase):
else:
return None
if scheme.lower() != "bearer":
if self.auto_error:
raise HTTPException(
status_code=HTTP_403_FORBIDDEN,
detail="Invalid authentication credentials",
)
... |
def test_security_http_bearer_no_credentials():
def test_security_http_bearer_incorrect_scheme_credentials():
response = client.get("/users/me", headers={"Authorization": "Basic notreally"})
assert response.status_code == 403
assert response.json() == {"detail": "Invalid authentication credentials"} | def test_security_http_bearer_no_credentials():
def test_security_http_bearer_incorrect_scheme_credentials():
response = client.get("/users/me", headers={"Authorization": "Basic notreally"})
assert response.status_code == 200
assert response.json() == {"msg": "Create an account first"} |
"""
import os
import threading
from itertools import chain
| """
import os
import re
import sys
import threading
from itertools import chain
|
_cache = {}
_cache_lock = threading.RLock()
_dirname = os.path.join(os.path.dirname(__file__), 'locale-data')
def normalize_locale(name): | _cache = {}
_cache_lock = threading.RLock()
_dirname = os.path.join(os.path.dirname(__file__), 'locale-data')
_windows_reserved_name_re = re.compile("^(con|prn|aux|nul|com[0-9]|lpt[0-9])$", re.I)
def normalize_locale(name): |
def normalize_locale(name):
return locale_id
def exists(name):
"""Check whether locale data is available for the given locale.
| def normalize_locale(name):
return locale_id
def resolve_locale_filename(name):
"""
Resolve a locale identifier to a `.dat` path on disk.
"""
# Clean up any possible relative paths.
name = os.path.basename(name)
# Ensure we're not left with one of the Windows reserved names.
... |
def exists(name):
return False
if name in _cache:
return True
file_found = os.path.exists(os.path.join(_dirname, '%s.dat' % name))
return True if file_found else bool(normalize_locale(name))
| def exists(name):
return False
if name in _cache:
return True
file_found = os.path.exists(resolve_locale_filename(name))
return True if file_found else bool(normalize_locale(name))
|
def load(name, merge_inherited=True):
:raise `IOError`: if no locale data file is found for the given locale
identifer, or one of the locales it inherits from
"""
_cache_lock.acquire()
try:
data = _cache.get(name) | def load(name, merge_inherited=True):
:raise `IOError`: if no locale data file is found for the given locale
identifer, or one of the locales it inherits from
"""
name = os.path.basename(name)
_cache_lock.acquire()
try:
data = _cache.get(name) |
def load(name, merge_inherited=True):
else:
parent = '_'.join(parts[:-1])
data = load(parent).copy()
filename = os.path.join(_dirname, '%s.dat' % name)
with open(filename, 'rb') as fileobj:
if name != 'root' and merge_in... | def load(name, merge_inherited=True):
else:
parent = '_'.join(parts[:-1])
data = load(parent).copy()
filename = resolve_locale_filename(name)
with open(filename, 'rb') as fileobj:
if name != 'root' and merge_inherited:
... |
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://babel.edgewall.org/log/.
import unittest
import random
from operator import methodcaller
from babel import localedata
class MergeResolveTestCase(unittest.TestCase): | # individuals. For the exact contribution history, see the revision
# history and logs, available at http://babel.edgewall.org/log/.
import os
import pickle
import sys
import tempfile
import unittest
import random
from operator import methodcaller
import pytest
from babel import localedata, Locale, UnknownLocaleErro... |
def listdir_spy(*args):
localedata.locale_identifiers.cache = None
assert localedata.locale_identifiers()
assert len(listdir_calls) == 2 | def listdir_spy(*args):
localedata.locale_identifiers.cache = None
assert localedata.locale_identifiers()
assert len(listdir_calls) == 2
def test_locale_name_cleanup():
"""
Test that locale identifiers are cleaned up to avoid directory traversal.
"""
no_exist_name = os.path.join(tempfile.g... |
def load_data(path='imdb.npz', num_words=None, skip_top=0,
path = get_file(path,
origin='https://s3.amazonaws.com/text-datasets/imdb.npz',
file_hash='599dadb1135973df5b59232a0e9a887c')
with np.load(path) as f:
x_train, labels_train = f['x_train'], f['y_train']
... | def load_data(path='imdb.npz', num_words=None, skip_top=0,
path = get_file(path,
origin='https://s3.amazonaws.com/text-datasets/imdb.npz',
file_hash='599dadb1135973df5b59232a0e9a887c')
with np.load(path, allow_pickle=True) as f:
x_train, labels_train = f['x_train'... |
def _isna_old(obj):
raise NotImplementedError("isna is not defined for MultiIndex")
elif isinstance(obj, type):
return False
elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass)):
return _isna_ndarraylike_old(obj)
elif isinstance(obj, ABCGeneric):
return obj._construct... | def _isna_old(obj):
raise NotImplementedError("isna is not defined for MultiIndex")
elif isinstance(obj, type):
return False
elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass, ABCExtensionArray)):
return _isna_ndarraylike_old(obj)
elif isinstance(obj, ABCGeneric):
re... |
class TestSeriesAnalytics:
ts.iloc[[0, 3, 5]] = np.nan
tm.assert_series_equal(ts.count(level=1), right - 1)
def test_dot(self):
a = Series(np.random.randn(4), index=["p", "q", "r", "s"])
b = DataFrame( | class TestSeriesAnalytics:
ts.iloc[[0, 3, 5]] = np.nan
tm.assert_series_equal(ts.count(level=1), right - 1)
# GH29478
with pd.option_context("use_inf_as_na", True):
assert pd.Series([pd.Timestamp("1990/1/1")]).count() == 1
def test_dot(self):
a = Series(np.rando... |
def map_obj_to_commands(updates, module, warnings):
else:
add('protocol unix-socket')
if needs_update('state') and not needs_update('vrf'):
if want['state'] == 'stopped':
add('shutdown')
elif want['state'] == 'started': | def map_obj_to_commands(updates, module, warnings):
else:
add('protocol unix-socket')
if needs_update('state'):
if want['state'] == 'stopped':
add('shutdown')
elif want['state'] == 'started': |
class TestEosEapiModule(TestEosModule):
def test_eos_eapi_vrf(self):
set_module_args(dict(vrf='test'))
commands = ['management api http-commands', 'vrf test', 'no shutdown']
self.start_unconfigured(changed=True, commands=commands)
def test_eos_eapi_change_from_default_vrf(self): | class TestEosEapiModule(TestEosModule):
def test_eos_eapi_vrf(self):
set_module_args(dict(vrf='test'))
commands = ['management api http-commands', 'no shutdown', 'vrf test', 'no shutdown']
self.start_unconfigured(changed=True, commands=commands)
def test_eos_eapi_change_from_default_vr... |
class TestEosEapiModule(TestEosModule):
commands = ['management api http-commands', 'vrf test', 'no shutdown']
self.start_configured(changed=True, commands=commands)
def test_eos_eapi_vrf_missing(self):
set_module_args(dict(vrf='missing'))
self.start_unconfigured(failed=True) | class TestEosEapiModule(TestEosModule):
commands = ['management api http-commands', 'vrf test', 'no shutdown']
self.start_configured(changed=True, commands=commands)
def test_eos_eapi_default(self):
set_module_args(dict())
self.start_configured(changed=False, commands=[])
def t... |
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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.