buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
class RNN(Layer):
output_shape = (input_shape[0], output_dim)
if self.return_state:
state_shape = [(input_shape[0], output_dim) for _ in self.states]
return [output_shape] + state_shape
else:
return output_shape | class RNN(Layer):
output_shape = (input_shape[0], output_dim)
if self.return_state:
state_shape = [(input_shape[0], dim) for dim in state_size]
return [output_shape] + state_shape
else:
return output_shape |
def test_stacked_rnn_attributes():
assert layer.get_losses_for(x) == [y]
@rnn_test
def test_batch_size_equal_one(layer_class):
inputs = Input(batch_shape=(1, timesteps, embedding_dim)) | def test_stacked_rnn_attributes():
assert layer.get_losses_for(x) == [y]
@keras_test
def test_stacked_rnn_compute_output_shape():
cells = [recurrent.LSTMCell(3),
recurrent.LSTMCell(6)]
layer = recurrent.RNN(cells, return_state=True, return_sequences=True)
output_shape = layer.compute_outp... |
except ImportError:
from ordereddict import OrderedDict
from luigi import six
class TaskClassException(Exception): | except ImportError:
from ordereddict import OrderedDict
from luigi import six
import logging
logger = logging.getLogger('luigi-interface')
class TaskClassException(Exception): |
from helpers import unittest
import luigi
import luigi.date_interval
import luigi.notifications
| from helpers import unittest
import luigi
import luigi.worker
import luigi.date_interval
import luigi.notifications
|
class InstanceTest(unittest.TestCase):
self.assertNotEqual(dummy_1, dummy_2)
self.assertEqual(dummy_1, dummy_1b)
if __name__ == '__main__':
unittest.main() | class InstanceTest(unittest.TestCase):
self.assertNotEqual(dummy_1, dummy_2)
self.assertEqual(dummy_1, dummy_1b)
def test_unhashable_type(self):
# See #857
class DummyTask(luigi.Task):
x = luigi.Parameter()
dummy = DummyTask(x={})
if __name__ == '__main__':
... |
all about the internals of models in order to get the information it needs.
"""
import difflib
import functools
from collections import Counter, OrderedDict, namedtuple
from collections.abc import Iterator, Mapping
from itertools import chain, count, product | all about the internals of models in order to get the information it needs.
"""
import difflib
import functools
import re
from collections import Counter, OrderedDict, namedtuple
from collections.abc import Iterator, Mapping
from itertools import chain, count, product |
from django.utils.tree import Node
__all__ = ['Query', 'RawQuery']
def get_field_names_from_opts(opts):
return set(chain.from_iterable( | from django.utils.tree import Node
__all__ = ['Query', 'RawQuery']
# Quotation marks ('"`[]), whitespace characters, semicolons, or inline
# SQL comments are forbidden in column aliases.
FORBIDDEN_ALIAS_PATTERN = re.compile(r"['`\"\]\[;\s]|--|/\*|\*/")
def get_field_names_from_opts(opts):
return set(chain.from_... |
class Query:
alias = seen[int_model] = join_info.joins[-1]
return alias or seen[None]
def add_annotation(self, annotation, alias, is_summary=False):
"""Add a single annotation expression to the Query."""
annotation = annotation.resolve_expression(self, allow_joins=True, reuse=No... | class Query:
alias = seen[int_model] = join_info.joins[-1]
return alias or seen[None]
def check_alias(self, alias):
if FORBIDDEN_ALIAS_PATTERN.search(alias):
raise ValueError(
"Column aliases cannot contain whitespace characters, quotation marks, "
... |
class Query:
else:
param_iter = iter([])
for name, entry in select.items():
entry = str(entry)
entry_params = []
pos = entry.find("%s") | class Query:
else:
param_iter = iter([])
for name, entry in select.items():
self.check_alias(name)
entry = str(entry)
entry_params = []
pos = entry.find("%s") |
class AggregateTestCase(TestCase):
Book.objects.aggregate(is_book=True)
with self.assertRaisesMessage(TypeError, msg % ', '.join([str(FloatField()), 'True'])):
Book.objects.aggregate(FloatField(), Avg('price'), is_book=True) | class AggregateTestCase(TestCase):
Book.objects.aggregate(is_book=True)
with self.assertRaisesMessage(TypeError, msg % ', '.join([str(FloatField()), 'True'])):
Book.objects.aggregate(FloatField(), Avg('price'), is_book=True)
def test_alias_sql_injection(self):
crafted_alias ... |
class NonAggregateAnnotationTestCase(TestCase):
total_books=Subquery(long_books_qs, output_field=IntegerField()),
).values('name')
self.assertCountEqual(publisher_books_qs, [{'name': 'Sams'}, {'name': 'Morgan Kaufmann'}]) | class NonAggregateAnnotationTestCase(TestCase):
total_books=Subquery(long_books_qs, output_field=IntegerField()),
).values('name')
self.assertCountEqual(publisher_books_qs, [{'name': 'Sams'}, {'name': 'Morgan Kaufmann'}])
def test_alias_sql_injection(self):
crafted_alias = """in... |
class ValuesExpressionsTests(TestCase):
[{'salary': 10}, {'salary': 20}, {'salary': 30}],
)
def test_values_expression_group_by(self):
# values() applies annotate() first, so values selected are grouped by
# id, not firstname. | class ValuesExpressionsTests(TestCase):
[{'salary': 10}, {'salary': 20}, {'salary': 30}],
)
def test_values_expression_alias_sql_injection(self):
crafted_alias = """injected_name" from "expressions_company"; --"""
msg = (
"Column aliases cannot contain whitespace cha... |
class Queries5Tests(TestCase):
'bar %s'
)
class SelectRelatedTests(TestCase):
def test_tickets_3045_3288(self): | class Queries5Tests(TestCase):
'bar %s'
)
def test_extra_select_alias_sql_injection(self):
crafted_alias = """injected_name" from "queries_note"; --"""
msg = (
"Column aliases cannot contain whitespace characters, quotation marks, "
"semicolons, or SQL co... |
class HttpRequest(object):
"""Return the HTTP host using the environment or request headers."""
host = self._get_raw_host()
# There is no hostname validation when DEBUG=True
if settings.DEBUG:
return host
domain, port = split_domain_port(host)
if domain and ... | class HttpRequest(object):
"""Return the HTTP host using the environment or request headers."""
host = self._get_raw_host()
# Allow variants of localhost if ALLOWED_HOSTS is empty and DEBUG=True.
allowed_hosts = settings.ALLOWED_HOSTS
if settings.DEBUG and not allowed_hosts:
... |
class HostValidationTests(SimpleTestCase):
self.assertEqual(request.get_port(), '8080')
@override_settings(DEBUG=True, ALLOWED_HOSTS=[])
def test_host_validation_disabled_in_debug_mode(self):
"""If ALLOWED_HOSTS is empty and DEBUG is True, all hosts pass."""
request = HttpRequest()
... | class HostValidationTests(SimpleTestCase):
self.assertEqual(request.get_port(), '8080')
@override_settings(DEBUG=True, ALLOWED_HOSTS=[])
def test_host_validation_in_debug_mode(self):
"""
If ALLOWED_HOSTS is empty and DEBUG is True, variants of localhost are
allowed.
"""
... |
class RNN(Layer):
self._num_constants = len(constants)
additional_specs += self.constants_spec
# at this point additional_inputs cannot be empty
is_keras_tensor = hasattr(additional_inputs[0], '_keras_history')
for tensor in additional_inputs:
if hasattr(tenso... | class RNN(Layer):
self._num_constants = len(constants)
additional_specs += self.constants_spec
# at this point additional_inputs cannot be empty
is_keras_tensor = K.is_keras_tensor(additional_inputs[0])
for tensor in additional_inputs:
if K.is_keras_tensor(ten... |
class Bidirectional(Wrapper):
self.supports_masking = True
self._trainable = True
super(Bidirectional, self).__init__(layer, **kwargs)
@property
def trainable(self): | class Bidirectional(Wrapper):
self.supports_masking = True
self._trainable = True
super(Bidirectional, self).__init__(layer, **kwargs)
self.input_spec = layer.input_spec
@property
def trainable(self): |
class Bidirectional(Wrapper):
return [output_shape] + state_shape + copy.copy(state_shape)
return output_shape
def call(self, inputs, training=None, mask=None, initial_state=None):
kwargs = {}
if has_arg(self.layer.call, 'training'): | class Bidirectional(Wrapper):
return [output_shape] + state_shape + copy.copy(state_shape)
return output_shape
def __call__(self, inputs, initial_state=None, **kwargs):
if isinstance(inputs, list):
if len(inputs) > 1:
initial_state = inputs[1:]
in... |
class Bidirectional(Wrapper):
kwargs['mask'] = mask
if initial_state is not None and has_arg(self.layer.call, 'initial_state'):
if not isinstance(initial_state, list):
raise ValueError(
'When passing `initial_state` to a Bidirectional RNN, the state '... | class Bidirectional(Wrapper):
kwargs['mask'] = mask
if initial_state is not None and has_arg(self.layer.call, 'initial_state'):
forward_state = initial_state[:len(initial_state) // 2]
backward_state = initial_state[len(initial_state) // 2:]
y = self.forward_layer... |
def test_Bidirectional_state_reuse():
timesteps = 3
units = 3
inputs = Input((timesteps, dim))
layer = wrappers.Bidirectional(rnn(units, return_state=True, return_sequences=True))
outputs = layer(inputs)
output, state = outputs[0], outputs[1:]
# test passing invalid initial_state: passing ... | def test_Bidirectional_state_reuse():
timesteps = 3
units = 3
input1 = Input((timesteps, dim))
layer = wrappers.Bidirectional(rnn(units, return_state=True, return_sequences=True))
state = layer(input1)[1:]
# test passing invalid initial_state: passing a tensor
input2 = Input((timesteps, di... |
def _make_wrapped_arith_op_with_freq(opname: str):
if result is NotImplemented:
return NotImplemented
new_freq = self._get_addsub_freq(other)
result._freq = new_freq
return result
| def _make_wrapped_arith_op_with_freq(opname: str):
if result is NotImplemented:
return NotImplemented
new_freq = self._get_addsub_freq(other, result)
result._freq = new_freq
return result
|
class DatetimeIndexOpsMixin(ExtensionIndex):
# --------------------------------------------------------------------
# Arithmetic Methods
def _get_addsub_freq(self, other) -> Optional[DateOffset]:
"""
Find the freq we expect the result of an addition/subtraction operation
to have.
... | class DatetimeIndexOpsMixin(ExtensionIndex):
# --------------------------------------------------------------------
# Arithmetic Methods
def _get_addsub_freq(self, other, result) -> Optional[DateOffset]:
"""
Find the freq we expect the result of an addition/subtraction operation
to ... |
class TestPeriodIndexSeriesMethods:
tm.assert_index_equal(result, exp)
exp = pd.TimedeltaIndex([np.nan, np.nan, np.nan, np.nan], name="idx")
tm.assert_index_equal(idx - pd.Period("NaT", freq="M"), exp)
tm.assert_index_equal(pd.Period("NaT", freq="M") - idx, exp)
def test_pi_sub_pdn... | class TestPeriodIndexSeriesMethods:
tm.assert_index_equal(result, exp)
exp = pd.TimedeltaIndex([np.nan, np.nan, np.nan, np.nan], name="idx")
result = idx - pd.Period("NaT", freq="M")
tm.assert_index_equal(result, exp)
assert result.freq == exp.freq
result = pd.Period("N... |
def stderr(branch_name):
def new_command(branch_name):
return [cmd.format(branch_name) for cmd in [
'git branch -d {0} && git branch {0}',
'git branch -D {0} && git branch {0}', 'git checkout {0}']]
@pytest.mark.parametrize('script, branch_name', [
('git branch foo', 'foo'),
('git branch b... | def stderr(branch_name):
def new_command(branch_name):
return [cmd.format(branch_name) for cmd in [
'git branch -d {0} && git branch {0}',
'git branch -d {0} && git checkout -b {0}',
'git branch -D {0} && git branch {0}',
'git branch -D {0} && git checkout -b {0}', 'git checkout {0}'... |
from thefuck.utils import eager
@git_support
def match(command):
return ('branch' in command.script
and "fatal: A branch named '" in command.stderr
and " already exists." in command.stderr)
| from thefuck.utils import eager
@git_support
def match(command):
return ("fatal: A branch named '" in command.stderr
and " already exists." in command.stderr)
|
def get_new_command(command):
branch_name = re.findall(
r"fatal: A branch named '([^']*)' already exists.", command.stderr)[0]
new_command_templates = [['git branch -d {0}', 'git branch {0}'],
['git branch -D {0}', 'git branch {0}'],
['git checko... | def get_new_command(command):
branch_name = re.findall(
r"fatal: A branch named '([^']*)' already exists.", command.stderr)[0]
new_command_templates = [['git branch -d {0}', 'git branch {0}'],
['git branch -d {0}', 'git checkout -b {0}'],
['git b... |
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): |
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'... |
class HttpProxyTestCase(unittest.TestCase):
request = Request('https://example.com', meta={'proxy': http_proxy})
return self.download_request(request, Spider('foo')).addCallback(_test)
def test_download_without_proxy(self):
def _test(response):
self.assertEquals(response.status,... | class HttpProxyTestCase(unittest.TestCase):
request = Request('https://example.com', meta={'proxy': http_proxy})
return self.download_request(request, Spider('foo')).addCallback(_test)
@defer.inlineCallbacks
def test_download_with_proxy_https_timeout(self):
http_proxy = self.getURL('')
... |
def test_overrun(self):
for file in [
"fli_overrun.bin",
"sgi_overrun.bin",
"pcx_overrun.bin",
"pcx_overrun2.bin",
]: | def test_overrun(self):
for file in [
"fli_overrun.bin",
"sgi_overrun.bin",
"sgi_overrun_expandrow.bin",
"sgi_overrun_expandrow2.bin",
"pcx_overrun.bin",
"pcx_overrun2.bin",
]: |
def _create_powershell_wrapper(b_module_data, module_args, environment,
exec_manifest['csharp_utils'][name] = b64_data
exec_manifest['csharp_utils_module'] = list(finder.cs_utils_module.keys())
# FUTURE: smuggle this back as a dict instead of serializing here;
# the connection plugin may need to mo... | def _create_powershell_wrapper(b_module_data, module_args, environment,
exec_manifest['csharp_utils'][name] = b64_data
exec_manifest['csharp_utils_module'] = list(finder.cs_utils_module.keys())
b_json = to_bytes(json.dumps(exec_manifest))
# delimit the payload JSON from the wrapper to keep sensitiv... |
class ActionModule(ActionBase):
# PowerShell runs the script in a special wrapper to enable things
# like become and environment args
if self._connection._shell.SHELL_FAMILY == "powershell":
# FIXME: use a more public method to get the exec payload
pc ... | class ActionModule(ActionBase):
# PowerShell runs the script in a special wrapper to enable things
# like become and environment args
if self._connection._shell.SHELL_FAMILY == "powershell":
# FUTURE: use a more public method to get the exec payload
pc... |
class Connection(ConnectionBase):
# starting a new interpreter to save on time
b_command = base64.b64decode(cmd.split(" ")[-1])
script = to_text(b_command, 'utf-16-le')
display.vvv("PSRP: EXEC %s" % script, host=self._psrp_host)
else:
# in other cases ... | class Connection(ConnectionBase):
# starting a new interpreter to save on time
b_command = base64.b64decode(cmd.split(" ")[-1])
script = to_text(b_command, 'utf-16-le')
in_data = to_text(in_data, errors="surrogate_or_strict", nonstring="passthru")
display.vvv(... |
import traceback
import json
import tempfile
import subprocess
HAVE_KERBEROS = False
try: | import traceback
import json
import tempfile
import subprocess
import xml.etree.ElementTree as ET
HAVE_KERBEROS = False
try: |
class Connection(ConnectionBase):
return (result.status_code, result.std_out, result.std_err)
def is_clixml(self, value):
return value.startswith(b"#< CLIXML")
# hacky way to get just stdout- not always sure of doc framing here, so use with care
def parse_clixml_stream(self, clixml_doc, st... | class Connection(ConnectionBase):
return (result.status_code, result.std_out, result.std_err)
def is_clixml(self, value):
return value.startswith(b"#< CLIXML\r\n")
# hacky way to get just stdout- not always sure of doc framing here, so use with care
def parse_clixml_stream(self, clixml_doc... |
import base64
import os
import re
import shlex
from ansible.errors import AnsibleError
from ansible.module_utils._text import to_text | import base64
import os
import re
import shlex
import pkgutil
from ansible.errors import AnsibleError
from ansible.module_utils._text import to_text |
class ShellModule(ShellBase):
return self._encode_script(script)
def build_module_command(self, env_string, shebang, cmd, arg_path=None):
# pipelining bypass
if cmd == '':
return '-'
# non-pipelining
| class ShellModule(ShellBase):
return self._encode_script(script)
def build_module_command(self, env_string, shebang, cmd, arg_path=None):
bootstrap_wrapper = pkgutil.get_data("ansible.executor.powershell", "bootstrap_wrapper.ps1")
# pipelining bypass
if cmd == '':
retur... |
class ShellModule(ShellBase):
cmd_parts = list(map(to_text, cmd_parts))
if shebang and shebang.lower() == '#!powershell':
if not self._unquote(cmd_parts[0]).lower().endswith('.ps1'):
cmd_parts[0] = '"%s.ps1"' % self._unquote(cmd_parts[0])
cmd_parts.insert(0, '&')
... | class ShellModule(ShellBase):
cmd_parts = list(map(to_text, cmd_parts))
if shebang and shebang.lower() == '#!powershell':
if not self._unquote(cmd_parts[0]).lower().endswith('.ps1'):
# we're running a module via the bootstrap wrapper
cmd_parts[0] = '"%s.ps1"' ... |
from django.utils.text import normalize_newlines
from .html_parser import HTMLParseError, HTMLParser
# Configuration for urlize() function.
TRAILING_PUNCTUATION_RE = re.compile(
'^' # Beginning of word
'(.*?)' # The URL in word
'([.,:;!]+)' # Allowed non-wrapping, trailing punctuation
... | from django.utils.text import normalize_newlines
from .html_parser import HTMLParseError, HTMLParser
# Configuration for urlize() function.
TRAILING_PUNCTUATION_CHARS = '.,:;!'
WRAPPING_PUNCTUATION = [('(', ')'), ('<', '>'), ('[', ']'), ('<', '>'), ('"', '"'), ('\'', '\'')]
# List of possible strings used for b... |
unencoded_ampersands_re = re.compile(r'&(?!(\w+|#\d+);)')
word_split_re = re.compile(r'''([\s<>"']+)''')
simple_url_re = re.compile(r'^https?://\[?\w', re.IGNORECASE)
simple_url_2_re = re.compile(r'^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)($|/.*)$', re.IGNORECASE)
simple_email_re = re.compile(r'^\S+@\S+\.\... | unencoded_ampersands_re = re.compile(r'&(?!(\w+|#\d+);)')
word_split_re = re.compile(r'''([\s<>"']+)''')
simple_url_re = re.compile(r'^https?://\[?\w', re.IGNORECASE)
simple_url_2_re = re.compile(r'^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)($|/.*)$', re.IGNORECASE)
@keep_lazy(six.text_type, SafeText) |
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
trimmed_something = False
# Trim trailing punctuation.
match = TRAILING_PUNCTUATION_RE.match(middle)
if match:
middle = match.group(1)
trail = match.group(2) + trail
... | def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
trimmed_something = False
# Trim trailing punctuation.
stripped = middle.rstrip(TRAILING_PUNCTUATION_CHARS)
if middle != stripped:
trail = middle[len(stripped):] + trail
... |
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
trimmed_something = True
return lead, middle, trail
words = word_split_re.split(force_text(text))
for i, word in enumerate(words):
if '.' in word or '@' in word or ':' in word: | def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
trimmed_something = True
return lead, middle, trail
def is_email_simple(value):
"""Return True if value looks like an email address."""
# An @ must be in the middle of the value.
if '@' not ... |
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
elif simple_url_2_re.match(middle):
middle, middle_unescaped, trail = unescape(middle, trail)
url = smart_urlquote('http://%s' % middle_unescaped)
elif ':' not in middle and simple_email_re.m... | def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
elif simple_url_2_re.match(middle):
middle, middle_unescaped, trail = unescape(middle, trail)
url = smart_urlquote('http://%s' % middle_unescaped)
elif ':' not in middle and is_email_simple(m... |
class TestUtilsHtml(SimpleTestCase):
@html.html_safe
class HtmlClass(object):
pass | class TestUtilsHtml(SimpleTestCase):
@html.html_safe
class HtmlClass(object):
pass
def test_urlize_unchanged_inputs(self):
tests = (
('a' + '@a' * 50000) + 'a', # simple_email_re catastrophic test
('a' + '.' * 1000000) + 'a', # trailing_punc... |
from itertools import cycle as itertools_cycle, groupby
from django.conf import settings
from django.utils import timezone
from django.utils.html import conditional_escape, format_html
from django.utils.lorem_ipsum import paragraphs, words
from django.utils.safestring import mark_safe
| from itertools import cycle as itertools_cycle, groupby
from django.conf import settings
from django.utils import timezone
from django.utils.html import conditional_escape, escape, format_html
from django.utils.lorem_ipsum import paragraphs, words
from django.utils.safestring import mark_safe
|
class CycleNode(Node):
class DebugNode(Node):
def render(self, context):
from pprint import pformat
output = [pformat(val) for val in context]
output.append('\n\n')
output.append(pformat(sys.modules))
return ''.join(output)
| class CycleNode(Node):
class DebugNode(Node):
def render(self, context):
if not settings.DEBUG:
return ''
from pprint import pformat
output = [escape(pformat(val)) for val in context]
output.append('\n\n')
output.append(escape(pformat(sys.modules)))
retu... |
import sys
from django.contrib.auth.models import Group
from django.template import (
Context, Engine, TemplateDoesNotExist, TemplateSyntaxError,
) | import sys
from django.template import (
Context, Engine, TemplateDoesNotExist, TemplateSyntaxError,
) |
class TemplateTestMixin:
with self.assertRaises(NoReverseMatch):
t.render(Context())
def test_debug_tag_non_ascii(self):
"""
#23060 -- Test non-ASCII model representation in debug output.
"""
group = Group(name="清風")
c1 = Context({"objs": [group]})
... | class TemplateTestMixin:
with self.assertRaises(NoReverseMatch):
t.render(Context())
def test_extends_generic_template(self):
"""
#24338 -- Allow extending django.template.backends.django.Template |
class Parser:
if (new_data == data).all():
data = new_data
result = True
except (TypeError, ValueError):
pass
# coerce ints to 64 | class Parser:
if (new_data == data).all():
data = new_data
result = True
except (TypeError, ValueError, OverflowError):
pass
# coerce ints to 64 |
DataFrame\\.index values are different \\(100\\.0 %\\)
with tm.assert_produces_warning(FutureWarning):
result = read_json(expected.to_json(), numpy=True)
tm.assert_frame_equal(result, expected) | DataFrame\\.index values are different \\(100\\.0 %\\)
with tm.assert_produces_warning(FutureWarning):
result = read_json(expected.to_json(), numpy=True)
tm.assert_frame_equal(result, expected)
def test_frame_int_overflow(self):
# GH 30320
encoded_json = json.dumps([... |
TECHNICAL_500_TEMPLATE = ("""
<h2>Traceback <span class="commands">{% if not is_email %}<a href="#" onclick="return switchPastebinFriendly(this);">
Switch to copy-and-paste view</a></span>{% endif %}
</h2>
{% autoescape off %}
<div id="browserTraceback">
<ul class="traceback">
{% for frame in fram... | TECHNICAL_500_TEMPLATE = ("""
<h2>Traceback <span class="commands">{% if not is_email %}<a href="#" onclick="return switchPastebinFriendly(this);">
Switch to copy-and-paste view</a></span>{% endif %}
</h2>
<div id="browserTraceback">
<ul class="traceback">
{% for frame in frames %}
{% ifchan... |
TECHNICAL_500_TEMPLATE = ("""
<tbody>
{% for var in frame.vars|dictsort:0 %}
<tr>
<td>{{ var.0|force_escape }}</td>
<td class="code"><pre>{{ var.1 }}</pre></td>
</tr>
{% endfor %} | TECHNICAL_500_TEMPLATE = ("""
<tbody>
{% for var in frame.vars|dictsort:0 %}
<tr>
<td>{{ var.0 }}</td>
<td class="code"><pre>{{ var.1 }}</pre></td>
</tr>
{% endfor %} |
TECHNICAL_500_TEMPLATE = ("""
{% endfor %}
</ul>
</div>
{% endautoescape %}
<form action="http://dpaste.com/" name="pasteform" id="pasteform" method="post">
{% if not is_email %}
<div id="pastebinTraceback" class="pastebin"> | TECHNICAL_500_TEMPLATE = ("""
{% endfor %}
</ul>
</div>
<form action="http://dpaste.com/" name="pasteform" id="pasteform" method="post">
{% if not is_email %}
<div id="pastebinTraceback" class="pastebin"> |
In template {{ template_info.name }}, error at line {{ template_info.line }}
Traceback:{% for frame in frames %}
{% ifchanged frame.exc_cause %}{% if frame.exc_cause %}{% if frame.exc_cause_explicit %}
The above exception ({{ frame.exc_cause }}) was the direct cause of the following exception:
{% else %}
During handli... | In template {{ template_info.name }}, error at line {{ template_info.line }}
Traceback:{% for frame in frames %}
{% ifchanged frame.exc_cause %}{% if frame.exc_cause %}{% if frame.exc_cause_explicit %}
The above exception ({{ frame.exc_cause|force_escape }}) was the direct cause of the following exception:
{% else %}
... |
error (raise ... from ...) can't be silenced using NOQA.
import sys
from django.test import RequestFactory, TestCase
from django.views.debug import ExceptionReporter
| error (raise ... from ...) can't be silenced using NOQA.
import sys
from django.test import RequestFactory, TestCase
from django.utils.safestring import mark_safe
from django.views.debug import ExceptionReporter
|
class Py3ExceptionReporterTests(TestCase):
request = self.rf.get('/test_view/')
try:
try:
raise AttributeError('Top level')
except AttributeError as explicit:
try:
raise ValueError('Second exception') from explicit
... | class Py3ExceptionReporterTests(TestCase):
request = self.rf.get('/test_view/')
try:
try:
raise AttributeError(mark_safe('<p>Top level</p>'))
except AttributeError as explicit:
try:
raise ValueError('<p>Second exception</p>') fr... |
class Py3ExceptionReporterTests(TestCase):
html = reporter.get_traceback_html()
# Both messages are twice on page -- one rendered as html,
# one as plain text (for pastebin)
self.assertEqual(2, html.count(explicit_exc.format("Top level")))
self.assertEqual(2, html.count(implicit_... | class Py3ExceptionReporterTests(TestCase):
html = reporter.get_traceback_html()
# Both messages are twice on page -- one rendered as html,
# one as plain text (for pastebin)
self.assertEqual(2, html.count(explicit_exc.format('<p>Top level</p>')))
self.assertEqual(2, h... |
def decode_bytes(src: bytes) -> Tuple[FileContent, Encoding, NewLine]:
"""
srcbuf = io.BytesIO(src)
encoding, lines = tokenize.detect_encoding(srcbuf.readline)
newline = "\r\n" if b"\r\n" == lines[0][-2:] else "\n"
srcbuf.seek(0)
with io.TextIOWrapper(srcbuf, encoding) as tiow: | def decode_bytes(src: bytes) -> Tuple[FileContent, Encoding, NewLine]:
"""
srcbuf = io.BytesIO(src)
encoding, lines = tokenize.detect_encoding(srcbuf.readline)
if not lines:
return "", encoding, "\n"
newline = "\r\n" if b"\r\n" == lines[0][-2:] else "\n"
srcbuf.seek(0)
with io.TextI... |
GRAMMARS = [
def lib2to3_parse(src_txt: str) -> Node:
"""Given a string with source, return the lib2to3 Node."""
grammar = pygram.python_grammar_no_print_statement
if src_txt[-1] != "\n":
src_txt += "\n"
for grammar in GRAMMARS:
drv = driver.Driver(grammar, pytree.convert) | GRAMMARS = [
def lib2to3_parse(src_txt: str) -> Node:
"""Given a string with source, return the lib2to3 Node."""
grammar = pygram.python_grammar_no_print_statement
if src_txt[-1:] != "\n":
src_txt += "\n"
for grammar in GRAMMARS:
drv = driver.Driver(grammar, pytree.convert) |
class BlackTestCase(unittest.TestCase):
black.err(str(ve))
self.assertEqual(expected, actual)
@patch("black.dump_to_file", dump_to_stderr)
def test_self(self) -> None:
source, expected = read_data("test_black") | class BlackTestCase(unittest.TestCase):
black.err(str(ve))
self.assertEqual(expected, actual)
@patch("black.dump_to_file", dump_to_stderr)
def test_empty(self) -> None:
source = expected = ""
actual = fs(source)
self.assertFormatEqual(expected, actual)
bl... |
from .helper import on_ci
"Tests/images/crash_1.tif",
"Tests/images/crash_2.tif",
"Tests/images/crash-2020-10-test.tif",
],
)
@pytest.mark.filterwarnings("ignore:Possibly corrupt EXIF data") | from .helper import on_ci
"Tests/images/crash_1.tif",
"Tests/images/crash_2.tif",
"Tests/images/crash-2020-10-test.tif",
"Tests/images/crash-1152ec2d1a1a71395b6f2ce6721c38924d025bf3.tif",
"Tests/images/crash-0e16d3bfb83be87356d026d66919deaefca44dac.tif",
],
)
@pytest.mark.fil... |
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 |
class TestExcelWriter:
):
write_frame.to_excel(path, "test1", columns=["C", "D"])
def test_comment_arg(self, path):
# see gh-18735
# | class TestExcelWriter:
):
write_frame.to_excel(path, "test1", columns=["C", "D"])
@pytest.mark.parametrize(
"to_excel_index,read_excel_index_col",
[
(True, 0), # Include index in write to file
(False, None), # Dont include index in write to file
... |
def parse_uri(self, uri):
", you need to change it to use the "
"swift+http:// scheme, like so: "
"swift+http://user:pass@authurl.com/v1/container/obj")
LOG.debug(_("Invalid store uri %(uri)s: %(reason)s") % locals())
raise exc... | def parse_uri(self, uri):
", you need to change it to use the "
"swift+http:// scheme, like so: "
"swift+http://user:pass@authurl.com/v1/container/obj")
LOG.debug(_("Invalid store URI: %(reason)s") % locals())
raise exception.B... |
def parse_uri(self, uri):
if creds:
cred_parts = creds.split(':')
if len(cred_parts) != 2:
reason = (_("Badly formed credentials '%(creds)s' in Swift "
"URI") % locals())
LOG.debug(reason)
raise exception.BadStor... | def parse_uri(self, uri):
if creds:
cred_parts = creds.split(':')
if len(cred_parts) != 2:
reason = (_("Badly formed credentials in Swift URI."))
LOG.debug(reason)
raise exception.BadStoreUri()
user, key = cred_parts |
def parse_uri(self, uri):
path_parts.insert(0, netloc)
self.auth_or_store_url = '/'.join(path_parts)
except IndexError:
reason = _("Badly formed Swift URI: %s") % uri
LOG.debug(reason)
raise exception.BadStoreUri()
| def parse_uri(self, uri):
path_parts.insert(0, netloc)
self.auth_or_store_url = '/'.join(path_parts)
except IndexError:
reason = _("Badly formed Swift URI.")
LOG.debug(reason)
raise exception.BadStoreUri()
|
def get(self, location, connection=None):
except swiftclient.ClientException, e:
if e.http_status == httplib.NOT_FOUND:
uri = location.get_uri()
raise exception.NotFound(_("Swift could not find image at "
"uri %(uri)s") % loc... | def get(self, location, connection=None):
except swiftclient.ClientException, e:
if e.http_status == httplib.NOT_FOUND:
uri = location.get_uri()
msg = _("Swift could not find image at URI.")
raise exception.NotFound(msg)
else:
... |
def add(self, image_id, image_file, image_size, connection=None):
except swiftclient.ClientException, e:
if e.http_status == httplib.CONFLICT:
raise exception.Duplicate(_("Swift already has an image at "
"location %s") %
... | def add(self, image_id, image_file, image_size, connection=None):
except swiftclient.ClientException, e:
if e.http_status == httplib.CONFLICT:
raise exception.Duplicate(_("Swift already has an image at "
"this location"))
msg = ... |
def delete(self, location, connection=None):
except swiftclient.ClientException, e:
if e.http_status == httplib.NOT_FOUND:
uri = location.get_uri()
raise exception.NotFound(_("Swift could not find image at "
"uri %(uri)s") % ... | def delete(self, location, connection=None):
except swiftclient.ClientException, e:
if e.http_status == httplib.NOT_FOUND:
uri = location.get_uri()
msg = _("Swift could not find image at URI.")
raise exception.NotFound(msg)
else:
... |
def set_acls(self, location, public=False, read_tenants=None,
except swiftclient.ClientException, e:
if e.http_status == httplib.NOT_FOUND:
uri = location.get_uri()
raise exception.NotFound(_("Swift could not find image at "
... | def set_acls(self, location, public=False, read_tenants=None,
except swiftclient.ClientException, e:
if e.http_status == httplib.NOT_FOUND:
uri = location.get_uri()
msg = _("Swift could not find image at URI.")
raise exception.NotFound(msg)
... |
def main():
download_set = {}
for pkg in download_list:
remote = pkg.returnSimple('relativepath')
rpmname = os.path.basename(remote)
download_set[rpmname] = 1
for pkg in current_pkgs: | def main():
download_set = {}
for pkg in download_list:
rpmname = os.path.basename(pkg.remote_path)
download_set[rpmname] = 1
for pkg in current_pkgs: |
def main():
remote_size = 0
if not opts.urls:
for pkg in download_list:
remote = pkg.returnSimple('relativepath')
local = local_repo_path + '/' + remote
sz = int(pkg.returnSimple('packagesize'))
if os.path.exists(local) and os.p... | def main():
remote_size = 0
if not opts.urls:
for pkg in download_list:
local = os.path.join(local_repo_path, pkg.remote_path)
sz = int(pkg.returnSimple('packagesize'))
if os.path.exists(local) and os.path.getsize(local) == sz:
... |
def main():
download_list.sort(key=lambda pkg: pkg.name)
if opts.urls:
for pkg in download_list:
remote = pkg.returnSimple('relativepath')
local = os.path.join(local_repo_path, remote)
if not (os.path.exists(local) and my.verifyPkg(local, pkg, ... | def main():
download_list.sort(key=lambda pkg: pkg.name)
if opts.urls:
for pkg in download_list:
local = os.path.join(local_repo_path, pkg.remote_path)
if not (os.path.exists(local) and my.verifyPkg(local, pkg, False)):
print urljoin(pkg.re... |
def main():
# set localpaths
for pkg in download_list:
rpmfn = pkg.remote_path
pkg.localpath = os.path.join(local_repo_path, rpmfn)
pkg.repo.copy_local = True
pkg.repo.cache = 0
localdir = os.path.dirname(pkg.localpath) | def main():
# set localpaths
for pkg in download_list:
pkg.localpath = os.path.join(local_repo_path, pkg.remote_path)
pkg.repo.copy_local = True
pkg.repo.cache = 0
localdir = os.path.dirname(pkg.localpath) |
class KerasRegressor(BaseWrapper):
Predictions.
"""
kwargs = self.filter_sk_params(Sequential.predict, kwargs)
return np.squeeze(self.model.predict(x, **kwargs))
def score(self, x, y, **kwargs):
"""Returns the mean loss on the given test data and labels. | class KerasRegressor(BaseWrapper):
Predictions.
"""
kwargs = self.filter_sk_params(Sequential.predict, kwargs)
return np.squeeze(self.model.predict(x, **kwargs), axis=-1)
def score(self, x, y, **kwargs):
"""Returns the mean loss on the given test data and labels. |
def assert_regression_works(reg):
assert preds.shape == (num_test, )
if __name__ == '__main__':
pytest.main([__file__])
| def assert_regression_works(reg):
assert preds.shape == (num_test, )
def test_regression_predict_shape_correct_num_test_0():
assert_regression_predict_shape_correct(num_test=0)
def test_regression_predict_shape_correct_num_test_1():
assert_regression_predict_shape_correct(num_test=1)
def assert_regres... |
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
try:
loc = self._get_string_slice(key)
return series[loc]
except (TypeError, ValueError):
pass
asdt, reso = parse_time_string(key, self.freq) | class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
try:
loc = self._get_string_slice(key)
return series[loc]
except (TypeError, ValueError, OverflowError):
pass
asdt, reso = parse_time_string(key, self.freq) |
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
"""
if isinstance(key, str):
try:
return self._get_string_slice(key)
except (TypeError, KeyError, ValueError, OverflowError):
pass
try:
asdt, r... | class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
"""
if isinstance(key, str):
try:
loc = self._get_string_slice(key)
return loc
except (TypeError, ValueError):
pass
try:
asdt,... |
class TestIndexing:
ps0 = [p0, p1, p2]
idx0 = pd.PeriodIndex(ps0)
for p in ps0:
assert p in idx0
assert str(p) in idx0
assert "2017-09-01 00:00:01" in idx0
assert "2017-09" in idx0
| class TestIndexing:
ps0 = [p0, p1, p2]
idx0 = pd.PeriodIndex(ps0)
ser = pd.Series(range(6, 9), index=idx0)
for p in ps0:
assert p in idx0
assert str(p) in idx0
# GH#31172
# Higher-resolution period-like are _not_ considered as contained
... |
from matplotlib._pylab_helpers import Gcf
from matplotlib.backend_managers import ToolManager
from matplotlib.transforms import Affine2D
from matplotlib.path import Path
_log = logging.getLogger(__name__) | from matplotlib._pylab_helpers import Gcf
from matplotlib.backend_managers import ToolManager
from matplotlib.transforms import Affine2D
from matplotlib.path import Path
from matplotlib.cbook import _setattr_cm
_log = logging.getLogger(__name__) |
class KeyEvent(LocationEvent):
self.key = key
def _get_renderer(figure, print_method=None, *, draw_disabled=False):
"""
Get the renderer that would be used to save a `~.Figure`, and cache it on
the figure.
If *draw_disabled* is True, additionally replace drawing methods on
*renderer* by n... | class KeyEvent(LocationEvent):
self.key = key
def _get_renderer(figure, print_method=None):
"""
Get the renderer that would be used to save a `~.Figure`, and cache it on
the figure.
If you need a renderer without any active draw methods use
cbook._setattr_cm to temporary patch them out at... |
def _get_renderer(figure, print_method=None, *, draw_disabled=False):
except Done as exc:
renderer, = figure._cachedRenderer, = exc.args
if draw_disabled:
for meth_name in dir(RendererBase):
if (meth_name.startswith("draw_")
or meth_name in ["open_group",... | def _get_renderer(figure, print_method=None, *, draw_disabled=False):
except Done as exc:
renderer, = figure._cachedRenderer, = exc.args
return renderer
|
class FigureCanvasBase:
renderer = _get_renderer(
self.figure,
functools.partial(
print_method, orientation=orientation),
draw_disabled=True)
self.figure.draw(renderer)
... | class FigureCanvasBase:
renderer = _get_renderer(
self.figure,
functools.partial(
print_method, orientation=orientation)
)
no_ops = {
meth_name: lambda *args, *... |
default: 'top'
from .tight_layout import (
get_renderer, get_subplotspec_list, get_tight_layout_figure)
subplotspec_list = get_subplotspec_list(self.axes)
if None in subplotspec_list: | default: 'top'
from .tight_layout import (
get_renderer, get_subplotspec_list, get_tight_layout_figure)
from .cbook import _setattr_cm
from .backend_bases import RendererBase
subplotspec_list = get_subplotspec_list(self.axes)
if None in subplotspec_list: |
default: 'top'
if renderer is None:
renderer = get_renderer(self)
kwargs = get_tight_layout_figure(
self, self.axes, subplotspec_list, renderer,
pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)
if kwargs:
self.subplots_adjust(**kwargs)
| default: 'top'
if renderer is None:
renderer = get_renderer(self)
no_ops = {
meth_name: lambda *args, **kwargs: None
for meth_name in dir(RendererBase)
if (meth_name.startswith("draw_")
or meth_name in ["open_group", "close_group"])
... |
def test_tight_pcolorfast():
# Previously, the bbox would include the area of the image clipped out by
# the axes, resulting in a very tall image given the y limits of (0, 0.1).
assert width > height | def test_tight_pcolorfast():
# Previously, the bbox would include the area of the image clipped out by
# the axes, resulting in a very tall image given the y limits of (0, 0.1).
assert width > height
def test_noop_tight_bbox():
from PIL import Image
x_size, y_size = (10, 7)
dpi = 100
# mak... |
def get_renderer(fig):
return canvas.get_renderer()
else:
from . import backend_bases
return backend_bases._get_renderer(fig, draw_disabled=True)
def get_subplotspec_list(axes_list, grid_spec=None): | def get_renderer(fig):
return canvas.get_renderer()
else:
from . import backend_bases
return backend_bases._get_renderer(fig)
def get_subplotspec_list(axes_list, grid_spec=None): |
class WorkerProcess(multiprocessing.Process):
# set to /dev/null
self._new_stdin = os.devnull
def run(self):
'''
Called when the process is started. Pushes the result onto the | class WorkerProcess(multiprocessing.Process):
# set to /dev/null
self._new_stdin = os.devnull
# NOTE: this works due to fork, if switching to threads this should change to per thread storage of temp files
# clear var to ensure we only delete files for this child
self._lo... |
class WorkerProcess(multiprocessing.Process):
except:
display.debug(u"WORKER EXCEPTION: %s" % to_text(e))
display.debug(u"WORKER TRACEBACK: %s" % to_text(traceback.format_exc()))
display.debug("WORKER PROCESS EXITING")
| class WorkerProcess(multiprocessing.Process):
except:
display.debug(u"WORKER EXCEPTION: %s" % to_text(e))
display.debug(u"WORKER TRACEBACK: %s" % to_text(traceback.format_exc()))
finally:
self._clean_up()
display.debug(... |
class WorkerProcess(multiprocessing.Process):
# ps.print_stats()
# with open('worker_%06d.stats' % os.getpid(), 'w') as f:
# f.write(s.getvalue()) | class WorkerProcess(multiprocessing.Process):
# ps.print_stats()
# with open('worker_%06d.stats' % os.getpid(), 'w') as f:
# f.write(s.getvalue())
def _clean_up(self):
# NOTE: see note in init about forks
# ensure we cleanup all temp files for this worker
self._l... |
class DataLoader:
'''
def __init__(self):
self._basedir = '.'
self._FILE_CACHE = dict()
self._tempfiles = set()
# initialize the vault stuff with an empty password | class DataLoader:
'''
def __init__(self):
self._basedir = '.'
# NOTE: not effective with forks as the main copy does not get updated.
# avoids rereading files
self._FILE_CACHE = dict()
# NOTE: not thread safe, also issues with forks not returning data to main proc
... |
class DataLoader:
def _create_content_tempfile(self, content):
''' Create a tempfile containing defined content '''
fd, content_tempfile = tempfile.mkstemp()
f = os.fdopen(fd, 'wb')
content = to_bytes(content)
try: | class DataLoader:
def _create_content_tempfile(self, content):
''' Create a tempfile containing defined content '''
fd, content_tempfile = tempfile.mkstemp(dir=C.DEFAULT_LOCAL_TMP)
f = os.fdopen(fd, 'wb')
content = to_bytes(content)
try: |
class DataLoader:
self._tempfiles.remove(file_path)
def cleanup_all_tmp_files(self):
for f in self._tempfiles:
try:
self.cleanup_tmp_file(f) | class DataLoader:
self._tempfiles.remove(file_path)
def cleanup_all_tmp_files(self):
"""
Removes all temporary files that DataLoader has created
NOTE: not thread safe, forks also need special handling see __init__ for details.
"""
for f in self._tempfiles:
... |
class VaultEditor:
# Create a tempfile
root, ext = os.path.splitext(os.path.realpath(filename))
fd, tmp_path = tempfile.mkstemp(suffix=ext)
os.close(fd)
cmd = self._editor_shell_command(tmp_path) | class VaultEditor:
# Create a tempfile
root, ext = os.path.splitext(os.path.realpath(filename))
fd, tmp_path = tempfile.mkstemp(suffix=ext, dir=C.DEFAULT_LOCAL_TMP)
os.close(fd)
cmd = self._editor_shell_command(tmp_path) |
import os
# Import salt libs
import salt.utils.files
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six | import os
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.verify
# Import 3rd-party libs
from salt.ext import six |
def write(data, path, saltenv='base', index=0):
if os.path.isabs(path):
return ('The path passed in {0} is not relative to the environment '
'{1}').format(path, saltenv)
dest = os.path.join(__opts__['pillar_roots'][saltenv][index], path)
dest_dir = os.path.dirname(dest)
if not os... | def write(data, path, saltenv='base', index=0):
if os.path.isabs(path):
return ('The path passed in {0} is not relative to the environment '
'{1}').format(path, saltenv)
roots_dir = __opts__['pillar_roots'][saltenv][index]
dest = os.path.join(roots_dir, path)
if not salt.utils.ve... |
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 |
class TestExcelWriter:
):
write_frame.to_excel(path, "test1", columns=["C", "D"])
def test_comment_arg(self, path):
# see gh-18735
# | class TestExcelWriter:
):
write_frame.to_excel(path, "test1", columns=["C", "D"])
@pytest.mark.parametrize(
"to_excel_index,read_excel_index_col",
[
(True, 0), # Include index in write to file
(False, None), # Dont include index in write to file
... |
class TestCustomDateRange:
result = pd.date_range(start=start, end=end, periods=2, closed="left")
expected = DatetimeIndex([start])
tm.assert_index_equal(result, expected) | class TestCustomDateRange:
result = pd.date_range(start=start, end=end, periods=2, closed="left")
expected = DatetimeIndex([start])
tm.assert_index_equal(result, expected)
def test_date_range_with_custom_holidays():
# GH 30593
freq = pd.offsets.CustomBusinessHour(start="15:00", holiday... |
class BusinessHourMixin(BusinessMixin):
# adjust by business days first
if bd != 0:
skip_bd = BusinessDay(n=bd)
# midnight business hour may not on BusinessDay
if not self.next_bday.is_on_offset(other):
prev_open = self._prev_o... | class BusinessHourMixin(BusinessMixin):
# adjust by business days first
if bd != 0:
if isinstance(self, _CustomMixin): # GH 30593
skip_bd = CustomBusinessDay(
n=bd,
weekmask=self.weekmask,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.