buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
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()
... |
class GroupSelfAcceptInviteServlet(RestServlet):
PATTERNS = client_patterns("/groups/(?P<group_id>[^/]*)/self/accept_invite$")
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 GroupSelfAcceptInviteServlet(RestServlet):
PATTERNS = client_patterns("/groups/(?P<group_id>[^/]*)/self/accept_invite$")
def __init__(self, hs: "HomeServer"):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_loca... |
class GroupSelfUpdatePublicityServlet(RestServlet):
PATTERNS = client_patterns("/groups/(?P<group_id>[^/]*)/self/update_publicity$")
def __init__(self, hs):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.store = hs.get_datastore()
@_validate_... | class GroupSelfUpdatePublicityServlet(RestServlet):
PATTERNS = client_patterns("/groups/(?P<group_id>[^/]*)/self/update_publicity$")
def __init__(self, hs: "HomeServer"):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.store = hs.get_datastore()
... |
class PublicisedGroupsForUserServlet(RestServlet):
PATTERNS = client_patterns("/publicised_groups/(?P<user_id>[^/]*)$")
def __init__(self, hs):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.store = hs.get_datastore()
self.groups_handler =... | class PublicisedGroupsForUserServlet(RestServlet):
PATTERNS = client_patterns("/publicised_groups/(?P<user_id>[^/]*)$")
def __init__(self, hs: "HomeServer"):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.store = hs.get_datastore()
self.gr... |
class PublicisedGroupsForUsersServlet(RestServlet):
PATTERNS = client_patterns("/publicised_groups$")
def __init__(self, hs):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.store = hs.get_datastore()
self.groups_handler = hs.get_groups_loc... | class PublicisedGroupsForUsersServlet(RestServlet):
PATTERNS = client_patterns("/publicised_groups$")
def __init__(self, hs: "HomeServer"):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.store = hs.get_datastore()
self.groups_handler = hs.... |
class GroupsForUserServlet(RestServlet):
PATTERNS = client_patterns("/joined_groups$")
def __init__(self, hs):
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):
... | class GroupsForUserServlet(RestServlet):
PATTERNS = client_patterns("/joined_groups$")
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, ... |
async def on_GET(self, request):
return 200, result
def register_servlets(hs, http_server):
GroupServlet(hs).register(http_server)
GroupSummaryServlet(hs).register(http_server)
GroupInvitedUsersServlet(hs).register(http_server) | async def on_GET(self, request):
return 200, result
def register_servlets(hs: "HomeServer", http_server):
GroupServlet(hs).register(http_server)
GroupSummaryServlet(hs).register(http_server)
GroupInvitedUsersServlet(hs).register(http_server) |
async def on_POST(self, request):
body, ["client_secret", "country", "phone_number", "send_attempt"]
)
client_secret = body["client_secret"]
country = body["country"]
phone_number = body["phone_number"]
send_attempt = body["send_attempt"] | async def on_POST(self, request):
body, ["client_secret", "country", "phone_number", "send_attempt"]
)
client_secret = body["client_secret"]
assert_valid_client_secret(client_secret)
country = body["country"]
phone_number = body["phone_number"]
send_attempt = ... |
async def on_GET(self, request, medium):
sid = parse_string(request, "sid", required=True)
client_secret = parse_string(request, "client_secret", required=True)
token = parse_string(request, "token", required=True)
# Attempt to validate a 3PID session | async def on_GET(self, request, medium):
sid = parse_string(request, "sid", required=True)
client_secret = parse_string(request, "client_secret", required=True)
assert_valid_client_secret(client_secret)
token = parse_string(request, "token", required=True)
# Attempt to validate... |
import functools
import logging
import os
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, TypeVar, cast
import twisted.internet.base
import twisted.internet.tcp | import functools
import logging
import os
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
List,
Optional,
TypeVar,
Union,
cast,
)
import twisted.internet.base
import twisted.internet.tcp |
def get_user_directory_handler(self) -> UserDirectoryHandler:
return UserDirectoryHandler(self)
@cache_in_self
def get_groups_local_handler(self):
if self.config.worker_app:
return GroupsLocalWorkerHandler(self)
else: | def get_user_directory_handler(self) -> UserDirectoryHandler:
return UserDirectoryHandler(self)
@cache_in_self
def get_groups_local_handler(
self,
) -> Union[GroupsLocalWorkerHandler, GroupsLocalHandler]:
if self.config.worker_app:
return GroupsLocalWorkerHandler(self)
... |
_string_with_symbols = string.digits + string.ascii_letters + ".,;:^&*-_+=#~@"
# https://matrix.org/docs/spec/client_server/r0.6.0#post-matrix-client-r0-register-email-requesttoken
client_secret_regex = re.compile(r"^[0-9a-zA-Z\.\=\_\-]+$")
# https://matrix.org/docs/spec/client_server/r0.6.1#matrix-content-mxc-uris,
... | _string_with_symbols = string.digits + string.ascii_letters + ".,;:^&*-_+=#~@"
# https://matrix.org/docs/spec/client_server/r0.6.0#post-matrix-client-r0-register-email-requesttoken
CLIENT_SECRET_REGEX = re.compile(r"^[0-9a-zA-Z\.=_\-]+$")
# https://matrix.org/docs/spec/client_server/r0.6.1#matrix-content-mxc-uris,
# ... |
rand = random.SystemRandom()
def random_string(length):
return "".join(rand.choice(string.ascii_letters) for _ in range(length))
def random_string_with_symbols(length):
return "".join(rand.choice(_string_with_symbols) for _ in range(length))
def is_ascii(s):
if isinstance(s, bytes):
try:
... | rand = random.SystemRandom()
def random_string(length: int) -> str:
return "".join(rand.choice(string.ascii_letters) for _ in range(length))
def random_string_with_symbols(length: int) -> str:
return "".join(rand.choice(_string_with_symbols) for _ in range(length))
def is_ascii(s: bytes) -> bool:
try:... |
def split_line(
return
line_str = str(line).strip("\n")
if not line.should_explode and is_line_short_enough(
line, line_length=line_length, line_str=line_str
):
yield line
return | def split_line(
return
line_str = str(line).strip("\n")
# we don't want to split special comments like type annotations
# https://github.com/python/typing/issues/186
has_special_comment = False
for leaf in line.leaves:
for comment in line.comments_after(leaf):
if leaf.t... |
def is_import(leaf: Leaf) -> bool:
)
def normalize_prefix(leaf: Leaf, *, inside_brackets: bool) -> None:
"""Leave existing extra newlines if not `inside_brackets`. Remove everything
else. | def is_import(leaf: Leaf) -> bool:
)
def is_special_comment(leaf: Leaf) -> bool:
"""Return True if the given leaf is a special comment.
Only returns true for type comments for now."""
t = leaf.type
v = leaf.value
return bool(
(t == token.COMMENT or t == STANDALONE_COMMENT) and (v.start... |
def ensure_visible(leaf: Leaf) -> None:
def should_explode(line: Line, opening_bracket: Leaf) -> bool:
"""Should `line` immediately be split with `delimiter_split()` after RHS?"""
if not (
opening_bracket.parent
and opening_bracket.parent.type in {syms.atom, syms.import_from} | def ensure_visible(leaf: Leaf) -> None:
def should_explode(line: Line, opening_bracket: Leaf) -> bool:
"""Should `line` immediately be split with `delimiter_split()` after RHS?"""
if not (
opening_bracket.parent
and opening_bracket.parent.type in {syms.atom, syms.import_from} |
class BlackTestCase(unittest.TestCase):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, line_length=ll)
@patch("black.dump_to_file", dump_to_stderr)
def test_cantfit(self) -> None:
source, expected = read_data("cantfit") | class BlackTestCase(unittest.TestCase):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, line_length=ll)
@patch("black.dump_to_file", dump_to_stderr)
def test_comments6(self) -> None:
source, expected = read_data("comments6")
actual = fs(source)
... |
def Ghostscript(tile, size, fp, scale=1):
import tempfile, os, subprocess
file = tempfile.mktemp()
# Build ghostscript command
command = ["gs", | def Ghostscript(tile, size, fp, scale=1):
import tempfile, os, subprocess
out_fd, file = tempfile.mkstemp()
os.close(out_fd)
# Build ghostscript command
command = ["gs", |
class Image:
self.readonly = 0
def _dump(self, file=None, format=None):
import tempfile
if not file:
file = tempfile.mktemp()
self.load()
if not format or format == "PPM":
self.im.save_ppm(file)
else:
file = file + "." + format
... | class Image:
self.readonly = 0
def _dump(self, file=None, format=None):
import tempfile, os
if not file:
f, file = tempfile.mkstemp(format or '')
os.close(f)
self.load()
if not format or format == "PPM":
self.im.save_ppm(file)... |
class IptcImageFile(ImageFile.ImageFile):
self.fp.seek(offset)
# Copy image data to temporary file
outfile = tempfile.mktemp()
o = open(outfile, "wb")
if encoding == "raw":
# To simplify access to the extracted file,
# prepend a PPM header | class IptcImageFile(ImageFile.ImageFile):
self.fp.seek(offset)
# Copy image data to temporary file
o_fd, outfile = tempfile.mkstemp(text=False)
o = os.fdopen(o_fd)
if encoding == "raw":
# To simplify access to the extracted file,
# prepend a PPM header |
class JpegImageFile(ImageFile.ImageFile):
# ALTERNATIVE: handle JPEGs via the IJG command line utilities
import tempfile, os
file = tempfile.mktemp()
os.system("djpeg %s >%s" % (self.filename, file))
try:
self.im = Image.core.open_ppm(file)
finally:
... | class JpegImageFile(ImageFile.ImageFile):
# ALTERNATIVE: handle JPEGs via the IJG command line utilities
import tempfile, os
f, path = tempfile.mkstemp()
os.close(f)
if os.path.exists(self.filename):
os.system("djpeg '%s' >'%s'" % (self.filename, path))
else:... |
def _recast_datetimelike_result(result: DataFrame) -> DataFrame:
result = result.copy()
obj_cols = [
idx for idx in range(len(result.columns)) if is_object_dtype(result.dtypes[idx])
]
# See GH#26285 | def _recast_datetimelike_result(result: DataFrame) -> DataFrame:
result = result.copy()
obj_cols = [
idx
for idx in range(len(result.columns))
if is_object_dtype(result.dtypes.iloc[idx])
]
# See GH#26285 |
def test_apply_with_mixed_types():
result = g.apply(lambda x: x / x.sum())
tm.assert_frame_equal(result, expected) | def test_apply_with_mixed_types():
result = g.apply(lambda x: x / x.sum())
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
"group_column_dtlike",
[datetime.today(), datetime.today().date(), datetime.today().time()],
)
def test_apply_datetime_issue(group_column_dtlike):
# GH-2824... |
from django.utils.cache import (
)
from django.utils.deprecation import MiddlewareMixin, RemovedInDjango21Warning
from django.utils.encoding import force_text
from django.utils.six.moves.urllib.parse import urlparse
| from django.utils.cache import (
)
from django.utils.deprecation import MiddlewareMixin, RemovedInDjango21Warning
from django.utils.encoding import force_text
from django.utils.http import escape_leading_slashes
from django.utils.six.moves.urllib.parse import urlparse
|
class CommonMiddleware(MiddlewareMixin):
POST, PUT, or PATCH.
"""
new_path = request.get_full_path(force_append_slash=True)
if settings.DEBUG and request.method in ('POST', 'PUT', 'PATCH'):
raise RuntimeError(
"You called this URL via %(method)s, but the URL d... | class CommonMiddleware(MiddlewareMixin):
POST, PUT, or PATCH.
"""
new_path = request.get_full_path(force_append_slash=True)
# Prevent construction of scheme relative urls.
new_path = escape_leading_slashes(new_path)
if settings.DEBUG and request.method in ('POST', 'PUT', ... |
from django.utils import lru_cache, six
from django.utils.datastructures import MultiValueDict
from django.utils.encoding import force_str, force_text
from django.utils.functional import cached_property
from django.utils.http import RFC3986_SUBDELIMS, urlquote
from django.utils.regex_helper import normalize
from django... | from django.utils import lru_cache, six
from django.utils.datastructures import MultiValueDict
from django.utils.encoding import force_str, force_text
from django.utils.functional import cached_property
from django.utils.http import (
RFC3986_SUBDELIMS, escape_leading_slashes, urlquote,
)
from django.utils.regex_he... |
class RegexURLResolver(LocaleRegexProvider):
# safe characters from `pchar` definition of RFC 3986
url = urlquote(candidate_pat % candidate_subs, safe=RFC3986_SUBDELIMS + str('/~:@'))
# Don't allow construction of scheme relative urls.
if u... | class RegexURLResolver(LocaleRegexProvider):
# safe characters from `pchar` definition of RFC 3986
url = urlquote(candidate_pat % candidate_subs, safe=RFC3986_SUBDELIMS + str('/~:@'))
# Don't allow construction of scheme relative urls.
retu... |
def limited_parse_qsl(qs, keep_blank_values=False, encoding='utf-8',
value = unquote(nv[1].replace(b'+', b' '))
r.append((name, value))
return r | def limited_parse_qsl(qs, keep_blank_values=False, encoding='utf-8',
value = unquote(nv[1].replace(b'+', b' '))
r.append((name, value))
return r
def escape_leading_slashes(url):
"""
If redirecting to an absolute path (two leading slashes), a slash must be
escaped to prevent... |
class CommonMiddlewareTest(SimpleTestCase):
self.assertEqual(r.status_code, 301)
self.assertEqual(r.url, '/needsquoting%23/')
@override_settings(APPEND_SLASH=False, PREPEND_WWW=True)
def test_prepend_www(self):
request = self.rf.get('/path/') | class CommonMiddlewareTest(SimpleTestCase):
self.assertEqual(r.status_code, 301)
self.assertEqual(r.url, '/needsquoting%23/')
@override_settings(APPEND_SLASH=True)
def test_append_slash_leading_slashes(self):
"""
Paths starting with two slashes are escaped to prevent open redire... |
urlpatterns = [
url(r'^noslash$', views.empty_view),
url(r'^slash/$', views.empty_view),
url(r'^needsquoting#/$', views.empty_view),
] | urlpatterns = [
url(r'^noslash$', views.empty_view),
url(r'^slash/$', views.empty_view),
url(r'^needsquoting#/$', views.empty_view),
# Accepts paths with two leading slashes.
url(r'^(.+)/security/$', views.empty_view),
] |
class HttpDateProcessingTests(unittest.TestCase):
def test_parsing_asctime(self):
parsed = http.parse_http_date('Sun Nov 6 08:49:37 1994')
self.assertEqual(datetime.utcfromtimestamp(parsed), datetime(1994, 11, 6, 8, 49, 37)) | class HttpDateProcessingTests(unittest.TestCase):
def test_parsing_asctime(self):
parsed = http.parse_http_date('Sun Nov 6 08:49:37 1994')
self.assertEqual(datetime.utcfromtimestamp(parsed), datetime(1994, 11, 6, 8, 49, 37))
class EscapeLeadingSlashesTests(unittest.TestCase):
def test(self):
... |
def repercent_broken_unicode(path):
repercent-encode any octet produced that is not part of a strictly legal
UTF-8 octet sequence.
"""
try:
path.decode()
except UnicodeDecodeError as e:
repercent = quote(path[e.start:e.end], safe=b"/#%[]=:;$&()+,!?*@'~")
path = repercent_brok... | def repercent_broken_unicode(path):
repercent-encode any octet produced that is not part of a strictly legal
UTF-8 octet sequence.
"""
while True:
try:
path.decode()
except UnicodeDecodeError as e:
# CVE-2019-14235: A recursion shouldn't be used since the exceptio... |
import datetime
import unittest
from unittest import mock
from urllib.parse import quote_plus | import datetime
import sys
import unittest
from unittest import mock
from urllib.parse import quote_plus |
from urllib.parse import quote_plus
from django.test import SimpleTestCase
from django.utils.encoding import (
DjangoUnicodeDecodeError, escape_uri_path, filepath_to_uri, force_bytes,
force_str, get_system_encoding, iri_to_uri, smart_bytes, smart_str,
uri_to_iri,
)
from django.utils.functional import Simple... | from urllib.parse import quote_plus
from django.test import SimpleTestCase
from django.utils.encoding import (
DjangoUnicodeDecodeError, escape_uri_path, filepath_to_uri, force_bytes,
force_str, get_system_encoding, iri_to_uri, repercent_broken_unicode,
smart_bytes, smart_str, uri_to_iri,
)
from django.util... |
class TestEncodingUtils(SimpleTestCase):
with mock.patch('locale.getdefaultlocale', side_effect=Exception):
self.assertEqual(get_system_encoding(), 'ascii')
class TestRFC3987IEncodingUtils(unittest.TestCase):
| class TestEncodingUtils(SimpleTestCase):
with mock.patch('locale.getdefaultlocale', side_effect=Exception):
self.assertEqual(get_system_encoding(), 'ascii')
def test_repercent_broken_unicode_recursion_error(self):
# Prepare a string long enough to force a recursion error if the tested
... |
class HttpRequest:
def scheme(self):
if settings.SECURE_PROXY_SSL_HEADER:
try:
header, value = settings.SECURE_PROXY_SSL_HEADER
except ValueError:
raise ImproperlyConfigured(
'The SECURE_PROXY_SSL_HEADER setting must be a tuple cont... | class HttpRequest:
def scheme(self):
if settings.SECURE_PROXY_SSL_HEADER:
try:
header, secure_value = settings.SECURE_PROXY_SSL_HEADER
except ValueError:
raise ImproperlyConfigured(
'The SECURE_PROXY_SSL_HEADER setting must be a tup... |
class SecureProxySslHeaderTest(SimpleTestCase):
req.META['HTTP_X_FORWARDED_PROTOCOL'] = 'https'
self.assertIs(req.is_secure(), True)
class IsOverriddenTest(SimpleTestCase):
def test_configure(self): | class SecureProxySslHeaderTest(SimpleTestCase):
req.META['HTTP_X_FORWARDED_PROTOCOL'] = 'https'
self.assertIs(req.is_secure(), True)
@override_settings(SECURE_PROXY_SSL_HEADER=('HTTP_X_FORWARDED_PROTOCOL', 'https'))
def test_xheader_preferred_to_underlying_request(self):
class ProxyRequ... |
from RestrictedPython.Utilities import utility_builtins
from zExceptions import Unauthorized
from AccessControl.SecurityInfo import secureModule
from AccessControl.SecurityManagement import getSecurityManager
from AccessControl.SimpleObjectPolicies import ContainerAssertions | from RestrictedPython.Utilities import utility_builtins
from zExceptions import Unauthorized
from AccessControl.SecurityInfo import ModuleSecurityInfo
from AccessControl.SecurityInfo import secureModule
from AccessControl.SecurityManagement import getSecurityManager
from AccessControl.SimpleObjectPolicies import Conta... |
math.__allow_access_to_unprotected_subobjects__ = 1
random.__allow_access_to_unprotected_subobjects__ = 1
# AccessControl.Implementation inserts these names into this module as
# module globals: aq_validate, guarded_getattr
| math.__allow_access_to_unprotected_subobjects__ = 1
random.__allow_access_to_unprotected_subobjects__ = 1
# Mark some unprotected module attributes as private, these should not be
# used in untrusted Python code such as Scripts (Python)
string_modsec = ModuleSecurityInfo('string')
for name in ('Formatter', 'Template')... |
def testAccessToSimpleContainer(self):
c.attr = PublicMethod()
self.assertPolicyAllows(c, 'attr')
def testUnicodeAttributeLookups(self):
item = self.item
r_item = self.a.r_item | def testAccessToSimpleContainer(self):
c.attr = PublicMethod()
self.assertPolicyAllows(c, 'attr')
def testAccessToStringModule(self):
# The string module is available to restricted code and its members are
# explicitly allowed via a
# ``__allow_access_to_unprotected_subobjec... |
def _unstack_multiple(data, clocs, fill_value=None):
comp_ids, obs_ids = compress_group_index(group_index, sort=False)
recons_codes = decons_obs_group_ids(comp_ids, obs_ids, shape, ccodes, xnull=False)
if rlocs == []:
# Everything is in clocs, so the dummy df has a regular index
dummy_index... | def _unstack_multiple(data, clocs, fill_value=None):
comp_ids, obs_ids = compress_group_index(group_index, sort=False)
recons_codes = decons_obs_group_ids(comp_ids, obs_ids, shape, ccodes, xnull=False)
if not rlocs:
# Everything is in clocs, so the dummy df has a regular index
dummy_index =... |
def _unstack_multiple(data, clocs, fill_value=None):
for i in range(len(clocs)):
val = clocs[i]
result = result.unstack(val, fill_value=fill_value)
clocs = [v if i > v else v - 1 for v in clocs]
return result
| def _unstack_multiple(data, clocs, fill_value=None):
for i in range(len(clocs)):
val = clocs[i]
result = result.unstack(val, fill_value=fill_value)
clocs = [v if v < val else v - 1 for v in clocs]
return result
|
class TestDataFrameReshape:
expected.index = expected.index.droplevel("C")
tm.assert_frame_equal(result, expected)
def test_unstack_nan_index(self): # GH7466
def cast(val):
val_str = "" if val != val else val | class TestDataFrameReshape:
expected.index = expected.index.droplevel("C")
tm.assert_frame_equal(result, expected)
def test_unstack_long_index(self):
# PH 32624: Error when using a lot of indices to unstack.
# The error occurred only, if a lot of indices are used.
df = pd.Da... |
from django.contrib.gis.db.models.fields import ExtentField
from django.db.models.aggregates import Aggregate
__all__ = ['Collect', 'Extent', 'Extent3D', 'MakeLine', 'Union'] | from django.contrib.gis.db.models.fields import ExtentField
from django.db.models import Value
from django.db.models.aggregates import Aggregate
__all__ = ['Collect', 'Extent', 'Extent3D', 'MakeLine', 'Union'] |
class GeoAggregate(Aggregate):
return super(GeoAggregate, self).as_sql(compiler, connection)
def as_oracle(self, compiler, connection):
if not hasattr(self, 'tolerance'):
self.tolerance = 0.05
self.extra['tolerance'] = self.tolerance
if not self.is_extent:
se... | class GeoAggregate(Aggregate):
return super(GeoAggregate, self).as_sql(compiler, connection)
def as_oracle(self, compiler, connection):
if not self.is_extent:
tolerance = self.extra.get('tolerance') or getattr(self, 'tolerance', 0.05)
clone = self.copy()
expressi... |
class OracleToleranceMixin(object):
tolerance = 0.05
def as_oracle(self, compiler, connection):
tol = self.extra.get('tolerance', self.tolerance)
self.template = "%%(function)s(%%(expressions)s, %s)" % tol
return super(OracleToleranceMixin, self).as_sql(compiler, connection)
| class OracleToleranceMixin(object):
tolerance = 0.05
def as_oracle(self, compiler, connection):
tol = self._handle_param(
self.extra.get('tolerance', self.tolerance),
'tolerance',
NUMERIC_TYPES,
)
self.template = "%%(function)s(%%(expressions)s, %s)" ... |
from __future__ import unicode_literals
from unittest import skipIf
from django.contrib.gis.db.models.functions import (
Area, Distance, Length, Perimeter, Transform, | from __future__ import unicode_literals
from unittest import skipIf, skipUnless
from django.contrib.gis.db.models.functions import (
Area, Distance, Length, Perimeter, Transform, |
class DistanceFunctionsTests(TestCase):
for i, c in enumerate(qs):
self.assertAlmostEqual(sphere_distances[i], c.distance.m, tol)
@no_oracle # Oracle already handles geographic distance calculation.
@skipUnlessDBFeature("has_Distance_function", 'has_Transform_function')
def tes... | class DistanceFunctionsTests(TestCase):
for i, c in enumerate(qs):
self.assertAlmostEqual(sphere_distances[i], c.distance.m, tol)
@skipUnless(
connection.vendor == 'oracle',
'Oracle supports tolerance paremeter.',
)
def test_distance_function_tolerance_escaping(s... |
from __future__ import unicode_literals
import re
import tempfile
from django.contrib.gis import gdal
from django.contrib.gis.db.models import Extent, MakeLine, Union | from __future__ import unicode_literals
import re
import tempfile
import unittest
from django.contrib.gis import gdal
from django.contrib.gis.db.models import Extent, MakeLine, Union |
from django.contrib.gis.geos import (
MultiPoint, MultiPolygon, Point, Polygon, fromstr,
)
from django.core.management import call_command
from django.db import connection
from django.test import TestCase, ignore_warnings, skipUnlessDBFeature
from django.utils import six
from django.utils.deprecation import Removed... | from django.contrib.gis.geos import (
MultiPoint, MultiPolygon, Point, Polygon, fromstr,
)
from django.core.management import call_command
from django.db import DatabaseError, connection
from django.test import TestCase, ignore_warnings, skipUnlessDBFeature
from django.utils import six
from django.utils.deprecation... |
class GeoQuerySetTest(TestCase):
qs = City.objects.filter(name='NotACity')
self.assertIsNone(qs.aggregate(Union('point'))['point__union'])
def test_within_subquery(self):
"""
Using a queryset inside a geo lookup is working (using a subquery) | class GeoQuerySetTest(TestCase):
qs = City.objects.filter(name='NotACity')
self.assertIsNone(qs.aggregate(Union('point'))['point__union'])
@unittest.skipUnless(
connection.vendor == 'oracle',
'Oracle supports tolerance paremeter.',
)
def test_unionagg_tolerance(self):
... |
def main():
download_set = {}
for pkg in download_list:
remote = pkg.returnSimple('relativepath')
rpmname = os.path.basename(remote)
download_set[rpmname] = 1
for pkg in current_pkgs: | def main():
download_set = {}
for pkg in download_list:
rpmname = os.path.basename(pkg.remote_path)
download_set[rpmname] = 1
for pkg in current_pkgs: |
def main():
remote_size = 0
if not opts.urls:
for pkg in download_list:
remote = pkg.returnSimple('relativepath')
local = local_repo_path + '/' + remote
sz = int(pkg.returnSimple('packagesize'))
if os.path.exists(local) and os.p... | def main():
remote_size = 0
if not opts.urls:
for pkg in download_list:
local = os.path.join(local_repo_path, pkg.remote_path)
sz = int(pkg.returnSimple('packagesize'))
if os.path.exists(local) and os.path.getsize(local) == sz:
... |
def main():
download_list.sort(key=lambda pkg: pkg.name)
if opts.urls:
for pkg in download_list:
remote = pkg.returnSimple('relativepath')
local = os.path.join(local_repo_path, remote)
if not (os.path.exists(local) and my.verifyPkg(local, pkg, ... | def main():
download_list.sort(key=lambda pkg: pkg.name)
if opts.urls:
for pkg in download_list:
local = os.path.join(local_repo_path, pkg.remote_path)
if not (os.path.exists(local) and my.verifyPkg(local, pkg, False)):
print urljoin(pkg.re... |
def main():
# set localpaths
for pkg in download_list:
rpmfn = pkg.remote_path
pkg.localpath = os.path.join(local_repo_path, rpmfn)
pkg.repo.copy_local = True
pkg.repo.cache = 0
localdir = os.path.dirname(pkg.localpath) | def main():
# set localpaths
for pkg in download_list:
pkg.localpath = os.path.join(local_repo_path, pkg.remote_path)
pkg.repo.copy_local = True
pkg.repo.cache = 0
localdir = os.path.dirname(pkg.localpath) |
class TestJSInterpreter(unittest.TestCase):
}''')
self.assertEqual(jsi.call_function('x'), [20, 20, 30, 40, 50])
if __name__ == '__main__':
unittest.main() | class TestJSInterpreter(unittest.TestCase):
}''')
self.assertEqual(jsi.call_function('x'), [20, 20, 30, 40, 50])
def test_call(self):
jsi = JSInterpreter('''
function x() { return 2; }
function y(a) { return x() + a; }
function z() { return y(3); }
''')
... |
class JSInterpreter(object):
return opfunc(x, y)
m = re.match(
r'^(?P<func>%s)\((?P<args>[a-zA-Z0-9_$,]+)\)$' % _NAME_RE, expr)
if m:
fname = m.group('func')
argvals = tuple([
int(v) if v.isdigit() else local_vars[v]
for v ... | class JSInterpreter(object):
return opfunc(x, y)
m = re.match(
r'^(?P<func>%s)\((?P<args>[a-zA-Z0-9_$,]*)\)$' % _NAME_RE, expr)
if m:
fname = m.group('func')
argvals = tuple([
int(v) if v.isdigit() else local_vars[v]
for v ... |
def format_sizeof(num, suffix=''):
Number with Order of Magnitude SI unit postfix.
"""
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
if abs(num) < 1000.0:
if abs(num) < 100.0:
if abs(num) < 10.0:
return '{0:1.2f}'.format(num) + unit + suffix... | def format_sizeof(num, suffix=''):
Number with Order of Magnitude SI unit postfix.
"""
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
if abs(num) < 999.95:
if abs(num) < 99.95:
if abs(num) < 9.995:
return '{0:1.2f}'.format(num) + unit + suffi... |
class tqdm(object):
if ascii is None:
ascii = not _supports_unicode(file)
if gui: # pragma: no cover
try:
import matplotlib as mpl
import matplotlib.pyplot as plt | class tqdm(object):
if ascii is None:
ascii = not _supports_unicode(file)
if gui: # pragma: no cover
try:
import matplotlib as mpl
import matplotlib.pyplot as plt |
class tqdm(object):
self.unit_scale = unit_scale
self.gui = gui
if gui: # pragma: no cover
# Initialize the GUI display
if not disable:
file.write('Warning: GUI is experimental/alpha\n') | class tqdm(object):
self.unit_scale = unit_scale
self.gui = gui
if gui: # pragma: no cover
# Initialize the GUI display
if not disable:
file.write('Warning: GUI is experimental/alpha\n') |
class tqdm(object):
self.n = 0
def __len__(self):
return len(self.iterable)
def __iter__(self):
''' Backward-compatibility to use: for x in tqdm(iterable) ''' | class tqdm(object):
self.n = 0
def __len__(self):
return len(self.iterable) if self.iterable else self.total
def __iter__(self):
''' Backward-compatibility to use: for x in tqdm(iterable) ''' |
class tqdm(object):
last_print_n = self.last_print_n
n = self.n
gui = self.gui
if gui: # pragma: no cover
plt = self.plt
ax = self.ax
xdata = self.xdata | class tqdm(object):
last_print_n = self.last_print_n
n = self.n
gui = self.gui
if gui: # pragma: no cover
plt = self.plt
ax = self.ax
xdata = self.xdata |
class tqdm(object):
delta_t = cur_t - last_print_t
if delta_t >= mininterval:
elapsed = cur_t - start_t
if gui: # pragma: no cover
# Inline due to multiple calls
total = self.t... | class tqdm(object):
delta_t = cur_t - last_print_t
if delta_t >= mininterval:
elapsed = cur_t - start_t
if gui: # pragma: no cover
# Inline due to multiple calls
total = self.... |
def test_format_meter():
" 10% 100/1000 [00:12<01:48, 8.33it/s]"
def test_all_defaults():
for i in tqdm(range(10)):
pass
import sys
sys.stderr.write('tests_tqdm.test_all_defaults ... ') | def test_format_meter():
" 10% 100/1000 [00:12<01:48, 8.33it/s]"
def test_si_format():
""" Test SI unit prefixes """
assert '9.00 ' in format_meter(1, 9, 1, unit_scale=True, unit='B')
assert '99.0 ' in format_meter(1, 99, 1, unit_scale=True)
assert '999 ' in format_meter(1, 999, 1, unit_scale... |
def test_update():
""" Test manual creation and updates """
our_file = StringIO()
progressbar = tqdm(total=2, file=our_file, miniters=1)
progressbar.update(2)
our_file.seek(0)
assert '| 2/2' in our_file.read() | def test_update():
""" Test manual creation and updates """
our_file = StringIO()
progressbar = tqdm(total=2, file=our_file, miniters=1)
assert len(progressbar) == 2
progressbar.update(2)
our_file.seek(0)
assert '| 2/2' in our_file.read() |
class S3CopyToTable(rdbms.CopyToTable, _CredentialsMixin):
"""
logger.info("Inserting file: %s", f)
colnames = ''
if len(self.columns) > 0:
colnames = ",".join([x[0] for x in self.columns])
colnames = '({})'.format(colnames)
| class S3CopyToTable(rdbms.CopyToTable, _CredentialsMixin):
"""
logger.info("Inserting file: %s", f)
colnames = ''
if self.columns and len(self.columns) > 0:
colnames = ",".join([x[0] for x in self.columns])
colnames = '({})'.format(colnames)
|
class DummyS3CopyToTableBase(luigi.contrib.redshift.S3CopyToTable):
user = 'dummy_user'
password = 'dummy_password'
table = luigi.Parameter(default='dummy_table')
columns = (
('some_text', 'varchar(255)'),
('some_int', 'int'),
)
copy_options = '' | class DummyS3CopyToTableBase(luigi.contrib.redshift.S3CopyToTable):
user = 'dummy_user'
password = 'dummy_password'
table = luigi.Parameter(default='dummy_table')
columns = luigi.TupleParameter(
default=(
('some_text', 'varchar(255)'),
('some_int', 'int'),
)
)... |
class TestS3CopyToTable(unittest.TestCase):
(task.table,),
)
class TestS3CopyToSchemaTable(unittest.TestCase):
@mock.patch("luigi.contrib.redshift.S3CopyToTable.copy") | class TestS3CopyToTable(unittest.TestCase):
(task.table,),
)
@mock.patch("luigi.contrib.redshift.RedshiftTarget")
def test_s3_copy_with_valid_columns(self, mock_redshift_target):
task = DummyS3CopyToTableKey()
task.run()
# The mocked connection cursor passed to
... |
import sys
import types
import importlib
from xml.etree import ElementTree
# we do not use this ourselves, but mock methods often want to use this | import sys
import types
import importlib
import imp
from xml.etree import ElementTree
# we do not use this ourselves, but mock methods often want to use this |
def load_module(name):
if os.path.exists(name) and os.path.splitext(name)[1] == '.py':
sys.path.insert(0, os.path.dirname(os.path.abspath(name)))
try:
m = os.path.splitext(os.path.basename(name))[0]
module = importlib.import_module(m)
finally:
sys.path.po... |
def load_module(name):
if os.path.exists(name) and os.path.splitext(name)[1] == '.py':
mod = imp.new_module(os.path.splitext(os.path.basename(name))[0])
with open(name) as f:
exec(f.read(), mod.__dict__, mod.__dict__)
return mod
return importlib.import_module('dbusmock.temp... |
def load(mock, parameters):
self.addCleanup(p_mock.terminate)
self.addCleanup(p_mock.stdout.close)
self.assertEqual(dbus_ultimate.Answer(), 42)
# should appear in introspection | def load(mock, parameters):
self.addCleanup(p_mock.terminate)
self.addCleanup(p_mock.stdout.close)
# ensure that we don't use/write any .pyc files, they are dangerous
# in a world-writable directory like /tmp
self.assertFalse(os.path.exists(my_template.name +... |
class TestUtil(unittest.TestCase):
"playlist":[{"controls":{"all":null}}]
}''')
inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
json_code = js_to_json(inp)
self.assertEqual(json.loads(json_code... | class TestUtil(unittest.TestCase):
"playlist":[{"controls":{"all":null}}]
}''')
inp = '''"The CW\\'s \\'Crazy Ex-Girlfriend\\'"'''
self.assertEqual(js_to_json(inp), '''"The CW's 'Crazy Ex-Girlfriend'"''')
inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabaner... |
def js_to_json(code):
if v in ('true', 'false', 'null'):
return v
if v.startswith('"'):
return v
if v.startswith("'"):
v = v[1:-1]
v = re.sub(r"\\\\|\\'|\"", lambda m: {
'\\\\': '\\\\', | def js_to_json(code):
if v in ('true', 'false', 'null'):
return v
if v.startswith('"'):
v = re.sub(r"\\'", "'", v[1:-1])
elif v.startswith("'"):
v = v[1:-1]
v = re.sub(r"\\\\|\\'|\"", lambda m: {
'\\\\': '\\\\', |
class ReduceLROnPlateau(Callback):
monitored has stopped increasing; in `auto`
mode, the direction is automatically inferred
from the name of the monitored quantity.
epsilon: threshold for measuring the new optimum,
to only focus on significant changes.
co... | class ReduceLROnPlateau(Callback):
monitored has stopped increasing; in `auto`
mode, the direction is automatically inferred
from the name of the monitored quantity.
min_delta: threshold for measuring the new optimum,
to only focus on significant changes.
... |
class ReduceLROnPlateau(Callback):
"""
def __init__(self, monitor='val_loss', factor=0.1, patience=10,
verbose=0, mode='auto', epsilon=1e-4, cooldown=0, min_lr=0):
super(ReduceLROnPlateau, self).__init__()
self.monitor = monitor
if factor >= 1.0:
raise Valu... | class ReduceLROnPlateau(Callback):
"""
def __init__(self, monitor='val_loss', factor=0.1, patience=10,
verbose=0, mode='auto', min_delta=1e-4, cooldown=0, min_lr=0,
**kwargs):
super(ReduceLROnPlateau, self).__init__()
self.monitor = monitor
if factor >... |
class ReduceLROnPlateau(Callback):
self.mode = 'auto'
if (self.mode == 'min' or
(self.mode == 'auto' and 'acc' not in self.monitor)):
self.monitor_op = lambda a, b: np.less(a, b - self.epsilon)
self.best = np.Inf
else:
self.monitor_op = lambda a... | class ReduceLROnPlateau(Callback):
self.mode = 'auto'
if (self.mode == 'min' or
(self.mode == 'auto' and 'acc' not in self.monitor)):
self.monitor_op = lambda a, b: np.less(a, b - self.min_delta)
self.best = np.Inf
else:
self.monitor_op = lambda... |
class ReduceLROnPlateau(Callback):
self.best = current
self.wait = 0
elif not self.in_cooldown():
if self.wait >= self.patience:
old_lr = float(K.get_value(self.model.optimizer.lr))
if old_lr > self.min_lr: | class ReduceLROnPlateau(Callback):
self.best = current
self.wait = 0
elif not self.in_cooldown():
self.wait += 1
if self.wait >= self.patience:
old_lr = float(K.get_value(self.model.optimizer.lr))
if old_... |
class ReduceLROnPlateau(Callback):
'rate to %s.' % (epoch + 1, new_lr))
self.cooldown_counter = self.cooldown
self.wait = 0
self.wait += 1
def in_cooldown(self):
return self.cooldown_counter > 0 | class ReduceLROnPlateau(Callback):
'rate to %s.' % (epoch + 1, new_lr))
self.cooldown_counter = self.cooldown
self.wait = 0
def in_cooldown(self):
return self.cooldown_counter > 0 |
def test_ReduceLROnPlateau():
model = make_model()
# This should reduce the LR after the first epoch (due to high epsilon).
cbks = [callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.1, epsilon=10, patience=1, cooldown=5)]
model.fit(X_train, y_train, batch_size=batch_size,
validatio... | def test_ReduceLROnPlateau():
model = make_model()
# This should reduce the LR after the first epoch (due to high epsilon).
cbks = [callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.1, min_delta=10, patience=1, cooldown=5)]
model.fit(X_train, y_train, batch_size=batch_size,
validat... |
def wrapped(self, *args, **kwargs):
try:
try:
return_tuple = func(self, *args, **kwargs)
display.vvv(return_tuple, host=self.host)
# 0 = success
# 1-254 = remote command return code
# 255 coul... | def wrapped(self, *args, **kwargs):
try:
try:
return_tuple = func(self, *args, **kwargs)
if self._play_context.no_log:
display.vvv('rc=%s, stdout & stderr censored due to no log' % return_tuple[0], host=self.host)
... |
def wrapped(self, *args, **kwargs):
break
if SSH_ERROR:
raise AnsibleConnectionFailure("Failed to connect to the host via ssh: %s"
% to_native(return_tuple[2]))
break
| def wrapped(self, *args, **kwargs):
break
if SSH_ERROR:
msg = "Failed to connect to the host via ssh: "
if self._play_context.no_log:
msg += '<error censored due to no log>'
... |
import sys
import os
import platform
import math
import binascii |
import sys
import os
import re
import platform
import math
import binascii |
def formatExceptionTrace(e):
"""Return exception information formatted as string"""
return str(e)
else:
# Python 2.6 requires strings instead of bytearrays in a couple places,
# so we define this function so it does the conversion if needed. | def formatExceptionTrace(e):
"""Return exception information formatted as string"""
return str(e)
def remove_whitespace(text):
"""Removes all whitespace from passed in string"""
return re.sub(r"\s+", "", text, flags=re.UNICODE)
else:
# Python 2.6 requires strings instead of byt... |
def formatExceptionTrace(e):
if sys.version_info < (2, 7) or sys.version_info < (2, 7, 4) \
or platform.system() == 'Java':
def compat26Str(x): return str(x)
else:
def compat26Str(x): return x
def compatAscii2Bytes(val):
"""Convert ASCII string to bytes."""
retur... | def formatExceptionTrace(e):
if sys.version_info < (2, 7) or sys.version_info < (2, 7, 4) \
or platform.system() == 'Java':
def compat26Str(x): return str(x)
def remove_whitespace(text):
"""Removes all whitespace from passed in string"""
return re.sub(r"\s+", "",... |
def ct_lt_u32(val_a, val_b):
return (val_a^((val_a^val_b)|(((val_a-val_b)&0xffffffff)^val_b)))>>31
def ct_gt_u32(val_a, val_b):
"""
Return 1 if val_a > val_b, 0 otherwise. Constant time. | def ct_lt_u32(val_a, val_b):
return (val_a^((val_a^val_b)|(((val_a-val_b)&0xffffffff)^val_b)))>>31
def ct_gt_u32(val_a, val_b):
"""
Return 1 if val_a > val_b, 0 otherwise. Constant time. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.