buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class TestUtilsText(SimpleTestCase): truncator = text.Truncator('<i>Buenos d&iacute;as! &#x00bf;C&oacute;mo est&aacute;?</i>') self.assertEqual('<i>Buenos d&iacute;as! &#x00bf;C&oacute;mo…</i>', truncator.words(3, html=True)) truncator = text.Truncator('<p>I &lt;3 python, what about you?</p>') ...
class TestUtilsText(SimpleTestCase): truncator = text.Truncator('<i>Buenos d&iacute;as! &#x00bf;C&oacute;mo est&aacute;?</i>') self.assertEqual('<i>Buenos d&iacute;as! &#x00bf;C&oacute;mo…</i>', truncator.words(3, html=True)) truncator = text.Truncator('<p>I &lt;3 python, what about you?</p>') ...
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 KerasRegressor(BaseWrapper): Predictions. """ kwargs = self.filter_sk_params(Sequential.predict, kwargs) return np.squeeze(self.model.predict(x, **kwargs)) def score(self, x, y, **kwargs): """Returns the mean loss on the given test data and labels.
class KerasRegressor(BaseWrapper): Predictions. """ kwargs = self.filter_sk_params(Sequential.predict, kwargs) return np.squeeze(self.model.predict(x, **kwargs), axis=-1) def score(self, x, y, **kwargs): """Returns the mean loss on the given test data and labels.
def assert_regression_works(reg): assert preds.shape == (num_test, ) if __name__ == '__main__': pytest.main([__file__])
def assert_regression_works(reg): assert preds.shape == (num_test, ) def test_regression_predict_shape_correct_num_test_0(): assert_regression_predict_shape_correct(num_test=0) def test_regression_predict_shape_correct_num_test_1(): assert_regression_predict_shape_correct(num_test=1) def assert_regres...
optional. if bin_range is not None: bin_range = self.convert_xunits(bin_range) # We need to do to 'weights' what was done to 'x' if weights is not None: w = cbook._reshape_2D(weights, 'weights')
optional. if bin_range is not None: bin_range = self.convert_xunits(bin_range) if not cbook.is_scalar_or_string(bins): bins = self.convert_xunits(bins) # We need to do to 'weights' what was done to 'x' if weights is not None: w = cbook._reshape_2D(we...
def test_hist_datetime_datasets(): ax.hist(data, stacked=False) @pytest.mark.parametrize('data, expected_number_of_hists', [([], 1), ([[]], 1),
def test_hist_datetime_datasets(): ax.hist(data, stacked=False) @pytest.mark.parametrize("bins_preprocess", [mpl.dates.date2num, lambda bins: bins, lambda bins: np.asarray(bins).astype('datetime64')], ids=['date2...
def format(number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep='', # sign sign = '' if isinstance(number, Decimal): str_number = '{:f}'.format(number) else: str_number = str(number) if str_number[0] == '-':
def format(number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep='', # sign sign = '' if isinstance(number, Decimal): # Format values with more than 200 digits (an arbitrary cutoff) using # scientific notation to avoid high memory usage in {:f}'.format(). _, digits, exponen...
class TestNumberFormat(SimpleTestCase): ) self.assertEqual(nformat(Decimal('3.'), '.'), '3') self.assertEqual(nformat(Decimal('3.0'), '.'), '3.0') def test_decimal_subclass(self): class EuroDecimal(Decimal):
class TestNumberFormat(SimpleTestCase): ) self.assertEqual(nformat(Decimal('3.'), '.'), '3') self.assertEqual(nformat(Decimal('3.0'), '.'), '3.0') # Very large & small numbers. tests = [ ('9e9999', None, '9e+9999'), ('9e9999', 3, '9.000e+9999'), ...
from django.db import models from django.http import Http404 from django.template.engine import Engine from django.urls import get_mod_func, get_resolver, get_urlconf from django.utils.decorators import method_decorator from django.utils.inspect import ( func_accepts_kwargs, func_accepts_var_args, get_func_full_arg...
from django.db import models from django.http import Http404 from django.template.engine import Engine from django.urls import get_mod_func, get_resolver, get_urlconf from django.utils._os import safe_join from django.utils.decorators import method_decorator from django.utils.inspect import ( func_accepts_kwargs, f...
class TemplateDetailView(BaseAdminDocsView): else: # This doesn't account for template loaders (#24128). for index, directory in enumerate(default_engine.dirs): template_file = Path(directory) / template if template_file.exists(): with ...
class TemplateDetailView(BaseAdminDocsView): else: # This doesn't account for template loaders (#24128). for index, directory in enumerate(default_engine.dirs): template_file = Path(safe_join(directory, template)) if template_file.exists(): ...
class AdminDocViewTests(TestDataMixin, AdminDocsTestCase): self.assertContains(response, 'View documentation') @override_settings(TEMPLATES=[{ 'NAME': 'ONE', 'BACKEND': 'django.template.backends.django.DjangoTemplates',
class AdminDocViewTests(TestDataMixin, AdminDocsTestCase): self.assertContains(response, 'View documentation') @unittest.skipUnless(utils.docutils_is_available, 'no docutils installed.') class AdminDocViewDefaultEngineOnly(TestDataMixin, AdminDocsTestCase): def setUp(self): self.client.force_logi...
class PandasArray(ExtensionArray, ExtensionOpsMixin, NDArrayOperatorsMixin): if not lib.is_scalar(value): value = np.asarray(value) values = self._ndarray t = np.result_type(value, values) if t != self._ndarray.dtype: values = values.astype(t, casting="safe") ...
class PandasArray(ExtensionArray, ExtensionOpsMixin, NDArrayOperatorsMixin): if not lib.is_scalar(value): value = np.asarray(value) value = np.asarray(value, dtype=self._ndarray.dtype) self._ndarray[key] = value def __len__(self) -> int: return len(self._ndarray)
def test_basic_binop(): result = x + x expected = PandasArray(np.array([2, 4, 6])) tm.assert_extension_array_equal(result, expected)
def test_basic_binop(): result = x + x expected = PandasArray(np.array([2, 4, 6])) tm.assert_extension_array_equal(result, expected) @pytest.mark.parametrize("dtype", [None, object]) def test_setitem_object_typecode(dtype): arr = PandasArray(np.array(["a", "b", "c"], dtype=dtype)) arr[0] = "t" ...
def load_data(path='imdb.npz', num_words=None, skip_top=0, path = get_file(path, origin='https://s3.amazonaws.com/text-datasets/imdb.npz', file_hash='599dadb1135973df5b59232a0e9a887c') with np.load(path) as f: x_train, labels_train = f['x_train'], f['y_train'] ...
def load_data(path='imdb.npz', num_words=None, skip_top=0, path = get_file(path, origin='https://s3.amazonaws.com/text-datasets/imdb.npz', file_hash='599dadb1135973df5b59232a0e9a887c') with np.load(path, allow_pickle=True) as f: x_train, labels_train = f['x_train'...
async def request_body_to_args( for field in required_params: value: Any = None if received_body is not None: if field.shape in sequence_shapes and isinstance( received_body, FormData ): value = received_body.getlist...
async def request_body_to_args( for field in required_params: value: Any = None if received_body is not None: if ( field.shape in sequence_shapes or field.type_ in sequence_types ) and isinstance(received_body, FormData): ...
import os # Import salt libs import salt.utils.files import salt.utils.path # Import 3rd-party libs from salt.ext import six
import os # Import salt libs import salt.utils.files import salt.utils.path import salt.utils.verify # Import 3rd-party libs from salt.ext import six
def write(data, path, saltenv='base', index=0): if os.path.isabs(path): return ('The path passed in {0} is not relative to the environment ' '{1}').format(path, saltenv) dest = os.path.join(__opts__['pillar_roots'][saltenv][index], path) dest_dir = os.path.dirname(dest) if not os...
def write(data, path, saltenv='base', index=0): if os.path.isabs(path): return ('The path passed in {0} is not relative to the environment ' '{1}').format(path, saltenv) roots_dir = __opts__['pillar_roots'][saltenv][index] dest = os.path.join(roots_dir, path) if not salt.utils.ve...
def create_instance(objcls, settings, crawler, *args, **kwargs): ``*args`` and ``**kwargs`` are forwarded to the constructors. Raises ``ValueError`` if both ``settings`` and ``crawler`` are ``None``. """ if settings is None: if crawler is None: raise ValueError("Specify at least one...
def create_instance(objcls, settings, crawler, *args, **kwargs): ``*args`` and ``**kwargs`` are forwarded to the constructors. Raises ``ValueError`` if both ``settings`` and ``crawler`` are ``None``. Raises ``TypeError`` if the resulting instance is ``None`` (e.g. if an extension has not been implemen...
class UtilsMiscTestCase(unittest.TestCase): # 2. with from_settings() constructor # 3. with from_crawler() constructor # 4. with from_settings() and from_crawler() constructor spec_sets = ([], ['from_settings'], ['from_crawler'], ['from_settings', 'from_crawler...
class UtilsMiscTestCase(unittest.TestCase): # 2. with from_settings() constructor # 3. with from_crawler() constructor # 4. with from_settings() and from_crawler() constructor spec_sets = ( ['__qualname__'], ['__qualname__', 'from_settings'], ['_...
class UtilsMiscTestCase(unittest.TestCase): _test_with_crawler(m, settings, crawler) # Check adoption of crawler settings m = mock.MagicMock(spec_set=['from_settings']) create_instance(m, None, crawler, *args, **kwargs) m.from_settings.assert_called_once_with(crawler.setting...
class UtilsMiscTestCase(unittest.TestCase): _test_with_crawler(m, settings, crawler) # Check adoption of crawler settings m = mock.MagicMock(spec_set=['__qualname__', 'from_settings']) create_instance(m, None, crawler, *args, **kwargs) m.from_settings.assert_called_once_with...
class UtilsMiscTestCase(unittest.TestCase): with self.assertRaises(ValueError): create_instance(m, None, None) def test_set_environ(self): assert os.environ.get('some_test_environ') is None with set_environ(some_test_environ='test_value'):
class UtilsMiscTestCase(unittest.TestCase): with self.assertRaises(ValueError): create_instance(m, None, None) m.from_settings.return_value = None with self.assertRaises(TypeError): create_instance(m, settings, None) def test_set_environ(self): assert os.env...
from jose.constants import ALGORITHMS from jose.exceptions import JWKError from jose.utils import base64url_decode # PyCryptodome's RSA module doesn't have PyCrypto's _RSAobj class # Instead it has a class named RsaKey, which serves the same purpose.
from jose.constants import ALGORITHMS from jose.exceptions import JWKError from jose.utils import base64url_decode from jose.utils import constant_time_string_compare # PyCryptodome's RSA module doesn't have PyCrypto's _RSAobj class # Instead it has a class named RsaKey, which serves the same purpose.
def sign(self, msg): return hmac.new(self.prepared_key, msg, self.hash_alg).digest() def verify(self, msg, sig): return sig == self.sign(msg) class RSAKey(Key):
def sign(self, msg): return hmac.new(self.prepared_key, msg, self.hash_alg).digest() def verify(self, msg, sig): return constant_time_string_compare(sig, self.sign(msg)) class RSAKey(Key):
import base64 def calculate_at_hash(access_token, hash_alg):
import base64 import hmac def calculate_at_hash(access_token, hash_alg):
def timedelta_total_seconds(delta): delta (timedelta): A timedelta to convert to seconds. """ return delta.days * 24 * 60 * 60 + delta.seconds
def timedelta_total_seconds(delta): delta (timedelta): A timedelta to convert to seconds. """ return delta.days * 24 * 60 * 60 + delta.seconds def constant_time_string_compare(a, b): """Helper for comparing string in constant time, independent of the python version being used. Args: ...
import base64 import binascii import hashlib import importlib from collections import OrderedDict from django.conf import settings
import base64 import binascii import hashlib import importlib import warnings from collections import OrderedDict from django.conf import settings
def check_password(password, encoded, setter=None, preferred='default'): preferred = get_hasher(preferred) hasher = identify_hasher(encoded) must_update = hasher.algorithm != preferred.algorithm if not must_update: must_update = preferred.must_update(encoded) is_correct = hasher.verify(pass...
def check_password(password, encoded, setter=None, preferred='default'): preferred = get_hasher(preferred) hasher = identify_hasher(encoded) hasher_changed = hasher.algorithm != preferred.algorithm must_update = hasher_changed or preferred.must_update(encoded) is_correct = hasher.verify(password, e...
class BasePasswordHasher(object): def must_update(self, encoded): return False class PBKDF2PasswordHasher(BasePasswordHasher): """
class BasePasswordHasher(object): def must_update(self, encoded): return False def harden_runtime(self, password, encoded): """ Bridge the runtime gap between the work factor supplied in `encoded` and the work factor suggested by this hasher. Taking PBKDF2 as an example...
class PBKDF2PasswordHasher(BasePasswordHasher): algorithm, iterations, salt, hash = encoded.split('$', 3) return int(iterations) != self.iterations class PBKDF2SHA1PasswordHasher(PBKDF2PasswordHasher): """
class PBKDF2PasswordHasher(BasePasswordHasher): algorithm, iterations, salt, hash = encoded.split('$', 3) return int(iterations) != self.iterations def harden_runtime(self, password, encoded): algorithm, iterations, salt, hash = encoded.split('$', 3) extra_iterations = self.iteratio...
class BCryptSHA256PasswordHasher(BasePasswordHasher): def verify(self, password, encoded): algorithm, data = encoded.split('$', 1) assert algorithm == self.algorithm bcrypt = self._load_library() # Hash the password prior to using bcrypt to prevent password # truncation as d...
class BCryptSHA256PasswordHasher(BasePasswordHasher): def verify(self, password, encoded): algorithm, data = encoded.split('$', 1) assert algorithm == self.algorithm encoded_2 = self.encode(password, force_bytes(data)) return constant_time_compare(encoded, encoded_2) def safe_su...
class BCryptSHA256PasswordHasher(BasePasswordHasher): algorithm, empty, algostr, rounds, data = encoded.split('$', 4) return int(rounds) != self.rounds class BCryptPasswordHasher(BCryptSHA256PasswordHasher): """
class BCryptSHA256PasswordHasher(BasePasswordHasher): algorithm, empty, algostr, rounds, data = encoded.split('$', 4) return int(rounds) != self.rounds def harden_runtime(self, password, encoded): _, data = encoded.split('$', 1) salt = data[:29] # Length of the salt in bcrypt. ...
class SHA1PasswordHasher(BasePasswordHasher): (_('hash'), mask_hash(hash)), ]) class MD5PasswordHasher(BasePasswordHasher): """
class SHA1PasswordHasher(BasePasswordHasher): (_('hash'), mask_hash(hash)), ]) def harden_runtime(self, password, encoded): pass class MD5PasswordHasher(BasePasswordHasher): """
class MD5PasswordHasher(BasePasswordHasher): (_('hash'), mask_hash(hash)), ]) class UnsaltedSHA1PasswordHasher(BasePasswordHasher): """
class MD5PasswordHasher(BasePasswordHasher): (_('hash'), mask_hash(hash)), ]) def harden_runtime(self, password, encoded): pass class UnsaltedSHA1PasswordHasher(BasePasswordHasher): """
class UnsaltedSHA1PasswordHasher(BasePasswordHasher): (_('hash'), mask_hash(hash)), ]) class UnsaltedMD5PasswordHasher(BasePasswordHasher): """
class UnsaltedSHA1PasswordHasher(BasePasswordHasher): (_('hash'), mask_hash(hash)), ]) def harden_runtime(self, password, encoded): pass class UnsaltedMD5PasswordHasher(BasePasswordHasher): """
class UnsaltedMD5PasswordHasher(BasePasswordHasher): (_('hash'), mask_hash(encoded, show=3)), ]) class CryptPasswordHasher(BasePasswordHasher): """
class UnsaltedMD5PasswordHasher(BasePasswordHasher): (_('hash'), mask_hash(encoded, show=3)), ]) def harden_runtime(self, password, encoded): pass class CryptPasswordHasher(BasePasswordHasher): """
class CryptPasswordHasher(BasePasswordHasher): (_('salt'), salt), (_('hash'), mask_hash(data, show=3)), ])
class CryptPasswordHasher(BasePasswordHasher): (_('salt'), salt), (_('hash'), mask_hash(data, show=3)), ]) def harden_runtime(self, password, encoded): pass
from django.contrib.auth.hashers import ( check_password, get_hasher, identify_hasher, is_password_usable, make_password, ) from django.test import SimpleTestCase from django.test.utils import override_settings from django.utils import six try: import crypt
from django.contrib.auth.hashers import ( check_password, get_hasher, identify_hasher, is_password_usable, make_password, ) from django.test import SimpleTestCase, mock from django.test.utils import override_settings from django.utils import six from django.utils.encoding import force_bytes try: import cry...
class TestUtilsHashPass(SimpleTestCase): finally: hasher.rounds = old_rounds def test_unusable(self): encoded = make_password(None) self.assertEqual(len(encoded), len(UNUSABLE_PASSWORD_PREFIX) + UNUSABLE_PASSWORD_SUFFIX_LENGTH)
class TestUtilsHashPass(SimpleTestCase): finally: hasher.rounds = old_rounds @skipUnless(bcrypt, "bcrypt not installed") def test_bcrypt_harden_runtime(self): hasher = get_hasher('bcrypt') self.assertEqual('bcrypt', hasher.algorithm) with mock.patch.object(hasher, '...
class TestUtilsHashPass(SimpleTestCase): finally: hasher.iterations = old_iterations def test_pbkdf2_upgrade_new_hasher(self): hasher = get_hasher('default') self.assertEqual('pbkdf2_sha256', hasher.algorithm)
class TestUtilsHashPass(SimpleTestCase): finally: hasher.iterations = old_iterations def test_pbkdf2_harden_runtime(self): hasher = get_hasher('default') self.assertEqual('pbkdf2_sha256', hasher.algorithm) with mock.patch.object(hasher, 'iterations', 1): enc...
class TestUtilsHashPass(SimpleTestCase): self.assertTrue(check_password('letmein', encoded, setter)) self.assertTrue(state['upgraded']) def test_load_library_no_algorithm(self): with self.assertRaises(ValueError) as e: BasePasswordHasher()._load_library()
class TestUtilsHashPass(SimpleTestCase): self.assertTrue(check_password('letmein', encoded, setter)) self.assertTrue(state['upgraded']) def test_check_password_calls_harden_runtime(self): hasher = get_hasher('default') encoded = make_password('letmein') with mock.pa...
default: :rc:`scatter.edgecolors` marker_obj.get_transform()) if not marker_obj.is_filled(): edgecolors = 'face' linewidths = rcParams['lines.linewidth'] offsets = np.ma.column_stack([x, y])
default: :rc:`scatter.edgecolors` marker_obj.get_transform()) if not marker_obj.is_filled(): edgecolors = 'face' if linewidths is None: linewidths = rcParams['lines.linewidth'] elif np.iterable(linewidths): linewidths = [ ...
class TestScatter: ax_test.scatter(np.ones(3), range(3), c=rgb) ax_test.scatter(np.ones(4)*2, range(4), c=rgba) def _params(c=None, xsize=2, *, edgecolors=None, **kwargs): return (c, edgecolors, kwargs if kwargs is not None else {}, xsize)
class TestScatter: ax_test.scatter(np.ones(3), range(3), c=rgb) ax_test.scatter(np.ones(4)*2, range(4), c=rgba) def test_scatter_linewidths(self): x = np.arange(5) fig, ax = plt.subplots() for i in range(3): pc = ax.scatter(x, np.full(5, i), c=f'C{i}', marker='x...
try: import pickle except ImportError: import cPickle as pickle import marshal import os import socket
import base64 import hashlib import hmac try: import cPickle as pickle except ImportError: import pickle import marshal import os import socket
import tempfile import threading class PythonFileRunner(object): """A class for running python project files"""
import tempfile import threading def _compat_compare_digest(a, b): """Implementation of hmac.compare_digest for python < 2.7.7. This function uses an approach designed to prevent timing analysis by avoiding content-based short circuiting behaviour, making it appropriate for cryptography. """ ...
class _SocketReceiver(_MessageReceiver): def __init__(self): self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.data_port = 3037 while self.data_port < 4000: try: self.server_socket.bind(('', self.data_port)) break ...
class _SocketReceiver(_MessageReceiver): def __init__(self): self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.data_port = 3037 self.key = os.urandom(32) while self.data_port < 4000: try: self.server_socket.bind(('localhost', sel...
def __rope_start_everything(): import sys import socket try: import pickle except ImportError: import cPickle as pickle import marshal import inspect import types import threading import rope.base.utils.pycompat as pycompat class _MessageSender(object):
def __rope_start_everything(): import sys import socket try: import cPickle as pickle except ImportError: import pickle import marshal import inspect import types import threading import rope.base.utils.pycompat as pycompat import base64 import hashlib imp...
def __rope_start_everything(): class _SocketSender(_MessageSender): def __init__(self, port): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', port)) self.my_file = s.makefile('wb') def send_data(self, data): if not self...
def __rope_start_everything(): class _SocketSender(_MessageSender): def __init__(self, port, key): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', port)) self.my_file = s.makefile('wb') self.key = base64.b64decode(key) ...
def __rope_start_everything(): def __init__(self, send_info, project_root): self.project_root = project_root if send_info.isdigit(): self.sender = _SocketSender(int(send_info)) else: self.sender = _FileSender(send_info)
def __rope_start_everything(): def __init__(self, send_info, project_root): self.project_root = project_root if send_info[0].isdigit(): port, key = send_info.split(':', 1) self.sender = _SocketSender(int(port), key) else: self....
from rope.base.exceptions import ModuleNotFoundError from rope.base.resources import File, Folder, _ResourceMatcher try: import pickle except ImportError: import cPickle as pickle class _Project(object):
from rope.base.exceptions import ModuleNotFoundError from rope.base.resources import File, Folder, _ResourceMatcher try: import cPickle as pickle except ImportError: import pickle class _Project(object):
except ImportError: import ropetest.projecttest import ropetest.codeanalyzetest import ropetest.type_hinting_test import ropetest.pycoretest import ropetest.pyscopestest
except ImportError: import ropetest.projecttest import ropetest.codeanalyzetest import ropetest.doatest import ropetest.type_hinting_test import ropetest.pycoretest import ropetest.pyscopestest
def suite(): result = unittest.TestSuite() result.addTests(ropetest.projecttest.suite()) result.addTests(ropetest.codeanalyzetest.suite()) result.addTests(ropetest.type_hinting_test.suite()) result.addTests(ropetest.pycoretest.suite()) result.addTests(ropetest.pyscopestest.suite())
def suite(): result = unittest.TestSuite() result.addTests(ropetest.projecttest.suite()) result.addTests(ropetest.codeanalyzetest.suite()) result.addTests(ropetest.doatest.suite()) result.addTests(ropetest.type_hinting_test.suite()) result.addTests(ropetest.pycoretest.suite()) result.addTest...
def get_flat_dependant(dependant: Dependant) -> Dependant: def is_scalar_field(field: Field) -> bool: return ( field.shape == Shape.SINGLETON and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, sequence_types + (dict,)) and not isinstance(fiel...
def get_flat_dependant(dependant: Dependant) -> Dependant: def is_scalar_field(field: Field) -> bool: if not ( field.shape == Shape.SINGLETON and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, sequence_types + (dict,)) and not isinstance(fiel...
async def get_file( try: length = await make_deferred_yieldable( readBodyToFile(response, output_stream, max_size) ) except SynapseError: # This can happen e.g. because the body is too large. raise except Exception as e: ...
async def get_file( try: length = await make_deferred_yieldable( read_body_with_max_size(response, output_stream, max_size) ) except BodyExceededMaxSize: SynapseError( 502, "Requested file is too large > %r bytes" % (ma...
def _timeout_to_request_timed_out_error(f: Failure): return f class _ReadBodyToFileProtocol(protocol.Protocol): def __init__( self, stream: BinaryIO, deferred: defer.Deferred, max_size: Optional[int] ):
def _timeout_to_request_timed_out_error(f: Failure): return f class BodyExceededMaxSize(Exception): """The maximum allowed size of the HTTP body was exceeded.""" class _ReadBodyWithMaxSizeProtocol(protocol.Protocol): def __init__( self, stream: BinaryIO, deferred: defer.Deferred, max_size: Optio...
def dataReceived(self, data: bytes) -> None: self.stream.write(data) self.length += len(data) if self.max_size is not None and self.length >= self.max_size: self.deferred.errback( SynapseError( 502, "Requested file is too large ...
def dataReceived(self, data: bytes) -> None: self.stream.write(data) self.length += len(data) if self.max_size is not None and self.length >= self.max_size: self.deferred.errback(BodyExceededMaxSize()) self.deferred = defer.Deferred() self.transport.loseConnec...
def connectionLost(self, reason: Failure) -> None: self.deferred.errback(reason) def readBodyToFile( response: IResponse, stream: BinaryIO, max_size: Optional[int] ) -> defer.Deferred: """ Read a HTTP response body to a file-object. Optionally enforcing a maximum file size. Args: ...
def connectionLost(self, reason: Failure) -> None: self.deferred.errback(reason) def read_body_with_max_size( response: IResponse, stream: BinaryIO, max_size: Optional[int] ) -> defer.Deferred: """ Read a HTTP response body to a file-object. Optionally enforcing a maximum file size. If th...
def readBodyToFile( """ d = defer.Deferred() response.deliverBody(_ReadBodyToFileProtocol(stream, d, max_size)) return d
def readBodyToFile( """ d = defer.Deferred() response.deliverBody(_ReadBodyWithMaxSizeProtocol(stream, d, max_size)) return d
import logging import random import time from typing import Callable, Dict, Optional, Tuple import attr from twisted.internet import defer from twisted.internet.interfaces import IReactorTime from twisted.web.client import RedirectAgent, readBody from twisted.web.http import stringToDatetime from twisted.web.http_hea...
import logging import random import time from io import BytesIO from typing import Callable, Dict, Optional, Tuple import attr from twisted.internet import defer from twisted.internet.interfaces import IReactorTime from twisted.web.client import RedirectAgent from twisted.web.http import stringToDatetime from twisted...
# lower bound for .well-known cache period WELL_KNOWN_MIN_CACHE_PERIOD = 5 * 60 # Attempt to refetch a cached well-known N% of the TTL before it expires. # e.g. if set to 0.2 and we have a cached entry with a TTL of 5mins, then # we'll start trying to refetch 1 minute before it expires.
# lower bound for .well-known cache period WELL_KNOWN_MIN_CACHE_PERIOD = 5 * 60 # The maximum size (in bytes) to allow a well-known file to be. WELL_KNOWN_MAX_SIZE = 50 * 1024 # 50 KiB # Attempt to refetch a cached well-known N% of the TTL before it expires. # e.g. if set to 0.2 and we have a cached entry with a TTL...
async def _make_well_known_request( server_name: name of the server, from the requested url retry: Whether to retry the request if it fails. Returns: Returns the response object and body. Response may be a non-200 response. """
async def _make_well_known_request( server_name: name of the server, from the requested url retry: Whether to retry the request if it fails. Raises: _FetchWellKnownFailure if we fail to lookup a result Returns: Returns the response object and body. Respo...
async def _make_well_known_request( b"GET", uri, headers=Headers(headers) ) ) body = await make_deferred_yieldable(readBody(response)) if 500 <= response.code < 600: raise Exception("Non-200 response %s" % (...
async def _make_well_known_request( b"GET", uri, headers=Headers(headers) ) ) body_stream = BytesIO() await make_deferred_yieldable( read_body_with_max_size(response, body_stream, WELL_KNOWN_MAX_SIZE) ...
async def _make_well_known_request( except defer.CancelledError: # Bail if we've been cancelled raise except Exception as e: if not retry or i >= WELL_KNOWN_RETRY_ATTEMPTS: logger.info("Error fetching %s: %s", uri_str, e)
async def _make_well_known_request( except defer.CancelledError: # Bail if we've been cancelled raise except BodyExceededMaxSize: # If the well-known file was too large, do not keep attempting # to download it, but consider it a tem...
import synapse.metrics import synapse.util.retryutils from synapse.api.errors import ( FederationDeniedError, HttpResponseException, RequestSendFailed, ) from synapse.http import QuieterFileBodyProducer from synapse.http.client import ( BlacklistingAgentWrapper, BlacklistingReactorWrapper, encod...
import synapse.metrics import synapse.util.retryutils from synapse.api.errors import ( Codes, FederationDeniedError, HttpResponseException, RequestSendFailed, SynapseError, ) from synapse.http import QuieterFileBodyProducer from synapse.http.client import ( BlacklistingAgentWrapper, Blacklis...
async def get_file( headers = dict(response.headers.getAllRawHeaders()) try: d = readBodyToFile(response, output_stream, max_size) d.addTimeout(self.default_timeout, self.reactor) length = await make_deferred_yieldable(d) except Exception as e: lo...
async def get_file( headers = dict(response.headers.getAllRawHeaders()) try: d = read_body_with_max_size(response, output_stream, max_size) d.addTimeout(self.default_timeout, self.reactor) length = await make_deferred_yieldable(d) except BodyExceededMaxSize: ...
from synapse.http.federation.matrix_federation_agent import MatrixFederationAgent from synapse.http.federation.srv_resolver import Server from synapse.http.federation.well_known_resolver import ( WellKnownResolver, _cache_period_from_headers, )
from synapse.http.federation.matrix_federation_agent import MatrixFederationAgent from synapse.http.federation.srv_resolver import Server from synapse.http.federation.well_known_resolver import ( WELL_KNOWN_MAX_SIZE, WellKnownResolver, _cache_period_from_headers, )
def test_well_known_cache_with_temp_failure(self): r = self.successResultOf(fetch_d) self.assertEqual(r.delegated_server, None) def test_srv_fallbacks(self): """Test that other SRV results are tried if the first one fails. """
def test_well_known_cache_with_temp_failure(self): r = self.successResultOf(fetch_d) self.assertEqual(r.delegated_server, None) def test_well_known_too_large(self): """A well-known query that returns a result which is too large should be rejected.""" self.reactor.lookups["testserv"]...
class DataFrame(NDFrame): scalar """ if takeable: series = self._iget_item_cache(col) return com.maybe_box_datetimelike(series._values[index]) series = self._get_item_cache(col) engine = self.index._engine
class DataFrame(NDFrame): scalar """ if takeable: series = self._ixs(col, axis=1) return series._values[index] series = self._get_item_cache(col) engine = self.index._engine
""" test scalar indexing, including at and iat """ import numpy as np import pytest
""" test scalar indexing, including at and iat """ from datetime import datetime, timedelta import numpy as np import pytest
class TestScalar2: s = Series([1, 2]) result = s[np.array(0)] assert result == 1
class TestScalar2: s = Series([1, 2]) result = s[np.array(0)] assert result == 1 def test_iat_dont_wrap_object_datetimelike(): # GH#32809 .iat calls go through DataFrame._get_value, should not # call maybe_box_datetimelike dti = date_range("2016-01-01", periods=3) tdi = dti - ...
import stat import tarfile import zipfile class ArchiveException(Exception): """
import stat import tarfile import zipfile from django.core.exceptions import SuspiciousOperation class ArchiveException(Exception): """
class BaseArchive: return False return True def extract(self): raise NotImplementedError('subclasses of BaseArchive must provide an extract() method')
class BaseArchive: return False return True def target_filename(self, to_path, name): target_path = os.path.abspath(to_path) filename = os.path.abspath(os.path.join(target_path, name)) if not filename.startswith(target_path): raise SuspiciousOperation("Ar...
class TarArchive(BaseArchive): name = member.name if leading: name = self.split_leading_dir(name)[1] filename = os.path.join(to_path, name) if member.isdir(): if filename: os.makedirs(filename, exist_ok=True)
class TarArchive(BaseArchive): name = member.name if leading: name = self.split_leading_dir(name)[1] filename = self.target_filename(to_path, name) if member.isdir(): if filename: os.makedirs(filename, exist_ok=True)
class ZipArchive(BaseArchive): info = self._archive.getinfo(name) if leading: name = self.split_leading_dir(name)[1] filename = os.path.join(to_path, name) if filename.endswith(('/', '\\')): # A directory os.makedirs(filenam...
class ZipArchive(BaseArchive): info = self._archive.getinfo(name) if leading: name = self.split_leading_dir(name)[1] if not name: continue filename = self.target_filename(to_path, name) if name.endswith(('/', '\\')): ...
import sys import tempfile import unittest from django.utils import archive
import sys import tempfile import unittest from django.core.exceptions import SuspiciousOperation from django.test import SimpleTestCase from django.utils import archive
class TestArchive(unittest.TestCase): # A file is readable even if permission data is missing. filepath = os.path.join(tmpdir, 'no_permissions') self.assertEqual(os.stat(filepath).st_mode & mask, 0o666 & ~umask)
class TestArchive(unittest.TestCase): # A file is readable even if permission data is missing. filepath = os.path.join(tmpdir, 'no_permissions') self.assertEqual(os.stat(filepath).st_mode & mask, 0o666 & ~umask) class TestArchiveInvalid(SimpleTestCase): def test_ext...
class TFOptimizer(Optimizer): @interfaces.legacy_get_updates_support def get_updates(self, loss, params): grads = self.optimizer.compute_gradients(loss, params) self.updates = [K.update_add(self.iterations, 1)] opt_update = self.optimizer.apply_gradients( grads, global_step=...
class TFOptimizer(Optimizer): @interfaces.legacy_get_updates_support def get_updates(self, loss, params): grads = self.optimizer.compute_gradients(loss, var_list=params) self.updates = [K.update_add(self.iterations, 1)] opt_update = self.optimizer.apply_gradients( grads, glo...
def test_tfoptimizer(): optimizer.from_config(None) if __name__ == '__main__': pytest.main([__file__])
def test_tfoptimizer(): optimizer.from_config(None) @pytest.mark.skipif((K.backend() != 'tensorflow'), reason='Requires TensorFlow backend') def test_tfoptimizer_pass_correct_named_params_to_native_tensorflow_optimizer(): from keras import constraints from tensorflow import train ...
class TestUtil(unittest.TestCase): def test_urljoin(self): self.assertEqual(urljoin('http://foo.de/', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt') self.assertEqual(urljoin('//foo.de/', '/a/b/c.txt'), '//foo.de/a/b/c.txt') self.assertEqual(urljoin('http://foo.de/', 'a/b/c.txt'), 'http://foo.de/...
class TestUtil(unittest.TestCase): def test_urljoin(self): self.assertEqual(urljoin('http://foo.de/', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt') self.assertEqual(urljoin(b'http://foo.de/', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt') self.assertEqual(urljoin('http://foo.de/', b'/a/b/c.txt'), 'h...
def base_url(url): def urljoin(base, path): if not isinstance(path, compat_str) or not path: return None if re.match(r'^(?:https?:)?//', path): return path if not isinstance(base, compat_str) or not re.match(r'^(?:https?:)?//', base): return None return compat_urlparse.urljoin(...
def base_url(url): def urljoin(base, path): if isinstance(path, bytes): path = path.decode('utf-8') if not isinstance(path, compat_str) or not path: return None if re.match(r'^(?:https?:)?//', path): return path if isinstance(base, bytes): base = base.decode('utf-8') ...
def init_ndarray(values, index, columns, dtype=None, copy=False): return arrays_to_mgr([values], columns, index, columns, dtype=dtype) elif is_extension_array_dtype(values) or is_extension_array_dtype(dtype): # GH#19157 if columns is None: columns = [0] return arrays_to_m...
def init_ndarray(values, index, columns, dtype=None, copy=False): return arrays_to_mgr([values], columns, index, columns, dtype=dtype) elif is_extension_array_dtype(values) or is_extension_array_dtype(dtype): # GH#19157 if isinstance(values, np.ndarray) and values.ndim > 1: # GH...
class TestDataFrameConstructorWithDatetimeTZ: "datetime64[ns, CET]", ] assert (res.dtypes == expected_dtypes).all()
class TestDataFrameConstructorWithDatetimeTZ: "datetime64[ns, CET]", ] assert (res.dtypes == expected_dtypes).all() def test_from_2d_ndarray_with_dtype(self): # GH#12513 array_dim2 = np.arange(10).reshape((5, 2)) df = pd.DataFrame(array_dim2, dtype="datetime64[ns...
class ArchRunner(Runner): elif abs(now - mktime_tz(tup)) > \ mm_cfg.ARCHIVER_ALLOWABLE_SANE_DATE_SKEW: clobber = 1 except ValueError: # The likely cause of this is that the year in the Date: field # is horribly inco...
class ArchRunner(Runner): elif abs(now - mktime_tz(tup)) > \ mm_cfg.ARCHIVER_ALLOWABLE_SANE_DATE_SKEW: clobber = 1 except (ValueError, OverflowError): # The likely cause of this is that the year in the Date: field #...
def _clone_functional_model(model, input_tensors=None): kwargs['mask'] = computed_mask output_tensors = to_list( layer(computed_tensor, **kwargs)) output_masks = to_list( layer.compute_mask(computed_tenso...
def _clone_functional_model(model, input_tensors=None): kwargs['mask'] = computed_mask output_tensors = to_list( layer(computed_tensor, **kwargs)) if layer.supports_masking: output_masks = to_list( ...
def _clone_functional_model(model, input_tensors=None): kwargs['mask'] = computed_masks output_tensors = to_list( layer(computed_tensors, **kwargs)) output_masks = to_list( layer.compute_mask(computed_ten...
def _clone_functional_model(model, input_tensors=None): kwargs['mask'] = computed_masks output_tensors = to_list( layer(computed_tensors, **kwargs)) if layer.supports_masking: output_masks = to_list( ...
def test_clone_functional_model(): new_model.train_on_batch(None, val_out) def test_clone_sequential_model(): val_a = np.random.random((10, 4)) val_out = np.random.random((10, 4))
def test_clone_functional_model(): new_model.train_on_batch(None, val_out) def test_clone_functional_model_with_multi_outputs(): input_layer = keras.Input(shape=(4,)) # Layer with single input and multiple outputs layer1 = keras.layers.Lambda(lambda x: [x + 1, x], lam...
def gendata4(): data = [gendata1(), gendata2(), gendata4()] class TestAudioop(unittest.TestCase):
def gendata4(): data = [gendata1(), gendata2(), gendata4()] INVALID_DATA = [ ('abc', 0), ('abc', 2), ('abc', 4), ] class TestAudioop(unittest.TestCase):
def test_negativelen(self): self.assertRaises(audioop.error, audioop.findmax, ''.join(chr(x) for x in range(256)), -2392392) def test_main(): run_unittest(TestAudioop)
def test_negativelen(self): self.assertRaises(audioop.error, audioop.findmax, ''.join(chr(x) for x in range(256)), -2392392) def test_issue7673(self): state = None for data, size in INVALID_DATA: size2 = size self.assertRaises(audioop.error, audioop.getsa...
# All kinds of schemes besides just javascript: that can cause # execution: _is_image_dataurl = re.compile( r'^data:image/.+;base64', re.I).search _is_possibly_malicious_scheme = re.compile( r'(?:javascript|jscript|livescript|vbscript|data|about|mocha):', re.I).search def _is_javascript_scheme(s): if _...
# All kinds of schemes besides just javascript: that can cause # execution: _find_image_dataurls = re.compile( r'^data:image/(.+);base64,', re.I).findall _is_possibly_malicious_scheme = re.compile( r'(javascript|jscript|livescript|vbscript|data|about|mocha):', re.I).findall # SVG images can contain script ...
import unittest from lxml.tests.common_imports import make_doctest
import base64 import gzip import unittest from lxml.tests.common_imports import make_doctest
def test_sneaky_import_in_style(self): cleaned, "%s -> %s" % (style_code, cleaned)) def test_formaction_attribute_in_button_input(self): # The formaction attribute overrides the form's action and should be # treated as a malicious link attribute
def test_sneaky_import_in_style(self): cleaned, "%s -> %s" % (style_code, cleaned)) def test_svg_data_links(self): # Remove SVG images with potentially insecure content. svg = b'<svg onload="alert(123)" />' svgz = gzip.compress(svg) svg_b64 = base64...
class ModelAdmin(BaseModelAdmin): ) def get_inline_formsets(self, request, formsets, inline_instances, obj=None): inline_admin_formsets = [] for inline, formset in zip(inline_instances, formsets): fieldsets = list(inline.get_fieldsets(request, obj)) readonly = list(i...
class ModelAdmin(BaseModelAdmin): ) def get_inline_formsets(self, request, formsets, inline_instances, obj=None): # Edit permissions on parent model are required for editable inlines. can_edit_parent = self.has_change_permission(request, obj) if obj else self.has_add_permission(request) ...
class ModelAdmin(BaseModelAdmin): else: obj = self.get_object(request, unquote(object_id), to_field) if not self.has_view_or_change_permission(request, obj): raise PermissionDenied if obj is None: return self._get_obj_does_not_exist_redirect(...
class ModelAdmin(BaseModelAdmin): else: obj = self.get_object(request, unquote(object_id), to_field) if request.method == 'POST': if not self.has_change_permission(request, obj): raise PermissionDenied else: if not self.has...
from django.contrib.admin import ModelAdmin, TabularInline from django.contrib.admin.helpers import InlineAdminForm from django.contrib.admin.tests import AdminSeleniumTestCase
from selenium.common.exceptions import NoSuchElementException from django.contrib.admin import ModelAdmin, TabularInline from django.contrib.admin.helpers import InlineAdminForm from django.contrib.admin.tests import AdminSeleniumTestCase
class TestInlinePermissions(TestCase): ) @override_settings(ROOT_URLCONF='admin_inlines.urls') class SeleniumTests(AdminSeleniumTestCase):
class TestInlinePermissions(TestCase): ) @override_settings(ROOT_URLCONF='admin_inlines.urls') class TestReadOnlyChangeViewInlinePermissions(TestCase): @classmethod def setUpTestData(cls): cls.user = User.objects.create_user('testing', password='password', is_staff=True) cls.user.user...
class SeleniumTests(AdminSeleniumTestCase): self.assertEqual(ProfileCollection.objects.all().count(), 1) self.assertEqual(Profile.objects.all().count(), 3) def test_delete_inlines(self): self.admin_login(username='super', password='secret') self.selenium.get(self.live_server_url + r...
class SeleniumTests(AdminSeleniumTestCase): self.assertEqual(ProfileCollection.objects.all().count(), 1) self.assertEqual(Profile.objects.all().count(), 3) def test_add_inline_link_absent_for_view_only_parent_model(self): user = User.objects.create_user('testing', password='password', is_st...