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
95
def _period_array_cmp(cls, op): @unpack_zerodim_and_defer(opname) def wrapper(self, other): ordinal_op = getattr(self.asi8, opname) if isinstance(other, str): try:
def _period_array_cmp(cls, op): @unpack_zerodim_and_defer(opname) def wrapper(self, other): if isinstance(other, str): try:
pytest pandas/tests/arithmetic/test_period.py::TestPeriodIndexComparisons::test_eq_integer_disallowed
pandas
95
def _period_array_cmp(cls, op): except ValueError: # string that can't be parsed as Period return invalid_comparison(self, other, op) elif isinstance(other, int): # TODO: sure we want to allow this? we dont for DTA/TDA # 2 tests rely on this ...
def _period_array_cmp(cls, op): except ValueError: # string that can't be parsed as Period return invalid_comparison(self, other, op) if isinstance(other, self._recognized_scalars) or other is NaT: other = self._scalar_type(other)
pytest pandas/tests/arithmetic/test_period.py::TestPeriodIndexComparisons::test_eq_integer_disallowed
pandas
68
from pandas.core.dtypes.common import ( from pandas.core.dtypes.dtypes import IntervalDtype from pandas.core.dtypes.generic import ( ABCDatetimeIndex, ABCIndexClass, ABCInterval, ABCIntervalIndex,
from pandas.core.dtypes.common import ( from pandas.core.dtypes.dtypes import IntervalDtype from pandas.core.dtypes.generic import ( ABCDatetimeIndex, ABCExtensionArray, ABCIndexClass, ABCInterval, ABCIntervalIndex,
pytest pandas/tests/arrays/interval/test_interval.py::TestMethods::test_shift
pandas
68
class IntervalArray(IntervalMixin, ExtensionArray): # Avoid materializing self.values return self.left.size def take(self, indices, allow_fill=False, fill_value=None, axis=None, **kwargs): """ Take elements from the IntervalArray.
class IntervalArray(IntervalMixin, ExtensionArray): # Avoid materializing self.values return self.left.size def shift(self, periods: int = 1, fill_value: object = None) -> ABCExtensionArray: if not len(self) or periods == 0: return self.copy() if isna(fill_value): ...
pytest pandas/tests/arrays/interval/test_interval.py::TestMethods::test_shift
pandas
68
class BaseMethodsTests(BaseExtensionTests): expected = empty self.assert_extension_array_equal(result, expected) def test_shift_fill_value(self, data): arr = data[:4] fill_value = data[0]
class BaseMethodsTests(BaseExtensionTests): expected = empty self.assert_extension_array_equal(result, expected) def test_shift_zero_copies(self, data): result = data.shift(0) assert result is not data result = data[:0].shift(2) assert result is not data def te...
pytest pandas/tests/arrays/interval/test_interval.py::TestMethods::test_shift
black
13
def generate_tokens(readline): stashed = tok continue if token == 'def': if (stashed and stashed[0] == NAME and stashed[1] == 'async'): ...
def generate_tokens(readline): stashed = tok continue if token in ('def', 'for'): if (stashed and stashed[0] == NAME and stashed[1] == 'async'): ...
python -m unittest -q tests.test_black.BlackTestCase.test_python37
scrapy
33
from scrapy.exceptions import DontCloseSpider from scrapy.http import Response, Request from scrapy.utils.misc import load_object from scrapy.utils.reactor import CallLaterOnce from scrapy.utils.log import logformatter_adapter logger = logging.getLogger(__name__)
from scrapy.exceptions import DontCloseSpider from scrapy.http import Response, Request from scrapy.utils.misc import load_object from scrapy.utils.reactor import CallLaterOnce from scrapy.utils.log import logformatter_adapter, failure_to_exc_info logger = logging.getLogger(__name__)
python -m unittest -q tests.test_utils_log.FailureToExcInfoTest.test_non_failure
scrapy
33
class ExecutionEngine(object): d = self._download(request, spider) d.addBoth(self._handle_downloader_output, request, spider) d.addErrback(lambda f: logger.info('Error while handling downloader output', extra={'spider': spider, 'failure': f})) d...
class ExecutionEngine(object): d = self._download(request, spider) d.addBoth(self._handle_downloader_output, request, spider) d.addErrback(lambda f: logger.info('Error while handling downloader output', exc_info=failure_to_exc_info(f), ...
python -m unittest -q tests.test_utils_log.FailureToExcInfoTest.test_non_failure
scrapy
33
class ExecutionEngine(object): # response is a Response or Failure d = self.scraper.enqueue_scrape(response, request, spider) d.addErrback(lambda f: logger.error('Error while enqueuing downloader output', extra={'spider': spider, 'failure': f})) ...
class ExecutionEngine(object): # response is a Response or Failure d = self.scraper.enqueue_scrape(response, request, spider) d.addErrback(lambda f: logger.error('Error while enqueuing downloader output', exc_info=failure_to_exc_info(f), ...
python -m unittest -q tests.test_utils_log.FailureToExcInfoTest.test_non_failure
scrapy
33
class ExecutionEngine(object): def log_failure(msg): def errback(failure): logger.error(msg, extra={'spider': spider, 'failure': failure}) return errback dfd.addBoth(lambda _: self.downloader.close())
class ExecutionEngine(object): def log_failure(msg): def errback(failure): logger.error( msg, exc_info=failure_to_exc_info(failure), extra={'spider': spider} ) return errback dfd.addBoth...
python -m unittest -q tests.test_utils_log.FailureToExcInfoTest.test_non_failure
scrapy
33
from twisted.internet import defer from scrapy.utils.defer import defer_result, defer_succeed, parallel, iter_errback from scrapy.utils.spider import iterate_spider_output from scrapy.utils.misc import load_object from scrapy.utils.log import logformatter_adapter from scrapy.exceptions import CloseSpider, DropItem, Ign...
from twisted.internet import defer from scrapy.utils.defer import defer_result, defer_succeed, parallel, iter_errback from scrapy.utils.spider import iterate_spider_output from scrapy.utils.misc import load_object from scrapy.utils.log import logformatter_adapter, failure_to_exc_info from scrapy.exceptions import Close...
python -m unittest -q tests.test_utils_log.FailureToExcInfoTest.test_non_failure
scrapy
33
class Scraper(object): dfd.addErrback( lambda f: logger.error('Scraper bug processing %(request)s', {'request': request}, extra={'spider': spider, 'failure': f})) self._scrape_next(spider, slot) return dfd
class Scraper(object): dfd.addErrback( lambda f: logger.error('Scraper bug processing %(request)s', {'request': request}, exc_info=failure_to_exc_info(f), extra={'spider': spider})) self....
python -m unittest -q tests.test_utils_log.FailureToExcInfoTest.test_non_failure
scrapy
33
class Scraper(object): logger.error( "Spider error processing %(request)s (referer: %(referer)s)", {'request': request, 'referer': referer}, extra={'spider': spider, 'failure': _failure} ) self.signals.send_catch_log( signal=signals.spider_error,
class Scraper(object): logger.error( "Spider error processing %(request)s (referer: %(referer)s)", {'request': request, 'referer': referer}, exc_info=failure_to_exc_info(_failure), extra={'spider': spider} ) self.signals.send_catch_log( ...
python -m unittest -q tests.test_utils_log.FailureToExcInfoTest.test_non_failure
scrapy
33
class Scraper(object): if download_failure.frames: logger.error('Error downloading %(request)s', {'request': request}, extra={'spider': spider, 'failure': download_failure}) else: errmsg = download_failure....
class Scraper(object): if download_failure.frames: logger.error('Error downloading %(request)s', {'request': request}, exc_info=failure_to_exc_info(download_failure), extra={'spider': spider}) ...
python -m unittest -q tests.test_utils_log.FailureToExcInfoTest.test_non_failure
scrapy
33
class Scraper(object): spider=spider, exception=output.value) else: logger.error('Error processing %(item)s', {'item': item}, extra={'spider': spider, 'failure': output}) else: logkws = self.logformatter.scraped(output, res...
class Scraper(object): spider=spider, exception=output.value) else: logger.error('Error processing %(item)s', {'item': item}, exc_info=failure_to_exc_info(output), extra={'spider': spider}) else: ...
python -m unittest -q tests.test_utils_log.FailureToExcInfoTest.test_non_failure
scrapy
33
from six.moves.urllib import robotparser from scrapy.exceptions import NotConfigured, IgnoreRequest from scrapy.http import Request from scrapy.utils.httpobj import urlparse_cached logger = logging.getLogger(__name__)
from six.moves.urllib import robotparser from scrapy.exceptions import NotConfigured, IgnoreRequest from scrapy.http import Request from scrapy.utils.httpobj import urlparse_cached from scrapy.utils.log import failure_to_exc_info logger = logging.getLogger(__name__)
python -m unittest -q tests.test_utils_log.FailureToExcInfoTest.test_non_failure
scrapy
33
class RobotsTxtMiddleware(object): if failure.type is not IgnoreRequest: logger.error("Error downloading %(request)s: %(f_exception)s", {'request': request, 'f_exception': failure.value}, extra={'spider': spider, 'failure': failure}) def _parse_...
class RobotsTxtMiddleware(object): if failure.type is not IgnoreRequest: logger.error("Error downloading %(request)s: %(f_exception)s", {'request': request, 'f_exception': failure.value}, exc_info=failure_to_exc_info(failure), ...
python -m unittest -q tests.test_utils_log.FailureToExcInfoTest.test_non_failure
scrapy
33
from scrapy.utils.ftp import ftp_makedirs_cwd from scrapy.exceptions import NotConfigured from scrapy.utils.misc import load_object from scrapy.utils.python import get_func_args logger = logging.getLogger(__name__)
from scrapy.utils.ftp import ftp_makedirs_cwd from scrapy.exceptions import NotConfigured from scrapy.utils.misc import load_object from scrapy.utils.python import get_func_args from scrapy.utils.log import failure_to_exc_info logger = logging.getLogger(__name__)
python -m unittest -q tests.test_utils_log.FailureToExcInfoTest.test_non_failure
scrapy
33
class FeedExporter(object): d.addCallback(lambda _: logger.info(logfmt % "Stored", log_args, extra={'spider': spider})) d.addErrback(lambda f: logger.error(logfmt % "Error storing", log_args, extra={'spider': spider,...
class FeedExporter(object): d.addCallback(lambda _: logger.info(logfmt % "Stored", log_args, extra={'spider': spider})) d.addErrback(lambda f: logger.error(logfmt % "Error storing", log_args, exc_info=failure_to_exc_...
python -m unittest -q tests.test_utils_log.FailureToExcInfoTest.test_non_failure
scrapy
33
""" This module is kept to provide a helpful warning about its removal. """ import logging import warnings from twisted.python.failure import Failure from scrapy.exceptions import ScrapyDeprecationWarning logger = logging.getLogger(__name__) warnings.warn("Module `scrapy.log` has been deprecated, Scrapy now relies...
# -*- coding: utf-8 -*- import sys import logging import warnings from logging.config import dictConfig from twisted.python.failure import Failure from twisted.python import log as twisted_log import scrapy from scrapy.settings import overridden_settings, Settings from scrapy.exceptions import ScrapyDeprecationWarni...
python -m unittest -q tests.test_utils_log.FailureToExcInfoTest.test_non_failure
scrapy
33
from scrapy.pipelines.media import MediaPipeline from scrapy.exceptions import NotConfigured, IgnoreRequest from scrapy.http import Request from scrapy.utils.misc import md5sum logger = logging.getLogger(__name__)
from scrapy.pipelines.media import MediaPipeline from scrapy.exceptions import NotConfigured, IgnoreRequest from scrapy.http import Request from scrapy.utils.misc import md5sum from scrapy.utils.log import failure_to_exc_info logger = logging.getLogger(__name__)
python -m unittest -q tests.test_utils_log.FailureToExcInfoTest.test_non_failure
scrapy
33
class FilesPipeline(MediaPipeline): dfd.addErrback( lambda f: logger.error(self.__class__.__name__ + '.store.stat_file', extra={'spider': info.spider, 'failure': f}) ) return dfd
class FilesPipeline(MediaPipeline): dfd.addErrback( lambda f: logger.error(self.__class__.__name__ + '.store.stat_file', exc_info=failure_to_exc_info(f), extra={'spider': info.spider}) ) return dfd
python -m unittest -q tests.test_utils_log.FailureToExcInfoTest.test_non_failure
scrapy
33
from twisted.python.failure import Failure from scrapy.utils.defer import mustbe_deferred, defer_result from scrapy.utils.request import request_fingerprint from scrapy.utils.misc import arg_to_iter logger = logging.getLogger(__name__)
from twisted.python.failure import Failure from scrapy.utils.defer import mustbe_deferred, defer_result from scrapy.utils.request import request_fingerprint from scrapy.utils.misc import arg_to_iter from scrapy.utils.log import failure_to_exc_info logger = logging.getLogger(__name__)
python -m unittest -q tests.test_utils_log.FailureToExcInfoTest.test_non_failure
scrapy
33
class MediaPipeline(object): dfd.addCallback(self._check_media_to_download, request, info) dfd.addBoth(self._cache_result_and_execute_waiters, fp, info) dfd.addErrback(lambda f: logger.error( f.value, extra={'spider': info.spider, 'failure': f}) ) return dfd.addBoth(l...
class MediaPipeline(object): dfd.addCallback(self._check_media_to_download, request, info) dfd.addBoth(self._cache_result_and_execute_waiters, fp, info) dfd.addErrback(lambda f: logger.error( f.value, exc_info=failure_to_exc_info(f), extra={'spider': info.spider}) ) r...
python -m unittest -q tests.test_utils_log.FailureToExcInfoTest.test_non_failure
scrapy
33
class MediaPipeline(object): logger.error( '%(class)s found errors processing %(item)s', {'class': self.__class__.__name__, 'item': item}, extra={'spider': info.spider, 'failure': value} ) return item
class MediaPipeline(object): logger.error( '%(class)s found errors processing %(item)s', {'class': self.__class__.__name__, 'item': item}, exc_info=failure_to_exc_info(value), extra={'spider': info.spider...
python -m unittest -q tests.test_utils_log.FailureToExcInfoTest.test_non_failure
scrapy
33
from twisted.python.failure import Failure from scrapy.xlib.pydispatch.dispatcher import Any, Anonymous, liveReceivers, \ getAllReceivers, disconnect from scrapy.xlib.pydispatch.robustapply import robustApply logger = logging.getLogger(__name__)
from twisted.python.failure import Failure from scrapy.xlib.pydispatch.dispatcher import Any, Anonymous, liveReceivers, \ getAllReceivers, disconnect from scrapy.xlib.pydispatch.robustapply import robustApply from scrapy.utils.log import failure_to_exc_info logger = logging.getLogger(__name__)
python -m unittest -q tests.test_utils_log.FailureToExcInfoTest.test_non_failure
scrapy
33
def send_catch_log_deferred(signal=Any, sender=Anonymous, *arguments, **named): if dont_log is None or not isinstance(failure.value, dont_log): logger.error("Error caught on signal handler: %(receiver)s", {'receiver': recv}, extra={'spider': spider, ...
def send_catch_log_deferred(signal=Any, sender=Anonymous, *arguments, **named): if dont_log is None or not isinstance(failure.value, dont_log): logger.error("Error caught on signal handler: %(receiver)s", {'receiver': recv}, exc_info=failure_to_exc_i...
python -m unittest -q tests.test_utils_log.FailureToExcInfoTest.test_non_failure
keras
8
class Network(Layer): unprocessed_nodes = {} def add_unprocessed_node(layer, node_data): if layer not in unprocessed_nodes: unprocessed_nodes[layer] = [node_data] else: unprocessed_nodes[layer].append(node_data) def process_node(layer, no...
class Network(Layer): unprocessed_nodes = {} def add_unprocessed_node(layer, node_data): """Add node to layer list Args: layer: layer object node_data: Node data specifying layer call """ if layer not in unprocessed_nodes:...
pytest tests/keras/engine/test_topology.py::test_layer_sharing_at_heterogeneous_depth_order
keras
8
class Network(Layer): else: raise ValueError('Improperly formatted model config.') inbound_layer = created_layers[inbound_layer_name] if len(inbound_layer._inbound_nodes) <= inbound_node_index: add_unprocessed_node(layer, node_data)...
class Network(Layer): else: raise ValueError('Improperly formatted model config.') inbound_layer = created_layers[inbound_layer_name] # Raise an error if the corresponding layer node # has not yet been created if len(inb...
pytest tests/keras/engine/test_topology.py::test_layer_sharing_at_heterogeneous_depth_order
keras
8
class Network(Layer): # First, we create all layers and enqueue nodes to be processed for layer_data in config['layers']: process_layer(layer_data) # Then we process nodes in order of layer depth. # Nodes that cannot yet be processed (if the inbound node # does not ye...
class Network(Layer): # First, we create all layers and enqueue nodes to be processed for layer_data in config['layers']: process_layer(layer_data) # Then we process nodes in order of layer depth. # Nodes that cannot yet be processed (if the inbound node # does not y...
pytest tests/keras/engine/test_topology.py::test_layer_sharing_at_heterogeneous_depth_order
keras
8
class Network(Layer): while unprocessed_nodes: for layer_data in config['layers']: layer = created_layers[layer_data['name']] if layer in unprocessed_nodes: for node_data in unprocessed_nodes.pop(layer): process_node(layer, ...
class Network(Layer): while unprocessed_nodes: for layer_data in config['layers']: layer = created_layers[layer_data['name']] # Process all nodes in layer, if not yet processed if layer in unprocessed_nodes: node_data_list = unproc...
pytest tests/keras/engine/test_topology.py::test_layer_sharing_at_heterogeneous_depth_order
tornado
15
setup( "options_test.cfg", "static/robots.txt", "static/dir/index.html", "templates/utf8.html", "test.crt", "test.key",
setup( "options_test.cfg", "static/robots.txt", "static/dir/index.html", "static_foo.txt", "templates/utf8.html", "test.crt", "test.key",
python -m unittest -q tornado.test.web_test.StaticFileTest.test_path_traversal_protection
tornado
15
class StaticFileHandler(RequestHandler): .. versionadded:: 3.1 """ root = os.path.abspath(root) # os.path.abspath strips a trailing / # it needs to be temporarily added back for requests to root/ if not (absolute_path + os.path.sep).startswith(root): raise HT...
class StaticFileHandler(RequestHandler): .. versionadded:: 3.1 """ # os.path.abspath strips a trailing /. # We must add it back to `root` so that we only match files # in a directory named `root` instead of files starting with # that prefix. root = os.path.abspat...
python -m unittest -q tornado.test.web_test.StaticFileTest.test_path_traversal_protection
pandas
26
class Categorical(ExtensionArray, PandasObject): good = self._codes != -1 if not good.all(): if skipna: pointer = self._codes[good].min() else: return np.nan
class Categorical(ExtensionArray, PandasObject): good = self._codes != -1 if not good.all(): if skipna and good.any(): pointer = self._codes[good].min() else: return np.nan
pytest pandas/tests/arrays/categorical/test_analytics.py::TestCategoricalAnalytics::test_min_max_only_nan
pandas
26
class Categorical(ExtensionArray, PandasObject): good = self._codes != -1 if not good.all(): if skipna: pointer = self._codes[good].max() else: return np.nan
class Categorical(ExtensionArray, PandasObject): good = self._codes != -1 if not good.all(): if skipna and good.any(): pointer = self._codes[good].max() else: return np.nan
pytest pandas/tests/arrays/categorical/test_analytics.py::TestCategoricalAnalytics::test_min_max_only_nan
pandas
115
def interpolate_1d( inds = lib.maybe_convert_objects(inds) else: inds = xvalues result[invalid] = np.interp(inds[invalid], inds[valid], yvalues[valid]) result[preserve_nans] = np.nan return result
def interpolate_1d( inds = lib.maybe_convert_objects(inds) else: inds = xvalues # np.interp requires sorted X values, #21037 indexer = np.argsort(inds[valid]) result[invalid] = np.interp( inds[invalid], inds[valid][indexer], yvalues[valid][indexer]...
pytest pandas/tests/series/test_missing.py::TestSeriesInterpolateData::test_interpolate_unsorted_index
youtube-dl
38
from ..utils import ( compat_urllib_error, compat_urllib_parse, compat_urllib_request, ExtractorError, )
from ..utils import ( compat_urllib_error, compat_urllib_parse, compat_urllib_request, urlencode_postdata, ExtractorError, )
python -m unittest -q test.test_utils.TestUtil.test_urlencode_postdata
youtube-dl
38
class FacebookIE(InfoExtractor): login_page_req = compat_urllib_request.Request(self._LOGIN_URL) login_page_req.add_header('Cookie', 'locale=en_US') self.report_login() login_page = self._download_webpage(login_page_req, None, note=False, errnote='Unable to download login pa...
class FacebookIE(InfoExtractor): login_page_req = compat_urllib_request.Request(self._LOGIN_URL) login_page_req.add_header('Cookie', 'locale=en_US') login_page = self._download_webpage(login_page_req, None, note='Downloading login page', errnote='Unable to download login...
python -m unittest -q test.test_utils.TestUtil.test_urlencode_postdata
youtube-dl
38
class FacebookIE(InfoExtractor): 'timezone': '-60', 'trynum': '1', } request = compat_urllib_request.Request(self._LOGIN_URL, compat_urllib_parse.urlencode(login_form)) request.add_header('Content-Type', 'application/x-www-form-urlencoded') try: lo...
class FacebookIE(InfoExtractor): 'timezone': '-60', 'trynum': '1', } request = compat_urllib_request.Request(self._LOGIN_URL, urlencode_postdata(login_form)) request.add_header('Content-Type', 'application/x-www-form-urlencoded') try: login_results...
python -m unittest -q test.test_utils.TestUtil.test_urlencode_postdata
youtube-dl
38
def read_batch_urls(batch_fd): with contextlib.closing(batch_fd) as fd: return [url for url in map(fixup, fd) if url]
def read_batch_urls(batch_fd): with contextlib.closing(batch_fd) as fd: return [url for url in map(fixup, fd) if url] def urlencode_postdata(*args, **kargs): return compat_urllib_parse.urlencode(*args, **kargs).encode('ascii')
python -m unittest -q test.test_utils.TestUtil.test_urlencode_postdata
pandas
49
def str_repeat(arr, repeats): else: def rep(x, r): try: return bytes.__mul__(x, r) except TypeError:
def str_repeat(arr, repeats): else: def rep(x, r): if x is libmissing.NA: return x try: return bytes.__mul__(x, r) except TypeError:
pytest pandas/tests/test_strings.py::TestStringMethods::test_repeat_with_null
ansible
11
commands: - string """ from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.connection import exec_command from ansible.module_utils.network.ios.ios import load_config from ansible.module_utils.network.ios.ios import ios_argument_spec import re def map_obj_to_commands(updates, module):
commands: - string """ from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.network.ios.ios import get_config, load_config from ansible.module_utils.network.ios.ios import ios_argument_spec from re import search, M def map_obj_to_commands(updates, module):
pytest test/units/modules/network/ios/test_ios_banner.py::TestIosBannerIos12Module::test_ios_banner_nochange
ansible
11
def map_obj_to_commands(updates, module): if want['text'] and (want['text'] != have.get('text')): banner_cmd = 'banner %s' % module.params['banner'] banner_cmd += ' @\n' banner_cmd += want['text'].strip() banner_cmd += '\n@' commands.append(banner_cmd)...
def map_obj_to_commands(updates, module): if want['text'] and (want['text'] != have.get('text')): banner_cmd = 'banner %s' % module.params['banner'] banner_cmd += ' @\n' banner_cmd += want['text'].strip('\n') banner_cmd += '\n@' commands.append(banner_...
pytest test/units/modules/network/ios/test_ios_banner.py::TestIosBannerIos12Module::test_ios_banner_nochange
ansible
11
def map_obj_to_commands(updates, module): def map_config_to_obj(module): rc, out, err = exec_command(module, 'show banner %s' % module.params['banner']) if rc == 0: output = out else: rc, out, err = exec_command(module, 'show running-config | begin banne...
def map_obj_to_commands(updates, module): def map_config_to_obj(module): """ This function gets the banner config without stripping any whitespaces, and then fetches the required banner from it. :param module: :return: banner config dict object. """ out = get_config(module, flags='| begin ...
pytest test/units/modules/network/ios/test_ios_banner.py::TestIosBannerIos12Module::test_ios_banner_nochange
ansible
11
def map_config_to_obj(module): def map_params_to_obj(module): text = module.params['text'] if text: text = str(text).strip() return { 'banner': module.params['banner'], 'text': text,
def map_config_to_obj(module): def map_params_to_obj(module): text = module.params['text'] return { 'banner': module.params['banner'], 'text': text,
pytest test/units/modules/network/ios/test_ios_banner.py::TestIosBannerIos12Module::test_ios_banner_nochange
scrapy
7
This module implements the FormRequest class which is a more convenient class See documentation in docs/topics/request-response.rst """ from six.moves.urllib.parse import urljoin, urlencode import lxml.html from parsel.selector import create_root_node import six from scrapy.http.request import Request from scrapy.util...
This module implements the FormRequest class which is a more convenient class See documentation in docs/topics/request-response.rst """ import six from six.moves.urllib.parse import urljoin, urlencode import lxml.html from parsel.selector import create_root_node from w3lib.html import strip_html5_whitespace from scr...
python -m unittest -q tests.test_http_request.FormRequestTest.test_spaces_in_action
scrapy
7
class FormRequest(Request): def _get_form_url(form, url): if url is None: return urljoin(form.base_url, form.action) return urljoin(form.base_url, url)
class FormRequest(Request): def _get_form_url(form, url): if url is None: action = form.get('action') if action is None: return form.base_url return urljoin(form.base_url, strip_html5_whitespace(action)) return urljoin(form.base_url, url)
python -m unittest -q tests.test_http_request.FormRequestTest.test_spaces_in_action
ansible
8
import re import shlex import pkgutil import xml.etree.ElementTree as ET from ansible.errors import AnsibleError from ansible.module_utils._text import to_bytes, to_text
import re import shlex import pkgutil import xml.etree.ElementTree as ET import ntpath from ansible.errors import AnsibleError from ansible.module_utils._text import to_bytes, to_text
pytest test/units/plugins/shell/test_powershell.py::test_join_path_unc
ansible
8
class ShellModule(ShellBase): return "" def join_path(self, *args): parts = [] for arg in args: arg = self._unquote(arg).replace('/', '\\') parts.extend([a for a in arg.split('\\') if a]) path = '\\'.join(parts) if path.startswith('~'): re...
class ShellModule(ShellBase): return "" def join_path(self, *args): # use normpath() to remove doubled slashed and convert forward to backslashes parts = [ntpath.normpath(self._unquote(arg)) for arg in args] # Becuase ntpath.join treats any component that begins with a backslash as...
pytest test/units/plugins/shell/test_powershell.py::test_join_path_unc
spacy
6
class Language(object): """ if name not in self.pipe_names: raise ValueError(Errors.E001.format(name=name, opts=self.pipe_names)) if ENABLE_PIPELINE_ANALYSIS: analyze_all_pipes(self.pipeline) return self.pipeline.pop(self.pipe_names.index(name)) def __call__(...
class Language(object): """ if name not in self.pipe_names: raise ValueError(Errors.E001.format(name=name, opts=self.pipe_names)) removed = self.pipeline.pop(self.pipe_names.index(name)) if ENABLE_PIPELINE_ANALYSIS: analyze_all_pipes(self.pipeline) return ...
py.test spacy/tests/pipeline/test_analysis.py::test_analysis_validate_attrs_remove_pipe
luigi
7
class Scheduler(object): for batch_task in self._state.get_batch_running_tasks(task.batch_id): batch_task.expl = expl if not (task.status in (RUNNING, BATCH_RUNNING) and status == PENDING) or new_deps: # don't allow re-scheduling of task while it is running, it m...
class Scheduler(object): for batch_task in self._state.get_batch_running_tasks(task.batch_id): batch_task.expl = expl if not (task.status in (RUNNING, BATCH_RUNNING) and (status not in (DONE, FAILED, RUNNING) or task.worker_running != worker_id)) or new_deps: # d...
pytest test/scheduler_api_test.py::SchedulerApiTest::test_status_wont_override
keras
21
class EarlyStopping(Callback): baseline: Baseline value for the monitored quantity to reach. Training will stop if the model doesn't show improvement over the baseline. """ def __init__(self,
class EarlyStopping(Callback): baseline: Baseline value for the monitored quantity to reach. Training will stop if the model doesn't show improvement over the baseline. restore_best_weights: whether to restore model weights from the epoch with the best value of the mo...
pytest tests/keras/test_callbacks.py::test_EarlyStopping_final_weights_when_restoring_model_weights
keras
21
class EarlyStopping(Callback): patience=0, verbose=0, mode='auto', baseline=None): super(EarlyStopping, self).__init__() self.monitor = monitor
class EarlyStopping(Callback): patience=0, verbose=0, mode='auto', baseline=None, restore_best_weights=False): super(EarlyStopping, self).__init__() self.monitor = monitor
pytest tests/keras/test_callbacks.py::test_EarlyStopping_final_weights_when_restoring_model_weights
keras
21
class EarlyStopping(Callback): self.min_delta = min_delta self.wait = 0 self.stopped_epoch = 0 if mode not in ['auto', 'min', 'max']: warnings.warn('EarlyStopping mode %s is unknown, '
class EarlyStopping(Callback): self.min_delta = min_delta self.wait = 0 self.stopped_epoch = 0 self.restore_best_weights = restore_best_weights self.best_weights = None if mode not in ['auto', 'min', 'max']: warnings.warn('EarlyStopping mode %s is unknown, '
pytest tests/keras/test_callbacks.py::test_EarlyStopping_final_weights_when_restoring_model_weights
keras
21
class EarlyStopping(Callback): if self.monitor_op(current - self.min_delta, self.best): self.best = current self.wait = 0 else: self.wait += 1 if self.wait >= self.patience: self.stopped_epoch = epoch self.model.stop_trainin...
class EarlyStopping(Callback): if self.monitor_op(current - self.min_delta, self.best): self.best = current self.wait = 0 if self.restore_best_weights: self.best_weights = self.model.get_weights() else: self.wait += 1 if self.wa...
pytest tests/keras/test_callbacks.py::test_EarlyStopping_final_weights_when_restoring_model_weights
scrapy
12
class Selector(_ParselSelector, object_ref): selectorlist_cls = SelectorList def __init__(self, response=None, text=None, type=None, root=None, _root=None, **kwargs): st = _st(response, type or self._default_type) if _root is not None:
class Selector(_ParselSelector, object_ref): selectorlist_cls = SelectorList def __init__(self, response=None, text=None, type=None, root=None, _root=None, **kwargs): if not(response is None or text is None): raise ValueError('%s.__init__() received both response and text' ...
python -m unittest -q tests.test_selector.SelectorTestCase.test_selector_bad_args
black
5
class Line: bracket_depth = leaf.bracket_depth if bracket_depth == depth and leaf.type == token.COMMA: commas += 1 if leaf.parent and leaf.parent.type == syms.arglist: commas += 1 break
class Line: bracket_depth = leaf.bracket_depth if bracket_depth == depth and leaf.type == token.COMMA: commas += 1 if leaf.parent and leaf.parent.type in { syms.arglist, syms.typedargslist, }: ...
python -m unittest -q tests.test_black.BlackTestCase.test_function_trailing_comma
black
5
def bracket_split_build_line( if leaves: # Since body is a new indent level, remove spurious leading whitespace. normalize_prefix(leaves[0], inside_brackets=True) # Ensure a trailing comma for imports, but be careful not to add one after # any comments. ...
def bracket_split_build_line( if leaves: # Since body is a new indent level, remove spurious leading whitespace. normalize_prefix(leaves[0], inside_brackets=True) # Ensure a trailing comma for imports and standalone function arguments, but # be careful not to add ...
python -m unittest -q tests.test_black.BlackTestCase.test_function_trailing_comma
ansible
4
__metaclass__ = type from ansible.module_utils.six import string_types from ansible.playbook.attribute import FieldAttribute from ansible.utils.collection_loader import AnsibleCollectionLoader def _ensure_default_collection(collection_list=None):
__metaclass__ = type from ansible.module_utils.six import string_types from ansible.playbook.attribute import FieldAttribute from ansible.utils.collection_loader import AnsibleCollectionLoader from ansible.template import is_template, Environment from ansible.utils.display import Display display = Display() def _ens...
pytest test/units/playbook/test_collectionsearch.py::test_collection_static_warning
ansible
4
def _ensure_default_collection(collection_list=None): class CollectionSearch: # this needs to be populated before we can resolve tasks/roles/etc _collections = FieldAttribute(isa='list', listof=string_types, priority=100, default=_ensure_default_collection) def _load_collections(self, attr, ds): #...
def _ensure_default_collection(collection_list=None): class CollectionSearch: # this needs to be populated before we can resolve tasks/roles/etc _collections = FieldAttribute(isa='list', listof=string_types, priority=100, default=_ensure_default_collection, always_post_validat...
pytest test/units/playbook/test_collectionsearch.py::test_collection_static_warning
ansible
4
class CollectionSearch: if not ds: # don't return an empty collection list, just return None return None return ds
class CollectionSearch: if not ds: # don't return an empty collection list, just return None return None # This duplicates static attr checking logic from post_validate() # because if the user attempts to template a collection name, it will # error before it ever gets to th...
pytest test/units/playbook/test_collectionsearch.py::test_collection_static_warning
keras
42
class Model(Container): @interfaces.legacy_generator_methods_support def fit_generator(self, generator, steps_per_epoch, epochs=1, verbose=1, callbacks=None,
class Model(Container): @interfaces.legacy_generator_methods_support def fit_generator(self, generator, steps_per_epoch=None, epochs=1, verbose=1, callbacks=None,
pytest tests/keras/engine/test_training.py::test_model_methods
keras
42
class Model(Container): to yield from `generator` before declaring one epoch finished and starting the next epoch. It should typically be equal to the number of samples of your dataset divided by the batch size. Not used if using `Sequence`. ep...
class Model(Container): to yield from `generator` before declaring one epoch finished and starting the next epoch. It should typically be equal to the number of samples of your dataset divided by the batch size. Optional for `Sequence`: if ...
pytest tests/keras/engine/test_training.py::test_model_methods
keras
42
class Model(Container): validation_steps: Only relevant if `validation_data` is a generator. Total number of steps (batches of samples) to yield from `generator` before stopping. class_weight: Dictionary mapping class indices to a weight for the cl...
class Model(Container): validation_steps: Only relevant if `validation_data` is a generator. Total number of steps (batches of samples) to yield from `generator` before stopping. Optional for `Sequence`: if unspecified, will use the `len(valida...
pytest tests/keras/engine/test_training.py::test_model_methods
keras
42
class Model(Container): if do_validation: self._make_test_function() # python 2 has 'next', 3 has '__next__' # avoid any explicit version checks val_gen = (hasattr(validation_data, 'next') or hasattr(validation_data, '__next__') or isins...
class Model(Container): if do_validation: self._make_test_function() is_sequence = isinstance(generator, Sequence) if not is_sequence and use_multiprocessing and workers > 1: warnings.warn( UserWarning('Using a generator with `use_multiprocessing=True`' ...
pytest tests/keras/engine/test_training.py::test_model_methods
keras
42
class Model(Container): val_data += [0.] for cbk in callbacks: cbk.validation_data = val_data is_sequence = isinstance(generator, Sequence) if not is_sequence and use_multiprocessing and workers > 1: warnings.warn( UserWarning('Usin...
class Model(Container): val_data += [0.] for cbk in callbacks: cbk.validation_data = val_data enqueuer = None try:
pytest tests/keras/engine/test_training.py::test_model_methods
keras
42
class Model(Container): return self.history @interfaces.legacy_generator_methods_support def evaluate_generator(self, generator, steps, max_queue_size=10, workers=1, use_multiprocessing=False):
class Model(Container): return self.history @interfaces.legacy_generator_methods_support def evaluate_generator(self, generator, steps=None, max_queue_size=10, workers=1, use_multiprocessing=False):
pytest tests/keras/engine/test_training.py::test_model_methods
keras
42
class Model(Container): when using multiprocessing. steps: Total number of steps (batches of samples) to yield from `generator` before stopping. Not used if using Sequence. max_queue_size: maximum size for the generator queue worker...
class Model(Container): when using multiprocessing. steps: Total number of steps (batches of samples) to yield from `generator` before stopping. Optional for `Sequence`: if unspecified, will use the `len(generator)` as a number of steps. ...
pytest tests/keras/engine/test_training.py::test_model_methods
keras
42
class Model(Container): ' and multiple workers may duplicate your data.' ' Please consider using the`keras.utils.Sequence' ' class.')) if is_sequence: steps = len(generator) enqueuer = None try:
class Model(Container): ' and multiple workers may duplicate your data.' ' Please consider using the`keras.utils.Sequence' ' class.')) if steps is None: if is_sequence: steps = len(generator) ...
pytest tests/keras/engine/test_training.py::test_model_methods
keras
42
class Model(Container): return averages @interfaces.legacy_generator_methods_support def predict_generator(self, generator, steps, max_queue_size=10, workers=1, use_multiprocessing=False,
class Model(Container): return averages @interfaces.legacy_generator_methods_support def predict_generator(self, generator, steps=None, max_queue_size=10, workers=1, use_multiprocessing=False,
pytest tests/keras/engine/test_training.py::test_model_methods
keras
42
class Model(Container): when using multiprocessing. steps: Total number of steps (batches of samples) to yield from `generator` before stopping. Not used if using Sequence. max_queue_size: Maximum size for the generator queue. worke...
class Model(Container): when using multiprocessing. steps: Total number of steps (batches of samples) to yield from `generator` before stopping. Optional for `Sequence`: if unspecified, will use the `len(generator)` as a number of steps. ...
pytest tests/keras/engine/test_training.py::test_model_methods
keras
42
class Model(Container): ' and multiple workers may duplicate your data.' ' Please consider using the`keras.utils.Sequence' ' class.')) if is_sequence: steps = len(generator) enqueuer = None try:
class Model(Container): ' and multiple workers may duplicate your data.' ' Please consider using the`keras.utils.Sequence' ' class.')) if steps is None: if is_sequence: steps = len(generator) ...
pytest tests/keras/engine/test_training.py::test_model_methods
keras
42
class Sequential(Model): @interfaces.legacy_generator_methods_support def fit_generator(self, generator, steps_per_epoch, epochs=1, verbose=1, callbacks=None,
class Sequential(Model): @interfaces.legacy_generator_methods_support def fit_generator(self, generator, steps_per_epoch=None, epochs=1, verbose=1, callbacks=None,
pytest tests/keras/engine/test_training.py::test_model_methods
keras
42
class Sequential(Model): finished and starting the next epoch. It should typically be equal to the number of samples of your dataset divided by the batch size. epochs: Integer, total number of iterations on the data. Note that in conjunction wi...
class Sequential(Model): finished and starting the next epoch. It should typically be equal to the number of samples of your dataset divided by the batch size. Optional for `Sequence`: if unspecified, will use the `len(generator)` as a numb...
pytest tests/keras/engine/test_training.py::test_model_methods
keras
42
class Sequential(Model): at the end of every epoch. It should typically be equal to the number of samples of your validation dataset divided by the batch size. class_weight: Dictionary mapping class indices to a weight for the class. ...
class Sequential(Model): at the end of every epoch. It should typically be equal to the number of samples of your validation dataset divided by the batch size. Optional for `Sequence`: if unspecified, will use the `len(validation_data)` as ...
pytest tests/keras/engine/test_training.py::test_model_methods
keras
42
class Sequential(Model): initial_epoch=initial_epoch) @interfaces.legacy_generator_methods_support def evaluate_generator(self, generator, steps, max_queue_size=10, workers=1, use_multiprocessing=False): """Ev...
class Sequential(Model): initial_epoch=initial_epoch) @interfaces.legacy_generator_methods_support def evaluate_generator(self, generator, steps=None, max_queue_size=10, workers=1, use_multiprocessing=False): ...
pytest tests/keras/engine/test_training.py::test_model_methods
keras
42
class Sequential(Model): or (inputs, targets, sample_weights) steps: Total number of steps (batches of samples) to yield from `generator` before stopping. max_queue_size: maximum size for the generator queue workers: maximum number of processes to spin...
class Sequential(Model): or (inputs, targets, sample_weights) steps: Total number of steps (batches of samples) to yield from `generator` before stopping. Optional for `Sequence`: if unspecified, will use the `len(generator)` as a number of ste...
pytest tests/keras/engine/test_training.py::test_model_methods
keras
42
class Sequential(Model): use_multiprocessing=use_multiprocessing) @interfaces.legacy_generator_methods_support def predict_generator(self, generator, steps, max_queue_size=10, workers=1, use_multiprocessing=False, ...
class Sequential(Model): use_multiprocessing=use_multiprocessing) @interfaces.legacy_generator_methods_support def predict_generator(self, generator, steps=None, max_queue_size=10, workers=1, use_multiprocessing=Fa...
pytest tests/keras/engine/test_training.py::test_model_methods
keras
42
class Sequential(Model): generator: generator yielding batches of input samples. steps: Total number of steps (batches of samples) to yield from `generator` before stopping. max_queue_size: maximum size for the generator queue workers: maximum number of pr...
class Sequential(Model): generator: generator yielding batches of input samples. steps: Total number of steps (batches of samples) to yield from `generator` before stopping. Optional for `Sequence`: if unspecified, will use the `len(generator)` as ...
pytest tests/keras/engine/test_training.py::test_model_methods
black
9
def get_grammars(target_versions: Set[TargetVersion]) -> List[Grammar]: if not target_versions: return GRAMMARS elif all(not version.is_python2() for version in target_versions): # Python 2-compatible code, so don't try Python 3 grammar. return [ pygram.python_grammar_no_prin...
def get_grammars(target_versions: Set[TargetVersion]) -> List[Grammar]: if not target_versions: return GRAMMARS elif all(not version.is_python2() for version in target_versions): # Python 3-compatible code, so don't try Python 2 grammar return [ pygram.python_grammar_no_print...
python -m unittest -q tests.test_black.BlackTestCase.test_python2_print_function
tqdm
7
def posix_pipe(fin, fout, delim='\n', buf_size=256, # ((opt, type), ... ) RE_OPTS = re.compile(r'\n {8}(\S+)\s{2,}:\s*([^,]+)') # better split method assuming no positional args RE_SHLEX = re.compile(r'\s*--?([^\s=]+)(?:\s*|=|$)') # TODO: add custom support for some of the following? UNSUPPORTED_OPTS = ('iterable', 'g...
def posix_pipe(fin, fout, delim='\n', buf_size=256, # ((opt, type), ... ) RE_OPTS = re.compile(r'\n {8}(\S+)\s{2,}:\s*([^,]+)') # better split method assuming no positional args RE_SHLEX = re.compile(r'\s*(?<!\S)--?([^\s=]+)(?:\s*|=|$)') # TODO: add custom support for some of the following? UNSUPPORTED_OPTS = ('iterab...
python3 -m pytest tqdm/tests/tests_main.py::test_main
luigi
30
class TaskProcess(AbstractTaskProcess): self.task.trigger_event(Event.START, self.task) t0 = time.time() status = None try: new_deps = self._run_get_new_deps() if new_deps is None: status = RUNNING else: ...
class TaskProcess(AbstractTaskProcess): self.task.trigger_event(Event.START, self.task) t0 = time.time() status = None new_deps = self._run_get_new_deps() if new_deps is None: status = DONE self.task.trigger_event( ...
pytest test/test_event_callbacks.py::TestEventCallbacks::test_processing_time_handler_failure
youtube-dl
2
class InfoExtractor(object): f['url'] = initialization_url f['fragments'].append({location_key(initialization_url): initialization_url}) f['fragments'].extend(representation_ms_info['fragments']) try:...
class InfoExtractor(object): f['url'] = initialization_url f['fragments'].append({location_key(initialization_url): initialization_url}) f['fragments'].extend(representation_ms_info['fragments']) # Ac...
python -m unittest -q test.test_InfoExtractor.TestInfoExtractor.test_parse_mpd_formats
thefuck
23
from difflib import get_close_matches from functools import wraps import shelve from decorator import decorator import tempfile import os
from difflib import get_close_matches from functools import wraps import shelve from decorator import decorator from contextlib import closing import tempfile import os
pytest tests/test_utils.py::TestCache::test_with_blank_cache
thefuck
23
def cache(*depends_on): return fn(*args, **kwargs) cache_path = os.path.join(tempfile.gettempdir(), '.thefuck-cache') key = '{}.{}'.format(fn.__module__, repr(fn).split('at')[0]) etag = '.'.join(_get_mtime(name) for name in depends_on) with shelve.open(cache_path) as db: ...
def cache(*depends_on): return fn(*args, **kwargs) cache_path = os.path.join(tempfile.gettempdir(), '.thefuck-cache') # A bit obscure, but simplest way to generate unique key for # functions and methods in python 2 and 3: key = '{}.{}'.format(fn.__module__, repr(fn).split('a...
pytest tests/test_utils.py::TestCache::test_with_blank_cache
pandas
119
def _add_margins( row_names = result.index.names try: for dtype in set(result.dtypes): cols = result.select_dtypes([dtype]).columns margin_dummy[cols] = margin_dummy[cols].astype(dtype) result = result.append(margin_dummy) except TypeError:
def _add_margins( row_names = result.index.names try: # check the result column and leave floats for dtype in set(result.dtypes): cols = result.select_dtypes([dtype]).columns margin_dummy[cols] = margin_dummy[cols].apply( maybe_downcast_to_dtype, args=(dt...
pytest pandas/tests/reshape/test_pivot.py::TestPivotTable::test_margins_casted_to_float
youtube-dl
34
class ExtractorError(Exception): expected = True if video_id is not None: msg = video_id + ': ' + msg if not expected: msg = msg + u'; please report this issue on https://yt-dl.org/bug . Be sure to call youtube-dl with the --verbose flag and include its complete outpu...
class ExtractorError(Exception): expected = True if video_id is not None: msg = video_id + ': ' + msg if cause: msg += u' (caused by %r)' % cause if not expected: msg = msg + u'; please report this issue on https://yt-dl.org/bug . Be sure to call y...
python -m unittest -q test.test_utils.TestUtil.test_js_to_json
youtube-dl
34
def js_to_json(code): ([{,]\s*) ("[^"]*"|\'[^\']*\'|[a-z0-9A-Z]+) (:\s*) ([0-9.]+|true|false|"[^"]*"|\'[^\']*\'|\[|\{) ''', fix_kv, code) res = re.sub(r',(\s*\])', lambda m: m.group(1), res) return res
def js_to_json(code): ([{,]\s*) ("[^"]*"|\'[^\']*\'|[a-z0-9A-Z]+) (:\s*) ([0-9.]+|true|false|"[^"]*"|\'[^\']*\'| (?=\[|\{) ) ''', fix_kv, code) res = re.sub(r',(\s*\])', lambda m: m.group(1), res) return res
python -m unittest -q test.test_utils.TestUtil.test_js_to_json
pandas
45
and Index.__new__. These should not depend on core.internals. """ from typing import TYPE_CHECKING, Any, Optional, Sequence, Union, cast import numpy as np
and Index.__new__. These should not depend on core.internals. """ from collections import abc from typing import TYPE_CHECKING, Any, Optional, Sequence, Union, cast import numpy as np
pytest pandas/tests/frame/test_constructors.py::TestDataFrameConstructorWithDatetimeTZ::test_construction_from_set_raises
pandas
45
def sanitize_array( # GH#16804 arr = np.arange(data.start, data.stop, data.step, dtype="int64") subarr = _try_cast(arr, dtype, copy, raise_cast_failure) else: subarr = _try_cast(data, dtype, copy, raise_cast_failure)
def sanitize_array( # GH#16804 arr = np.arange(data.start, data.stop, data.step, dtype="int64") subarr = _try_cast(arr, dtype, copy, raise_cast_failure) elif isinstance(data, abc.Set): raise TypeError("Set type is unordered") else: subarr = _try_cast(data, dtype, copy, ra...
pytest pandas/tests/frame/test_constructors.py::TestDataFrameConstructorWithDatetimeTZ::test_construction_from_set_raises
keras
4
class TFOptimizer(Optimizer): @interfaces.legacy_get_updates_support def get_updates(self, loss, params): grads = self.optimizer.compute_gradients(loss, params) self.updates = [K.update_add(self.iterations, 1)] opt_update = self.optimizer.apply_gradients( grads, global_step=...
class TFOptimizer(Optimizer): @interfaces.legacy_get_updates_support def get_updates(self, loss, params): grads = self.optimizer.compute_gradients(loss, var_list=params) self.updates = [K.update_add(self.iterations, 1)] opt_update = self.optimizer.apply_gradients( grads, glo...
pytest tests/keras/optimizers_test.py::test_tfoptimizer_pass_correct_named_params_to_native_tensorflow_optimizer
youtube-dl
15
def js_to_json(code): "(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"| '(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'| {comment}|,(?={skip}[\]}}])| [a-zA-Z_][.a-zA-Z_0-9]*| \b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:{skip}:)?| [0-9]+(?={skip}:) '''.format(comment=COMMENT_R...
def js_to_json(code): "(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"| '(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'| {comment}|,(?={skip}[\]}}])| (?:(?<![0-9])[eE]|[a-df-zA-DF-Z_])[.a-zA-Z_0-9]*| \b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:{skip}:)?| [0-9]+(?={skip}:) '''...
python -m unittest -q test.test_utils.TestUtil.test_js_to_json_edgecases test.test_utils.TestUtil.test_js_to_json_realworld
pandas
138
from pandas._libs.lib import infer_dtype from pandas.core.dtypes.common import ( _NS_DTYPE, ensure_int64, is_categorical_dtype, is_datetime64_dtype, is_datetime64tz_dtype,
from pandas._libs.lib import infer_dtype from pandas.core.dtypes.common import ( _NS_DTYPE, ensure_int64, is_bool_dtype, is_categorical_dtype, is_datetime64_dtype, is_datetime64tz_dtype,
pytest pandas/tests/reshape/test_qcut.py::test_qcut_bool_coercion_to_int
pandas
138
def _bins_to_cuts( def _coerce_to_type(x): """ if the passed data is of datetime/timedelta type, this method converts it to numeric so that cut method can handle it """ dtype = None
def _bins_to_cuts( def _coerce_to_type(x): """ if the passed data is of datetime/timedelta or bool type, this method converts it to numeric so that cut or qcut method can handle it """ dtype = None
pytest pandas/tests/reshape/test_qcut.py::test_qcut_bool_coercion_to_int
pandas
138
def _coerce_to_type(x): elif is_timedelta64_dtype(x): x = to_timedelta(x) dtype = np.dtype("timedelta64[ns]") if dtype is not None: # GH 19768: force NaT to NaN during integer conversion
def _coerce_to_type(x): elif is_timedelta64_dtype(x): x = to_timedelta(x) dtype = np.dtype("timedelta64[ns]") elif is_bool_dtype(x): # GH 20303 x = x.astype(np.int64) if dtype is not None: # GH 19768: force NaT to NaN during integer conversion
pytest pandas/tests/reshape/test_qcut.py::test_qcut_bool_coercion_to_int
pandas
138
def test_timedelta_cut_roundtrip(): ["0 days 23:57:07.200000", "2 days 00:00:00", "3 days 00:00:00"] ) tm.assert_index_equal(result_bins, expected_bins)
def test_timedelta_cut_roundtrip(): ["0 days 23:57:07.200000", "2 days 00:00:00", "3 days 00:00:00"] ) tm.assert_index_equal(result_bins, expected_bins) @pytest.mark.parametrize("bins", [6, 7]) @pytest.mark.parametrize( "box, compare", [ (Series, tm.assert_series_equal), (np.ar...
pytest pandas/tests/reshape/test_qcut.py::test_qcut_bool_coercion_to_int
tornado
7
import time import traceback import math from tornado.concurrent import TracebackFuture, is_future from tornado.log import app_log, gen_log from tornado.platform.auto import set_close_exec, Waker from tornado import stack_context
import time import traceback import math from tornado.concurrent import TracebackFuture, is_future, chain_future from tornado.log import app_log, gen_log from tornado.platform.auto import set_close_exec, Waker from tornado import stack_context
python -m unittest -q tornado.test.ioloop_test.TestIOLoopFutures.test_run_in_executor_native
tornado
7
class IOLoop(Configurable): from tornado.process import cpu_count self._executor = ThreadPoolExecutor(max_workers=(cpu_count() * 5)) executor = self._executor return executor.submit(func, *args) def set_default_executor(self, executor): """Sets the defau...
class IOLoop(Configurable): from tornado.process import cpu_count self._executor = ThreadPoolExecutor(max_workers=(cpu_count() * 5)) executor = self._executor c_future = executor.submit(func, *args) # Concurrent Futures are not usable with await. Wrap this in ...
python -m unittest -q tornado.test.ioloop_test.TestIOLoopFutures.test_run_in_executor_native
pandas
99
from pandas.core.dtypes.generic import ( ) from pandas.core.dtypes.missing import notna from pandas.core import algorithms from pandas.core.algorithms import unique
from pandas.core.dtypes.generic import ( ) from pandas.core.dtypes.missing import notna from pandas.arrays import IntegerArray from pandas.core import algorithms from pandas.core.algorithms import unique
pytest pandas/tests/indexes/datetimes/test_tools.py::test_nullable_integer_to_datetime
pandas
99
def _convert_listlike_datetimes( elif unit is not None: if format is not None: raise ValueError("cannot specify both format and unit") arg = getattr(arg, "values", arg) result, tz_parsed = tslib.array_with_unit_to_datetime(arg, unit, errors=errors) if errors == "ignore": ...
def _convert_listlike_datetimes( elif unit is not None: if format is not None: raise ValueError("cannot specify both format and unit") arg = getattr(arg, "_values", arg) # GH 30050 pass an ndarray to tslib.array_with_unit_to_datetime # because it expects an ndarray argum...
pytest pandas/tests/indexes/datetimes/test_tools.py::test_nullable_integer_to_datetime