buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
class LogoutTest(AuthViewsTestCase):
self.assertRedirects(response, '/logout/', fetch_redirect_response=False)
# Redirect in test_user_change_password will fail if session auth hash
# isn't updated after password change (#21649)
@override_settings(ROOT_URLCONF='auth_tests.urls_admin') | class LogoutTest(AuthViewsTestCase):
self.assertRedirects(response, '/logout/', fetch_redirect_response=False)
def get_perm(Model, perm):
ct = ContentType.objects.get_for_model(Model)
return Permission.objects.get(content_type=ct, codename=perm)
# Redirect in test_user_change_password will fail if s... |
class ChangelistTests(AuthViewsTestCase):
(_request, user), _kwargs = has_change_permission.call_args
self.assertEqual(user.pk, self.admin.pk)
@override_settings(
AUTH_USER_MODEL='auth_tests.UUIDUser', | class ChangelistTests(AuthViewsTestCase):
(_request, user), _kwargs = has_change_permission.call_args
self.assertEqual(user.pk, self.admin.pk)
def test_view_user_password_is_readonly(self):
u = User.objects.get(username='testclient')
u.is_superuser = False
u.save()
u... |
def test_categorical_no_compress():
def test_sort():
# http://stackoverflow.com/questions/23814368/sorting-pandas-categorical-labels-after-groupby # noqa: E501
# This should result in a properly sorted Series so that the plot
# has a sorted x axis
# self.cat.groupby(['value_group'])['value_group'].co... | def test_categorical_no_compress():
def test_sort():
# http://stackoverflow.com/questions/23814368/sorting-pandas-
# categorical-labels-after-groupby
# This should result in a properly sorted Series so that the plot
# has a sorted x axis
# self.cat.groupby(['value_group'])['value_group'].co... |
from datetime import datetime
import pytest
from pandas import DatetimeIndex
import pandas.util.testing as tm
from pandas.tseries.holiday import ( | from datetime import datetime
import pytest
from pandas import DatetimeIndex, offsets, to_datetime
import pandas.util.testing as tm
from pandas.tseries.holiday import ( |
from pandas.tseries.holiday import (
Holiday,
Timestamp,
USFederalHolidayCalendar,
USThanksgivingDay,
get_calendar,
) | from pandas.tseries.holiday import (
Holiday,
Timestamp,
USFederalHolidayCalendar,
USLaborDay,
USThanksgivingDay,
get_calendar,
) |
def test_calendar_observance_dates():
def test_rule_from_name():
us_fed_cal = get_calendar("USFederalHolidayCalendar")
assert us_fed_cal.rule_from_name("Thanksgiving") == USThanksgivingDay | def test_calendar_observance_dates():
def test_rule_from_name():
us_fed_cal = get_calendar("USFederalHolidayCalendar")
assert us_fed_cal.rule_from_name("Thanksgiving") == USThanksgivingDay
def test_calendar_2031():
# See gh-27790
#
# Labor Day 2031 is on September 1. Saturday before is August 30.
... |
class AbstractHolidayCalendar(metaclass=HolidayCalendarMetaClass):
rules = [] # type: List[Holiday]
start_date = Timestamp(datetime(1970, 1, 1))
end_date = Timestamp(datetime(2030, 12, 31))
_cache = None
def __init__(self, name=None, rules=None): | class AbstractHolidayCalendar(metaclass=HolidayCalendarMetaClass):
rules = [] # type: List[Holiday]
start_date = Timestamp(datetime(1970, 1, 1))
end_date = Timestamp(datetime(2200, 12, 31))
_cache = None
def __init__(self, name=None, rules=None): |
ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
{'like_count': 190, 'dislike_count': 10}))
def test_parse_dfxp_time_expr(self):
self.assertEqual(parse_dfxp_time_expr(None), 0.0)
self.assertEqual(parse_dfxp_time_expr(''), 0.0)
self.assertEqual(parse_dfxp... | ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
{'like_count': 190, 'dislike_count': 10}))
def test_parse_dfxp_time_expr(self):
self.assertEqual(parse_dfxp_time_expr(None), None)
self.assertEqual(parse_dfxp_time_expr(''), None)
self.assertEqual(parse_df... |
ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
<p begin="0" end="1">The following line contains Chinese characters and special symbols</p>
<p begin="1" end="2">第二行<br/>♪♪</p>
<p begin="2" dur="1"><span>Third<br/>Line</span></p>
... | ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
<p begin="0" end="1">The following line contains Chinese characters and special symbols</p>
<p begin="1" end="2">第二行<br/>♪♪</p>
<p begin="2" dur="1"><span>Third<br/>Line</span></p>
... |
def match_filter_func(filter_str):
def parse_dfxp_time_expr(time_expr):
if not time_expr:
return 0.0
mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr)
if mobj: | def match_filter_func(filter_str):
def parse_dfxp_time_expr(time_expr):
if not time_expr:
return
mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr)
if mobj: |
def dfxp2srt(dfxp_data):
raise ValueError('Invalid dfxp/TTML subtitle')
for para, index in zip(paras, itertools.count(1)):
begin_time = parse_dfxp_time_expr(para.attrib['begin'])
end_time = parse_dfxp_time_expr(para.attrib.get('end'))
if not end_time:
end_time = begin_ti... | def dfxp2srt(dfxp_data):
raise ValueError('Invalid dfxp/TTML subtitle')
for para, index in zip(paras, itertools.count(1)):
begin_time = parse_dfxp_time_expr(para.attrib.get('begin'))
end_time = parse_dfxp_time_expr(para.attrib.get('end'))
dur = parse_dfxp_time_expr(para.attrib.get('... |
from django.db.models.deletion import CASCADE
from django.urls import reverse
from django.urls.exceptions import NoReverseMatch
from django.utils.html import smart_urlquote
from django.utils.safestring import mark_safe
from django.utils.text import Truncator
from django.utils.translation import get_language, gettext as... | from django.db.models.deletion import CASCADE
from django.urls import reverse
from django.urls.exceptions import NoReverseMatch
from django.utils.html import smart_urlquote
from django.utils.http import urlencode
from django.utils.text import Truncator
from django.utils.translation import get_language, gettext as _
|
class ForeignKeyRawIdWidget(forms.TextInput):
params = self.url_parameters()
if params:
related_url += '?' + '&'.join('%s=%s' % (k, v) for k, v in params.items())
context['related_url'] = mark_safe(related_url)
context['link_title'] = _('Lookup')
... | class ForeignKeyRawIdWidget(forms.TextInput):
params = self.url_parameters()
if params:
related_url += '?' + urlencode(params)
context['related_url'] = related_url
context['link_title'] = _('Lookup')
# The JavaScript code looks for this class.... |
class Band(models.Model):
return self.name
class Album(models.Model):
band = models.ForeignKey(Band, models.CASCADE)
featuring = models.ManyToManyField(Band, related_name='featured') | class Band(models.Model):
return self.name
class UnsafeLimitChoicesTo(models.Model):
band = models.ForeignKey(
Band,
models.CASCADE,
limit_choices_to={'name': '"&><escapeme'},
)
class Album(models.Model):
band = models.ForeignKey(Band, models.CASCADE)
featuring = mode... |
from django.utils import translation
from .models import (
Advisor, Album, Band, Bee, Car, Company, Event, Honeycomb, Individual,
Inventory, Member, MyFileField, Profile, School, Student,
)
from .widgetadmin import site as widget_admin_site
| from django.utils import translation
from .models import (
Advisor, Album, Band, Bee, Car, Company, Event, Honeycomb, Individual,
Inventory, Member, MyFileField, Profile, School, Student,
UnsafeLimitChoicesTo,
)
from .widgetadmin import site as widget_admin_site
|
class ForeignKeyRawIdWidgetTest(TestCase):
'Hidden</a></strong>' % {'pk': hidden.pk}
)
@override_settings(ROOT_URLCONF='admin_widgets.urls')
class ManyToManyRawIdWidgetTest(TestCase): | class ForeignKeyRawIdWidgetTest(TestCase):
'Hidden</a></strong>' % {'pk': hidden.pk}
)
def test_render_unsafe_limit_choices_to(self):
rel = UnsafeLimitChoicesTo._meta.get_field('band').remote_field
w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site)
self.assertHTML... |
class ActionBase(with_metaclass(ABCMeta, object)):
'''
become_unprivileged = self._is_become_unprivileged()
try:
remote_tmp = self._connection._shell.get_option('remote_tmp')
except AnsibleError:
remote_tmp = '~/.ansible/tmp'
# deal with tmpdir creation
... | class ActionBase(with_metaclass(ABCMeta, object)):
'''
become_unprivileged = self._is_become_unprivileged()
# deal with tmpdir creation
basefile = 'ansible-tmp-%s-%s' % (time.time(), random.randint(0, 2**48)) |
class ActionBase(with_metaclass(ABCMeta, object)):
if getattr(self._connection, '_remote_is_local', False):
tmpdir = C.DEFAULT_LOCAL_TMP
else:
tmpdir = self._remote_expand_user(remote_tmp, sudoable=False)
cmd = self._connection._shell.mkdtemp(basefile=basefile, system=bec... | class ActionBase(with_metaclass(ABCMeta, object)):
if getattr(self._connection, '_remote_is_local', False):
tmpdir = C.DEFAULT_LOCAL_TMP
else:
# NOTE: shell plugins should populate this setting anyways, but they dont do remote expansion, which
# we need for 'non posix... |
class ActionBase(with_metaclass(ABCMeta, object)):
elif u'No space left on device' in result['stderr']:
output = result['stderr']
else:
output = ('Authentication or permission failure. '
'In some cases, you may have been able to authentic... | class ActionBase(with_metaclass(ABCMeta, object)):
elif u'No space left on device' in result['stderr']:
output = result['stderr']
else:
output = ('Failed to create temporary directory.'
'In some cases, you may have been able to authentica... |
import random
import re
import time
import ansible.constants as C
from ansible.errors import AnsibleError
from ansible.module_utils.six import text_type
from ansible.module_utils.six.moves import shlex_quote | import random
import re
import time
from ansible import constants as C
from ansible.errors import AnsibleError
from ansible.module_utils.six import text_type
from ansible.module_utils.six.moves import shlex_quote |
class ShellBase(AnsiblePlugin):
except AnsibleError:
pass
def env_prefix(self, **kwargs):
return ' '.join(['%s=%s' % (k, shlex_quote(text_type(v))) for k, v in kwargs.items()])
| class ShellBase(AnsiblePlugin):
except AnsibleError:
pass
@staticmethod
def _generate_temp_dir_name():
return 'ansible-tmp-%s-%s-%s' % (time.time(), os.getpid(), random.randint(0, 2**48))
def env_prefix(self, **kwargs):
return ' '.join(['%s=%s' % (k, shlex_quote(text_ty... |
class ShellBase(AnsiblePlugin):
def mkdtemp(self, basefile=None, system=False, mode=0o700, tmpdir=None):
if not basefile:
basefile = 'ansible-tmp-%s-%s' % (time.time(), random.randint(0, 2**48))
# When system is specified we have to create this in a directory where
# other user... | class ShellBase(AnsiblePlugin):
def mkdtemp(self, basefile=None, system=False, mode=0o700, tmpdir=None):
if not basefile:
basefile = self.__class__._generate_temp_dir_name()
# When system is specified we have to create this in a directory where
# other users can read and access... |
class ShellBase(AnsiblePlugin):
# passed in tmpdir if it is valid or the first one from the setting if not.
if system:
tmpdir = tmpdir.rstrip('/')
if tmpdir in self.get_option('system_tmpdirs'):
basetmpdir = tmpdir | class ShellBase(AnsiblePlugin):
# passed in tmpdir if it is valid or the first one from the setting if not.
if system:
if tmpdir:
tmpdir = tmpdir.rstrip('/')
if tmpdir in self.get_option('system_tmpdirs'):
basetmpdir = tmpdir |
class ShellBase(AnsiblePlugin):
basetmp = self.join_path(basetmpdir, basefile)
cmd = 'mkdir -p %s echo %s %s' % (self._SHELL_SUB_LEFT, basetmp, self._SHELL_SUB_RIGHT)
cmd += ' %s echo %s=%s echo %s %s' % (self._SHELL_AND, basefile, self._SHELL_SUB_LEFT, basetmp, self._SHELL_SUB_RIGHT)
... | class ShellBase(AnsiblePlugin):
basetmp = self.join_path(basetmpdir, basefile)
# use mkdir -p to ensure parents exist, but mkdir fullpath to ensure last one is created by us
cmd = 'mkdir -p %s echo %s %s' % (self._SHELL_SUB_LEFT, basetmpdir, self._SHELL_SUB_RIGHT)
cmd += '%s mkdir %s' ... |
class ShellModule(ShellBase):
def mkdtemp(self, basefile=None, system=False, mode=None, tmpdir=None):
# Windows does not have an equivalent for the system temp files, so
# the param is ignored
basefile = self._escape(self._unquote(basefile))
basetmpdir = tmpdir if tmpdir else self.ge... | class ShellModule(ShellBase):
def mkdtemp(self, basefile=None, system=False, mode=None, tmpdir=None):
# Windows does not have an equivalent for the system temp files, so
# the param is ignored
if not basefile:
basefile = self.__class__._generate_temp_dir_name()
basefile =... |
from itertools import cycle as itertools_cycle, groupby
from django.conf import settings
from django.utils import timezone
from django.utils.html import conditional_escape, format_html
from django.utils.lorem_ipsum import paragraphs, words
from django.utils.safestring import mark_safe
| from itertools import cycle as itertools_cycle, groupby
from django.conf import settings
from django.utils import timezone
from django.utils.html import conditional_escape, escape, format_html
from django.utils.lorem_ipsum import paragraphs, words
from django.utils.safestring import mark_safe
|
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 |
class Axis(martist.Artist):
the top for the y-axis; the "inverse" direction is increasing to the
left for the x-axis and to the bottom for the y-axis.
"""
a, b = self.get_view_interval()
if inverted:
self.set_view_interval(max(a, b), min(a, b), ignore=True)
el... | class Axis(martist.Artist):
the top for the y-axis; the "inverse" direction is increasing to the
left for the x-axis and to the bottom for the y-axis.
"""
# Currently, must be implemented in subclasses using set_xlim/set_ylim
# rather than generically using set_view_interval, so ... |
class XAxis(Axis):
def get_minpos(self):
return self.axes.dataLim.minposx
def set_default_intervals(self):
# docstring inherited
xmin, xmax = 0., 1. | class XAxis(Axis):
def get_minpos(self):
return self.axes.dataLim.minposx
def set_inverted(self, inverted):
# docstring inherited
a, b = self.get_view_interval()
self.axes.set_xlim(sorted((a, b), reverse=inverted), auto=None)
def set_default_intervals(self):
# docst... |
class YAxis(Axis):
def get_minpos(self):
return self.axes.dataLim.minposy
def set_default_intervals(self):
# docstring inherited
ymin, ymax = 0., 1. | class YAxis(Axis):
def get_minpos(self):
return self.axes.dataLim.minposy
def set_inverted(self, inverted):
# docstring inherited
a, b = self.get_view_interval()
self.axes.set_ylim(sorted((a, b), reverse=inverted), auto=None)
def set_default_intervals(self):
# docst... |
def test_inverted_cla():
ax.cla()
ax.imshow(img)
plt.autoscale()
assert not(ax.xaxis_inverted())
assert ax.yaxis_inverted()
# 5. two shared axes. Clearing the master axis should bring axes in shared
# axes back to normal
ax0 = plt.subplot(211)
ax1 = plt.subplot(212, sharey=ax0)
... | def test_inverted_cla():
ax.cla()
ax.imshow(img)
plt.autoscale()
assert not ax.xaxis_inverted()
assert ax.yaxis_inverted()
# 5. two shared axes. Inverting the master axis should invert the shared
# axes; clearing the master axis should bring axes in shared
# axes back to normal.
ax0... |
INTERNAL_RESULT_KEYS = ('add_host', 'add_group')
LOCALHOST = ('127.0.0.1', 'localhost', '::1')
MODULE_REQUIRE_ARGS = ('command', 'win_command', 'shell', 'win_shell', 'raw', 'script')
MODULE_NO_JSON = ('command', 'win_command', 'shell', 'win_shell', 'raw')
RESTRICTED_RESULT_KEYS = ('ansible_rsync_path', 'ansible_playboo... | INTERNAL_RESULT_KEYS = ('add_host', 'add_group')
LOCALHOST = ('127.0.0.1', 'localhost', '::1')
MODULE_REQUIRE_ARGS = ('command', 'win_command', 'shell', 'win_shell', 'raw', 'script')
MODULE_NO_JSON = ('command', 'win_command', 'shell', 'win_shell', 'raw')
RESTRICTED_RESULT_KEYS = ('ansible_rsync_path', 'ansible_playboo... |
from ansible.module_utils.common._collections_compat import MutableMapping, Muta
from ansible.plugins.loader import connection_loader
from ansible.utils.display import Display
display = Display()
| from ansible.module_utils.common._collections_compat import MutableMapping, Muta
from ansible.plugins.loader import connection_loader
from ansible.utils.display import Display
display = Display()
|
def namespace_facts(facts):
''' return all facts inside 'ansible_facts' w/o an ansible_ prefix '''
deprefixed = {}
for k in facts:
if k in ('ansible_local',):
# exceptions to 'deprefixing'
deprefixed[k] = module_response_deepcopy(facts[k])
else:
deprefixed... | def namespace_facts(facts):
''' return all facts inside 'ansible_facts' w/o an ansible_ prefix '''
deprefixed = {}
for k in facts:
if k.startswith('ansible_') and k not in ('ansible_local',):
deprefixed[k[8:]] = module_response_deepcopy(facts[k])
else:
deprefixed[k] =... |
from absl.testing import parameterized
import numpy as np
from tensorflow.python.dlpack import dlpack
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.platform import test
from tensorflow.python.ops imp... | from absl.testing import parameterized
import numpy as np
from tensorflow.python.dlpack import dlpack
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import ops
from tensorflow.python.pla... |
def UnsupportedComplex64():
self.assertRaisesRegex(Exception, ".* is not supported by dlpack",
UnsupportedComplex64)
if __name__ == "__main__":
ops.enable_eager_execution() | def UnsupportedComplex64():
self.assertRaisesRegex(Exception, ".* is not supported by dlpack",
UnsupportedComplex64)
def testMustPassTensorArgumentToDLPack(self):
with self.assertRaisesRegex(
errors.InvalidArgumentError,
"The argument to `to_dlpack` must be a TF ten... |
class _AtIndexer(_ScalarAccessIndexer):
if is_setter:
return list(key)
for ax, i in zip(self.obj.axes, key):
if ax.is_integer():
if not is_integer(i):
raise ValueError(
"At based indexing on an integer index "
... | class _AtIndexer(_ScalarAccessIndexer):
if is_setter:
return list(key)
lkey = list(key)
for n, (ax, i) in enumerate(zip(self.obj.axes, key)):
lkey[n] = ax._convert_scalar_indexer(i, kind="loc")
return tuple(lkey)
@Appender(IndexingMixin.iat.__doc__) |
class TestScalar2:
result = df.iat[2, 0]
assert result == 2
def test_at_to_fail(self):
# at should not fallback
# GH 7814
s = Series([1, 2, 3], index=list("abc"))
result = s.at["a"]
assert result == 1
msg = (
"At based indexing on an non-i... | class TestScalar2:
result = df.iat[2, 0]
assert result == 2
def test_series_at_raises_type_error(self):
# at should not fallback
# GH 7814
# GH#31724 .at should match .loc
ser = Series([1, 2, 3], index=list("abc"))
result = ser.at["a"]
assert result =... |
class Templar:
res = ansible_native_concat(rf)
else:
res = j2_concat(rf)
if getattr(new_context, 'unsafe', False):
res = wrap_var(res)
except TypeError as te:
if 'AnsibleUndefined' in to_native(te): | class Templar:
res = ansible_native_concat(rf)
else:
res = j2_concat(rf)
unsafe = getattr(new_context, 'unsafe', False)
if unsafe:
res = wrap_var(res)
except TypeError as te:
if 'Ansib... |
class Templar:
res_newlines = _count_newlines_from_end(res)
if data_newlines > res_newlines:
res += self.environment.newline_sequence * (data_newlines - res_newlines)
return res
except (UndefinedError, AnsibleUndefinedVariable) as e:
if... | class Templar:
res_newlines = _count_newlines_from_end(res)
if data_newlines > res_newlines:
res += self.environment.newline_sequence * (data_newlines - res_newlines)
if unsafe:
res = wrap_var(res)
return res
... |
class NDFrame(PandasObject, SelectionMixin):
data = self.fillna(method=fill_method, limit=limit, axis=axis)
rs = data.div(data.shift(periods=periods, freq=freq, axis=axis, **kwargs)) - 1
rs = rs.loc[~rs.index.duplicated()]
rs = rs.reindex_like(data)
if freq is None:
... | class NDFrame(PandasObject, SelectionMixin):
data = self.fillna(method=fill_method, limit=limit, axis=axis)
rs = data.div(data.shift(periods=periods, freq=freq, axis=axis, **kwargs)) - 1
if freq is not None:
# Shift method is implemented differently when freq is not None
... |
class TestDataFramePctChange:
rs_freq = empty_ts.pct_change(freq=freq, fill_method=fill_method, limit=limit)
rs_periods = empty_ts.pct_change(periods, fill_method=fill_method, limit=limit)
tm.assert_frame_equal(rs_freq, rs_periods) | class TestDataFramePctChange:
rs_freq = empty_ts.pct_change(freq=freq, fill_method=fill_method, limit=limit)
rs_periods = empty_ts.pct_change(periods, fill_method=fill_method, limit=limit)
tm.assert_frame_equal(rs_freq, rs_periods)
@pytest.mark.parametrize("fill_method", ["pad", "ffill", None]... |
class TestSeriesPctChange:
rs_freq = empty_ts.pct_change(freq=freq, fill_method=fill_method, limit=limit)
rs_periods = empty_ts.pct_change(periods, fill_method=fill_method, limit=limit)
tm.assert_series_equal(rs_freq, rs_periods) | class TestSeriesPctChange:
rs_freq = empty_ts.pct_change(freq=freq, fill_method=fill_method, limit=limit)
rs_periods = empty_ts.pct_change(periods, fill_method=fill_method, limit=limit)
tm.assert_series_equal(rs_freq, rs_periods)
@pytest.mark.parametrize("fill_method", ["pad", "ffill", None])
... |
from django.contrib.gis.db.models.fields import (
ExtentField, GeometryCollectionField, GeometryField, LineStringField,
)
from django.db.models.aggregates import Aggregate
from django.utils.functional import cached_property
| from django.contrib.gis.db.models.fields import (
ExtentField, GeometryCollectionField, GeometryField, LineStringField,
)
from django.db.models import Value
from django.db.models.aggregates import Aggregate
from django.utils.functional import cached_property
|
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.test import TestCase, skipUnlessDBFeature
from ..utils import ( | 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.test import TestCase, skipUnlessDBFeature
from ..utils import ( |
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):
... |
class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin):
if not is_list:
start = self.index[0]
if isinstance(self.index, PeriodIndex):
where = Period(where, freq=self.index.freq).ordinal
start = start.ordinal
if where < start:
... | class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin):
if not is_list:
start = self.index[0]
if isinstance(self.index, PeriodIndex):
where = Period(where, freq=self.index.freq)
if where < start:
if not is_series: |
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
@Substitution(klass="PeriodIndex")
@Appender(_shared_docs["searchsorted"])
def searchsorted(self, value, side="left", sorter=None):
if isinstance(value, Period):
if value.freq != self.freq:
raise r... | class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
@Substitution(klass="PeriodIndex")
@Appender(_shared_docs["searchsorted"])
def searchsorted(self, value, side="left", sorter=None):
if isinstance(value, Period) or value is NaT:
self._data._check_compatible_with(v... |
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
t1, t2 = self._parsed_string_to_bounds(reso, parsed)
return slice(
self.searchsorted(t1.ordinal, side="left"),
self.searchsorted(t2.ordinal, side="right"),
)
def _convert_tolerance(self, tole... | class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
t1, t2 = self._parsed_string_to_bounds(reso, parsed)
return slice(
self.searchsorted(t1, side="left"), self.searchsorted(t2, side="right")
)
def _convert_tolerance(self, tolerance, target): |
class TimeGrouper(Grouper):
rng += freq_mult
# adjust bin edge indexes to account for base
rng -= bin_shift
bins = memb.searchsorted(rng, side="left")
if nat_count > 0:
# NaT handling as in pandas._lib.lib.generate_bins_dt64() | class TimeGrouper(Grouper):
rng += freq_mult
# adjust bin edge indexes to account for base
rng -= bin_shift
# Wrap in PeriodArray for PeriodArray.searchsorted
prng = type(memb._data)(rng, dtype=memb.dtype)
bins = memb.searchsorted(prng, side="left")
if nat_count... |
import numpy as np
import pytest
from pandas import DataFrame, Series, Timestamp, date_range, to_datetime
import pandas._testing as tm
| import numpy as np
import pytest
from pandas import DataFrame, Period, Series, Timestamp, date_range, to_datetime
import pandas._testing as tm
|
class TestFrameAsof:
)
tm.assert_frame_equal(result, expected)
def test_all_nans(self, date_range_frame):
# GH 15713
# DataFrame is all nans | class TestFrameAsof:
)
tm.assert_frame_equal(result, expected)
# Check that we handle PeriodIndex correctly, dont end up with
# period.ordinal for series name
df = df.to_period("D")
result = df.asof("1989-12-31")
assert isinstance(result.name, Period)
def t... |
class TestPeriodIndex(DatetimeLike):
idx = PeriodIndex([2000, 2007, 2007, 2009, 2009], freq="A-JUN")
ts = Series(np.random.randn(len(idx)), index=idx)
result = ts[2007]
expected = ts[1:3]
tm.assert_series_equal(result, expected)
result[:] = 1 | class TestPeriodIndex(DatetimeLike):
idx = PeriodIndex([2000, 2007, 2007, 2009, 2009], freq="A-JUN")
ts = Series(np.random.randn(len(idx)), index=idx)
result = ts["2007"]
expected = ts[1:3]
tm.assert_series_equal(result, expected)
result[:] = 1 |
class TestPeriodIndex(DatetimeLike):
idx = PeriodIndex([2000, 2007, 2007, 2009, 2007], freq="A-JUN")
ts = Series(np.random.randn(len(idx)), index=idx)
result = ts[2007]
expected = ts[idx == "2007"]
tm.assert_series_equal(result, expected)
| class TestPeriodIndex(DatetimeLike):
idx = PeriodIndex([2000, 2007, 2007, 2009, 2007], freq="A-JUN")
ts = Series(np.random.randn(len(idx)), index=idx)
result = ts["2007"]
expected = ts[idx == "2007"]
tm.assert_series_equal(result, expected)
|
class TestPeriodIndex:
p2 = pd.Period("2014-01-04", freq=freq)
assert pidx.searchsorted(p2) == 3
msg = "Input has different freq=H from PeriodIndex"
with pytest.raises(IncompatibleFrequency, match=msg):
pidx.searchsorted(pd.Period("2014-01-01", freq="H"))
msg = "Inp... | class TestPeriodIndex:
p2 = pd.Period("2014-01-04", freq=freq)
assert pidx.searchsorted(p2) == 3
assert pidx.searchsorted(pd.NaT) == 0
msg = "Input has different freq=H from PeriodArray"
with pytest.raises(IncompatibleFrequency, match=msg):
pidx.searchsorted(pd.Peri... |
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.... |
class ModelAdmin(BaseModelAdmin):
)
def get_inline_formsets(self, request, formsets, inline_instances, obj=None):
inline_admin_formsets = []
for inline, formset in zip(inline_instances, formsets):
fieldsets = list(inline.get_fieldsets(request, obj))
readonly = list(i... | class ModelAdmin(BaseModelAdmin):
)
def get_inline_formsets(self, request, formsets, inline_instances, obj=None):
# Edit permissions on parent model are required for editable inlines.
can_edit_parent = self.has_change_permission(request, obj) if obj else self.has_add_permission(request)
... |
class ModelAdmin(BaseModelAdmin):
else:
obj = self.get_object(request, unquote(object_id), to_field)
if not self.has_view_or_change_permission(request, obj):
raise PermissionDenied
if obj is None:
return self._get_obj_does_not_exist_redirect(... | class ModelAdmin(BaseModelAdmin):
else:
obj = self.get_object(request, unquote(object_id), to_field)
if request.method == 'POST':
if not self.has_change_permission(request, obj):
raise PermissionDenied
else:
if not self.has... |
from django.contrib.admin import ModelAdmin, TabularInline
from django.contrib.admin.helpers import InlineAdminForm
from django.contrib.admin.tests import AdminSeleniumTestCase | from selenium.common.exceptions import NoSuchElementException
from django.contrib.admin import ModelAdmin, TabularInline
from django.contrib.admin.helpers import InlineAdminForm
from django.contrib.admin.tests import AdminSeleniumTestCase |
class TestInlinePermissions(TestCase):
)
@override_settings(ROOT_URLCONF='admin_inlines.urls')
class SeleniumTests(AdminSeleniumTestCase):
| class TestInlinePermissions(TestCase):
)
@override_settings(ROOT_URLCONF='admin_inlines.urls')
class TestReadOnlyChangeViewInlinePermissions(TestCase):
@classmethod
def setUpTestData(cls):
cls.user = User.objects.create_user('testing', password='password', is_staff=True)
cls.user.user... |
class SeleniumTests(AdminSeleniumTestCase):
self.assertEqual(ProfileCollection.objects.all().count(), 1)
self.assertEqual(Profile.objects.all().count(), 3)
def test_delete_inlines(self):
self.admin_login(username='super', password='secret')
self.selenium.get(self.live_server_url + r... | class SeleniumTests(AdminSeleniumTestCase):
self.assertEqual(ProfileCollection.objects.all().count(), 1)
self.assertEqual(Profile.objects.all().count(), 3)
def test_add_inline_link_absent_for_view_only_parent_model(self):
user = User.objects.create_user('testing', password='password', is_st... |
class ArticleAdmin9(admin.ModelAdmin):
site9 = admin.AdminSite(name='admin9')
site9.register(Article, ArticleAdmin9)
class ArticleAdmin10(admin.ModelAdmin):
def has_change_permission(self, request, obj=None):
return False
site10 = admin.AdminSite(name='admin10')
site10.register(Article, ArticleAdmin10) | class ArticleAdmin9(admin.ModelAdmin):
site9 = admin.AdminSite(name='admin9')
site9.register(Article, ArticleAdmin9) |
class AdminViewPermissionsTest(TestCase):
self.assertEqual(post.status_code, 403)
self.client.get(reverse('admin:logout'))
# view user should be able to view the article but not change any of them
# (the POST can be sent, but no modification occurs)
self.client.force_login(self.... | class AdminViewPermissionsTest(TestCase):
self.assertEqual(post.status_code, 403)
self.client.get(reverse('admin:logout'))
# view user can view articles but not make changes.
self.client.force_login(self.viewuser)
response = self.client.get(article_changelist_url)
self.a... |
class AdminViewPermissionsTest(TestCase):
self.assertContains(response, '<label>Extra form field:</label>')
self.assertContains(response, '<a href="/test_admin/admin/admin_views/article/" class="closelink">Close</a>')
post = self.client.post(article_change_url, change_dict)
self.assertEq... | class AdminViewPermissionsTest(TestCase):
self.assertContains(response, '<label>Extra form field:</label>')
self.assertContains(response, '<a href="/test_admin/admin/admin_views/article/" class="closelink">Close</a>')
post = self.client.post(article_change_url, change_dict)
self.assertEq... |
class AdminViewPermissionsTest(TestCase):
response = self.client.get(change_url_3)
self.assertEqual(response.status_code, 200)
response = self.client.post(change_url_3, {'name': 'changed'})
self.assertRedirects(response, self.index_url)
sel... | class AdminViewPermissionsTest(TestCase):
response = self.client.get(change_url_3)
self.assertEqual(response.status_code, 200)
response = self.client.post(change_url_3, {'name': 'changed'})
self.assertEqual(response.status_code, 403)
self.a... |
class AdminViewPermissionsTest(TestCase):
self.assertEqual(response.context['title'], 'View article')
self.assertContains(response, '<a href="/test_admin/admin9/admin_views/article/" class="closelink">Close</a>')
def test_change_view_post_without_object_change_permission(self):
"""A POST re... | class AdminViewPermissionsTest(TestCase):
self.assertEqual(response.context['title'], 'View article')
self.assertContains(response, '<a href="/test_admin/admin9/admin_views/article/" class="closelink">Close</a>')
def test_change_view_save_as_new(self):
"""
'Save as new' should raise... |
class AdminInlineTests(TestCase):
self.assertEqual(Widget.objects.count(), 1)
self.assertEqual(Widget.objects.all()[0].name, "Widget 1 Updated")
def test_simple_inline_permissions(self):
"""
Changes aren't allowed without change permissions for the inline object.
"""
... | class AdminInlineTests(TestCase):
self.assertEqual(Widget.objects.count(), 1)
self.assertEqual(Widget.objects.all()[0].name, "Widget 1 Updated")
def test_explicit_autofield_inline(self):
"A model with an explicit autofield primary key can be saved as inlines. Regression for #8093"
#... |
urlpatterns = [
# All admin views accept `extra_context` to allow adding it like this:
path('test_admin/admin8/', (admin.site.get_urls(), 'admin', 'admin-extra-context'), {'extra_context': {}}),
path('test_admin/admin9/', admin.site9.urls),
path('test_admin/admin10/', admin.site10.urls),
path('test_... | urlpatterns = [
# All admin views accept `extra_context` to allow adding it like this:
path('test_admin/admin8/', (admin.site.get_urls(), 'admin', 'admin-extra-context'), {'extra_context': {}}),
path('test_admin/admin9/', admin.site9.urls),
path('test_admin/has_permission_admin/', custom_has_permission_... |
class ChangelistTests(AuthViewsTestCase):
data['password'] = 'shouldnotchange'
change_url = reverse('auth_test_admin:auth_user_change', args=(u.pk,))
response = self.client.post(change_url, data)
self.assertRedirects(response, reverse('auth_test_admin:auth_user_changelist'))
u.re... | class ChangelistTests(AuthViewsTestCase):
data['password'] = 'shouldnotchange'
change_url = reverse('auth_test_admin:auth_user_change', args=(u.pk,))
response = self.client.post(change_url, data)
self.assertEqual(response.status_code, 403)
u.refresh_from_db()
self.assertE... |
def test_osx_proxy_bypass(self):
bypass = {'exclude_simple': True, 'exceptions': []}
self.assertTrue(_proxy_bypass_macosx_sysconf('test', bypass))
def test_basic_auth(self, quote_char='"'):
opener = OpenerDirector()
password_manager = MockPasswordManager()
auth_handler = url... | def test_osx_proxy_bypass(self):
bypass = {'exclude_simple': True, 'exceptions': []}
self.assertTrue(_proxy_bypass_macosx_sysconf('test', bypass))
def check_basic_auth(self, headers, realm):
with self.subTest(realm=realm, headers=headers):
opener = OpenerDirector()
p... |
class AbstractBasicAuthHandler:
# allow for double- and single-quoted realm values
# (single quotes are a violation of the RFC, but appear in the wild)
rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+'
'realm=(["\']?)([^"\']*)\\2', re.I)
# XXX could pre-emptively send auth info alrea... | class AbstractBasicAuthHandler:
# allow for double- and single-quoted realm values
# (single quotes are a violation of the RFC, but appear in the wild)
rx = re.compile('(?:^|,)' # start of the string or ','
'[ \t]*' # optional whitespaces
'([^ \t]+)' # scheme li... |
def __init__(self, password_mgr=None):
self.passwd = password_mgr
self.add_password = self.passwd.add_password
def http_error_auth_reqed(self, authreq, host, req, headers):
# host may be an authority (without userinfo) or a URL with an
# authority
# XXX could be multiple hea... | def __init__(self, password_mgr=None):
self.passwd = password_mgr
self.add_password = self.passwd.add_password
def _parse_realm(self, header):
# parse WWW-Authenticate header: accept multiple challenges per header
found_challenge = False
for mo in AbstractBasicAuthHandler.rx... |
class NDFrame(PandasObject, SelectionMixin):
data = self.fillna(method=fill_method, limit=limit, axis=axis)
rs = data.div(data.shift(periods=periods, freq=freq, axis=axis, **kwargs)) - 1
rs = rs.loc[~rs.index.duplicated()]
rs = rs.reindex_like(data)
if freq is None:
... | class NDFrame(PandasObject, SelectionMixin):
data = self.fillna(method=fill_method, limit=limit, axis=axis)
rs = data.div(data.shift(periods=periods, freq=freq, axis=axis, **kwargs)) - 1
if freq is not None:
# Shift method is implemented differently when freq is not None
... |
class TestDataFramePctChange:
rs_freq = empty_ts.pct_change(freq=freq, fill_method=fill_method, limit=limit)
rs_periods = empty_ts.pct_change(periods, fill_method=fill_method, limit=limit)
tm.assert_frame_equal(rs_freq, rs_periods) | class TestDataFramePctChange:
rs_freq = empty_ts.pct_change(freq=freq, fill_method=fill_method, limit=limit)
rs_periods = empty_ts.pct_change(periods, fill_method=fill_method, limit=limit)
tm.assert_frame_equal(rs_freq, rs_periods)
@pytest.mark.parametrize("fill_method", ["pad", "ffill", None]... |
class TestSeriesPctChange:
rs_freq = empty_ts.pct_change(freq=freq, fill_method=fill_method, limit=limit)
rs_periods = empty_ts.pct_change(periods, fill_method=fill_method, limit=limit)
tm.assert_series_equal(rs_freq, rs_periods) | class TestSeriesPctChange:
rs_freq = empty_ts.pct_change(freq=freq, fill_method=fill_method, limit=limit)
rs_periods = empty_ts.pct_change(periods, fill_method=fill_method, limit=limit)
tm.assert_series_equal(rs_freq, rs_periods)
@pytest.mark.parametrize("fill_method", ["pad", "ffill", None])
... |
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... |
class RFPDupeFilter(BaseDupeFilter):
self.logger = logging.getLogger(__name__)
if path:
self.file = open(os.path.join(path, 'requests.seen'), 'a+')
self.fingerprints.update(x.rstrip() for x in self.file)
@classmethod | class RFPDupeFilter(BaseDupeFilter):
self.logger = logging.getLogger(__name__)
if path:
self.file = open(os.path.join(path, 'requests.seen'), 'a+')
self.file.seek(0)
self.fingerprints.update(x.rstrip() for x in self.file)
@classmethod |
import hashlib
import unittest
from scrapy.dupefilters import RFPDupeFilter
from scrapy.http import Request | import hashlib
import tempfile
import unittest
import shutil
from scrapy.dupefilters import RFPDupeFilter
from scrapy.http import Request |
class RFPDupeFilterTest(unittest.TestCase):
dupefilter.close('finished')
def test_request_fingerprint(self):
"""Test if customization of request_fingerprint method will change
output of request_seen. | class RFPDupeFilterTest(unittest.TestCase):
dupefilter.close('finished')
def test_dupefilter_path(self):
r1 = Request('http://scrapytest.org/1')
r2 = Request('http://scrapytest.org/2')
path = tempfile.mkdtemp()
try:
df = RFPDupeFilter(path)
df.open(... |
RETURN = """
- values from the environment variables.
type: list
"""
import os
from ansible.plugins.lookup import LookupBase
class LookupModule(LookupBase): | RETURN = """
- values from the environment variables.
type: list
"""
from ansible.plugins.lookup import LookupBase
from ansible.utils import py3compat
class LookupModule(LookupBase): |
class LookupModule(LookupBase):
ret = []
for term in terms:
var = term.split()[0]
ret.append(os.getenv(var, ''))
return ret | class LookupModule(LookupBase):
ret = []
for term in terms:
var = term.split()[0]
ret.append(py3compat.environ.get(var, ''))
return ret |
class ColorbarBase(_ColorbarMappableDummy):
def set_label(self, label, **kw):
"""Label the long axis of the colorbar."""
self._label = str(label)
self._labelkw = kw
self._set_label()
| class ColorbarBase(_ColorbarMappableDummy):
def set_label(self, label, **kw):
"""Label the long axis of the colorbar."""
self._label = label
self._labelkw = kw
self._set_label()
|
def test_mappable_no_alpha():
fig.colorbar(sm)
sm.set_cmap('plasma')
plt.draw() | def test_mappable_no_alpha():
fig.colorbar(sm)
sm.set_cmap('plasma')
plt.draw()
def test_colorbar_label():
"""
Test the label parameter. It should just be mapped to the xlabel/ylabel of
the axes, depending on the orientation.
"""
fig, ax = plt.subplots()
im = ax.imshow([[1, 2], [3,... |
def test_buffer_size(fig_test, fig_ref):
ax = fig_ref.add_subplot()
ax.set_yticks([0, 1])
ax.set_yticklabels(["€", ""]) | def test_buffer_size(fig_test, fig_ref):
ax = fig_ref.add_subplot()
ax.set_yticks([0, 1])
ax.set_yticklabels(["€", ""])
def test_fontproperties_kwarg_precedence():
"""Test that kwargs take precedence over fontproperties defaults."""
plt.figure()
text1 = plt.xlabel("value", fontproperties='Time... |
class Text(Artist):
def update(self, kwargs):
# docstring inherited
# Update bbox last, as it depends on font properties.
sentinel = object() # bbox can be None, so use another sentinel.
bbox = kwargs.pop("bbox", sentinel)
super().update(kwargs)
if bbox is not senti... | class Text(Artist):
def update(self, kwargs):
# docstring inherited
sentinel = object() # bbox can be None, so use another sentinel.
# Update fontproperties first, as it has lowest priority.
fontproperties = kwargs.pop("fontproperties", sentinel)
if fontproperties is not se... |
# this is a package
__version__ = "4.6.4"
def get_include(): | # this is a package
__version__ = "4.6.5"
def get_include(): |
def handle_write(self):
if self.will_close:
self.handle_close()
def _flush_exception(self, flush):
if flush:
try:
return (flush(), False)
except OSError:
if self.adj.log_socket_errors:
self.logger.exception("Soc... | def handle_write(self):
if self.will_close:
self.handle_close()
def _flush_exception(self, flush, do_close=True):
if flush:
try:
return (flush(do_close=do_close), False)
except OSError:
if self.adj.log_socket_errors:
... |
def received(self, data):
return True
def _flush_some_if_lockable(self):
# Since our task may be appending to the outbuf, we try to acquire
# the lock, but we don't block if we can't.
if self.outbuf_lock.acquire(False):
try:
self._flush_some()
... | def received(self, data):
return True
def _flush_some_if_lockable(self, do_close=True):
# Since our task may be appending to the outbuf, we try to acquire
# the lock, but we don't block if we can't.
if self.outbuf_lock.acquire(False):
try:
self._flush_s... |
def _flush_some(self):
while outbuflen > 0:
chunk = outbuf.get(self.sendbuf_len)
num_sent = self.send(chunk)
if num_sent:
outbuf.skip(num_sent, True) | def _flush_some(self):
while outbuflen > 0:
chunk = outbuf.get(self.sendbuf_len)
num_sent = self.send(chunk, do_close=do_close)
if num_sent:
outbuf.skip(num_sent, True) |
def write_soon(self, data):
self.total_outbufs_len += num_bytes
if self.total_outbufs_len >= self.adj.send_bytes:
(flushed, exception) = self._flush_exception(self._flush_some)
if (
exception | def write_soon(self, data):
self.total_outbufs_len += num_bytes
if self.total_outbufs_len >= self.adj.send_bytes:
(flushed, exception) = self._flush_exception(
self._flush_some, do_close=False
)
if (
... |
def _flush_outbufs_below_high_watermark(self):
if self.total_outbufs_len > self.adj.outbuf_high_watermark:
with self.outbuf_lock:
(_, exception) = self._flush_exception(self._flush_some)
if exception:
# An exception happened while flushing, wake ... | def _flush_outbufs_below_high_watermark(self):
if self.total_outbufs_len > self.adj.outbuf_high_watermark:
with self.outbuf_lock:
(_, exception) = self._flush_exception(self._flush_some, do_close=False)
if exception:
# An exception happened while... |
def accept(self):
else:
return conn, addr
def send(self, data):
try:
result = self.socket.send(data)
return result | def accept(self):
else:
return conn, addr
def send(self, data, do_close=True):
try:
result = self.socket.send(data)
return result |
def send(self, data):
if why.args[0] == EWOULDBLOCK:
return 0
elif why.args[0] in _DISCONNECTED:
self.handle_close()
return 0
else:
raise | def send(self, data):
if why.args[0] == EWOULDBLOCK:
return 0
elif why.args[0] in _DISCONNECTED:
if do_close:
self.handle_close()
return 0
else:
raise |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.