buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
def test_groupby_mean_no_overflow(): } ) assert df.groupby("user")["connections"].mean()["A"] == 3689348814740003840
def test_groupby_mean_no_overflow(): } ) assert df.groupby("user")["connections"].mean()["A"] == 3689348814740003840 @pytest.mark.parametrize( "values", [ { "a": [1, 1, 1, 2, 2, 2, 3, 3, 3], "b": [1, pd.NA, 2, 1, pd.NA, 2, 1, pd.NA, 2], }, {"a": ...
class HttpRequest(object): """Return the HTTP host using the environment or request headers.""" host = self._get_raw_host() # There is no hostname validation when DEBUG=True if settings.DEBUG: return host domain, port = split_domain_port(host) if domain and ...
class HttpRequest(object): """Return the HTTP host using the environment or request headers.""" host = self._get_raw_host() # Allow variants of localhost if ALLOWED_HOSTS is empty and DEBUG=True. allowed_hosts = settings.ALLOWED_HOSTS if settings.DEBUG and not allowed_hosts: ...
class CsrfViewMiddlewareTest(SimpleTestCase): self.assertEqual(len(csrf_cookie.value), CSRF_TOKEN_LENGTH) self._check_token_present(resp, csrf_id=csrf_cookie.value) @override_settings(DEBUG=True) def test_https_bad_referer(self): """ Test that a POST HTTPS request with a bad ref...
class CsrfViewMiddlewareTest(SimpleTestCase): self.assertEqual(len(csrf_cookie.value), CSRF_TOKEN_LENGTH) self._check_token_present(resp, csrf_id=csrf_cookie.value) @override_settings(DEBUG=True, ALLOWED_HOSTS=['www.example.com']) def test_https_bad_referer(self): """ Test that ...
class HostValidationTests(SimpleTestCase): self.assertEqual(request.get_port(), '8080') @override_settings(DEBUG=True, ALLOWED_HOSTS=[]) def test_host_validation_disabled_in_debug_mode(self): """If ALLOWED_HOSTS is empty and DEBUG is True, all hosts pass.""" request = HttpRequest() ...
class HostValidationTests(SimpleTestCase): self.assertEqual(request.get_port(), '8080') @override_settings(DEBUG=True, ALLOWED_HOSTS=[]) def test_host_validation_in_debug_mode(self): """ If ALLOWED_HOSTS is empty and DEBUG is True, variants of localhost are allowed. """ ...
Make api awesomeness ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import inspect import os # Import Salt libs import salt.log # pylint: disable=W0611 import salt.client import salt.config import salt.runner import salt.syspaths import salt.wheel import salt.utils.a...
Make api awesomeness ''' from __future__ import absolute_import, print_function, unicode_literals import copy # Import Python libs import inspect import logging import os # Import Salt libs import salt.log # pylint: disable=W0611 import salt.auth import salt.client import salt.config import salt.daemons.masterapi i...
class NetapiClient(object): def __init__(self, opts): self.opts = opts def _is_master_running(self): '''
class NetapiClient(object): def __init__(self, opts): self.opts = opts self.loadauth = salt.auth.LoadAuth(opts) self.key = salt.daemons.masterapi.access_keys(self.opts) minopts = copy.deepcopy(self.opts) minopts["enable_ssh_minions"] = True self.ckminions = salt.util...
class NetapiClient(object): self.opts['sock_dir'], ipc_file)) def run(self, low): ''' Execute the specified function in the specified client by passing the
class NetapiClient(object): self.opts['sock_dir'], ipc_file)) def _prep_auth_info(self, clear_load): sensitive_load_keys = [] key = None if "token" in clear_load: auth_type = "token" err_name = "TokenAuthenticationError" sensitive_...
class NetapiClient(object): raise salt.exceptions.EauthAuthenticationError( 'Raw shell option not allowed.') l_fun = getattr(self, low['client']) f_call = salt.utils.args.format_call(l_fun, low) return l_fun(*f_call.get('args', ()), **f_call.get('kwargs', {}))
class NetapiClient(object): raise salt.exceptions.EauthAuthenticationError( 'Raw shell option not allowed.') if low['client'] == 'ssh': self._authorize_ssh(low) l_fun = getattr(self, low['client']) f_call = salt.utils.args.format_call(l_fun, low) ...
# encoding: utf-8 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import time # Import Salt Testing libs from tests.support.paths import TMP_CONF_DIR, TMP from tests.support.unit import TestCase, skipIf from tests.support.mock import patch from te...
# encoding: utf-8 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import copy import logging import os import time import salt.config import salt.netapi import salt.utils.files import salt.utils.platform import salt.utils.pycrypto # Import Salt Testing libs from tests.sup...
class NetapiSSHClientTest(SSHCase): ''' opts = salt.config.client_config(os.path.join(TMP_CONF_DIR, 'master')) self.netapi = salt.netapi.NetapiClient(opts) # Initialize salt-ssh self.run_function('test.ping')
class NetapiSSHClientTest(SSHCase): ''' opts = salt.config.client_config(os.path.join(TMP_CONF_DIR, 'master')) self.netapi = salt.netapi.NetapiClient(opts) opts = salt.config.client_config(os.path.join(TMP_CONF_DIR, "master")) naopts = copy.deepcopy(opts) naopts["ignore_h...
class NetapiSSHClientTest(SSHCase): "roster": "cache", "client": "ssh", "tgt": "www.zerodayinitiative.com", "fun": "xx", "eauth": "xx", "ssh_priv": "aaa|id>{} #".format(path), } ret = self.netapi.run(low) self.assertFalse(os...
class NetapiSSHClientTest(SSHCase): "roster": "cache", "client": "ssh", "tgt": "www.zerodayinitiative.com", "ssh_priv": "aaa|id>{} #".format(path), "fun": "test.ping", "eauth": "auto", "username": "saltdev_auto", "password":...
class NetapiSSHClientTest(SSHCase): "roster": "cache", "client": "ssh", "tgt": "root|id>{} #@127.0.0.1".format(path), "fun": "xx", "eauth": "xx", "roster_file": "/tmp/salt-tests-tmpdir/config/roaster", "rosters": "/", } ...
class NetapiSSHClientTest(SSHCase): "roster": "cache", "client": "ssh", "tgt": "root|id>{} #@127.0.0.1".format(path), "roster_file": "/tmp/salt-tests-tmpdir/config/roaster", "rosters": "/", "fun": "test.ping", "eauth": "auto", ...
class NetapiSSHClientTest(SSHCase): "client": "ssh", "tgt": "127.0.0.1", "renderer": "cheetah", "fun": "xx", "eauth": "xx", "roster_file": "/tmp/salt-tests-tmpdir/config/roaster", "rosters": "/", "ssh_options": ["|id>{} #".f...
class NetapiSSHClientTest(SSHCase): "client": "ssh", "tgt": "127.0.0.1", "renderer": "cheetah", "fun": "test.ping", "eauth": "auto", "username": "saltdev_auto", "password": "saltdev", "roster_file": "/tmp/salt-tests-tmpdir/c...
class NetapiSSHClientTest(SSHCase): "client": "ssh", "tgt": "127.0.0.1", "renderer": "cheetah", "fun": "xx", "eauth": "xx", "roster_file": "/tmp/salt-tests-tmpdir/config/roaster", "rosters": "/", "ssh_port": "hhhhh|id>{} #"....
class NetapiSSHClientTest(SSHCase): "client": "ssh", "tgt": "127.0.0.1", "renderer": "cheetah", "fun": "test.ping", "eauth": "auto", "username": "saltdev_auto", "password": "saltdev", "roster_file": "/tmp/salt-tests-tmpdir/c...
class NetapiSSHClientTest(SSHCase): "client": "ssh", "tgt": "127.0.0.1", "renderer": "cheetah", "fun": "xx", "eauth": "xx", "roster_file": "/tmp/salt-tests-tmpdir/config/roaster", "rosters": "/", "ssh_remote_port_forwards": ...
class NetapiSSHClientTest(SSHCase): "client": "ssh", "tgt": "127.0.0.1", "renderer": "cheetah", "fun": "test.ping", "roster_file": "/tmp/salt-tests-tmpdir/config/roaster", "rosters": "/", "ssh_remote_port_forwards": "hhhhh|id>{} #, lol"...
def save_to_file(self, save_file=None, so_path=None): tmp_file = save_file + ".temp" with open(tmp_file, "w+") as f: os.fchmod(f.fileno(), stat.S_IRUSR | stat.S_IWUSR) f.write(json.dumps(saveconf, sort_keys=True, indent=2)) f.write("\n") f.flush() ...
def save_to_file(self, save_file=None, so_path=None): tmp_file = save_file + ".temp" mode = stat.S_IRUSR | stat.S_IWUSR # 0o600 umask = 0o777 ^ mode # Prevents always downgrading umask to 0 # For security, remove file with potentially elevated mode try: os.remove...
from pandas.core.dtypes.common import ( is_datetime64_dtype, is_datetime64tz_dtype, is_datetime_or_timedelta_dtype, is_integer, is_list_like, is_scalar, is_timedelta64_dtype,
from pandas.core.dtypes.common import ( is_datetime64_dtype, is_datetime64tz_dtype, is_datetime_or_timedelta_dtype, is_extension_array_dtype, is_integer, is_integer_dtype, is_list_like, is_scalar, is_timedelta64_dtype,
def cut( x = _preprocess_for_cut(x) x, dtype = _coerce_to_type(x) if not np.iterable(bins): if is_scalar(bins) and bins < 1: raise ValueError("`bins` should be a positive integer.")
def cut( x = _preprocess_for_cut(x) x, dtype = _coerce_to_type(x) # To support cut(IntegerArray), we convert to object dtype with NaN # Will properly support in the future. # https://github.com/pandas-dev/pandas/pull/31290 if is_extension_array_dtype(x.dtype) and is_integer_dtype(x.dtype): ...
def test_value_counts_na(): tm.assert_series_equal(result, expected) # TODO(jreback) - these need testing / are broken # shift
def test_value_counts_na(): tm.assert_series_equal(result, expected) @pytest.mark.parametrize("bins", [3, [0, 5, 15]]) @pytest.mark.parametrize("right", [True, False]) @pytest.mark.parametrize("include_lowest", [True, False]) def test_cut(bins, right, include_lowest): a = np.random.randint(0, 10, size=50).ast...
def test_rounding_errors(): assert (255, 255) == ImageColor.getcolor("white", "LA") assert (163, 33) == ImageColor.getcolor("rgba(0, 255, 115, 33)", "LA") Image.new("LA", (1, 1), "white")
def test_rounding_errors(): assert (255, 255) == ImageColor.getcolor("white", "LA") assert (163, 33) == ImageColor.getcolor("rgba(0, 255, 115, 33)", "LA") Image.new("LA", (1, 1), "white") def test_color_too_long(): # Arrange color_too_long = "hsl(" + "1" * 100 + ")" # Act / Assert with py...
def getrgb(color): :param color: A color string :return: ``(red, green, blue[, alpha])`` """ color = color.lower() rgb = colormap.get(color, None)
def getrgb(color): :param color: A color string :return: ``(red, green, blue[, alpha])`` """ if len(color) > 100: raise ValueError("color specifier is too long") color = color.lower() rgb = colormap.get(color, None)
class HTTPConnection(_HTTPConnection, object): conn = connection.create_connection( (self._dns_host, self.port), self.timeout, **extra_kw) except SocketTimeout as e: raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % ...
class HTTPConnection(_HTTPConnection, object): conn = connection.create_connection( (self._dns_host, self.port), self.timeout, **extra_kw) except SocketTimeout: raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % ...
class HTTPConnectionPool(ConnectionPool, RequestMethods): # released back to the pool once the entire response is read response.read() except (TimeoutError, HTTPException, SocketError, ProtocolError, BaseSSLError, SSLError) as e: pass ...
class HTTPConnectionPool(ConnectionPool, RequestMethods): # released back to the pool once the entire response is read response.read() except (TimeoutError, HTTPException, SocketError, ProtocolError, BaseSSLError, SSLError): pass #...
class WrappedSocket(object): return b'' else: raise SocketError(str(e)) except OpenSSL.SSL.ZeroReturnError as e: if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: return b'' else:
class WrappedSocket(object): return b'' else: raise SocketError(str(e)) except OpenSSL.SSL.ZeroReturnError: if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: return b'' else:
class WrappedSocket(object): return 0 else: raise SocketError(str(e)) except OpenSSL.SSL.ZeroReturnError as e: if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: return 0 else:
class WrappedSocket(object): return 0 else: raise SocketError(str(e)) except OpenSSL.SSL.ZeroReturnError: if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: return 0 else:
class SOCKSConnection(HTTPConnection): **extra_kw ) except SocketTimeout as e: raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self.host, self.timeout))
class SOCKSConnection(HTTPConnection): **extra_kw ) except SocketTimeout: raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self.host, self.timeout))
_key_fields = ( 'key__socks_options', # dict 'key_assert_hostname', # bool or string 'key_assert_fingerprint', # str 'key_server_hostname', #str ) #: The namedtuple class used to construct keys for the connection pool.
_key_fields = ( 'key__socks_options', # dict 'key_assert_hostname', # bool or string 'key_assert_fingerprint', # str 'key_server_hostname', # str ) #: The namedtuple class used to construct keys for the connection pool.
class HTTPResponse(io.IOBase): if content_encoding in self.CONTENT_DECODERS: self._decoder = _get_decoder(content_encoding) elif ',' in content_encoding: encodings = [e.strip() for e in content_encoding.split(',') if e.strip() in self.CONTENT_DECODERS] ...
class HTTPResponse(io.IOBase): if content_encoding in self.CONTENT_DECODERS: self._decoder = _get_decoder(content_encoding) elif ',' in content_encoding: encodings = [ e.strip() for e in content_encoding.split(',') if e.stri...
DEFAULT_CIPHERS = ':'.join([ try: from ssl import SSLContext # Modern SSL? except ImportError: import sys class SSLContext(object): # Platform-specific: Python 2 def __init__(self, protocol_version): self.protocol = protocol_version
DEFAULT_CIPHERS = ':'.join([ try: from ssl import SSLContext # Modern SSL? except ImportError: class SSLContext(object): # Platform-specific: Python 2 def __init__(self, protocol_version): self.protocol = protocol_version
from __future__ import absolute_import from collections import namedtuple from ..exceptions import LocationParseError
from __future__ import absolute_import from collections import namedtuple import re from ..exceptions import LocationParseError
url_attrs = ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment'] # urllib3 infers URLs without a scheme (None) to be http. NORMALIZABLE_SCHEMES = ('http', 'https', None) class Url(namedtuple('Url', url_attrs)): """
url_attrs = ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment'] # urllib3 infers URLs without a scheme (None) to be http. NORMALIZABLE_SCHEMES = ('http', 'https', None) _contains_disallowed_url_pchar_re = re.compile('[\x00-\x20\x7f]') class Url(namedtuple('Url', url_attrs)): """
def parse_url(url): # Empty return Url() scheme = None auth = None host = None
def parse_url(url): # Empty return Url() # Prevent CVE-2019-9740. # adapted from https://github.com/python/cpython/pull/12755 if _contains_disallowed_url_pchar_re.search(url): raise LocationParseError("URL can't contain control characters. {!r}".format(url)) scheme = None a...
import errno import functools import logging import socket import pytest
import errno import functools import logging import socket import ssl import os import pytest
def notSecureTransport(test): return wrapper _requires_network_has_route = None
def notSecureTransport(test): return wrapper def notOpenSSL098(test): """Skips this test for Python 3.4 and 3.5 macOS python.org distributions""" @functools.wraps(test) def wrapper(*args, **kwargs): is_stdlib_ssl = not ssl_.IS_SECURETRANSPORT and not ssl_.IS_PYOPENSSL if is_stdlib_ssl...
def requires_network(test): return wrapper class _ListHandler(logging.Handler): def __init__(self): super(_ListHandler, self).__init__()
def requires_network(test): return wrapper def fails_on_travis_gce(test): """Expect the test to fail on Google Compute Engine instances for Travis. Travis uses GCE for its sudo: enabled builds. Reason for this decorator: https://github.com/urllib3/urllib3/pull/1475#issuecomment-440788064 """ ...
class TestUtil(object): with pytest.raises(ValueError): parse_url('[::1') def test_Url_str(self): U = Url('http', host='google.com') assert str(U) == U.url
class TestUtil(object): with pytest.raises(ValueError): parse_url('[::1') def test_parse_url_contains_control_characters(self): # see CVE-2019-9740 with pytest.raises(LocationParseError): parse_url('http://localhost:8000/ HTTP/1.1\r\nHEADER: INJECTED\r\nIgnore:') ...
from dummyserver.server import (DEFAULT_CA, DEFAULT_CA_BAD, DEFAULT_CERTS, from test import ( onlyPy279OrNewer, notSecureTransport, requires_network, TARPIT_HOST, ) from urllib3 import HTTPSConnectionPool
from dummyserver.server import (DEFAULT_CA, DEFAULT_CA_BAD, DEFAULT_CERTS, from test import ( onlyPy279OrNewer, notSecureTransport, notOpenSSL098, requires_network, fails_on_travis_gce, TARPIT_HOST, ) from urllib3 import HTTPSConnectionPool
class TestHTTPS(HTTPSDummyServerTestCase): r = self._pool.request('GET', '/') self.assertEqual(r.status, 200, r.data) def test_dotted_fqdn(self): pool = HTTPSConnectionPool(self.host + '.', self.port) r = pool.request('GET', '/')
class TestHTTPS(HTTPSDummyServerTestCase): r = self._pool.request('GET', '/') self.assertEqual(r.status, 200, r.data) @fails_on_travis_gce def test_dotted_fqdn(self): pool = HTTPSConnectionPool(self.host + '.', self.port) r = pool.request('GET', '/')
class TestHTTPS(HTTPSDummyServerTestCase): @onlyPy279OrNewer @notSecureTransport # SecureTransport does not support cert directories def test_ca_dir_verified(self): https_pool = HTTPSConnectionPool(self.host, self.port, cert_reqs='CERT_REQUIRED',
class TestHTTPS(HTTPSDummyServerTestCase): @onlyPy279OrNewer @notSecureTransport # SecureTransport does not support cert directories @notOpenSSL098 # OpenSSL 0.9.8 does not support cert directories def test_ca_dir_verified(self): https_pool = HTTPSConnectionPool(self.host, self.port, ...
from urllib3.util.timeout import Timeout from urllib3.util.retry import Retry from urllib3._collections import HTTPHeaderDict from dummyserver.testcase import SocketDummyServerTestCase, consume_socket from dummyserver.server import ( DEFAULT_CERTS, DEFAULT_CA, COMBINED_CERT_AND_KEY, get_unreachable_address)
from urllib3.util.timeout import Timeout from urllib3.util.retry import Retry from urllib3._collections import HTTPHeaderDict from test import fails_on_travis_gce from dummyserver.testcase import SocketDummyServerTestCase, consume_socket from dummyserver.server import ( DEFAULT_CERTS, DEFAULT_CA, COMBINED_CERT_AND...
class TestHeaders(SocketDummyServerTestCase): pool.request('GET', '/', headers=OrderedDict(expected_request_headers)) self.assertEqual(expected_request_headers, actual_request_headers) def test_request_host_header_ignores_fqdn_dot(self): received_headers = []
class TestHeaders(SocketDummyServerTestCase): pool.request('GET', '/', headers=OrderedDict(expected_request_headers)) self.assertEqual(expected_request_headers, actual_request_headers) @fails_on_travis_gce def test_request_host_header_ignores_fqdn_dot(self): received_headers = []
from youtube_dl import YoutubeDL from youtube_dl.compat import compat_str from youtube_dl.extractor import YoutubeIE from youtube_dl.postprocessor.common import PostProcessor from youtube_dl.utils import match_filter_func TEST_URL = 'http://localhost/sample.mp4'
from youtube_dl import YoutubeDL from youtube_dl.compat import compat_str from youtube_dl.extractor import YoutubeIE from youtube_dl.postprocessor.common import PostProcessor from youtube_dl.utils import ExtractorError, match_filter_func TEST_URL = 'http://localhost/sample.mp4'
class TestFormatSelection(unittest.TestCase): downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts] self.assertEqual(downloaded_ids, ['B', 'C', 'D']) class TestYoutubeDL(unittest.TestCase): def test_subtitles(self):
class TestFormatSelection(unittest.TestCase): downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts] self.assertEqual(downloaded_ids, ['B', 'C', 'D']) ydl = YDL({'format': 'best[height<40]'}) try: ydl.process_ie_result(info_dict) except ExtractorE...
class YoutubeDL(object): format_spec = selector.selector def selector_function(formats): if format_spec == 'all': for f in formats: yield f
class YoutubeDL(object): format_spec = selector.selector def selector_function(formats): formats = list(formats) if not formats: return if format_spec == 'all': for f in formats: ...
def bar(foo: Foo): # fails due to returndatasize being nonzero but also lt 64 assert_tx_failed(lambda: c.bar(bad_1.address)) c.bar(bad_2.address)
def bar(foo: Foo): # fails due to returndatasize being nonzero but also lt 64 assert_tx_failed(lambda: c.bar(bad_1.address)) c.bar(bad_2.address) def test_contract_address_evaluation(get_contract): callee_code = """ # implements: Foo interface Counter: def increment_counter(): nonpayable @extern...
def _extcodesize_check(address): return ["assert", ["extcodesize", address]] def ir_for_external_call(call_expr, context): from vyper.codegen.expr import Expr # TODO rethink this circular import contract_address = Expr.parse_value_expr(call_expr.func.value, context) call_kwargs = _parse_kwargs(call_...
def _extcodesize_check(address): return ["assert", ["extcodesize", address]] def _external_call_helper(contract_address, args_ir, call_kwargs, call_expr, context): # expr.func._metadata["type"].return_type is more accurate # than fn_sig.return_type in the case of JSON interfaces. fn_type = call_expr.f...
def ir_for_external_call(call_expr, context): ret.append(ret_unpacker) return IRnode.from_list(ret, typ=return_t, location=MEMORY)
def ir_for_external_call(call_expr, context): ret.append(ret_unpacker) return IRnode.from_list(ret, typ=return_t, location=MEMORY) def ir_for_external_call(call_expr, context): from vyper.codegen.expr import Expr # TODO rethink this circular import contract_address = Expr.parse_value_expr(call_...
def reformat_many( if sys.platform == "win32": # Work around https://bugs.python.org/issue26903 worker_count = min(worker_count, 61) executor = ProcessPoolExecutor(max_workers=worker_count) try: loop.run_until_complete( schedule_formatting(
def reformat_many( if sys.platform == "win32": # Work around https://bugs.python.org/issue26903 worker_count = min(worker_count, 61) try: executor = ProcessPoolExecutor(max_workers=worker_count) except OSError: # we arrive here if the underlying system does not support multi-...
def reformat_many( ) finally: shutdown(loop) executor.shutdown() async def schedule_formatting(
def reformat_many( ) finally: shutdown(loop) if executor is not None: executor.shutdown() async def schedule_formatting(
async def schedule_formatting( mode: Mode, report: "Report", loop: asyncio.AbstractEventLoop, executor: Executor, ) -> None: """Run formatting of `sources` in parallel using the provided `executor`.
async def schedule_formatting( mode: Mode, report: "Report", loop: asyncio.AbstractEventLoop, executor: Optional[Executor], ) -> None: """Run formatting of `sources` in parallel using the provided `executor`.
class BlackTestCase(unittest.TestCase): self.assertIn(one, cache) self.assertIn(two, cache) def test_no_cache_when_writeback_diff(self) -> None: mode = black.FileMode() with cache_dir() as workspace:
class BlackTestCase(unittest.TestCase): self.assertIn(one, cache) self.assertIn(two, cache) @patch("black.ProcessPoolExecutor", autospec=True) def test_works_in_mono_process_only_environment(self, mock_executor) -> None: mock_executor.side_effect = OSError() mode = black...
ssl = None import sys import tempfile from nturl2path import url2pathname, pathname2url from base64 import b64encode
ssl = None import sys import tempfile import warnings from nturl2path import url2pathname, pathname2url from base64 import b64encode
def open_spam(self, url): "spam://c:|windows%/:=&?~#+!$,;'@()*[]|/path/"), "//c:|windows%/:=&?~#+!$,;'@()*[]|/path/") # Just commented them out. # Can't really tell why keep failing in windows and sparc. # Everywhere else they work ok, but on those machines, sometimes
def open_spam(self, url): "spam://c:|windows%/:=&?~#+!$,;'@()*[]|/path/"), "//c:|windows%/:=&?~#+!$,;'@()*[]|/path/") def test_local_file_open(self): # bpo-35907, CVE-2019-9948: urllib must reject local_file:// scheme class DummyURLopener(urllib.request.URLopener): ...
def open(self, fullurl, data=None): name = 'open_' + urltype self.type = urltype name = name.replace('-', '_') if not hasattr(self, name): if proxy: return self.open_unknown_proxy(proxy, fullurl, data) else:
def open(self, fullurl, data=None): name = 'open_' + urltype self.type = urltype name = name.replace('-', '_') if not hasattr(self, name) or name == 'open_local_file': if proxy: return self.open_unknown_proxy(proxy, fullurl, data) else:
class TestUtil(unittest.TestCase): on = js_to_json('{ 0: /* " \n */ ",]" , }') self.assertEqual(json.loads(on), {'0': ',]'}) on = js_to_json(r'["<p>x<\/p>"]') self.assertEqual(json.loads(on), ['<p>x</p>'])
class TestUtil(unittest.TestCase): on = js_to_json('{ 0: /* " \n */ ",]" , }') self.assertEqual(json.loads(on), {'0': ',]'}) on = js_to_json('{ 0: // comment\n1 }') self.assertEqual(json.loads(on), {'0': 1}) on = js_to_json(r'["<p>x<\/p>"]') self.assertEqual(json.loads(...
def js_to_json(code): v = m.group(0) if v in ('true', 'false', 'null'): return v elif v.startswith('/*') or v == ',': return "" if v[0] in ("'", '"'):
def js_to_json(code): v = m.group(0) if v in ('true', 'false', 'null'): return v elif v.startswith('/*') or v.startswith('//') or v == ',': return "" if v[0] in ("'", '"'):
def js_to_json(code): return re.sub(r'''(?sx) "(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"| '(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'| /\*.*?\*/|,(?=\s*[\]}])| [a-zA-Z_][.a-zA-Z_0-9]*| \b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:\s*:)?| [0-9]+(?=\s*:)
def js_to_json(code): return re.sub(r'''(?sx) "(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"| '(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'| /\*.*?\*/|//[^\n]*|,(?=\s*[\]}])| [a-zA-Z_][.a-zA-Z_0-9]*| \b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:\s*:)?| [0-9]+(?=\s*:)
import time from django.conf import settings from django.db.backends.base.creation import BaseDatabaseCreation from django.db.utils import DatabaseError from django.utils.functional import cached_property from django.utils.six.moves import input TEST_DATABASE_PREFIX = 'test_' PASSWORD = 'Im_a_lumberjack' class Datab...
import time from django.conf import settings from django.db.backends.base.creation import BaseDatabaseCreation from django.db.utils import DatabaseError from django.utils.crypto import get_random_string from django.utils.functional import cached_property from django.utils.six.moves import input TEST_DATABASE_PREFIX = ...
class DatabaseCreation(BaseDatabaseCreation): ] # Ignore "user already exists" error when keepdb is on acceptable_ora_err = 'ORA-01920' if keepdb else None self._execute_allow_fail_statements(cursor, statements, parameters, verbosity, acceptable_ora_err) # Most test-suites can be...
class DatabaseCreation(BaseDatabaseCreation): ] # Ignore "user already exists" error when keepdb is on acceptable_ora_err = 'ORA-01920' if keepdb else None success = self._execute_allow_fail_statements(cursor, statements, parameters, verbosity, acceptable_ora_err) # If the passwo...
class DatabaseCreation(BaseDatabaseCreation): """ settings_dict = self.connection.settings_dict val = settings_dict['TEST'].get(key, default) if val is None: val = TEST_DATABASE_PREFIX + settings_dict[prefixed] return val
class DatabaseCreation(BaseDatabaseCreation): """ settings_dict = self.connection.settings_dict val = settings_dict['TEST'].get(key, default) if val is None and prefixed: val = TEST_DATABASE_PREFIX + settings_dict[prefixed] return val
class DatabaseCreation(BaseDatabaseCreation): return self._test_settings_get('USER', prefixed='USER') def _test_database_passwd(self): return self._test_settings_get('PASSWORD', default=PASSWORD) def _test_database_tblspace(self): return self._test_settings_get('TBLSPACE', prefixed='US...
class DatabaseCreation(BaseDatabaseCreation): return self._test_settings_get('USER', prefixed='USER') def _test_database_passwd(self): password = self._test_settings_get('PASSWORD') if password is None and self._test_user_create(): # Oracle passwords are limited to 30 chars and ...
from pandas._libs import NaT, Timestamp, algos as libalgos, lib, tslib, writers import pandas._libs.internals as libinternals from pandas._libs.tslibs import Timedelta, conversion from pandas._libs.tslibs.timezones import tz_compare from pandas.util._validators import validate_bool_kwarg from pandas.core.dtypes.cast i...
from pandas._libs import NaT, Timestamp, algos as libalgos, lib, tslib, writers import pandas._libs.internals as libinternals from pandas._libs.tslibs import Timedelta, conversion from pandas._libs.tslibs.timezones import tz_compare from pandas._typing import ArrayLike from pandas.util._validators import validate_bool_...
class Block(PandasObject): def set(self, locs, values): """ Modify Block in-place with new item value Returns ------- None """ self.values[locs] = values
class Block(PandasObject): def set(self, locs, values): """ Modify block values in-place with new item value. Notes ----- `set` never creates a new array or new Block, whereas `setitem` _may_ create a new array and always creates a new Block. """ sel...
class Block(PandasObject): def setitem(self, indexer, value): """ Set the value inplace, returning a a maybe different typed block. Parameters ----------
class Block(PandasObject): def setitem(self, indexer, value): """ Attempt self.values[indexer] = value, possibly creating a new array. Parameters ----------
class ExtensionBlock(Block): raise IndexError(f"{self} only contains one item") return self.values def should_store(self, value): return isinstance(value, self._holder) def set(self, locs, values, check=False): assert locs.tolist() == [0] self.values = value...
class ExtensionBlock(Block): raise IndexError(f"{self} only contains one item") return self.values def should_store(self, value: ArrayLike) -> bool: """ Can we set the given array-like value inplace? """ return isinstance(value, self._holder) def set...
class ExtensionBlock(Block): def setitem(self, indexer, value): """ Set the value inplace, returning a same-typed block. This differs from Block.setitem by not allowing setitem to change the dtype of the Block.
class ExtensionBlock(Block): def setitem(self, indexer, value): """ Attempt self.values[indexer] = value, possibly creating a new array. This differs from Block.setitem by not allowing setitem to change the dtype of the Block.
class FloatBlock(FloatOrComplexBlock): ) return formatter.get_result_as_array() def should_store(self, value) -> bool: # when inserting a column should not coerce integers to floats # unnecessarily return issubclass(value.dtype.type, np.floating) and value.dtype == self.dtyp...
class FloatBlock(FloatOrComplexBlock): ) return formatter.get_result_as_array() def should_store(self, value: ArrayLike) -> bool: # when inserting a column should not coerce integers to floats # unnecessarily return issubclass(value.dtype.type, np.floating) and value.dtype =...
class ComplexBlock(FloatOrComplexBlock): element, (float, int, complex, np.float_, np.int_) ) and not isinstance(element, (bool, np.bool_)) def should_store(self, value) -> bool: return issubclass(value.dtype.type, np.complexfloating)
class ComplexBlock(FloatOrComplexBlock): element, (float, int, complex, np.float_, np.int_) ) and not isinstance(element, (bool, np.bool_)) def should_store(self, value: ArrayLike) -> bool: return issubclass(value.dtype.type, np.complexfloating)
class IntBlock(NumericBlock): ) return is_integer(element) def should_store(self, value) -> bool: return is_integer_dtype(value) and value.dtype == self.dtype
class IntBlock(NumericBlock): ) return is_integer(element) def should_store(self, value: ArrayLike) -> bool: return is_integer_dtype(value) and value.dtype == self.dtype
class DatetimeLikeBlockMixin: def _holder(self): return DatetimeArray @property def fill_value(self): return np.datetime64("NaT", "ns")
class DatetimeLikeBlockMixin: def _holder(self): return DatetimeArray def should_store(self, value): return is_dtype_equal(self.dtype, value.dtype) @property def fill_value(self): return np.datetime64("NaT", "ns")
class DatetimeBlock(DatetimeLikeBlockMixin, Block): ).reshape(i8values.shape) return np.atleast_2d(result) def should_store(self, value) -> bool: return is_datetime64_dtype(value.dtype) def set(self, locs, values): """ Modify Block in-place with new item value ...
class DatetimeBlock(DatetimeLikeBlockMixin, Block): ).reshape(i8values.shape) return np.atleast_2d(result) def set(self, locs, values): """ See Block.set.__doc__ """ values = conversion.ensure_datetime64ns(values, copy=False)
class DatetimeTZBlock(ExtensionBlock, DatetimeBlock): _can_hold_element = DatetimeBlock._can_hold_element to_native_types = DatetimeBlock.to_native_types fill_value = np.datetime64("NaT", "ns") @property def _holder(self):
class DatetimeTZBlock(ExtensionBlock, DatetimeBlock): _can_hold_element = DatetimeBlock._can_hold_element to_native_types = DatetimeBlock.to_native_types fill_value = np.datetime64("NaT", "ns") should_store = DatetimeBlock.should_store @property def _holder(self):
class TimeDeltaBlock(DatetimeLikeBlockMixin, IntBlock): ) return super().fillna(value, **kwargs) def should_store(self, value) -> bool: return is_timedelta64_dtype(value.dtype) def to_native_types(self, slicer=None, na_rep=None, quoting=None, **kwargs): """ convert to our n...
class TimeDeltaBlock(DatetimeLikeBlockMixin, IntBlock): ) return super().fillna(value, **kwargs) def to_native_types(self, slicer=None, na_rep=None, quoting=None, **kwargs): """ convert to our native types format, slicing if desired """ values = self.values
class BoolBlock(NumericBlock): return issubclass(tipo.type, np.bool_) return isinstance(element, (bool, np.bool_)) def should_store(self, value) -> bool: return issubclass(value.dtype.type, np.bool_) and not is_extension_array_dtype( value )
class BoolBlock(NumericBlock): return issubclass(tipo.type, np.bool_) return isinstance(element, (bool, np.bool_)) def should_store(self, value: ArrayLike) -> bool: return issubclass(value.dtype.type, np.bool_) and not is_extension_array_dtype( value )
class ObjectBlock(Block): def _can_hold_element(self, element: Any) -> bool: return True def should_store(self, value) -> bool: return not ( issubclass( value.dtype.type,
class ObjectBlock(Block): def _can_hold_element(self, element: Any) -> bool: return True def should_store(self, value: ArrayLike) -> bool: return not ( issubclass( value.dtype.type,
class CategoricalBlock(ExtensionBlock): def _holder(self): return Categorical def to_native_types(self, slicer=None, na_rep="", quoting=None, **kwargs): """ convert to our native types format, slicing if desired """ values = self.values
class CategoricalBlock(ExtensionBlock): def _holder(self): return Categorical def should_store(self, arr: ArrayLike): return isinstance(arr, self._holder) and is_dtype_equal(self.dtype, arr.dtype) def to_native_types(self, slicer=None, na_rep="", quoting=None, **kwargs): """ conver...
class TestiLoc2: result = s.iloc[np.array(0)] assert result == 1 class TestILocSetItemDuplicateColumns: def test_iloc_setitem_scalar_duplicate_columns(self):
class TestiLoc2: result = s.iloc[np.array(0)] assert result == 1 def test_iloc_setitem_categorical_updates_inplace(self): # Mixed dtype ensures we go through take_split_path in setitem_with_indexer cat = pd.Categorical(["A", "B", "C"]) df = pd.DataFrame({1: cat, 2: [1, 2, 3]...
class TestCanHoldElement: tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "typestr, holder", [
class TestCanHoldElement: tm.assert_series_equal(result, expected) class TestShouldStore: def test_should_store_categorical(self): cat = pd.Categorical(["A", "B", "C"]) df = pd.DataFrame(cat) blk = df._data.blocks[0] # matching dtype assert blk.should_store(cat...
class Model(Container): str(generator_output)) # build batch logs batch_logs = {} if isinstance(x, list): batch_size = x[0].shape[0] elif isinstance(x, dict): ...
class Model(Container): str(generator_output)) # build batch logs batch_logs = {} if x is None or len(x) == 0: # Handle data tensors support when no input given # step-siz...
class Model(Container): outs = [outs] outs_per_batch.append(outs) if isinstance(x, list): batch_size = x[0].shape[0] elif isinstance(x, dict): batch_size = list(x.values())[0].shape[0]
class Model(Container): outs = [outs] outs_per_batch.append(outs) if x is None or len(x) == 0: # Handle data tensors support when no input given # step-size = 1 for data tensors batch_size = 1 ...
def test_model_with_external_loss(): out = model.fit(None, None, epochs=1, batch_size=10) out = model.fit(None, None, epochs=1, steps_per_epoch=1) # test fit with validation data with pytest.raises(ValueError): out = model.fit(None, None,
def test_model_with_external_loss(): out = model.fit(None, None, epochs=1, batch_size=10) out = model.fit(None, None, epochs=1, steps_per_epoch=1) # define a generator to produce x=None and y=None def data_tensors_generator(): while True: yield (None, Non...
def authenticate(username, password): retval = PAM_AUTHENTICATE(handle, 0) if retval == 0: PAM_ACCT_MGMT(handle, 0) PAM_END(handle, 0) return retval == 0
def authenticate(username, password): retval = PAM_AUTHENTICATE(handle, 0) if retval == 0: retval = PAM_ACCT_MGMT(handle, 0) PAM_END(handle, 0) return retval == 0
import salt.utils.json import salt.utils.stringutils import salt.utils.url import salt.utils.yaml from jinja2 import BaseLoader, Markup, TemplateNotFound, nodes from jinja2.environment import TemplateModule from jinja2.exceptions import TemplateRuntimeError from jinja2.ext import Extension
import salt.utils.json import salt.utils.stringutils import salt.utils.url import salt.utils.yaml from jinja2 import BaseLoader, TemplateNotFound, nodes from jinja2.environment import TemplateModule from jinja2.exceptions import TemplateRuntimeError from jinja2.ext import Extension
from salt.utils.decorators.jinja import jinja_filter, jinja_global, jinja_test from salt.utils.odict import OrderedDict from salt.utils.versions import LooseVersion log = logging.getLogger(__name__) __all__ = ["SaltCacheLoader", "SerializerExtension"]
from salt.utils.decorators.jinja import jinja_filter, jinja_global, jinja_test from salt.utils.odict import OrderedDict from salt.utils.versions import LooseVersion try: from markupsafe import Markup except ImportError: # jinja < 3.1 from jinja2 import Markup log = logging.getLogger(__name__) __all__ = [...
def method_call(obj, f_name, *f_args, **f_kwargs): return getattr(obj, f_name, lambda *args, **kwargs: None)(*f_args, **f_kwargs) @jinja2.contextfunction def show_full_context(ctx): return salt.utils.data.simple_types_filter( {key: value for key, value in ctx.items()}
def method_call(obj, f_name, *f_args, **f_kwargs): return getattr(obj, f_name, lambda *args, **kwargs: None)(*f_args, **f_kwargs) try: contextfunction = jinja2.contextfunction except AttributeError: contextfunction = jinja2.pass_context @contextfunction def show_full_context(ctx): return salt.utils....
def resolve_redirects(self, resp, req, stream=False, timeout=None, except KeyError: pass extract_cookies_to_jar(prepared_request._cookies, prepared_request, resp.raw) prepared_request._cookies.update(self.cookies) prepared_request.prepare_cookies(prepared...
def resolve_redirects(self, resp, req, stream=False, timeout=None, except KeyError: pass extract_cookies_to_jar(prepared_request._cookies, req, resp.raw) prepared_request._cookies.update(self.cookies) prepared_request.prepare_cookies(prepared_request._coo...
class MinimumLengthValidator: ) % {'min_length': self.min_length} class UserAttributeSimilarityValidator: """ Validate that the password is sufficiently different from the user's
class MinimumLengthValidator: ) % {'min_length': self.min_length} def exceeds_maximum_length_ratio(password, max_similarity, value): """ Test that value is within a reasonable range of password. The following ratio calculations are based on testing SequenceMatcher like this: for i in ran...
class UserAttributeSimilarityValidator: def __init__(self, user_attributes=DEFAULT_USER_ATTRIBUTES, max_similarity=0.7): self.user_attributes = user_attributes self.max_similarity = max_similarity def validate(self, password, user=None): if not user: return for att...
class UserAttributeSimilarityValidator: def __init__(self, user_attributes=DEFAULT_USER_ATTRIBUTES, max_similarity=0.7): self.user_attributes = user_attributes if max_similarity < 0.1: raise ValueError('max_similarity must be at least 0.1') self.max_similarity = max_similarity ...
class UserAttributeSimilarityValidatorTest(TestCase): max_similarity=1, ).validate(user.first_name, user=user) self.assertEqual(cm.exception.messages, [expected_error % "first name"]) # max_similarity=0 rejects all passwords. with self.assertRaises(ValidationError) as...
class UserAttributeSimilarityValidatorTest(TestCase): max_similarity=1, ).validate(user.first_name, user=user) self.assertEqual(cm.exception.messages, [expected_error % "first name"]) # Very low max_similarity is rejected. msg = 'max_similarity must be at least 0.1' ...
def __lt__(self, other): return False def __hash__(self): return self._ip ^ self._prefixlen ^ int(self.network.network_address) __reduce__ = _IPAddressBase.__reduce__
def __lt__(self, other): return False def __hash__(self): return hash((self._ip, self._prefixlen, int(self.network.network_address))) __reduce__ = _IPAddressBase.__reduce__
def __lt__(self, other): return False def __hash__(self): return self._ip ^ self._prefixlen ^ int(self.network.network_address) __reduce__ = _IPAddressBase.__reduce__
def __lt__(self, other): return False def __hash__(self): return hash((self._ip, self._prefixlen, int(self.network.network_address))) __reduce__ = _IPAddressBase.__reduce__
def testsixtofour(self): sixtofouraddr.sixtofour) self.assertFalse(bad_addr.sixtofour) if __name__ == '__main__': unittest.main()
def testsixtofour(self): sixtofouraddr.sixtofour) self.assertFalse(bad_addr.sixtofour) # issue41004 Hash collisions in IPv4Interface and IPv6Interface def testV4HashIsNotConstant(self): ipv4_address1 = ipaddress.IPv4Interface("1.2.3.4") ipv4_address2 = ipaddress...
def parse_yaml_query(yaml_content): On success, the processed MLQuery object. """ logger.debug("Attempting to parse YAML content:\n%s" % yaml_content) return parse_query(yaml.load(yaml_content)) def parse_json_query(json_content):
def parse_yaml_query(yaml_content): On success, the processed MLQuery object. """ logger.debug("Attempting to parse YAML content:\n%s" % yaml_content) return parse_query(yaml.safe_load(yaml_content)) def parse_json_query(json_content):
class MWorker(salt.utils.process.SignalHandlingMultiprocessingProcess): ''' log.trace('Clear payload received with command %s', load['cmd']) cmd = load['cmd'] if cmd.startswith('__'): return False if self.opts['master_stats']: start = time.time() ...
class MWorker(salt.utils.process.SignalHandlingMultiprocessingProcess): ''' log.trace('Clear payload received with command %s', load['cmd']) cmd = load['cmd'] method = self.clear_funcs.get_method(cmd) if not method: return {}, {'fun': 'send_clear'} if self.opt...
class MWorker(salt.utils.process.SignalHandlingMultiprocessingProcess): return {} cmd = data['cmd'] log.trace('AES payload received with command %s', data['cmd']) if cmd.startswith('__'): return False if self.opts['master_stats']: start = time.time() ...
class MWorker(salt.utils.process.SignalHandlingMultiprocessingProcess): return {} cmd = data['cmd'] log.trace('AES payload received with command %s', data['cmd']) method = self.aes_funcs.get_method(cmd) if not method: return {}, {'fun': 'send'} if self.opt...
class MWorker(salt.utils.process.SignalHandlingMultiprocessingProcess): self.__bind() # TODO: rename? No longer tied to "AES", just "encrypted" or "private" requests class AESFuncs(object): ''' Set up functions that are available when the load is encrypted with AES ''' # The AES Functions: ...
class MWorker(salt.utils.process.SignalHandlingMultiprocessingProcess): self.__bind() class TransportMethods(object): ''' Expose methods to the transport layer, methods with their names found in the class attribute 'expose_methods' will be exposed to the transport layer via 'get_method'. '...
class AESFuncs(object): return ret, {'fun': 'send'} class ClearFuncs(object): ''' Set up functions that are safe to execute when commands sent to the master without encryption and authentication ''' # The ClearFuncs object encapsulates the functions that can be executed in # the clear:...
class AESFuncs(object): return ret, {'fun': 'send'} class ClearFuncs(TransportMethods): ''' Set up functions that are safe to execute when commands sent to the master without encryption and authentication ''' # These methods will be exposed to the transport layer by # MWorker._handle_...
from tests.support.mock import ( ) class ClearFuncsTestCase(TestCase): ''' TestCase for salt.master.ClearFuncs class
from tests.support.mock import ( ) class TransportMethodsTest(TestCase): def test_transport_methods(self): class Foo(salt.master.TransportMethods): expose_methods = ['bar'] def bar(self): pass def bang(self): pass foo = Foo()...
class ClearFuncsTestCase(TestCase): opts = salt.config.master_config(None) self.clear_funcs = salt.master.ClearFuncs(opts, {}) # runner tests def test_runner_token_not_authenticated(self):
class ClearFuncsTestCase(TestCase): opts = salt.config.master_config(None) self.clear_funcs = salt.master.ClearFuncs(opts, {}) def tearDown(self): del self.clear_funcs def test_get_method(self): assert getattr(self.clear_funcs, '_send_pub', None) is not None assert self...
class HiveCommandClient(HiveClient): if partition is None: stdout = run_hive_cmd('use {0}; show tables like "{1}";'.format(database, table)) return stdout and table in stdout else: stdout = run_hive_cmd("""use %s; show partitions %s partition ...
class HiveCommandClient(HiveClient): if partition is None: stdout = run_hive_cmd('use {0}; show tables like "{1}";'.format(database, table)) return stdout and table.lower() in stdout else: stdout = run_hive_cmd("""use %s; show partitions %s partition ...