buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
def test_multi_input_multi_output_recursion(self): json_str = model.to_json() models.model_from_json(json_str) if yaml is not None: yaml_str = model.to_yaml() models.model_from_yaml(yaml_str) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_invalid_g...
def test_multi_input_multi_output_recursion(self): json_str = model.to_json() models.model_from_json(json_str) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_invalid_graphs(self): a = layers.Input(shape=(32,), name='input_a')
def test_constant_initializer_with_numpy(self): json_str = model.to_json() models.model_from_json(json_str) if yaml is not None: yaml_str = model.to_yaml() models.model_from_yaml(yaml_str) def test_subclassed_error_if_init_not_called(self): class MyNetwork(training_lib.Model):
def test_constant_initializer_with_numpy(self): json_str = model.to_json() models.model_from_json(json_str) def test_subclassed_error_if_init_not_called(self): class MyNetwork(training_lib.Model):
import h5py except ImportError: h5py = None try: import yaml except ImportError: yaml = None # pylint: enable=g-import-not-at-top
import h5py except ImportError: h5py = None # pylint: enable=g-import-not-at-top
def to_json(self, **kwargs): def to_yaml(self, **kwargs): """Returns a yaml string containing the network configuration. To load a network from a yaml save file, use `keras.models.model_from_yaml(yaml_string, custom_objects={})`.
def to_json(self, **kwargs): def to_yaml(self, **kwargs): """Returns a yaml string containing the network configuration. Note: Since TF 2.6, this method is no longer supported and will raise a RuntimeError. To load a network from a yaml save file, use `keras.models.model_from_yaml(yaml_string, c...
def to_yaml(self, **kwargs): A YAML string. Raises: ImportError: if yaml module is not found. """ if yaml is None: raise ImportError( 'Requires yaml module installed (`pip install pyyaml`).') return yaml.dump(self._updated_config(), **kwargs) def reset_states(self): ...
def to_yaml(self, **kwargs): A YAML string. Raises: RuntimeError: announces that the method poses a security risk """ raise RuntimeError( 'Method `model.to_yaml()` has been removed due to security risk of ' 'arbitrary code execution. Please use `model.to_json()` instead.' ...
from tensorflow.python.keras.saving.saved_model import json_utils from tensorflow.python.util.tf_export import keras_export # pylint: disable=g-import-not-at-top try: import yaml except ImportError: yaml = None # pylint: enable=g-import-not-at-top @keras_export('keras.models.model_from_config') def model_from_co...
from tensorflow.python.keras.saving.saved_model import json_utils from tensorflow.python.util.tf_export import keras_export @keras_export('keras.models.model_from_config') def model_from_config(config, custom_objects=None): """Instantiates a Keras model from its config. Usage: ``` # for a Functional API mode...
def model_from_config(config, custom_objects=None): def model_from_yaml(yaml_string, custom_objects=None): """Parses a yaml model configuration file and returns a model instance. Usage: >>> model = tf.keras.Sequential([ ... tf.keras.layers.Dense(5, input_shape=(3,)), ... tf.keras.layers.Softmax()]) ...
def model_from_config(config, custom_objects=None): def model_from_yaml(yaml_string, custom_objects=None): """Parses a yaml model configuration file and returns a model instance. Note: Since TF 2.6, this method is no longer supported and will raise a RuntimeError. Args: yaml_string: YAML string or open ...
def model_from_yaml(yaml_string, custom_objects=None): A Keras model instance (uncompiled). Raises: ImportError: if yaml module is not found. """ if yaml is None: raise ImportError('Requires yaml module installed (`pip install pyyaml`).') # The method unsafe_load only exists in PyYAML 5.x+, so ...
def model_from_yaml(yaml_string, custom_objects=None): A Keras model instance (uncompiled). Raises: RuntimeError: announces that the method poses a security risk """ raise RuntimeError( 'Method `model_from_yaml()` has been removed due to security risk of ' 'arbitrary code execution. Pleas...
# -*- coding: utf-8 -*- import pytest from thefuck.shells import Bash
# -*- coding: utf-8 -*- import os import pytest from thefuck.shells import Bash
class TestBash(object): return Bash() @pytest.fixture(autouse=True) def Popen(self, mocker): mock = mocker.patch('thefuck.shells.bash.Popen') mock.return_value.stdout.read.return_value = ( b'alias fuck=\'eval $(thefuck $(fc -ln -1))\'\n' b'alias l=\'ls -CF\'\n' ...
class TestBash(object): return Bash() @pytest.fixture(autouse=True) def shell_aliases(self): os.environ['TF_SHELL_ALIASES'] = ( 'alias fuck=\'eval $(thefuck $(fc -ln -1))\'\n' 'alias l=\'ls -CF\'\n' 'alias la=\'ls -A\'\n' 'alias ll=\'ls -alF\'') ...
from subprocess import Popen, PIPE import os from ..conf import settings from ..utils import DEVNULL, memoize, cache from .generic import Generic
import os from ..conf import settings from ..utils import memoize from .generic import Generic
class Bash(Generic): def app_alias(self, fuck): alias = "TF_ALIAS={0}" \ " alias {0}='PYTHONIOENCODING=utf-8" \ " TF_CMD=$(thefuck $(fc -ln -1)) && " \ " eval $TF_CMD".format(fuck) if settings.alter_history:
class Bash(Generic): def app_alias(self, fuck): alias = "TF_ALIAS={0}" \ " alias {0}='PYTHONIOENCODING=utf-8" \ " TF_CMD=$(TF_SHELL_ALIASES=$(alias) thefuck $(fc -ln -1)) && " \ " eval $TF_CMD".format(fuck) if settings.alter_history:
class Bash(Generic): return name, value @memoize @cache('.bashrc', '.bash_profile') def get_aliases(self): proc = Popen(['bash', '-ic', 'alias'], stdout=PIPE, stderr=DEVNULL) return dict( self._parse_alias(alias) for alias in proc.stdout.read().decode...
class Bash(Generic): return name, value @memoize def get_aliases(self): raw_aliases = os.environ.get('TF_SHELL_ALIASES', '').split('\n') return dict(self._parse_alias(alias) for alias in raw_aliases if alias and '=' in alias) def _get_history_file_name(self): ...
class Zsh(Generic): @memoize def get_aliases(self): raw_aliases = os.environ['TF_SHELL_ALIASES'].split('\n') return dict(self._parse_alias(alias) for alias in raw_aliases if alias and '=' in alias)
class Zsh(Generic): @memoize def get_aliases(self): raw_aliases = os.environ.get('TF_SHELL_ALIASES', '').split('\n') return dict(self._parse_alias(alias) for alias in raw_aliases if alias and '=' in alias)
setup(name='gym', if package.startswith('gym')], zip_safe=False, install_requires=[ 'scipy', 'numpy>=1.10.4', 'pyglet>=1.4.0,<=1.5.0', 'Pillow<=7.2.0', 'cloudpickle>=1.2.0,<1.7.0', ], extras_require=extras, package_data={'gym': [
setup(name='gym', if package.startswith('gym')], zip_safe=False, install_requires=[ 'scipy', 'numpy>=1.10.4', 'pyglet>=1.4.0,<=1.5.15', 'Pillow<=8.2.0', 'cloudpickle>=1.2.0,<1.7.0', ], extras_require=extras, package_data={'gym': [
from hashlib import sha1 import unittest from paramiko import Transport, SecurityOptions, ServerInterface, RSAKey, DSSKey, \ SSHException, ChannelException, Packetizer from paramiko import AUTH_FAILED, AUTH_SUCCESSFUL from paramiko import OPEN_SUCCEEDED, OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED from paramiko.common...
from hashlib import sha1 import unittest from paramiko import Transport, SecurityOptions, ServerInterface, RSAKey, DSSKey, \ SSHException, ChannelException, Packetizer, Channel from paramiko import AUTH_FAILED, AUTH_SUCCESSFUL from paramiko import OPEN_SUCCEEDED, OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED from parami...
class NullServer (ServerInterface): def check_global_request(self, kind, msg): self._global_request = kind return False def check_channel_x11_request(self, channel, single_connection, auth_protocol, auth_cookie, screen_number): self._x11_single_connection = single_connection
class NullServer (ServerInterface): def check_global_request(self, kind, msg): self._global_request = kind # NOTE: for w/e reason, older impl of this returned False always, even # tho that's only supposed to occur if the request cannot be served. # For now, leaving that the default ...
class TransportTest(unittest.TestCase): # sendall() accepts a memoryview instance chan.sendall(memoryview(data)) self.assertEqual(sfile.read(len(data)), data)
class TransportTest(unittest.TestCase): # sendall() accepts a memoryview instance chan.sendall(memoryview(data)) self.assertEqual(sfile.read(len(data)), data) def test_server_rejects_open_channel_without_auth(self): try: self.setup_test_server(connect_kwargs=...
from pandas.core.dtypes.common import ( is_bool, is_bool_dtype, is_categorical_dtype, is_datetime64_dtype, is_datetime64tz_dtype, is_datetimelike, is_dtype_equal,
from pandas.core.dtypes.common import ( is_bool, is_bool_dtype, is_categorical_dtype, is_datetime64tz_dtype, is_datetimelike, is_dtype_equal,
class _AsOfMerge(_OrderedMerge): ) ) if is_datetime64_dtype(lt) or is_datetime64tz_dtype(lt): if not isinstance(self.tolerance, Timedelta): raise MergeError(msg) if self.tolerance < Timedelta(0):
class _AsOfMerge(_OrderedMerge): ) ) if is_datetimelike(lt): if not isinstance(self.tolerance, Timedelta): raise MergeError(msg) if self.tolerance < Timedelta(0):
import numpy as np import pytest import pytz
import datetime import numpy as np import pytest import pytz
class TestAsOfMerge: # ok, though has dupes merge_asof(trades, self.quotes, on="time", by="ticker") def test_tolerance(self): trades = self.trades quotes = self.quotes result = merge_asof( trades, quotes, on="time", by="ticker", tolerance=Timedelta("1day") ...
class TestAsOfMerge: # ok, though has dupes merge_asof(trades, self.quotes, on="time", by="ticker") @pytest.mark.parametrize( "tolerance", [ Timedelta("1day"), pytest.param( datetime.timedelta(days=1), marks=pytest.mark.xfail(r...
class TestAsOfMerge: ) expected["value_y"] = np.array([np.nan], dtype=object) assert_frame_equal(result, expected)
class TestAsOfMerge: ) expected["value_y"] = np.array([np.nan], dtype=object) assert_frame_equal(result, expected) def test_timedelta_tolerance_nearest(self): # GH 27642 left = pd.DataFrame( list(zip([0, 5, 10, 15, 20, 25], [0, 1, 2, 3, 4, 5])), colu...
class URLValidator(RegexValidator): ul = '\u00a1-\uffff' # Unicode letters range (must not be a raw string). # IP patterns ipv4_re = r'(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}' ipv6_re = r'\[[0-9a-f:.]+\]' # (simple regex, validated later) # Host patterns
class URLValidator(RegexValidator): ul = '\u00a1-\uffff' # Unicode letters range (must not be a raw string). # IP patterns ipv4_re = r'(?:0|25[0-5]|2[0-4]\d|1\d?\d?|[1-9]\d?)(?:\.(?:0|25[0-5]|2[0-4]\d|1\d?\d?|[1-9]\d?)){3}' ipv6_re = r'\[[0-9a-f:.]+\]' # (simple regex, validated later) # Host pa...
def validate_ipv4_address(value): ipaddress.IPv4Address(value) except ValueError: raise ValidationError(_('Enter a valid IPv4 address.'), code='invalid', params={'value': value}) def validate_ipv6_address(value):
def validate_ipv4_address(value): ipaddress.IPv4Address(value) except ValueError: raise ValidationError(_('Enter a valid IPv4 address.'), code='invalid', params={'value': value}) else: # Leading zeros are forbidden to avoid ambiguity with the octal # notation. This restriction is...
TEST_DATA = [ (validate_ipv4_address, '1.1.1.1\n', ValidationError), (validate_ipv4_address, '٧.2٥.3٣.243', ValidationError), # validate_ipv6_address uses django.utils.ipv6, which # is tested in much greater detail in its own testcase (validate_ipv6_address, 'fe80::1', None),
TEST_DATA = [ (validate_ipv4_address, '1.1.1.1\n', ValidationError), (validate_ipv4_address, '٧.2٥.3٣.243', ValidationError), # Leading zeros are forbidden to avoid ambiguity with the octal notation. (validate_ipv4_address, '000.000.000.000', ValidationError), (validate_ipv4_address, '016.016.016.0...
TEST_DATA = [ (validate_ipv46_address, '::zzz', ValidationError), (validate_ipv46_address, '12345::', ValidationError), (validate_comma_separated_integer_list, '1', None), (validate_comma_separated_integer_list, '12', None), (validate_comma_separated_integer_list, '1,2', None),
TEST_DATA = [ (validate_ipv46_address, '::zzz', ValidationError), (validate_ipv46_address, '12345::', ValidationError), # Leading zeros are forbidden to avoid ambiguity with the octal notation. (validate_ipv46_address, '000.000.000.000', ValidationError), (validate_ipv46_address, '016.016.016.016',...
from RestrictedPython.Utilities import utility_builtins from zExceptions import Unauthorized from AccessControl.SecurityInfo import secureModule from AccessControl.SecurityManagement import getSecurityManager from AccessControl.SimpleObjectPolicies import ContainerAssertions
from RestrictedPython.Utilities import utility_builtins from zExceptions import Unauthorized from AccessControl.SecurityInfo import ModuleSecurityInfo from AccessControl.SecurityInfo import secureModule from AccessControl.SecurityManagement import getSecurityManager from AccessControl.SimpleObjectPolicies import Conta...
math.__allow_access_to_unprotected_subobjects__ = 1 random.__allow_access_to_unprotected_subobjects__ = 1 # AccessControl.Implementation inserts these names into this module as # module globals: aq_validate, guarded_getattr
math.__allow_access_to_unprotected_subobjects__ = 1 random.__allow_access_to_unprotected_subobjects__ = 1 # Mark some unprotected module attributes as private, these should not be # used in untrusted Python code such as Scripts (Python) string_modsec = ModuleSecurityInfo('string') for name in ('Formatter', 'Template')...
def testAccessToSimpleContainer(self): c.attr = PublicMethod() self.assertPolicyAllows(c, 'attr') def testUnicodeAttributeLookups(self): item = self.item r_item = self.a.r_item
def testAccessToSimpleContainer(self): c.attr = PublicMethod() self.assertPolicyAllows(c, 'attr') def testAccessToStringModule(self): # The string module is available to restricted code and its members are # explicitly allowed via a # ``__allow_access_to_unprotected_subobjec...
class TestUtil(unittest.TestCase): self.assertEqual(parse_duration('0s'), 0) self.assertEqual(parse_duration('01:02:03.05'), 3723.05) self.assertEqual(parse_duration('T30M38S'), 1838) def test_fix_xml_ampersands(self): self.assertEqual(
class TestUtil(unittest.TestCase): self.assertEqual(parse_duration('0s'), 0) self.assertEqual(parse_duration('01:02:03.05'), 3723.05) self.assertEqual(parse_duration('T30M38S'), 1838) self.assertEqual(parse_duration('5 s'), 5) self.assertEqual(parse_duration('3 min'), 180) ...
from ..compat import ( ) from ..utils import ( int_or_none, parse_filesize, )
from ..compat import ( ) from ..utils import ( int_or_none, parse_duration, parse_filesize, )
class MinhatecaIE(InfoExtractor): filesize_approx = parse_filesize(self._html_search_regex( r'<p class="fileSize">(.*?)</p>', webpage, 'file size approximation', fatal=False)) duration = int_or_none(self._html_search_regex( r'(?s)<p class="fileLeng[ht][th]">.*?([0-9]+...
class MinhatecaIE(InfoExtractor): filesize_approx = parse_filesize(self._html_search_regex( r'<p class="fileSize">(.*?)</p>', webpage, 'file size approximation', fatal=False)) duration = parse_duration(self._html_search_regex( r'(?s)<p class="fileLeng[ht][th]">.*?clas...
def parse_duration(s): m = re.match( r'''(?ix)T? (?: (?:(?P<hours>[0-9]+)\s*(?:[:h]|hours?)\s*)? (?P<mins>[0-9]+)\s*(?:[:m]|mins?|minutes?)\s* )? (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*(?:s|secs?|seconds?)?$''', s) if not m: retur...
def parse_duration(s): m = re.match( r'''(?ix)T? (?: (?P<only_mins>[0-9.]+)\s*(?:mins?|minutes?)\s*| (?P<only_hours>[0-9.]+)\s*(?:hours?)| (?: (?:(?P<hours>[0-9]+)\s*(?:[:h]|hours?)\s*)? (?P<mins>[0-9]+)\s*(?:[:m]|mins?|minutes?)\...
def strip_tags(value): value = str(value) while '<' in value and '>' in value: new_value = _strip_once(value) if len(new_value) >= len(value): # _strip_once was not able to detect more tags break value = new_value return value
def strip_tags(value): value = str(value) while '<' in value and '>' in value: new_value = _strip_once(value) if value.count('<') == new_value.count('<'): # _strip_once wasn't able to detect more tags. break value = new_value return value
class TestUtilsHtml(SimpleTestCase): ('&gotcha&#;<>', '&gotcha&#;<>'), ('<sc<!-- -->ript>test<<!-- -->/script>', 'ript>test'), ('<script>alert()</script>&h', 'alert()h'), ) for value, output in items: with self.subTest(value=value, output=output):
class TestUtilsHtml(SimpleTestCase): ('&gotcha&#;<>', '&gotcha&#;<>'), ('<sc<!-- -->ript>test<<!-- -->/script>', 'ript>test'), ('<script>alert()</script>&h', 'alert()h'), ('><!' + ('&' * 16000) + 'D', '><!' + ('&' * 16000) + 'D'), ('X<<<<br>br>br>br>X', 'XX'),...
def Ghostscript(tile, size, fp, scale=1): status = gs.wait() if status: raise IOError("gs failed (status %d)" % status) im = Image.core.open_ppm(outfile) finally: try: os.unlink(outfile)
def Ghostscript(tile, size, fp, scale=1): status = gs.wait() if status: raise IOError("gs failed (status %d)" % status) im = Image.open(outfile) im.load() finally: try: os.unlink(outfile)
def Ghostscript(tile, size, fp, scale=1): except OSError: pass return im class PSFile(object):
def Ghostscript(tile, size, fp, scale=1): except OSError: pass return im.im.copy() class PSFile(object):
def _wedge(): return Image()._new(core.wedge("L")) def new(mode, size, color=0): """
def _wedge(): return Image()._new(core.wedge("L")) def _check_size(size): """ Common check to enforce type and sanity check on size tuples :param size: Should be a 2 tuple of (width, height) :returns: True, or raises a ValueError """ if not isinstance(size, tuple): raise ValueErr...
def new(mode, size, color=0): :returns: An :py:class:`~PIL.Image.Image` object. """ if color is None: # don't initialize return Image()._new(core.new(mode, size))
def new(mode, size, color=0): :returns: An :py:class:`~PIL.Image.Image` object. """ _check_size(size) if color is None: # don't initialize return Image()._new(core.new(mode, size))
def frombytes(mode, size, data, decoder_name="raw", *args): :returns: An :py:class:`~PIL.Image.Image` object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0]
def frombytes(mode, size, data, decoder_name="raw", *args): :returns: An :py:class:`~PIL.Image.Image` object. """ _check_size(size) # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0]
def frombuffer(mode, size, data, decoder_name="raw", *args): .. versionadded:: 1.1.4 """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0]
def frombuffer(mode, size, data, decoder_name="raw", *args): .. versionadded:: 1.1.4 """ _check_size(size) # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0]
def load(self): if d == "raw" and a[0] == self.mode and a[0] in Image._MAPMODES: try: if hasattr(Image.core, "map"): # use built-in mapper self.map = Image.core.map(self.filename) self.map.seek(o) ...
def load(self): if d == "raw" and a[0] == self.mode and a[0] in Image._MAPMODES: try: if hasattr(Image.core, "map"): # use built-in mapper WIN32 only self.map = Image.core.map(self.filename) self.map...
def load(self): o.close() try: try: # fast self.im = Image.core.open_ppm(outfile) except: # slightly slower im = Image.open(outfile) im.load() self.im = im.im finally: ...
def load(self): o.close() try: _im = Image.open(outfile) _im.load() self.im = _im.im finally: try: os.unlink(outfile)
def load_djpeg(self): raise ValueError("Invalid Filename") try: self.im = Image.core.open_ppm(path) finally: try: os.unlink(path)
def load_djpeg(self): raise ValueError("Invalid Filename") try: _im = Image.open(path) _im.load() self.im = _im.im finally: try: os.unlink(path)
def _open(self): self.fp.tell(), (rawmode, 0, 1))] # ALTERNATIVE: load via builtin debug function # self.im = Image.core.open_ppm(self.filename) # self.mode = self.im.mode # self.size = self.im.size # # ----------------------------------------...
def _open(self): self.fp.tell(), (rawmode, 0, 1))] # # --------------------------------------------------------------------
def test_truncated_file(self): self.assertRaises(ValueError, lambda: Image.open(path)) if __name__ == '__main__': unittest.main()
def test_truncated_file(self): self.assertRaises(ValueError, lambda: Image.open(path)) def test_neg_ppm(self): # Storage.c accepted negative values for xsize, ysize. the # internal open_ppm function didn't check for sanity but it # has been removed. The default opener doesn't acce...
def test_effect_spread(self): im3 = Image.open('Tests/images/effect_spread.png') self.assert_image_similar(im2, im3, 110) if __name__ == '__main__': unittest.main()
def test_effect_spread(self): im3 = Image.open('Tests/images/effect_spread.png') self.assert_image_similar(im2, im3, 110) def test_check_size(self): # Checking that the _check_size function throws value errors when we want it to. with self.assertRaises(ValueError): Imag...
def sendEmail(sydent, templateName, mailTo, substitutions): allSubstitutions[k+"_forhtml"] = cgi.escape(v.decode('utf8')) allSubstitutions[k+"_forurl"] = urllib.quote(v) mailString = open(mailTemplateFile).read() % allSubstitutions rawFrom = email.utils.parseaddr(mailFrom)[1] ...
def sendEmail(sydent, templateName, mailTo, substitutions): allSubstitutions[k+"_forhtml"] = cgi.escape(v.decode('utf8')) allSubstitutions[k+"_forurl"] = urllib.quote(v) mailString = open(mailTemplateFile).read().decode('utf8') % allSubstitutions parsedFrom = email.utils.parsead...
def sendEmail(sydent, templateName, mailTo, substitutions): smtp = smtplib.SMTP(mailServer, mailPort, myHostname) if mailUsername != '': smtp.login(mailUsername, mailPassword) smtp.sendmail(rawFrom, rawTo, mailString.encode('utf-8')) smtp.quit() ...
def sendEmail(sydent, templateName, mailTo, substitutions): smtp = smtplib.SMTP(mailServer, mailPort, myHostname) if mailUsername != '': smtp.login(mailUsername, mailPassword) # We're using the parsing above to do basic validation, but instead of # fa...
class CollectionRequirement: shutil.rmtree(b_collection_path) os.makedirs(b_collection_path) with tarfile.open(self.b_path, mode='r') as collection_tar: files_member_obj = collection_tar.getmember('FILES.json') with _tarfile_extract(collection_tar, files_member_obj) ...
class CollectionRequirement: shutil.rmtree(b_collection_path) os.makedirs(b_collection_path) try: with tarfile.open(self.b_path, mode='r') as collection_tar: files_member_obj = collection_tar.getmember('FILES.json') with _tarfile_extract(collectio...
def _extract_tar_file(tar, filename, b_dest, b_temp_path, expected_hash=None): raise AnsibleError("Checksum mismatch for '%s' inside collection at '%s'" % (n_filename, to_native(tar.name))) b_dest_filepath = os.path.join(b_dest, to_bytes(filename, errors='surrogate_or...
def _extract_tar_file(tar, filename, b_dest, b_temp_path, expected_hash=None): raise AnsibleError("Checksum mismatch for '%s' inside collection at '%s'" % (n_filename, to_native(tar.name))) b_dest_filepath = os.path.abspath(os.path.join(b_dest, to_bytes(filename, erro...
__metaclass__ = type import json import os import pytest import tarfile import uuid
__metaclass__ = type import json import os import pytest import re import tarfile import uuid
def test_extract_tar_file_missing_parent_dir(tmp_tarfile): collection._extract_tar_file(tfile, filename, output_dir, temp_dir, checksum) os.path.isfile(output_file)
def test_extract_tar_file_missing_parent_dir(tmp_tarfile): collection._extract_tar_file(tfile, filename, output_dir, temp_dir, checksum) os.path.isfile(output_file) def test_extract_tar_file_outside_dir(tmp_path_factory): filename = u'ÅÑŚÌβŁÈ' temp_dir = to_bytes(tmp_path_factory.mktemp('test-%s Coll...
class Series(base.IndexOpsMixin, generic.NDFrame): from pandas.core.reshape.concat import concat if isinstance(to_append, (list, tuple)): to_concat = [self] + to_append else: to_concat = [self, to_append] return concat(
class Series(base.IndexOpsMixin, generic.NDFrame): from pandas.core.reshape.concat import concat if isinstance(to_append, (list, tuple)): to_concat = [self] to_concat.extend(to_append) else: to_concat = [self, to_append] return concat(
class TestSeriesCombine: with pytest.raises(ValueError, match=msg): pd.concat([s1, s2], verify_integrity=True) def test_combine_scalar(self): # GH 21248 # Note - combine() with another Series is tested elsewhere because
class TestSeriesCombine: with pytest.raises(ValueError, match=msg): pd.concat([s1, s2], verify_integrity=True) def test_append_tuples(self): # GH 28410 s = pd.Series([1, 2, 3]) list_input = [s, s] tuple_input = (s, s) expected = s.append(list_input) ...
To push the current branch and set the remote as upstream, use '''.format(branch_name, branch_name) @pytest.mark.parametrize('script, branch_name', [ ('git push', 'master'), ('git push origin', 'master')])
To push the current branch and set the remote as upstream, use '''.format(branch_name, branch_name) @pytest.fixture def output_bitbucket(): return '''Total 0 (delta 0), reused 0 (delta 0) remote: remote: Create pull request for feature/set-upstream: remote: https://bitbucket.org/set-upstream remote: To git@bitb...
def test_match(output, script, branch_name): assert match(Command(script, output)) @pytest.mark.parametrize('script, branch_name', [ ('git push master', None), ('ls', 'master')])
def test_match(output, script, branch_name): assert match(Command(script, output)) def test_match_bitbucket(output_bitbucket): assert not match(Command('git push origin', output_bitbucket)) @pytest.mark.parametrize('script, branch_name', [ ('git push master', None), ('ls', 'master')])
from thefuck.specific.git import git_support @git_support def match(command): return ('push' in command.script_parts and 'set-upstream' in command.output) def _get_upstream_option_index(command_parts):
from thefuck.specific.git import git_support @git_support def match(command): return ('push' in command.script_parts and 'git push --set-upstream' in command.output) def _get_upstream_option_index(command_parts):
from django.db.models.deletion import CASCADE from django.urls import reverse from django.urls.exceptions import NoReverseMatch from django.utils.html import smart_urlquote from django.utils.safestring import mark_safe from django.utils.text import Truncator from django.utils.translation import get_language, gettext as...
from django.db.models.deletion import CASCADE from django.urls import reverse from django.urls.exceptions import NoReverseMatch from django.utils.html import smart_urlquote from django.utils.http import urlencode from django.utils.text import Truncator from django.utils.translation import get_language, gettext as _
class ForeignKeyRawIdWidget(forms.TextInput): params = self.url_parameters() if params: related_url += '?' + '&amp;'.join('%s=%s' % (k, v) for k, v in params.items()) context['related_url'] = mark_safe(related_url) context['link_title'] = _('Lookup') ...
class ForeignKeyRawIdWidget(forms.TextInput): params = self.url_parameters() if params: related_url += '?' + urlencode(params) context['related_url'] = related_url context['link_title'] = _('Lookup') # The JavaScript code looks for this class....
class Band(models.Model): return self.name class Album(models.Model): band = models.ForeignKey(Band, models.CASCADE) featuring = models.ManyToManyField(Band, related_name='featured')
class Band(models.Model): return self.name class UnsafeLimitChoicesTo(models.Model): band = models.ForeignKey( Band, models.CASCADE, limit_choices_to={'name': '"&><escapeme'}, ) class Album(models.Model): band = models.ForeignKey(Band, models.CASCADE) featuring = mode...
from django.utils import translation from .models import ( Advisor, Album, Band, Bee, Car, Company, Event, Honeycomb, Individual, Inventory, Member, MyFileField, Profile, School, Student, ) from .widgetadmin import site as widget_admin_site
from django.utils import translation from .models import ( Advisor, Album, Band, Bee, Car, Company, Event, Honeycomb, Individual, Inventory, Member, MyFileField, Profile, School, Student, UnsafeLimitChoicesTo, ) from .widgetadmin import site as widget_admin_site
class ForeignKeyRawIdWidgetTest(TestCase): 'Hidden</a></strong>' % {'pk': hidden.pk} ) @override_settings(ROOT_URLCONF='admin_widgets.urls') class ManyToManyRawIdWidgetTest(TestCase):
class ForeignKeyRawIdWidgetTest(TestCase): 'Hidden</a></strong>' % {'pk': hidden.pk} ) def test_render_unsafe_limit_choices_to(self): rel = UnsafeLimitChoicesTo._meta.get_field('band').remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTML...
commands: - string """ from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.connection import exec_command from ansible.module_utils.network.ios.ios import load_config from ansible.module_utils.network.ios.ios import ios_argument_spec import re def map_obj_to_commands(updates, module):
commands: - string """ from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.network.ios.ios import get_config, load_config from ansible.module_utils.network.ios.ios import ios_argument_spec from re import search, M def map_obj_to_commands(updates, module):
def map_obj_to_commands(updates, module): if want['text'] and (want['text'] != have.get('text')): banner_cmd = 'banner %s' % module.params['banner'] banner_cmd += ' @\n' banner_cmd += want['text'].strip() banner_cmd += '\n@' commands.append(banner_cmd)...
def map_obj_to_commands(updates, module): if want['text'] and (want['text'] != have.get('text')): banner_cmd = 'banner %s' % module.params['banner'] banner_cmd += ' @\n' banner_cmd += want['text'].strip('\n') banner_cmd += '\n@' commands.append(banner_...
def map_obj_to_commands(updates, module): def map_config_to_obj(module): rc, out, err = exec_command(module, 'show banner %s' % module.params['banner']) if rc == 0: output = out else: rc, out, err = exec_command(module, 'show running-config | begin banne...
def map_obj_to_commands(updates, module): def map_config_to_obj(module): """ This function gets the banner config without stripping any whitespaces, and then fetches the required banner from it. :param module: :return: banner config dict object. """ out = get_config(module, flags='| begin ...
def map_config_to_obj(module): def map_params_to_obj(module): text = module.params['text'] if text: text = str(text).strip() return { 'banner': module.params['banner'], 'text': text,
def map_config_to_obj(module): def map_params_to_obj(module): text = module.params['text'] return { 'banner': module.params['banner'], 'text': text,
class TestIosBannerModule(TestIosModule): def setUp(self): super(TestIosBannerModule, self).setUp() self.mock_exec_command = patch('ansible.modules.network.ios.ios_banner.exec_command') self.exec_command = self.mock_exec_command.start() self.mock_load_config = patch('ansible.module...
class TestIosBannerModule(TestIosModule): def setUp(self): super(TestIosBannerModule, self).setUp() self.mock_get_config = patch('ansible.modules.network.ios.ios_banner.get_config') self.get_config = self.mock_get_config.start() self.mock_load_config = patch('ansible.modules.networ...
class TestIosBannerModule(TestIosModule): self.execute_module(changed=True, commands=commands) def test_ios_banner_nochange(self): banner_text = load_fixture('ios_banner_show_banner.txt').strip() set_module_args(dict(banner='login', text=banner_text)) self.execute_module() class T...
class TestIosBannerModule(TestIosModule): self.execute_module(changed=True, commands=commands) def test_ios_banner_nochange(self): banner_text = load_fixture('ios_banner_show_banner.txt') set_module_args(dict(banner='login', text=banner_text)) self.execute_module() class TestIosBa...
ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4') self.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1) self.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0) self.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1) def test_dfxp2srt(self): dfxp_data = '''<...
ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4') self.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1) self.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0) self.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1) self.assertEqual(parse_dfxp_time_expr('00:00:0...
def parse_dfxp_time_expr(time_expr): if mobj: return float(mobj.group('time_offset')) mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:\.\d+)?)$', time_expr) if mobj: return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3)) def srt_subtitles_timecode(seconds):
def parse_dfxp_time_expr(time_expr): if mobj: return float(mobj.group('time_offset')) mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:(?:\.|:)\d+)?)$', time_expr) if mobj: return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3).replace(':', '.')) def srt_subtitles_timecod...
class ActionBase(with_metaclass(ABCMeta, object)): Create and return a temporary path on a remote box. ''' become_unprivileged = self._is_become_unprivileged() remote_tmp = self.get_shell_option('remote_tmp', default='~/.ansible/tmp') # deal with tmpdir creation basefil...
class ActionBase(with_metaclass(ABCMeta, object)): Create and return a temporary path on a remote box. ''' # Network connection plugins (network_cli, netconf, etc.) execute on the controller, rather than the remote host. # As such, we want to avoid using remote_user for paths as remote...
class ActionBase(with_metaclass(ABCMeta, object)): elif u'No space left on device' in result['stderr']: output = result['stderr'] else: output = ('Authentication or permission failure. ' 'In some cases, you may have been able to authentic...
class ActionBase(with_metaclass(ABCMeta, object)): elif u'No space left on device' in result['stderr']: output = result['stderr'] else: output = ('Failed to create temporary directory.' 'In some cases, you may have been able to authentica...
import random import re import time import ansible.constants as C from ansible.errors import AnsibleError from ansible.module_utils.six import text_type from ansible.module_utils.six.moves import shlex_quote
import random import re import time from ansible import constants as C from ansible.errors import AnsibleError from ansible.module_utils.six import text_type from ansible.module_utils.six.moves import shlex_quote
class ShellBase(AnsiblePlugin): except KeyError: pass def env_prefix(self, **kwargs): return ' '.join(['%s=%s' % (k, shlex_quote(text_type(v))) for k, v in kwargs.items()])
class ShellBase(AnsiblePlugin): except KeyError: pass @staticmethod def _generate_temp_dir_name(): return 'ansible-tmp-%s-%s-%s' % (time.time(), os.getpid(), random.randint(0, 2**48)) def env_prefix(self, **kwargs): return ' '.join(['%s=%s' % (k, shlex_quote(text_type(v...
class ShellBase(AnsiblePlugin): def mkdtemp(self, basefile=None, system=False, mode=0o700, tmpdir=None): if not basefile: basefile = 'ansible-tmp-%s-%s' % (time.time(), random.randint(0, 2**48)) # When system is specified we have to create this in a directory where # other user...
class ShellBase(AnsiblePlugin): def mkdtemp(self, basefile=None, system=False, mode=0o700, tmpdir=None): if not basefile: basefile = self.__class__._generate_temp_dir_name() # When system is specified we have to create this in a directory where # other users can read and access...
class ShellBase(AnsiblePlugin): # passed in tmpdir if it is valid or the first one from the setting if not. if system: tmpdir = tmpdir.rstrip('/') if tmpdir in self.get_option('system_tmpdirs'): basetmpdir = tmpdir
class ShellBase(AnsiblePlugin): # passed in tmpdir if it is valid or the first one from the setting if not. if system: if tmpdir: tmpdir = tmpdir.rstrip('/') if tmpdir in self.get_option('system_tmpdirs'): basetmpdir = tmpdir
class ShellBase(AnsiblePlugin): basetmp = self.join_path(basetmpdir, basefile) cmd = 'mkdir -p %s echo %s %s' % (self._SHELL_SUB_LEFT, basetmp, self._SHELL_SUB_RIGHT) cmd += ' %s echo %s=%s echo %s %s' % (self._SHELL_AND, basefile, self._SHELL_SUB_LEFT, basetmp, self._SHELL_SUB_RIGHT) ...
class ShellBase(AnsiblePlugin): basetmp = self.join_path(basetmpdir, basefile) # use mkdir -p to ensure parents exist, but mkdir fullpath to ensure last one is created by us cmd = 'mkdir -p %s echo %s %s' % (self._SHELL_SUB_LEFT, basetmpdir, self._SHELL_SUB_RIGHT) cmd += '%s mkdir %s' ...
class ShellModule(ShellBase): def mkdtemp(self, basefile=None, system=False, mode=None, tmpdir=None): # Windows does not have an equivalent for the system temp files, so # the param is ignored basefile = self._escape(self._unquote(basefile)) basetmpdir = tmpdir if tmpdir else self.ge...
class ShellModule(ShellBase): def mkdtemp(self, basefile=None, system=False, mode=None, tmpdir=None): # Windows does not have an equivalent for the system temp files, so # the param is ignored if not basefile: basefile = self.__class__._generate_temp_dir_name() basefile =...
class EarlyStopping(Callback): baseline: Baseline value for the monitored quantity to reach. Training will stop if the model doesn't show improvement over the baseline. """ def __init__(self,
class EarlyStopping(Callback): baseline: Baseline value for the monitored quantity to reach. Training will stop if the model doesn't show improvement over the baseline. restore_best_weights: whether to restore model weights from the epoch with the best value of the mo...
class EarlyStopping(Callback): patience=0, verbose=0, mode='auto', baseline=None): super(EarlyStopping, self).__init__() self.monitor = monitor
class EarlyStopping(Callback): patience=0, verbose=0, mode='auto', baseline=None, restore_best_weights=False): super(EarlyStopping, self).__init__() self.monitor = monitor
class EarlyStopping(Callback): self.min_delta = min_delta self.wait = 0 self.stopped_epoch = 0 if mode not in ['auto', 'min', 'max']: warnings.warn('EarlyStopping mode %s is unknown, '
class EarlyStopping(Callback): self.min_delta = min_delta self.wait = 0 self.stopped_epoch = 0 self.restore_best_weights = restore_best_weights self.best_weights = None if mode not in ['auto', 'min', 'max']: warnings.warn('EarlyStopping mode %s is unknown, '
class EarlyStopping(Callback): if self.monitor_op(current - self.min_delta, self.best): self.best = current self.wait = 0 else: self.wait += 1 if self.wait >= self.patience: self.stopped_epoch = epoch self.model.stop_trainin...
class EarlyStopping(Callback): if self.monitor_op(current - self.min_delta, self.best): self.best = current self.wait = 0 if self.restore_best_weights: self.best_weights = self.model.get_weights() else: self.wait += 1 if self.wa...
def test_EarlyStopping_patience(): def __init__(self): self.stop_training = False early_stop = callbacks.EarlyStopping(monitor='val_loss', patience=2) early_stop.model = DummyModel()
def test_EarlyStopping_patience(): def __init__(self): self.stop_training = False def get_weights(self): return [] def set_weights(self, weights): pass early_stop = callbacks.EarlyStopping(monitor='val_loss', patience=2) early_stop.model = DummyMode...
def test_EarlyStopping_baseline(): def __init__(self): self.stop_training = False def baseline_tester(acc_levels): early_stop = callbacks.EarlyStopping(monitor='val_acc', baseline=0.75, patience=2) early_stop.model = DummyModel()
def test_EarlyStopping_baseline(): def __init__(self): self.stop_training = False def get_weights(self): return [] def set_weights(self, weights): pass def baseline_tester(acc_levels): early_stop = callbacks.EarlyStopping(monitor='val_acc', base...
def test_EarlyStopping_baseline(): assert baseline_not_met == 2 @keras_test def test_LearningRateScheduler(): np.random.seed(1337)
def test_EarlyStopping_baseline(): assert baseline_not_met == 2 @keras_test def test_EarlyStopping_final_weights(): class DummyModel(object): def __init__(self): self.stop_training = False self.weights = -1 def get_weights(self): return self.weights ...
class SeriesGroupBy(GroupBy): periods=periods, fill_method=fill_method, limit=limit, freq=freq ) ) filled = getattr(self, fill_method)(limit=limit) fill_grp = filled.groupby(self.grouper.codes) shifted = fill_grp.shift(periods=periods, freq=freq)
class SeriesGroupBy(GroupBy): periods=periods, fill_method=fill_method, limit=limit, freq=freq ) ) if fill_method is None: # GH30463 fill_method = "pad" limit = 0 filled = getattr(self, fill_method)(limit=limit) fill_grp = ...
class GroupBy(_GroupBy): axis=axis, ) ) filled = getattr(self, fill_method)(limit=limit) fill_grp = filled.groupby(self.grouper.codes) shifted = fill_grp.shift(periods=periods, freq=freq)
class GroupBy(_GroupBy): axis=axis, ) ) if fill_method is None: # GH30463 fill_method = "pad" limit = 0 filled = getattr(self, fill_method)(limit=limit) fill_grp = filled.groupby(self.grouper.codes) shifted = fill_g...
def test_pad_stable_sorting(fill_method): ), ], ) @pytest.mark.parametrize( "periods,fill_method,limit", [ (1, "ffill", None), (1, "ffill", 1), (1, "bfill", None), (1, "bfill", 1), (-1, "ffill", None), (-1, "ffill", 1), (-1, "bfill", None), ...
def test_pad_stable_sorting(fill_method): ), ], ) @pytest.mark.parametrize("periods", [1, -1]) @pytest.mark.parametrize("fill_method", ["ffill", "bfill", None]) @pytest.mark.parametrize("limit", [None, 1]) def test_pct_change(test_series, freq, periods, fill_method, limit): # GH 21200, 21621, 30463 ...
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') ...
except ImportError: from gzip import GzipFile import six # - Python>=3.5 GzipFile's read() has issues returning leftover # uncompressed data when input is corrupted
except ImportError: from gzip import GzipFile import six import re # - Python>=3.5 GzipFile's read() has issues returning leftover # uncompressed data when input is corrupted
def gunzip(data): raise return output def is_gzipped(response): """Return True if the response is gzipped, or False otherwise""" ctype = response.headers.get('Content-Type', b'') return ctype in (b'application/x-gzip', b'application/gzip')
def gunzip(data): raise return output _is_gzipped_re = re.compile(br'^application/(x-)?gzip\b', re.I) def is_gzipped(response): """Return True if the response is gzipped, or False otherwise""" ctype = response.headers.get('Content-Type', b'') return _is_gzipped_re.search(ctype) is not ...
import unittest from os.path import join from scrapy.utils.gz import gunzip from tests import tests_datadir SAMPLEDIR = join(tests_datadir, 'compressed')
import unittest from os.path import join from scrapy.utils.gz import gunzip, is_gzipped from scrapy.http import Response, Headers from tests import tests_datadir SAMPLEDIR = join(tests_datadir, 'compressed')
class GunzipTest(unittest.TestCase): with open(join(SAMPLEDIR, 'truncated-crc-error-short.gz'), 'rb') as f: text = gunzip(f.read()) assert text.endswith(b'</html>')
class GunzipTest(unittest.TestCase): with open(join(SAMPLEDIR, 'truncated-crc-error-short.gz'), 'rb') as f: text = gunzip(f.read()) assert text.endswith(b'</html>') def test_is_x_gzipped_right(self): hdrs = Headers({"Content-Type": "application/x-gzip"}) r1 = Respons...
def _make_wrapped_arith_op_with_freq(opname: str): if result is NotImplemented: return NotImplemented new_freq = self._get_addsub_freq(other) result._freq = new_freq return result
def _make_wrapped_arith_op_with_freq(opname: str): if result is NotImplemented: return NotImplemented new_freq = self._get_addsub_freq(other, result) result._freq = new_freq return result
class DatetimeIndexOpsMixin(ExtensionIndex): # -------------------------------------------------------------------- # Arithmetic Methods def _get_addsub_freq(self, other) -> Optional[DateOffset]: """ Find the freq we expect the result of an addition/subtraction operation to have. ...
class DatetimeIndexOpsMixin(ExtensionIndex): # -------------------------------------------------------------------- # Arithmetic Methods def _get_addsub_freq(self, other, result) -> Optional[DateOffset]: """ Find the freq we expect the result of an addition/subtraction operation to ...
class TestPeriodIndexSeriesMethods: tm.assert_index_equal(result, exp) exp = pd.TimedeltaIndex([np.nan, np.nan, np.nan, np.nan], name="idx") tm.assert_index_equal(idx - pd.Period("NaT", freq="M"), exp) tm.assert_index_equal(pd.Period("NaT", freq="M") - idx, exp) def test_pi_sub_pdn...
class TestPeriodIndexSeriesMethods: tm.assert_index_equal(result, exp) exp = pd.TimedeltaIndex([np.nan, np.nan, np.nan, np.nan], name="idx") result = idx - pd.Period("NaT", freq="M") tm.assert_index_equal(result, exp) assert result.freq == exp.freq result = pd.Period("N...
""" Constants specific to the SQL storage portion of the ORM. """ # Size of each "chunk" for get_iterator calls. # Larger values are slightly faster at the expense of more storage space.
""" Constants specific to the SQL storage portion of the ORM. """ from django.utils.regex_helper import _lazy_re_compile # Size of each "chunk" for get_iterator calls. # Larger values are slightly faster at the expense of more storage space.