buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
def test_connected_ids():
test ckminion connected_ids when
local_port_tcp returns 127.0.0.1
"""
opts = {"publish_port": 4505}
minion = "minion"
ip = salt.utils.network.ip_addrs()
mdata = {"grains": {"ipv4": ip, "ipv6": []}}
ckminions = salt.utils.minions.CkMinions({"minion_data_cache": T... | def test_connected_ids():
test ckminion connected_ids when
local_port_tcp returns 127.0.0.1
"""
opts = {"publish_port": 4505, "minion_data_cache": True}
minion = "minion"
ip = salt.utils.network.ip_addrs()
mdata = {"grains": {"ipv4": ip, "ipv6": []}}
patch_net = patch("salt.utils.network... |
import OFS.interfaces
from AccessControl import safe_builtins
from Acquisition import aq_base
from MultiMapping import MultiMapping
from zExceptions import NotFound |
import OFS.interfaces
from AccessControl import safe_builtins
from AccessControl.SecurityManagement import getSecurityManager
from Acquisition import aq_base
from MultiMapping import MultiMapping
from zExceptions import NotFound |
def boboAwareZopeTraverse(object, path_items, econtext):
necessary (bobo-awareness).
"""
request = getattr(econtext, 'request', None)
path_items = list(path_items)
path_items.reverse()
while path_items:
name = path_items.pop()
if name == '_':
warnings.warn('Traversi... | def boboAwareZopeTraverse(object, path_items, econtext):
necessary (bobo-awareness).
"""
request = getattr(econtext, 'request', None)
validate = getSecurityManager().validate
path_items = list(path_items)
path_items.reverse()
while path_items:
name = path_items.pop()
if OFS... |
from chameleon.tales import NotExpr
from chameleon.tales import StringExpr
from AccessControl.ZopeGuards import guarded_apply
from AccessControl.ZopeGuards import guarded_getattr
from AccessControl.ZopeGuards import guarded_getitem | from chameleon.tales import NotExpr
from chameleon.tales import StringExpr
from AccessControl.SecurityManagement import getSecurityManager
from AccessControl.ZopeGuards import guarded_apply
from AccessControl.ZopeGuards import guarded_getattr
from AccessControl.ZopeGuards import guarded_getitem |
class BoboAwareZopeTraverse:
def traverse(cls, base, request, path_items):
"""See ``zope.app.pagetemplate.engine``."""
path_items = list(path_items)
path_items.reverse()
while path_items:
name = path_items.pop()
if name == '_':
warnings.warn... | class BoboAwareZopeTraverse:
def traverse(cls, base, request, path_items):
"""See ``zope.app.pagetemplate.engine``."""
validate = getSecurityManager().validate
path_items = list(path_items)
path_items.reverse()
while path_items:
name = path_items.pop()
... |
from AccessControl import safe_builtins
from zExceptions import NotFound
from zope.component.testing import PlacelessSetup
class EngineTestsBase(PlacelessSetup): | from AccessControl import safe_builtins
from zExceptions import NotFound
from zope.component.testing import PlacelessSetup
from zope.location.interfaces import LocationError
class EngineTestsBase(PlacelessSetup): |
def test_underscore_traversal(self):
with self.assertRaises(NotFound):
ec.evaluate("context/__class__")
with self.assertRaises(NotFound):
ec.evaluate("nocall: random/_itertools/repeat")
with self.assertRaises(NotFound):
ec.evaluate("random/_itertools/repeat/... | def test_underscore_traversal(self):
with self.assertRaises(NotFound):
ec.evaluate("context/__class__")
with self.assertRaises((NotFound, LocationError)):
ec.evaluate("nocall: random/_itertools/repeat")
with self.assertRaises((NotFound, LocationError)):
ec.e... |
DefaultUnicodeEncodingConflictResolver
from Products.PageTemplates.unicodeconflictresolver import \
PreferredCharsetResolver
from zExceptions import NotFound
from zope.component import provideUtility
from zope.traversing.adapters import DefaultTraversable
from .util import useChameleonEngine | DefaultUnicodeEncodingConflictResolver
from Products.PageTemplates.unicodeconflictresolver import \
PreferredCharsetResolver
from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate
from zExceptions import NotFound
from zope.component import provideUtility
from zope.location.interfaces import Locati... |
class AqPageTemplate(Implicit, PageTemplate):
pass
class Folder(util.Base):
pass
| class AqPageTemplate(Implicit, PageTemplate):
pass
class AqZopePageTemplate(Implicit, ZopePageTemplate):
pass
class Folder(util.Base):
pass
|
def setUp(self):
self.folder = f = Folder()
f.laf = AqPageTemplate()
f.t = AqPageTemplate()
self.policy = UnitTestSecurityPolicy()
self.oldPolicy = SecurityManager.setSecurityPolicy(self.policy)
noSecurityManager() # Use the new policy. | def setUp(self):
self.folder = f = Folder()
f.laf = AqPageTemplate()
f.t = AqPageTemplate()
f.z = AqZopePageTemplate('testing')
self.policy = UnitTestSecurityPolicy()
self.oldPolicy = SecurityManager.setSecurityPolicy(self.policy)
noSecurityManager() # Use the ne... |
def test_underscore_traversal(self):
t()
t.write('<p tal:define="p nocall: random/_itertools/repeat"/>')
with self.assertRaises(NotFound):
t()
t.write('<p tal:content="random/_itertools/repeat/foobar"/>')
with self.assertRaises(NotFound):
t() | def test_underscore_traversal(self):
t()
t.write('<p tal:define="p nocall: random/_itertools/repeat"/>')
with self.assertRaises((NotFound, LocationError)):
t()
t.write('<p tal:content="random/_itertools/repeat/foobar"/>')
with self.assertRaises((NotFound, Locati... |
from pandas.core.dtypes.common import (
is_bool,
is_bool_dtype,
is_categorical_dtype,
is_datetime64_dtype,
is_datetime64tz_dtype,
is_datetimelike,
is_dtype_equal, | from pandas.core.dtypes.common import (
is_bool,
is_bool_dtype,
is_categorical_dtype,
is_datetime64tz_dtype,
is_datetimelike,
is_dtype_equal, |
class _AsOfMerge(_OrderedMerge):
)
)
if is_datetime64_dtype(lt) or is_datetime64tz_dtype(lt):
if not isinstance(self.tolerance, Timedelta):
raise MergeError(msg)
if self.tolerance < Timedelta(0): | class _AsOfMerge(_OrderedMerge):
)
)
if is_datetimelike(lt):
if not isinstance(self.tolerance, Timedelta):
raise MergeError(msg)
if self.tolerance < Timedelta(0): |
import numpy as np
import pytest
import pytz | import datetime
import numpy as np
import pytest
import pytz |
class TestAsOfMerge:
# ok, though has dupes
merge_asof(trades, self.quotes, on="time", by="ticker")
def test_tolerance(self):
trades = self.trades
quotes = self.quotes
result = merge_asof(
trades, quotes, on="time", by="ticker", tolerance=Timedelta("1day")
... | class TestAsOfMerge:
# ok, though has dupes
merge_asof(trades, self.quotes, on="time", by="ticker")
@pytest.mark.parametrize(
"tolerance",
[
Timedelta("1day"),
pytest.param(
datetime.timedelta(days=1),
marks=pytest.mark.xfail(r... |
class TestAsOfMerge:
)
expected["value_y"] = np.array([np.nan], dtype=object)
assert_frame_equal(result, expected) | class TestAsOfMerge:
)
expected["value_y"] = np.array([np.nan], dtype=object)
assert_frame_equal(result, expected)
def test_timedelta_tolerance_nearest(self):
# GH 27642
left = pd.DataFrame(
list(zip([0, 5, 10, 15, 20, 25], [0, 1, 2, 3, 4, 5])),
colu... |
from django.db import NotSupportedError, transaction
from django.db.backends import utils
from django.utils import timezone
from django.utils.encoding import force_str
from django.utils.regex_helper import _lazy_re_compile
class BaseDatabaseOperations: | from django.db import NotSupportedError, transaction
from django.db.backends import utils
from django.utils import timezone
from django.utils.encoding import force_str
class BaseDatabaseOperations: |
class BaseDatabaseOperations:
# Prefix for EXPLAIN queries, or None EXPLAIN isn't supported.
explain_prefix = None
extract_trunc_lookup_pattern = _lazy_re_compile(r"[\w\-_()]+")
def __init__(self, connection):
self.connection = connection
self._cache = None | class BaseDatabaseOperations:
# Prefix for EXPLAIN queries, or None EXPLAIN isn't supported.
explain_prefix = None
def __init__(self, connection):
self.connection = connection
self._cache = None |
class BaseDatabaseOperations:
"""
return "%s"
def date_extract_sql(self, lookup_type, field_name):
"""
Given a lookup_type of 'year', 'month', or 'day', return the SQL that
extracts a value from the given date field field_name. | class BaseDatabaseOperations:
"""
return "%s"
def date_extract_sql(self, lookup_type, sql, params):
"""
Given a lookup_type of 'year', 'month', or 'day', return the SQL that
extracts a value from the given date field field_name. |
class BaseDatabaseOperations:
"method"
)
def date_trunc_sql(self, lookup_type, field_name, tzname=None):
"""
Given a lookup_type of 'year', 'month', or 'day', return the SQL that
truncates the given date or datetime field field_name to a date object | class BaseDatabaseOperations:
"method"
)
def date_trunc_sql(self, lookup_type, sql, params, tzname=None):
"""
Given a lookup_type of 'year', 'month', or 'day', return the SQL that
truncates the given date or datetime field field_name to a date object |
class BaseDatabaseOperations:
"method."
)
def datetime_cast_date_sql(self, field_name, tzname):
"""
Return the SQL to cast a datetime value to date value.
""" | class BaseDatabaseOperations:
"method."
)
def datetime_cast_date_sql(self, sql, params, tzname):
"""
Return the SQL to cast a datetime value to date value.
""" |
class BaseDatabaseOperations:
"datetime_cast_date_sql() method."
)
def datetime_cast_time_sql(self, field_name, tzname):
"""
Return the SQL to cast a datetime value to time value.
""" | class BaseDatabaseOperations:
"datetime_cast_date_sql() method."
)
def datetime_cast_time_sql(self, sql, params, tzname):
"""
Return the SQL to cast a datetime value to time value.
""" |
class BaseDatabaseOperations:
"datetime_cast_time_sql() method"
)
def datetime_extract_sql(self, lookup_type, field_name, tzname):
"""
Given a lookup_type of 'year', 'month', 'day', 'hour', 'minute', or
'second', return the SQL that extracts a value from the given | class BaseDatabaseOperations:
"datetime_cast_time_sql() method"
)
def datetime_extract_sql(self, lookup_type, sql, params, tzname):
"""
Given a lookup_type of 'year', 'month', 'day', 'hour', 'minute', or
'second', return the SQL that extracts a value from the given |
class BaseDatabaseOperations:
"method"
)
def datetime_trunc_sql(self, lookup_type, field_name, tzname):
"""
Given a lookup_type of 'year', 'month', 'day', 'hour', 'minute', or
'second', return the SQL that truncates the given datetime field | class BaseDatabaseOperations:
"method"
)
def datetime_trunc_sql(self, lookup_type, sql, params, tzname):
"""
Given a lookup_type of 'year', 'month', 'day', 'hour', 'minute', or
'second', return the SQL that truncates the given datetime field |
class BaseDatabaseOperations:
"method"
)
def time_trunc_sql(self, lookup_type, field_name, tzname=None):
"""
Given a lookup_type of 'hour', 'minute' or 'second', return the SQL
that truncates the given time or datetime field field_name to a time | class BaseDatabaseOperations:
"method"
)
def time_trunc_sql(self, lookup_type, sql, params, tzname=None):
"""
Given a lookup_type of 'hour', 'minute' or 'second', return the SQL
that truncates the given time or datetime field field_name to a time |
class BaseDatabaseOperations:
"subclasses of BaseDatabaseOperations may require a time_trunc_sql() method"
)
def time_extract_sql(self, lookup_type, field_name):
"""
Given a lookup_type of 'hour', 'minute', or 'second', return the SQL
that extracts a value from the given... | class BaseDatabaseOperations:
"subclasses of BaseDatabaseOperations may require a time_trunc_sql() method"
)
def time_extract_sql(self, lookup_type, sql, params):
"""
Given a lookup_type of 'hour', 'minute', or 'second', return the SQL
that extracts a value from the give... |
from django.db.models import Exists, ExpressionWrapper, Lookup
from django.db.models.constants import OnConflict
from django.utils import timezone
from django.utils.encoding import force_str
class DatabaseOperations(BaseDatabaseOperations): | from django.db.models import Exists, ExpressionWrapper, Lookup
from django.db.models.constants import OnConflict
from django.utils import timezone
from django.utils.encoding import force_str
from django.utils.regex_helper import _lazy_re_compile
class DatabaseOperations(BaseDatabaseOperations): |
class DatabaseOperations(BaseDatabaseOperations):
cast_char_field_without_max_length = "char"
explain_prefix = "EXPLAIN"
def date_extract_sql(self, lookup_type, field_name):
# https://dev.mysql.com/doc/mysql/en/date-and-time-functions.html
if lookup_type == "week_day":
# DAYOFWE... | class DatabaseOperations(BaseDatabaseOperations):
cast_char_field_without_max_length = "char"
explain_prefix = "EXPLAIN"
# EXTRACT format cannot be passed in parameters.
_extract_format_re = _lazy_re_compile(r"[A-Z_]+")
def date_extract_sql(self, lookup_type, sql, params):
# https://dev.my... |
END;
f"ORDER BY {cache_key} OFFSET %%s ROWS FETCH FIRST 1 ROWS ONLY"
)
def date_extract_sql(self, lookup_type, field_name):
if lookup_type == "week_day":
# TO_CHAR(field, 'D') returns an integer from 1-7, where 1=Sunday.
return "TO_CHAR(%s, 'D')" % field_name
... | END;
f"ORDER BY {cache_key} OFFSET %%s ROWS FETCH FIRST 1 ROWS ONLY"
)
# EXTRACT format cannot be passed in parameters.
_extract_format_re = _lazy_re_compile(r"[A-Z_]+")
def date_extract_sql(self, lookup_type, sql, params):
extract_sql = f"TO_CHAR({sql}, %s)"
extract_pa... |
END;
tzname, sign, offset = split_tzname_delta(tzname)
return f"{sign}{offset}" if offset else tzname
def _convert_field_to_tz(self, field_name, tzname):
if not (settings.USE_TZ and tzname):
return field_name
if not self._tzname_re.match(tzname):
raise ValueE... | END;
tzname, sign, offset = split_tzname_delta(tzname)
return f"{sign}{offset}" if offset else tzname
def _convert_field_to_tz(self, sql, params, tzname):
if not (settings.USE_TZ and tzname):
return sql, params
if not self._tzname_re.match(tzname):
raise Valu... |
class DatabaseOperations(BaseDatabaseOperations):
)
return "%s"
def date_extract_sql(self, lookup_type, field_name):
# https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT
if lookup_type == "week_day":
# For consistency across ba... | class DatabaseOperations(BaseDatabaseOperations):
)
return "%s"
def date_extract_sql(self, lookup_type, sql, params):
# https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT
extract_sql = f"EXTRACT(%s FROM {sql})"
extract_param = look... |
class DatabaseOperations(BaseDatabaseOperations):
return f"{tzname}{sign}{offset}"
return tzname
def _convert_field_to_tz(self, field_name, tzname):
if tzname and settings.USE_TZ:
field_name = "%s AT TIME ZONE '%s'" % (
field_name,
self._prepa... | class DatabaseOperations(BaseDatabaseOperations):
return f"{tzname}{sign}{offset}"
return tzname
def _convert_sql_to_tz(self, sql, params, tzname):
if tzname and settings.USE_TZ:
tzname_param = self._prepare_tzname_delta(tzname)
return f"{sql} AT TIME ZONE %s", (... |
class DatabaseOperations(BaseDatabaseOperations):
"accepting multiple arguments."
)
def date_extract_sql(self, lookup_type, field_name):
"""
Support EXTRACT with a user-defined function django_date_extract()
that's registered in connect(). Use single quotes becau... | class DatabaseOperations(BaseDatabaseOperations):
"accepting multiple arguments."
)
def date_extract_sql(self, lookup_type, sql, params):
"""
Support EXTRACT with a user-defined function django_date_extract()
that's registered in connect(). Use single quotes beca... |
class DatabaseOperations(BaseDatabaseOperations):
"""Do nothing since formatting is handled in the custom function."""
return sql
def date_trunc_sql(self, lookup_type, field_name, tzname=None):
return "django_date_trunc('%s', %s, %s, %s)" % (
lookup_type.lower(),
fie... | class DatabaseOperations(BaseDatabaseOperations):
"""Do nothing since formatting is handled in the custom function."""
return sql
def date_trunc_sql(self, lookup_type, sql, params, tzname=None):
return f"django_date_trunc(%s, {sql}, %s, %s)", (
lookup_type.lower(),
*... |
class Extract(TimezoneMixin, Transform):
super().__init__(expression, **extra)
def as_sql(self, compiler, connection):
if not connection.ops.extract_trunc_lookup_pattern.fullmatch(self.lookup_name):
raise ValueError("Invalid lookup_name: %s" % self.lookup_name)
sql, params = com... | class Extract(TimezoneMixin, Transform):
super().__init__(expression, **extra)
def as_sql(self, compiler, connection):
sql, params = compiler.compile(self.lhs)
lhs_output_field = self.lhs.output_field
if isinstance(lhs_output_field, DateTimeField):
tzname = self.get_tzna... |
class TruncBase(TimezoneMixin, Transform):
super().__init__(expression, output_field=output_field, **extra)
def as_sql(self, compiler, connection):
if not connection.ops.extract_trunc_lookup_pattern.fullmatch(self.kind):
raise ValueError("Invalid kind: %s" % self.kind)
inner_sql... | class TruncBase(TimezoneMixin, Transform):
super().__init__(expression, output_field=output_field, **extra)
def as_sql(self, compiler, connection):
sql, params = compiler.compile(self.lhs)
tzname = None
if isinstance(self.lhs.output_field, DateTimeField):
tzname = self.g... |
class TruncDate(TruncBase):
def as_sql(self, compiler, connection):
# Cast to date rather than truncate to date.
lhs, lhs_params = compiler.compile(self.lhs)
tzname = self.get_tzname()
sql = connection.ops.datetime_cast_date_sql(lhs, tzname)
return sql, lhs_params
class Tr... | class TruncDate(TruncBase):
def as_sql(self, compiler, connection):
# Cast to date rather than truncate to date.
sql, params = compiler.compile(self.lhs)
tzname = self.get_tzname()
return connection.ops.datetime_cast_date_sql(sql, tuple(params), tzname)
class TruncTime(TruncBase): |
class TruncTime(TruncBase):
def as_sql(self, compiler, connection):
# Cast to time rather than truncate to time.
lhs, lhs_params = compiler.compile(self.lhs)
tzname = self.get_tzname()
sql = connection.ops.datetime_cast_time_sql(lhs, tzname)
return sql, lhs_params
class Tr... | class TruncTime(TruncBase):
def as_sql(self, compiler, connection):
# Cast to time rather than truncate to time.
sql, params = compiler.compile(self.lhs)
tzname = self.get_tzname()
return connection.ops.datetime_cast_time_sql(sql, tuple(params), tzname)
class TruncHour(TruncBase): |
class SimpleDatabaseOperationTests(SimpleTestCase):
with self.assertRaisesMessage(
NotImplementedError, self.may_require_msg % "date_extract_sql"
):
self.ops.date_extract_sql(None, None)
def test_time_extract_sql(self):
with self.assertRaisesMessage(
NotI... | class SimpleDatabaseOperationTests(SimpleTestCase):
with self.assertRaisesMessage(
NotImplementedError, self.may_require_msg % "date_extract_sql"
):
self.ops.date_extract_sql(None, None, None)
def test_time_extract_sql(self):
with self.assertRaisesMessage(
... |
class YearTransform(models.Transform):
def as_sql(self, compiler, connection):
lhs_sql, params = compiler.compile(self.lhs)
return connection.ops.date_extract_sql("year", lhs_sql), params
@property
def output_field(self): | class YearTransform(models.Transform):
def as_sql(self, compiler, connection):
lhs_sql, params = compiler.compile(self.lhs)
return connection.ops.date_extract_sql("year", lhs_sql, params)
@property
def output_field(self): |
except ImportError:
pytz = None
from django.conf import settings
from django.db.models import (
DateField,
DateTimeField, | except ImportError:
pytz = None
from django.conf import settings
from django.db import DataError, OperationalError
from django.db.models import (
DateField,
DateTimeField, |
class DateFunctionTests(TestCase):
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
msg = "Invalid lookup_name: "
with self.assertRaisesMessage(ValueError, msg):
DTModel.objects.filter(
start_datetime__year=Extra... | class DateFunctionTests(TestCase):
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
with self.assertRaises((DataError, OperationalError, ValueError)):
DTModel.objects.filter(
start_datetime__year=Extract(
... |
class DateFunctionTests(TestCase):
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
msg = "Invalid kind: "
with self.assertRaisesMessage(ValueError, msg):
DTModel.objec... | class DateFunctionTests(TestCase):
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
# Database backends raise an exception or don't return any results.
try:
exists = DT... |
from tests.utils import Command
Command(script='open foo.org'),
Command(script='open foo.net'),
Command(script='open foo.se'),
Command(script='open foo.io')])
def test_match(command):
assert match(command, None)
| from tests.utils import Command
Command(script='open foo.org'),
Command(script='open foo.net'),
Command(script='open foo.se'),
Command(script='open foo.io'),
Command(script='xdg-open foo.com'),
Command(script='gnome-open foo.com'),
Command(script='kde-open foo.com')])
def test_match(command)... |
def test_match(command):
(Command('open foo.org'), 'open http://foo.org'),
(Command('open foo.net'), 'open http://foo.net'),
(Command('open foo.se'), 'open http://foo.se'),
(Command('open foo.io'), 'open http://foo.io')])
def test_get_new_command(command, new_command):
assert get_new_command(command... | def test_match(command):
(Command('open foo.org'), 'open http://foo.org'),
(Command('open foo.net'), 'open http://foo.net'),
(Command('open foo.se'), 'open http://foo.se'),
(Command('open foo.io'), 'open http://foo.io'),
(Command('xdg-open foo.io'), 'xdg-open http://foo.io'),
(Command('gnome-ope... |
def match(command, settings):
def get_new_command(command, settings):
return 'open http://' + command.script[5:] | def match(command, settings):
def get_new_command(command, settings):
return command.script.replace('open ', 'open http://') |
def get_meta_refresh(response):
def response_status_message(status):
"""Return status code plus status text descriptive message
>>> response_status_message(200)
'200 OK'
>>> response_status_message(404)
'404 Not Found'
"""
return '%s %s' % (status, to_native_str(http.RESPONSES.get(int(sta... | def get_meta_refresh(response):
def response_status_message(status):
"""Return status code plus status text descriptive message
"""
return '%s %s' % (status, to_native_str(http.RESPONSES.get(int(status), "Unknown Status")))
def response_httprepr(response): |
from six.moves.urllib.parse import urlparse
from scrapy.http import Response, TextResponse, HtmlResponse
from scrapy.utils.python import to_bytes
from scrapy.utils.response import (response_httprepr, open_in_browser,
get_meta_refresh, get_base_url)
__doctests__ = ['scrapy.utils.respo... | from six.moves.urllib.parse import urlparse
from scrapy.http import Response, TextResponse, HtmlResponse
from scrapy.utils.python import to_bytes
from scrapy.utils.response import (response_httprepr, open_in_browser,
get_meta_refresh, get_base_url, response_status_message)
__doctests... |
class ResponseUtilsTest(unittest.TestCase):
resp2 = HtmlResponse("http://www.example.com", body=b"""
<html><body>blahablsdfsal&</body></html>""")
self.assertEqual(get_base_url(resp2), "http://www.example.com") | class ResponseUtilsTest(unittest.TestCase):
resp2 = HtmlResponse("http://www.example.com", body=b"""
<html><body>blahablsdfsal&</body></html>""")
self.assertEqual(get_base_url(resp2), "http://www.example.com")
def test_response_status_message(self):
self.assertEqual(response_sta... |
class Index(IndexOpsMixin, PandasObject):
pass
# Return an actual float index.
return Float64Index(data, copy=copy, dtype=dtype, name=name)
elif inferred == "string":
pass | class Index(IndexOpsMixin, PandasObject):
pass
# Return an actual float index.
return Float64Index(data, copy=copy, name=name)
elif inferred == "string":
pass |
from pandas.core.dtypes.common import (
is_float_dtype,
is_integer_dtype,
is_scalar,
needs_i8_conversion,
pandas_dtype,
) | from pandas.core.dtypes.common import (
is_float_dtype,
is_integer_dtype,
is_scalar,
is_signed_integer_dtype,
is_unsigned_integer_dtype,
needs_i8_conversion,
pandas_dtype,
) |
from pandas.core.dtypes.generic import (
)
from pandas.core.dtypes.missing import isna
from pandas.core import algorithms
import pandas.core.common as com
from pandas.core.indexes.base import Index, InvalidIndexError, _index_shared_docs | from pandas.core.dtypes.generic import (
)
from pandas.core.dtypes.missing import isna
from pandas._typing import Dtype
from pandas.core import algorithms
import pandas.core.common as com
from pandas.core.indexes.base import Index, InvalidIndexError, _index_shared_docs |
class NumericIndex(Index):
_is_numeric_dtype = True
def __new__(cls, data=None, dtype=None, copy=False, name=None, fastpath=None):
if fastpath is not None:
warnings.warn(
"The 'fastpath' keyword is deprecated, and will be " | class NumericIndex(Index):
_is_numeric_dtype = True
def __new__(cls, data=None, dtype=None, copy=False, name=None, fastpath=None):
cls._validate_dtype(dtype)
if fastpath is not None:
warnings.warn(
"The 'fastpath' keyword is deprecated, and will be " |
class NumericIndex(Index):
name = data.name
return cls._simple_new(subarr, name=name)
@Appender(_index_shared_docs["_maybe_cast_slice_bound"])
def _maybe_cast_slice_bound(self, label, side, kind):
assert kind in ["ix", "loc", "getitem", None] | class NumericIndex(Index):
name = data.name
return cls._simple_new(subarr, name=name)
@classmethod
def _validate_dtype(cls, dtype: Dtype) -> None:
if dtype is None:
return
validation_metadata = {
"int64index": (is_signed_integer_dtype, "signed integer... |
from pandas.util._decorators import Appender, cache_readonly
from pandas.core.dtypes.common import (
ensure_platform_int,
ensure_python_int,
is_int64_dtype,
is_integer,
is_integer_dtype,
is_list_like, | from pandas.util._decorators import Appender, cache_readonly
from pandas.core.dtypes.common import (
ensure_platform_int,
ensure_python_int,
is_integer,
is_integer_dtype,
is_list_like, |
class RangeIndex(Int64Index):
# --------------------------------------------------------------------
@staticmethod
def _validate_dtype(dtype):
""" require dtype to be None or int64 """
if not (dtype is None or is_int64_dtype(dtype)):
raise TypeError("Invalid to pass a non-int64... | class RangeIndex(Int64Index):
# --------------------------------------------------------------------
@cache_readonly
def _constructor(self):
""" return the class to use for construction """ |
class TestFloat64Index(Numeric):
result = Index(np.array([np.nan]))
assert pd.isna(result.values).all()
def test_constructor_invalid(self):
# invalid | class TestFloat64Index(Numeric):
result = Index(np.array([np.nan]))
assert pd.isna(result.values).all()
@pytest.mark.parametrize(
"index, dtype",
[
(pd.Int64Index, "float64"),
(pd.UInt64Index, "categorical"),
(pd.Float64Index, "datetime64"),
... |
class TestRangeIndex(Numeric):
result = RangeIndex(index)
tm.assert_index_equal(result, index, exact=True)
with pytest.raises(TypeError):
RangeIndex(index, dtype="float64")
def test_constructor_range(self): | class TestRangeIndex(Numeric):
result = RangeIndex(index)
tm.assert_index_equal(result, index, exact=True)
with pytest.raises(
ValueError,
match="Incorrect `dtype` passed: expected signed integer, received float64",
):
RangeIndex(index, dtype="float64... |
class TestRangeIndex(Numeric):
expected = RangeIndex(1, 5, 2)
tm.assert_index_equal(result, expected, exact=True)
with pytest.raises(TypeError):
Index(range(1, 5, 2), dtype="float64")
msg = r"^from_range\(\) got an unexpected keyword argument"
with pytest.raises(Type... | class TestRangeIndex(Numeric):
expected = RangeIndex(1, 5, 2)
tm.assert_index_equal(result, expected, exact=True)
with pytest.raises(
ValueError,
match="Incorrect `dtype` passed: expected signed integer, received float64",
):
Index(range(1, 5, 2), dty... |
class TestRangeIndex(Numeric):
RangeIndex(1.1, 10.2, 1.3)
# invalid passed type
with pytest.raises(TypeError):
RangeIndex(1, 5, dtype="float64")
@pytest.mark.parametrize( | class TestRangeIndex(Numeric):
RangeIndex(1.1, 10.2, 1.3)
# invalid passed type
with pytest.raises(
ValueError,
match="Incorrect `dtype` passed: expected signed integer, received float64",
):
RangeIndex(1, 5, dtype="float64")
@pytest.mark.par... |
def test_get():
1764.0,
1849.0,
1936.0,
],
dtype="object",
),
)
| def test_get():
1764.0,
1849.0,
1936.0,
]
),
)
|
from django.utils.text import (
from django.utils.timesince import timesince, timeuntil
from django.utils.translation import gettext, ngettext
from .base import Variable, VariableDoesNotExist
from .library import Library
register = Library() | from django.utils.text import (
from django.utils.timesince import timesince, timeuntil
from django.utils.translation import gettext, ngettext
from .base import VARIABLE_ATTRIBUTE_SEPARATOR
from .library import Library
register = Library() |
def striptags(value):
def _property_resolver(arg):
"""
When arg is convertible to float, behave like operator.itemgetter(arg)
Otherwise, behave like Variable(arg).resolve
>>> _property_resolver(1)('abc')
'b' | def striptags(value):
def _property_resolver(arg):
"""
When arg is convertible to float, behave like operator.itemgetter(arg)
Otherwise, chain __getitem__() and getattr().
>>> _property_resolver(1)('abc')
'b' |
def _property_resolver(arg):
try:
float(arg)
except ValueError:
return Variable(arg).resolve
else:
return itemgetter(arg)
| def _property_resolver(arg):
try:
float(arg)
except ValueError:
if VARIABLE_ATTRIBUTE_SEPARATOR + '_' in arg or arg[0] == '_':
raise AttributeError('Access to private variables is forbidden.')
parts = arg.split(VARIABLE_ATTRIBUTE_SEPARATOR)
def resolve(value):
... |
def dictsort(value, arg):
"""
try:
return sorted(value, key=_property_resolver(arg))
except (TypeError, VariableDoesNotExist):
return ''
| def dictsort(value, arg):
"""
try:
return sorted(value, key=_property_resolver(arg))
except (AttributeError, TypeError):
return ''
|
def dictsortreversed(value, arg):
"""
try:
return sorted(value, key=_property_resolver(arg), reverse=True)
except (TypeError, VariableDoesNotExist):
return ''
| def dictsortreversed(value, arg):
"""
try:
return sorted(value, key=_property_resolver(arg), reverse=True)
except (AttributeError, TypeError):
return ''
|
from django.template.defaultfilters import dictsort
from django.test import SimpleTestCase
class FunctionTests(SimpleTestCase):
def test_sort(self):
sorted_dicts = dictsort(
[{'age': 23, 'name': 'Barbara-Ann'}, | from django.template.defaultfilters import _property_resolver, dictsort
from django.test import SimpleTestCase
class User:
password = 'abc'
_private = 'private'
@property
def test_property(self):
return 'cde'
def test_method(self):
"""This is just a test method."""
class Funct... |
class FunctionTests(SimpleTestCase):
def test_dictsort_complex_sorting_key(self):
"""
Since dictsort uses template.Variable under the hood, it can sort
on keys like 'foo.bar'.
"""
data = [ | class FunctionTests(SimpleTestCase):
def test_dictsort_complex_sorting_key(self):
"""
Since dictsort uses dict.get()/getattr() under the hood, it can sort
on keys like 'foo.bar'.
"""
data = [ |
class FunctionTests(SimpleTestCase):
self.assertEqual(dictsort('Hello!', 'age'), '')
self.assertEqual(dictsort({'a': 1}, 'age'), '')
self.assertEqual(dictsort(1, 'age'), '') | class FunctionTests(SimpleTestCase):
self.assertEqual(dictsort('Hello!', 'age'), '')
self.assertEqual(dictsort({'a': 1}, 'age'), '')
self.assertEqual(dictsort(1, 'age'), '')
def test_invalid_args(self):
"""Fail silently if invalid lookups are passed."""
self.assertEqual(dict... |
class FunctionTests(SimpleTestCase):
self.assertEqual(dictsortreversed('Hello!', 'age'), '')
self.assertEqual(dictsortreversed({'a': 1}, 'age'), '')
self.assertEqual(dictsortreversed(1, 'age'), '') | class FunctionTests(SimpleTestCase):
self.assertEqual(dictsortreversed('Hello!', 'age'), '')
self.assertEqual(dictsortreversed({'a': 1}, 'age'), '')
self.assertEqual(dictsortreversed(1, 'age'), '')
def test_invalid_args(self):
"""Fail silently if invalid lookups are passed."""
... |
from thefuck.rules.git_diff_staged import match, get_new_command
from tests.utils import Command
@pytest.mark.parametrize('command', [Command(script='git diff')])
def test_match(command):
assert match(command, None)
| from thefuck.rules.git_diff_staged import match, get_new_command
from tests.utils import Command
@pytest.mark.parametrize('command', [
Command(script='git diff foo'),
Command(script='git diff')])
def test_match(command):
assert match(command, None)
|
def test_not_match(command):
@pytest.mark.parametrize('command, new_command', [
(Command('git diff'), 'git diff --staged')])
def test_get_new_command(command, new_command):
assert get_new_command(command, None) == new_command | def test_not_match(command):
@pytest.mark.parametrize('command, new_command', [
(Command('git diff'), 'git diff --staged'),
(Command('git diff foo'), 'git diff --staged foo')])
def test_get_new_command(command, new_command):
assert get_new_command(command, None) == new_command |
def match(command, settings):
@utils.git_support
def get_new_command(command, settings):
return '{} --staged'.format(command.script) | def match(command, settings):
@utils.git_support
def get_new_command(command, settings):
return command.script.replace(' diff', ' diff --staged') |
unencoded_ampersands_re = re.compile(r'&(?!(\w+|#\d+);)')
word_split_re = re.compile(r'(\s+)')
simple_url_re = re.compile(r'^https?://\[?\w', re.IGNORECASE)
simple_url_2_re = re.compile(r'^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)($|/.*)$', re.IGNORECASE)
simple_email_re = re.compile(r'^\S+@\S+\.\S+$')
link... | unencoded_ampersands_re = re.compile(r'&(?!(\w+|#\d+);)')
word_split_re = re.compile(r'(\s+)')
simple_url_re = re.compile(r'^https?://\[?\w', re.IGNORECASE)
simple_url_2_re = re.compile(r'^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)($|/.*)$', re.IGNORECASE)
link_target_attribute_re = re.compile(r'(<a [^>]*?)t... |
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
trail = ''
return text, unescaped, trail
words = word_split_re.split(force_text(text))
for i, word in enumerate(words):
if '.' in word or '@' in word or ':' in word: | def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
trail = ''
return text, unescaped, trail
def is_email_simple(value):
"""Return True if value looks like an email address."""
# An @ must be in the middle of the value.
if '@' not in value or value.s... |
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
elif simple_url_2_re.match(middle):
middle, middle_unescaped, trail = unescape(middle, trail)
url = smart_urlquote('http://%s' % middle_unescaped)
elif ':' not in middle and simple_email_re.m... | def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
elif simple_url_2_re.match(middle):
middle, middle_unescaped, trail = unescape(middle, trail)
url = smart_urlquote('http://%s' % middle_unescaped)
elif ':' not in middle and is_email_simple(m... |
class TestUtilsHtml(SimpleTestCase):
@html.html_safe
class HtmlClass(object):
pass | class TestUtilsHtml(SimpleTestCase):
@html.html_safe
class HtmlClass(object):
pass
def test_urlize_unchanged_inputs(self):
tests = (
('a' + '@a' * 50000) + 'a', # simple_email_re catastrophic test
('a' + '.' * 1000000) + 'a', # trailing_punc... |
class IntervalArray(IntervalMixin, ExtensionArray):
msg = f"'value' should be an interval type, got {type(value)} instead."
raise TypeError(msg) from err
key = check_array_indexer(self, key)
# Need to ensure that left and right are updated atomically, so we're
# ... | class IntervalArray(IntervalMixin, ExtensionArray):
msg = f"'value' should be an interval type, got {type(value)} instead."
raise TypeError(msg) from err
if needs_float_conversion:
raise ValueError("Cannot set float NaN to integer-backed IntervalArray")
key ... |
class TestSetitem:
def test_set_na(self, left_right_dtypes):
left, right = left_right_dtypes
result = IntervalArray.from_arrays(left, right)
result[0] = np.nan
expected_left = Index([left._na_value] + list(left[1:])) | class TestSetitem:
def test_set_na(self, left_right_dtypes):
left, right = left_right_dtypes
result = IntervalArray.from_arrays(left, right)
if result.dtype.subtype.kind in ["i", "u"]:
msg = "Cannot set float NaN to integer-backed IntervalArray"
with pytest.raises(Va... |
def test_arrow_array_missing():
import pyarrow as pa
from pandas.core.arrays._arrow_utils import ArrowIntervalType
arr = IntervalArray.from_breaks([0, 1, 2, 3])
arr[1] = None
result = pa.array(arr) | def test_arrow_array_missing():
import pyarrow as pa
from pandas.core.arrays._arrow_utils import ArrowIntervalType
arr = IntervalArray.from_breaks([0.0, 1.0, 2.0, 3.0])
arr[1] = None
result = pa.array(arr) |
def test_arrow_array_missing():
@pyarrow_skip
@pytest.mark.parametrize(
"breaks",
[[0, 1, 2, 3], pd.date_range("2017", periods=4, freq="D")],
ids=["int", "datetime64[ns]"],
)
def test_arrow_table_roundtrip(breaks):
import pyarrow as pa | def test_arrow_array_missing():
@pyarrow_skip
@pytest.mark.parametrize(
"breaks",
[[0.0, 1.0, 2.0, 3.0], pd.date_range("2017", periods=4, freq="D")],
ids=["float", "datetime64[ns]"],
)
def test_arrow_table_roundtrip(breaks):
import pyarrow as pa |
from itertools import product
import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
| from itertools import product
import numpy as np
import pytest
from pandas.core.dtypes.common import is_interval_dtype
import pandas as pd
import pandas._testing as tm
|
class TestSeriesConvertDtypes:
# Test that it is a copy
copy = series.copy(deep=True)
ns[ns.notna()] = np.nan
# Make sure original not changed
tm.assert_series_equal(series, copy) | class TestSeriesConvertDtypes:
# Test that it is a copy
copy = series.copy(deep=True)
if is_interval_dtype(ns.dtype) and ns.dtype.subtype.kind in ["i", "u"]:
msg = "Cannot set float NaN to integer-backed IntervalArray"
with pytest.raises(ValueError, match=msg):
... |
notes:
rules. This should work out in most cases, but it is theoretically
possible to see spurious changes when target and actual values are
semantically identical but lexically distinct.
version_added: '2.3'
author:
- Jiri Tyr (@jtyr) | notes:
rules. This should work out in most cases, but it is theoretically
possible to see spurious changes when target and actual values are
semantically identical but lexically distinct.
- "The I(params) parameter is deprecated in Ansible-2.7 due to circumventing Ansible's parameter
handling. The I(... |
options:
a list of strings (see examples).
type: raw
required: true
params:
description:
- Additional module parameters.
type: dict
extends_documentation_fragment:
- ldap.documentation
''' | options:
a list of strings (see examples).
type: raw
required: true
extends_documentation_fragment:
- ldap.documentation
''' |
EXAMPLES = r'''
# server_uri: ldap://localhost/
# bind_dn: cn=admin,dc=example,dc=com
# bind_pw: password
- name: Get rid of an unneeded attribute
ldap_attr:
dn: uid=jdoe,ou=people,dc=example,dc=com
name: shadowExpire
values: []
state: exact
params: "{{ ldap_auth }}"
'''
RETURN = r''' | EXAMPLES = r'''
# server_uri: ldap://localhost/
# bind_dn: cn=admin,dc=example,dc=com
# bind_pw: password
#
# In the example below, 'args' is a task keyword, passed at the same level as the module
- name: Get rid of an unneeded attribute
ldap_attr:
dn: uid=jdoe,ou=people,dc=example,dc=com
name: shadowEx... |
modlist:
'''
import traceback
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils._text import to_native, to_bytes | modlist:
'''
import traceback
from distutils.version import LooseVersion
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils._text import to_native, to_bytes |
def main():
module.fail_json(msg=missing_required_lib('python-ldap'),
exception=LDAP_IMP_ERR)
# Update module parameters with user's parameters if defined
if 'params' in module.params and isinstance(module.params['params'], dict):
module.params.update(module.params['par... | 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']:
... |
notes:
rule allowing root to modify the server configuration. If you need to use
a simple bind to access your server, pass the credentials in I(bind_dn)
and I(bind_pw).
version_added: '2.3'
author:
- Jiri Tyr (@jtyr) | notes:
rule allowing root to modify the server configuration. If you need to use
a simple bind to access your server, pass the credentials in I(bind_dn)
and I(bind_pw).
- "The I(params) parameter is deprecated in Ansible-2.7 due to circumventing Ansible's parameter
handling. The I(params) parameter s... |
options:
- If I(state=present), value or list of values to use when creating
the entry. It can either be a string or an actual list of
strings.
params:
description:
- List of options which allows to overwrite any of the task or the
I(attributes) options. To remove an option, se... | options:
- If I(state=present), value or list of values to use when creating
the entry. It can either be a string or an actual list of
strings.
state:
description:
- The target state of the entry. |
EXAMPLES = """
# server_uri: ldap://localhost/
# bind_dn: cn=admin,dc=example,dc=com
# bind_pw: password
- name: Get rid of an old entry
ldap_entry:
dn: ou=stuff,dc=example,dc=com
state: absent
params: "{{ ldap_auth }}"
"""
| EXAMPLES = """
# server_uri: ldap://localhost/
# bind_dn: cn=admin,dc=example,dc=com
# bind_pw: password
#
# In the example below, 'args' is a task keyword, passed at the same level as the module
- name: Get rid of an old entry
ldap_entry:
dn: ou=stuff,dc=example,dc=com
state: absent
args: "{{ ldap_au... |
RETURN = """
"""
import traceback
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.six import string_types | RETURN = """
"""
import traceback
from distutils.version import LooseVersion
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.six import string_types |
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 HttpRequest:
def scheme(self):
if settings.SECURE_PROXY_SSL_HEADER:
try:
header, value = settings.SECURE_PROXY_SSL_HEADER
except ValueError:
raise ImproperlyConfigured(
'The SECURE_PROXY_SSL_HEADER setting must be a tuple cont... | class HttpRequest:
def scheme(self):
if settings.SECURE_PROXY_SSL_HEADER:
try:
header, secure_value = settings.SECURE_PROXY_SSL_HEADER
except ValueError:
raise ImproperlyConfigured(
'The SECURE_PROXY_SSL_HEADER setting must be a tup... |
class SecureProxySslHeaderTest(SimpleTestCase):
req.META['HTTP_X_FORWARDED_PROTOCOL'] = 'https'
self.assertIs(req.is_secure(), True)
class IsOverriddenTest(SimpleTestCase):
def test_configure(self): | class SecureProxySslHeaderTest(SimpleTestCase):
req.META['HTTP_X_FORWARDED_PROTOCOL'] = 'https'
self.assertIs(req.is_secure(), True)
@override_settings(SECURE_PROXY_SSL_HEADER=('HTTP_X_FORWARDED_PROTOCOL', 'https'))
def test_xheader_preferred_to_underlying_request(self):
class ProxyRequ... |
class IOLoop(Configurable):
if IOLoop.current(instance=False) is None:
self.make_current()
elif make_current:
if IOLoop.current(instance=False) is None:
raise RuntimeError("current IOLoop already exists")
self.make_current()
| class IOLoop(Configurable):
if IOLoop.current(instance=False) is None:
self.make_current()
elif make_current:
if IOLoop.current(instance=False) is not None:
raise RuntimeError("current IOLoop already exists")
self.make_current()
|
class TestIOLoop(AsyncTestCase):
# automatically set as current.
class TestIOLoopCurrent(unittest.TestCase):
def setUp(self):
self.io_loop = IOLoop()
def tearDown(self):
self.io_loop.close()
def test_current(self):
def f():
self.current_io_loop = IOLoop.current()
... | class TestIOLoop(AsyncTestCase):
# automatically set as current.
class TestIOLoopCurrent(unittest.TestCase):
def setUp(self):
self.io_loop = None
IOLoop.clear_current()
def tearDown(self):
if self.io_loop is not None:
self.io_loop.close()
def test_default_current(self):... |
from django.utils.six.moves.urllib.parse import (
urlparse,
)
ETAG_MATCH = re.compile(r'(?:W/)?"((?:\\.|[^"])*)"')
MONTHS = 'jan feb mar apr may jun jul aug sep oct nov dec'.split() | from django.utils.six.moves.urllib.parse import (
urlparse,
)
if six.PY2:
from urlparse import (
ParseResult, SplitResult, _splitnetloc, _splitparams, scheme_chars,
uses_params,
)
_coerce_args = None
else:
from urllib.parse import (
ParseResult, SplitResult, _coerce_args, _s... |
def is_safe_url(url, host=None):
return _is_safe_url(url, host) and _is_safe_url(url.replace('\\', '/'), host)
def _is_safe_url(url, host):
# Chrome considers any URL with more than two slashes to be absolute, but
# urlparse is not so flexible. Treat any url with three slashes as unsafe.
if url.starts... | def is_safe_url(url, host=None):
return _is_safe_url(url, host) and _is_safe_url(url.replace('\\', '/'), host)
# Copied from urllib.parse.urlparse() but uses fixed urlsplit() function.
def _urlparse(url, scheme='', allow_fragments=True):
"""Parse a URL into 6 components:
<scheme>://<netloc>/<path>;<params... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.