project stringclasses 17
values | bug_id int64 1 169 | buggy stringlengths 81 57.2k | fixed stringlengths 85 31.2k | test_command stringlengths 44 133 |
|---|---|---|---|---|
scrapy | 1 | class OffsiteMiddleware(object):
if not allowed_domains:
return re.compile('') # allow all by default
url_pattern = re.compile("^https?://.*$")
for domain in allowed_domains:
if url_pattern.match(domain):
message = ("allowed_domains accepts only domains, ... | class OffsiteMiddleware(object):
if not allowed_domains:
return re.compile('') # allow all by default
url_pattern = re.compile("^https?://.*$")
domains = []
for domain in allowed_domains:
if domain is None:
continue
elif url_pattern.ma... | python -m unittest -q tests.test_spidermiddleware_offsite.TestOffsiteMiddleware4.test_process_spider_output |
ansible | 17 | class LinuxHardware(Hardware):
# regex used against mtab content to find entries that are bind mounts
MTAB_BIND_MOUNT_RE = re.compile(r'.*bind.*"')
def populate(self, collected_facts=None):
hardware_facts = {}
self.module.run_command_environ_update = {'LANG': 'C', 'LC_ALL': 'C', 'LC_NUMERIC... | class LinuxHardware(Hardware):
# regex used against mtab content to find entries that are bind mounts
MTAB_BIND_MOUNT_RE = re.compile(r'.*bind.*"')
# regex used for replacing octal escape sequences
OCTAL_ESCAPE_RE = re.compile(r'\\[0-9]{3}')
def populate(self, collected_facts=None):
hardwa... | pytest test/units/module_utils/facts/test_facts.py::TestFactsLinuxHardwareGetMountFacts::test_get_mount_facts |
ansible | 17 | class LinuxHardware(Hardware):
mtab_entries.append(fields)
return mtab_entries
def get_mount_info(self, mount, device, uuids):
mount_size = get_mount_size(mount) | class LinuxHardware(Hardware):
mtab_entries.append(fields)
return mtab_entries
@staticmethod
def _replace_octal_escapes_helper(match):
# Convert to integer using base8 and then convert to character
return chr(int(match.group()[1:], 8))
def _replace_octal_escapes(self, v... | pytest test/units/module_utils/facts/test_facts.py::TestFactsLinuxHardwareGetMountFacts::test_get_mount_facts |
ansible | 17 | class LinuxHardware(Hardware):
pool = ThreadPool(processes=min(len(mtab_entries), cpu_count()))
maxtime = globals().get('GATHER_TIMEOUT') or timeout.DEFAULT_GATHER_TIMEOUT
for fields in mtab_entries:
device, mount, fstype, options = fields[0], fields[1], fields[2], fields[3]
| class LinuxHardware(Hardware):
pool = ThreadPool(processes=min(len(mtab_entries), cpu_count()))
maxtime = globals().get('GATHER_TIMEOUT') or timeout.DEFAULT_GATHER_TIMEOUT
for fields in mtab_entries:
# Transform octal escape sequences
fields = [self._replace_octal_escapes... | pytest test/units/module_utils/facts/test_facts.py::TestFactsLinuxHardwareGetMountFacts::test_get_mount_facts |
scrapy | 35 | def _get_spider_loader(settings):
'Please use SPIDER_LOADER_CLASS.',
category=ScrapyDeprecationWarning, stacklevel=2
)
cls_path = settings.get('SPIDER_LOADER_CLASS',
settings.get('SPIDER_MANAGER_CLASS'))
loader_cls = load_object(cls_path)
verifyCla... | def _get_spider_loader(settings):
'Please use SPIDER_LOADER_CLASS.',
category=ScrapyDeprecationWarning, stacklevel=2
)
cls_path = settings.get('SPIDER_MANAGER_CLASS',
settings.get('SPIDER_LOADER_CLASS'))
loader_cls = load_object(cls_path)
verifyCla... | python -m unittest -q tests.test_crawler.CrawlerRunnerTestCase.test_spidermanager_deprecation |
tornado | 13 | class HTTP1Connection(httputil.HTTPConnection):
return connection_header != "close"
elif ("Content-Length" in headers
or headers.get("Transfer-Encoding", "").lower() == "chunked"
or start_line.method in ("HEAD", "GET")):
return connection_header == "keep-alive... | class HTTP1Connection(httputil.HTTPConnection):
return connection_header != "close"
elif ("Content-Length" in headers
or headers.get("Transfer-Encoding", "").lower() == "chunked"
or getattr(start_line, 'method', None) in ("HEAD", "GET")):
# start_line may be a... | python -m unittest -q tornado.test.http1connection_test.HTTP1ConnectionTest.test_http10_no_content_length |
tornado | 13 | TEST_MODULES = [
'tornado.test.curl_httpclient_test',
'tornado.test.escape_test',
'tornado.test.gen_test',
'tornado.test.httpclient_test',
'tornado.test.httpserver_test',
'tornado.test.httputil_test', | TEST_MODULES = [
'tornado.test.curl_httpclient_test',
'tornado.test.escape_test',
'tornado.test.gen_test',
'tornado.test.http1connection_test',
'tornado.test.httpclient_test',
'tornado.test.httpserver_test',
'tornado.test.httputil_test', | python -m unittest -q tornado.test.http1connection_test.HTTP1ConnectionTest.test_http10_no_content_length |
pandas | 132 | def nanstd(values, axis=None, skipna=True, ddof=1, mask=None):
>>> nanops.nanstd(s)
1.0
"""
result = np.sqrt(nanvar(values, axis=axis, skipna=skipna, ddof=ddof, mask=mask))
return _wrap_results(result, values.dtype)
@disallow("M8")
@bottleneck_switch(ddof=1)
def nanvar(values, axis=None, skipna=Tr... | def nanstd(values, axis=None, skipna=True, ddof=1, mask=None):
>>> nanops.nanstd(s)
1.0
"""
orig_dtype = values.dtype
values, mask, dtype, dtype_max, fill_value = _get_values(values, skipna, mask=mask)
result = np.sqrt(nanvar(values, axis=axis, skipna=skipna, ddof=ddof, mask=mask))
return _... | pytest pandas/tests/reductions/test_reductions.py::TestSeriesReductions::test_ops_consistency_on_empty |
pandas | 132 | class Series(base.IndexOpsMixin, generic.NDFrame):
If we have an ndarray as a value, then simply perform the operation,
otherwise delegate to the object.
"""
delegate = self._values
if axis is not None: | class Series(base.IndexOpsMixin, generic.NDFrame):
If we have an ndarray as a value, then simply perform the operation,
otherwise delegate to the object.
"""
delegate = self._values
if axis is not None: | pytest pandas/tests/reductions/test_reductions.py::TestSeriesReductions::test_ops_consistency_on_empty |
pandas | 93 | from datetime import datetime, timedelta
import operator
from typing import Any, Sequence, Type, Union, cast
import warnings
import numpy as np
from pandas._libs import NaT, NaTType, Timestamp, algos, iNaT, lib
from pandas._libs.tslibs.c_timestamp import integer_op_not_supported
from pandas._libs.tslibs.period import... | """
Base and utility classes for tseries type pandas objects.
"""
import operator
from typing import List, Optional, Set
import numpy as np
from pandas._libs import NaT, iNaT, join as libjoin, lib
from pandas._libs.algos import unique_deltas
from pandas._libs.tslibs import timezones
from pandas.compat.numpy import fu... | pytest pandas/tests/indexes/period/test_indexing.py::TestWhere::test_where_invalid_dtypes |
matplotlib | 28 | class _AxesBase(martist.Artist):
if right is None:
right = old_right
if self.get_xscale() == 'log':
if left <= 0:
cbook._warn_external(
'Attempted to set non-positive left xlim on a ' | class _AxesBase(martist.Artist):
if right is None:
right = old_right
if self.get_xscale() == 'log' and (left <= 0 or right <= 0):
# Axes init calls set_xlim(0, 1) before get_xlim() can be called,
# so only grab the limits if we really need them.
o... | pytest lib/matplotlib/tests/test_axes.py::test_log_scales_invalid |
black | 15 | from typing import (
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
cast, | from typing import (
Sequence,
Set,
Tuple,
TypeVar,
Union,
cast, | python -m unittest -q tests.test_black.BlackTestCase.test_fmtonoff2 |
black | 15 | class CannotSplit(Exception):
"""
class FormatError(Exception):
"""Base exception for `# fmt: on` and `# fmt: off` handling.
It holds the number of bytes of the prefix consumed before the format
control comment appeared.
"""
def __init__(self, consumed: int) -> None:
super().__init__... | class CannotSplit(Exception):
"""
class WriteBack(Enum):
NO = 0
YES = 1 | python -m unittest -q tests.test_black.BlackTestCase.test_fmtonoff2 |
black | 15 | class DebugVisitor(Visitor[T]):
out(f" {node.value!r}", fg="blue", bold=False)
@classmethod
def show(cls, code: str) -> None:
"""Pretty-print the lib2to3 AST of a given string of `code`.
Convenience method for debugging.
"""
v: DebugVisitor[None] = DebugVisitor()
... | class DebugVisitor(Visitor[T]):
out(f" {node.value!r}", fg="blue", bold=False)
@classmethod
def show(cls, code: Union[str, Leaf, Node]) -> None:
"""Pretty-print the lib2to3 AST of a given string of `code`.
Convenience method for debugging.
"""
v: DebugVisitor[None] ... | python -m unittest -q tests.test_black.BlackTestCase.test_fmtonoff2 |
black | 15 | class Line:
return bool(self.leaves or self.comments)
class UnformattedLines(Line):
"""Just like :class:`Line` but stores lines which aren't reformatted."""
def append(self, leaf: Leaf, preformatted: bool = True) -> None:
"""Just add a new `leaf` to the end of the lines.
The `preform... | class Line:
return bool(self.leaves or self.comments)
@dataclass
class EmptyLineTracker:
"""Provides a stateful method that returns the number of potential extra | python -m unittest -q tests.test_black.BlackTestCase.test_fmtonoff2 |
black | 15 | class EmptyLineTracker:
This is for separating `def`, `async def` and `class` with extra empty
lines (two on module-level).
"""
if isinstance(current_line, UnformattedLines):
return 0, 0
before, after = self._maybe_empty_lines(current_line)
before -= self.pre... | class EmptyLineTracker:
This is for separating `def`, `async def` and `class` with extra empty
lines (two on module-level).
"""
before, after = self._maybe_empty_lines(current_line)
before -= self.previous_after
self.previous_after = after | python -m unittest -q tests.test_black.BlackTestCase.test_fmtonoff2 |
black | 15 | class LineGenerator(Visitor[Line]):
current_line: Line = Factory(Line)
remove_u_prefix: bool = False
def line(self, indent: int = 0, type: Type[Line] = Line) -> Iterator[Line]:
"""Generate a line.
If the line is empty, only emit if it makes sense. | class LineGenerator(Visitor[Line]):
current_line: Line = Factory(Line)
remove_u_prefix: bool = False
def line(self, indent: int = 0) -> Iterator[Line]:
"""Generate a line.
If the line is empty, only emit if it makes sense. | python -m unittest -q tests.test_black.BlackTestCase.test_fmtonoff2 |
black | 15 | class LineGenerator(Visitor[Line]):
If any lines were generated, set up a new current_line.
"""
if not self.current_line:
if self.current_line.__class__ == type:
self.current_line.depth += indent
else:
self.current_line = type(depth=self.cu... | class LineGenerator(Visitor[Line]):
If any lines were generated, set up a new current_line.
"""
if not self.current_line:
self.current_line.depth += indent
return # Line is empty, don't emit. Creating a new one unnecessary.
complete_line = self.current_line
... | python -m unittest -q tests.test_black.BlackTestCase.test_fmtonoff2 |
black | 15 | class LineGenerator(Visitor[Line]):
yield from self.visit_default(leaf)
yield from self.line()
def visit_unformatted(self, node: LN) -> Iterator[Line]:
"""Used when file contained a `# fmt: off`."""
if isinstance(node, Node):
for child in node.children:
y... | class LineGenerator(Visitor[Line]):
yield from self.visit_default(leaf)
yield from self.line()
def visit_STANDALONE_COMMENT(self, leaf: Leaf) -> Iterator[Line]:
if not self.current_line.bracket_tracker.any_open_brackets():
yield from self.line()
yield from self.visit_def... | python -m unittest -q tests.test_black.BlackTestCase.test_fmtonoff2 |
black | 15 | def container_of(leaf: Leaf) -> LN:
if parent.children[0].prefix != same_prefix:
break
if parent.type in SURROUNDED_BY_BRACKETS:
break
| def container_of(leaf: Leaf) -> LN:
if parent.children[0].prefix != same_prefix:
break
if parent.type == syms.file_input:
break
if parent.type in SURROUNDED_BY_BRACKETS:
break
| python -m unittest -q tests.test_black.BlackTestCase.test_fmtonoff2 |
black | 15 | def generate_comments(leaf: LN) -> Iterator[Leaf]:
"""
for pc in list_comments(leaf.prefix, is_endmarker=leaf.type == token.ENDMARKER):
yield Leaf(pc.type, pc.value, prefix="\n" * pc.newlines)
if pc.value in FMT_ON:
raise FormatOn(pc.consumed)
if pc.value in FMT_OFF:
... | def generate_comments(leaf: LN) -> Iterator[Leaf]:
"""
for pc in list_comments(leaf.prefix, is_endmarker=leaf.type == token.ENDMARKER):
yield Leaf(pc.type, pc.value, prefix="\n" * pc.newlines)
@dataclass | python -m unittest -q tests.test_black.BlackTestCase.test_fmtonoff2 |
black | 15 | def split_line(
If `py36` is True, splitting may generate syntax that is only compatible
with Python 3.6 and later.
"""
if isinstance(line, UnformattedLines) or line.is_comment:
yield line
return
| def split_line(
If `py36` is True, splitting may generate syntax that is only compatible
with Python 3.6 and later.
"""
if line.is_comment:
yield line
return
| python -m unittest -q tests.test_black.BlackTestCase.test_fmtonoff2 |
black | 15 | def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None:
def normalize_fmt_off(node: Node) -> None:
"""Allow `# fmt: off`/`# fmt: on` within bracket pairs.
Ignores `# fmt: off` and `# fmt: on` outside of brackets.
Raises :exc:`SyntaxError` if no matching `# fmt: on` is found for a `# ... | def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None:
def normalize_fmt_off(node: Node) -> None:
"""Convert content between `# fmt: off`/`# fmt: on` into standalone comments."""
try_again = True
while try_again:
try_again = convert_one_fmt_off_pair(node)
def convert_one_fmt... | python -m unittest -q tests.test_black.BlackTestCase.test_fmtonoff2 |
black | 15 | def hide_fmt_off(node: Node) -> bool:
hidden_value = (
comment.value + "\n" + "".join(str(n) for n in ignored_nodes)
)
first_idx = None
for ignored in ignored_nodes:
index = ignored.remove() | def hide_fmt_off(node: Node) -> bool:
hidden_value = (
comment.value + "\n" + "".join(str(n) for n in ignored_nodes)
)
if hidden_value.endswith("\n"):
# That happens when one of the `ignored_nodes` ended with a NEWLINE
... | python -m unittest -q tests.test_black.BlackTestCase.test_fmtonoff2 |
black | 15 | def hide_fmt_off(node: Node) -> bool:
def generate_ignored_nodes(leaf: Leaf) -> Iterator[LN]:
container: Optional[LN] = container_of(leaf)
while container is not None:
for comment in list_comments(container.prefix, is_endmarker=False):
if comment.value in FMT_ON:
return | def hide_fmt_off(node: Node) -> bool:
def generate_ignored_nodes(leaf: Leaf) -> Iterator[LN]:
"""Starting from the container of `leaf`, generate all leaves until `# fmt: on`.
Stops at the end of the block.
"""
container: Optional[LN] = container_of(leaf)
while container is not None and container.... | python -m unittest -q tests.test_black.BlackTestCase.test_fmtonoff2 |
luigi | 21 | def run(cmdline_args=None, main_task_cls=None,
:param use_dynamic_argparse:
:param local_scheduler:
"""
if use_dynamic_argparse:
interface = DynamicArgParseInterface()
else: | def run(cmdline_args=None, main_task_cls=None,
:param use_dynamic_argparse:
:param local_scheduler:
"""
if cmdline_args is None:
cmdline_args = sys.argv[1:]
if use_dynamic_argparse:
interface = DynamicArgParseInterface()
else: | pytest test/interface_test.py::InterfaceTest::test_just_run_main_task_cls |
pandas | 167 | class Index(IndexOpsMixin, PandasObject):
_infer_as_myclass = False
_engine_type = libindex.ObjectEngine
_accessors = {"str"}
| class Index(IndexOpsMixin, PandasObject):
_infer_as_myclass = False
_engine_type = libindex.ObjectEngine
# whether we support partial string indexing. Overridden
# in DatetimeIndex and PeriodIndex
_supports_partial_string_indexing = False
_accessors = {"str"}
| pytest pandas/tests/indexes/datetimes/test_partial_slicing.py::TestSlicing::test_slice_reduce_to_series |
pandas | 167 | class DatetimeIndex(DatetimeIndexOpsMixin, Int64Index, DatetimeDelegateMixin):
)
_engine_type = libindex.DatetimeEngine
_tz = None
_freq = None | class DatetimeIndex(DatetimeIndexOpsMixin, Int64Index, DatetimeDelegateMixin):
)
_engine_type = libindex.DatetimeEngine
_supports_partial_string_indexing = True
_tz = None
_freq = None | pytest pandas/tests/indexes/datetimes/test_partial_slicing.py::TestSlicing::test_slice_reduce_to_series |
pandas | 167 | class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
_data = None
_engine_type = libindex.PeriodEngine
# ------------------------------------------------------------------------
# Index Constructors | class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
_data = None
_engine_type = libindex.PeriodEngine
_supports_partial_string_indexing = True
# ------------------------------------------------------------------------
# Index Constructors | pytest pandas/tests/indexes/datetimes/test_partial_slicing.py::TestSlicing::test_slice_reduce_to_series |
pandas | 167 | class _LocIndexer(_LocationIndexer):
if isinstance(ax, MultiIndex):
return False
if not ax.is_unique:
return False
| class _LocIndexer(_LocationIndexer):
if isinstance(ax, MultiIndex):
return False
if isinstance(k, str) and ax._supports_partial_string_indexing:
# partial string indexing, df.loc['2000', 'A']
# should not be considered scalar
retur... | pytest pandas/tests/indexes/datetimes/test_partial_slicing.py::TestSlicing::test_slice_reduce_to_series |
pandas | 167 | class _LocIndexer(_LocationIndexer):
"""Translate any partial string timestamp matches in key, returning the
new key (GH 10331)"""
if isinstance(labels, MultiIndex):
if isinstance(key, str) and labels.levels[0].is_all_dates:
# Convert key '2016-01-01' to
... | class _LocIndexer(_LocationIndexer):
"""Translate any partial string timestamp matches in key, returning the
new key (GH 10331)"""
if isinstance(labels, MultiIndex):
if (
isinstance(key, str)
and labels.levels[0]._supports_partial_string_indexing
... | pytest pandas/tests/indexes/datetimes/test_partial_slicing.py::TestSlicing::test_slice_reduce_to_series |
pandas | 167 | class _LocIndexer(_LocationIndexer):
# (..., slice('2016-01-01', '2016-01-01', None), ...)
new_key = []
for i, component in enumerate(key):
if isinstance(component, str) and labels.levels[i].is_all_dates:
new_key.append(slice(co... | class _LocIndexer(_LocationIndexer):
# (..., slice('2016-01-01', '2016-01-01', None), ...)
new_key = []
for i, component in enumerate(key):
if (
isinstance(component, str)
and labels.levels[i]._supports_p... | pytest pandas/tests/indexes/datetimes/test_partial_slicing.py::TestSlicing::test_slice_reduce_to_series |
pandas | 167 | def convert_to_index_sliceable(obj, key):
# We might have a datetimelike string that we can translate to a
# slice here via partial string indexing
if idx.is_all_dates:
try:
return idx._get_string_slice(key)
except (KeyError, ValueError, NotImplementedErr... | def convert_to_index_sliceable(obj, key):
# We might have a datetimelike string that we can translate to a
# slice here via partial string indexing
if idx._supports_partial_string_indexing:
try:
return idx._get_string_slice(key)
except (KeyError, ValueErr... | pytest pandas/tests/indexes/datetimes/test_partial_slicing.py::TestSlicing::test_slice_reduce_to_series |
matplotlib | 12 | class Axes(_AxesBase):
if not np.iterable(xmax):
xmax = [xmax]
y, xmin, xmax = cbook.delete_masked_points(y, xmin, xmax)
y = np.ravel(y)
xmin = np.resize(xmin, y.shape)
xmax = np.resize(xmax, y.shape)
verts = [((thisxmin, thisy), (thisxmax, thisy))
... | class Axes(_AxesBase):
if not np.iterable(xmax):
xmax = [xmax]
# Create and combine masked_arrays from input
y, xmin, xmax = cbook._combine_masks(y, xmin, xmax)
y = np.ravel(y)
xmin = np.ravel(xmin)
xmax = np.ravel(xmax)
masked_verts = np.ma.empty((l... | pytest lib/matplotlib/tests/test_axes.py::test_lines_with_colors |
matplotlib | 12 | class Axes(_AxesBase):
if not np.iterable(ymax):
ymax = [ymax]
x, ymin, ymax = cbook.delete_masked_points(x, ymin, ymax)
x = np.ravel(x)
ymin = np.resize(ymin, x.shape)
ymax = np.resize(ymax, x.shape)
verts = [((thisx, thisymin), (thisx, thisymax))
... | class Axes(_AxesBase):
if not np.iterable(ymax):
ymax = [ymax]
# Create and combine masked_arrays from input
x, ymin, ymax = cbook._combine_masks(x, ymin, ymax)
x = np.ravel(x)
ymin = np.ravel(ymin)
ymax = np.ravel(ymax)
masked_verts = np.ma.empty((l... | pytest lib/matplotlib/tests/test_axes.py::test_lines_with_colors |
fastapi | 6 | async def request_body_to_args(
for field in required_params:
value: Any = None
if received_body is not None:
if field.shape in sequence_shapes and isinstance(
received_body, FormData
):
value = received_body.getlist... | async def request_body_to_args(
for field in required_params:
value: Any = None
if received_body is not None:
if (
field.shape in sequence_shapes or field.type_ in sequence_types
) and isinstance(received_body, FormData):
... | pytest tests/test_forms_from_non_typing_sequences.py::test_python_tuple_param_as_form |
thefuck | 32 | def match(command, settings):
return 'ls' in command.script and not ('ls -' in command.script)
def get_new_command(command, settings): | def match(command, settings):
return (command.script == 'ls'
or command.script.startswith('ls ')
and not ('ls -' in command.script))
def get_new_command(command, settings): | pytest tests/rules/test_ls_lah.py::test_match |
youtube-dl | 25 | def js_to_json(code):
}.get(m.group(0), m.group(0)), v[1:-1])
INTEGER_TABLE = (
(r'^0[xX][0-9a-fA-F]+', 16),
(r'^0+[0-7]+', 8),
)
for regex, base in INTEGER_TABLE:
im = re.match(regex, v)
if im:
i = int(im.group(0), ba... | def js_to_json(code):
}.get(m.group(0), m.group(0)), v[1:-1])
INTEGER_TABLE = (
(r'^(0[xX][0-9a-fA-F]+)\s*:?$', 16),
(r'^(0+[0-7]+)\s*:?$', 8),
)
for regex, base in INTEGER_TABLE:
im = re.match(regex, v)
if im:
i = int... | python -m unittest -q test.test_utils.TestUtil.test_js_to_json_realworld |
pandas | 108 | from .common import (
is_unsigned_integer_dtype,
pandas_dtype,
)
from .dtypes import DatetimeTZDtype, ExtensionDtype, PeriodDtype
from .generic import (
ABCDataFrame,
ABCDatetimeArray, | from .common import (
is_unsigned_integer_dtype,
pandas_dtype,
)
from .dtypes import DatetimeTZDtype, ExtensionDtype, IntervalDtype, PeriodDtype
from .generic import (
ABCDataFrame,
ABCDatetimeArray, | pytest pandas/tests/dtypes/cast/test_infer_dtype.py::test_infer_from_interval |
pandas | 108 | def infer_dtype_from_scalar(val, pandas_dtype: bool = False):
if lib.is_period(val):
dtype = PeriodDtype(freq=val.freq)
val = val.ordinal
return dtype, val
| def infer_dtype_from_scalar(val, pandas_dtype: bool = False):
if lib.is_period(val):
dtype = PeriodDtype(freq=val.freq)
val = val.ordinal
elif lib.is_interval(val):
subtype = infer_dtype_from_scalar(val.left, pandas_dtype=True)[0]
dtype = IntervalDtype(sub... | pytest pandas/tests/dtypes/cast/test_infer_dtype.py::test_infer_from_interval |
pandas | 54 | class CategoricalDtype(PandasExtensionDtype, ExtensionDtype):
raise ValueError(
"Cannot specify `categories` or `ordered` together with `dtype`."
)
elif is_categorical(values):
# If no "dtype" was passed, use the one from "values", but honor
... | class CategoricalDtype(PandasExtensionDtype, ExtensionDtype):
raise ValueError(
"Cannot specify `categories` or `ordered` together with `dtype`."
)
elif not isinstance(dtype, CategoricalDtype):
raise ValueError(f"Cannot not construct Catego... | pytest pandas/tests/dtypes/test_dtypes.py::TestCategoricalDtype::test_from_values_or_dtype_invalid_dtype |
pandas | 54 | class Base:
assert not indices.equals(np.array(indices))
# Cannot pass in non-int64 dtype to RangeIndex
if not isinstance(indices, RangeIndex):
same_values = Index(indices, dtype=object)
assert indices.equals(same_values)
assert same_values.equals(indices) | class Base:
assert not indices.equals(np.array(indices))
# Cannot pass in non-int64 dtype to RangeIndex
if not isinstance(indices, (RangeIndex, CategoricalIndex)):
# TODO: CategoricalIndex can be re-allowed following GH#32167
same_values = Index(indices, dtype=object)
... | pytest pandas/tests/dtypes/test_dtypes.py::TestCategoricalDtype::test_from_values_or_dtype_invalid_dtype |
thefuck | 3 | class Fish(Generic):
def info(self):
"""Returns the name and version of the current shell"""
proc = Popen(['fish', '-c', 'echo $FISH_VERSION'],
stdout=PIPE, stderr=DEVNULL)
version = proc.stdout.read().decode('utf-8').strip()
return u'Fish Shell {}'.format(versi... | class Fish(Generic):
def info(self):
"""Returns the name and version of the current shell"""
proc = Popen(['fish', '--version'],
stdout=PIPE, stderr=DEVNULL)
version = proc.stdout.read().decode('utf-8').split()[-1]
return u'Fish Shell {}'.format(version)
de... | pytest tests/shells/test_fish.py::TestFish::test_info |
sanic | 5 | LOGGING_CONFIG_DEFAULTS = dict(
version=1,
disable_existing_loggers=False,
loggers={
"root": {"level": "INFO", "handlers": ["console"]},
"sanic.error": {
"level": "INFO",
"handlers": ["error_console"], | LOGGING_CONFIG_DEFAULTS = dict(
version=1,
disable_existing_loggers=False,
loggers={
"sanic.root": {"level": "INFO", "handlers": ["console"]},
"sanic.error": {
"level": "INFO",
"handlers": ["error_console"], | pytest tests/test_logging.py::test_logging_modified_root_logger_config |
pandas | 129 | class DatetimeLikeArrayMixin(ExtensionOpsMixin, AttributesMixin, ExtensionArray)
if is_datetime64_any_dtype(other) and is_timedelta64_dtype(self.dtype):
# ndarray[datetime64] cannot be subtracted from self, so
# we need to wrap in DatetimeArray/Index and flip the operation
if... | class DatetimeLikeArrayMixin(ExtensionOpsMixin, AttributesMixin, ExtensionArray)
if is_datetime64_any_dtype(other) and is_timedelta64_dtype(self.dtype):
# ndarray[datetime64] cannot be subtracted from self, so
# we need to wrap in DatetimeArray/Index and flip the operation
if... | pytest pandas/tests/arithmetic/test_timedelta64.py::TestTimedeltaArraylikeAddSubOps::test_td64arr_add_sub_datetimelike_scalar |
pandas | 88 | def pivot_table(
agged[v] = maybe_downcast_to_dtype(agged[v], data[v].dtype)
table = agged
if table.index.nlevels > 1:
# Related GH #17123
# If index_names are integers, determine whether the integers refer
# to the level position or name. | def pivot_table(
agged[v] = maybe_downcast_to_dtype(agged[v], data[v].dtype)
table = agged
# GH17038, this check should only happen if index is defined (not None)
if table.index.nlevels > 1 and index:
# Related GH #17123
# If index_names are integers, determine whether the ... | pytest pandas/tests/reshape/test_pivot.py::TestPivotTable::test_pivot_table_multiindex_only |
pandas | 75 | class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
try:
loc = self._get_string_slice(key)
return series[loc]
except (TypeError, ValueError):
pass
asdt, reso = parse_time_string(key, self.freq) | class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
try:
loc = self._get_string_slice(key)
return series[loc]
except (TypeError, ValueError, OverflowError):
pass
asdt, reso = parse_time_string(key, self.freq) | pytest pandas/tests/indexes/period/test_indexing.py::TestIndexing::test_contains |
pandas | 75 | class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
"""
if isinstance(key, str):
try:
return self._get_string_slice(key)
except (TypeError, KeyError, ValueError, OverflowError):
pass
try:
asdt, r... | class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
"""
if isinstance(key, str):
try:
loc = self._get_string_slice(key)
return loc
except (TypeError, ValueError):
pass
try:
asdt,... | pytest pandas/tests/indexes/period/test_indexing.py::TestIndexing::test_contains |
thefuck | 13 | from thefuck.utils import eager
@git_support
def match(command):
return ('branch' in command.script
and "fatal: A branch named '" in command.stderr
and " already exists." in command.stderr)
| from thefuck.utils import eager
@git_support
def match(command):
return ("fatal: A branch named '" in command.stderr
and " already exists." in command.stderr)
| pytest tests/rules/test_git_branch_exists.py::test_get_new_command |
thefuck | 13 | def get_new_command(command):
branch_name = re.findall(
r"fatal: A branch named '([^']*)' already exists.", command.stderr)[0]
new_command_templates = [['git branch -d {0}', 'git branch {0}'],
['git branch -D {0}', 'git branch {0}'],
['git checko... | def get_new_command(command):
branch_name = re.findall(
r"fatal: A branch named '([^']*)' already exists.", command.stderr)[0]
new_command_templates = [['git branch -d {0}', 'git branch {0}'],
['git branch -d {0}', 'git checkout -b {0}'],
['git b... | pytest tests/rules/test_git_branch_exists.py::test_get_new_command |
pandas | 146 | def array_equivalent(left, right, strict_nan=False):
if not isinstance(right_value, float) or not np.isnan(right_value):
return False
else:
if np.any(left_value != right_value):
return False
return True
# NaNs can occur in ... | def array_equivalent(left, right, strict_nan=False):
if not isinstance(right_value, float) or not np.isnan(right_value):
return False
else:
try:
if np.any(left_value != right_value):
return False
... | pytest pandas/tests/dtypes/test_missing.py::test_array_equivalent_tzawareness |
pandas | 146 | class Index(IndexOpsMixin, PandasObject):
# if other is not object, use other's logic for coercion
return other.equals(self)
try:
return array_equivalent(
com.values_from_object(self), com.values_from_object(other)
)
except Exception:
... | class Index(IndexOpsMixin, PandasObject):
# if other is not object, use other's logic for coercion
return other.equals(self)
return array_equivalent(
com.values_from_object(self), com.values_from_object(other)
)
def identical(self, other):
""" | pytest pandas/tests/dtypes/test_missing.py::test_array_equivalent_tzawareness |
pandas | 125 | class Categorical(ExtensionArray, PandasObject):
code_values = code_values[null_mask | (code_values >= 0)]
return algorithms.isin(self.codes, code_values)
# The Series.cat accessor
| class Categorical(ExtensionArray, PandasObject):
code_values = code_values[null_mask | (code_values >= 0)]
return algorithms.isin(self.codes, code_values)
def replace(self, to_replace, value, inplace: bool = False):
"""
Replaces all instances of one value with another
Param... | pytest pandas/tests/frame/test_replace.py::TestDataFrameReplace::test_categorical_replace_with_dict |
pandas | 125 | class CategoricalBlock(ExtensionBlock):
)
return result
# -----------------------------------------------------------------
# Constructor Helpers | class CategoricalBlock(ExtensionBlock):
)
return result
def replace(
self,
to_replace,
value,
inplace: bool = False,
filter=None,
regex: bool = False,
convert: bool = True,
):
inplace = validate_bool_kwarg(inplace, "inplace")
... | pytest pandas/tests/frame/test_replace.py::TestDataFrameReplace::test_categorical_replace_with_dict |
pandas | 84 | def _unstack_multiple(data, clocs, fill_value=None):
index = data.index
clocs = [index._get_level_number(i) for i in clocs]
rlocs = [i for i in range(index.nlevels) if i not in clocs] | def _unstack_multiple(data, clocs, fill_value=None):
index = data.index
# GH 19966 Make sure if MultiIndexed index has tuple name, they will be
# recognised as a whole
if clocs in index.names:
clocs = [clocs]
clocs = [index._get_level_number(i) for i in clocs]
rlocs = [i for i in rang... | pytest pandas/tests/frame/test_reshape.py::TestDataFrameReshape::test_unstack_mixed_type_name_in_multiindex |
pandas | 84 | import pytest
import pandas.util._test_decorators as td
import pandas as pd
from pandas import DataFrame, MultiIndex, Series
import pandas._testing as tm
| import pytest
import pandas.util._test_decorators as td
import pandas as pd
from pandas import DataFrame, Series
import pandas._testing as tm
| pytest pandas/tests/frame/test_reshape.py::TestDataFrameReshape::test_unstack_mixed_type_name_in_multiindex |
pandas | 84 | class TestSeriesAnalytics:
assert s.is_monotonic is False
assert s.is_monotonic_decreasing is True
def test_unstack(self):
index = MultiIndex(
levels=[["bar", "foo"], ["one", "three", "two"]],
codes=[[1, 1, 0, 0], [0, 1, 0, 2]],
)
s = Series(np.aran... | class TestSeriesAnalytics:
assert s.is_monotonic is False
assert s.is_monotonic_decreasing is True
@pytest.mark.parametrize("func", [np.any, np.all])
@pytest.mark.parametrize("kwargs", [dict(keepdims=True), dict(out=object())])
@td.skip_if_np_lt("1.15") | pytest pandas/tests/frame/test_reshape.py::TestDataFrameReshape::test_unstack_mixed_type_name_in_multiindex |
pandas | 79 | from pandas.core.frame import DataFrame
from pandas.core.groupby import ops
from pandas.core.groupby.categorical import recode_for_groupby, recode_from_groupby
from pandas.core.indexes.api import CategoricalIndex, Index, MultiIndex
from pandas.core.series import Series
from pandas.io.formats.printing import pprint_thi... | from pandas.core.frame import DataFrame
from pandas.core.groupby import ops
from pandas.core.groupby.categorical import recode_for_groupby, recode_from_groupby
from pandas.core.indexes.api import CategoricalIndex, Index, MultiIndex
from pandas.core.indexes.base import InvalidIndexError
from pandas.core.series import Se... | pytest pandas/tests/indexes/datetimes/test_indexing.py::TestDatetimeIndex::test_get_loc |
pandas | 79 | def get_grouper(
items = obj._data.items
try:
items.get_loc(key)
except (KeyError, TypeError):
# TypeError shows up here if we pass e.g. Int64Index
return False
| def get_grouper(
items = obj._data.items
try:
items.get_loc(key)
except (KeyError, TypeError, InvalidIndexError):
# TypeError shows up here if we pass e.g. Int64Index
return False
| pytest pandas/tests/indexes/datetimes/test_indexing.py::TestDatetimeIndex::test_get_loc |
pandas | 79 | from pandas.core.arrays.datetimes import (
validate_tz_from_dtype,
)
import pandas.core.common as com
from pandas.core.indexes.base import Index, maybe_extract_name
from pandas.core.indexes.datetimelike import (
DatetimelikeDelegateMixin,
DatetimeTimedeltaMixin, | from pandas.core.arrays.datetimes import (
validate_tz_from_dtype,
)
import pandas.core.common as com
from pandas.core.indexes.base import Index, InvalidIndexError, maybe_extract_name
from pandas.core.indexes.datetimelike import (
DatetimelikeDelegateMixin,
DatetimeTimedeltaMixin, | pytest pandas/tests/indexes/datetimes/test_indexing.py::TestDatetimeIndex::test_get_loc |
pandas | 79 | class DatetimeIndex(DatetimeTimedeltaMixin, DatetimeDelegateMixin):
Fast lookup of value from 1-dimensional ndarray. Only use this if you
know what you're doing
"""
if isinstance(key, (datetime, np.datetime64)):
return self.get_value_maybe_box(series, key) | class DatetimeIndex(DatetimeTimedeltaMixin, DatetimeDelegateMixin):
Fast lookup of value from 1-dimensional ndarray. Only use this if you
know what you're doing
"""
if not is_scalar(key):
raise InvalidIndexError(key)
if isinstance(key, (datetime, np.datetime64)):
... | pytest pandas/tests/indexes/datetimes/test_indexing.py::TestDatetimeIndex::test_get_loc |
pandas | 79 | class DatetimeIndex(DatetimeTimedeltaMixin, DatetimeDelegateMixin):
-------
loc : int
"""
if is_valid_nat_for_dtype(key, self.dtype):
key = NaT
| class DatetimeIndex(DatetimeTimedeltaMixin, DatetimeDelegateMixin):
-------
loc : int
"""
if not is_scalar(key):
raise InvalidIndexError(key)
if is_valid_nat_for_dtype(key, self.dtype):
key = NaT
| pytest pandas/tests/indexes/datetimes/test_indexing.py::TestDatetimeIndex::test_get_loc |
pandas | 79 | class MultiIndex(Index):
indexer = self._get_level_indexer(key, level=level)
new_index = maybe_mi_droplevels(indexer, [0], drop_level)
return indexer, new_index
except TypeError:
pass
if not any(isinstance(k, slice) for... | class MultiIndex(Index):
indexer = self._get_level_indexer(key, level=level)
new_index = maybe_mi_droplevels(indexer, [0], drop_level)
return indexer, new_index
except (TypeError, InvalidIndexError):
pass
if not any(isi... | pytest pandas/tests/indexes/datetimes/test_indexing.py::TestDatetimeIndex::test_get_loc |
pandas | 79 | class Series(base.IndexOpsMixin, generic.NDFrame):
self[:] = value
else:
self.loc[key] = value
except TypeError as e:
if isinstance(key, tuple) and not isinstance(self.index, MultiIndex): | class Series(base.IndexOpsMixin, generic.NDFrame):
self[:] = value
else:
self.loc[key] = value
except InvalidIndexError:
# e.g. slice
self._set_with(key, value)
except TypeError as e:
if isinstance(key, tuple) and not isins... | pytest pandas/tests/indexes/datetimes/test_indexing.py::TestDatetimeIndex::test_get_loc |
pandas | 16 | def _make_wrapped_arith_op_with_freq(opname: str):
if result is NotImplemented:
return NotImplemented
new_freq = self._get_addsub_freq(other)
result._freq = new_freq
return result
| def _make_wrapped_arith_op_with_freq(opname: str):
if result is NotImplemented:
return NotImplemented
new_freq = self._get_addsub_freq(other, result)
result._freq = new_freq
return result
| pytest pandas/tests/arithmetic/test_period.py::TestPeriodIndexSeriesMethods::test_pi_sub_period |
pandas | 16 | class DatetimeIndexOpsMixin(ExtensionIndex):
# --------------------------------------------------------------------
# Arithmetic Methods
def _get_addsub_freq(self, other) -> Optional[DateOffset]:
"""
Find the freq we expect the result of an addition/subtraction operation
to have.
... | class DatetimeIndexOpsMixin(ExtensionIndex):
# --------------------------------------------------------------------
# Arithmetic Methods
def _get_addsub_freq(self, other, result) -> Optional[DateOffset]:
"""
Find the freq we expect the result of an addition/subtraction operation
to ... | pytest pandas/tests/arithmetic/test_period.py::TestPeriodIndexSeriesMethods::test_pi_sub_period |
fastapi | 11 | def get_flat_dependant(dependant: Dependant) -> Dependant:
def is_scalar_field(field: Field) -> bool:
return (
field.shape == Shape.SINGLETON
and not lenient_issubclass(field.type_, BaseModel)
and not lenient_issubclass(field.type_, sequence_types + (dict,))
and not isinstance(fiel... | def get_flat_dependant(dependant: Dependant) -> Dependant:
def is_scalar_field(field: Field) -> bool:
if not (
field.shape == Shape.SINGLETON
and not lenient_issubclass(field.type_, BaseModel)
and not lenient_issubclass(field.type_, sequence_types + (dict,))
and not isinstance(fiel... | pytest tests/test_union_inherited_body.py::test_post_item |
scrapy | 22 | class XmlItemExporter(BaseItemExporter):
elif is_listlike(serialized_value):
for value in serialized_value:
self._export_xml_field('value', value)
else:
self._xg_characters(serialized_value)
self.xg.endElement(name)
# Workaround for http://bugs.python... | class XmlItemExporter(BaseItemExporter):
elif is_listlike(serialized_value):
for value in serialized_value:
self._export_xml_field('value', value)
elif isinstance(serialized_value, six.text_type):
self._xg_characters(serialized_value)
else:
sel... | python -m unittest -q tests.test_exporters.XmlItemExporterTest.test_nonstring_types_item |
keras | 11 | from __future__ import print_function
import warnings
import numpy as np
from .training_utils import iter_sequence_infinite
from .. import backend as K
from ..utils.data_utils import Sequence | from __future__ import print_function
import warnings
import numpy as np
from .training_utils import is_sequence
from .training_utils import iter_sequence_infinite
from .. import backend as K
from ..utils.data_utils import Sequence | pytest tests/integration_tests/test_image_data_tasks.py::test_image_data_generator_training |
keras | 11 | def fit_generator(model,
if do_validation:
model._make_test_function()
is_sequence = isinstance(generator, Sequence)
if not is_sequence and use_multiprocessing and workers > 1:
warnings.warn(
UserWarning('Using a generator with `use_multiprocessing=True`'
... | def fit_generator(model,
if do_validation:
model._make_test_function()
use_sequence_api = is_sequence(generator)
if not use_sequence_api and use_multiprocessing and workers > 1:
warnings.warn(
UserWarning('Using a generator with `use_multiprocessing=True`'
... | pytest tests/integration_tests/test_image_data_tasks.py::test_image_data_generator_training |
keras | 11 | def fit_generator(model,
# python 2 has 'next', 3 has '__next__'
# avoid any explicit version checks
val_gen = (hasattr(validation_data, 'next') or
hasattr(validation_data, '__next__') or
isinstance(validation_data, Sequence))
if (val_gen and not isinstance(validation_data... | def fit_generator(model,
# python 2 has 'next', 3 has '__next__'
# avoid any explicit version checks
val_use_sequence_api = is_sequence(validation_data)
val_gen = (hasattr(validation_data, 'next') or
hasattr(validation_data, '__next__') or
val_use_sequence_api)
if (val... | pytest tests/integration_tests/test_image_data_tasks.py::test_image_data_generator_training |
keras | 11 | def fit_generator(model,
if val_gen and workers > 0:
# Create an Enqueuer that can be reused
val_data = validation_data
if isinstance(val_data, Sequence):
val_enqueuer = OrderedEnqueuer(
val_data,
... | def fit_generator(model,
if val_gen and workers > 0:
# Create an Enqueuer that can be reused
val_data = validation_data
if is_sequence(val_data):
val_enqueuer = OrderedEnqueuer(
val_data,
use_... | pytest tests/integration_tests/test_image_data_tasks.py::test_image_data_generator_training |
keras | 11 | def fit_generator(model,
val_enqueuer_gen = val_enqueuer.get()
elif val_gen:
val_data = validation_data
if isinstance(val_data, Sequence):
val_enqueuer_gen = iter_sequence_infinite(val_data)
validation_steps = validation... | def fit_generator(model,
val_enqueuer_gen = val_enqueuer.get()
elif val_gen:
val_data = validation_data
if is_sequence(val_data):
val_enqueuer_gen = iter_sequence_infinite(val_data)
validation_steps = validation_steps or... | pytest tests/integration_tests/test_image_data_tasks.py::test_image_data_generator_training |
keras | 11 | def fit_generator(model,
cbk.validation_data = val_data
if workers > 0:
if is_sequence:
enqueuer = OrderedEnqueuer(
generator,
use_multiprocessing=use_multiprocessing, | def fit_generator(model,
cbk.validation_data = val_data
if workers > 0:
if use_sequence_api:
enqueuer = OrderedEnqueuer(
generator,
use_multiprocessing=use_multiprocessing, | pytest tests/integration_tests/test_image_data_tasks.py::test_image_data_generator_training |
keras | 11 | def fit_generator(model,
enqueuer.start(workers=workers, max_queue_size=max_queue_size)
output_generator = enqueuer.get()
else:
if is_sequence:
output_generator = iter_sequence_infinite(generator)
else:
output_generator = generator | def fit_generator(model,
enqueuer.start(workers=workers, max_queue_size=max_queue_size)
output_generator = enqueuer.get()
else:
if use_sequence_api:
output_generator = iter_sequence_infinite(generator)
else:
output_generator = gener... | pytest tests/integration_tests/test_image_data_tasks.py::test_image_data_generator_training |
keras | 11 | def evaluate_generator(model, generator,
steps_done = 0
outs_per_batch = []
batch_sizes = []
is_sequence = isinstance(generator, Sequence)
if not is_sequence and use_multiprocessing and workers > 1:
warnings.warn(
UserWarning('Using a generator with `use_multiprocessing=True`'
... | def evaluate_generator(model, generator,
steps_done = 0
outs_per_batch = []
batch_sizes = []
use_sequence_api = is_sequence(generator)
if not use_sequence_api and use_multiprocessing and workers > 1:
warnings.warn(
UserWarning('Using a generator with `use_multiprocessing=True`'
... | pytest tests/integration_tests/test_image_data_tasks.py::test_image_data_generator_training |
keras | 11 | def evaluate_generator(model, generator,
try:
if workers > 0:
if is_sequence:
enqueuer = OrderedEnqueuer(
generator,
use_multiprocessing=use_multiprocessing) | def evaluate_generator(model, generator,
try:
if workers > 0:
if use_sequence_api:
enqueuer = OrderedEnqueuer(
generator,
use_multiprocessing=use_multiprocessing) | pytest tests/integration_tests/test_image_data_tasks.py::test_image_data_generator_training |
keras | 11 | def evaluate_generator(model, generator,
enqueuer.start(workers=workers, max_queue_size=max_queue_size)
output_generator = enqueuer.get()
else:
if is_sequence:
output_generator = iter_sequence_infinite(generator)
else:
output_genera... | def evaluate_generator(model, generator,
enqueuer.start(workers=workers, max_queue_size=max_queue_size)
output_generator = enqueuer.get()
else:
if use_sequence_api:
output_generator = iter_sequence_infinite(generator)
else:
output_g... | pytest tests/integration_tests/test_image_data_tasks.py::test_image_data_generator_training |
keras | 11 | def predict_generator(model, generator,
steps_done = 0
all_outs = []
is_sequence = isinstance(generator, Sequence)
if not is_sequence and use_multiprocessing and workers > 1:
warnings.warn(
UserWarning('Using a generator with `use_multiprocessing=True`'
' and... | def predict_generator(model, generator,
steps_done = 0
all_outs = []
use_sequence_api = is_sequence(generator)
if not use_sequence_api and use_multiprocessing and workers > 1:
warnings.warn(
UserWarning('Using a generator with `use_multiprocessing=True`'
' an... | pytest tests/integration_tests/test_image_data_tasks.py::test_image_data_generator_training |
keras | 11 | def predict_generator(model, generator,
try:
if workers > 0:
if is_sequence:
enqueuer = OrderedEnqueuer(
generator,
use_multiprocessing=use_multiprocessing) | def predict_generator(model, generator,
try:
if workers > 0:
if use_sequence_api:
enqueuer = OrderedEnqueuer(
generator,
use_multiprocessing=use_multiprocessing) | pytest tests/integration_tests/test_image_data_tasks.py::test_image_data_generator_training |
keras | 11 | def predict_generator(model, generator,
enqueuer.start(workers=workers, max_queue_size=max_queue_size)
output_generator = enqueuer.get()
else:
if is_sequence:
output_generator = iter_sequence_infinite(generator)
else:
output_generat... | def predict_generator(model, generator,
enqueuer.start(workers=workers, max_queue_size=max_queue_size)
output_generator = enqueuer.get()
else:
if use_sequence_api:
output_generator = iter_sequence_infinite(generator)
else:
output_ge... | pytest tests/integration_tests/test_image_data_tasks.py::test_image_data_generator_training |
keras | 11 | import warnings
from .. import backend as K
from .. import losses
from ..utils.generic_utils import to_list
| import warnings
from .. import backend as K
from .. import losses
from ..utils import Sequence
from ..utils.generic_utils import to_list
| pytest tests/integration_tests/test_image_data_tasks.py::test_image_data_generator_training |
keras | 11 | def iter_sequence_infinite(seq):
while True:
for item in seq:
yield item | def iter_sequence_infinite(seq):
while True:
for item in seq:
yield item
def is_sequence(seq):
"""Determine if an object follows the Sequence API.
# Arguments
seq: a possible Sequence object
# Returns
boolean, whether the object follows the Sequence API.
"""
... | pytest tests/integration_tests/test_image_data_tasks.py::test_image_data_generator_training |
keras | 11 | class Sequence(object):
```
"""
@abstractmethod
def __getitem__(self, index):
"""Gets batch at position `index`. | class Sequence(object):
```
"""
use_sequence_api = True
@abstractmethod
def __getitem__(self, index):
"""Gets batch at position `index`. | pytest tests/integration_tests/test_image_data_tasks.py::test_image_data_generator_training |
keras | 11 | from keras.utils.data_utils import validate_file
from keras import backend as K
pytestmark = pytest.mark.skipif(
K.backend() == 'tensorflow',
reason='Temporarily disabled until the use_multiprocessing problem is solved')
if sys.version_info < (3,): | from keras.utils.data_utils import validate_file
from keras import backend as K
pytestmark = pytest.mark.skipif(
K.backend() == 'tensorflow' and 'TRAVIS_PYTHON_VERSION' in os.environ,
reason='Temporarily disabled until the use_multiprocessing problem is solved')
if sys.version_info < (3,): | pytest tests/integration_tests/test_image_data_tasks.py::test_image_data_generator_training |
keras | 11 | from keras.utils import Sequence
from keras import backend as K
pytestmark = pytest.mark.skipif(
K.backend() == 'tensorflow',
reason='Temporarily disabled until the use_multiprocessing problem is solved')
STEPS_PER_EPOCH = 100 | from keras.utils import Sequence
from keras import backend as K
pytestmark = pytest.mark.skipif(
K.backend() == 'tensorflow' and 'TRAVIS_PYTHON_VERSION' in os.environ,
reason='Temporarily disabled until the use_multiprocessing problem is solved')
STEPS_PER_EPOCH = 100 | pytest tests/integration_tests/test_image_data_tasks.py::test_image_data_generator_training |
pandas | 37 | from pandas.core.dtypes.inference import is_array_like
from pandas import compat
from pandas.core import ops
from pandas.core.arrays import PandasArray
from pandas.core.construction import extract_array
from pandas.core.indexers import check_array_indexer
from pandas.core.missing import isna | from pandas.core.dtypes.inference import is_array_like
from pandas import compat
from pandas.core import ops
from pandas.core.arrays import IntegerArray, PandasArray
from pandas.core.arrays.integer import _IntegerDtype
from pandas.core.construction import extract_array
from pandas.core.indexers import check_array_inde... | pytest pandas/tests/arrays/string_/test_string.py::test_astype_int |
pandas | 37 | class StringArray(PandasArray):
if copy:
return self.copy()
return self
return super().astype(dtype, copy)
def _reduce(self, name, skipna=True, **kwargs): | class StringArray(PandasArray):
if copy:
return self.copy()
return self
elif isinstance(dtype, _IntegerDtype):
arr = self._ndarray.copy()
mask = self.isna()
arr[mask] = 0
values = arr.astype(dtype.numpy_dtype)
re... | pytest pandas/tests/arrays/string_/test_string.py::test_astype_int |
black | 23 | def format_str(src_contents: str, line_length: int) -> FileContent:
return dst_contents
def lib2to3_parse(src_txt: str) -> Node:
"""Given a string with source, return the lib2to3 Node."""
grammar = pygram.python_grammar_no_print_statement
drv = driver.Driver(grammar, pytree.convert)
if src_txt[-1]... | def format_str(src_contents: str, line_length: int) -> FileContent:
return dst_contents
GRAMMARS = [
pygram.python_grammar_no_print_statement_no_exec_statement,
pygram.python_grammar_no_print_statement,
pygram.python_grammar_no_exec_statement,
pygram.python_grammar,
]
def lib2to3_parse(src_txt: ... | python -m unittest -q tests.test_black.BlackTestCase.test_python2 |
black | 23 | def whitespace(leaf: Leaf) -> str: # noqa C901
):
return NO
elif prev.type in OPENING_BRACKETS:
return NO
| def whitespace(leaf: Leaf) -> str: # noqa C901
):
return NO
elif (
prevp.type == token.RIGHTSHIFT
and prevp.parent
and prevp.parent.type == syms.shift_expr
and prevp.prev_sibling
and prevp.prev_sibling.type == token.NAME
... | python -m unittest -q tests.test_black.BlackTestCase.test_python2 |
black | 23 | def assert_equivalent(src: str, dst: str) -> None:
try:
src_ast = ast.parse(src)
except Exception as exc:
raise AssertionError(f"cannot parse source: {exc}") from None
try:
dst_ast = ast.parse(dst) | def assert_equivalent(src: str, dst: str) -> None:
try:
src_ast = ast.parse(src)
except Exception as exc:
major, minor = sys.version_info[:2]
raise AssertionError(
f"cannot use --safe with this file; failed to parse source file "
f"with Python {major}.{minor}'s bu... | python -m unittest -q tests.test_black.BlackTestCase.test_python2 |
black | 23 | python_symbols = Symbols(python_grammar)
python_grammar_no_print_statement = python_grammar.copy()
del python_grammar_no_print_statement.keywords["print"]
pattern_grammar = driver.load_packaged_grammar("blib2to3", _PATTERN_GRAMMAR_FILE)
pattern_symbols = Symbols(pattern_grammar) | python_symbols = Symbols(python_grammar)
python_grammar_no_print_statement = python_grammar.copy()
del python_grammar_no_print_statement.keywords["print"]
python_grammar_no_exec_statement = python_grammar.copy()
del python_grammar_no_exec_statement.keywords["exec"]
python_grammar_no_print_statement_no_exec_statement ... | python -m unittest -q tests.test_black.BlackTestCase.test_python2 |
black | 23 | def func_no_args():
for i in range(10):
print(i)
continue
return None
async def coroutine(arg):
"Single-line docstring. Multiline is harder to reformat."
async with some_connection() as conn:
await conn.do_what_i_mean('SELECT bobby, tables FROM xkcd', timeout=2) | def func_no_args():
for i in range(10):
print(i)
continue
exec("new-style exec", {}, {})
return None
async def coroutine(arg, exec=False):
"Single-line docstring. Multiline is harder to reformat."
async with some_connection() as conn:
await conn.do_what_i_mean('SELECT bobby, tables FROM xkcd', time... | python -m unittest -q tests.test_black.BlackTestCase.test_python2 |
black | 23 | def func_no_args():
print(i)
continue
return None
async def coroutine(arg):
"Single-line docstring. Multiline is harder to reformat."
async with some_connection() as conn:
await conn.do_what_i_mean('SELECT bobby, tables FROM xkcd', timeout=2) | def func_no_args():
print(i)
continue
exec("new-style exec", {}, {})
return None
async def coroutine(arg, exec=False):
"Single-line docstring. Multiline is harder to reformat."
async with some_connection() as conn:
await conn.do_what_i_mean('SELECT bobby, tables FROM xkcd', ti... | python -m unittest -q tests.test_black.BlackTestCase.test_python2 |
youtube-dl | 29 | def unified_strdate(date_str, day_first=True):
timetuple = email.utils.parsedate_tz(date_str)
if timetuple:
upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
return compat_str(upload_date)
def determine_ext(url, default_ext='unknown_video'): | def unified_strdate(date_str, day_first=True):
timetuple = email.utils.parsedate_tz(date_str)
if timetuple:
upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
if upload_date is not None:
return compat_str(upload_date)
def determine_ext(url, default_ext='unknown_... | python -m unittest -q test.test_utils.TestUtil.test_unified_dates |
pandas | 104 | class GroupBy(_GroupBy):
# >>> result.stack(0).loc[pd.IndexSlice[:, ..., q], :]
# but this hits https://github.com/pandas-dev/pandas/issues/10710
# which doesn't reorder the list-like `q` on the inner level.
order = np.roll(list(range(result.index.nlevels)), -1)
... | class GroupBy(_GroupBy):
# >>> result.stack(0).loc[pd.IndexSlice[:, ..., q], :]
# but this hits https://github.com/pandas-dev/pandas/issues/10710
# which doesn't reorder the list-like `q` on the inner level.
order = list(range(1, result.index.nlevels)) + [0]
... | pytest pandas/tests/groupby/test_function.py::test_groupby_quantile_with_arraylike_q_and_int_columns |
pandas | 58 | class Categorical(ExtensionArray, PandasObject):
)
raise ValueError(msg)
codes = np.asarray(codes) # #21767
if len(codes) and not is_integer_dtype(codes):
raise ValueError("codes need to be array-like integers")
| class Categorical(ExtensionArray, PandasObject):
)
raise ValueError(msg)
if is_extension_array_dtype(codes) and is_integer_dtype(codes):
# Avoid the implicit conversion of Int to object
if isna(codes).any():
raise ValueError("codes cannot contain ... | pytest pandas/tests/arrays/categorical/test_constructors.py::TestCategoricalConstructors::test_from_codes_with_nullable_int_na_raises |
keras | 30 | class Model(Container):
str(generator_output))
# build batch logs
batch_logs = {}
if isinstance(x, list):
batch_size = x[0].shape[0]
elif isinstance(x, dict):
... | class Model(Container):
str(generator_output))
# build batch logs
batch_logs = {}
if x is None or len(x) == 0:
# Handle data tensors support when no input given
# step-siz... | pytest tests/keras/engine/test_training.py::test_model_with_external_loss |
keras | 30 | class Model(Container):
outs = [outs]
outs_per_batch.append(outs)
if isinstance(x, list):
batch_size = x[0].shape[0]
elif isinstance(x, dict):
batch_size = list(x.values())[0].shape[0] | class Model(Container):
outs = [outs]
outs_per_batch.append(outs)
if x is None or len(x) == 0:
# Handle data tensors support when no input given
# step-size = 1 for data tensors
batch_size = 1
... | pytest tests/keras/engine/test_training.py::test_model_with_external_loss |
keras | 3 | def _clone_functional_model(model, input_tensors=None):
kwargs['mask'] = computed_mask
output_tensors = to_list(
layer(computed_tensor, **kwargs))
output_masks = to_list(
layer.compute_mask(computed_tenso... | def _clone_functional_model(model, input_tensors=None):
kwargs['mask'] = computed_mask
output_tensors = to_list(
layer(computed_tensor, **kwargs))
if layer.supports_masking:
output_masks = to_list(
... | pytest tests/keras/test_sequential_model.py::test_clone_functional_model_with_multi_outputs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.