project stringclasses 17
values | bug_id int64 1 169 | buggy stringlengths 81 57.2k | fixed stringlengths 85 31.2k | test_command stringlengths 44 133 |
|---|---|---|---|---|
keras | 19 | class RNN(Layer):
state_size = self.cell.state_size
else:
state_size = [self.cell.state_size]
output_dim = state_size[0]
if self.return_sequences:
output_shape = (input_shape[0], input_shape[1], output_dim) | class RNN(Layer):
state_size = self.cell.state_size
else:
state_size = [self.cell.state_size]
if getattr(self.cell, 'output_size', None) is not None:
output_dim = self.cell.output_size
else:
output_dim = state_size[0]
if self.return_seque... | pytest tests/keras/layers/recurrent_test.py::test_minimal_rnn_cell_non_layer_multiple_states |
keras | 19 | class SimpleRNNCell(Layer):
self.dropout = min(1., max(0., dropout))
self.recurrent_dropout = min(1., max(0., recurrent_dropout))
self.state_size = self.units
self._dropout_mask = None
self._recurrent_dropout_mask = None
| class SimpleRNNCell(Layer):
self.dropout = min(1., max(0., dropout))
self.recurrent_dropout = min(1., max(0., recurrent_dropout))
self.state_size = self.units
self.output_size = self.units
self._dropout_mask = None
self._recurrent_dropout_mask = None
| pytest tests/keras/layers/recurrent_test.py::test_minimal_rnn_cell_non_layer_multiple_states |
keras | 19 | class GRUCell(Layer):
self.implementation = implementation
self.reset_after = reset_after
self.state_size = self.units
self._dropout_mask = None
self._recurrent_dropout_mask = None
| class GRUCell(Layer):
self.implementation = implementation
self.reset_after = reset_after
self.state_size = self.units
self.output_size = self.units
self._dropout_mask = None
self._recurrent_dropout_mask = None
| pytest tests/keras/layers/recurrent_test.py::test_minimal_rnn_cell_non_layer_multiple_states |
keras | 19 | class LSTMCell(Layer):
self.recurrent_dropout = min(1., max(0., recurrent_dropout))
self.implementation = implementation
self.state_size = (self.units, self.units)
self._dropout_mask = None
self._recurrent_dropout_mask = None
| class LSTMCell(Layer):
self.recurrent_dropout = min(1., max(0., recurrent_dropout))
self.implementation = implementation
self.state_size = (self.units, self.units)
self.output_size = self.units
self._dropout_mask = None
self._recurrent_dropout_mask = None
| pytest tests/keras/layers/recurrent_test.py::test_minimal_rnn_cell_non_layer_multiple_states |
thefuck | 7 | from thefuck.utils import replace_argument, for_app
@for_app('php')
def match(command):
return "php -s" in command.script
def get_new_command(command):
return replace_argument(command.script, "-s", "-S")
requires_output = False | from thefuck.utils import replace_argument, for_app
@for_app('php')
def match(command):
return " -s " in command.script
def get_new_command(command):
return replace_argument(command.script, "-s", "-S") | pytest tests/rules/test_php_s.py::test_match |
tqdm | 8 | class tqdm(object):
# Format left/right sides of the bar, and format the bar
# later in the remaining space (avoid breaking display)
l_bar_user, r_bar_user = bar_format.split('{bar}')
l_bar, r_bar = l_bar.format(**bar_args), r_bar.format(**... | class tqdm(object):
# Format left/right sides of the bar, and format the bar
# later in the remaining space (avoid breaking display)
l_bar_user, r_bar_user = bar_format.split('{bar}')
l_bar, r_bar = l_bar_user.format(**bar_args), r_bar_user... | python3 -m pytest tqdm/tests/tests_tqdm.py::test_format_meter |
black | 6 | from blib2to3 import pygram, pytree
from blib2to3.pgen2 import driver, token
from blib2to3.pgen2.grammar import Grammar
from blib2to3.pgen2.parse import ParseError
__version__ = "19.3b0" | from blib2to3 import pygram, pytree
from blib2to3.pgen2 import driver, token
from blib2to3.pgen2.grammar import Grammar
from blib2to3.pgen2.parse import ParseError
from blib2to3.pgen2.tokenize import TokenizerConfig
__version__ = "19.3b0" | python -m unittest -q tests.test_black.BlackTestCase.test_python37 |
black | 6 | class Feature(Enum):
NUMERIC_UNDERSCORES = 3
TRAILING_COMMA_IN_CALL = 4
TRAILING_COMMA_IN_DEF = 5
VERSION_TO_FEATURES: Dict[TargetVersion, Set[Feature]] = {
TargetVersion.PY27: set(),
TargetVersion.PY33: {Feature.UNICODE_LITERALS},
TargetVersion.PY34: {Feature.UNICODE_LITERALS},
TargetVers... | class Feature(Enum):
NUMERIC_UNDERSCORES = 3
TRAILING_COMMA_IN_CALL = 4
TRAILING_COMMA_IN_DEF = 5
# The following two feature-flags are mutually exclusive, and exactly one should be
# set for every version of python.
ASYNC_IS_VALID_IDENTIFIER = 6
ASYNC_IS_RESERVED_KEYWORD = 7
VERSION_TO_FE... | python -m unittest -q tests.test_black.BlackTestCase.test_python37 |
black | 6 | VERSION_TO_FEATURES: Dict[TargetVersion, Set[Feature]] = {
Feature.NUMERIC_UNDERSCORES,
Feature.TRAILING_COMMA_IN_CALL,
Feature.TRAILING_COMMA_IN_DEF,
},
TargetVersion.PY38: {
Feature.UNICODE_LITERALS, | VERSION_TO_FEATURES: Dict[TargetVersion, Set[Feature]] = {
Feature.NUMERIC_UNDERSCORES,
Feature.TRAILING_COMMA_IN_CALL,
Feature.TRAILING_COMMA_IN_DEF,
Feature.ASYNC_IS_RESERVED_KEYWORD,
},
TargetVersion.PY38: {
Feature.UNICODE_LITERALS, | python -m unittest -q tests.test_black.BlackTestCase.test_python37 |
black | 6 | VERSION_TO_FEATURES: Dict[TargetVersion, Set[Feature]] = {
Feature.NUMERIC_UNDERSCORES,
Feature.TRAILING_COMMA_IN_CALL,
Feature.TRAILING_COMMA_IN_DEF,
},
}
| VERSION_TO_FEATURES: Dict[TargetVersion, Set[Feature]] = {
Feature.NUMERIC_UNDERSCORES,
Feature.TRAILING_COMMA_IN_CALL,
Feature.TRAILING_COMMA_IN_DEF,
Feature.ASYNC_IS_RESERVED_KEYWORD,
},
}
| python -m unittest -q tests.test_black.BlackTestCase.test_python37 |
black | 6 | def decode_bytes(src: bytes) -> Tuple[FileContent, Encoding, NewLine]:
return tiow.read(), encoding, newline
def get_grammars(target_versions: Set[TargetVersion]) -> List[Grammar]:
if not target_versions:
# No target_version specified, so try all grammars.
return [
pygram.pytho... | def decode_bytes(src: bytes) -> Tuple[FileContent, Encoding, NewLine]:
return tiow.read(), encoding, newline
@dataclass(frozen=True)
class ParserConfig:
grammar: Grammar
tokenizer_config: TokenizerConfig = TokenizerConfig()
def get_parser_configs(target_versions: Set[TargetVersion]) -> List[ParserCo... | python -m unittest -q tests.test_black.BlackTestCase.test_python37 |
black | 6 | def lib2to3_parse(src_txt: str, target_versions: Iterable[TargetVersion] = ()) -
if src_txt[-1:] != "\n":
src_txt += "\n"
for grammar in get_grammars(set(target_versions)):
drv = driver.Driver(grammar, pytree.convert)
try:
result = drv.parse_string(src_txt, True)
... | def lib2to3_parse(src_txt: str, target_versions: Iterable[TargetVersion] = ()) -
if src_txt[-1:] != "\n":
src_txt += "\n"
for parser_config in get_parser_configs(set(target_versions)):
drv = driver.Driver(
parser_config.grammar,
pytree.convert,
tokenizer_conf... | python -m unittest -q tests.test_black.BlackTestCase.test_python37 |
black | 6 | from . import grammar, parse, token, tokenize, pgen
class Driver(object):
def __init__(self, grammar, convert=None, logger=None):
self.grammar = grammar
if logger is None:
logger = logging.getLogger(__name__)
self.logger = logger
self.convert = convert
def parse_to... | from . import grammar, parse, token, tokenize, pgen
class Driver(object):
def __init__(
self,
grammar,
convert=None,
logger=None,
tokenizer_config=tokenize.TokenizerConfig(),
):
self.grammar = grammar
if logger is None:
logger = logging.getLo... | python -m unittest -q tests.test_black.BlackTestCase.test_python37 |
black | 6 | class Driver(object):
def parse_stream_raw(self, stream, debug=False):
"""Parse a stream and return the syntax tree."""
tokens = tokenize.generate_tokens(stream.readline)
return self.parse_tokens(tokens, debug)
def parse_stream(self, stream, debug=False): | class Driver(object):
def parse_stream_raw(self, stream, debug=False):
"""Parse a stream and return the syntax tree."""
tokens = tokenize.generate_tokens(stream.readline, config=self.tokenizer_config)
return self.parse_tokens(tokens, debug)
def parse_stream(self, stream, debug=False): | python -m unittest -q tests.test_black.BlackTestCase.test_python37 |
black | 6 | class Driver(object):
def parse_string(self, text, debug=False):
"""Parse a string and return the syntax tree."""
tokens = tokenize.generate_tokens(io.StringIO(text).readline)
return self.parse_tokens(tokens, debug)
def _partially_consume_prefix(self, prefix, column): | class Driver(object):
def parse_string(self, text, debug=False):
"""Parse a string and return the syntax tree."""
tokens = tokenize.generate_tokens(
io.StringIO(text).readline,
config=self.tokenizer_config,
)
return self.parse_tokens(tokens, debug)
def _... | python -m unittest -q tests.test_black.BlackTestCase.test_python37 |
black | 6 | __credits__ = \
import re
from codecs import BOM_UTF8, lookup
from blib2to3.pgen2.token import *
from . import token | __credits__ = \
import re
from codecs import BOM_UTF8, lookup
from attr import dataclass
from blib2to3.pgen2.token import *
from . import token | python -m unittest -q tests.test_black.BlackTestCase.test_python37 |
black | 6 | single_quoted = (
tabsize = 8
class TokenError(Exception): pass
class StopTokenizing(Exception): pass | single_quoted = (
tabsize = 8
@dataclass(frozen=True)
class TokenizerConfig:
async_is_reserved_keyword: bool = False
class TokenError(Exception): pass
class StopTokenizing(Exception): pass | python -m unittest -q tests.test_black.BlackTestCase.test_python37 |
black | 6 | def untokenize(iterable):
ut = Untokenizer()
return ut.untokenize(iterable)
def generate_tokens(readline):
"""
The generate_tokens() generator requires one argument, readline, which
must be a callable object which provides the same interface as the | def untokenize(iterable):
ut = Untokenizer()
return ut.untokenize(iterable)
def generate_tokens(readline, config: TokenizerConfig = TokenizerConfig()):
"""
The generate_tokens() generator requires one argument, readline, which
must be a callable object which provides the same interface as the | python -m unittest -q tests.test_black.BlackTestCase.test_python37 |
black | 6 | def generate_tokens(readline):
contline = None
indents = [0]
# 'stashed' and 'async_*' are used for async/await parsing
stashed = None
async_def = False | def generate_tokens(readline):
contline = None
indents = [0]
# If we know we're parsing 3.7+, we can unconditionally parse `async` and
# `await` as keywords.
async_is_reserved_keyword = config.async_is_reserved_keyword
# 'stashed' and 'async_*' are used for async/await parsing
stashed = Non... | python -m unittest -q tests.test_black.BlackTestCase.test_python37 |
black | 6 | def generate_tokens(readline):
yield (STRING, token, spos, epos, line)
elif initial.isidentifier(): # ordinary name
if token in ('async', 'await'):
if async_def:
yield (ASYNC if token == 'async'... | def generate_tokens(readline):
yield (STRING, token, spos, epos, line)
elif initial.isidentifier(): # ordinary name
if token in ('async', 'await'):
if async_is_reserved_keyword or async_def:
yie... | python -m unittest -q tests.test_black.BlackTestCase.test_python37 |
black | 6 | async def func():
self.async_inc, arange(8), batch_size=3
)
]
# output
| async def func():
self.async_inc, arange(8), batch_size=3
)
]
def awaited_generator_value(n):
return (await awaitable for awaitable in awaitable_list)
def make_arange(n):
return (i * 2 for i in range(n) if await wrap(i))
# output
| python -m unittest -q tests.test_black.BlackTestCase.test_python37 |
black | 6 | async def func():
self.async_inc, arange(8), batch_size=3
)
] | async def func():
self.async_inc, arange(8), batch_size=3
)
]
def awaited_generator_value(n):
return (await awaitable for awaitable in awaitable_list)
def make_arange(n):
return (i * 2 for i in range(n) if await wrap(i)) | python -m unittest -q tests.test_black.BlackTestCase.test_python37 |
scrapy | 11 | def gunzip(data):
# contains the whole page content
if output or getattr(f, 'extrabuf', None):
try:
output += f.extrabuf
finally:
break
else: | def gunzip(data):
# contains the whole page content
if output or getattr(f, 'extrabuf', None):
try:
output += f.extrabuf[-f.extrasize:]
finally:
break
else: | python -m unittest -q tests.test_utils_gz.GunzipTest.test_gunzip_illegal_eof |
spacy | 5 | class Language(object):
kwargs = component_cfg.get(name, {})
kwargs.setdefault("batch_size", batch_size)
if not hasattr(pipe, "pipe"):
docs = _pipe(pipe, docs, kwargs)
else:
docs = pipe.pipe(docs, **kwargs)
for doc, gold in zip(docs... | class Language(object):
kwargs = component_cfg.get(name, {})
kwargs.setdefault("batch_size", batch_size)
if not hasattr(pipe, "pipe"):
docs = _pipe(docs, pipe, kwargs)
else:
docs = pipe.pipe(docs, **kwargs)
for doc, gold in zip(docs... | py.test spacy/tests/test_language.py::test_evaluate_no_pipe |
keras | 22 | class InputLayer(Layer):
self.trainable = False
self.built = True
self.sparse = sparse
if input_shape and batch_input_shape:
raise ValueError('Only provide the input_shape OR ' | class InputLayer(Layer):
self.trainable = False
self.built = True
self.sparse = sparse
self.supports_masking = True
if input_shape and batch_input_shape:
raise ValueError('Only provide the input_shape OR ' | pytest tests/keras/layers/core_test.py::test_sequential_as_downstream_of_masking_layer |
luigi | 4 | class S3CopyToTable(rdbms.CopyToTable, _CredentialsMixin):
"""
logger.info("Inserting file: %s", f)
colnames = ''
if len(self.columns) > 0:
colnames = ",".join([x[0] for x in self.columns])
colnames = '({})'.format(colnames)
| class S3CopyToTable(rdbms.CopyToTable, _CredentialsMixin):
"""
logger.info("Inserting file: %s", f)
colnames = ''
if self.columns and len(self.columns) > 0:
colnames = ",".join([x[0] for x in self.columns])
colnames = '({})'.format(colnames)
| pytest test/contrib/redshift_test.py::TestS3CopyToTable::test_s3_copy_with_nonetype_columns |
pandas | 116 | class _MergeOperation:
)
]
else:
left_keys = [self.left.index.values]
if left_drop:
self.left = self.left._drop_labels_or_levels(left_drop) | class _MergeOperation:
)
]
else:
left_keys = [self.left.index._values]
if left_drop:
self.left = self.left._drop_labels_or_levels(left_drop) | pytest pandas/tests/reshape/merge/test_merge_asof.py::TestAsOfMerge::test_merge_index_column_tz |
ansible | 12 | RETURN = """
- values from the environment variables.
type: list
"""
import os
from ansible.plugins.lookup import LookupBase
class LookupModule(LookupBase): | RETURN = """
- values from the environment variables.
type: list
"""
from ansible.plugins.lookup import LookupBase
from ansible.utils import py3compat
class LookupModule(LookupBase): | pytest test/units/plugins/lookup/test_env.py |
ansible | 12 | class LookupModule(LookupBase):
ret = []
for term in terms:
var = term.split()[0]
ret.append(os.getenv(var, ''))
return ret | class LookupModule(LookupBase):
ret = []
for term in terms:
var = term.split()[0]
ret.append(py3compat.environ.get(var, ''))
return ret | pytest test/units/plugins/lookup/test_env.py |
scrapy | 4 | class ContractsManager(object):
def eb_wrapper(failure):
case = _create_testcase(method, 'errback')
exc_info = failure.value, failure.type, failure.getTracebackObject()
results.addError(case, exc_info)
request.callback = cb_wrapper | class ContractsManager(object):
def eb_wrapper(failure):
case = _create_testcase(method, 'errback')
exc_info = failure.type, failure.value, failure.getTracebackObject()
results.addError(case, exc_info)
request.callback = cb_wrapper | python -m unittest -q tests.test_contracts.ContractsManagerTest.test_errback |
pandas | 25 | default 'raise'
"""
from pandas import DataFrame
sarray = fields.build_isocalendar_sarray(self.asi8)
iso_calendar_df = DataFrame(
sarray, columns=["year", "week", "day"], dtype="UInt32"
) | default 'raise'
"""
from pandas import DataFrame
if self.tz is not None and not timezones.is_utc(self.tz):
values = self._local_timestamps()
else:
values = self.asi8
sarray = fields.build_isocalendar_sarray(values)
iso_calendar_df = DataFrame(
... | pytest pandas/tests/indexes/datetimes/test_misc.py::test_isocalendar_returns_correct_values_close_to_new_year_with_tz |
tornado | 16 | class WaitIterator(object):
self.current_index = self.current_future = None
self._running_future = None
self_ref = weakref.ref(self)
for future in futures:
future.add_done_callback(functools.partial( | class WaitIterator(object):
self.current_index = self.current_future = None
self._running_future = None
# Use a weak reference to self to avoid cycles that may delay
# garbage collection.
self_ref = weakref.ref(self)
for future in futures:
future.add_done_cal... | python -m unittest -q tornado.test.gen_test.WaitIteratorTest.test_no_ref |
tornado | 16 | class WaitIterator(object):
the inputs.
"""
self._running_future = TracebackFuture()
if self._finished:
self._return_result(self._finished.popleft()) | class WaitIterator(object):
the inputs.
"""
self._running_future = TracebackFuture()
# As long as there is an active _running_future, we must
# ensure that the WaitIterator is not GC'd (due to the
# use of weak references in __init__). Add a callback that
# refere... | python -m unittest -q tornado.test.gen_test.WaitIteratorTest.test_no_ref |
scrapy | 30 | def _iter_command_classes(module_name):
# TODO: add `name` attribute to commands and and merge this function with
# scrapy.utils.spider.iter_spider_classes
for module in walk_modules(module_name):
for obj in vars(module).itervalues():
if inspect.isclass(obj) and \
issubcla... | def _iter_command_classes(module_name):
# TODO: add `name` attribute to commands and and merge this function with
# scrapy.utils.spider.iter_spider_classes
for module in walk_modules(module_name):
for obj in vars(module).values():
if inspect.isclass(obj) and \
issubcl... | python -m unittest -q tests.test_command_version.VersionTest.test_output |
scrapy | 30 | class TestProcessProtocol(protocol.ProcessProtocol):
def __init__(self):
self.deferred = defer.Deferred()
self.out = ''
self.err = ''
self.exitcode = None
def outReceived(self, data): | class TestProcessProtocol(protocol.ProcessProtocol):
def __init__(self):
self.deferred = defer.Deferred()
self.out = b''
self.err = b''
self.exitcode = None
def outReceived(self, data): | python -m unittest -q tests.test_command_version.VersionTest.test_output |
scrapy | 30 | class CmdlineTest(unittest.TestCase):
self.env['SCRAPY_SETTINGS_MODULE'] = 'tests.test_cmdline.settings'
def _execute(self, *new_args, **kwargs):
args = (sys.executable, '-m', 'scrapy.cmdline') + new_args
proc = Popen(args, stdout=PIPE, stderr=PIPE, env=self.env, **kwargs)
comm = pr... | class CmdlineTest(unittest.TestCase):
self.env['SCRAPY_SETTINGS_MODULE'] = 'tests.test_cmdline.settings'
def _execute(self, *new_args, **kwargs):
encoding = getattr(sys.stdout, 'encoding') or 'utf-8'
args = (sys.executable, '-m', 'scrapy.cmdline') + new_args
proc = Popen(args, stdou... | python -m unittest -q tests.test_command_version.VersionTest.test_output |
black | 10 | class Driver(object):
current_line = ""
current_column = 0
wait_for_nl = False
elif char == ' ':
current_column += 1
elif char == '\t':
current_column += 4
elif char == '\n':
#... | class Driver(object):
current_line = ""
current_column = 0
wait_for_nl = False
elif char in ' \t':
current_column += 1
elif char == '\n':
# unexpected empty line
current_column = 0 | python -m unittest -q tests.test_black.BlackTestCase.test_comment_indentation |
pandas | 158 | class Series(base.IndexOpsMixin, generic.NDFrame):
"""
kwargs["inplace"] = validate_bool_kwarg(kwargs.get("inplace", False), "inplace")
non_mapping = is_scalar(index) or (
is_list_like(index) and not is_dict_like(index)
)
if non_mapping:
return self._set_... | class Series(base.IndexOpsMixin, generic.NDFrame):
"""
kwargs["inplace"] = validate_bool_kwarg(kwargs.get("inplace", False), "inplace")
if callable(index) or is_dict_like(index):
return super().rename(index=index, **kwargs)
else:
return self._set_name(index, inpl... | pytest pandas/tests/series/test_alter_axes.py::TestSeriesAlterAxes::test_rename_with_custom_indexer_inplace |
pandas | 137 | from pandas.core.algorithms import (
)
from pandas.core.base import NoNewAttributesMixin, PandasObject, _shared_docs
import pandas.core.common as com
from pandas.core.construction import extract_array, sanitize_array
from pandas.core.missing import interpolate_2d
from pandas.core.sorting import nargsort
| from pandas.core.algorithms import (
)
from pandas.core.base import NoNewAttributesMixin, PandasObject, _shared_docs
import pandas.core.common as com
from pandas.core.construction import array, extract_array, sanitize_array
from pandas.core.missing import interpolate_2d
from pandas.core.sorting import nargsort
| pytest pandas/tests/reshape/merge/test_merge.py::test_merge_on_cat_and_ext_array |
pandas | 137 | class Categorical(ExtensionArray, PandasObject):
if dtype == self.dtype:
return self
return self._set_dtype(dtype)
if is_integer_dtype(dtype) and self.isna().any():
msg = "Cannot convert float NaN to integer"
raise ValueError(msg) | class Categorical(ExtensionArray, PandasObject):
if dtype == self.dtype:
return self
return self._set_dtype(dtype)
if is_extension_array_dtype(dtype):
return array(self, dtype=dtype, copy=copy) # type: ignore # GH 28770
if is_integer_dtype(dtype) and ... | pytest pandas/tests/reshape/merge/test_merge.py::test_merge_on_cat_and_ext_array |
tornado | 8 | class WebSocketProtocol13(WebSocketProtocol):
def accept_connection(self):
try:
self._handle_websocket_headers()
self._accept_connection()
except ValueError:
gen_log.debug("Malformed WebSocket request received", | class WebSocketProtocol13(WebSocketProtocol):
def accept_connection(self):
try:
self._handle_websocket_headers()
except ValueError:
self.handler.set_status(400)
log_msg = "Missing/Invalid WebSocket headers"
self.handler.finish(log_msg)
gen_... | python -m unittest -q tornado.test.websocket_test.WebSocketTest.test_missing_websocket_key |
pandas | 96 | class BusinessHourMixin(BusinessMixin):
# adjust by business days first
if bd != 0:
skip_bd = BusinessDay(n=bd)
# midnight business hour may not on BusinessDay
if not self.next_bday.is_on_offset(other):
prev_open = self._prev_o... | class BusinessHourMixin(BusinessMixin):
# adjust by business days first
if bd != 0:
if isinstance(self, _CustomMixin): # GH 30593
skip_bd = CustomBusinessDay(
n=bd,
weekmask=self.weekmask,
... | pytest pandas/tests/indexes/datetimes/test_date_range.py::test_date_range_with_custom_holidays |
luigi | 12 | The implementations of the hdfs clients. The hadoop cli client and the
snakebite client.
"""
from luigi.contrib.hdfs import config as hdfs_config
from luigi.contrib.hdfs import snakebite_client as hdfs_snakebite_client
from luigi.contrib.hdfs import webhdfs_client as hdfs_webhdfs_client
from luigi.contrib.hdfs import... | The implementations of the hdfs clients. The hadoop cli client and the
snakebite client.
"""
import logging
import threading
from luigi.contrib.hdfs import config as hdfs_config
from luigi.contrib.hdfs import snakebite_client as hdfs_snakebite_client
from luigi.contrib.hdfs import webhdfs_client as hdfs_webhdfs_client... | pytest test/hdfs_client_test.py::HdfsClientTest::test_get_autoconfig_client_cached |
pandas | 154 | class GroupBy(_GroupBy):
base_func = getattr(libgroupby, how)
for name, obj in self._iterate_slices():
if aggregate:
result_sz = ngroups
else:
result_sz = len(obj.values)
if not cython_dtype:
cython_dtype = obj.values.... | class GroupBy(_GroupBy):
base_func = getattr(libgroupby, how)
for name, obj in self._iterate_slices():
values = obj._data._values
if aggregate:
result_sz = ngroups
else:
result_sz = len(values)
if not cython_dtype:
... | pytest pandas/tests/groupby/test_groupby.py::test_shift_bfill_ffill_tz |
pandas | 154 | class GroupBy(_GroupBy):
func(**kwargs) # Call func to modify indexer values in place
if result_is_index:
result = algorithms.take_nd(obj.values, result)
if post_processing:
result = post_processing(result, inferences) | class GroupBy(_GroupBy):
func(**kwargs) # Call func to modify indexer values in place
if result_is_index:
result = algorithms.take_nd(values, result)
if post_processing:
result = post_processing(result, inferences) | pytest pandas/tests/groupby/test_groupby.py::test_shift_bfill_ffill_tz |
matplotlib | 21 | class Axes(_AxesBase):
zdelta = 0.1
def line_props_with_rcdefaults(subkey, explicit, zdelta=0):
d = {k.split('.')[-1]: v for k, v in rcParams.items()
if k.startswith(f'boxplot.{subkey}')}
d['zorder'] = zorder + zdelta
if explicit is not None:
... | class Axes(_AxesBase):
zdelta = 0.1
def line_props_with_rcdefaults(subkey, explicit, zdelta=0,
use_marker=True):
d = {k.split('.')[-1]: v for k, v in rcParams.items()
if k.startswith(f'boxplot.{subkey}')}
d['zorder'] = zor... | pytest lib/matplotlib/tests/test_axes.py::test_boxplot_marker_behavior |
matplotlib | 21 | class Axes(_AxesBase):
cbook.normalize_kwargs(
boxprops, mpatches.PathPatch._alias_map))
else:
final_boxprops = line_props_with_rcdefaults('boxprops', boxprops)
final_whiskerprops = line_props_with_rcdefaults(
'whiskerprops', whiskerpro... | class Axes(_AxesBase):
cbook.normalize_kwargs(
boxprops, mpatches.PathPatch._alias_map))
else:
final_boxprops = line_props_with_rcdefaults('boxprops', boxprops,
use_marker=False)
final_whisker... | pytest lib/matplotlib/tests/test_axes.py::test_boxplot_marker_behavior |
youtube-dl | 16 | class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor):
dfxp_file = old_file
srt_file = subtitles_filename(filename, lang, 'srt')
with io.open(dfxp_file, 'rt', encoding='utf-8') as f:
srt_data = dfxp2srt(f.read())
with io.open(srt_file... | class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor):
dfxp_file = old_file
srt_file = subtitles_filename(filename, lang, 'srt')
with open(dfxp_file, 'rb') as f:
srt_data = dfxp2srt(f.read())
with io.open(srt_file, 'wt', encoding='utf... | python -m unittest -q test.test_utils.TestUtil.test_dfxp2srt |
youtube-dl | 16 | def srt_subtitles_timecode(seconds):
def dfxp2srt(dfxp_data):
LEGACY_NAMESPACES = (
('http://www.w3.org/ns/ttml', [
'http://www.w3.org/2004/11/ttaf1',
'http://www.w3.org/2006/04/ttaf1',
'http://www.w3.org/2006/10/ttaf1',
]),
('http://www.w3.org/ns/ttml#s... | def srt_subtitles_timecode(seconds):
def dfxp2srt(dfxp_data):
'''
@param dfxp_data A bytes-like object containing DFXP data
@returns A unicode object containing converted SRT data
'''
LEGACY_NAMESPACES = (
(b'http://www.w3.org/ns/ttml', [
b'http://www.w3.org/2004/11/ttaf1',
... | python -m unittest -q test.test_utils.TestUtil.test_dfxp2srt |
youtube-dl | 16 | def dfxp2srt(dfxp_data):
for ns in v:
dfxp_data = dfxp_data.replace(ns, k)
dfxp = compat_etree_fromstring(dfxp_data.encode('utf-8'))
out = []
paras = dfxp.findall(_x('.//ttml:p')) or dfxp.findall('.//p')
| def dfxp2srt(dfxp_data):
for ns in v:
dfxp_data = dfxp_data.replace(ns, k)
dfxp = compat_etree_fromstring(dfxp_data)
out = []
paras = dfxp.findall(_x('.//ttml:p')) or dfxp.findall('.//p')
| python -m unittest -q test.test_utils.TestUtil.test_dfxp2srt |
tornado | 4 | class StaticFileHandler(RequestHandler):
size = self.get_content_size()
if request_range:
start, end = request_range
if (start is not None and start >= size) or end == 0:
# As per RFC 2616 14.35.1, a range is not satisfiable only: if
# the first re... | class StaticFileHandler(RequestHandler):
size = self.get_content_size()
if request_range:
start, end = request_range
if start is not None and start < 0:
start += size
if start < 0:
start = 0
if (
star... | python -m unittest -q tornado.test.web_test.StaticFileTest.test_static_unsatisfiable_range_end_less_than_start |
pandas | 67 | import warnings
import numpy as np
from pandas._libs import NaT, algos as libalgos, lib, tslib, writers
from pandas._libs.index import convert_scalar
import pandas._libs.internals as libinternals
from pandas._libs.tslibs import Timedelta, conversion | import warnings
import numpy as np
from pandas._libs import NaT, Timestamp, algos as libalgos, lib, tslib, writers
from pandas._libs.index import convert_scalar
import pandas._libs.internals as libinternals
from pandas._libs.tslibs import Timedelta, conversion | pytest pandas/tests/frame/indexing/test_indexing.py::test_object_casting_indexing_wraps_datetimelike |
pandas | 67 | class DatetimeLikeBlockMixin:
# Override to return DatetimeArray and TimedeltaArray
return self.array_values()
class DatetimeBlock(DatetimeLikeBlockMixin, Block):
__slots__ = () | class DatetimeLikeBlockMixin:
# Override to return DatetimeArray and TimedeltaArray
return self.array_values()
def iget(self, key):
# GH#31649 we need to wrap scalars in Timestamp/Timedelta
# TODO: this can be removed if we ever have 2D EA
result = super().iget(key)
... | pytest pandas/tests/frame/indexing/test_indexing.py::test_object_casting_indexing_wraps_datetimelike |
pandas | 3 | Name: Max Speed, dtype: float64
if copy:
new_values = new_values.copy()
assert isinstance(self.index, PeriodIndex)
new_index = self.index.to_timestamp(freq=freq, how=how) # type: ignore
return self._constructor(new_values, index=new_index).__finalize__(
self, me... | Name: Max Speed, dtype: float64
if copy:
new_values = new_values.copy()
if not isinstance(self.index, PeriodIndex):
raise TypeError(f"unsupported Type {type(self.index).__name__}")
new_index = self.index.to_timestamp(freq=freq, how=how) # type: ignore
return sel... | pytest pandas/tests/series/methods/test_to_timestamp.py::TestToTimestamp::test_to_timestamp_raises |
pandas | 3 | Name: Max Speed, dtype: float64
if copy:
new_values = new_values.copy()
assert isinstance(self.index, DatetimeIndex)
new_index = self.index.to_period(freq=freq) # type: ignore
return self._constructor(new_values, index=new_index).__finalize__(
self, method="to_p... | Name: Max Speed, dtype: float64
if copy:
new_values = new_values.copy()
if not isinstance(self.index, DatetimeIndex):
raise TypeError(f"unsupported Type {type(self.index).__name__}")
new_index = self.index.to_period(freq=freq) # type: ignore
return self._constru... | pytest pandas/tests/series/methods/test_to_timestamp.py::TestToTimestamp::test_to_timestamp_raises |
keras | 7 | class KerasRegressor(BaseWrapper):
Predictions.
"""
kwargs = self.filter_sk_params(Sequential.predict, kwargs)
return np.squeeze(self.model.predict(x, **kwargs))
def score(self, x, y, **kwargs):
"""Returns the mean loss on the given test data and labels. | class KerasRegressor(BaseWrapper):
Predictions.
"""
kwargs = self.filter_sk_params(Sequential.predict, kwargs)
return np.squeeze(self.model.predict(x, **kwargs), axis=-1)
def score(self, x, y, **kwargs):
"""Returns the mean loss on the given test data and labels. | pytest tests/keras/wrappers/scikit_learn_test.py::test_regression_predict_shape_correct_num_test_1 |
youtube-dl | 37 | # -*- coding: utf-8 -*-
import calendar
import contextlib
import ctypes
import datetime | # -*- coding: utf-8 -*-
import calendar
import codecs
import contextlib
import ctypes
import datetime | python -m unittest -q test.test_utils.TestUtil.test_uppercase_escpae |
youtube-dl | 37 | class PagedList(object):
def uppercase_escape(s):
return re.sub(
r'\\U[0-9a-fA-F]{8}',
lambda m: m.group(0).decode('unicode-escape'), s)
try:
struct.pack(u'!I', 0) | class PagedList(object):
def uppercase_escape(s):
unicode_escape = codecs.getdecoder('unicode_escape')
return re.sub(
r'\\U[0-9a-fA-F]{8}',
lambda m: unicode_escape(m.group(0))[0],
s)
try:
struct.pack(u'!I', 0) | python -m unittest -q test.test_utils.TestUtil.test_uppercase_escpae |
pandas | 46 | class MultiIndex(Index):
if names is lib.no_default:
names = [getattr(it, "name", None) for it in iterables]
codes = cartesian_product(codes)
return MultiIndex(levels, codes, sortorder=sortorder, names=names)
| class MultiIndex(Index):
if names is lib.no_default:
names = [getattr(it, "name", None) for it in iterables]
# codes are all ndarrays, so cartesian_product is lossless
codes = cartesian_product(codes)
return MultiIndex(levels, codes, sortorder=sortorder, names=names)
| pytest pandas/tests/reshape/test_pivot.py::TestPivotTable::test_pivot_table_retains_tz |
pandas | 46 | import numpy as np
from pandas.core.dtypes.common import is_list_like
import pandas.core.common as com
def cartesian_product(X):
""" | import numpy as np
from pandas.core.dtypes.common import is_list_like
def cartesian_product(X):
""" | pytest pandas/tests/reshape/test_pivot.py::TestPivotTable::test_pivot_table_retains_tz |
pandas | 46 | def cartesian_product(X):
# if any factor is empty, the cartesian product is empty
b = np.zeros_like(cumprodX)
return [
np.tile(
np.repeat(np.asarray(com.values_from_object(x)), b[i]), np.product(a[i])
)
for i, x in enumerate(X)
] | def cartesian_product(X):
# if any factor is empty, the cartesian product is empty
b = np.zeros_like(cumprodX)
return [_tile_compat(np.repeat(x, b[i]), np.product(a[i])) for i, x in enumerate(X)]
def _tile_compat(arr, num: int):
"""
Index compat for np.tile.
Notes
-----
Does ... | pytest pandas/tests/reshape/test_pivot.py::TestPivotTable::test_pivot_table_retains_tz |
pandas | 46 | class TestCartesianProduct:
tm.assert_index_equal(result1, expected1)
tm.assert_index_equal(result2, expected2)
def test_empty(self):
# product of empty factors
X = [[], [0, 1], []] | class TestCartesianProduct:
tm.assert_index_equal(result1, expected1)
tm.assert_index_equal(result2, expected2)
def test_tzaware_retained(self):
x = date_range("2000-01-01", periods=2, tz="US/Pacific")
y = np.array([3, 4])
result1, result2 = cartesian_product([x, y])
... | pytest pandas/tests/reshape/test_pivot.py::TestPivotTable::test_pivot_table_retains_tz |
scrapy | 8 | class Field(dict):
class ItemMeta(ABCMeta):
def __new__(mcs, class_name, bases, attrs):
new_bases = tuple(base._class for base in bases if hasattr(base, '_class'))
_class = super(ItemMeta, mcs).__new__(mcs, 'x_' + class_name, new_bases, attrs)
| class Field(dict):
class ItemMeta(ABCMeta):
def __new__(mcs, class_name, bases, attrs):
classcell = attrs.pop('__classcell__', None)
new_bases = tuple(base._class for base in bases if hasattr(base, '_class'))
_class = super(ItemMeta, mcs).__new__(mcs, 'x_' + class_name, new_bases, attrs)
| python -m unittest -q tests.test_item.ItemMetaClassCellRegression.test_item_meta_classcell_regression |
scrapy | 8 | class ItemMeta(ABCMeta):
new_attrs['fields'] = fields
new_attrs['_class'] = _class
return super(ItemMeta, mcs).__new__(mcs, class_name, bases, new_attrs)
| class ItemMeta(ABCMeta):
new_attrs['fields'] = fields
new_attrs['_class'] = _class
if classcell is not None:
new_attrs['__classcell__'] = classcell
return super(ItemMeta, mcs).__new__(mcs, class_name, bases, new_attrs)
| python -m unittest -q tests.test_item.ItemMetaClassCellRegression.test_item_meta_classcell_regression |
pandas | 29 | class IntervalArray(IntervalMixin, ExtensionArray):
msg = f"'value' should be an interval type, got {type(value)} instead."
raise TypeError(msg) from err
key = check_array_indexer(self, key)
# Need to ensure that left and right are updated atomically, so we're
# ... | class IntervalArray(IntervalMixin, ExtensionArray):
msg = f"'value' should be an interval type, got {type(value)} instead."
raise TypeError(msg) from err
if needs_float_conversion:
raise ValueError("Cannot set float NaN to integer-backed IntervalArray")
key ... | pytest pandas/tests/series/methods/test_convert_dtypes.py::TestSeriesConvertDtypes::test_convert_dtypes |
luigi | 33 | class Task(object):
exc_desc = '%s[args=%s, kwargs=%s]' % (task_name, args, kwargs)
# Fill in the positional arguments
positional_params = [(n, p) for n, p in params if p.significant]
for i, arg in enumerate(args):
if i >= len(positional_params):
raise parame... | class Task(object):
exc_desc = '%s[args=%s, kwargs=%s]' % (task_name, args, kwargs)
# Fill in the positional arguments
positional_params = [(n, p) for n, p in params if not p.is_global]
for i, arg in enumerate(args):
if i >= len(positional_params):
raise para... | pytest test/parameter_test.py::TestRemoveGlobalParameters::test_mixed_params_inheritence |
thefuck | 20 | import os
import zipfile
from thefuck.utils import for_app
def _is_bad_zip(file): | import os
import zipfile
from thefuck.utils import for_app
from thefuck.shells import quote
def _is_bad_zip(file): | pytest tests/rules/test_dirty_unzip.py::test_get_new_command |
thefuck | 20 | def _zip_file(command):
# unzip [-flags] file[.zip] [file(s) ...] [-x file(s) ...]
# ^ ^ files to unzip from the archive
# archive to unzip
for c in command.script.split()[1:]:
if not c.startswith('-'):
if c.endswith('.zip'):
ret... | def _zip_file(command):
# unzip [-flags] file[.zip] [file(s) ...] [-x file(s) ...]
# ^ ^ files to unzip from the archive
# archive to unzip
for c in command.split_script[1:]:
if not c.startswith('-'):
if c.endswith('.zip'):
retur... | pytest tests/rules/test_dirty_unzip.py::test_get_new_command |
thefuck | 20 | def match(command):
def get_new_command(command):
return '{} -d {}'.format(command.script, _zip_file(command)[:-4])
def side_effect(old_cmd, command): | def match(command):
def get_new_command(command):
return '{} -d {}'.format(command.script, quote(_zip_file(command)[:-4]))
def side_effect(old_cmd, command): | pytest tests/rules/test_dirty_unzip.py::test_get_new_command |
youtube-dl | 1 | def _match_one(filter_part, dct):
return op(actual_value, comparison_value)
UNARY_OPERATORS = {
'': lambda v: v is not None,
'!': lambda v: v is None,
}
operator_rex = re.compile(r'''(?x)\s*
(?P<op>%s)\s*(?P<key>[a-z_]+) | def _match_one(filter_part, dct):
return op(actual_value, comparison_value)
UNARY_OPERATORS = {
'': lambda v: (v is True) if isinstance(v, bool) else (v is not None),
'!': lambda v: (v is False) if isinstance(v, bool) else (v is None),
}
operator_rex = re.compile(r'''(?x)\s*
... | python -m unittest -q test.test_utils.TestUtil.test_match_str |
keras | 41 | import sys
import tarfile
import threading
import time
import zipfile
from abc import abstractmethod
from multiprocessing.pool import ThreadPool | import sys
import tarfile
import threading
import time
import traceback
import zipfile
from abc import abstractmethod
from multiprocessing.pool import ThreadPool | pytest tests/keras/utils/data_utils_test.py::test_generator_enqueuer_fail_threads |
keras | 41 | class OrderedEnqueuer(SequenceEnqueuer):
yield inputs
except Exception as e:
self.stop()
raise StopIteration(e)
def _send_sequence(self):
"""Send current Sequence to all workers.""" | class OrderedEnqueuer(SequenceEnqueuer):
yield inputs
except Exception as e:
self.stop()
six.raise_from(StopIteration(e), e)
def _send_sequence(self):
"""Send current Sequence to all workers.""" | pytest tests/keras/utils/data_utils_test.py::test_generator_enqueuer_fail_threads |
keras | 41 | class GeneratorEnqueuer(SequenceEnqueuer):
self._use_multiprocessing = use_multiprocessing
self._threads = []
self._stop_event = None
self.queue = None
self.seed = seed
| class GeneratorEnqueuer(SequenceEnqueuer):
self._use_multiprocessing = use_multiprocessing
self._threads = []
self._stop_event = None
self._manager = None
self.queue = None
self.seed = seed
| pytest tests/keras/utils/data_utils_test.py::test_generator_enqueuer_fail_threads |
keras | 41 | class GeneratorEnqueuer(SequenceEnqueuer):
try:
if self._use_multiprocessing or self.queue.qsize() < max_queue_size:
generator_output = next(self._generator)
self.queue.put(generator_output)
else:
... | class GeneratorEnqueuer(SequenceEnqueuer):
try:
if self._use_multiprocessing or self.queue.qsize() < max_queue_size:
generator_output = next(self._generator)
self.queue.put((True, generator_output))
else:
... | pytest tests/keras/utils/data_utils_test.py::test_generator_enqueuer_fail_threads |
keras | 41 | class GeneratorEnqueuer(SequenceEnqueuer):
else:
thread.join(timeout)
if self._use_multiprocessing:
if self.queue is not None:
self.queue.close()
self._threads = []
self._stop_event = None | class GeneratorEnqueuer(SequenceEnqueuer):
else:
thread.join(timeout)
if self._manager:
self._manager.shutdown()
self._threads = []
self._stop_event = None | pytest tests/keras/utils/data_utils_test.py::test_generator_enqueuer_fail_threads |
keras | 41 | class GeneratorEnqueuer(SequenceEnqueuer):
"""
while self.is_running():
if not self.queue.empty():
inputs = self.queue.get()
if inputs is not None:
yield inputs
else:
all_finished = all([not thread.is_alive() for... | class GeneratorEnqueuer(SequenceEnqueuer):
"""
while self.is_running():
if not self.queue.empty():
success, value = self.queue.get()
# Rethrow any exceptions found in the queue
if not success:
six.reraise(value.__class__, va... | pytest tests/keras/utils/data_utils_test.py::test_generator_enqueuer_fail_threads |
keras | 41 | def test_multiprocessing_fit_error():
"""Raises an exception after a few good batches"""
for i in range(good_batches):
yield (np.random.randint(batch_size, 256, (50, 2)),
np.random.randint(batch_size, 2, 50))
raise RuntimeError
model = Sequential() | def test_multiprocessing_fit_error():
"""Raises an exception after a few good batches"""
for i in range(good_batches):
yield (np.random.randint(batch_size, 256, (50, 2)),
np.random.randint(batch_size, 12, 50))
raise RuntimeError
model = Sequential() | pytest tests/keras/utils/data_utils_test.py::test_generator_enqueuer_fail_threads |
keras | 41 | def test_multiprocessing_fit_error():
samples = batch_size * (good_batches + 1)
with pytest.raises(StopIteration):
model.fit_generator(
custom_generator(), samples, 1,
workers=4, use_multiprocessing=True,
)
with pytest.raises(StopIteration):
model.fit_gener... | def test_multiprocessing_fit_error():
samples = batch_size * (good_batches + 1)
with pytest.raises(RuntimeError):
model.fit_generator(
custom_generator(), samples, 1,
workers=4, use_multiprocessing=True,
)
with pytest.raises(RuntimeError):
model.fit_generat... | pytest tests/keras/utils/data_utils_test.py::test_generator_enqueuer_fail_threads |
keras | 41 | def test_multiprocessing_fit_error():
def test_multiprocessing_evaluate_error():
batch_size = 10
good_batches = 3
def custom_generator():
"""Raises an exception after a few good batches"""
for i in range(good_batches):
yield (np.random.randint(batch_size, 256, (50, 2)),
... | def test_multiprocessing_fit_error():
def test_multiprocessing_evaluate_error():
batch_size = 10
good_batches = 3
workers = 4
def custom_generator():
"""Raises an exception after a few good batches"""
for i in range(good_batches):
yield (np.random.randint(batch_size, 256, (5... | pytest tests/keras/utils/data_utils_test.py::test_generator_enqueuer_fail_threads |
keras | 41 | def test_multiprocessing_predict_error():
model.add(Dense(1, input_shape=(5,)))
model.compile(loss='mse', optimizer='adadelta')
with pytest.raises(StopIteration):
model.predict_generator(
custom_generator(), good_batches * workers + 1, 1,
workers=workers, use_multiprocessing... | def test_multiprocessing_predict_error():
model.add(Dense(1, input_shape=(5,)))
model.compile(loss='mse', optimizer='adadelta')
with pytest.raises(RuntimeError):
model.predict_generator(
custom_generator(), good_batches * workers + 1, 1,
workers=workers, use_multiprocessing=... | pytest tests/keras/utils/data_utils_test.py::test_generator_enqueuer_fail_threads |
tqdm | 4 | class tqdm(Comparable):
# apply custom scale if necessary
if unit_scale and unit_scale not in (True, 1):
total *= unit_scale
n *= unit_scale
if rate:
rate *= unit_scale # by default rate = 1 / self.avg_time | class tqdm(Comparable):
# apply custom scale if necessary
if unit_scale and unit_scale not in (True, 1):
if total:
total *= unit_scale
n *= unit_scale
if rate:
rate *= unit_scale # by default rate = 1 / self.avg_time | python3 -m pytest tqdm/tests/tests_tqdm.py::test_nototal |
ansible | 7 | def generate_commands(vlan_id, to_set, to_remove):
if "vlan_id" in to_remove:
return ["no vlan {0}".format(vlan_id)]
for key, value in to_set.items():
if key == "vlan_id" or value is None:
continue
commands.append("{0} {1}".format(key, value))
for key in to_remove:
... | def generate_commands(vlan_id, to_set, to_remove):
if "vlan_id" in to_remove:
return ["no vlan {0}".format(vlan_id)]
for key in to_remove:
if key in to_set.keys():
continue
commands.append("no {0}".format(key))
for key, value in to_set.items():
if key == "vlan_i... | pytest test/units/modules/network/eos/test_eos_vlans.py::TestEosVlansModule::test_eos_vlan_replaced |
spacy | 9 | class Warnings(object):
"loaded. (Shape: {shape})")
W021 = ("Unexpected hash collision in PhraseMatcher. Matches may be "
"incorrect. Modify PhraseMatcher._terminal_hash to fix.")
@add_codes | class Warnings(object):
"loaded. (Shape: {shape})")
W021 = ("Unexpected hash collision in PhraseMatcher. Matches may be "
"incorrect. Modify PhraseMatcher._terminal_hash to fix.")
W022 = ("Training a new part-of-speech tagger using a model with no "
"lemmatization rules or da... | py.test spacy/tests/pipeline/test_tagger.py::test_tagger_warns_no_lemma_lookups |
luigi | 8 | class S3CopyToTable(rdbms.CopyToTable):
if '.' in self.table:
query = ("select 1 as table_exists "
"from information_schema.tables "
"where table_schema = %s and table_name = %s limit 1")
else:
query = ("select 1 as table_exists "
... | class S3CopyToTable(rdbms.CopyToTable):
if '.' in self.table:
query = ("select 1 as table_exists "
"from information_schema.tables "
"where table_schema = lower(%s) and table_name = lower(%s) limit 1")
else:
query = ("select 1 as table_ex... | pytest test/contrib/redshift_test.py::TestS3CopyToSchemaTable::test_s3_copy_to_table |
matplotlib | 19 | class RadialLocator(mticker.Locator):
:class:`~matplotlib.ticker.Locator` (which may be different
depending on the scale of the *r*-axis.
"""
def __init__(self, base, axes=None):
self.base = base
self._axes = axes | class RadialLocator(mticker.Locator):
:class:`~matplotlib.ticker.Locator` (which may be different
depending on the scale of the *r*-axis.
"""
def __init__(self, base, axes=None):
self.base = base
self._axes = axes | pytest lib/matplotlib/tests/test_axes.py::test_polar_no_data |
matplotlib | 19 | class RadialLocator(mticker.Locator):
# docstring inherited
return self.base.refresh()
def view_limits(self, vmin, vmax):
vmin, vmax = self.base.view_limits(vmin, vmax)
if vmax > vmin: | class RadialLocator(mticker.Locator):
# docstring inherited
return self.base.refresh()
def nonsingular(self, vmin, vmax):
# docstring inherited
return ((0, 1) if (vmin, vmax) == (-np.inf, np.inf) # Init. limits.
else self.base.nonsingular(vmin, vmax))
def view_... | pytest lib/matplotlib/tests/test_axes.py::test_polar_no_data |
youtube-dl | 41 | def unified_strdate(date_str):
"""Return a string with the date in the format YYYYMMDD"""
upload_date = None
#Replace commas
date_str = date_str.replace(',',' ')
# %z (UTC offset) is only supported in python>=3.2
date_str = re.sub(r' ?(\+|-)[0-9:]*$', '', date_str)
format_expressions = [
... | def unified_strdate(date_str):
"""Return a string with the date in the format YYYYMMDD"""
upload_date = None
#Replace commas
date_str = date_str.replace(',', ' ')
# %z (UTC offset) is only supported in python>=3.2
date_str = re.sub(r' ?(\+|-)[0-9]{2}:?[0-9]{2}$', '', date_str)
format_express... | python -m unittest -q test.test_utils.TestUtil.test_unified_dates |
pandas | 30 | class Parser:
for date_unit in date_units:
try:
new_data = to_datetime(new_data, errors="raise", unit=date_unit)
except (ValueError, OverflowError):
continue
return new_data, True
return data, False | class Parser:
for date_unit in date_units:
try:
new_data = to_datetime(new_data, errors="raise", unit=date_unit)
except (ValueError, OverflowError, TypeError):
continue
return new_data, True
return data, False | pytest pandas/tests/io/json/test_pandas.py::TestPandasContainer::test_readjson_bool_series |
pandas | 103 | class SeriesGroupBy(GroupBy):
periods=periods, fill_method=fill_method, limit=limit, freq=freq
)
)
filled = getattr(self, fill_method)(limit=limit)
fill_grp = filled.groupby(self.grouper.codes)
shifted = fill_grp.shift(periods=periods, freq=freq) | class SeriesGroupBy(GroupBy):
periods=periods, fill_method=fill_method, limit=limit, freq=freq
)
)
if fill_method is None: # GH30463
fill_method = "pad"
limit = 0
filled = getattr(self, fill_method)(limit=limit)
fill_grp = ... | pytest pandas/tests/groupby/test_transform.py::test_pct_change |
pandas | 103 | class GroupBy(_GroupBy):
axis=axis,
)
)
filled = getattr(self, fill_method)(limit=limit)
fill_grp = filled.groupby(self.grouper.codes)
shifted = fill_grp.shift(periods=periods, freq=freq) | class GroupBy(_GroupBy):
axis=axis,
)
)
if fill_method is None: # GH30463
fill_method = "pad"
limit = 0
filled = getattr(self, fill_method)(limit=limit)
fill_grp = filled.groupby(self.grouper.codes)
shifted = fill_g... | pytest pandas/tests/groupby/test_transform.py::test_pct_change |
keras | 37 | class RNN(Layer):
self._num_constants = len(constants)
additional_specs += self.constants_spec
# at this point additional_inputs cannot be empty
is_keras_tensor = hasattr(additional_inputs[0], '_keras_history')
for tensor in additional_inputs:
if hasattr(tenso... | class RNN(Layer):
self._num_constants = len(constants)
additional_specs += self.constants_spec
# at this point additional_inputs cannot be empty
is_keras_tensor = K.is_keras_tensor(additional_inputs[0])
for tensor in additional_inputs:
if K.is_keras_tensor(ten... | pytest tests/keras/layers/wrappers_test.py::test_Bidirectional_state_reuse |
keras | 37 | class Bidirectional(Wrapper):
self.supports_masking = True
self._trainable = True
super(Bidirectional, self).__init__(layer, **kwargs)
@property
def trainable(self): | class Bidirectional(Wrapper):
self.supports_masking = True
self._trainable = True
super(Bidirectional, self).__init__(layer, **kwargs)
self.input_spec = layer.input_spec
@property
def trainable(self): | pytest tests/keras/layers/wrappers_test.py::test_Bidirectional_state_reuse |
keras | 37 | class Bidirectional(Wrapper):
return [output_shape] + state_shape + copy.copy(state_shape)
return output_shape
def call(self, inputs, training=None, mask=None, initial_state=None):
kwargs = {}
if has_arg(self.layer.call, 'training'): | class Bidirectional(Wrapper):
return [output_shape] + state_shape + copy.copy(state_shape)
return output_shape
def __call__(self, inputs, initial_state=None, **kwargs):
if isinstance(inputs, list):
if len(inputs) > 1:
initial_state = inputs[1:]
in... | pytest tests/keras/layers/wrappers_test.py::test_Bidirectional_state_reuse |
keras | 37 | class Bidirectional(Wrapper):
kwargs['mask'] = mask
if initial_state is not None and has_arg(self.layer.call, 'initial_state'):
if not isinstance(initial_state, list):
raise ValueError(
'When passing `initial_state` to a Bidirectional RNN, the state '... | class Bidirectional(Wrapper):
kwargs['mask'] = mask
if initial_state is not None and has_arg(self.layer.call, 'initial_state'):
forward_state = initial_state[:len(initial_state) // 2]
backward_state = initial_state[len(initial_state) // 2:]
y = self.forward_layer... | pytest tests/keras/layers/wrappers_test.py::test_Bidirectional_state_reuse |
pandas | 83 | __all__ = [
def get_objs_combined_axis(
objs, intersect: bool = False, axis=0, sort: bool = True
) -> Index:
"""
Extract combined index: return intersection or union (depending on the | __all__ = [
def get_objs_combined_axis(
objs, intersect: bool = False, axis=0, sort: bool = True, copy: bool = False
) -> Index:
"""
Extract combined index: return intersection or union (depending on the | pytest pandas/tests/reshape/test_concat.py::test_concat_copy_index |
pandas | 83 | def get_objs_combined_axis(
The axis to extract indexes from.
sort : bool, default True
Whether the result index should come out sorted or not.
Returns
-------
Index
"""
obs_idxes = [obj._get_axis(axis) for obj in objs]
return _get_combined_index(obs_idxes, intersect=interse... | def get_objs_combined_axis(
The axis to extract indexes from.
sort : bool, default True
Whether the result index should come out sorted or not.
copy : bool, default False
If True, return a copy of the combined index.
Returns
-------
Index
"""
obs_idxes = [obj._get_ax... | pytest pandas/tests/reshape/test_concat.py::test_concat_copy_index |
pandas | 83 | def _get_distinct_objs(objs: List[Index]) -> List[Index]:
def _get_combined_index(
indexes: List[Index], intersect: bool = False, sort: bool = False
) -> Index:
"""
Return the union or intersection of indexes. | def _get_distinct_objs(objs: List[Index]) -> List[Index]:
def _get_combined_index(
indexes: List[Index],
intersect: bool = False,
sort: bool = False,
copy: bool = False,
) -> Index:
"""
Return the union or intersection of indexes. | pytest pandas/tests/reshape/test_concat.py::test_concat_copy_index |
pandas | 83 | def _get_combined_index(
calculate the union.
sort : bool, default False
Whether the result index should come out sorted or not.
Returns
------- | def _get_combined_index(
calculate the union.
sort : bool, default False
Whether the result index should come out sorted or not.
copy : bool, default False
If True, return a copy of the combined index.
Returns
------- | pytest pandas/tests/reshape/test_concat.py::test_concat_copy_index |
pandas | 83 | def _get_combined_index(
index = index.sort_values()
except TypeError:
pass
return index
| def _get_combined_index(
index = index.sort_values()
except TypeError:
pass
# GH 29879
if copy:
index = index.copy()
return index
| pytest pandas/tests/reshape/test_concat.py::test_concat_copy_index |
pandas | 83 | class _Concatenator:
def _get_comb_axis(self, i: int) -> Index:
data_axis = self.objs[0]._get_block_manager_axis(i)
return get_objs_combined_axis(
self.objs, axis=data_axis, intersect=self.intersect, sort=self.sort
)
def _get_concat_axis(self) -> Index: | class _Concatenator:
def _get_comb_axis(self, i: int) -> Index:
data_axis = self.objs[0]._get_block_manager_axis(i)
return get_objs_combined_axis(
self.objs,
axis=data_axis,
intersect=self.intersect,
sort=self.sort,
copy=self.copy,
... | pytest pandas/tests/reshape/test_concat.py::test_concat_copy_index |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.