uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b8ad213bca510312d94d8ade | train | function | def get_manager() -> multiprocessing.managers.SyncManager:
"""Return a singleton shared manager."""
global _manager
if _manager is None:
_manager = context.Manager()
return _manager
| def get_manager() -> multiprocessing.managers.SyncManager:
| """Return a singleton shared manager."""
global _manager
if _manager is None:
_manager = context.Manager()
return _manager
| windows and mac, but can't execute non-global functions
# see https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods
context = multiprocessing.get_context(DEFAULT_START_METHOD)
_manager = None
log = logging.getLogger(__name__)
def get_manager() -> multiprocessing.managers.SyncManager:
| 64 | 64 | 43 | 11 | 53 | graingert/aiomultiprocess | aiomultiprocess/core.py | Python | get_manager | get_manager | 25 | 31 | 25 | 25 | 98c73d4b04325b82922d39cbf8db8e7e051da7fd | bigcode/the-stack | train |
1995c141ccf4726e4087bbb5 | train | function | def set_context(method: Optional[str] = None) -> None:
"""
Set the start method and context used for future processes/pools. [DEPRECATED]
Retained for backwards compatibility, and to retain prior behavior of "no parameter"
resulting in selection of the platform's default start method.
"""
retur... | def set_context(method: Optional[str] = None) -> None:
| """
Set the start method and context used for future processes/pools. [DEPRECATED]
Retained for backwards compatibility, and to retain prior behavior of "no parameter"
resulting in selection of the platform's default start method.
"""
return set_start_method(method)
| /library/multiprocessing.html#contexts-and-start-methods
"""
global context
context = multiprocessing.get_context(method)
def get_context() -> Context:
"""Get the current active global context."""
global context
return context
def set_context(method: Optional[str] = None) -> None:
| 64 | 64 | 72 | 14 | 49 | graingert/aiomultiprocess | aiomultiprocess/core.py | Python | set_context | set_context | 62 | 69 | 62 | 62 | 3d16d0686b52fcb3c48490aaa960c36af9d3515e | bigcode/the-stack | train |
2659a5bf168886e6fb2b09a1 | train | class | class Worker(Process):
"""Execute a coroutine on a separate process and return the result."""
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, process_target=Worker.run_async, **kwargs)
self.unit.namespace.result = None
@staticmethod
def run_async(unit: Unit) -> R:
... | class Worker(Process):
| """Execute a coroutine on a separate process and return the result."""
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, process_target=Worker.run_async, **kwargs)
self.unit.namespace.result = None
@staticmethod
def run_async(unit: Unit) -> R:
"""Initialize t... | if sys.version_info >= (3, 7):
def kill(self) -> None:
"""Send SIGKILL to child process."""
return self.aio_process.kill()
def close(self) -> None:
"""Clean up child process once finished."""
return self.aio_process.close()
class Worker(Process):
| 66 | 66 | 221 | 4 | 62 | graingert/aiomultiprocess | aiomultiprocess/core.py | Python | Worker | Worker | 200 | 230 | 200 | 200 | aba55863fae1743a1867315aa5abf9f7c5940e2a | bigcode/the-stack | train |
2dd0d56e2974f14f57dcc663 | train | function | async def not_implemented(*args: Any, **kwargs: Any) -> None:
"""Default function to call when none given."""
raise NotImplementedError()
| async def not_implemented(*args: Any, **kwargs: Any) -> None:
| """Default function to call when none given."""
raise NotImplementedError()
| processes/pools. [DEPRECATED]
Retained for backwards compatibility, and to retain prior behavior of "no parameter"
resulting in selection of the platform's default start method.
"""
return set_start_method(method)
async def not_implemented(*args: Any, **kwargs: Any) -> None:
| 64 | 64 | 34 | 18 | 46 | graingert/aiomultiprocess | aiomultiprocess/core.py | Python | not_implemented | not_implemented | 72 | 74 | 72 | 72 | 465e31fdb0d142c5e50da5e6de822b76d7aa016f | bigcode/the-stack | train |
77e68e24e53dc9e3a6773d53 | train | function | def get_context() -> Context:
"""Get the current active global context."""
global context
return context
| def get_context() -> Context:
| """Get the current active global context."""
global context
return context
| the current platform rather than defaulting to "spawn".
See the official multiprocessing documentation for details on start methods:
https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods
"""
global context
context = multiprocessing.get_context(method)
def get_context() ... | 64 | 64 | 24 | 7 | 57 | graingert/aiomultiprocess | aiomultiprocess/core.py | Python | get_context | get_context | 56 | 59 | 56 | 56 | 62e939d292b1959046ca0fb33677d54ad4a55eb7 | bigcode/the-stack | train |
f3c2b301314a3e1d93a1738d | train | function | def cook_continual(verbose = 1, **kwargs):
"""
Wrapper to cook mnist dataset that also creates a split dataset. Will take as input,
Args:
save_directory: which directory to save the cooked dataset onto.
dataset_parms: default is the dictionary. Refer to :mod:`setup_dataset`
preproc... | def cook_continual(verbose = 1, **kwargs):
| """
Wrapper to cook mnist dataset that also creates a split dataset. Will take as input,
Args:
save_directory: which directory to save the cooked dataset onto.
dataset_parms: default is the dictionary. Refer to :mod:`setup_dataset`
preprocess_params: default is the dictionary. Refe... | from yann.special.datasets import split_continual
def cook_continual(verbose = 1, **kwargs):
| 24 | 162 | 540 | 13 | 10 | ragavvenkatesan/Incremental-GAN | svhn-continual/dataset.py | Python | cook_continual | cook_continual | 3 | 68 | 3 | 3 | c5f051b9d3fad2784eaab02163b51fa231de3917 | bigcode/the-stack | train |
90ef76af02c1a0fb6324eec4 | train | function | def get_batch(fpath1, fpath2, maxlen1, maxlen2, vocab_fpath, batch_size, shuffle=False):
'''Gets training / evaluation mini-batches
fpath1: source file path. string.
fpath2: target file path. string.
maxlen1: source sent maximum length. scalar.
maxlen2: target sent maximum length. scalar.
... | def get_batch(fpath1, fpath2, maxlen1, maxlen2, vocab_fpath, batch_size, shuffle=False):
| '''Gets training / evaluation mini-batches
fpath1: source file path. string.
fpath2: target file path. string.
maxlen1: source sent maximum length. scalar.
maxlen2: target sent maximum length. scalar.
vocab_fpath: string. vocabulary file path.
batch_size: scalar
shuffle: boolean
... | .repeat() # iterate forever
dataset = dataset.padded_batch(batch_size, shapes, paddings).prefetch(1)
return dataset
# de -> en
def get_batch(fpath1, fpath2, maxlen1, maxlen2, vocab_fpath, batch_size, shuffle=False):
| 65 | 65 | 217 | 29 | 35 | ZhichaoOuyang/transformer | data_load.py | Python | get_batch | get_batch | 133 | 151 | 133 | 133 | 71c60bc825e35142c476238618367368ab0c72e9 | bigcode/the-stack | train |
cdc711625976fcaf8baa41ca | train | function | def load_data(fpath1, fpath2, maxlen1, maxlen2):
'''Loads source and target data and filters out too lengthy samples.
fpath1: source file path. string.
fpath2: target file path. string.
maxlen1: source sent maximum length. scalar.
maxlen2: target sent maximum length. scalar.
Returns
... | def load_data(fpath1, fpath2, maxlen1, maxlen2):
| '''Loads source and target data and filters out too lengthy samples.
fpath1: source file path. string.
fpath2: target file path. string.
maxlen1: source sent maximum length. scalar.
maxlen2: target sent maximum length. scalar.
Returns
sents1: list of source sents
sents2: list of... | ='utf-8').read().splitlines()]
token2idx = {token: idx for idx, token in enumerate(vocab)}
idx2token = {idx: token for idx, token in enumerate(vocab)}
return token2idx, idx2token
def load_data(fpath1, fpath2, maxlen1, maxlen2):
| 76 | 76 | 254 | 19 | 56 | ZhichaoOuyang/transformer | data_load.py | Python | load_data | load_data | 29 | 47 | 29 | 29 | 93f386e8ab42311cd16f752f6b6dd3cfc0ad3549 | bigcode/the-stack | train |
3bc9ffb17d77eda01c985b7c | train | function | def encode(inp, type, dict):
'''Converts string to number. Used for `generator_fn`.
inp: 1d byte array.
type: "x" (source side) or "y" (target side)
dict: token2idx dictionary
Returns
list of numbers
'''
inp_str = inp.decode("utf-8")
if type=="x": tokens = inp_str.split() ... | def encode(inp, type, dict):
| '''Converts string to number. Used for `generator_fn`.
inp: 1d byte array.
type: "x" (source side) or "y" (target side)
dict: token2idx dictionary
Returns
list of numbers
'''
inp_str = inp.decode("utf-8")
if type=="x": tokens = inp_str.split() + ["</s>"]
else: tokens =... | .split()) + 1 > maxlen2: continue # 1: </s>
sents1.append(sent1.strip())
sents2.append(sent2.strip())
return sents1, sents2 # 得到source 和 tgt里的sample
def encode(inp, type, dict):
| 64 | 64 | 142 | 8 | 55 | ZhichaoOuyang/transformer | data_load.py | Python | encode | encode | 50 | 64 | 50 | 50 | 689a8d479fe08aba14bcc6406d5c148eeb61ca25 | bigcode/the-stack | train |
e3158dcf9e9a265ea3ea40bb | train | function | def load_vocab(vocab_fpath):
'''Loads vocabulary file and returns idx<->token maps
vocab_fpath: string. vocabulary file path.
Note that these are reserved
0: <pad>, 1: <unk>, 2: <s>, 3: </s>
Returns
two dictionaries.
'''
vocab = [line.split()[0] for line in open(vocab_fpath, 'r... | def load_vocab(vocab_fpath):
| '''Loads vocabulary file and returns idx<->token maps
vocab_fpath: string. vocabulary file path.
Note that these are reserved
0: <pad>, 1: <unk>, 2: <s>, 3: </s>
Returns
two dictionaries.
'''
vocab = [line.split()[0] for line in open(vocab_fpath, 'r', encoding='utf-8').read().sp... | , entities on the source side have the prefix 1, and the target side 2, for convenience.
For example, fpath1, fpath2 means source file path and target file path, respectively.
'''
import tensorflow as tf
from utils import calc_num_batches
def load_vocab(vocab_fpath):
| 64 | 64 | 152 | 8 | 55 | ZhichaoOuyang/transformer | data_load.py | Python | load_vocab | load_vocab | 15 | 27 | 15 | 15 | f934becca51b60e4a84c3ee251a9db46109eb2d9 | bigcode/the-stack | train |
ee342b6db7780ed33d2782fc | train | function | def input_fn(sents1, sents2, vocab_fpath, batch_size, shuffle=False):
'''Batchify data
sents1: list of source sents
sents2: list of target sents
vocab_fpath: string. vocabulary file path.
batch_size: scalar
shuffle: boolean
Returns
xs: tuple of
x: int32 tensor. (N, T1)... | def input_fn(sents1, sents2, vocab_fpath, batch_size, shuffle=False):
| '''Batchify data
sents1: list of source sents
sents2: list of target sents
vocab_fpath: string. vocabulary file path.
batch_size: scalar
shuffle: boolean
Returns
xs: tuple of
x: int32 tensor. (N, T1)
x_seqlens: int32 tensor. (N,)
sents1: str tensor. (N... | ):
x = encode(sent1, "x", token2idx)
y = encode(sent2, "y", token2idx)
decoder_input, y = y[:-1], y[1:]
x_seqlen, y_seqlen = len(x), len(y)
yield (x, x_seqlen, sent1), (decoder_input, y, y_seqlen, sent2)
def input_fn(sents1, sents2, vocab_fpath, batch_size, shuffle=False):... | 109 | 109 | 366 | 21 | 88 | ZhichaoOuyang/transformer | data_load.py | Python | input_fn | input_fn | 92 | 130 | 92 | 92 | 21979c07f926c77f8c9defd03c1a297df5ec795b | bigcode/the-stack | train |
da84164354f8378815e53b9c | train | function | def generator_fn(sents1, sents2, vocab_fpath):
'''Generates training / evaluation data
sents1: list of source sents
sents2: list of target sents
vocab_fpath: string. vocabulary file path.
yields
xs: tuple of
x: list of source token ids in a sent
x_seqlen: int. sequence ... | def generator_fn(sents1, sents2, vocab_fpath):
| '''Generates training / evaluation data
sents1: list of source sents
sents2: list of target sents
vocab_fpath: string. vocabulary file path.
yields
xs: tuple of
x: list of source token ids in a sent
x_seqlen: int. sequence length of x
sent1: str. raw source (=in... | = inp.decode("utf-8")
if type=="x": tokens = inp_str.split() + ["</s>"]
else: tokens = ["<s>"] + inp_str.split() + ["</s>"]
x = [dict.get(t, dict["<unk>"]) for t in tokens]
return x
def generator_fn(sents1, sents2, vocab_fpath):
| 86 | 86 | 288 | 15 | 70 | ZhichaoOuyang/transformer | data_load.py | Python | generator_fn | generator_fn | 66 | 90 | 66 | 66 | e588c29d3ce6310c7855a1a21e9509b57a66df23 | bigcode/the-stack | train |
ab34882352bffb491148bca2 | train | class | class Solution:
# Dynamic Programming
def countSubstrings(self, s: str) -> int:
if not s:
return 0
count = 0
# Base case: single letter substrings.
pln = [[False] * len(s) for _ in s]
for i in range(len(s)):
pln[i][i] = True
count += 1... | class Solution:
# Dynamic Programming
| def countSubstrings(self, s: str) -> int:
if not s:
return 0
count = 0
# Base case: single letter substrings.
pln = [[False] * len(s) for _ in s]
for i in range(len(s)):
pln[i][i] = True
count += 1
# Base case: double letter subst... | # 647. Palindromic Substrings
# Runtime: 546 ms, faster than 15.15% of Python3 online submissions for Palindromic Substrings.
# Memory Usage: 22.1 MB, less than 27.60% of Python3 online submissions for Palindromic Substrings.
class Solution:
# Dynamic Programming
| 76 | 79 | 265 | 8 | 68 | czs108/LeetCode-Solutions | Medium/647. Palindromic Substrings/solution (1).py | Python | Solution | Solution | 8 | 36 | 8 | 9 | 8899310fcb2f6aa32eea52706eddba0220c963d6 | bigcode/the-stack | train |
23274a73bfa0f6a01430067c | train | class | class PixivAPI(BasePixivAPI):
def __init__(self, **requests_kwargs):
"""initialize requests kwargs if need be"""
super(PixivAPI, self).__init__(**requests_kwargs)
# Check auth and set BearerToken to headers
def auth_requests_call(self, method, url, headers=None, params=None, data=None):
... | class PixivAPI(BasePixivAPI):
| def __init__(self, **requests_kwargs):
"""initialize requests kwargs if need be"""
super(PixivAPI, self).__init__(**requests_kwargs)
# Check auth and set BearerToken to headers
def auth_requests_call(self, method, url, headers=None, params=None, data=None):
self.require_auth()
... | # -*- coding:utf-8 -*-
from requests.structures import CaseInsensitiveDict
from .api import BasePixivAPI
from .utils import PixivError
# Public-API
class PixivAPI(BasePixivAPI):
| 47 | 256 | 2,853 | 9 | 37 | kerosukedakero/pixivpy | pixivpy3/papi.py | Python | PixivAPI | PixivAPI | 10 | 286 | 10 | 11 | 41dfe0e069580f0c1669f5584d39a9207acfda6f | bigcode/the-stack | train |
2a5e702db5fdfff0ceaed8b0 | train | function | def setup_handlers():
port = __opts__['runtests_log_port']
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
sock.connect(('localhost', port))
except socket.error as exc:
if exc.errno == errno.ECONNREFUSED:
... | def setup_handlers():
| port = __opts__['runtests_log_port']
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
sock.connect(('localhost', port))
except socket.error as exc:
if exc.errno == errno.ECONNREFUSED:
log.warning('Fai... | def __virtual__():
if 'runtests_log_port' not in __opts__:
return False, "'runtests_log_port' not in options"
if six.PY3:
return False, "runtests external logging handler is temporarily disabled for Python 3 tests"
return True
def setup_handlers():
| 70 | 70 | 235 | 4 | 65 | byteskeptical/salt | tests/integration/files/log_handlers/runtests_log_handler.py | Python | setup_handlers | setup_handlers | 41 | 69 | 41 | 41 | 7a1d3c31b3752c8eb97fa7054930d22bf6745aa5 | bigcode/the-stack | train |
c68f50c5c609e3fa0359fc12 | train | function | def process_queue(port, queue):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
sock.connect(('localhost', port))
except socket.error as exc:
if exc.errno == errno.ECONNREFUSED:
sock.shutdown(socket.SHUT... | def process_queue(port, queue):
| sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
sock.connect(('localhost', port))
except socket.error as exc:
if exc.errno == errno.ECONNREFUSED:
sock.shutdown(socket.SHUT_RDWR)
sock.close()
... | = 10000000
queue = Queue(queue_size)
handler = salt.log.setup.QueueHandler(queue)
level = salt.log.setup.LOG_LEVELS[(__opts__.get('runtests_log_level') or 'error').lower()]
handler.setLevel(level)
process_queue_thread = threading.Thread(target=process_queue, args=(port, queue))
process_queue_th... | 100 | 100 | 335 | 7 | 92 | byteskeptical/salt | tests/integration/files/log_handlers/runtests_log_handler.py | Python | process_queue | process_queue | 72 | 118 | 72 | 72 | 89c4dc3dac9396532f74d92f46599bfcd276d1a5 | bigcode/the-stack | train |
2fe232a154438b28ffda9ece | train | function | def __virtual__():
if 'runtests_log_port' not in __opts__:
return False, "'runtests_log_port' not in options"
if six.PY3:
return False, "runtests external logging handler is temporarily disabled for Python 3 tests"
return True
| def __virtual__():
| if 'runtests_log_port' not in __opts__:
return False, "'runtests_log_port' not in options"
if six.PY3:
return False, "runtests external logging handler is temporarily disabled for Python 3 tests"
return True
| threading
from multiprocessing import Queue
# Import Salt libs
import salt.utils.msgpack
from salt.ext import six
from salt.utils.platform import is_darwin
import salt.log.setup
log = logging.getLogger(__name__)
__virtualname__ = 'runtests_log_handler'
def __virtual__():
| 64 | 64 | 66 | 5 | 59 | byteskeptical/salt | tests/integration/files/log_handlers/runtests_log_handler.py | Python | __virtual__ | __virtual__ | 33 | 38 | 33 | 33 | 48144ce0609596d6459f8ce043050610640ae013 | bigcode/the-stack | train |
4fa38ce7d6e344a56a33ff6e | train | class | class ConfigurationError(ConverterError):
"""
Raised if there are any configuration errors.
"""
pass
| class ConfigurationError(ConverterError):
| """
Raised if there are any configuration errors.
"""
pass
| from converter.errors import ConverterError
class ConfigurationError(ConverterError):
| 14 | 64 | 23 | 7 | 6 | stufraser1/OasisDataConverter | converter/config/errors.py | Python | ConfigurationError | ConfigurationError | 4 | 9 | 4 | 4 | 27f45f1a633c27681616832097716b2091d5cfba | bigcode/the-stack | train |
b12d4cf5d4ac14c72bb101ad | train | class | class TestDistrict(unittest.TestCase):
def test_set_id(self):
district = District(id=10)
self.assertEqual(10, district.id)
def test_no_id(self):
district = District()
self.assertTrue(district.id is None)
def test_dict_party(self):
party_votes = {"republican":100, "... | class TestDistrict(unittest.TestCase):
| def test_set_id(self):
district = District(id=10)
self.assertEqual(10, district.id)
def test_no_id(self):
district = District()
self.assertTrue(district.id is None)
def test_dict_party(self):
party_votes = {"republican":100, "democrat":200, "other":700}
dist... | import unittest
from libdistrict.district import District
"""
TODO write tests for the District class
"""
class TestDistrict(unittest.TestCase):
| 28 | 64 | 106 | 7 | 21 | PlanScore/libdistrict | tests/test_district.py | Python | TestDistrict | TestDistrict | 10 | 23 | 10 | 11 | f5ced82b9b67a36cf42cbbc4f37da54d76b7b3e4 | bigcode/the-stack | train |
5eb6f66a46c7405d60f7e423 | train | function | def find_rotation_point(lst):
if len(lst) == 0:
raise Exception("List of words can't be empty!")
start_point = 0
end_point = len(lst) - 1
first = lst[0]
while start_point < end_point:
mid_point = start_point + ((end_point - start_point) // 2)
if lst[mid_point] >= ... | def find_rotation_point(lst):
| if len(lst) == 0:
raise Exception("List of words can't be empty!")
start_point = 0
end_point = len(lst) - 1
first = lst[0]
while start_point < end_point:
mid_point = start_point + ((end_point - start_point) // 2)
if lst[mid_point] >= first:
start_point... | ',
'asymptote', # <-- rotates here!
'babka',
'banoffee',
'engender',
'karpatka',
'othellolagkage',
]
Since the list is mostly ordered, immediately think binary search
"""
def find_rotation_point(lst):
| 64 | 64 | 122 | 6 | 58 | muniri92/microsoft-interview-study | src/find_rotation_point.py | Python | find_rotation_point | find_rotation_point | 23 | 41 | 23 | 23 | 86e6cbaa6c1fac721efd139131628a319e3dcb2a | bigcode/the-stack | train |
b354cfa438d8857457f4149b | train | function | def test_optimize_for_inference():
@trace(symbolic=True, capture_as_const=True)
def f(x):
return exp(x)
_, out = mkstemp()
f(tensor(5.0))
f.dump(out, enable_io16xc32=True)
res = G.load_graph(out)
computing_input = res.output_vars_list[0].owner.inputs[0]
assert computing_input.d... | def test_optimize_for_inference():
@trace(symbolic=True, capture_as_const=True)
| def f(x):
return exp(x)
_, out = mkstemp()
f(tensor(5.0))
f.dump(out, enable_io16xc32=True)
res = G.load_graph(out)
computing_input = res.output_vars_list[0].owner.inputs[0]
assert computing_input.dtype == np.float16
| outputs = G.load_graph(out).output_vars_list
oprs_2 = cgtools.get_oprs_seq(outputs)
assert len(oprs_1) - len(oprs_2) == 2
def test_optimize_for_inference():
@trace(symbolic=True, capture_as_const=True)
| 64 | 64 | 93 | 20 | 43 | Olalaye/MegEngine | imperative/python/test/unit/jit/test_tracing.py | Python | test_optimize_for_inference | test_optimize_for_inference | 379 | 390 | 379 | 380 | 8bd9de7fef62194b4d5a5b69ab9b069475f24270 | bigcode/the-stack | train |
ea4cda409f2f09ded976514a | train | function | def test_dump_with_testcase():
@trace(symbolic=True, capture_as_const=True)
def f(x):
return exp(x)
f(tensor(1.0))
file = io.BytesIO()
f.dump(file, input_data=["#rand(0, 255, 1)"])
| def test_dump_with_testcase():
@trace(symbolic=True, capture_as_const=True)
| def f(x):
return exp(x)
f(tensor(1.0))
file = io.BytesIO()
f.dump(file, input_data=["#rand(0, 255, 1)"])
| tools.GraphInference(file)
results = list((infer_cg.run(x0, x1)).values())
np.testing.assert_equal(results[0], y)
np.testing.assert_equal(results[1], dx0)
def test_dump_with_testcase():
@trace(symbolic=True, capture_as_const=True)
| 64 | 64 | 65 | 19 | 45 | Olalaye/MegEngine | imperative/python/test/unit/jit/test_tracing.py | Python | test_dump_with_testcase | test_dump_with_testcase | 296 | 303 | 296 | 297 | e6f087d6cc69990c6c4ea606707c29c0894073d0 | bigcode/the-stack | train |
bc9dc4de7318975abcbc130a | train | function | def test_trace_cvt_bool():
x = tensor([0], dtype=np.int32)
@trace(symbolic=True)
def f(x):
a = x.shape
b = a[0]
assert isscalar(b)
return b == 0
for i in range(3):
np.testing.assert_equal(f(x).numpy(), False)
| def test_trace_cvt_bool():
| x = tensor([0], dtype=np.int32)
@trace(symbolic=True)
def f(x):
a = x.shape
b = a[0]
assert isscalar(b)
return b == 0
for i in range(3):
np.testing.assert_equal(f(x).numpy(), False)
| = tensor(np.ones(1, dtype=np.float32))
@trace(capture_as_const=True, symbolic_shape=True)
def f():
return a._broadcast(tensor([1, 10], dtype=np.int32))
f()
f.dump(io.BytesIO())
def test_trace_cvt_bool():
| 64 | 64 | 77 | 7 | 57 | Olalaye/MegEngine | imperative/python/test/unit/jit/test_tracing.py | Python | test_trace_cvt_bool | test_trace_cvt_bool | 404 | 415 | 404 | 404 | 40a7dc96b688ed77348efab753080eb430d409fb | bigcode/the-stack | train |
5aca5d0226a199dfd83072ce | train | function | def test_goptions_log_sum_exp():
@trace(symbolic=True, opt_level=0, capture_as_const=True)
def f(x, y):
return log(exp(x) + exp(y))
@trace(symbolic=True, opt_level=1, capture_as_const=True)
def g(x, y):
return log(exp(x) + exp(y))
val = 1.0e4
d = tensor(val)
o = tensor(0.0)... | def test_goptions_log_sum_exp():
@trace(symbolic=True, opt_level=0, capture_as_const=True)
| def f(x, y):
return log(exp(x) + exp(y))
@trace(symbolic=True, opt_level=1, capture_as_const=True)
def g(x, y):
return log(exp(x) + exp(y))
val = 1.0e4
d = tensor(val)
o = tensor(0.0)
assert not np.isfinite(f(d, o).numpy())
np.testing.assert_almost_equal(g(d, o), val)
| y
d = tensor(0.0)
assert not np.isfinite(f(d).numpy())
np.testing.assert_equal(g(d).numpy().item(), 1.0)
def test_goptions_log_sum_exp():
@trace(symbolic=True, opt_level=0, capture_as_const=True)
| 64 | 64 | 128 | 25 | 39 | Olalaye/MegEngine | imperative/python/test/unit/jit/test_tracing.py | Python | test_goptions_log_sum_exp | test_goptions_log_sum_exp | 340 | 353 | 340 | 341 | 12df4442a02233adaea57aa443d4858fe45ec1c2 | bigcode/the-stack | train |
ed5c9857238fa4c28b78c911 | train | function | def test_dump_backward_graph():
x0 = tensor(np.random.randn(3, 4))
x1 = tensor(np.random.randn(3, 4))
gm = GradManager().attach(x0)
@trace(symbolic=True, capture_as_const=True)
def f(x0, x1):
with gm:
y = x0 * x1
gm.backward(y, F.ones_like(y))
dx0 = x0.g... | def test_dump_backward_graph():
| x0 = tensor(np.random.randn(3, 4))
x1 = tensor(np.random.randn(3, 4))
gm = GradManager().attach(x0)
@trace(symbolic=True, capture_as_const=True)
def f(x0, x1):
with gm:
y = x0 * x1
gm.backward(y, F.ones_like(y))
dx0 = x0.grad
return y, dx0
y... | , optimize_for_inference=False)
file.seek(0)
(out,) = G.load_graph(file).output_vars_list
assert (
cgtools.get_owner_opr_type(cgtools.get_owner_opr_inputs(out)[1])
== "ImmutableTensor"
)
def test_dump_backward_graph():
| 64 | 64 | 203 | 6 | 58 | Olalaye/MegEngine | imperative/python/test/unit/jit/test_tracing.py | Python | test_dump_backward_graph | test_dump_backward_graph | 268 | 293 | 268 | 268 | 667a3c660e2db52b84aae25110e03588242dcf69 | bigcode/the-stack | train |
7d66b8783a01099b46bbbc09 | train | function | def test_trace_topk():
x = tensor([5, 2, 7, 1, 0, 3, 2])
@trace(symbolic=True)
def f(x):
y = F.topk(x, 3)
np.testing.assert_equal(y[0].shape.numpy(), np.array([3,]))
return y
for i in range(3):
f(x)
| def test_trace_topk():
| x = tensor([5, 2, 7, 1, 0, 3, 2])
@trace(symbolic=True)
def f(x):
y = F.topk(x, 3)
np.testing.assert_equal(y[0].shape.numpy(), np.array([3,]))
return y
for i in range(3):
f(x)
| , 10, 10))
@trace(symbolic=trace_mode, capture_as_const=True)
def f(x):
y = x.reshape(x.shape[0], 100)
return y
f(x1)
f(x2)
f(x3)
def test_trace_topk():
| 64 | 64 | 88 | 6 | 58 | Olalaye/MegEngine | imperative/python/test/unit/jit/test_tracing.py | Python | test_trace_topk | test_trace_topk | 434 | 444 | 434 | 434 | ef5db841948259a20350c27e1a0669d819684437 | bigcode/the-stack | train |
c3cd12c4948285b64d1940fa | train | function | @pytest.mark.parametrize("trace_mode", [False, True])
def test_trace_profiler(trace_mode):
@trace(symbolic=trace_mode, profiling=True)
def f(x):
return -x
x = tensor([1])
y = f(x).numpy()
f(x)
f(x) # XXX: has to run twice
out = f.get_profile()
assert out.get("profiler")
| @pytest.mark.parametrize("trace_mode", [False, True])
def test_trace_profiler(trace_mode):
@trace(symbolic=trace_mode, profiling=True)
| def f(x):
return -x
x = tensor([1])
y = f(x).numpy()
f(x)
f(x) # XXX: has to run twice
out = f.get_profile()
assert out.get("profiler")
| 1.0))
file = io.BytesIO()
f.dump(file, input_data=["#rand(0, 255, 1)"])
@pytest.mark.parametrize("trace_mode", [False, True])
def test_trace_profiler(trace_mode):
@trace(symbolic=trace_mode, profiling=True)
| 63 | 64 | 89 | 32 | 31 | Olalaye/MegEngine | imperative/python/test/unit/jit/test_tracing.py | Python | test_trace_profiler | test_trace_profiler | 306 | 319 | 306 | 308 | 4e9466451b0e9406f8fe944267268c592354561b | bigcode/the-stack | train |
14765417f3d5a92b10a3145c | train | function | @pytest.mark.parametrize("trace_mode", [False, True])
@pytest.mark.parametrize("return_mode", ["Value", "Tuple", "List", "Dict"])
def test_trace(trace_mode, return_mode):
@trace(symbolic=trace_mode)
def f(x):
if return_mode == "Tuple":
return (-x,)
elif return_mode == "List":
... | @pytest.mark.parametrize("trace_mode", [False, True])
@pytest.mark.parametrize("return_mode", ["Value", "Tuple", "List", "Dict"])
def test_trace(trace_mode, return_mode):
@trace(symbolic=trace_mode)
| def f(x):
if return_mode == "Tuple":
return (-x,)
elif return_mode == "List":
return [-x]
elif return_mode == "Dict":
return {"neg": -x}
else:
return -x
def get_numpy(y):
if return_mode == "Tuple" or return_mode == "List":
... | .random import normal, uniform
from megengine.utils.naming import AutoNaming
@pytest.mark.parametrize("trace_mode", [False, True])
@pytest.mark.parametrize("return_mode", ["Value", "Tuple", "List", "Dict"])
def test_trace(trace_mode, return_mode):
@trace(symbolic=trace_mode)
| 64 | 64 | 189 | 49 | 14 | Olalaye/MegEngine | imperative/python/test/unit/jit/test_tracing.py | Python | test_trace | test_trace | 34 | 59 | 34 | 37 | 5dc97eaa5a3744b69d95df88d87041e5fe20c85c | bigcode/the-stack | train |
7b4e0b81af2623af6d42fcce | train | function | @pytest.mark.parametrize("trace_mode", [False, True])
def test_elemwise_fuse(trace_mode):
# explicitly declare opt_level as 2
@trace(symbolic=trace_mode, opt_level=2)
def f(a, b):
base = 0
c = b - a
_, idx = F.topk(c, 3)
# internally, biased_idx will be idx as gopt will ignor... | @pytest.mark.parametrize("trace_mode", [False, True])
def test_elemwise_fuse(trace_mode):
# explicitly declare opt_level as 2
@trace(symbolic=trace_mode, opt_level=2)
| def f(a, b):
base = 0
c = b - a
_, idx = F.topk(c, 3)
# internally, biased_idx will be idx as gopt will ignore the addition
biased_idx = base + idx
return biased_idx
a = tensor(np.ones((7, 2)), dtype=np.int32)
b = tensor(2 * np.ones((7, 2)), dtype=np.float32)... | y = f(x).numpy()
np.testing.assert_equal(f(x).numpy(), y)
@pytest.mark.parametrize("trace_mode", [False, True])
def test_elemwise_fuse(trace_mode):
# explicitly declare opt_level as 2
@trace(symbolic=trace_mode, opt_level=2)
| 64 | 64 | 164 | 45 | 19 | Olalaye/MegEngine | imperative/python/test/unit/jit/test_tracing.py | Python | test_elemwise_fuse | test_elemwise_fuse | 129 | 146 | 129 | 132 | acf3e58fc4db73217e53c6b8a5bbf0c8804eafe8 | bigcode/the-stack | train |
b8f74991bab8be75fea1b7bb | train | function | def test_trace_valid_broadcast():
x1 = tensor(np.random.randn(1, 1))
x2 = tensor(np.random.randn(1, 2))
shape = (tensor([2]), tensor([2]))
@trace(symbolic=False)
def f(x, shape):
y = F.broadcast_to(x, shape)
return y
f(x1, shape)
f(x2, shape)
| def test_trace_valid_broadcast():
| x1 = tensor(np.random.randn(1, 1))
x2 = tensor(np.random.randn(1, 2))
shape = (tensor([2]), tensor([2]))
@trace(symbolic=False)
def f(x, shape):
y = F.broadcast_to(x, shape)
return y
f(x1, shape)
f(x2, shape)
| with exclude_from_trace():
_ = F.vision.nms(boxes, scores=scores, iou_thresh=0.5)
return results
f(*make_inputs(10))
f(*make_inputs(20))
f(*make_inputs(30))
def test_trace_valid_broadcast():
| 64 | 64 | 89 | 7 | 57 | Olalaye/MegEngine | imperative/python/test/unit/jit/test_tracing.py | Python | test_trace_valid_broadcast | test_trace_valid_broadcast | 539 | 550 | 539 | 539 | 65dce619fca9ee48e923d7156ffca9b30fae8534 | bigcode/the-stack | train |
8bb06740e46ee503dbe55b9f | train | function | def test_goptions():
@trace(symbolic=True, opt_level=0, capture_as_const=True)
def f(x):
# directly return x / x will not trigger gopt
# since there's no way to tell the two x are the same
y = 2.0 * x
return y / y
@trace(symbolic=True, opt_level=1, capture_as_const=True)
... | def test_goptions():
@trace(symbolic=True, opt_level=0, capture_as_const=True)
| def f(x):
# directly return x / x will not trigger gopt
# since there's no way to tell the two x are the same
y = 2.0 * x
return y / y
@trace(symbolic=True, opt_level=1, capture_as_const=True)
def g(x):
y = 2.0 * x
return y / y
d = tensor(0.0)
assert... | 1])
y = f(x).numpy()
f(x)
f(x) # XXX: has to run twice
out = f.get_profile()
assert out.get("profiler")
def test_goptions():
@trace(symbolic=True, opt_level=0, capture_as_const=True)
| 64 | 64 | 146 | 22 | 42 | Olalaye/MegEngine | imperative/python/test/unit/jit/test_tracing.py | Python | test_goptions | test_goptions | 322 | 337 | 322 | 323 | 885390e75afd2b1509865cbb9ab907bc427721cf | bigcode/the-stack | train |
f6fe52ed136f372d7ae825c1 | train | function | @pytest.mark.parametrize("shape_mode", [False, True])
def test_trace_advance_indexing(shape_mode):
funcs = [
lambda x, i: x[i],
lambda x, i, j: x[i, j],
lambda x, i, j: x[i, :, j, ...],
lambda x, start, end: x[start:end],
lambda x, start, end: x[:, 0, start:end, ..., 1],
... | @pytest.mark.parametrize("shape_mode", [False, True])
def test_trace_advance_indexing(shape_mode):
| funcs = [
lambda x, i: x[i],
lambda x, i, j: x[i, j],
lambda x, i, j: x[i, :, j, ...],
lambda x, start, end: x[start:end],
lambda x, start, end: x[:, 0, start:end, ..., 1],
lambda x, vec: x[vec],
lambda x, vec: x[vec, ..., 0, 1:3],
lambda x, vec: x[vec... | True])
def test_random(shape_mode):
def run_test(op):
@trace(symbolic=True, symbolic_shape=shape_mode)
def f():
out = op(size=[10, 10])
out_shape = out.shape
assert out_shape is not None
if not isinstance(out_shape, tuple):
assert out.... | 124 | 124 | 416 | 22 | 102 | Olalaye/MegEngine | imperative/python/test/unit/jit/test_tracing.py | Python | test_trace_advance_indexing | test_trace_advance_indexing | 601 | 639 | 601 | 602 | 10d8e70fb0e300847007010afc7bb847cb6357ed | bigcode/the-stack | train |
f51de9e45cf719eec6738528 | train | function | def test_slice():
@trace
def f(x):
return x[:, 1::2]
x = F.arange(8).reshape(2, 4)
f(x)
y = f(x)
np.testing.assert_array_equal(y.numpy(), x.numpy()[:, 1::2])
y + y
| def test_slice():
@trace
| def f(x):
return x[:, 1::2]
x = F.arange(8).reshape(2, 4)
f(x)
y = f(x)
np.testing.assert_array_equal(y.numpy(), x.numpy()[:, 1::2])
y + y
| )
return y
for i in range(3):
f(x, tensor([0]), tensor([1]))
for i in range(3):
f(x, tensor([5]), tensor([4]))
# test returning noncontiguous tensor from trace
def test_slice():
@trace
| 64 | 64 | 70 | 8 | 55 | Olalaye/MegEngine | imperative/python/test/unit/jit/test_tracing.py | Python | test_slice | test_slice | 570 | 579 | 570 | 571 | 8736c95595ef3905b195ab0352affcb78fab245f | bigcode/the-stack | train |
2a0983d11d626c753e7acf1a | train | function | def test_goptions_log_exp():
@trace(symbolic=True, opt_level=0, capture_as_const=True)
def f(x):
return log(exp(x))
@trace(symbolic=True, opt_level=1, capture_as_const=True)
def g(x):
return log(exp(x))
f(tensor(1.0))
_, out = mkstemp()
f.dump(out, optimize_for_inference=Fa... | def test_goptions_log_exp():
@trace(symbolic=True, opt_level=0, capture_as_const=True)
| def f(x):
return log(exp(x))
@trace(symbolic=True, opt_level=1, capture_as_const=True)
def g(x):
return log(exp(x))
f(tensor(1.0))
_, out = mkstemp()
f.dump(out, optimize_for_inference=False)
outputs = G.load_graph(out).output_vars_list
oprs_1 = cgtools.get_oprs_seq(out... | = tensor(val)
o = tensor(0.0)
assert not np.isfinite(f(d, o).numpy())
np.testing.assert_almost_equal(g(d, o), val)
def test_goptions_log_exp():
@trace(symbolic=True, opt_level=0, capture_as_const=True)
| 64 | 64 | 182 | 24 | 40 | Olalaye/MegEngine | imperative/python/test/unit/jit/test_tracing.py | Python | test_goptions_log_exp | test_goptions_log_exp | 356 | 376 | 356 | 357 | 55fdf5bba14a219971a103120ae727d5a3659cd2 | bigcode/the-stack | train |
99625f10842f127226ac617d | train | function | @pytest.mark.parametrize("trace_mode", [False, True])
def test_elemwise_fuse_in_grad(trace_mode):
w = Parameter(np.ones([4, 6]), dtype="float32")
gm = GradManager().attach(w)
opt = optim.SGD([w], lr=0.01, momentum=0.9, weight_decay=5e-4)
# explicitly declare opt_level as 2
@trace(symbolic=trace_mo... | @pytest.mark.parametrize("trace_mode", [False, True])
def test_elemwise_fuse_in_grad(trace_mode):
| w = Parameter(np.ones([4, 6]), dtype="float32")
gm = GradManager().attach(w)
opt = optim.SGD([w], lr=0.01, momentum=0.9, weight_decay=5e-4)
# explicitly declare opt_level as 2
@trace(symbolic=trace_mode, opt_level=2)
def f():
with gm:
wm = F.sum(w ** 2, axis=1) ** 0.5
... | )
b = tensor(2 * np.ones((7, 2)), dtype=np.float32)
for i in range(3):
y = f(a, b)
y.numpy()
@pytest.mark.parametrize("trace_mode", [False, True])
def test_elemwise_fuse_in_grad(trace_mode):
| 64 | 64 | 169 | 23 | 41 | Olalaye/MegEngine | imperative/python/test/unit/jit/test_tracing.py | Python | test_elemwise_fuse_in_grad | test_elemwise_fuse_in_grad | 149 | 168 | 149 | 150 | a0ff6d78217e6d229715bf5bf9a470b84715e3cf | bigcode/the-stack | train |
e3a6826a269f310dd9215f26 | train | function | @pytest.mark.parametrize("trace_mode", [False, True])
def test_tensor_detach(trace_mode):
@trace(symbolic=True)
def f(x):
y = x.detach() ** 2
z = y.detach() + 1
return z.detach()
x = tensor([1, 2, 3, 4])
for _ in range(3):
f(x).numpy()
| @pytest.mark.parametrize("trace_mode", [False, True])
def test_tensor_detach(trace_mode):
@trace(symbolic=True)
| def f(x):
y = x.detach() ** 2
z = y.detach() + 1
return z.detach()
x = tensor([1, 2, 3, 4])
for _ in range(3):
f(x).numpy()
| numpy()
ys[symbolic].append(y)
for i in range(3):
np.testing.assert_equal(ys[False][i], ys[True][i])
@pytest.mark.parametrize("trace_mode", [False, True])
def test_tensor_detach(trace_mode):
@trace(symbolic=True)
| 64 | 64 | 87 | 27 | 37 | Olalaye/MegEngine | imperative/python/test/unit/jit/test_tracing.py | Python | test_tensor_detach | test_tensor_detach | 98 | 108 | 98 | 100 | 2bb72661bfa0960bacd90e062af348ba27f11e82 | bigcode/the-stack | train |
a4dbf088a5e164ab14aea38b | train | function | @pytest.mark.require_ngpu(1) # nvrtc backend
def test_trace_jit_config():
def run(fuse_dimshuffle, fuse_reduce):
config = GraphOptimizationConfig()
config.jit_fuse_dimshuffle = fuse_dimshuffle
config.jit_fuse_reduce = fuse_reduce
# set opt_level = 1 to avoid fusing dimshuffle and r... | @pytest.mark.require_ngpu(1) # nvrtc backend
def test_trace_jit_config():
| def run(fuse_dimshuffle, fuse_reduce):
config = GraphOptimizationConfig()
config.jit_fuse_dimshuffle = fuse_dimshuffle
config.jit_fuse_reduce = fuse_reduce
# set opt_level = 1 to avoid fusing dimshuffle and reduce at the same time
@trace(opt_level=1, graph_opt_config=config)... | perative = f(**params)
np.testing.assert_equal(expected, result_imperative.numpy())
for _ in range(3):
result_trace = f_traced(**params)
np.testing.assert_equal(expected, result_trace.numpy())
@pytest.mark.require_ngpu(1) # nvrtc backend
def test_trace_jit_config():
| 70 | 70 | 236 | 21 | 49 | Olalaye/MegEngine | imperative/python/test/unit/jit/test_tracing.py | Python | test_trace_jit_config | test_trace_jit_config | 642 | 666 | 642 | 643 | 1a2d29aa9e644db87a02e089195373ae0be97981 | bigcode/the-stack | train |
f5a35ff5b911684137340938 | train | function | @pytest.mark.parametrize("trace_mode", [False, True])
def test_trace_reshape(trace_mode):
x1 = tensor(np.random.randn(2, 10, 10))
x2 = tensor(np.random.randn(4, 10, 10))
x3 = tensor(np.random.randn(8, 10, 10))
@trace(symbolic=trace_mode, capture_as_const=True)
def f(x):
y = x.reshape(x.shap... | @pytest.mark.parametrize("trace_mode", [False, True])
def test_trace_reshape(trace_mode):
| x1 = tensor(np.random.randn(2, 10, 10))
x2 = tensor(np.random.randn(4, 10, 10))
x3 = tensor(np.random.randn(8, 10, 10))
@trace(symbolic=trace_mode, capture_as_const=True)
def f(x):
y = x.reshape(x.shape[0], 100)
return y
f(x1)
f(x2)
f(x3)
| = x.shape
b = a[0]
assert isscalar(b)
return b == 0
for i in range(3):
np.testing.assert_equal(f(x).numpy(), False)
@pytest.mark.parametrize("trace_mode", [False, True])
def test_trace_reshape(trace_mode):
| 64 | 64 | 122 | 20 | 44 | Olalaye/MegEngine | imperative/python/test/unit/jit/test_tracing.py | Python | test_trace_reshape | test_trace_reshape | 418 | 431 | 418 | 419 | a79b34b5623e586c0b4a4373cea9f05310f3988b | bigcode/the-stack | train |
bc2c9f715c4633c9b6181db6 | train | function | @pytest.mark.parametrize("shape_mode", [False, True])
def test_random(shape_mode):
def run_test(op):
@trace(symbolic=True, symbolic_shape=shape_mode)
def f():
out = op(size=[10, 10])
out_shape = out.shape
assert out_shape is not None
if not isinstance(... | @pytest.mark.parametrize("shape_mode", [False, True])
def test_random(shape_mode):
| def run_test(op):
@trace(symbolic=True, symbolic_shape=shape_mode)
def f():
out = op(size=[10, 10])
out_shape = out.shape
assert out_shape is not None
if not isinstance(out_shape, tuple):
assert out.shape.numpy() is not None
... | = F.arange(8).reshape(2, 4)
f(x)
y = f(x)
np.testing.assert_array_equal(y.numpy(), x.numpy()[:, 1::2])
y + y
@pytest.mark.parametrize("shape_mode", [False, True])
def test_random(shape_mode):
| 64 | 64 | 112 | 18 | 45 | Olalaye/MegEngine | imperative/python/test/unit/jit/test_tracing.py | Python | test_random | test_random | 582 | 598 | 582 | 583 | 20b57612aeaa600d3a6d8816690331f71a9a51bc | bigcode/the-stack | train |
58d55fbee4ad80bf67061634 | train | function | @pytest.mark.parametrize("trace_mode", [False, True])
def test_clip(trace_mode):
x = tensor(np.random.randn(10, 10))
@trace(symbolic=trace_mode)
def f(x, lower, upper):
y = F.clip(x, lower, upper)
return y
for i in range(3):
f(x, tensor([0]), tensor([1]))
for i in range(3)... | @pytest.mark.parametrize("trace_mode", [False, True])
def test_clip(trace_mode):
| x = tensor(np.random.randn(10, 10))
@trace(symbolic=trace_mode)
def f(x, lower, upper):
y = F.clip(x, lower, upper)
return y
for i in range(3):
f(x, tensor([0]), tensor([1]))
for i in range(3):
f(x, tensor([5]), tensor([4]))
| tensor([2]))
@trace(symbolic=False)
def f(x, shape):
y = F.broadcast_to(x, shape)
return y
f(x1, shape)
f(x2, shape)
@pytest.mark.parametrize("trace_mode", [False, True])
def test_clip(trace_mode):
| 64 | 64 | 104 | 18 | 46 | Olalaye/MegEngine | imperative/python/test/unit/jit/test_tracing.py | Python | test_clip | test_clip | 553 | 566 | 553 | 554 | 76fd133faaeb360c5e2bd29fde44e7899aa07b6c | bigcode/the-stack | train |
77a2a174c7d56fcd90632350 | train | function | def test_raise_on_trace():
step_count = 0
catch_count = 0
bad_step = 10
class CatchMe(Exception):
pass
a = tensor([1, 2, 3, 4])
b = tensor([5, 6, 7, 8])
c = tensor([9, 0, 1, 2])
@trace
def add_abc(a, b, c):
ps = a + b
result = ps + c
if step_count =... | def test_raise_on_trace():
| step_count = 0
catch_count = 0
bad_step = 10
class CatchMe(Exception):
pass
a = tensor([1, 2, 3, 4])
b = tensor([5, 6, 7, 8])
c = tensor([9, 0, 1, 2])
@trace
def add_abc(a, b, c):
ps = a + b
result = ps + c
if step_count == bad_step:
rai... | .vision.warp_perspective(x, M, (2, 2))
np.testing.assert_equal(out.shape.numpy(), np.array([1, 1, 2, 2]))
return out
for i in range(3):
f(x, M)
def test_raise_on_trace():
| 64 | 64 | 205 | 6 | 58 | Olalaye/MegEngine | imperative/python/test/unit/jit/test_tracing.py | Python | test_raise_on_trace | test_raise_on_trace | 467 | 496 | 467 | 467 | 814d15f9dde8745f72c1664fbaefb6b5389e583f | bigcode/the-stack | train |
be0bf8583cef53ff5c1eb2fd | train | function | def test_capture_dump():
a = tensor([2])
@trace(symbolic=True, capture_as_const=True)
def f(x):
return x * a
x = tensor([3])
y = f(x).numpy()
for i in range(3):
np.testing.assert_equal(f(x).numpy(), y)
file = io.BytesIO()
f.dump(file)
file.seek(0)
infer_cg = c... | def test_capture_dump():
| a = tensor([2])
@trace(symbolic=True, capture_as_const=True)
def f(x):
return x * a
x = tensor([3])
y = f(x).numpy()
for i in range(3):
np.testing.assert_equal(f(x).numpy(), y)
file = io.BytesIO()
f.dump(file)
file.seek(0)
infer_cg = cgtools.GraphInference(fil... | "])
np.testing.assert_equal(dump_info.outputs, ["ADD"])
file.seek(0)
infer_cg = cgtools.GraphInference(file)
result = list((infer_cg.run(a, b)).values())[0]
np.testing.assert_equal(result[0], y)
def test_capture_dump():
| 64 | 64 | 125 | 5 | 59 | Olalaye/MegEngine | imperative/python/test/unit/jit/test_tracing.py | Python | test_capture_dump | test_capture_dump | 224 | 242 | 224 | 224 | 67409fd1c7db877c5425ae618d65feeee7023e10 | bigcode/the-stack | train |
051865f9c6052718cd2af346 | train | function | def test_print_in_trace():
for symbolic in [False]: # cannot read value in symbolic mode
@trace(symbolic=symbolic)
def f(x):
nonlocal buf
x = -x
buf = x.numpy()
x = -x
return x
buf = None
x = tensor([1])
for i in... | def test_print_in_trace():
| for symbolic in [False]: # cannot read value in symbolic mode
@trace(symbolic=symbolic)
def f(x):
nonlocal buf
x = -x
buf = x.numpy()
x = -x
return x
buf = None
x = tensor([1])
for i in range(3):
y = ... | wm = F.sum(w ** 2, axis=1) ** 0.5
loss = wm.mean()
gm.backward(loss)
opt.step().clear_grad()
return loss
for i in range(3):
y = f()
y.numpy()
def test_print_in_trace():
| 64 | 64 | 122 | 6 | 58 | Olalaye/MegEngine | imperative/python/test/unit/jit/test_tracing.py | Python | test_print_in_trace | test_print_in_trace | 171 | 190 | 171 | 171 | a8539ba164ffd5fa731915a3018e3ad3c56421d2 | bigcode/the-stack | train |
36b4ed4eb6d4fabca2a8460a | train | function | def test_output_copy_trace():
class Simple(Module):
def __init__(self):
super().__init__()
self.a = Parameter([1.0], dtype=np.float32)
def forward(self, x):
x = x * self.a
# will result into a copy of output in grad
x = F.exp(x)
... | def test_output_copy_trace():
| class Simple(Module):
def __init__(self):
super().__init__()
self.a = Parameter([1.0], dtype=np.float32)
def forward(self, x):
x = x * self.a
# will result into a copy of output in grad
x = F.exp(x)
return x
ys = {False: [... | "List":
return y[0].numpy()
elif return_mode == "Dict":
return y["neg"].numpy()
return y.numpy()
x = tensor([1])
y = get_numpy(f(x))
for i in range(3):
np.testing.assert_equal(get_numpy(f(x)), y)
def test_output_copy_trace():
| 73 | 73 | 246 | 6 | 67 | Olalaye/MegEngine | imperative/python/test/unit/jit/test_tracing.py | Python | test_output_copy_trace | test_output_copy_trace | 62 | 95 | 62 | 62 | ac36385c534f04770ed2d9d11ad2552268b97f52 | bigcode/the-stack | train |
dd4382412fb2f4fd7c921dfc | train | function | def test_trace_nms():
def make_inputs(n):
boxes = np.zeros((n, 4))
boxes[:, :2] = np.random.rand(n, 2) * 100
boxes[:, 2:] = np.random.rand(n, 2) * 100 + 100
scores = np.random.rand(n)
return tensor(boxes), tensor(scores)
@trace(symbolic=False)
def f(boxes, scores):... | def test_trace_nms():
| def make_inputs(n):
boxes = np.zeros((n, 4))
boxes[:, :2] = np.random.rand(n, 2) * 100
boxes[:, 2:] = np.random.rand(n, 2) * 100 + 100
scores = np.random.rand(n)
return tensor(boxes), tensor(scores)
@trace(symbolic=False)
def f(boxes, scores):
# with tracin... | 5))
@trace(symbolic=trace_mode, capture_as_const=True)
def f(x):
y = F.broadcast_to(x, (3, 4, 5))
return y
f(x1)
f(x2)
f(x3)
def test_trace_nms():
| 64 | 64 | 206 | 6 | 58 | Olalaye/MegEngine | imperative/python/test/unit/jit/test_tracing.py | Python | test_trace_nms | test_trace_nms | 515 | 536 | 515 | 515 | e43dd6a1915d7aa00aee0cf7b3eed55eefc2bb00 | bigcode/the-stack | train |
e9433795dbe829ffcd442def | train | function | @pytest.mark.parametrize("trace_mode", [False, True])
def test_trace_broadcast(trace_mode):
x1 = tensor(np.random.randn(3, 1, 1))
x2 = tensor(np.random.randn(1, 4, 1))
x3 = tensor(np.random.randn(1, 1, 5))
@trace(symbolic=trace_mode, capture_as_const=True)
def f(x):
y = F.broadcast_to(x, (3... | @pytest.mark.parametrize("trace_mode", [False, True])
def test_trace_broadcast(trace_mode):
| x1 = tensor(np.random.randn(3, 1, 1))
x2 = tensor(np.random.randn(1, 4, 1))
x3 = tensor(np.random.randn(1, 1, 5))
@trace(symbolic=trace_mode, capture_as_const=True)
def f(x):
y = F.broadcast_to(x, (3, 4, 5))
return y
f(x1)
f(x2)
f(x3)
| e:
catch_count += 1
else:
np.testing.assert_equal(d.numpy(), (a + b + c).numpy())
step_count += 1
assert catch_count == 1
@pytest.mark.parametrize("trace_mode", [False, True])
def test_trace_broadcast(trace_mode):
| 64 | 64 | 126 | 20 | 43 | Olalaye/MegEngine | imperative/python/test/unit/jit/test_tracing.py | Python | test_trace_broadcast | test_trace_broadcast | 499 | 512 | 499 | 500 | d2f9487490bb37be6589e6df685eb42045612dbd | bigcode/the-stack | train |
6d05071dcb1b8b1e744ab1bd | train | function | def test_trace_warp_perspective():
inp_shape = (1, 1, 4, 4)
x = tensor(np.arange(16, dtype=np.float32).reshape(inp_shape))
M_shape = (1, 3, 3)
M = tensor(
np.array(
[[1.0, 0.0, 1.0], [0.0, 1.0, 1.0], [0.0, 0.0, 1.0]], dtype=np.float32
).reshape(M_shape)
)
@trace(symb... | def test_trace_warp_perspective():
| inp_shape = (1, 1, 4, 4)
x = tensor(np.arange(16, dtype=np.float32).reshape(inp_shape))
M_shape = (1, 3, 3)
M = tensor(
np.array(
[[1.0, 0.0, 1.0], [0.0, 1.0, 1.0], [0.0, 0.0, 1.0]], dtype=np.float32
).reshape(M_shape)
)
@trace(symbolic=True)
def f(x, M):
... | trace(symbolic=True)
def f(x):
y = F.topk(x, 3)
np.testing.assert_equal(y[0].shape.numpy(), np.array([3,]))
return y
for i in range(3):
f(x)
def test_trace_warp_perspective():
| 64 | 64 | 200 | 9 | 55 | Olalaye/MegEngine | imperative/python/test/unit/jit/test_tracing.py | Python | test_trace_warp_perspective | test_trace_warp_perspective | 447 | 464 | 447 | 447 | 8d6035ebf910a20721bea4ecd08f6c5c4349526a | bigcode/the-stack | train |
10c5668ceab43af42a1f99ce | train | function | @pytest.mark.parametrize(
"dump_format",
[
"FBS",
],
)
def test_dump(dump_format):
@trace(symbolic=True, capture_as_const=True)
def f(a, b):
return a + b
# prevent from remaining scope from exception test
AutoNaming.clear()
a = tensor([2])
b = tensor([4])
y = f(a... | @pytest.mark.parametrize(
"dump_format",
[
"FBS",
],
)
def test_dump(dump_format):
@trace(symbolic=True, capture_as_const=True)
| def f(a, b):
return a + b
# prevent from remaining scope from exception test
AutoNaming.clear()
a = tensor([2])
b = tensor([4])
y = f(a, b).numpy()
for i in range(3):
np.testing.assert_equal(f(a, b).numpy(), y)
file = io.BytesIO()
dump_info = f.dump(file, dump_form... | buf
buf = None
np.testing.assert_equal(f(x).numpy(), y)
np.testing.assert_equal(z, buf)
@pytest.mark.parametrize(
"dump_format",
[
"FBS",
],
)
def test_dump(dump_format):
@trace(symbolic=True, capture_as_const=True)
| 66 | 66 | 222 | 38 | 28 | Olalaye/MegEngine | imperative/python/test/unit/jit/test_tracing.py | Python | test_dump | test_dump | 193 | 221 | 193 | 200 | 4d5bb83ce9734c4dd797dfdb64ab9244d00cfdf5 | bigcode/the-stack | train |
0f2cd6024ca5c9d48587afad | train | function | def test_optimize_for_inference_broadcast():
a = tensor(np.ones(1, dtype=np.float32))
@trace(capture_as_const=True, symbolic_shape=True)
def f():
return a._broadcast(tensor([1, 10], dtype=np.int32))
f()
f.dump(io.BytesIO())
| def test_optimize_for_inference_broadcast():
| a = tensor(np.ones(1, dtype=np.float32))
@trace(capture_as_const=True, symbolic_shape=True)
def f():
return a._broadcast(tensor([1, 10], dtype=np.int32))
f()
f.dump(io.BytesIO())
| f(tensor(5.0))
f.dump(out, enable_io16xc32=True)
res = G.load_graph(out)
computing_input = res.output_vars_list[0].owner.inputs[0]
assert computing_input.dtype == np.float16
def test_optimize_for_inference_broadcast():
| 64 | 64 | 69 | 10 | 53 | Olalaye/MegEngine | imperative/python/test/unit/jit/test_tracing.py | Python | test_optimize_for_inference_broadcast | test_optimize_for_inference_broadcast | 393 | 401 | 393 | 393 | 3a5cb00488cfe26df862b63ed51afb81bc39f205 | bigcode/the-stack | train |
cd5c5477b15ac32a0d460ba7 | train | function | @pytest.mark.parametrize("trace_mode", [False, True])
def test_exclude_from_trace(trace_mode):
@trace(symbolic=trace_mode)
def f(x):
x = -x
with exclude_from_trace():
if i % 2:
x = -x
x = -x
return x
x = tensor([1])
for i in range(3):
... | @pytest.mark.parametrize("trace_mode", [False, True])
def test_exclude_from_trace(trace_mode):
@trace(symbolic=trace_mode)
| def f(x):
x = -x
with exclude_from_trace():
if i % 2:
x = -x
x = -x
return x
x = tensor([1])
for i in range(3):
y = f(x).numpy()
np.testing.assert_equal(f(x).numpy(), y)
| return z.detach()
x = tensor([1, 2, 3, 4])
for _ in range(3):
f(x).numpy()
@pytest.mark.parametrize("trace_mode", [False, True])
def test_exclude_from_trace(trace_mode):
@trace(symbolic=trace_mode)
| 64 | 64 | 105 | 30 | 34 | Olalaye/MegEngine | imperative/python/test/unit/jit/test_tracing.py | Python | test_exclude_from_trace | test_exclude_from_trace | 111 | 126 | 111 | 113 | 5cae337ec18780f3f60ab68bcc50d5d529250ae1 | bigcode/the-stack | train |
743aae3953082fa5a049b4c0 | train | function | def test_dump_volatile():
p = tensor([2])
@trace(symbolic=True, capture_as_const=True)
def f(x):
return x * p
x = tensor([3])
y = f(x).numpy()
for i in range(3):
np.testing.assert_equal(f(x).numpy(), y)
file = io.BytesIO()
f.dump(file, optimize_for_inference=False)
... | def test_dump_volatile():
| p = tensor([2])
@trace(symbolic=True, capture_as_const=True)
def f(x):
return x * p
x = tensor([3])
y = f(x).numpy()
for i in range(3):
np.testing.assert_equal(f(x).numpy(), y)
file = io.BytesIO()
f.dump(file, optimize_for_inference=False)
file.seek(0)
(out,) ... | (), y)
file = io.BytesIO()
f.dump(file)
file.seek(0)
infer_cg = cgtools.GraphInference(file)
result = list((infer_cg.run(x)).values())[0]
np.testing.assert_equal(result[0], y)
def test_dump_volatile():
| 64 | 64 | 140 | 6 | 58 | Olalaye/MegEngine | imperative/python/test/unit/jit/test_tracing.py | Python | test_dump_volatile | test_dump_volatile | 245 | 265 | 245 | 245 | 25a321bcce68dd04b22038a8f8fe3e71e14dc462 | bigcode/the-stack | train |
ef011eb23145fe4cb2a2cb53 | train | class | class IQNAgent(BaseAgent):
def __init__(self, env, test_env, log_dir, num_steps=5*(10**7),
batch_size=32, N=64, N_dash=64, K=32, num_cosines=64,
kappa=1.0, lr=5e-5, memory_size=10**6, gamma=0.99,
multi_step=1, update_interval=4, target_update_interval=10000,
... | class IQNAgent(BaseAgent):
| def __init__(self, env, test_env, log_dir, num_steps=5*(10**7),
batch_size=32, N=64, N_dash=64, K=32, num_cosines=64,
kappa=1.0, lr=5e-5, memory_size=10**6, gamma=0.99,
multi_step=1, update_interval=4, target_update_interval=10000,
start_steps=5000... | _size = states.shape[0]
action = torch.unsqueeze(action, dim=1).repeat(1, 64, 1)
action= action.reshape(batch_size * 64, *action.shape[2:])
states = torch.unsqueeze(states, dim=1).repeat(1, 64, 1, 1, 1)
states = states.reshape(batch_size * 64, *states.shape[2:])
state_embeddings ... | 256 | 256 | 1,948 | 7 | 248 | robinzixuan/IQN_Agent | fqf_iqn_qrdqn/agent/iqn_agent.py | Python | IQNAgent | IQNAgent | 64 | 245 | 64 | 64 | bf288631d16a22eccdd8917cb138c5f4d6ffa5cb | bigcode/the-stack | train |
fd879f1e4febc20a69f79362 | train | class | class Discriminator(nn.Module):
def __init__(self, num_channels, n):
super(Discriminator, self).__init__()
self.dqn_net = DQNBase(num_channels=num_channels)
self.model2 = nn.Sequential(
nn.Linear(1,64),
nn.LeakyReLU(),
nn.Linear(64,128),
nn.ReL... | class Discriminator(nn.Module):
| def __init__(self, num_channels, n):
super(Discriminator, self).__init__()
self.dqn_net = DQNBase(num_channels=num_channels)
self.model2 = nn.Sequential(
nn.Linear(1,64),
nn.LeakyReLU(),
nn.Linear(64,128),
nn.ReLU())
self.model1 = nn.Se... | import torch
from torch.optim import Adam
import torch.nn as nn
import numpy as np
from fqf_iqn_qrdqn.model import IQN
from fqf_iqn_qrdqn.utils import calculate_quantile_huber_loss, disable_gradients, evaluate_quantile_at_action, update_params
from .base_agent import BaseAgent
import torch.optim as optim
from torch... | 110 | 131 | 438 | 6 | 103 | robinzixuan/IQN_Agent | fqf_iqn_qrdqn/agent/iqn_agent.py | Python | Discriminator | Discriminator | 18 | 61 | 18 | 18 | d6df5b1f1cb401fabe51829e9576bb9c09592ac1 | bigcode/the-stack | train |
a040e7b27be6124a5d273b88 | train | function | def iterate_with_template_sources(
frames,
with_locals=True,
library_frame_context_lines=None,
in_app_frame_context_lines=None,
include_paths_re=None,
exclude_paths_re=None,
locals_processor_func=None,
):
template = None
for frame, lineno in frames:
f_code = getattr(frame, "f... | def iterate_with_template_sources(
frames,
with_locals=True,
library_frame_context_lines=None,
in_app_frame_context_lines=None,
include_paths_re=None,
exclude_paths_re=None,
locals_processor_func=None,
):
| template = None
for frame, lineno in frames:
f_code = getattr(frame, "f_code", None)
if f_code:
function_name = frame.f_code.co_name
if function_name == "render":
renderer = getattr(frame, "f_locals", {}).get("self")
if renderer and isinsta... | from django.template.base import Node
from elasticapm.utils.stacks import get_frame_info
try:
from django.template.base import Template
except ImportError:
class Template(object):
pass
def iterate_with_template_sources(
frames,
with_locals=True,
library_frame_context_lines=None,
in_ap... | 90 | 103 | 344 | 49 | 40 | lyrixderaven/apm-agent-python | elasticapm/contrib/django/utils.py | Python | iterate_with_template_sources | iterate_with_template_sources | 13 | 54 | 13 | 21 | 30cfabe16f3b2f4e6c239f8723d600321c72cc79 | bigcode/the-stack | train |
4917c9e10e2fcfe7625024b5 | train | function | def test_RunIDSeqDedup_safe_csv(util, short_read_mngs_bench3_viral_outputs):
# load the task's inputs from the end-to-end workflow test
inputs, _ = util.miniwdl_inputs_outputs(
os.path.join(
short_read_mngs_bench3_viral_outputs["dir"], "call-host_filter/call-RunIDSeqDedup"
)
)
... | def test_RunIDSeqDedup_safe_csv(util, short_read_mngs_bench3_viral_outputs):
# load the task's inputs from the end-to-end workflow test
| inputs, _ = util.miniwdl_inputs_outputs(
os.path.join(
short_read_mngs_bench3_viral_outputs["dir"], "call-host_filter/call-RunIDSeqDedup"
)
)
with NamedTemporaryFile(prefix=os.path.dirname(__file__), mode="w") as input_file:
quote_count = 10
special_char_rows = 0... | import os
import csv
import json
from tempfile import NamedTemporaryFile
def test_RunIDSeqDedup_safe_csv(util, short_read_mngs_bench3_viral_outputs):
# load the task's inputs from the end-to-end workflow test
| 54 | 124 | 415 | 38 | 15 | chanzuckerberg/idseq-workflows | short-read-mngs/test/host_filter/test_RunIDSeqDedup.py | Python | test_RunIDSeqDedup_safe_csv | test_RunIDSeqDedup_safe_csv | 7 | 53 | 7 | 8 | 3f5c2a6b9423752889840f60c723215a5de24892 | bigcode/the-stack | train |
36078418d07be7d4c10ae5ef | train | class | class time_to_close(object):
def __init__(self,
config=None,
requestTypes=None,
tableName="ingest_staging_table"):
"""
Choose table from database by setting the value of tableName.
Default table is the staging table.
"""
self... | class time_to_close(object):
| def __init__(self,
config=None,
requestTypes=None,
tableName="ingest_staging_table"):
"""
Choose table from database by setting the value of tableName.
Default table is the staging table.
"""
self.config = config
self... | from configparser import ConfigParser
import sqlalchemy as db
import pandas as pd
import json
class time_to_close(object):
| 26 | 256 | 1,089 | 6 | 19 | JRHutson/311-data | server/src/services/time_to_close.py | Python | time_to_close | time_to_close | 7 | 166 | 7 | 7 | ab6a98edf0fc6655e84e2f9c731f86d24454d19c | bigcode/the-stack | train |
a1f98ebf432617786c620320 | train | function | @flaky(max_runs=5)
@pytest.mark.parametrize(
"lib", [('str', 'class str', 1),
('numpy.compat', 'numpy.compat', 2)
])
@pytest.mark.skipif(
sys.platform == 'darwin', reason="Does not work on Mac")
def test_get_pydoc(pydocbrowser, lib):
"""
Go to the documentation by url.
Regres... | @flaky(max_runs=5)
@pytest.mark.parametrize(
"lib", [('str', 'class str', 1),
('numpy.compat', 'numpy.compat', 2)
])
@pytest.mark.skipif(
sys.platform == 'darwin', reason="Does not work on Mac")
def test_get_pydoc(pydocbrowser, lib):
| """
Go to the documentation by url.
Regression test for spyder-ide/spyder#10740
"""
qtbot, browser = pydocbrowser
element, doc, matches = lib
webview = browser.webview
element_url = browser.text_to_url(element)
with qtbot.waitSignal(webview.loadFinished):
browser.set_url(ele... | @flaky(max_runs=5)
@pytest.mark.parametrize(
"lib", [('str', 'class str', 1),
('numpy.compat', 'numpy.compat', 2)
])
@pytest.mark.skipif(
sys.platform == 'darwin', reason="Does not work on Mac")
def test_get_pydoc(pydocbrowser, lib):
| 74 | 64 | 208 | 74 | 0 | feiser2016/spyder | spyder/plugins/onlinehelp/tests/test_pydocgui.py | Python | test_get_pydoc | test_get_pydoc | 41 | 64 | 41 | 48 | 041dbb8b575602d61d3863e70b45f13dbdb5d4a8 | bigcode/the-stack | train |
0d1cdf488a479592603995f9 | train | function | @pytest.fixture
def pydocbrowser(qtbot):
"""Set up pydocbrowser."""
widget = PydocBrowser(parent=None, name='pydoc')
options = PydocBrowser.DEFAULT_OPTIONS.copy()
widget._setup(options)
with qtbot.waitSignal(widget.sig_load_finished, timeout=6000):
widget.setup(options)
qtbot.addWidget... | @pytest.fixture
def pydocbrowser(qtbot):
| """Set up pydocbrowser."""
widget = PydocBrowser(parent=None, name='pydoc')
options = PydocBrowser.DEFAULT_OPTIONS.copy()
widget._setup(options)
with qtbot.waitSignal(widget.sig_load_finished, timeout=6000):
widget.setup(options)
qtbot.addWidget(widget)
return qtbot, widget
| MIT License
#
"""
Tests for pydocgui.py
"""
# Standard library imports
import sys
# Test library imports
import pytest
from flaky import flaky
# Local imports
from spyder.plugins.onlinehelp.widgets import PydocBrowser
@pytest.fixture
def pydocbrowser(qtbot):
| 64 | 64 | 89 | 12 | 51 | feiser2016/spyder | spyder/plugins/onlinehelp/tests/test_pydocgui.py | Python | pydocbrowser | pydocbrowser | 21 | 32 | 21 | 22 | d214938ed7af2618e18a64d3ff28c7261e6e4952 | bigcode/the-stack | train |
2b4f512e488fdef26a6a460a | train | function | def test_pydocbrowser(pydocbrowser):
"""Run Pydoc Browser."""
qtbot, browser = pydocbrowser
assert browser
| def test_pydocbrowser(pydocbrowser):
| """Run Pydoc Browser."""
qtbot, browser = pydocbrowser
assert browser
| ')
options = PydocBrowser.DEFAULT_OPTIONS.copy()
widget._setup(options)
with qtbot.waitSignal(widget.sig_load_finished, timeout=6000):
widget.setup(options)
qtbot.addWidget(widget)
return qtbot, widget
def test_pydocbrowser(pydocbrowser):
| 64 | 64 | 34 | 11 | 52 | feiser2016/spyder | spyder/plugins/onlinehelp/tests/test_pydocgui.py | Python | test_pydocbrowser | test_pydocbrowser | 35 | 38 | 35 | 35 | d186dc8820ae2e90ccb54c34b69bed0ffb79fe02 | bigcode/the-stack | train |
18fa0f5df6164e14e601100a | train | function | def _get_counts(
values_shape: Tuple[int, ...],
mask: Optional[np.ndarray],
axis: Optional[int],
dtype: Dtype = float,
) -> Union[int, float, np.ndarray]:
"""
Get the count of non-null values along an axis
Parameters
----------
values_shape : tuple of int
shape tuple from va... | def _get_counts(
values_shape: Tuple[int, ...],
mask: Optional[np.ndarray],
axis: Optional[int],
dtype: Dtype = float,
) -> Union[int, float, np.ndarray]:
| """
Get the count of non-null values along an axis
Parameters
----------
values_shape : tuple of int
shape tuple from values ndarray, used if mask is None
mask : Optional[ndarray[bool]]
locations in values that should be considered missing
axis : Optional[int]
axis t... | # "int", variable has type "ndarray")
result = -1 # type: ignore[assignment]
else:
if mask.any():
# error: Incompatible types in assignment (expression has type
# "int", variable has type "ndarray")
result = -1 # type: ignore[assignm... | 163 | 163 | 544 | 45 | 117 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | _get_counts | _get_counts | 1,376 | 1,432 | 1,376 | 1,381 | e0edd2120c6c6a6dd361e7591181f187a5ff2f60 | bigcode/the-stack | train |
9ec51be505abcf8de5916707 | train | function | @disallow(PeriodDtype)
@bottleneck_switch()
@_datetimelike_compat
def nanmean(
values: np.ndarray,
*,
axis: Optional[int] = None,
skipna: bool = True,
mask: Optional[np.ndarray] = None,
) -> float:
"""
Compute the mean of the element along an axis ignoring NaNs
Parameters
----------... | @disallow(PeriodDtype)
@bottleneck_switch()
@_datetimelike_compat
def nanmean(
values: np.ndarray,
*,
axis: Optional[int] = None,
skipna: bool = True,
mask: Optional[np.ndarray] = None,
) -> float:
| """
Compute the mean of the element along an axis ignoring NaNs
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
float
Unless input is a float array, in wh... | Type]:
if isinstance(result, np.ndarray):
# we need to apply the mask
result = result.astype("i8").view(orig_values.dtype)
axis_mask = mask.any(axis=axis)
result[axis_mask] = iNaT
else:
if mask.any():
return NaT
return result
@disallow(PeriodDtype)
@bottle... | 137 | 137 | 458 | 66 | 70 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | nanmean | nanmean | 614 | 677 | 614 | 623 | 7e14753c1fe8e427e6fada587fcc2eaf88746339 | bigcode/the-stack | train |
65051dd03f4a8050896e2cb3 | train | function | @bottleneck_switch()
def nanmedian(values, *, axis=None, skipna=True, mask=None):
"""
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : float
Unless inp... | @bottleneck_switch()
def nanmedian(values, *, axis=None, skipna=True, mask=None):
| """
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : float
Unless input is a float array, in which case use the same
precision as the input arr... | dtype_sum = dtype
dtype_count = dtype
count = _get_counts(values.shape, mask, axis, dtype=dtype_count)
the_sum = _ensure_numeric(values.sum(axis, dtype=dtype_sum))
if axis is not None and getattr(the_sum, "ndim", False):
count = cast(np.ndarray, count)
with np.errstate(all="ignore... | 170 | 170 | 569 | 22 | 147 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | nanmedian | nanmedian | 680 | 755 | 680 | 681 | d5525df5aea32e76fdb2872d87993da9601ba975 | bigcode/the-stack | train |
74e9525abc974db734e70799 | train | function | @disallow("M8", "m8")
def nankurt(
values: np.ndarray,
*,
axis: Optional[int] = None,
skipna: bool = True,
mask: Optional[np.ndarray] = None,
) -> float:
"""
Compute the sample excess kurtosis
The statistic computed here is the adjusted Fisher-Pearson standardized
moment coefficient... | @disallow("M8", "m8")
def nankurt(
values: np.ndarray,
*,
axis: Optional[int] = None,
skipna: bool = True,
mask: Optional[np.ndarray] = None,
) -> float:
| """
Compute the sample excess kurtosis
The statistic computed here is the adjusted Fisher-Pearson standardized
moment coefficient G2, computed directly from the second and fourth
central moment.
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default T... | fperr to treat m2 <1e-14 as zero
m2 = _zero_out_fperr(m2)
m3 = _zero_out_fperr(m3)
with np.errstate(invalid="ignore", divide="ignore"):
result = (count * (count - 1) ** 0.5 / (count - 2)) * (m3 / m2 ** 1.5)
dtype = values.dtype
if is_float_dtype(dtype):
result = result.astype(dtyp... | 235 | 235 | 785 | 55 | 179 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | nankurt | nankurt | 1,206 | 1,299 | 1,206 | 1,213 | 384dd4eb4a8764dcb6827d23c741ed6b36c8064b | bigcode/the-stack | train |
682e731334e3043fba246ac3 | train | function | def _get_values(
values: np.ndarray,
skipna: bool,
fill_value: Any = None,
fill_value_typ: Optional[str] = None,
mask: Optional[np.ndarray] = None,
) -> Tuple[np.ndarray, Optional[np.ndarray], np.dtype, np.dtype, Any]:
"""
Utility to get the values view, mask, dtype, dtype_max, and fill_valu... | def _get_values(
values: np.ndarray,
skipna: bool,
fill_value: Any = None,
fill_value_typ: Optional[str] = None,
mask: Optional[np.ndarray] = None,
) -> Tuple[np.ndarray, Optional[np.ndarray], np.dtype, np.dtype, Any]:
| """
Utility to get the values view, mask, dtype, dtype_max, and fill_value.
If both mask and fill_value/fill_value_typ are not None and skipna is True,
the values array will be copied.
For input arrays of boolean or integer dtypes, copies will only occur if a
precomputed mask, a fill_value/fil... | using isna() by default. Setting invert=True selects
notna() as the masking function.
Parameters
----------
values : ndarray
input array to potentially compute mask for
skipna : bool
boolean for whether NaNs should be skipped
mask : Optional[ndarray]
nan-mask if known
... | 210 | 210 | 703 | 64 | 145 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | _get_values | _get_values | 260 | 346 | 260 | 266 | 71e6df659a4cebf87aad95c6c6fe134d046779d8 | bigcode/the-stack | train |
d97f10b4a95c1ce08b5d25a6 | train | function | def _wrap_results(result, dtype: np.dtype, fill_value=None):
""" wrap our results if needed """
if result is NaT:
pass
elif is_datetime64_any_dtype(dtype):
if fill_value is None:
# GH#24293
fill_value = iNaT
if not isinstance(result, np.ndarray):
... | def _wrap_results(result, dtype: np.dtype, fill_value=None):
| """ wrap our results if needed """
if result is NaT:
pass
elif is_datetime64_any_dtype(dtype):
if fill_value is None:
# GH#24293
fill_value = iNaT
if not isinstance(result, np.ndarray):
assert not isna(fill_value), "Expected non-null fill_value"
... | _float_dtype(dtype):
dtype_max = np.dtype(np.float64)
return values, mask, dtype, dtype_max, fill_value
def _na_ok_dtype(dtype: DtypeObj) -> bool:
if needs_i8_conversion(dtype):
return False
return not issubclass(dtype.type, np.integer)
def _wrap_results(result, dtype: np.dtype, fill_valu... | 81 | 81 | 273 | 15 | 66 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | _wrap_results | _wrap_results | 355 | 389 | 355 | 355 | 1e8d9ae1c1773449b329288230d2b36962324b40 | bigcode/the-stack | train |
54f56f4ddbe2806c584fcd94 | train | function | @disallow("M8", "m8")
def nanskew(
values: np.ndarray,
*,
axis: Optional[int] = None,
skipna: bool = True,
mask: Optional[np.ndarray] = None,
) -> float:
"""
Compute the sample skewness.
The statistic computed here is the adjusted Fisher-Pearson standardized
moment coefficient G1. T... | @disallow("M8", "m8")
def nanskew(
values: np.ndarray,
*,
axis: Optional[int] = None,
skipna: bool = True,
mask: Optional[np.ndarray] = None,
) -> float:
| """
Compute the sample skewness.
The statistic computed here is the adjusted Fisher-Pearson standardized
moment coefficient G1. The algorithm computes this coefficient directly
from the second and third central moment.
Parameters
----------
values : ndarray
axis: int, optional
... | ., 2.],
[ 3., 4., 5.],
[nan, 7., 8.],
[nan, 10., 11.]])
>>> nanops.nanargmin(arr, axis=1)
array([0, 0, 1, 1], dtype=int64)
"""
values, mask, _, _, _ = _get_values(values, True, fill_value_typ="+inf", mask=mask)
# error: Need type annotation for 'result'
resu... | 208 | 208 | 696 | 55 | 152 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | nanskew | nanskew | 1,119 | 1,203 | 1,119 | 1,126 | b0a419d1978f32fc37a534820dac56a10fd24b8b | bigcode/the-stack | train |
3e795846c57b5b7b16fddcc2 | train | function | def _nanpercentile_1d(
values: np.ndarray, mask: np.ndarray, q: np.ndarray, na_value: Scalar, interpolation
) -> Union[Scalar, np.ndarray]:
"""
Wrapper for np.percentile that skips missing values, specialized to
1-dimensional case.
Parameters
----------
values : array over which to find qua... | def _nanpercentile_1d(
values: np.ndarray, mask: np.ndarray, q: np.ndarray, na_value: Scalar, interpolation
) -> Union[Scalar, np.ndarray]:
| """
Wrapper for np.percentile that skips missing values, specialized to
1-dimensional case.
Parameters
----------
values : array over which to find quantiles
mask : ndarray[bool]
locations in values that should be considered missing
q : np.ndarray[float64] of quantile indices to... | _nancomp(operator.le)
naneq = make_nancomp(operator.eq)
nanne = make_nancomp(operator.ne)
def _nanpercentile_1d(
values: np.ndarray, mask: np.ndarray, q: np.ndarray, na_value: Scalar, interpolation
) -> Union[Scalar, np.ndarray]:
| 64 | 64 | 208 | 41 | 23 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | _nanpercentile_1d | _nanpercentile_1d | 1,646 | 1,673 | 1,646 | 1,648 | 31378acac1436ba6ce67aadaa9f9960da047d92e | bigcode/the-stack | train |
d89136fbce47f50934327e76 | train | function | def _ensure_numeric(x):
if isinstance(x, np.ndarray):
if is_integer_dtype(x) or is_bool_dtype(x):
x = x.astype(np.float64)
elif is_object_dtype(x):
try:
x = x.astype(np.complex128)
except (TypeError, ValueError):
try:
... | def _ensure_numeric(x):
| if isinstance(x, np.ndarray):
if is_integer_dtype(x) or is_bool_dtype(x):
x = x.astype(np.float64)
elif is_object_dtype(x):
try:
x = x.astype(np.complex128)
except (TypeError, ValueError):
try:
x = x.astype(np.fl... | (a) & notna(b)
if not valid.all():
a = a[valid]
b = b[valid]
if len(a) < min_periods:
return np.nan
return np.cov(a, b, ddof=ddof)[0, 1]
def _ensure_numeric(x):
| 68 | 68 | 228 | 6 | 62 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | _ensure_numeric | _ensure_numeric | 1,587 | 1,613 | 1,587 | 1,587 | 847b60e0b17cc6600972e1d2080159714608ac8e | bigcode/the-stack | train |
e5a615c51d3aec13dc4c87e0 | train | function | def _maybe_null_out(
result: np.ndarray | float | NaTType,
axis: Optional[int],
mask: Optional[np.ndarray],
shape: Tuple[int, ...],
min_count: int = 1,
) -> np.ndarray | float | NaTType:
"""
Returns
-------
Dtype
The product of all elements on a given axis. ( NaNs are treated... | def _maybe_null_out(
result: np.ndarray | float | NaTType,
axis: Optional[int],
mask: Optional[np.ndarray],
shape: Tuple[int, ...],
min_count: int = 1,
) -> np.ndarray | float | NaTType:
| """
Returns
-------
Dtype
The product of all elements on a given axis. ( NaNs are treated as 1)
"""
if mask is not None and axis is not None and isinstance(result, np.ndarray):
null_mask = (mask.shape[axis] - mask.sum(axis) - min_count) < 0
if np.any(null_mask):
... | , dtype=dtype) # type: ignore[arg-type]
def _maybe_null_out(
result: np.ndarray | float | NaTType,
axis: Optional[int],
mask: Optional[np.ndarray],
shape: Tuple[int, ...],
min_count: int = 1,
) -> np.ndarray | float | NaTType:
| 72 | 72 | 243 | 59 | 13 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | _maybe_null_out | _maybe_null_out | 1,435 | 1,464 | 1,435 | 1,441 | db0154fff58748c2d36294626f532434e40c5f7e | bigcode/the-stack | train |
c082a17a745214b7ce71aa1f | train | function | def set_use_bottleneck(v: bool = True) -> None:
# set/unset to use bottleneck
global _USE_BOTTLENECK
if _BOTTLENECK_INSTALLED:
_USE_BOTTLENECK = v
| def set_use_bottleneck(v: bool = True) -> None:
# set/unset to use bottleneck
| global _USE_BOTTLENECK
if _BOTTLENECK_INSTALLED:
_USE_BOTTLENECK = v
| extract_array
bn = import_optional_dependency("bottleneck", errors="warn")
_BOTTLENECK_INSTALLED = bn is not None
_USE_BOTTLENECK = False
def set_use_bottleneck(v: bool = True) -> None:
# set/unset to use bottleneck
| 64 | 64 | 56 | 25 | 38 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | set_use_bottleneck | set_use_bottleneck | 67 | 71 | 67 | 68 | 59e5efeeeea0c133838606dfc0eca1c14e95f930 | bigcode/the-stack | train |
0d44dd92db3f1960fbcacdda | train | class | class bottleneck_switch:
def __init__(self, name=None, **kwargs):
self.name = name
self.kwargs = kwargs
def __call__(self, alt: F) -> F:
bn_name = self.name or alt.__name__
try:
bn_func = getattr(bn, bn_name)
except (AttributeError, NameError): # pragma: no... | class bottleneck_switch:
| def __init__(self, name=None, **kwargs):
self.name = name
self.kwargs = kwargs
def __call__(self, alt: F) -> F:
bn_name = self.name or alt.__name__
try:
bn_func = getattr(bn, bn_name)
except (AttributeError, NameError): # pragma: no cover
bn_fun... | _name = f.__name__.replace("nan", "")
raise TypeError(
f"reduction operation '{f_name}' not allowed for this dtype"
)
try:
with np.errstate(invalid="ignore"):
return f(*args, **kwargs)
except ValueError as e:... | 141 | 141 | 471 | 5 | 136 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | bottleneck_switch | bottleneck_switch | 109 | 162 | 109 | 109 | 611f93d69ec6b3fd20b123f3d2fa760c5b10ccf6 | bigcode/the-stack | train |
124e34aba1e5f1006f1501e2 | train | function | def nanall(
values: np.ndarray,
*,
axis: Optional[int] = None,
skipna: bool = True,
mask: Optional[np.ndarray] = None,
) -> bool:
"""
Check if all elements along an axis evaluate to True.
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default T... | def nanall(
values: np.ndarray,
*,
axis: Optional[int] = None,
skipna: bool = True,
mask: Optional[np.ndarray] = None,
) -> bool:
| """
Check if all elements along an axis evaluate to True.
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : bool
Examples
--------
>>> import ... | type (got "Union[bool_, ndarray]", expected
# "bool")
return values.any(axis) # type: ignore[return-value]
def nanall(
values: np.ndarray,
*,
axis: Optional[int] = None,
skipna: bool = True,
mask: Optional[np.ndarray] = None,
) -> bool:
| 75 | 75 | 251 | 43 | 32 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | nanall | nanall | 499 | 536 | 499 | 505 | 8495d88cb9ca7ba1e524446f6248a108d22cf232 | bigcode/the-stack | train |
860bc2f60134121bfafa9a79 | train | function | @disallow("M8", "m8")
def nancov(
a: np.ndarray,
b: np.ndarray,
*,
min_periods: Optional[int] = None,
ddof: Optional[int] = 1,
):
if len(a) != len(b):
raise AssertionError("Operands to nancov must have same size")
if min_periods is None:
min_periods = 1
valid = notna(a)... | @disallow("M8", "m8")
def nancov(
a: np.ndarray,
b: np.ndarray,
*,
min_periods: Optional[int] = None,
ddof: Optional[int] = 1,
):
| if len(a) != len(b):
raise AssertionError("Operands to nancov must have same size")
if min_periods is None:
min_periods = 1
valid = notna(a) & notna(b)
if not valid.all():
a = a[valid]
b = b[valid]
if len(a) < min_periods:
return np.nan
return np.cov(a... | arman', 'pearson', or callable"
)
@disallow("M8", "m8")
def nancov(
a: np.ndarray,
b: np.ndarray,
*,
min_periods: Optional[int] = None,
ddof: Optional[int] = 1,
):
| 64 | 64 | 160 | 53 | 11 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | nancov | nancov | 1,562 | 1,584 | 1,562 | 1,569 | 4423557504d05055bb2d33a10eb772f734c568ca | bigcode/the-stack | train |
d145a3dabff9ffbb91a2d23d | train | function | def check_below_min_count(
shape: Tuple[int, ...], mask: Optional[np.ndarray], min_count: int
) -> bool:
"""
Check for the `min_count` keyword. Returns True if below `min_count` (when
missing value should be returned from the reduction).
Parameters
----------
shape : tuple
The shape... | def check_below_min_count(
shape: Tuple[int, ...], mask: Optional[np.ndarray], min_count: int
) -> bool:
| """
Check for the `min_count` keyword. Returns True if below `min_count` (when
missing value should be returned from the reduction).
Parameters
----------
shape : tuple
The shape of the values (`values.shape`).
mask : ndarray or None
Boolean numpy array (typically of same sh... | None
elif result is not NaT:
if check_below_min_count(shape, mask, min_count):
result = np.nan
return result
def check_below_min_count(
shape: Tuple[int, ...], mask: Optional[np.ndarray], min_count: int
) -> bool:
| 64 | 64 | 197 | 30 | 33 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | check_below_min_count | check_below_min_count | 1,467 | 1,495 | 1,467 | 1,469 | cbdf3bc8e53ab2503708fdb87a020018a2daece5 | bigcode/the-stack | train |
7fb0d256ba855133038f9aeb | train | function | def get_corr_func(method):
if method == "kendall":
from scipy.stats import kendalltau
def func(a, b):
return kendalltau(a, b)[0]
return func
elif method == "spearman":
from scipy.stats import spearmanr
def func(a, b):
return spearmanr(a, b)[0]
... | def get_corr_func(method):
| if method == "kendall":
from scipy.stats import kendalltau
def func(a, b):
return kendalltau(a, b)[0]
return func
elif method == "spearman":
from scipy.stats import spearmanr
def func(a, b):
return spearmanr(a, b)[0]
return func
eli... | na(a) & notna(b)
if not valid.all():
a = a[valid]
b = b[valid]
if len(a) < min_periods:
return np.nan
f = get_corr_func(method)
return f(a, b)
def get_corr_func(method):
| 64 | 64 | 162 | 6 | 58 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | get_corr_func | get_corr_func | 1,532 | 1,559 | 1,532 | 1,532 | 546fb22f9c8821905c05845bdcb4afe74126a083 | bigcode/the-stack | train |
c5120b9ff2c36b3b386b27e9 | train | function | @disallow("M8")
@_datetimelike_compat
def nansum(
values: np.ndarray,
*,
axis: Optional[int] = None,
skipna: bool = True,
min_count: int = 0,
mask: Optional[np.ndarray] = None,
) -> float:
"""
Sum the elements along an axis ignoring NaNs
Parameters
----------
values : ndarra... | @disallow("M8")
@_datetimelike_compat
def nansum(
values: np.ndarray,
*,
axis: Optional[int] = None,
skipna: bool = True,
min_count: int = 0,
mask: Optional[np.ndarray] = None,
) -> float:
| """
Sum the elements along an axis ignoring NaNs
Parameters
----------
values : ndarray[dtype]
axis: int, optional
skipna : bool, default True
min_count: int, default 0
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : dtype
Examples... | """
values, _, _, _, _ = _get_values(values, skipna, fill_value=True, mask=mask)
# error: Incompatible return value type (got "Union[bool_, ndarray]", expected
# "bool")
return values.all(axis) # type: ignore[return-value]
@disallow("M8")
@_datetimelike_compat
def nansum(
values: np.ndarray,
*... | 134 | 134 | 449 | 69 | 65 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | nansum | nansum | 539 | 594 | 539 | 548 | 4c40dd9ddeb879cd342c36cc20d3a85bbaabd020 | bigcode/the-stack | train |
7207ccf7ca4584e0192e45da | train | function | def _has_infs(result) -> bool:
if isinstance(result, np.ndarray):
if result.dtype == "f8":
return lib.has_infs_f8(result.ravel("K"))
elif result.dtype == "f4":
return lib.has_infs_f4(result.ravel("K"))
try:
return np.isinf(result).any()
except (TypeError, NotI... | def _has_infs(result) -> bool:
| if isinstance(result, np.ndarray):
if result.dtype == "f8":
return lib.has_infs_f8(result.ravel("K"))
elif result.dtype == "f4":
return lib.has_infs_f4(result.ravel("K"))
try:
return np.isinf(result).any()
except (TypeError, NotImplementedError):
# if ... | # further we also want to preserve NaN when all elements
# are NaN, unlike bottleneck/numpy which consider this
# to be 0
return name not in ["nansum", "nanprod"]
return False
def _has_infs(result) -> bool:
| 64 | 64 | 106 | 10 | 53 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | _has_infs | _has_infs | 181 | 191 | 181 | 181 | c18f4c2bc03a5a80bfef07d2c21b5c18cb9e7040 | bigcode/the-stack | train |
c2796ec67a7fc2ccd14e6219 | train | function | def _na_for_min_count(
values: np.ndarray, axis: Optional[int]
) -> Union[Scalar, np.ndarray]:
"""
Return the missing value for `values`.
Parameters
----------
values : ndarray
axis : int or None
axis for the reduction, required if values.ndim > 1.
Returns
-------
resul... | def _na_for_min_count(
values: np.ndarray, axis: Optional[int]
) -> Union[Scalar, np.ndarray]:
| """
Return the missing value for `values`.
Parameters
----------
values : ndarray
axis : int or None
axis for the reduction, required if values.ndim > 1.
Returns
-------
result : scalar or ndarray
For 1-D values, returns a scalar of the correct missing type.
... | is not None # checked above
result = _mask_datetimelike_result(result, axis, mask, orig_values)
return result
return cast(F, new_func)
def _na_for_min_count(
values: np.ndarray, axis: Optional[int]
) -> Union[Scalar, np.ndarray]:
| 66 | 66 | 220 | 27 | 39 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | _na_for_min_count | _na_for_min_count | 426 | 456 | 426 | 428 | 82d36194d3e31ed79c1ea87ba778670b79d253ba | bigcode/the-stack | train |
c5dc3d12ac110610c239237c | train | function | def _zero_out_fperr(arg):
# #18044 reference this behavior to fix rolling skew/kurt issue
if isinstance(arg, np.ndarray):
with np.errstate(invalid="ignore"):
return np.where(np.abs(arg) < 1e-14, 0, arg)
else:
return arg.dtype.type(0) if np.abs(arg) < 1e-14 else arg
| def _zero_out_fperr(arg):
# #18044 reference this behavior to fix rolling skew/kurt issue
| if isinstance(arg, np.ndarray):
with np.errstate(invalid="ignore"):
return np.where(np.abs(arg) < 1e-14, 0, arg)
else:
return arg.dtype.type(0) if np.abs(arg) < 1e-14 else arg
| non_nulls = np.prod(shape)
else:
non_nulls = mask.size - mask.sum()
if non_nulls < min_count:
return True
return False
def _zero_out_fperr(arg):
# #18044 reference this behavior to fix rolling skew/kurt issue
| 64 | 64 | 88 | 25 | 38 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | _zero_out_fperr | _zero_out_fperr | 1,498 | 1,504 | 1,498 | 1,499 | 66aff8c61cee70b82a3f7bfbb59890eb9df71e88 | bigcode/the-stack | train |
2048234e50b72ee393632558 | train | function | def make_nancomp(op):
def f(x, y):
xmask = isna(x)
ymask = isna(y)
mask = xmask | ymask
with np.errstate(all="ignore"):
result = op(x, y)
if mask.any():
if is_bool_dtype(result):
result = result.astype("O")
np.putmask(resu... | def make_nancomp(op):
| def f(x, y):
xmask = isna(x)
ymask = isna(y)
mask = xmask | ymask
with np.errstate(all="ignore"):
result = op(x, y)
if mask.any():
if is_bool_dtype(result):
result = result.astype("O")
np.putmask(result, mask, np.nan)
... | j" or "foo"
try:
x = complex(x)
except ValueError as err:
# e.g. "foo"
raise TypeError(f"Could not convert {x} to numeric") from err
return x
# NA-friendly array comparisons
def make_nancomp(op):
| 64 | 64 | 94 | 6 | 57 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | make_nancomp | make_nancomp | 1,619 | 1,635 | 1,619 | 1,619 | 1464d74f10d4597d884f4a2d9b3f2a0591189f35 | bigcode/the-stack | train |
6fb00f9d7170de7026db489c | train | function | @disallow("M8", "m8")
def nanprod(
values: np.ndarray,
*,
axis: Optional[int] = None,
skipna: bool = True,
min_count: int = 0,
mask: Optional[np.ndarray] = None,
) -> float:
"""
Parameters
----------
values : ndarray[dtype]
axis: int, optional
skipna : bool, default True
... | @disallow("M8", "m8")
def nanprod(
values: np.ndarray,
*,
axis: Optional[int] = None,
skipna: bool = True,
min_count: int = 0,
mask: Optional[np.ndarray] = None,
) -> float:
| """
Parameters
----------
values : ndarray[dtype]
axis: int, optional
skipna : bool, default True
min_count: int, default 0
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
Dtype
The product of all elements on a given axis. ( NaNs are treated ... | if isinstance(result, np.ndarray):
result = np.where(denominator == 0, 0, result)
result[count < 4] = np.nan
return result
@disallow("M8", "m8")
def nanprod(
values: np.ndarray,
*,
axis: Optional[int] = None,
skipna: bool = True,
min_count: int = 0,
mask: Optional[np.ndarra... | 102 | 102 | 340 | 63 | 38 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | nanprod | nanprod | 1,302 | 1,345 | 1,302 | 1,310 | f4956e2680b19c99e1e833293cd5248bb1da0763 | bigcode/the-stack | train |
29f197827adeaa84b0c33232 | train | function | def _get_fill_value(
dtype: DtypeObj, fill_value: Optional[Scalar] = None, fill_value_typ=None
):
""" return the correct fill value for the dtype of the values """
if fill_value is not None:
return fill_value
if _na_ok_dtype(dtype):
if fill_value_typ is None:
return np.nan
... | def _get_fill_value(
dtype: DtypeObj, fill_value: Optional[Scalar] = None, fill_value_typ=None
):
| """ return the correct fill value for the dtype of the values """
if fill_value is not None:
return fill_value
if _na_ok_dtype(dtype):
if fill_value_typ is None:
return np.nan
else:
if fill_value_typ == "+inf":
return np.inf
else:
... | inf(result).any()
except (TypeError, NotImplementedError):
# if it doesn't support infs, then it can't have infs
return False
def _get_fill_value(
dtype: DtypeObj, fill_value: Optional[Scalar] = None, fill_value_typ=None
):
| 64 | 64 | 143 | 29 | 34 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | _get_fill_value | _get_fill_value | 194 | 213 | 194 | 196 | f53bad1bd4ec06d4798b4ae8ba5dc25068d7e26d | bigcode/the-stack | train |
05bfc56a75c0e3b4fea8f92b | train | function | def na_accum_func(values: ArrayLike, accum_func, *, skipna: bool) -> ArrayLike:
"""
Cumulative function with skipna support.
Parameters
----------
values : np.ndarray or ExtensionArray
accum_func : {np.cumprod, np.maximum.accumulate, np.cumsum, np.minimum.accumulate}
skipna : bool
Retu... | def na_accum_func(values: ArrayLike, accum_func, *, skipna: bool) -> ArrayLike:
| """
Cumulative function with skipna support.
Parameters
----------
values : np.ndarray or ExtensionArray
accum_func : {np.cumprod, np.maximum.accumulate, np.cumsum, np.minimum.accumulate}
skipna : bool
Returns
-------
np.ndarray or ExtensionArray
"""
mask_a, mask_b = {
... | _value.view("i8"),
mask=mask,
interpolation=interpolation,
)
# Note: we have to do `astype` and not view because in general we
# have float result at this point, not i8
return result.astype(values.dtype)
if not lib.is_scalar(mask) and mask.any():
# ... | 198 | 198 | 660 | 23 | 175 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | na_accum_func | na_accum_func | 1,729 | 1,804 | 1,729 | 1,729 | d7c4d0146c46c83bee3b0d96ddf5902efce771b5 | bigcode/the-stack | train |
4a9e47660417d1a48b08128d | train | function | def _mask_datetimelike_result(
result: Union[np.ndarray, np.datetime64, np.timedelta64],
axis: Optional[int],
mask: np.ndarray,
orig_values: np.ndarray,
) -> Union[np.ndarray, np.datetime64, np.timedelta64, NaTType]:
if isinstance(result, np.ndarray):
# we need to apply the mask
resu... | def _mask_datetimelike_result(
result: Union[np.ndarray, np.datetime64, np.timedelta64],
axis: Optional[int],
mask: np.ndarray,
orig_values: np.ndarray,
) -> Union[np.ndarray, np.datetime64, np.timedelta64, NaTType]:
| if isinstance(result, np.ndarray):
# we need to apply the mask
result = result.astype("i8").view(orig_values.dtype)
axis_mask = mask.any(axis=axis)
result[axis_mask] = iNaT
else:
if mask.any():
return NaT
return result
| return-value]
def _mask_datetimelike_result(
result: Union[np.ndarray, np.datetime64, np.timedelta64],
axis: Optional[int],
mask: np.ndarray,
orig_values: np.ndarray,
) -> Union[np.ndarray, np.datetime64, np.timedelta64, NaTType]:
| 64 | 64 | 130 | 61 | 3 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | _mask_datetimelike_result | _mask_datetimelike_result | 597 | 611 | 597 | 602 | cdb68b47060a132703de0da4ac6fc8982f92c644 | bigcode/the-stack | train |
92c330ec2017e0e2eadb2110 | train | function | @disallow("M8", "m8")
def nancorr(
a: np.ndarray, b: np.ndarray, *, method="pearson", min_periods: Optional[int] = None
):
"""
a, b: ndarrays
"""
if len(a) != len(b):
raise AssertionError("Operands to nancorr must have same size")
if min_periods is None:
min_periods = 1
val... | @disallow("M8", "m8")
def nancorr(
a: np.ndarray, b: np.ndarray, *, method="pearson", min_periods: Optional[int] = None
):
| """
a, b: ndarrays
"""
if len(a) != len(b):
raise AssertionError("Operands to nancorr must have same size")
if min_periods is None:
min_periods = 1
valid = notna(a) & notna(b)
if not valid.all():
a = a[valid]
b = b[valid]
if len(a) < min_periods:
... | arg.dtype.type(0) if np.abs(arg) < 1e-14 else arg
@disallow("M8", "m8")
def nancorr(
a: np.ndarray, b: np.ndarray, *, method="pearson", min_periods: Optional[int] = None
):
| 64 | 64 | 158 | 44 | 19 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | nancorr | nancorr | 1,507 | 1,529 | 1,507 | 1,510 | d5da7bbf0d427bf5ab44ce99e109352336ec406a | bigcode/the-stack | train |
6c9bee41d6b03f75dd6bfedc | train | function | def _na_ok_dtype(dtype: DtypeObj) -> bool:
if needs_i8_conversion(dtype):
return False
return not issubclass(dtype.type, np.integer)
| def _na_ok_dtype(dtype: DtypeObj) -> bool:
| if needs_i8_conversion(dtype):
return False
return not issubclass(dtype.type, np.integer)
| _dtype(dtype) or is_bool_dtype(dtype):
dtype_max = np.dtype(np.int64)
elif is_float_dtype(dtype):
dtype_max = np.dtype(np.float64)
return values, mask, dtype, dtype_max, fill_value
def _na_ok_dtype(dtype: DtypeObj) -> bool:
| 64 | 64 | 38 | 14 | 49 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | _na_ok_dtype | _na_ok_dtype | 349 | 352 | 349 | 349 | 5f0a3d70a065d7a08882e9a1bf68a2c188f30e1e | bigcode/the-stack | train |
d59baf5cef84b02b401331bb | train | function | def _datetimelike_compat(func: F) -> F:
"""
If we have datetime64 or timedelta64 values, ensure we have a correct
mask before calling the wrapped function, then cast back afterwards.
"""
@functools.wraps(func)
def new_func(
values: np.ndarray,
*,
axis: Optional[int] = No... | def _datetimelike_compat(func: F) -> F:
| """
If we have datetime64 or timedelta64 values, ensure we have a correct
mask before calling the wrapped function, then cast back afterwards.
"""
@functools.wraps(func)
def new_func(
values: np.ndarray,
*,
axis: Optional[int] = None,
skipna: bool = True,
... | .fabs(result) > np.iinfo(np.int64).max:
raise ValueError("overflow in timedelta operation")
result = Timedelta(result, unit="ns")
else:
result = result.astype("m8[ns]").view(dtype)
return result
def _datetimelike_compat(func: F) -> F:
| 72 | 72 | 240 | 15 | 56 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | _datetimelike_compat | _datetimelike_compat | 392 | 423 | 392 | 392 | b3a0f9605a17c92c191d7851c5da15686b40e15b | bigcode/the-stack | train |
82e4d358388941726ed401d6 | train | function | def get_empty_reduction_result(
shape: Tuple[int, ...], axis: int, dtype: np.dtype, fill_value: Any
) -> np.ndarray:
"""
The result from a reduction on an empty ndarray.
Parameters
----------
shape : Tuple[int]
axis : int
dtype : np.dtype
fill_value : Any
Returns
-------
... | def get_empty_reduction_result(
shape: Tuple[int, ...], axis: int, dtype: np.dtype, fill_value: Any
) -> np.ndarray:
| """
The result from a reduction on an empty ndarray.
Parameters
----------
shape : Tuple[int]
axis : int
dtype : np.dtype
fill_value : Any
Returns
-------
np.ndarray
"""
shp = np.array(shape)
dims = np.arange(len(shape))
ret = np.empty(shp[dims != axis], dty... | otherwise return a scalar value
res = get_median(values) if notempty else np.nan
return _wrap_results(res, dtype)
def get_empty_reduction_result(
shape: Tuple[int, ...], axis: int, dtype: np.dtype, fill_value: Any
) -> np.ndarray:
| 64 | 64 | 127 | 34 | 30 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | get_empty_reduction_result | get_empty_reduction_result | 758 | 779 | 758 | 760 | 77d8bed88b547095c15abb599b700c23edef27f4 | bigcode/the-stack | train |
696f009d2329b1ef17bd0b46 | train | function | @disallow("O")
def nanargmin(
values: np.ndarray,
*,
axis: Optional[int] = None,
skipna: bool = True,
mask: Optional[np.ndarray] = None,
) -> Union[int, np.ndarray]:
"""
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
mask : ndarray[... | @disallow("O")
def nanargmin(
values: np.ndarray,
*,
axis: Optional[int] = None,
skipna: bool = True,
mask: Optional[np.ndarray] = None,
) -> Union[int, np.ndarray]:
| """
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : int or ndarray[int]
The index/indices of min value in specified axis or -1 in the NA case
Exa... | , fill_value_typ="-inf", mask=mask)
# error: Need type annotation for 'result'
result = values.argmax(axis) # type: ignore[var-annotated]
result = _maybe_arg_null_out(result, axis, mask, skipna)
return result
@disallow("O")
def nanargmin(
values: np.ndarray,
*,
axis: Optional[int] = None,
... | 114 | 114 | 381 | 54 | 59 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | nanargmin | nanargmin | 1,073 | 1,116 | 1,073 | 1,080 | f67b1b950427ccd3572597c2d62964a9e398fe50 | bigcode/the-stack | train |
c87ce81bf5f10651e2989c36 | train | function | def _get_counts_nanvar(
values_shape: Shape,
mask: Optional[np.ndarray],
axis: Optional[int],
ddof: int,
dtype: Dtype = float,
) -> Tuple[Union[int, np.ndarray], Union[int, np.ndarray]]:
"""
Get the count of non-null values along an axis, accounting
for degrees of freedom.
Parameter... | def _get_counts_nanvar(
values_shape: Shape,
mask: Optional[np.ndarray],
axis: Optional[int],
ddof: int,
dtype: Dtype = float,
) -> Tuple[Union[int, np.ndarray], Union[int, np.ndarray]]:
| """
Get the count of non-null values along an axis, accounting
for degrees of freedom.
Parameters
----------
values_shape : Tuple[int, ...]
shape tuple from values ndarray, used if mask is None
mask : Optional[ndarray[bool]]
locations in values that should be considered miss... | : Tuple[int]
axis : int
dtype : np.dtype
fill_value : Any
Returns
-------
np.ndarray
"""
shp = np.array(shape)
dims = np.arange(len(shape))
ret = np.empty(shp[dims != axis], dtype=dtype)
ret.fill(fill_value)
return ret
def _get_counts_nanvar(
values_shape: Shape,
... | 129 | 129 | 430 | 56 | 72 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | _get_counts_nanvar | _get_counts_nanvar | 782 | 832 | 782 | 788 | f6d3a2912198852edd97251df28e7daed46d94f4 | bigcode/the-stack | train |
022d82d928d1567a22b0477b | train | function | @disallow("M8", "m8")
def nansem(
values: np.ndarray,
*,
axis: Optional[int] = None,
skipna: bool = True,
ddof: int = 1,
mask: Optional[np.ndarray] = None,
) -> float:
"""
Compute the standard error in the mean along given axis while ignoring NaNs
Parameters
----------
value... | @disallow("M8", "m8")
def nansem(
values: np.ndarray,
*,
axis: Optional[int] = None,
skipna: bool = True,
ddof: int = 1,
mask: Optional[np.ndarray] = None,
) -> float:
| """
Compute the standard error in the mean along given axis while ignoring NaNs
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
ddof : int, default 1
Delta Degrees of Freedom. The divisor used in calculations is N - ddof,
where N re... | (the datatype used in the accumulator),
# unless we were dealing with a float array, in which case use the same
# precision as the original values array.
if is_float_dtype(dtype):
result = result.astype(dtype)
return result
@disallow("M8", "m8")
def nansem(
values: np.ndarray,
*,
ax... | 116 | 116 | 387 | 63 | 52 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | nansem | nansem | 943 | 990 | 943 | 951 | b1a0b3d600f58f103aaacac5957af9d147bf566d | bigcode/the-stack | train |
38ba574652d2f98693217da9 | train | function | @disallow("O")
def nanargmax(
values: np.ndarray,
*,
axis: Optional[int] = None,
skipna: bool = True,
mask: Optional[np.ndarray] = None,
) -> Union[int, np.ndarray]:
"""
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
mask : ndarray[... | @disallow("O")
def nanargmax(
values: np.ndarray,
*,
axis: Optional[int] = None,
skipna: bool = True,
mask: Optional[np.ndarray] = None,
) -> Union[int, np.ndarray]:
| """
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : int or ndarray[int]
The index/indices of max value in specified axis or -1 in the NA case
Ex... | )(axis)
result = _maybe_null_out(result, axis, mask, values.shape)
return result
return reduction
nanmin = _nanminmax("min", fill_value_typ="+inf")
nanmax = _nanminmax("max", fill_value_typ="-inf")
@disallow("O")
def nanargmax(
values: np.ndarray,
*,
axis: Optional[int] = None,
s... | 113 | 113 | 378 | 54 | 59 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | nanargmax | nanargmax | 1,027 | 1,070 | 1,027 | 1,034 | 45c0ce229ad4035273d5dd2d1de843204d9b8169 | bigcode/the-stack | train |
2ba8a46f2ff37548b501c046 | train | function | def nanany(
values: np.ndarray,
*,
axis: Optional[int] = None,
skipna: bool = True,
mask: Optional[np.ndarray] = None,
) -> bool:
"""
Check if any elements along an axis evaluate to True.
Parameters
----------
values : ndarray
axis : int, optional
skipna : bool, default ... | def nanany(
values: np.ndarray,
*,
axis: Optional[int] = None,
skipna: bool = True,
mask: Optional[np.ndarray] = None,
) -> bool:
| """
Check if any elements along an axis evaluate to True.
Parameters
----------
values : ndarray
axis : int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : bool
Examples
--------
>>> import... | values.shape[:axis] + values.shape[axis + 1 :]
return np.full(result_shape, fill_value, dtype=values.dtype)
def nanany(
values: np.ndarray,
*,
axis: Optional[int] = None,
skipna: bool = True,
mask: Optional[np.ndarray] = None,
) -> bool:
| 73 | 73 | 246 | 43 | 30 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | nanany | nanany | 459 | 496 | 459 | 465 | 15f8ce4dc5a874eac9e54a222cfd340a91409418 | bigcode/the-stack | train |
3887d53397bfd588866b2e75 | train | function | def _maybe_get_mask(
values: np.ndarray, skipna: bool, mask: Optional[np.ndarray]
) -> Optional[np.ndarray]:
"""
Compute a mask if and only if necessary.
This function will compute a mask iff it is necessary. Otherwise,
return the provided mask (potentially None) when a mask does not need to be
... | def _maybe_get_mask(
values: np.ndarray, skipna: bool, mask: Optional[np.ndarray]
) -> Optional[np.ndarray]:
| """
Compute a mask if and only if necessary.
This function will compute a mask iff it is necessary. Otherwise,
return the provided mask (potentially None) when a mask does not need to be
computed.
A mask is never necessary if the values array is of boolean or integer
dtypes, as these are i... | if fill_value_typ == "+inf":
return np.inf
else:
return -np.inf
else:
if fill_value_typ == "+inf":
# need the max int here
return np.iinfo(np.int64).max
else:
return iNaT
def _maybe_get_mask(
values: np.n... | 92 | 92 | 307 | 29 | 62 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | _maybe_get_mask | _maybe_get_mask | 216 | 257 | 216 | 218 | 803353725d5d948940f36a919da9f17bfc302ce8 | bigcode/the-stack | train |
d154abb1529f25313605fa3a | train | function | @disallow("M8", "m8")
@bottleneck_switch(ddof=1)
def nanvar(values, *, axis=None, skipna=True, ddof=1, mask=None):
"""
Compute the variance along given axis while ignoring NaNs
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
ddof : int, default 1
... | @disallow("M8", "m8")
@bottleneck_switch(ddof=1)
def nanvar(values, *, axis=None, skipna=True, ddof=1, mask=None):
| """
Compute the variance along given axis while ignoring NaNs
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
ddof : int, default 1
Delta Degrees of Freedom. The divisor used in calculations is N - ddof,
where N represents the numbe... | nanops
>>> s = pd.Series([1, np.nan, 2, 3])
>>> nanops.nanstd(s)
1.0
"""
if values.dtype == "M8[ns]":
values = values.view("m8[ns]")
orig_dtype = values.dtype
values, mask, _, _, _ = _get_values(values, skipna, mask=mask)
result = np.sqrt(nanvar(values, axis=axis, skipna=skipn... | 171 | 171 | 570 | 42 | 129 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | nanvar | nanvar | 874 | 940 | 874 | 876 | a82b12101210799a9103b19c8f3a35eb3c27ed15 | bigcode/the-stack | train |
c3cee5ae200c39f26440477d | train | function | def nanpercentile(
values: np.ndarray,
q: np.ndarray,
*,
na_value,
mask: np.ndarray,
interpolation,
):
"""
Wrapper for np.percentile that skips missing values.
Parameters
----------
values : np.ndarray[ndim=2] over which to find quantiles
q : np.ndarray[float64] of quan... | def nanpercentile(
values: np.ndarray,
q: np.ndarray,
*,
na_value,
mask: np.ndarray,
interpolation,
):
| """
Wrapper for np.percentile that skips missing values.
Parameters
----------
values : np.ndarray[ndim=2] over which to find quantiles
q : np.ndarray[float64] of quantile indices to find
na_value : scalar
value to return for empty or all-null values
mask : ndarray[bool]
... | str
Returns
-------
quantiles : scalar or array
"""
# mask is Union[ExtensionArray, ndarray]
values = values[~mask]
if len(values) == 0:
return np.array([na_value] * len(q), dtype=values.dtype)
return np.percentile(values, q, interpolation=interpolation)
def nanpercentile(
... | 109 | 109 | 364 | 33 | 76 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | nanpercentile | nanpercentile | 1,676 | 1,726 | 1,676 | 1,683 | 86259aa09937243819591bee1942876adbe8836e | bigcode/the-stack | train |
4a24009df9bb7ed60005a16e | train | function | @bottleneck_switch(ddof=1)
def nanstd(values, *, axis=None, skipna=True, ddof=1, mask=None):
"""
Compute the standard deviation along given axis while ignoring NaNs
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
ddof : int, default 1
Delta... | @bottleneck_switch(ddof=1)
def nanstd(values, *, axis=None, skipna=True, ddof=1, mask=None):
| """
Compute the standard deviation along given axis while ignoring NaNs
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
ddof : int, default 1
Delta Degrees of Freedom. The divisor used in calculations is N - ddof,
where N represents... | .nan)
# error: Incompatible return value type (got "Tuple[Union[int, float,
# ndarray], Any]", expected "Tuple[Union[int, ndarray], Union[int,
# ndarray]]")
return count, d # type: ignore[return-value]
@bottleneck_switch(ddof=1)
def nanstd(values, *, axis=None, skipna=True, ddof=1, mask=None):
| 89 | 89 | 298 | 31 | 58 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | nanstd | nanstd | 835 | 871 | 835 | 836 | 0109b92052f0b655450fd63253e49ff8356ecb0d | bigcode/the-stack | train |
55bbc0c15783b9f51ea463f9 | train | class | class disallow:
def __init__(self, *dtypes):
super().__init__()
self.dtypes = tuple(pandas_dtype(dtype).type for dtype in dtypes)
def check(self, obj) -> bool:
return hasattr(obj, "dtype") and issubclass(obj.dtype.type, self.dtypes)
def __call__(self, f: F) -> F:
@functools... | class disallow:
| def __init__(self, *dtypes):
super().__init__()
self.dtypes = tuple(pandas_dtype(dtype).type for dtype in dtypes)
def check(self, obj) -> bool:
return hasattr(obj, "dtype") and issubclass(obj.dtype.type, self.dtypes)
def __call__(self, f: F) -> F:
@functools.wraps(f)
... | = False
def set_use_bottleneck(v: bool = True) -> None:
# set/unset to use bottleneck
global _USE_BOTTLENECK
if _BOTTLENECK_INSTALLED:
_USE_BOTTLENECK = v
set_use_bottleneck(get_option("compute.use_bottleneck"))
class disallow:
| 77 | 78 | 263 | 4 | 73 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | disallow | disallow | 77 | 106 | 77 | 77 | cddef88a42d3a8fe0c3054047d06ae570684678d | bigcode/the-stack | train |
78f69b5d15d0b0c5aba3c32d | train | function | def _maybe_arg_null_out(
result: np.ndarray, axis: Optional[int], mask: Optional[np.ndarray], skipna: bool
) -> Union[np.ndarray, int]:
# helper function for nanargmin/nanargmax
if mask is None:
return result
if axis is None or not getattr(result, "ndim", False):
if skipna:
... | def _maybe_arg_null_out(
result: np.ndarray, axis: Optional[int], mask: Optional[np.ndarray], skipna: bool
) -> Union[np.ndarray, int]:
# helper function for nanargmin/nanargmax
| if mask is None:
return result
if axis is None or not getattr(result, "ndim", False):
if skipna:
if mask.all():
# error: Incompatible types in assignment (expression has type
# "int", variable has type "ndarray")
result = -1 # type: i... | , min_count=min_count # type: ignore[arg-type]
)
def _maybe_arg_null_out(
result: np.ndarray, axis: Optional[int], mask: Optional[np.ndarray], skipna: bool
) -> Union[np.ndarray, int]:
# helper function for nanargmin/nanargmax
| 65 | 65 | 219 | 50 | 15 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | _maybe_arg_null_out | _maybe_arg_null_out | 1,348 | 1,373 | 1,348 | 1,351 | 1f1875d302c6f543a68d81afa361e0fdc0d247f5 | bigcode/the-stack | train |
35a809a2c600689262c00553 | train | function | def _bn_ok_dtype(dtype: DtypeObj, name: str) -> bool:
# Bottleneck chokes on datetime64, PeriodDtype (or and EA)
if not is_object_dtype(dtype) and not needs_i8_conversion(dtype):
# GH 15507
# bottleneck does not properly upcast during the sum
# so can overflow
# GH 9422
... | def _bn_ok_dtype(dtype: DtypeObj, name: str) -> bool:
# Bottleneck chokes on datetime64, PeriodDtype (or and EA)
| if not is_object_dtype(dtype) and not needs_i8_conversion(dtype):
# GH 15507
# bottleneck does not properly upcast during the sum
# so can overflow
# GH 9422
# further we also want to preserve NaN when all elements
# are NaN, unlike bottleneck/numpy which consider t... | alt(values, axis=axis, skipna=skipna, **kwds)
return result
return cast(F, f)
def _bn_ok_dtype(dtype: DtypeObj, name: str) -> bool:
# Bottleneck chokes on datetime64, PeriodDtype (or and EA)
| 64 | 64 | 139 | 36 | 28 | Pawel-Kranzberg/pandas | pandas/core/nanops.py | Python | _bn_ok_dtype | _bn_ok_dtype | 165 | 178 | 165 | 166 | 920e31107785e1e57136181b602a462e05007213 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.