project stringclasses 17
values | bug_id int64 1 169 | buggy stringlengths 81 57.2k | fixed stringlengths 85 31.2k | test_command stringlengths 44 133 |
|---|---|---|---|---|
pandas | 155 | class Rolling(_Rolling_and_Expanding):
def _on(self):
if self.on is None:
return self.obj.index
elif isinstance(self.obj, ABCDataFrame) and self.on in self.obj.columns:
return Index(self.obj[self.on])
else: | class Rolling(_Rolling_and_Expanding):
def _on(self):
if self.on is None:
if self.axis == 0:
return self.obj.index
elif self.axis == 1:
return self.obj.columns
elif isinstance(self.obj, ABCDataFrame) and self.on in self.obj.columns:
... | pytest pandas/tests/window/test_rolling.py::TestRolling::test_rolling_datetime |
luigi | 13 | class LocalFileSystem(FileSystem):
raise RuntimeError('Destination exists: %s' % new_path)
d = os.path.dirname(new_path)
if d and not os.path.exists(d):
self.fs.mkdir(d)
os.rename(old_path, new_path)
| class LocalFileSystem(FileSystem):
raise RuntimeError('Destination exists: %s' % new_path)
d = os.path.dirname(new_path)
if d and not os.path.exists(d):
self.mkdir(d)
os.rename(old_path, new_path)
| pytest test/file_test.py::FileSystemTest::test_move_to_new_dir |
cookiecutter | 1 | def generate_context(
context = OrderedDict([])
try:
with open(context_file) as file_handle:
obj = json.load(file_handle, object_pairs_hook=OrderedDict)
except ValueError as e:
# JSON decoding error. Let's throw a new exception that is more | def generate_context(
context = OrderedDict([])
try:
with open(context_file, encoding='utf-8') as file_handle:
obj = json.load(file_handle, object_pairs_hook=OrderedDict)
except ValueError as e:
# JSON decoding error. Let's throw a new exception that is more | tox tests/test_generate_context.py::test_generate_context_decodes_non_ascii_chars |
pandas | 66 | class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin):
new_index = self.index[loc]
if is_scalar(loc):
new_values = self._data.fast_xs(loc)
# may need to box a datelike-scalar
#
# if we encounter an array-like and we only have 1 dim
... | class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin):
new_index = self.index[loc]
if is_scalar(loc):
# In this case loc should be an integer
if self.ndim == 1:
# if we encounter an array-like and we only have 1 dim
# that me... | pytest pandas/tests/series/indexing/test_xs.py::test_xs_datetimelike_wrapping |
pandas | 66 | class SingleBlockManager(BlockManager):
fast path for getting a cross-section
return a view of the data
"""
return self._block.values[loc]
def concat(self, to_concat, new_axis) -> "SingleBlockManager":
""" | class SingleBlockManager(BlockManager):
fast path for getting a cross-section
return a view of the data
"""
raise NotImplementedError("Use series._values[loc] instead")
def concat(self, to_concat, new_axis) -> "SingleBlockManager":
""" | pytest pandas/tests/series/indexing/test_xs.py::test_xs_datetimelike_wrapping |
tornado | 5 | class PeriodicCallback(object):
self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run)
def _update_next(self, current_time):
if self._next_timeout <= current_time:
callback_time_sec = self.callback_time / 1000.0
self._next_timeout += (math.floor((current... | class PeriodicCallback(object):
self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run)
def _update_next(self, current_time):
callback_time_sec = self.callback_time / 1000.0
if self._next_timeout <= current_time:
# The period should be measured from the start... | python -m unittest -q tornado.test.ioloop_test.TestPeriodicCallbackMath.test_clock_backwards |
youtube-dl | 17 | def cli_option(params, command_option, param):
def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None):
param = params.get(param)
assert isinstance(param, bool)
if separator:
return [command_option + separator + (true_value if param else false_valu... | def cli_option(params, command_option, param):
def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None):
param = params.get(param)
if param is None:
return []
assert isinstance(param, bool)
if separator:
return [command_option + separato... | python -m unittest -q test.test_utils.TestUtil.test_cli_bool_option |
tqdm | 5 | class tqdm(Comparable):
if disable is None and hasattr(file, "isatty") and not file.isatty():
disable = True
if disable:
self.iterable = iterable
self.disable = disable
self.pos = self._get_free_pos(self)
self._instances.remove(self)
... | class tqdm(Comparable):
if disable is None and hasattr(file, "isatty") and not file.isatty():
disable = True
if total is None and iterable is not None:
try:
total = len(iterable)
except (TypeError, AttributeError):
total = None
... | python3 -m pytest tqdm/tests/tests_tqdm.py::test_bool |
tqdm | 5 | class tqdm(Comparable):
else TqdmKeyError("Unknown argument(s): " + str(kwargs)))
# Preprocess the arguments
if total is None and iterable is not None:
try:
total = len(iterable)
except (TypeError, AttributeError):
total = None
... | class tqdm(Comparable):
else TqdmKeyError("Unknown argument(s): " + str(kwargs)))
# Preprocess the arguments
if ((ncols is None) and (file in (sys.stderr, sys.stdout))) or \
dynamic_ncols: # pragma: no cover
if dynamic_ncols: | python3 -m pytest tqdm/tests/tests_tqdm.py::test_bool |
keras | 40 | class RNN(Layer):
input_shape = input_shape[0]
if hasattr(self.cell.state_size, '__len__'):
output_dim = self.cell.state_size[0]
else:
output_dim = self.cell.state_size
if self.return_sequences:
output_shape = (input_shape[0], input_shape[1], out... | class RNN(Layer):
input_shape = input_shape[0]
if hasattr(self.cell.state_size, '__len__'):
state_size = self.cell.state_size
else:
state_size = [self.cell.state_size]
output_dim = state_size[0]
if self.return_sequences:
output_shape = (i... | pytest tests/keras/layers/recurrent_test.py::test_stacked_rnn_compute_output_shape |
keras | 40 | class RNN(Layer):
output_shape = (input_shape[0], output_dim)
if self.return_state:
state_shape = [(input_shape[0], output_dim) for _ in self.states]
return [output_shape] + state_shape
else:
return output_shape | class RNN(Layer):
output_shape = (input_shape[0], output_dim)
if self.return_state:
state_shape = [(input_shape[0], dim) for dim in state_size]
return [output_shape] + state_shape
else:
return output_shape | pytest tests/keras/layers/recurrent_test.py::test_stacked_rnn_compute_output_shape |
luigi | 9 | def _partition_tasks(worker):
set_tasks["completed"] = {task for (task, status, ext) in task_history if status == 'DONE' and task in pending_tasks}
set_tasks["already_done"] = {task for (task, status, ext) in task_history
if status == 'DONE' and task not in pending_tasks and tas... | def _partition_tasks(worker):
set_tasks["completed"] = {task for (task, status, ext) in task_history if status == 'DONE' and task in pending_tasks}
set_tasks["already_done"] = {task for (task, status, ext) in task_history
if status == 'DONE' and task not in pending_tasks and tas... | pytest test/execution_summary_test.py::ExecutionSummaryTest::test_status_with_task_retry |
luigi | 9 | def _depth_first_search(set_tasks, current_task, visited):
for task in current_task._requires():
if task not in visited:
_depth_first_search(set_tasks, task, visited)
if task in set_tasks["failed"] or task in set_tasks["upstream_failure"]:
set_tasks["upstr... | def _depth_first_search(set_tasks, current_task, visited):
for task in current_task._requires():
if task not in visited:
_depth_first_search(set_tasks, task, visited)
if task in set_tasks["ever_failed"] or task in set_tasks["upstream_failure"]:
set_tasks["... | pytest test/execution_summary_test.py::ExecutionSummaryTest::test_status_with_task_retry |
luigi | 9 | def _get_comments(group_tasks):
_ORDERED_STATUSES = (
"already_done",
"completed",
"failed",
"scheduling_error",
"still_pending", | def _get_comments(group_tasks):
_ORDERED_STATUSES = (
"already_done",
"completed",
"ever_failed",
"failed",
"scheduling_error",
"still_pending", | pytest test/execution_summary_test.py::ExecutionSummaryTest::test_status_with_task_retry |
luigi | 9 | def _summary_format(set_tasks, worker):
str_output += 'Did not run any tasks'
smiley = ""
reason = ""
if set_tasks["failed"]:
smiley = ":("
reason = "there were failed tasks"
if set_tasks["scheduling_error"]:
reason += " and tasks whose scheduling failed"
elif... | def _summary_format(set_tasks, worker):
str_output += 'Did not run any tasks'
smiley = ""
reason = ""
if set_tasks["ever_failed"]:
if not set_tasks["failed"]:
smiley = ":)"
reason = "there were failed tasks but they all suceeded in a retry"
else:
s... | pytest test/execution_summary_test.py::ExecutionSummaryTest::test_status_with_task_retry |
luigi | 9 | class RetcodesTest(LuigiTestCase):
with mock.patch('luigi.scheduler.Scheduler.add_task', new_func):
self.run_and_expect('RequiringTask', 0)
self.run_and_expect('RequiringTask --retcode-not-run 5', 5) | class RetcodesTest(LuigiTestCase):
with mock.patch('luigi.scheduler.Scheduler.add_task', new_func):
self.run_and_expect('RequiringTask', 0)
self.run_and_expect('RequiringTask --retcode-not-run 5', 5)
"""
Test that a task once crashing and then succeeding should be counted as no ... | pytest test/execution_summary_test.py::ExecutionSummaryTest::test_status_with_task_retry |
spacy | 8 | class Errors(object):
"details: https://spacy.io/api/lemmatizer#init")
E174 = ("Architecture '{name}' not found in registry. Available "
"names: {names}")
@add_codes | class Errors(object):
"details: https://spacy.io/api/lemmatizer#init")
E174 = ("Architecture '{name}' not found in registry. Available "
"names: {names}")
E175 = ("Can't remove rule for unknown match pattern ID: {key}")
@add_codes | py.test spacy/tests/matcher/test_matcher_logic.py::test_matcher_remove |
ansible | 6 | class CollectionRequirement:
requirement = req
op = operator.eq
# In the case we are checking a new requirement on a base requirement (parent != None) we can't accept
# version as '*' (unknown version) unless the requirement is also '*'.
i... | class CollectionRequirement:
requirement = req
op = operator.eq
# In the case we are checking a new requirement on a base requirement (parent != None) we can't accept
# version as '*' (unknown version) unless the requirement is also '*'.
if parent and... | pytest test/units/galaxy/test_collection_install.py::test_add_collection_requirement_to_unknown_installed_version |
ansible | 6 | class CollectionRequirement:
manifest = info['manifest_file']['collection_info']
namespace = manifest['namespace']
name = manifest['name']
version = manifest['version']
dependencies = manifest['dependencies']
else:
display.warning("Collecti... | class CollectionRequirement:
manifest = info['manifest_file']['collection_info']
namespace = manifest['namespace']
name = manifest['name']
version = to_text(manifest['version'], errors='surrogate_or_strict')
if not hasattr(LooseVersion(version), 'version'):
... | pytest test/units/galaxy/test_collection_install.py::test_add_collection_requirement_to_unknown_installed_version |
ansible | 6 | def _get_collection_info(dep_map, existing_collections, collection, requirement,
existing = [c for c in existing_collections if to_text(c) == to_text(collection_info)]
if existing and not collection_info.force:
# Test that the installed collection fits the requirement
existing[0].add_requirement... | def _get_collection_info(dep_map, existing_collections, collection, requirement,
existing = [c for c in existing_collections if to_text(c) == to_text(collection_info)]
if existing and not collection_info.force:
# Test that the installed collection fits the requirement
existing[0].add_requirement... | pytest test/units/galaxy/test_collection_install.py::test_add_collection_requirement_to_unknown_installed_version |
scrapy | 9 | else:
from twisted.internet import defer, reactor, ssl
logger = logging.getLogger(__name__)
| else:
from twisted.internet import defer, reactor, ssl
from .utils.misc import arg_to_iter
logger = logging.getLogger(__name__)
| python -m unittest -q tests.test_mail.MailSenderTest.test_send_single_values_to_and_cc |
scrapy | 9 | class MailSender(object):
msg = MIMEMultipart()
else:
msg = MIMENonMultipart(*mimetype.split('/', 1))
msg['From'] = self.mailfrom
msg['To'] = COMMASPACE.join(to)
msg['Date'] = formatdate(localtime=True) | class MailSender(object):
msg = MIMEMultipart()
else:
msg = MIMENonMultipart(*mimetype.split('/', 1))
to = list(arg_to_iter(to))
cc = list(arg_to_iter(cc))
msg['From'] = self.mailfrom
msg['To'] = COMMASPACE.join(to)
msg['Date'] = formatdate(local... | python -m unittest -q tests.test_mail.MailSenderTest.test_send_single_values_to_and_cc |
pandas | 47 | class DataFrame(NDFrame):
for k1, k2 in zip(key, value.columns):
self[k1] = value[k2]
else:
indexer = self.loc._get_listlike_indexer(
key, axis=1, raise_missing=False
)[1] | class DataFrame(NDFrame):
for k1, k2 in zip(key, value.columns):
self[k1] = value[k2]
else:
self.loc._ensure_listlike_indexer(key, axis=1)
indexer = self.loc._get_listlike_indexer(
key, axis=1, raise_missing=False
... | pytest pandas/tests/indexing/test_loc.py::TestLoc2::test_loc_setitem_missing_columns |
pandas | 47 | from pandas.errors import AbstractMethodError
from pandas.util._decorators import Appender
from pandas.core.dtypes.common import (
is_integer,
is_iterator,
is_list_like, | from pandas.errors import AbstractMethodError
from pandas.util._decorators import Appender
from pandas.core.dtypes.common import (
is_hashable,
is_integer,
is_iterator,
is_list_like, | pytest pandas/tests/indexing/test_loc.py::TestLoc2::test_loc_setitem_missing_columns |
pandas | 47 | class _LocationIndexer(_NDFrameIndexerBase):
"""
Convert a potentially-label-based key into a positional indexer.
"""
if self.axis is not None:
return self._convert_tuple(key, is_setter=True)
| class _LocationIndexer(_NDFrameIndexerBase):
"""
Convert a potentially-label-based key into a positional indexer.
"""
if self.name == "loc":
self._ensure_listlike_indexer(key)
if self.axis is not None:
return self._convert_tuple(key, is_setter=True)
| pytest pandas/tests/indexing/test_loc.py::TestLoc2::test_loc_setitem_missing_columns |
pandas | 47 | class _LocationIndexer(_NDFrameIndexerBase):
raise
raise IndexingError(key) from e
def __setitem__(self, key, value):
if isinstance(key, tuple):
key = tuple(com.apply_if_callable(x, self.obj) for x in key) | class _LocationIndexer(_NDFrameIndexerBase):
raise
raise IndexingError(key) from e
def _ensure_listlike_indexer(self, key, axis=None):
"""
Ensure that a list-like of column labels are all present by adding them if
they do not already exist.
Parameters
... | pytest pandas/tests/indexing/test_loc.py::TestLoc2::test_loc_setitem_missing_columns |
youtube-dl | 36 | from ..utils import (
class FacebookIE(InfoExtractor):
_VALID_URL = r'''(?x)
https?://(?:\w+\.)?facebook\.com/
(?:[^#?]*\#!/)?
(?:video/video\.php|photo\.php|video/embed)\?(?:.*?)
(?:v|video_id)=(?P<id>[0-9]+)
(?:.*)''' | from ..utils import (
class FacebookIE(InfoExtractor):
_VALID_URL = r'''(?x)
https?://(?:\w+\.)?facebook\.com/
(?:[^#]*?\#!/)?
(?:video/video\.php|photo\.php|video/embed)\?(?:.*?)
(?:v|video_id)=(?P<id>[0-9]+)
(?:.*)''' | python -m unittest -q test.test_all_urls.TestAllURLsMatching.test_facebook_matching |
thefuck | 21 | from thefuck.specific.git import git_support
@git_support
def match(command):
return (command.script.split()[1] == 'stash'
and 'usage:' in command.stderr)
# git's output here is too complicated to be parsed (see the test file)
stash_commands = ( | from thefuck.specific.git import git_support
@git_support
def match(command):
splited_script = command.script.split()
if len(splited_script) > 1:
return (splited_script[1] == 'stash'
and 'usage:' in command.stderr)
else:
return False
# git's output here is too complicated t... | pytest tests/rules/test_git_fix_stash.py::test_not_match |
luigi | 32 | except ImportError:
from ordereddict import OrderedDict
from luigi import six
class TaskClassException(Exception): | except ImportError:
from ordereddict import OrderedDict
from luigi import six
import logging
logger = logging.getLogger('luigi-interface')
class TaskClassException(Exception): | pytest test/instance_test.py::InstanceTest::test_unhashable_type |
pandas | 28 | class StringMethods(NoNewAttributesMixin):
if isinstance(others, ABCSeries):
return [others]
elif isinstance(others, ABCIndexClass):
return [Series(others._values, index=others)]
elif isinstance(others, ABCDataFrame):
return [others[x] for x in others]
... | class StringMethods(NoNewAttributesMixin):
if isinstance(others, ABCSeries):
return [others]
elif isinstance(others, ABCIndexClass):
return [Series(others._values, index=idx)]
elif isinstance(others, ABCDataFrame):
return [others[x] for x in others]
el... | pytest pandas/tests/test_strings.py::test_cat_different_classes |
keras | 15 | import numpy as np
import time
import json
import warnings
from collections import deque
from collections import OrderedDict | import numpy as np
import time
import json
import warnings
import io
import sys
from collections import deque
from collections import OrderedDict | pytest tests/keras/test_callbacks.py::test_CSVLogger |
keras | 15 | class CSVLogger(Callback):
self.writer = None
self.keys = None
self.append_header = True
self.file_flags = 'b' if six.PY2 and os.name == 'nt' else ''
super(CSVLogger, self).__init__()
def on_train_begin(self, logs=None): | class CSVLogger(Callback):
self.writer = None
self.keys = None
self.append_header = True
if six.PY2:
self.file_flags = 'b'
self._open_args = {}
else:
self.file_flags = ''
self._open_args = {'newline': '\n'}
super(CSVLogger, ... | pytest tests/keras/test_callbacks.py::test_CSVLogger |
keras | 15 | class CSVLogger(Callback):
if os.path.exists(self.filename):
with open(self.filename, 'r' + self.file_flags) as f:
self.append_header = not bool(len(f.readline()))
self.csv_file = open(self.filename, 'a' + self.file_flags)
else:
self.csv_fi... | class CSVLogger(Callback):
if os.path.exists(self.filename):
with open(self.filename, 'r' + self.file_flags) as f:
self.append_header = not bool(len(f.readline()))
mode = 'a'
else:
mode = 'w'
self.csv_file = io.open(self.filename,
... | pytest tests/keras/test_callbacks.py::test_CSVLogger |
keras | 15 | class CSVLogger(Callback):
if not self.writer:
class CustomDialect(csv.excel):
delimiter = self.sep
self.writer = csv.DictWriter(self.csv_file,
fieldnames=['epoch'] + self.keys, dialect=CustomDialect)
if self.append_he... | class CSVLogger(Callback):
if not self.writer:
class CustomDialect(csv.excel):
delimiter = self.sep
fieldnames = ['epoch'] + self.keys
if six.PY2:
fieldnames = [unicode(x) for x in fieldnames]
self.writer = csv.DictWriter(self.csv_f... | pytest tests/keras/test_callbacks.py::test_CSVLogger |
httpie | 3 | class Session(BaseConfigDict):
"""
for name, value in request_headers.items():
value = value.decode('utf8')
if name == 'User-Agent' and value.startswith('HTTPie/'):
continue | class Session(BaseConfigDict):
"""
for name, value in request_headers.items():
if value is None:
continue # Ignore explicitely unset headers
value = value.decode('utf8')
if name == 'User-Agent' and value.startswith('HTTPie/'):
conti... | pytest tests/test_sessions.py::TestSession::test_download_in_session |
scrapy | 26 | class BaseSettings(MutableMapping):
def getbool(self, name, default=False):
"""
Get a setting value as a boolean.
``1``, ``'1'``, and ``True`` return ``True``, while ``0``, ``'0'``,
``False`` and ``None`` return ``False``.
For example, settings populated through en... | class BaseSettings(MutableMapping):
def getbool(self, name, default=False):
"""
Get a setting value as a boolean.
``1``, ``'1'``, and ``True`` return ``True``, while ``0``, ``'0'``,
``False`` and ``None`` return ``False``.
For example, settings populated through environment... | python -m unittest -q tests.test_settings.__init__.BaseSettingsTest.test_getcomposite |
scrapy | 26 | class BaseSettings(MutableMapping):
if basename in self:
warnings.warn('_BASE settings are deprecated.',
category=ScrapyDeprecationWarning)
compsett = BaseSettings(self[name + "_BASE"], priority='default')
compsett.update(self[name])
retu... | class BaseSettings(MutableMapping):
if basename in self:
warnings.warn('_BASE settings are deprecated.',
category=ScrapyDeprecationWarning)
# When users defined a _BASE setting, they explicitly don't want to
# use any of Scrapy's defaults. Therefore,... | python -m unittest -q tests.test_settings.__init__.BaseSettingsTest.test_getcomposite |
fastapi | 15 | class APIRouter(routing.Router):
include_in_schema=route.include_in_schema,
name=route.name,
)
def get(
self, | class APIRouter(routing.Router):
include_in_schema=route.include_in_schema,
name=route.name,
)
elif isinstance(route, routing.WebSocketRoute):
self.add_websocket_route(
prefix + route.path, route.endpoint, name=route... | pytest tests/test_ws_router.py::test_prefix_router |
pandas | 12 | from pandas.core.dtypes.cast import (
validate_numeric_casting,
)
from pandas.core.dtypes.common import (
ensure_float64,
ensure_int64,
ensure_platform_int,
infer_dtype_from_object, | from pandas.core.dtypes.cast import (
validate_numeric_casting,
)
from pandas.core.dtypes.common import (
ensure_int64,
ensure_platform_int,
infer_dtype_from_object, | pytest pandas/tests/frame/methods/test_cov_corr.py::TestDataFrameCov::test_cov_nullable_integer |
pandas | 12 | Wild 185.0
numeric_df = self._get_numeric_data()
cols = numeric_df.columns
idx = cols.copy()
mat = numeric_df.values
if method == "pearson":
correl = libalgos.nancorr(ensure_float64(mat), minp=min_periods)
elif method == "spearman":
correl... | Wild 185.0
numeric_df = self._get_numeric_data()
cols = numeric_df.columns
idx = cols.copy()
mat = numeric_df.astype(float, copy=False).to_numpy()
if method == "pearson":
correl = libalgos.nancorr(mat, minp=min_periods)
elif method == "spearman":
... | pytest pandas/tests/frame/methods/test_cov_corr.py::TestDataFrameCov::test_cov_nullable_integer |
pandas | 12 | Wild 185.0
numeric_df = self._get_numeric_data()
cols = numeric_df.columns
idx = cols.copy()
mat = numeric_df.values
if notna(mat).all():
if min_periods is not None and min_periods > len(mat):
baseCov = np.empty((mat.shape[1], mat.shape[1]))
... | Wild 185.0
numeric_df = self._get_numeric_data()
cols = numeric_df.columns
idx = cols.copy()
mat = numeric_df.astype(float, copy=False).to_numpy()
if notna(mat).all():
if min_periods is not None and min_periods > len(mat):
base_cov = np.empty(... | pytest pandas/tests/frame/methods/test_cov_corr.py::TestDataFrameCov::test_cov_nullable_integer |
pandas | 80 | class BaseMaskedArray(ExtensionArray, ExtensionOpsMixin):
def __len__(self) -> int:
return len(self._data)
def to_numpy(
self, dtype=None, copy=False, na_value: "Scalar" = lib.no_default,
): | class BaseMaskedArray(ExtensionArray, ExtensionOpsMixin):
def __len__(self) -> int:
return len(self._data)
def __invert__(self):
return type(self)(~self._data, self._mask)
def to_numpy(
self, dtype=None, copy=False, na_value: "Scalar" = lib.no_default,
): | pytest pandas/tests/arrays/sparse/test_arithmetics.py::test_invert |
pandas | 80 | class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin):
# inv fails with 0 len
return self
arr = operator.inv(com.values_from_object(self))
return self.__array_wrap__(arr)
def __nonzero__(self):
raise ValueError( | class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin):
# inv fails with 0 len
return self
new_data = self._data.apply(operator.invert)
result = self._constructor(new_data).__finalize__(self)
return result
def __nonzero__(self):
raise ValueError... | pytest pandas/tests/arrays/sparse/test_arithmetics.py::test_invert |
pandas | 80 | def check_bool_indexer(index: Index, key) -> np.ndarray:
result = result.astype(bool)._values
else:
if is_sparse(result):
result = result.to_dense()
result = check_bool_array_indexer(index, result)
return result | def check_bool_indexer(index: Index, key) -> np.ndarray:
result = result.astype(bool)._values
else:
if is_sparse(result):
result = np.asarray(result)
result = check_bool_array_indexer(index, result)
return result | pytest pandas/tests/arrays/sparse/test_arithmetics.py::test_invert |
pandas | 80 | import operator
import numpy as np
import pytest
import pandas.util._test_decorators as td
import pandas as pd
import pandas._testing as tm
from pandas.arrays import BooleanArray
from pandas.core.arrays.boolean import coerce_to_array
from pandas.tests.extension.base import BaseOpsUtil
def make_data(): | """
This file contains a minimal set of tests for compliance with the extension
array interface test suite, and should contain no other tests.
The test suite for the full functionality of the array is located in
`pandas/tests/arrays/`.
The tests in this file are inherited from the BaseExtensionTests, and only
minimal ... | pytest pandas/tests/arrays/sparse/test_arithmetics.py::test_invert |
pandas | 80 | def make_data():
@pytest.fixture
def dtype():
return pd.BooleanDtype()
@pytest.fixture | def make_data():
@pytest.fixture
def dtype():
return BooleanDtype()
@pytest.fixture | pytest pandas/tests/arrays/sparse/test_arithmetics.py::test_invert |
pandas | 80 | def data(dtype):
return pd.array(make_data(), dtype=dtype)
def test_boolean_array_constructor():
values = np.array([True, False, True, False], dtype="bool")
mask = np.array([False, False, False, True], dtype="bool")
result = BooleanArray(values, mask)
expected = pd.array([True, False, True, None]... | def data(dtype):
return pd.array(make_data(), dtype=dtype)
@pytest.fixture
def data_for_twos(dtype):
return pd.array(np.ones(100), dtype=dtype)
@pytest.fixture
def data_missing(dtype):
return pd.array([np.nan, True], dtype=dtype)
@pytest.fixture
def data_for_sorting(dtype):
return pd.array([True, ... | pytest pandas/tests/arrays/sparse/test_arithmetics.py::test_invert |
pandas | 80 | from .interface import BaseInterfaceTests # noqa
from .io import BaseParsingTests # noqa
from .methods import BaseMethodsTests # noqa
from .missing import BaseMissingTests # noqa
from .ops import BaseArithmeticOpsTests, BaseComparisonOpsTests, BaseOpsUtil # noqa
from .printing import BasePrintingTests # noqa
from... | from .interface import BaseInterfaceTests # noqa
from .io import BaseParsingTests # noqa
from .methods import BaseMethodsTests # noqa
from .missing import BaseMissingTests # noqa
from .ops import ( # noqa
BaseArithmeticOpsTests,
BaseComparisonOpsTests,
BaseOpsUtil,
BaseUnaryOpsTests,
)
from .printi... | pytest pandas/tests/arrays/sparse/test_arithmetics.py::test_invert |
pandas | 80 | class BaseComparisonOpsTests(BaseOpsUtil):
assert result is NotImplemented
else:
raise pytest.skip(f"{type(data).__name__} does not implement __eq__") | class BaseComparisonOpsTests(BaseOpsUtil):
assert result is NotImplemented
else:
raise pytest.skip(f"{type(data).__name__} does not implement __eq__")
class BaseUnaryOpsTests(BaseOpsUtil):
def test_invert(self, data):
s = pd.Series(data, name="name")
result = ~s
... | pytest pandas/tests/arrays/sparse/test_arithmetics.py::test_invert |
pandas | 80 | class TestDataFrameUnaryOperators:
tm.assert_frame_equal(-(df < 0), ~(df < 0))
@pytest.mark.parametrize(
"df",
[ | class TestDataFrameUnaryOperators:
tm.assert_frame_equal(-(df < 0), ~(df < 0))
def test_invert_mixed(self):
shape = (10, 5)
df = pd.concat(
[
pd.DataFrame(np.zeros(shape, dtype="bool")),
pd.DataFrame(np.zeros(shape, dtype=int)),
],
... | pytest pandas/tests/arrays/sparse/test_arithmetics.py::test_invert |
pandas | 121 | class ObjectBlock(Block):
if convert:
block = [b.convert(numeric=False, copy=True) for b in block]
return block
return self
| class ObjectBlock(Block):
if convert:
block = [b.convert(numeric=False, copy=True) for b in block]
return block
if convert:
return [self.convert(numeric=False, copy=True)]
return self
| pytest pandas/tests/frame/test_replace.py::TestDataFrameReplace::test_replace_replacer_dtype |
pandas | 121 | class BlockManager(PandasObject):
convert=convert,
regex=regex,
)
if m.any():
new_rb = _extend_blocks(result, new_rb)
else:
new_rb.append(b) | class BlockManager(PandasObject):
convert=convert,
regex=regex,
)
if m.any() or convert:
new_rb = _extend_blocks(result, new_rb)
else:
new_rb.append(b) | pytest pandas/tests/frame/test_replace.py::TestDataFrameReplace::test_replace_replacer_dtype |
matplotlib | 8 | class _AxesBase(martist.Artist):
left, right = sorted([left, right], reverse=bool(reverse))
self._viewLim.intervalx = (left, right)
if auto is not None:
self._autoscaleXon = bool(auto)
| class _AxesBase(martist.Artist):
left, right = sorted([left, right], reverse=bool(reverse))
self._viewLim.intervalx = (left, right)
# Mark viewlims as no longer stale without triggering an autoscale.
for ax in self._shared_x_axes.get_siblings(self):
ax._stale_viewlim_x = Fal... | pytest lib/matplotlib/tests/test_axes.py::test_unautoscaley;pytest lib/matplotlib/tests/test_axes.py::test_unautoscalex |
matplotlib | 8 | class _AxesBase(martist.Artist):
bottom, top = sorted([bottom, top], reverse=bool(reverse))
self._viewLim.intervaly = (bottom, top)
if auto is not None:
self._autoscaleYon = bool(auto)
| class _AxesBase(martist.Artist):
bottom, top = sorted([bottom, top], reverse=bool(reverse))
self._viewLim.intervaly = (bottom, top)
# Mark viewlims as no longer stale without triggering an autoscale.
for ax in self._shared_y_axes.get_siblings(self):
ax._stale_viewlim_y = Fal... | pytest lib/matplotlib/tests/test_axes.py::test_unautoscaley;pytest lib/matplotlib/tests/test_axes.py::test_unautoscalex |
keras | 34 | class Model(Container):
val_enqueuer.start(workers=workers, max_queue_size=max_queue_size)
validation_generator = val_enqueuer.get()
else:
validation_generator = validation_data
else:
if len(v... | class Model(Container):
val_enqueuer.start(workers=workers, max_queue_size=max_queue_size)
validation_generator = val_enqueuer.get()
else:
if isinstance(validation_data, Sequence):
validation_generato... | pytest tests/test_multiprocessing.py::test_multiprocessing_training |
keras | 34 | class Model(Container):
enqueuer.start(workers=workers, max_queue_size=max_queue_size)
output_generator = enqueuer.get()
else:
output_generator = generator
callback_model.stop_training = False
# Construct epoch logs. | class Model(Container):
enqueuer.start(workers=workers, max_queue_size=max_queue_size)
output_generator = enqueuer.get()
else:
if is_sequence:
output_generator = iter(generator)
else:
output_generator = g... | pytest tests/test_multiprocessing.py::test_multiprocessing_training |
keras | 34 | class Model(Container):
enqueuer.start(workers=workers, max_queue_size=max_queue_size)
output_generator = enqueuer.get()
else:
output_generator = generator
while steps_done < steps:
generator_output = next(output_generator) | class Model(Container):
enqueuer.start(workers=workers, max_queue_size=max_queue_size)
output_generator = enqueuer.get()
else:
if is_sequence:
output_generator = iter(generator)
else:
output_generator = g... | pytest tests/test_multiprocessing.py::test_multiprocessing_training |
keras | 34 | class Model(Container):
enqueuer.start(workers=workers, max_queue_size=max_queue_size)
output_generator = enqueuer.get()
else:
output_generator = generator
if verbose == 1:
progbar = Progbar(target=steps) | class Model(Container):
enqueuer.start(workers=workers, max_queue_size=max_queue_size)
output_generator = enqueuer.get()
else:
if is_sequence:
output_generator = iter(generator)
else:
output_generator = g... | pytest tests/test_multiprocessing.py::test_multiprocessing_training |
keras | 34 | class Sequence(object):
"""
pass
# Global variables to be shared across processes
_SHARED_SEQUENCES = {} | class Sequence(object):
"""
pass
def __iter__(self):
"""Create an infinite generator that iterate over the Sequence."""
while True:
for item in (self[i] for i in range(len(self))):
yield item
# Global variables to be shared across processes
_SHARED_SEQU... | pytest tests/test_multiprocessing.py::test_multiprocessing_training |
pandas | 100 | class NDFrame(PandasObject, SelectionMixin):
data = self.fillna(method=fill_method, limit=limit, axis=axis)
rs = data.div(data.shift(periods=periods, freq=freq, axis=axis, **kwargs)) - 1
rs = rs.loc[~rs.index.duplicated()]
rs = rs.reindex_like(data)
if freq is None:
... | class NDFrame(PandasObject, SelectionMixin):
data = self.fillna(method=fill_method, limit=limit, axis=axis)
rs = data.div(data.shift(periods=periods, freq=freq, axis=axis, **kwargs)) - 1
if freq is not None:
# Shift method is implemented differently when freq is not None
... | pytest pandas/tests/frame/methods/test_pct_change.py::test_pct_change_with_duplicated_indices |
youtube-dl | 42 | import re
from .common import InfoExtractor
from ..utils import (
find_xpath_attr,
fix_xml_all_ampersand,
)
| import re
from .common import InfoExtractor
from ..utils import (
find_xpath_attr,
fix_xml_ampersands
)
| python -m unittest -q test.test_utils.TestUtil.test_fix_xml_ampersands |
youtube-dl | 42 | class ClipsyndicateIE(InfoExtractor):
pdoc = self._download_xml(
'http://eplayer.clipsyndicate.com/osmf/playlist?%s' % flvars,
video_id, u'Downloading video info',
transform_source=fix_xml_all_ampersand)
track_doc = pdoc.find('trackList/track')
def find_para... | class ClipsyndicateIE(InfoExtractor):
pdoc = self._download_xml(
'http://eplayer.clipsyndicate.com/osmf/playlist?%s' % flvars,
video_id, u'Downloading video info',
transform_source=fix_xml_ampersands)
track_doc = pdoc.find('trackList/track')
def find_param(na... | python -m unittest -q test.test_utils.TestUtil.test_fix_xml_ampersands |
youtube-dl | 42 | import re
from .common import InfoExtractor
from ..utils import (
fix_xml_all_ampersand,
)
| import re
from .common import InfoExtractor
from ..utils import (
fix_xml_ampersands,
)
| python -m unittest -q test.test_utils.TestUtil.test_fix_xml_ampersands |
youtube-dl | 42 | class MetacriticIE(InfoExtractor):
webpage = self._download_webpage(url, video_id)
# The xml is not well formatted, there are raw '&'
info = self._download_xml('http://www.metacritic.com/video_data?video=' + video_id,
video_id, 'Downloading info xml', transform_source=fix_xml_all_amp... | class MetacriticIE(InfoExtractor):
webpage = self._download_webpage(url, video_id)
# The xml is not well formatted, there are raw '&'
info = self._download_xml('http://www.metacritic.com/video_data?video=' + video_id,
video_id, 'Downloading info xml', transform_source=fix_xml_ampersa... | python -m unittest -q test.test_utils.TestUtil.test_fix_xml_ampersands |
youtube-dl | 42 | from .common import InfoExtractor
from ..utils import (
compat_urllib_parse,
ExtractorError,
)
def _media_xml_tag(tag): | from .common import InfoExtractor
from ..utils import (
compat_urllib_parse,
ExtractorError,
fix_xml_ampersands,
)
def _media_xml_tag(tag): | python -m unittest -q test.test_utils.TestUtil.test_fix_xml_ampersands |
youtube-dl | 42 | class MTVServicesInfoExtractor(InfoExtractor):
video_id = self._id_from_uri(uri)
data = compat_urllib_parse.urlencode({'uri': uri})
def fix_ampersand(s):
""" Fix unencoded ampersand in XML """
return s.replace(u'& ', '& ')
idoc = self._download_xml(
... | class MTVServicesInfoExtractor(InfoExtractor):
video_id = self._id_from_uri(uri)
data = compat_urllib_parse.urlencode({'uri': uri})
idoc = self._download_xml(
self._FEED_URL + '?' + data, video_id,
u'Downloading info', transform_source=fix_xml_ampersands)
return ... | python -m unittest -q test.test_utils.TestUtil.test_fix_xml_ampersands |
youtube-dl | 42 | def month_by_name(name):
return None
def fix_xml_all_ampersand(xml_str):
"""Replace all the '&' by '&' in XML"""
return xml_str.replace(u'&', u'&')
def setproctitle(title): | def month_by_name(name):
return None
def fix_xml_ampersands(xml_str):
"""Replace all the '&' by '&' in XML"""
return re.sub(
r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
u'&',
xml_str)
def setproctitle(title): | python -m unittest -q test.test_utils.TestUtil.test_fix_xml_ampersands |
pandas | 33 | class IntegerArray(BaseMaskedArray):
ExtensionArray.argsort
"""
data = self._data.copy()
data[self._mask] = data.min() - 1
return data
@classmethod | class IntegerArray(BaseMaskedArray):
ExtensionArray.argsort
"""
data = self._data.copy()
if self._mask.any():
data[self._mask] = data.min() - 1
return data
@classmethod | pytest pandas/tests/arrays/integer/test_function.py::test_value_counts_empty |
luigi | 29 | class Register(abc.ABCMeta):
# We return this in a topologically sorted list of inheritance: this is useful in some cases (#822)
reg = OrderedDict()
for cls in cls._reg:
if cls.run == NotImplemented:
continue
name = cls.task_family
if name in ... | class Register(abc.ABCMeta):
# We return this in a topologically sorted list of inheritance: this is useful in some cases (#822)
reg = OrderedDict()
for cls in cls._reg:
name = cls.task_family
if name in reg and reg[name] != cls and \ | pytest test/task_test.py::TaskTest::test_external_tasks_loadable |
luigi | 29 | class AmbiguousClass(luigi.Task):
pass
class NonAmbiguousClass(luigi.ExternalTask):
pass
class NonAmbiguousClass(luigi.Task):
def run(self):
NonAmbiguousClass.has_run = True
class TaskWithSameName(luigi.Task):
def run(self): | class AmbiguousClass(luigi.Task):
pass
class TaskWithSameName(luigi.Task):
def run(self): | pytest test/task_test.py::TaskTest::test_external_tasks_loadable |
luigi | 29 | class CmdlineTest(unittest.TestCase):
def test_cmdline_ambiguous_class(self, logger):
self.assertRaises(Exception, luigi.run, ['--local-scheduler', '--no-lock', 'AmbiguousClass'])
@mock.patch("logging.getLogger")
@mock.patch("warnings.warn")
def test_cmdline_non_ambiguous_class(self, warn, logg... | class CmdlineTest(unittest.TestCase):
def test_cmdline_ambiguous_class(self, logger):
self.assertRaises(Exception, luigi.run, ['--local-scheduler', '--no-lock', 'AmbiguousClass'])
@mock.patch("logging.getLogger")
@mock.patch("logging.StreamHandler")
def test_setup_interface_logging(self, handle... | pytest test/task_test.py::TaskTest::test_external_tasks_loadable |
pandas | 50 | def _cat_compare_op(op):
mask = (self._codes == -1) | (other_codes == -1)
if mask.any():
# In other series, the leads to False, so do that here too
ret[mask] = False
return ret
if is_scalar(other): | def _cat_compare_op(op):
mask = (self._codes == -1) | (other_codes == -1)
if mask.any():
# In other series, the leads to False, so do that here too
if opname == "__ne__":
ret[(self._codes == -1) & (other_codes == -1)] = True
els... | pytest pandas/tests/extension/test_categorical.py::TestComparisonOps::test_not_equal_with_na |
youtube-dl | 21 | def base_url(url):
def urljoin(base, path):
if not isinstance(path, compat_str) or not path:
return None
if re.match(r'^(?:https?:)?//', path):
return path
if not isinstance(base, compat_str) or not re.match(r'^(?:https?:)?//', base):
return None
return compat_urlparse.urljoin(... | def base_url(url):
def urljoin(base, path):
if isinstance(path, bytes):
path = path.decode('utf-8')
if not isinstance(path, compat_str) or not path:
return None
if re.match(r'^(?:https?:)?//', path):
return path
if isinstance(base, bytes):
base = base.decode('utf-8')
... | python -m unittest -q test.test_utils.TestUtil.test_urljoin |
pandas | 163 | class _Window(PandasObject, SelectionMixin):
except (ValueError, TypeError):
raise TypeError("cannot handle this type -> {0}".format(values.dtype))
# Always convert inf to nan
values[np.isinf(values)] = np.NaN
return values
| class _Window(PandasObject, SelectionMixin):
except (ValueError, TypeError):
raise TypeError("cannot handle this type -> {0}".format(values.dtype))
# Convert inf to nan for C funcs
inf = np.isinf(values)
if inf.any():
values = np.where(inf, np.nan, values... | pytest pandas/tests/window/test_rolling.py::TestRolling::test_readonly_array |
fastapi | 2 | class APIRouter(routing.Router):
def add_api_websocket_route(
self, path: str, endpoint: Callable, name: str = None
) -> None:
route = APIWebSocketRoute(path, endpoint=endpoint, name=name)
self.routes.append(route)
def websocket(self, path: str, name: str = None) -> Callable: | class APIRouter(routing.Router):
def add_api_websocket_route(
self, path: str, endpoint: Callable, name: str = None
) -> None:
route = APIWebSocketRoute(
path,
endpoint=endpoint,
name=name,
dependency_overrides_provider=self.dependency_overrides_pr... | pytest tests/test_ws_router.py::test_router_ws_depends_with_override |
matplotlib | 16 | def nonsingular(vmin, vmax, expander=0.001, tiny=1e-15, increasing=True):
vmin, vmax = vmax, vmin
swapped = True
maxabsvalue = max(abs(vmin), abs(vmax))
if maxabsvalue < (1e6 / tiny) * np.finfo(float).tiny:
vmin = -expander | def nonsingular(vmin, vmax, expander=0.001, tiny=1e-15, increasing=True):
vmin, vmax = vmax, vmin
swapped = True
# Expand vmin, vmax to float: if they were integer types, they can wrap
# around in abs (abs(np.int8(-128)) == -128) and vmax - vmin can overflow.
vmin, vmax = map(float, [vmin, ... | pytest lib/matplotlib/tests/test_colorbar.py::test_colorbar_int |
luigi | 25 | class S3CopyToTable(rdbms.CopyToTable):
if not (self.table):
raise Exception("table need to be specified")
path = self.s3_load_path()
connection = self.output().connect()
if not self.does_table_exist(connection):
# try creating table | class S3CopyToTable(rdbms.CopyToTable):
if not (self.table):
raise Exception("table need to be specified")
path = self.s3_load_path
connection = self.output().connect()
if not self.does_table_exist(connection):
# try creating table | pytest test/contrib/redshift_test.py::TestS3CopyToTable::test_s3_copy_to_table |
matplotlib | 4 | class Axes(_AxesBase):
@_preprocess_data(replace_names=["y", "xmin", "xmax", "colors"],
label_namer="y")
def hlines(self, y, xmin, xmax, colors='k', linestyles='solid',
label='', **kwargs):
"""
Plot horizontal lines at each *y* from *xmin* to *xmax*. | class Axes(_AxesBase):
@_preprocess_data(replace_names=["y", "xmin", "xmax", "colors"],
label_namer="y")
def hlines(self, y, xmin, xmax, colors=None, linestyles='solid',
label='', **kwargs):
"""
Plot horizontal lines at each *y* from *xmin* to *xmax*. | pytest lib/matplotlib/tests/test_axes.py::test_vlines_default |
matplotlib | 4 | class Axes(_AxesBase):
Respective beginning and end of each line. If scalars are
provided, all lines will have same length.
colors : list of colors, default: 'k'
linestyles : {'solid', 'dashed', 'dashdot', 'dotted'}, optional
| class Axes(_AxesBase):
Respective beginning and end of each line. If scalars are
provided, all lines will have same length.
colors : list of colors, default: :rc:`lines.color`
linestyles : {'solid', 'dashed', 'dashdot', 'dotted'}, optional
| pytest lib/matplotlib/tests/test_axes.py::test_vlines_default |
matplotlib | 4 | class Axes(_AxesBase):
@_preprocess_data(replace_names=["x", "ymin", "ymax", "colors"],
label_namer="x")
def vlines(self, x, ymin, ymax, colors='k', linestyles='solid',
label='', **kwargs):
"""
Plot vertical lines. | class Axes(_AxesBase):
@_preprocess_data(replace_names=["x", "ymin", "ymax", "colors"],
label_namer="x")
def vlines(self, x, ymin, ymax, colors=None, linestyles='solid',
label='', **kwargs):
"""
Plot vertical lines. | pytest lib/matplotlib/tests/test_axes.py::test_vlines_default |
matplotlib | 4 | class Axes(_AxesBase):
Respective beginning and end of each line. If scalars are
provided, all lines will have same length.
colors : list of colors, default: 'k'
linestyles : {'solid', 'dashed', 'dashdot', 'dotted'}, optional
| class Axes(_AxesBase):
Respective beginning and end of each line. If scalars are
provided, all lines will have same length.
colors : list of colors, default: :rc:`lines.color`
linestyles : {'solid', 'dashed', 'dashdot', 'dotted'}, optional
| pytest lib/matplotlib/tests/test_axes.py::test_vlines_default |
matplotlib | 4 | def hist2d(
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.hlines)
def hlines(
y, xmin, xmax, colors='k', linestyles='solid', label='', *,
data=None, **kwargs):
return gca().hlines(
y, xmin, xmax, colors=colors, linestyles=lines... | def hist2d(
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.hlines)
def hlines(
y, xmin, xmax, colors=None, linestyles='solid', label='', *,
data=None, **kwargs):
return gca().hlines(
y, xmin, xmax, colors=colors, linestyles=line... | pytest lib/matplotlib/tests/test_axes.py::test_vlines_default |
matplotlib | 4 | def violinplot(
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.vlines)
def vlines(
x, ymin, ymax, colors='k', linestyles='solid', label='', *,
data=None, **kwargs):
return gca().vlines(
x, ymin, ymax, colors=colors, linestyles=l... | def violinplot(
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.vlines)
def vlines(
x, ymin, ymax, colors=None, linestyles='solid', label='', *,
data=None, **kwargs):
return gca().vlines(
x, ymin, ymax, colors=colors, linestyles=... | pytest lib/matplotlib/tests/test_axes.py::test_vlines_default |
keras | 38 | class StackedRNNCells(Layer):
output_dim = cell.state_size[0]
else:
output_dim = cell.state_size
input_shape = (input_shape[0], input_shape[1], output_dim)
self.built = True
def get_config(self): | class StackedRNNCells(Layer):
output_dim = cell.state_size[0]
else:
output_dim = cell.state_size
input_shape = (input_shape[0], output_dim)
self.built = True
def get_config(self): | pytest tests/keras/layers/recurrent_test.py::test_minimal_rnn_cell_layer |
thefuck | 17 | from subprocess import Popen, PIPE
import os
from ..conf import settings
from ..utils import DEVNULL, memoize, cache
from .generic import Generic
| import os
from ..conf import settings
from ..utils import memoize
from .generic import Generic
| pytest tests/shells/test_bash.py::TestBash::test_from_shell |
thefuck | 17 | class Bash(Generic):
def app_alias(self, fuck):
alias = "TF_ALIAS={0}" \
" alias {0}='PYTHONIOENCODING=utf-8" \
" TF_CMD=$(thefuck $(fc -ln -1)) && " \
" eval $TF_CMD".format(fuck)
if settings.alter_history: | class Bash(Generic):
def app_alias(self, fuck):
alias = "TF_ALIAS={0}" \
" alias {0}='PYTHONIOENCODING=utf-8" \
" TF_CMD=$(TF_SHELL_ALIASES=$(alias) thefuck $(fc -ln -1)) && " \
" eval $TF_CMD".format(fuck)
if settings.alter_history: | pytest tests/shells/test_bash.py::TestBash::test_from_shell |
thefuck | 17 | class Bash(Generic):
return name, value
@memoize
@cache('.bashrc', '.bash_profile')
def get_aliases(self):
proc = Popen(['bash', '-ic', 'alias'], stdout=PIPE, stderr=DEVNULL)
return dict(
self._parse_alias(alias)
for alias in proc.stdout.read().decode... | class Bash(Generic):
return name, value
@memoize
def get_aliases(self):
raw_aliases = os.environ.get('TF_SHELL_ALIASES', '').split('\n')
return dict(self._parse_alias(alias)
for alias in raw_aliases if alias and '=' in alias)
def _get_history_file_name(self):
... | pytest tests/shells/test_bash.py::TestBash::test_from_shell |
thefuck | 17 | class Zsh(Generic):
@memoize
def get_aliases(self):
raw_aliases = os.environ['TF_SHELL_ALIASES'].split('\n')
return dict(self._parse_alias(alias)
for alias in raw_aliases if alias and '=' in alias)
| class Zsh(Generic):
@memoize
def get_aliases(self):
raw_aliases = os.environ.get('TF_SHELL_ALIASES', '').split('\n')
return dict(self._parse_alias(alias)
for alias in raw_aliases if alias and '=' in alias)
| pytest tests/shells/test_bash.py::TestBash::test_from_shell |
pandas | 142 | def diff(arr, n: int, axis: int = 0):
dtype = arr.dtype
is_timedelta = False
if needs_i8_conversion(arr):
dtype = np.float64
arr = arr.view("i8") | def diff(arr, n: int, axis: int = 0):
dtype = arr.dtype
is_timedelta = False
is_bool = False
if needs_i8_conversion(arr):
dtype = np.float64
arr = arr.view("i8") | pytest pandas/tests/series/test_analytics.py::TestSeriesAnalytics::test_bool_diff |
pandas | 142 | def diff(arr, n: int, axis: int = 0):
elif is_bool_dtype(dtype):
dtype = np.object_
elif is_integer_dtype(dtype):
dtype = np.float64 | def diff(arr, n: int, axis: int = 0):
elif is_bool_dtype(dtype):
dtype = np.object_
is_bool = True
elif is_integer_dtype(dtype):
dtype = np.float64 | pytest pandas/tests/series/test_analytics.py::TestSeriesAnalytics::test_bool_diff |
pandas | 142 | def diff(arr, n: int, axis: int = 0):
result = res - lag
result[mask] = na
out_arr[res_indexer] = result
else:
out_arr[res_indexer] = arr[res_indexer] - arr[lag_indexer]
| def diff(arr, n: int, axis: int = 0):
result = res - lag
result[mask] = na
out_arr[res_indexer] = result
elif is_bool:
out_arr[res_indexer] = arr[res_indexer] ^ arr[lag_indexer]
else:
out_arr[res_indexer] = arr[res_indexer] - arr[lag_indexer]
| pytest pandas/tests/series/test_analytics.py::TestSeriesAnalytics::test_bool_diff |
pandas | 142 | class TestTimeSeries(TestData):
)
tm.assert_index_equal(expected.index, result.index)
def test_diff(self):
# Just run the function
self.ts.diff()
# int dtype
a = 10000000000000000
b = a + 1
s = Series([a, b])
rs = s.diff()
assert rs[... | class TestTimeSeries(TestData):
)
tm.assert_index_equal(expected.index, result.index)
def test_pct_change(self):
rs = self.ts.pct_change(fill_method=None)
assert_series_equal(rs, self.ts / self.ts.shift(1) - 1) | pytest pandas/tests/series/test_analytics.py::TestSeriesAnalytics::test_bool_diff |
pandas | 71 | from pandas.core.dtypes.common import (
is_datetime64_dtype,
is_datetime64tz_dtype,
is_datetime_or_timedelta_dtype,
is_integer,
is_list_like,
is_scalar,
is_timedelta64_dtype, | from pandas.core.dtypes.common import (
is_datetime64_dtype,
is_datetime64tz_dtype,
is_datetime_or_timedelta_dtype,
is_extension_array_dtype,
is_integer,
is_integer_dtype,
is_list_like,
is_scalar,
is_timedelta64_dtype, | pytest pandas/tests/arrays/test_integer.py::test_cut |
pandas | 71 | def cut(
x = _preprocess_for_cut(x)
x, dtype = _coerce_to_type(x)
if not np.iterable(bins):
if is_scalar(bins) and bins < 1:
raise ValueError("`bins` should be a positive integer.") | def cut(
x = _preprocess_for_cut(x)
x, dtype = _coerce_to_type(x)
# To support cut(IntegerArray), we convert to object dtype with NaN
# Will properly support in the future.
# https://github.com/pandas-dev/pandas/pull/31290
if is_extension_array_dtype(x.dtype) and is_integer_dtype(x.dtype):
... | pytest pandas/tests/arrays/test_integer.py::test_cut |
sanic | 1 | class Sanic:
if _rn not in self.named_response_middleware:
self.named_response_middleware[_rn] = deque()
if middleware not in self.named_response_middleware[_rn]:
self.named_response_middleware[_rn].append(middleware)
# Decorator
def middl... | class Sanic:
if _rn not in self.named_response_middleware:
self.named_response_middleware[_rn] = deque()
if middleware not in self.named_response_middleware[_rn]:
self.named_response_middleware[_rn].appendleft(middleware)
# Decorator
def m... | pytest tests/test_blueprints.py::test_bp_middleware_order |
keras | 19 | def rnn(step_function, inputs, initial_states,
for o, p in zip(new_states, place_holders):
n_s.append(o.replace_placeholders({p: o.output}))
if len(n_s) > 0:
new_output = n_s[0]
return new_output, n_s
final_output, final_states = _recurrence(r... | def rnn(step_function, inputs, initial_states,
for o, p in zip(new_states, place_holders):
n_s.append(o.replace_placeholders({p: o.output}))
if len(n_s) > 0:
new_output = n_s[-1]
return new_output, n_s
final_output, final_states = _recurrence(... | pytest tests/keras/layers/recurrent_test.py::test_minimal_rnn_cell_non_layer_multiple_states |
keras | 19 | class StackedRNNCells(Layer):
'`state_size` attribute. '
'received cells:', cells)
self.cells = cells
super(StackedRNNCells, self).__init__(**kwargs)
@property
def state_size(self):
# States are a flat list
# in r... | class StackedRNNCells(Layer):
'`state_size` attribute. '
'received cells:', cells)
self.cells = cells
# reverse_state_order determines whether the state size will be in a
# reverse order of the cells' state. User might want to set... | pytest tests/keras/layers/recurrent_test.py::test_minimal_rnn_cell_non_layer_multiple_states |
keras | 19 | class StackedRNNCells(Layer):
# Format the new states as a flat list
# in reverse cell order.
states = []
for cell_states in new_nested_states[::-1]:
states += cell_states
return inputs, states
def build(self, input_shape):
if isinstance(input_shape, lis... | class StackedRNNCells(Layer):
# Format the new states as a flat list
# in reverse cell order.
new_states = []
if self.reverse_state_order:
new_nested_states = new_nested_states[::-1]
for cell_states in new_nested_states:
new_states += cell_states
... | pytest tests/keras/layers/recurrent_test.py::test_minimal_rnn_cell_non_layer_multiple_states |
keras | 19 | class StackedRNNCells(Layer):
cell.build([input_shape] + constants_shape)
else:
cell.build(input_shape)
if hasattr(cell.state_size, '__len__'):
output_dim = cell.state_size[0]
else:
output_dim = cell.state_si... | class StackedRNNCells(Layer):
cell.build([input_shape] + constants_shape)
else:
cell.build(input_shape)
if getattr(cell, 'output_size', None) is not None:
output_dim = cell.output_size
elif hasattr(cell.state_size, '__len__'... | pytest tests/keras/layers/recurrent_test.py::test_minimal_rnn_cell_non_layer_multiple_states |
keras | 19 | class RNN(Layer):
the size of the recurrent state
(which should be the same as the size of the cell output).
This can also be a list/tuple of integers
(one size per state). In this case, the first entry
(`state_size[0]`) should be the same ... | class RNN(Layer):
the size of the recurrent state
(which should be the same as the size of the cell output).
This can also be a list/tuple of integers
(one size per state).
- a `output_size` attribute. This can be a single integer or a
... | pytest tests/keras/layers/recurrent_test.py::test_minimal_rnn_cell_non_layer_multiple_states |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.