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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f7f8ad3040c4416c89eb2f86 | train | class | class ExponentialLR(TorchScheduler):
def __init__(self, gamma, last_epoch=-1):
super(ExponentialLR, self).__init__(scheduler_fn=partial(lrs.ExponentialLR,
gamma=gamma, last_epoch=last_epoch))
| class ExponentialLR(TorchScheduler):
| def __init__(self, gamma, last_epoch=-1):
super(ExponentialLR, self).__init__(scheduler_fn=partial(lrs.ExponentialLR,
gamma=gamma, last_epoch=last_epoch))
| __init__(self, milestones, gamma=0.1, last_epoch=-1):
super(MultiStepLR, self).__init__(scheduler_fn=partial(lrs.MultiStepLR,
milestones=milestones,
gamma=gamma, last_epoch=last_epoch))... | 64 | 64 | 54 | 8 | 56 | vladstreltsin/blox | btorch/scheduler.py | Python | ExponentialLR | ExponentialLR | 45 | 48 | 45 | 45 | 84b73d592f9c7da1ef2fd32a4e7df3bccdcbfa4d | bigcode/the-stack | train |
3374a11b27a686112818496a | train | class | class CosineAnnealingWarmRestarts(TorchScheduler):
def __init__(self, T_0, T_mult=1, eta_min=0, last_epoch=-1):
super(CosineAnnealingWarmRestarts, self).__init__(scheduler_fn=partial(lrs.CosineAnnealingWarmRestarts,
T_0=T_0,
... | class CosineAnnealingWarmRestarts(TorchScheduler):
| def __init__(self, T_0, T_mult=1, eta_min=0, last_epoch=-1):
super(CosineAnnealingWarmRestarts, self).__init__(scheduler_fn=partial(lrs.CosineAnnealingWarmRestarts,
T_0=T_0,
... | gamma=gamma,
scale_fn=scale_fn,
scale_mode=scale_mode,
cycle_momentum=cycle_mome... | 64 | 64 | 95 | 12 | 52 | vladstreltsin/blox | btorch/scheduler.py | Python | CosineAnnealingWarmRestarts | CosineAnnealingWarmRestarts | 98 | 104 | 98 | 98 | f9871d72114f06a8fe13565ba9dcd1abdb18dbb6 | bigcode/the-stack | train |
34c9a38c9749d1f73fb074ab | train | class | class StepLR(TorchScheduler):
def __init__(self, step_size, gamma=0.1, last_epoch=-1):
super(StepLR, self).__init__(scheduler_fn=partial(lrs.StepLR,
step_size=step_size, gamma=gamma, last_epoch=last_epoch))
| class StepLR(TorchScheduler):
| def __init__(self, step_size, gamma=0.1, last_epoch=-1):
super(StepLR, self).__init__(scheduler_fn=partial(lrs.StepLR,
step_size=step_size, gamma=gamma, last_epoch=last_epoch))
| (epoch=None)
class LambdaLR(TorchScheduler):
def __init__(self, lr_lambda, last_epoch=-1):
super(LambdaLR, self).__init__(scheduler_fn=partial(lrs.LambdaLR, lr_lambda=lr_lambda, last_epoch=last_epoch))
class StepLR(TorchScheduler):
| 64 | 64 | 64 | 7 | 57 | vladstreltsin/blox | btorch/scheduler.py | Python | StepLR | StepLR | 32 | 35 | 32 | 32 | 263b24efb1df3bfc9a83788a7c6c5f3c49356c5e | bigcode/the-stack | train |
75712784f29e540de50b6767 | train | class | class CosineAnnealingLR(TorchScheduler):
def __init__(self, T_max, eta_min=0, last_epoch=-1):
super(CosineAnnealingLR, self).__init__(scheduler_fn=partial(lrs.CosineAnnealingLR,
T_max=T_max, eta_min=eta_min,
... | class CosineAnnealingLR(TorchScheduler):
| def __init__(self, T_max, eta_min=0, last_epoch=-1):
super(CosineAnnealingLR, self).__init__(scheduler_fn=partial(lrs.CosineAnnealingLR,
T_max=T_max, eta_min=eta_min,
las... | class ExponentialLR(TorchScheduler):
def __init__(self, gamma, last_epoch=-1):
super(ExponentialLR, self).__init__(scheduler_fn=partial(lrs.ExponentialLR,
gamma=gamma, last_epoch=last_epoch))
class CosineAnnealingLR(TorchScheduler):
| 64 | 64 | 74 | 10 | 54 | vladstreltsin/blox | btorch/scheduler.py | Python | CosineAnnealingLR | CosineAnnealingLR | 51 | 55 | 51 | 51 | 424cf489b39dd85eea46fd678b0db5c3f61c8d63 | bigcode/the-stack | train |
61e12d1ddc9210e96c096558 | train | class | class CyclicLR(TorchScheduler):
def __init__(self, base_lr,
max_lr,
step_size_up=2000,
step_size_down=None,
mode='triangular',
gamma=1.,
scale_fn=None,
scale_mode='cycle',
cycle_mo... | class CyclicLR(TorchScheduler):
| def __init__(self, base_lr,
max_lr,
step_size_up=2000,
step_size_down=None,
mode='triangular',
gamma=1.,
scale_fn=None,
scale_mode='cycle',
cycle_momentum=True,
ba... | (lrs.ReduceLROnPlateau,
mode=mode, factor=factor, patience=patience,
verbose=verbose, threshold=threshold,
thresh... | 64 | 64 | 196 | 8 | 56 | vladstreltsin/blox | btorch/scheduler.py | Python | CyclicLR | CyclicLR | 70 | 95 | 70 | 70 | 674ba53c614f6f974d0465af5bde269708c83db0 | bigcode/the-stack | train |
d914584ea88fa77cc16cd0df | train | class | class TorchScheduler:
def __init__(self, scheduler_fn):
self.__scheduler_fn = scheduler_fn
self.__scheduler: T.Optional[lrs._LRScheduler] = None
def init(self, optimizer):
self.__scheduler = self.__scheduler_fn(optimizer)
def step(self):
maybe_error(self.__scheduler, Torch... | class TorchScheduler:
| def __init__(self, scheduler_fn):
self.__scheduler_fn = scheduler_fn
self.__scheduler: T.Optional[lrs._LRScheduler] = None
def init(self, optimizer):
self.__scheduler = self.__scheduler_fn(optimizer)
def step(self):
maybe_error(self.__scheduler, TorchSchedulerError("The sch... | from functools import partial
from torch.optim import lr_scheduler as lrs
import typing as T
from blox_old.utils import maybe_error
from blox_old.core.engine import SessionError
class TorchSchedulerError(SessionError):
pass
class TorchScheduler:
| 53 | 64 | 89 | 4 | 48 | vladstreltsin/blox | btorch/scheduler.py | Python | TorchScheduler | TorchScheduler | 13 | 24 | 13 | 14 | 58893a567a6710d7a190161f1cd85743ef0d3e23 | bigcode/the-stack | train |
c422da80aa355d40c70123f9 | train | class | class TorchSchedulerError(SessionError):
pass
| class TorchSchedulerError(SessionError):
| pass
| from functools import partial
from torch.optim import lr_scheduler as lrs
import typing as T
from blox_old.utils import maybe_error
from blox_old.core.engine import SessionError
class TorchSchedulerError(SessionError):
| 46 | 64 | 10 | 7 | 38 | vladstreltsin/blox | btorch/scheduler.py | Python | TorchSchedulerError | TorchSchedulerError | 9 | 10 | 9 | 9 | 0e2be58d3c5197412e3a55096bed399e1f34b5de | bigcode/the-stack | train |
43012511a9b5c023efc6ff7f | train | class | class LambdaLR(TorchScheduler):
def __init__(self, lr_lambda, last_epoch=-1):
super(LambdaLR, self).__init__(scheduler_fn=partial(lrs.LambdaLR, lr_lambda=lr_lambda, last_epoch=last_epoch))
| class LambdaLR(TorchScheduler):
| def __init__(self, lr_lambda, last_epoch=-1):
super(LambdaLR, self).__init__(scheduler_fn=partial(lrs.LambdaLR, lr_lambda=lr_lambda, last_epoch=last_epoch))
| ._LRScheduler] = None
def init(self, optimizer):
self.__scheduler = self.__scheduler_fn(optimizer)
def step(self):
maybe_error(self.__scheduler, TorchSchedulerError("The scheduler was not initialized"))
self.__scheduler.step(epoch=None)
class LambdaLR(TorchScheduler):
| 64 | 64 | 54 | 7 | 57 | vladstreltsin/blox | btorch/scheduler.py | Python | LambdaLR | LambdaLR | 27 | 29 | 27 | 27 | 42f6e6ff23cbbd67e919ed517edf36c2073b6869 | bigcode/the-stack | train |
69ad031c0283e31ef8cd22b7 | train | class | class MultiStepLR(TorchScheduler):
def __init__(self, milestones, gamma=0.1, last_epoch=-1):
super(MultiStepLR, self).__init__(scheduler_fn=partial(lrs.MultiStepLR,
milestones=milestones,
... | class MultiStepLR(TorchScheduler):
| def __init__(self, milestones, gamma=0.1, last_epoch=-1):
super(MultiStepLR, self).__init__(scheduler_fn=partial(lrs.MultiStepLR,
milestones=milestones,
gamma=gamma, last_epoch=last_... | def __init__(self, step_size, gamma=0.1, last_epoch=-1):
super(StepLR, self).__init__(scheduler_fn=partial(lrs.StepLR,
step_size=step_size, gamma=gamma, last_epoch=last_epoch))
class MultiStepLR(TorchScheduler):
| 64 | 64 | 66 | 8 | 56 | vladstreltsin/blox | btorch/scheduler.py | Python | MultiStepLR | MultiStepLR | 38 | 42 | 38 | 38 | 4ef7722f1b006aed747cd1e546958542e0d84cae | bigcode/the-stack | train |
243ceb881e8c84dc88d43072 | train | class | class TestV1alpha1RepoCreds(unittest.TestCase):
"""V1alpha1RepoCreds unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional):
"""Test V1alpha1RepoCreds
include_option is a boolean, when False only required
... | class TestV1alpha1RepoCreds(unittest.TestCase):
| """V1alpha1RepoCreds unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional):
"""Test V1alpha1RepoCreds
include_option is a boolean, when False only required
params are included, when True both require... | api-generator.tech
"""
from __future__ import absolute_import
import unittest
import datetime
import argocd_client
from argocd_client.models.v1alpha1_repo_creds import V1alpha1RepoCreds # noqa: E501
from argocd_client.rest import ApiException
class TestV1alpha1RepoCreds(unittest.TestCase):
| 76 | 76 | 254 | 13 | 62 | thepabloaguilar/argocd-client | test/test_v1alpha1_repo_creds.py | Python | TestV1alpha1RepoCreds | TestV1alpha1RepoCreds | 22 | 53 | 22 | 22 | a72639124597ac7f3a7d7c0b55f2a811fa3014e4 | bigcode/the-stack | train |
a32af902898c1cc286db2545 | train | class | class BlobFs_Download_SAS_User_Scenarios(unittest.TestCase):
def setUp(self):
cmd = util.Command("login").add_arguments("--service-principal").add_flags("application-id", os.environ['ACTIVE_DIRECTORY_APPLICATION_ID'])
cmd.execute_azcopy_copy_command()
self.cachedAzCopyAccountKey = os.environ... | class BlobFs_Download_SAS_User_Scenarios(unittest.TestCase):
| def setUp(self):
cmd = util.Command("login").add_arguments("--service-principal").add_flags("application-id", os.environ['ACTIVE_DIRECTORY_APPLICATION_ID'])
cmd.execute_azcopy_copy_command()
self.cachedAzCopyAccountKey = os.environ['ACCOUNT_KEY']
os.environ['ACCOUNT_KEY'] = ''
d... | import unittest
import os
import utility as util
import shutil
class BlobFs_Download_SAS_User_Scenarios(unittest.TestCase):
| 29 | 256 | 1,071 | 15 | 13 | rioriost/azure-storage-azcopy | testSuite/scripts/test_blobfs_download_SAS.py | Python | BlobFs_Download_SAS_User_Scenarios | BlobFs_Download_SAS_User_Scenarios | 6 | 107 | 6 | 6 | 40c6e2e3075e9d9472e77b2085e52b3623187a7d | bigcode/the-stack | train |
83e7faa8c08161e5778b2c84 | train | class | class ExampleTest(BitcoinTestFramework):
# Each functional test is a subclass of the BitcoinTestFramework class.
# Override the set_test_params(), skip_test_if_missing_module(), add_options(), setup_chain(), setup_network()
# and setup_nodes() methods to customize the test setup as required.
def set_t... | class ExampleTest(BitcoinTestFramework):
# Each functional test is a subclass of the BitcoinTestFramework class.
# Override the set_test_params(), skip_test_if_missing_module(), add_options(), setup_chain(), setup_network()
# and setup_nodes() methods to customize the test setup as required.
| def set_test_params(self):
"""Override test parameters for your individual test.
This method must be overridden and num_nodes must be explicitly set."""
self.setup_clean_chain = True
self.num_nodes = 3
# Use self.extra_args to change command-line arguments for the nodes
... | message of each type, which should be sufficient for the
needs of most tests.
Call super().__init__() first for standard initialization and then
initialize custom properties."""
super().__init__()
# Stores a dictionary of all blocks received
self.block_receive_map = def... | 256 | 256 | 1,356 | 61 | 194 | DreamShokk/bagicoin | test/functional/example_test.py | Python | ExampleTest | ExampleTest | 71 | 209 | 71 | 76 | e9e2b07822e1e47b5ec02a77644d4254f2367024 | bigcode/the-stack | train |
03acb59e388e3fad9e10433f | train | function | def custom_function():
"""Do some custom behaviour
If this function is more generally useful for other tests, consider
moving it to a module in test_framework."""
# self.log.info("running custom_function") # Oops! Can't run self.log outside the BitcoinTestFramework
pass
| def custom_function():
| """Do some custom behaviour
If this function is more generally useful for other tests, consider
moving it to a module in test_framework."""
# self.log.info("running custom_function") # Oops! Can't run self.log outside the BitcoinTestFramework
pass
| the standard on_block callback
Store the hash of a received block in the dictionary."""
message.block.calc_sha256()
self.block_receive_map[message.block.sha256] += 1
def on_inv(self, message):
"""Override the standard on_inv callback"""
pass
def custom_function():
| 64 | 64 | 63 | 4 | 59 | DreamShokk/bagicoin | test/functional/example_test.py | Python | custom_function | custom_function | 62 | 68 | 62 | 62 | 5a73212444c7e95a96fd62e47a82288b9d698508 | bigcode/the-stack | train |
c7cb7996528daa9ceb3e60c6 | train | class | class BaseNode(P2PInterface):
def __init__(self):
"""Initialize the P2PInterface
Used to initialize custom properties for the Node that aren't
included by default in the base class. Be aware that the P2PInterface
base class already stores a counter for each P2P message type and the
... | class BaseNode(P2PInterface):
| def __init__(self):
"""Initialize the P2PInterface
Used to initialize custom properties for the Node that aren't
included by default in the base class. Be aware that the P2PInterface
base class already stores a counter for each P2P message type and the
last received message ... | ,
wait_until,
)
# P2PInterface is a class containing callbacks to be executed when a P2P
# message is received from the node-under-test. Subclass P2PInterface and
# override the on_*() methods if you need custom behaviour.
class BaseNode(P2PInterface):
| 64 | 64 | 206 | 8 | 56 | DreamShokk/bagicoin | test/functional/example_test.py | Python | BaseNode | BaseNode | 35 | 60 | 35 | 35 | 27e40e6af562bce4c0e5e865d017a755b4e61ca7 | bigcode/the-stack | train |
6484fcf9cfde628a5009c7d7 | train | function | def gather(strategy, value):
"""Gathers value from all workers.
This is intended for tests before we implement an official all-gather API.
Args:
strategy: a `tf.distribute.Strategy`.
value: a nested structure of n-dim `tf.distribute.DistributedValue` of
`tf.Tensor`, or of a `tf.Tensor` if the stra... | def gather(strategy, value):
| """Gathers value from all workers.
This is intended for tests before we implement an official all-gather API.
Args:
strategy: a `tf.distribute.Strategy`.
value: a nested structure of n-dim `tf.distribute.DistributedValue` of
`tf.Tensor`, or of a `tf.Tensor` if the strategy only has one replica.
... | from tensorflow.python.distribute import cross_device_utils
from tensorflow.python.distribute import distribute_utils
from tensorflow.python.distribute import values
from tensorflow.python.eager import def_function
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.p... | 64 | 64 | 129 | 6 | 57 | yage99/tensorflow | tensorflow/python/distribute/test_util.py | Python | gather | gather | 33 | 47 | 33 | 33 | b1cdb18348941fbdd21da8338fd2e094b538e30c | bigcode/the-stack | train |
6d337b6be7d7a94686bb9f02 | train | function | def _gather(strategy, value):
"""Gathers a single value."""
# pylint: disable=protected-access
if not isinstance(value, values.DistributedValues):
value = values.PerReplica([ops.convert_to_tensor(value)])
if not isinstance(strategy.extended,
collective_all_reduce_strategy.CollectiveAllRe... | def _gather(strategy, value):
| """Gathers a single value."""
# pylint: disable=protected-access
if not isinstance(value, values.DistributedValues):
value = values.PerReplica([ops.convert_to_tensor(value)])
if not isinstance(strategy.extended,
collective_all_reduce_strategy.CollectiveAllReduceExtended):
return arra... | `tf.Tensor` if the strategy only has one replica.
Cannot contain tf.sparse.SparseTensor.
Returns:
a (n+1)-dim `tf.Tensor`.
"""
return nest.map_structure(functools.partial(_gather, strategy), value)
def _gather(strategy, value):
| 64 | 64 | 206 | 8 | 56 | yage99/tensorflow | tensorflow/python/distribute/test_util.py | Python | _gather | _gather | 50 | 71 | 50 | 50 | adc59b8971b5d96ac96a8e7a553fcaf6c732e88e | bigcode/the-stack | train |
85c5746c2685314288401666 | train | function | def get_bool_from_text_value(value):
""" to be deprecated
It has issues, as accepting into the registry whatever=value, as False, without
complaining
"""
return (value == "1" or value.lower() == "yes" or value.lower() == "y" or
value.lower() == "true") if value else True
| def get_bool_from_text_value(value):
| """ to be deprecated
It has issues, as accepting into the registry whatever=value, as False, without
complaining
"""
return (value == "1" or value.lower() == "yes" or value.lower() == "y" or
value.lower() == "true") if value else True
| import re
from conans.errors import ConanException
def get_bool_from_text_value(value):
| 19 | 64 | 76 | 8 | 10 | laundry-96/conan | conans/util/config_parser.py | Python | get_bool_from_text_value | get_bool_from_text_value | 6 | 12 | 6 | 6 | 64ce9f73a38aed704196a459468c9f77498841bb | bigcode/the-stack | train |
14cbc6a5e3b4fcfa961c2a25 | train | class | class ConfigParser(object):
""" util class to load a file with sections as [section1]
checking the values of those sections, and returns each section
as parser.section
Currently used in ConanInfo and ConanFileTextLoader
"""
def __init__(self, text, allowed_fields=None, parse_lines=False, raise_u... | class ConfigParser(object):
| """ util class to load a file with sections as [section1]
checking the values of those sections, and returns each section
as parser.section
Currently used in ConanInfo and ConanFileTextLoader
"""
def __init__(self, text, allowed_fields=None, parse_lines=False, raise_unexpected_field=True):
... | """
return (value == "1" or value.lower() == "yes" or value.lower() == "y" or
value.lower() == "true") if value else True
def get_bool_from_text(value):
value = value.lower()
if value in ["1", "yes", "y", "true"]:
return True
if value in ["0", "no", "n", "false"]:
return F... | 113 | 113 | 377 | 5 | 108 | laundry-96/conan | conans/util/config_parser.py | Python | ConfigParser | ConfigParser | 24 | 67 | 24 | 24 | 766dedad96a010a41a7fccb995c761ef226471fd | bigcode/the-stack | train |
a859635cb19ad1e877edbaeb | train | function | def get_bool_from_text(value):
value = value.lower()
if value in ["1", "yes", "y", "true"]:
return True
if value in ["0", "no", "n", "false"]:
return False
raise ConanException("Unrecognized boolean value '%s'" % value)
| def get_bool_from_text(value):
| value = value.lower()
if value in ["1", "yes", "y", "true"]:
return True
if value in ["0", "no", "n", "false"]:
return False
raise ConanException("Unrecognized boolean value '%s'" % value)
| as accepting into the registry whatever=value, as False, without
complaining
"""
return (value == "1" or value.lower() == "yes" or value.lower() == "y" or
value.lower() == "true") if value else True
def get_bool_from_text(value):
| 64 | 64 | 68 | 7 | 56 | laundry-96/conan | conans/util/config_parser.py | Python | get_bool_from_text | get_bool_from_text | 15 | 21 | 15 | 15 | a0beb53675581ab3368b8e61c0142257fb2357e8 | bigcode/the-stack | train |
2063537d7d514aa243585971 | train | function | @derived_from(np)
def isclose(arr1, arr2, rtol=1e-5, atol=1e-8, equal_nan=False):
func = partial(np.isclose, rtol=rtol, atol=atol, equal_nan=equal_nan)
return elemwise(func, arr1, arr2, dtype="bool")
| @derived_from(np)
def isclose(arr1, arr2, rtol=1e-5, atol=1e-8, equal_nan=False):
| func = partial(np.isclose, rtol=rtol, atol=atol, equal_nan=equal_nan)
return elemwise(func, arr1, arr2, dtype="bool")
| _isnull, values, dtype="bool")
def notnull(values):
""" pandas.notnull for dask arrays """
return ~isnull(values)
@derived_from(np)
def isclose(arr1, arr2, rtol=1e-5, atol=1e-8, equal_nan=False):
| 64 | 64 | 74 | 33 | 31 | Pranay144/dask | dask/array/routines.py | Python | isclose | isclose | 1,148 | 1,151 | 1,148 | 1,149 | 81ff836d3710336b7e1bfe2f007210218a5d07c3 | bigcode/the-stack | train |
c51b0e73e1543705bbde4dce | train | function | def _int_piecewise(x, *condlist, **kwargs):
return np.piecewise(
x, list(condlist), kwargs["funclist"], *kwargs["func_args"], **kwargs["func_kw"]
)
| def _int_piecewise(x, *condlist, **kwargs):
| return np.piecewise(
x, list(condlist), kwargs["funclist"], *kwargs["func_args"], **kwargs["func_kw"]
)
| derived_from(np)
def nonzero(a):
ind = argwhere(a)
if ind.ndim > 1:
return tuple(ind[:, i] for i in range(ind.shape[1]))
else:
return (ind,)
def _int_piecewise(x, *condlist, **kwargs):
| 63 | 64 | 48 | 14 | 49 | Pranay144/dask | dask/array/routines.py | Python | _int_piecewise | _int_piecewise | 1,243 | 1,246 | 1,243 | 1,243 | 87e15e7f3ca28d20f3d67b05aa6f185fa8ce345c | bigcode/the-stack | train |
a5619b6ec78a6c0fa7acc896 | train | function | @derived_from(np)
def result_type(*args):
args = [a if is_scalar_for_elemwise(a) else a.dtype for a in args]
return np.result_type(*args)
| @derived_from(np)
def result_type(*args):
| args = [a if is_scalar_for_elemwise(a) else a.dtype for a in args]
return np.result_type(*args)
| dtype=None, ndmin=None):
while ndmin is not None and x.ndim < ndmin:
x = x[None, :]
if dtype is not None and x.dtype != dtype:
x = x.astype(dtype)
return x
@derived_from(np)
def result_type(*args):
| 64 | 64 | 40 | 11 | 52 | Pranay144/dask | dask/array/routines.py | Python | result_type | result_type | 53 | 56 | 53 | 54 | 91e72ab047c2f8b160a09015b9d4b5460ebcd87e | bigcode/the-stack | train |
6542c420dbc196c190d2436f | train | function | def variadic_choose(a, *choices):
return np.choose(a, choices)
| def variadic_choose(a, *choices):
| return np.choose(a, choices)
| close(arr1, arr2, rtol=1e-5, atol=1e-8, equal_nan=False):
return isclose(arr1, arr2, rtol=rtol, atol=atol, equal_nan=equal_nan).all()
def variadic_choose(a, *choices):
| 64 | 64 | 17 | 9 | 55 | Pranay144/dask | dask/array/routines.py | Python | variadic_choose | variadic_choose | 1,159 | 1,160 | 1,159 | 1,159 | bb141433757173fb71164bec9cbeb5806c87b7db | bigcode/the-stack | train |
a23e9ff522735e1240a0a78e | train | function | @derived_from(np)
def apply_along_axis(func1d, axis, arr, *args, dtype=None, shape=None, **kwargs):
"""
Apply a function to 1-D slices along the given axis. This is
a blocked variant of :func:`numpy.apply_along_axis` implemented via
:func:`dask.array.map_blocks`
Parameters
__________
func1... | @derived_from(np)
def apply_along_axis(func1d, axis, arr, *args, dtype=None, shape=None, **kwargs):
| """
Apply a function to 1-D slices along the given axis. This is
a blocked variant of :func:`numpy.apply_along_axis` implemented via
:func:`dask.array.map_blocks`
Parameters
__________
func1d : callable
Function to apply to 1-D slices of the array along the given axis
axis : in... | = out[..., 0, :]
if b_is_1d:
out = out[..., 0]
return out
@derived_from(np)
def outer(a, b):
a = a.flatten()
b = b.flatten()
dtype = np.outer(a.dtype.type(), b.dtype.type()).dtype
return blockwise(np.outer, "ij", a, "i", b, "j", dtype=dtype)
def _inner_apply_along_axis(arr, func1... | 177 | 177 | 592 | 30 | 147 | Pranay144/dask | dask/array/routines.py | Python | apply_along_axis | apply_along_axis | 344 | 409 | 344 | 345 | c5723ea5c15e885ea16d3fcbc8474f26ea95b41b | bigcode/the-stack | train |
2128adea1e7347e0bacf033d | train | function | def _isnonzero_vec(v):
return bool(np.count_nonzero(v))
| def _isnonzero_vec(v):
| return bool(np.count_nonzero(v))
| , atol=atol, equal_nan=equal_nan).all()
def variadic_choose(a, *choices):
return np.choose(a, choices)
@derived_from(np)
def choose(a, choices):
return elemwise(variadic_choose, a, *choices)
def _isnonzero_vec(v):
| 64 | 64 | 17 | 8 | 56 | Pranay144/dask | dask/array/routines.py | Python | _isnonzero_vec | _isnonzero_vec | 1,168 | 1,169 | 1,168 | 1,168 | dae4d2ac8365c02be0e4fb9d3df43e545719625f | bigcode/the-stack | train |
2d9fc1b769c80d197640a42f | train | function | @derived_from(np)
def cov(m, y=None, rowvar=1, bias=0, ddof=None):
# This was copied almost verbatim from np.cov
# See numpy license at https://github.com/numpy/numpy/blob/master/LICENSE.txt
# or NUMPY_LICENSE.txt within this directory
if ddof is not None and ddof != int(ddof):
raise ValueError(... | @derived_from(np)
def cov(m, y=None, rowvar=1, bias=0, ddof=None):
# This was copied almost verbatim from np.cov
# See numpy license at https://github.com/numpy/numpy/blob/master/LICENSE.txt
# or NUMPY_LICENSE.txt within this directory
| if ddof is not None and ddof != int(ddof):
raise ValueError("ddof must be integer")
# Handles complex arrays too
m = asarray(m)
if y is None:
dtype = np.result_type(m, np.float64)
else:
y = asarray(y)
dtype = np.result_type(m, y, np.float64)
X = array(m, ndmin=2,... | :
db = from_array(np.diff(bins).astype(float), chunks=n.chunks)
return n / db / n.sum(), bins
else:
return n, bins
else:
return n, bins
@derived_from(np)
def cov(m, y=None, rowvar=1, bias=0, ddof=None):
# This was copied almost verbatim from np.cov
# See n... | 116 | 116 | 389 | 68 | 47 | Pranay144/dask | dask/array/routines.py | Python | cov | cov | 748 | 793 | 748 | 752 | bc9808b7574bd164b6ccb83d90c7debc70ba5b48 | bigcode/the-stack | train |
f64dbf9e033184c457050dad | train | function | @derived_from(np)
def apply_over_axes(func, a, axes):
# Validate arguments
a = asarray(a)
try:
axes = tuple(axes)
except TypeError:
axes = (axes,)
sl = a.ndim * (slice(None),)
# Compute using `apply_along_axis`.
result = a
for i in axes:
result = apply_along_axi... | @derived_from(np)
def apply_over_axes(func, a, axes):
# Validate arguments
| a = asarray(a)
try:
axes = tuple(axes)
except TypeError:
axes = (axes,)
sl = a.ndim * (slice(None),)
# Compute using `apply_along_axis`.
result = a
for i in axes:
result = apply_along_axis(func, i, result, 0)
# Restore original dimensionality or error.
... | len(shape), 1)),
func1d=func1d,
func1d_axis=axis,
func1d_args=args,
func1d_kwargs=kwargs,
)
return result
@derived_from(np)
def apply_over_axes(func, a, axes):
# Validate arguments
| 64 | 64 | 176 | 20 | 43 | Pranay144/dask | dask/array/routines.py | Python | apply_over_axes | apply_over_axes | 412 | 437 | 412 | 414 | 2aa4776df66f5735a418d5520e775bc48536ad1e | bigcode/the-stack | train |
bfd070969da8111bf240a6fe | train | function | @derived_from(np)
def atleast_1d(*arys):
new_arys = []
for x in arys:
x = asanyarray(x)
if x.ndim == 0:
x = x[None]
new_arys.append(x)
if len(new_arys) == 1:
return new_arys[0]
else:
return new_arys
| @derived_from(np)
def atleast_1d(*arys):
| new_arys = []
for x in arys:
x = asanyarray(x)
if x.ndim == 0:
x = x[None]
new_arys.append(x)
if len(new_arys) == 1:
return new_arys[0]
else:
return new_arys
| x.ndim == 1:
x = x[None, :]
new_arys.append(x)
if len(new_arys) == 1:
return new_arys[0]
else:
return new_arys
@derived_from(np)
def atleast_1d(*arys):
| 64 | 64 | 85 | 13 | 50 | Pranay144/dask | dask/array/routines.py | Python | atleast_1d | atleast_1d | 97 | 110 | 97 | 98 | 1e57f248c604216cf089b4e9990e596bf4486b18 | bigcode/the-stack | train |
abe232df9f6ad3a10e9d30be | train | function | @derived_from(np)
def dot(a, b):
return tensordot(a, b, axes=((a.ndim - 1,), (b.ndim - 2,)))
| @derived_from(np)
def dot(a, b):
| return tensordot(a, b, axes=((a.ndim - 1,), (b.ndim - 2,)))
| tensordot,
out_index,
lhs,
left_index,
rhs,
right_index,
dtype=dt,
axes=(left_axes, right_axes),
)
result = intermediate.sum(axis=left_axes)
return result
@derived_from(np)
def dot(a, b):
| 64 | 64 | 38 | 11 | 52 | Pranay144/dask | dask/array/routines.py | Python | dot | dot | 278 | 280 | 278 | 279 | 21d1fc8c1f3c8a6a1d00aba10385ac2ce5d42c66 | bigcode/the-stack | train |
804a226a9807d06470d47f62 | train | function | @derived_from(np)
def argwhere(a):
a = asarray(a)
nz = isnonzero(a).flatten()
ind = indices(a.shape, dtype=np.intp, chunks=a.chunks)
if ind.ndim > 1:
ind = stack([ind[i].ravel() for i in range(len(ind))], axis=1)
ind = compress(nz, ind, axis=0)
return ind
| @derived_from(np)
def argwhere(a):
| a = asarray(a)
nz = isnonzero(a).flatten()
ind = indices(a.shape, dtype=np.intp, chunks=a.chunks)
if ind.ndim > 1:
ind = stack([ind[i].ravel() for i in range(len(ind))], axis=1)
ind = compress(nz, ind, axis=0)
return ind
| . #
# #
# xref: https://github.com/numpy/numpy/issues/9479 #
######################################################
return a.map_blocks(_isnonzero_vec, dtype=bool)
else:
return a.astype(bool)
... | 64 | 64 | 93 | 10 | 54 | Pranay144/dask | dask/array/routines.py | Python | argwhere | argwhere | 1,190 | 1,201 | 1,190 | 1,191 | fbbaceaceb2013f7b9410e0e96cbc28bc883ea6d | bigcode/the-stack | train |
e4429ec63cbe4599a824027b | train | function | @derived_from(np)
def atleast_3d(*arys):
new_arys = []
for x in arys:
x = asanyarray(x)
if x.ndim == 0:
x = x[None, None, None]
elif x.ndim == 1:
x = x[None, :, None]
elif x.ndim == 2:
x = x[:, :, None]
new_arys.append(x)
if len(n... | @derived_from(np)
def atleast_3d(*arys):
| new_arys = []
for x in arys:
x = asanyarray(x)
if x.ndim == 0:
x = x[None, None, None]
elif x.ndim == 1:
x = x[None, :, None]
elif x.ndim == 2:
x = x[:, :, None]
new_arys.append(x)
if len(new_arys) == 1:
return new_arys[0]... | x = x.astype(dtype)
return x
@derived_from(np)
def result_type(*args):
args = [a if is_scalar_for_elemwise(a) else a.dtype for a in args]
return np.result_type(*args)
@derived_from(np)
def atleast_3d(*arys):
| 64 | 64 | 125 | 13 | 51 | Pranay144/dask | dask/array/routines.py | Python | atleast_3d | atleast_3d | 59 | 76 | 59 | 60 | d71fad5fda61d0ab04ac1cea43b9992bc479118a | bigcode/the-stack | train |
7af742e281166148d81ce443 | train | function | def isnonzero(a):
try:
np.zeros(tuple(), dtype=a.dtype).astype(bool)
except ValueError:
######################################################
# Handle special cases where conversion to bool does #
# not work correctly. #
# ... | def isnonzero(a):
| try:
np.zeros(tuple(), dtype=a.dtype).astype(bool)
except ValueError:
######################################################
# Handle special cases where conversion to bool does #
# not work correctly. #
# ... | (np)
def choose(a, choices):
return elemwise(variadic_choose, a, *choices)
def _isnonzero_vec(v):
return bool(np.count_nonzero(v))
_isnonzero_vec = np.vectorize(_isnonzero_vec, otypes=[bool])
def isnonzero(a):
| 64 | 64 | 100 | 6 | 58 | Pranay144/dask | dask/array/routines.py | Python | isnonzero | isnonzero | 1,175 | 1,187 | 1,175 | 1,175 | 17f661068529e9023db542462de24ed4f6ee36b9 | bigcode/the-stack | train |
a5c41b382b24967374ec84ab | train | function | @derived_from(np)
def allclose(arr1, arr2, rtol=1e-5, atol=1e-8, equal_nan=False):
return isclose(arr1, arr2, rtol=rtol, atol=atol, equal_nan=equal_nan).all()
| @derived_from(np)
def allclose(arr1, arr2, rtol=1e-5, atol=1e-8, equal_nan=False):
| return isclose(arr1, arr2, rtol=rtol, atol=atol, equal_nan=equal_nan).all()
| =rtol, atol=atol, equal_nan=equal_nan)
return elemwise(func, arr1, arr2, dtype="bool")
@derived_from(np)
def allclose(arr1, arr2, rtol=1e-5, atol=1e-8, equal_nan=False):
| 64 | 64 | 62 | 33 | 31 | Pranay144/dask | dask/array/routines.py | Python | allclose | allclose | 1,154 | 1,156 | 1,154 | 1,155 | c654a999868faa2af527c2cc80d690ced28d0ae8 | bigcode/the-stack | train |
e71ff9aabae98ca9c12fc2ff | train | function | @derived_from(np)
def digitize(a, bins, right=False):
bins = np.asarray(bins)
dtype = np.digitize([0], bins, right=False).dtype
return a.map_blocks(np.digitize, dtype=dtype, bins=bins, right=right)
| @derived_from(np)
def digitize(a, bins, right=False):
| bins = np.asarray(bins)
dtype = np.digitize([0], bins, right=False).dtype
return a.map_blocks(np.digitize, dtype=dtype, bins=bins, right=right)
| :
chunks = ((np.nan,),)
else:
chunks = ((minlength,),)
meta = meta_from_array(x, 1, dtype=dtype)
return Array(graph, final_name, chunks, meta=meta)
@derived_from(np)
def digitize(a, bins, right=False):
| 64 | 64 | 62 | 15 | 49 | Pranay144/dask | dask/array/routines.py | Python | digitize | digitize | 631 | 635 | 631 | 632 | ba1bfd05b1b20ea86feb2519d64620f3863f7640 | bigcode/the-stack | train |
adfb75ec49a314a4dd9dc93f | train | function | @derived_from(np)
def gradient(f, *varargs, **kwargs):
f = asarray(f)
kwargs["edge_order"] = math.ceil(kwargs.get("edge_order", 1))
if kwargs["edge_order"] > 2:
raise ValueError("edge_order must be less than or equal to 2.")
drop_result_list = False
axis = kwargs.pop("axis", None)
if a... | @derived_from(np)
def gradient(f, *varargs, **kwargs):
| f = asarray(f)
kwargs["edge_order"] = math.ceil(kwargs.get("edge_order", 1))
if kwargs["edge_order"] > 2:
raise ValueError("edge_order must be less than or equal to 2.")
drop_result_list = False
axis = kwargs.pop("axis", None)
if axis is None:
axis = tuple(range(f.ndim))
el... | return r
def _gradient_kernel(x, block_id, coord, axis, array_locs, grad_kwargs):
"""
x: nd-array
array of one block
coord: 1d-array or scalar
coordinate along which the gradient is computed.
axis: int
axis along which the gradient is computed
array_locs:
actual lo... | 180 | 180 | 601 | 16 | 163 | Pranay144/dask | dask/array/routines.py | Python | gradient | gradient | 504 | 580 | 504 | 505 | 1b51994a0402bea42fdd2f64aeca13a9ed0b3b90 | bigcode/the-stack | train |
8c8fa8834d021dd641615c66 | train | function | @derived_from(np)
def matmul(a, b):
a = asanyarray(a)
b = asanyarray(b)
if a.ndim == 0 or b.ndim == 0:
raise ValueError("`matmul` does not support scalars.")
a_is_1d = False
if a.ndim == 1:
a_is_1d = True
a = a[np.newaxis, :]
b_is_1d = False
if b.ndim == 1:
... | @derived_from(np)
def matmul(a, b):
| a = asanyarray(a)
b = asanyarray(b)
if a.ndim == 0 or b.ndim == 0:
raise ValueError("`matmul` does not support scalars.")
a_is_1d = False
if a.ndim == 1:
a_is_1d = True
a = a[np.newaxis, :]
b_is_1d = False
if b.ndim == 1:
b_is_1d = True
b = b[:, np.... | _axes),
)
result = intermediate.sum(axis=left_axes)
return result
@derived_from(np)
def dot(a, b):
return tensordot(a, b, axes=((a.ndim - 1,), (b.ndim - 2,)))
@derived_from(np)
def vdot(a, b):
return dot(a.conj().ravel(), b.ravel())
@derived_from(np)
def matmul(a, b):
| 95 | 95 | 318 | 12 | 83 | Pranay144/dask | dask/array/routines.py | Python | matmul | matmul | 288 | 327 | 288 | 289 | 03f359c97fb27d7be73288f24775d76c5b580849 | bigcode/the-stack | train |
957d4953f34dca119ba79ab1 | train | function | @derived_from(np)
def flatnonzero(a):
return argwhere(asarray(a).ravel())[:, 0]
| @derived_from(np)
def flatnonzero(a):
| return argwhere(asarray(a).ravel())[:, 0]
| ).astype(dtype)
else:
return elemwise(np.where, condition, x, y)
@derived_from(np)
def count_nonzero(a, axis=None):
return isnonzero(asarray(a)).astype(np.intp).sum(axis=axis)
@derived_from(np)
def flatnonzero(a):
| 64 | 64 | 26 | 11 | 53 | Pranay144/dask | dask/array/routines.py | Python | flatnonzero | flatnonzero | 1,229 | 1,231 | 1,229 | 1,230 | f2816506a528a7a8ef2377a2e9349f8a7df2235f | bigcode/the-stack | train |
8b731d62baa923fee13c9e8d | train | function | @derived_from(np)
def array(x, dtype=None, ndmin=None):
while ndmin is not None and x.ndim < ndmin:
x = x[None, :]
if dtype is not None and x.dtype != dtype:
x = x.astype(dtype)
return x
| @derived_from(np)
def array(x, dtype=None, ndmin=None):
| while ndmin is not None and x.ndim < ndmin:
x = x[None, :]
if dtype is not None and x.dtype != dtype:
x = x.astype(dtype)
return x
| broadcast_shapes,
is_scalar_for_elemwise,
broadcast_to,
tensordot_lookup,
)
from .einsumfuncs import einsum # noqa
from .numpy_compat import _unravel_index_keyword
@derived_from(np)
def array(x, dtype=None, ndmin=None):
| 64 | 64 | 62 | 16 | 47 | Pranay144/dask | dask/array/routines.py | Python | array | array | 44 | 50 | 44 | 45 | 279a7370fda424ddb05bedbf1f1b6b76f92325ea | bigcode/the-stack | train |
5dafae07fda68646f521115b | train | function | def histogram(a, bins=None, range=None, normed=False, weights=None, density=None):
"""
Blocked variant of :func:`numpy.histogram`.
Follows the signature of :func:`numpy.histogram` exactly with the following
exceptions:
- Either an iterable specifying the ``bins`` or the number of ``bins``
an... | def histogram(a, bins=None, range=None, normed=False, weights=None, density=None):
| """
Blocked variant of :func:`numpy.histogram`.
Follows the signature of :func:`numpy.histogram` exactly with the following
exceptions:
- Either an iterable specifying the ``bins`` or the number of ``bins``
and a ``range`` argument is required as computing ``min`` and ``max``
over bloc... | weights=[1]).dtype
else:
dsk = {
(name, i): (np.bincount, (x.name, i), None, minlength)
for i, _ in enumerate(x.__dask_keys__())
}
dtype = np.bincount([]).dtype
dsk[(final_name, 0)] = (_bincount_sum, list(dsk), dtype)
graph = HighLevelGraph.from_collections(... | 256 | 256 | 961 | 20 | 236 | Pranay144/dask | dask/array/routines.py | Python | histogram | histogram | 638 | 745 | 638 | 638 | 6028844ee37214cbf3f2c18c8cf0c128b59fac50 | bigcode/the-stack | train |
84e7a16483d345450cc69ab0 | train | function | @wraps(chunk.coarsen)
def coarsen(reduction, x, axes, trim_excess=False):
if not trim_excess and not all(
bd % div == 0 for i, div in axes.items() for bd in x.chunks[i]
):
msg = "Coarsening factor does not align with block dimensions"
raise ValueError(msg)
if "dask" in inspect.getfi... | @wraps(chunk.coarsen)
def coarsen(reduction, x, axes, trim_excess=False):
| if not trim_excess and not all(
bd % div == 0 for i, div in axes.items() for bd in x.chunks[i]
):
msg = "Coarsening factor does not align with block dimensions"
raise ValueError(msg)
if "dask" in inspect.getfile(reduction):
reduction = getattr(np, reduction.__name__)
na... | ):
return map_blocks(
_int_piecewise,
x,
*condlist,
dtype=x.dtype,
name="piecewise",
funclist=funclist,
func_args=args,
func_kw=kw
)
@wraps(chunk.coarsen)
def coarsen(reduction, x, axes, trim_excess=False):
| 77 | 77 | 257 | 24 | 53 | Pranay144/dask | dask/array/routines.py | Python | coarsen | coarsen | 1,286 | 1,308 | 1,286 | 1,287 | 1fc69f0ccbe9c91e48b1d0363bf3cb9d47c060f7 | bigcode/the-stack | train |
737b11a8bab49f4c971d3fad | train | function | @derived_from(np)
def atleast_2d(*arys):
new_arys = []
for x in arys:
x = asanyarray(x)
if x.ndim == 0:
x = x[None, None]
elif x.ndim == 1:
x = x[None, :]
new_arys.append(x)
if len(new_arys) == 1:
return new_arys[0]
else:
return n... | @derived_from(np)
def atleast_2d(*arys):
| new_arys = []
for x in arys:
x = asanyarray(x)
if x.ndim == 0:
x = x[None, None]
elif x.ndim == 1:
x = x[None, :]
new_arys.append(x)
if len(new_arys) == 1:
return new_arys[0]
else:
return new_arys
| elif x.ndim == 2:
x = x[:, :, None]
new_arys.append(x)
if len(new_arys) == 1:
return new_arys[0]
else:
return new_arys
@derived_from(np)
def atleast_2d(*arys):
| 64 | 64 | 105 | 13 | 50 | Pranay144/dask | dask/array/routines.py | Python | atleast_2d | atleast_2d | 79 | 94 | 79 | 80 | 4f6f130364f95e68c3ebd799a47ff6f81bad34cf | bigcode/the-stack | train |
2bfe097b06d5ffab06460040 | train | function | @derived_from(np)
def roll(array, shift, axis=None):
result = array
if axis is None:
result = ravel(result)
if not isinstance(shift, Integral):
raise TypeError(
"Expect `shift` to be an instance of Integral" " when `axis` is None."
)
shift = (sh... | @derived_from(np)
def roll(array, shift, axis=None):
| result = array
if axis is None:
result = ravel(result)
if not isinstance(shift, Integral):
raise TypeError(
"Expect `shift` to be an instance of Integral" " when `axis` is None."
)
shift = (shift,)
axis = (0,)
else:
try:
... | _axes,
test_elements,
test_axes,
adjust_chunks={axis: lambda _: 1 for axis in test_axes},
dtype=bool,
assume_unique=assume_unique,
)
result = mapped.any(axis=test_axes)
if invert:
result = ~result
return result
@derived_from(np)
def roll(array, shift, axi... | 78 | 78 | 263 | 14 | 63 | Pranay144/dask | dask/array/routines.py | Python | roll | roll | 995 | 1,039 | 995 | 996 | eaab189385f147c659891837073b2105f07e6b0c | bigcode/the-stack | train |
5d03154aa69cf7135919bb21 | train | function | def _unique_internal(ar, indices, counts, return_inverse=False):
"""
Helper/wrapper function for :func:`numpy.unique`.
Uses :func:`numpy.unique` to find the unique values for the array chunk.
Given this chunk may not represent the whole array, also take the
``indices`` and ``counts`` that are in 1-... | def _unique_internal(ar, indices, counts, return_inverse=False):
| """
Helper/wrapper function for :func:`numpy.unique`.
Uses :func:`numpy.unique` to find the unique values for the array chunk.
Given this chunk may not represent the whole array, also take the
``indices`` and ``counts`` that are in 1-to-1 correspondence to ``ar``
and reduce them in the same fas... | 1 - axis, keepdims=True)
if not rowvar:
return (dot(X.T, X.conj()) / fact).squeeze()
else:
return (dot(X, X.T.conj()) / fact).squeeze()
@derived_from(np)
def corrcoef(x, y=None, rowvar=1):
c = cov(x, y, rowvar)
if c.shape == ():
return c / c
d = diag(c)
d = d.reshape((d... | 180 | 180 | 601 | 14 | 166 | Pranay144/dask | dask/array/routines.py | Python | _unique_internal | _unique_internal | 812 | 870 | 812 | 812 | 77c2939ee25ddd6f258e5a8be1df456eb2f216e8 | bigcode/the-stack | train |
02ad29ce2ddd4770129de725 | train | function | @derived_from(np)
def vstack(tup, allow_unknown_chunksizes=False):
tup = tuple(atleast_2d(x) for x in tup)
return concatenate(tup, axis=0, allow_unknown_chunksizes=allow_unknown_chunksizes)
| @derived_from(np)
def vstack(tup, allow_unknown_chunksizes=False):
| tup = tuple(atleast_2d(x) for x in tup)
return concatenate(tup, axis=0, allow_unknown_chunksizes=allow_unknown_chunksizes)
| im == 0:
x = x[None]
new_arys.append(x)
if len(new_arys) == 1:
return new_arys[0]
else:
return new_arys
@derived_from(np)
def vstack(tup, allow_unknown_chunksizes=False):
| 64 | 64 | 53 | 17 | 46 | Pranay144/dask | dask/array/routines.py | Python | vstack | vstack | 113 | 116 | 113 | 114 | 987c4c14dd345d32bde29bc47901f7df104c70cd | bigcode/the-stack | train |
60ae0795ea2df7bbeb8fa8ec | train | function | @derived_from(np)
def swapaxes(a, axis1, axis2):
if axis1 == axis2:
return a
if axis1 < 0:
axis1 = axis1 + a.ndim
if axis2 < 0:
axis2 = axis2 + a.ndim
ind = list(range(a.ndim))
out = list(ind)
out[axis1], out[axis2] = axis2, axis1
return blockwise(np.swapaxes, out, a... | @derived_from(np)
def swapaxes(a, axis1, axis2):
| if axis1 == axis2:
return a
if axis1 < 0:
axis1 = axis1 + a.ndim
if axis2 < 0:
axis2 = axis2 + a.ndim
ind = list(range(a.ndim))
out = list(ind)
out[axis1], out[axis2] = axis2, axis1
return blockwise(np.swapaxes, out, a, ind, axis1=axis1, axis2=axis2, dtype=a.dtype)
| def dstack(tup, allow_unknown_chunksizes=False):
tup = tuple(atleast_3d(x) for x in tup)
return concatenate(tup, axis=2, allow_unknown_chunksizes=allow_unknown_chunksizes)
@derived_from(np)
def swapaxes(a, axis1, axis2):
| 64 | 64 | 129 | 16 | 48 | Pranay144/dask | dask/array/routines.py | Python | swapaxes | swapaxes | 137 | 149 | 137 | 138 | f9c9e5dff5e2c2217c4fb3450b470db15e9b545b | bigcode/the-stack | train |
0c08761e5090a7efb8a3f93b | train | function | @derived_from(np)
def squeeze(a, axis=None):
if axis is None:
axis = tuple(i for i, d in enumerate(a.shape) if d == 1)
elif not isinstance(axis, tuple):
axis = (axis,)
if any(a.shape[i] != 1 for i in axis):
raise ValueError("cannot squeeze axis with size other than one")
axis =... | @derived_from(np)
def squeeze(a, axis=None):
| if axis is None:
axis = tuple(i for i, d in enumerate(a.shape) if d == 1)
elif not isinstance(axis, tuple):
axis = (axis,)
if any(a.shape[i] != 1 for i in axis):
raise ValueError("cannot squeeze axis with size other than one")
axis = validate_axis(axis, a.ndim)
sl = tuple(... | tuple(sl2)
result = concatenate([result[sl1], result[sl2]], axis=i)
result = result.reshape(array.shape)
return result
@derived_from(np)
def ravel(array):
return array.reshape((-1,))
@derived_from(np)
def squeeze(a, axis=None):
| 63 | 64 | 127 | 12 | 52 | Pranay144/dask | dask/array/routines.py | Python | squeeze | squeeze | 1,047 | 1,063 | 1,047 | 1,048 | 667060be2ed1b43e5aec849bbb822ed78b7d712d | bigcode/the-stack | train |
77641ce35f1ab24bb3b5cae3 | train | function | def _unravel_index_kernel(indices, func_kwargs):
return np.stack(np.unravel_index(indices, **func_kwargs))
| def _unravel_index_kernel(indices, func_kwargs):
| return np.stack(np.unravel_index(indices, **func_kwargs))
| (ind,)
def _int_piecewise(x, *condlist, **kwargs):
return np.piecewise(
x, list(condlist), kwargs["funclist"], *kwargs["func_args"], **kwargs["func_kw"]
)
def _unravel_index_kernel(indices, func_kwargs):
| 64 | 64 | 27 | 12 | 52 | Pranay144/dask | dask/array/routines.py | Python | _unravel_index_kernel | _unravel_index_kernel | 1,249 | 1,250 | 1,249 | 1,249 | 3645b0e5e951521e87ca91135b941930ac362dec | bigcode/the-stack | train |
3d274238e8ebb4c4e480b27b | train | function | @derived_from(np)
def hstack(tup, allow_unknown_chunksizes=False):
if all(x.ndim == 1 for x in tup):
return concatenate(
tup, axis=0, allow_unknown_chunksizes=allow_unknown_chunksizes
)
else:
return concatenate(
tup, axis=1, allow_unknown_chunksizes=allow_unknown_... | @derived_from(np)
def hstack(tup, allow_unknown_chunksizes=False):
| if all(x.ndim == 1 for x in tup):
return concatenate(
tup, axis=0, allow_unknown_chunksizes=allow_unknown_chunksizes
)
else:
return concatenate(
tup, axis=1, allow_unknown_chunksizes=allow_unknown_chunksizes
)
| vstack(tup, allow_unknown_chunksizes=False):
tup = tuple(atleast_2d(x) for x in tup)
return concatenate(tup, axis=0, allow_unknown_chunksizes=allow_unknown_chunksizes)
@derived_from(np)
def hstack(tup, allow_unknown_chunksizes=False):
| 64 | 64 | 80 | 17 | 47 | Pranay144/dask | dask/array/routines.py | Python | hstack | hstack | 119 | 128 | 119 | 120 | 7385b2a6d7c71c1790b220125d779388d15fa2d1 | bigcode/the-stack | train |
1dc7ca3c7d255fb93ba2a283 | train | function | @derived_from(np)
def around(x, decimals=0):
return map_blocks(partial(np.around, decimals=decimals), x, dtype=x.dtype)
| @derived_from(np)
def around(x, decimals=0):
| return map_blocks(partial(np.around, decimals=decimals), x, dtype=x.dtype)
| (a, indices, axis):
assert isinstance(a, np.ndarray)
assert isinstance(indices, Array)
return indices.map_blocks(
lambda block: np.take(a, block, axis), chunks=indices.chunks, dtype=a.dtype
)
@derived_from(np)
def around(x, decimals=0):
| 64 | 64 | 34 | 13 | 51 | Pranay144/dask | dask/array/routines.py | Python | around | around | 1,124 | 1,126 | 1,124 | 1,125 | 7a4ffaf0c0dd73717b9793af004270d7e0f0bd88 | bigcode/the-stack | train |
db037176975ff967fd079f10 | train | function | @derived_from(np)
def count_nonzero(a, axis=None):
return isnonzero(asarray(a)).astype(np.intp).sum(axis=axis)
| @derived_from(np)
def count_nonzero(a, axis=None):
| return isnonzero(asarray(a)).astype(np.intp).sum(axis=axis)
| array(y)
shape = broadcast_shapes(x.shape, y.shape)
out = x if condition else y
return broadcast_to(out, shape).astype(dtype)
else:
return elemwise(np.where, condition, x, y)
@derived_from(np)
def count_nonzero(a, axis=None):
| 64 | 64 | 33 | 14 | 50 | Pranay144/dask | dask/array/routines.py | Python | count_nonzero | count_nonzero | 1,224 | 1,226 | 1,224 | 1,225 | 87b19784c44c44e1150d3f245abbc81e1d6be166 | bigcode/the-stack | train |
d2a6a0bd4fe3d5dfd9da9361 | train | function | def _bincount_sum(bincounts, dtype=int):
n = max(map(len, bincounts))
out = zeros_like_safe(bincounts[0], shape=n, dtype=dtype)
for b in bincounts:
out[: len(b)] += b
return out
| def _bincount_sum(bincounts, dtype=int):
| n = max(map(len, bincounts))
out = zeros_like_safe(bincounts[0], shape=n, dtype=dtype)
for b in bincounts:
out[: len(b)] += b
return out
| boundary="none",
coord=varargs[i],
axis=ax,
array_locs=array_locs,
grad_kwargs=kwargs,
)
)
if drop_result_list:
results = results[0]
return results
def _bincount_sum(bincounts, dtype=int):
| 64 | 64 | 66 | 14 | 49 | Pranay144/dask | dask/array/routines.py | Python | _bincount_sum | _bincount_sum | 583 | 588 | 583 | 583 | 50d42fd8bde5bf11f3a1e121d1a233ec5e1defe4 | bigcode/the-stack | train |
e893ea43d7111c43ac08b863 | train | function | @derived_from(np)
def ediff1d(ary, to_end=None, to_begin=None):
ary = asarray(ary)
aryf = ary.flatten()
r = aryf[1:] - aryf[:-1]
r = [r]
if to_begin is not None:
r = [asarray(to_begin).flatten()] + r
if to_end is not None:
r = r + [asarray(to_end).flatten()]
r = concatenate... | @derived_from(np)
def ediff1d(ary, to_end=None, to_begin=None):
| ary = asarray(ary)
aryf = ary.flatten()
r = aryf[1:] - aryf[:-1]
r = [r]
if to_begin is not None:
r = [asarray(to_begin).flatten()] + r
if to_end is not None:
r = r + [asarray(to_end).flatten()]
r = concatenate(r)
return r
| )
sl_2 = tuple(sl_2)
r = a
for i in range(n):
r = r[sl_1] - r[sl_2]
return r
@derived_from(np)
def ediff1d(ary, to_end=None, to_begin=None):
| 64 | 64 | 109 | 21 | 42 | Pranay144/dask | dask/array/routines.py | Python | ediff1d | ediff1d | 467 | 481 | 467 | 468 | 5575314e43ca2a4f17545521191c3be4d629125e | bigcode/the-stack | train |
439a2dbbc7379db45617b99f | train | function | @derived_from(np)
def outer(a, b):
a = a.flatten()
b = b.flatten()
dtype = np.outer(a.dtype.type(), b.dtype.type()).dtype
return blockwise(np.outer, "ij", a, "i", b, "j", dtype=dtype)
| @derived_from(np)
def outer(a, b):
| a = a.flatten()
b = b.flatten()
dtype = np.outer(a.dtype.type(), b.dtype.type()).dtype
return blockwise(np.outer, "ij", a, "i", b, "j", dtype=dtype)
| im),
dtype=result_type(a, b),
concatenate=True,
)
if a_is_1d:
out = out[..., 0, :]
if b_is_1d:
out = out[..., 0]
return out
@derived_from(np)
def outer(a, b):
| 64 | 64 | 62 | 11 | 52 | Pranay144/dask | dask/array/routines.py | Python | outer | outer | 330 | 337 | 330 | 331 | e3471362c3be48dd7bdd4a7ffefb604633d52fe0 | bigcode/the-stack | train |
f08d5c4c7d0cc3e37a49da8a | train | function | @derived_from(np)
def choose(a, choices):
return elemwise(variadic_choose, a, *choices)
| @derived_from(np)
def choose(a, choices):
| return elemwise(variadic_choose, a, *choices)
| -8, equal_nan=False):
return isclose(arr1, arr2, rtol=rtol, atol=atol, equal_nan=equal_nan).all()
def variadic_choose(a, *choices):
return np.choose(a, choices)
@derived_from(np)
def choose(a, choices):
| 64 | 64 | 25 | 11 | 53 | Pranay144/dask | dask/array/routines.py | Python | choose | choose | 1,163 | 1,165 | 1,163 | 1,164 | fbb8e523000b1b68003b6de8abf0feb5fb0cdd7a | bigcode/the-stack | train |
5a1dc8afc3a4a16add1881e1 | train | function | @derived_from(np)
def diff(a, n=1, axis=-1):
a = asarray(a)
n = int(n)
axis = int(axis)
sl_1 = a.ndim * [slice(None)]
sl_2 = a.ndim * [slice(None)]
sl_1[axis] = slice(1, None)
sl_2[axis] = slice(None, -1)
sl_1 = tuple(sl_1)
sl_2 = tuple(sl_2)
r = a
for i in range(n):
... | @derived_from(np)
def diff(a, n=1, axis=-1):
| a = asarray(a)
n = int(n)
axis = int(axis)
sl_1 = a.ndim * [slice(None)]
sl_2 = a.ndim * [slice(None)]
sl_1[axis] = slice(1, None)
sl_2[axis] = slice(None, -1)
sl_1 = tuple(sl_1)
sl_2 = tuple(sl_2)
r = a
for i in range(n):
r = r[sl_1] - r[sl_2]
return r
| ity of the input"
" or reduce it by one."
)
return result
@derived_from(np)
def ptp(a, axis=None):
return a.max(axis=axis) - a.min(axis=axis)
@derived_from(np)
def diff(a, n=1, axis=-1):
| 64 | 64 | 142 | 17 | 47 | Pranay144/dask | dask/array/routines.py | Python | diff | diff | 445 | 464 | 445 | 446 | 3c5ac908c392ada175f1c67d7450154123a52865 | bigcode/the-stack | train |
2dece060c5eee004b7cbd4eb | train | function | @derived_from(np)
def vdot(a, b):
return dot(a.conj().ravel(), b.ravel())
| @derived_from(np)
def vdot(a, b):
| return dot(a.conj().ravel(), b.ravel())
| result = intermediate.sum(axis=left_axes)
return result
@derived_from(np)
def dot(a, b):
return tensordot(a, b, axes=((a.ndim - 1,), (b.ndim - 2,)))
@derived_from(np)
def vdot(a, b):
| 63 | 64 | 26 | 12 | 51 | Pranay144/dask | dask/array/routines.py | Python | vdot | vdot | 283 | 285 | 283 | 284 | 77b492fb56a678ec2ec26b2af201a73e46bbb077 | bigcode/the-stack | train |
17e3f9f991af743df5f7df22 | train | function | def _inner_apply_along_axis(arr, func1d, func1d_axis, func1d_args, func1d_kwargs):
return np.apply_along_axis(func1d, func1d_axis, arr, *func1d_args, **func1d_kwargs)
| def _inner_apply_along_axis(arr, func1d, func1d_axis, func1d_args, func1d_kwargs):
| return np.apply_along_axis(func1d, func1d_axis, arr, *func1d_args, **func1d_kwargs)
| np.outer(a.dtype.type(), b.dtype.type()).dtype
return blockwise(np.outer, "ij", a, "i", b, "j", dtype=dtype)
def _inner_apply_along_axis(arr, func1d, func1d_axis, func1d_args, func1d_kwargs):
| 64 | 64 | 58 | 28 | 36 | Pranay144/dask | dask/array/routines.py | Python | _inner_apply_along_axis | _inner_apply_along_axis | 340 | 341 | 340 | 340 | 0e2819d0b0b40a7ff08143f2a7ca306e31b4cc2b | bigcode/the-stack | train |
01a210746b14a218d28934fe | train | function | @derived_from(np)
def insert(arr, obj, values, axis):
# axis is a required argument here to avoid needing to deal with the numpy
# default case (which reshapes the array to make it flat)
axis = validate_axis(axis, arr.ndim)
if isinstance(obj, slice):
obj = np.arange(*obj.indices(arr.shape[axis]... | @derived_from(np)
def insert(arr, obj, values, axis):
# axis is a required argument here to avoid needing to deal with the numpy
# default case (which reshapes the array to make it flat)
| axis = validate_axis(axis, arr.ndim)
if isinstance(obj, slice):
obj = np.arange(*obj.indices(arr.shape[axis]))
obj = np.asarray(obj)
scalar_obj = obj.ndim == 0
if scalar_obj:
obj = np.atleast_1d(obj)
obj = np.where(obj < 0, obj + arr.shape[axis], obj)
if (np.diff(obj) < 0).... | ]), array([3, 4]), array([5])]
"""
padded_breaks = concat([[None], breaks, [None]])
slices = [slice(i, j) for i, j in sliding_window(2, padded_breaks)]
preslice = (slice(None),) * axis
split_array = [array[preslice + (s,)] for s in slices]
return split_array
@derived_from(np)
def insert(arr, obj... | 134 | 134 | 449 | 47 | 86 | Pranay144/dask | dask/array/routines.py | Python | insert | insert | 1,324 | 1,370 | 1,324 | 1,327 | 51e73ef73c568832a4eac0e11dccdae024362280 | bigcode/the-stack | train |
923c3828ebc439197d2020ac | train | function | @derived_from(np)
def ravel(array):
return array.reshape((-1,))
| @derived_from(np)
def ravel(array):
| return array.reshape((-1,))
| [i] = slice(None, s)
sl1 = tuple(sl1)
sl2 = tuple(sl2)
result = concatenate([result[sl1], result[sl2]], axis=i)
result = result.reshape(array.shape)
return result
@derived_from(np)
def ravel(array):
| 64 | 64 | 17 | 10 | 53 | Pranay144/dask | dask/array/routines.py | Python | ravel | ravel | 1,042 | 1,044 | 1,042 | 1,043 | 5f0c00471f817fe0813115babbc9772386a03f39 | bigcode/the-stack | train |
ace466635991765e1b2d506b | train | function | @derived_from(np)
def unique(ar, return_index=False, return_inverse=False, return_counts=False):
ar = ar.ravel()
# Run unique on each chunk and collect results in a Dask Array of
# unknown size.
args = [ar, "i"]
out_dtype = [("values", ar.dtype)]
if return_index:
args.extend([arange(ar... | @derived_from(np)
def unique(ar, return_index=False, return_inverse=False, return_counts=False):
| ar = ar.ravel()
# Run unique on each chunk and collect results in a Dask Array of
# unknown size.
args = [ar, "i"]
out_dtype = [("values", ar.dtype)]
if return_index:
args.extend([arange(ar.shape[0], dtype=np.intp, chunks=ar.chunks[0]), "i"])
out_dtype.append(("indices", np.int... | using this strategy.
"""
return_index = indices is not None
return_counts = counts is not None
u = np.unique(ar)
dt = [("values", u.dtype)]
if return_index:
dt.append(("indices", np.intp))
if return_inverse:
dt.append(("inverse", np.intp))
if return_counts:
dt... | 233 | 233 | 778 | 21 | 211 | Pranay144/dask | dask/array/routines.py | Python | unique | unique | 873 | 963 | 873 | 874 | c6b3c729dd68586273221db0be81e39035ed9064 | bigcode/the-stack | train |
1e119768697eca0fb28695dc | train | function | def isnull(values):
""" pandas.isnull for dask arrays """
# eagerly raise ImportError, if pandas isn't available
import pandas as pd # noqa
return elemwise(_asarray_isnull, values, dtype="bool")
| def isnull(values):
| """ pandas.isnull for dask arrays """
# eagerly raise ImportError, if pandas isn't available
import pandas as pd # noqa
return elemwise(_asarray_isnull, values, dtype="bool")
| )
@derived_from(np)
def around(x, decimals=0):
return map_blocks(partial(np.around, decimals=decimals), x, dtype=x.dtype)
def _asarray_isnull(values):
import pandas as pd
return np.asarray(pd.isnull(values))
def isnull(values):
| 64 | 64 | 52 | 5 | 59 | Pranay144/dask | dask/array/routines.py | Python | isnull | isnull | 1,135 | 1,140 | 1,135 | 1,135 | 5255da9b7803233f8ce993d3497378f126230930 | bigcode/the-stack | train |
397388e8951765b43dc166c1 | train | function | def notnull(values):
""" pandas.notnull for dask arrays """
return ~isnull(values)
| def notnull(values):
| """ pandas.notnull for dask arrays """
return ~isnull(values)
| np.asarray(pd.isnull(values))
def isnull(values):
""" pandas.isnull for dask arrays """
# eagerly raise ImportError, if pandas isn't available
import pandas as pd # noqa
return elemwise(_asarray_isnull, values, dtype="bool")
def notnull(values):
| 64 | 64 | 22 | 5 | 59 | Pranay144/dask | dask/array/routines.py | Python | notnull | notnull | 1,143 | 1,145 | 1,143 | 1,143 | a3cc6b7e72c3b40cb5b637cdfc7e5edfcec3e577 | bigcode/the-stack | train |
b43ae9787ae41d4aec5e8f8f | train | function | def _tensordot(a, b, axes):
x = max([a, b], key=lambda x: x.__array_priority__)
tensordot = tensordot_lookup.dispatch(type(x))
# workaround may be removed when numpy version (currently 1.13.0) is bumped
a_dims = np.array([a.shape[i] for i in axes[0]])
b_dims = np.array([b.shape[i] for i in axes[1]]... | def _tensordot(a, b, axes):
| x = max([a, b], key=lambda x: x.__array_priority__)
tensordot = tensordot_lookup.dispatch(type(x))
# workaround may be removed when numpy version (currently 1.13.0) is bumped
a_dims = np.array([a.shape[i] for i in axes[0]])
b_dims = np.array([b.shape[i] for i in axes[1]])
if (
len(a_dim... | (m.ndim))
)
sl = tuple(sl)
return m[sl]
@derived_from(np)
def flipud(m):
return flip(m, 0)
@derived_from(np)
def fliplr(m):
return flip(m, 1)
alphabet = "abcdefghijklmnopqrstuvwxyz"
ALPHABET = alphabet.upper()
def _tensordot(a, b, axes):
| 79 | 79 | 265 | 12 | 67 | Pranay144/dask | dask/array/routines.py | Python | _tensordot | _tensordot | 207 | 233 | 207 | 207 | de574799bd8bfb5384f182f8b61c62eebf217e28 | bigcode/the-stack | train |
a71e1fe8e8265a8d93fdc384 | train | function | def _asarray_isnull(values):
import pandas as pd
return np.asarray(pd.isnull(values))
| def _asarray_isnull(values):
| import pandas as pd
return np.asarray(pd.isnull(values))
| block: np.take(a, block, axis), chunks=indices.chunks, dtype=a.dtype
)
@derived_from(np)
def around(x, decimals=0):
return map_blocks(partial(np.around, decimals=decimals), x, dtype=x.dtype)
def _asarray_isnull(values):
| 64 | 64 | 23 | 8 | 56 | Pranay144/dask | dask/array/routines.py | Python | _asarray_isnull | _asarray_isnull | 1,129 | 1,132 | 1,129 | 1,129 | 41eba1d537e30cf815779966158724a0a3789913 | bigcode/the-stack | train |
f65e6b5d49813af67bb6fef0 | train | function | @derived_from(np)
def fliplr(m):
return flip(m, 1)
| @derived_from(np)
def fliplr(m):
| return flip(m, 1)
| ` of %s invalid for %s-D array" % (str(axis), str(m.ndim))
)
sl = tuple(sl)
return m[sl]
@derived_from(np)
def flipud(m):
return flip(m, 0)
@derived_from(np)
def fliplr(m):
| 64 | 64 | 19 | 11 | 53 | Pranay144/dask | dask/array/routines.py | Python | fliplr | fliplr | 198 | 200 | 198 | 199 | bbbf610dea980c0c916d9c11fc9f45a0f0c63f03 | bigcode/the-stack | train |
84af7c895c8ce08ec9de0ae3 | train | function | @derived_from(np)
def tensordot(lhs, rhs, axes=2):
if isinstance(axes, Iterable):
left_axes, right_axes = axes
else:
left_axes = tuple(range(lhs.ndim - 1, lhs.ndim - axes - 1, -1))
right_axes = tuple(range(0, axes))
if isinstance(left_axes, Integral):
left_axes = (left_axes,... | @derived_from(np)
def tensordot(lhs, rhs, axes=2):
| if isinstance(axes, Iterable):
left_axes, right_axes = axes
else:
left_axes = tuple(range(lhs.ndim - 1, lhs.ndim - axes - 1, -1))
right_axes = tuple(range(0, axes))
if isinstance(left_axes, Integral):
left_axes = (left_axes,)
if isinstance(right_axes, Integral):
... | [1]]
)
)
else:
x = tensordot(a, b, axes=axes)
ind = [slice(None, None)] * x.ndim
for a in sorted(axes[0]):
ind.insert(a, None)
x = x[tuple(ind)]
return x
@derived_from(np)
def tensordot(lhs, rhs, axes=2):
| 84 | 84 | 280 | 17 | 66 | Pranay144/dask | dask/array/routines.py | Python | tensordot | tensordot | 236 | 275 | 236 | 237 | 78e0239f4ab26cd4d87c198e58a387d8cec1052b | bigcode/the-stack | train |
64caf8726fc499d34b64265b | train | function | @derived_from(np)
def where(condition, x=None, y=None):
if (x is None) != (y is None):
raise ValueError("either both or neither of x and y should be given")
if (x is None) and (y is None):
return nonzero(condition)
if np.isscalar(condition):
dtype = result_type(x, y)
x = asa... | @derived_from(np)
def where(condition, x=None, y=None):
| if (x is None) != (y is None):
raise ValueError("either both or neither of x and y should be given")
if (x is None) and (y is None):
return nonzero(condition)
if np.isscalar(condition):
dtype = result_type(x, y)
x = asarray(x)
y = asarray(y)
shape = broadcas... | if ind.ndim > 1:
ind = stack([ind[i].ravel() for i in range(len(ind))], axis=1)
ind = compress(nz, ind, axis=0)
return ind
@derived_from(np)
def where(condition, x=None, y=None):
| 64 | 64 | 142 | 15 | 48 | Pranay144/dask | dask/array/routines.py | Python | where | where | 1,204 | 1,221 | 1,204 | 1,205 | e07e79a6cba540be1396a8000f2d4638d9692a4a | bigcode/the-stack | train |
8fc7e72a8c707068aa3a29b1 | train | function | def _gradient_kernel(x, block_id, coord, axis, array_locs, grad_kwargs):
"""
x: nd-array
array of one block
coord: 1d-array or scalar
coordinate along which the gradient is computed.
axis: int
axis along which the gradient is computed
array_locs:
actual location along... | def _gradient_kernel(x, block_id, coord, axis, array_locs, grad_kwargs):
| """
x: nd-array
array of one block
coord: 1d-array or scalar
coordinate along which the gradient is computed.
axis: int
axis along which the gradient is computed
array_locs:
actual location along axis. None if coordinate is scalar
grad_kwargs:
keyword to b... | r = [asarray(to_begin).flatten()] + r
if to_end is not None:
r = r + [asarray(to_end).flatten()]
r = concatenate(r)
return r
def _gradient_kernel(x, block_id, coord, axis, array_locs, grad_kwargs):
| 64 | 64 | 161 | 20 | 43 | Pranay144/dask | dask/array/routines.py | Python | _gradient_kernel | _gradient_kernel | 484 | 501 | 484 | 484 | 6a1181a3c9d0186fd80c9c847de84819ba707ad3 | bigcode/the-stack | train |
5c792f4632ddfc1ee929724e | train | function | @derived_from(np)
def flipud(m):
return flip(m, 0)
| @derived_from(np)
def flipud(m):
| return flip(m, 0)
| , None, -1)
except IndexError:
raise ValueError(
"`axis` of %s invalid for %s-D array" % (str(axis), str(m.ndim))
)
sl = tuple(sl)
return m[sl]
@derived_from(np)
def flipud(m):
| 64 | 64 | 18 | 10 | 54 | Pranay144/dask | dask/array/routines.py | Python | flipud | flipud | 193 | 195 | 193 | 194 | 40950b001e6c7aad211007e390b16da19a943d1c | bigcode/the-stack | train |
07d347503a9194defb9ac699 | train | function | @derived_from(np)
def nonzero(a):
ind = argwhere(a)
if ind.ndim > 1:
return tuple(ind[:, i] for i in range(ind.shape[1]))
else:
return (ind,)
| @derived_from(np)
def nonzero(a):
| ind = argwhere(a)
if ind.ndim > 1:
return tuple(ind[:, i] for i in range(ind.shape[1]))
else:
return (ind,)
| def count_nonzero(a, axis=None):
return isnonzero(asarray(a)).astype(np.intp).sum(axis=axis)
@derived_from(np)
def flatnonzero(a):
return argwhere(asarray(a).ravel())[:, 0]
@derived_from(np)
def nonzero(a):
| 64 | 64 | 50 | 10 | 54 | Pranay144/dask | dask/array/routines.py | Python | nonzero | nonzero | 1,234 | 1,240 | 1,234 | 1,235 | fad6475829a0a1a2bd9f48efb01cf52ac95eee0f | bigcode/the-stack | train |
cf1b074b93890f8983c3989c | train | function | @derived_from(np)
def transpose(a, axes=None):
if axes:
if len(axes) != a.ndim:
raise ValueError("axes don't match array")
else:
axes = tuple(range(a.ndim))[::-1]
axes = tuple(d + a.ndim if d < 0 else d for d in axes)
return blockwise(
np.transpose, axes, a, tuple(ran... | @derived_from(np)
def transpose(a, axes=None):
| if axes:
if len(axes) != a.ndim:
raise ValueError("axes don't match array")
else:
axes = tuple(range(a.ndim))[::-1]
axes = tuple(d + a.ndim if d < 0 else d for d in axes)
return blockwise(
np.transpose, axes, a, tuple(range(a.ndim)), dtype=a.dtype, axes=axes
)
| = list(ind)
out[axis1], out[axis2] = axis2, axis1
return blockwise(np.swapaxes, out, a, ind, axis1=axis1, axis2=axis2, dtype=a.dtype)
@derived_from(np)
def transpose(a, axes=None):
| 64 | 64 | 102 | 12 | 52 | Pranay144/dask | dask/array/routines.py | Python | transpose | transpose | 152 | 162 | 152 | 153 | 0ae1acf496f393f7b9d4fadc0f9e156d2acda03f | bigcode/the-stack | train |
b65fd5a085312a4e1d98f71f | train | function | @derived_from(np)
def corrcoef(x, y=None, rowvar=1):
c = cov(x, y, rowvar)
if c.shape == ():
return c / c
d = diag(c)
d = d.reshape((d.shape[0], 1))
sqr_d = sqrt(d)
return (c / sqr_d) / sqr_d.T
| @derived_from(np)
def corrcoef(x, y=None, rowvar=1):
| c = cov(x, y, rowvar)
if c.shape == ():
return c / c
d = diag(c)
d = d.reshape((d.shape[0], 1))
sqr_d = sqrt(d)
return (c / sqr_d) / sqr_d.T
| dims=True)
if not rowvar:
return (dot(X.T, X.conj()) / fact).squeeze()
else:
return (dot(X, X.T.conj()) / fact).squeeze()
@derived_from(np)
def corrcoef(x, y=None, rowvar=1):
| 64 | 64 | 85 | 18 | 46 | Pranay144/dask | dask/array/routines.py | Python | corrcoef | corrcoef | 796 | 804 | 796 | 797 | b04ada6d6708c1b5892c395a468ed53daef634d1 | bigcode/the-stack | train |
4ef110449d8c188d6e07f460 | train | function | @derived_from(np)
def compress(condition, a, axis=None):
if not is_arraylike(condition):
# Allow `condition` to be anything array-like, otherwise ensure `condition`
# is a numpy array.
condition = np.asarray(condition)
condition = condition.astype(bool)
a = asarray(a)
if condit... | @derived_from(np)
def compress(condition, a, axis=None):
| if not is_arraylike(condition):
# Allow `condition` to be anything array-like, otherwise ensure `condition`
# is a numpy array.
condition = np.asarray(condition)
condition = condition.astype(bool)
a = asarray(a)
if condition.ndim != 1:
raise ValueError("Condition must be... | size other than one")
axis = validate_axis(axis, a.ndim)
sl = tuple(0 if i in axis else slice(None) for i, s in enumerate(a.shape))
a = a[sl]
return a
@derived_from(np)
def compress(condition, a, axis=None):
| 64 | 64 | 213 | 14 | 49 | Pranay144/dask | dask/array/routines.py | Python | compress | compress | 1,066 | 1,095 | 1,066 | 1,068 | f07ed9c214b8332bf09170ae2b51f0f288cc2cc4 | bigcode/the-stack | train |
1e0bffc899ec2fbdc5593402 | train | function | @derived_from(np)
def take(a, indices, axis=0):
axis = validate_axis(axis, a.ndim)
if isinstance(a, np.ndarray) and isinstance(indices, Array):
return _take_dask_array_from_numpy(a, indices, axis)
else:
return a[(slice(None),) * axis + (indices,)]
| @derived_from(np)
def take(a, indices, axis=0):
| axis = validate_axis(axis, a.ndim)
if isinstance(a, np.ndarray) and isinstance(indices, Array):
return _take_dask_array_from_numpy(a, indices, axis)
else:
return a[(slice(None),) * axis + (indices,)]
| range(a.ndim))]
return a
@derived_from(np)
def extract(condition, arr):
condition = asarray(condition).astype(bool)
arr = asarray(arr)
return compress(condition.ravel(), arr.ravel())
@derived_from(np)
def take(a, indices, axis=0):
| 64 | 64 | 73 | 15 | 49 | Pranay144/dask | dask/array/routines.py | Python | take | take | 1,105 | 1,112 | 1,105 | 1,106 | 1545a39511a0056c94081627d82308cec303db71 | bigcode/the-stack | train |
18c87c518fc4e1ec0350f354 | train | function | @derived_from(np)
def unravel_index(indices, dims, order="C"):
# TODO: deprecate dims as well?
if dims and indices.size:
unraveled_indices = tuple(
indices.map_blocks(
_unravel_index_kernel,
dtype=np.intp,
chunks=(((len(dims),),) + indices.chun... | @derived_from(np)
def unravel_index(indices, dims, order="C"):
# TODO: deprecate dims as well?
| if dims and indices.size:
unraveled_indices = tuple(
indices.map_blocks(
_unravel_index_kernel,
dtype=np.intp,
chunks=(((len(dims),),) + indices.chunks),
new_axis=0,
func_kwargs={_unravel_index_keyword: dims, "order"... | _args"], **kwargs["func_kw"]
)
def _unravel_index_kernel(indices, func_kwargs):
return np.stack(np.unravel_index(indices, **func_kwargs))
@derived_from(np)
def unravel_index(indices, dims, order="C"):
# TODO: deprecate dims as well?
| 64 | 64 | 136 | 27 | 37 | Pranay144/dask | dask/array/routines.py | Python | unravel_index | unravel_index | 1,253 | 1,269 | 1,253 | 1,255 | 2c2d59f1fb34f4f9902f435cb396fe5e463c4d4c | bigcode/the-stack | train |
693dc3321cc1c1efa4de2251 | train | function | @derived_from(np)
def average(a, axis=None, weights=None, returned=False):
return _average(a, axis, weights, returned, is_masked=False)
| @derived_from(np)
def average(a, axis=None, weights=None, returned=False):
| return _average(a, axis, weights, returned, is_masked=False)
| _dtype).sum(axis) / scl
if returned:
if scl.shape != avg.shape:
scl = broadcast_to(scl, avg.shape).copy()
return avg, scl
else:
return avg
@derived_from(np)
def average(a, axis=None, weights=None, returned=False):
| 64 | 64 | 35 | 18 | 45 | Pranay144/dask | dask/array/routines.py | Python | average | average | 1,424 | 1,426 | 1,424 | 1,425 | f96be0371718727ed614c8e987aeaaf6fdf54bbc | bigcode/the-stack | train |
fdc9f195fa7df03ab1962a84 | train | function | @derived_from(np)
def extract(condition, arr):
condition = asarray(condition).astype(bool)
arr = asarray(arr)
return compress(condition.ravel(), arr.ravel())
| @derived_from(np)
def extract(condition, arr):
| condition = asarray(condition).astype(bool)
arr = asarray(arr)
return compress(condition.ravel(), arr.ravel())
| for i in range(a.ndim)
)
]
# Use `condition` to select along 1 dimension
a = a[tuple(condition if i == axis else slice(None) for i in range(a.ndim))]
return a
@derived_from(np)
def extract(condition, arr):
| 64 | 64 | 39 | 11 | 52 | Pranay144/dask | dask/array/routines.py | Python | extract | extract | 1,098 | 1,102 | 1,098 | 1,099 | cd049b0cc66a39b661ead5df5537c1a6e14258d5 | bigcode/the-stack | train |
946d710b5a5643c98b9a885f | train | function | def split_at_breaks(array, breaks, axis=0):
""" Split an array into a list of arrays (using slices) at the given breaks
>>> split_at_breaks(np.arange(6), [3, 5])
[array([0, 1, 2]), array([3, 4]), array([5])]
"""
padded_breaks = concat([[None], breaks, [None]])
slices = [slice(i, j) for i, j in ... | def split_at_breaks(array, breaks, axis=0):
| """ Split an array into a list of arrays (using slices) at the given breaks
>>> split_at_breaks(np.arange(6), [3, 5])
[array([0, 1, 2]), array([3, 4]), array([5])]
"""
padded_breaks = concat([[None], breaks, [None]])
slices = [slice(i, j) for i, j in sliding_window(2, padded_breaks)]
presli... | dt = reduction(np.empty((1,) * x.ndim, dtype=x.dtype)).dtype
graph = HighLevelGraph.from_collections(name, dsk, dependencies=[x])
return Array(graph, name, chunks, dtype=dt)
def split_at_breaks(array, breaks, axis=0):
| 64 | 64 | 147 | 13 | 51 | Pranay144/dask | dask/array/routines.py | Python | split_at_breaks | split_at_breaks | 1,311 | 1,321 | 1,311 | 1,311 | fc518d6519be050036b3d58c69c4434fd353f288 | bigcode/the-stack | train |
df588bfb0853b7f4f211b160 | train | function | @derived_from(np)
def piecewise(x, condlist, funclist, *args, **kw):
return map_blocks(
_int_piecewise,
x,
*condlist,
dtype=x.dtype,
name="piecewise",
funclist=funclist,
func_args=args,
func_kw=kw
)
| @derived_from(np)
def piecewise(x, condlist, funclist, *args, **kw):
| return map_blocks(
_int_piecewise,
x,
*condlist,
dtype=x.dtype,
name="piecewise",
funclist=funclist,
func_args=args,
func_kw=kw
)
| order": order},
)
)
else:
unraveled_indices = tuple(empty((0,), dtype=np.intp, chunks=1) for i in dims)
return unraveled_indices
@derived_from(np)
def piecewise(x, condlist, funclist, *args, **kw):
| 64 | 64 | 75 | 23 | 40 | Pranay144/dask | dask/array/routines.py | Python | piecewise | piecewise | 1,272 | 1,283 | 1,272 | 1,273 | 694f3419ce2f0226b86c888a4b9c402a6b9deb0a | bigcode/the-stack | train |
a6ce0250e08b5fd689ea40a9 | train | function | @derived_from(np)
def round(a, decimals=0):
return a.map_blocks(np.round, decimals=decimals, dtype=a.dtype)
| @derived_from(np)
def round(a, decimals=0):
| return a.map_blocks(np.round, decimals=decimals, dtype=a.dtype)
| ():
return c / c
d = diag(c)
d = d.reshape((d.shape[0], 1))
sqr_d = sqrt(d)
return (c / sqr_d) / sqr_d.T
@derived_from(np)
def round(a, decimals=0):
| 64 | 64 | 30 | 13 | 50 | Pranay144/dask | dask/array/routines.py | Python | round | round | 807 | 809 | 807 | 808 | 862e4c7e03215596c86e98dc6927dbdbd5622ecb | bigcode/the-stack | train |
f4c3e4b34f5f682e661508a5 | train | function | @derived_from(np)
def ptp(a, axis=None):
return a.max(axis=axis) - a.min(axis=axis)
| @derived_from(np)
def ptp(a, axis=None):
| return a.max(axis=axis) - a.min(axis=axis)
| [sl[:i] + (None,)]
elif result.ndim != a.ndim:
raise ValueError(
"func must either preserve dimensionality of the input"
" or reduce it by one."
)
return result
@derived_from(np)
def ptp(a, axis=None):
| 64 | 64 | 28 | 13 | 50 | Pranay144/dask | dask/array/routines.py | Python | ptp | ptp | 440 | 442 | 440 | 441 | 33c8c9e318337ee18952a908ceb8f15dc175fbf3 | bigcode/the-stack | train |
c373c0c090ac6f1acb61152c | train | function | def _take_dask_array_from_numpy(a, indices, axis):
assert isinstance(a, np.ndarray)
assert isinstance(indices, Array)
return indices.map_blocks(
lambda block: np.take(a, block, axis), chunks=indices.chunks, dtype=a.dtype
)
| def _take_dask_array_from_numpy(a, indices, axis):
| assert isinstance(a, np.ndarray)
assert isinstance(indices, Array)
return indices.map_blocks(
lambda block: np.take(a, block, axis), chunks=indices.chunks, dtype=a.dtype
)
| im)
if isinstance(a, np.ndarray) and isinstance(indices, Array):
return _take_dask_array_from_numpy(a, indices, axis)
else:
return a[(slice(None),) * axis + (indices,)]
def _take_dask_array_from_numpy(a, indices, axis):
| 63 | 64 | 59 | 14 | 49 | Pranay144/dask | dask/array/routines.py | Python | _take_dask_array_from_numpy | _take_dask_array_from_numpy | 1,115 | 1,121 | 1,115 | 1,115 | d9b0bd5c1aae293db8b706ea73431b7be6fd16c1 | bigcode/the-stack | train |
2d78d4dab89c74fa360edebf | train | function | @derived_from(np)
def dstack(tup, allow_unknown_chunksizes=False):
tup = tuple(atleast_3d(x) for x in tup)
return concatenate(tup, axis=2, allow_unknown_chunksizes=allow_unknown_chunksizes)
| @derived_from(np)
def dstack(tup, allow_unknown_chunksizes=False):
| tup = tuple(atleast_3d(x) for x in tup)
return concatenate(tup, axis=2, allow_unknown_chunksizes=allow_unknown_chunksizes)
| concatenate(
tup, axis=0, allow_unknown_chunksizes=allow_unknown_chunksizes
)
else:
return concatenate(
tup, axis=1, allow_unknown_chunksizes=allow_unknown_chunksizes
)
@derived_from(np)
def dstack(tup, allow_unknown_chunksizes=False):
| 64 | 64 | 53 | 17 | 47 | Pranay144/dask | dask/array/routines.py | Python | dstack | dstack | 131 | 134 | 131 | 132 | 8eaf5ef06f005d235b22f6dcc850f4c4f19b180f | bigcode/the-stack | train |
570edab08d5e58e5978281e3 | train | function | @safe_wraps(getattr(np, "isin", None))
def isin(element, test_elements, assume_unique=False, invert=False):
element = asarray(element)
test_elements = asarray(test_elements)
element_axes = tuple(range(element.ndim))
test_axes = tuple(i + element.ndim for i in range(test_elements.ndim))
mapped = bloc... | @safe_wraps(getattr(np, "isin", None))
def isin(element, test_elements, assume_unique=False, invert=False):
| element = asarray(element)
test_elements = asarray(test_elements)
element_axes = tuple(range(element.ndim))
test_axes = tuple(i + element.ndim for i in range(test_elements.ndim))
mapped = blockwise(
_isin_kernel,
element_axes + test_axes,
element,
element_axes,
... | values = np.in1d(element.ravel(), test_elements, assume_unique=assume_unique)
return values.reshape(element.shape + (1,) * test_elements.ndim)
@safe_wraps(getattr(np, "isin", None))
def isin(element, test_elements, assume_unique=False, invert=False):
| 64 | 64 | 159 | 27 | 37 | Pranay144/dask | dask/array/routines.py | Python | isin | isin | 971 | 992 | 971 | 972 | 4714ccfd5969b80efa127dbd86ce23ff764cfe08 | bigcode/the-stack | train |
0b221ef3f98c1ab5ac130f77 | train | function | @derived_from(np)
def bincount(x, weights=None, minlength=0):
if x.ndim != 1:
raise ValueError("Input array must be one dimensional. " "Try using x.ravel()")
if weights is not None:
if weights.chunks != x.chunks:
raise ValueError("Chunks of input array x and weights must match.")
... | @derived_from(np)
def bincount(x, weights=None, minlength=0):
| if x.ndim != 1:
raise ValueError("Input array must be one dimensional. " "Try using x.ravel()")
if weights is not None:
if weights.chunks != x.chunks:
raise ValueError("Chunks of input array x and weights must match.")
token = tokenize(x, weights, minlength)
name = "bincount... | grad_kwargs=kwargs,
)
)
if drop_result_list:
results = results[0]
return results
def _bincount_sum(bincounts, dtype=int):
n = max(map(len, bincounts))
out = zeros_like_safe(bincounts[0], shape=n, dtype=dtype)
for b in bincounts:
out[: len(b)] +... | 110 | 110 | 367 | 17 | 92 | Pranay144/dask | dask/array/routines.py | Python | bincount | bincount | 591 | 628 | 591 | 592 | 6c414fa91cfe0be07ac9b83bb1b1a1f1757980d2 | bigcode/the-stack | train |
16b2168fa2f671df2248871a | train | function | def _average(a, axis=None, weights=None, returned=False, is_masked=False):
# This was minimally modified from numpy.average
# See numpy license at https://github.com/numpy/numpy/blob/master/LICENSE.txt
# or NUMPY_LICENSE.txt within this directory
# Wrapper used by da.average or da.ma.average.
a = as... | def _average(a, axis=None, weights=None, returned=False, is_masked=False):
# This was minimally modified from numpy.average
# See numpy license at https://github.com/numpy/numpy/blob/master/LICENSE.txt
# or NUMPY_LICENSE.txt within this directory
# Wrapper used by da.average or da.ma.average.
| a = asanyarray(a)
if weights is None:
avg = a.mean(axis)
scl = avg.dtype.type(a.size / avg.size)
else:
wgt = asanyarray(weights)
if issubclass(a.dtype.type, (np.integer, np.bool_)):
result_dtype = result_type(a.dtype, wgt.dtype, "f8")
else:
r... | _at_breaks(values, values_breaks, axis)
interleaved = list(interleave([split_arr, split_values]))
interleaved = [i for i in interleaved if i.nbytes]
return concatenate(interleaved, axis=axis)
def _average(a, axis=None, weights=None, returned=False, is_masked=False):
# This was minimally modified from n... | 126 | 126 | 422 | 71 | 55 | Pranay144/dask | dask/array/routines.py | Python | _average | _average | 1,373 | 1,421 | 1,373 | 1,377 | 9babe91f6087bb14a7c51461eb80d4e135731a45 | bigcode/the-stack | train |
9b95d0c81d75980b198f6d7b | train | function | def _isin_kernel(element, test_elements, assume_unique=False):
values = np.in1d(element.ravel(), test_elements, assume_unique=assume_unique)
return values.reshape(element.shape + (1,) * test_elements.ndim)
| def _isin_kernel(element, test_elements, assume_unique=False):
| values = np.in1d(element.ravel(), test_elements, assume_unique=assume_unique)
return values.reshape(element.shape + (1,) * test_elements.ndim)
| * out["inverse"]).sum(axis=1))
if return_counts:
result.append(out["counts"])
if len(result) == 1:
result = result[0]
else:
result = tuple(result)
return result
def _isin_kernel(element, test_elements, assume_unique=False):
| 64 | 64 | 50 | 13 | 50 | Pranay144/dask | dask/array/routines.py | Python | _isin_kernel | _isin_kernel | 966 | 968 | 966 | 966 | b4fc179fb372e79e49fb034ceae526c8152f5520 | bigcode/the-stack | train |
536a798f69ad357a1ae34a17 | train | function | def flip(m, axis):
"""
Reverse element order along axis.
Parameters
----------
axis : int
Axis to reverse element order of.
Returns
-------
reversed array : ndarray
"""
m = asanyarray(m)
sl = m.ndim * [slice(None)]
try:
sl[axis] = slice(None, None, -1)... | def flip(m, axis):
| """
Reverse element order along axis.
Parameters
----------
axis : int
Axis to reverse element order of.
Returns
-------
reversed array : ndarray
"""
m = asanyarray(m)
sl = m.ndim * [slice(None)]
try:
sl[axis] = slice(None, None, -1)
except IndexEr... | (range(a.ndim))[::-1]
axes = tuple(d + a.ndim if d < 0 else d for d in axes)
return blockwise(
np.transpose, axes, a, tuple(range(a.ndim)), dtype=a.dtype, axes=axes
)
def flip(m, axis):
| 64 | 64 | 130 | 6 | 58 | Pranay144/dask | dask/array/routines.py | Python | flip | flip | 165 | 190 | 165 | 165 | acfc50b3310cf58e45ed83cdfcb51e9523d99def | bigcode/the-stack | train |
5fa5ca6c3f9403ffcc42a54a | train | class | class ActorSpiderSpiderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the spider middleware does not modify the
# passed objects.
@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
... | class ActorSpiderSpiderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the spider middleware does not modify the
# passed objects.
@classmethod
| def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_spider_input(self, response, spider):
# Called for each response that goes throug... | # -*- coding: utf-8 -*-
# Define here the models for your spider middleware
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy import signals
class ActorSpiderSpiderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# scrapy... | 92 | 108 | 362 | 47 | 44 | TaooCAI/actor_spider | actor_spider/middlewares.py | Python | ActorSpiderSpiderMiddleware | ActorSpiderSpiderMiddleware | 11 | 56 | 11 | 16 | 8f1e40529d69d67aeb9571fa9df5e7babe3ee102 | bigcode/the-stack | train |
d135a2964cfe0bf5a6e8dd2a | train | function | def modify_device(big_item,model,com_port,device_id):
return run_sql("update device set big_item='{}', model ='{}', com_port='{}' where id='{}'".format(big_item,model,com_port,device_id))
| def modify_device(big_item,model,com_port,device_id):
| return run_sql("update device set big_item='{}', model ='{}', com_port='{}' where id='{}'".format(big_item,model,com_port,device_id))
| _sql("delete from device where id = '{}'".format(deviceId))
def get_all(line_id):
return run_sql("select id,big_item,model,com_port,line_id from device where line_id ='{}'".format(line_id))
def modify_device(big_item,model,com_port,device_id):
| 64 | 64 | 54 | 14 | 50 | bkdwei/kdCarCheckDevSimulator | kdCarCheckDevSimulator/device.py | Python | modify_device | modify_device | 20 | 21 | 20 | 20 | c7bbc5f3f5ba800a2a339c31dfcf9432831241d8 | bigcode/the-stack | train |
f6f54fef994043c9e31f06de | train | function | def run_sql(sql):
conn = sqlite3.connect(db_file)
cs = conn.cursor()
print("execute sql:" + sql )
cs.execute(sql)
if "select" in sql:
return cs.fetchall()
conn.commit() | def run_sql(sql):
| conn = sqlite3.connect(db_file)
cs = conn.cursor()
print("execute sql:" + sql )
cs.execute(sql)
if "select" in sql:
return cs.fetchall()
conn.commit() | format(line_id))
def modify_device(big_item,model,com_port,device_id):
return run_sql("update device set big_item='{}', model ='{}', com_port='{}' where id='{}'".format(big_item,model,com_port,device_id))
def run_sql(sql):
| 64 | 64 | 53 | 6 | 58 | bkdwei/kdCarCheckDevSimulator | kdCarCheckDevSimulator/device.py | Python | run_sql | run_sql | 23 | 30 | 23 | 23 | 19b3237b170c4b4ff3d91b7f3b6215b002019999 | bigcode/the-stack | train |
ee3525d93c216491bdfd8496 | train | function | def get_all(line_id):
return run_sql("select id,big_item,model,com_port,line_id from device where line_id ='{}'".format(line_id))
| def get_all(line_id):
| return run_sql("select id,big_item,model,com_port,line_id from device where line_id ='{}'".format(line_id))
| ("insert into device (big_item,model,com_port,line_id) values(?,?,?,?)",(big_item,model,com_port,line_id))
conn.commit()
def delete_device(deviceId):
run_sql("delete from device where id = '{}'".format(deviceId))
def get_all(line_id):
| 64 | 64 | 36 | 6 | 58 | bkdwei/kdCarCheckDevSimulator | kdCarCheckDevSimulator/device.py | Python | get_all | get_all | 18 | 19 | 18 | 18 | 41169c74be0dc3349e1ad597a0c8e25b25fde8e3 | bigcode/the-stack | train |
da5afc55ba7d96b25ba80d67 | train | function | def delete_device(deviceId):
run_sql("delete from device where id = '{}'".format(deviceId))
| def delete_device(deviceId):
| run_sql("delete from device where id = '{}'".format(deviceId))
| _port,line_id):
conn = sqlite3.connect(db_file)
cs = conn.cursor()
cs.execute("insert into device (big_item,model,com_port,line_id) values(?,?,?,?)",(big_item,model,com_port,line_id))
conn.commit()
def delete_device(deviceId):
| 63 | 64 | 22 | 6 | 57 | bkdwei/kdCarCheckDevSimulator | kdCarCheckDevSimulator/device.py | Python | delete_device | delete_device | 16 | 17 | 16 | 16 | 77ee134cf7f7bc71d6b36661dbfbef09b637ce2c | bigcode/the-stack | train |
307ce6af361d06d613d5d3e3 | train | function | def add_device(big_item,model,com_port,line_id):
conn = sqlite3.connect(db_file)
cs = conn.cursor()
cs.execute("insert into device (big_item,model,com_port,line_id) values(?,?,?,?)",(big_item,model,com_port,line_id))
conn.commit()
| def add_device(big_item,model,com_port,line_id):
| conn = sqlite3.connect(db_file)
cs = conn.cursor()
cs.execute("insert into device (big_item,model,com_port,line_id) values(?,?,?,?)",(big_item,model,com_port,line_id))
conn.commit()
| 年5月21日
@author: bkd
'''
from os.path import expanduser,join
import sqlite3
db_file = join(expanduser("~"),".config/kdCarCheckDevSimulator/kdCarCheckDevSimulator.db")
def add_device(big_item,model,com_port,line_id):
| 64 | 64 | 66 | 13 | 51 | bkdwei/kdCarCheckDevSimulator | kdCarCheckDevSimulator/device.py | Python | add_device | add_device | 10 | 14 | 10 | 10 | d0cc9d4c05e471c51be2b0991849a620b437283d | bigcode/the-stack | train |
679fc4e0e3f8123120dbb688 | train | class | class PluginTestObjFactory:
@classmethod
def replace_obj_attr_values(cls, obj, obj_attr_values):
# 原地修改
if obj_attr_values is None:
return obj
for attr, value in obj_attr_values.items():
if attr not in obj:
continue
obj[attr] = value
... | class PluginTestObjFactory:
@classmethod
| def replace_obj_attr_values(cls, obj, obj_attr_values):
# 原地修改
if obj_attr_values is None:
return obj
for attr, value in obj_attr_values.items():
if attr not in obj:
continue
obj[attr] = value
@classmethod
def get_obj(cls, init_par... | _release_version": True,
"is_ready": True,
}
GSE_PLUGIN_DESC = {
"name": DEFAULT_PLUGIN_NAME,
"description": "测试插件啊",
"scenario": "测试",
"category": "external",
"launch_node": "all",
"config_file": "config.yaml",
"config_format": "yaml",
"use_db": False,
}
class PluginTestObjFactory:... | 93 | 93 | 312 | 10 | 83 | zhangzhw8/bk-nodeman | apps/backend/tests/plugin/utils.py | Python | PluginTestObjFactory | PluginTestObjFactory | 51 | 88 | 51 | 52 | 41c2e958c15d3e12a1b196277ad2ed1a0a287269 | bigcode/the-stack | train |
1b58d62a8a3c94084348b238 | train | class | class UtilsClient(Client, TestCase):
def success_assert(self, response):
response_data = json.loads(response.content)
self.assertEqual(response.status_code, 200)
self.assertTrue(response_data["result"])
return response_data
def get(self, path, data=None, follow=False, secure=Fal... | class UtilsClient(Client, TestCase):
| def success_assert(self, response):
response_data = json.loads(response.content)
self.assertEqual(response.status_code, 200)
self.assertTrue(response_data["result"])
return response_data
def get(self, path, data=None, follow=False, secure=False, **extra):
response = supe... | @classmethod
def batch_create_pkg(cls, packages):
return cls.bulk_create(packages, models.Packages)
@classmethod
def batch_create_plugin_desc(cls, plugin_descs):
return cls.bulk_create(plugin_descs, models.GsePluginDesc)
class UtilsClient(Client, TestCase):
| 64 | 64 | 147 | 8 | 56 | zhangzhw8/bk-nodeman | apps/backend/tests/plugin/utils.py | Python | UtilsClient | UtilsClient | 91 | 104 | 91 | 91 | cf0f0c86e20e846555f9b04a2db13bb96bb0137e | bigcode/the-stack | train |
bbd69135b546c0431f3a6c72 | train | class | class L3AgentTestFramework(base.BaseSudoTestCase):
INTERFACE_DRIVER = 'neutron.agent.linux.interface.OVSInterfaceDriver'
NESTED_NAMESPACE_SEPARATOR = '@'
def setUp(self):
super(L3AgentTestFramework, self).setUp()
self.mock_plugin_api = mock.patch(
'neutron.agent.l3.agent.L3Plugi... | class L3AgentTestFramework(base.BaseSudoTestCase):
| INTERFACE_DRIVER = 'neutron.agent.linux.interface.OVSInterfaceDriver'
NESTED_NAMESPACE_SEPARATOR = '@'
def setUp(self):
super(L3AgentTestFramework, self).setUp()
self.mock_plugin_api = mock.patch(
'neutron.agent.l3.agent.L3PluginApi').start().return_value
mock.patch('neu... | implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import copy
import functools
import mock
import netaddr
from neutron_lib import constants
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import uuidutils
import testt... | 256 | 256 | 5,430 | 13 | 243 | MultipleCrashes/neutron | neutron/tests/functional/agent/l3/framework.py | Python | L3AgentTestFramework | L3AgentTestFramework | 52 | 635 | 52 | 52 | 893b4144ab348cb50e13db2a6285d2525853747f | bigcode/the-stack | train |
2f8a759cd8a9a5d856074126 | train | function | def get_ovs_bridge(br_name):
return ovs_lib.OVSBridge(br_name)
| def get_ovs_bridge(br_name):
| return ovs_lib.OVSBridge(br_name)
| utils as common_utils
from neutron.conf.agent import common as agent_config
from neutron.conf import common as common_config
from neutron.tests.common import l3_test_common
from neutron.tests.common import net_helpers
from neutron.tests.functional import base
_uuid = uuidutils.generate_uuid
def get_ovs_bridge(br_nam... | 64 | 64 | 19 | 8 | 55 | MultipleCrashes/neutron | neutron/tests/functional/agent/l3/framework.py | Python | get_ovs_bridge | get_ovs_bridge | 48 | 49 | 48 | 48 | d0a3020c664a5bfa6fa34c47296f9b56b753ba97 | bigcode/the-stack | train |
2a929933bd08305d0c5dedc4 | train | class | class MeetingView(BaseLTIView):
"""Video view."""
model = Meeting
serializer_class = MeetingSerializer
| class MeetingView(BaseLTIView):
| """Video view."""
model = Meeting
serializer_class = MeetingSerializer
| """Views of the ``bbb`` app of the Marsha project."""
from marsha.core.views import BaseLTIView
from .models import Meeting
from .serializers import MeetingSerializer
class MeetingView(BaseLTIView):
| 47 | 64 | 25 | 8 | 38 | insad/marsha | src/backend/marsha/bbb/views.py | Python | MeetingView | MeetingView | 9 | 13 | 9 | 9 | 9f37638d6c85e138dc2cdf28319764738d33e05f | bigcode/the-stack | train |
79b0ddfd8a96bd6d8f4dd225 | train | function | def index():
''' default generic error page '''
try:
code = request.vars["code"]
description = defined_status[int(code)]
except KeyError:
description = "unknown error"
code = "NA"
# Send a JSON message if non-interactive request
request_url = request.vars["request_u... | def index():
| ''' default generic error page '''
try:
code = request.vars["code"]
description = defined_status[int(code)]
except KeyError:
description = "unknown error"
code = "NA"
# Send a JSON message if non-interactive request
request_url = request.vars["request_url"]
path... | (T("Sorry, things didn't get done on time."),
[T("The server did not receive a timely response from another server that it was accessing to fill the request by the browser."),
T("Hit the back button on your browser to try again."),
T("Come back later. Everyone visiting this site is... | 77 | 78 | 263 | 3 | 74 | flavour/lacity | controllers/errors.py | Python | index | index | 55 | 88 | 55 | 55 | af6dbb50332a3682fa7bc2ed49be22514d6759aa | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.