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
64
class ExcelFormatter: # Deprecated in GH#17295, enforced in 1.0.0 raise KeyError("Not all names specified in 'columns' are found") self.df = df self.columns = self.df.columns self.float_format = float_format
class ExcelFormatter: # Deprecated in GH#17295, enforced in 1.0.0 raise KeyError("Not all names specified in 'columns' are found") self.df = df.reindex(columns=cols) self.columns = self.df.columns self.float_format = float_format
pytest pandas/tests/io/excel/test_writers.py::TestExcelWriter::test_write_subset_columns
cookiecutter
3
def read_user_choice(var_name, options): )) user_choice = click.prompt( prompt, type=click.Choice(choices), default=default ) return choice_map[user_choice]
def read_user_choice(var_name, options): )) user_choice = click.prompt( prompt, type=click.Choice(choices), default=default, show_choices=False ) return choice_map[user_choice]
tox tests/test_read_user_choice.py::test_click_invocation
luigi
11
class Scheduler(object): if (best_task and batched_params and task.family == best_task.family and len(batched_tasks) < max_batch_size and task.is_batchable() and all( task.params.get(name) == value for name, value in unbatched_params.items())): for na...
class Scheduler(object): if (best_task and batched_params and task.family == best_task.family and len(batched_tasks) < max_batch_size and task.is_batchable() and all( task.params.get(name) == value for name, value in unbatched_params.items()) and ...
pytest test/scheduler_api_test.py::SchedulerApiTest::test_batch_ignore_items_not_ready
pandas
157
from pandas.core.dtypes.common import ( is_bool, is_bool_dtype, is_categorical_dtype, is_datetime64_dtype, is_datetime64tz_dtype, is_datetimelike, is_dtype_equal,
from pandas.core.dtypes.common import ( is_bool, is_bool_dtype, is_categorical_dtype, is_datetime64tz_dtype, is_datetimelike, is_dtype_equal,
pytest pandas/tests/reshape/merge/test_merge_asof.py::TestAsOfMerge::test_timedelta_tolerance_nearest
pandas
157
class _AsOfMerge(_OrderedMerge): ) ) if is_datetime64_dtype(lt) or is_datetime64tz_dtype(lt): if not isinstance(self.tolerance, Timedelta): raise MergeError(msg) if self.tolerance < Timedelta(0):
class _AsOfMerge(_OrderedMerge): ) ) if is_datetimelike(lt): if not isinstance(self.tolerance, Timedelta): raise MergeError(msg) if self.tolerance < Timedelta(0):
pytest pandas/tests/reshape/merge/test_merge_asof.py::TestAsOfMerge::test_timedelta_tolerance_nearest
matplotlib
22
optional. if bin_range is not None: bin_range = self.convert_xunits(bin_range) # We need to do to 'weights' what was done to 'x' if weights is not None: w = cbook._reshape_2D(weights, 'weights')
optional. if bin_range is not None: bin_range = self.convert_xunits(bin_range) if not cbook.is_scalar_or_string(bins): bins = self.convert_xunits(bins) # We need to do to 'weights' what was done to 'x' if weights is not None: w = cbook._reshape_2D(we...
pytest lib/matplotlib/tests/test_axes.py::test_hist_datetime_datasets_bins
keras
36
def separable_conv1d(x, depthwise_kernel, pointwise_kernel, strides=1, padding = _preprocess_padding(padding) if tf_data_format == 'NHWC': spatial_start_dim = 1 strides = (1, 1) + strides + (1,) else: spatial_start_dim = 2 strides = (1, 1, 1) + strides x = tf.expand_dims(...
def separable_conv1d(x, depthwise_kernel, pointwise_kernel, strides=1, padding = _preprocess_padding(padding) if tf_data_format == 'NHWC': spatial_start_dim = 1 strides = (1,) + strides * 2 + (1,) else: spatial_start_dim = 2 strides = (1, 1) + strides * 2 x = tf.expand_di...
pytest tests/keras/layers/convolutional_test.py::test_separable_conv_1d
pandas
31
from pandas.util._decorators import Appender, Substitution, cache_readonly, doc from pandas.core.dtypes.cast import maybe_cast_result from pandas.core.dtypes.common import ( ensure_float, is_datetime64_dtype, is_integer_dtype, is_numeric_dtype, is_object_dtype,
from pandas.util._decorators import Appender, Substitution, cache_readonly, doc from pandas.core.dtypes.cast import maybe_cast_result from pandas.core.dtypes.common import ( ensure_float, is_bool_dtype, is_datetime64_dtype, is_extension_array_dtype, is_integer_dtype, is_numeric_dtype, is_obj...
pytest pandas/tests/groupby/test_function.py::test_groupby_quantile_nullable_array
pandas
31
class GroupBy(_GroupBy[FrameOrSeries]): ) inference = None if is_integer_dtype(vals): inference = np.int64 elif is_datetime64_dtype(vals): inference = "datetime64[ns]" vals = np.asarray(vals).astype(np.float)
class GroupBy(_GroupBy[FrameOrSeries]): ) inference = None if is_integer_dtype(vals.dtype): if is_extension_array_dtype(vals.dtype): vals = vals.to_numpy(dtype=float, na_value=np.nan) inference = np.int64 elif is_bo...
pytest pandas/tests/groupby/test_function.py::test_groupby_quantile_nullable_array
youtube-dl
40
import base64 import io import itertools import os from struct import unpack, pack import time import xml.etree.ElementTree as etree from .common import FileDownloader from .http import HttpFD from ..utils import ( compat_urllib_request, compat_urlparse, format_bytes,
import base64 import io import itertools import os import time import xml.etree.ElementTree as etree from .common import FileDownloader from .http import HttpFD from ..utils import ( struct_pack, struct_unpack, compat_urllib_request, compat_urlparse, format_bytes,
python -m unittest -q test.test_utils.TestUtil.test_struct_unpack
youtube-dl
40
class FlvReader(io.BytesIO): # Utility functions for reading numbers and strings def read_unsigned_long_long(self): return unpack('!Q', self.read(8))[0] def read_unsigned_int(self): return unpack('!I', self.read(4))[0] def read_unsigned_char(self): return unpack('!B', self.rea...
class FlvReader(io.BytesIO): # Utility functions for reading numbers and strings def read_unsigned_long_long(self): return struct_unpack('!Q', self.read(8))[0] def read_unsigned_int(self): return struct_unpack('!I', self.read(4))[0] def read_unsigned_char(self): return struct_...
python -m unittest -q test.test_utils.TestUtil.test_struct_unpack
youtube-dl
40
def write_flv_header(stream, metadata): # Script data stream.write(b'\x12') # Size of the metadata with 3 bytes stream.write(pack('!L', len(metadata))[1:]) stream.write(b'\x00\x00\x00\x00\x00\x00\x00') stream.write(metadata) # Magic numbers extracted from the output files produced by AdobeHD...
def write_flv_header(stream, metadata): # Script data stream.write(b'\x12') # Size of the metadata with 3 bytes stream.write(struct_pack('!L', len(metadata))[1:]) stream.write(b'\x00\x00\x00\x00\x00\x00\x00') stream.write(metadata) # Magic numbers extracted from the output files produced by ...
python -m unittest -q test.test_utils.TestUtil.test_struct_unpack
youtube-dl
40
import platform import re import ssl import socket import subprocess import sys import traceback
import platform import re import ssl import socket import struct import subprocess import sys import traceback
python -m unittest -q test.test_utils.TestUtil.test_struct_unpack
youtube-dl
40
def uppercase_escape(s): return re.sub( r'\\U([0-9a-fA-F]{8})', lambda m: compat_chr(int(m.group(1), base=16)), s)
def uppercase_escape(s): return re.sub( r'\\U([0-9a-fA-F]{8})', lambda m: compat_chr(int(m.group(1), base=16)), s) try: struct.pack(u'!I', 0) except TypeError: # In Python 2.6 (and some 2.7 versions), struct requires a bytes argument def struct_pack(spec, *args): if isinstance(s...
python -m unittest -q test.test_utils.TestUtil.test_struct_unpack
matplotlib
18
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
18
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
pandas
102
def init_ndarray(values, index, columns, dtype=None, copy=False): return arrays_to_mgr([values], columns, index, columns, dtype=dtype) elif is_extension_array_dtype(values) or is_extension_array_dtype(dtype): # GH#19157 if columns is None: columns = [0] return arrays_to_m...
def init_ndarray(values, index, columns, dtype=None, copy=False): return arrays_to_mgr([values], columns, index, columns, dtype=dtype) elif is_extension_array_dtype(values) or is_extension_array_dtype(dtype): # GH#19157 if isinstance(values, np.ndarray) and values.ndim > 1: # GH...
pytest pandas/tests/frame/test_constructors.py::TestDataFrameConstructorWithDatetimeTZ::test_from_2d_ndarray_with_dtype
thefuck
9
def get_new_command(command): pass if upstream_option_index is not -1: command.script_parts.pop(upstream_option_index) command.script_parts.pop(upstream_option_index) push_upstream = command.stderr.split('\n')[-3].strip().partition('git ')[2] return replace_argument(" ".join(command...
def get_new_command(command): pass if upstream_option_index is not -1: command.script_parts.pop(upstream_option_index) try: command.script_parts.pop(upstream_option_index) except IndexError: # This happens for `git push -u` pass push_upstream ...
pytest tests/rules/test_git_push.py::test_get_new_command
scrapy
24
class TunnelingTCP4ClientEndpoint(TCP4ClientEndpoint): for it. """ _responseMatcher = re.compile('HTTP/1\.. 200') def __init__(self, reactor, host, port, proxyConf, contextFactory, timeout=30, bindAddress=None):
class TunnelingTCP4ClientEndpoint(TCP4ClientEndpoint): for it. """ _responseMatcher = re.compile(b'HTTP/1\.. 200') def __init__(self, reactor, host, port, proxyConf, contextFactory, timeout=30, bindAddress=None):
python -m unittest -q tests.test_downloader_handlers.HttpProxyTestCase.test_download_with_proxy_https_timeout
scrapy
24
class TunnelingTCP4ClientEndpoint(TCP4ClientEndpoint): def requestTunnel(self, protocol): """Asks the proxy to open a tunnel.""" tunnelReq = 'CONNECT %s:%s HTTP/1.1\r\n' % (self._tunneledHost, self._tunneledPort) if self._proxyAuthHeader: ...
class TunnelingTCP4ClientEndpoint(TCP4ClientEndpoint): def requestTunnel(self, protocol): """Asks the proxy to open a tunnel.""" tunnelReq = ( b'CONNECT ' + to_bytes(self._tunneledHost, encoding='ascii') + b':' + to_bytes(str(self._tunneledPort)) + b'...
python -m unittest -q tests.test_downloader_handlers.HttpProxyTestCase.test_download_with_proxy_https_timeout
httpie
1
from __future__ import division import os import re import sys import mimetypes import threading from time import sleep, time
from __future__ import division import os import re import sys import errno import mimetypes import threading from time import sleep, time
pytest tests/test_downloads.py::TestDownloadUtils::test_unique_filename
httpie
1
def filename_from_url(url, content_type): return fn def get_unique_filename(filename, exists=os.path.exists): attempt = 0 while True: suffix = '-' + str(attempt) if attempt > 0 else '' if not exists(filename + suffix): return filename + suffix attempt += 1
def filename_from_url(url, content_type): return fn def trim_filename(filename, max_len): if len(filename) > max_len: trim_by = len(filename) - max_len name, ext = os.path.splitext(filename) if trim_by >= len(name): filename = filename[:-trim_by] else: f...
pytest tests/test_downloads.py::TestDownloadUtils::test_unique_filename
keras
17
def categorical_accuracy(y_true, y_pred): def sparse_categorical_accuracy(y_true, y_pred): return K.cast(K.equal(K.max(y_true, axis=-1), K.cast(K.argmax(y_pred, axis=-1), K.floatx())), K.floatx())
def categorical_accuracy(y_true, y_pred): def sparse_categorical_accuracy(y_true, y_pred): # flatten y_true in case it's in shape (num_samples, 1) instead of (num_samples,) return K.cast(K.equal(K.flatten(y_true), K.cast(K.argmax(y_pred, axis=-1), K.floatx())), K.fl...
pytest tests/keras/metrics_test.py::test_sparse_categorical_accuracy_correctness
pandas
123
class Index(IndexOpsMixin, PandasObject): pass # Return an actual float index. return Float64Index(data, copy=copy, dtype=dtype, name=name) elif inferred == "string": pass
class Index(IndexOpsMixin, PandasObject): pass # Return an actual float index. return Float64Index(data, copy=copy, name=name) elif inferred == "string": pass
pytest pandas/tests/indexes/test_range.py::TestRangeIndex::test_constructor_corner
pandas
123
from pandas.core.dtypes.common import ( is_float_dtype, is_integer_dtype, is_scalar, needs_i8_conversion, pandas_dtype, )
from pandas.core.dtypes.common import ( is_float_dtype, is_integer_dtype, is_scalar, is_signed_integer_dtype, is_unsigned_integer_dtype, needs_i8_conversion, pandas_dtype, )
pytest pandas/tests/indexes/test_range.py::TestRangeIndex::test_constructor_corner
pandas
123
from pandas.core.dtypes.generic import ( ) from pandas.core.dtypes.missing import isna from pandas.core import algorithms import pandas.core.common as com from pandas.core.indexes.base import Index, InvalidIndexError, _index_shared_docs
from pandas.core.dtypes.generic import ( ) from pandas.core.dtypes.missing import isna from pandas._typing import Dtype from pandas.core import algorithms import pandas.core.common as com from pandas.core.indexes.base import Index, InvalidIndexError, _index_shared_docs
pytest pandas/tests/indexes/test_range.py::TestRangeIndex::test_constructor_corner
pandas
123
class NumericIndex(Index): _is_numeric_dtype = True def __new__(cls, data=None, dtype=None, copy=False, name=None, fastpath=None): if fastpath is not None: warnings.warn( "The 'fastpath' keyword is deprecated, and will be "
class NumericIndex(Index): _is_numeric_dtype = True def __new__(cls, data=None, dtype=None, copy=False, name=None, fastpath=None): cls._validate_dtype(dtype) if fastpath is not None: warnings.warn( "The 'fastpath' keyword is deprecated, and will be "
pytest pandas/tests/indexes/test_range.py::TestRangeIndex::test_constructor_corner
pandas
123
class NumericIndex(Index): name = data.name return cls._simple_new(subarr, name=name) @Appender(_index_shared_docs["_maybe_cast_slice_bound"]) def _maybe_cast_slice_bound(self, label, side, kind): assert kind in ["ix", "loc", "getitem", None]
class NumericIndex(Index): name = data.name return cls._simple_new(subarr, name=name) @classmethod def _validate_dtype(cls, dtype: Dtype) -> None: if dtype is None: return validation_metadata = { "int64index": (is_signed_integer_dtype, "signed integer...
pytest pandas/tests/indexes/test_range.py::TestRangeIndex::test_constructor_corner
pandas
123
from pandas.util._decorators import Appender, cache_readonly from pandas.core.dtypes.common import ( ensure_platform_int, ensure_python_int, is_int64_dtype, is_integer, is_integer_dtype, is_list_like,
from pandas.util._decorators import Appender, cache_readonly from pandas.core.dtypes.common import ( ensure_platform_int, ensure_python_int, is_integer, is_integer_dtype, is_list_like,
pytest pandas/tests/indexes/test_range.py::TestRangeIndex::test_constructor_corner
pandas
123
class RangeIndex(Int64Index): # -------------------------------------------------------------------- @staticmethod def _validate_dtype(dtype): """ require dtype to be None or int64 """ if not (dtype is None or is_int64_dtype(dtype)): raise TypeError("Invalid to pass a non-int64...
class RangeIndex(Int64Index): # -------------------------------------------------------------------- @cache_readonly def _constructor(self): """ return the class to use for construction """
pytest pandas/tests/indexes/test_range.py::TestRangeIndex::test_constructor_corner
pandas
82
def _get_empty_dtype_and_na(join_units): dtype = upcast_classes["datetimetz"] return dtype[0], tslibs.NaT elif "datetime" in upcast_classes: return np.dtype("M8[ns]"), tslibs.iNaT elif "timedelta" in upcast_classes: return np.dtype("m8[ns]"), np.timedelta64("NaT", "ns") else:...
def _get_empty_dtype_and_na(join_units): dtype = upcast_classes["datetimetz"] return dtype[0], tslibs.NaT elif "datetime" in upcast_classes: return np.dtype("M8[ns]"), np.datetime64("NaT", "ns") elif "timedelta" in upcast_classes: return np.dtype("m8[ns]"), np.timedelta64("NaT", ...
pytest pandas/tests/reshape/merge/test_merge.py::test_merge_datetime_upcast_dtype
pandas
10
class ExtensionBlock(Block): new_values = self.values if inplace else self.values.copy() if isinstance(new, np.ndarray) and len(new) == len(mask): new = new[mask] mask = _safe_reshape(mask, new_values.shape)
class ExtensionBlock(Block): new_values = self.values if inplace else self.values.copy() if isinstance(new, (np.ndarray, ExtensionArray)) and len(new) == len(mask): new = new[mask] mask = _safe_reshape(mask, new_values.shape)
pytest pandas/tests/series/methods/test_update.py::TestUpdate::test_update_extension_array_series
thefuck
19
def match(command): @git_support def get_new_command(command): return replace_argument(command.script, 'push', 'push --force') enabled_by_default = False
def match(command): @git_support def get_new_command(command): return replace_argument(command.script, 'push', 'push --force-with-lease') enabled_by_default = False
pytest tests/rules/test_git_push_force.py::test_get_new_command
pandas
73
class DataFrame(NDFrame): # ---------------------------------------------------------------------- # Arithmetic / combination related def _combine_frame(self, other, func, fill_value=None, level=None): # at this point we have `self._indexed_same(other)` if fill_value is None:
class DataFrame(NDFrame): # ---------------------------------------------------------------------- # Arithmetic / combination related def _combine_frame(self, other: "DataFrame", func, fill_value=None): # at this point we have `self._indexed_same(other)` if fill_value is None:
pytest pandas/tests/frame/test_arithmetic.py::TestFrameFlexArithmetic::test_floordiv_axis0
pandas
73
class DataFrame(NDFrame): return new_data def _combine_match_index(self, other, func): # at this point we have `self.index.equals(other.index)` if ops.should_series_dispatch(self, other, func):
class DataFrame(NDFrame): return new_data def _combine_match_index(self, other: Series, func): # at this point we have `self.index.equals(other.index)` if ops.should_series_dispatch(self, other, func):
pytest pandas/tests/frame/test_arithmetic.py::TestFrameFlexArithmetic::test_floordiv_axis0
pandas
73
class DataFrame(NDFrame): new_data = ops.dispatch_to_series(self, other, func) else: # fastpath --> operate directly on values with np.errstate(all="ignore"): new_data = func(self.values.T, other.values).T return new_data def _construct_result(sel...
class DataFrame(NDFrame): new_data = ops.dispatch_to_series(self, other, func) else: # fastpath --> operate directly on values other_vals = other.values.reshape(-1, 1) with np.errstate(all="ignore"): new_data = func(self.values, other_vals) ...
pytest pandas/tests/frame/test_arithmetic.py::TestFrameFlexArithmetic::test_floordiv_axis0
pandas
73
def mask_zero_div_zero(x, y, result): return result if zmask.any(): shape = result.shape # Flip sign if necessary for -0.0 zneg_mask = zmask & np.signbit(y) zpos_mask = zmask & ~zneg_mask nan_mask = (zmask & (x == 0)).ravel() with np.errstate(invalid="ignor...
def mask_zero_div_zero(x, y, result): return result if zmask.any(): # Flip sign if necessary for -0.0 zneg_mask = zmask & np.signbit(y) zpos_mask = zmask & ~zneg_mask nan_mask = zmask & (x == 0) with np.errstate(invalid="ignore"): neginf_mask = (zpos_ma...
pytest pandas/tests/frame/test_arithmetic.py::TestFrameFlexArithmetic::test_floordiv_axis0
pandas
140
def _recast_datetimelike_result(result: DataFrame) -> DataFrame: result = result.copy() obj_cols = [ idx for idx in range(len(result.columns)) if is_object_dtype(result.dtypes[idx]) ] # See GH#26285
def _recast_datetimelike_result(result: DataFrame) -> DataFrame: result = result.copy() obj_cols = [ idx for idx in range(len(result.columns)) if is_object_dtype(result.dtypes.iloc[idx]) ] # See GH#26285
pytest pandas/tests/groupby/test_apply.py::test_apply_datetime_issue
thefuck
15
from thefuck.specific.git import git_support @git_support def match(command): return ('did not match any file(s) known to git.' in command.stderr and "Did you forget to 'git add'?" in command.stderr) @git_support def get_new_command(command): missing_file = re.findall( r"error: pathsp...
from thefuck.specific.git import git_support @git_support def match(command): return 'did not match any file(s) known to git.' in command.stderr @git_support def get_new_command(command): missing_file = re.findall( r"error: pathspec '([^']*)' " r'did not match any file\(s\) known to git.', co...
pytest tests/rules/test_git_add.py::test_match
scrapy
28
class RFPDupeFilter(BaseDupeFilter): self.logger = logging.getLogger(__name__) if path: self.file = open(os.path.join(path, 'requests.seen'), 'a+') self.fingerprints.update(x.rstrip() for x in self.file) @classmethod
class RFPDupeFilter(BaseDupeFilter): self.logger = logging.getLogger(__name__) if path: self.file = open(os.path.join(path, 'requests.seen'), 'a+') self.file.seek(0) self.fingerprints.update(x.rstrip() for x in self.file) @classmethod
python -m unittest -q tests.test_dupefilters.RFPDupeFilterTest.test_dupefilter_path
thefuck
5
from thefuck.specific.git import git_support @git_support def match(command): return ('push' in command.script_parts and 'set-upstream' in command.output) def _get_upstream_option_index(command_parts):
from thefuck.specific.git import git_support @git_support def match(command): return ('push' in command.script_parts and 'git push --set-upstream' in command.output) def _get_upstream_option_index(command_parts):
pytest tests/rules/test_git_push.py::test_match_bitbucket
sanic
3
class Sanic: "Endpoint with name `{}` was not found".format(view_name) ) if view_name == "static" or view_name.endswith(".static"): filename = kwargs.pop("filename", None) # it's static folder
class Sanic: "Endpoint with name `{}` was not found".format(view_name) ) # If the route has host defined, split that off # TODO: Retain netloc and path separately in Route objects host = uri.find("/") if host > 0: host, uri = uri[:host], uri[host:...
pytest tests/test_url_for.py::test_routes_with_host
sanic
3
class Sanic: netloc = kwargs.pop("_server", None) if netloc is None and external: netloc = self.config.get("SERVER_NAME", "") if external: if not scheme:
class Sanic: netloc = kwargs.pop("_server", None) if netloc is None and external: netloc = host or self.config.get("SERVER_NAME", "") if external: if not scheme:
pytest tests/test_url_for.py::test_routes_with_host
luigi
27
class Parameter(object): return [str(v) for v in x] return str(x) def parse_from_input(self, param_name, x): """ Parses the parameter value from input ``x``, handling defaults and is_list.
class Parameter(object): return [str(v) for v in x] return str(x) def parse_from_input(self, param_name, x, task_name=None): """ Parses the parameter value from input ``x``, handling defaults and is_list.
pytest test/parameter_test.py::TestParamWithDefaultFromConfig::testCommandLineNoDefault
luigi
27
class Parameter(object): :raises MissingParameterException: if x is false-y and no default is specified. """ if not x: if self.has_value: return self.value elif self.is_bool: return False elif self.is_list:
class Parameter(object): :raises MissingParameterException: if x is false-y and no default is specified. """ if not x: if self.has_task_value(param_name=param_name, task_name=task_name): return self.task_value(param_name=param_name, task_name=task_name) el...
pytest test/parameter_test.py::TestParamWithDefaultFromConfig::testCommandLineNoDefault
luigi
27
class Parameter(object): description.append('for all instances of class %s' % task_name) elif self.description: description.append(self.description) if self.has_value: description.append(" [default: %s]" % (self.value,)) if self.is_list: action = ...
class Parameter(object): description.append('for all instances of class %s' % task_name) elif self.description: description.append(self.description) if self.has_task_value(param_name=param_name, task_name=task_name): value = self.task_value(param_name=param_name, task...
pytest test/parameter_test.py::TestParamWithDefaultFromConfig::testCommandLineNoDefault
luigi
27
class Parameter(object): dest = self.parser_dest(param_name, task_name, glob=False) if dest is not None: value = getattr(args, dest, None) params[param_name] = self.parse_from_input(param_name, value) def set_global_from_args(self, param_name, task_name, args, is_without_sec...
class Parameter(object): dest = self.parser_dest(param_name, task_name, glob=False) if dest is not None: value = getattr(args, dest, None) params[param_name] = self.parse_from_input(param_name, value, task_name=task_name) def set_global_from_args(self, param_name, task_name,...
pytest test/parameter_test.py::TestParamWithDefaultFromConfig::testCommandLineNoDefault
luigi
27
class Parameter(object): if dest is not None: value = getattr(args, dest, None) if value: self.set_global(self.parse_from_input(param_name, value)) else: # either False (bools) or None (everything else) self.reset_global()
class Parameter(object): if dest is not None: value = getattr(args, dest, None) if value: self.set_global(self.parse_from_input(param_name, value, task_name=task_name)) else: # either False (bools) or None (everything else) self.reset_global()...
pytest test/parameter_test.py::TestParamWithDefaultFromConfig::testCommandLineNoDefault
matplotlib
14
class Text(Artist): def update(self, kwargs): # docstring inherited # Update bbox last, as it depends on font properties. sentinel = object() # bbox can be None, so use another sentinel. bbox = kwargs.pop("bbox", sentinel) super().update(kwargs) if bbox is not senti...
class Text(Artist): def update(self, kwargs): # docstring inherited sentinel = object() # bbox can be None, so use another sentinel. # Update fontproperties first, as it has lowest priority. fontproperties = kwargs.pop("fontproperties", sentinel) if fontproperties is not se...
pytest lib/matplotlib/tests/test_text.py::test_fontproperties_kwarg_precedence
pandas
161
class Categorical(ExtensionArray, PandasObject): raise ValueError("fill value must be in categories") values_codes = _get_codes_for_values(value, self.categories) indexer = np.where(values_codes != -1) codes[indexer] = values_codes[values_codes != -1]...
class Categorical(ExtensionArray, PandasObject): raise ValueError("fill value must be in categories") values_codes = _get_codes_for_values(value, self.categories) indexer = np.where(codes == -1) codes[indexer] = values_codes[indexer] # If...
pytest pandas/tests/series/test_missing.py::TestSeriesMissingData::test_fillna_categorical_with_new_categories
youtube-dl
23
def js_to_json(code): v = m.group(0) if v in ('true', 'false', 'null'): return v elif v.startswith('/*') or v == ',': return "" if v[0] in ("'", '"'):
def js_to_json(code): v = m.group(0) if v in ('true', 'false', 'null'): return v elif v.startswith('/*') or v.startswith('//') or v == ',': return "" if v[0] in ("'", '"'):
python -m unittest -q test.test_utils.TestUtil.test_js_to_json_edgecases
youtube-dl
23
def js_to_json(code): return re.sub(r'''(?sx) "(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"| '(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'| /\*.*?\*/|,(?=\s*[\]}])| [a-zA-Z_][.a-zA-Z_0-9]*| \b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:\s*:)?| [0-9]+(?=\s*:)
def js_to_json(code): return re.sub(r'''(?sx) "(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"| '(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'| /\*.*?\*/|//[^\n]*|,(?=\s*[\]}])| [a-zA-Z_][.a-zA-Z_0-9]*| \b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:\s*:)?| [0-9]+(?=\s*:)
python -m unittest -q test.test_utils.TestUtil.test_js_to_json_edgecases
pandas
52
class SeriesGroupBy(GroupBy): val = self.obj._internal_get_values() # GH 27951 # temporary fix while we wait for NumPy bug 12629 to be fixed val[isna(val)] = np.datetime64("NaT") try: sorter = np.lexsort((val, ids)) except TypeError: # catches object dtype...
class SeriesGroupBy(GroupBy): val = self.obj._internal_get_values() codes, _ = algorithms.factorize(val, sort=False) sorter = np.lexsort((codes, ids)) codes = codes[sorter] ids = ids[sorter] # group boundaries are where group ids change # unique observations ar...
pytest pandas/tests/groupby/test_function.py::test_series_groupby_nunique
matplotlib
6
class Axes(_AxesBase): except ValueError: pass # Failed to convert to float array; must be color specs. else: # If c can be either mapped values or a RGB(A) color, prefer # the former if shapes match, the latter otherwise. if c.siz...
class Axes(_AxesBase): except ValueError: pass # Failed to convert to float array; must be color specs. else: # handle the documented special case of a 2D array with 1 # row which as RGB(A) to broadcast. if c.shape == (1, 4) or c.s...
pytest lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_single_color_c
scrapy
32
class CrawlerProcess(CrawlerRunner): def __init__(self, settings): super(CrawlerProcess, self).__init__(settings) install_shutdown_handlers(self._signal_shutdown) configure_logging(settings) log_scrapy_info(settings) def _signal_shutdown(self, signum, _): install_shutdow...
class CrawlerProcess(CrawlerRunner): def __init__(self, settings): super(CrawlerProcess, self).__init__(settings) install_shutdown_handlers(self._signal_shutdown) configure_logging(self.settings) log_scrapy_info(self.settings) def _signal_shutdown(self, signum, _): insta...
python -m unittest -q tests.test_crawler.CrawlerProcessTest.test_crawler_process_accepts_dict
keras
9
def count_leading_spaces(s): def process_list_block(docstring, starting_point, section_end, leading_spaces, marker): ending_point = docstring.find('\n\n', starting_point) block = docstring[starting_point:(None if ending_point == -1 else ending_point -...
def count_leading_spaces(s): def process_list_block(docstring, starting_point, section_end, leading_spaces, marker): ending_point = docstring.find('\n\n', starting_point) block = docstring[starting_point:(ending_point - 1 if ending_point > -1 else sec...
pytest tests/test_doc_auto_generation.py::test_doc_lists[docs_descriptor1]
tornado
14
class IOLoop(Configurable): if IOLoop.current(instance=False) is None: self.make_current() elif make_current: if IOLoop.current(instance=False) is None: raise RuntimeError("current IOLoop already exists") self.make_current()
class IOLoop(Configurable): if IOLoop.current(instance=False) is None: self.make_current() elif make_current: if IOLoop.current(instance=False) is not None: raise RuntimeError("current IOLoop already exists") self.make_current()
python -m unittest -q tornado.test.ioloop_test.TestIOLoopCurrent.test_force_current
pandas
69
class _AtIndexer(_ScalarAccessIndexer): "can only have integer indexers" ) else: if is_integer(i) and not ax.holds_integer(): raise ValueError( "At based indexing on an non-integer " ...
class _AtIndexer(_ScalarAccessIndexer): "can only have integer indexers" ) else: if is_integer(i) and not (ax.holds_integer() or ax.is_floating()): raise ValueError( "At based indexing on an non-integer "...
pytest pandas/tests/indexes/test_numeric.py::TestFloat64Index::test_lookups_datetimelike_values
pandas
94
from pandas.core.dtypes.generic import ABCIndex, ABCIndexClass, ABCSeries from pandas.core import algorithms from pandas.core.accessor import PandasDelegate from pandas.core.arrays import ExtensionArray, ExtensionOpsMixin from pandas.core.arrays.datetimelike import ( DatetimeLikeArrayMixin, _ensure_datetimelik...
from pandas.core.dtypes.generic import ABCIndex, ABCIndexClass, ABCSeries from pandas.core import algorithms from pandas.core.accessor import PandasDelegate from pandas.core.arrays import ( DatetimeArray, ExtensionArray, ExtensionOpsMixin, TimedeltaArray, ) from pandas.core.arrays.datetimelike import (...
pytest pandas/tests/indexes/datetimes/test_constructors.py::TestDatetimeIndex::test_shallow_copy_inherits_array_freq
pandas
94
class DatetimeIndexOpsMixin(ExtensionIndex, ExtensionOpsMixin): if isinstance(maybe_slice, slice): return self[maybe_slice] taken = ExtensionIndex.take( self, indices, axis, allow_fill, fill_value, **kwargs ) # keep freq in PeriodArray/Index, reset otherwise ...
class DatetimeIndexOpsMixin(ExtensionIndex, ExtensionOpsMixin): if isinstance(maybe_slice, slice): return self[maybe_slice] return ExtensionIndex.take( self, indices, axis, allow_fill, fill_value, **kwargs ) _can_hold_na = True _na_value = NaT
pytest pandas/tests/indexes/datetimes/test_constructors.py::TestDatetimeIndex::test_shallow_copy_inherits_array_freq
pandas
94
class DatetimeIndexOpsMixin(ExtensionIndex, ExtensionOpsMixin): @Appender(_index_shared_docs["repeat"] % _index_doc_kwargs) def repeat(self, repeats, axis=None): nv.validate_repeat(tuple(), dict(axis=axis)) freq = self.freq if is_period_dtype(self) else None return self._shallow_copy(sel...
class DatetimeIndexOpsMixin(ExtensionIndex, ExtensionOpsMixin): @Appender(_index_shared_docs["repeat"] % _index_doc_kwargs) def repeat(self, repeats, axis=None): nv.validate_repeat(tuple(), dict(axis=axis)) result = type(self._data)(self.asi8.repeat(repeats), dtype=self.dtype) return sel...
pytest pandas/tests/indexes/datetimes/test_constructors.py::TestDatetimeIndex::test_shallow_copy_inherits_array_freq
pandas
94
class DatetimeTimedeltaMixin(DatetimeIndexOpsMixin, Int64Index): self._data._freq = freq # -------------------------------------------------------------------- # Set Operation Methods
class DatetimeTimedeltaMixin(DatetimeIndexOpsMixin, Int64Index): self._data._freq = freq def _shallow_copy(self, values=None, **kwargs): if values is None: values = self._data if isinstance(values, type(self)): values = values._data attributes = self._get_a...
pytest pandas/tests/indexes/datetimes/test_constructors.py::TestDatetimeIndex::test_shallow_copy_inherits_array_freq
pandas
135
class BaseGrouper: pass else: raise return self._aggregate_series_pure_python(obj, func) def _aggregate_series_fast(self, obj, func): func = self._is_builtin_func(func)
class BaseGrouper: pass else: raise except TypeError as err: if "ndarray" in str(err): # raised in libreduction if obj's values is no ndarray pass else: raise return self._aggregate_series...
pytest pandas/tests/extension/decimal/test_decimal.py::test_groupby_agg_ea_method
youtube-dl
18
class YoutubeDL(object): force_properties = dict( (k, v) for k, v in ie_result.items() if v is not None) for f in ('_type', 'url', 'ie_key'): if f in force_properties: del force_properties[f] new_result = info.copy()
class YoutubeDL(object): force_properties = dict( (k, v) for k, v in ie_result.items() if v is not None) for f in ('_type', 'url', 'id', 'extractor', 'extractor_key', 'ie_key'): if f in force_properties: del force_properties[f] new...
python -m unittest -q test.test_YoutubeDL.TestYoutubeDL.test_do_not_override_ie_key_in_url_transparent
black
12
class BracketTracker: bracket_match: Dict[Tuple[Depth, NodeType], Leaf] = Factory(dict) delimiters: Dict[LeafID, Priority] = Factory(dict) previous: Optional[Leaf] = None _for_loop_variable: int = 0 _lambda_arguments: int = 0 def mark(self, leaf: Leaf) -> None: """Mark `leaf` with brack...
class BracketTracker: bracket_match: Dict[Tuple[Depth, NodeType], Leaf] = Factory(dict) delimiters: Dict[LeafID, Priority] = Factory(dict) previous: Optional[Leaf] = None _for_loop_depths: List[int] = Factory(list) _lambda_argument_depths: List[int] = Factory(list) def mark(self, leaf: Leaf) ->...
python -m unittest -q tests.test_black.BlackTestCase.test_bracket_match
black
12
class BracketTracker: """ if leaf.type == token.NAME and leaf.value == "for": self.depth += 1 self._for_loop_variable += 1 return True return False def maybe_decrement_after_for_loop_variable(self, leaf: Leaf) -> bool: """See `maybe_increment_for...
class BracketTracker: """ if leaf.type == token.NAME and leaf.value == "for": self.depth += 1 self._for_loop_depths.append(self.depth) return True return False def maybe_decrement_after_for_loop_variable(self, leaf: Leaf) -> bool: """See `maybe_i...
python -m unittest -q tests.test_black.BlackTestCase.test_bracket_match
black
12
class BracketTracker: """ if leaf.type == token.NAME and leaf.value == "lambda": self.depth += 1 self._lambda_arguments += 1 return True return False def maybe_decrement_after_lambda_arguments(self, leaf: Leaf) -> bool: """See `maybe_increment_la...
class BracketTracker: """ if leaf.type == token.NAME and leaf.value == "lambda": self.depth += 1 self._lambda_argument_depths.append(self.depth) return True return False def maybe_decrement_after_lambda_arguments(self, leaf: Leaf) -> bool: """See...
python -m unittest -q tests.test_black.BlackTestCase.test_bracket_match
keras
20
def in_top_k(predictions, targets, k): def conv2d_transpose(x, kernel, output_shape, strides=(1, 1), padding='valid', data_format=None): data_format = normalize_data_format(data_format) x = _preprocess_conv2d_input(x, data_format)
def in_top_k(predictions, targets, k): def conv2d_transpose(x, kernel, output_shape, strides=(1, 1), padding='valid', data_format=None, dilation_rate=(1, 1)): data_format = normalize_data_format(data_format) x = _preprocess_conv2d_input(x, data_format)
pytest tests/keras/layers/convolutional_test.py::test_conv2d_transpose_dilation
keras
20
def conv2d_transpose(x, kernel, output_shape, strides=(1, 1), False, padding, padding], output_shape=output_shape) return _postprocess_conv2d_output(x, data_format)
def conv2d_transpose(x, kernel, output_shape, strides=(1, 1), False, padding, padding], output_shape=output_shape, dilation=dilation_rate) return _postprocess_conv2d_output(x, data_format)
pytest tests/keras/layers/convolutional_test.py::test_conv2d_transpose_dilation
keras
20
def _preprocess_conv1d_input(x, data_format): return x, tf_data_format def _preprocess_conv2d_input(x, data_format): """Transpose and cast the input before the conv2d. # Arguments x: input tensor. data_format: string, `"channels_last"` or `"channels_first"`. # Returns A tenso...
def _preprocess_conv1d_input(x, data_format): return x, tf_data_format def _preprocess_conv2d_input(x, data_format, force_transpose=False): """Transpose and cast the input before the conv2d. # Arguments x: input tensor. data_format: string, `"channels_last"` or `"channels_first"`. ...
pytest tests/keras/layers/convolutional_test.py::test_conv2d_transpose_dilation
keras
20
def _preprocess_conv2d_input(x, data_format): x = tf.cast(x, 'float32') tf_data_format = 'NHWC' if data_format == 'channels_first': if not _has_nchw_support(): x = tf.transpose(x, (0, 2, 3, 1)) # NCHW -> NHWC else: tf_data_format = 'NCHW'
def _preprocess_conv2d_input(x, data_format): x = tf.cast(x, 'float32') tf_data_format = 'NHWC' if data_format == 'channels_first': if not _has_nchw_support() or force_transpose: x = tf.transpose(x, (0, 2, 3, 1)) # NCHW -> NHWC else: tf_data_format = 'NCHW'
pytest tests/keras/layers/convolutional_test.py::test_conv2d_transpose_dilation
keras
20
def conv2d(x, kernel, strides=(1, 1), padding='valid', def conv2d_transpose(x, kernel, output_shape, strides=(1, 1), padding='valid', data_format=None): """2D deconvolution (i.e. transposed convolution). # Arguments
def conv2d(x, kernel, strides=(1, 1), padding='valid', def conv2d_transpose(x, kernel, output_shape, strides=(1, 1), padding='valid', data_format=None, dilation_rate=(1, 1)): """2D deconvolution (i.e. transposed convolution). # Arguments
pytest tests/keras/layers/convolutional_test.py::test_conv2d_transpose_dilation
keras
20
def conv2d_transpose(x, kernel, output_shape, strides=(1, 1), data_format: string, `"channels_last"` or `"channels_first"`. Whether to use Theano or TensorFlow/CNTK data format for inputs/kernels/outputs. # Returns A tensor, result of transposed 2D convolution.
def conv2d_transpose(x, kernel, output_shape, strides=(1, 1), data_format: string, `"channels_last"` or `"channels_first"`. Whether to use Theano or TensorFlow/CNTK data format for inputs/kernels/outputs. dilation_rate: tuple of 2 integers. # Returns A tensor, result...
pytest tests/keras/layers/convolutional_test.py::test_conv2d_transpose_dilation
keras
20
def conv2d_transpose(x, kernel, output_shape, strides=(1, 1), if isinstance(output_shape, (tuple, list)): output_shape = tf.stack(output_shape) x, tf_data_format = _preprocess_conv2d_input(x, data_format) if data_format == 'channels_first' and tf_data_format == 'NHWC': output_shape = (outp...
def conv2d_transpose(x, kernel, output_shape, strides=(1, 1), if isinstance(output_shape, (tuple, list)): output_shape = tf.stack(output_shape) # tf.nn.atrous_conv2d_transpose input only supports NHWC format if data_format == 'channels_first' and dilation_rate != (1, 1): force_transpose = T...
pytest tests/keras/layers/convolutional_test.py::test_conv2d_transpose_dilation
keras
20
def conv2d_transpose(x, kernel, output_shape, strides=(1, 1), else: strides = (1, 1) + strides x = tf.nn.conv2d_transpose(x, kernel, output_shape, strides, padding=padding, data_format=tf_data_format) if data_format == 'channels_first' a...
def conv2d_transpose(x, kernel, output_shape, strides=(1, 1), else: strides = (1, 1) + strides if dilation_rate == (1, 1): x = tf.nn.conv2d_transpose(x, kernel, output_shape, strides, padding=padding, data_format=tf_data_form...
pytest tests/keras/layers/convolutional_test.py::test_conv2d_transpose_dilation
keras
20
def conv2d(x, kernel, strides=(1, 1), padding='valid', def conv2d_transpose(x, kernel, output_shape, strides=(1, 1), padding='valid', data_format=None): """2D deconvolution (transposed convolution). # Arguments
def conv2d(x, kernel, strides=(1, 1), padding='valid', def conv2d_transpose(x, kernel, output_shape, strides=(1, 1), padding='valid', data_format=None, dilation_rate=(1, 1)): """2D deconvolution (transposed convolution). # Arguments
pytest tests/keras/layers/convolutional_test.py::test_conv2d_transpose_dilation
keras
20
def conv2d_transpose(x, kernel, output_shape, strides=(1, 1), padding: string, "same" or "valid". data_format: "channels_last" or "channels_first". Whether to use Theano or TensorFlow data format in inputs/kernels/outputs. # Raises ValueError: if using an even kernel siz...
def conv2d_transpose(x, kernel, output_shape, strides=(1, 1), padding: string, "same" or "valid". data_format: "channels_last" or "channels_first". Whether to use Theano or TensorFlow data format in inputs/kernels/outputs. dilation_rate: tuple of 2 integers. # Raises...
pytest tests/keras/layers/convolutional_test.py::test_conv2d_transpose_dilation
keras
20
def conv2d_transpose(x, kernel, output_shape, strides=(1, 1), kshp=kernel_shape, subsample=strides, border_mode=th_padding, ...
def conv2d_transpose(x, kernel, output_shape, strides=(1, 1), kshp=kernel_shape, subsample=strides, border_mode=th_padding, ...
pytest tests/keras/layers/convolutional_test.py::test_conv2d_transpose_dilation
keras
20
class Conv2DTranspose(Conv2D): padding='valid', output_padding=None, data_format=None, activation=None, use_bias=True, kernel_initializer='glorot_uniform',
class Conv2DTranspose(Conv2D): padding='valid', output_padding=None, data_format=None, dilation_rate=(1, 1), activation=None, use_bias=True, kernel_initializer='glorot_uniform',
pytest tests/keras/layers/convolutional_test.py::test_conv2d_transpose_dilation
keras
20
class Conv2DTranspose(Conv2D): strides=strides, padding=padding, data_format=data_format, activation=activation, use_bias=use_bias, kernel_initializer=kernel_initializer,
class Conv2DTranspose(Conv2D): strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activation, use_bias=use_bias, kernel_initializer=kernel_initializer,
pytest tests/keras/layers/convolutional_test.py::test_conv2d_transpose_dilation
keras
20
class Conv2DTranspose(Conv2D): out_height = conv_utils.deconv_length(height, stride_h, kernel_h, self.padding, out_pad_h) out_width = conv_utils.deconv_length(width, ...
class Conv2DTranspose(Conv2D): out_height = conv_utils.deconv_length(height, stride_h, kernel_h, self.padding, out_pad_h, self.d...
pytest tests/keras/layers/convolutional_test.py::test_conv2d_transpose_dilation
keras
20
class Conv2DTranspose(Conv2D): output_shape, self.strides, padding=self.padding, data_format=self.data_format) if self.use_bias: outputs = K.bias_add(
class Conv2DTranspose(Conv2D): output_shape, self.strides, padding=self.padding, data_format=self.data_format, dilation_rate=self.dilation_rate) if self.use_bias: outputs = K.bias_add(
pytest tests/keras/layers/convolutional_test.py::test_conv2d_transpose_dilation
keras
20
class Conv2DTranspose(Conv2D): stride_h, kernel_h, self.padding, out_pad_h) output_shape...
class Conv2DTranspose(Conv2D): stride_h, kernel_h, self.padding, out_pad_h, ...
pytest tests/keras/layers/convolutional_test.py::test_conv2d_transpose_dilation
keras
20
def conv_input_length(output_length, filter_size, padding, stride): return (output_length - 1) * stride - 2 * pad + filter_size def deconv_length(dim_size, stride_size, kernel_size, padding, output_padding): """Determines output length of a transposed convolution given input length. # Arguments
def conv_input_length(output_length, filter_size, padding, stride): return (output_length - 1) * stride - 2 * pad + filter_size def deconv_length(dim_size, stride_size, kernel_size, padding, output_padding, dilation=1): """Determines output length of a transposed convolution given input leng...
pytest tests/keras/layers/convolutional_test.py::test_conv2d_transpose_dilation
keras
20
def deconv_length(dim_size, stride_size, kernel_size, padding, output_padding): padding: One of `"same"`, `"valid"`, `"full"`. output_padding: Integer, amount of padding along the output dimension, Can be set to `None` in which case the output length is inferred. # Returns The o...
def deconv_length(dim_size, stride_size, kernel_size, padding, output_padding): padding: One of `"same"`, `"valid"`, `"full"`. output_padding: Integer, amount of padding along the output dimension, Can be set to `None` in which case the output length is inferred. dilation: dilation r...
pytest tests/keras/layers/convolutional_test.py::test_conv2d_transpose_dilation
keras
20
def deconv_length(dim_size, stride_size, kernel_size, padding, output_padding): if dim_size is None: return None # Infer length if output padding is None, else compute the exact length if output_padding is None: if padding == 'valid':
def deconv_length(dim_size, stride_size, kernel_size, padding, output_padding): if dim_size is None: return None # Get the dilated kernel size kernel_size = kernel_size + (kernel_size - 1) * (dilation - 1) # Infer length if output padding is None, else compute the exact length if output_pa...
pytest tests/keras/layers/convolutional_test.py::test_conv2d_transpose_dilation
luigi
6
def _recursively_freeze(value): """ if isinstance(value, Mapping): return _FrozenOrderedDict(((k, _recursively_freeze(v)) for k, v in value.items())) elif isinstance(value, list): return tuple(_recursively_freeze(v) for v in value) return value class DictParameter(Parameter): """ ...
def _recursively_freeze(value): """ if isinstance(value, Mapping): return _FrozenOrderedDict(((k, _recursively_freeze(v)) for k, v in value.items())) elif isinstance(value, list) or isinstance(value, tuple): return tuple(_recursively_freeze(v) for v in value) return value class _DictPa...
pytest test/parameter_test.py::TestParametersHashability::test_tuple_dict
luigi
6
class DictParameter(Parameter): tags, that are dynamically constructed outside Luigi), or you have a complex parameter containing logically related values (like a database connection config). """ class _DictParamEncoder(JSONEncoder): """ JSON encoder for :py:class:`~DictParameter`, whic...
class DictParameter(Parameter): tags, that are dynamically constructed outside Luigi), or you have a complex parameter containing logically related values (like a database connection config). """ def normalize(self, value): """ Ensure that dictionary parameter is converted to a _FrozenOr...
pytest test/parameter_test.py::TestParametersHashability::test_tuple_dict
luigi
6
class DictParameter(Parameter): return json.loads(s, object_pairs_hook=_FrozenOrderedDict) def serialize(self, x): return json.dumps(x, cls=DictParameter._DictParamEncoder) class ListParameter(Parameter):
class DictParameter(Parameter): return json.loads(s, object_pairs_hook=_FrozenOrderedDict) def serialize(self, x): return json.dumps(x, cls=_DictParamEncoder) class ListParameter(Parameter):
pytest test/parameter_test.py::TestParametersHashability::test_tuple_dict
luigi
6
class ListParameter(Parameter): """ def normalize(self, x): """ Ensure that list parameter is converted to a tuple so it can be hashed. :param str x: the value to parse. :return: the normalized (hashable/immutable) value.
class ListParameter(Parameter): """ def normalize(self, x): """ Ensure that struct is recursively converted to a tuple so it can be hashed. :param str x: the value to parse. :return: the normalized (hashable/immutable) value.
pytest test/parameter_test.py::TestParametersHashability::test_tuple_dict
luigi
6
class ListParameter(Parameter): :param str x: the value to parse. :return: the parsed value. """ return list(json.loads(x)) def serialize(self, x): """
class ListParameter(Parameter): :param str x: the value to parse. :return: the parsed value. """ return list(json.loads(x, object_pairs_hook=_FrozenOrderedDict)) def serialize(self, x): """
pytest test/parameter_test.py::TestParametersHashability::test_tuple_dict
luigi
6
class ListParameter(Parameter): :param x: the value to serialize. """ return json.dumps(x) class TupleParameter(Parameter): """ Parameter whose value is a ``tuple`` or ``tuple`` of tuples.
class ListParameter(Parameter): :param x: the value to serialize. """ return json.dumps(x, cls=_DictParamEncoder) class TupleParameter(ListParameter): """ Parameter whose value is a ``tuple`` or ``tuple`` of tuples.
pytest test/parameter_test.py::TestParametersHashability::test_tuple_dict
luigi
6
class TupleParameter(Parameter): $ luigi --module my_tasks MyTask --book_locations '((12,3),(4,15),(52,1))' """ def parse(self, x): """ Parse an individual value from the input.
class TupleParameter(Parameter): $ luigi --module my_tasks MyTask --book_locations '((12,3),(4,15),(52,1))' """ def parse(self, x): """ Parse an individual value from the input.
pytest test/parameter_test.py::TestParametersHashability::test_tuple_dict
luigi
6
class TupleParameter(Parameter): # Therefore, if json.loads(x) returns a ValueError, try ast.literal_eval(x). # ast.literal_eval(t_str) == t try: return tuple(tuple(x) for x in json.loads(x)) # loop required to parse tuple of tuples except ValueError: return lite...
class TupleParameter(Parameter): # Therefore, if json.loads(x) returns a ValueError, try ast.literal_eval(x). # ast.literal_eval(t_str) == t try: # loop required to parse tuple of tuples return tuple(tuple(x) for x in json.loads(x, object_pairs_hook=_FrozenOrderedDict)) ...
pytest test/parameter_test.py::TestParametersHashability::test_tuple_dict
spacy
7
dependency tree to find the noun phrase they are referring to – for example: $9.4 million --> Net income. Compatible with: spaCy v2.0.0+ Last tested with: v2.1.0 """ from __future__ import unicode_literals, print_function
dependency tree to find the noun phrase they are referring to – for example: $9.4 million --> Net income. Compatible with: spaCy v2.0.0+ Last tested with: v2.2.1 """ from __future__ import unicode_literals, print_function
py.test spacy/tests/doc/test_span.py::test_filter_spans
spacy
7
def main(model="en_core_web_sm"): def filter_spans(spans): # Filter a sequence of spans so they don't contain overlaps get_sort_key = lambda span: (span.end - span.start, span.start) sorted_spans = sorted(spans, key=get_sort_key, reverse=True) result = [] seen_tokens = set() for span in sorted_...
def main(model="en_core_web_sm"): def filter_spans(spans): # Filter a sequence of spans so they don't contain overlaps # For spaCy 2.1.4+: this function is available as spacy.util.filter_spans() get_sort_key = lambda span: (span.end - span.start, -span.start) sorted_spans = sorted(spans, key=get_sort_k...
py.test spacy/tests/doc/test_span.py::test_filter_spans
spacy
7
def filter_spans(spans): spans (iterable): The spans to filter. RETURNS (list): The filtered spans. """ get_sort_key = lambda span: (span.end - span.start, span.start) sorted_spans = sorted(spans, key=get_sort_key, reverse=True) result = [] seen_tokens = set()
def filter_spans(spans): spans (iterable): The spans to filter. RETURNS (list): The filtered spans. """ get_sort_key = lambda span: (span.end - span.start, -span.start) sorted_spans = sorted(spans, key=get_sort_key, reverse=True) result = [] seen_tokens = set()
py.test spacy/tests/doc/test_span.py::test_filter_spans
ansible
9
class Rhsm(RegistrationBase): for pool_id, quantity in sorted(pool_ids.items()): if pool_id in available_pool_ids: args = [SUBMAN_CMD, 'attach', '--pool', pool_id, '--quantity', quantity] rc, stderr, stdout = self.module.run_command(args, check_rc=True) e...
class Rhsm(RegistrationBase): for pool_id, quantity in sorted(pool_ids.items()): if pool_id in available_pool_ids: args = [SUBMAN_CMD, 'attach', '--pool', pool_id] if quantity is not None: args.extend(['--quantity', to_native(quantity)]) ...
pytest test/units/modules/packaging/os/test_redhat_subscription.py::test_redhat_subscribtion
ansible
9
def main(): module.fail_json(msg='Unable to parse pool_ids option.') pool_id, quantity = list(value.items())[0] else: pool_id, quantity = value, 1 pool_ids[pool_id] = str(quantity) consumer_type = module.params["consumer_type"] consumer_name = module.param...
def main(): module.fail_json(msg='Unable to parse pool_ids option.') pool_id, quantity = list(value.items())[0] else: pool_id, quantity = value, None pool_ids[pool_id] = quantity consumer_type = module.params["consumer_type"] consumer_name = module.params[...
pytest test/units/modules/packaging/os/test_redhat_subscription.py::test_redhat_subscribtion
scrapy
13
class ImagesPipeline(FilesPipeline): # ImagesPipeline. They may be overridden by settings. MIN_WIDTH = 0 MIN_HEIGHT = 0 EXPIRES = 0 THUMBS = {} DEFAULT_IMAGES_URLS_FIELD = 'image_urls' DEFAULT_IMAGES_RESULT_FIELD = 'images'
class ImagesPipeline(FilesPipeline): # ImagesPipeline. They may be overridden by settings. MIN_WIDTH = 0 MIN_HEIGHT = 0 EXPIRES = 90 THUMBS = {} DEFAULT_IMAGES_URLS_FIELD = 'image_urls' DEFAULT_IMAGES_RESULT_FIELD = 'images'
python -m unittest -q tests.test_pipeline_images.ImagesPipelineTestCaseCustomSettings