buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
def test_SymLogNorm(): _mask_tester(norm, vals) # Ensure that specifying vmin returns the same result as above norm = mcolors.SymLogNorm(3, vmin=-30, vmax=5, linscale=1.2) normed_vals = norm(vals) assert_array_almost_equal(normed_vals, expected) def test_SymLogNorm_colorbar(): """ Test un...
def test_SymLogNorm(): _mask_tester(norm, vals) # Ensure that specifying vmin returns the same result as above norm = mcolors.SymLogNorm(3, vmin=-30, vmax=5, linscale=1.2, base=np.e) normed_vals = norm(vals) assert_array_almost_equal(normed_vals, expected) # test something more easily checked....
def test_SymLogNorm_single_zero(): Test SymLogNorm to ensure it is not adding sub-ticks to zero label """ fig = plt.figure() norm = mcolors.SymLogNorm(1e-5, vmin=-1, vmax=1) cbar = mcolorbar.ColorbarBase(fig.add_subplot(111), norm=norm) ticks = cbar.get_ticks() assert sum(ticks == 0) == 1
def test_SymLogNorm_single_zero(): Test SymLogNorm to ensure it is not adding sub-ticks to zero label """ fig = plt.figure() norm = mcolors.SymLogNorm(1e-5, vmin=-1, vmax=1, base=np.e) cbar = mcolorbar.ColorbarBase(fig.add_subplot(111), norm=norm) ticks = cbar.get_ticks() assert sum(ticks ==...
def test_ndarray_subclass_norm(recwarn): mydata = data.view(MyArray) for norm in [mcolors.Normalize(), mcolors.LogNorm(), mcolors.SymLogNorm(3, vmax=5, linscale=1), mcolors.Normalize(vmin=mydata.min(), vmax=mydata.max()), mcolors.SymLogNorm(3, vmin=mydata.min(...
def test_ndarray_subclass_norm(recwarn): mydata = data.view(MyArray) for norm in [mcolors.Normalize(), mcolors.LogNorm(), mcolors.SymLogNorm(3, vmax=5, linscale=1, base=np.e), mcolors.Normalize(vmin=mydata.min(), vmax=mydata.max()), mcolors.SymLogNorm(3, vmin=...
fig, ax = plt.subplots(2, 1) pcm = ax[0].pcolormesh(X, Y, Z, norm=colors.SymLogNorm(linthresh=0.03, linscale=0.03, vmin=-1.0, vmax=1.0), cmap='RdBu_r') fig.colorbar(pcm, ax=ax[0], extend='both')
fig, ax = plt.subplots(2, 1) pcm = ax[0].pcolormesh(X, Y, Z, norm=colors.SymLogNorm(linthresh=0.03, linscale=0.03, vmin=-1.0, vmax=1.0, base=10), cmap='RdBu_r') fig.colorbar(pcm, ax=ax[0], extend='both')
class PdfParser: whitespace_or_hex = br"[\000\011\012\014\015\0400-9a-fA-F]" whitespace_optional = whitespace + b"*" whitespace_mandatory = whitespace + b"+" newline_only = br"[\r\n]+" newline = whitespace_optional + newline_only + whitespace_optional re_trailer_end = re.compile( whitesp...
class PdfParser: whitespace_or_hex = br"[\000\011\012\014\015\0400-9a-fA-F]" whitespace_optional = whitespace + b"*" whitespace_mandatory = whitespace + b"+" whitespace_optional_no_nl = br"[\000\011\014\015\040]*" # no "\012" aka "\n" newline_only = br"[\r\n]+" newline = whitespace_optional_no_...
ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4') {'like_count': 190, 'dislike_count': 10})) def test_parse_dfxp_time_expr(self): self.assertEqual(parse_dfxp_time_expr(None), 0.0) self.assertEqual(parse_dfxp_time_expr(''), 0.0) self.assertEqual(parse_dfxp...
ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4') {'like_count': 190, 'dislike_count': 10})) def test_parse_dfxp_time_expr(self): self.assertEqual(parse_dfxp_time_expr(None), None) self.assertEqual(parse_dfxp_time_expr(''), None) self.assertEqual(parse_df...
ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4') <p begin="0" end="1">The following line contains Chinese characters and special symbols</p> <p begin="1" end="2">第二行<br/>♪♪</p> <p begin="2" dur="1"><span>Third<br/>Line</span></p> ...
ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4') <p begin="0" end="1">The following line contains Chinese characters and special symbols</p> <p begin="1" end="2">第二行<br/>♪♪</p> <p begin="2" dur="1"><span>Third<br/>Line</span></p> ...
def match_filter_func(filter_str): def parse_dfxp_time_expr(time_expr): if not time_expr: return 0.0 mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr) if mobj:
def match_filter_func(filter_str): def parse_dfxp_time_expr(time_expr): if not time_expr: return mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr) if mobj:
def dfxp2srt(dfxp_data): raise ValueError('Invalid dfxp/TTML subtitle') for para, index in zip(paras, itertools.count(1)): begin_time = parse_dfxp_time_expr(para.attrib['begin']) end_time = parse_dfxp_time_expr(para.attrib.get('end')) if not end_time: end_time = begin_ti...
def dfxp2srt(dfxp_data): raise ValueError('Invalid dfxp/TTML subtitle') for para, index in zip(paras, itertools.count(1)): begin_time = parse_dfxp_time_expr(para.attrib.get('begin')) end_time = parse_dfxp_time_expr(para.attrib.get('end')) dur = parse_dfxp_time_expr(para.attrib.get('...
from synapse.http.server import finish_request, respond_with_json from synapse.http.site import SynapseRequest from synapse.logging.context import make_deferred_yieldable from synapse.util.stringutils import is_ascii logger = logging.getLogger(__name__)
from synapse.http.server import finish_request, respond_with_json from synapse.http.site import SynapseRequest from synapse.logging.context import make_deferred_yieldable from synapse.util.stringutils import is_ascii, parse_and_validate_server_name logger = logging.getLogger(__name__)
def parse_media_id(request: Request) -> Tuple[str, str, Optional[str]]: try: # The type on postpath seems incorrect in Twisted 21.2.0. postpath: List[bytes] = request.postpath # type: ignore
def parse_media_id(request: Request) -> Tuple[str, str, Optional[str]]: """Parses the server name, media ID and optional file name from the request URI Also performs some rough validation on the server name. Args: request: The `Request`. Returns: A tuple containing the parsed server...
def parse_media_id(request: Request) -> Tuple[str, str, Optional[str]]: server_name = server_name_bytes.decode("utf-8") media_id = media_id_bytes.decode("utf8") file_name = None if len(postpath) > 2: try:
def parse_media_id(request: Request) -> Tuple[str, str, Optional[str]]: server_name = server_name_bytes.decode("utf-8") media_id = media_id_bytes.decode("utf8") # Validate the server name, raising if invalid parse_and_validate_server_name(server_name) file_name = None i...
import functools import os import re from typing import Any, Callable, List, TypeVar, cast NEW_FORMAT_ID_RE = re.compile(r"^\d\d\d\d-\d\d-\d\d")
import functools import os import re import string from typing import Any, Callable, List, TypeVar, Union, cast NEW_FORMAT_ID_RE = re.compile(r"^\d\d\d\d-\d\d-\d\d")
def _wrapped(self: "MediaFilePaths", *args: Any, **kwargs: Any) -> str: return cast(F, _wrapped) class MediaFilePaths: """Describes where files are stored on disk.
def _wrapped(self: "MediaFilePaths", *args: Any, **kwargs: Any) -> str: return cast(F, _wrapped) GetPathMethod = TypeVar( "GetPathMethod", bound=Union[Callable[..., str], Callable[..., List[str]]] ) def _wrap_with_jail_check(func: GetPathMethod) -> GetPathMethod: """Wraps a path-returning method to chec...
class MediaFilePaths: def __init__(self, primary_base_path: str): self.base_path = primary_base_path def local_media_filepath_rel(self, media_id: str) -> str: return os.path.join("local_content", media_id[0:2], media_id[2:4], media_id[4:]) local_media_filepath = _wrap_in_base_path(local_me...
class MediaFilePaths: def __init__(self, primary_base_path: str): self.base_path = primary_base_path # The media store directory, with all symlinks resolved. self.real_base_path = os.path.realpath(primary_base_path) # Refuse to initialize if paths cannot be validated correctly for ...
def local_media_thumbnail_dir(self, media_id: str) -> str: return os.path.join( self.base_path, "local_thumbnails", media_id[0:2], media_id[2:4], media_id[4:], ) def remote_media_filepath_rel(self, server_name: str, file_id: str) -> str: ...
def local_media_thumbnail_dir(self, media_id: str) -> str: return os.path.join( self.base_path, "local_thumbnails", _validate_path_component(media_id[0:2]), _validate_path_component(media_id[2:4]), _validate_path_component(media_id[4:]), ) ...
def remote_media_thumbnail_rel( file_name = "%i-%i-%s-%s-%s" % (width, height, top_level_type, sub_type, method) return os.path.join( "remote_thumbnail", server_name, file_id[0:2], file_id[2:4], file_id[4:], file_name, ) ...
def remote_media_thumbnail_rel( file_name = "%i-%i-%s-%s-%s" % (width, height, top_level_type, sub_type, method) return os.path.join( "remote_thumbnail", _validate_path_component(server_name), _validate_path_component(file_id[0:2]), _validate_path_componen...
def remote_media_thumbnail_rel( # Legacy path that was used to store thumbnails previously. # Should be removed after some time, when most of the thumbnails are stored # using the new path. def remote_media_thumbnail_rel_legacy( self, server_name: str, file_id: str, width: int, height: int, cont...
def remote_media_thumbnail_rel( # Legacy path that was used to store thumbnails previously. # Should be removed after some time, when most of the thumbnails are stored # using the new path. @_wrap_with_jail_check def remote_media_thumbnail_rel_legacy( self, server_name: str, file_id: str, wi...
def remote_media_thumbnail_rel_legacy( file_name = "%i-%i-%s-%s" % (width, height, top_level_type, sub_type) return os.path.join( "remote_thumbnail", server_name, file_id[0:2], file_id[2:4], file_id[4:], file_name, ) de...
def remote_media_thumbnail_rel_legacy( file_name = "%i-%i-%s-%s" % (width, height, top_level_type, sub_type) return os.path.join( "remote_thumbnail", _validate_path_component(server_name), _validate_path_component(file_id[0:2]), _validate_path_component(fi...
def url_cache_thumbnail_rel( if NEW_FORMAT_ID_RE.match(media_id): return os.path.join( "url_cache_thumbnails", media_id[:10], media_id[11:], file_name ) else: return os.path.join( "url_cache_thumbnails", media_id[0:2], ...
def url_cache_thumbnail_rel( if NEW_FORMAT_ID_RE.match(media_id): return os.path.join( "url_cache_thumbnails", _validate_path_component(media_id[:10]), _validate_path_component(media_id[11:]), _validate_path_component(file_name), ...
def url_cache_thumbnail_dirs_to_delete(self, media_id: str) -> List[str]: if NEW_FORMAT_ID_RE.match(media_id): return [ os.path.join( self.base_path, "url_cache_thumbnails", media_id[:10], media_id[11:] ), os.path.join(self.base_pat...
def url_cache_thumbnail_dirs_to_delete(self, media_id: str) -> List[str]: if NEW_FORMAT_ID_RE.match(media_id): return [ os.path.join( self.base_path, "url_cache_thumbnails", _validate_path_component(media_id[:10]), ...
from collections.abc import Iterable from typing import Optional, Tuple from synapse.api.errors import Codes, SynapseError _string_with_symbols = string.digits + string.ascii_letters + ".,;:^&*-_+=#~@"
from collections.abc import Iterable from typing import Optional, Tuple from netaddr import valid_ipv6 from synapse.api.errors import Codes, SynapseError _string_with_symbols = string.digits + string.ascii_letters + ".,;:^&*-_+=#~@"
def parse_server_name(server_name: str) -> Tuple[str, Optional[int]]: raise ValueError("Invalid server name '%s'" % server_name) VALID_HOST_REGEX = re.compile("\\A[0-9a-zA-Z.-]+\\Z") def parse_and_validate_server_name(server_name: str) -> Tuple[str, Optional[int]]:
def parse_server_name(server_name: str) -> Tuple[str, Optional[int]]: raise ValueError("Invalid server name '%s'" % server_name) # An approximation of the domain name syntax in RFC 1035, section 2.3.1. # NB: "\Z" is not equivalent to "$". # The latter will match the position before a "\n" at the end of a ...
def parse_and_validate_server_name(server_name: str) -> Tuple[str, Optional[int] if host[0] == "[": if host[-1] != "]": raise ValueError("Mismatched [...] in server name '%s'" % (server_name,)) return host, port # otherwise it should only be alphanumerics. if not VALID_HOST_REGE...
def parse_and_validate_server_name(server_name: str) -> Tuple[str, Optional[int] if host[0] == "[": if host[-1] != "]": raise ValueError("Mismatched [...] in server name '%s'" % (server_name,)) # valid_ipv6 raises when given an empty string ipv6_address = host[1:-1] if n...
def test_validate_bad_server_names(self): "localhost:http", # non-numeric port "1234]", # smells like ipv6 literal but isn't "[1234", "underscore_.com", "percent%65.com", "1234:5678:80", # too many colons ] for i in test_data:
def test_validate_bad_server_names(self): "localhost:http", # non-numeric port "1234]", # smells like ipv6 literal but isn't "[1234", "[1.2.3.4]", "underscore_.com", "percent%65.com", "newline.com\n", ".empty-label.com", ...
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from synapse.rest.media.v1.filepath import MediaFilePaths from tests import unittest
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import inspect from typing import Iterable from synapse.rest.media.v1.filepath import MediaFilePaths from tests import unittest
def test_url_cache_thumbnail_dirs_to_delete_legacy(self): "/media_store/url_cache_thumbnails/Ge", ], )
def test_url_cache_thumbnail_dirs_to_delete_legacy(self): "/media_store/url_cache_thumbnails/Ge", ], ) def test_server_name_validation(self): """Test validation of server names""" self._test_path_validation( [ "remote_media_filepath_re...
import functools import http from typing import Any, Awaitable, Callable, Iterable, Optional, Tuple, Union, cast
import functools import hmac import http from typing import Any, Awaitable, Callable, Iterable, Optional, Tuple, Union, cast
def basic_auth_protocol_factory( if credentials is not None: if is_credentials(credentials): async def check_credentials(username: str, password: str) -> bool: return (username, password) == credentials elif isinstance(credentials, Iterable): credentials_li...
def basic_auth_protocol_factory( if credentials is not None: if is_credentials(credentials): credentials_list = [cast(Credentials, credentials)] elif isinstance(credentials, Iterable): credentials_list = list(credentials) if not all(is_credentials(item) for item ...
async def check_credentials(username: str, password: str) -> bool: ) return functools.partial( create_protocol, realm=realm, check_credentials=check_credentials )
async def check_credentials(username: str, password: str) -> bool: ) return functools.partial( create_protocol, realm=realm, check_credentials=check_credentials, )
import unittest import urllib.error
import hmac import unittest import urllib.error
def test_basic_auth_bad_multiple_credentials(self): ) async def check_credentials(username, password): return password == "iloveyou" create_protocol_check_credentials = basic_auth_protocol_factory( realm="auth-tests",
def test_basic_auth_bad_multiple_credentials(self): ) async def check_credentials(username, password): return hmac.compare_digest(password, "iloveyou") create_protocol_check_credentials = basic_auth_protocol_factory( realm="auth-tests",
def test_basic_auth_unsupported_credentials_details(self): self.assertEqual(raised.exception.read().decode(), "Unsupported credentials\n") @with_server(create_protocol=create_protocol) def test_basic_auth_invalid_credentials(self): with self.assertRaises(InvalidStatusCode) as raised: ...
def test_basic_auth_unsupported_credentials_details(self): self.assertEqual(raised.exception.read().decode(), "Unsupported credentials\n") @with_server(create_protocol=create_protocol) def test_basic_auth_invalid_username(self): with self.assertRaises(InvalidStatusCode) as raised: s...
) from .jwks_client import PyJWKClient __version__ = "2.3.0" __title__ = "PyJWT" __description__ = "JSON Web Token implementation in Python"
) from .jwks_client import PyJWKClient __version__ = "2.4.0" __title__ = "PyJWT" __description__ = "JSON Web Token implementation in Python"
der_to_raw_signature, force_bytes, from_base64url_uint, raw_to_der_signature, to_base64url_uint, )
der_to_raw_signature, force_bytes, from_base64url_uint, is_pem_format, is_ssh_key, raw_to_der_signature, to_base64url_uint, )
def __init__(self, hash_alg): def prepare_key(self, key): key = force_bytes(key) invalid_strings = [ b"-----BEGIN PUBLIC KEY-----", b"-----BEGIN CERTIFICATE-----", b"-----BEGIN RSA PUBLIC KEY-----", b"ssh-rsa", ] if any(string_value i...
def __init__(self, hash_alg): def prepare_key(self, key): key = force_bytes(key) if is_pem_format(key) or is_ssh_key(key): raise InvalidKeyError( "The specified key is an asymmetric key or x509 certificate and" " should not be used as an HMAC secret."
def __init__(self, **kwargs): pass def prepare_key(self, key): if isinstance( key, (Ed25519PrivateKey, Ed25519PublicKey, Ed448PrivateKey, Ed448PublicKey), ): return key if isinstance(key, (bytes, str)): ...
def __init__(self, **kwargs): pass def prepare_key(self, key): if isinstance(key, (bytes, str)): if isinstance(key, str): key = key.encode("utf-8") str_key = key.decode("utf-8") if "-----BEGIN PUBLIC" in str_key: ...
import base64 import binascii from typing import Any, Union try:
import base64 import binascii import re from typing import Any, Union try:
def raw_to_der_signature(raw_sig: bytes, curve: EllipticCurve) -> bytes: s = bytes_to_number(raw_sig[num_bytes:]) return encode_dss_signature(r, s)
def raw_to_der_signature(raw_sig: bytes, curve: EllipticCurve) -> bytes: s = bytes_to_number(raw_sig[num_bytes:]) return encode_dss_signature(r, s) # Based on https://github.com/hynek/pem/blob/7ad94db26b0bc21d10953f5dbad3acfdfacf57aa/src/pem/_core.py#L224-L252 _PEMS = { b"CERTIFICATE", b"TRUSTED CERT...
class TestOKPAlgorithms: def test_okp_ed25519_should_reject_non_string_key(self): algo = OKPAlgorithm() with pytest.raises(TypeError): algo.prepare_key(None) with open(key_path("testkey_ed25519")) as keyfile:
class TestOKPAlgorithms: def test_okp_ed25519_should_reject_non_string_key(self): algo = OKPAlgorithm() with pytest.raises(InvalidKeyError): algo.prepare_key(None) with open(key_path("testkey_ed25519")) as keyfile:
def _create_powershell_wrapper(b_module_data, module_args, environment, exec_manifest['csharp_utils'][name] = b64_data exec_manifest['csharp_utils_module'] = list(finder.cs_utils_module.keys()) # FUTURE: smuggle this back as a dict instead of serializing here; # the connection plugin may need to mo...
def _create_powershell_wrapper(b_module_data, module_args, environment, exec_manifest['csharp_utils'][name] = b64_data exec_manifest['csharp_utils_module'] = list(finder.cs_utils_module.keys()) b_json = to_bytes(json.dumps(exec_manifest)) # delimit the payload JSON from the wrapper to keep sensitiv...
class ActionModule(ActionBase): # PowerShell runs the script in a special wrapper to enable things # like become and environment args if self._connection._shell.SHELL_FAMILY == "powershell": # FIXME: use a more public method to get the exec payload pc ...
class ActionModule(ActionBase): # PowerShell runs the script in a special wrapper to enable things # like become and environment args if self._connection._shell.SHELL_FAMILY == "powershell": # FUTURE: use a more public method to get the exec payload pc...
class Connection(ConnectionBase): # starting a new interpreter to save on time b_command = base64.b64decode(cmd.split(" ")[-1]) script = to_text(b_command, 'utf-16-le') display.vvv("PSRP: EXEC %s" % script, host=self._psrp_host) else: # in other cases ...
class Connection(ConnectionBase): # starting a new interpreter to save on time b_command = base64.b64decode(cmd.split(" ")[-1]) script = to_text(b_command, 'utf-16-le') in_data = to_text(in_data, errors="surrogate_or_strict", nonstring="passthru") display.vvv(...
import traceback import json import tempfile import subprocess HAVE_KERBEROS = False try:
import traceback import json import tempfile import subprocess import xml.etree.ElementTree as ET HAVE_KERBEROS = False try:
class Connection(ConnectionBase): return (result.status_code, result.std_out, result.std_err) def is_clixml(self, value): return value.startswith(b"#< CLIXML") # hacky way to get just stdout- not always sure of doc framing here, so use with care def parse_clixml_stream(self, clixml_doc, st...
class Connection(ConnectionBase): return (result.status_code, result.std_out, result.std_err) def is_clixml(self, value): return value.startswith(b"#< CLIXML\r\n") # hacky way to get just stdout- not always sure of doc framing here, so use with care def parse_clixml_stream(self, clixml_doc...
import base64 import os import re import shlex from ansible.errors import AnsibleError from ansible.module_utils._text import to_text
import base64 import os import re import shlex import pkgutil from ansible.errors import AnsibleError from ansible.module_utils._text import to_text
class ShellModule(ShellBase): return self._encode_script(script) def build_module_command(self, env_string, shebang, cmd, arg_path=None): # pipelining bypass if cmd == '': return '-' # non-pipelining
class ShellModule(ShellBase): return self._encode_script(script) def build_module_command(self, env_string, shebang, cmd, arg_path=None): bootstrap_wrapper = pkgutil.get_data("ansible.executor.powershell", "bootstrap_wrapper.ps1") # pipelining bypass if cmd == '': retur...
class ShellModule(ShellBase): cmd_parts = list(map(to_text, cmd_parts)) if shebang and shebang.lower() == '#!powershell': if not self._unquote(cmd_parts[0]).lower().endswith('.ps1'): cmd_parts[0] = '"%s.ps1"' % self._unquote(cmd_parts[0]) cmd_parts.insert(0, '&') ...
class ShellModule(ShellBase): cmd_parts = list(map(to_text, cmd_parts)) if shebang and shebang.lower() == '#!powershell': if not self._unquote(cmd_parts[0]).lower().endswith('.ps1'): # we're running a module via the bootstrap wrapper cmd_parts[0] = '"%s.ps1"' ...
class DataFrame(NDFrame): if is_transposed: data = data.T result = data._data.quantile( qs=q, axis=1, interpolation=interpolation, transposed=is_transposed )
class DataFrame(NDFrame): if is_transposed: data = data.T if len(data.columns) == 0: # GH#23925 _get_numeric_data may have dropped all columns cols = Index([], name=self.columns.name) if is_list_like(q): return self._constructor([], index=...
class TestDataFrameQuantile: ) tm.assert_frame_equal(res, exp) def test_quantile_empty(self): # floats df = DataFrame(columns=["a", "b"], dtype="float64")
class TestDataFrameQuantile: ) tm.assert_frame_equal(res, exp) def test_quantile_empty_no_rows(self): # floats df = DataFrame(columns=["a", "b"], dtype="float64")
class TestDataFrameQuantile: # FIXME (gives NaNs instead of NaT in 0.18.1 or 0.19.0) # res = df.quantile(0.5, numeric_only=False)
class TestDataFrameQuantile: # FIXME (gives NaNs instead of NaT in 0.18.1 or 0.19.0) # res = df.quantile(0.5, numeric_only=False) def test_quantile_empty_no_columns(self): # GH#23925 _get_numeric_data may drop all columns df = pd.DataFrame(pd.date_range("1/1/18", periods=5)) ...
logger = None if getattr(C, 'DEFAULT_LOG_PATH'): path = C.DEFAULT_LOG_PATH if path and (os.path.exists(path) and os.access(path, os.W_OK)) or os.access(os.path.dirname(path), os.W_OK): logging.basicConfig(filename=path, level=logging.DEBUG, format='%(asctime)s p=%(process)d u...
logger = None if getattr(C, 'DEFAULT_LOG_PATH'): path = C.DEFAULT_LOG_PATH if path and (os.path.exists(path) and os.access(path, os.W_OK)) or os.access(os.path.dirname(path), os.W_OK): # NOTE: level is kept at INFO to avoid security disclosures caused by certain libraries when using DEBUG loggin...
""" import logging import OFS.interfaces from AccessControl import safe_builtins
""" import logging import warnings import OFS.interfaces from AccessControl import safe_builtins
def boboAwareZopeTraverse(object, path_items, econtext): while path_items: name = path_items.pop() if OFS.interfaces.ITraversable.providedBy(object): object = object.restrictedTraverse(name) else:
def boboAwareZopeTraverse(object, path_items, econtext): while path_items: name = path_items.pop() if name == '_': warnings.warn('Traversing to the name `_` is deprecated ' 'and will be removed in Zope 6.', DeprecationWarning) ...
"""``chameleon.tales`` expressions.""" from ast import NodeTransformer from ast import parse
"""``chameleon.tales`` expressions.""" import warnings from ast import NodeTransformer from ast import parse
def traverse(cls, base, request, path_items): while path_items: name = path_items.pop() if ITraversable.providedBy(base): base = getattr(base, cls.traverseMethod)(name) else: base = traversePathElement(base, name, path_items, ...
def traverse(cls, base, request, path_items): while path_items: name = path_items.pop() if name == '_': warnings.warn('Traversing to the name `_` is deprecated ' 'and will be removed in Zope 6.', DeprecationWar...
from ..expression import getEngine from . import testHTMLTests
import unittest from ..expression import getEngine from . import testHTMLTests
def setUp(self): # expressions (e.g. the ``zope.tales`` ``not`` expression # returns ``int``, that of ``chameleon.tales`` ``bool`` PREFIX = "CH_"
def setUp(self): # expressions (e.g. the ``zope.tales`` ``not`` expression # returns ``int``, that of ``chameleon.tales`` ``bool`` PREFIX = "CH_" @unittest.skip('The test in the base class relies on a Zope context with' ' the "random" module available in expressions') def tes...
import unittest from AccessControl import safe_builtins from zope.component.testing import PlacelessSetup
import unittest import warnings from AccessControl import safe_builtins from zExceptions import NotFound from zope.component.testing import PlacelessSetup
def test_evaluate_alternative_first_missing(self): self.assertTrue(ec.evaluate('x | nothing') is None) def test_evaluate_dict_key_as_underscore(self): ec = self._makeContext() self.assertEqual(ec.evaluate('d/_'), 'under') def test_evaluate_dict_with_key_from_expansion(self): ec...
def test_evaluate_alternative_first_missing(self): self.assertTrue(ec.evaluate('x | nothing') is None) def test_evaluate_dict_key_as_underscore(self): # Traversing to the name `_` will raise a DeprecationWarning # because it will go away in Zope 6. ec = self._makeContext() w...
def test_list_in_path_expr(self): ec = self._makeContext() self.assertIs(ec.evaluate('nocall: list'), safe_builtins["list"]) class TrustedEngineTests(EngineTestsBase, unittest.TestCase):
def test_list_in_path_expr(self): ec = self._makeContext() self.assertIs(ec.evaluate('nocall: list'), safe_builtins["list"]) def test_underscore_traversal(self): # Prevent traversal to names starting with an underscore (_) ec = self._makeContext() with self.assertRaises(Not...
DefaultUnicodeEncodingConflictResolver from Products.PageTemplates.unicodeconflictresolver import \ PreferredCharsetResolver from zope.component import provideUtility from zope.traversing.adapters import DefaultTraversable
DefaultUnicodeEncodingConflictResolver from Products.PageTemplates.unicodeconflictresolver import \ PreferredCharsetResolver from zExceptions import NotFound from zope.component import provideUtility from zope.traversing.adapters import DefaultTraversable
def testPathNothing(self): def testPathAlt(self): self.assert_expected(self.folder.t, 'CheckPathAlt.html') def testBatchIteration(self): self.assert_expected(self.folder.t, 'CheckBatchIteration.html')
def testPathNothing(self): def testPathAlt(self): self.assert_expected(self.folder.t, 'CheckPathAlt.html') def testPathTraverse(self): # need to perform this test with a "real" folder from OFS.Folder import Folder f = self.folder self.folder = Folder() self.folde...
def test_unicode_conflict_resolution(self): provideUtility(PreferredCharsetResolver) t = PageTemplate() self.assert_expected(t, 'UnicodeResolution.html')
def test_unicode_conflict_resolution(self): provideUtility(PreferredCharsetResolver) t = PageTemplate() self.assert_expected(t, 'UnicodeResolution.html') def test_underscore_traversal(self): t = self.folder.t t.write('<p tal:define="p context/__class__" />') with se...
class RFPDupeFilter(BaseDupeFilter): self.logger = logging.getLogger(__name__) if path: self.file = open(os.path.join(path, 'requests.seen'), 'a+') self.fingerprints.update(x.rstrip() for x in self.file) @classmethod
class RFPDupeFilter(BaseDupeFilter): self.logger = logging.getLogger(__name__) if path: self.file = open(os.path.join(path, 'requests.seen'), 'a+') self.file.seek(0) self.fingerprints.update(x.rstrip() for x in self.file) @classmethod
import hashlib import unittest from scrapy.dupefilters import RFPDupeFilter from scrapy.http import Request
import hashlib import tempfile import unittest import shutil from scrapy.dupefilters import RFPDupeFilter from scrapy.http import Request
class RFPDupeFilterTest(unittest.TestCase): dupefilter.close('finished') def test_request_fingerprint(self): """Test if customization of request_fingerprint method will change output of request_seen.
class RFPDupeFilterTest(unittest.TestCase): dupefilter.close('finished') def test_dupefilter_path(self): r1 = Request('http://scrapytest.org/1') r2 = Request('http://scrapytest.org/2') path = tempfile.mkdtemp() try: df = RFPDupeFilter(path) df.open(...
class ObjectBlock(Block): if convert: block = [b.convert(numeric=False, copy=True) for b in block] return block return self
class ObjectBlock(Block): if convert: block = [b.convert(numeric=False, copy=True) for b in block] return block if convert: return [self.convert(numeric=False, copy=True)] return self
class BlockManager(PandasObject): convert=convert, regex=regex, ) if m.any(): new_rb = _extend_blocks(result, new_rb) else: new_rb.append(b)
class BlockManager(PandasObject): convert=convert, regex=regex, ) if m.any() or convert: new_rb = _extend_blocks(result, new_rb) else: new_rb.append(b)
class TestDataFrameReplace: expected = pd.DataFrame(exp) result = df.replace(to_replace) tm.assert_frame_equal(result, expected)
class TestDataFrameReplace: expected = pd.DataFrame(exp) result = df.replace(to_replace) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "replacer", [ pd.Timestamp("20170827"), np.int8(1), np.int16(1), np.flo...
class TestUtil(unittest.TestCase): inp = '''{"duration": "00:01:07"}''' self.assertEqual(js_to_json(inp), '''{"duration": "00:01:07"}''') def test_js_to_json_edgecases(self): on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}") self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\...
class TestUtil(unittest.TestCase): inp = '''{"duration": "00:01:07"}''' self.assertEqual(js_to_json(inp), '''{"duration": "00:01:07"}''') inp = '''{segments: [{"offset":-3.885780586188048e-16,"duration":39.75000000000001}]}''' self.assertEqual(js_to_json(inp), '''{"segments": [{"offset"...
class TestUtil(unittest.TestCase): on = js_to_json('{/*comment\n*/42/*comment\n*/:/*comment\n*/42/*comment\n*/}') self.assertEqual(json.loads(on), {'42': 42}) def test_extract_attributes(self): self.assertEqual(extract_attributes('<e x="y">'), {'x': 'y'}) self.assertEqual(extract_at...
class TestUtil(unittest.TestCase): on = js_to_json('{/*comment\n*/42/*comment\n*/:/*comment\n*/42/*comment\n*/}') self.assertEqual(json.loads(on), {'42': 42}) on = js_to_json('{42:4.2e1}') self.assertEqual(json.loads(on), {'42': 42.0}) def test_extract_attributes(self): sel...
def js_to_json(code): "(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"| '(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'| {comment}|,(?={skip}[\]}}])| [a-zA-Z_][.a-zA-Z_0-9]*| \b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:{skip}:)?| [0-9]+(?={skip}:) '''.format(comment=COMMENT_R...
def js_to_json(code): "(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"| '(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'| {comment}|,(?={skip}[\]}}])| (?:(?<![0-9])[eE]|[a-df-zA-DF-Z_])[.a-zA-Z_0-9]*| \b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:{skip}:)?| [0-9]+(?={skip}:) '''...
def parse_uri(self, uri): ", you need to change it to use the " "swift+http:// scheme, like so: " "swift+http://user:pass@authurl.com/v1/container/obj") LOG.debug(_("Invalid store uri %(uri)s: %(reason)s") % locals()) raise exc...
def parse_uri(self, uri): ", you need to change it to use the " "swift+http:// scheme, like so: " "swift+http://user:pass@authurl.com/v1/container/obj") LOG.debug(_("Invalid store URI: %(reason)s") % locals()) raise exception.B...
def parse_uri(self, uri): if creds: cred_parts = creds.split(':') if len(cred_parts) != 2: reason = (_("Badly formed credentials '%(creds)s' in Swift " "URI") % locals()) LOG.debug(reason) raise exception.BadStor...
def parse_uri(self, uri): if creds: cred_parts = creds.split(':') if len(cred_parts) != 2: reason = (_("Badly formed credentials in Swift URI.")) LOG.debug(reason) raise exception.BadStoreUri() user, key = cred_parts
def parse_uri(self, uri): path_parts.insert(0, netloc) self.auth_or_store_url = '/'.join(path_parts) except IndexError: reason = _("Badly formed Swift URI: %s") % uri LOG.debug(reason) raise exception.BadStoreUri()
def parse_uri(self, uri): path_parts.insert(0, netloc) self.auth_or_store_url = '/'.join(path_parts) except IndexError: reason = _("Badly formed Swift URI.") LOG.debug(reason) raise exception.BadStoreUri()
def get(self, location, connection=None): except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_uri() raise exception.NotFound(_("Swift could not find image at " "uri %(uri)s") % loc...
def get(self, location, connection=None): except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_uri() msg = _("Swift could not find image at URI.") raise exception.NotFound(msg) else: ...
def add(self, image_id, image_file, image_size, connection=None): except swiftclient.ClientException, e: if e.http_status == httplib.CONFLICT: raise exception.Duplicate(_("Swift already has an image at " "location %s") % ...
def add(self, image_id, image_file, image_size, connection=None): except swiftclient.ClientException, e: if e.http_status == httplib.CONFLICT: raise exception.Duplicate(_("Swift already has an image at " "this location")) msg = ...
def delete(self, location, connection=None): except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_uri() raise exception.NotFound(_("Swift could not find image at " "uri %(uri)s") % ...
def delete(self, location, connection=None): except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_uri() msg = _("Swift could not find image at URI.") raise exception.NotFound(msg) else: ...
def set_acls(self, location, public=False, read_tenants=None, except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_uri() raise exception.NotFound(_("Swift could not find image at " ...
def set_acls(self, location, public=False, read_tenants=None, except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_uri() msg = _("Swift could not find image at URI.") raise exception.NotFound(msg) ...
def do_POST(self): L = [] while size_remaining: chunk_size = min(size_remaining, max_chunk_size) L.append(self.rfile.read(chunk_size)) size_remaining -= len(L[-1]) data = ''.join(L)
def do_POST(self): L = [] while size_remaining: chunk_size = min(size_remaining, max_chunk_size) chunk = self.rfile.read(chunk_size) if not chunk: break L.append(chunk) size_remaining -= len(L[-1]...
def test_dotted_attribute(self): # This avoids waiting for the socket timeout. self.test_simple1() class MultiPathServerTestCase(BaseServerTestCase): threadFunc = staticmethod(http_multi_server) request_count = 2
def test_dotted_attribute(self): # This avoids waiting for the socket timeout. self.test_simple1() def test_partial_post(self): # Check that a partial POST doesn't make the server loop: issue #14001. conn = httplib.HTTPConnection(ADDR, PORT) conn.request('POST', '/RPC2 HTTP/...
class Worker(object): return six.moves.filter(lambda task: task.status in [PENDING, RUNNING], self.tasks) else: return state.get_pending_tasks() def is_trivial_worker(self, state): """
class Worker(object): return six.moves.filter(lambda task: task.status in [PENDING, RUNNING], self.tasks) else: return six.moves.filter(lambda task: self.id in task.workers, state.get_pending_tasks()) def is_trivial_worker(self, state): ""...
class SchedulerIoTest(unittest.TestCase): self.assertFalse(task_9.has_excessive_failures()) task_9.add_failure() self.assertTrue(task_9.has_excessive_failures())
class SchedulerIoTest(unittest.TestCase): self.assertFalse(task_9.has_excessive_failures()) task_9.add_failure() self.assertTrue(task_9.has_excessive_failures()) class SchedulerWorkerTest(unittest.TestCase): def get_pending_ids(self, worker, state): return {task.id for task in work...
def test_partial(self): ) def test_errors(self): self.assertRaises(UnicodeDecodeError, codecs.utf_16_le_decode, b"\xff", "strict", True) def test_nonbmp(self): self.assertEqual("\U00010203".encode(self.encoding),
def test_partial(self): ) def test_errors(self): tests = [ (b'\xff', '\ufffd'), (b'A\x00Z', 'A\ufffd'), (b'A\x00B\x00C\x00D\x00Z', 'ABCD\ufffd'), (b'\x00\xd8', '\ufffd'), (b'\x00\xd8A', '\ufffd'), (b'\x00\xd8A\x00', '\ufffdA'),...
def test_partial(self): ) def test_errors(self): self.assertRaises(UnicodeDecodeError, codecs.utf_16_be_decode, b"\xff", "strict", True) def test_nonbmp(self): self.assertEqual("\U00010203".encode(self.encoding),
def test_partial(self): ) def test_errors(self): tests = [ (b'\xff', '\ufffd'), (b'\x00A\xff', 'A\ufffd'), (b'\x00A\x00B\x00C\x00DZ', 'ABCD\ufffd'), (b'\xd8\x00', '\ufffd'), (b'\xd8\x00\xdc', '\ufffd'), (b'\xd8\x00\x00A', '\uff...
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>' ...
def url_concat(url, args): >>> url_concat("http://example.com/foo?a=b", [("c", "d"), ("c", "d2")]) 'http://example.com/foo?a=b&c=d&c=d2' """ parsed_url = urlparse(url) if isinstance(args, dict): parsed_query = parse_qsl(parsed_url.query, keep_blank_values=True)
def url_concat(url, args): >>> url_concat("http://example.com/foo?a=b", [("c", "d"), ("c", "d2")]) 'http://example.com/foo?a=b&c=d&c=d2' """ if args is None: return url parsed_url = urlparse(url) if isinstance(args, dict): parsed_query = parse_qsl(parsed_url.query, keep_blank_val...
class TestUrlConcat(unittest.TestCase): ) self.assertEqual(url, "https://localhost/path?r=1&t=2") def test_url_concat_with_frag(self): url = url_concat( "https://localhost/path#tab",
class TestUrlConcat(unittest.TestCase): ) self.assertEqual(url, "https://localhost/path?r=1&t=2") def test_url_concat_none_params(self): url = url_concat( "https://localhost/path?r=1&t=2", None, ) self.assertEqual(url, "https://localhost/path?r=1&t=2"...
class RedirectMiddleware(BaseRedirectMiddleware): def process_response(self, request, response, spider): if (request.meta.get('dont_redirect', False) or response.status in getattr(spider, 'handle_httpstatus_list', [])): return response if request.method == 'HEAD':
class RedirectMiddleware(BaseRedirectMiddleware): def process_response(self, request, response, spider): if (request.meta.get('dont_redirect', False) or response.status in getattr(spider, 'handle_httpstatus_list', []) or response.status in request.meta.get('handle_httpstatus_l...
class RedirectMiddlewareTest(unittest.TestCase): r = self.mw.process_response(req, rsp, smartspider) self.assertIs(r, rsp) class MetaRefreshMiddlewareTest(unittest.TestCase):
class RedirectMiddlewareTest(unittest.TestCase): r = self.mw.process_response(req, rsp, smartspider) self.assertIs(r, rsp) def test_request_meta_handling(self): url = 'http://www.example.com/301' url2 = 'http://www.example.com/redirected' def _test_passthrough(req): ...
def dispatch_to_series(left, right, func, str_rep=None, axis=None): # in which case we specifically want to operate row-by-row assert right.index.equals(left.columns) def column_op(a, b): return {i: func(a.iloc[:, i], b.iloc[i]) for i in range(len(a.columns))} elif isinstance(r...
def dispatch_to_series(left, right, func, str_rep=None, axis=None): # in which case we specifically want to operate row-by-row assert right.index.equals(left.columns) if right.dtype == "timedelta64[ns]": # ensure we treat NaT values as the correct dtype # Note: we do not...
class TestFrameFlexArithmetic: class TestFrameArithmetic: def test_df_add_2d_array_rowlike_broadcasts(self): # GH#23000 arr = np.arange(6).reshape(3, 2)
class TestFrameFlexArithmetic: class TestFrameArithmetic: def test_td64_op_nat_casting(self): # Make sure we don't accidentally treat timedelta64(NaT) as datetime64 # when calling dispatch_to_series in DataFrame arithmetic ser = pd.Series(["NaT", "NaT"], dtype="timedelta64[ns]") d...
from pandas.util._decorators import Appender, Substitution, cache_readonly, doc from pandas.core.dtypes.cast import maybe_cast_result from pandas.core.dtypes.common import ( ensure_float, is_datetime64_dtype, is_integer_dtype, is_numeric_dtype, is_object_dtype,
from pandas.util._decorators import Appender, Substitution, cache_readonly, doc from pandas.core.dtypes.cast import maybe_cast_result from pandas.core.dtypes.common import ( ensure_float, is_bool_dtype, is_datetime64_dtype, is_extension_array_dtype, is_integer_dtype, is_numeric_dtype, is_obj...
class GroupBy(_GroupBy[FrameOrSeries]): ) inference = None if is_integer_dtype(vals): inference = np.int64 elif is_datetime64_dtype(vals): inference = "datetime64[ns]" vals = np.asarray(vals).astype(np.float)
class GroupBy(_GroupBy[FrameOrSeries]): ) inference = None if is_integer_dtype(vals.dtype): if is_extension_array_dtype(vals.dtype): vals = vals.to_numpy(dtype=float, na_value=np.nan) inference = np.int64 elif is_bo...
def test_quantile_missing_group_values_correct_results(): tm.assert_frame_equal(result, expected) # pipe # --------------------------------
def test_quantile_missing_group_values_correct_results(): tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "values", [ pd.array([1, 0, None] * 2, dtype="Int64"), pd.array([True, False, None] * 2, dtype="boolean"), ], ) @pytest.mark.parametrize("q", [0.5, [0.0, 0.5, 1.0...
default: :rc:`scatter.edgecolors` - 'none': No patch boundary will be drawn. - A color or sequence of colors. For non-filled markers, the *edgecolors* kwarg is ignored and forced to 'face' internally. plotnonfinite : bool, default: False Set to plot ...
default: :rc:`scatter.edgecolors` - 'none': No patch boundary will be drawn. - A color or sequence of colors. For non-filled markers, *edgecolors* is ignored. Instead, the color is determined like with 'face', i.e. from *c*, *colors*, or *facecolors*. ...
default: :rc:`scatter.edgecolors` path = marker_obj.get_path().transformed( marker_obj.get_transform()) if not marker_obj.is_filled(): edgecolors = 'face' if linewidths is None: linewidths = rcParams['lines.linewidth'] elif np.iterable(line...
default: :rc:`scatter.edgecolors` path = marker_obj.get_path().transformed( marker_obj.get_transform()) if not marker_obj.is_filled(): if linewidths is None: linewidths = rcParams['lines.linewidth'] elif np.iterable(linewidths):
default: :rc:`scatter.edgecolors` collection = mcoll.PathCollection( (path,), scales, facecolors=colors, edgecolors=edgecolors, linewidths=linewidths, offsets=offsets, transOffset=kwargs.pop('transform', self.transD...
default: :rc:`scatter.edgecolors` collection = mcoll.PathCollection( (path,), scales, facecolors=colors if marker_obj.is_filled() else 'none', edgecolors=edgecolors if marker_obj.is_filled() else colors, linewidths=linewidths, offs...