buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
class _Numeric:
raise ValueError
def __gt__(self, other):
return not self.__lt__(other)
def __le__(self, other):
return self.__lt__(other) or self.__eq__(other)
def __ge__(self, other):
return self.__gt__(other) or self.__eq__(other)
class SemanticVersion(Version): | class _Numeric:
raise ValueError
def __le__(self, other):
return self.__lt__(other) or self.__eq__(other)
def __gt__(self, other):
return not self.__le__(other)
def __ge__(self, other):
return not self.__lt__(other)
class SemanticVersion(Version): |
def test_alpha():
assert _Alpha('b') >= _Alpha('a')
assert _Alpha('b') >= _Alpha('b')
def test_numeric():
assert _Numeric(1) == _Numeric(1) | def test_alpha():
assert _Alpha('b') >= _Alpha('a')
assert _Alpha('b') >= _Alpha('b')
# The following 3*6 tests check that all comparison operators perform
# as expected. DO NOT remove any of them, or reformulate them (to remove
# the explicit `not`)!
assert _Alpha('a') == _Alpha('a')
asse... |
def test_numeric():
assert _Numeric(1) <= _Numeric(2)
assert _Numeric(2) >= _Numeric(1)
assert _Numeric(2) >= _Numeric(2) | def test_numeric():
assert _Numeric(1) <= _Numeric(2)
assert _Numeric(2) >= _Numeric(1)
assert _Numeric(2) >= _Numeric(2)
# The following 3*6 tests check that all comparison operators perform
# as expected. DO NOT remove any of them, or reformulate them (to remove
# the explicit `not`)!
as... |
from pandas.core.dtypes.common import (
from pandas.core.dtypes.dtypes import IntervalDtype
from pandas.core.dtypes.generic import (
ABCDatetimeIndex,
ABCIndexClass,
ABCInterval,
ABCIntervalIndex, | from pandas.core.dtypes.common import (
from pandas.core.dtypes.dtypes import IntervalDtype
from pandas.core.dtypes.generic import (
ABCDatetimeIndex,
ABCExtensionArray,
ABCIndexClass,
ABCInterval,
ABCIntervalIndex, |
class IntervalArray(IntervalMixin, ExtensionArray):
# Avoid materializing self.values
return self.left.size
def take(self, indices, allow_fill=False, fill_value=None, axis=None, **kwargs):
"""
Take elements from the IntervalArray. | class IntervalArray(IntervalMixin, ExtensionArray):
# Avoid materializing self.values
return self.left.size
def shift(self, periods: int = 1, fill_value: object = None) -> ABCExtensionArray:
if not len(self) or periods == 0:
return self.copy()
if isna(fill_value):
... |
class TestMethods:
with pytest.raises(ValueError, match=match):
ser.where([True, False, True], other=other)
class TestSetitem:
def test_set_na(self, left_right_dtypes): | class TestMethods:
with pytest.raises(ValueError, match=match):
ser.where([True, False, True], other=other)
def test_shift(self):
# https://github.com/pandas-dev/pandas/issues/31495
a = IntervalArray.from_breaks([1, 2, 3])
result = a.shift()
# int -> float
... |
class BaseMethodsTests(BaseExtensionTests):
expected = empty
self.assert_extension_array_equal(result, expected)
def test_shift_fill_value(self, data):
arr = data[:4]
fill_value = data[0] | class BaseMethodsTests(BaseExtensionTests):
expected = empty
self.assert_extension_array_equal(result, expected)
def test_shift_zero_copies(self, data):
result = data.shift(0)
assert result is not data
result = data[:0].shift(2)
assert result is not data
def te... |
class FileSystemStorage(Storage):
directory = os.path.dirname(full_path)
try:
if self.directory_permissions_mode is not None:
# os.makedirs applies the global umask, so we reset it,
# for consistency with file_permissions_mode behavior.
old_uma... | class FileSystemStorage(Storage):
directory = os.path.dirname(full_path)
try:
if self.directory_permissions_mode is not None:
# Set the umask because os.makedirs() doesn't apply the "mode"
# argument to intermediate-level directories.
old_umask... |
import time
import unittest
from datetime import datetime, timedelta
from io import StringIO
from urllib.request import urlopen
from django.core.cache import cache | import time
import unittest
from datetime import datetime, timedelta
from io import StringIO
from pathlib import Path
from urllib.request import urlopen
from django.core.cache import cache |
class FileStoragePermissions(unittest.TestCase):
@override_settings(FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765)
def test_file_upload_directory_permissions(self):
self.storage = FileSystemStorage(self.storage_dir)
name = self.storage.save("the_directory/the_file", ContentFile("data"))
dir_mo... | class FileStoragePermissions(unittest.TestCase):
@override_settings(FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765)
def test_file_upload_directory_permissions(self):
self.storage = FileSystemStorage(self.storage_dir)
name = self.storage.save('the_directory/subdir/the_file', ContentFile('data'))
... |
import sys
import tempfile
import unittest
from io import StringIO
from unittest import mock
from django.conf import settings | import sys
import tempfile
import unittest
from io import StringIO
from pathlib import Path
from unittest import mock
from django.conf import settings |
class TestStaticFilePermissions(CollectionTestCase):
)
def test_collect_static_files_permissions(self):
call_command('collectstatic', **self.command_params)
test_file = os.path.join(settings.STATIC_ROOT, "test.txt")
test_dir = os.path.join(settings.STATIC_ROOT, "subdir")
file_mod... | class TestStaticFilePermissions(CollectionTestCase):
)
def test_collect_static_files_permissions(self):
call_command('collectstatic', **self.command_params)
static_root = Path(settings.STATIC_ROOT)
test_file = static_root / 'test.txt'
file_mode = test_file.stat().st_mode & 0o777
... |
class TestStaticFilePermissions(CollectionTestCase):
)
def test_collect_static_files_default_permissions(self):
call_command('collectstatic', **self.command_params)
test_file = os.path.join(settings.STATIC_ROOT, "test.txt")
test_dir = os.path.join(settings.STATIC_ROOT, "subdir")
... | class TestStaticFilePermissions(CollectionTestCase):
)
def test_collect_static_files_default_permissions(self):
call_command('collectstatic', **self.command_params)
static_root = Path(settings.STATIC_ROOT)
test_file = static_root / 'test.txt'
file_mode = test_file.stat().st_mode ... |
class TestStaticFilePermissions(CollectionTestCase):
)
def test_collect_static_files_subclass_of_static_storage(self):
call_command('collectstatic', **self.command_params)
test_file = os.path.join(settings.STATIC_ROOT, "test.txt")
test_dir = os.path.join(settings.STATIC_ROOT, "subdir")
... | class TestStaticFilePermissions(CollectionTestCase):
)
def test_collect_static_files_subclass_of_static_storage(self):
call_command('collectstatic', **self.command_params)
static_root = Path(settings.STATIC_ROOT)
test_file = static_root / 'test.txt'
file_mode = test_file.stat().s... |
from pandas.core.dtypes.cast import (
validate_numeric_casting,
)
from pandas.core.dtypes.common import (
ensure_float64,
ensure_int64,
ensure_platform_int,
infer_dtype_from_object, | from pandas.core.dtypes.cast import (
validate_numeric_casting,
)
from pandas.core.dtypes.common import (
ensure_int64,
ensure_platform_int,
infer_dtype_from_object, |
Wild 185.0
numeric_df = self._get_numeric_data()
cols = numeric_df.columns
idx = cols.copy()
mat = numeric_df.values
if method == "pearson":
correl = libalgos.nancorr(ensure_float64(mat), minp=min_periods)
elif method == "spearman":
correl... | Wild 185.0
numeric_df = self._get_numeric_data()
cols = numeric_df.columns
idx = cols.copy()
mat = numeric_df.astype(float, copy=False).to_numpy()
if method == "pearson":
correl = libalgos.nancorr(mat, minp=min_periods)
elif method == "spearman":
... |
Wild 185.0
numeric_df = self._get_numeric_data()
cols = numeric_df.columns
idx = cols.copy()
mat = numeric_df.values
if notna(mat).all():
if min_periods is not None and min_periods > len(mat):
baseCov = np.empty((mat.shape[1], mat.shape[1]))
... | Wild 185.0
numeric_df = self._get_numeric_data()
cols = numeric_df.columns
idx = cols.copy()
mat = numeric_df.astype(float, copy=False).to_numpy()
if notna(mat).all():
if min_periods is not None and min_periods > len(mat):
base_cov = np.empty(... |
class TestDataFrameCov:
)
tm.assert_frame_equal(result, expected)
class TestDataFrameCorr:
# DataFrame.corr(), as opposed to DataFrame.corrwith | class TestDataFrameCov:
)
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
"other_column", [pd.array([1, 2, 3]), np.array([1.0, 2.0, 3.0])]
)
def test_cov_nullable_integer(self, other_column):
# https://github.com/pandas-dev/pandas/issues/33803
data ... |
class TestDataFrameCorr:
df3.cov()
df3.corr()
class TestDataFrameCorrWith:
def test_corrwith(self, datetime_frame): | class TestDataFrameCorr:
df3.cov()
df3.corr()
@td.skip_if_no_scipy
@pytest.mark.parametrize(
"nullable_column", [pd.array([1, 2, 3]), pd.array([1, 2, None])]
)
@pytest.mark.parametrize(
"other_column",
[pd.array([1, 2, 3]), np.array([1.0, 2.0, 3.0]), np.array([1.... |
def get_grouper(
return False
try:
return gpr is obj[gpr.name]
except (KeyError, IndexError):
return False
for i, (gpr, level) in enumerate(zip(keys, levels)): | def get_grouper(
return False
try:
return gpr is obj[gpr.name]
except (KeyError, IndexError, ValueError):
# TODO: ValueError: Given date string not likely a datetime.
# should be KeyError?
return False
for i, (gpr, level) in enumerate(zip(... |
import numpy as np
import pytest
from pandas import DataFrame, Index, Series
import pandas._testing as tm
| import numpy as np
import pytest
from pandas import DataFrame, Index, PeriodIndex, Series
import pandas._testing as tm
|
def test_size_groupby_all_null():
result = df.groupby("A").size()
expected = Series(dtype="int64", index=Index([], name="A"))
tm.assert_series_equal(result, expected) | def test_size_groupby_all_null():
result = df.groupby("A").size()
expected = Series(dtype="int64", index=Index([], name="A"))
tm.assert_series_equal(result, expected)
def test_size_period_index():
# https://github.com/pandas-dev/pandas/issues/34010
ser = Series([1], index=PeriodIndex(["2000"], nam... |
def _get_clickable(clickdata, form):
"""
clickables = [
el for el in form.xpath(
'descendant::*[(self::input or self::button)'
' and re:test(@type, "^submit$", "i")]'
'|descendant::button[not(@type)]',
namespaces={"re": "http://exslt.org/regular-expression... | def _get_clickable(clickdata, form):
"""
clickables = [
el for el in form.xpath(
'descendant::input[re:test(@type, "^(submit|image)$", "i")]'
'|descendant::button[not(@type) or re:test(@type, "^submit$", "i")]',
namespaces={"re": "http://exslt.org/regular-expressions"... |
class FormRequestTest(RequestTest):
req = self.request_class.from_response(response, dont_click=True)
fs = _qs(req)
self.assertEqual(fs, {b'i1': [b'i1v'], b'i2': [b'i2v']})
def test_from_response_multiple_clickdata(self):
response = _buildresponse( | class FormRequestTest(RequestTest):
req = self.request_class.from_response(response, dont_click=True)
fs = _qs(req)
self.assertEqual(fs, {b'i1': [b'i1v'], b'i2': [b'i2v']})
def test_from_response_clickdata_does_not_ignore_image(self):
response = _buildresponse(
"""<f... |
def test_retry_method_not_in_whitelist(self):
retry = Retry()
with pytest.raises(ReadTimeoutError):
retry.increment(method='POST', error=error) | def test_retry_method_not_in_whitelist(self):
retry = Retry()
with pytest.raises(ReadTimeoutError):
retry.increment(method='POST', error=error)
def test_retry_default_remove_headers_on_redirect(self):
retry = Retry()
assert list(retry.remove_headers_on_redirect) == ['Au... |
def test_too_many_redirects(self):
except MaxRetryError:
pass
def test_raise_on_redirect(self):
http = PoolManager()
self.addCleanup(http.clear) | def test_too_many_redirects(self):
except MaxRetryError:
pass
def test_redirect_cross_host_remove_headers(self):
http = PoolManager()
self.addCleanup(http.clear)
r = http.request('GET', '%s/redirect' % self.base_url,
fields={'target': '%s/header... |
def urlopen(self, method, url, redirect=True, **kw):
kw['assert_same_host'] = False
kw['redirect'] = False
if 'headers' not in kw:
kw['headers'] = self.headers
if self.proxy is not None and u.scheme == "http":
response = conn.urlopen(method, url, **kw) | def urlopen(self, method, url, redirect=True, **kw):
kw['assert_same_host'] = False
kw['redirect'] = False
if 'headers' not in kw:
kw['headers'] = self.headers.copy()
if self.proxy is not None and u.scheme == "http":
response = conn.urlopen(method, url, **kw) |
def urlopen(self, method, url, redirect=True, **kw):
if not isinstance(retries, Retry):
retries = Retry.from_int(retries, redirect=redirect)
try:
retries = retries.increment(method, url, response=response, _pool=conn)
except MaxRetryError: | def urlopen(self, method, url, redirect=True, **kw):
if not isinstance(retries, Retry):
retries = Retry.from_int(retries, redirect=redirect)
# Strip headers marked as unsafe to forward to the redirected location.
# Check remove_headers_on_redirect to avoid a potential network call w... |
log = logging.getLogger(__name__)
# Data structure for representing the metadata of requests that result in a retry.
RequestHistory = namedtuple('RequestHistory', ["method", "url", "error",
"status", "redirect_location"]) |
log = logging.getLogger(__name__)
# Data structure for representing the metadata of requests that result in a retry.
RequestHistory = namedtuple('RequestHistory', ["method", "url", "error",
"status", "redirect_location"]) |
class Retry(object):
Whether to respect Retry-After header on status codes defined as
:attr:`Retry.RETRY_AFTER_STATUS_CODES` or not.
"""
DEFAULT_METHOD_WHITELIST = frozenset([ | class Retry(object):
Whether to respect Retry-After header on status codes defined as
:attr:`Retry.RETRY_AFTER_STATUS_CODES` or not.
:param iterable remove_headers_on_redirect:
Sequence of headers to remove from the request when a response
indicating a redirect is returned before fi... |
class Retry(object):
RETRY_AFTER_STATUS_CODES = frozenset([413, 429, 503])
#: Maximum backoff time.
BACKOFF_MAX = 120
def __init__(self, total=10, connect=None, read=None, redirect=None, status=None,
method_whitelist=DEFAULT_METHOD_WHITELIST, status_forcelist=None,
b... | class Retry(object):
RETRY_AFTER_STATUS_CODES = frozenset([413, 429, 503])
DEFAULT_REDIRECT_HEADERS_BLACKLIST = frozenset(['Authorization'])
#: Maximum backoff time.
BACKOFF_MAX = 120
def __init__(self, total=10, connect=None, read=None, redirect=None, status=None,
method_whitel... |
def __init__(self, total=10, connect=None, read=None, redirect=None, status=None
self.raise_on_status = raise_on_status
self.history = history or tuple()
self.respect_retry_after_header = respect_retry_after_header
def new(self, **kw):
params = dict( | def __init__(self, total=10, connect=None, read=None, redirect=None, status=None
self.raise_on_status = raise_on_status
self.history = history or tuple()
self.respect_retry_after_header = respect_retry_after_header
self.remove_headers_on_redirect = remove_headers_on_redirect
def new... |
def new(self, **kw):
raise_on_redirect=self.raise_on_redirect,
raise_on_status=self.raise_on_status,
history=self.history,
)
params.update(kw)
return type(self)(**params) | def new(self, **kw):
raise_on_redirect=self.raise_on_redirect,
raise_on_status=self.raise_on_status,
history=self.history,
remove_headers_on_redirect=self.remove_headers_on_redirect
)
params.update(kw)
return type(self)(**params) |
async def request_body_to_args(
for field in required_params:
value: Any = None
if received_body is not None:
if field.shape in sequence_shapes and isinstance(
received_body, FormData
):
value = received_body.getlist... | async def request_body_to_args(
for field in required_params:
value: Any = None
if received_body is not None:
if (
field.shape in sequence_shapes or field.type_ in sequence_types
) and isinstance(received_body, FormData):
... |
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', |
from RestrictedPython.Utilities import utility_builtins
from zExceptions import Unauthorized
from AccessControl.SecurityInfo import secureModule
from AccessControl.SecurityManagement import getSecurityManager
from AccessControl.SimpleObjectPolicies import ContainerAssertions | from RestrictedPython.Utilities import utility_builtins
from zExceptions import Unauthorized
from AccessControl.SecurityInfo import ModuleSecurityInfo
from AccessControl.SecurityInfo import secureModule
from AccessControl.SecurityManagement import getSecurityManager
from AccessControl.SimpleObjectPolicies import Conta... |
math.__allow_access_to_unprotected_subobjects__ = 1
random.__allow_access_to_unprotected_subobjects__ = 1
# AccessControl.Implementation inserts these names into this module as
# module globals: aq_validate, guarded_getattr
| math.__allow_access_to_unprotected_subobjects__ = 1
random.__allow_access_to_unprotected_subobjects__ = 1
# Mark some unprotected module attributes as private, these should not be
# used in untrusted Python code such as Scripts (Python)
string_modsec = ModuleSecurityInfo('string')
for name in ('Formatter', 'Template')... |
def testAccessToSimpleContainer(self):
c.attr = PublicMethod()
self.assertPolicyAllows(c, 'attr')
def testUnicodeAttributeLookups(self):
item = self.item
r_item = self.a.r_item | def testAccessToSimpleContainer(self):
c.attr = PublicMethod()
self.assertPolicyAllows(c, 'attr')
def testAccessToStringModule(self):
# The string module is available to restricted code and its members are
# explicitly allowed via a
# ``__allow_access_to_unprotected_subobjec... |
def any_int_dtype(request):
return request.param
@pytest.fixture(params=ALL_REAL_DTYPES)
def any_real_dtype(request):
""" | def any_int_dtype(request):
return request.param
@pytest.fixture(params=ALL_EA_INT_DTYPES)
def any_nullable_int_dtype(request):
"""
Parameterized fixture for any nullable integer dtype.
* 'UInt8'
* 'Int8'
* 'UInt16'
* 'Int16'
* 'UInt32'
* 'Int32'
* 'UInt64'
* 'Int64'
"... |
from pandas.core.dtypes.missing import isna, notna
from pandas.core import nanops, ops
from pandas.core.algorithms import take
from pandas.core.arrays import ExtensionArray, ExtensionOpsMixin
from pandas.core.ops.common import unpack_zerodim_and_defer
from pandas.core.tools.numeric import to_numeric
| from pandas.core.dtypes.missing import isna, notna
from pandas.core import nanops, ops
from pandas.core.algorithms import take
from pandas.core.arrays import ExtensionArray, ExtensionOpsMixin
from pandas.core.ops import invalid_comparison
from pandas.core.ops.common import unpack_zerodim_and_defer
from pandas.core.tool... |
class IntegerArray(ExtensionArray, ExtensionOpsMixin):
with warnings.catch_warnings():
warnings.filterwarnings("ignore", "elementwise", FutureWarning)
with np.errstate(all="ignore"):
result = op(self._data, other)
# nans propagate
... | class IntegerArray(ExtensionArray, ExtensionOpsMixin):
with warnings.catch_warnings():
warnings.filterwarnings("ignore", "elementwise", FutureWarning)
with np.errstate(all="ignore"):
method = getattr(self._data, f"__{op_name}__")
result... |
class TestComparisonOps(base.BaseComparisonOpsTests):
def _compare_other(self, s, data, op_name, other):
self.check_opname(s, op_name, other)
class TestInterface(base.BaseInterfaceTests):
pass | class TestComparisonOps(base.BaseComparisonOpsTests):
def _compare_other(self, s, data, op_name, other):
self.check_opname(s, op_name, other)
def test_compare_to_string(self, any_nullable_int_dtype):
# GH 28930
s = pd.Series([1, None], dtype=any_nullable_int_dtype)
result = s ==... |
from django.db import NotSupportedError, transaction
from django.db.backends import utils
from django.utils import timezone
from django.utils.encoding import force_str
class BaseDatabaseOperations: | from django.db import NotSupportedError, transaction
from django.db.backends import utils
from django.utils import timezone
from django.utils.encoding import force_str
from django.utils.regex_helper import _lazy_re_compile
class BaseDatabaseOperations: |
class BaseDatabaseOperations:
# Prefix for EXPLAIN queries, or None EXPLAIN isn't supported.
explain_prefix = None
def __init__(self, connection):
self.connection = connection
self._cache = None | class BaseDatabaseOperations:
# Prefix for EXPLAIN queries, or None EXPLAIN isn't supported.
explain_prefix = None
extract_trunc_lookup_pattern = _lazy_re_compile(r"[\w\-_()]+")
def __init__(self, connection):
self.connection = connection
self._cache = None |
class Extract(TimezoneMixin, Transform):
super().__init__(expression, **extra)
def as_sql(self, compiler, connection):
sql, params = compiler.compile(self.lhs)
lhs_output_field = self.lhs.output_field
if isinstance(lhs_output_field, DateTimeField): | class Extract(TimezoneMixin, Transform):
super().__init__(expression, **extra)
def as_sql(self, compiler, connection):
if not connection.ops.extract_trunc_lookup_pattern.fullmatch(self.lookup_name):
raise ValueError("Invalid lookup_name: %s" % self.lookup_name)
sql, params = com... |
class TruncBase(TimezoneMixin, Transform):
super().__init__(expression, output_field=output_field, **extra)
def as_sql(self, compiler, connection):
inner_sql, inner_params = compiler.compile(self.lhs)
tzname = None
if isinstance(self.lhs.output_field, DateTimeField): | class TruncBase(TimezoneMixin, Transform):
super().__init__(expression, output_field=output_field, **extra)
def as_sql(self, compiler, connection):
if not connection.ops.extract_trunc_lookup_pattern.fullmatch(self.kind):
raise ValueError("Invalid kind: %s" % self.kind)
inner_sql... |
class DateFunctionTests(TestCase):
self.assertEqual(qs.count(), 1)
self.assertGreaterEqual(str(qs.query).lower().count('extract'), 2)
def test_extract_func(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = datetime(2016, 6, 15, 14, 10, 50,... | class DateFunctionTests(TestCase):
self.assertEqual(qs.count(), 1)
self.assertGreaterEqual(str(qs.query).lower().count('extract'), 2)
def test_extract_lookup_name_sql_injection(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = datetime(201... |
class DateFunctionTests(TestCase):
)
self.assertEqual(DTModel.objects.filter(start_datetime__second=ExtractSecond('start_datetime')).count(), 2)
def test_trunc_func(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) | class DateFunctionTests(TestCase):
)
self.assertEqual(DTModel.objects.filter(start_datetime__second=ExtractSecond('start_datetime')).count(), 2)
def test_trunc_lookup_name_sql_injection(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = datetime(2016, 6, 1... |
class _Window(PandasObject, SelectionMixin):
except (ValueError, TypeError):
raise TypeError("cannot handle this type -> {0}".format(values.dtype))
# Always convert inf to nan
values[np.isinf(values)] = np.NaN
return values
| class _Window(PandasObject, SelectionMixin):
except (ValueError, TypeError):
raise TypeError("cannot handle this type -> {0}".format(values.dtype))
# Convert inf to nan for C funcs
inf = np.isinf(values)
if inf.any():
values = np.where(inf, np.nan, values... |
class TestRolling(Base):
result = df.rolling(2, axis=axis_frame).count()
tm.assert_frame_equal(result, expected) | class TestRolling(Base):
result = df.rolling(2, axis=axis_frame).count()
tm.assert_frame_equal(result, expected)
def test_readonly_array(self):
# GH-27766
arr = np.array([1, 3, np.nan, 3, 5])
arr.setflags(write=False)
result = pd.Series(arr).rolling(2).mean()
... |
class KeyValueType(object):
"""A type used with `argparse`."""
def __init__(self, *separators):
self.separators = separators
def __call__(self, string):
found = {}
for sep in self.separators:
regex = '[^\\\\]' + sep
match = re.search(regex, string)
... | class KeyValueType(object):
"""A type used with `argparse`."""
def __init__(self, *separators):
self.separators = separators
self.escapes = ['\\\\' + sep for sep in separators]
def __call__(self, string):
found = {}
found_escapes = []
for esc in self.escapes:
... |
class TestItemParsing(BaseTest):
})
self.assertIn('bar@baz', files)
def test_valid_items(self):
headers, data, files = cli.parse_items([ | class TestItemParsing(BaseTest):
})
self.assertIn('bar@baz', files)
def test_escape_longsep(self):
headers, data, files = cli.parse_items([
self.kv('bob\\:==foo'),
])
self.assertDictEqual(data, {
'bob:=': 'foo',
})
def test_valid_item... |
class SplunkHTTPCollectorSource(object):
else:
ansible_role = None
data = {}
data['uuid'] = result._task._uuid
data['session'] = self.session | class SplunkHTTPCollectorSource(object):
else:
ansible_role = None
if 'args' in result._task_fields:
del result._task_fields['args']
data = {}
data['uuid'] = result._task._uuid
data['session'] = self.session |
class SumologicHTTPCollectorSource(object):
else:
ansible_role = None
data = {}
data['uuid'] = result._task._uuid
data['session'] = self.session | class SumologicHTTPCollectorSource(object):
else:
ansible_role = None
if 'args' in result._task_fields:
del result._task_fields['args']
data = {}
data['uuid'] = result._task._uuid
data['session'] = self.session |
part 3</font></u>
cli_bool_option(
{'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
['--check-certificate=true'])
def test_ohdave_rsa_encrypt(self):
N = 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3af... | part 3</font></u>
cli_bool_option(
{'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
['--check-certificate=true'])
self.assertEqual(
cli_bool_option(
{}, '--check-certificate', 'nocheckcertificat... |
def cli_option(params, command_option, param):
def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None):
param = params.get(param)
assert isinstance(param, bool)
if separator:
return [command_option + separator + (true_value if param else false_valu... | def cli_option(params, command_option, param):
def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None):
param = params.get(param)
if param is None:
return []
assert isinstance(param, bool)
if separator:
return [command_option + separato... |
class TestUtil(unittest.TestCase):
self.assertEqual(unescapeHTML('%20;'), '%20;')
self.assertEqual(unescapeHTML('/'), '/')
self.assertEqual(unescapeHTML('/'), '/')
self.assertEqual(
unescapeHTML('é'), 'é')
def test_daterange(self):
_20century = Da... | class TestUtil(unittest.TestCase):
self.assertEqual(unescapeHTML('%20;'), '%20;')
self.assertEqual(unescapeHTML('/'), '/')
self.assertEqual(unescapeHTML('/'), '/')
self.assertEqual(unescapeHTML('é'), 'é')
self.assertEqual(unescapeHTML('�'), '�... |
def _htmlentity_transform(entity):
numstr = '0%s' % numstr
else:
base = 10
return compat_chr(int(numstr, base))
# Unknown entity in name, return its literal representation
return ('&%s;' % entity) | def _htmlentity_transform(entity):
numstr = '0%s' % numstr
else:
base = 10
# See https://github.com/rg3/youtube-dl/issues/7518
try:
return compat_chr(int(numstr, base))
except ValueError:
pass
# Unknown entity in name, return its liter... |
def find_meta(meta):
package_dir={"": "src"},
install_requires=[
# Fix cryptographyMinimum in tox.ini when changing this!
"cryptography>=1.9",
"six>=1.5.2"
],
extras_require={ | def find_meta(meta):
package_dir={"": "src"},
install_requires=[
# Fix cryptographyMinimum in tox.ini when changing this!
"cryptography>=2.1.4",
"six>=1.5.2"
],
extras_require={ |
def __init__(self, callback):
@wraps(callback)
def wrapper(ok, store_ctx):
cert = X509.__new__(X509)
cert._x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
error_depth = _lib.X509_STORE_CTX_get... | def __init__(self, callback):
@wraps(callback)
def wrapper(ok, store_ctx):
x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
_lib.X509_up_ref(x509)
cert = X509._from_raw_x509_ptr(x509)
error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
... |
def load_pkcs12(buffer, passphrase=None):
pycert = None
friendlyname = None
else:
pycert = X509.__new__(X509)
pycert._x509 = _ffi.gc(cert[0], _lib.X509_free)
friendlyname_length = _ffi.new("int*")
friendlyname_buffer = _lib.X509_alias_get0( | def load_pkcs12(buffer, passphrase=None):
pycert = None
friendlyname = None
else:
pycert = X509._from_raw_x509_ptr(cert[0])
friendlyname_length = _ffi.new("int*")
friendlyname_buffer = _lib.X509_alias_get0( |
def load_pkcs12(buffer, passphrase=None):
pycacerts = []
for i in range(_lib.sk_X509_num(cacerts)):
pycacert = X509.__new__(X509)
pycacert._x509 = _lib.sk_X509_value(cacerts, i)
pycacerts.append(pycacert)
if not pycacerts:
pycacerts = None | def load_pkcs12(buffer, passphrase=None):
pycacerts = []
for i in range(_lib.sk_X509_num(cacerts)):
x509 = _lib.sk_X509_value(cacerts, i)
pycacert = X509._from_raw_x509_ptr(x509)
pycacerts.append(pycacert)
if not pycacerts:
pycacerts = None |
def callback(self, connection, *args):
assert verify.connection is clientConnection
def test_set_verify_callback_exception(self):
"""
If the verify callback passed to `Context.set_verify` raises an | def callback(self, connection, *args):
assert verify.connection is clientConnection
def test_x509_in_verify_works(self):
"""
We had a bug where the X509 cert instantiated in the callback wrapper
didn't __init__ so it was missing objects needed when calling
get_subject. This... |
default 'raise'
DatetimeIndex(['2018-03-01 09:00:00-05:00',
'2018-03-02 09:00:00-05:00',
'2018-03-03 09:00:00-05:00'],
dtype='datetime64[ns, US/Eastern]', freq='D')
With the ``tz=None``, we can remove the time zone information
... | default 'raise'
DatetimeIndex(['2018-03-01 09:00:00-05:00',
'2018-03-02 09:00:00-05:00',
'2018-03-03 09:00:00-05:00'],
dtype='datetime64[ns, US/Eastern]', freq=None)
With the ``tz=None``, we can remove the time zone information
... |
default 'raise'
>>> tz_aware.tz_localize(None)
DatetimeIndex(['2018-03-01 09:00:00', '2018-03-02 09:00:00',
'2018-03-03 09:00:00'],
dtype='datetime64[ns]', freq='D')
Be careful with DST changes. When there is sequential data, pandas can
infer... | default 'raise'
>>> tz_aware.tz_localize(None)
DatetimeIndex(['2018-03-01 09:00:00', '2018-03-02 09:00:00',
'2018-03-03 09:00:00'],
dtype='datetime64[ns]', freq=None)
Be careful with DST changes. When there is sequential data, pandas can
infe... |
default 'raise'
)
new_dates = new_dates.view(DT64NS_DTYPE)
dtype = tz_to_dtype(tz)
return self._simple_new(new_dates, dtype=dtype, freq=self.freq)
# ----------------------------------------------------------------
# Conversion Methods - Vectorized analogues of Timestamp meth... | default 'raise'
)
new_dates = new_dates.view(DT64NS_DTYPE)
dtype = tz_to_dtype(tz)
freq = None
if timezones.is_utc(tz) or (len(self) == 1 and not isna(new_dates[0])):
# we can preserve freq
# TODO: Also for fixed-offsets
freq = self.freq
... |
class TestDatetimeIndexTimezones:
)
for i, ts in enumerate(index):
assert ts == index[i] | class TestDatetimeIndexTimezones:
)
for i, ts in enumerate(index):
assert ts == index[i]
def test_tz_localize_invalidates_freq():
# we only preserve freq in unambiguous cases
# if localized to US/Eastern, this crosses a DST transition
dti = date_range("2014-03-08 23:00", "2014... |
class TestSeriesComparison:
# datetime64tz dtype
dti = dti.tz_localize("US/Central")
ser = Series(dti).rename(names[1])
result = op(ser, dti)
assert result.name == names[2] | class TestSeriesComparison:
# datetime64tz dtype
dti = dti.tz_localize("US/Central")
dti._set_freq("infer") # freq not preserved by tz_localize
ser = Series(dti).rename(names[1])
result = op(ser, dti)
assert result.name == names[2] |
def test_bad_server_hostname(self):
with self.assertRaises(ValueError):
ctx.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO(),
server_hostname=".example.org")
class MemoryBIOTests(unittest.TestCase): | def test_bad_server_hostname(self):
with self.assertRaises(ValueError):
ctx.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO(),
server_hostname=".example.org")
with self.assertRaises(TypeError):
ctx.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO(),
... |
import os
# Import salt libs
import salt.utils.files
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six | import os
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.verify
# Import 3rd-party libs
from salt.ext import six |
def write(data, path, saltenv='base', index=0):
if os.path.isabs(path):
return ('The path passed in {0} is not relative to the environment '
'{1}').format(path, saltenv)
dest = os.path.join(__opts__['pillar_roots'][saltenv][index], path)
dest_dir = os.path.dirname(dest)
if not os... | def write(data, path, saltenv='base', index=0):
if os.path.isabs(path):
return ('The path passed in {0} is not relative to the environment '
'{1}').format(path, saltenv)
roots_dir = __opts__['pillar_roots'][saltenv][index]
dest = os.path.join(roots_dir, path)
if not salt.utils.ve... |
class LinuxHardware(Hardware):
# The fields for ARM CPUs do not always include 'vendor_id' or 'model name',
# and sometimes includes both 'processor' and 'Processor'.
# Always use 'processor' count for ARM systems
if collected_facts.get('ansible_architecture', '').startswith(('armv', 'a... | class LinuxHardware(Hardware):
# The fields for ARM CPUs do not always include 'vendor_id' or 'model name',
# and sometimes includes both 'processor' and 'Processor'.
# The fields for Power CPUs include 'processor' and 'cpu'.
# Always use 'processor' count for ARM and Power systems
... |
CPU_INFO_TEST_SCENARIOS = [
'7', 'POWER7 (architected), altivec supported'
],
'processor_cores': 1,
'processor_count': 16,
'processor_threads_per_core': 1,
'processor_vcpus': 16
},
},
{ | CPU_INFO_TEST_SCENARIOS = [
'7', 'POWER7 (architected), altivec supported'
],
'processor_cores': 1,
'processor_count': 8,
'processor_threads_per_core': 1,
'processor_vcpus': 8
},
},
{ |
CPU_INFO_TEST_SCENARIOS = [
'23', 'POWER8 (architected), altivec supported',
],
'processor_cores': 1,
'processor_count': 48,
'processor_threads_per_core': 1,
'processor_vcpus': 48
},
},
{ | CPU_INFO_TEST_SCENARIOS = [
'23', 'POWER8 (architected), altivec supported',
],
'processor_cores': 1,
'processor_count': 24,
'processor_threads_per_core': 1,
'processor_vcpus': 24
},
},
{ |
def test_get_cpu_info_missing_arch(mocker):
module = mocker.Mock()
inst = linux.LinuxHardware(module)
# ARM will report incorrect processor count if architecture is not available
mocker.patch('os.path.exists', return_value=False)
mocker.patch('os.access', return_value=True)
for test in CPU_INFO... | def test_get_cpu_info_missing_arch(mocker):
module = mocker.Mock()
inst = linux.LinuxHardware(module)
# ARM and Power will report incorrect processor count if architecture is not available
mocker.patch('os.path.exists', return_value=False)
mocker.patch('os.access', return_value=True)
for test i... |
from pandas._libs.tslibs import (
timezones,
tzconversion,
)
from pandas.errors import PerformanceWarning
from pandas.core.dtypes.common import ( | from pandas._libs.tslibs import (
timezones,
tzconversion,
)
import pandas._libs.tslibs.frequencies as libfrequencies
from pandas.errors import PerformanceWarning
from pandas.core.dtypes.common import ( |
default 'raise'
"You must pass a freq argument as current index has none."
)
freq = get_period_alias(freq)
return PeriodArray._from_datetime64(self._data, freq, tz=self.tz)
| default 'raise'
"You must pass a freq argument as current index has none."
)
res = get_period_alias(freq)
# https://github.com/pandas-dev/pandas/issues/33358
if res is None:
base, stride = libfrequencies._base_and_stride(freq)
... |
import dateutil.tz
from dateutil.tz import tzlocal
import pytest | import warnings
import dateutil.tz
from dateutil.tz import tzlocal
import pytest |
class TestToPeriod:
with pytest.raises(ValueError, match=INVALID_FREQ_ERR_MSG):
date_range("01-Jan-2012", periods=8, freq="EOM")
def test_period_dt64_round_trip(self):
dti = date_range("1/1/2000", "1/7/2002", freq="B")
pi = dti.to_period() | class TestToPeriod:
with pytest.raises(ValueError, match=INVALID_FREQ_ERR_MSG):
date_range("01-Jan-2012", periods=8, freq="EOM")
def test_to_period_infer(self):
# https://github.com/pandas-dev/pandas/issues/33358
rng = date_range(
start="2019-12-22 06:40:00+00:00",
... |
import base64
import binascii
import hashlib
import importlib
from collections import OrderedDict
from django.conf import settings | import base64
import binascii
import hashlib
import importlib
import warnings
from collections import OrderedDict
from django.conf import settings |
def check_password(password, encoded, setter=None, preferred='default'):
preferred = get_hasher(preferred)
hasher = identify_hasher(encoded)
must_update = hasher.algorithm != preferred.algorithm
if not must_update:
must_update = preferred.must_update(encoded)
is_correct = hasher.verify(pass... | def check_password(password, encoded, setter=None, preferred='default'):
preferred = get_hasher(preferred)
hasher = identify_hasher(encoded)
hasher_changed = hasher.algorithm != preferred.algorithm
must_update = hasher_changed or preferred.must_update(encoded)
is_correct = hasher.verify(password, e... |
class BasePasswordHasher(object):
def must_update(self, encoded):
return False
class PBKDF2PasswordHasher(BasePasswordHasher):
""" | class BasePasswordHasher(object):
def must_update(self, encoded):
return False
def harden_runtime(self, password, encoded):
"""
Bridge the runtime gap between the work factor supplied in `encoded`
and the work factor suggested by this hasher.
Taking PBKDF2 as an example... |
class PBKDF2PasswordHasher(BasePasswordHasher):
algorithm, iterations, salt, hash = encoded.split('$', 3)
return int(iterations) != self.iterations
class PBKDF2SHA1PasswordHasher(PBKDF2PasswordHasher):
""" | class PBKDF2PasswordHasher(BasePasswordHasher):
algorithm, iterations, salt, hash = encoded.split('$', 3)
return int(iterations) != self.iterations
def harden_runtime(self, password, encoded):
algorithm, iterations, salt, hash = encoded.split('$', 3)
extra_iterations = self.iteratio... |
class BCryptSHA256PasswordHasher(BasePasswordHasher):
def verify(self, password, encoded):
algorithm, data = encoded.split('$', 1)
assert algorithm == self.algorithm
bcrypt = self._load_library()
# Hash the password prior to using bcrypt to prevent password truncation
# Se... | class BCryptSHA256PasswordHasher(BasePasswordHasher):
def verify(self, password, encoded):
algorithm, data = encoded.split('$', 1)
assert algorithm == self.algorithm
encoded_2 = self.encode(password, force_bytes(data))
return constant_time_compare(encoded, encoded_2)
def safe_su... |
class BCryptSHA256PasswordHasher(BasePasswordHasher):
algorithm, empty, algostr, rounds, data = encoded.split('$', 4)
return int(rounds) != self.rounds
class BCryptPasswordHasher(BCryptSHA256PasswordHasher):
""" | class BCryptSHA256PasswordHasher(BasePasswordHasher):
algorithm, empty, algostr, rounds, data = encoded.split('$', 4)
return int(rounds) != self.rounds
def harden_runtime(self, password, encoded):
_, data = encoded.split('$', 1)
salt = data[:29] # Length of the salt in bcrypt.
... |
class SHA1PasswordHasher(BasePasswordHasher):
(_('hash'), mask_hash(hash)),
])
class MD5PasswordHasher(BasePasswordHasher):
""" | class SHA1PasswordHasher(BasePasswordHasher):
(_('hash'), mask_hash(hash)),
])
def harden_runtime(self, password, encoded):
pass
class MD5PasswordHasher(BasePasswordHasher):
""" |
class MD5PasswordHasher(BasePasswordHasher):
(_('hash'), mask_hash(hash)),
])
class UnsaltedSHA1PasswordHasher(BasePasswordHasher):
""" | class MD5PasswordHasher(BasePasswordHasher):
(_('hash'), mask_hash(hash)),
])
def harden_runtime(self, password, encoded):
pass
class UnsaltedSHA1PasswordHasher(BasePasswordHasher):
""" |
class UnsaltedSHA1PasswordHasher(BasePasswordHasher):
(_('hash'), mask_hash(hash)),
])
class UnsaltedMD5PasswordHasher(BasePasswordHasher):
""" | class UnsaltedSHA1PasswordHasher(BasePasswordHasher):
(_('hash'), mask_hash(hash)),
])
def harden_runtime(self, password, encoded):
pass
class UnsaltedMD5PasswordHasher(BasePasswordHasher):
""" |
class UnsaltedMD5PasswordHasher(BasePasswordHasher):
(_('hash'), mask_hash(encoded, show=3)),
])
class CryptPasswordHasher(BasePasswordHasher):
""" | class UnsaltedMD5PasswordHasher(BasePasswordHasher):
(_('hash'), mask_hash(encoded, show=3)),
])
def harden_runtime(self, password, encoded):
pass
class CryptPasswordHasher(BasePasswordHasher):
""" |
class CryptPasswordHasher(BasePasswordHasher):
(_('salt'), salt),
(_('hash'), mask_hash(data, show=3)),
]) | class CryptPasswordHasher(BasePasswordHasher):
(_('salt'), salt),
(_('hash'), mask_hash(data, show=3)),
])
def harden_runtime(self, password, encoded):
pass |
from django.contrib.auth.hashers import (
check_password, get_hasher, identify_hasher, is_password_usable,
make_password,
)
from django.test import SimpleTestCase
from django.test.utils import override_settings
from django.utils import six
try:
import crypt | from django.contrib.auth.hashers import (
check_password, get_hasher, identify_hasher, is_password_usable,
make_password,
)
from django.test import SimpleTestCase, mock
from django.test.utils import override_settings
from django.utils import six
from django.utils.encoding import force_bytes
try:
import cry... |
class TestUtilsHashPass(SimpleTestCase):
finally:
hasher.rounds = old_rounds
def test_unusable(self):
encoded = make_password(None)
self.assertEqual(len(encoded), len(UNUSABLE_PASSWORD_PREFIX) + UNUSABLE_PASSWORD_SUFFIX_LENGTH) | class TestUtilsHashPass(SimpleTestCase):
finally:
hasher.rounds = old_rounds
@skipUnless(bcrypt, "bcrypt not installed")
def test_bcrypt_harden_runtime(self):
hasher = get_hasher('bcrypt')
self.assertEqual('bcrypt', hasher.algorithm)
with mock.patch.object(hasher, '... |
class TestUtilsHashPass(SimpleTestCase):
finally:
hasher.iterations = old_iterations
def test_pbkdf2_upgrade_new_hasher(self):
hasher = get_hasher('default')
self.assertEqual('pbkdf2_sha256', hasher.algorithm) | class TestUtilsHashPass(SimpleTestCase):
finally:
hasher.iterations = old_iterations
def test_pbkdf2_harden_runtime(self):
hasher = get_hasher('default')
self.assertEqual('pbkdf2_sha256', hasher.algorithm)
with mock.patch.object(hasher, 'iterations', 1):
enc... |
class TestUtilsHashPass(SimpleTestCase):
self.assertTrue(check_password('letmein', encoded, setter))
self.assertTrue(state['upgraded'])
def test_load_library_no_algorithm(self):
with self.assertRaises(ValueError) as e:
BasePasswordHasher()._load_library() | class TestUtilsHashPass(SimpleTestCase):
self.assertTrue(check_password('letmein', encoded, setter))
self.assertTrue(state['upgraded'])
def test_check_password_calls_harden_runtime(self):
hasher = get_hasher('default')
encoded = make_password('letmein')
with mock.pa... |
class Driver(object):
current_line = ""
current_column = 0
wait_for_nl = False
elif char == ' ':
current_column += 1
elif char == '\t':
current_column += 4
elif char == '\n':
#... | class Driver(object):
current_line = ""
current_column = 0
wait_for_nl = False
elif char in ' \t':
current_column += 1
elif char == '\n':
# unexpected empty line
current_column = 0 |
class BlackTestCase(unittest.TestCase):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, line_length=ll)
def test_report_verbose(self) -> None:
report = black.Report(verbose=True)
out_lines = [] | class BlackTestCase(unittest.TestCase):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, line_length=ll)
def test_comment_indentation(self) -> None:
contents_tab = "if 1:\n\tif 2:\n\t\tpass\n\t# comment\n\tpass\n"
contents_spc = "if 1:\n if 2:\n ... |
DEFAULT_FORCE_HANDLERS = get_config(p, DEFAULTS, 'force_handlers', 'ANSIBLE_F
DEFAULT_INVENTORY_IGNORE = get_config(p, DEFAULTS, 'inventory_ignore_extensions', 'ANSIBLE_INVENTORY_IGNORE', ["~", ".orig", ".bak", ".ini", ".cfg", ".retry", ".pyc", ".pyo"], value_type='list')
DEFAULT_VAR_COMPRESSION_LEVEL = get_config(... | DEFAULT_FORCE_HANDLERS = get_config(p, DEFAULTS, 'force_handlers', 'ANSIBLE_F
DEFAULT_INVENTORY_IGNORE = get_config(p, DEFAULTS, 'inventory_ignore_extensions', 'ANSIBLE_INVENTORY_IGNORE', ["~", ".orig", ".bak", ".ini", ".cfg", ".retry", ".pyc", ".pyo"], value_type='list')
DEFAULT_VAR_COMPRESSION_LEVEL = get_config(... |
class Templar:
loader=FileSystemLoader(self._basedir),
)
self.SINGLE_VAR = re.compile(r"^%s\s*(\w*)\s*%s$" % (self.environment.variable_start_string, self.environment.variable_end_string))
self.block_start = self.environment.block_start_string | class Templar:
loader=FileSystemLoader(self._basedir),
)
# the current rendering context under which the templar class is working
self.cur_context = None
self.SINGLE_VAR = re.compile(r"^%s\s*(\w*)\s*%s$" % (self.environment.variable_start_string, self.environment.variable_e... |
class Templar:
if instance is not None:
wantlist = kwargs.pop('wantlist', False)
from ansible.utils.listify import listify_lookup_plugin_terms
loop_terms = listify_lookup_plugin_terms(terms=args, templar=self, loader=self._loader, fail_on_undefined=True, convert_bare=False) | class Templar:
if instance is not None:
wantlist = kwargs.pop('wantlist', False)
allow_unsafe = kwargs.pop('allow_unsafe', C.DEFAULT_ALLOW_UNSAFE_LOOKUPS)
from ansible.utils.listify import listify_lookup_plugin_terms
loop_terms = listify_lookup_plugin_terms(term... |
class Templar:
raise AnsibleError("An unhandled exception occurred while running the lookup plugin '%s'. Error was a %s, original message: %s" % (name, type(e), e))
ran = None
if ran:
if wantlist:
ran = wrap_var(ran)
el... | class Templar:
raise AnsibleError("An unhandled exception occurred while running the lookup plugin '%s'. Error was a %s, original message: %s" % (name, type(e), e))
ran = None
if ran and not allow_unsafe:
from ansible.vars.unsafe_proxy import UnsafeProxy,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.