buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
def test_digest_next_nonce_nc():
password = tests.gen_password()
grenew_nonce = [None]
handler = tests.http_reflect_with_auth(
allow_scheme="digest",
allow_credentials=(("joe", password),),
out_renew_nonce=grenew_nonce,
)
with tests.server_request(handler, request_count=5) as... | def test_digest_next_nonce_nc():
password = tests.gen_password()
grenew_nonce = [None]
handler = tests.http_reflect_with_auth(
allow_scheme="digest", allow_credentials=(("joe", password),), out_renew_nonce=grenew_nonce,
)
with tests.server_request(handler, request_count=5) as uri:
ht... |
def test_digest_auth_stale():
http.add_credentials("joe", password)
response, _ = http.request(uri, "GET")
assert response.status == 200
info = httplib2._parse_www_authenticate(
requests[0][1].headers, "www-authenticate"
)
grenew_nonce[0]()
response, _... | def test_digest_auth_stale():
http.add_credentials("joe", password)
response, _ = http.request(uri, "GET")
assert response.status == 200
info = httplib2.auth._parse_www_authenticate(requests[0][1].headers, "www-authenticate")
grenew_nonce[0]()
response, _ = http.request(u... |
def test_digest_auth_stale():
({}, {}),
({"www-authenticate": ""}, {}),
(
{
"www-authenticate": 'Test realm="test realm" , foo=foo ,bar="bar", baz=baz,qux=qux'
},
{
"test": {
"realm": "test realm",
... | def test_digest_auth_stale():
({}, {}),
({"www-authenticate": ""}, {}),
(
{"www-authenticate": 'Test realm="test realm" , foo=foo ,bar="bar", baz=baz,qux=qux'},
{"test": {"realm": "test realm", "foo": "foo", "bar": "bar", "baz": "baz", "qux": "qux"}},
),
(... |
def test_digest_auth_stale():
# 'wsse': {'realm': 'very', 'profile': 'UsernameToken'}}),
# more quote combos
(
{
"www-authenticate": 'Digest realm="myrealm", nonce="KBAA=3", algorithm=MD5, qop="auth", stale=true'
},
{
"digest"... | def test_digest_auth_stale():
# 'wsse': {'realm': 'very', 'profile': 'UsernameToken'}}),
# more quote combos
(
{"www-authenticate": 'Digest realm="myrealm", nonce="KBAA=3", algorithm=MD5, qop="auth", stale=true'},
{"digest": {"realm": "myrealm", "nonce": "KBAA=3", "algo... |
def test_parse_www_authenticate_correct(data, strict):
# FIXME: move strict to parse argument
httplib2.USE_WWW_AUTH_STRICT_PARSING = strict
try:
assert httplib2._parse_www_authenticate(headers) == info
finally:
httplib2.USE_WWW_AUTH_STRICT_PARSING = 0
def test_parse_www_authenticate_ma... | def test_parse_www_authenticate_correct(data, strict):
# FIXME: move strict to parse argument
httplib2.USE_WWW_AUTH_STRICT_PARSING = strict
try:
assert httplib2.auth._parse_www_authenticate(headers) == info
finally:
httplib2.USE_WWW_AUTH_STRICT_PARSING = 0
@pytest.mark.parametrize(
... |
def test_digest_object():
host = None
request_uri = "/test/digest/"
headers = {}
response = {
"www-authenticate": 'Digest realm="myrealm", nonce="KBAA=35", algorithm=MD5, qop="auth"'
}
content = b""
d = httplib2.DigestAuthentication(
credentials, host, request_uri, headers, ... | def test_digest_object():
host = None
request_uri = "/test/digest/"
headers = {}
response = {"www-authenticate": 'Digest realm="myrealm", nonce="KBAA=35", algorithm=MD5, qop="auth"'}
content = b""
d = httplib2.DigestAuthentication(credentials, host, request_uri, headers, response, content, None... |
def test_digest_object_with_opaque():
request_uri = "/digest/opaque/"
headers = {}
response = {
"www-authenticate": 'Digest realm="myrealm", nonce="30352fd", algorithm=MD5, '
'qop="auth", opaque="atestopaque"'
}
content = ""
d = httplib2.DigestAuthentication(
credentials... | def test_digest_object_with_opaque():
request_uri = "/digest/opaque/"
headers = {}
response = {
"www-authenticate": 'Digest realm="myrealm", nonce="30352fd", algorithm=MD5, ' 'qop="auth", opaque="atestopaque"'
}
content = ""
d = httplib2.DigestAuthentication(credentials, host, request_u... |
def test_digest_object_stale():
request_uri = "/digest/stale/"
headers = {}
response = httplib2.Response({})
response["www-authenticate"] = (
'Digest realm="myrealm", nonce="bd669f", '
'algorithm=MD5, qop="auth", stale=true'
)
response.status = 401
content = b""
d = httpl... | def test_digest_object_stale():
request_uri = "/digest/stale/"
headers = {}
response = httplib2.Response({})
response["www-authenticate"] = 'Digest realm="myrealm", nonce="bd669f", ' 'algorithm=MD5, qop="auth", stale=true'
response.status = 401
content = b""
d = httplib2.DigestAuthentication... |
def test_digest_object_auth_info():
request_uri = "/digest/nextnonce/"
headers = {}
response = httplib2.Response({})
response["www-authenticate"] = (
'Digest realm="myrealm", nonce="barney", '
'algorithm=MD5, qop="auth", stale=true'
)
response["authentication-info"] = 'nextnonce=... | def test_digest_object_auth_info():
request_uri = "/digest/nextnonce/"
headers = {}
response = httplib2.Response({})
response["www-authenticate"] = 'Digest realm="myrealm", nonce="barney", ' 'algorithm=MD5, qop="auth", stale=true'
response["authentication-info"] = 'nextnonce="fred"'
content = b"... |
import sys
# Import 3rd-party libs
import jinja2
import jinja2.ext
from salt.ext import six
if sys.version_info[:2] >= (3, 5): | import sys
# Import 3rd-party libs
import jinja2
import jinja2.ext
import jinja2.sandbox
from salt.ext import six
if sys.version_info[:2] >= (3, 5): |
def render_jinja_tmpl(tmplstr, context, tmplpath=None):
opt_jinja_env_helper(opt_jinja_env, 'jinja_env')
if opts.get('allow_undefined', False):
jinja_env = jinja2.Environment(**env_args)
else:
jinja_env = jinja2.Environment(undefined=jinja2.StrictUndefined,
... | def render_jinja_tmpl(tmplstr, context, tmplpath=None):
opt_jinja_env_helper(opt_jinja_env, 'jinja_env')
if opts.get('allow_undefined', False):
jinja_env = jinja2.sandbox.SandboxedEnvironment(**env_args)
else:
jinja_env = jinja2.sandbox.SandboxedEnvironment(undefined=jinja2.StrictUndefi... |
def render_jinja_tmpl(tmplstr, context, tmplpath=None):
exc, out),
buf=tmplstr)
except (jinja2.exceptions.TemplateRuntimeError,
jinja2.exceptions.TemplateSyntaxError) as exc:
trace = traceback.extract_tb(sys.exc_info()[2])
line, out = _get_jinja_error(trace, c... | def render_jinja_tmpl(tmplstr, context, tmplpath=None):
exc, out),
buf=tmplstr)
except (jinja2.exceptions.TemplateRuntimeError,
jinja2.exceptions.TemplateSyntaxError,
jinja2.exceptions.SecurityError) as exc:
trace = traceback.extract_tb(sys.exc_info()[2])
... |
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import logging
# Import Salt libs
import salt.utils.templates | from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import logging
import pytest
# Import Salt libs
import salt.utils.templates |
class RenderTestCase(TestCase):
res = salt.utils.templates.render_cheetah_tmpl(tmpl, ctx)
self.assertEqual(res.strip(), 'OK')
class MockRender(object):
def __call__(self, tplstr, context, tmplpath=None): | class RenderTestCase(TestCase):
res = salt.utils.templates.render_cheetah_tmpl(tmpl, ctx)
self.assertEqual(res.strip(), 'OK')
def test_render_jinja_cve_2021_25283(self):
tmpl = '''{{ [].__class__ }}'''
ctx = dict(self.context)
ctx['var'] = 'OK'
with pytest.raises(sal... |
class TestUtil(unittest.TestCase):
self.assertEqual(unified_timestamp('25-09-2014'), 1411603200)
self.assertEqual(unified_timestamp('27.02.2016 17:30'), 1456594200)
self.assertEqual(unified_timestamp('UNKNOWN DATE FORMAT'), None)
def test_determine_ext(self):
self.assertEqual(determ... | class TestUtil(unittest.TestCase):
self.assertEqual(unified_timestamp('25-09-2014'), 1411603200)
self.assertEqual(unified_timestamp('27.02.2016 17:30'), 1456594200)
self.assertEqual(unified_timestamp('UNKNOWN DATE FORMAT'), None)
self.assertEqual(unified_timestamp('May 16, 2016 11:15 PM'... |
def unified_timestamp(date_str, day_first=True):
date_str = date_str.replace(',', ' ')
pm_delta = datetime.timedelta(hours=12 if re.search(r'(?i)PM', date_str) else 0)
timezone, date_str = extract_timezone(date_str)
# Remove AM/PM + timezone | def unified_timestamp(date_str, day_first=True):
date_str = date_str.replace(',', ' ')
pm_delta = 12 if re.search(r'(?i)PM', date_str) else 0
timezone, date_str = extract_timezone(date_str)
# Remove AM/PM + timezone |
def unified_timestamp(date_str, day_first=True):
for expression in date_formats(day_first):
try:
dt = datetime.datetime.strptime(date_str, expression) - timezone + pm_delta
return calendar.timegm(dt.timetuple())
except ValueError:
pass
timetuple = email.utils... | def unified_timestamp(date_str, day_first=True):
for expression in date_formats(day_first):
try:
dt = datetime.datetime.strptime(date_str, expression) - timezone + datetime.timedelta(hours=pm_delta)
return calendar.timegm(dt.timetuple())
except ValueError:
pass
... |
def generate_timestamp():
def generate_nonce(length=8):
"""Generate pseudorandom number."""
return ''.join([str(random.randint(0, 9)) for i in range(length)])
def generate_verifier(length=8):
"""Generate pseudorandom number."""
return ''.join([str(random.randint(0, 9)) for i in range(length)])
clas... | def generate_timestamp():
def generate_nonce(length=8):
"""Generate pseudorandom number."""
return ''.join([str(random.SystemRandom().randint(0, 9)) for i in range(length)])
def generate_verifier(length=8):
"""Generate pseudorandom number."""
return ''.join([str(random.SystemRandom().randint(0, 9)) f... |
class Request(dict):
@classmethod
def make_nonce(cls):
"""Generate pseudorandom number."""
return str(random.randint(0, 100000000))
@classmethod
def from_request(cls, http_method, http_url, headers=None, parameters=None, | class Request(dict):
@classmethod
def make_nonce(cls):
"""Generate pseudorandom number."""
return str(random.SystemRandom().randint(0, 100000000))
@classmethod
def from_request(cls, http_method, http_url, headers=None, parameters=None, |
from .helper import on_ci
"Tests/images/crash_1.tif",
"Tests/images/crash_2.tif",
"Tests/images/crash-2020-10-test.tif",
],
)
@pytest.mark.filterwarnings("ignore:Possibly corrupt EXIF data") | from .helper import on_ci
"Tests/images/crash_1.tif",
"Tests/images/crash_2.tif",
"Tests/images/crash-2020-10-test.tif",
"Tests/images/crash-1152ec2d1a1a71395b6f2ce6721c38924d025bf3.tif",
"Tests/images/crash-0e16d3bfb83be87356d026d66919deaefca44dac.tif",
],
)
@pytest.mark.fil... |
def fit_generator(model,
elif val_gen:
val_data = validation_data
if isinstance(val_data, Sequence):
val_enqueuer_gen = iter_sequence_infinite(generator)
else:
val_enqueuer_gen = val_data
else: | def fit_generator(model,
elif val_gen:
val_data = validation_data
if isinstance(val_data, Sequence):
val_enqueuer_gen = iter_sequence_infinite(val_data)
validation_steps = validation_steps or len(val_data)
else:
... |
def test_model_methods():
assert trained_batches == list(range(12)) * 5
assert len(val_seq.logs) == 12 * 5
# fit_generator will throw an exception
# if steps is unspecified for regular generator
with pytest.raises(ValueError): | def test_model_methods():
assert trained_batches == list(range(12)) * 5
assert len(val_seq.logs) == 12 * 5
# test for workers = 0
trained_epochs = []
trained_batches = []
val_seq = RandomSequence(4)
out = model.fit_generator(generator=RandomSequence(3),
epochs=... |
def list_logical_volumes(vg):
return [line.strip() for line in out.splitlines()]
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 list_logical_volumes(vg):
return [line.strip() for line in out.splitlines()]
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... |
class FileBasedCache(BaseCache):
def _createdir(self):
if not os.path.exists(self._dir):
try:
os.makedirs(self._dir, 0o700)
except FileExistsError:
pass
def _key_to_file(self, key, version=None):
""" | class FileBasedCache(BaseCache):
def _createdir(self):
if not os.path.exists(self._dir):
# Set the umask because os.makedirs() doesn't apply the "mode" argument
# to intermediate-level directories.
old_umask = os.umask(0o077)
try:
os.makedirs(... |
import os
import pickle
import re
import shutil
import tempfile
import threading
import time
import unittest
from unittest import mock
from django.conf import settings
from django.core import management, signals | import os
import pickle
import re
import shutil
import sys
import tempfile
import threading
import time
import unittest
from pathlib import Path
from unittest import mock, skipIf
from django.conf import settings
from django.core import management, signals |
class FileBasedCacheTests(BaseCacheTests, TestCase):
# Returns the default instead of erroring.
self.assertEqual(cache.get('foo', 'baz'), 'baz')
def test_get_does_not_ignore_non_filenotfound_exceptions(self):
with mock.patch('builtins.open', side_effect=IOError):
with self.asser... | class FileBasedCacheTests(BaseCacheTests, TestCase):
# Returns the default instead of erroring.
self.assertEqual(cache.get('foo', 'baz'), 'baz')
@skipIf(
sys.platform == 'win32',
'Windows only partially supports umasks and chmod.',
)
def test_cache_dir_permissions(self):
... |
This module implements the FormRequest class which is a more convenient class
See documentation in docs/topics/request-response.rst
"""
from six.moves.urllib.parse import urljoin, urlencode
import lxml.html
from parsel.selector import create_root_node
import six
from scrapy.http.request import Request
from scrapy.util... | This module implements the FormRequest class which is a more convenient class
See documentation in docs/topics/request-response.rst
"""
import six
from six.moves.urllib.parse import urljoin, urlencode
import lxml.html
from parsel.selector import create_root_node
from w3lib.html import strip_html5_whitespace
from scr... |
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)
| class FormRequest(Request):
def _get_form_url(form, url):
if url is None:
action = form.get('action')
if action is None:
return form.base_url
return urljoin(form.base_url, strip_html5_whitespace(action))
return urljoin(form.base_url, url)
|
class FormRequestTest(RequestTest):
fs = _qs(req, to_unicode=True, encoding='latin1')
self.assertTrue(fs[u'price in \u00a5'])
def test_from_response_multiple_forms_clickdata(self):
response = _buildresponse(
"""<form name="form1"> | class FormRequestTest(RequestTest):
fs = _qs(req, to_unicode=True, encoding='latin1')
self.assertTrue(fs[u'price in \u00a5'])
def test_from_response_multiple_forms_clickdata(self):
response = _buildresponse(
"""<form name="form1"> |
class FormRequestTest(RequestTest):
"""
<html>
<head>
<base href="http://b.com/">
</head>
<body>
<form action="test_form"> | class FormRequestTest(RequestTest):
"""
<html>
<head>
<base href=" http://b.com/">
</head>
<body>
<form action="test_form"> |
class FormRequestTest(RequestTest):
req = self.request_class.from_response(response)
self.assertEqual(req.url, 'http://b.com/test_form')
def test_from_response_css(self):
response = _buildresponse(
"""<form action="post.php" method="POST"> | class FormRequestTest(RequestTest):
req = self.request_class.from_response(response)
self.assertEqual(req.url, 'http://b.com/test_form')
def test_spaces_in_action(self):
resp = _buildresponse('<body><form action=" path\n"></form></body>')
req = self.request_class.from_response(resp)... |
class FormRequestTest(RequestTest):
self.assertRaises(ValueError, self.request_class.from_response,
response, formcss="input[name='abc']")
def _buildresponse(body, **kwargs):
kwargs.setdefault('body', body)
kwargs.setdefault('url', 'http://example.com')
kwargs.setdefault('... | class FormRequestTest(RequestTest):
self.assertRaises(ValueError, self.request_class.from_response,
response, formcss="input[name='abc']")
def _buildresponse(body, **kwargs):
kwargs.setdefault('body', body)
kwargs.setdefault('url', 'http://example.com')
kwargs.setdefault(... |
class IntegerArray(BaseMaskedArray):
ExtensionArray.argsort
"""
data = self._data.copy()
data[self._mask] = data.min() - 1
return data
@classmethod | class IntegerArray(BaseMaskedArray):
ExtensionArray.argsort
"""
data = self._data.copy()
if self._mask.any():
data[self._mask] = data.min() - 1
return data
@classmethod |
def test_value_counts_na():
tm.assert_series_equal(result, expected)
# TODO(jreback) - these need testing / are broken
# shift | def test_value_counts_na():
tm.assert_series_equal(result, expected)
def test_value_counts_empty():
# https://github.com/pandas-dev/pandas/issues/33317
s = pd.Series([], dtype="Int64")
result = s.value_counts()
# TODO: The dtype of the index seems wrong (it's int64 for non-empty)
idx = pd.Inde... |
class TimedeltaIndex(
"represent unambiguous timedelta values durations."
)
if isinstance(data, TimedeltaArray):
if copy:
data = data.copy()
return cls._simple_new(data, name=name, freq=freq) | class TimedeltaIndex(
"represent unambiguous timedelta values durations."
)
if isinstance(data, TimedeltaArray) and freq is None:
if copy:
data = data.copy()
return cls._simple_new(data, name=name, freq=freq) |
class TestTimedeltaIndex:
# GH#23789
TimedeltaArray(tdi, freq="D")
def test_dt64_data_invalid(self):
# GH#23539
# passing tz-aware DatetimeIndex raises, naive or ndarray[datetime64] | class TestTimedeltaIndex:
# GH#23789
TimedeltaArray(tdi, freq="D")
with pytest.raises(ValueError, match=msg):
TimedeltaIndex(tdi._data, freq="D")
with pytest.raises(ValueError, match=msg):
TimedeltaArray(tdi._data, freq="D")
def test_dt64_data_inval... |
def test_match(stderr, stdout):
def test_not_match():
assert not match(Command())
@pytest.mark.parametrize('before, after', [ | def test_match(stderr, stdout):
def test_not_match():
assert not match(Command())
assert not match(Command(script='sudo ls', stderr='Permission denied'))
@pytest.mark.parametrize('before, after', [ |
patterns = ['permission denied',
def match(command):
for pattern in patterns:
if pattern.lower() in command.stderr.lower()\
or pattern.lower() in command.stdout.lower(): | patterns = ['permission denied',
def match(command):
if command.script_parts and command.script_parts[0] == 'sudo':
return False
for pattern in patterns:
if pattern.lower() in command.stderr.lower()\
or pattern.lower() in command.stdout.lower(): |
def test_overflowing_header_limit_after_100(self):
'r\n' * 32768
)
resp = client.HTTPResponse(FakeSocket(body))
self.assertRaises(client.HTTPException, resp.begin)
def test_overflowing_chunked_line(self):
body = ( | def test_overflowing_header_limit_after_100(self):
'r\n' * 32768
)
resp = client.HTTPResponse(FakeSocket(body))
with self.assertRaises(client.HTTPException) as cm:
resp.begin()
# We must assert more because other reasonable errors that we
# do not want can... |
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')
|
import inspect
import sys
PY3 = (sys.version_info[0] == 3)
if hasattr(abc, 'ABC'):
ABC = abc.ABC | import inspect
import sys
PY3 = (sys.version_info[0] == 3)
PY2 = not PY3
if hasattr(abc, 'ABC'):
ABC = abc.ABC |
import traceback
from .variables import CommonVariable, Exploding, BaseVariable
from . import utils, pycompat
ipython_filename_pattern = re.compile('^<ipython-input-([0-9]+)-.*>$') | import traceback
from .variables import CommonVariable, Exploding, BaseVariable
from . import utils, pycompat
if pycompat.PY2:
from io import open
ipython_filename_pattern = re.compile('^<ipython-input-([0-9]+)-.*>$') |
def get_source_from_frame(frame):
# apply tokenize.detect_encoding to decode the source into a
# string, then we should do that ourselves.
if isinstance(source[0], bytes):
encoding = 'ascii'
for line in source[:2]:
# File coding may be specified. Match pattern from PEP-263
... | def get_source_from_frame(frame):
# apply tokenize.detect_encoding to decode the source into a
# string, then we should do that ourselves.
if isinstance(source[0], bytes):
encoding = 'utf-8'
for line in source[:2]:
# File coding may be specified. Match pattern from PEP-263
... |
class FileWriter(object):
self.overwrite = overwrite
def write(self, s):
with open(self.path, 'w' if self.overwrite else 'a') as output_file:
output_file.write(s)
self.overwrite = False
| class FileWriter(object):
self.overwrite = overwrite
def write(self, s):
with open(self.path, 'w' if self.overwrite else 'a',
encoding='utf-8') as output_file:
output_file.write(s)
self.overwrite = False
|
def assert_output(output, expected_entries, prefix=None):
any_mismatch = False
result = ''
template = '\n{line!s:%s} {expected_entry} {arrow}' % max(map(len, lines))
for expected_entry, line in zip_longest(expected_entries, lines, fillvalue=""):
mismatch = not (expected_entry and expected_en... | def assert_output(output, expected_entries, prefix=None):
any_mismatch = False
result = ''
template = u'\n{line!s:%s} {expected_entry} {arrow}' % max(map(len, lines))
for expected_entry, line in zip_longest(expected_entries, lines, fillvalue=""):
mismatch = not (expected_entry and expected_e... |
def assert_sample_output(module):
with sys_tools.OutputCapturer(stdout=False,
stderr=True) as output_capturer:
module.main()
time = '21:10:42.298924'
time_pattern = re.sub(r'\d', r'\\d', time)
| def assert_sample_output(module):
with sys_tools.OutputCapturer(stdout=False,
stderr=True) as output_capturer:
module.main()
time = '21:10:42.298924'
time_pattern = re.sub(r'\d', r'\\d', time)
|
class Sequential(Model):
first_layer = layer.layers[0]
while isinstance(first_layer, (Model, Sequential)):
first_layer = first_layer.layers[0]
batch_shape = first_layer.batch_input_shape
dtype = first_layer.dtype
... | class Sequential(Model):
first_layer = layer.layers[0]
while isinstance(first_layer, (Model, Sequential)):
first_layer = first_layer.layers[0]
if hasattr(first_layer, 'batch_input_shape'):
batch_shape = first_layer.batc... |
def test_sequential_deferred_build():
assert len(new_model.weights) == 4
if __name__ == '__main__':
pytest.main([__file__]) | def test_sequential_deferred_build():
assert len(new_model.weights) == 4
@keras_test
def test_nested_sequential_deferred_build():
inner_model = keras.models.Sequential()
inner_model.add(keras.layers.Dense(3))
inner_model.add(keras.layers.Dense(3))
model = keras.models.Sequential()
model.add(i... |
class FileBasedCache(BaseCache):
self._delete(fname)
def _createdir(self):
os.makedirs(self._dir, 0o700, exist_ok=True)
def _key_to_file(self, key, version=None):
""" | class FileBasedCache(BaseCache):
self._delete(fname)
def _createdir(self):
# Set the umask because os.makedirs() doesn't apply the "mode" argument
# to intermediate-level directories.
old_umask = os.umask(0o077)
try:
os.makedirs(self._dir, 0o700, exist_ok=Tru... |
import os
import pickle
import re
import shutil
import tempfile
import threading
import time
import unittest
from unittest import mock
from django.conf import settings
from django.core import management, signals | import os
import pickle
import re
import shutil
import sys
import tempfile
import threading
import time
import unittest
from pathlib import Path
from unittest import mock, skipIf
from django.conf import settings
from django.core import management, signals |
class FileBasedCacheTests(BaseCacheTests, TestCase):
# Returns the default instead of erroring.
self.assertEqual(cache.get('foo', 'baz'), 'baz')
def test_get_does_not_ignore_non_filenotfound_exceptions(self):
with mock.patch('builtins.open', side_effect=OSError):
with self.asser... | class FileBasedCacheTests(BaseCacheTests, TestCase):
# Returns the default instead of erroring.
self.assertEqual(cache.get('foo', 'baz'), 'baz')
@skipIf(
sys.platform == 'win32',
'Windows only partially supports umasks and chmod.',
)
def test_cache_dir_permissions(self):
... |
def _isna_new(obj):
elif isinstance(obj, type):
return False
elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass, ABCExtensionArray)):
return _isna_ndarraylike(obj)
elif isinstance(obj, ABCDataFrame):
return obj.isna()
elif isinstance(obj, list):
return _isna_ndarr... | def _isna_new(obj):
elif isinstance(obj, type):
return False
elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass, ABCExtensionArray)):
return _isna_ndarraylike(obj, old=False)
elif isinstance(obj, ABCDataFrame):
return obj.isna()
elif isinstance(obj, list):
return ... |
def _isna_old(obj):
elif isinstance(obj, type):
return False
elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass, ABCExtensionArray)):
return _isna_ndarraylike_old(obj)
elif isinstance(obj, ABCDataFrame):
return obj.isna()
elif isinstance(obj, list):
return _isna_n... | def _isna_old(obj):
elif isinstance(obj, type):
return False
elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass, ABCExtensionArray)):
return _isna_ndarraylike(obj, old=True)
elif isinstance(obj, ABCDataFrame):
return obj.isna()
elif isinstance(obj, list):
return _... |
def _use_inf_as_na(key):
globals()["_isna"] = _isna_new
def _isna_ndarraylike(obj):
values = getattr(obj, "_values", obj)
dtype = values.dtype
if is_extension_array_dtype(dtype):
result = values.isna()
elif is_string_dtype(dtype):
result = _isna_string_dtype(values, dtype, old... | def _use_inf_as_na(key):
globals()["_isna"] = _isna_new
def _isna_ndarraylike(obj, old: bool = False):
"""
Return an array indicating which values of the input array are NaN / NA.
Parameters
----------
obj: array-like
The input array whose elements are to be checked.
old: bool... |
import pytest
from pandas.core.dtypes.dtypes import CategoricalDtype
from pandas import Categorical, Index, Series, isna
import pandas._testing as tm
| import pytest
from pandas.core.dtypes.dtypes import CategoricalDtype
import pandas as pd
from pandas import Categorical, DataFrame, Index, Series, isna
import pandas._testing as tm
|
class TestCategoricalMissing:
expected = Categorical(["A", "B", "C", "B", "A"], dtype=cat.dtype)
tm.assert_categorical_equal(result, expected)
assert isna(cat[-1]) # didnt modify original inplace | class TestCategoricalMissing:
expected = Categorical(["A", "B", "C", "B", "A"], dtype=cat.dtype)
tm.assert_categorical_equal(result, expected)
assert isna(cat[-1]) # didnt modify original inplace
@pytest.mark.parametrize(
"values, expected",
[
([1, 2, 3], np.arr... |
class DatetimeTimedeltaMixin(DatetimeIndexOpsMixin, Int64Index):
start = right[0]
if end < start:
return type(self)(data=[])
else:
lslice = slice(*left.slice_locs(start, end))
left_chunk = left.values[lslice]
return self._shallow_copy(left_chunk)
... | class DatetimeTimedeltaMixin(DatetimeIndexOpsMixin, Int64Index):
start = right[0]
if end < start:
return type(self)(data=[], dtype=self.dtype, freq=self.freq)
else:
lslice = slice(*left.slice_locs(start, end))
left_chunk = left._values[lslice]
ret... |
class TestGetItem:
def test_dti_business_getitem(self):
rng = pd.bdate_range(START, END)
smaller = rng[:5]
exp = DatetimeIndex(rng.view(np.ndarray)[:5])
tm.assert_index_equal(smaller, exp)
assert smaller.freq == rng.freq
| class TestGetItem:
def test_dti_business_getitem(self):
rng = pd.bdate_range(START, END)
smaller = rng[:5]
exp = DatetimeIndex(rng.view(np.ndarray)[:5], freq="B")
tm.assert_index_equal(smaller, exp)
assert smaller.freq == exp.freq
assert smaller.freq == rng.freq
|
class TestGetItem:
def test_dti_custom_getitem(self):
rng = pd.bdate_range(START, END, freq="C")
smaller = rng[:5]
exp = DatetimeIndex(rng.view(np.ndarray)[:5])
tm.assert_index_equal(smaller, exp)
assert smaller.freq == rng.freq
sliced = rng[::5] | class TestGetItem:
def test_dti_custom_getitem(self):
rng = pd.bdate_range(START, END, freq="C")
smaller = rng[:5]
exp = DatetimeIndex(rng.view(np.ndarray)[:5], freq="C")
tm.assert_index_equal(smaller, exp)
assert smaller.freq == exp.freq
assert smaller.freq == rng.fr... |
class TestDatetimeIndexSetOps:
assert result.freq is None
assert result.tz == expected.tz
def test_intersection_empty(self):
# empty same freq GH2129
rng = date_range("6/1/2000", "6/15/2000", freq="T")
result = rng[0:0].intersection(rng)
assert len(result) ==... | class TestDatetimeIndexSetOps:
assert result.freq is None
assert result.tz == expected.tz
# parametrize over both anchored and non-anchored freqs, as they
# have different code paths
@pytest.mark.parametrize("freq", ["T", "B"])
def test_intersection_empty(self, tz_aware_fixture... |
class TestBusinessDatetimeIndex:
b = bdate_range("12/10/2011", "12/20/2011")
result = a.intersection(b)
tm.assert_index_equal(result, b)
def test_month_range_union_tz_pytz(self, sort):
from pytz import timezone | class TestBusinessDatetimeIndex:
b = bdate_range("12/10/2011", "12/20/2011")
result = a.intersection(b)
tm.assert_index_equal(result, b)
assert result.freq == b.freq
def test_month_range_union_tz_pytz(self, sort):
from pytz import timezone |
class TestCustomDatetimeIndex:
b = bdate_range("12/10/2011", "12/20/2011", freq="C")
result = a.intersection(b)
tm.assert_index_equal(result, b) | class TestCustomDatetimeIndex:
b = bdate_range("12/10/2011", "12/20/2011", freq="C")
result = a.intersection(b)
tm.assert_index_equal(result, b)
assert result.freq == b.freq |
class TestTimedeltaIndex:
result = index_1 & index_2
expected = timedelta_range("1 day 01:00:00", periods=3, freq="h")
tm.assert_index_equal(result, expected)
def test_intersection_equal(self, sort):
# GH 24471 Test intersection outcome given the sort keyword | class TestTimedeltaIndex:
result = index_1 & index_2
expected = timedelta_range("1 day 01:00:00", periods=3, freq="h")
tm.assert_index_equal(result, expected)
assert result.freq == expected.freq
def test_intersection_equal(self, sort):
# GH 24471 Test intersection outcome gi... |
class TestTimedeltaIndex:
TimedeltaIndex(["2 hour", "5 hour", "5 hour", "1 hour"], name="other"),
TimedeltaIndex(["1 hour", "2 hour"], name=None),
),
# reveresed index
(
TimedeltaIndex(["1 hour", "2 hour", "4 hour", "3 hour"], name="idx... | class TestTimedeltaIndex:
TimedeltaIndex(["2 hour", "5 hour", "5 hour", "1 hour"], name="other"),
TimedeltaIndex(["1 hour", "2 hour"], name=None),
),
# reversed index
(
TimedeltaIndex(["1 hour", "2 hour", "4 hour", "3 hour"], name="idx"... |
class TestTimedeltaIndex:
tm.assert_index_equal(result, expected)
assert result.name == expected.name
# if reveresed order, frequency is still the same
if all(base == rng[::-1]) and sort is None:
assert isinstance(result.freq, Hour)
else: | class TestTimedeltaIndex:
tm.assert_index_equal(result, expected)
assert result.name == expected.name
# if reversed order, frequency is still the same
if all(base == rng[::-1]) and sort is None:
assert isinstance(result.freq, Hour)
else: |
def find_hook(hook_name, hooks_dir='hooks'):
logger.debug('No hooks/dir in template_dir')
return None
for hook_file in os.listdir(hooks_dir):
if valid_hook(hook_file, hook_name):
return os.path.abspath(os.path.join(hooks_dir, hook_file))
return None
def run_script(script_... | def find_hook(hook_name, hooks_dir='hooks'):
logger.debug('No hooks/dir in template_dir')
return None
scripts = []
for hook_file in os.listdir(hooks_dir):
if valid_hook(hook_file, hook_name):
scripts.append(os.path.abspath(os.path.join(hooks_dir, hook_file)))
if len(scr... |
def run_hook(hook_name, project_dir, context):
:param project_dir: The directory to execute the script from.
:param context: Cookiecutter project context.
"""
script = find_hook(hook_name)
if script is None:
logger.debug('No %s hook found', hook_name)
return
logger.debug('Running... | def run_hook(hook_name, project_dir, context):
:param project_dir: The directory to execute the script from.
:param context: Cookiecutter project context.
"""
scripts = find_hook(hook_name)
if not scripts:
logger.debug('No %s hook found', hook_name)
return
logger.debug('Running h... |
import pytest
from cookiecutter import hooks, utils, exceptions
def make_test_repo(name):
"""Create test repository for test setup methods."""
hook_dir = os.path.join(name, 'hooks')
template = os.path.join(name, 'input{{hooks}}') | import pytest
from cookiecutter import hooks, utils, exceptions
def make_test_repo(name, multiple_hooks=False):
"""Create test repository for test setup methods."""
hook_dir = os.path.join(name, 'hooks')
template = os.path.join(name, 'input{{hooks}}') |
def make_test_repo(name):
# Set the execute bit
os.chmod(filename, os.stat(filename).st_mode | stat.S_IXUSR)
return post
| def make_test_repo(name):
# Set the execute bit
os.chmod(filename, os.stat(filename).st_mode | stat.S_IXUSR)
# Adding an additional pre script
if multiple_hooks:
if sys.platform.startswith('win'):
pre = 'pre_gen_project.bat'
with open(os.path.join(hook_dir, pre),... |
class TestFindHooks(object):
with utils.work_in(self.repo_path):
expected_pre = os.path.abspath('hooks/pre_gen_project.py')
actual_hook_path = hooks.find_hook('pre_gen_project')
assert expected_pre == actual_hook_path
expected_post = os.path.abspath('hooks/{}'.fo... | class TestFindHooks(object):
with utils.work_in(self.repo_path):
expected_pre = os.path.abspath('hooks/pre_gen_project.py')
actual_hook_path = hooks.find_hook('pre_gen_project')
assert expected_pre == actual_hook_path[0]
expected_post = os.path.abspath('hooks/{}'... |
class TestExternalHooks(object):
def setup_method(self, method):
"""External hooks related tests setup fixture."""
self.post_hook = make_test_repo(self.repo_path)
def teardown_method(self, method):
"""External hooks related tests teardown fixture.""" | class TestExternalHooks(object):
def setup_method(self, method):
"""External hooks related tests setup fixture."""
self.post_hook = make_test_repo(self.repo_path, multiple_hooks=True)
def teardown_method(self, method):
"""External hooks related tests teardown fixture.""" |
class TestExternalHooks(object):
os.remove('python_pre.txt')
if os.path.exists('shell_post.txt'):
os.remove('shell_post.txt')
if os.path.exists('tests/shell_post.txt'):
os.remove('tests/shell_post.txt')
if os.path.exists('tests/test-hooks/input{{hooks}}/python... | class TestExternalHooks(object):
os.remove('python_pre.txt')
if os.path.exists('shell_post.txt'):
os.remove('shell_post.txt')
if os.path.exists('shell_pre.txt'):
os.remove('shell_pre.txt')
if os.path.exists('tests/shell_post.txt'):
os.remove('tests... |
class TestExternalHooks(object):
with utils.work_in(self.repo_path):
hooks.run_hook('pre_gen_project', tests_dir, {})
assert os.path.isfile(os.path.join(tests_dir, 'python_pre.txt'))
hooks.run_hook('post_gen_project', tests_dir, {})
assert os.path.isfile(os.path.... | class TestExternalHooks(object):
with utils.work_in(self.repo_path):
hooks.run_hook('pre_gen_project', tests_dir, {})
assert os.path.isfile(os.path.join(tests_dir, 'python_pre.txt'))
assert os.path.isfile(os.path.join(tests_dir, 'shell_pre.txt'))
hooks.run_hook('... |
class InvalidModeException(CookiecutterException):
Raised when cookiecutter is called with both `no_input==True` and
`replay==True` at the same time.
""" | class InvalidModeException(CookiecutterException):
Raised when cookiecutter is called with both `no_input==True` and
`replay==True` at the same time.
"""
class FailedHookException(CookiecutterException):
"""
Raised when a hook script fails
""" |
from binaryornot.check import is_binary
from .exceptions import (
NonTemplatedInputDirException,
ContextDecodingException,
OutputDirExistsException
)
from .find import find_template
from .utils import make_sure_path_exists, work_in
from .hooks import run_hook, EXIT_SUCCESS
def copy_without_render(path, co... | from binaryornot.check import is_binary
from .exceptions import (
NonTemplatedInputDirException,
ContextDecodingException,
FailedHookException,
OutputDirExistsException
)
from .find import find_template
from .utils import make_sure_path_exists, work_in
from .hooks import run_hook
def copy_without_rend... |
def generate_files(repo_dir, context=None, output_dir='.',
# run pre-gen hook from repo_dir
with work_in(repo_dir):
if run_hook('pre_gen_project', project_dir, context) != EXIT_SUCCESS:
logging.error("Stopping generation because pre_gen_project"
" hook script didn'... | def generate_files(repo_dir, context=None, output_dir='.',
# run pre-gen hook from repo_dir
with work_in(repo_dir):
try:
run_hook('pre_gen_project', project_dir, context)
except FailedHookException:
shutil.rmtree(project_dir, ignore_errors=True)
logging.error... |
import tempfile
from jinja2 import Template
from cookiecutter import utils
_HOOKS = [ | import tempfile
from jinja2 import Template
from cookiecutter import utils
from .exceptions import FailedHookException
_HOOKS = [ |
def run_script(script_path, cwd='.'):
shell=run_thru_shell,
cwd=cwd
)
return proc.wait()
def run_script_with_context(script_path, cwd, context): | def run_script(script_path, cwd='.'):
shell=run_thru_shell,
cwd=cwd
)
exit_status = proc.wait()
if exit_status != EXIT_SUCCESS:
raise FailedHookException(
"Hook script failed (exit status: %d)" % exit_status)
def run_script_with_context(script_path, cwd, context): |
def run_script_with_context(script_path, cwd, context):
) as temp:
temp.write(Template(contents).render(**context))
return run_script(temp.name, cwd)
def run_hook(hook_name, project_dir, context): | def run_script_with_context(script_path, cwd, context):
) as temp:
temp.write(Template(contents).render(**context))
run_script(temp.name, cwd)
def run_hook(hook_name, project_dir, context): |
def run_hook(hook_name, project_dir, context):
script = find_hooks().get(hook_name)
if script is None:
logging.debug('No hooks found')
return EXIT_SUCCESS
return run_script_with_context(script, project_dir, context) | def run_hook(hook_name, project_dir, context):
script = find_hooks().get(hook_name)
if script is None:
logging.debug('No hooks found')
return
run_script_with_context(script, project_dir, context) |
Tests for `cookiecutter.hooks` module.
import sys
import os
import stat
from cookiecutter import hooks, utils
def make_test_repo(name): | Tests for `cookiecutter.hooks` module.
import sys
import os
import stat
import pytest
from cookiecutter import hooks, utils, exceptions
def make_test_repo(name): |
class TestExternalHooks(object):
hooks.run_hook('post_gen_project', tests_dir, {})
assert os.path.isfile(os.path.join(tests_dir, 'shell_post.txt')) | class TestExternalHooks(object):
hooks.run_hook('post_gen_project', tests_dir, {})
assert os.path.isfile(os.path.join(tests_dir, 'shell_post.txt'))
def test_run_failing_hook(self):
hook_path = os.path.join(self.hooks_path, 'pre_gen_project.py')
tests_dir = os.path.join(self... |
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... |
from django.db.models.deletion import CASCADE
from django.urls import reverse
from django.urls.exceptions import NoReverseMatch
from django.utils.html import smart_urlquote
from django.utils.safestring import mark_safe
from django.utils.text import Truncator
from django.utils.translation import get_language, gettext as... | from django.db.models.deletion import CASCADE
from django.urls import reverse
from django.urls.exceptions import NoReverseMatch
from django.utils.html import smart_urlquote
from django.utils.http import urlencode
from django.utils.text import Truncator
from django.utils.translation import get_language, gettext as _
|
class ForeignKeyRawIdWidget(forms.TextInput):
params = self.url_parameters()
if params:
related_url += '?' + '&'.join('%s=%s' % (k, v) for k, v in params.items())
context['related_url'] = mark_safe(related_url)
context['link_title'] = _('Lookup')
... | class ForeignKeyRawIdWidget(forms.TextInput):
params = self.url_parameters()
if params:
related_url += '?' + urlencode(params)
context['related_url'] = related_url
context['link_title'] = _('Lookup')
# The JavaScript code looks for this class.... |
class Band(models.Model):
return self.name
class Album(models.Model):
band = models.ForeignKey(Band, models.CASCADE)
featuring = models.ManyToManyField(Band, related_name='featured') | class Band(models.Model):
return self.name
class UnsafeLimitChoicesTo(models.Model):
band = models.ForeignKey(
Band,
models.CASCADE,
limit_choices_to={'name': '"&><escapeme'},
)
class Album(models.Model):
band = models.ForeignKey(Band, models.CASCADE)
featuring = mode... |
from django.utils import translation
from .models import (
Advisor, Album, Band, Bee, Car, Company, Event, Honeycomb, Individual,
Inventory, Member, MyFileField, Profile, School, Student,
)
from .widgetadmin import site as widget_admin_site
| from django.utils import translation
from .models import (
Advisor, Album, Band, Bee, Car, Company, Event, Honeycomb, Individual,
Inventory, Member, MyFileField, Profile, School, Student,
UnsafeLimitChoicesTo,
)
from .widgetadmin import site as widget_admin_site
|
class ForeignKeyRawIdWidgetTest(TestCase):
'Hidden</a></strong>' % {'pk': hidden.pk}
)
@override_settings(ROOT_URLCONF='admin_widgets.urls')
class ManyToManyRawIdWidgetTest(TestCase): | class ForeignKeyRawIdWidgetTest(TestCase):
'Hidden</a></strong>' % {'pk': hidden.pk}
)
def test_render_unsafe_limit_choices_to(self):
rel = UnsafeLimitChoicesTo._meta.get_field('band').remote_field
w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site)
self.assertHTML... |
import numpy as np
import time
import json
import warnings
from collections import deque
from collections import OrderedDict | import numpy as np
import time
import json
import warnings
import io
import sys
from collections import deque
from collections import OrderedDict |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.