buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
class CentralPlannerTest(unittest.TestCase):
self.assertTrue(0 <= res < NUM_PENDING)
self.sch.add_task(worker=WORKER, task_id=str(res), status=DONE)
if __name__ == '__main__':
unittest.main() | class CentralPlannerTest(unittest.TestCase):
self.assertTrue(0 <= res < NUM_PENDING)
self.sch.add_task(worker=WORKER, task_id=str(res), status=DONE)
def test_assistants_dont_nurture_finished_statuses(self):
"""
Assistants should not affect longevity of DONE tasks
Al... |
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.utils.translation import ugettext as _
from keystoneclient import exceptions as keystone_exceptions
| from django.conf import settings
from django.contrib import messages
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.utils.http import same_origin
from django.utils.translation import ugettext as _
from keystoneclient import exceptions as keystone_exceptions
|
def handle(self, request, data):
request.session['region_endpoint'] = endpoint
request.session['region_name'] = region_name
redirect_to = request.REQUEST.get(REDIRECT_FIELD_NAME, "")
if data.get('tenant', None):
try: | def handle(self, request, data):
request.session['region_endpoint'] = endpoint
request.session['region_name'] = region_name
redirect_to = request.REQUEST.get(REDIRECT_FIELD_NAME, None)
# Make sure the requested redirect matches the protocol,
# domain, and port of this request
... |
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... |
def strip_tags(value):
value = force_text(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 or length increased
# due to http://bugs.python.org/issue20288
... | def strip_tags(value):
value = force_text(value)
while '<' in value and '>' in value:
new_value = _strip_once(value)
if len(new_value) >= len(value) or value.count('<') == new_value.count('<'):
# _strip_once wasn't able to detect more tags, or line length increased.
# due... |
class TestUtilsHtml(SimpleTestCase):
# caused infinite loop on Pythons not patched with
# http://bugs.python.org/issue20288
('&gotcha&#;<>', '&gotcha&#;<>'),
)
for value, output in items:
self.check_output(f, value, output) | class TestUtilsHtml(SimpleTestCase):
# caused infinite loop on Pythons not patched with
# http://bugs.python.org/issue20288
('&gotcha&#;<>', '&gotcha&#;<>'),
('><!' + ('&' * 16000) + 'D', '><!' + ('&' * 16000) + 'D'),
('X<<<<br>br>br>br>X', 'XX'),
)
... |
def _make_concat_multiindex(indexes, keys, levels=None, names=None) -> MultiInde
for hlevel, level in zip(zipped, levels):
to_concat = []
for key, index in zip(hlevel, indexes):
try:
i = level.get_loc(key)
except KeyError as err:
... | def _make_concat_multiindex(indexes, keys, levels=None, names=None) -> MultiInde
for hlevel, level in zip(zipped, levels):
to_concat = []
for key, index in zip(hlevel, indexes):
mask = level == key
if not mask.any():
raise ValueError(f"... |
def test_concat_multiindex_datetime_object_index():
)
result = concat([s, s2], axis=1)
tm.assert_frame_equal(result, expected) | def test_concat_multiindex_datetime_object_index():
)
result = concat([s, s2], axis=1)
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("keys", [["e", "f", "f"], ["f", "e", "f"]])
def test_duplicate_keys(keys):
# GH 33654
df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
s1 = Se... |
def _create_instance(self, context, instance_type,
security_group, block_device_mapping)
instances.append(instance)
instance_uuids.append(instance['uuid'])
# In the case of any exceptions, attempt DB cleanup and rollback the
# quota reservations. | def _create_instance(self, context, instance_type,
security_group, block_device_mapping)
instances.append(instance)
instance_uuids.append(instance['uuid'])
self._validate_bdm(context, instance)
# send a state update notification for... |
def _update_block_device_mapping(self, elevated_context,
self.db.block_device_mapping_update_or_create(elevated_context,
values)
def _populate_instance_for_bdm(self, context, instance, instance_type,
image, block_device_mapping):
... | def _update_block_device_mapping(self, elevated_context,
self.db.block_device_mapping_update_or_create(elevated_context,
values)
def _validate_bdm(self, context, instance):
for bdm in self.db.block_device_mapping_get_all_by_instance(
... |
def create_db_entry_for_new_instance(self, context, instance_type, image,
self._populate_instance_for_bdm(context, instance,
instance_type, image, block_device_mapping)
# send a state update notification for the initial create to
# show it going from non-existent to BUILDING
... | def create_db_entry_for_new_instance(self, context, instance_type, image,
self._populate_instance_for_bdm(context, instance,
instance_type, image, block_device_mapping)
return instance
def _check_create_policies(self, context, availability_zone, |
class InvalidSnapshot(Invalid):
message = _("Invalid snapshot") + ": %(reason)s"
class VolumeUnattached(Invalid):
message = _("Volume %(volume_id)s is not attached to anything")
| class InvalidSnapshot(Invalid):
message = _("Invalid snapshot") + ": %(reason)s"
class InvalidBDM(Invalid):
message = _("Block Device Mapping is Invalid.")
class InvalidBDMSnapshot(InvalidBDM):
message = _("Block Device Mapping is Invalid: "
"failed to get snapshot %(id)s.")
class Inva... |
def update_user(self, context, user_id, user):
raise exception.UserNotFound(user_id=user_id)
user_ref = self.identity_api.update_user(context, user_id, user)
return {'user': user_ref}
def delete_user(self, context, user_id): | def update_user(self, context, user_id, user):
raise exception.UserNotFound(user_id=user_id)
user_ref = self.identity_api.update_user(context, user_id, user)
# If the password was changed or the user was disabled we clear tokens
if user.get('password') or user.get('enabled', True) ... |
def set_user_enabled(self, context, user_id, user):
return self.update_user(context, user_id, user)
def set_user_password(self, context, user_id, user):
user_ref = self.update_user(context, user_id, user)
try:
for token_id in self.token_api.list_tokens(context, user_id):
... | def set_user_enabled(self, context, user_id, user):
return self.update_user(context, user_id, user)
def set_user_password(self, context, user_id, user):
return self.update_user(context, user_id, user)
def update_user_tenant(self, context, user_id, user):
"""Update the default tenant.""... |
from keystone.common import wsgi
class AdminRouter(wsgi.ComposingRouter):
def __init__(self):
mapper = routes.Mapper() | from keystone.common import wsgi
LOG = logging.getLogger(__name__)
class AdminRouter(wsgi.ComposingRouter):
def __init__(self):
mapper = routes.Mapper() |
def authenticate(self, context, auth=None):
# If the user is disabled don't allow them to authenticate
if not user_ref.get('enabled', True):
raise exception.Forbidden(message='User has been disabled')
except AssertionError as e:
raise exce... | def authenticate(self, context, auth=None):
# If the user is disabled don't allow them to authenticate
if not user_ref.get('enabled', True):
LOG.warning('User %s is disabled' % user_id)
raise exception.Unauthorized()
except AssertionEr... |
def authenticate(self, context, auth=None):
user_ref = old_token_ref['user']
tenants = self.identity_api.get_tenants_for_user(context,
user_ref['id'])
if tenant_id: | def authenticate(self, context, auth=None):
user_ref = old_token_ref['user']
# If the user is disabled don't allow them to authenticate
current_user_ref = self.identity_api.get_user(
context=context,
... |
def test_change_password_invalidates_token(self):
client.tokens.authenticate,
token=token_id)
def test_user_create_update_delete(self):
from keystoneclient import exceptions as client_exceptions
| def test_change_password_invalidates_token(self):
client.tokens.authenticate,
token=token_id)
def test_disable_user_invalidates_token(self):
from keystoneclient import exceptions as client_exceptions
admin_client = self.get_client(admin=True)
... |
def test_user_create_update_delete(self):
user = client.users.get(user.id)
self.assertFalse(user.enabled)
self.assertRaises(client_exceptions.AuthorizationFailure,
self._client,
username=test_username,
password='password') | def test_user_create_update_delete(self):
user = client.users.get(user.id)
self.assertFalse(user.enabled)
self.assertRaises(client_exceptions.Unauthorized,
self._client,
username=test_username,
password='password') |
def test_user_create_update_delete(self):
user = client.users.get(user.id)
self.assertFalse(user.enabled)
self.assertRaises(client_exceptions.AuthorizationFailure,
self._client,
username=test_username,
password='password') | def test_user_create_update_delete(self):
user = client.users.get(user.id)
self.assertFalse(user.enabled)
self.assertRaises(client_exceptions.Unauthorized,
self._client,
username=test_username,
password='password') |
def __init__(self, host, port=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
(self.host, self.port) = self._get_hostport(host, port)
# This is stored as an instance variable to allow unit
# tests to replace it with a suitable mockup
self._create_connection = socket.create_connection | def __init__(self, host, port=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
(self.host, self.port) = self._get_hostport(host, port)
self._validate_host(self.host)
# This is stored as an instance variable to allow unit
# tests to replace it with a suitable mockup
self._create_co... |
def _validate_path(self, url):
).format(matched=match.group(), **locals())
raise InvalidURL(msg)
def putheader(self, header, *values):
"""Send a request header line to the server.
| def _validate_path(self, url):
).format(matched=match.group(), **locals())
raise InvalidURL(msg)
def _validate_host(self, host):
"""Validate a host so it doesn't contain control characters."""
# Prevent CVE-2019-18348.
match = _contains_disallowed_url_pchar_re.search... |
def run_server():
thread.join()
self.assertEqual(result, b"proxied data\n")
def test_putrequest_override_validation(self):
"""
It should be possible to override the default validation
behavior in putrequest (bpo-38216). | def run_server():
thread.join()
self.assertEqual(result, b"proxied data\n")
def test_putrequest_override_domain_validation(self):
"""
It should be possible to override the default validation
behavior in putrequest (bpo-38216). |
def _validate_path(self, url):
conn.sock = FakeSocket('')
conn.putrequest('GET', '/\x00')
def test_putrequest_override_encoding(self):
"""
It should be possible to override the default encoding | def _validate_path(self, url):
conn.sock = FakeSocket('')
conn.putrequest('GET', '/\x00')
def test_putrequest_override_host_validation(self):
class UnsafeHTTPConnection(client.HTTPConnection):
def _validate_host(self, url):
pass
conn = UnsafeHTTPConnecti... |
def test_willclose(self):
self.unfakehttp()
@unittest.skipUnless(ssl, "ssl module required")
def test_url_with_control_char_rejected(self):
for char_no in list(range(0, 0x21)) + [0x7f]:
char = chr(char_no)
schemeless_url = "//localhost:7777/test{}/".format(char) | def test_willclose(self):
self.unfakehttp()
@unittest.skipUnless(ssl, "ssl module required")
def test_url_path_with_control_char_rejected(self):
for char_no in list(range(0, 0x21)) + [0x7f]:
char = chr(char_no)
schemeless_url = "//localhost:7777/test{}/".format(char) |
def test_url_with_control_char_rejected(self):
self.unfakehttp()
@unittest.skipUnless(ssl, "ssl module required")
def test_url_with_newline_header_injection_rejected(self):
self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello.")
host = "localhost:7777?a=1 HTTP/1.1\r\nX-injected: header\... | def test_url_with_control_char_rejected(self):
self.unfakehttp()
@unittest.skipUnless(ssl, "ssl module required")
def test_url_path_with_newline_header_injection_rejected(self):
self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello.")
host = "localhost:7777?a=1 HTTP/1.1\r\nX-injected: he... |
def test_url_with_newline_header_injection_rejected(self):
finally:
self.unfakehttp()
def test_read_0_9(self):
# "0.9" response accepted (but not "simple responses" without
# a status line) | def test_url_with_newline_header_injection_rejected(self):
finally:
self.unfakehttp()
@unittest.skipUnless(ssl, "ssl module required")
def test_url_host_with_control_char_rejected(self):
for char_no in list(range(0, 0x21)) + [0x7f]:
char = chr(char_no)
scheme... |
class ObjectBlock(Block):
if convert:
block = [b.convert(numeric=False, copy=True) for b in block]
return block
return self
| class ObjectBlock(Block):
if convert:
block = [b.convert(numeric=False, copy=True) for b in block]
return block
if convert:
return [self.convert(numeric=False, copy=True)]
return self
|
class BlockManager(PandasObject):
convert=convert,
regex=regex,
)
if m.any():
new_rb = _extend_blocks(result, new_rb)
else:
new_rb.append(b) | class BlockManager(PandasObject):
convert=convert,
regex=regex,
)
if m.any() or convert:
new_rb = _extend_blocks(result, new_rb)
else:
new_rb.append(b) |
class TestDataFrameReplace:
expected = pd.DataFrame(exp)
result = df.replace(to_replace)
tm.assert_frame_equal(result, expected) | class TestDataFrameReplace:
expected = pd.DataFrame(exp)
result = df.replace(to_replace)
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
"replacer",
[
pd.Timestamp("20170827"),
np.int8(1),
np.int16(1),
np.flo... |
from parsel.selector import create_root_node
import six
from scrapy.http.request import Request
from scrapy.utils.python import to_bytes, is_listlike
class FormRequest(Request): | from parsel.selector import create_root_node
import six
from scrapy.http.request import Request
from scrapy.utils.python import to_bytes, is_listlike
from scrapy.utils.response import get_base_url
class FormRequest(Request): |
class FormRequest(Request):
def _get_form_url(form, url):
if url is None:
return form.action or form.base_url
return urljoin(form.base_url, url)
| class FormRequest(Request):
def _get_form_url(form, url):
if url is None:
return urljoin(form.base_url, form.action)
return urljoin(form.base_url, url)
|
def _urlencode(seq, enc):
def _get_form(response, formname, formid, formnumber, formxpath):
"""Find the form element """
text = response.body_as_unicode()
root = create_root_node(text, lxml.html.HTMLParser, base_url=response.url)
forms = root.xpath('//form')
if not forms:
raise ValueError("N... | def _urlencode(seq, enc):
def _get_form(response, formname, formid, formnumber, formxpath):
"""Find the form element """
text = response.body_as_unicode()
root = create_root_node(text, lxml.html.HTMLParser, base_url=get_base_url(response))
forms = root.xpath('//form')
if not forms:
raise Val... |
class FormRequestTest(RequestTest):
self.assertEqual(fs[b'test2'], [b'val2'])
self.assertEqual(fs[b'button1'], [b''])
def _buildresponse(body, **kwargs):
kwargs.setdefault('body', body)
kwargs.setdefault('url', 'http://example.com') | class FormRequestTest(RequestTest):
self.assertEqual(fs[b'test2'], [b'val2'])
self.assertEqual(fs[b'button1'], [b''])
def test_html_base_form_action(self):
response = _buildresponse(
"""
<html>
<head>
<base href="http://b.com/">
... |
class Storage:
content = File(content, name)
name = self.get_available_name(name, max_length=max_length)
return self._save(name, content)
# These methods are part of the public API, with default implementations.
| class Storage:
content = File(content, name)
name = self.get_available_name(name, max_length=max_length)
name = self._save(name, content)
# Ensure that the name returned from the storage system is still valid.
validate_file_name(name, allow_relative_path=True)
return... |
class Storage:
Return a filename that's free on the target storage system and
available for new content to be written to.
"""
dir_name, file_name = os.path.split(name)
if '..' in pathlib.PurePath(dir_name).parts:
raise SuspiciousFileOperation("Detected path traversal ... | class Storage:
Return a filename that's free on the target storage system and
available for new content to be written to.
"""
name = str(name).replace('\\', '/')
dir_name, file_name = os.path.split(name)
if '..' in pathlib.PurePath(dir_name).parts:
raise Suspi... |
class Storage:
Validate the filename by calling get_valid_name() and return a filename
to be passed to the save() method.
"""
# `filename` may include a path as returned by FileField.upload_to.
dirname, filename = os.path.split(filename)
if '..' in pathlib.PurePath(dirnam... | class Storage:
Validate the filename by calling get_valid_name() and return a filename
to be passed to the save() method.
"""
filename = str(filename).replace('\\', '/')
# `filename` may include a path as returned by FileField.upload_to.
dirname, filename = os.path.split(... |
class FileSystemStorage(Storage):
if self.file_permissions_mode is not None:
os.chmod(full_path, self.file_permissions_mode)
# Store filenames with forward slashes, even on Windows.
return name.replace('\\', '/')
| class FileSystemStorage(Storage):
if self.file_permissions_mode is not None:
os.chmod(full_path, self.file_permissions_mode)
# Ensure the saved path is always relative to the storage root.
name = os.path.relpath(full_path, self.location)
# Store filenames with forward slashe... |
class GenerateFilenameStorageTests(SimpleTestCase):
s.generate_filename(file_name)
def test_storage_dangerous_paths_dir_name(self):
file_name = '/tmp/../path'
s = FileSystemStorage()
msg = "Detected path traversal attempt in '/tmp/..'"
with self.assertRaisesMessa... | class GenerateFilenameStorageTests(SimpleTestCase):
s.generate_filename(file_name)
def test_storage_dangerous_paths_dir_name(self):
candidates = [
('tmp/../path', 'tmp/..'),
('tmp\\..\\path', 'tmp/..'),
('/tmp/../path', '/tmp/..'),
('\\tmp... |
class FileStorageTests(SimpleTestCase):
self.storage.delete('path/to/test.file')
def test_save_doesnt_close(self):
with TemporaryUploadedFile('test', 'text/plain', 1, 'utf8') as file:
file.write(b'1') | class FileStorageTests(SimpleTestCase):
self.storage.delete('path/to/test.file')
def test_file_save_abs_path(self):
test_name = 'path/to/test.file'
f = ContentFile('file saved with path')
f_name = self.storage.save(os.path.join(self.temp_dir, test_name), f)
self.assertEqual... |
class HTTPRequest(HTTPMessage):
)
headers = dict(self._orig.headers)
if 'Host' not in headers:
headers['Host'] = url.netloc.split('@')[-1]
headers = ['%s: %s' % (name, value) | class HTTPRequest(HTTPMessage):
)
headers = dict(self._orig.headers)
if 'Host' not in self._orig.headers:
headers['Host'] = url.netloc.split('@')[-1]
headers = ['%s: %s' % (name, value) |
class MetricsHandler(tornado.web.RequestHandler):
self._scheduler = scheduler
def get(self):
metrics = self._scheduler._state._metrics_collector.generate_latest()
if metrics:
metrics.configure_http_handler(self)
self.write(metrics)
| class MetricsHandler(tornado.web.RequestHandler):
self._scheduler = scheduler
def get(self):
metrics_collector = self._scheduler._state._metrics_collector
metrics = metrics_collector.generate_latest()
if metrics:
metrics_collector.configure_http_handler(self)
... |
class MetricsHandlerTest(unittest.TestCase):
with mock.patch.object(self.handler, 'write') as patched_write:
self.handler.get()
patched_write.assert_called_once_with(mock_metrics)
mock_metrics.configure_http_handler.assert_called_once_with(self.handler)
def test_get_no_m... | class MetricsHandlerTest(unittest.TestCase):
with mock.patch.object(self.handler, 'write') as patched_write:
self.handler.get()
patched_write.assert_called_once_with(mock_metrics)
self.mock_scheduler._state._metrics_collector.configure_http_handler.assert_called_once_with(
... |
class ArchRunner(Runner):
elif abs(now - mktime_tz(tup)) > \
mm_cfg.ARCHIVER_ALLOWABLE_SANE_DATE_SKEW:
clobber = 1
except ValueError:
# The likely cause of this is that the year in the Date: field
# is horribly inco... | class ArchRunner(Runner):
elif abs(now - mktime_tz(tup)) > \
mm_cfg.ARCHIVER_ALLOWABLE_SANE_DATE_SKEW:
clobber = 1
except (ValueError, OverflowError):
# The likely cause of this is that the year in the Date: field
#... |
def logical_volume_info(path):
return dict(zip(*info))
def remove_logical_volumes(*paths):
"""Remove one or more logical volume."""
if paths:
lvremove = ('lvremove', '-f') + paths
execute(*lvremove, attempts=3, run_as_root=True) | def logical_volume_info(path):
return dict(zip(*info))
def logical_volume_size(path):
"""Get logical volume size in bytes.
:param path: logical volume path
"""
# TODO(p-draigbrady) POssibly replace with the more general
# use of blockdev --getsize64 in future
out, _err = execute('lvs', '-... |
logger = logging.getLogger(__name__)
title_regex = re.compile(r"(?<=<title>).*(?=</title>)")
id_regex = re.compile(r"(?<=<id>)\d*(?=</id>)")
text_regex = re.compile(r"(?<=<text xml:space=\"preserve\">).*(?=</text)")
info_regex = re.compile(r"{[^{]*?}")
html_regex = re.compile(r"<!--[^-]*-->")
ref_regex = re.comp... | logger = logging.getLogger(__name__)
title_regex = re.compile(r"(?<=<title>).*(?=</title>)")
id_regex = re.compile(r"(?<=<id>)\d*(?=</id>)")
text_tag_regex = re.compile(r"(?<=<text).*?(?=>)")
text_regex = re.compile(r"(?<=<text>).*(?=</text)")
info_regex = re.compile(r"{[^{]*?}")
html_regex = re.compile(r"<!--[^-]*... |
def _process_wp_text(article_title, article_text, wp_to_id):
return None, None
# remove the text tags
text_search = text_regex.search(article_text)
if text_search is None:
return None, None
text = text_search.group(0) | def _process_wp_text(article_title, article_text, wp_to_id):
return None, None
# remove the text tags
text_search = text_tag_regex.sub("", article_text)
text_search = text_regex.search(text_search)
if text_search is None:
return None, None
text = text_search.group(0) |
class Function(object):
# (since the outputs of fetches are never returned).
# This requires us to wrap fetches in `identity` ops.
self.fetches = [tf.identity(x) for x in self.fetches]
self.session_kwargs = session_kwargs
if session_kwargs:
raise ValueError('Some keys... | class Function(object):
# (since the outputs of fetches are never returned).
# This requires us to wrap fetches in `identity` ops.
self.fetches = [tf.identity(x) for x in self.fetches]
# self.session_kwargs is used for _legacy_call
self.session_kwargs = session_kwargs.copy()
... |
class Function(object):
callable_opts.fetch.append(x.name)
# Handle updates.
callable_opts.target.append(self.updates_op.name)
# Create callable.
callable_fn = session._make_callable_from_options(callable_opts)
# Cache parameters corresponding to the generated callabl... | class Function(object):
callable_opts.fetch.append(x.name)
# Handle updates.
callable_opts.target.append(self.updates_op.name)
# Handle run_options.
if self.run_options:
callable_opts.run_options.CopyFrom(self.run_options)
# Create callable.
callab... |
class Function(object):
feed_symbols,
symbol_vals,
session)
fetched = self._callable_fn(*array_vals)
return fetched[:len(self.outputs)]
def _legacy_call(self, inputs): | class Function(object):
feed_symbols,
symbol_vals,
session)
if self.run_metadata:
fetched = self._callable_fn(*array_vals, run_metadata=self.run_metadata)
else:
fetched = self._callabl... |
class Function(object):
'supported with sparse inputs.')
return self._legacy_call(inputs)
return self._call(inputs)
else:
if py_any(is_tensor(x) for x in inputs): | class Function(object):
'supported with sparse inputs.')
return self._legacy_call(inputs)
# callable generated by Session._make_callable_from_options accepts
# `run_metadata` keyword argument since TF 1.10
if (self.run_metadata and
... |
class TestBackend(object):
assert output == [21.]
assert K.get_session().run(fetches=[x, y]) == [30., 40.]
@pytest.mark.skipif(K.backend() != 'tensorflow',
reason='Uses the `string` type for a tensor.')
def test_function_tf_string_input(self): | class TestBackend(object):
assert output == [21.]
assert K.get_session().run(fetches=[x, y]) == [30., 40.]
@pytest.mark.skipif(K.backend() != 'tensorflow',
reason='Uses the `options` and `run_metadata` arguments.')
def test_function_tf_run_options_with_run_metadata(self)... |
Make api awesomeness
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import inspect
import os
# Import Salt libs
import salt.log # pylint: disable=W0611
import salt.client
import salt.config
import salt.runner
import salt.syspaths
import salt.wheel
import salt.utils.a... | Make api awesomeness
'''
from __future__ import absolute_import, print_function, unicode_literals
import copy
# Import Python libs
import inspect
import logging
import os
# Import Salt libs
import salt.log # pylint: disable=W0611
import salt.auth
import salt.client
import salt.config
import salt.daemons.masterapi
i... |
class NetapiClient(object):
def __init__(self, opts):
self.opts = opts
def _is_master_running(self):
''' | class NetapiClient(object):
def __init__(self, opts):
self.opts = opts
self.loadauth = salt.auth.LoadAuth(opts)
self.key = salt.daemons.masterapi.access_keys(self.opts)
minopts = copy.deepcopy(self.opts)
minopts["enable_ssh_minions"] = True
self.ckminions = salt.util... |
class NetapiClient(object):
self.opts['sock_dir'],
ipc_file))
def run(self, low):
'''
Execute the specified function in the specified client by passing the | class NetapiClient(object):
self.opts['sock_dir'],
ipc_file))
def _prep_auth_info(self, clear_load):
sensitive_load_keys = []
key = None
if "token" in clear_load:
auth_type = "token"
err_name = "TokenAuthenticationError"
sensitive_... |
class NetapiClient(object):
raise salt.exceptions.EauthAuthenticationError(
'Raw shell option not allowed.')
l_fun = getattr(self, low['client'])
f_call = salt.utils.args.format_call(l_fun, low)
return l_fun(*f_call.get('args', ()), **f_call.get('kwargs', {})) | class NetapiClient(object):
raise salt.exceptions.EauthAuthenticationError(
'Raw shell option not allowed.')
if low['client'] == 'ssh':
self._authorize_ssh(low)
l_fun = getattr(self, low['client'])
f_call = salt.utils.args.format_call(l_fun, low)
... |
# encoding: utf-8
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import time
# Import Salt Testing libs
from tests.support.paths import TMP_CONF_DIR, TMP
from tests.support.runtests import RUNTIME_VARS
from tests.support.unit import TestCase, ski... | # encoding: utf-8
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import os
import time
import salt.config
import salt.netapi
import salt.utils.files
import salt.utils.platform
import salt.utils.pycrypto
# Import Salt Testing libs
from tests.sup... |
class NetapiSSHClientTest(SSHCase):
'''
opts = salt.config.client_config(os.path.join(TMP_CONF_DIR, 'master'))
self.netapi = salt.netapi.NetapiClient(opts)
self.priv_file = os.path.join(RUNTIME_VARS.TMP_CONF_DIR, 'key_test')
self.rosters = os.path.join(RUNTIME_VARS.TMP_CONF_DIR) | class NetapiSSHClientTest(SSHCase):
'''
opts = salt.config.client_config(os.path.join(TMP_CONF_DIR, 'master'))
self.netapi = salt.netapi.NetapiClient(opts)
opts = salt.config.client_config(os.path.join(TMP_CONF_DIR, "master"))
naopts = copy.deepcopy(opts)
naopts["ignore_h... |
class NetapiSSHClientTest(SSHCase):
"roster": "cache",
"client": "ssh",
"tgt": "www.zerodayinitiative.com",
"fun": "xx",
"eauth": "xx",
"ssh_priv": "aaa|id>{} #".format(path),
}
ret = self.netapi.run(low)
self.assertFalse(os... | class NetapiSSHClientTest(SSHCase):
"roster": "cache",
"client": "ssh",
"tgt": "www.zerodayinitiative.com",
"ssh_priv": "aaa|id>{} #".format(path),
"fun": "test.ping",
"eauth": "auto",
"username": "saltdev_auto",
"password":... |
class NetapiSSHClientTest(SSHCase):
"roster": "cache",
"client": "ssh",
"tgt": "root|id>{} #@127.0.0.1".format(path),
"fun": "xx",
"eauth": "xx",
"roster_file": "/tmp/salt-tests-tmpdir/config/roaster",
"rosters": "/",
}
... | class NetapiSSHClientTest(SSHCase):
"roster": "cache",
"client": "ssh",
"tgt": "root|id>{} #@127.0.0.1".format(path),
"roster_file": "/tmp/salt-tests-tmpdir/config/roaster",
"rosters": "/",
"fun": "test.ping",
"eauth": "auto",
... |
class NetapiSSHClientTest(SSHCase):
"client": "ssh",
"tgt": "127.0.0.1",
"renderer": "cheetah",
"fun": "xx",
"eauth": "xx",
"roster_file": "/tmp/salt-tests-tmpdir/config/roaster",
"rosters": "/",
"ssh_options": ["|id>{} #".f... | class NetapiSSHClientTest(SSHCase):
"client": "ssh",
"tgt": "127.0.0.1",
"renderer": "cheetah",
"fun": "test.ping",
"eauth": "auto",
"username": "saltdev_auto",
"password": "saltdev",
"roster_file": "/tmp/salt-tests-tmpdir/c... |
class NetapiSSHClientTest(SSHCase):
"client": "ssh",
"tgt": "127.0.0.1",
"renderer": "cheetah",
"fun": "xx",
"eauth": "xx",
"roster_file": "/tmp/salt-tests-tmpdir/config/roaster",
"rosters": "/",
"ssh_port": "hhhhh|id>{} #".... | class NetapiSSHClientTest(SSHCase):
"client": "ssh",
"tgt": "127.0.0.1",
"renderer": "cheetah",
"fun": "test.ping",
"eauth": "auto",
"username": "saltdev_auto",
"password": "saltdev",
"roster_file": "/tmp/salt-tests-tmpdir/c... |
class NetapiSSHClientTest(SSHCase):
"client": "ssh",
"tgt": "127.0.0.1",
"renderer": "cheetah",
"fun": "xx",
"eauth": "xx",
"roster_file": "/tmp/salt-tests-tmpdir/config/roaster",
"rosters": "/",
"ssh_remote_port_forwards": ... | class NetapiSSHClientTest(SSHCase):
"client": "ssh",
"tgt": "127.0.0.1",
"renderer": "cheetah",
"fun": "test.ping",
"roster_file": "/tmp/salt-tests-tmpdir/config/roaster",
"rosters": "/",
"ssh_remote_port_forwards": "hhhhh|id>{} #, lol"... |
class Grouping:
self._group_index = CategoricalIndex(
Categorical.from_codes(
codes=codes, categories=categories, ordered=self.grouper.ordered
)
)
# we are done | class Grouping:
self._group_index = CategoricalIndex(
Categorical.from_codes(
codes=codes, categories=categories, ordered=self.grouper.ordered
),
name=self.name,
)
# we are done |
def test_preserve_categories():
# ordered=True
df = DataFrame({"A": Categorical(list("ba"), categories=categories, ordered=True)})
index = CategoricalIndex(categories, categories, ordered=True)
tm.assert_index_equal(
df.groupby("A", sort=True, observed=False).first().index, index
) | def test_preserve_categories():
# ordered=True
df = DataFrame({"A": Categorical(list("ba"), categories=categories, ordered=True)})
index = CategoricalIndex(categories, categories, ordered=True, name="A")
tm.assert_index_equal(
df.groupby("A", sort=True, observed=False).first().index, index
... |
def test_preserve_categories():
# ordered=False
df = DataFrame({"A": Categorical(list("ba"), categories=categories, ordered=False)})
sort_index = CategoricalIndex(categories, categories, ordered=False)
nosort_index = CategoricalIndex(list("bac"), list("bac"), ordered=False)
tm.assert_index_equal(
... | def test_preserve_categories():
# ordered=False
df = DataFrame({"A": Categorical(list("ba"), categories=categories, ordered=False)})
sort_index = CategoricalIndex(categories, categories, ordered=False, name="A")
nosort_index = CategoricalIndex(list("bac"), list("bac"), ordered=False, name="A")
tm.a... |
def test_groupby_categorical_axis_1(code):
result = df.groupby(cat, axis=1).mean()
expected = df.T.groupby(cat, axis=0).mean().T
assert_frame_equal(result, expected) | def test_groupby_categorical_axis_1(code):
result = df.groupby(cat, axis=1).mean()
expected = df.T.groupby(cat, axis=0).mean().T
assert_frame_equal(result, expected)
def test_groupby_cat_preserves_structure(observed):
# GH 28787
df = DataFrame([("Bob", 1), ("Greg", 2)], columns=["Name", "Item"])
... |
import pandas.core.indexes.base as ibase
from pandas.core.indexes.base import Index, _index_shared_docs, maybe_extract_name
from pandas.core.indexes.extension import ExtensionIndex, inherit_names
import pandas.core.missing as missing
_index_doc_kwargs = dict(ibase._index_doc_kwargs)
_index_doc_kwargs.update(dict(targe... | import pandas.core.indexes.base as ibase
from pandas.core.indexes.base import Index, _index_shared_docs, maybe_extract_name
from pandas.core.indexes.extension import ExtensionIndex, inherit_names
import pandas.core.missing as missing
from pandas.core.ops import get_op_result_name
_index_doc_kwargs = dict(ibase._index_... |
class CategoricalIndex(ExtensionIndex, accessor.PandasDelegate):
return res
return CategoricalIndex(res, name=self.name)
CategoricalIndex._add_numeric_methods_add_sub_disabled()
CategoricalIndex._add_numeric_methods_disabled() | class CategoricalIndex(ExtensionIndex, accessor.PandasDelegate):
return res
return CategoricalIndex(res, name=self.name)
def _wrap_joined_index(
self, joined: np.ndarray, other: "CategoricalIndex"
) -> "CategoricalIndex":
name = get_op_result_name(self, other)
return... |
def test_merge_datetime_upcast_dtype():
}
)
tm.assert_frame_equal(result, expected) | def test_merge_datetime_upcast_dtype():
}
)
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("n_categories", [5, 128])
def test_categorical_non_unique_monotonic(n_categories):
# GH 28189
# With n_categories as 5, we test the int8 case is hit in libjoin,
# with n_categories ... |
setup(
python_requires="~=3.6",
install_requires=[
"urwid>=1.1.1",
"pygments>=1.0",
"jedi>=0.18,<1"
],
test_requires=[ | setup(
python_requires="~=3.6",
install_requires=[
"urwid>=1.1.1",
"pygments>=2.7.4",
"jedi>=0.18,<1"
],
test_requires=[ |
# Imports
#-----------------------------------------------------------------------------
try:
from http.cookies import SimpleCookie # Py 3
except ImportError: | # Imports
#-----------------------------------------------------------------------------
try:
from urllib.parse import urlparse # Py 3
except ImportError:
from urlparse import urlparse # Py 2
try:
from http.cookies import SimpleCookie # Py 3
except ImportError: |
#-----------------------------------------------------------------------------
class ZMQStreamHandler(websocket.WebSocketHandler):
def clear_cookie(self, *args, **kwargs):
"""meaningless for websockets"""
pass | #-----------------------------------------------------------------------------
class ZMQStreamHandler(websocket.WebSocketHandler):
def same_origin(self):
"""Check to see that origin and host match in the headers."""
# The difference between version 8 and 13 is that in 8 the
# client sends... |
def allow_draft76(self):
class AuthenticatedZMQStreamHandler(ZMQStreamHandler, IPythonHandler):
def open(self, kernel_id):
self.kernel_id = cast_unicode(kernel_id, 'ascii')
self.session = Session(config=self.config)
self.save_on_message = self.on_message | def allow_draft76(self):
class AuthenticatedZMQStreamHandler(ZMQStreamHandler, IPythonHandler):
def open(self, kernel_id):
# Check to see that origin matches host directly, including ports
if not self.same_origin():
self.log.warn("Cross Origin WebSocket Attempt.")
raise web.... |
def on_first_message(self, msg):
if self.get_current_user() is None:
self.log.warn("Couldn't authenticate WebSocket connection")
raise web.HTTPError(403)
self.on_message = self.save_on_message | def on_first_message(self, msg):
if self.get_current_user() is None:
self.log.warn("Couldn't authenticate WebSocket connection")
raise web.HTTPError(403)
self.on_message = self.save_on_message |
class inherits(object):
self.task_to_inherit = task_to_inherit
def __call__(self, task_that_inherits):
for param_name, param_obj in self.task_to_inherit.get_params():
if not hasattr(task_that_inherits, param_name):
setattr(task_that_inherits, param_name, param_obj)
... | class inherits(object):
self.task_to_inherit = task_to_inherit
def __call__(self, task_that_inherits):
# Get all parameter objects from the underlying task
for param_name, param_obj in self.task_to_inherit.get_params():
# Check if the parameter exists in the inheriting task
... |
class requires(object):
def __call__(self, task_that_requires):
task_that_requires = self.inherit_decorator(task_that_requires)
# Modify task_that_requres by subclassing it and adding methods
@task._task_wraps(task_that_requires)
class Wrapped(task_that_requires):
def r... | class requires(object):
def __call__(self, task_that_requires):
task_that_requires = self.inherit_decorator(task_that_requires)
# Modify task_that_requres by adding methods
def requires(_self):
return _self.clone_parent()
task_that_requires.requires = requires
r... |
from helpers import LuigiTestCase, RunOnceTask
import luigi
import luigi.task
from luigi.util import requires
class BasicsTest(LuigiTestCase):
def test_task_ids_using_requries(self):
class ParentTask(luigi.Task):
my_param = luigi.Parameter() | from helpers import LuigiTestCase, RunOnceTask
import luigi
import luigi.task
from luigi.util import inherits, requires
class BasicsTest(LuigiTestCase):
# following tests using inherits decorator
def test_task_ids_using_inherits(self):
class ParentTask(luigi.Task):
my_param = luigi.Parame... |
class BasicsTest(LuigiTestCase):
ParentTask = self._setup_parent_and_child()
self.assertTrue(self.run_locally_split('ParentTask --my-parameter actuallyset'))
self.assertEqual(ParentTask.class_variable, 'actuallyset') | class BasicsTest(LuigiTestCase):
ParentTask = self._setup_parent_and_child()
self.assertTrue(self.run_locally_split('ParentTask --my-parameter actuallyset'))
self.assertEqual(ParentTask.class_variable, 'actuallyset')
def _setup_requires_inheritence(self):
class RequiredTask(luigi.Ta... |
class BaseMaskedArray(ExtensionArray, ExtensionOpsMixin):
def __len__(self) -> int:
return len(self._data)
def to_numpy(
self, dtype=None, copy=False, na_value: "Scalar" = lib.no_default,
): | class BaseMaskedArray(ExtensionArray, ExtensionOpsMixin):
def __len__(self) -> int:
return len(self._data)
def __invert__(self):
return type(self)(~self._data, self._mask)
def to_numpy(
self, dtype=None, copy=False, na_value: "Scalar" = lib.no_default,
): |
class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin):
# inv fails with 0 len
return self
arr = operator.inv(com.values_from_object(self))
return self.__array_wrap__(arr)
def __nonzero__(self):
raise ValueError( | class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin):
# inv fails with 0 len
return self
new_data = self._data.apply(operator.invert)
result = self._constructor(new_data).__finalize__(self)
return result
def __nonzero__(self):
raise ValueError... |
def check_bool_indexer(index: Index, key) -> np.ndarray:
result = result.astype(bool)._values
else:
if is_sparse(result):
result = result.to_dense()
result = check_bool_array_indexer(index, result)
return result | def check_bool_indexer(index: Index, key) -> np.ndarray:
result = result.astype(bool)._values
else:
if is_sparse(result):
result = np.asarray(result)
result = check_bool_array_indexer(index, result)
return result |
def test_invert(fill_value):
expected = SparseArray(~arr, fill_value=not fill_value)
tm.assert_sp_array_equal(result, expected)
@pytest.mark.parametrize("fill_value", [0, np.nan])
@pytest.mark.parametrize("op", [operator.pos, operator.neg]) | def test_invert(fill_value):
expected = SparseArray(~arr, fill_value=not fill_value)
tm.assert_sp_array_equal(result, expected)
result = ~pd.Series(sparray)
expected = pd.Series(expected)
tm.assert_series_equal(result, expected)
result = ~pd.DataFrame({"A": sparray})
expected = pd.DataFram... |
def test_ufunc_reduce_raises(values):
np.add.reduce(a)
class TestLogicalOps(BaseOpsUtil):
def test_numpy_scalars_ok(self, all_logical_operators):
a = pd.array([True, False, None], dtype="boolean") | def test_ufunc_reduce_raises(values):
np.add.reduce(a)
class TestUnaryOps:
def test_invert(self):
a = pd.array([True, False, None], dtype="boolean")
expected = pd.array([False, True, None], dtype="boolean")
tm.assert_extension_array_equal(~a, expected)
expected = pd.Series... |
from .interface import BaseInterfaceTests # noqa
from .io import BaseParsingTests # noqa
from .methods import BaseMethodsTests # noqa
from .missing import BaseMissingTests # noqa
from .ops import BaseArithmeticOpsTests, BaseComparisonOpsTests, BaseOpsUtil # noqa
from .printing import BasePrintingTests # noqa
from... | from .interface import BaseInterfaceTests # noqa
from .io import BaseParsingTests # noqa
from .methods import BaseMethodsTests # noqa
from .missing import BaseMissingTests # noqa
from .ops import ( # noqa
BaseArithmeticOpsTests,
BaseComparisonOpsTests,
BaseOpsUtil,
BaseUnaryOpsTests,
)
from .printi... |
class BaseComparisonOpsTests(BaseOpsUtil):
assert result is NotImplemented
else:
raise pytest.skip(f"{type(data).__name__} does not implement __eq__") | class BaseComparisonOpsTests(BaseOpsUtil):
assert result is NotImplemented
else:
raise pytest.skip(f"{type(data).__name__} does not implement __eq__")
class BaseUnaryOpsTests(BaseOpsUtil):
def test_invert(self, data):
s = pd.Series(data, name="name")
result = ~s
... |
class TestPrinting(base.BasePrintingTests):
pass
# TODO parsing not yet supported
# class TestParsing(base.BaseParsingTests):
# pass | class TestPrinting(base.BasePrintingTests):
pass
class TestUnaryOps(base.BaseUnaryOpsTests):
pass
# TODO parsing not yet supported
# class TestParsing(base.BaseParsingTests):
# pass |
class TestDataFrameUnaryOperators:
tm.assert_frame_equal(-(df < 0), ~(df < 0))
@pytest.mark.parametrize(
"df",
[ | class TestDataFrameUnaryOperators:
tm.assert_frame_equal(-(df < 0), ~(df < 0))
def test_invert_mixed(self):
shape = (10, 5)
df = pd.concat(
[
pd.DataFrame(np.zeros(shape, dtype="bool")),
pd.DataFrame(np.zeros(shape, dtype=int)),
],
... |
def test_partial(self):
)
def test_errors(self):
self.assertRaises(UnicodeDecodeError, codecs.utf_16_le_decode,
b"\xff", "strict", True)
def test_nonbmp(self):
self.assertEqual("\U00010203".encode(self.encoding), | def test_partial(self):
)
def test_errors(self):
tests = [
(b'\xff', '\ufffd'),
(b'A\x00Z', 'A\ufffd'),
(b'A\x00B\x00C\x00D\x00Z', 'ABCD\ufffd'),
(b'\x00\xd8', '\ufffd'),
(b'\x00\xd8A', '\ufffd'),
(b'\x00\xd8A\x00', '\ufffdA'),... |
def test_partial(self):
)
def test_errors(self):
self.assertRaises(UnicodeDecodeError, codecs.utf_16_be_decode,
b"\xff", "strict", True)
def test_nonbmp(self):
self.assertEqual("\U00010203".encode(self.encoding), | def test_partial(self):
)
def test_errors(self):
tests = [
(b'\xff', '\ufffd'),
(b'\x00A\xff', 'A\ufffd'),
(b'\x00A\x00B\x00C\x00DZ', 'ABCD\ufffd'),
(b'\xd8\x00', '\ufffd'),
(b'\xd8\x00\xdc', '\ufffd'),
(b'\xd8\x00\x00A', '\uff... |
def localpkgs(directory):
cache[name] = {'path': fn, 'size': st.st_size, 'device': st.st_dev}
return cache
def parseArgs():
usage = _("""
Reposync is used to synchronize a remote yum repository to a local | def localpkgs(directory):
cache[name] = {'path': fn, 'size': st.st_size, 'device': st.st_dev}
return cache
def is_subpath(path, root):
root = os.path.realpath(root)
path = os.path.realpath(os.path.join(root, path))
# join() is used below to ensure root ends with a slash
return path.star... |
def parseArgs():
parser.add_option("", "--download-metadata", dest="downloadmd",
default=False, action="store_true",
help=_("download all the non-default metadata"))
(opts, args) = parser.parse_args()
return (opts, args)
| def parseArgs():
parser.add_option("", "--download-metadata", dest="downloadmd",
default=False, action="store_true",
help=_("download all the non-default metadata"))
parser.add_option("", "--allow-path-traversal", default=False,
action="store_true",
help=_("Allow packages stored ... |
def main():
else:
local_repo_path = opts.destdir + '/' + repo.id
if opts.delete and os.path.exists(local_repo_path):
current_pkgs = localpkgs(local_repo_path)
download_set = {}
for pkg in download_list:
remote = pkg.returnSimple('relative... | def main():
else:
local_repo_path = opts.destdir + '/' + repo.id
# Ensure we don't traverse out of local_repo_path by dropping any
# packages whose remote_path is absolute or contains up-level
# references (unless explicitly allowed).
# See RHBZ#1600221 for details.
... |
def main():
remote_size = 0
if not opts.urls:
for pkg in download_list:
remote = pkg.returnSimple('relativepath')
local = local_repo_path + '/' + remote
sz = int(pkg.returnSimple('packagesize'))
if os.path.exists(local) and os.p... | def main():
remote_size = 0
if not opts.urls:
for pkg in download_list:
local = os.path.join(local_repo_path, pkg.remote_path)
sz = int(pkg.returnSimple('packagesize'))
if os.path.exists(local) and os.path.getsize(local) == sz:
... |
def main():
download_list.sort(key=lambda pkg: pkg.name)
if opts.urls:
for pkg in download_list:
remote = pkg.returnSimple('relativepath')
local = os.path.join(local_repo_path, remote)
if not (os.path.exists(local) and my.verifyPkg(local, pkg, ... | def main():
download_list.sort(key=lambda pkg: pkg.name)
if opts.urls:
for pkg in download_list:
local = os.path.join(local_repo_path, pkg.remote_path)
if not (os.path.exists(local) and my.verifyPkg(local, pkg, False)):
print urljoin(pkg.re... |
def main():
# set localpaths
for pkg in download_list:
rpmfn = pkg.remote_path
pkg.localpath = os.path.join(local_repo_path, rpmfn)
pkg.repo.copy_local = True
pkg.repo.cache = 0
localdir = os.path.dirname(pkg.localpath) | def main():
# set localpaths
for pkg in download_list:
pkg.localpath = os.path.join(local_repo_path, pkg.remote_path)
pkg.repo.copy_local = True
pkg.repo.cache = 0
localdir = os.path.dirname(pkg.localpath) |
def do_setup():
'gunicorn>=19.5.0, <20.0',
'iso8601>=0.1.12',
'json-merge-patch==0.2',
'jinja2>=2.7.3, <=2.10.0',
'lxml>=4.0.0',
'markdown>=2.5.2, <3.0',
'pandas>=0.17.1, <1.0.0',
'pendulum==1.4.4', | def do_setup():
'gunicorn>=19.5.0, <20.0',
'iso8601>=0.1.12',
'json-merge-patch==0.2',
'jinja2>=2.10.1, <2.11.0',
'markdown>=2.5.2, <3.0',
'pandas>=0.17.1, <1.0.0',
'pendulum==1.4.4', |
def in_top_k(predictions, targets, k):
def conv2d_transpose(x, kernel, output_shape, strides=(1, 1),
padding='valid', data_format=None):
data_format = normalize_data_format(data_format)
x = _preprocess_conv2d_input(x, data_format) | def in_top_k(predictions, targets, k):
def conv2d_transpose(x, kernel, output_shape, strides=(1, 1),
padding='valid', data_format=None, dilation_rate=(1, 1)):
data_format = normalize_data_format(data_format)
x = _preprocess_conv2d_input(x, data_format) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.