project stringclasses 17
values | bug_id int64 1 169 | buggy stringlengths 81 57.2k | fixed stringlengths 85 31.2k | test_command stringlengths 44 133 |
|---|---|---|---|---|
luigi | 23 | class CentralPlannerScheduler(Scheduler):
# TODO: remove tasks that can't be done, figure out if the worker has absolutely
# nothing it can wait for
worker_id = kwargs['worker']
# Return remaining tasks that have no FAILED descendents
self.update(worker_id, {'host': host}) | class CentralPlannerScheduler(Scheduler):
# TODO: remove tasks that can't be done, figure out if the worker has absolutely
# nothing it can wait for
if self._config.prune_on_get_work:
self.prune()
worker_id = kwargs['worker']
# Return remaining tasks that have no FA... | pytest test/worker_external_task_test.py::WorkerExternalTaskTest::test_external_dependency_completes_later |
pandas | 39 | def add_special_arithmetic_methods(cls):
def f(self, other):
result = method(self, other)
# this makes sure that we are aligned like the input
# we are updating inplace so we want to ignore is_copy
self._update_inplace( | def add_special_arithmetic_methods(cls):
def f(self, other):
result = method(self, other)
# Delete cacher
self._reset_cacher()
# this makes sure that we are aligned like the input
# we are updating inplace so we want to ignore is_copy
self... | pytest pandas/tests/frame//test_axis_select_reindex.py::TestDataFrameSelectReindex::test_inplace_drop_and_operation |
pandas | 106 | class Index(IndexOpsMixin, PandasObject):
if is_categorical(target):
tgt_values = np.asarray(target)
elif self.is_all_dates:
tgt_values = target.asi8
else:
tgt_values = target._ndarray_values | class Index(IndexOpsMixin, PandasObject):
if is_categorical(target):
tgt_values = np.asarray(target)
elif self.is_all_dates and target.is_all_dates: # GH 30399
tgt_values = target.asi8
else:
tgt_values = target._ndarray_values | pytest pandas/tests/indexes/multi/test_drop.py::test_drop_with_non_unique_datetime_index_and_invalid_keys |
fastapi | 8 | class APIRouter(routing.Router):
include_in_schema: bool = True,
response_class: Type[Response] = None,
name: str = None,
) -> None:
route = self.route_class(
path,
endpoint=endpoint,
response_model=response_model, | class APIRouter(routing.Router):
include_in_schema: bool = True,
response_class: Type[Response] = None,
name: str = None,
route_class_override: Optional[Type[APIRoute]] = None,
) -> None:
route_class = route_class_override or self.route_class
route = route_class(
... | pytest tests/test_custom_route_class.py::test_route_classes |
fastapi | 8 | class APIRouter(routing.Router):
include_in_schema=route.include_in_schema,
response_class=route.response_class or default_response_class,
name=route.name,
)
elif isinstance(route, routing.Route):
self.add_route( | class APIRouter(routing.Router):
include_in_schema=route.include_in_schema,
response_class=route.response_class or default_response_class,
name=route.name,
route_class_override=type(route),
)
elif isinstance(rout... | pytest tests/test_custom_route_class.py::test_route_classes |
pandas | 169 | class DataFrame(NDFrame):
if is_transposed:
data = data.T
result = data._data.quantile(
qs=q, axis=1, interpolation=interpolation, transposed=is_transposed
) | class DataFrame(NDFrame):
if is_transposed:
data = data.T
if len(data.columns) == 0:
# GH#23925 _get_numeric_data may have dropped all columns
cols = Index([], name=self.columns.name)
if is_list_like(q):
return self._constructor([], index=... | pytest pandas/tests/frame/test_quantile.py::TestDataFrameQuantile::test_quantile_empty_no_columns |
black | 21 | def dump_to_file(*output: str) -> str:
import tempfile
with tempfile.NamedTemporaryFile(
mode="w", prefix="blk_", suffix=".log", delete=False
) as f:
for lines in output:
f.write(lines) | def dump_to_file(*output: str) -> str:
import tempfile
with tempfile.NamedTemporaryFile(
mode="w", prefix="blk_", suffix=".log", delete=False, encoding="utf8"
) as f:
for lines in output:
f.write(lines) | python -m unittest -q tests.test_black.BlackTestCase.test_expression_ff |
pandas | 35 | class PeriodIndex(DatetimeIndexOpsMixin, Int64Index):
@cache_readonly
def _engine(self):
# To avoid a reference cycle, pass a weakref of self to _engine_type.
period = weakref.ref(self)
return self._engine_type(period, len(self))
@doc(Index.__contains__) | class PeriodIndex(DatetimeIndexOpsMixin, Int64Index):
@cache_readonly
def _engine(self):
# To avoid a reference cycle, pass a weakref of self._values to _engine_type.
period = weakref.ref(self._values)
return self._engine_type(period, len(self))
@doc(Index.__contains__) | pytest pandas/tests/indexes/multi/test_get_level_values.py::test_get_level_values_when_periods |
keras | 32 | class ReduceLROnPlateau(Callback):
monitored has stopped increasing; in `auto`
mode, the direction is automatically inferred
from the name of the monitored quantity.
epsilon: threshold for measuring the new optimum,
to only focus on significant changes.
co... | class ReduceLROnPlateau(Callback):
monitored has stopped increasing; in `auto`
mode, the direction is automatically inferred
from the name of the monitored quantity.
min_delta: threshold for measuring the new optimum,
to only focus on significant changes.
... | pytest tests/keras/test_callbacks.py::test_ReduceLROnPlateau_backwards_compatibility |
keras | 32 | class ReduceLROnPlateau(Callback):
"""
def __init__(self, monitor='val_loss', factor=0.1, patience=10,
verbose=0, mode='auto', epsilon=1e-4, cooldown=0, min_lr=0):
super(ReduceLROnPlateau, self).__init__()
self.monitor = monitor
if factor >= 1.0:
raise Valu... | class ReduceLROnPlateau(Callback):
"""
def __init__(self, monitor='val_loss', factor=0.1, patience=10,
verbose=0, mode='auto', min_delta=1e-4, cooldown=0, min_lr=0,
**kwargs):
super(ReduceLROnPlateau, self).__init__()
self.monitor = monitor
if factor >... | pytest tests/keras/test_callbacks.py::test_ReduceLROnPlateau_backwards_compatibility |
keras | 32 | class ReduceLROnPlateau(Callback):
self.mode = 'auto'
if (self.mode == 'min' or
(self.mode == 'auto' and 'acc' not in self.monitor)):
self.monitor_op = lambda a, b: np.less(a, b - self.epsilon)
self.best = np.Inf
else:
self.monitor_op = lambda a... | class ReduceLROnPlateau(Callback):
self.mode = 'auto'
if (self.mode == 'min' or
(self.mode == 'auto' and 'acc' not in self.monitor)):
self.monitor_op = lambda a, b: np.less(a, b - self.min_delta)
self.best = np.Inf
else:
self.monitor_op = lambda... | pytest tests/keras/test_callbacks.py::test_ReduceLROnPlateau_backwards_compatibility |
keras | 32 | class ReduceLROnPlateau(Callback):
self.best = current
self.wait = 0
elif not self.in_cooldown():
if self.wait >= self.patience:
old_lr = float(K.get_value(self.model.optimizer.lr))
if old_lr > self.min_lr: | class ReduceLROnPlateau(Callback):
self.best = current
self.wait = 0
elif not self.in_cooldown():
self.wait += 1
if self.wait >= self.patience:
old_lr = float(K.get_value(self.model.optimizer.lr))
if old_... | pytest tests/keras/test_callbacks.py::test_ReduceLROnPlateau_backwards_compatibility |
keras | 32 | class ReduceLROnPlateau(Callback):
'rate to %s.' % (epoch + 1, new_lr))
self.cooldown_counter = self.cooldown
self.wait = 0
self.wait += 1
def in_cooldown(self):
return self.cooldown_counter > 0 | class ReduceLROnPlateau(Callback):
'rate to %s.' % (epoch + 1, new_lr))
self.cooldown_counter = self.cooldown
self.wait = 0
def in_cooldown(self):
return self.cooldown_counter > 0 | pytest tests/keras/test_callbacks.py::test_ReduceLROnPlateau_backwards_compatibility |
pandas | 148 | class FrameApply:
from pandas import Series
if not should_reduce:
EMPTY_SERIES = Series([])
try:
r = self.f(EMPTY_SERIES, *self.args, **self.kwds)
except Exception:
pass
else:
should_reduce = not isinstance... | class FrameApply:
from pandas import Series
if not should_reduce:
try:
r = self.f(Series([]))
except Exception:
pass
else:
should_reduce = not isinstance(r, Series)
if should_reduce:
if len(self.agg... | pytest pandas/tests/frame/test_apply.py::TestDataFrameApply::test_nunique_empty |
fastapi | 13 | class APIRouter(routing.Router):
assert not prefix.endswith(
"/"
), "A path prefix must not end with '/', as the routes will start with '/'"
for route in router.routes:
if isinstance(route, APIRoute):
if responses is None:
r... | class APIRouter(routing.Router):
assert not prefix.endswith(
"/"
), "A path prefix must not end with '/', as the routes will start with '/'"
if responses is None:
responses = {}
for route in router.routes:
if isinstance(route, APIRoute):
... | pytest tests/test_additional_responses_router.py::test_openapi_schema |
fastapi | 13 | class APIRouter(routing.Router):
summary=route.summary,
description=route.description,
response_description=route.response_description,
responses=responses,
deprecated=route.deprecated,
methods=route.... | class APIRouter(routing.Router):
summary=route.summary,
description=route.description,
response_description=route.response_description,
responses=combined_responses,
deprecated=route.deprecated,
metho... | pytest tests/test_additional_responses_router.py::test_openapi_schema |
pandas | 14 | def should_series_dispatch(left, right, op):
# numpy integer dtypes as timedelta64 dtypes in this scenario
return True
if is_datetime64_dtype(ldtype) and is_object_dtype(rdtype):
# in particular case where right is an array of DateOffsets
return True
return False | def should_series_dispatch(left, right, op):
# numpy integer dtypes as timedelta64 dtypes in this scenario
return True
if (is_datetime64_dtype(ldtype) and is_object_dtype(rdtype)) or (
is_datetime64_dtype(rdtype) and is_object_dtype(ldtype)
):
# in particular case where one is a... | pytest pandas/tests/arithmetic/test_timedelta64.py::TestTimedeltaArraylikeAddSubOps::test_td64arr_add_offset_index |
pandas | 14 | def id_func(x):
# ------------------------------------------------------------------
@pytest.fixture(params=[1, np.array(1, dtype=np.int64)]) | def id_func(x):
# ------------------------------------------------------------------
@pytest.fixture(
params=[
("foo", None, None),
("Egon", "Venkman", None),
("NCC1701D", "NCC1701D", "NCC1701D"),
]
)
def names(request):
"""
A 3-tuple of names, the first two for operands, the l... | pytest pandas/tests/arithmetic/test_timedelta64.py::TestTimedeltaArraylikeAddSubOps::test_td64arr_add_offset_index |
pandas | 86 | def _convert_by(by):
@Substitution("\ndata : DataFrame")
@Appender(_shared_docs["pivot"], indents=1)
def pivot(data: "DataFrame", index=None, columns=None, values=None) -> "DataFrame":
if values is None:
cols = [columns] if index is None else [index, columns]
append = index is None | def _convert_by(by):
@Substitution("\ndata : DataFrame")
@Appender(_shared_docs["pivot"], indents=1)
def pivot(data: "DataFrame", index=None, columns=None, values=None) -> "DataFrame":
if columns is None:
raise TypeError("pivot() missing 1 required argument: 'columns'")
if values is None:
cols ... | pytest pandas/tests/reshape/test_pivot.py::TestPivotTable::test_pivot_columns_none_raise_error |
pandas | 127 | class NDFrame(PandasObject, SelectionMixin):
data = self.fillna(method=fill_method, limit=limit, axis=axis)
rs = data.div(data.shift(periods=periods, freq=freq, axis=axis, **kwargs)) - 1
rs = rs.reindex_like(data)
if freq is None:
mask = isna(com.values_from_object(data)... | class NDFrame(PandasObject, SelectionMixin):
data = self.fillna(method=fill_method, limit=limit, axis=axis)
rs = data.div(data.shift(periods=periods, freq=freq, axis=axis, **kwargs)) - 1
rs = rs.loc[~rs.index.duplicated()]
rs = rs.reindex_like(data)
if freq is None:
... | pytest pandas/tests/series/test_timeseries.py::TestTimeSeries::test_pct_change_with_duplicate_axis |
keras | 13 | def fit_generator(model,
elif val_gen:
val_data = validation_data
if isinstance(val_data, Sequence):
val_enqueuer_gen = iter_sequence_infinite(generator)
else:
val_enqueuer_gen = val_data
else: | def fit_generator(model,
elif val_gen:
val_data = validation_data
if isinstance(val_data, Sequence):
val_enqueuer_gen = iter_sequence_infinite(val_data)
validation_steps = validation_steps or len(val_data)
else:
... | pytest tests/keras/engine/test_training.py::test_model_methods |
httpie | 5 | class KeyValueType(object):
"""A type used with `argparse`."""
def __init__(self, *separators):
self.separators = separators
def __call__(self, string):
found = {}
for sep in self.separators:
regex = '[^\\\\]' + sep
match = re.search(regex, string)
... | class KeyValueType(object):
"""A type used with `argparse`."""
def __init__(self, *separators):
self.separators = separators
self.escapes = ['\\\\' + sep for sep in separators]
def __call__(self, string):
found = {}
found_escapes = []
for esc in self.escapes:
... | pytest tests/tests.py::TestItemParsing::test_escape_longsep |
scrapy | 20 | class SitemapSpider(Spider):
def _parse_sitemap(self, response):
if response.url.endswith('/robots.txt'):
for url in sitemap_urls_from_robots(response.body):
yield Request(url, callback=self._parse_sitemap)
else:
body = self._get_sitemap_body(response) | class SitemapSpider(Spider):
def _parse_sitemap(self, response):
if response.url.endswith('/robots.txt'):
for url in sitemap_urls_from_robots(response.text):
yield Request(url, callback=self._parse_sitemap)
else:
body = self._get_sitemap_body(response) | python -m unittest -q tests.test_spider.SitemapSpiderTest.test_get_sitemap_urls_from_robotstxt |
tqdm | 2 | class tqdm(Comparable):
if not _is_ascii(full_bar.charset) and _is_ascii(bar_format):
bar_format = _unicode(bar_format)
res = bar_format.format(bar=full_bar, **format_dict)
if ncols:
return disp_trim(res, ncols)
elif bar_format:
# ... | class tqdm(Comparable):
if not _is_ascii(full_bar.charset) and _is_ascii(bar_format):
bar_format = _unicode(bar_format)
res = bar_format.format(bar=full_bar, **format_dict)
return disp_trim(res, ncols) if ncols else res
elif bar_format:
# user-spe... | python3 -m pytest tqdm/tests/tests_tqdm.py::test_format_meter |
tqdm | 2 | class tqdm(Comparable):
if ncols else 10,
charset=Bar.BLANK)
res = bar_format.format(bar=full_bar, **format_dict)
if ncols:
return disp_trim(res, ncols)
else:
# no total: no progressbar, ETA, just progress stats
retu... | class tqdm(Comparable):
if ncols else 10,
charset=Bar.BLANK)
res = bar_format.format(bar=full_bar, **format_dict)
return disp_trim(res, ncols) if ncols else res
else:
# no total: no progressbar, ETA, just progress stats
return ((pre... | python3 -m pytest tqdm/tests/tests_tqdm.py::test_format_meter |
tqdm | 2 | def disp_trim(data, length):
if len(data) == disp_len(data):
return data[:length]
while disp_len(data) > length: # carefully delete one char at a time
data = data[:-1]
if RE_ANSI.search(data): # assume ANSI reset is required
return data + "\033[0m"
return data | def disp_trim(data, length):
if len(data) == disp_len(data):
return data[:length]
ansi_present = bool(RE_ANSI.search(data))
while disp_len(data) > length: # carefully delete one char at a time
data = data[:-1]
if ansi_present and bool(RE_ANSI.search(data)):
# assume ANSI reset ... | python3 -m pytest tqdm/tests/tests_tqdm.py::test_format_meter |
ansible | 1 | def verify_collections(collections, search_paths, apis, validate_certs, ignore_e
for search_path in search_paths:
b_search_path = to_bytes(os.path.join(search_path, namespace, name), errors='surrogate_or_strict')
if os.path.isdir(b_search_path):
... | def verify_collections(collections, search_paths, apis, validate_certs, ignore_e
for search_path in search_paths:
b_search_path = to_bytes(os.path.join(search_path, namespace, name), errors='surrogate_or_strict')
if os.path.isdir(b_search_path):
... | pytest test/units/galaxy/test_collection.py::test_verify_collections_no_version |
keras | 28 | class TimeseriesGenerator(Sequence):
self.reverse = reverse
self.batch_size = batch_size
def __len__(self):
return int(np.ceil(
(self.end_index - self.start_index) /
(self.batch_size * self.stride)))
def _empty_batch(self, num_rows): | class TimeseriesGenerator(Sequence):
self.reverse = reverse
self.batch_size = batch_size
if self.start_index > self.end_index:
raise ValueError('`start_index+length=%i > end_index=%i` '
'is disallowed, as no part of the sequence '
... | pytest tests/keras/preprocessing/sequence_test.py::test_TimeseriesGenerator |
keras | 28 | class TimeseriesGenerator(Sequence):
def __getitem__(self, index):
if self.shuffle:
rows = np.random.randint(
self.start_index, self.end_index, size=self.batch_size)
else:
i = self.start_index + self.batch_size * self.stride * index
rows = np.arang... | class TimeseriesGenerator(Sequence):
def __getitem__(self, index):
if self.shuffle:
rows = np.random.randint(
self.start_index, self.end_index + 1, size=self.batch_size)
else:
i = self.start_index + self.batch_size * self.stride * index
rows = np.a... | pytest tests/keras/preprocessing/sequence_test.py::test_TimeseriesGenerator |
youtube-dl | 31 | from ..compat import (
)
from ..utils import (
int_or_none,
parse_filesize,
)
| from ..compat import (
)
from ..utils import (
int_or_none,
parse_duration,
parse_filesize,
)
| python -m unittest -q test.test_utils.TestUtil.test_parse_duration |
youtube-dl | 31 | class MinhatecaIE(InfoExtractor):
filesize_approx = parse_filesize(self._html_search_regex(
r'<p class="fileSize">(.*?)</p>',
webpage, 'file size approximation', fatal=False))
duration = int_or_none(self._html_search_regex(
r'(?s)<p class="fileLeng[ht][th]">.*?([0-9]+... | class MinhatecaIE(InfoExtractor):
filesize_approx = parse_filesize(self._html_search_regex(
r'<p class="fileSize">(.*?)</p>',
webpage, 'file size approximation', fatal=False))
duration = parse_duration(self._html_search_regex(
r'(?s)<p class="fileLeng[ht][th]">.*?clas... | python -m unittest -q test.test_utils.TestUtil.test_parse_duration |
youtube-dl | 31 | def parse_duration(s):
m = re.match(
r'''(?ix)T?
(?:
(?:(?P<hours>[0-9]+)\s*(?:[:h]|hours?)\s*)?
(?P<mins>[0-9]+)\s*(?:[:m]|mins?|minutes?)\s*
)?
(?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*(?:s|secs?|seconds?)?$''', s)
if not m:
retur... | def parse_duration(s):
m = re.match(
r'''(?ix)T?
(?:
(?P<only_mins>[0-9.]+)\s*(?:mins?|minutes?)\s*|
(?P<only_hours>[0-9.]+)\s*(?:hours?)|
(?:
(?:(?P<hours>[0-9]+)\s*(?:[:h]|hours?)\s*)?
(?P<mins>[0-9]+)\s*(?:[:m]|mins?|minutes?)\... | python -m unittest -q test.test_utils.TestUtil.test_parse_duration |
ansible | 18 | class GalaxyCLI(CLI):
''' create an options parser for bin/ansible '''
super(GalaxyCLI, self).init_parser(
desc="Perform various Role related operations.",
)
# common | class GalaxyCLI(CLI):
''' create an options parser for bin/ansible '''
super(GalaxyCLI, self).init_parser(
desc="Perform various Role and Collection related operations.",
)
# common | pytest test/units/cli/test_galaxy.py::test_collection_default |
ansible | 18 | class GalaxyCLI(CLI):
obj_name = context.CLIARGS['{0}_name'.format(galaxy_type)]
inject_data = dict(
description='your description',
ansible_plugin_list_dir=get_versioned_doclink('plugins/plugins.html'),
)
if galaxy_type == 'role': | class GalaxyCLI(CLI):
obj_name = context.CLIARGS['{0}_name'.format(galaxy_type)]
inject_data = dict(
description='your {0} description'.format(galaxy_type),
ansible_plugin_list_dir=get_versioned_doclink('plugins/plugins.html'),
)
if galaxy_type == 'role': | pytest test/units/cli/test_galaxy.py::test_collection_default |
ansible | 18 | class GalaxyCLI(CLI):
if not os.path.exists(b_dir_path):
os.makedirs(b_dir_path)
display.display("- %s was created successfully" % obj_name)
def execute_info(self):
""" | class GalaxyCLI(CLI):
if not os.path.exists(b_dir_path):
os.makedirs(b_dir_path)
display.display("- %s %s was created successfully" % (galaxy_type.title(), obj_name))
def execute_info(self):
""" | pytest test/units/cli/test_galaxy.py::test_collection_default |
pandas | 40 | import copy
import datetime
from functools import partial
import string
from typing import TYPE_CHECKING, Optional, Tuple, Union
import warnings
import numpy as np
from pandas._libs import Timedelta, hashtable as libhashtable, lib
import pandas._libs.join as libjoin
from pandas._typing import FrameOrSeries
from panda... | import copy
import datetime
from functools import partial
import string
from typing import TYPE_CHECKING, Optional, Tuple, Union, cast
import warnings
import numpy as np
from pandas._libs import Timedelta, hashtable as libhashtable, lib
import pandas._libs.join as libjoin
from pandas._typing import ArrayLike, FrameOr... | pytest pandas/tests/reshape/merge/test_merge.py::TestMerge::test_merge_preserves_row_order |
pandas | 40 | from pandas.core.dtypes.common import (
is_array_like,
is_bool,
is_bool_dtype,
is_categorical_dtype,
is_datetime64tz_dtype,
is_dtype_equal, | from pandas.core.dtypes.common import (
is_array_like,
is_bool,
is_bool_dtype,
is_categorical,
is_categorical_dtype,
is_datetime64tz_dtype,
is_dtype_equal, | pytest pandas/tests/reshape/merge/test_merge.py::TestMerge::test_merge_preserves_row_order |
pandas | 40 | def _get_join_indexers(
# get left & right join labels and num. of levels at each location
mapped = (
_factorize_keys(left_keys[n], right_keys[n], sort=sort)
for n in range(len(left_keys))
)
zipped = zip(*mapped) | def _get_join_indexers(
# get left & right join labels and num. of levels at each location
mapped = (
_factorize_keys(left_keys[n], right_keys[n], sort=sort, how=how)
for n in range(len(left_keys))
)
zipped = zip(*mapped) | pytest pandas/tests/reshape/merge/test_merge.py::TestMerge::test_merge_preserves_row_order |
pandas | 40 | def _get_join_indexers(
# factorize keys to a dense i8 space
# `count` is the num. of unique keys
# set(lkey) | set(rkey) == range(count)
lkey, rkey, count = _factorize_keys(lkey, rkey, sort=sort)
# preserve left frame order if how == 'left' and sort == False
kwargs = copy.copy(kwargs)
if h... | def _get_join_indexers(
# factorize keys to a dense i8 space
# `count` is the num. of unique keys
# set(lkey) | set(rkey) == range(count)
lkey, rkey, count = _factorize_keys(lkey, rkey, sort=sort, how=how)
# preserve left frame order if how == 'left' and sort == False
kwargs = copy.copy(kwargs)... | pytest pandas/tests/reshape/merge/test_merge.py::TestMerge::test_merge_preserves_row_order |
pandas | 40 | def _right_outer_join(x, y, max_groups):
return left_indexer, right_indexer
def _factorize_keys(lk, rk, sort=True):
# Some pre-processing for non-ndarray lk / rk
lk = extract_array(lk, extract_numpy=True)
rk = extract_array(rk, extract_numpy=True) | def _right_outer_join(x, y, max_groups):
return left_indexer, right_indexer
def _factorize_keys(
lk: ArrayLike, rk: ArrayLike, sort: bool = True, how: str = "inner"
) -> Tuple[np.array, np.array, int]:
"""
Encode left and right keys as enumerated types.
This is used to get the join indexers to be... | pytest pandas/tests/reshape/merge/test_merge.py::TestMerge::test_merge_preserves_row_order |
pandas | 40 | def _factorize_keys(lk, rk, sort=True):
rk, _ = rk._values_for_factorize()
elif (
is_categorical_dtype(lk) and is_categorical_dtype(rk) and lk.is_dtype_equal(rk)
):
if lk.categories.equals(rk.categories):
# if we exactly match in categories, allow us to factorize on codes
... | def _factorize_keys(lk, rk, sort=True):
rk, _ = rk._values_for_factorize()
elif (
is_categorical_dtype(lk) and is_categorical_dtype(rk) and is_dtype_equal(lk, rk)
):
assert is_categorical(lk) and is_categorical(rk)
lk = cast(Categorical, lk)
rk = cast(Categorical, rk)
... | pytest pandas/tests/reshape/merge/test_merge.py::TestMerge::test_merge_preserves_row_order |
pandas | 40 | def _factorize_keys(lk, rk, sort=True):
np.putmask(rlab, rmask, count)
count += 1
return llab, rlab, count
| def _factorize_keys(lk, rk, sort=True):
np.putmask(rlab, rmask, count)
count += 1
if how == "right":
return rlab, llab, count
return llab, rlab, count
| pytest pandas/tests/reshape/merge/test_merge.py::TestMerge::test_merge_preserves_row_order |
thefuck | 26 | def match(command, settings):
def get_new_command(command, settings):
cmds = command.script.split(' ')
machine = ""
if len(cmds) >= 3:
machine = cmds[2]
return shells.and_("vagrant up " + machine, command.script) | def match(command, settings):
def get_new_command(command, settings):
cmds = command.script.split(' ')
machine = None
if len(cmds) >= 3:
machine = cmds[2]
startAllInstances = shells.and_("vagrant up", command.script)
if machine is None:
return startAllInstances
else:
r... | pytest tests/rules/test_vagrant_up.py::test_get_new_command |
youtube-dl | 7 | def js_to_json(code):
if v in ('true', 'false', 'null'):
return v
if v.startswith('"'):
return v
if v.startswith("'"):
v = v[1:-1]
v = re.sub(r"\\\\|\\'|\"", lambda m: {
'\\\\': '\\\\', | def js_to_json(code):
if v in ('true', 'false', 'null'):
return v
if v.startswith('"'):
v = re.sub(r"\\'", "'", v[1:-1])
elif v.startswith("'"):
v = v[1:-1]
v = re.sub(r"\\\\|\\'|\"", lambda m: {
'\\\\': '\\\\', | python -m unittest -q test.test_utils.TestUtil.test_js_to_json_realworld |
pandas | 5 | class Index(IndexOpsMixin, PandasObject):
multi_join_idx = multi_join_idx.remove_unused_levels()
return multi_join_idx, lidx, ridx
jl = list(overlap)[0]
| class Index(IndexOpsMixin, PandasObject):
multi_join_idx = multi_join_idx.remove_unused_levels()
if return_indexers:
return multi_join_idx, lidx, ridx
else:
return multi_join_idx
jl = list(overlap)[0]
| pytest pandas/tests/groupby/test_function.py::test_ops_not_as_index |
pandas | 5 | def test_join_multi_wrong_order():
midx1 = pd.MultiIndex.from_product([[1, 2], [3, 4]], names=["a", "b"])
midx2 = pd.MultiIndex.from_product([[1, 2], [3, 4]], names=["b", "a"])
join_idx, lidx, ridx = midx1.join(midx2, return_indexers=False)
exp_ridx = np.array([-1, -1, -1, -1], dtype=np.intp)
tm.... | def test_join_multi_wrong_order():
midx1 = pd.MultiIndex.from_product([[1, 2], [3, 4]], names=["a", "b"])
midx2 = pd.MultiIndex.from_product([[1, 2], [3, 4]], names=["b", "a"])
join_idx, lidx, ridx = midx1.join(midx2, return_indexers=True)
exp_ridx = np.array([-1, -1, -1, -1], dtype=np.intp)
tm.a... | pytest pandas/tests/groupby/test_function.py::test_ops_not_as_index |
keras | 1 | from tensorflow.python.ops import functional_ops
from tensorflow.python.ops import ctc_ops as ctc
from .common import floatx, epsilon, image_data_format
import functools
import threading
| from tensorflow.python.ops import functional_ops
from tensorflow.python.ops import ctc_ops as ctc
from .common import floatx, epsilon, image_data_format
import sys
import functools
import threading
| pytest tests/keras/initializers_test.py::test_statefulness |
keras | 1 | def update(x, new_x):
# Returns
The variable `x` updated.
"""
return tf_state_ops.assign(x, new_x)
@symbolic | def update(x, new_x):
# Returns
The variable `x` updated.
"""
op = tf_state_ops.assign(x, new_x)
with tf.control_dependencies([op]):
return tf.identity(x)
@symbolic | pytest tests/keras/initializers_test.py::test_statefulness |
keras | 1 | def update_add(x, increment):
# Returns
The variable `x` updated.
"""
return tf_state_ops.assign_add(x, increment)
@symbolic | def update_add(x, increment):
# Returns
The variable `x` updated.
"""
op = tf_state_ops.assign_add(x, increment)
with tf.control_dependencies([op]):
return tf.identity(x)
@symbolic | pytest tests/keras/initializers_test.py::test_statefulness |
keras | 1 | def update_sub(x, decrement):
# Returns
The variable `x` updated.
"""
return tf_state_ops.assign_sub(x, decrement)
@symbolic | def update_sub(x, decrement):
# Returns
The variable `x` updated.
"""
op = tf_state_ops.assign_sub(x, decrement)
with tf.control_dependencies([op]):
return tf.identity(x)
@symbolic | pytest tests/keras/initializers_test.py::test_statefulness |
keras | 1 | def get_variable_shape(x):
return int_shape(x)
def print_tensor(x, message=''):
"""Prints `message` and the tensor value when evaluated.
| def get_variable_shape(x):
return int_shape(x)
@symbolic
def print_tensor(x, message=''):
"""Prints `message` and the tensor value when evaluated.
| pytest tests/keras/initializers_test.py::test_statefulness |
keras | 1 | def print_tensor(x, message=''):
# Returns
The same tensor `x`, unchanged.
"""
# TODO
return tf.Print(x, [x], message)
# GRAPH MANIPULATION | def print_tensor(x, message=''):
# Returns
The same tensor `x`, unchanged.
"""
op = tf.print(message, x, output_stream=sys.stdout)
with tf.control_dependencies([op]):
return tf.identity(x)
# GRAPH MANIPULATION | pytest tests/keras/initializers_test.py::test_statefulness |
keras | 1 | def get_variable_shape(x):
def print_tensor(x, message=''):
"""Print the message and the tensor when evaluated and return the same
tensor.
"""
p_op = Print(message)
return p_op(x) | def get_variable_shape(x):
def print_tensor(x, message=''):
"""Print the message & the tensor when evaluated & return the same tensor.
"""
p_op = Print(message)
return p_op(x) | pytest tests/keras/initializers_test.py::test_statefulness |
keras | 1 | class RandomNormal(Initializer):
self.seed = seed
def __call__(self, shape, dtype=None):
return K.random_normal(shape, self.mean, self.stddev,
dtype=dtype, seed=self.seed)
def get_config(self):
return { | class RandomNormal(Initializer):
self.seed = seed
def __call__(self, shape, dtype=None):
x = K.random_normal(shape, self.mean, self.stddev,
dtype=dtype, seed=self.seed)
if self.seed is not None:
self.seed += 1
return x
def get_config(self... | pytest tests/keras/initializers_test.py::test_statefulness |
keras | 1 | class RandomUniform(Initializer):
self.seed = seed
def __call__(self, shape, dtype=None):
return K.random_uniform(shape, self.minval, self.maxval,
dtype=dtype, seed=self.seed)
def get_config(self):
return { | class RandomUniform(Initializer):
self.seed = seed
def __call__(self, shape, dtype=None):
x = K.random_uniform(shape, self.minval, self.maxval,
dtype=dtype, seed=self.seed)
if self.seed is not None:
self.seed += 1
return x
def get_config... | pytest tests/keras/initializers_test.py::test_statefulness |
keras | 1 | class TruncatedNormal(Initializer):
self.seed = seed
def __call__(self, shape, dtype=None):
return K.truncated_normal(shape, self.mean, self.stddev,
dtype=dtype, seed=self.seed)
def get_config(self):
return { | class TruncatedNormal(Initializer):
self.seed = seed
def __call__(self, shape, dtype=None):
x = K.truncated_normal(shape, self.mean, self.stddev,
dtype=dtype, seed=self.seed)
if self.seed is not None:
self.seed += 1
return x
def get_co... | pytest tests/keras/initializers_test.py::test_statefulness |
keras | 1 | class VarianceScaling(Initializer):
if self.distribution == 'normal':
# 0.879... = scipy.stats.truncnorm.std(a=-2, b=2, loc=0., scale=1.)
stddev = np.sqrt(scale) / .87962566103423978
return K.truncated_normal(shape, 0., stddev,
dtype=dtyp... | class VarianceScaling(Initializer):
if self.distribution == 'normal':
# 0.879... = scipy.stats.truncnorm.std(a=-2, b=2, loc=0., scale=1.)
stddev = np.sqrt(scale) / .87962566103423978
x = K.truncated_normal(shape, 0., stddev,
dtype=dtype, see... | pytest tests/keras/initializers_test.py::test_statefulness |
keras | 1 | class Orthogonal(Initializer):
rng = np.random
if self.seed is not None:
rng = np.random.RandomState(self.seed)
a = rng.normal(0.0, 1.0, flat_shape)
u, _, v = np.linalg.svd(a, full_matrices=False)
# Pick the one with the correct shape. | class Orthogonal(Initializer):
rng = np.random
if self.seed is not None:
rng = np.random.RandomState(self.seed)
self.seed += 1
a = rng.normal(0.0, 1.0, flat_shape)
u, _, v = np.linalg.svd(a, full_matrices=False)
# Pick the one with the correct shape. | pytest tests/keras/initializers_test.py::test_statefulness |
keras | 1 | class TestBackend(object):
else:
assert_list_pairwise(v_list, shape=False, allclose=False, itself=True)
def test_print_tensor(self):
check_single_tensor_operation('print_tensor', (), WITH_NP)
check_single_tensor_operation('print_tensor', (2,), WITH_NP)
check_single_tenso... | class TestBackend(object):
else:
assert_list_pairwise(v_list, shape=False, allclose=False, itself=True)
def test_print_tensor(self, capsys):
for k in [KTH, KTF]:
x = k.placeholder((1, 1))
y = k.print_tensor(x, 'msg')
fn = k.function([x], [y])
... | pytest tests/keras/initializers_test.py::test_statefulness |
keras | 1 | class TestBackend(object):
def test_log(self):
check_single_tensor_operation('log', (4, 2), WITH_NP)
@pytest.mark.skipif(K.backend() == 'theano',
reason='theano returns tuples for update ops')
def test_update_add(self):
x = np.random.randn(3, 4)
x_var = K.var... | class TestBackend(object):
def test_log(self):
check_single_tensor_operation('log', (4, 2), WITH_NP)
@pytest.mark.skipif(K.backend() == 'theano',
reason='theano returns tuples for update ops')
def test_update(self):
x = np.ones((3, 4))
x_var = K.variable(x)
... | pytest tests/keras/initializers_test.py::test_statefulness |
keras | 1 | class TestBackend(object):
assert output == [21.]
assert K.get_session().run(fetches=[x, y]) == [30., 40.]
@pytest.mark.skipif(K.backend() != 'tensorflow',
reason='Uses the `options` and `run_metadata` arguments.')
def test_function_tf_run_options_with_run_metadata(self)... | class TestBackend(object):
assert output == [21.]
assert K.get_session().run(fetches=[x, y]) == [30., 40.]
@pytest.mark.skipif(K.backend() != 'tensorflow' or not KTF._is_tf_1(),
reason='Uses the `options` and `run_metadata` arguments.')
def test_function_tf_run_options_w... | pytest tests/keras/initializers_test.py::test_statefulness |
keras | 1 | class TestBackend(object):
assert_allclose(y1, y2, atol=1e-05)
def test_random_normal(self):
# test standard normal as well as a normal with a different set of parameters
for mean, std in [(0., 1.), (-10., 5.)]:
rand = K.eval(K.random_normal((300, 200),
... | class TestBackend(object):
assert_allclose(y1, y2, atol=1e-05)
def test_random_normal(self):
# TODO: make this a parameterized test
for mean, std in [(0., 1.), (-10., 5.)]:
rand = K.eval(K.random_normal((200, 200),
mean=mean,
... | pytest tests/keras/initializers_test.py::test_statefulness |
keras | 1 | class TestBackend(object):
np.asarray([-5., -4., 0., 4., 9.],
dtype=np.float32))
@pytest.mark.skipif(K.backend() != 'tensorflow' or KTF._is_tf_1(),
reason='This test is for tensorflow parallelism.')
def test_tensorflow_ses... | class TestBackend(object):
np.asarray([-5., -4., 0., 4., 9.],
dtype=np.float32))
if __name__ == '__main__':
pytest.main([__file__]) | pytest tests/keras/initializers_test.py::test_statefulness |
luigi | 14 | class scheduler(Config):
# These disables last for disable_persist seconds.
disable_window = parameter.IntParameter(default=3600,
config_path=dict(section='scheduler', name='disable-window-seconds'))
disable_failures = parameter.IntParameter(default=None,
... | class scheduler(Config):
# These disables last for disable_persist seconds.
disable_window = parameter.IntParameter(default=3600,
config_path=dict(section='scheduler', name='disable-window-seconds'))
disable_failures = parameter.IntParameter(default=999999999,
... | pytest test/central_planner_test.py::CentralPlannerTest::test_no_crash_on_only_disable_hard_timeout |
luigi | 14 | class Task(object):
self.failures.add_failure()
def has_excessive_failures(self):
if (self.failures.first_failure_time is not None and
self.disable_hard_timeout):
if (time.time() >= self.failures.first_failure_time +
self.disable_hard_timeout):
... | class Task(object):
self.failures.add_failure()
def has_excessive_failures(self):
if self.failures.first_failure_time is not None:
if (time.time() >= self.failures.first_failure_time +
self.disable_hard_timeout):
return True | pytest test/central_planner_test.py::CentralPlannerTest::test_no_crash_on_only_disable_hard_timeout |
luigi | 14 | class Task(object):
return False
def can_disable(self):
return (self.disable_failures is not None or
self.disable_hard_timeout is not None)
@property
def pretty_id(self):
param_str = ', '.join('{}={}'.format(key, value) for key, value in self.params.items()) | class Task(object):
return False
@property
def pretty_id(self):
param_str = ', '.join('{}={}'.format(key, value) for key, value in self.params.items()) | pytest test/central_planner_test.py::CentralPlannerTest::test_no_crash_on_only_disable_hard_timeout |
luigi | 14 | class SimpleTaskState(object):
elif task.scheduler_disable_time is not None and new_status != DISABLED:
return
if new_status == FAILED and task.can_disable() and task.status != DISABLED:
task.add_failure()
if task.has_excessive_failures():
tas... | class SimpleTaskState(object):
elif task.scheduler_disable_time is not None and new_status != DISABLED:
return
if new_status == FAILED and task.status != DISABLED:
task.add_failure()
if task.has_excessive_failures():
task.scheduler_disable_tim... | pytest test/central_planner_test.py::CentralPlannerTest::test_no_crash_on_only_disable_hard_timeout |
matplotlib | 27 | class ColorbarBase(_ColorbarMappableDummy):
def set_label(self, label, **kw):
"""Label the long axis of the colorbar."""
self._label = str(label)
self._labelkw = kw
self._set_label()
| class ColorbarBase(_ColorbarMappableDummy):
def set_label(self, label, **kw):
"""Label the long axis of the colorbar."""
self._label = label
self._labelkw = kw
self._set_label()
| pytest lib/matplotlib/tests/test_colorbar.py::test_colorbar_label |
pandas | 152 | class Series(base.IndexOpsMixin, generic.NDFrame):
from pandas.core.reshape.concat import concat
if isinstance(to_append, (list, tuple)):
to_concat = [self] + to_append
else:
to_concat = [self, to_append]
return concat( | class Series(base.IndexOpsMixin, generic.NDFrame):
from pandas.core.reshape.concat import concat
if isinstance(to_append, (list, tuple)):
to_concat = [self]
to_concat.extend(to_append)
else:
to_concat = [self, to_append]
return concat( | pytest pandas/tests/series/test_combine_concat.py::TestSeriesCombine::test_append_tuples |
tornado | 2 | class HTTP1Connection(httputil.HTTPConnection):
self._chunking_output = (
start_line.method in ("POST", "PUT", "PATCH")
and "Content-Length" not in headers
and "Transfer-Encoding" not in headers
)
else:
assert isinstance(start_l... | class HTTP1Connection(httputil.HTTPConnection):
self._chunking_output = (
start_line.method in ("POST", "PUT", "PATCH")
and "Content-Length" not in headers
and (
"Transfer-Encoding" not in headers
or headers["Transfer-En... | python -m unittest -q tornado.test.httpclient_test.HTTPClientCommonTestCase.test_redirect_put_without_body |
youtube-dl | 10 | def js_to_json(code):
return '"%s"' % v
res = re.sub(r'''(?x)
"(?:[^"\\]*(?:\\\\|\\")?)*"|
'(?:[^'\\]*(?:\\\\|\\')?)*'|
[a-zA-Z_][.a-zA-Z_0-9]*
''', fix_kv, code)
res = re.sub(r',(\s*\])', lambda m: m.group(1), res) | def js_to_json(code):
return '"%s"' % v
res = re.sub(r'''(?x)
"(?:[^"\\]*(?:\\\\|\\['"nu]))*[^"\\]*"|
'(?:[^'\\]*(?:\\\\|\\['"nu]))*[^'\\]*'|
[a-zA-Z_][.a-zA-Z_0-9]*
''', fix_kv, code)
res = re.sub(r',(\s*\])', lambda m: m.group(1), res) | python -m unittest -q test.test_utils.TestUtil.test_js_to_json_realworld |
pandas | 61 | class Series(base.IndexOpsMixin, generic.NDFrame):
indexer = self.index.get_indexer_for(key)
return self.iloc[indexer]
else:
return self._get_values(key)
if isinstance(key, (list, tuple)):
# TODO: de-dup with tuple case handled above? | class Series(base.IndexOpsMixin, generic.NDFrame):
indexer = self.index.get_indexer_for(key)
return self.iloc[indexer]
else:
return self.iloc[key]
if isinstance(key, (list, tuple)):
# TODO: de-dup with tuple case handled above? | pytest pandas/tests/indexing/test_indexing.py::TestFancy::test_getitem_ndarray_3d |
luigi | 18 | class SimpleTaskState(object):
self.re_enable(task)
# don't allow workers to override a scheduler disable
elif task.scheduler_disable_time is not None:
return
if new_status == FAILED and task.can_disable() and task.status != DISABLED: | class SimpleTaskState(object):
self.re_enable(task)
# don't allow workers to override a scheduler disable
elif task.scheduler_disable_time is not None and new_status != DISABLED:
return
if new_status == FAILED and task.can_disable() and task.status != DI... | pytest test/central_planner_test.py::CentralPlannerTest::test_no_automatic_re_enable_after_auto_then_manual_disable |
black | 16 | def gen_python_files_in_dir(
"""Generate all files under `path` whose paths are not excluded by the
`exclude` regex, but are included by the `include` regex.
`report` is where output about exclusions goes.
"""
assert root.is_absolute(), f"INTERNAL ERROR: `root` must be absolute but is {root}"
f... | def gen_python_files_in_dir(
"""Generate all files under `path` whose paths are not excluded by the
`exclude` regex, but are included by the `include` regex.
Symbolic links pointing outside of the root directory are ignored.
`report` is where output about exclusions goes.
"""
assert root.is_ab... | python -m unittest -q tests.test_black.BlackTestCase.test_symlink_out_of_root_directory |
pandas | 131 | from pandas.core.dtypes.common import (
from pandas.core.dtypes.generic import ABCSeries
from pandas.core.accessor import PandasDelegate, delegate_names
from pandas.core.algorithms import take_1d
from pandas.core.arrays import DatetimeArray, PeriodArray, TimedeltaArray
from pandas.core.base import NoNewAttributesMixin... | from pandas.core.dtypes.common import (
from pandas.core.dtypes.generic import ABCSeries
from pandas.core.accessor import PandasDelegate, delegate_names
from pandas.core.arrays import DatetimeArray, PeriodArray, TimedeltaArray
from pandas.core.base import NoNewAttributesMixin, PandasObject
from pandas.core.indexes.dat... | pytest pandas/tests/series/test_datetime_values.py::TestSeriesDatetimeValues::test_dt_tz_convert_categorical |
pandas | 131 | class Properties(PandasDelegate, PandasObject, NoNewAttributesMixin):
result = np.asarray(result)
# blow up if we operate on categories
if self.orig is not None:
result = take_1d(result, self.orig.cat.codes)
index = self.orig.index
else:
index = self... | class Properties(PandasDelegate, PandasObject, NoNewAttributesMixin):
result = np.asarray(result)
if self.orig is not None:
index = self.orig.index
else:
index = self._parent.index | pytest pandas/tests/series/test_datetime_values.py::TestSeriesDatetimeValues::test_dt_tz_convert_categorical |
pandas | 131 | class CombinedDatetimelikeProperties(
orig = data if is_categorical_dtype(data) else None
if orig is not None:
data = Series(orig.values.categories, name=orig.name, copy=False)
if is_datetime64_dtype(data.dtype):
return DatetimeProperties(data, orig) | class CombinedDatetimelikeProperties(
orig = data if is_categorical_dtype(data) else None
if orig is not None:
data = Series(
orig.array,
name=orig.name,
copy=False,
dtype=orig.values.categories.dtype,
)
if... | pytest pandas/tests/series/test_datetime_values.py::TestSeriesDatetimeValues::test_dt_tz_convert_categorical |
pandas | 90 | import os
from shutil import rmtree
import string
import tempfile
from typing import List, Optional, Union, cast
import warnings
import zipfile
| import os
from shutil import rmtree
import string
import tempfile
from typing import Any, List, Optional, Union, cast
import warnings
import zipfile
| pytest pandas/tests/io/test_pickle.py::test_pickle_generalurl_read |
pandas | 90 | from pandas._config.localization import ( # noqa:F401
)
import pandas._libs.testing as _testing
from pandas._typing import FrameOrSeries
from pandas.compat import _get_lzma_file, _import_lzma
from pandas.core.dtypes.common import ( | from pandas._config.localization import ( # noqa:F401
)
import pandas._libs.testing as _testing
from pandas._typing import FilePathOrBuffer, FrameOrSeries
from pandas.compat import _get_lzma_file, _import_lzma
from pandas.core.dtypes.common import ( | pytest pandas/tests/io/test_pickle.py::test_pickle_generalurl_read |
pandas | 90 | def reset_display_options():
pd.reset_option("^display.", silent=True)
def round_trip_pickle(obj: FrameOrSeries, path: Optional[str] = None) -> FrameOrSeries:
"""
Pickle an object and then read it again.
Parameters
----------
obj : pandas object
The object to pickle and then re-read.
... | def reset_display_options():
pd.reset_option("^display.", silent=True)
def round_trip_pickle(
obj: Any, path: Optional[FilePathOrBuffer] = None
) -> FrameOrSeries:
"""
Pickle an object and then read it again.
Parameters
----------
obj : any object
The object to pickle and then re-... | pytest pandas/tests/io/test_pickle.py::test_pickle_generalurl_read |
pandas | 90 | def round_trip_pickle(obj: FrameOrSeries, path: Optional[str] = None) -> FrameOr
pandas object
The original object that was pickled and then re-read.
"""
if path is None:
path = f"__{rands(10)}__.pickle"
with ensure_clean(path) as path:
pd.to_pickle(obj, path)
return pd.r... | def round_trip_pickle(obj: FrameOrSeries, path: Optional[str] = None) -> FrameOr
pandas object
The original object that was pickled and then re-read.
"""
_path = path
if _path is None:
_path = f"__{rands(10)}__.pickle"
with ensure_clean(_path) as path:
pd.to_pickle(obj, _path... | pytest pandas/tests/io/test_pickle.py::test_pickle_generalurl_read |
pandas | 90 | """ pickle compat """
import pickle
import warnings
from pandas.compat import pickle_compat as pc
from pandas.io.common import get_handle, stringify_path
def to_pickle(obj, path, compression="infer", protocol=pickle.HIGHEST_PROTOCOL):
"""
Pickle (serialize) object to file.
| """ pickle compat """
import pickle
from typing import Any, Optional
import warnings
from pandas._typing import FilePathOrBuffer
from pandas.compat import pickle_compat as pc
from pandas.io.common import get_filepath_or_buffer, get_handle
def to_pickle(
obj: Any,
filepath_or_buffer: FilePathOrBuffer,
co... | pytest pandas/tests/io/test_pickle.py::test_pickle_generalurl_read |
pandas | 90 | def to_pickle(obj, path, compression="infer", protocol=pickle.HIGHEST_PROTOCOL):
----------
obj : any object
Any python object.
path : str
File path where the pickled object will be stored.
compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default 'infer'
A string repres... | def to_pickle(obj, path, compression="infer", protocol=pickle.HIGHEST_PROTOCOL):
----------
obj : any object
Any python object.
filepath_or_buffer : str, path object or file-like object
File path, URL, or buffer where the pickled object will be stored.
.. versionchanged:: 1.0.0
... | pytest pandas/tests/io/test_pickle.py::test_pickle_generalurl_read |
pandas | 90 | def to_pickle(obj, path, compression="infer", protocol=pickle.HIGHEST_PROTOCOL):
>>> import os
>>> os.remove("./dummy.pkl")
"""
path = stringify_path(path)
f, fh = get_handle(path, "wb", compression=compression, is_text=False)
if protocol < 0:
protocol = pickle.HIGHEST_PROTOCOL
try: | def to_pickle(obj, path, compression="infer", protocol=pickle.HIGHEST_PROTOCOL):
>>> import os
>>> os.remove("./dummy.pkl")
"""
fp_or_buf, _, compression, should_close = get_filepath_or_buffer(
filepath_or_buffer, compression=compression, mode="wb"
)
if not isinstance(fp_or_buf, str) and... | pytest pandas/tests/io/test_pickle.py::test_pickle_generalurl_read |
pandas | 90 | def to_pickle(obj, path, compression="infer", protocol=pickle.HIGHEST_PROTOCOL):
f.close()
for _f in fh:
_f.close()
def read_pickle(path, compression="infer"):
"""
Load pickled pandas object (or any object) from file.
| def to_pickle(obj, path, compression="infer", protocol=pickle.HIGHEST_PROTOCOL):
f.close()
for _f in fh:
_f.close()
if should_close:
try:
fp_or_buf.close()
except ValueError:
pass
def read_pickle(
filepath_or_buffer: FileP... | pytest pandas/tests/io/test_pickle.py::test_pickle_generalurl_read |
pandas | 90 | def read_pickle(path, compression="infer"):
Parameters
----------
path : str
File path where the pickled object will be loaded.
compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default 'infer'
For on-the-fly decompression of on-disk data. If 'infer', then use
gzip, bz2... | def read_pickle(path, compression="infer"):
Parameters
----------
filepath_or_buffer : str, path object or file-like object
File path, URL, or buffer where the pickled object will be loaded from.
.. versionchanged:: 1.0.0
Accept URL. URL is not limited to S3 and GCS.
compre... | pytest pandas/tests/io/test_pickle.py::test_pickle_generalurl_read |
pandas | 90 | def read_pickle(path, compression="infer"):
>>> import os
>>> os.remove("./dummy.pkl")
"""
path = stringify_path(path)
f, fh = get_handle(path, "rb", compression=compression, is_text=False)
# 1) try standard library Pickle
# 2) try pickle_compat (older pandas version) to handle subclass cha... | def read_pickle(path, compression="infer"):
>>> import os
>>> os.remove("./dummy.pkl")
"""
fp_or_buf, _, compression, should_close = get_filepath_or_buffer(
filepath_or_buffer, compression=compression
)
if not isinstance(fp_or_buf, str) and compression == "infer":
compression = N... | pytest pandas/tests/io/test_pickle.py::test_pickle_generalurl_read |
pandas | 90 | def read_pickle(path, compression="infer"):
f.close()
for _f in fh:
_f.close() | def read_pickle(path, compression="infer"):
f.close()
for _f in fh:
_f.close()
if should_close:
try:
fp_or_buf.close()
except ValueError:
pass | pytest pandas/tests/io/test_pickle.py::test_pickle_generalurl_read |
tornado | 10 | class RequestHandler(object):
self._log()
self._finished = True
self.on_finish()
# Break up a reference cycle between this handler and the
# _ui_module closures to allow for faster GC on CPython.
self.ui = None | class RequestHandler(object):
self._log()
self._finished = True
self.on_finish()
self._break_cycles()
def _break_cycles(self):
# Break up a reference cycle between this handler and the
# _ui_module closures to allow for faster GC on CPython.
self.ui = None | python -m unittest -q tornado.test.websocket_test.WebSocketTest.test_render_message |
tornado | 10 | class WebSocketHandler(tornado.web.RequestHandler):
if not self._on_close_called:
self._on_close_called = True
self.on_close()
def send_error(self, *args, **kwargs):
if self.stream is None: | class WebSocketHandler(tornado.web.RequestHandler):
if not self._on_close_called:
self._on_close_called = True
self.on_close()
self._break_cycles()
def _break_cycles(self):
# WebSocketHandlers call finish() early, but we don't want to
# break up reference... | python -m unittest -q tornado.test.websocket_test.WebSocketTest.test_render_message |
pandas | 9 | from pandas.core.dtypes.common import (
from pandas.core.dtypes.dtypes import CategoricalDtype
from pandas.core.dtypes.generic import ABCIndexClass, ABCSeries
from pandas.core.dtypes.inference import is_hashable
from pandas.core.dtypes.missing import isna, notna
from pandas.core import ops
from pandas.core.accessor im... | from pandas.core.dtypes.common import (
from pandas.core.dtypes.dtypes import CategoricalDtype
from pandas.core.dtypes.generic import ABCIndexClass, ABCSeries
from pandas.core.dtypes.inference import is_hashable
from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna, notna
from pandas.core import ops
from... | pytest pandas/tests/indexes/categorical/test_indexing.py::TestContains::test_contains_na_dtype |
pandas | 9 | class Categorical(NDArrayBackedExtensionArray, PandasObject):
Returns True if `key` is in this Categorical.
"""
# if key is a NaN, check if any NaN is in self.
if is_scalar(key) and isna(key):
return self.isna().any()
return contains(self, key, container=self._codes) | class Categorical(NDArrayBackedExtensionArray, PandasObject):
Returns True if `key` is in this Categorical.
"""
# if key is a NaN, check if any NaN is in self.
if is_valid_nat_for_dtype(key, self.categories.dtype):
return self.isna().any()
return contains(self, key, ... | pytest pandas/tests/indexes/categorical/test_indexing.py::TestContains::test_contains_na_dtype |
pandas | 9 | from pandas.core.dtypes.common import (
is_scalar,
)
from pandas.core.dtypes.dtypes import CategoricalDtype
from pandas.core.dtypes.missing import isna
from pandas.core import accessor
from pandas.core.algorithms import take_1d | from pandas.core.dtypes.common import (
is_scalar,
)
from pandas.core.dtypes.dtypes import CategoricalDtype
from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna
from pandas.core import accessor
from pandas.core.algorithms import take_1d | pytest pandas/tests/indexes/categorical/test_indexing.py::TestContains::test_contains_na_dtype |
pandas | 9 | class CategoricalIndex(ExtensionIndex, accessor.PandasDelegate):
@doc(Index.__contains__)
def __contains__(self, key: Any) -> bool:
# if key is a NaN, check if any NaN is in self.
if is_scalar(key) and isna(key):
return self.hasnans
hash(key)
return contains(self, ke... | class CategoricalIndex(ExtensionIndex, accessor.PandasDelegate):
@doc(Index.__contains__)
def __contains__(self, key: Any) -> bool:
# if key is a NaN, check if any NaN is in self.
if is_valid_nat_for_dtype(key, self.categories.dtype):
return self.hasnans
return contains(self... | pytest pandas/tests/indexes/categorical/test_indexing.py::TestContains::test_contains_na_dtype |
scrapy | 36 | def create_instance(objcls, settings, crawler, *args, **kwargs):
``*args`` and ``**kwargs`` are forwarded to the constructors.
Raises ``ValueError`` if both ``settings`` and ``crawler`` are ``None``.
"""
if settings is None:
if crawler is None:
raise ValueError("Specify at least one... | def create_instance(objcls, settings, crawler, *args, **kwargs):
``*args`` and ``**kwargs`` are forwarded to the constructors.
Raises ``ValueError`` if both ``settings`` and ``crawler`` are ``None``.
Raises ``TypeError`` if the resulting instance is ``None`` (e.g. if an
extension has not been implemen... | python -m unittest -q tests.test_utils_misc.__init__.UtilsMiscTestCase.test_create_instance |
pandas | 110 | class Index(IndexOpsMixin, PandasObject):
is_null_slicer = start is None and stop is None
is_index_slice = is_int(start) and is_int(stop)
is_positional = is_index_slice and not self.is_integer()
if kind == "getitem":
""" | class Index(IndexOpsMixin, PandasObject):
is_null_slicer = start is None and stop is None
is_index_slice = is_int(start) and is_int(stop)
is_positional = is_index_slice and not (
self.is_integer() or self.is_categorical()
)
if kind == "getitem":
""" | pytest pandas/tests/indexing/test_categorical.py::TestCategoricalIndex::test_loc_slice |
pandas | 110 | class CategoricalIndex(Index, accessor.PandasDelegate):
take_nd = take
def map(self, mapper):
"""
Map values using input correspondence (a dict, Series, or function). | class CategoricalIndex(Index, accessor.PandasDelegate):
take_nd = take
@Appender(_index_shared_docs["_maybe_cast_slice_bound"])
def _maybe_cast_slice_bound(self, label, side, kind):
if kind == "loc":
return label
return super()._maybe_cast_slice_bound(label, side, kind)
d... | pytest pandas/tests/indexing/test_categorical.py::TestCategoricalIndex::test_loc_slice |
scrapy | 2 | class LocalCache(collections.OrderedDict):
self.limit = limit
def __setitem__(self, key, value):
while len(self) >= self.limit:
self.popitem(last=False)
super(LocalCache, self).__setitem__(key, value)
| class LocalCache(collections.OrderedDict):
self.limit = limit
def __setitem__(self, key, value):
if self.limit:
while len(self) >= self.limit:
self.popitem(last=False)
super(LocalCache, self).__setitem__(key, value)
| python -m unittest -q tests.test_utils_datatypes.LocalCacheTest.test_cache_without_limit |
ansible | 14 | from ansible.module_utils.urls import open_url
from ansible.utils.display import Display
from ansible.utils.hashing import secure_hash_s
display = Display()
| from ansible.module_utils.urls import open_url
from ansible.utils.display import Display
from ansible.utils.hashing import secure_hash_s
try:
from urllib.parse import urlparse
except ImportError:
# Python 2
from urlparse import urlparse
display = Display()
| pytest test/units/galaxy/test_api.py::test_get_role_versions_pagination |
ansible | 14 | class GalaxyAPI:
data = self._call_galaxy(url)
results = data['results']
done = (data.get('next_link', None) is None)
while not done:
url = _urljoin(self.api_server, data['next_link'])
data = self._call_galaxy(url)
results +... | class GalaxyAPI:
data = self._call_galaxy(url)
results = data['results']
done = (data.get('next_link', None) is None)
# https://github.com/ansible/ansible/issues/64355
# api_server contains part of the API path but next_link includes the the /api part so stri... | pytest test/units/galaxy/test_api.py::test_get_role_versions_pagination |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.