buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
def main():
module.fail_json(msg=missing_required_lib('python-ldap'),
exception=LDAP_IMP_ERR)
state = module.params['state']
# Check if objectClass is present when needed | def main():
module.fail_json(msg=missing_required_lib('python-ldap'),
exception=LDAP_IMP_ERR)
# For Ansible-2.9.x and below, allow the params module parameter with a warning
if LooseVersion(module.ansible_version) < LooseVersion('2.10'):
if module.params['params']:
... |
def main():
isinstance(module.params['objectClass'], list))):
module.fail_json(msg="objectClass must be either a string or a list.")
# Update module parameters with user's parameters if defined
if 'params' in module.params and isinstance(module.params['params'], dict):
for key, ... | def main():
isinstance(module.params['objectClass'], list))):
module.fail_json(msg="objectClass must be either a string or a list.")
# Instantiate the LdapEntry object
ldap = LdapEntry(module)
|
class Sanic:
"Endpoint with name `{}` was not found".format(view_name)
)
if view_name == "static" or view_name.endswith(".static"):
filename = kwargs.pop("filename", None)
# it's static folder | class Sanic:
"Endpoint with name `{}` was not found".format(view_name)
)
# If the route has host defined, split that off
# TODO: Retain netloc and path separately in Route objects
host = uri.find("/")
if host > 0:
host, uri = uri[:host], uri[host:... |
class Sanic:
netloc = kwargs.pop("_server", None)
if netloc is None and external:
netloc = self.config.get("SERVER_NAME", "")
if external:
if not scheme: | class Sanic:
netloc = kwargs.pop("_server", None)
if netloc is None and external:
netloc = host or self.config.get("SERVER_NAME", "")
if external:
if not scheme: |
def read_user_choice(var_name, options):
))
user_choice = click.prompt(
prompt, type=click.Choice(choices), default=default
)
return choice_map[user_choice]
| def read_user_choice(var_name, options):
))
user_choice = click.prompt(
prompt, type=click.Choice(choices), default=default, show_choices=False
)
return choice_map[user_choice]
|
def test_click_invocation(mocker, user_choice, expected_value):
prompt.assert_called_once_with(
EXPECTED_PROMPT,
type=click.Choice(OPTIONS),
default='1'
)
| def test_click_invocation(mocker, user_choice, expected_value):
prompt.assert_called_once_with(
EXPECTED_PROMPT,
type=click.Choice(OPTIONS),
default='1',
show_choices=False
)
|
else:
from twisted.internet import defer, reactor, ssl
logger = logging.getLogger(__name__)
| else:
from twisted.internet import defer, reactor, ssl
from .utils.misc import arg_to_iter
logger = logging.getLogger(__name__)
|
class MailSender(object):
msg = MIMEMultipart()
else:
msg = MIMENonMultipart(*mimetype.split('/', 1))
msg['From'] = self.mailfrom
msg['To'] = COMMASPACE.join(to)
msg['Date'] = formatdate(localtime=True) | class MailSender(object):
msg = MIMEMultipart()
else:
msg = MIMENonMultipart(*mimetype.split('/', 1))
to = list(arg_to_iter(to))
cc = list(arg_to_iter(cc))
msg['From'] = self.mailfrom
msg['To'] = COMMASPACE.join(to)
msg['Date'] = formatdate(local... |
class MailSenderTest(unittest.TestCase):
def test_send(self):
mailsender = MailSender(debug=True)
mailsender.send(to=['test@scrapy.org'], subject='subject', body='body', _callback=self._catch_mail_sent)
assert self.catched_msg
| class MailSenderTest(unittest.TestCase):
def test_send(self):
mailsender = MailSender(debug=True)
mailsender.send(to=['test@scrapy.org'], subject='subject', body='body',
_callback=self._catch_mail_sent)
assert self.catched_msg
|
class MailSenderTest(unittest.TestCase):
self.assertEqual(msg.get_payload(), 'body')
self.assertEqual(msg.get('Content-Type'), 'text/plain')
def test_send_html(self):
mailsender = MailSender(debug=True)
mailsender.send(to=['test@scrapy.org'], subject='subject', body='<p>body</p>', m... | class MailSenderTest(unittest.TestCase):
self.assertEqual(msg.get_payload(), 'body')
self.assertEqual(msg.get('Content-Type'), 'text/plain')
def test_send_single_values_to_and_cc(self):
mailsender = MailSender(debug=True)
mailsender.send(to='test@scrapy.org', subject='subject', body... |
class MailSenderTest(unittest.TestCase):
mailsender = MailSender(debug=True)
mailsender.send(to=['test@scrapy.org'], subject=subject, body=body,
attachs=attachs, charset='utf-8', _callback=self._catch_mail_sent)
assert self.catched_msg
self.assertEqual(self.catc... | class MailSenderTest(unittest.TestCase):
mailsender = MailSender(debug=True)
mailsender.send(to=['test@scrapy.org'], subject=subject, body=body,
attachs=attachs, charset='utf-8',
_callback=self._catch_mail_sent)
assert self.catched_msg
se... |
class MailSenderTest(unittest.TestCase):
msg = self.catched_msg['msg']
self.assertEqual(msg['subject'], subject)
self.assertEqual(msg.get_charset(), Charset('utf-8'))
self.assertEqual(msg.get('Content-Type'), 'multipart/mixed; charset="utf-8"')
payload = msg.get_payload()
... | class MailSenderTest(unittest.TestCase):
msg = self.catched_msg['msg']
self.assertEqual(msg['subject'], subject)
self.assertEqual(msg.get_charset(), Charset('utf-8'))
self.assertEqual(msg.get('Content-Type'),
'multipart/mixed; charset="utf-8"')
payload =... |
class OffsiteMiddleware(object):
if not allowed_domains:
return re.compile('') # allow all by default
url_pattern = re.compile("^https?://.*$")
for domain in allowed_domains:
if url_pattern.match(domain):
message = ("allowed_domains accepts only domains, ... | class OffsiteMiddleware(object):
if not allowed_domains:
return re.compile('') # allow all by default
url_pattern = re.compile("^https?://.*$")
domains = []
for domain in allowed_domains:
if domain is None:
continue
elif url_pattern.ma... |
class TestOffsiteMiddleware2(TestOffsiteMiddleware):
class TestOffsiteMiddleware3(TestOffsiteMiddleware2):
def _get_spider(self):
return Spider('foo')
class TestOffsiteMiddleware4(TestOffsiteMiddleware3):
def _get_spider(self):
bad_hostname = urlparse('http:////scrapytest.org').hostname
... | class TestOffsiteMiddleware2(TestOffsiteMiddleware):
class TestOffsiteMiddleware3(TestOffsiteMiddleware2):
def _get_spiderargs(self):
return dict(name='foo')
class TestOffsiteMiddleware4(TestOffsiteMiddleware3):
def _get_spiderargs(self):
bad_hostname = urlparse('http:////scrapytest.org').h... |
class AsyncioServer:
task = asyncio.ensure_future(coro, loop=self.loop)
return task
def __await__(self):
"""Starts the asyncio server, returns AsyncServerCoro"""
task = asyncio.ensure_future(self.serve_coro) | class AsyncioServer:
task = asyncio.ensure_future(coro, loop=self.loop)
return task
def start_serving(self):
if self.server:
try:
return self.server.start_serving()
except AttributeError:
raise NotImplementedError(
... |
def test_create_asyncio_server(app):
@pytest.mark.skipif(
sys.version_info < (3, 7), reason="requires python3.7 or higher"
)
def test_asyncio_server_start_serving(app):
if not uvloop_installed():
loop = asyncio.get_event_loop()
asyncio_srv_coro = app.create_server( | def test_create_asyncio_server(app):
@pytest.mark.skipif(
sys.version_info < (3, 7), reason="requires python3.7 or higher"
)
def test_asyncio_server_no_start_serving(app):
if not uvloop_installed():
loop = asyncio.get_event_loop()
asyncio_srv_coro = app.create_server( |
def test_asyncio_server_start_serving(app):
srv = loop.run_until_complete(asyncio_srv_coro)
assert srv.is_serving() is False
def test_app_loop_not_running(app):
with pytest.raises(SanicException) as excinfo: | def test_asyncio_server_start_serving(app):
srv = loop.run_until_complete(asyncio_srv_coro)
assert srv.is_serving() is False
@pytest.mark.skipif(
sys.version_info < (3, 7), reason="requires python3.7 or higher"
)
def test_asyncio_server_start_serving(app):
if not uvloop_installed():
loo... |
class BarPlot(MPLPlot):
def _decorate_ticks(self, ax, name, ticklabels, start_edge, end_edge):
ax.set_xlim((start_edge, end_edge))
ax.set_xticks(self.tick_pos)
ax.set_xticklabels(ticklabels)
if name is not None and self.use_index:
ax.set_xlabel(name)
| class BarPlot(MPLPlot):
def _decorate_ticks(self, ax, name, ticklabels, start_edge, end_edge):
ax.set_xlim((start_edge, end_edge))
if self.xticks is not None:
ax.set_xticks(np.array(self.xticks))
else:
ax.set_xticks(self.tick_pos)
ax.set_xticklabels(tick... |
class TestSeriesPlots(TestPlotBase):
exp = ["P{i:02d}".format(i=i) for i in [0, 3, 5, 9]]
self._check_text_labels(ax.get_xticklabels(), exp)
def test_custom_business_day_freq(self):
# GH7222
from pandas.tseries.offsets import CustomBusinessDay | class TestSeriesPlots(TestPlotBase):
exp = ["P{i:02d}".format(i=i) for i in [0, 3, 5, 9]]
self._check_text_labels(ax.get_xticklabels(), exp)
def test_xtick_barPlot(self):
# GH28172
s = pd.Series(range(10), index=["P{i:02d}".format(i=i) for i in range(10)])
ax = s.plot.bar(xt... |
def format_file_in_place(
with open(src, "w", encoding=src_buffer.encoding) as f:
f.write(dst_contents)
elif write_back == write_back.DIFF:
src_name = f"{src.name} (original)"
dst_name = f"{src.name} (formatted)"
diff_contents = diff(src_contents, dst_contents, src_name... | def format_file_in_place(
with open(src, "w", encoding=src_buffer.encoding) as f:
f.write(dst_contents)
elif write_back == write_back.DIFF:
src_name = f"{src} (original)"
dst_name = f"{src} (formatted)"
diff_contents = diff(src_contents, dst_contents, src_name, dst_name... |
class BlackTestCase(unittest.TestCase):
self.assertTrue(ff(tmp_file, write_back=black.WriteBack.DIFF))
sys.stdout.seek(0)
actual = sys.stdout.read()
actual = actual.replace(tmp_file.name, "<stdin>")
finally:
sys.stdout = hold_stdout
os.unli... | class BlackTestCase(unittest.TestCase):
self.assertTrue(ff(tmp_file, write_back=black.WriteBack.DIFF))
sys.stdout.seek(0)
actual = sys.stdout.read()
actual = actual.replace(str(tmp_file), "<stdin>")
finally:
sys.stdout = hold_stdout
os.unli... |
class DatabaseFeatures(BaseDatabaseFeatures):
only_supports_unbounded_with_preceding_and_following = True
supports_aggregate_filter_clause = True
supported_explain_formats = {"JSON", "TEXT", "XML", "YAML"}
validates_explain_options = False # A query will error on invalid options.
supports_deferrabl... | class DatabaseFeatures(BaseDatabaseFeatures):
only_supports_unbounded_with_preceding_and_following = True
supports_aggregate_filter_clause = True
supported_explain_formats = {"JSON", "TEXT", "XML", "YAML"}
supports_deferrable_unique_constraints = True
has_json_operators = True
json_key_contains_... |
from django.db.models.constants import OnConflict
class DatabaseOperations(BaseDatabaseOperations):
cast_char_field_without_max_length = "varchar"
explain_prefix = "EXPLAIN"
cast_data_types = {
"AutoField": "integer",
"BigAutoField": "bigint", | from django.db.models.constants import OnConflict
class DatabaseOperations(BaseDatabaseOperations):
cast_char_field_without_max_length = "varchar"
explain_prefix = "EXPLAIN"
explain_options = frozenset(
[
"ANALYZE",
"BUFFERS",
"COSTS",
"SETTINGS",
... |
class DatabaseOperations(BaseDatabaseOperations):
return super().subtract_temporals(internal_type, lhs, rhs)
def explain_query_prefix(self, format=None, **options):
prefix = super().explain_query_prefix(format)
extra = {}
if format:
extra["FORMAT"] = format
if op... | class DatabaseOperations(BaseDatabaseOperations):
return super().subtract_temporals(internal_type, lhs, rhs)
def explain_query_prefix(self, format=None, **options):
extra = {}
# Normalize options.
if options:
options = {
name.upper(): "true" if value else... |
__all__ = ["Query", "RawQuery"]
# SQL comments are forbidden in column aliases.
FORBIDDEN_ALIAS_PATTERN = _lazy_re_compile(r"['`\"\]\[;\s]|--|/\*|\*/")
def get_field_names_from_opts(opts):
if opts is None: | __all__ = ["Query", "RawQuery"]
# SQL comments are forbidden in column aliases.
FORBIDDEN_ALIAS_PATTERN = _lazy_re_compile(r"['`\"\]\[;\s]|--|/\*|\*/")
# Inspired from
# https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS
EXPLAIN_OPTIONS_PATTERN = _lazy_re_compile(r"[\w\-]+")
def g... |
class Query(BaseExpression):
def explain(self, using, format=None, **options):
q = self.clone()
q.explain_info = ExplainInfo(format, options)
compiler = q.get_compiler(using=using)
return "\n".join(compiler.explain_query()) | class Query(BaseExpression):
def explain(self, using, format=None, **options):
q = self.clone()
for option_name in options:
if (
not EXPLAIN_OPTIONS_PATTERN.fullmatch(option_name)
or "--" in option_name
):
raise ValueError(f"In... |
class ExplainTests(TestCase):
@skipUnlessDBFeature("validates_explain_options")
def test_unknown_options(self):
with self.assertRaisesMessage(ValueError, "Unknown options: test, test2"):
Tag.objects.explain(test=1, test2=1)
def test_unknown_format(self):
msg = "DOES NOT EXIST i... | class ExplainTests(TestCase):
@skipUnlessDBFeature("validates_explain_options")
def test_unknown_options(self):
with self.assertRaisesMessage(ValueError, "Unknown options: TEST, TEST2"):
Tag.objects.explain(**{"TEST": 1, "TEST2": 1})
def test_unknown_format(self):
msg = "DOES N... |
class ExplainTests(TestCase):
option = "{} {}".format(name.upper(), "true" if value else "false")
self.assertIn(option, captured_queries[0]["sql"])
@unittest.skipUnless(connection.vendor == "mysql", "MySQL specific")
def test_mysql_text_to_traditional(self):
# En... | class ExplainTests(TestCase):
option = "{} {}".format(name.upper(), "true" if value else "false")
self.assertIn(option, captured_queries[0]["sql"])
def test_option_sql_injection(self):
qs = Tag.objects.filter(name="test")
options = {"SUMMARY true) SELECT 1; -... |
class _AxesBase(martist.Artist):
left, right = sorted([left, right], reverse=bool(reverse))
self._viewLim.intervalx = (left, right)
if auto is not None:
self._autoscaleXon = bool(auto)
| class _AxesBase(martist.Artist):
left, right = sorted([left, right], reverse=bool(reverse))
self._viewLim.intervalx = (left, right)
# Mark viewlims as no longer stale without triggering an autoscale.
for ax in self._shared_x_axes.get_siblings(self):
ax._stale_viewlim_x = Fal... |
class _AxesBase(martist.Artist):
bottom, top = sorted([bottom, top], reverse=bool(reverse))
self._viewLim.intervaly = (bottom, top)
if auto is not None:
self._autoscaleYon = bool(auto)
| class _AxesBase(martist.Artist):
bottom, top = sorted([bottom, top], reverse=bool(reverse))
self._viewLim.intervaly = (bottom, top)
# Mark viewlims as no longer stale without triggering an autoscale.
for ax in self._shared_y_axes.get_siblings(self):
ax._stale_viewlim_y = Fal... |
def test_ytickcolor_is_not_markercolor():
assert tick.tick1line.get_markeredgecolor() != 'white'
@check_figures_equal(extensions=["png"])
def test_polar_interpolation_steps_variable_r(fig_test, fig_ref):
l, = fig_test.add_subplot(projection="polar").plot([0, np.pi/2], [1, 2]) | def test_ytickcolor_is_not_markercolor():
assert tick.tick1line.get_markeredgecolor() != 'white'
@pytest.mark.parametrize('auto', (True, False, None))
def test_unautoscaley(auto):
fig, ax = plt.subplots()
x = np.arange(100)
y = np.linspace(-.1, .1, 100)
ax.scatter(x, y)
post_auto = ax.get... |
class StringMethods(NoNewAttributesMixin):
_doc_args["istitle"] = dict(type="titlecase", method="istitle")
_doc_args["isnumeric"] = dict(type="numeric", method="isnumeric")
_doc_args["isdecimal"] = dict(type="decimal", method="isdecimal")
isalnum = _noarg_wrapper(
lambda x: x.isalnum(),
... | class StringMethods(NoNewAttributesMixin):
_doc_args["istitle"] = dict(type="titlecase", method="istitle")
_doc_args["isnumeric"] = dict(type="numeric", method="isnumeric")
_doc_args["isdecimal"] = dict(type="decimal", method="isdecimal")
# force _noarg_wrapper return type with dtype=bool (GH 29624)
... |
class TestStringMethods:
tm.assert_series_equal(empty_str, empty.str.get(0))
tm.assert_series_equal(empty_str, empty_bytes.str.decode("ascii"))
tm.assert_series_equal(empty_bytes, empty.str.encode("ascii"))
tm.assert_series_equal(empty_str, empty.str.isalnum())
tm.assert_series_e... | class TestStringMethods:
tm.assert_series_equal(empty_str, empty.str.get(0))
tm.assert_series_equal(empty_str, empty_bytes.str.decode("ascii"))
tm.assert_series_equal(empty_bytes, empty.str.encode("ascii"))
# ismethods should always return boolean (GH 29624)
tm.assert_series_equa... |
HOST = test_support.HOST
CERTFILE = None
SVN_PYTHON_ORG_ROOT_CERT = None
def handle_error(prefix):
exc_format = ' '.join(traceback.format_exception(*sys.exc_info())) | HOST = test_support.HOST
CERTFILE = None
SVN_PYTHON_ORG_ROOT_CERT = None
NULLBYTECERT = None
def handle_error(prefix):
exc_format = ' '.join(traceback.format_exception(*sys.exc_info())) |
def test_parse_cert(self):
if test_support.verbose:
sys.stdout.write("\n" + pprint.pformat(p) + "\n")
def test_DER_to_PEM(self):
with open(SVN_PYTHON_ORG_ROOT_CERT, 'r') as f:
pem = f.read() | def test_parse_cert(self):
if test_support.verbose:
sys.stdout.write("\n" + pprint.pformat(p) + "\n")
def test_parse_cert_CVE_2013_4073(self):
p = ssl._ssl._test_decode_cert(NULLBYTECERT)
if test_support.verbose:
sys.stdout.write("\n" + pprint.pformat(p) + "\n")
... |
def test_main(verbose=False):
if skip_expected:
raise test_support.TestSkipped("No SSL support")
global CERTFILE, SVN_PYTHON_ORG_ROOT_CERT
CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir,
"keycert.pem")
SVN_PYTHON_ORG_ROOT_CERT = os.path.join(
... | def test_main(verbose=False):
if skip_expected:
raise test_support.TestSkipped("No SSL support")
global CERTFILE, SVN_PYTHON_ORG_ROOT_CERT, NULLBYTECERT
CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir,
"keycert.pem")
SVN_PYTHON_ORG_ROOT_CERT = os.path.... |
def configure():
register_cli_str('pydev-debug-host', default=None)
register_cli_int('pydev-debug-port', default=None)
register_str('admin_token', default='ADMIN')
register_str('bind_host', default='0.0.0.0')
register_int('compute_port', default=8774)
register_int('admin_port', default=35357) | def configure():
register_cli_str('pydev-debug-host', default=None)
register_cli_int('pydev-debug-port', default=None)
register_str('admin_token', secret=True, default='ADMIN')
register_str('bind_host', default='0.0.0.0')
register_int('compute_port', default=8774)
register_int('admin_port', def... |
def configure():
# ldap
register_str('url', group='ldap', default='ldap://localhost')
register_str('user', group='ldap', default=None)
register_str('password', group='ldap', default=None)
register_str('suffix', group='ldap', default='cn=example,cn=com')
register_bool('use_dumb_member', group='ld... | def configure():
# ldap
register_str('url', group='ldap', default='ldap://localhost')
register_str('user', group='ldap', default=None)
register_str('password', group='ldap', secret=True, default=None)
register_str('suffix', group='ldap', default='cn=example,cn=com')
register_bool('use_dumb_membe... |
class DataFrame(NDFrame):
other = other._convert(datetime=True, timedelta=True)
if not self.columns.equals(combined_columns):
self = self.reindex(columns=combined_columns)
elif isinstance(other, list) and not isinstance(other[0], DataFrame):
other = DataFrame(... | class DataFrame(NDFrame):
other = other._convert(datetime=True, timedelta=True)
if not self.columns.equals(combined_columns):
self = self.reindex(columns=combined_columns)
elif isinstance(other, list):
if not other:
pass
elif not is... |
class TestDataFrameConcatCommon:
)
tm.assert_frame_equal(results, expected)
def test_append_series_dict(self):
df = DataFrame(np.random.randn(5, 4), columns=["foo", "bar", "baz", "qux"])
| class TestDataFrameConcatCommon:
)
tm.assert_frame_equal(results, expected)
def test_append_empty_list(self):
# GH 28769
df = DataFrame()
result = df.append([])
expected = df
tm.assert_frame_equal(result, expected)
assert result is not df
df ... |
def ctc_batch_cost(y_true, y_pred, input_length, label_length):
Tensor with shape (samples,1) containing the
CTC loss of each element.
"""
label_length = tf.to_int32(tf.squeeze(label_length))
input_length = tf.to_int32(tf.squeeze(input_length))
sparse_labels = tf.to_int32(ctc_label_d... | def ctc_batch_cost(y_true, y_pred, input_length, label_length):
Tensor with shape (samples,1) containing the
CTC loss of each element.
"""
label_length = tf.to_int32(tf.squeeze(label_length, axis=-1))
input_length = tf.to_int32(tf.squeeze(input_length, axis=-1))
sparse_labels = tf.to... |
class TestBackend(object):
res = K.eval(K.ctc_batch_cost(k_labels, k_inputs, k_input_lens, k_label_lens))
assert_allclose(res[0, :] if K.backend() == 'theano' else res[:, 0], ref, atol=1e-05)
'''only tensorflow tested, need special handle'''
def test_ctc_decode_greedy(self): | class TestBackend(object):
res = K.eval(K.ctc_batch_cost(k_labels, k_inputs, k_input_lens, k_label_lens))
assert_allclose(res[0, :] if K.backend() == 'theano' else res[:, 0], ref, atol=1e-05)
# test when batch_size = 1, that is, one sample only
# get only first sample from above test ca... |
class TestUtil(unittest.TestCase):
unified_strdate('2/2/2015 6:47:40 PM', day_first=False),
'20150202')
self.assertEqual(unified_strdate('25-09-2014'), '20140925')
def test_find_xpath_attr(self):
testxml = '''<root> | class TestUtil(unittest.TestCase):
unified_strdate('2/2/2015 6:47:40 PM', day_first=False),
'20150202')
self.assertEqual(unified_strdate('25-09-2014'), '20140925')
self.assertEqual(unified_strdate('UNKNOWN DATE FORMAT'), None)
def test_find_xpath_attr(self):
testxml ... |
def unified_strdate(date_str, day_first=True):
timetuple = email.utils.parsedate_tz(date_str)
if timetuple:
upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
return compat_str(upload_date)
def determine_ext(url, default_ext='unknown_video'): | def unified_strdate(date_str, day_first=True):
timetuple = email.utils.parsedate_tz(date_str)
if timetuple:
upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
if upload_date is not None:
return compat_str(upload_date)
def determine_ext(url, default_ext='unknown_... |
def url(tgpath, tgparams=None, **kwargs):
'''
if not isinstance(tgpath, six.string_types):
tgpath = '/'.join(list(tgpath))
if tgpath.startswith('/'):
webpath = (config.get('server.webpath') or '').rstrip('/')
if tg_util.request_available(): | def url(tgpath, tgparams=None, **kwargs):
'''
if not isinstance(tgpath, six.string_types):
tgpath = '/'.join(list(tgpath))
if not tgpath.startswith('/'):
# Do not allow the url() function to be used for external urls.
# This function is primarily used in redirect() calls, so this pre... |
from itertools import cycle as itertools_cycle, groupby
from django.conf import settings
from django.utils import timezone
from django.utils.deprecation import RemovedInDjango40Warning
from django.utils.html import conditional_escape, format_html
from django.utils.lorem_ipsum import paragraphs, words
from django.utils.... | from itertools import cycle as itertools_cycle, groupby
from django.conf import settings
from django.utils import timezone
from django.utils.deprecation import RemovedInDjango40Warning
from django.utils.html import conditional_escape, escape, format_html
from django.utils.lorem_ipsum import paragraphs, words
from djang... |
class CycleNode(Node):
class DebugNode(Node):
def render(self, context):
from pprint import pformat
output = [pformat(val) for val in context]
output.append('\n\n')
output.append(pformat(sys.modules))
return ''.join(output)
| class CycleNode(Node):
class DebugNode(Node):
def render(self, context):
if not settings.DEBUG:
return ''
from pprint import pformat
output = [escape(pformat(val)) for val in context]
output.append('\n\n')
output.append(escape(pformat(sys.modules)))
retu... |
import sys
from django.contrib.auth.models import Group
from django.template import Context, Engine, TemplateSyntaxError
from django.template.base import UNKNOWN_SOURCE
from django.test import SimpleTestCase, override_settings | import sys
from django.template import Context, Engine, TemplateSyntaxError
from django.template.base import UNKNOWN_SOURCE
from django.test import SimpleTestCase, override_settings |
class TemplateTests(SimpleTestCase):
with self.assertRaises(NoReverseMatch):
t.render(Context())
def test_debug_tag_non_ascii(self):
"""
#23060 -- Test non-ASCII model representation in debug output.
"""
group = Group(name="清風")
c1 = Context({"objs": [gro... | class TemplateTests(SimpleTestCase):
with self.assertRaises(NoReverseMatch):
t.render(Context())
def test_extends_generic_template(self):
"""
#24338 -- Allow extending django.template.backends.django.Template |
from keystone import exception
from keystone import policy
from keystone import token
from keystone.common import manager
from keystone.common import wsgi
CONF = config.CONF
class Manager(manager.Manager):
"""Default pivot point for the Identity backend. | from keystone import exception
from keystone import policy
from keystone import token
from keystone.common import logging
from keystone.common import manager
from keystone.common import wsgi
CONF = config.CONF
LOG = logging.getLogger(__name__)
class Manager(manager.Manager):
"""Default pivot point for the Iden... |
def set_user_enabled(self, context, user_id, user):
return self.update_user(context, user_id, user)
def set_user_password(self, context, user_id, user):
return self.update_user(context, user_id, user)
def update_user_tenant(self, context, user_id, user):
"""Update the default tenant.""... | def set_user_enabled(self, context, user_id, user):
return self.update_user(context, user_id, user)
def set_user_password(self, context, user_id, user):
user_ref = self.update_user(context, user_id, user)
try:
for token_id in self.token_api.list_tokens(context, user_id):
... |
def delete_token(self, token_id):
return self.db.delete('token-%s' % token_id)
except KeyError:
raise exception.TokenNotFound(token_id=token_id) | def delete_token(self, token_id):
return self.db.delete('token-%s' % token_id)
except KeyError:
raise exception.TokenNotFound(token_id=token_id)
def list_tokens(self, user_id):
tokens = []
now = datetime.datetime.utcnow()
for token, user_ref in self.db.items(... |
def delete_token(self, token_id):
with session.begin():
session.delete(token_ref)
session.flush() | def delete_token(self, token_id):
with session.begin():
session.delete(token_ref)
session.flush()
def list_tokens(self, user_id):
session = self.get_session()
tokens = []
now = datetime.datetime.utcnow()
for token_ref in session.query(TokenModel)\
... |
def delete_token(self, token_id):
"""
raise exception.NotImplemented()
def _get_default_expire_time(self):
"""Determine when a token should expire based on the config.
| def delete_token(self, token_id):
"""
raise exception.NotImplemented()
def list_tokens(self, user_id):
"""Returns a list of current token_id's for a user
:param user_id: identity of the user
:type user_id: string
:returns: list of token_id's
"""
rai... |
def test_invalid_user_password(self):
username='blah',
password='blah')
def test_user_create_update_delete(self):
from keystoneclient import exceptions as client_exceptions
| def test_invalid_user_password(self):
username='blah',
password='blah')
def test_change_password_invalidates_token(self):
from keystoneclient import exceptions as client_exceptions
client = self.get_client(admin=True)
username = uuid.uui... |
class tqdm(Comparable):
if disable is None and hasattr(file, "isatty") and not file.isatty():
disable = True
if disable:
self.iterable = iterable
self.disable = disable
self.pos = self._get_free_pos(self)
self._instances.remove(self)
... | class tqdm(Comparable):
if disable is None and hasattr(file, "isatty") and not file.isatty():
disable = True
if total is None and iterable is not None:
try:
total = len(iterable)
except (TypeError, AttributeError):
total = None
... |
class tqdm(Comparable):
else TqdmKeyError("Unknown argument(s): " + str(kwargs)))
# Preprocess the arguments
if total is None and iterable is not None:
try:
total = len(iterable)
except (TypeError, AttributeError):
total = None
... | class tqdm(Comparable):
else TqdmKeyError("Unknown argument(s): " + str(kwargs)))
# Preprocess the arguments
if ((ncols is None) and (file in (sys.stderr, sys.stdout))) or \
dynamic_ncols: # pragma: no cover
if dynamic_ncols: |
def test_threading():
# TODO: test interleaved output #445
@with_setup(pretest, posttest)
def test_autonotebook():
"""Test autonotebook fallback""" | def test_threading():
# TODO: test interleaved output #445
@with_setup(pretest, posttest)
def test_bool():
"""Test boolean cast"""
def internal(our_file, disable):
with tqdm(total=10, file=our_file, disable=disable) as t:
assert t
with tqdm(total=0, file=our_file, disable=disab... |
setup(
author='Jeff Knupp',
tests_require=['pytest', 'pytest-cov', 'pytest-flask>=0.4.0'],
install_requires=[
'Flask>=0.10.1',
'Flask-SQLAlchemy>=1.0',
'SQLAlchemy==1.2.12',
'Flask-Admin>=1.0.9', | setup(
author='Jeff Knupp',
tests_require=['pytest', 'pytest-cov', 'pytest-flask>=0.4.0'],
install_requires=[
'Flask>=1.0.2',
'Flask-SQLAlchemy>=1.0',
'SQLAlchemy==1.2.12',
'Flask-Admin>=1.0.9', |
class DatabaseFeatures(BaseDatabaseFeatures):
supports_over_clause = True
supports_aggregate_filter_clause = True
supported_explain_formats = {'JSON', 'TEXT', 'XML', 'YAML'}
validates_explain_options = False # A query will error on invalid options.
@cached_property
def is_postgresql_9_5(self): | class DatabaseFeatures(BaseDatabaseFeatures):
supports_over_clause = True
supports_aggregate_filter_clause = True
supported_explain_formats = {'JSON', 'TEXT', 'XML', 'YAML'}
@cached_property
def is_postgresql_9_5(self): |
from django.db.backends.base.operations import BaseDatabaseOperations
class DatabaseOperations(BaseDatabaseOperations):
cast_char_field_without_max_length = 'varchar'
explain_prefix = 'EXPLAIN'
cast_data_types = {
'AutoField': 'integer',
'BigAutoField': 'bigint', | from django.db.backends.base.operations import BaseDatabaseOperations
class DatabaseOperations(BaseDatabaseOperations):
cast_char_field_without_max_length = 'varchar'
explain_prefix = 'EXPLAIN'
explain_options = frozenset(
[
"ANALYZE",
"BUFFERS",
"COSTS",
... |
class DatabaseOperations(BaseDatabaseOperations):
return start_, end_
def explain_query_prefix(self, format=None, **options):
prefix = super().explain_query_prefix(format)
extra = {}
if format:
extra['FORMAT'] = format
if options:
extra.update({
... | class DatabaseOperations(BaseDatabaseOperations):
return start_, end_
def explain_query_prefix(self, format=None, **options):
extra = {}
# Normalize options.
if options:
options = {
name.upper(): 'true' if value else 'false'
for name, valu... |
__all__ = ['Query', 'RawQuery']
# SQL comments are forbidden in column aliases.
FORBIDDEN_ALIAS_PATTERN = re.compile(r"['`\"\]\[;\s]|--|/\*|\*/")
def get_field_names_from_opts(opts):
return set(chain.from_iterable( | __all__ = ['Query', 'RawQuery']
# SQL comments are forbidden in column aliases.
FORBIDDEN_ALIAS_PATTERN = re.compile(r"['`\"\]\[;\s]|--|/\*|\*/")
# Inspired from
# https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS
EXPLAIN_OPTIONS_PATTERN = re.compile(r"[\w\-]+")
def get_field_nam... |
class Query:
def explain(self, using, format=None, **options):
q = self.clone()
q.explain_query = True
q.explain_format = format
q.explain_options = options | class Query:
def explain(self, using, format=None, **options):
q = self.clone()
for option_name in options:
if (
not EXPLAIN_OPTIONS_PATTERN.fullmatch(option_name) or
"--" in option_name
):
raise ValueError("Invalid option name... |
class ExplainTests(TestCase):
@skipUnlessDBFeature('validates_explain_options')
def test_unknown_options(self):
with self.assertRaisesMessage(ValueError, 'Unknown options: test, test2'):
Tag.objects.all().explain(test=1, test2=1)
def test_unknown_format(self):
msg = 'DOES NOT E... | class ExplainTests(TestCase):
@skipUnlessDBFeature('validates_explain_options')
def test_unknown_options(self):
with self.assertRaisesMessage(ValueError, "Unknown options: TEST, TEST2"):
Tag.objects.all().explain(**{"TEST": 1, "TEST2": 1})
def test_unknown_format(self):
msg = '... |
class ExplainTests(TestCase):
option = '{} {}'.format(name.upper(), 'true' if value else 'false')
self.assertIn(option, captured_queries[0]['sql'])
@unittest.skipUnless(connection.vendor == 'mysql', 'MySQL specific')
def test_mysql_text_to_traditional(self):
# In... | class ExplainTests(TestCase):
option = '{} {}'.format(name.upper(), 'true' if value else 'false')
self.assertIn(option, captured_queries[0]['sql'])
def test_option_sql_injection(self):
qs = Tag.objects.filter(name="test")
options = {"SUMMARY true) SELECT 1; -... |
from pandas.core.frame import DataFrame
from pandas.core.groupby import ops
from pandas.core.groupby.categorical import recode_for_groupby, recode_from_groupby
from pandas.core.indexes.api import CategoricalIndex, Index, MultiIndex
from pandas.core.series import Series
from pandas.io.formats.printing import pprint_thi... | from pandas.core.frame import DataFrame
from pandas.core.groupby import ops
from pandas.core.groupby.categorical import recode_for_groupby, recode_from_groupby
from pandas.core.indexes.api import CategoricalIndex, Index, MultiIndex
from pandas.core.indexes.base import InvalidIndexError
from pandas.core.series import Se... |
def get_grouper(
items = obj._data.items
try:
items.get_loc(key)
except (KeyError, TypeError):
# TypeError shows up here if we pass e.g. Int64Index
return False
| def get_grouper(
items = obj._data.items
try:
items.get_loc(key)
except (KeyError, TypeError, InvalidIndexError):
# TypeError shows up here if we pass e.g. Int64Index
return False
|
from pandas.core.arrays.datetimes import (
validate_tz_from_dtype,
)
import pandas.core.common as com
from pandas.core.indexes.base import Index, maybe_extract_name
from pandas.core.indexes.datetimelike import (
DatetimelikeDelegateMixin,
DatetimeTimedeltaMixin, | from pandas.core.arrays.datetimes import (
validate_tz_from_dtype,
)
import pandas.core.common as com
from pandas.core.indexes.base import Index, InvalidIndexError, maybe_extract_name
from pandas.core.indexes.datetimelike import (
DatetimelikeDelegateMixin,
DatetimeTimedeltaMixin, |
class DatetimeIndex(DatetimeTimedeltaMixin, DatetimeDelegateMixin):
Fast lookup of value from 1-dimensional ndarray. Only use this if you
know what you're doing
"""
if isinstance(key, (datetime, np.datetime64)):
return self.get_value_maybe_box(series, key) | class DatetimeIndex(DatetimeTimedeltaMixin, DatetimeDelegateMixin):
Fast lookup of value from 1-dimensional ndarray. Only use this if you
know what you're doing
"""
if not is_scalar(key):
raise InvalidIndexError(key)
if isinstance(key, (datetime, np.datetime64)):
... |
class DatetimeIndex(DatetimeTimedeltaMixin, DatetimeDelegateMixin):
-------
loc : int
"""
if is_valid_nat_for_dtype(key, self.dtype):
key = NaT
| class DatetimeIndex(DatetimeTimedeltaMixin, DatetimeDelegateMixin):
-------
loc : int
"""
if not is_scalar(key):
raise InvalidIndexError(key)
if is_valid_nat_for_dtype(key, self.dtype):
key = NaT
|
class MultiIndex(Index):
indexer = self._get_level_indexer(key, level=level)
new_index = maybe_mi_droplevels(indexer, [0], drop_level)
return indexer, new_index
except TypeError:
pass
if not any(isinstance(k, slice) for... | class MultiIndex(Index):
indexer = self._get_level_indexer(key, level=level)
new_index = maybe_mi_droplevels(indexer, [0], drop_level)
return indexer, new_index
except (TypeError, InvalidIndexError):
pass
if not any(isi... |
class Series(base.IndexOpsMixin, generic.NDFrame):
self[:] = value
else:
self.loc[key] = value
except TypeError as e:
if isinstance(key, tuple) and not isinstance(self.index, MultiIndex): | class Series(base.IndexOpsMixin, generic.NDFrame):
self[:] = value
else:
self.loc[key] = value
except InvalidIndexError:
# e.g. slice
self._set_with(key, value)
except TypeError as e:
if isinstance(key, tuple) and not isins... |
import pytz
import pandas as pd
from pandas import DatetimeIndex, Index, Timestamp, date_range, notna
import pandas._testing as tm
from pandas.tseries.offsets import BDay, CDay
| import pytz
import pandas as pd
from pandas import DatetimeIndex, Index, Timestamp, date_range, notna
import pandas._testing as tm
from pandas.core.indexes.base import InvalidIndexError
from pandas.tseries.offsets import BDay, CDay
|
class TestDatetimeIndex:
with pytest.raises(KeyError, match="'foobar'"):
idx.get_loc("foobar")
with pytest.raises(TypeError):
idx.get_loc(slice(2))
idx = pd.to_datetime(["2000-01-01", "2000-01-04"]) | class TestDatetimeIndex:
with pytest.raises(KeyError, match="'foobar'"):
idx.get_loc("foobar")
with pytest.raises(InvalidIndexError, match=r"slice\(None, 2, None\)"):
idx.get_loc(slice(2))
idx = pd.to_datetime(["2000-01-01", "2000-01-04"]) |
def aesEncrypt(data, key):
except ImportError:
from Crypto.Cipher import AES
def aesEncrypt(data, key):
cipher = AES.new(key)
data = data + (" " * (16 - (len(data) % 16)))
return cipher.encrypt(data)
def aesDecrypt(data, key):
cipher = AES.new(key)
return cipher.... | def aesEncrypt(data, key):
except ImportError:
from Crypto.Cipher import AES
from Crypto.Util import Counter
def aesEncrypt(data, key):
cipher = AES.new(key, AES.MODE_CTR,
counter=Counter.new(128, initial_value=0))
return cipher.encrypt(data)
def aesDecrypt(d... |
from .helper import on_ci
@pytest.mark.parametrize(
"test_file", ["Tests/images/crash_1.tif", "Tests/images/crash_2.tif"]
)
@pytest.mark.filterwarnings("ignore:Possibly corrupt EXIF data")
@pytest.mark.filterwarnings("ignore:Metadata warning") | from .helper import on_ci
@pytest.mark.parametrize(
"test_file",
[
"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")
@pytest.mark.filterwarnings("ignore:Metadata warni... |
from ..packages import six, rfc3986
from ..packages.rfc3986.exceptions import RFC3986Exception, ValidationError
from ..packages.rfc3986.validators import Validator
url_attrs = ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment'] | from ..packages import six, rfc3986
from ..packages.rfc3986.exceptions import RFC3986Exception, ValidationError
from ..packages.rfc3986.validators import Validator
from ..packages.rfc3986 import abnf_regexp, normalizers, compat, misc
url_attrs = ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment'] |
# Regex for detecting URLs with schemes. RFC 3986 Section 3.1
SCHEME_REGEX = re.compile(r"^(?:[a-zA-Z][a-zA-Z0-9+\-]*:|/)")
class Url(namedtuple('Url', url_attrs)):
""" | # Regex for detecting URLs with schemes. RFC 3986 Section 3.1
SCHEME_REGEX = re.compile(r"^(?:[a-zA-Z][a-zA-Z0-9+\-]*:|/)")
PATH_CHARS = abnf_regexp.UNRESERVED_CHARS_SET | abnf_regexp.SUB_DELIMITERS_SET | {':', '@', '/'}
QUERY_CHARS = FRAGMENT_CHARS = PATH_CHARS | {'?'}
class Url(namedtuple('Url', url_attrs)):
"... |
def split_first(s, delims):
return s[:min_idx], s[min_idx + 1:], min_delim
def parse_url(url):
"""
Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is | def split_first(s, delims):
return s[:min_idx], s[min_idx + 1:], min_delim
def _encode_invalid_chars(component, allowed_chars, encoding='utf-8'):
"""Percent-encodes a URI component without reapplying
onto an already percent-encoded component. Based on
rfc3986.normalizers.encode_component()
"""
... |
def parse_url(url):
return Url()
is_string = not isinstance(url, six.binary_type)
if not is_string:
url = url.decode("utf-8")
# RFC 3986 doesn't like URLs that have a host but don't start
# with a scheme and we support URLs like that so we need to | def parse_url(url):
return Url()
is_string = not isinstance(url, six.binary_type)
# RFC 3986 doesn't like URLs that have a host but don't start
# with a scheme and we support URLs like that so we need to |
def parse_url(url):
if not SCHEME_REGEX.search(url):
url = "//" + url
try:
iri_ref = rfc3986.IRIReference.from_string(url, encoding="utf-8")
except (ValueError, RFC3986Exception):
six.raise_from(LocationParseError(url), None)
def idna_encode(name):
if name and any([ord(... | def parse_url(url):
if not SCHEME_REGEX.search(url):
url = "//" + url
def idna_encode(name):
if name and any([ord(x) > 128 for x in name]):
try: |
def idna_encode(name):
raise LocationParseError(u"Name '%s' is not a valid IDNA label" % name)
return name
has_authority = iri_ref.authority is not None
uri_ref = iri_ref.encode(idna_encoder=idna_encode)
# rfc3986 strips the authority if it's invalid
if has_authority and uri_re... | def idna_encode(name):
raise LocationParseError(u"Name '%s' is not a valid IDNA label" % name)
return name
try:
split_iri = misc.IRI_MATCHER.match(compat.to_str(url)).groupdict()
iri_ref = rfc3986.IRIReference(
split_iri['scheme'], split_iri['authority'],
... |
def idna_encode(name):
*validator.COMPONENT_NAMES
).validate(uri_ref)
except ValidationError:
six.raise_from(LocationParseError(url), None)
# For the sake of backwards compatibility we put empty
# string values for path if there are any defined values | def idna_encode(name):
*validator.COMPONENT_NAMES
).validate(uri_ref)
except ValidationError:
return six.raise_from(LocationParseError(url), None)
# For the sake of backwards compatibility we put empty
# string values for path if there are any defined values |
def test_invalid_host(self, location):
'http://user\\@google.com',
'http://google\\.com',
'user\\@google.com',
'http://google.com#fragment#',
'http://user@user@google.com/',
])
def test_invalid_url(self, url):
with pytest.raises(LocationParseError): | def test_invalid_host(self, location):
'http://user\\@google.com',
'http://google\\.com',
'user\\@google.com',
'http://user@user@google.com/',
# Invalid IDNA labels
u'http://\uD7FF.com',
u'http://❤️',
# Unicode surrogates
u'http://\uD800.com',
... |
def test_invalid_url(self, url):
('HTTPS://Example.Com/?Key=Value', 'https://example.com/?Key=Value'),
('Https://Example.Com/#Fragment', 'https://example.com/#Fragment'),
('[::Ff%etH0%Ff]/%ab%Af', '[::ff%25etH0%Ff]/%AB%AF'),
])
def test_parse_url_normalization(self, url, expected_normali... | def test_invalid_url(self, url):
('HTTPS://Example.Com/?Key=Value', 'https://example.com/?Key=Value'),
('Https://Example.Com/#Fragment', 'https://example.com/#Fragment'),
('[::Ff%etH0%Ff]/%ab%Af', '[::ff%25etH0%Ff]/%AB%AF'),
# Invalid characters for the query/fragment getting encoded
... |
def test_parse_url_normalization(self, url, expected_normalized_url):
# Uppercase IRI
(u'http://Königsgäßchen.de/straße',
Url('http', host='xn--knigsgchen-b4a3dun.de', path='/stra%C3%9Fe'))
]
@pytest.mark.parametrize( | def test_parse_url_normalization(self, url, expected_normalized_url):
# Uppercase IRI
(u'http://Königsgäßchen.de/straße',
Url('http', host='xn--knigsgchen-b4a3dun.de', path='/stra%C3%9Fe')),
# Unicode Surrogates
(u'http://google.com/\uD800', Url('http', host='google.com', path... |
def do_client_test(options, conn):
For example to delete the client XYZ in the realm ABC:
{prog_name} -s http://example.com:8080 -p password client delete -r ABC -c XYZ
where 'client' is the noun, 'delete' is the verb and -r ABC -c XYZ are
arguments to the delete action. | def do_client_test(options, conn):
For example to delete the client XYZ in the realm ABC:
echo password | {prog_name} -s http://example.com:8080 -P - client delete -r ABC -c XYZ
where 'client' is the noun, 'delete' is the verb and -r ABC -c XYZ are
arguments to the delete action. |
def main():
default='admin',
help='admin user name (default: admin)')
group.add_argument('-p', '--admin-password',
required=True,
help='admin password')
group.add_argument('--admin-realm',
defaul... | def main():
default='admin',
help='admin user name (default: admin)')
group.add_argument('-P', '--admin-password-file',
type=argparse.FileType('rb'),
help=('file containing admin password '
'(or... |
def main():
if options.permit_insecure_transport:
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
try:
anonymous_conn = KeycloakAnonymousConnection(options.server,
options.tls_verify) | def main():
if options.permit_insecure_transport:
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
# Get admin password
options.admin_password = None
# 1. Try password file
if options.admin_password_file is not None:
options.admin_password = options.keycloak_admin_password_file.read... |
class TestHTTPS_TLSv1(HTTPSDummyServerTestCase):
self._pool = HTTPSConnectionPool(self.host, self.port)
def test_set_ssl_version_to_sslv3(self):
self._pool.ssl_version = ssl.PROTOCOL_SSLv3
self.assertRaises(SSLError, self._pool.request, 'GET', '/')
def test_ssl_version_as_string(self):... | class TestHTTPS_TLSv1(HTTPSDummyServerTestCase):
self._pool = HTTPSConnectionPool(self.host, self.port)
def test_set_ssl_version_to_sslv3(self):
self.assertEqual(
ssl.PROTOCOL_SSLv3,
util.ssl_.resolve_ssl_version(ssl.PROTOCOL_SSLv3)
)
def test_ssl_version_as_str... |
try:
except AttributeError:
pass
_openssl_verify = {
ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE,
ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER,
ssl.CERT_REQUIRED:
OpenSSL.SSL.VERIFY_PEER + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
}
#: The list of supported SSL/TLS cipher suites.
DEFAULT_SSL_CIPHER_LI... | try:
except AttributeError:
pass
_stdlib_to_openssl_verify = {
ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE,
ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER,
ssl.CERT_REQUIRED:
OpenSSL.SSL.VERIFY_PEER + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
}
_openssl_to_stdlib_verify = dict(
(v, k) for k, v in _st... |
class PyOpenSSLContext(object):
@property
def verify_mode(self):
return self._ctx.get_verify_mode()
@verify_mode.setter
def verify_mode(self, value):
self._ctx.set_verify(value, _verify_callback)
def set_default_verify_paths(self):
self._ctx.set_default_verify_paths() | class PyOpenSSLContext(object):
@property
def verify_mode(self):
return _openssl_to_stdlib_verify[self._ctx.get_verify_mode()]
@verify_mode.setter
def verify_mode(self, value):
self._ctx.set_verify(
_stdlib_to_openssl_verify[value],
_verify_callback
)
... |
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
if keyfile:
ctx.use_privatekey_file(keyfile)
if cert_reqs != ssl.CERT_NONE:
ctx.set_verify(_openssl_verify[cert_reqs], _verify_callback)
if ca_certs or ca_cert_dir:
try:
ctx.load_verify_locations(ca_ce... | def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
if keyfile:
ctx.use_privatekey_file(keyfile)
if cert_reqs != ssl.CERT_NONE:
ctx.set_verify(_stdlib_to_openssl_verify[cert_reqs], _verify_callback)
if ca_certs or ca_cert_dir:
try:
ctx.load_verify_locat... |
from django.contrib.gis.db.models.fields import (
ExtentField, GeometryCollectionField, GeometryField, LineStringField,
)
from django.db.models import Aggregate
from django.utils.functional import cached_property
__all__ = ['Collect', 'Extent', 'Extent3D', 'MakeLine', 'Union'] | from django.contrib.gis.db.models.fields import (
ExtentField, GeometryCollectionField, GeometryField, LineStringField,
)
from django.db.models import Aggregate, Value
from django.utils.functional import cached_property
__all__ = ['Collect', 'Extent', 'Extent3D', 'MakeLine', 'Union'] |
class GeoAggregate(Aggregate):
)
def as_oracle(self, compiler, connection, **extra_context):
tolerance = self.extra.get('tolerance') or getattr(self, 'tolerance', 0.05)
template = None if self.is_extent else '%(function)s(SDOAGGRTYPE(%(expressions)s,%(tolerance)s))'
return self.as_s... | class GeoAggregate(Aggregate):
)
def as_oracle(self, compiler, connection, **extra_context):
if not self.is_extent:
tolerance = self.extra.get('tolerance') or getattr(self, 'tolerance', 0.05)
clone = self.copy()
clone.set_source_expressions([
*sel... |
class OracleToleranceMixin:
tolerance = 0.05
def as_oracle(self, compiler, connection, **extra_context):
tol = self.extra.get('tolerance', self.tolerance)
return self.as_sql(
compiler, connection,
template="%%(function)s(%%(expressions)s, %s)" % tol,
**extra_... | class OracleToleranceMixin:
tolerance = 0.05
def as_oracle(self, compiler, connection, **extra_context):
tolerance = Value(self._handle_param(
self.extra.get('tolerance', self.tolerance),
'tolerance',
NUMERIC_TYPES,
))
clone = self.copy()
clon... |
class DistanceFunctionsTests(FuncTestMixin, TestCase):
).filter(d=D(m=1))
self.assertTrue(qs.exists())
@skipIfDBFeature("supports_distance_geodetic")
@skipUnlessDBFeature("has_Distance_function")
def test_distance_function_raw_result_d_lookup(self): | class DistanceFunctionsTests(FuncTestMixin, TestCase):
).filter(d=D(m=1))
self.assertTrue(qs.exists())
@unittest.skipUnless(
connection.vendor == 'oracle',
'Oracle supports tolerance paremeter.',
)
def test_distance_function_tolerance_escaping(self):
qs = Interstate.... |
from django.contrib.gis.geos import (
MultiPoint, MultiPolygon, Point, Polygon, fromstr,
)
from django.core.management import call_command
from django.db import NotSupportedError, connection
from django.db.models import F, OuterRef, Subquery
from django.test import TestCase, skipUnlessDBFeature
| from django.contrib.gis.geos import (
MultiPoint, MultiPolygon, Point, Polygon, fromstr,
)
from django.core.management import call_command
from django.db import DatabaseError, NotSupportedError, connection
from django.db.models import F, OuterRef, Subquery
from django.test import TestCase, skipUnlessDBFeature
|
class GeoQuerySetTest(TestCase):
qs = City.objects.filter(name='NotACity')
self.assertIsNone(qs.aggregate(Union('point'))['point__union'])
def test_within_subquery(self):
"""
Using a queryset inside a geo lookup is working (using a subquery) | class GeoQuerySetTest(TestCase):
qs = City.objects.filter(name='NotACity')
self.assertIsNone(qs.aggregate(Union('point'))['point__union'])
@unittest.skipUnless(
connection.vendor == 'oracle',
'Oracle supports tolerance paremeter.',
)
def test_unionagg_tolerance(self):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.