buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
class TestGetItem:
class TestWhere:
# placeholder for symmetry with DatetimeIndex and PeriodIndex tests
pass
class TestTake: | class TestGetItem:
class TestWhere:
def test_where_invalid_dtypes(self):
tdi = timedelta_range("1 day", periods=3, freq="D", name="idx")
i2 = tdi.copy()
i2 = Index([pd.NaT, pd.NaT] + tdi[2:].tolist())
with pytest.raises(TypeError, match="Where requires matching dtype"):
... |
def render_full(self, evalex=False, secret=None,
evalex_trusted=True):
"""Render the Full HTML page with the traceback info."""
exc = escape(self.exception)
return PAGE_HTML % {
'evalex': evalex and 'true' or 'false',
'evalex_trusted': eval... | def render_full(self, evalex=False, secret=None,
evalex_trusted=True):
"""Render the Full HTML page with the traceback info."""
exc = escape(self.exception)
ptext = escape(self.plaintext)
return PAGE_HTML % {
'evalex': evalex and 'true' or 'false... |
def render_full(self, evalex=False, secret=None,
'exception': exc,
'exception_type': escape(self.exception_type),
'summary': self.render_summary(include_title=False),
'plaintext': self.plaintext,
'plaintext_cs': re.sub('-{2,}', '-'... | def render_full(self, evalex=False, secret=None,
'exception': exc,
'exception_type': escape(self.exception_type),
'summary': self.render_summary(include_title=False),
'plaintext': ptext,
'plaintext_cs': re.sub('-{2,}', '-', self.pl... |
import logging
import salt.utils.files
import salt.utils.path
import salt.payload
from salt.ext import six | import logging
import salt.utils.files
import salt.utils.path
import salt.utils.verify
import salt.payload
from salt.ext import six |
def get_token(opts, tok):
:returns: Token data if successful. Empty dict if failed.
'''
t_path = os.path.join(opts['token_dir'], tok)
if not os.path.isfile(t_path):
return {}
serial = salt.payload.Serial(opts) | def get_token(opts, tok):
:returns: Token data if successful. Empty dict if failed.
'''
t_path = os.path.join(opts['token_dir'], tok)
if not salt.utils.verify.clean_path(opts['token_dir'], t_path):
return {}
if not os.path.isfile(t_path):
return {}
serial = salt.payload.Serial(op... |
import salt.utils.files
import salt.utils.path
import salt.utils.platform
import salt.utils.user
log = logging.getLogger(__name__)
| import salt.utils.files
import salt.utils.path
import salt.utils.platform
import salt.utils.user
import salt.ext.six
log = logging.getLogger(__name__)
|
def check_max_open_files(opts):
log.log(level=level, msg=msg)
def clean_path(root, path, subdir=False):
'''
Accepts the root the path needs to be under and verifies that the path is
under said root. Pass in subdir=True if the path can result in a
subdirectory of the root instead of having to resid... | def check_max_open_files(opts):
log.log(level=level, msg=msg)
def _realpath_darwin(path):
base = ''
for part in path.split(os.path.sep)[1:]:
if base != '':
if os.path.islink(os.path.sep.join([base, part])):
base = os.readlink(os.path.sep.join([base, part]))
... |
def update_config(file_name, yaml_contents):
dir_path = os.path.join(__opts__['config_dir'],
os.path.dirname(__opts__['default_include']))
try:
yaml_out = salt.utils.yaml.safe_dump(yaml_contents, default_flow_style=False)
if not os.path.exists(dir_path):
... | def update_config(file_name, yaml_contents):
dir_path = os.path.join(__opts__['config_dir'],
os.path.dirname(__opts__['default_include']))
try:
yaml_out = salt.utils.yaml.safe_dump(
yaml_contents,
default_flow_style=False,
)
if not os.... |
def find(path, saltenv='base'):
return ret
for root in __opts__['file_roots'][saltenv]:
full = os.path.join(root, path)
if os.path.isfile(full):
# Add it to the dict
with salt.utils.files.fopen(full, 'rb') as fp_: | def find(path, saltenv='base'):
return ret
for root in __opts__['file_roots'][saltenv]:
full = os.path.join(root, path)
if not salt.utils.verify.clean_path(root, full):
continue
if os.path.isfile(full):
# Add it to the dict
with salt.utils.files.fo... |
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__['file_roots'][saltenv][index], path)
dest_dir = os.path.dirname(dest)
if not os.p... | 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)
root = __opts__['file_roots'][saltenv][index]
dest = os.path.join(root, path)
if not salt.utils.verify.clean_p... |
class ClearFuncsPubTestCase(TestCase):
ret_evt = raw
break
assert not os.path.exists(self.tmpfile), 'Evil file created' | class ClearFuncsPubTestCase(TestCase):
ret_evt = raw
break
assert not os.path.exists(self.tmpfile), 'Evil file created'
class ClearFuncsConfigTest(TestCase):
def setUp(self):
master_opts = AdaptedConfigurationTestCaseMixin.get_config('master')
self.conf_dir... |
class BadTestModuleNamesTestCase(TestCase):
'integration.loader.test_ext_modules',
'integration.logging.test_jid_logging',
'integration.master.test_event_return',
'integration.minion.test_blackout',
'integration.minion.test_pillar',
'integration.mi... | class BadTestModuleNamesTestCase(TestCase):
'integration.loader.test_ext_modules',
'integration.logging.test_jid_logging',
'integration.master.test_event_return',
'integration.master.test_clear_funcs',
'integration.minion.test_blackout',
'integrati... |
import stat
import shutil
import tempfile
import socket
# Import third party libs
if sys.platform.startswith('win'): | import stat
import shutil
import tempfile
import socket
import ctypes
# Import third party libs
if sys.platform.startswith('win'): |
from salt.utils.verify import (
verify_log,
verify_logs_filter,
verify_log_files,
)
# Import 3rd-party libs | from salt.utils.verify import (
verify_log,
verify_logs_filter,
verify_log_files,
clean_path
)
# Import 3rd-party libs |
class TestVerifyLog(TestCase):
self.assertFalse(os.path.exists(path))
verify_log_files([path], getpass.getuser())
self.assertTrue(os.path.exists(path)) | class TestVerifyLog(TestCase):
self.assertFalse(os.path.exists(path))
verify_log_files([path], getpass.getuser())
self.assertTrue(os.path.exists(path))
class TestCleanPath(TestCase):
'''
salt.utils.clean_path works as expected
'''
def setUp(self):
self.tmpdir = tempfil... |
class BeamDataflowJobTask(MixinNaiveBulkComplete, luigi.Task):
def __init__(self):
if not isinstance(self.dataflow_params, DataflowParamKeys):
raise ValueError("dataflow_params must be of type DataflowParamKeys")
@abstractmethod
def dataflow_executable(self): | class BeamDataflowJobTask(MixinNaiveBulkComplete, luigi.Task):
def __init__(self):
if not isinstance(self.dataflow_params, DataflowParamKeys):
raise ValueError("dataflow_params must be of type DataflowParamKeys")
super(BeamDataflowJobTask, self).__init__()
@abstractmethod
def da... |
class BeamDataflowJobTask(MixinNaiveBulkComplete, luigi.Task):
@staticmethod
def get_target_path(target):
if isinstance(target, luigi.LocalTarget) or isinstance(target, gcs.GCSTarget):
return target.path
elif isinstance(target, bigquery.BigQueryTarget):
"{}:{}.{}".format... | class BeamDataflowJobTask(MixinNaiveBulkComplete, luigi.Task):
@staticmethod
def get_target_path(target):
"""
Given a luigi Target, determine a stringly typed path to pass as a
Dataflow job argument.
"""
if isinstance(target, luigi.LocalTarget) or isinstance(targ... |
import json
import luigi
from luigi.contrib import beam_dataflow
from luigi import local_target
import mock
from mock import MagicMock, patch |
import json
import luigi
from luigi.contrib import beam_dataflow, bigquery, gcs
from luigi import local_target
import mock
from mock import MagicMock, patch |
class BeamDataflowTest(unittest.TestCase):
self.assertEqual(TestTaskDictOfMixedCompleteOutput().complete(), False)
def test_dataflow_runner_resolution(self):
task = SimpleTestTask()
# Test that supported runners are passed through | class BeamDataflowTest(unittest.TestCase):
self.assertEqual(TestTaskDictOfMixedCompleteOutput().complete(), False)
def test_get_target_path(self):
bq_target = bigquery.BigQueryTarget("p", "d", "t", client="fake_client")
self.assertEqual(
SimpleTestTask.get_target_path(bq_target... |
def capfirst(x):
# Set up regular expressions
re_words = re.compile(r'<.*?>|((?:\w[-\w]*|&.*?;)+)', re.U | re.S)
re_chars = re.compile(r'<.*?>|(.)', re.U | re.S)
re_tag = re.compile(r'<(/)?(\S+?)(?:(\s*/)|\s.*?)?>', re.S)
re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines
re_camel_case = re.compile(r'... | def capfirst(x):
# Set up regular expressions
re_words = re.compile(r'<[^>]+?>|([^<>\s]+)', re.S)
re_chars = re.compile(r'<[^>]+?>|(.)', re.S)
re_tag = re.compile(r'<(/)?(\S+?)(?:(\s*/)|\s.*?)?>', re.S)
re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines
re_camel_case = re.compile(r'(((?<=[a-z])[A-Z])|... |
class FunctionTests(SimpleTestCase):
def test_truncate2(self):
self.assertEqual(
truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 4),
'<p>one <a href="#">two - three <br>four ...</a></p>',
)
def test_truncate3(self):
self.assertEqual(
... | class FunctionTests(SimpleTestCase):
def test_truncate2(self):
self.assertEqual(
truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 4),
'<p>one <a href="#">two - three ...</a></p>',
)
def test_truncate3(self):
self.assertEqual(
... |
class TestUtilsText(SimpleTestCase):
# lazy strings are handled correctly
self.assertEqual(text.Truncator(lazystr('The quick brown fox')).chars(12), 'The quick...')
def test_truncate_words(self):
truncator = text.Truncator('The quick brown fox jumped over the lazy dog.')
self.assert... | class TestUtilsText(SimpleTestCase):
# lazy strings are handled correctly
self.assertEqual(text.Truncator(lazystr('The quick brown fox')).chars(12), 'The quick...')
def test_truncate_chars_html(self):
perf_test_values = [
(('</a' + '\t' * 50000) + '//>', None),
('&' ... |
class TestUtilsText(SimpleTestCase):
truncator = text.Truncator('<i>Buenos días! ¿Cómo está?</i>')
self.assertEqual('<i>Buenos días! ¿Cómo...</i>', truncator.words(3, '...', html=True))
truncator = text.Truncator('<p>I <3 python, what about you... | class TestUtilsText(SimpleTestCase):
truncator = text.Truncator('<i>Buenos días! ¿Cómo está?</i>')
self.assertEqual('<i>Buenos días! ¿Cómo...</i>', truncator.words(3, '...', html=True))
truncator = text.Truncator('<p>I <3 python, what about you... |
from ansible.galaxy.role import GalaxyRole
from ansible.galaxy.token import BasicAuthToken, GalaxyToken, KeycloakToken, NoTokenSentinel
from ansible.module_utils.ansible_release import __version__ as ansible_version
from ansible.module_utils._text import to_bytes, to_native, to_text
from ansible.parsing.yaml.loader imp... | from ansible.galaxy.role import GalaxyRole
from ansible.galaxy.token import BasicAuthToken, GalaxyToken, KeycloakToken, NoTokenSentinel
from ansible.module_utils.ansible_release import __version__ as ansible_version
from ansible.module_utils._text import to_bytes, to_native, to_text
from ansible.module_utils import six... |
class GalaxyCLI(CLI):
else:
requirements = []
for collection_input in collections:
name, dummy, requirement = collection_input.partition(':')
requirements.append((name, requirement or '*', None))
output_path = GalaxyCLI._re... | class GalaxyCLI(CLI):
else:
requirements = []
for collection_input in collections:
requirement = None
if os.path.isfile(to_bytes(collection_input, errors='surrogate_or_strict')) or \
urlparse(collection_input... |
def _get_collection_info(dep_map, existing_collections, collection, requirement,
if os.path.isfile(to_bytes(collection, errors='surrogate_or_strict')):
display.vvvv("Collection requirement '%s' is a tar artifact" % to_text(collection))
b_tar_path = to_bytes(collection, errors='surrogate_or_strict')
... | def _get_collection_info(dep_map, existing_collections, collection, requirement,
if os.path.isfile(to_bytes(collection, errors='surrogate_or_strict')):
display.vvvv("Collection requirement '%s' is a tar artifact" % to_text(collection))
b_tar_path = to_bytes(collection, errors='surrogate_or_strict')
... |
def test_collection_install_in_collection_dir(collection_install, monkeypatch):
assert mock_install.call_args[0][7] is False
def test_collection_install_name_and_requirements_fail(collection_install):
test_path = collection_install[2]
expected = 'The positional collection_name arg and --requirements-file ... | def test_collection_install_in_collection_dir(collection_install, monkeypatch):
assert mock_install.call_args[0][7] is False
def test_collection_install_with_url(collection_install):
mock_install, dummy, output_dir = collection_install
galaxy_args = ['ansible-galaxy', 'collection', 'install', 'https://fo... |
class Parameter(object):
return [str(v) for v in x]
return str(x)
def parse_from_input(self, param_name, x):
"""
Parses the parameter value from input ``x``, handling defaults and is_list.
| class Parameter(object):
return [str(v) for v in x]
return str(x)
def parse_from_input(self, param_name, x, task_name=None):
"""
Parses the parameter value from input ``x``, handling defaults and is_list.
|
class Parameter(object):
:raises MissingParameterException: if x is false-y and no default is specified.
"""
if not x:
if self.has_value:
return self.value
elif self.is_bool:
return False
elif self.is_list: | class Parameter(object):
:raises MissingParameterException: if x is false-y and no default is specified.
"""
if not x:
if self.has_task_value(param_name=param_name, task_name=task_name):
return self.task_value(param_name=param_name, task_name=task_name)
el... |
class Parameter(object):
description.append('for all instances of class %s' % task_name)
elif self.description:
description.append(self.description)
if self.has_value:
description.append(" [default: %s]" % (self.value,))
if self.is_list:
action = ... | class Parameter(object):
description.append('for all instances of class %s' % task_name)
elif self.description:
description.append(self.description)
if self.has_task_value(param_name=param_name, task_name=task_name):
value = self.task_value(param_name=param_name, task... |
class Parameter(object):
dest = self.parser_dest(param_name, task_name, glob=False)
if dest is not None:
value = getattr(args, dest, None)
params[param_name] = self.parse_from_input(param_name, value)
def set_global_from_args(self, param_name, task_name, args, is_without_sec... | class Parameter(object):
dest = self.parser_dest(param_name, task_name, glob=False)
if dest is not None:
value = getattr(args, dest, None)
params[param_name] = self.parse_from_input(param_name, value, task_name=task_name)
def set_global_from_args(self, param_name, task_name,... |
class Parameter(object):
if dest is not None:
value = getattr(args, dest, None)
if value:
self.set_global(self.parse_from_input(param_name, value))
else: # either False (bools) or None (everything else)
self.reset_global()
| class Parameter(object):
if dest is not None:
value = getattr(args, dest, None)
if value:
self.set_global(self.parse_from_input(param_name, value, task_name=task_name))
else: # either False (bools) or None (everything else)
self.reset_global()... |
class TestRemoveGlobalParameters(unittest.TestCase):
class TestParamWithDefaultFromConfig(unittest.TestCase):
def testNoSection(self):
self.assertRaises(ParameterException, lambda: luigi.Parameter(config_path=dict(section="foo", name="bar")).value)
| class TestRemoveGlobalParameters(unittest.TestCase):
class TestParamWithDefaultFromConfig(unittest.TestCase):
def run_and_check(self, args):
run_exit_status = luigi.run(['--local-scheduler', '--no-lock'] + args)
return run_exit_status
def testNoSection(self):
self.assertRaises(Paramet... |
class TestParamWithDefaultFromConfig(unittest.TestCase):
self.assertEqual(123, luigi.tools.range.RangeDaily(of=A).days_back)
self.assertEqual(70, luigi.tools.range.RangeDaily(of=A, days_back=70).days_back)
class OverrideEnvStuff(unittest.TestCase):
| class TestParamWithDefaultFromConfig(unittest.TestCase):
self.assertEqual(123, luigi.tools.range.RangeDaily(of=A).days_back)
self.assertEqual(70, luigi.tools.range.RangeDaily(of=A, days_back=70).days_back)
@with_config({"MyClass": {"p_not_global": "123"}})
def testCommandLineWithDefault(self):
... |
class InputLayer(Layer):
self.trainable = False
self.built = True
self.sparse = sparse
if input_shape and batch_input_shape:
raise ValueError('Only provide the input_shape OR ' | class InputLayer(Layer):
self.trainable = False
self.built = True
self.sparse = sparse
self.supports_masking = True
if input_shape and batch_input_shape:
raise ValueError('Only provide the input_shape OR ' |
from numpy.testing import assert_allclose
from keras import backend as K
from keras import layers
from keras.models import Model
from keras.utils.test_utils import layer_test
from keras.utils.test_utils import keras_test
from keras import regularizers | from numpy.testing import assert_allclose
from keras import backend as K
from keras import layers
from keras.models import Model
from keras.models import Sequential
from keras.utils.test_utils import layer_test
from keras.utils.test_utils import keras_test
from keras import regularizers |
def test_activity_regularization():
model.compile('rmsprop', 'mse')
if __name__ == '__main__':
pytest.main([__file__]) | def test_activity_regularization():
model.compile('rmsprop', 'mse')
@keras_test
def test_sequential_as_downstream_of_masking_layer():
inputs = layers.Input(shape=(3, 4))
x = layers.Masking(mask_value=0., input_shape=(3, 4))(inputs)
s = Sequential()
s.add(layers.Dense(5, input_shape=(4,)))
s.a... |
class TupleParameter(ListParameter):
try:
# loop required to parse tuple of tuples
return tuple(tuple(x) for x in json.loads(x, object_pairs_hook=_FrozenOrderedDict))
except ValueError:
return literal_eval(x) # if this causes an error, let that error be raised.
cla... | class TupleParameter(ListParameter):
try:
# loop required to parse tuple of tuples
return tuple(tuple(x) for x in json.loads(x, object_pairs_hook=_FrozenOrderedDict))
except (ValueError, TypeError):
return tuple(literal_eval(x)) # if this causes an error, let that er... |
class TestTaskParameter(LuigiTestCase):
self.assertTrue(self.run_locally(['MainTask']))
class NewStyleParameters822Test(LuigiTestCase):
"""
I bet these tests created at 2015-03-08 are reduntant by now (Oct 2015). | class TestTaskParameter(LuigiTestCase):
self.assertTrue(self.run_locally(['MainTask']))
class TestSerializeTupleParameter(LuigiTestCase):
def testSerialize(self):
the_tuple = (1, 2, 3)
self.assertEqual(luigi.TupleParameter().parse(luigi.TupleParameter().serialize(the_tuple)), the_tuple)
... |
from pandas.core.algorithms import (
)
from pandas.core.base import NoNewAttributesMixin, PandasObject, _shared_docs
import pandas.core.common as com
from pandas.core.construction import extract_array, sanitize_array
from pandas.core.missing import interpolate_2d
from pandas.core.sorting import nargsort
| from pandas.core.algorithms import (
)
from pandas.core.base import NoNewAttributesMixin, PandasObject, _shared_docs
import pandas.core.common as com
from pandas.core.construction import array, extract_array, sanitize_array
from pandas.core.missing import interpolate_2d
from pandas.core.sorting import nargsort
|
class Categorical(ExtensionArray, PandasObject):
if dtype == self.dtype:
return self
return self._set_dtype(dtype)
if is_integer_dtype(dtype) and self.isna().any():
msg = "Cannot convert float NaN to integer"
raise ValueError(msg) | class Categorical(ExtensionArray, PandasObject):
if dtype == self.dtype:
return self
return self._set_dtype(dtype)
if is_extension_array_dtype(dtype):
return array(self, dtype=dtype, copy=copy) # type: ignore # GH 28770
if is_integer_dtype(dtype) and ... |
class TestCasting(base.BaseCastingTests):
with pytest.raises((ValueError, TypeError), match=msg):
s.astype(int)
class TestArithmeticOps(base.BaseArithmeticOpsTests):
def test_arith_series_with_scalar(self, data, all_arithmetic_operators): | class TestCasting(base.BaseCastingTests):
with pytest.raises((ValueError, TypeError), match=msg):
s.astype(int)
@pytest.mark.parametrize(
"expected",
[
pd.Series(["2019", "2020"], dtype="datetime64[ns, UTC]"),
pd.Series([0, 0], dtype="timedelta64[ns]"),
... |
def test_merge_equal_cat_dtypes2():
tm.assert_frame_equal(result, expected, check_categorical=False)
def test_merge_multiindex_columns():
# Issue #28518
# Verify that merging two dataframes give the expected labels | def test_merge_equal_cat_dtypes2():
tm.assert_frame_equal(result, expected, check_categorical=False)
def test_merge_on_cat_and_ext_array():
# GH 28668
right = DataFrame(
{"a": Series([pd.Interval(0, 1), pd.Interval(1, 2)], dtype="interval")}
)
left = right.copy()
left["a"] = left["a"].... |
def url(tgpath, tgparams=None, **kwargs):
'''
if not isinstance(tgpath, six.string_types):
tgpath = '/'.join(list(tgpath))
if tgpath.startswith('/'):
webpath = (config.get('server.webpath') or '').rstrip('/')
if tg_util.request_available(): | def url(tgpath, tgparams=None, **kwargs):
'''
if not isinstance(tgpath, six.string_types):
tgpath = '/'.join(list(tgpath))
if not tgpath.startswith('/'):
# Do not allow the url() function to be used for external urls.
# This function is primarily used in redirect() calls, so this pre... |
def history_without_current(mocker):
('vom file.py', 'vom: not found'),
('fucck', 'fucck: not found'),
('got commit', 'got: command not found')])
def test_match(script, stderr):
assert match(Command(script, stderr=stderr))
@pytest.mark.usefixtures('no_memoize')
@pytest.mark.parametrize('script, stderr... | def history_without_current(mocker):
('vom file.py', 'vom: not found'),
('fucck', 'fucck: not found'),
('got commit', 'got: command not found')])
def test_match(mocker, script, stderr):
mocker.patch('thefuck.rules.no_command.which', return_value=None)
assert match(Command(script, stderr=stderr))
... |
from difflib import get_close_matches
from thefuck.utils import get_all_executables, \
get_valid_history_without_current, get_closest
from thefuck.specific.sudo import sudo_support
@sudo_support
def match(command):
return (command.script_parts
and 'not found' in command.stderr
and bool... | from difflib import get_close_matches
from thefuck.utils import get_all_executables, \
get_valid_history_without_current, get_closest, which
from thefuck.specific.sudo import sudo_support
@sudo_support
def match(command):
return (not which(command.script_parts[0])
and 'not found' in command.stderr... |
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 | 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 |
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=... |
def verify_signature(pubkey_path, message, signature):
try:
return pubkey.verify(digest, signature)
except RSA.RSAError as exc:
if exc.args[0] == "bad signature":
return False
raise
else:
verifier = PKCS1_v1_5.new(pubkey)
return ver... | def verify_signature(pubkey_path, message, signature):
try:
return pubkey.verify(digest, signature)
except RSA.RSAError as exc:
log.debug("Signature verification failed: %s", exc.args[0])
return False
else:
verifier = PKCS1_v1_5.new(pubkey)
return ... |
class AsyncAuth:
clear_signature = payload["sig"]
payload = salt.payload.loads(clear_signed_data)
auth["aes"] = self.verify_master(payload, master_pub="token" in sign_in_payload)
if not auth["aes"]:
log.critical(
"The Salt Master server's public key did not a... | class AsyncAuth:
clear_signature = payload["sig"]
payload = salt.payload.loads(clear_signed_data)
if "pub_key" in payload:
auth["aes"] = self.verify_master(
payload, master_pub="token" in sign_in_payload
)
if not auth["aes"]:
l... |
import salt.crypt
import salt.master
import salt.utils.files
def test_get_rsa_pub_key_bad_key(tmp_path):
""" | import salt.crypt
import salt.master
import salt.utils.files
PRIV_KEY = """
-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAoAsMPt+4kuIG6vKyw9r3+OuZrVBee/2vDdVetW+Js5dTlgrJ
aghWWn3doGmKlEjqh7E4UTa+t2Jd6w8RSLnyHNJ/HpVhMG0M07MF6FMfILtDrrt8
ZX7eDVt8sx5gCEpYI+XG8Y07Ga9i3Hiczt+fu6HYwu96HggmG2pqkOrn3iGfqBvV
YVFJzSZYe7e4c1Pe... |
def test_cryptical_dumps_invalid_nonce():
assert isinstance(ret, bytes)
with pytest.raises(salt.crypt.SaltClientError, match="Nonce verification error"):
assert master_crypt.loads(ret, nonce="abcde") | def test_cryptical_dumps_invalid_nonce():
assert isinstance(ret, bytes)
with pytest.raises(salt.crypt.SaltClientError, match="Nonce verification error"):
assert master_crypt.loads(ret, nonce="abcde")
def test_verify_signature(tmpdir):
tmpdir.join("foo.pem").write(PRIV_KEY.strip())
tmpdir.join(... |
async def test_req_chan_auth_v2_with_master_signing(pki_dir, io_loop):
pki_dir.join("minion", "minion_master.pub").read()
== pki_dir.join("master", "master.pub").read()
) | async def test_req_chan_auth_v2_with_master_signing(pki_dir, io_loop):
pki_dir.join("minion", "minion_master.pub").read()
== pki_dir.join("master", "master.pub").read()
)
async def test_req_chan_auth_v2_new_minion_with_master_pub(pki_dir, io_loop):
pki_dir.join("master", "minions", "minion").... |
class APIRouter(routing.Router):
include_in_schema: bool = True,
response_class: Type[Response] = None,
name: str = None,
) -> None:
route = self.route_class(
path,
endpoint=endpoint,
response_model=response_model, | class APIRouter(routing.Router):
include_in_schema: bool = True,
response_class: Type[Response] = None,
name: str = None,
route_class_override: Optional[Type[APIRoute]] = None,
) -> None:
route_class = route_class_override or self.route_class
route = route_class(
... |
class APIRouter(routing.Router):
include_in_schema=route.include_in_schema,
response_class=route.response_class or default_response_class,
name=route.name,
)
elif isinstance(route, routing.Route):
self.add_route( | class APIRouter(routing.Router):
include_in_schema=route.include_in_schema,
response_class=route.response_class or default_response_class,
name=route.name,
route_class_override=type(route),
)
elif isinstance(rout... |
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z1,
norm=colors.SymLogNorm(linthresh=0.03, linscale=0.03,
vmin=-1.0, vmax=1.0),
cmap='RdBu_r')
fig.colorbar(pcm, ax=ax[0], extend='both')
| fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z1,
norm=colors.SymLogNorm(linthresh=0.03, linscale=0.03,
vmin=-1.0, vmax=1.0, base=10),
cmap='RdBu_r')
fig.colorbar(pcm, ax=ax[0], extend='both')
|
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z,
norm=colors.SymLogNorm(linthresh=0.03, linscale=0.03,
vmin=-1.0, vmax=1.0),
cmap='RdBu_r')
fig.colorbar(pcm, ax=ax[0], extend='both')
| fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z,
norm=colors.SymLogNorm(linthresh=0.03, linscale=0.03,
vmin=-1.0, vmax=1.0, base=10),
cmap='RdBu_r')
fig.colorbar(pcm, ax=ax[0], extend='both')
|
class SymLogNorm(Normalize):
*linthresh* allows the user to specify the size of this range
(-*linthresh*, *linthresh*).
"""
def __init__(self, linthresh, linscale=1.0,
vmin=None, vmax=None, clip=False):
"""
Parameters
---------- | class SymLogNorm(Normalize):
*linthresh* allows the user to specify the size of this range
(-*linthresh*, *linthresh*).
"""
def __init__(self, linthresh, linscale=1.0, vmin=None, vmax=None,
clip=False, base=None):
"""
Parameters
---------- |
class SymLogNorm(Normalize):
linscale : float, default: 1
This allows the linear range (-*linthresh* to *linthresh*) to be
stretched relative to the logarithmic range. Its value is the
number of decades to use for each half of the linear range. For
example, when *... | class SymLogNorm(Normalize):
linscale : float, default: 1
This allows the linear range (-*linthresh* to *linthresh*) to be
stretched relative to the logarithmic range. Its value is the
number of powers of *base* (decades for base 10) to use for each
half of the li... |
class SymLogNorm(Normalize):
with np.errstate(invalid="ignore"):
masked = np.abs(a) > self.linthresh
sign = np.sign(a[masked])
log = (self._linscale_adj + np.log(np.abs(a[masked]) / self.linthresh))
log *= sign * self.linthresh
a[masked] = log
a[~masked] *= se... | class SymLogNorm(Normalize):
with np.errstate(invalid="ignore"):
masked = np.abs(a) > self.linthresh
sign = np.sign(a[masked])
log = (self._linscale_adj +
np.log(np.abs(a[masked]) / self.linthresh) / self._log_base)
log *= sign * self.linthresh
a[masked... |
class SymLogNorm(Normalize):
"""Inverse inplace Transformation."""
masked = np.abs(a) > (self.linthresh * self._linscale_adj)
sign = np.sign(a[masked])
exp = np.exp(sign * a[masked] / self.linthresh - self._linscale_adj)
exp *= sign * self.linthresh
a[masked] = exp
... | class SymLogNorm(Normalize):
"""Inverse inplace Transformation."""
masked = np.abs(a) > (self.linthresh * self._linscale_adj)
sign = np.sign(a[masked])
exp = np.power(self._base,
sign * a[masked] / self.linthresh - self._linscale_adj)
exp *= sign * self.lin... |
def test_SymLogNorm():
"""
Test SymLogNorm behavior
"""
norm = mcolors.SymLogNorm(3, vmax=5, linscale=1.2)
vals = np.array([-30, -1, 2, 6], dtype=float)
normed_vals = norm(vals)
expected = [0., 0.53980074, 0.826991, 1.02758204] | def test_SymLogNorm():
"""
Test SymLogNorm behavior
"""
norm = mcolors.SymLogNorm(3, vmax=5, linscale=1.2, base=np.e)
vals = np.array([-30, -1, 2, 6], dtype=float)
normed_vals = norm(vals)
expected = [0., 0.53980074, 0.826991, 1.02758204] |
def test_SymLogNorm():
_mask_tester(norm, vals)
# Ensure that specifying vmin returns the same result as above
norm = mcolors.SymLogNorm(3, vmin=-30, vmax=5, linscale=1.2)
normed_vals = norm(vals)
assert_array_almost_equal(normed_vals, expected)
def test_SymLogNorm_colorbar():
"""
Test un... | def test_SymLogNorm():
_mask_tester(norm, vals)
# Ensure that specifying vmin returns the same result as above
norm = mcolors.SymLogNorm(3, vmin=-30, vmax=5, linscale=1.2, base=np.e)
normed_vals = norm(vals)
assert_array_almost_equal(normed_vals, expected)
# test something more easily checked.... |
def test_SymLogNorm_single_zero():
Test SymLogNorm to ensure it is not adding sub-ticks to zero label
"""
fig = plt.figure()
norm = mcolors.SymLogNorm(1e-5, vmin=-1, vmax=1)
cbar = mcolorbar.ColorbarBase(fig.add_subplot(111), norm=norm)
ticks = cbar.get_ticks()
assert sum(ticks == 0) == 1 | def test_SymLogNorm_single_zero():
Test SymLogNorm to ensure it is not adding sub-ticks to zero label
"""
fig = plt.figure()
norm = mcolors.SymLogNorm(1e-5, vmin=-1, vmax=1, base=np.e)
cbar = mcolorbar.ColorbarBase(fig.add_subplot(111), norm=norm)
ticks = cbar.get_ticks()
assert sum(ticks ==... |
def test_ndarray_subclass_norm(recwarn):
mydata = data.view(MyArray)
for norm in [mcolors.Normalize(), mcolors.LogNorm(),
mcolors.SymLogNorm(3, vmax=5, linscale=1),
mcolors.Normalize(vmin=mydata.min(), vmax=mydata.max()),
mcolors.SymLogNorm(3, vmin=mydata.min(... | def test_ndarray_subclass_norm(recwarn):
mydata = data.view(MyArray)
for norm in [mcolors.Normalize(), mcolors.LogNorm(),
mcolors.SymLogNorm(3, vmax=5, linscale=1, base=np.e),
mcolors.Normalize(vmin=mydata.min(), vmax=mydata.max()),
mcolors.SymLogNorm(3, vmin=... |
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z,
norm=colors.SymLogNorm(linthresh=0.03, linscale=0.03,
vmin=-1.0, vmax=1.0),
cmap='RdBu_r')
fig.colorbar(pcm, ax=ax[0], extend='both')
| fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z,
norm=colors.SymLogNorm(linthresh=0.03, linscale=0.03,
vmin=-1.0, vmax=1.0, base=10),
cmap='RdBu_r')
fig.colorbar(pcm, ax=ax[0], extend='both')
|
class _LocIndexer(_LocationIndexer):
return self._getbool_axis(key, axis=axis)
elif is_list_like_indexer(key):
# convert various list-like indexers
# to a list of keys
# we will use the *values* of the object
# and NOT the index if its a PandasObject
... | class _LocIndexer(_LocationIndexer):
return self._getbool_axis(key, axis=axis)
elif is_list_like_indexer(key):
# an iterable multi-selection
if not (isinstance(key, tuple) and isinstance(labels, ABCMultiIndex)):
|
class TestMultiIndexLoc:
@pytest.mark.parametrize("key, pos", [([2, 4], [0, 1]), ([2], []), ([2, 3], [])])
def test_loc_multiindex_list_missing_label(self, key, pos):
# GH 27148 - lists with missing labels do not raise:
df = DataFrame(
np.random.randn(3, 3),
columns=[[2,... | class TestMultiIndexLoc:
@pytest.mark.parametrize("key, pos", [([2, 4], [0, 1]), ([2], []), ([2, 3], [])])
def test_loc_multiindex_list_missing_label(self, key, pos):
# GH 27148 - lists with missing labels _do_ raise
df = DataFrame(
np.random.randn(3, 3),
columns=[[2, 2,... |
class TestMultiIndexLoc:
[
([], []), # empty ok
(["A"], slice(3)),
(["A", "D"], slice(3)),
(["D", "E"], []), # no values found - fine
(["D"], []), # same, with single item list: GH 27148
(pd.IndexSlice[:, ["foo"]], slice(2, None, 3)),
(pd.IndexSlice[:, ["fo... | class TestMultiIndexLoc:
[
([], []), # empty ok
(["A"], slice(3)),
(["A", "D"], []), # "D" isnt present -> raise
(["D", "E"], []), # no values found -> raise
(["D"], []), # same, with single item list: GH 27148
(pd.IndexSlice[:, ["foo"]], slice(2, None, 3)),
... |
def test_loc_getitem_duplicates_multiindex_missing_indexers(indexer, pos):
)
s = Series(np.arange(9, dtype="int64"), index=idx).sort_index()
expected = s.iloc[pos]
result = s.loc[indexer]
tm.assert_series_equal(result, expected)
def test_series_loc_getitem_fancy(multiindex_year_month_day_dataframe... | def test_loc_getitem_duplicates_multiindex_missing_indexers(indexer, pos):
)
s = Series(np.arange(9, dtype="int64"), index=idx).sort_index()
expected = s.iloc[pos]
if expected.size == 0 and indexer != []:
with pytest.raises(KeyError, match=str(indexer)):
s.loc[indexer]
else:
... |
class TestMultiIndexSlicers:
with pytest.raises(ValueError, match=msg):
df.loc[(slice(None), np.array([True, False])), :]
# ambiguous notation
# this is interpreted as slicing on both axes (GH #16396)
result = df.loc[slice(None), [1]]
expected = df.iloc[:, []]
... | class TestMultiIndexSlicers:
with pytest.raises(ValueError, match=msg):
df.loc[(slice(None), np.array([True, False])), :]
with pytest.raises(KeyError, match=r"\[1\] not in index"):
# slice(None) is on the index, [1] is on the columns, but 1 is
# not in the columns, ... |
class TestSeriesGetitemListLike:
result = ser[key]
tm.assert_series_equal(result, expected)
def test_getitem_generator(string_series):
gen = (x > 0 for x in string_series) | class TestSeriesGetitemListLike:
result = ser[key]
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("box", [list, np.array, pd.Index])
@pytest.mark.parametrize("dtype", [np.int64, np.float64, np.uint64])
def test_getitem_intlist_multiindex_numeric_level(self, dtype, box):
... |
from __future__ import print_function
import warnings
import numpy as np
from .training_utils import iter_sequence_infinite
from .. import backend as K
from ..utils.data_utils import Sequence | from __future__ import print_function
import warnings
import numpy as np
from .training_utils import is_sequence
from .training_utils import iter_sequence_infinite
from .. import backend as K
from ..utils.data_utils import Sequence |
def fit_generator(model,
if do_validation:
model._make_test_function()
is_sequence = isinstance(generator, Sequence)
if not is_sequence and use_multiprocessing and workers > 1:
warnings.warn(
UserWarning('Using a generator with `use_multiprocessing=True`'
... | def fit_generator(model,
if do_validation:
model._make_test_function()
use_sequence_api = is_sequence(generator)
if not use_sequence_api and use_multiprocessing and workers > 1:
warnings.warn(
UserWarning('Using a generator with `use_multiprocessing=True`'
... |
def fit_generator(model,
# python 2 has 'next', 3 has '__next__'
# avoid any explicit version checks
val_gen = (hasattr(validation_data, 'next') or
hasattr(validation_data, '__next__') or
isinstance(validation_data, Sequence))
if (val_gen and not isinstance(validation_data... | def fit_generator(model,
# python 2 has 'next', 3 has '__next__'
# avoid any explicit version checks
val_use_sequence_api = is_sequence(validation_data)
val_gen = (hasattr(validation_data, 'next') or
hasattr(validation_data, '__next__') or
val_use_sequence_api)
if (val... |
def fit_generator(model,
if val_gen and workers > 0:
# Create an Enqueuer that can be reused
val_data = validation_data
if isinstance(val_data, Sequence):
val_enqueuer = OrderedEnqueuer(
val_data,
... | def fit_generator(model,
if val_gen and workers > 0:
# Create an Enqueuer that can be reused
val_data = validation_data
if is_sequence(val_data):
val_enqueuer = OrderedEnqueuer(
val_data,
use_... |
def fit_generator(model,
val_enqueuer_gen = val_enqueuer.get()
elif val_gen:
val_data = validation_data
if isinstance(val_data, Sequence):
val_enqueuer_gen = iter_sequence_infinite(val_data)
validation_steps = validation... | def fit_generator(model,
val_enqueuer_gen = val_enqueuer.get()
elif val_gen:
val_data = validation_data
if is_sequence(val_data):
val_enqueuer_gen = iter_sequence_infinite(val_data)
validation_steps = validation_steps or... |
def fit_generator(model,
cbk.validation_data = val_data
if workers > 0:
if is_sequence:
enqueuer = OrderedEnqueuer(
generator,
use_multiprocessing=use_multiprocessing, | def fit_generator(model,
cbk.validation_data = val_data
if workers > 0:
if use_sequence_api:
enqueuer = OrderedEnqueuer(
generator,
use_multiprocessing=use_multiprocessing, |
def fit_generator(model,
enqueuer.start(workers=workers, max_queue_size=max_queue_size)
output_generator = enqueuer.get()
else:
if is_sequence:
output_generator = iter_sequence_infinite(generator)
else:
output_generator = generator | def fit_generator(model,
enqueuer.start(workers=workers, max_queue_size=max_queue_size)
output_generator = enqueuer.get()
else:
if use_sequence_api:
output_generator = iter_sequence_infinite(generator)
else:
output_generator = gener... |
def evaluate_generator(model, generator,
steps_done = 0
outs_per_batch = []
batch_sizes = []
is_sequence = isinstance(generator, Sequence)
if not is_sequence and use_multiprocessing and workers > 1:
warnings.warn(
UserWarning('Using a generator with `use_multiprocessing=True`'
... | def evaluate_generator(model, generator,
steps_done = 0
outs_per_batch = []
batch_sizes = []
use_sequence_api = is_sequence(generator)
if not use_sequence_api and use_multiprocessing and workers > 1:
warnings.warn(
UserWarning('Using a generator with `use_multiprocessing=True`'
... |
def evaluate_generator(model, generator,
try:
if workers > 0:
if is_sequence:
enqueuer = OrderedEnqueuer(
generator,
use_multiprocessing=use_multiprocessing) | def evaluate_generator(model, generator,
try:
if workers > 0:
if use_sequence_api:
enqueuer = OrderedEnqueuer(
generator,
use_multiprocessing=use_multiprocessing) |
def evaluate_generator(model, generator,
enqueuer.start(workers=workers, max_queue_size=max_queue_size)
output_generator = enqueuer.get()
else:
if is_sequence:
output_generator = iter_sequence_infinite(generator)
else:
output_genera... | def evaluate_generator(model, generator,
enqueuer.start(workers=workers, max_queue_size=max_queue_size)
output_generator = enqueuer.get()
else:
if use_sequence_api:
output_generator = iter_sequence_infinite(generator)
else:
output_g... |
def predict_generator(model, generator,
steps_done = 0
all_outs = []
is_sequence = isinstance(generator, Sequence)
if not is_sequence and use_multiprocessing and workers > 1:
warnings.warn(
UserWarning('Using a generator with `use_multiprocessing=True`'
' and... | def predict_generator(model, generator,
steps_done = 0
all_outs = []
use_sequence_api = is_sequence(generator)
if not use_sequence_api and use_multiprocessing and workers > 1:
warnings.warn(
UserWarning('Using a generator with `use_multiprocessing=True`'
' an... |
def predict_generator(model, generator,
try:
if workers > 0:
if is_sequence:
enqueuer = OrderedEnqueuer(
generator,
use_multiprocessing=use_multiprocessing) | def predict_generator(model, generator,
try:
if workers > 0:
if use_sequence_api:
enqueuer = OrderedEnqueuer(
generator,
use_multiprocessing=use_multiprocessing) |
def predict_generator(model, generator,
enqueuer.start(workers=workers, max_queue_size=max_queue_size)
output_generator = enqueuer.get()
else:
if is_sequence:
output_generator = iter_sequence_infinite(generator)
else:
output_generat... | def predict_generator(model, generator,
enqueuer.start(workers=workers, max_queue_size=max_queue_size)
output_generator = enqueuer.get()
else:
if use_sequence_api:
output_generator = iter_sequence_infinite(generator)
else:
output_ge... |
import warnings
from .. import backend as K
from .. import losses
from ..utils.generic_utils import to_list
| import warnings
from .. import backend as K
from .. import losses
from ..utils import Sequence
from ..utils.generic_utils import to_list
|
def iter_sequence_infinite(seq):
while True:
for item in seq:
yield item | def iter_sequence_infinite(seq):
while True:
for item in seq:
yield item
def is_sequence(seq):
"""Determine if an object follows the Sequence API.
# Arguments
seq: a possible Sequence object
# Returns
boolean, whether the object follows the Sequence API.
"""
... |
class Sequence(object):
```
"""
@abstractmethod
def __getitem__(self, index):
"""Gets batch at position `index`. | class Sequence(object):
```
"""
use_sequence_api = True
@abstractmethod
def __getitem__(self, index):
"""Gets batch at position `index`. |
from __future__ import print_function
import numpy as np
import pytest
from keras.utils.test_utils import get_test_data
from keras.models import Sequential
from keras import layers | from __future__ import print_function
import numpy as np
import pytest
from keras.preprocessing.image import ImageDataGenerator
from keras.utils.test_utils import get_test_data
from keras.models import Sequential
from keras import layers |
def test_image_classification():
model = Sequential.from_config(config)
if __name__ == '__main__':
pytest.main([__file__]) | def test_image_classification():
model = Sequential.from_config(config)
def test_image_data_generator_training():
np.random.seed(1337)
img_gen = ImageDataGenerator(rescale=1.) # Dummy ImageDataGenerator
input_shape = (16, 16, 3)
(x_train, y_train), (x_test, y_test) = get_test_data(num_train=500,
... |
from keras.utils.data_utils import validate_file
from keras import backend as K
pytestmark = pytest.mark.skipif(
K.backend() == 'tensorflow',
reason='Temporarily disabled until the use_multiprocessing problem is solved')
if sys.version_info < (3,): | from keras.utils.data_utils import validate_file
from keras import backend as K
pytestmark = pytest.mark.skipif(
K.backend() == 'tensorflow' and 'TRAVIS_PYTHON_VERSION' in os.environ,
reason='Temporarily disabled until the use_multiprocessing problem is solved')
if sys.version_info < (3,): |
from keras.utils import Sequence
from keras import backend as K
pytestmark = pytest.mark.skipif(
K.backend() == 'tensorflow',
reason='Temporarily disabled until the use_multiprocessing problem is solved')
STEPS_PER_EPOCH = 100 | from keras.utils import Sequence
from keras import backend as K
pytestmark = pytest.mark.skipif(
K.backend() == 'tensorflow' and 'TRAVIS_PYTHON_VERSION' in os.environ,
reason='Temporarily disabled until the use_multiprocessing problem is solved')
STEPS_PER_EPOCH = 100 |
def rnn(step_function, inputs, initial_states,
for o, p in zip(new_states, place_holders):
n_s.append(o.replace_placeholders({p: o.output}))
if len(n_s) > 0:
new_output = n_s[0]
return new_output, n_s
final_output, final_states = _recurrence(r... | def rnn(step_function, inputs, initial_states,
for o, p in zip(new_states, place_holders):
n_s.append(o.replace_placeholders({p: o.output}))
if len(n_s) > 0:
new_output = n_s[-1]
return new_output, n_s
final_output, final_states = _recurrence(... |
class StackedRNNCells(Layer):
'`state_size` attribute. '
'received cells:', cells)
self.cells = cells
super(StackedRNNCells, self).__init__(**kwargs)
@property
def state_size(self):
# States are a flat list
# in r... | class StackedRNNCells(Layer):
'`state_size` attribute. '
'received cells:', cells)
self.cells = cells
# reverse_state_order determines whether the state size will be in a
# reverse order of the cells' state. User might want to set... |
class StackedRNNCells(Layer):
# Format the new states as a flat list
# in reverse cell order.
states = []
for cell_states in new_nested_states[::-1]:
states += cell_states
return inputs, states
def build(self, input_shape):
if isinstance(input_shape, lis... | class StackedRNNCells(Layer):
# Format the new states as a flat list
# in reverse cell order.
new_states = []
if self.reverse_state_order:
new_nested_states = new_nested_states[::-1]
for cell_states in new_nested_states:
new_states += cell_states
... |
class StackedRNNCells(Layer):
cell.build([input_shape] + constants_shape)
else:
cell.build(input_shape)
if hasattr(cell.state_size, '__len__'):
output_dim = cell.state_size[0]
else:
output_dim = cell.state_si... | class StackedRNNCells(Layer):
cell.build([input_shape] + constants_shape)
else:
cell.build(input_shape)
if getattr(cell, 'output_size', None) is not None:
output_dim = cell.output_size
elif hasattr(cell.state_size, '__len__'... |
class RNN(Layer):
the size of the recurrent state
(which should be the same as the size of the cell output).
This can also be a list/tuple of integers
(one size per state). In this case, the first entry
(`state_size[0]`) should be the same ... | class RNN(Layer):
the size of the recurrent state
(which should be the same as the size of the cell output).
This can also be a list/tuple of integers
(one size per state).
- a `output_size` attribute. This can be a single integer or a
... |
class RNN(Layer):
state_size = self.cell.state_size
else:
state_size = [self.cell.state_size]
output_dim = state_size[0]
if self.return_sequences:
output_shape = (input_shape[0], input_shape[1], output_dim) | class RNN(Layer):
state_size = self.cell.state_size
else:
state_size = [self.cell.state_size]
if getattr(self.cell, 'output_size', None) is not None:
output_dim = self.cell.output_size
else:
output_dim = state_size[0]
if self.return_seque... |
class SimpleRNNCell(Layer):
self.dropout = min(1., max(0., dropout))
self.recurrent_dropout = min(1., max(0., recurrent_dropout))
self.state_size = self.units
self._dropout_mask = None
self._recurrent_dropout_mask = None
| class SimpleRNNCell(Layer):
self.dropout = min(1., max(0., dropout))
self.recurrent_dropout = min(1., max(0., recurrent_dropout))
self.state_size = self.units
self.output_size = self.units
self._dropout_mask = None
self._recurrent_dropout_mask = None
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.