buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
def sendEmail(sydent, templateName, mailTo, substitutions):
smtp = smtplib.SMTP(mailServer, mailPort, myHostname)
if mailUsername != '':
smtp.login(mailUsername, mailPassword)
smtp.sendmail(rawFrom, rawTo, mailString.encode('utf-8'))
smtp.quit()
... | def sendEmail(sydent, templateName, mailTo, substitutions):
smtp = smtplib.SMTP(mailServer, mailPort, myHostname)
if mailUsername != '':
smtp.login(mailUsername, mailPassword)
# We're using the parsing above to do basic validation, but instead of
# fa... |
def test_urlopener_retrieve_remote(self):
filename, _ = urllib.request.URLopener().retrieve(url)
self.assertEqual(os.path.splitext(filename)[1], ".txt")
# Just commented them out.
# Can't really tell why keep failing in windows and sparc. | def test_urlopener_retrieve_remote(self):
filename, _ = urllib.request.URLopener().retrieve(url)
self.assertEqual(os.path.splitext(filename)[1], ".txt")
@support.ignore_warnings(category=DeprecationWarning)
def test_local_file_open(self):
# bpo-35907, CVE-2019-9948: urllib must reject l... |
def open(self, fullurl, data=None):
name = 'open_' + urltype
self.type = urltype
name = name.replace('-', '_')
if not hasattr(self, name):
if proxy:
return self.open_unknown_proxy(proxy, fullurl, data)
else: | def open(self, fullurl, data=None):
name = 'open_' + urltype
self.type = urltype
name = name.replace('-', '_')
if not hasattr(self, name) or name == 'open_local_file':
if proxy:
return self.open_unknown_proxy(proxy, fullurl, data)
else: |
class tqdm(Comparable):
# apply custom scale if necessary
if unit_scale and unit_scale not in (True, 1):
total *= unit_scale
n *= unit_scale
if rate:
rate *= unit_scale # by default rate = 1 / self.avg_time | class tqdm(Comparable):
# apply custom scale if necessary
if unit_scale and unit_scale not in (True, 1):
if total:
total *= unit_scale
n *= unit_scale
if rate:
rate *= unit_scale # by default rate = 1 / self.avg_time |
def test_infinite_total():
pass
@with_setup(pretest, posttest)
def test_unit():
"""Test SI unit prefix""" | def test_infinite_total():
pass
@with_setup(pretest, posttest)
def test_nototal():
"""Test unknown total length"""
with closing(StringIO()) as our_file:
for i in tqdm((i for i in range(10)), file=our_file, unit_scale=10):
pass
assert "100it" in our_file.getvalue()
@wi... |
class ActionBase(with_metaclass(ABCMeta, object)):
Create and return a temporary path on a remote box.
'''
become_unprivileged = self._is_become_unprivileged()
remote_tmp = self.get_shell_option('remote_tmp', default='~/.ansible/tmp')
# deal with tmpdir creation
basefil... | class ActionBase(with_metaclass(ABCMeta, object)):
Create and return a temporary path on a remote box.
'''
# Network connection plugins (network_cli, netconf, etc.) execute on the controller, rather than the remote host.
# As such, we want to avoid using remote_user for paths as remote... |
class ActionBase(with_metaclass(ABCMeta, object)):
elif u'No space left on device' in result['stderr']:
output = result['stderr']
else:
output = ('Authentication or permission failure. '
'In some cases, you may have been able to authentic... | class ActionBase(with_metaclass(ABCMeta, object)):
elif u'No space left on device' in result['stderr']:
output = result['stderr']
else:
output = ('Failed to create temporary directory.'
'In some cases, you may have been able to authentica... |
import random
import re
import time
import ansible.constants as C
from ansible.errors import AnsibleError
from ansible.module_utils.six import text_type
from ansible.module_utils.six.moves import shlex_quote | import random
import re
import time
from ansible import constants as C
from ansible.errors import AnsibleError
from ansible.module_utils.six import text_type
from ansible.module_utils.six.moves import shlex_quote |
class ShellBase(AnsiblePlugin):
except KeyError:
pass
def env_prefix(self, **kwargs):
return ' '.join(['%s=%s' % (k, shlex_quote(text_type(v))) for k, v in kwargs.items()])
| class ShellBase(AnsiblePlugin):
except KeyError:
pass
@staticmethod
def _generate_temp_dir_name():
return 'ansible-tmp-%s-%s-%s' % (time.time(), os.getpid(), random.randint(0, 2**48))
def env_prefix(self, **kwargs):
return ' '.join(['%s=%s' % (k, shlex_quote(text_type(v... |
class ShellBase(AnsiblePlugin):
def mkdtemp(self, basefile=None, system=False, mode=0o700, tmpdir=None):
if not basefile:
basefile = 'ansible-tmp-%s-%s' % (time.time(), random.randint(0, 2**48))
# When system is specified we have to create this in a directory where
# other user... | class ShellBase(AnsiblePlugin):
def mkdtemp(self, basefile=None, system=False, mode=0o700, tmpdir=None):
if not basefile:
basefile = self.__class__._generate_temp_dir_name()
# When system is specified we have to create this in a directory where
# other users can read and access... |
class ShellBase(AnsiblePlugin):
# passed in tmpdir if it is valid or the first one from the setting if not.
if system:
tmpdir = tmpdir.rstrip('/')
if tmpdir in self.get_option('system_tmpdirs'):
basetmpdir = tmpdir | class ShellBase(AnsiblePlugin):
# passed in tmpdir if it is valid or the first one from the setting if not.
if system:
if tmpdir:
tmpdir = tmpdir.rstrip('/')
if tmpdir in self.get_option('system_tmpdirs'):
basetmpdir = tmpdir |
class ShellBase(AnsiblePlugin):
basetmp = self.join_path(basetmpdir, basefile)
cmd = 'mkdir -p %s echo %s %s' % (self._SHELL_SUB_LEFT, basetmp, self._SHELL_SUB_RIGHT)
cmd += ' %s echo %s=%s echo %s %s' % (self._SHELL_AND, basefile, self._SHELL_SUB_LEFT, basetmp, self._SHELL_SUB_RIGHT)
... | class ShellBase(AnsiblePlugin):
basetmp = self.join_path(basetmpdir, basefile)
# use mkdir -p to ensure parents exist, but mkdir fullpath to ensure last one is created by us
cmd = 'mkdir -p %s echo %s %s' % (self._SHELL_SUB_LEFT, basetmpdir, self._SHELL_SUB_RIGHT)
cmd += '%s mkdir %s' ... |
class ShellModule(ShellBase):
def mkdtemp(self, basefile=None, system=False, mode=None, tmpdir=None):
# Windows does not have an equivalent for the system temp files, so
# the param is ignored
basefile = self._escape(self._unquote(basefile))
basetmpdir = tmpdir if tmpdir else self.ge... | class ShellModule(ShellBase):
def mkdtemp(self, basefile=None, system=False, mode=None, tmpdir=None):
# Windows does not have an equivalent for the system temp files, so
# the param is ignored
if not basefile:
basefile = self.__class__._generate_temp_dir_name()
basefile =... |
from typing import (
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
cast, | from typing import (
Sequence,
Set,
Tuple,
TypeVar,
Union,
cast, |
class CannotSplit(Exception):
"""
class FormatError(Exception):
"""Base exception for `# fmt: on` and `# fmt: off` handling.
It holds the number of bytes of the prefix consumed before the format
control comment appeared.
"""
def __init__(self, consumed: int) -> None:
super().__init__... | class CannotSplit(Exception):
"""
class WriteBack(Enum):
NO = 0
YES = 1 |
class DebugVisitor(Visitor[T]):
out(f" {node.value!r}", fg="blue", bold=False)
@classmethod
def show(cls, code: str) -> None:
"""Pretty-print the lib2to3 AST of a given string of `code`.
Convenience method for debugging.
"""
v: DebugVisitor[None] = DebugVisitor()
... | class DebugVisitor(Visitor[T]):
out(f" {node.value!r}", fg="blue", bold=False)
@classmethod
def show(cls, code: Union[str, Leaf, Node]) -> None:
"""Pretty-print the lib2to3 AST of a given string of `code`.
Convenience method for debugging.
"""
v: DebugVisitor[None] ... |
class Line:
return bool(self.leaves or self.comments)
class UnformattedLines(Line):
"""Just like :class:`Line` but stores lines which aren't reformatted."""
def append(self, leaf: Leaf, preformatted: bool = True) -> None:
"""Just add a new `leaf` to the end of the lines.
The `preform... | class Line:
return bool(self.leaves or self.comments)
@dataclass
class EmptyLineTracker:
"""Provides a stateful method that returns the number of potential extra |
class EmptyLineTracker:
This is for separating `def`, `async def` and `class` with extra empty
lines (two on module-level).
"""
if isinstance(current_line, UnformattedLines):
return 0, 0
before, after = self._maybe_empty_lines(current_line)
before -= self.pre... | class EmptyLineTracker:
This is for separating `def`, `async def` and `class` with extra empty
lines (two on module-level).
"""
before, after = self._maybe_empty_lines(current_line)
before -= self.previous_after
self.previous_after = after |
class LineGenerator(Visitor[Line]):
current_line: Line = Factory(Line)
remove_u_prefix: bool = False
def line(self, indent: int = 0, type: Type[Line] = Line) -> Iterator[Line]:
"""Generate a line.
If the line is empty, only emit if it makes sense. | class LineGenerator(Visitor[Line]):
current_line: Line = Factory(Line)
remove_u_prefix: bool = False
def line(self, indent: int = 0) -> Iterator[Line]:
"""Generate a line.
If the line is empty, only emit if it makes sense. |
class LineGenerator(Visitor[Line]):
If any lines were generated, set up a new current_line.
"""
if not self.current_line:
if self.current_line.__class__ == type:
self.current_line.depth += indent
else:
self.current_line = type(depth=self.cu... | class LineGenerator(Visitor[Line]):
If any lines were generated, set up a new current_line.
"""
if not self.current_line:
self.current_line.depth += indent
return # Line is empty, don't emit. Creating a new one unnecessary.
complete_line = self.current_line
... |
class LineGenerator(Visitor[Line]):
yield from self.visit_default(leaf)
yield from self.line()
def visit_unformatted(self, node: LN) -> Iterator[Line]:
"""Used when file contained a `# fmt: off`."""
if isinstance(node, Node):
for child in node.children:
y... | class LineGenerator(Visitor[Line]):
yield from self.visit_default(leaf)
yield from self.line()
def visit_STANDALONE_COMMENT(self, leaf: Leaf) -> Iterator[Line]:
if not self.current_line.bracket_tracker.any_open_brackets():
yield from self.line()
yield from self.visit_def... |
def container_of(leaf: Leaf) -> LN:
if parent.children[0].prefix != same_prefix:
break
if parent.type in SURROUNDED_BY_BRACKETS:
break
| def container_of(leaf: Leaf) -> LN:
if parent.children[0].prefix != same_prefix:
break
if parent.type == syms.file_input:
break
if parent.type in SURROUNDED_BY_BRACKETS:
break
|
def generate_comments(leaf: LN) -> Iterator[Leaf]:
"""
for pc in list_comments(leaf.prefix, is_endmarker=leaf.type == token.ENDMARKER):
yield Leaf(pc.type, pc.value, prefix="\n" * pc.newlines)
if pc.value in FMT_ON:
raise FormatOn(pc.consumed)
if pc.value in FMT_OFF:
... | def generate_comments(leaf: LN) -> Iterator[Leaf]:
"""
for pc in list_comments(leaf.prefix, is_endmarker=leaf.type == token.ENDMARKER):
yield Leaf(pc.type, pc.value, prefix="\n" * pc.newlines)
@dataclass |
def split_line(
If `py36` is True, splitting may generate syntax that is only compatible
with Python 3.6 and later.
"""
if isinstance(line, UnformattedLines) or line.is_comment:
yield line
return
| def split_line(
If `py36` is True, splitting may generate syntax that is only compatible
with Python 3.6 and later.
"""
if line.is_comment:
yield line
return
|
def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None:
def normalize_fmt_off(node: Node) -> None:
"""Allow `# fmt: off`/`# fmt: on` within bracket pairs.
Ignores `# fmt: off` and `# fmt: on` outside of brackets.
Raises :exc:`SyntaxError` if no matching `# fmt: on` is found for a `# ... | def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None:
def normalize_fmt_off(node: Node) -> None:
"""Convert content between `# fmt: off`/`# fmt: on` into standalone comments."""
try_again = True
while try_again:
try_again = convert_one_fmt_off_pair(node)
def convert_one_fmt... |
def hide_fmt_off(node: Node) -> bool:
hidden_value = (
comment.value + "\n" + "".join(str(n) for n in ignored_nodes)
)
first_idx = None
for ignored in ignored_nodes:
index = ignored.remove() | def hide_fmt_off(node: Node) -> bool:
hidden_value = (
comment.value + "\n" + "".join(str(n) for n in ignored_nodes)
)
if hidden_value.endswith("\n"):
# That happens when one of the `ignored_nodes` ended with a NEWLINE
... |
def hide_fmt_off(node: Node) -> bool:
def generate_ignored_nodes(leaf: Leaf) -> Iterator[LN]:
container: Optional[LN] = container_of(leaf)
while container is not None:
for comment in list_comments(container.prefix, is_endmarker=False):
if comment.value in FMT_ON:
return | def hide_fmt_off(node: Node) -> bool:
def generate_ignored_nodes(leaf: Leaf) -> Iterator[LN]:
"""Starting from the container of `leaf`, generate all leaves until `# fmt: on`.
Stops at the end of the block.
"""
container: Optional[LN] = container_of(leaf)
while container is not None and container.... |
class BlackTestCase(unittest.TestCase):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, line_length=ll)
@patch("black.dump_to_file", dump_to_stderr)
def test_remove_empty_parentheses_after_class(self) -> None:
source, expected = read_data("class_blank_parenth... | class BlackTestCase(unittest.TestCase):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, line_length=ll)
@patch("black.dump_to_file", dump_to_stderr)
def test_fmtonoff2(self) -> None:
source, expected = read_data("fmtonoff2")
actual = fs(source)
... |
class HMACKey(Key):
invalid_strings = [
b'-----BEGIN PUBLIC KEY-----',
b'-----BEGIN CERTIFICATE-----',
b'ssh-rsa'
] | class HMACKey(Key):
invalid_strings = [
b'-----BEGIN PUBLIC KEY-----',
b'-----BEGIN RSA PUBLIC KEY-----',
b'-----BEGIN CERTIFICATE-----',
b'ssh-rsa'
] |
class TestHMACAlgorithm:
with pytest.raises(JOSEError):
HMACKey(key, ALGORITHMS.HS256)
key = "-----BEGIN CERTIFICATE-----"
with pytest.raises(JOSEError):
HMACKey(key, ALGORITHMS.HS256) | class TestHMACAlgorithm:
with pytest.raises(JOSEError):
HMACKey(key, ALGORITHMS.HS256)
key = "-----BEGIN RSA PUBLIC KEY-----"
with pytest.raises(JOSEError):
HMACKey(key, ALGORITHMS.HS256)
key = "-----BEGIN CERTIFICATE-----"
with pytest.raises(JOSEError):... |
def test_overrun(self):
except IOError as e:
self.assertEqual(str(e), "buffer overrun when reading image file")
class MockEncoder(object):
pass | def test_overrun(self):
except IOError as e:
self.assertEqual(str(e), "buffer overrun when reading image file")
with Image.open("Tests/images/fli_overrun2.bin") as im:
try:
im.seek(1)
self.assertFail()
except IOError as e:
... |
from youtube_dl.utils import (
unified_strdate,
unsmuggle_url,
url_basename,
xpath_with_ns,
)
| from youtube_dl.utils import (
unified_strdate,
unsmuggle_url,
url_basename,
urlencode_postdata,
xpath_with_ns,
)
|
class TestUtil(unittest.TestCase):
bam''')
self.assertEqual(read_batch_urls(f), [u'foo', u'bar', u'baz', u'bam'])
if __name__ == '__main__':
unittest.main() | class TestUtil(unittest.TestCase):
bam''')
self.assertEqual(read_batch_urls(f), [u'foo', u'bar', u'baz', u'bam'])
def test_urlencode_postdata(self):
data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
self.assertTrue(isinstance(data, bytes))
if __name__ =... |
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,
) |
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... |
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... |
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') |
def categorical_accuracy(y_true, y_pred):
def sparse_categorical_accuracy(y_true, y_pred):
return K.cast(K.equal(K.max(y_true, axis=-1),
K.cast(K.argmax(y_pred, axis=-1), K.floatx())),
K.floatx())
| def categorical_accuracy(y_true, y_pred):
def sparse_categorical_accuracy(y_true, y_pred):
# flatten y_true in case it's in shape (num_samples, 1) instead of (num_samples,)
return K.cast(K.equal(K.flatten(y_true),
K.cast(K.argmax(y_pred, axis=-1), K.floatx())),
K.fl... |
def test_sparse_metrics():
assert K.eval(metric(y_a, y_b)).shape == (6,)
def test_serialize():
'''This is a mock 'round trip' of serialize and deserialize.
''' | def test_sparse_metrics():
assert K.eval(metric(y_a, y_b)).shape == (6,)
@keras_test
def test_sparse_categorical_accuracy_correctness():
y_a = K.variable(np.random.randint(0, 7, (6,)), dtype=K.floatx())
y_b = K.variable(np.random.random((6, 7)), dtype=K.floatx())
# use one_hot embedding to convert... |
def match(command):
def _parse_operations(help_text_lines):
# The regex has to be a bytes-style regex since reading from a file
# like stdin returns a bytes-style object and a string-style regex
# wouldn't work.
operation_regex = re.compile(b'^([a-z-]+) +', re.MULTILINE)
return operation_regex.fin... | def match(command):
def _parse_operations(help_text_lines):
operation_regex = re.compile(r'^([a-z-]+) +', re.MULTILINE)
return operation_regex.findall(help_text_lines)
|
def _get_operations():
proc = subprocess.Popen(["dnf", '--help'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
lines = proc.stdout.read()
return _parse_operations(lines)
| def _get_operations():
proc = subprocess.Popen(["dnf", '--help'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
lines = proc.stdout.read().decode("utf-8")
return _parse_operations(lines)
|
from django.utils.cache import (
)
from django.utils.deprecation import MiddlewareMixin, RemovedInDjango21Warning
from django.utils.encoding import force_text
from django.utils.six.moves.urllib.parse import urlparse
| from django.utils.cache import (
)
from django.utils.deprecation import MiddlewareMixin, RemovedInDjango21Warning
from django.utils.encoding import force_text
from django.utils.http import escape_leading_slashes
from django.utils.six.moves.urllib.parse import urlparse
|
class CommonMiddleware(MiddlewareMixin):
POST, PUT, or PATCH.
"""
new_path = request.get_full_path(force_append_slash=True)
if settings.DEBUG and request.method in ('POST', 'PUT', 'PATCH'):
raise RuntimeError(
"You called this URL via %(method)s, but the URL d... | class CommonMiddleware(MiddlewareMixin):
POST, PUT, or PATCH.
"""
new_path = request.get_full_path(force_append_slash=True)
# Prevent construction of scheme relative urls.
new_path = escape_leading_slashes(new_path)
if settings.DEBUG and request.method in ('POST', 'PUT', ... |
from django.utils import lru_cache, six
from django.utils.datastructures import MultiValueDict
from django.utils.encoding import force_str, force_text
from django.utils.functional import cached_property
from django.utils.http import RFC3986_SUBDELIMS, urlquote
from django.utils.regex_helper import normalize
from django... | from django.utils import lru_cache, six
from django.utils.datastructures import MultiValueDict
from django.utils.encoding import force_str, force_text
from django.utils.functional import cached_property
from django.utils.http import (
RFC3986_SUBDELIMS, escape_leading_slashes, urlquote,
)
from django.utils.regex_he... |
class RegexURLResolver(LocaleRegexProvider):
# safe characters from `pchar` definition of RFC 3986
url = urlquote(candidate_pat % candidate_subs, safe=RFC3986_SUBDELIMS + str('/~:@'))
# Don't allow construction of scheme relative urls.
if u... | class RegexURLResolver(LocaleRegexProvider):
# safe characters from `pchar` definition of RFC 3986
url = urlquote(candidate_pat % candidate_subs, safe=RFC3986_SUBDELIMS + str('/~:@'))
# Don't allow construction of scheme relative urls.
retu... |
def limited_parse_qsl(qs, keep_blank_values=False, encoding='utf-8',
value = unquote(nv[1].replace(b'+', b' '))
r.append((name, value))
return r | def limited_parse_qsl(qs, keep_blank_values=False, encoding='utf-8',
value = unquote(nv[1].replace(b'+', b' '))
r.append((name, value))
return r
def escape_leading_slashes(url):
"""
If redirecting to an absolute path (two leading slashes), a slash must be
escaped to prevent... |
class CommonMiddlewareTest(SimpleTestCase):
self.assertEqual(r.status_code, 301)
self.assertEqual(r.url, '/needsquoting%23/')
@override_settings(APPEND_SLASH=False, PREPEND_WWW=True)
def test_prepend_www(self):
request = self.rf.get('/path/') | class CommonMiddlewareTest(SimpleTestCase):
self.assertEqual(r.status_code, 301)
self.assertEqual(r.url, '/needsquoting%23/')
@override_settings(APPEND_SLASH=True)
def test_append_slash_leading_slashes(self):
"""
Paths starting with two slashes are escaped to prevent open redire... |
urlpatterns = [
url(r'^noslash$', views.empty_view),
url(r'^slash/$', views.empty_view),
url(r'^needsquoting#/$', views.empty_view),
] | urlpatterns = [
url(r'^noslash$', views.empty_view),
url(r'^slash/$', views.empty_view),
url(r'^needsquoting#/$', views.empty_view),
# Accepts paths with two leading slashes.
url(r'^(.+)/security/$', views.empty_view),
] |
class HttpDateProcessingTests(unittest.TestCase):
def test_parsing_asctime(self):
parsed = http.parse_http_date('Sun Nov 6 08:49:37 1994')
self.assertEqual(datetime.utcfromtimestamp(parsed), datetime(1994, 11, 6, 8, 49, 37)) | class HttpDateProcessingTests(unittest.TestCase):
def test_parsing_asctime(self):
parsed = http.parse_http_date('Sun Nov 6 08:49:37 1994')
self.assertEqual(datetime.utcfromtimestamp(parsed), datetime(1994, 11, 6, 8, 49, 37))
class EscapeLeadingSlashesTests(unittest.TestCase):
def test(self):
... |
def init_ndarray(values, index, columns, dtype=None, copy=False):
return arrays_to_mgr([values], columns, index, columns, dtype=dtype)
elif is_extension_array_dtype(values) or is_extension_array_dtype(dtype):
# GH#19157
if columns is None:
columns = [0]
return arrays_to_m... | def init_ndarray(values, index, columns, dtype=None, copy=False):
return arrays_to_mgr([values], columns, index, columns, dtype=dtype)
elif is_extension_array_dtype(values) or is_extension_array_dtype(dtype):
# GH#19157
if isinstance(values, np.ndarray) and values.ndim > 1:
# GH... |
class TestDataFrameConstructorWithDatetimeTZ:
"datetime64[ns, CET]",
]
assert (res.dtypes == expected_dtypes).all() | class TestDataFrameConstructorWithDatetimeTZ:
"datetime64[ns, CET]",
]
assert (res.dtypes == expected_dtypes).all()
def test_from_2d_ndarray_with_dtype(self):
# GH#12513
array_dim2 = np.arange(10).reshape((5, 2))
df = pd.DataFrame(array_dim2, dtype="datetime64[ns... |
def top_k_categorical_accuracy(y_true, y_pred, k=5):
def sparse_top_k_categorical_accuracy(y_true, y_pred, k=5):
return K.mean(K.in_top_k(y_pred, K.cast(K.max(y_true, axis=-1), 'int32'), k),
axis=-1)
| def top_k_categorical_accuracy(y_true, y_pred, k=5):
def sparse_top_k_categorical_accuracy(y_true, y_pred, k=5):
# If the shape of y_true is (num_samples, 1), flatten to (num_samples,)
return K.mean(K.in_top_k(y_pred, K.cast(K.flatten(y_true), 'int32'), k),
axis=-1)
|
def test_top_k_categorical_accuracy():
@pytest.mark.skipif((K.backend() == 'cntk'),
reason='CNTK backend does not support top_k yet')
def test_sparse_top_k_categorical_accuracy():
y_pred = K.variable(np.array([[0.3, 0.2, 0.1], [0.1, 0.2, 0.7]]))
y_true = K.variable(np.array([[1], [0]]))
... | def test_top_k_categorical_accuracy():
@pytest.mark.skipif((K.backend() == 'cntk'),
reason='CNTK backend does not support top_k yet')
@pytest.mark.parametrize('y_pred, y_true', [
# Test correctness if the shape of y_true is (num_samples, 1)
(np.array([[0.3, 0.2, 0.1], [0.1, 0.2, 0.7]]), np.... |
class TestUtil(unittest.TestCase):
self.assertEqual(urljoin('http://foo.de/', ''), None)
self.assertEqual(urljoin('http://foo.de/', ['foobar']), None)
self.assertEqual(urljoin('http://foo.de/a/b/c.txt', '.././../d.txt'), 'http://foo.de/d.txt')
def test_url_or_none(self):
self.assert... | class TestUtil(unittest.TestCase):
self.assertEqual(urljoin('http://foo.de/', ''), None)
self.assertEqual(urljoin('http://foo.de/', ['foobar']), None)
self.assertEqual(urljoin('http://foo.de/a/b/c.txt', '.././../d.txt'), 'http://foo.de/d.txt')
self.assertEqual(urljoin('http://foo.de/a/b/... |
def urljoin(base, path):
path = path.decode('utf-8')
if not isinstance(path, compat_str) or not path:
return None
if re.match(r'^(?:https?:)?//', path):
return path
if isinstance(base, bytes):
base = base.decode('utf-8') | def urljoin(base, path):
path = path.decode('utf-8')
if not isinstance(path, compat_str) or not path:
return None
if re.match(r'^(?:[a-zA-Z][a-zA-Z0-9+-.]*:)?//', path):
return path
if isinstance(base, bytes):
base = base.decode('utf-8') |
import io
import pytest
from PIL import EpsImagePlugin, Image, features | import io
import pytest
from PIL import EpsImagePlugin, Image, features |
def test_emptyline():
assert image.mode == "RGB"
assert image.size == (460, 352)
assert image.format == "EPS" | def test_emptyline():
assert image.mode == "RGB"
assert image.size == (460, 352)
assert image.format == "EPS"
@pytest.mark.timeout(timeout=5)
@pytest.mark.parametrize(
"test_file",
[
("Tests/images/timeout-d675703545fee17acab56e5fec644c19979175de.eps")
],
)
def test_timeout(test_file):... |
class PSFile:
self.fp.seek(offset, whence)
def readline(self):
s = self.char or b""
self.char = None
c = self.fp.read(1)
while c not in b"\r\n":
s = s + c
c = self.fp.read(1)
self.char = self.fp.read(1) | class PSFile:
self.fp.seek(offset, whence)
def readline(self):
s = [self.char or b""]
self.char = None
c = self.fp.read(1)
while (c not in b"\r\n") and len(c):
s.append(c)
c = self.fp.read(1)
self.char = self.fp.read(1) |
class PSFile:
if self.char in b"\r\n":
self.char = None
return s.decode("latin-1")
def _accept(prefix): | class PSFile:
if self.char in b"\r\n":
self.char = None
return b"".join(s).decode("latin-1")
def _accept(prefix): |
class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin):
res._is_copy = self._is_copy
return res
def _iget_item_cache(self, item):
"""Return the cached item, item represents a positional indexer."""
ax = self._info_axis
if ax.is_unique:
lower = se... | class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin):
res._is_copy = self._is_copy
return res
def _iget_item_cache(self, item: int):
"""Return the cached item, item represents a positional indexer."""
ax = self._info_axis
if ax.is_unique:
lower... |
class _iLocIndexer(_LocationIndexer):
if not is_integer(k):
return False
ax = self.obj.axes[i]
if not ax.is_unique:
return False
return True
def _validate_integer(self, key: int, axis: int) -> None: | class _iLocIndexer(_LocationIndexer):
if not is_integer(k):
return False
return True
def _validate_integer(self, key: int, axis: int) -> None: |
class TestiLoc(Base):
class TestiLoc2:
# TODO: better name, just separating out things that dont rely on base class
def test_iloc_exceeds_bounds(self):
# GH6296 | class TestiLoc(Base):
class TestiLoc2:
# TODO: better name, just separating out things that dont rely on base class
def test_is_scalar_access(self):
# GH#32085 index with duplicates doesnt matter for _is_scalar_access
index = pd.Index([1, 2, 1])
ser = pd.Series(range(3), index=index)
... |
def __lt__(self, other):
return False
def __hash__(self):
return self._ip ^ self._prefixlen ^ int(self.network.network_address)
__reduce__ = _IPAddressBase.__reduce__
| def __lt__(self, other):
return False
def __hash__(self):
return hash((self._ip, self._prefixlen, int(self.network.network_address)))
__reduce__ = _IPAddressBase.__reduce__
|
def __lt__(self, other):
return False
def __hash__(self):
return self._ip ^ self._prefixlen ^ int(self.network.network_address)
__reduce__ = _IPAddressBase.__reduce__
| def __lt__(self, other):
return False
def __hash__(self):
return hash((self._ip, self._prefixlen, int(self.network.network_address)))
__reduce__ = _IPAddressBase.__reduce__
|
def testsixtofour(self):
sixtofouraddr.sixtofour)
self.assertFalse(bad_addr.sixtofour)
if __name__ == '__main__':
unittest.main() | def testsixtofour(self):
sixtofouraddr.sixtofour)
self.assertFalse(bad_addr.sixtofour)
# issue41004 Hash collisions in IPv4Interface and IPv6Interface
def testV4HashIsNotConstant(self):
ipv4_address1 = ipaddress.IPv4Interface("1.2.3.4")
ipv4_address2 = ipaddress... |
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... |
class SchedulerApiTest(unittest.TestCase):
self.assertEqual(self.sch.get_work(worker='Y')['task_id'], 'C')
self.assertEqual(self.sch.get_work(worker='X')['task_id'], 'B')
def test_retry(self):
# Try to build A but fails, will retry after 100s
self.setTime(0) | class SchedulerApiTest(unittest.TestCase):
self.assertEqual(self.sch.get_work(worker='Y')['task_id'], 'C')
self.assertEqual(self.sch.get_work(worker='X')['task_id'], 'B')
def test_status_wont_override(self):
# Worker X is running A
# Worker Y wants to override the status to UNKNOWN ... |
def __virtual__():
return __virtualname__
def _check_cb(cb_):
"""
If the callback is None or is not callable, return a lambda that returns | def __virtual__():
return __virtualname__
def _log_cmd(cmd):
if not isinstance(cmd, list):
return cmd.split()[0].strip()
return cmd[0].strip()
def _check_cb(cb_):
"""
If the callback is None or is not callable, return a lambda that returns |
def _run(
)
env[bad_env_key] = ""
def _get_stripped(cmd):
# Return stripped command string copies to improve logging.
if isinstance(cmd, list):
return [x.strip() if isinstance(x, six.string_types) else x for x in cmd]
elif isinstance(cmd, six.string_types):
... | def _run(
)
env[bad_env_key] = ""
if output_loglevel is not None:
# Always log the shell commands at INFO unless quiet logging is
# requested. The command output is what will be controlled by the
# 'loglevel' parameter.
msg = "Executing command {0}{1}{0} {2}{3}in dir... |
def _run(
log.error(
"Failed to decode stdout from command %s, non-decodable "
"characters have been replaced",
cmd,
)
try: | def _run(
log.error(
"Failed to decode stdout from command %s, non-decodable "
"characters have been replaced",
_log_cmd(cmd),
)
try: |
def _run(
log.error(
"Failed to decode stderr from command %s, non-decodable "
"characters have been replaced",
cmd,
)
if rstrip: | def _run(
log.error(
"Failed to decode stderr from command %s, non-decodable "
"characters have been replaced",
_log_cmd(cmd),
)
if rstrip: |
def _run(
if output_loglevel < LOG_LEVELS["error"]:
output_loglevel = LOG_LEVELS["error"]
msg = "Command '{0}' failed with return code: {1}".format(
cmd, ret["retcode"]
)
log.error(log_callback(msg))
if ret["stdout"]: | def _run(
if output_loglevel < LOG_LEVELS["error"]:
output_loglevel = LOG_LEVELS["error"]
msg = "Command '{0}' failed with return code: {1}".format(
_log_cmd(cmd), ret["retcode"]
)
log.error(log_callback(msg))
if ret["stdout"]: |
def run(
if lvl < LOG_LEVELS["error"]:
lvl = LOG_LEVELS["error"]
msg = "Command '{0}' failed with return code: {1}".format(
cmd, ret["retcode"]
)
log.error(log_callback(msg))
if raise_err: | def run(
if lvl < LOG_LEVELS["error"]:
lvl = LOG_LEVELS["error"]
msg = "Command '{0}' failed with return code: {1}".format(
_log_cmd(cmd), ret["retcode"]
)
log.error(log_callback(msg))
if raise_err: |
class CMDMODTestCase(TestCase, LoaderModuleMockMixin):
umask=None,
use_vt=False,
) | class CMDMODTestCase(TestCase, LoaderModuleMockMixin):
umask=None,
use_vt=False,
)
def test_cve_2021_25284(self):
proc = MagicMock(
return_value=MockTimedProc(
stdout=b"foo",
stderr=b"wtf",
returncode=2
... |
def separable_conv1d(x, depthwise_kernel, pointwise_kernel, strides=1,
padding = _preprocess_padding(padding)
if tf_data_format == 'NHWC':
spatial_start_dim = 1
strides = (1, 1) + strides + (1,)
else:
spatial_start_dim = 2
strides = (1, 1, 1) + strides
x = tf.expand_dims(... | def separable_conv1d(x, depthwise_kernel, pointwise_kernel, strides=1,
padding = _preprocess_padding(padding)
if tf_data_format == 'NHWC':
spatial_start_dim = 1
strides = (1,) + strides * 2 + (1,)
else:
spatial_start_dim = 2
strides = (1, 1) + strides * 2
x = tf.expand_di... |
def test_separable_conv_1d():
num_step = 9
for padding in _convolution_paddings:
for multiplier in [1, 2]:
for dilation_rate in [1, 2]:
if padding == 'same':
continue
if dilation_rate != 1:
continue
lay... | def test_separable_conv_1d():
num_step = 9
for padding in _convolution_paddings:
for strides in [1, 2]:
for multiplier in [1, 2]:
for dilation_rate in [1, 2]:
if padding == 'same' and strides != 1:
continue
if d... |
class TestHTTPS_TLSv1(HTTPSDummyServerTestCase):
self._pool = HTTPSConnectionPool(self.host, self.port)
def test_set_ssl_version_to_sslv3(self):
self._pool.ssl_version = ssl.PROTOCOL_SSLv3
self.assertRaises(SSLError, self._pool.request, 'GET', '/')
def test_ssl_version_as_string(self):... | class TestHTTPS_TLSv1(HTTPSDummyServerTestCase):
self._pool = HTTPSConnectionPool(self.host, self.port)
def test_set_ssl_version_to_sslv3(self):
self.assertEqual(
ssl.PROTOCOL_SSLv3,
util.ssl_.resolve_ssl_version(ssl.PROTOCOL_SSLv3)
)
def test_ssl_version_as_str... |
try:
except AttributeError:
pass
_openssl_verify = {
ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE,
ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER,
ssl.CERT_REQUIRED:
OpenSSL.SSL.VERIFY_PEER + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
}
#: The list of supported SSL/TLS cipher suites.
DEFAULT_SSL_CIPHER_LI... | try:
except AttributeError:
pass
_stdlib_to_openssl_verify = {
ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE,
ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER,
ssl.CERT_REQUIRED:
OpenSSL.SSL.VERIFY_PEER + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
}
_openssl_to_stdlib_verify = dict(
(v, k) for k, v in _st... |
class PyOpenSSLContext(object):
@property
def verify_mode(self):
return self._ctx.get_verify_mode()
@verify_mode.setter
def verify_mode(self, value):
self._ctx.set_verify(value, _verify_callback)
def set_default_verify_paths(self):
self._ctx.set_default_verify_paths() | class PyOpenSSLContext(object):
@property
def verify_mode(self):
return _openssl_to_stdlib_verify[self._ctx.get_verify_mode()]
@verify_mode.setter
def verify_mode(self, value):
self._ctx.set_verify(
_stdlib_to_openssl_verify[value],
_verify_callback
)
... |
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
if keyfile:
ctx.use_privatekey_file(keyfile)
if cert_reqs != ssl.CERT_NONE:
ctx.set_verify(_openssl_verify[cert_reqs], _verify_callback)
if ca_certs or ca_cert_dir:
try:
ctx.load_verify_locations(ca_ce... | def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
if keyfile:
ctx.use_privatekey_file(keyfile)
if cert_reqs != ssl.CERT_NONE:
ctx.set_verify(_stdlib_to_openssl_verify[cert_reqs], _verify_callback)
if ca_certs or ca_cert_dir:
try:
ctx.load_verify_locat... |
def add_codes(err_cls):
class ErrorsWithCodes(object):
def __getattribute__(self, code):
msg = getattr(err_cls, code)
return "[{code}] {msg}".format(code=code, msg=msg)
return ErrorsWithCodes()
| def add_codes(err_cls):
class ErrorsWithCodes(object):
def __getattribute__(self, code):
if not code.startswith('__'):
msg = getattr(err_cls, code)
return "[{code}] {msg}".format(code=code, msg=msg)
else:
return super().__getattribute_... |
__all__ = [
def get_objs_combined_axis(
objs, intersect: bool = False, axis=0, sort: bool = True
) -> Index:
"""
Extract combined index: return intersection or union (depending on the | __all__ = [
def get_objs_combined_axis(
objs, intersect: bool = False, axis=0, sort: bool = True, copy: bool = False
) -> Index:
"""
Extract combined index: return intersection or union (depending on the |
def get_objs_combined_axis(
The axis to extract indexes from.
sort : bool, default True
Whether the result index should come out sorted or not.
Returns
-------
Index
"""
obs_idxes = [obj._get_axis(axis) for obj in objs]
return _get_combined_index(obs_idxes, intersect=interse... | def get_objs_combined_axis(
The axis to extract indexes from.
sort : bool, default True
Whether the result index should come out sorted or not.
copy : bool, default False
If True, return a copy of the combined index.
Returns
-------
Index
"""
obs_idxes = [obj._get_ax... |
def _get_distinct_objs(objs: List[Index]) -> List[Index]:
def _get_combined_index(
indexes: List[Index], intersect: bool = False, sort: bool = False
) -> Index:
"""
Return the union or intersection of indexes. | def _get_distinct_objs(objs: List[Index]) -> List[Index]:
def _get_combined_index(
indexes: List[Index],
intersect: bool = False,
sort: bool = False,
copy: bool = False,
) -> Index:
"""
Return the union or intersection of indexes. |
def _get_combined_index(
calculate the union.
sort : bool, default False
Whether the result index should come out sorted or not.
Returns
------- | def _get_combined_index(
calculate the union.
sort : bool, default False
Whether the result index should come out sorted or not.
copy : bool, default False
If True, return a copy of the combined index.
Returns
------- |
def _get_combined_index(
index = index.sort_values()
except TypeError:
pass
return index
| def _get_combined_index(
index = index.sort_values()
except TypeError:
pass
# GH 29879
if copy:
index = index.copy()
return index
|
class _Concatenator:
def _get_comb_axis(self, i: int) -> Index:
data_axis = self.objs[0]._get_block_manager_axis(i)
return get_objs_combined_axis(
self.objs, axis=data_axis, intersect=self.intersect, sort=self.sort
)
def _get_concat_axis(self) -> Index: | class _Concatenator:
def _get_comb_axis(self, i: int) -> Index:
data_axis = self.objs[0]._get_block_manager_axis(i)
return get_objs_combined_axis(
self.objs,
axis=data_axis,
intersect=self.intersect,
sort=self.sort,
copy=self.copy,
... |
def test_concat_sparse():
)
result = pd.concat([a, a], axis=1)
tm.assert_frame_equal(result, expected) | def test_concat_sparse():
)
result = pd.concat([a, a], axis=1)
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("test_series", [True, False])
def test_concat_copy_index(test_series, axis):
# GH 29879
if test_series:
ser = Series([1, 2])
comb = concat([ser, ser], axi... |
import time
from django.conf import settings
from django.db.backends.base.creation import BaseDatabaseCreation
from django.db.utils import DatabaseError
from django.utils.functional import cached_property
from django.utils.six.moves import input
TEST_DATABASE_PREFIX = 'test_'
PASSWORD = 'Im_a_lumberjack'
class Datab... | import time
from django.conf import settings
from django.db.backends.base.creation import BaseDatabaseCreation
from django.db.utils import DatabaseError
from django.utils.crypto import get_random_string
from django.utils.functional import cached_property
from django.utils.six.moves import input
TEST_DATABASE_PREFIX = ... |
class DatabaseCreation(BaseDatabaseCreation):
]
# Ignore "user already exists" error when keepdb is on
acceptable_ora_err = 'ORA-01920' if keepdb else None
self._execute_allow_fail_statements(cursor, statements, parameters, verbosity, acceptable_ora_err)
# Most test-suites can be... | class DatabaseCreation(BaseDatabaseCreation):
]
# Ignore "user already exists" error when keepdb is on
acceptable_ora_err = 'ORA-01920' if keepdb else None
success = self._execute_allow_fail_statements(cursor, statements, parameters, verbosity, acceptable_ora_err)
# If the passwo... |
class DatabaseCreation(BaseDatabaseCreation):
"""
settings_dict = self.connection.settings_dict
val = settings_dict['TEST'].get(key, default)
if val is None:
val = TEST_DATABASE_PREFIX + settings_dict[prefixed]
return val
| class DatabaseCreation(BaseDatabaseCreation):
"""
settings_dict = self.connection.settings_dict
val = settings_dict['TEST'].get(key, default)
if val is None and prefixed:
val = TEST_DATABASE_PREFIX + settings_dict[prefixed]
return val
|
class DatabaseCreation(BaseDatabaseCreation):
return self._test_settings_get('USER', prefixed='USER')
def _test_database_passwd(self):
return self._test_settings_get('PASSWORD', default=PASSWORD)
def _test_database_tblspace(self):
return self._test_settings_get('TBLSPACE', prefixed='US... | class DatabaseCreation(BaseDatabaseCreation):
return self._test_settings_get('USER', prefixed='USER')
def _test_database_passwd(self):
password = self._test_settings_get('PASSWORD')
if password is None and self._test_user_create():
# Oracle passwords are limited to 30 chars and ... |
from pandas.core.dtypes.common import (
ensure_object,
is_bool_dtype,
is_complex_dtype,
is_datetime64_dtype,
is_datetime64tz_dtype,
is_datetimelike_v_numeric,
is_dtype_equal,
is_extension_array_dtype,
is_float_dtype,
is_integer_dtype,
is_object_dtype,
is_period_dtype,
... | from pandas.core.dtypes.common import (
ensure_object,
is_bool_dtype,
is_complex_dtype,
is_datetimelike_v_numeric,
is_dtype_equal,
is_extension_array_dtype,
is_float_dtype,
is_integer_dtype,
is_object_dtype,
is_scalar,
is_string_dtype,
is_string_like_dtype,
needs_i8_c... |
def _isna_new(obj):
raise NotImplementedError("isna is not defined for MultiIndex")
elif isinstance(obj, type):
return False
elif isinstance(
obj,
(
ABCSeries,
np.ndarray,
ABCIndexClass,
ABCExtensionArray,
ABCDatetimeArr... | def _isna_new(obj):
raise NotImplementedError("isna is not defined for MultiIndex")
elif isinstance(obj, type):
return False
elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass, ABCExtensionArray)):
return _isna_ndarraylike(obj)
elif isinstance(obj, ABCDataFrame):
retu... |
def _isna_new(obj):
elif hasattr(obj, "__array__"):
return _isna_ndarraylike(np.asarray(obj))
else:
return obj is None
def _isna_old(obj): | def _isna_new(obj):
elif hasattr(obj, "__array__"):
return _isna_ndarraylike(np.asarray(obj))
else:
return False
def _isna_old(obj): |
def _isna_old(obj):
elif hasattr(obj, "__array__"):
return _isna_ndarraylike_old(np.asarray(obj))
else:
return obj is None
_isna = _isna_new | def _isna_old(obj):
elif hasattr(obj, "__array__"):
return _isna_ndarraylike_old(np.asarray(obj))
else:
return False
_isna = _isna_new |
def _use_inf_as_na(key):
def _isna_ndarraylike(obj):
is_extension = is_extension_array_dtype(obj)
if not is_extension:
# Avoid accessing `.values` on things like
# PeriodIndex, which may be expensive.
values = getattr(obj, "_values", obj)
else:
values = obj
dtype = va... | def _use_inf_as_na(key):
def _isna_ndarraylike(obj):
is_extension = is_extension_array_dtype(obj.dtype)
values = getattr(obj, "_values", obj)
dtype = values.dtype
if is_extension:
result = values.isna()
elif is_string_dtype(dtype):
result = _isna_string_dtype(values, dtype, old=Fa... |
def _isna_ndarraylike_old(obj):
dtype = values.dtype
if is_string_dtype(dtype):
# Working around NumPy ticket 1542
shape = values.shape
if is_string_like_dtype(dtype):
result = np.zeros(values.shape, dtype=bool)
else:
result = np.empty(shape, dtype=bool)... | def _isna_ndarraylike_old(obj):
dtype = values.dtype
if is_string_dtype(dtype):
result = _isna_string_dtype(values, dtype, old=True)
elif needs_i8_conversion(dtype):
# this is the NaT pattern
result = values.view("i8") == iNaT
else: |
def _isna_ndarraylike_old(obj):
return result
def notna(obj):
"""
Detect non-missing values for an array-like object. | def _isna_ndarraylike_old(obj):
return result
def _isna_string_dtype(values: np.ndarray, dtype: np.dtype, old: bool) -> np.ndarray:
# Working around NumPy ticket 1542
shape = values.shape
if is_string_like_dtype(dtype):
result = np.zeros(values.shape, dtype=bool)
else:
result = np... |
def na_value_for_dtype(dtype, compat: bool = True):
if is_extension_array_dtype(dtype):
return dtype.na_value
if (
is_datetime64_dtype(dtype)
or is_datetime64tz_dtype(dtype)
or is_timedelta64_dtype(dtype)
or is_period_dtype(dtype)
):
return NaT
elif is_fl... | def na_value_for_dtype(dtype, compat: bool = True):
if is_extension_array_dtype(dtype):
return dtype.na_value
if needs_i8_conversion(dtype):
return NaT
elif is_float_dtype(dtype):
return np.nan |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.