project stringclasses 17
values | bug_id int64 1 169 | buggy stringlengths 81 57.2k | fixed stringlengths 85 31.2k | test_command stringlengths 44 133 |
|---|---|---|---|---|
pandas | 13 | def _isna_new(obj):
elif isinstance(obj, type):
return False
elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass, ABCExtensionArray)):
return _isna_ndarraylike(obj)
elif isinstance(obj, ABCDataFrame):
return obj.isna()
elif isinstance(obj, list):
return _isna_ndarr... | def _isna_new(obj):
elif isinstance(obj, type):
return False
elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass, ABCExtensionArray)):
return _isna_ndarraylike(obj, old=False)
elif isinstance(obj, ABCDataFrame):
return obj.isna()
elif isinstance(obj, list):
return ... | pytest pandas/tests/arrays/categorical/test_missing.py::TestCategoricalMissing::test_use_inf_as_na_outside_context |
pandas | 13 | def _isna_old(obj):
elif isinstance(obj, type):
return False
elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass, ABCExtensionArray)):
return _isna_ndarraylike_old(obj)
elif isinstance(obj, ABCDataFrame):
return obj.isna()
elif isinstance(obj, list):
return _isna_n... | def _isna_old(obj):
elif isinstance(obj, type):
return False
elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass, ABCExtensionArray)):
return _isna_ndarraylike(obj, old=True)
elif isinstance(obj, ABCDataFrame):
return obj.isna()
elif isinstance(obj, list):
return _... | pytest pandas/tests/arrays/categorical/test_missing.py::TestCategoricalMissing::test_use_inf_as_na_outside_context |
pandas | 13 | def _use_inf_as_na(key):
globals()["_isna"] = _isna_new
def _isna_ndarraylike(obj):
values = getattr(obj, "_values", obj)
dtype = values.dtype
if is_extension_array_dtype(dtype):
result = values.isna()
elif is_string_dtype(dtype):
result = _isna_string_dtype(values, dtype, old... | def _use_inf_as_na(key):
globals()["_isna"] = _isna_new
def _isna_ndarraylike(obj, old: bool = False):
"""
Return an array indicating which values of the input array are NaN / NA.
Parameters
----------
obj: array-like
The input array whose elements are to be checked.
old: bool... | pytest pandas/tests/arrays/categorical/test_missing.py::TestCategoricalMissing::test_use_inf_as_na_outside_context |
fastapi | 14 | class SchemaBase(BaseModel):
not_: Optional[List[Any]] = PSchema(None, alias="not") # type: ignore
items: Optional[Any] = None
properties: Optional[Dict[str, Any]] = None
additionalProperties: Optional[Union[bool, Any]] = None
description: Optional[str] = None
format: Optional[str] = None
d... | class SchemaBase(BaseModel):
not_: Optional[List[Any]] = PSchema(None, alias="not") # type: ignore
items: Optional[Any] = None
properties: Optional[Dict[str, Any]] = None
additionalProperties: Optional[Union[Dict[str, Any], bool]] = None
description: Optional[str] = None
format: Optional[str] =... | pytest tests/test_additional_properties.py::test_additional_properties_schema |
fastapi | 14 | class Schema(SchemaBase):
not_: Optional[List[SchemaBase]] = PSchema(None, alias="not") # type: ignore
items: Optional[SchemaBase] = None
properties: Optional[Dict[str, SchemaBase]] = None
additionalProperties: Optional[Union[bool, SchemaBase]] = None
class Example(BaseModel): | class Schema(SchemaBase):
not_: Optional[List[SchemaBase]] = PSchema(None, alias="not") # type: ignore
items: Optional[SchemaBase] = None
properties: Optional[Dict[str, SchemaBase]] = None
additionalProperties: Optional[Union[SchemaBase, bool]] = None
class Example(BaseModel): | pytest tests/test_additional_properties.py::test_additional_properties_schema |
fastapi | 14 | class Operation(BaseModel):
operationId: Optional[str] = None
parameters: Optional[List[Union[Parameter, Reference]]] = None
requestBody: Optional[Union[RequestBody, Reference]] = None
responses: Union[Responses, Dict[Union[str], Response]]
# Workaround OpenAPI recursive reference
callbacks: Opt... | class Operation(BaseModel):
operationId: Optional[str] = None
parameters: Optional[List[Union[Parameter, Reference]]] = None
requestBody: Optional[Union[RequestBody, Reference]] = None
responses: Union[Responses, Dict[str, Response]]
# Workaround OpenAPI recursive reference
callbacks: Optional[D... | pytest tests/test_additional_properties.py::test_additional_properties_schema |
pandas | 120 | class SeriesGroupBy(GroupBy):
res, out = np.zeros(len(ri), dtype=out.dtype), res
res[ids[idx]] = out
return Series(res, index=ri, name=self._selection_name)
@Appender(Series.describe.__doc__)
def describe(self, **kwargs): | class SeriesGroupBy(GroupBy):
res, out = np.zeros(len(ri), dtype=out.dtype), res
res[ids[idx]] = out
result = Series(res, index=ri, name=self._selection_name)
return self._reindex_output(result, fill_value=0)
@Appender(Series.describe.__doc__)
def describe(self, **kwarg... | pytest pandas/tests/groupby/test_categorical.py::test_series_groupby_on_2_categoricals_unobserved_zeroes_or_nans |
pandas | 120 | class SeriesGroupBy(GroupBy):
minlength = ngroups or 0
out = np.bincount(ids[mask], minlength=minlength)
return Series(
out,
index=self.grouper.result_index,
name=self._selection_name,
dtype="int64",
)
def _apply_to_column_groupbys(se... | class SeriesGroupBy(GroupBy):
minlength = ngroups or 0
out = np.bincount(ids[mask], minlength=minlength)
result = Series(
out,
index=self.grouper.result_index,
name=self._selection_name,
dtype="int64",
)
return self._reindex_output... | pytest pandas/tests/groupby/test_categorical.py::test_series_groupby_on_2_categoricals_unobserved_zeroes_or_nans |
pandas | 120 | from pandas.core.dtypes.common import (
)
from pandas.core.dtypes.missing import isna, notna
from pandas.core import nanops
import pandas.core.algorithms as algorithms
from pandas.core.arrays import Categorical, try_cast_to_ea | from pandas.core.dtypes.common import (
)
from pandas.core.dtypes.missing import isna, notna
from pandas._typing import FrameOrSeries, Scalar
from pandas.core import nanops
import pandas.core.algorithms as algorithms
from pandas.core.arrays import Categorical, try_cast_to_ea | pytest pandas/tests/groupby/test_categorical.py::test_series_groupby_on_2_categoricals_unobserved_zeroes_or_nans |
pandas | 120 | class GroupBy(_GroupBy):
if isinstance(self.obj, Series):
result.name = self.obj.name
return result
@classmethod
def _add_numeric_operations(cls): | class GroupBy(_GroupBy):
if isinstance(self.obj, Series):
result.name = self.obj.name
return self._reindex_output(result, fill_value=0)
@classmethod
def _add_numeric_operations(cls): | pytest pandas/tests/groupby/test_categorical.py::test_series_groupby_on_2_categoricals_unobserved_zeroes_or_nans |
pandas | 120 | class GroupBy(_GroupBy):
if not self.observed and isinstance(result_index, CategoricalIndex):
out = out.reindex(result_index)
return out.sort_index() if self.sort else out
# dropna is truthy | class GroupBy(_GroupBy):
if not self.observed and isinstance(result_index, CategoricalIndex):
out = out.reindex(result_index)
out = self._reindex_output(out)
return out.sort_index() if self.sort else out
# dropna is truthy | pytest pandas/tests/groupby/test_categorical.py::test_series_groupby_on_2_categoricals_unobserved_zeroes_or_nans |
pandas | 120 | class GroupBy(_GroupBy):
mask = self._cumcount_array(ascending=False) < n
return self._selected_obj[mask]
def _reindex_output(self, output):
"""
If we have categorical groupers, then we might want to make sure that
we have a fully re-indexed output to the levels. This means ... | class GroupBy(_GroupBy):
mask = self._cumcount_array(ascending=False) < n
return self._selected_obj[mask]
def _reindex_output(
self, output: FrameOrSeries, fill_value: Scalar = np.NaN
) -> FrameOrSeries:
"""
If we have categorical groupers, then we might want to make sur... | pytest pandas/tests/groupby/test_categorical.py::test_series_groupby_on_2_categoricals_unobserved_zeroes_or_nans |
pandas | 120 | class GroupBy(_GroupBy):
Parameters
----------
output: Series or DataFrame
Object resulting from grouping and applying an operation.
Returns
------- | class GroupBy(_GroupBy):
Parameters
----------
output : Series or DataFrame
Object resulting from grouping and applying an operation.
fill_value : scalar, default np.NaN
Value to use for unobserved categories if self.observed is False.
Returns
--... | pytest pandas/tests/groupby/test_categorical.py::test_series_groupby_on_2_categoricals_unobserved_zeroes_or_nans |
pandas | 120 | class GroupBy(_GroupBy):
).sortlevel()
if self.as_index:
d = {self.obj._get_axis_name(self.axis): index, "copy": False}
return output.reindex(**d)
# GH 13204 | class GroupBy(_GroupBy):
).sortlevel()
if self.as_index:
d = {
self.obj._get_axis_name(self.axis): index,
"copy": False,
"fill_value": fill_value,
}
return output.reindex(**d)
# GH 13204 | pytest pandas/tests/groupby/test_categorical.py::test_series_groupby_on_2_categoricals_unobserved_zeroes_or_nans |
pandas | 120 | class GroupBy(_GroupBy):
output = output.drop(labels=list(g_names), axis=1)
# Set a temp index and reindex (possibly expanding)
output = output.set_index(self.grouper.result_index).reindex(index, copy=False)
# Reset in-axis grouper columns
# (using level numbers `g_nums` becaus... | class GroupBy(_GroupBy):
output = output.drop(labels=list(g_names), axis=1)
# Set a temp index and reindex (possibly expanding)
output = output.set_index(self.grouper.result_index).reindex(
index, copy=False, fill_value=fill_value
)
# Reset in-axis grouper columns
... | pytest pandas/tests/groupby/test_categorical.py::test_series_groupby_on_2_categoricals_unobserved_zeroes_or_nans |
pandas | 81 | from pandas.core.dtypes.common import (
is_list_like,
is_object_dtype,
is_scalar,
)
from pandas.core.dtypes.dtypes import register_extension_dtype
from pandas.core.dtypes.missing import isna | from pandas.core.dtypes.common import (
is_list_like,
is_object_dtype,
is_scalar,
pandas_dtype,
)
from pandas.core.dtypes.dtypes import register_extension_dtype
from pandas.core.dtypes.missing import isna | pytest pandas/tests/arrays/test_integer.py::TestCasting::test_astype_boolean |
pandas | 81 | class IntegerArray(BaseMaskedArray):
if incompatible type with an IntegerDtype, equivalent of same_kind
casting
"""
# if we are astyping to an existing IntegerDtype we can fastpath
if isinstance(dtype, _IntegerDtype):
result = self._data.astype(dtype.numpy_dt... | class IntegerArray(BaseMaskedArray):
if incompatible type with an IntegerDtype, equivalent of same_kind
casting
"""
from pandas.core.arrays.boolean import BooleanArray, BooleanDtype
dtype = pandas_dtype(dtype)
# if we are astyping to an existing IntegerDtype we ... | pytest pandas/tests/arrays/test_integer.py::TestCasting::test_astype_boolean |
httpie | 2 | def get_response(args, config_dir):
"""Send the request and return a `request.Response`."""
requests_session = get_requests_session()
if not args.session and not args.session_read_only:
kwargs = get_requests_kwargs(args) | def get_response(args, config_dir):
"""Send the request and return a `request.Response`."""
requests_session = get_requests_session()
requests_session.max_redirects = args.max_redirects
if not args.session and not args.session_read_only:
kwargs = get_requests_kwargs(args) | pytest tests/test_redirects.py::TestRedirects::test_max_redirects |
httpie | 2 | def main(args=sys.argv[1:], env=Environment(), error=None):
error('Too many redirects (--max-redirects=%s).', args.max_redirects)
except Exception as e:
# TODO: Better distinction between expected and unexpected errors.
# Network errors vs. bugs, etc.
if traceback:
... | def main(args=sys.argv[1:], env=Environment(), error=None):
error('Too many redirects (--max-redirects=%s).', args.max_redirects)
except Exception as e:
# TODO: Better distinction between expected and unexpected errors.
if traceback:
raise
msg = str(e) | pytest tests/test_redirects.py::TestRedirects::test_max_redirects |
keras | 14 | def top_k_categorical_accuracy(y_true, y_pred, k=5):
def sparse_top_k_categorical_accuracy(y_true, y_pred, k=5):
return K.mean(K.in_top_k(y_pred, K.cast(K.max(y_true, axis=-1), 'int32'), k),
axis=-1)
| def top_k_categorical_accuracy(y_true, y_pred, k=5):
def sparse_top_k_categorical_accuracy(y_true, y_pred, k=5):
# If the shape of y_true is (num_samples, 1), flatten to (num_samples,)
return K.mean(K.in_top_k(y_pred, K.cast(K.flatten(y_true), 'int32'), k),
axis=-1)
| pytest tests/keras/metrics_test.py::test_sparse_top_k_categorical_accuracy[y_pred1-y_true1] |
scrapy | 27 | class RedirectMiddleware(BaseRedirectMiddleware):
def process_response(self, request, response, spider):
if (request.meta.get('dont_redirect', False) or
response.status in getattr(spider, 'handle_httpstatus_list', [])):
return response
if request.method == 'HEAD': | class RedirectMiddleware(BaseRedirectMiddleware):
def process_response(self, request, response, spider):
if (request.meta.get('dont_redirect', False) or
response.status in getattr(spider, 'handle_httpstatus_list', []) or
response.status in request.meta.get('handle_httpstatus_l... | python -m unittest -q tests.test_downloadermiddleware_redirect.RedirectMiddlewareTest.test_request_meta_handling |
pandas | 101 | def astype_nansafe(arr, dtype, copy: bool = True, skipna: bool = False):
if is_object_dtype(dtype):
return tslib.ints_to_pydatetime(arr.view(np.int64))
elif dtype == np.int64:
return arr.view(dtype)
# allow frequency conversions | def astype_nansafe(arr, dtype, copy: bool = True, skipna: bool = False):
if is_object_dtype(dtype):
return tslib.ints_to_pydatetime(arr.view(np.int64))
elif dtype == np.int64:
if isna(arr).any():
raise ValueError("Cannot convert NaT values to integer")
... | pytest pandas/tests/dtypes/test_common.py::test_astype_nansafe |
pandas | 101 | def astype_nansafe(arr, dtype, copy: bool = True, skipna: bool = False):
if is_object_dtype(dtype):
return tslibs.ints_to_pytimedelta(arr.view(np.int64))
elif dtype == np.int64:
return arr.view(dtype)
if dtype not in [_INT64_DTYPE, _TD_DTYPE]: | def astype_nansafe(arr, dtype, copy: bool = True, skipna: bool = False):
if is_object_dtype(dtype):
return tslibs.ints_to_pytimedelta(arr.view(np.int64))
elif dtype == np.int64:
if isna(arr).any():
raise ValueError("Cannot convert NaT values to integer")
... | pytest pandas/tests/dtypes/test_common.py::test_astype_nansafe |
luigi | 28 | class HiveCommandClient(HiveClient):
if partition is None:
stdout = run_hive_cmd('use {0}; show tables like "{1}";'.format(database, table))
return stdout and table in stdout
else:
stdout = run_hive_cmd("""use %s; show partitions %s partition
... | class HiveCommandClient(HiveClient):
if partition is None:
stdout = run_hive_cmd('use {0}; show tables like "{1}";'.format(database, table))
return stdout and table.lower() in stdout
else:
stdout = run_hive_cmd("""use %s; show partitions %s partition
... | pytest test/contrib/hive_test.py::HiveCommandClientTest::test_apacheclient_table_exists |
pandas | 32 | https://support.sas.com/techsup/technote/ts140.pdf
"""
from collections import abc
from datetime import datetime
from io import BytesIO
import struct
import warnings
| https://support.sas.com/techsup/technote/ts140.pdf
"""
from collections import abc
from datetime import datetime
import struct
import warnings
| pytest pandas/tests/io/sas/test_xport.py::TestXport::test2_binary |
pandas | 32 | class XportReader(abc.Iterator):
if isinstance(filepath_or_buffer, (str, bytes)):
self.filepath_or_buffer = open(filepath_or_buffer, "rb")
else:
# Copy to BytesIO, and ensure no encoding
contents = filepath_or_buffer.read()
try:
contents = ... | class XportReader(abc.Iterator):
if isinstance(filepath_or_buffer, (str, bytes)):
self.filepath_or_buffer = open(filepath_or_buffer, "rb")
else:
# Since xport files include non-text byte sequences, xport files
# should already be opened in binary mode in Python 3.
... | pytest pandas/tests/io/sas/test_xport.py::TestXport::test2_binary |
youtube-dl | 43 | def remove_start(s, start):
def url_basename(url):
m = re.match(r'(?:https?:|)//[^/]+/(?:[^/?#]+/)?([^/?#]+)/?(?:[?#]|$)', url)
if not m:
return u''
return m.group(1) | def remove_start(s, start):
def url_basename(url):
m = re.match(r'(?:https?:|)//[^/]+/(?:[^?#]+/)?([^/?#]+)/?(?:[?#]|$)', url)
if not m:
return u''
return m.group(1) | python -m unittest -q test.test_utils.TestUtil.test_url_basename |
matplotlib | 9 | class PolarAxes(Axes):
@cbook._delete_parameter("3.3", "args")
@cbook._delete_parameter("3.3", "kwargs")
def draw(self, renderer, *args, **kwargs):
thetamin, thetamax = np.rad2deg(self._realViewLim.intervalx)
if thetamin > thetamax:
thetamin, thetamax = thetamax, thetamin | class PolarAxes(Axes):
@cbook._delete_parameter("3.3", "args")
@cbook._delete_parameter("3.3", "kwargs")
def draw(self, renderer, *args, **kwargs):
self._unstale_viewLim()
thetamin, thetamax = np.rad2deg(self._realViewLim.intervalx)
if thetamin > thetamax:
thetamin, theta... | pytest lib/matplotlib/tests/test_polar.py::test_polar_invertedylim_rorigin |
keras | 35 | class ImageDataGenerator(object):
# Returns
The inputs, normalized.
"""
if self.preprocessing_function:
x = self.preprocessing_function(x)
if self.rescale:
x *= self.rescale
if self.samplewise_center: | class ImageDataGenerator(object):
# Returns
The inputs, normalized.
"""
if self.rescale:
x *= self.rescale
if self.samplewise_center: | pytest tests/keras/preprocessing/image_test.py::TestImage::test_directory_iterator |
keras | 35 | class NumpyArrayIterator(Iterator):
dtype=K.floatx())
for i, j in enumerate(index_array):
x = self.x[j]
x = self.image_data_generator.random_transform(x.astype(K.floatx()))
x = self.image_data_generator.standardize(x)
batch_x[i] = x | class NumpyArrayIterator(Iterator):
dtype=K.floatx())
for i, j in enumerate(index_array):
x = self.x[j]
if self.image_data_generator.preprocessing_function:
x = self.image_data_generator.preprocessing_function(x)
x = self.image_data_... | pytest tests/keras/preprocessing/image_test.py::TestImage::test_directory_iterator |
keras | 35 | class DirectoryIterator(Iterator):
fname = self.filenames[j]
img = load_img(os.path.join(self.directory, fname),
grayscale=grayscale,
target_size=self.target_size,
interpolation=self.interpolation)
x = i... | class DirectoryIterator(Iterator):
fname = self.filenames[j]
img = load_img(os.path.join(self.directory, fname),
grayscale=grayscale,
target_size=None,
interpolation=self.interpolation)
if self.image_dat... | pytest tests/keras/preprocessing/image_test.py::TestImage::test_directory_iterator |
matplotlib | 5 | default: :rc:`scatter.edgecolors`
marker_obj.get_transform())
if not marker_obj.is_filled():
edgecolors = 'face'
linewidths = rcParams['lines.linewidth']
offsets = np.ma.column_stack([x, y])
| default: :rc:`scatter.edgecolors`
marker_obj.get_transform())
if not marker_obj.is_filled():
edgecolors = 'face'
if linewidths is None:
linewidths = rcParams['lines.linewidth']
elif np.iterable(linewidths):
linewidths = [
... | pytest lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_linewidths |
keras | 39 | class Progbar(object):
info = ' - %.0fs' % (now - self.start)
if self.verbose == 1:
if (not force and (now - self.last_update) < self.interval and
current < self.target):
return
prev_total_width = self.total_width | class Progbar(object):
info = ' - %.0fs' % (now - self.start)
if self.verbose == 1:
if (not force and (now - self.last_update) < self.interval and
(self.target is not None and current < self.target)):
return
prev_total_width = self.total_width | pytest tests/keras/utils/generic_utils_test.py::test_progbar |
youtube-dl | 20 | def get_elements_by_attribute(attribute, value, html, escape_value=True):
retlist = []
for m in re.finditer(r'''(?xs)
<([a-zA-Z0-9:._-]+)
(?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'))*?
\s+%s=['"]?%s['"]?
(?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[... | def get_elements_by_attribute(attribute, value, html, escape_value=True):
retlist = []
for m in re.finditer(r'''(?xs)
<([a-zA-Z0-9:._-]+)
(?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'|))*?
\s+%s=['"]?%s['"]?
(?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='... | python -m unittest -q test.test_utils.TestUtil.test_get_element_by_attribute |
pandas | 51 | import pandas.core.indexes.base as ibase
from pandas.core.indexes.base import Index, _index_shared_docs, maybe_extract_name
from pandas.core.indexes.extension import ExtensionIndex, inherit_names
import pandas.core.missing as missing
_index_doc_kwargs = dict(ibase._index_doc_kwargs)
_index_doc_kwargs.update(dict(targe... | import pandas.core.indexes.base as ibase
from pandas.core.indexes.base import Index, _index_shared_docs, maybe_extract_name
from pandas.core.indexes.extension import ExtensionIndex, inherit_names
import pandas.core.missing as missing
from pandas.core.ops import get_op_result_name
_index_doc_kwargs = dict(ibase._index_... | pytest pandas/tests/reshape/merge/test_merge.py::test_categorical_non_unique_monotonic |
pandas | 51 | class CategoricalIndex(ExtensionIndex, accessor.PandasDelegate):
return res
return CategoricalIndex(res, name=self.name)
CategoricalIndex._add_numeric_methods_add_sub_disabled()
CategoricalIndex._add_numeric_methods_disabled() | class CategoricalIndex(ExtensionIndex, accessor.PandasDelegate):
return res
return CategoricalIndex(res, name=self.name)
def _wrap_joined_index(
self, joined: np.ndarray, other: "CategoricalIndex"
) -> "CategoricalIndex":
name = get_op_result_name(self, other)
return... | pytest pandas/tests/reshape/merge/test_merge.py::test_categorical_non_unique_monotonic |
luigi | 24 | class SparkSubmitTask(luigi.Task):
command = []
if value and isinstance(value, dict):
for prop, value in value.items():
command += [name, '"{0}={1}"'.format(prop, value)]
return command
def _flag_arg(self, name, value): | class SparkSubmitTask(luigi.Task):
command = []
if value and isinstance(value, dict):
for prop, value in value.items():
command += [name, '{0}={1}'.format(prop, value)]
return command
def _flag_arg(self, name, value): | pytest test/contrib/spark_test.py::SparkSubmitTaskTest::test_defaults |
fastapi | 3 | except ImportError: # pragma: nocover
from pydantic.fields import Field as ModelField # type: ignore
async def serialize_response(
*,
field: ModelField = None, | except ImportError: # pragma: nocover
from pydantic.fields import Field as ModelField # type: ignore
def _prepare_response_content(
res: Any, *, by_alias: bool = True, exclude_unset: bool
) -> Any:
if isinstance(res, BaseModel):
if PYDANTIC_1:
return res.dict(by_alias=by_alias, exclu... | pytest tests/test_serialize_response_model.py::test_validdict_exclude_unset |
fastapi | 3 | async def serialize_response(
) -> Any:
if field:
errors = []
if exclude_unset and isinstance(response_content, BaseModel):
if PYDANTIC_1:
response_content = response_content.dict(exclude_unset=exclude_unset)
else:
response_content = response_c... | async def serialize_response(
) -> Any:
if field:
errors = []
response_content = _prepare_response_content(
response_content, by_alias=by_alias, exclude_unset=exclude_unset
)
if is_coroutine:
value, errors_ = field.validate(response_content, {}, loc=("response... | pytest tests/test_serialize_response_model.py::test_validdict_exclude_unset |
matplotlib | 17 | def nonsingular(vmin, vmax, expander=0.001, tiny=1e-15, increasing=True):
vmin, vmax = vmax, vmin
swapped = True
maxabsvalue = max(abs(vmin), abs(vmax))
if maxabsvalue < (1e6 / tiny) * np.finfo(float).tiny:
vmin = -expander | def nonsingular(vmin, vmax, expander=0.001, tiny=1e-15, increasing=True):
vmin, vmax = vmax, vmin
swapped = True
# Expand vmin, vmax to float: if they were integer types, they can wrap
# around in abs (abs(np.int8(-128)) == -128) and vmax - vmin can overflow.
vmin, vmax = map(float, [vmin, ... | pytest lib/matplotlib/tests/test_colorbar.py::test_colorbar_int |
pandas | 162 | def _normalize(table, normalize, margins, margins_name="All"):
table = table.fillna(0)
elif margins is True:
column_margin = table.loc[:, margins_name].drop(margins_name)
index_margin = table.loc[margins_name, :].drop(margins_name)
table = table.drop(margins_name, axis=1).drop(marg... | def _normalize(table, normalize, margins, margins_name="All"):
table = table.fillna(0)
elif margins is True:
# keep index and column of pivoted table
table_index = table.index
table_columns = table.columns
# check if margin name is in (for MI cases) or equal to last
... | pytest pandas/tests/reshape/test_pivot.py::TestCrosstab::test_margin_normalize |
pandas | 162 | def _normalize(table, normalize, margins, margins_name="All"):
column_margin = column_margin / column_margin.sum()
table = concat([table, column_margin], axis=1)
table = table.fillna(0)
elif normalize == "index":
index_margin = index_margin / index_margin.sum()
... | def _normalize(table, normalize, margins, margins_name="All"):
column_margin = column_margin / column_margin.sum()
table = concat([table, column_margin], axis=1)
table = table.fillna(0)
table.columns = table_columns
elif normalize == "index":
index_ma... | pytest pandas/tests/reshape/test_pivot.py::TestCrosstab::test_margin_normalize |
pandas | 162 | def _normalize(table, normalize, margins, margins_name="All"):
table = table.append(index_margin)
table = table.fillna(0)
else:
raise ValueError("Not a valid normalize argument")
table.index.names = table_index_names
table.columns.names = table_columns_name... | def _normalize(table, normalize, margins, margins_name="All"):
table = table.append(index_margin)
table = table.fillna(0)
table.index = table_index
table.columns = table_columns
else:
raise ValueError("Not a valid normalize argument")
else:
... | pytest pandas/tests/reshape/test_pivot.py::TestCrosstab::test_margin_normalize |
keras | 18 | class Function(object):
# (since the outputs of fetches are never returned).
# This requires us to wrap fetches in `identity` ops.
self.fetches = [tf.identity(x) for x in self.fetches]
self.session_kwargs = session_kwargs
if session_kwargs:
raise ValueError('Some keys... | class Function(object):
# (since the outputs of fetches are never returned).
# This requires us to wrap fetches in `identity` ops.
self.fetches = [tf.identity(x) for x in self.fetches]
# self.session_kwargs is used for _legacy_call
self.session_kwargs = session_kwargs.copy()
... | pytest tests/keras/backend/backend_test.py::TestBackend::test_function_tf_run_options_with_run_metadata |
keras | 18 | class Function(object):
callable_opts.fetch.append(x.name)
# Handle updates.
callable_opts.target.append(self.updates_op.name)
# Create callable.
callable_fn = session._make_callable_from_options(callable_opts)
# Cache parameters corresponding to the generated callabl... | class Function(object):
callable_opts.fetch.append(x.name)
# Handle updates.
callable_opts.target.append(self.updates_op.name)
# Handle run_options.
if self.run_options:
callable_opts.run_options.CopyFrom(self.run_options)
# Create callable.
callab... | pytest tests/keras/backend/backend_test.py::TestBackend::test_function_tf_run_options_with_run_metadata |
keras | 18 | class Function(object):
feed_symbols,
symbol_vals,
session)
fetched = self._callable_fn(*array_vals)
return fetched[:len(self.outputs)]
def _legacy_call(self, inputs): | class Function(object):
feed_symbols,
symbol_vals,
session)
if self.run_metadata:
fetched = self._callable_fn(*array_vals, run_metadata=self.run_metadata)
else:
fetched = self._callabl... | pytest tests/keras/backend/backend_test.py::TestBackend::test_function_tf_run_options_with_run_metadata |
keras | 18 | class Function(object):
'supported with sparse inputs.')
return self._legacy_call(inputs)
return self._call(inputs)
else:
if py_any(is_tensor(x) for x in inputs): | class Function(object):
'supported with sparse inputs.')
return self._legacy_call(inputs)
# callable generated by Session._make_callable_from_options accepts
# `run_metadata` keyword argument since TF 1.10
if (self.run_metadata and
... | pytest tests/keras/backend/backend_test.py::TestBackend::test_function_tf_run_options_with_run_metadata |
thefuck | 6 | from thefuck.utils import eager
@git_support
def match(command):
return ("fatal: A branch named '" in command.output
and " already exists." in command.output)
@git_support
@eager
def get_new_command(command):
branch_name = re.findall(
r"fatal: A branch named '([^']*)' already exists.", com... | from thefuck.utils import eager
@git_support
def match(command):
return ("fatal: A branch named '" in command.output
and "' already exists." in command.output)
@git_support
@eager
def get_new_command(command):
branch_name = re.findall(
r"fatal: A branch named '(.+)' already exists.", comma... | pytest tests/rules/test_git_branch_exists.py::test_get_new_command |
pandas | 143 | class RangeIndex(Int64Index):
@Appender(_index_shared_docs["get_indexer"])
def get_indexer(self, target, method=None, limit=None, tolerance=None):
if not (method is None and tolerance is None and is_list_like(target)):
return super().get_indexer(target, method=method, tolerance=tolerance)
... | class RangeIndex(Int64Index):
@Appender(_index_shared_docs["get_indexer"])
def get_indexer(self, target, method=None, limit=None, tolerance=None):
if com.any_not_none(method, tolerance, limit) or not is_list_like(target):
return super().get_indexer(
target, method=method, to... | pytest pandas/tests/indexes/test_range.py::TestRangeIndex::test_get_indexer_limit |
thefuck | 16 | from .generic import Generic
class Bash(Generic):
def app_alias(self, fuck):
alias = "TF_ALIAS={0}" \
" alias {0}='PYTHONIOENCODING=utf-8" \
" TF_CMD=$(TF_SHELL_ALIASES=$(alias) thefuck $(fc -ln -1)) && " \
" eval $TF_CMD".format(fuck)
if settings.al... | from .generic import Generic
class Bash(Generic):
def app_alias(self, fuck):
# It is VERY important to have the variables declared WITHIN the alias
alias = "alias {0}='TF_CMD=$(TF_ALIAS={0}" \
" PYTHONIOENCODING=utf-8" \
" TF_SHELL_ALIASES=$(alias)" \
... | pytest tests/shells/test_zsh.py::TestZsh::test_app_alias_variables_correctly_set |
thefuck | 16 | class Fish(Generic):
return ['cd', 'grep', 'ls', 'man', 'open']
def app_alias(self, fuck):
return ('function {0} -d "Correct your previous console command"\n'
' set -l fucked_up_command $history[1]\n'
' env TF_ALIAS={0} PYTHONIOENCODING=utf-8' | class Fish(Generic):
return ['cd', 'grep', 'ls', 'man', 'open']
def app_alias(self, fuck):
# It is VERY important to have the variables declared WITHIN the alias
return ('function {0} -d "Correct your previous console command"\n'
' set -l fucked_up_command $history[1]\n... | pytest tests/shells/test_zsh.py::TestZsh::test_app_alias_variables_correctly_set |
thefuck | 16 | from .generic import Generic
class Zsh(Generic):
def app_alias(self, alias_name):
alias = "alias {0}='TF_ALIAS={0}" \
" PYTHONIOENCODING=utf-8" \
' TF_SHELL_ALIASES=$(alias)' \
" TF_CMD=$(thefuck $(fc -ln -1 | tail -n 1)) &&" \
" eval $TF_CMD"... | from .generic import Generic
class Zsh(Generic):
def app_alias(self, alias_name):
# It is VERY important to have the variables declared WITHIN the alias
alias = "alias {0}='TF_CMD=$(TF_ALIAS={0}" \
" PYTHONIOENCODING=utf-8" \
" TF_SHELL_ALIASES=$(alias)" \
... | pytest tests/shells/test_zsh.py::TestZsh::test_app_alias_variables_correctly_set |
thefuck | 16 | class CorrectedCommand(object):
compatibility_call(self.side_effect, old_cmd, self.script)
# This depends on correct setting of PYTHONIOENCODING by the alias:
logs.debug(u'PYTHONIOENCODING: {}'.format(
os.environ.get('PYTHONIOENCODING', '>-not-set-<')))
print(self.script) | class CorrectedCommand(object):
compatibility_call(self.side_effect, old_cmd, self.script)
# This depends on correct setting of PYTHONIOENCODING by the alias:
logs.debug(u'PYTHONIOENCODING: {}'.format(
os.environ.get('PYTHONIOENCODING', '!!not-set!!')))
print(self.script) | pytest tests/shells/test_zsh.py::TestZsh::test_app_alias_variables_correctly_set |
pandas | 70 | b 2""",
# datetime64tz is handled correctly in agg_series,
# so is excluded here.
# return the same type (Series) as our caller
cls = dtype.construct_array_type()
result = try_cast_to_ea(cls, result, dtype=dtype)
elif numeric... | b 2""",
# datetime64tz is handled correctly in agg_series,
# so is excluded here.
if len(result) and isinstance(result[0], dtype.type):
cls = dtype.construct_array_type()
result = try_cast_to_ea(cls, result, dtype=dtype)
... | pytest pandas/tests/groupby/test_categorical.py::test_groupby_agg_categorical_columns |
pandas | 70 | class BaseGrouper:
if mask.any():
result = result.astype("float64")
result[mask] = np.nan
if kind == "aggregate" and self._filter_empty_groups and not counts.all():
assert result.ndim != 2 | class BaseGrouper:
if mask.any():
result = result.astype("float64")
result[mask] = np.nan
elif (
how == "add"
and is_integer_dtype(orig_values.dtype)
and is_extension_array_dtype(orig_values.dtype)
):
# We need t... | pytest pandas/tests/groupby/test_categorical.py::test_groupby_agg_categorical_columns |
pandas | 70 | def test_aggregate_mixed_types():
tm.assert_frame_equal(result, expected)
class TestLambdaMangling:
def test_basic(self):
df = pd.DataFrame({"A": [0, 0, 1, 1], "B": [1, 2, 3, 4]}) | def test_aggregate_mixed_types():
tm.assert_frame_equal(result, expected)
@pytest.mark.xfail(reason="Not implemented.")
def test_aggregate_udf_na_extension_type():
# https://github.com/pandas-dev/pandas/pull/31359
# This is currently failing to cast back to Int64Dtype.
# The presence of the NA causes ... | pytest pandas/tests/groupby/test_categorical.py::test_groupby_agg_categorical_columns |
pandas | 70 | def test_resample_integerarray():
result = ts.resample("3T").mean()
expected = Series(
[1, 4, 7], index=pd.date_range("1/1/2000", periods=3, freq="3T"), dtype="Int64"
)
tm.assert_series_equal(result, expected)
| def test_resample_integerarray():
result = ts.resample("3T").mean()
expected = Series(
[1, 4, 7],
index=pd.date_range("1/1/2000", periods=3, freq="3T"),
dtype="float64",
)
tm.assert_series_equal(result, expected)
| pytest pandas/tests/groupby/test_categorical.py::test_groupby_agg_categorical_columns |
pandas | 70 | def test_resample_categorical_data_with_timedeltaindex():
index=pd.to_timedelta([0, 10], unit="s"),
)
expected = expected.reindex(["Group_obj", "Group"], axis=1)
expected["Group"] = expected["Group_obj"].astype("category")
tm.assert_frame_equal(result, expected)
| def test_resample_categorical_data_with_timedeltaindex():
index=pd.to_timedelta([0, 10], unit="s"),
)
expected = expected.reindex(["Group_obj", "Group"], axis=1)
expected["Group"] = expected["Group_obj"]
tm.assert_frame_equal(result, expected)
| pytest pandas/tests/groupby/test_categorical.py::test_groupby_agg_categorical_columns |
scrapy | 5 | class Response(object_ref):
"""
if isinstance(url, Link):
url = url.url
url = self.urljoin(url)
return Request(url, callback,
method=method, | class Response(object_ref):
"""
if isinstance(url, Link):
url = url.url
elif url is None:
raise ValueError("url can't be None")
url = self.urljoin(url)
return Request(url, callback,
method=method, | python -m unittest -q tests.test_http_response.BaseResponseTest.test_follow_None_url |
ansible | 13 | from ansible.galaxy.role import GalaxyRole
from ansible.galaxy.token import BasicAuthToken, GalaxyToken, KeycloakToken, NoTokenSentinel
from ansible.module_utils.ansible_release import __version__ as ansible_version
from ansible.module_utils._text import to_bytes, to_native, to_text
from ansible.parsing.yaml.loader imp... | from ansible.galaxy.role import GalaxyRole
from ansible.galaxy.token import BasicAuthToken, GalaxyToken, KeycloakToken, NoTokenSentinel
from ansible.module_utils.ansible_release import __version__ as ansible_version
from ansible.module_utils._text import to_bytes, to_native, to_text
from ansible.module_utils import six... | pytest test/units/cli/test_galaxy.py::test_collection_install_with_url |
ansible | 13 | class GalaxyCLI(CLI):
else:
requirements = []
for collection_input in collections:
name, dummy, requirement = collection_input.partition(':')
requirements.append((name, requirement or '*', None))
output_path = GalaxyCLI._re... | class GalaxyCLI(CLI):
else:
requirements = []
for collection_input in collections:
requirement = None
if os.path.isfile(to_bytes(collection_input, errors='surrogate_or_strict')) or \
urlparse(collection_input... | pytest test/units/cli/test_galaxy.py::test_collection_install_with_url |
ansible | 13 | def _get_collection_info(dep_map, existing_collections, collection, requirement,
if os.path.isfile(to_bytes(collection, errors='surrogate_or_strict')):
display.vvvv("Collection requirement '%s' is a tar artifact" % to_text(collection))
b_tar_path = to_bytes(collection, errors='surrogate_or_strict')
... | def _get_collection_info(dep_map, existing_collections, collection, requirement,
if os.path.isfile(to_bytes(collection, errors='surrogate_or_strict')):
display.vvvv("Collection requirement '%s' is a tar artifact" % to_text(collection))
b_tar_path = to_bytes(collection, errors='surrogate_or_strict')
... | pytest test/units/cli/test_galaxy.py::test_collection_install_with_url |
pandas | 117 | def _isna_old(obj):
raise NotImplementedError("isna is not defined for MultiIndex")
elif isinstance(obj, type):
return False
elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass)):
return _isna_ndarraylike_old(obj)
elif isinstance(obj, ABCGeneric):
return obj._construct... | def _isna_old(obj):
raise NotImplementedError("isna is not defined for MultiIndex")
elif isinstance(obj, type):
return False
elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass, ABCExtensionArray)):
return _isna_ndarraylike_old(obj)
elif isinstance(obj, ABCGeneric):
re... | pytest pandas/tests/series/test_analytics.py::TestSeriesAnalytics::test_count |
pandas | 24 | default 'raise'
DatetimeIndex(['2018-03-01 09:00:00-05:00',
'2018-03-02 09:00:00-05:00',
'2018-03-03 09:00:00-05:00'],
dtype='datetime64[ns, US/Eastern]', freq='D')
With the ``tz=None``, we can remove the time zone information
... | default 'raise'
DatetimeIndex(['2018-03-01 09:00:00-05:00',
'2018-03-02 09:00:00-05:00',
'2018-03-03 09:00:00-05:00'],
dtype='datetime64[ns, US/Eastern]', freq=None)
With the ``tz=None``, we can remove the time zone information
... | pytest pandas/tests/indexes/datetimes/test_timezones.py::test_tz_localize_invalidates_freq |
pandas | 24 | default 'raise'
>>> tz_aware.tz_localize(None)
DatetimeIndex(['2018-03-01 09:00:00', '2018-03-02 09:00:00',
'2018-03-03 09:00:00'],
dtype='datetime64[ns]', freq='D')
Be careful with DST changes. When there is sequential data, pandas can
infer... | default 'raise'
>>> tz_aware.tz_localize(None)
DatetimeIndex(['2018-03-01 09:00:00', '2018-03-02 09:00:00',
'2018-03-03 09:00:00'],
dtype='datetime64[ns]', freq=None)
Be careful with DST changes. When there is sequential data, pandas can
infe... | pytest pandas/tests/indexes/datetimes/test_timezones.py::test_tz_localize_invalidates_freq |
pandas | 24 | default 'raise'
)
new_dates = new_dates.view(DT64NS_DTYPE)
dtype = tz_to_dtype(tz)
return self._simple_new(new_dates, dtype=dtype, freq=self.freq)
# ----------------------------------------------------------------
# Conversion Methods - Vectorized analogues of Timestamp meth... | default 'raise'
)
new_dates = new_dates.view(DT64NS_DTYPE)
dtype = tz_to_dtype(tz)
freq = None
if timezones.is_utc(tz) or (len(self) == 1 and not isna(new_dates[0])):
# we can preserve freq
# TODO: Also for fixed-offsets
freq = self.freq
... | pytest pandas/tests/indexes/datetimes/test_timezones.py::test_tz_localize_invalidates_freq |
pandas | 24 | class TestSeriesComparison:
# datetime64tz dtype
dti = dti.tz_localize("US/Central")
ser = Series(dti).rename(names[1])
result = op(ser, dti)
assert result.name == names[2] | class TestSeriesComparison:
# datetime64tz dtype
dti = dti.tz_localize("US/Central")
dti._set_freq("infer") # freq not preserved by tz_localize
ser = Series(dti).rename(names[1])
result = op(ser, dti)
assert result.name == names[2] | pytest pandas/tests/indexes/datetimes/test_timezones.py::test_tz_localize_invalidates_freq |
black | 7 | def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None:
check_lpar = False
for index, child in enumerate(list(node.children)):
if check_lpar:
if child.type == syms.atom:
if maybe_make_parens_invisible_in_atom(child, parent=node): | def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None:
check_lpar = False
for index, child in enumerate(list(node.children)):
# Add parentheses around long tuple unpacking in assignments.
if (
index == 0
and isinstance(child, Node)
and ch... | python -m unittest -q tests.test_black.BlackTestCase.test_tuple_assign |
black | 7 | def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None:
lpar = Leaf(token.LPAR, "")
rpar = Leaf(token.RPAR, "")
index = child.remove() or 0
node.insert_child(index, Node(syms.atom, [lpar, child, rpar]))
check_lpar = isinstance(... | def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None:
lpar = Leaf(token.LPAR, "")
rpar = Leaf(token.RPAR, "")
index = child.remove() or 0
prefix = child.prefix
child.prefix = ""
new_child = Node(syms.at... | python -m unittest -q tests.test_black.BlackTestCase.test_tuple_assign |
scrapy | 10 | import logging
from six.moves.urllib.parse import urljoin
from scrapy.http import HtmlResponse
from scrapy.utils.response import get_meta_refresh
from scrapy.utils.python import to_native_str
from scrapy.exceptions import IgnoreRequest, NotConfigured
logger = logging.getLogger(__name__) | import logging
from six.moves.urllib.parse import urljoin
from w3lib.url import safe_url_string
from scrapy.http import HtmlResponse
from scrapy.utils.response import get_meta_refresh
from scrapy.exceptions import IgnoreRequest, NotConfigured
logger = logging.getLogger(__name__) | python -m unittest -q tests.test_downloadermiddleware_redirect.RedirectMiddlewareTest.test_utf8_location |
scrapy | 10 | class RedirectMiddleware(BaseRedirectMiddleware):
if 'Location' not in response.headers or response.status not in allowed_status:
return response
# HTTP header is ascii or latin1, redirected url will be percent-encoded utf-8
location = to_native_str(response.headers['location'].deco... | class RedirectMiddleware(BaseRedirectMiddleware):
if 'Location' not in response.headers or response.status not in allowed_status:
return response
location = safe_url_string(response.headers['location'])
redirected_url = urljoin(request.url, location)
| python -m unittest -q tests.test_downloadermiddleware_redirect.RedirectMiddlewareTest.test_utf8_location |
tqdm | 9 | def format_sizeof(num, suffix=''):
Number with Order of Magnitude SI unit postfix.
"""
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
if abs(num) < 1000.0:
if abs(num) < 100.0:
if abs(num) < 10.0:
return '{0:1.2f}'.format(num) + unit + suffix... | def format_sizeof(num, suffix=''):
Number with Order of Magnitude SI unit postfix.
"""
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
if abs(num) < 999.95:
if abs(num) < 99.95:
if abs(num) < 9.995:
return '{0:1.2f}'.format(num) + unit + suffi... | python3 -m pytest tqdm/tests/tests_tqdm.py::test_update |
tqdm | 9 | class tqdm(object):
if ascii is None:
ascii = not _supports_unicode(file)
if gui: # pragma: no cover
try:
import matplotlib as mpl
import matplotlib.pyplot as plt | class tqdm(object):
if ascii is None:
ascii = not _supports_unicode(file)
if gui: # pragma: no cover
try:
import matplotlib as mpl
import matplotlib.pyplot as plt | python3 -m pytest tqdm/tests/tests_tqdm.py::test_update |
tqdm | 9 | class tqdm(object):
self.unit_scale = unit_scale
self.gui = gui
if gui: # pragma: no cover
# Initialize the GUI display
if not disable:
file.write('Warning: GUI is experimental/alpha\n') | class tqdm(object):
self.unit_scale = unit_scale
self.gui = gui
if gui: # pragma: no cover
# Initialize the GUI display
if not disable:
file.write('Warning: GUI is experimental/alpha\n') | python3 -m pytest tqdm/tests/tests_tqdm.py::test_update |
tqdm | 9 | class tqdm(object):
self.n = 0
def __len__(self):
return len(self.iterable)
def __iter__(self):
''' Backward-compatibility to use: for x in tqdm(iterable) ''' | class tqdm(object):
self.n = 0
def __len__(self):
return len(self.iterable) if self.iterable else self.total
def __iter__(self):
''' Backward-compatibility to use: for x in tqdm(iterable) ''' | python3 -m pytest tqdm/tests/tests_tqdm.py::test_update |
tqdm | 9 | class tqdm(object):
last_print_n = self.last_print_n
n = self.n
gui = self.gui
if gui: # pragma: no cover
plt = self.plt
ax = self.ax
xdata = self.xdata | class tqdm(object):
last_print_n = self.last_print_n
n = self.n
gui = self.gui
if gui: # pragma: no cover
plt = self.plt
ax = self.ax
xdata = self.xdata | python3 -m pytest tqdm/tests/tests_tqdm.py::test_update |
tqdm | 9 | class tqdm(object):
delta_t = cur_t - last_print_t
if delta_t >= mininterval:
elapsed = cur_t - start_t
if gui: # pragma: no cover
# Inline due to multiple calls
total = self.t... | class tqdm(object):
delta_t = cur_t - last_print_t
if delta_t >= mininterval:
elapsed = cur_t - start_t
if gui: # pragma: no cover
# Inline due to multiple calls
total = self.... | python3 -m pytest tqdm/tests/tests_tqdm.py::test_update |
luigi | 5 | class inherits(object):
self.task_to_inherit = task_to_inherit
def __call__(self, task_that_inherits):
for param_name, param_obj in self.task_to_inherit.get_params():
if not hasattr(task_that_inherits, param_name):
setattr(task_that_inherits, param_name, param_obj)
... | class inherits(object):
self.task_to_inherit = task_to_inherit
def __call__(self, task_that_inherits):
# Get all parameter objects from the underlying task
for param_name, param_obj in self.task_to_inherit.get_params():
# Check if the parameter exists in the inheriting task
... | pytest test/util_test.py::BasicsTest::test_requires_has_effect_MRO |
luigi | 5 | class requires(object):
def __call__(self, task_that_requires):
task_that_requires = self.inherit_decorator(task_that_requires)
# Modify task_that_requres by subclassing it and adding methods
@task._task_wraps(task_that_requires)
class Wrapped(task_that_requires):
def r... | class requires(object):
def __call__(self, task_that_requires):
task_that_requires = self.inherit_decorator(task_that_requires)
# Modify task_that_requres by adding methods
def requires(_self):
return _self.clone_parent()
task_that_requires.requires = requires
r... | pytest test/util_test.py::BasicsTest::test_requires_has_effect_MRO |
keras | 23 | class Sequential(Model):
first_layer = layer.layers[0]
while isinstance(first_layer, (Model, Sequential)):
first_layer = first_layer.layers[0]
batch_shape = first_layer.batch_input_shape
dtype = first_layer.dtype
... | class Sequential(Model):
first_layer = layer.layers[0]
while isinstance(first_layer, (Model, Sequential)):
first_layer = first_layer.layers[0]
if hasattr(first_layer, 'batch_input_shape'):
batch_shape = first_layer.batc... | pytest tests/keras/test_sequential_model.py::test_nested_sequential_deferred_build |
spacy | 4 | def read_conllx(input_data, use_morphology=False, n=0):
continue
try:
id_ = int(id_) - 1
head = (int(head) - 1) if head != "0" else id_
dep = "ROOT" if dep == "root" else dep
tag = pos if tag == "_" else ... | def read_conllx(input_data, use_morphology=False, n=0):
continue
try:
id_ = int(id_) - 1
head = (int(head) - 1) if head not in ["0", "_"] else id_
dep = "ROOT" if dep == "root" else dep
tag = pos if tag =... | py.test spacy/tests/regression/test_issue4665.py::test_issue4665 |
pandas | 159 | from pandas.core.internals.construction import (
sanitize_index,
to_arrays,
)
from pandas.core.series import Series
from pandas.io.formats import console, format as fmt | from pandas.core.internals.construction import (
sanitize_index,
to_arrays,
)
from pandas.core.ops.missing import dispatch_fill_zeros
from pandas.core.series import Series
from pandas.io.formats import console, format as fmt | pytest pandas/tests/arithmetic/test_numeric.py::test_dataframe_div_silenced |
pandas | 159 | class DataFrame(NDFrame):
# iterate over columns
return ops.dispatch_to_series(this, other, _arith_op)
else:
result = _arith_op(this.values, other.values)
return self._constructor(
result, index=new_index, columns=new_columns, copy=False
... | class DataFrame(NDFrame):
# iterate over columns
return ops.dispatch_to_series(this, other, _arith_op)
else:
with np.errstate(all="ignore"):
result = _arith_op(this.values, other.values)
result = dispatch_fill_zeros(func, this.values, other.values,... | pytest pandas/tests/arithmetic/test_numeric.py::test_dataframe_div_silenced |
black | 11 | def split_line(
return
line_str = str(line).strip("\n")
if not line.should_explode and is_line_short_enough(
line, line_length=line_length, line_str=line_str
):
yield line
return | def split_line(
return
line_str = str(line).strip("\n")
# we don't want to split special comments like type annotations
# https://github.com/python/typing/issues/186
has_special_comment = False
for leaf in line.leaves:
for comment in line.comments_after(leaf):
if leaf.t... | python -m unittest -q tests.test_black.BlackTestCase.test_comments6 |
black | 11 | def is_import(leaf: Leaf) -> bool:
)
def normalize_prefix(leaf: Leaf, *, inside_brackets: bool) -> None:
"""Leave existing extra newlines if not `inside_brackets`. Remove everything
else. | def is_import(leaf: Leaf) -> bool:
)
def is_special_comment(leaf: Leaf) -> bool:
"""Return True if the given leaf is a special comment.
Only returns true for type comments for now."""
t = leaf.type
v = leaf.value
return bool(
(t == token.COMMENT or t == STANDALONE_COMMENT) and (v.start... | python -m unittest -q tests.test_black.BlackTestCase.test_comments6 |
black | 11 | def ensure_visible(leaf: Leaf) -> None:
def should_explode(line: Line, opening_bracket: Leaf) -> bool:
"""Should `line` immediately be split with `delimiter_split()` after RHS?"""
if not (
opening_bracket.parent
and opening_bracket.parent.type in {syms.atom, syms.import_from} | def ensure_visible(leaf: Leaf) -> None:
def should_explode(line: Line, opening_bracket: Leaf) -> bool:
"""Should `line` immediately be split with `delimiter_split()` after RHS?"""
if not (
opening_bracket.parent
and opening_bracket.parent.type in {syms.atom, syms.import_from} | python -m unittest -q tests.test_black.BlackTestCase.test_comments6 |
pandas | 97 | class TimedeltaIndex(
this, other = self, other
if this._can_fast_union(other):
return this._fast_union(other)
else:
result = Index._union(this, other, sort=sort)
if isinstance(result, TimedeltaIndex): | class TimedeltaIndex(
this, other = self, other
if this._can_fast_union(other):
return this._fast_union(other, sort=sort)
else:
result = Index._union(this, other, sort=sort)
if isinstance(result, TimedeltaIndex): | pytest pandas/tests/indexes/timedeltas/test_setops.py::TestTimedeltaIndex::test_union_sort_false |
pandas | 97 | class TimedeltaIndex(
result._set_freq("infer")
return result
def _fast_union(self, other):
if len(other) == 0:
return self.view(type(self))
| class TimedeltaIndex(
result._set_freq("infer")
return result
def _fast_union(self, other, sort=None):
if len(other) == 0:
return self.view(type(self))
| pytest pandas/tests/indexes/timedeltas/test_setops.py::TestTimedeltaIndex::test_union_sort_false |
pandas | 97 | class TimedeltaIndex(
# to make our life easier, "sort" the two ranges
if self[0] <= other[0]:
left, right = self, other
else:
left, right = other, self
| class TimedeltaIndex(
# to make our life easier, "sort" the two ranges
if self[0] <= other[0]:
left, right = self, other
elif sort is False:
# TDIs are not in the "correct" order and we don't want
# to sort but want to remove overlaps
left, right ... | pytest pandas/tests/indexes/timedeltas/test_setops.py::TestTimedeltaIndex::test_union_sort_false |
pandas | 136 | from pandas.core.dtypes.common import (
is_dtype_equal,
is_extension_array_dtype,
is_float_dtype,
is_int64_dtype,
is_integer,
is_integer_dtype,
is_list_like, | from pandas.core.dtypes.common import (
is_dtype_equal,
is_extension_array_dtype,
is_float_dtype,
is_integer,
is_integer_dtype,
is_list_like, | pytest pandas/tests/reshape/merge/test_merge_asof.py::TestAsOfMerge::test_int_type_tolerance |
pandas | 136 | class _AsOfMerge(_OrderedMerge):
if self.tolerance < Timedelta(0):
raise MergeError("tolerance must be positive")
elif is_int64_dtype(lt):
if not is_integer(self.tolerance):
raise MergeError(msg)
if self.tolerance < 0: | class _AsOfMerge(_OrderedMerge):
if self.tolerance < Timedelta(0):
raise MergeError("tolerance must be positive")
elif is_integer_dtype(lt):
if not is_integer(self.tolerance):
raise MergeError(msg)
if self.tolerance < 0... | pytest pandas/tests/reshape/merge/test_merge_asof.py::TestAsOfMerge::test_int_type_tolerance |
tornado | 9 | def url_concat(url, args):
>>> url_concat("http://example.com/foo?a=b", [("c", "d"), ("c", "d2")])
'http://example.com/foo?a=b&c=d&c=d2'
"""
parsed_url = urlparse(url)
if isinstance(args, dict):
parsed_query = parse_qsl(parsed_url.query, keep_blank_values=True) | def url_concat(url, args):
>>> url_concat("http://example.com/foo?a=b", [("c", "d"), ("c", "d2")])
'http://example.com/foo?a=b&c=d&c=d2'
"""
if args is None:
return url
parsed_url = urlparse(url)
if isinstance(args, dict):
parsed_query = parse_qsl(parsed_url.query, keep_blank_val... | python -m unittest -q tornado.test.httputil_test.TestUrlConcat.test_url_concat_none_params |
scrapy | 31 | class WrappedRequest(object):
return name in self.request.headers
def get_header(self, name, default=None):
return to_native_str(self.request.headers.get(name, default))
def header_items(self):
return [
(to_native_str(k), [to_native_str(x) for x in v])
for k, v ... | class WrappedRequest(object):
return name in self.request.headers
def get_header(self, name, default=None):
return to_native_str(self.request.headers.get(name, default),
errors='replace')
def header_items(self):
return [
(to_native_str(k, errors... | python -m unittest -q tests.test_downloadermiddleware_cookies.CookiesMiddlewareTest.test_do_not_break_on_non_utf8_header |
scrapy | 31 | class WrappedResponse(object):
# python3 cookiejars calls get_all
def get_all(self, name, default=None):
return [to_native_str(v) for v in self.response.headers.getlist(name)]
# python2 cookiejars calls getheaders
getheaders = get_all | class WrappedResponse(object):
# python3 cookiejars calls get_all
def get_all(self, name, default=None):
return [to_native_str(v, errors='replace')
for v in self.response.headers.getlist(name)]
# python2 cookiejars calls getheaders
getheaders = get_all | python -m unittest -q tests.test_downloadermiddleware_cookies.CookiesMiddlewareTest.test_do_not_break_on_non_utf8_header |
keras | 6 | def weighted_masked_objective(fn):
score_array *= mask
# the loss per batch should be proportional
# to the number of unmasked samples.
score_array /= K.mean(mask)
# apply sample weighting
if weights is not None: | def weighted_masked_objective(fn):
score_array *= mask
# the loss per batch should be proportional
# to the number of unmasked samples.
score_array /= K.mean(mask) + K.epsilon()
# apply sample weighting
if weights is not None: | pytest tests/test_loss_masking.py::test_masking_is_all_zeros |
pandas | 2 | class _ScalarAccessIndexer(_NDFrameIndexerBase):
if not isinstance(key, tuple):
key = _tuplify(self.ndim, key)
if len(key) != self.ndim:
raise ValueError("Not enough indexers for scalar access (setting)!")
key = list(self._convert_key(key, is_setter=True))
self.... | class _ScalarAccessIndexer(_NDFrameIndexerBase):
if not isinstance(key, tuple):
key = _tuplify(self.ndim, key)
key = list(self._convert_key(key, is_setter=True))
if len(key) != self.ndim:
raise ValueError("Not enough indexers for scalar access (setting)!")
self.... | pytest pandas/tests/indexing/test_scalar.py::test_multiindex_at_set |
pandas | 2 | class _AtIndexer(_ScalarAccessIndexer):
Require they keys to be the same type as the index. (so we don't
fallback)
"""
# allow arbitrary setting
if is_setter:
return list(key) | class _AtIndexer(_ScalarAccessIndexer):
Require they keys to be the same type as the index. (so we don't
fallback)
"""
# GH 26989
# For series, unpacking key needs to result in the label.
# This is already the case for len(key) == 1; e.g. (1,)
if self.ndim == 1 an... | pytest pandas/tests/indexing/test_scalar.py::test_multiindex_at_set |
matplotlib | 20 | def _make_ghost_gridspec_slots(fig, gs):
# this gridspec slot doesn't have an axis so we
# make a "ghost".
ax = fig.add_subplot(gs[nn])
ax.set_frame_on(False)
ax.set_xticks([])
ax.set_yticks([])
ax.set_facecolor((1, 0, 0, 0))
def _mak... | def _make_ghost_gridspec_slots(fig, gs):
# this gridspec slot doesn't have an axis so we
# make a "ghost".
ax = fig.add_subplot(gs[nn])
ax.set_visible(False)
def _make_layout_margins(ax, renderer, h_pad, w_pad): | pytest lib/matplotlib/tests/test_axes.py::test_invisible_axes |
matplotlib | 20 | class FigureCanvasBase:
def inaxes(self, xy):
"""
Check if a point is in an axes.
Parameters
---------- | class FigureCanvasBase:
def inaxes(self, xy):
"""
Return the topmost visible `~.axes.Axes` containing the point *xy*.
Parameters
---------- | pytest lib/matplotlib/tests/test_axes.py::test_invisible_axes |
matplotlib | 20 | class FigureCanvasBase:
Returns
-------
axes: topmost axes containing the point, or None if no axes.
"""
axes_list = [a for a in self.figure.get_axes()
if a.patch.contains_point(xy)]
if axes_list:
axes = cbook._topmost_artist(axes_list)... | class FigureCanvasBase:
Returns
-------
axes : `~matplotlib.axes.Axes` or None
The topmost visible axes containing the point, or None if no axes.
"""
axes_list = [a for a in self.figure.get_axes()
if a.patch.contains_point(xy) and a.get_visible()... | pytest lib/matplotlib/tests/test_axes.py::test_invisible_axes |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.